utils.ts
This file
Path
src/helper/ssg/utils.ts
118 lines · 3.7 KiB · TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoption3a67f7f
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–19why, one step back1import type { Hono } from '../../hono'2import { METHOD_NAME_ALL } from '../../router'3import type { Env, RouterRoute } from '../../types'4import { findTargetHandler, isMiddleware } from '../../utils/handler'56/**7 * Get dirname8 * @param path File Path9 * @returns Parent dir path10 */11export const dirname = (path: string): string => {12 const separatedPath = path.split(/[\/\\]/)13 return separatedPath.slice(0, -1).join('/') // Windows supports slash path14}1516const normalizePath = (path: string): string => {17 return path.replace(/(\\)/g, '/').replace(/\/$/g, '')18}19Merge commit from forkTaku Amanobefore adoption3a67f7f
lines 20–28why, one step back20const getUncRoot = (path: string): string | undefined => {21 const uncRoot = path.replace(/\\/g, '/').match(/^\/\/([^/]+)\/([^/]+)/)22 if (uncRoot) {23 return `${uncRoot[1].toLowerCase()}/${uncRoot[2].toLowerCase()}`24 }25}2627const handleParent = (resultPaths: string[]): void => {28 if (resultPaths.length === 0 || resultPaths[resultPaths.length - 1] === '..') {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 29–45why, one step back29 resultPaths.push('..')30 } else {31 resultPaths.pop()32 }33}3435const handleNonDot = (path: string, resultPaths: string[]): void => {36 path = path.replace(/^\.(?!.)/, '')37 if (path !== '') {38 resultPaths.push(path)39 }40}4142const handleSegments = (paths: string[], resultPaths: string[]): void => {43 for (const path of paths) {44 // Handle `..`45 if (path === '..') {Merge commit from forkTaku Amanobefore adoption3a67f7f
line 46why, one step back46 handleParent(resultPaths)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 47–54why, one step back47 } else {48 // Handle `.` or `abc`49 handleNonDot(path, resultPaths)50 }51 }52}5354export const joinPaths = (...paths: string[]): string => {Merge commit from forkTaku Amanobefore adoption3a67f7f
line 55why, one step back55 const hasUncPrefix = getUncRoot(paths[0]) !== undefinedMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 56–58why, one step back56 paths = paths.map(normalizePath)57 const resultPaths: string[] = []58 handleSegments(paths.join('/').split('/'), resultPaths)Merge commit from forkTaku Amanobefore adoption3a67f7f
line 59why, one step back59 return (hasUncPrefix ? '//' : paths[0][0] === '/' ? '/' : '') + resultPaths.join('/')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 60–81why, one step back60}6162interface FilterStaticGenerateRouteData {63 path: string64}6566export const filterStaticGenerateRoutes = <E extends Env>(67 hono: Hono<E>68): FilterStaticGenerateRouteData[] => {69 return hono.routes.reduce((acc, { method, handler, path }: RouterRoute) => {70 const targetHandler = findTargetHandler(handler)71 if (['GET', METHOD_NAME_ALL].includes(method) && !isMiddleware(targetHandler)) {72 acc.push({ path })73 }74 return acc75 }, [] as FilterStaticGenerateRouteData[])76}7778export const isDynamicRoute = (path: string): boolean => {79 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))80}81Merge commit from forkTaku Amanobefore adoption3a67f7f
lines 82–99why, one step back82const toSegments = (path: string): string[] => (path === '' ? [] : path.split('/'))8384const getPathRoot = (path: string): string => {85 const normalizedPath = path.replace(/\\/g, '/')86 const uncRoot = getUncRoot(normalizedPath)87 if (uncRoot) {88 return `unc:${uncRoot}`89 }9091 const driveRoot = normalizedPath.match(/^([A-Za-z]):/)92 if (driveRoot) {93 const kind = normalizedPath[2] === '/' ? 'drive-absolute' : 'drive-relative'94 return `${kind}:${driveRoot[1].toLowerCase()}`95 }9697 return normalizedPath.startsWith('/') ? 'absolute' : 'relative'98}99Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 100why, one step back100export const ensureWithinOutDir = (outDir: string, filePath: string): void => {Merge commit from forkTaku Amanobefore adoption3a67f7f
lines 101–102why, one step back101 const outDirSegments = toSegments(joinPaths(outDir))102 const filePathSegments = toSegments(joinPaths(filePath))Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 103why, one step back103Merge commit from forkTaku Amanobefore adoption3a67f7f
lines 104–109why, one step back104 const hasMismatchedPathRoot = getPathRoot(outDir) !== getPathRoot(filePath)105106 // `joinPaths` collects every remaining `..` at the head, so a `..` right after107 // the outDir segments means the file path climbs above outDir108 const climbsAboveOutDir = filePathSegments[outDirSegments.length] === '..'109Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 110why, one step back110 if (Merge commit from forkTaku Amanobefore adoption3a67f7f
lines 111–114why, one step back111 hasMismatchedPathRoot ||112 filePathSegments.length <= outDirSegments.length ||113 !outDirSegments.every((segment, i) => segment === filePathSegments[i]) ||114 climbsAboveOutDirMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 115–118why, one step back115 ) {116 throw new Error(`Path traversal detected: "${filePath}" is outside the output directory`)117 }118}