page-path-utils.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import nodePath from 'path';
  2. import escapeStringRegexp from 'escape-string-regexp';
  3. import { isValidObjectId } from 'mongoose';
  4. import { addTrailingSlash } from './path-utils';
  5. /**
  6. * Whether path is the top page
  7. * @param path
  8. */
  9. export const isTopPage = (path: string): boolean => {
  10. return path === '/';
  11. };
  12. /**
  13. * Whether path is the top page of users
  14. * @param path
  15. */
  16. export const isUsersTopPage = (path: string): boolean => {
  17. return path === '/user';
  18. };
  19. /**
  20. * Whether the path is permalink
  21. * @param path
  22. */
  23. export const isPermalink = (path: string): boolean => {
  24. const pageIdStr = path.substring(1);
  25. return isValidObjectId(pageIdStr);
  26. };
  27. /**
  28. * Whether path is user's home page
  29. * @param path
  30. */
  31. export const isUsersHomePage = (path: string): boolean => {
  32. // https://regex101.com/r/utVQct/1
  33. if (path.match(/^\/user\/[^/]+$/)) {
  34. return true;
  35. }
  36. return false;
  37. };
  38. /**
  39. * Whether path is the protected pages for systems
  40. * @param path
  41. */
  42. export const isUsersProtectedPages = (path: string): boolean => {
  43. return isUsersTopPage(path) || isUsersHomePage(path);
  44. };
  45. /**
  46. * Whether path is movable
  47. * @param path
  48. */
  49. export const isMovablePage = (path: string): boolean => {
  50. return !isTopPage(path) && !isUsersProtectedPages(path);
  51. };
  52. /**
  53. * Whether path belongs to the user page
  54. * @param path
  55. */
  56. export const isUserPage = (path: string): boolean => {
  57. // https://regex101.com/r/BSDdRr/1
  58. if (path.match(/^\/user(\/.*)?$/)) {
  59. return true;
  60. }
  61. return false;
  62. };
  63. /**
  64. * Whether path belongs to the trash page
  65. * @param path
  66. */
  67. export const isTrashPage = (path: string): boolean => {
  68. // https://regex101.com/r/BSDdRr/1
  69. if (path.match(/^\/trash(\/.*)?$/)) {
  70. return true;
  71. }
  72. return false;
  73. };
  74. /**
  75. * Whether path belongs to the shared page
  76. * @param path
  77. */
  78. export const isSharedPage = (path: string): boolean => {
  79. // https://regex101.com/r/ZjdOiB/1
  80. if (path.match(/^\/share(\/.*)?$/)) {
  81. return true;
  82. }
  83. return false;
  84. };
  85. const restrictedPatternsToCreate: Array<RegExp> = [
  86. /\^|\$|\*|\+|#|%|\?/,
  87. /^\/-\/.*/,
  88. /^\/_r\/.*/,
  89. /^\/_apix?(\/.*)?/,
  90. /^\/?https?:\/\/.+$/, // avoid miss in renaming
  91. /\/{2,}/, // avoid miss in renaming
  92. /\s+\/\s+/, // avoid miss in renaming
  93. /.+\/edit$/,
  94. /.+\.md$/,
  95. /^(\.\.)$/, // see: https://github.com/weseek/growi/issues/3582
  96. /(\/\.\.)\/?/, // see: https://github.com/weseek/growi/issues/3582
  97. /^\/(_search|_private-legacy-pages)(\/.*|$)/,
  98. /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments|tags|share)(\/.*|$)/,
  99. /^\/user\/[^/]+$/, // see: https://regex101.com/r/utVQct/1
  100. ];
  101. export const isCreatablePage = (path: string): boolean => {
  102. return !restrictedPatternsToCreate.some(pattern => path.match(pattern));
  103. };
  104. /**
  105. * return user path
  106. * @param user
  107. */
  108. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  109. export const userPageRoot = (user: any): string => {
  110. if (!user || !user.username) {
  111. return '';
  112. }
  113. return `/user/${user.username}`;
  114. };
  115. /**
  116. * return user path
  117. * @param parentPath
  118. * @param childPath
  119. * @param newPath
  120. */
  121. export const convertToNewAffiliationPath = (oldPath: string, newPath: string, childPath: string): string => {
  122. if (newPath == null) {
  123. throw new Error('Please input the new page path');
  124. }
  125. const pathRegExp = new RegExp(`^${escapeStringRegexp(oldPath)}`, 'i');
  126. return childPath.replace(pathRegExp, newPath);
  127. };
  128. /**
  129. * Encode SPACE and IDEOGRAPHIC SPACE
  130. * @param {string} path
  131. * @returns {string}
  132. */
  133. export const encodeSpaces = (path?:string): string | undefined => {
  134. if (path == null) {
  135. return undefined;
  136. }
  137. // Encode SPACE and IDEOGRAPHIC SPACE
  138. return path.replace(/ /g, '%20').replace(/\u3000/g, '%E3%80%80');
  139. };
  140. /**
  141. * Generate editor path
  142. * @param {string} paths
  143. * @returns {string}
  144. */
  145. export const generateEditorPath = (...paths: string[]): string => {
  146. const joinedPath = [...paths].join('/');
  147. if (!isCreatablePage(joinedPath)) {
  148. throw new Error('Invalid characters on path');
  149. }
  150. try {
  151. const url = new URL(joinedPath, 'https://dummy');
  152. return `${url.pathname}#edit`;
  153. }
  154. catch (err) {
  155. throw new Error('Invalid path format');
  156. }
  157. };
  158. /**
  159. * returns ancestors paths
  160. * @param {string} path
  161. * @param {string[]} ancestorPaths
  162. * @returns {string[]}
  163. */
  164. export const collectAncestorPaths = (path: string, ancestorPaths: string[] = []): string[] => {
  165. if (isTopPage(path)) return ancestorPaths;
  166. const parentPath = nodePath.dirname(path);
  167. ancestorPaths.push(parentPath);
  168. return collectAncestorPaths(parentPath, ancestorPaths);
  169. };
  170. /**
  171. * return paths without duplicate area of regexp /^${path}\/.+/i
  172. * ex. expect(omitDuplicateAreaPathFromPaths(['/A', '/A/B', '/A/B/C'])).toStrictEqual(['/A'])
  173. * @param paths paths to be tested
  174. * @returns omitted paths
  175. */
  176. export const omitDuplicateAreaPathFromPaths = (paths: string[]): string[] => {
  177. const uniquePaths = Array.from(new Set(paths));
  178. return uniquePaths.filter((path) => {
  179. const isDuplicate = uniquePaths.filter(p => (new RegExp(`^${p}\\/.+`, 'i')).test(path)).length > 0;
  180. return !isDuplicate;
  181. });
  182. };
  183. /**
  184. * return pages with path without duplicate area of regexp /^${path}\/.+/i
  185. * if the pages' path are the same, it will NOT omit any of them since the other attributes will not be the same
  186. * @param paths paths to be tested
  187. * @returns omitted paths
  188. */
  189. export const omitDuplicateAreaPageFromPages = (pages: any[]): any[] => {
  190. return pages.filter((page) => {
  191. const isDuplicate = pages.some(p => (new RegExp(`^${p.path}\\/.+`, 'i')).test(page.path));
  192. return !isDuplicate;
  193. });
  194. };
  195. /**
  196. * Check if the area of either path1 or path2 includes the area of the other path
  197. * The area of path is the same as /^\/hoge\//i
  198. * @param pathToTest string
  199. * @param pathToBeTested string
  200. * @returns boolean
  201. */
  202. export const isEitherOfPathAreaOverlap = (path1: string, path2: string): boolean => {
  203. if (path1 === path2) {
  204. return true;
  205. }
  206. const path1WithSlash = addTrailingSlash(path1);
  207. const path2WithSlash = addTrailingSlash(path2);
  208. const path1Area = new RegExp(`^${escapeStringRegexp(path1WithSlash)}`, 'i');
  209. const path2Area = new RegExp(`^${escapeStringRegexp(path2WithSlash)}`, 'i');
  210. if (path1Area.test(path2) || path2Area.test(path1)) {
  211. return true;
  212. }
  213. return false;
  214. };
  215. /**
  216. * Check if the area of pathToTest includes the area of pathToBeTested
  217. * The area of path is the same as /^\/hoge\//i
  218. * @param pathToTest string
  219. * @param pathToBeTested string
  220. * @returns boolean
  221. */
  222. export const isPathAreaOverlap = (pathToTest: string, pathToBeTested: string): boolean => {
  223. if (pathToTest === pathToBeTested) {
  224. return true;
  225. }
  226. const pathWithSlash = addTrailingSlash(pathToTest);
  227. const pathAreaToTest = new RegExp(`^${escapeStringRegexp(pathWithSlash)}`, 'i');
  228. if (pathAreaToTest.test(pathToBeTested)) {
  229. return true;
  230. }
  231. return false;
  232. };
  233. /**
  234. * Determine whether can move by fromPath and toPath
  235. * @param fromPath string
  236. * @param toPath string
  237. * @returns boolean
  238. */
  239. export const canMoveByPath = (fromPath: string, toPath: string): boolean => {
  240. return !isPathAreaOverlap(fromPath, toPath);
  241. };
  242. /**
  243. * check if string has '/' in it
  244. */
  245. export const hasSlash = (str: string): boolean => {
  246. return str.includes('/');
  247. };
  248. /**
  249. * Generate RegExp instance for one level lower path
  250. */
  251. export const generateChildrenRegExp = (path: string): RegExp => {
  252. // https://regex101.com/r/laJGzj/1
  253. // ex. /any_level1
  254. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  255. // https://regex101.com/r/mrDJrx/1
  256. // ex. /parent/any_child OR /any_level1
  257. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  258. };