rsnext/packages/next/next-server/server/lib/path-match.ts
Tim Neutkens 2ba352da39 Move next-server back into next package (#8613)
* Initial move

* Make emitting work

* Update paths

* Remove leftover files

* Add correct externals configuration

* Import correct path

* Update path to work with ts-server test

* Update lib directory

* Compile next-server/lib
2019-09-04 10:00:54 -04:00

42 lines
1.1 KiB
TypeScript

// We borrow this code from https://github.com/pillarjs/path-match
// That's because, ^^^ package comes with very old version of path-to-regexp
// So, it'll give us issues when the app has used a newer version of path-to-regexp
// (When webpack resolving packages)
const pathToRegexp = require('path-to-regexp')
export default () => {
return (path: string) => {
const keys: any[] = []
const re = pathToRegexp(path, keys, {})
return (pathname: string | undefined, params?: any) => {
const m = re.exec(pathname)
if (!m) return false
params = params || {}
let key
let param
for (let i = 0; i < keys.length; i++) {
key = keys[i]
param = m[i + 1]
if (!param) continue
params[key.name] = decodeParam(param)
if (key.repeat) params[key.name] = params[key.name].split(key.delimiter)
}
return params
}
}
}
function decodeParam(param: string) {
try {
return decodeURIComponent(param)
} catch (_) {
const err = new Error('failed to decode param')
// @ts-ignore DECODE_FAILED is handled
err.code = 'DECODE_FAILED'
throw err
}
}