├── .editorconfig ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── ---bug-report.yml │ ├── ---documentation.yml │ ├── ---feature-suggestion.yml │ └── ---help-wanted.yml └── workflows │ ├── ci.yml │ └── release.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENCE ├── README.md ├── build.config.ts ├── eslint.config.js ├── package.json ├── playground ├── index.js └── package.json ├── pnpm-lock.yaml ├── pnpm-workspace.yaml ├── renovate.json ├── src ├── converters.ts ├── index.ts └── parse.ts ├── test └── unit │ ├── converters.spec.ts │ ├── integration.spec.ts │ └── parse.spec.ts ├── tsconfig.json └── vitest.config.ts /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.js] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [{package.json,*.yml,*.cjson}] 14 | indent_style = space 15 | indent_size = 2 16 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [danielroe] 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---bug-report.yml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug report 2 | description: Something's not working 3 | labels: [bug] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 🐛 The bug 10 | description: What isn't working? Describe what the bug is. 11 | - type: input 12 | validations: 13 | required: true 14 | attributes: 15 | label: 🛠️ To reproduce 16 | description: A reproduction of the bug via https://stackblitz.com/github/unjs/unrouting/tree/main/playground 17 | placeholder: https://stackblitz.com/[...] 18 | - type: textarea 19 | validations: 20 | required: true 21 | attributes: 22 | label: 🌈 Expected behaviour 23 | description: What did you expect to happen? Is there a section in the docs about this? 24 | - type: textarea 25 | attributes: 26 | label: ℹ️ Additional context 27 | description: Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---documentation.yml: -------------------------------------------------------------------------------- 1 | name: 📚 Documentation 2 | description: How do I ... ? 3 | labels: [documentation] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 📚 Is your documentation request related to a problem? 10 | description: A clear and concise description of what the problem is. 11 | placeholder: I feel I should be able to [...] but I can't see how to do it from the docs. 12 | - type: textarea 13 | attributes: 14 | label: 🔍 Where should you find it? 15 | description: What page of the docs do you expect this information to be found on? 16 | - type: textarea 17 | attributes: 18 | label: ℹ️ Additional context 19 | description: Add any other context or information. 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---feature-suggestion.yml: -------------------------------------------------------------------------------- 1 | name: 🆕 Feature suggestion 2 | description: Suggest an idea 3 | labels: [enhancement] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 🆒 Your use case 10 | description: Add a description of your use case, and how this feature would help you. 11 | placeholder: When I do [...] I would expect to be able to do [...] 12 | - type: textarea 13 | validations: 14 | required: true 15 | attributes: 16 | label: 🆕 The solution you'd like 17 | description: Describe what you want to happen. 18 | - type: textarea 19 | attributes: 20 | label: 🔍 Alternatives you've considered 21 | description: Have you considered any alternative solutions or features? 22 | - type: textarea 23 | attributes: 24 | label: ℹ️ Additional info 25 | description: Is there any other context you think would be helpful to know? 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/---help-wanted.yml: -------------------------------------------------------------------------------- 1 | name: 🆘 Help 2 | description: I need help with ... 3 | labels: [help] 4 | body: 5 | - type: textarea 6 | validations: 7 | required: true 8 | attributes: 9 | label: 📚 What are you trying to do? 10 | description: A clear and concise description of your objective. 11 | placeholder: I'm not sure how to [...]. 12 | - type: textarea 13 | attributes: 14 | label: 🔍 What have you tried? 15 | description: Have you looked through the docs? Tried different approaches? The more detail the better. 16 | - type: textarea 17 | attributes: 18 | label: ℹ️ Additional context 19 | description: Add any other context or information. 20 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | lint: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | - run: npm i -g --force corepack && corepack enable 18 | - uses: actions/setup-node@v4 19 | with: 20 | node-version: 20 21 | cache: pnpm 22 | 23 | - name: 📦 Install dependencies 24 | run: pnpm install --frozen-lockfile 25 | 26 | - name: 🔠 Lint project 27 | run: pnpm lint 28 | 29 | test: 30 | runs-on: ubuntu-latest 31 | 32 | steps: 33 | - uses: actions/checkout@v4 34 | - run: npm i -g --force corepack && corepack enable 35 | - uses: actions/setup-node@v4 36 | with: 37 | node-version: 20 38 | cache: pnpm 39 | 40 | - name: 📦 Install dependencies 41 | run: pnpm install --frozen-lockfile 42 | 43 | - name: 🛠 Build project 44 | run: pnpm build 45 | 46 | - name: 🧪 Test project 47 | run: pnpm test 48 | 49 | - name: 🟩 Coverage 50 | uses: codecov/codecov-action@v5 51 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v*' 10 | 11 | jobs: 12 | release: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | 19 | - name: Set node 20 | uses: actions/setup-node@v4 21 | with: 22 | node-version: 20 23 | 24 | - run: npx changelogithub 25 | env: 26 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | dist 2 | node_modules 3 | coverage 4 | .vscode 5 | .DS_Store 6 | .eslintcache 7 | *.log* 8 | *.env* 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [daniel@roe.dev](mailto:daniel@roe.dev). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 44 | 45 | [homepage]: https://www.contributor-covenant.org 46 | 47 | For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq 48 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Daniel Roe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📍 unrouting 2 | 3 | [![npm version][npm-version-src]][npm-version-href] 4 | [![npm downloads][npm-downloads-src]][npm-downloads-href] 5 | [![bundle][bundle-src]][bundle-href] 6 | [![Codecov][codecov-src]][codecov-href] 7 | [![License][license-src]][license-href] 8 | [![JSDocs][jsdocs-src]][jsdocs-href] 9 | 10 | > Making filesystem routing universal 11 | 12 | ## 🚧 In development 13 | 14 | This library is a work in progress and in active development. 15 | 16 | - [ ] generic route parsing function with options to cover major filesystem routing patterns 17 | - [x] [Nuxt](https://github.com/nuxt/nuxt) 18 | - [ ] [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) 19 | - [ ] export capability for framework routers 20 | - [x] RegExp patterns 21 | - [ ] [`vue-router`](https://router.vuejs.org/) routes 22 | - [ ] [radix3](http://github.com/unjs/radix3)/[Nitro](https://nitro.unjs.io/) routes 23 | - [ ] [SolidStart](https://start.solidjs.com/core-concepts/routing) 24 | - [ ] [SvelteKit](https://kit.svelte.dev/docs/routing) routes 25 | - [ ] support scanning FS (with optional watch mode) 26 | - [ ] and more 27 | 28 | ## Usage 29 | 30 | Install package: 31 | 32 | ```sh 33 | # npm 34 | npm install unrouting 35 | 36 | # pnpm 37 | pnpm install unrouting 38 | ``` 39 | 40 | ```js 41 | import {} from 'unrouting' 42 | ``` 43 | 44 | ## 💻 Development 45 | 46 | - Clone this repository 47 | - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10) 48 | - Install dependencies using `pnpm install` 49 | - Run interactive tests using `pnpm dev` 50 | 51 | ## License 52 | 53 | Made with ❤️ 54 | 55 | Published under [MIT License](./LICENCE). 56 | 57 | 58 | 59 | [npm-version-src]: https://img.shields.io/npm/v/unrouting?style=flat&colorA=18181B&colorB=F0DB4F 60 | [npm-version-href]: https://npmjs.com/package/unrouting 61 | [npm-downloads-src]: https://img.shields.io/npm/dm/unrouting?style=flat&colorA=18181B&colorB=F0DB4F 62 | [npm-downloads-href]: https://npmjs.com/package/unrouting 63 | [codecov-src]: https://img.shields.io/codecov/c/gh/unjs/unrouting/main?style=flat&colorA=18181B&colorB=F0DB4F 64 | [codecov-href]: https://codecov.io/gh/unjs/unrouting 65 | [bundle-src]: https://img.shields.io/bundlephobia/minzip/unrouting?style=flat&colorA=18181B&colorB=F0DB4F 66 | [bundle-href]: https://bundlephobia.com/result?p=unrouting 67 | [license-src]: https://img.shields.io/github/license/unjs/unrouting.svg?style=flat&colorA=18181B&colorB=F0DB4F 68 | [license-href]: https://github.com/unjs/unrouting/blob/main/LICENSE 69 | [jsdocs-src]: https://img.shields.io/badge/jsDocs.io-reference-18181B?style=flat&colorA=18181B&colorB=F0DB4F 70 | [jsdocs-href]: https://www.jsdocs.io/package/unrouting 71 | -------------------------------------------------------------------------------- /build.config.ts: -------------------------------------------------------------------------------- 1 | import { cp, readdir, rm } from 'node:fs/promises' 2 | import { defineBuildConfig } from 'unbuild' 3 | 4 | export default defineBuildConfig({ 5 | hooks: { 6 | 'rollup:done': async function () { 7 | // default to .js and .d.ts extensions 8 | for (const file of await readdir('dist')) { 9 | if (file.endsWith('.mjs') || file.endsWith('.d.mts')) { 10 | await cp(`dist/${file}`, `dist/${file.replace('.mjs', '.js').replace('.d.mts', '.d.ts')}`) 11 | await rm(`dist/${file}`) 12 | } 13 | } 14 | }, 15 | }, 16 | }) 17 | -------------------------------------------------------------------------------- /eslint.config.js: -------------------------------------------------------------------------------- 1 | import antfu from '@antfu/eslint-config' 2 | 3 | export default antfu() 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unrouting", 3 | "type": "module", 4 | "version": "0.0.1", 5 | "packageManager": "pnpm@10.11.1", 6 | "description": "", 7 | "license": "MIT", 8 | "repository": "unjs/unrouting", 9 | "sideEffects": false, 10 | "exports": { 11 | ".": "./dist/index.js" 12 | }, 13 | "main": "./dist/index.js", 14 | "module": "./dist/index.js", 15 | "types": "./dist/index.d.ts", 16 | "files": [ 17 | "dist" 18 | ], 19 | "scripts": { 20 | "build": "unbuild", 21 | "dev": "vitest dev", 22 | "lint": "eslint .", 23 | "prepare": "simple-git-hooks", 24 | "prepack": "pnpm build", 25 | "prepublishOnly": "pnpm lint && pnpm test", 26 | "release": "pnpm test && bumpp && npm publish", 27 | "test": "pnpm test:unit && pnpm test:types", 28 | "test:unit": "vitest", 29 | "test:types": "tsc --noEmit" 30 | }, 31 | "dependencies": { 32 | "escape-string-regexp": "^5.0.0", 33 | "ufo": "^1.3.2" 34 | }, 35 | "devDependencies": { 36 | "@antfu/eslint-config": "latest", 37 | "@types/node": "22.15.29", 38 | "@vitest/coverage-v8": "latest", 39 | "bumpp": "10.1.1", 40 | "eslint": "latest", 41 | "lint-staged": "latest", 42 | "radix3": "1.1.2", 43 | "simple-git-hooks": "latest", 44 | "typescript": "latest", 45 | "unbuild": "latest", 46 | "vite": "latest", 47 | "vitest": "latest", 48 | "vue-router": "4.5.1" 49 | }, 50 | "resolutions": { 51 | "unrouting": "link:." 52 | }, 53 | "simple-git-hooks": { 54 | "pre-commit": "npx lint-staged" 55 | }, 56 | "lint-staged": { 57 | "*.{js,ts,mjs,cjs,json,.*rc}": [ 58 | "pnpm eslint --fix" 59 | ] 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /playground/index.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert' 2 | import * as pkg from 'unrouting' 3 | 4 | // eslint-disable-next-line no-console 5 | console.log(pkg.welcome()) 6 | 7 | assert.strictEqual(pkg.welcome(), 'hello world') 8 | -------------------------------------------------------------------------------- /playground/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "module", 3 | "private": true, 4 | "scripts": { 5 | "dev": "node --watch index.js" 6 | }, 7 | "dependencies": { 8 | "unrouting": "latest" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - playground 3 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "github>danielroe/renovate" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /src/converters.ts: -------------------------------------------------------------------------------- 1 | import type { ParsedPath } from './parse' 2 | import escapeStringRegexp from 'escape-string-regexp' 3 | 4 | import { encodePath, joinURL } from 'ufo' 5 | import { parsePath } from './parse' 6 | 7 | /** 8 | * - [x] support exporting to pure RegExp matcher 9 | * - [x] support exporting to radix3/Nitro routes 10 | * - [ ] support exporting to `vue-router` routes 11 | * with compatibility for [Nuxt](https://github.com/nuxt/nuxt) and 12 | * [unplugin-vue-router](https://github.com/posva/unplugin-vue-router) 13 | * - [ ] support exporting to SolidStart 14 | * - [ ] support exporting to SvelteKit routes 15 | */ 16 | 17 | /** 18 | * TODO: need to implement protection logging + fall back to what radix3 supports. 19 | */ 20 | export function toRadix3(filePath: string | ParsedPath) { 21 | const segments = typeof filePath === 'string' ? parsePath(filePath) : filePath 22 | 23 | let route = '/' 24 | 25 | for (const segment of segments) { 26 | let radixSegment = '' 27 | for (const token of segment) { 28 | if (token.type === 'static') 29 | radixSegment += token.value 30 | 31 | if (token.type === 'dynamic') 32 | radixSegment += token.value ? `:${token.value}` : '*' 33 | 34 | if (token.type === 'optional') 35 | throw new TypeError('[unrouting] `toRadix3` does not support optional parameters') 36 | 37 | if (token.type === 'catchall') 38 | radixSegment += token.value ? `**:${token.value}` : '**' 39 | } 40 | 41 | // If a segment has value '' we skip adding it entirely 42 | if (route) 43 | route = joinURL(route, radixSegment) 44 | } 45 | 46 | return route 47 | } 48 | 49 | export function toVueRouter4(filePath: string | ParsedPath) { 50 | const segments = typeof filePath === 'string' ? parsePath(filePath) : filePath 51 | 52 | let path = '/' 53 | 54 | for (const segment of segments) { 55 | let pathSegment = '' 56 | for (const token of segment) { 57 | if (token.type === 'static') { 58 | pathSegment += encodePath(token.value).replace(/:/g, '\\:') 59 | continue 60 | } 61 | if (token.type === 'dynamic') 62 | pathSegment += `:${token.value}()` 63 | 64 | if (token.type === 'optional') 65 | pathSegment += `:${token.value}?` 66 | 67 | if (token.type === 'catchall') 68 | pathSegment += `:${token.value}(.*)*` 69 | } 70 | 71 | path = joinURL(path, pathSegment) 72 | } 73 | 74 | return { 75 | path, 76 | } 77 | } 78 | 79 | function sanitizeCaptureGroup(captureGroup: string) { 80 | return captureGroup.replace(/^(\d)/, '_$1').replace(/\./g, '') 81 | } 82 | export function toRegExp(filePath: string | ParsedPath) { 83 | const segments = typeof filePath === 'string' ? parsePath(filePath) : filePath 84 | 85 | let sourceRE = '\\/' 86 | 87 | for (const segment of segments) { 88 | let reSegment = '' 89 | for (const token of segment) { 90 | if (token.type === 'static') 91 | reSegment += escapeStringRegexp(token.value) 92 | 93 | if (token.type === 'dynamic') 94 | reSegment += `(?<${sanitizeCaptureGroup(token.value)}>[^/]+)` 95 | 96 | if (token.type === 'optional') 97 | reSegment += `(?<${sanitizeCaptureGroup(token.value)}>[^/]*)` 98 | 99 | if (token.type === 'catchall') 100 | reSegment += `(?<${sanitizeCaptureGroup(token.value)}>.*)` 101 | } 102 | 103 | if (segment.every(token => token.type === 'optional' || token.type === 'catchall')) { 104 | sourceRE += `(?:${reSegment}\\/?)` 105 | } 106 | else if (reSegment) { 107 | // If a segment has value '' we skip adding a trailing slash 108 | sourceRE += `${reSegment}\\/` 109 | } 110 | } 111 | 112 | // make final slash optional 113 | sourceRE += '?' 114 | 115 | return new RegExp(sourceRE) 116 | } 117 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { toRadix3, toRegExp, toVueRouter4 } from './converters' 2 | 3 | export type { ParsedPath, ParsedPathSegment, ParsedPathSegmentToken, ParsePathOptions, SegmentType } from './parse' 4 | export { parsePath } from './parse' 5 | -------------------------------------------------------------------------------- /src/parse.ts: -------------------------------------------------------------------------------- 1 | import { withoutLeadingSlash, withoutTrailingSlash } from 'ufo' 2 | 3 | /** 4 | * File system formats supported 5 | * - vue-router/nuxt 3 styles 6 | * - nitro style routes 7 | * - Next.js style 8 | * - sveltekit style 9 | * - solid start style 10 | */ 11 | 12 | export interface ParsePathOptions { 13 | /** 14 | * By default the extension of the file is stripped. To disable this behaviour, pass 15 | * an array of extensions to strip. The rest will be preserved. 16 | */ 17 | extensions?: string[] 18 | postfix?: string 19 | } 20 | 21 | export function parsePath(filePath: string, options: ParsePathOptions = {}): ParsedPath { 22 | // remove file extensions (allow-listed if `options.extensions` is specified) 23 | const EXT_RE = options.extensions ? new RegExp(`\\.(${options.extensions.join('|')})$`) : /\.\w+$/ 24 | filePath = filePath.replace(EXT_RE, '') 25 | 26 | // add leading slash and remove trailing slash: test/ -> /test 27 | const segments = withoutLeadingSlash(withoutTrailingSlash(filePath)).split('/') 28 | 29 | return segments.map(s => parseSegment(s)) 30 | } 31 | 32 | const PARAM_CHAR_RE = /[\w.]/ 33 | 34 | export type SegmentType = 'static' | 'dynamic' | 'optional' | 'catchall' 35 | export interface ParsedPathSegmentToken { type: SegmentType, value: string } 36 | export type ParsedPathSegment = Array 37 | export type ParsedPath = ParsedPathSegment[] 38 | 39 | export function parseSegment(segment: string) { 40 | type SegmentParserState = 'initial' | SegmentType 41 | let state: SegmentParserState = 'initial' 42 | let i = 0 43 | 44 | let buffer = '' 45 | const tokens: ParsedPathSegmentToken[] = [] 46 | 47 | function consumeBuffer() { 48 | if (!buffer) 49 | return 50 | if (state === 'initial') 51 | throw new Error('wrong state') 52 | 53 | tokens.push({ 54 | type: state, 55 | value: buffer, 56 | }) 57 | 58 | buffer = '' 59 | } 60 | 61 | while (i < segment.length) { 62 | const c = segment[i] 63 | 64 | switch (state) { 65 | case 'initial': 66 | buffer = '' 67 | if (c === '[') { 68 | state = 'dynamic' 69 | } 70 | else { 71 | i-- 72 | state = 'static' 73 | } 74 | break 75 | 76 | case 'static': 77 | if (c === '[') { 78 | consumeBuffer() 79 | state = 'dynamic' 80 | } 81 | else { 82 | buffer += c 83 | } 84 | break 85 | 86 | case 'catchall': 87 | case 'dynamic': 88 | case 'optional': 89 | if (buffer === '...') { 90 | buffer = '' 91 | state = 'catchall' 92 | } 93 | if (c === '[' && state === 'dynamic') 94 | state = 'optional' 95 | 96 | if (c === ']' && (state !== 'optional' || segment[i - 1] === ']')) { 97 | if (!buffer) 98 | throw new Error('Empty param') 99 | else 100 | consumeBuffer() 101 | 102 | state = 'initial' 103 | } 104 | else if (PARAM_CHAR_RE.test(c)) { 105 | buffer += c 106 | } 107 | break 108 | } 109 | i++ 110 | } 111 | 112 | if (state === 'dynamic') 113 | throw new Error(`Unfinished param "${buffer}"`) 114 | 115 | consumeBuffer() 116 | 117 | if (tokens.length === 1 && tokens[0].type === 'static' && tokens[0].value === 'index') 118 | tokens[0].value = '' 119 | 120 | return tokens 121 | } 122 | -------------------------------------------------------------------------------- /test/unit/converters.spec.ts: -------------------------------------------------------------------------------- 1 | import { createRouter as createRadixRouter } from 'radix3' 2 | import { describe, expect, it } from 'vitest' 3 | import { createMemoryHistory, createRouter as createVueRouter } from 'vue-router' 4 | import { toRadix3, toRegExp, toVueRouter4 } from '../../src' 5 | 6 | describe('radix3 support', () => { 7 | const paths = { 8 | 'file.vue': '/file', 9 | 'index.vue': '/', 10 | 'foo/index.vue': '/foo', 11 | 'test.html.vue': '/test.html', 12 | '[slug].vue': '/file', 13 | '/file/[...slug].vue': '/file/here/we/go', 14 | '[a1_1a].vue': '/file', 15 | '[b2.2b].vue': '/file', 16 | 'test:name.vue': '/test:name', 17 | // TODO: mixed parameters are not (yet?) supported in radix3 18 | // '[b2]_[2b].vue': '/fi_le', 19 | // TODO: optional parameters are not (yet?) supported in radix3 20 | // '[[foo]]/index.vue': '/some', 21 | // '[[sub]]/route-[slug].vue': '/some/route-value', 22 | // 'optional/[[opt]].vue': '/optional', 23 | // 'optional/prefix-[[opt]].vue': '/optional/prefix-test', 24 | // 'optional/[[opt]]-postfix.vue': '/optional/some-postfix', 25 | // 'optional/prefix-[[opt]]-postfix.vue': '/optional/prefix--postfix', 26 | // '[[c3@3c]].vue': '/file', 27 | // '[[d4-4d]].vue': '/file', 28 | } 29 | 30 | it('toRadix3', () => { 31 | const result = Object.fromEntries(Object.entries(paths).map(([path, example]) => { 32 | const routeMatcher = createRadixRouter() 33 | routeMatcher.insert(toRadix3(path), { value: example }) 34 | const result = routeMatcher.lookup(example) 35 | return [path, result?.params || result?.value] 36 | })) 37 | 38 | expect(result).toMatchInlineSnapshot(` 39 | { 40 | "/file/[...slug].vue": { 41 | "slug": "here/we/go", 42 | }, 43 | "[a1_1a].vue": { 44 | "a1_1a": "file", 45 | }, 46 | "[b2.2b].vue": { 47 | "b2.2b": "file", 48 | }, 49 | "[slug].vue": { 50 | "slug": "file", 51 | }, 52 | "file.vue": "/file", 53 | "foo/index.vue": "/foo", 54 | "index.vue": "/", 55 | "test.html.vue": "/test.html", 56 | "test:name.vue": "/test:name", 57 | } 58 | `) 59 | }) 60 | }) 61 | 62 | describe('regexp support', () => { 63 | const paths = { 64 | 'file.vue': '/file', 65 | 'test.html.vue': '/test.html', 66 | '[slug].vue': '/file', 67 | 'index.vue': '/', 68 | 'foo/index.vue': '/foo', 69 | '[...slug].vue': '/file/here/we/go', 70 | '[[foo]]/index.vue': '/some', 71 | '[[sub]]/route-[slug].vue': '/some/route-value', 72 | 'optional/[[opt]].vue': '/optional', 73 | 'optional/prefix-[[opt]].vue': '/optional/prefix-test', 74 | 'optional/[[opt]]-postfix.vue': '/optional/some-postfix', 75 | 'optional/prefix-[[opt]]-postfix.vue': '/optional/prefix--postfix', 76 | '[a1_1a].vue': '/file', 77 | '[b2.2b].vue': '/file', 78 | '[b2]_[2b].vue': '/fi_le', 79 | '[[c3@3c]].vue': '/file', 80 | '[[d4-4d]].vue': '/file', 81 | 'test:name.vue': '/test:name', 82 | } 83 | 84 | it('toRegExp', () => { 85 | const result = Object.fromEntries(Object.entries(paths).map(([path, example]) => { 86 | const result = example.match(toRegExp(path)) 87 | return [path, { 88 | regexp: toRegExp(path).toString(), 89 | result: result?.groups || result?.[0], 90 | }] 91 | })) 92 | expect(result).toMatchInlineSnapshot(` 93 | { 94 | "[...slug].vue": { 95 | "regexp": "/\\/(?:(?.*)\\/?)?/", 96 | "result": { 97 | "slug": "file/here/we/go", 98 | }, 99 | }, 100 | "[[c3@3c]].vue": { 101 | "regexp": "/\\/(?:(?[^/]*)\\/?)?/", 102 | "result": { 103 | "c33c": "file", 104 | }, 105 | }, 106 | "[[d4-4d]].vue": { 107 | "regexp": "/\\/(?:(?[^/]*)\\/?)?/", 108 | "result": { 109 | "d44d": "file", 110 | }, 111 | }, 112 | "[[foo]]/index.vue": { 113 | "regexp": "/\\/(?:(?[^/]*)\\/?)?/", 114 | "result": { 115 | "foo": "some", 116 | }, 117 | }, 118 | "[[sub]]/route-[slug].vue": { 119 | "regexp": "/\\/(?:(?[^/]*)\\/?)route\\x2d(?[^/]+)\\/?/", 120 | "result": { 121 | "slug": "value", 122 | "sub": "some", 123 | }, 124 | }, 125 | "[a1_1a].vue": { 126 | "regexp": "/\\/(?[^/]+)\\/?/", 127 | "result": { 128 | "a1_1a": "file", 129 | }, 130 | }, 131 | "[b2.2b].vue": { 132 | "regexp": "/\\/(?[^/]+)\\/?/", 133 | "result": { 134 | "b22b": "file", 135 | }, 136 | }, 137 | "[b2]_[2b].vue": { 138 | "regexp": "/\\/(?[^/]+)_(?<_2b>[^/]+)\\/?/", 139 | "result": { 140 | "_2b": "le", 141 | "b2": "fi", 142 | }, 143 | }, 144 | "[slug].vue": { 145 | "regexp": "/\\/(?[^/]+)\\/?/", 146 | "result": { 147 | "slug": "file", 148 | }, 149 | }, 150 | "file.vue": { 151 | "regexp": "/\\/file\\/?/", 152 | "result": "/file", 153 | }, 154 | "foo/index.vue": { 155 | "regexp": "/\\/foo\\/?/", 156 | "result": "/foo", 157 | }, 158 | "index.vue": { 159 | "regexp": "/\\/?/", 160 | "result": "/", 161 | }, 162 | "optional/[[opt]]-postfix.vue": { 163 | "regexp": "/\\/optional\\/(?[^/]*)\\x2dpostfix\\/?/", 164 | "result": { 165 | "opt": "some", 166 | }, 167 | }, 168 | "optional/[[opt]].vue": { 169 | "regexp": "/\\/optional\\/(?:(?[^/]*)\\/?)?/", 170 | "result": undefined, 171 | }, 172 | "optional/prefix-[[opt]]-postfix.vue": { 173 | "regexp": "/\\/optional\\/prefix\\x2d(?[^/]*)\\x2dpostfix\\/?/", 174 | "result": { 175 | "opt": "", 176 | }, 177 | }, 178 | "optional/prefix-[[opt]].vue": { 179 | "regexp": "/\\/optional\\/prefix\\x2d(?[^/]*)\\/?/", 180 | "result": { 181 | "opt": "test", 182 | }, 183 | }, 184 | "test.html.vue": { 185 | "regexp": "/\\/test\\.html\\/?/", 186 | "result": "/test.html", 187 | }, 188 | "test:name.vue": { 189 | "regexp": "/\\/test:name\\/?/", 190 | "result": "/test:name", 191 | }, 192 | } 193 | `) 194 | }) 195 | }) 196 | 197 | describe('vue-router support', () => { 198 | const paths = { 199 | 'file.vue': '/file', 200 | 'test.html.vue': '/test.html', 201 | '[slug].vue': '/file', 202 | 'index.vue': '/', 203 | 'foo/index.vue': '/foo', 204 | '[...slug].vue': '/file/here/we/go', 205 | '[[foo]]/index.vue': '/some', 206 | '[[sub]]/route-[slug].vue': '/some/route-value', 207 | 'optional/[[opt]].vue': '/optional', 208 | 'optional/prefix-[[opt]].vue': '/optional/prefix-test', 209 | 'optional/[[opt]]-postfix.vue': '/optional/some-postfix', 210 | 'optional/prefix-[[opt]]-postfix.vue': '/optional/prefix--postfix', 211 | '[a1_1a].vue': '/file', 212 | // TODO: should this be allowed? 213 | // '[b2.2b].vue': '/file', 214 | '[b2]_[2b].vue': '/fi_le', 215 | '[[c3@3c]].vue': '/file', 216 | '[[d4-4d]].vue': '/file', 217 | 'test:name.vue': '/test:name', 218 | } 219 | 220 | it('toVueRouter4', () => { 221 | const result = Object.fromEntries(Object.entries(paths).map(([path, example]) => { 222 | const route = toVueRouter4(path) 223 | const router = createVueRouter({ 224 | history: createMemoryHistory(), 225 | routes: [{ 226 | ...route, 227 | component: () => ({}), 228 | meta: { 229 | value: example, 230 | }, 231 | }], 232 | }) 233 | const result = router.resolve(example) 234 | return [path, result?.meta.value && result.params] 235 | })) 236 | expect(result).toMatchInlineSnapshot(` 237 | { 238 | "[...slug].vue": { 239 | "slug": [ 240 | "file", 241 | "here", 242 | "we", 243 | "go", 244 | ], 245 | }, 246 | "[[c3@3c]].vue": { 247 | "c33c": "file", 248 | }, 249 | "[[d4-4d]].vue": { 250 | "d44d": "file", 251 | }, 252 | "[[foo]]/index.vue": { 253 | "foo": "some", 254 | }, 255 | "[[sub]]/route-[slug].vue": { 256 | "slug": "value", 257 | "sub": "some", 258 | }, 259 | "[a1_1a].vue": { 260 | "a1_1a": "file", 261 | }, 262 | "[b2]_[2b].vue": { 263 | "2b": "le", 264 | "b2": "fi", 265 | }, 266 | "[slug].vue": { 267 | "slug": "file", 268 | }, 269 | "file.vue": {}, 270 | "foo/index.vue": {}, 271 | "index.vue": {}, 272 | "optional/[[opt]]-postfix.vue": { 273 | "opt": "some", 274 | }, 275 | "optional/[[opt]].vue": { 276 | "opt": "", 277 | }, 278 | "optional/prefix-[[opt]]-postfix.vue": { 279 | "opt": "", 280 | }, 281 | "optional/prefix-[[opt]].vue": { 282 | "opt": "test", 283 | }, 284 | "test.html.vue": {}, 285 | "test:name.vue": {}, 286 | } 287 | `) 288 | }) 289 | }) 290 | -------------------------------------------------------------------------------- /test/unit/integration.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, it } from 'vitest' 2 | 3 | describe('nuxt routing', () => { 4 | const _staticExamples = { 5 | 'index.vue': '/', 6 | 'admin/index.vue': '/admin', 7 | 'admin/users/index.vue': '/admin/users', 8 | 'admin/settings/index.vue': '/admin/settings', 9 | 'admin/settings/profile/index.vue': '/admin/settings/profile', 10 | } 11 | const _dynamicExamples = { 12 | 'user/[userId].vue': [[{ userId: 'foo' }, '/user/foo']], 13 | 'post/[slug].vue': [[{ slug: 'foo' }, '/post/foo']], 14 | 'post/[...slug].vue': [ 15 | [{}, '/post'], 16 | [{ slug: ['foo'] }, '/post/foo'], 17 | [{ slug: ['foo', 'bar'] }, '/post/foo/bar'], 18 | ], 19 | } 20 | it.todo('should parse examples', () => { 21 | 22 | }) 23 | }) 24 | 25 | describe('sveltekit routing', () => { 26 | const _staticExamples = { 27 | '+page.svelte': '/', 28 | 'admin/+page.svelte': '/admin', 29 | } 30 | const _dynamicExamples = { 31 | 'blog/[slug]/+page.svelte': [[{ slug: 'foo' }, '/blog/foo']], 32 | } 33 | it.todo('should serialise examples to routes', () => {}) 34 | }) 35 | 36 | describe('next.js app directory routing', () => { 37 | // examples of Next.js fs routing 38 | const _staticExamples = { 39 | 'app/page.tsx': '/', 40 | 'app/admin/page.tsx': '/admin', 41 | 'app/admin/users/page.tsx': '/admin/users', 42 | 'app/admin/settings/page.tsx': '/admin/settings', 43 | 'app/admin/settings/profile/page.tsx': '/admin/settings/profile', 44 | } 45 | const _dynamicExamples = { 46 | 'app/user/[userId]/page.tsx': [[{ userId: 'foo' }, '/user/foo']], 47 | 'app/post/[slug]/page.tsx': [[{ slug: 'foo' }, '/post/foo']], 48 | 'app/post/[...slug]/page.tsx': [ 49 | [{}, '/post'], 50 | [{ slug: ['foo'] }, '/post/foo'], 51 | [{ slug: ['foo', 'bar'] }, '/post/foo/bar'], 52 | ], 53 | } 54 | it.todo('should parse examples', () => {}) 55 | it.todo('should serialise examples to routes', () => {}) 56 | }) 57 | -------------------------------------------------------------------------------- /test/unit/parse.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest' 2 | import { parsePath } from '../../src' 3 | 4 | describe('parsing vue file paths', () => { 5 | const paths = [ 6 | 'file.vue', 7 | 'test.html.vue', 8 | '[slug].vue', 9 | '[...slug].vue', 10 | '[[foo]]/index.vue', 11 | '[[sub]]/route-[slug].vue', 12 | 'optional/[[opt]].vue', 13 | 'optional/prefix-[[opt]].vue', 14 | 'optional/[[opt]]-postfix.vue', 15 | 'optional/prefix-[[opt]]-postfix.vue', 16 | '[a1_1a].vue', 17 | '[b2.2b].vue', 18 | '[b2]_[2b].vue', 19 | '[[c3@3c]].vue', 20 | '[[d4-4d]].vue', 21 | 'test:name.vue', 22 | ] 23 | const errors = [ 24 | '[slug.vue', 25 | '[].vue', 26 | ] 27 | 28 | it('throws errors when appropriate', () => { 29 | for (const path of errors) { 30 | let err 31 | try { 32 | parsePath(path) 33 | } 34 | catch (e) { 35 | err = e 36 | } 37 | expect(err).toBeDefined() 38 | } 39 | }) 40 | 41 | it('works', () => { 42 | const result = Object.fromEntries(paths.map(path => [path, parsePath(path)])) 43 | expect(result).toMatchInlineSnapshot(` 44 | { 45 | "[...slug].vue": [ 46 | [ 47 | { 48 | "type": "catchall", 49 | "value": "slug", 50 | }, 51 | ], 52 | ], 53 | "[[c3@3c]].vue": [ 54 | [ 55 | { 56 | "type": "optional", 57 | "value": "c33c", 58 | }, 59 | ], 60 | ], 61 | "[[d4-4d]].vue": [ 62 | [ 63 | { 64 | "type": "optional", 65 | "value": "d44d", 66 | }, 67 | ], 68 | ], 69 | "[[foo]]/index.vue": [ 70 | [ 71 | { 72 | "type": "optional", 73 | "value": "foo", 74 | }, 75 | ], 76 | [ 77 | { 78 | "type": "static", 79 | "value": "", 80 | }, 81 | ], 82 | ], 83 | "[[sub]]/route-[slug].vue": [ 84 | [ 85 | { 86 | "type": "optional", 87 | "value": "sub", 88 | }, 89 | ], 90 | [ 91 | { 92 | "type": "static", 93 | "value": "route-", 94 | }, 95 | { 96 | "type": "dynamic", 97 | "value": "slug", 98 | }, 99 | ], 100 | ], 101 | "[a1_1a].vue": [ 102 | [ 103 | { 104 | "type": "dynamic", 105 | "value": "a1_1a", 106 | }, 107 | ], 108 | ], 109 | "[b2.2b].vue": [ 110 | [ 111 | { 112 | "type": "dynamic", 113 | "value": "b2.2b", 114 | }, 115 | ], 116 | ], 117 | "[b2]_[2b].vue": [ 118 | [ 119 | { 120 | "type": "dynamic", 121 | "value": "b2", 122 | }, 123 | { 124 | "type": "static", 125 | "value": "_", 126 | }, 127 | { 128 | "type": "dynamic", 129 | "value": "2b", 130 | }, 131 | ], 132 | ], 133 | "[slug].vue": [ 134 | [ 135 | { 136 | "type": "dynamic", 137 | "value": "slug", 138 | }, 139 | ], 140 | ], 141 | "file.vue": [ 142 | [ 143 | { 144 | "type": "static", 145 | "value": "file", 146 | }, 147 | ], 148 | ], 149 | "optional/[[opt]]-postfix.vue": [ 150 | [ 151 | { 152 | "type": "static", 153 | "value": "optional", 154 | }, 155 | ], 156 | [ 157 | { 158 | "type": "optional", 159 | "value": "opt", 160 | }, 161 | { 162 | "type": "static", 163 | "value": "-postfix", 164 | }, 165 | ], 166 | ], 167 | "optional/[[opt]].vue": [ 168 | [ 169 | { 170 | "type": "static", 171 | "value": "optional", 172 | }, 173 | ], 174 | [ 175 | { 176 | "type": "optional", 177 | "value": "opt", 178 | }, 179 | ], 180 | ], 181 | "optional/prefix-[[opt]]-postfix.vue": [ 182 | [ 183 | { 184 | "type": "static", 185 | "value": "optional", 186 | }, 187 | ], 188 | [ 189 | { 190 | "type": "static", 191 | "value": "prefix-", 192 | }, 193 | { 194 | "type": "optional", 195 | "value": "opt", 196 | }, 197 | { 198 | "type": "static", 199 | "value": "-postfix", 200 | }, 201 | ], 202 | ], 203 | "optional/prefix-[[opt]].vue": [ 204 | [ 205 | { 206 | "type": "static", 207 | "value": "optional", 208 | }, 209 | ], 210 | [ 211 | { 212 | "type": "static", 213 | "value": "prefix-", 214 | }, 215 | { 216 | "type": "optional", 217 | "value": "opt", 218 | }, 219 | ], 220 | ], 221 | "test.html.vue": [ 222 | [ 223 | { 224 | "type": "static", 225 | "value": "test.html", 226 | }, 227 | ], 228 | ], 229 | "test:name.vue": [ 230 | [ 231 | { 232 | "type": "static", 233 | "value": "test:name", 234 | }, 235 | ], 236 | ], 237 | } 238 | `) 239 | }) 240 | }) 241 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "module": "ESNext", 5 | "moduleResolution": "Bundler", 6 | "strict": true, 7 | "esModuleInterop": true, 8 | "skipLibCheck": true 9 | }, 10 | "include": ["src", "test", "playground"] 11 | } 12 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { fileURLToPath } from 'node:url' 2 | import { defineConfig } from 'vitest/config' 3 | 4 | export default defineConfig({ 5 | resolve: { 6 | alias: { 7 | unrouting: fileURLToPath( 8 | new URL('./src/index.ts', import.meta.url).href, 9 | ), 10 | }, 11 | }, 12 | test: { 13 | coverage: { 14 | include: ['src'], 15 | reporter: ['text', 'json', 'html'], 16 | }, 17 | }, 18 | }) 19 | --------------------------------------------------------------------------------