1
0

25 Commits

Author SHA1 Message Date
eea9e580f6 3.0.0 2023-08-19 18:10:11 +02:00
68e614b3fa prepare workflow for release 2023-08-19 18:00:13 +02:00
7a20454f79 update dependencies 2023-08-19 17:55:53 +02:00
101de4f5f6 3.0.0-16 2023-05-25 20:38:48 +02:00
9ee1182fa9 update node for dev 2023-05-25 20:37:41 +02:00
0309b0131f update migration guide 2023-05-25 20:34:55 +02:00
afd7ea662f 3.0.0-15 2023-05-25 20:01:45 +02:00
a742753cb7 update workflow 2023-05-25 20:01:36 +02:00
d631645b99 3.0.0-14 2023-05-25 19:55:37 +02:00
cb1bf98053 update types 2023-05-25 19:55:25 +02:00
648514a3c7 3.0.0-13 2023-05-25 19:52:56 +02:00
34f4512dee allow for context extension 2023-05-25 19:52:31 +02:00
02b65e85e6 clean up 2023-05-25 17:35:11 +02:00
d71b0638c4 3.0.0-12 2023-03-15 22:04:06 +01:00
0c7f04d71b make body reusable 2023-03-15 22:04:06 +01:00
c18e164018 update dependencies 2023-03-15 01:31:33 +01:00
307a93d86c 3.0.0-11 2023-02-21 15:45:20 +01:00
3a955af1bc fix cors edge case 2023-02-21 15:45:12 +01:00
db22422968 add arrayBuffer, text, formData, blob 2023-02-21 15:44:49 +01:00
0a73e4c32e 3.0.0-10 2023-02-05 02:11:19 +01:00
8bd8e50ee5 update 2023-02-05 02:11:09 +01:00
e4ec06bf47 3.0.0-9 2023-02-05 01:46:53 +01:00
2ad75dc3fb move things around, update body behavior 2023-02-05 01:46:20 +01:00
c2b6189a86 3.0.0-8 2023-02-02 20:53:11 +01:00
33cafbf17c update replace to be case insensitive 2023-02-02 20:53:02 +01:00
6 changed files with 99 additions and 78 deletions

View File

@@ -1,4 +1,4 @@
name: Publish (pre)
name: Publish (main)
on:
release:
@@ -11,7 +11,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
node-version: latest
registry-url: https://registry.npmjs.org/
- name: Install dependencies
run: npm ci
@@ -20,11 +20,12 @@ jobs:
- name: Publish to npmjs
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
run: npm publish --tag pre --access public
- uses: actions/setup-node@v1
run: npm publish --tag latest --access public
- uses: actions/setup-node@v3
with:
node-version: latest
registry-url: https://npm.pkg.github.com/
- name: Publish to GPR
env:
NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}}
run: npm publish --tag pre --access public
run: npm publish --tag latest --access public

1
.nvmrc
View File

@@ -1 +0,0 @@
v16

View File

@@ -15,7 +15,7 @@ From `v2.x.x` to `v3.x.x`.
Update to the latest version version of the router.
```bash
npm i -D @tsndr/cloudflare-worker-router
npm i -D @tsndr/cloudflare-worker-router@^3
```

38
package-lock.json generated
View File

@@ -1,50 +1,36 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-7",
"lockfileVersion": 2,
"version": "3.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-7",
"version": "3.0.0",
"license": "MIT",
"devDependencies": {
"@cloudflare/workers-types": "^4.20230115.0",
"typescript": "^4.9.5"
"@cloudflare/workers-types": "^4.20230814.0",
"typescript": "^5.1.6"
}
},
"node_modules/@cloudflare/workers-types": {
"version": "4.20230115.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
"integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
"version": "4.20230814.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230814.0.tgz",
"integrity": "sha512-+jHiGjZg2UpULZSSHmHLqUG45TLg1s+uppSMlGvMn0u/xyFsRX9HX6b8Ydg/oHSp3jfSuPtX05GSvtgRAmrWTg==",
"dev": true
},
"node_modules/typescript": {
"version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.1.6.tgz",
"integrity": "sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
"node": ">=14.17"
}
}
},
"dependencies": {
"@cloudflare/workers-types": {
"version": "4.20230115.0",
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20230115.0.tgz",
"integrity": "sha512-GPJEiO8AFN+jUpA+DHJ1qdVmk4s/hq8JYKjOV/+U7avGquQbVnj905+Kg6uAEfrq16muwmRKl+XJGqsvlBlDNg==",
"dev": true
},
"typescript": {
"version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.0.0-7",
"version": "3.0.0",
"description": "",
"main": "index.js",
"types": "index.d.ts",
@@ -31,7 +31,7 @@
},
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
"devDependencies": {
"@cloudflare/workers-types": "^4.20230115.0",
"typescript": "^4.9.5"
"@cloudflare/workers-types": "^4.20230814.0",
"typescript": "^5.1.6"
}
}

View File

@@ -6,10 +6,10 @@
* @property {string} url URL String
* @property {RouterHandler[]} handlers Array of handler functions
*/
export type Route<TEnv, TExt> = {
export type Route<TEnv, TCtx, TReq> = {
method: string
url: string
handlers: RouterHandler<TEnv, TExt>[]
handlers: RouterHandler<TEnv, TCtx, TReq>[]
}
/**
@@ -20,9 +20,9 @@ export type Route<TEnv, TExt> = {
* @property {RouterRequest} req Request Object
* @property {ExecutionContext} ctx Context Object
*/
export type RouterContext<TEnv = any, TExt = any> = {
export type RouterContext<TEnv = any, TCtx = any, TReq = any> = TCtx & {
env: TEnv
req: RouterRequest<TExt>
req: RouterRequest<TReq>
dbg: boolean
ctx?: ExecutionContext
}
@@ -36,20 +36,24 @@ export type RouterContext<TEnv = any, TExt = any> = {
* @property {RouterRequestParams} params Object containing all parameters defined in the url string
* @property {RouterRequestQuery} query Object containing all query parameters
* @property {Headers} headers Request headers object
* @property {string | any} body Only available if method is `POST`, `PUT`, `PATCH` or `DELETE`. Contains either the received body string or a parsed object if valid JSON was sent.
* @property {Request} raw Raw Request Object
* @property {IncomingRequestCfProperties} [cf] object containing custom Cloudflare properties. (https://developers.cloudflare.com/workers/examples/accessing-the-cloudflare-object)
*/
export type RouterRequest<TExt> = {
export type RouterRequest<TReq> = TReq & {
url: string
method: string
params: RouterRequestParams
query: RouterRequestQuery
headers: Headers
body: string | any
raw: Request
arrayBuffer(): Promise<ArrayBuffer>
text(): Promise<string>
json<T>(): Promise<T>
formData(): Promise<FormData>
blob(): Promise<Blob>
bearer: () => string | undefined
cf?: IncomingRequestCfProperties
bearer: () => string
} & TExt
}
/**
* Request Parameters
@@ -76,8 +80,8 @@ export type RouterRequestQuery = {
* @param {RouterContext} ctx
* @returns {Promise<Response | void> Response | void}
*/
export type RouterHandler<TEnv = any, TExt = any> = {
(ctx: RouterContext<TEnv, TExt>): Promise<Response | void> | Response | void
export type RouterHandler<TEnv = any, TCtx = any, TReq = any> = {
(ctx: RouterContext<TEnv, TCtx, TReq>): Promise<Response | void> | Response | void
}
/**
@@ -98,13 +102,21 @@ export type RouterCorsConfig = {
optionsSuccessStatus?: number
}
export type RouterBuffer = {
arrayBuffer?: ArrayBuffer
text?: string
json?: any
formData?: FormData
blob?: Blob
}
/**
* Router
*
* @public
* @class
*/
export class Router<TEnv = any, TExt = any> {
export class Router<TEnv = any, TCtx = any, TReq = any> {
/**
* Router Array
@@ -112,7 +124,7 @@ export class Router<TEnv = any, TExt = any> {
* @protected
* @type {Route[]}
*/
protected routes: Route<TEnv, TExt>[] = []
protected routes: Route<TEnv, TCtx, TReq>[] = []
/**
* Global Handlers
@@ -120,7 +132,7 @@ export class Router<TEnv = any, TExt = any> {
* @protected
* @type {RouterHandler[]}
*/
protected globalHandlers: RouterHandler<TEnv, TExt>[] = []
protected globalHandlers: RouterHandler<TEnv, TCtx, TReq>[] = []
/**
* Debug Mode
@@ -138,6 +150,14 @@ export class Router<TEnv = any, TExt = any> {
*/
protected corsConfig: RouterCorsConfig = {}
/**
* Buffer
*
* @protected
* @type {RouterBuffer}
*/
protected buffer: RouterBuffer = {}
/**
* CORS enabled
*
@@ -152,7 +172,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public use(...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public use(...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
for (let handler of handlers) {
this.globalHandlers.push(handler)
}
@@ -166,7 +186,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public connect(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public connect(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('CONNECT', url, handlers)
}
@@ -177,7 +197,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public delete(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public delete(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('DELETE', url, handlers)
}
@@ -188,7 +208,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public get(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public get(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('GET', url, handlers)
}
@@ -199,7 +219,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public head(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public head(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('HEAD', url, handlers)
}
@@ -210,7 +230,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public options(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public options(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('OPTIONS', url, handlers)
}
@@ -221,7 +241,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public patch(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public patch(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('PATCH', url, handlers)
}
@@ -232,7 +252,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public post(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public post(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('POST', url, handlers)
}
@@ -243,7 +263,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public put(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public put(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('PUT', url, handlers)
}
@@ -254,7 +274,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public trace(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public trace(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('TRACE', url, handlers)
}
@@ -265,7 +285,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public any(url: string, ...handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
public any(url: string, ...handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
return this.register('*', url, handlers)
}
@@ -275,7 +295,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {boolean} [state=true] Whether to turn on or off debug mode (default: true)
* @returns {Router}
*/
public debug(state: boolean = true): Router<TEnv, TExt> {
public debug(state: boolean = true): Router<TEnv, TCtx, TReq> {
this.debugMode = state
return this
}
@@ -286,7 +306,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterCorsConfig} [config]
* @returns {Router}
*/
public cors(config?: RouterCorsConfig): Router<TEnv, TExt> {
public cors(config?: RouterCorsConfig): Router<TEnv, TCtx, TReq> {
this.corsEnabled = true
this.corsConfig = {
allowOrigin: config?.allowOrigin ?? '*',
@@ -319,7 +339,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterHandler[]} handlers Arrar of handler functions
* @returns {Router}
*/
private register(method: string, url: string, handlers: RouterHandler<TEnv, TExt>[]): Router<TEnv, TExt> {
private register(method: string, url: string, handlers: RouterHandler<TEnv, TCtx, TReq>[]): Router<TEnv, TCtx, TReq> {
this.routes.push({
method,
url,
@@ -336,7 +356,7 @@ export class Router<TEnv = any, TExt = any> {
* @param {RouterRequest} request
* @returns {Route | undefined}
*/
private getRoute(request: RouterRequest<TExt>): Route<TEnv, TExt> | undefined {
private getRoute(request: RouterRequest<TReq>): Route<TEnv, TCtx, TReq> | undefined {
const url = new URL(request.url)
const pathArr = url.pathname.split('/').filter(i => i)
@@ -375,12 +395,13 @@ export class Router<TEnv = any, TExt = any> {
*
* @param {Request} request
* @param {TEnv} env
* @param {TExt} [ext]
* @param {TCtx} [extCtx]
* @param {TReq} [extReq]
* @returns {Promise<Response>}
*/
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, ext?: TExt): Promise<Response> {
public async handle(request: Request, env: TEnv, ctx?: ExecutionContext, extCtx?: TCtx, extReq?: TReq): Promise<Response> {
const req = {
...(ext ?? {}),
...(extReq ?? {}),
method: request.method,
headers: request.headers,
url: request.url,
@@ -388,14 +409,13 @@ export class Router<TEnv = any, TExt = any> {
raw: request,
params: {},
query: {},
body: '',
bearer: () => request.headers.get('Authorization')?.replace('Bearer ', '').trim() ?? '',
} as RouterRequest<TExt>
const route = this.getRoute(req)
if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
arrayBuffer: async (): Promise<ArrayBuffer> => this.buffer.arrayBuffer ? this.buffer.arrayBuffer : this.buffer.arrayBuffer = await request.arrayBuffer(),
text: async (): Promise<string> => this.buffer.text ? this.buffer.text : this.buffer.text = await request.text(),
json: async <T>(): Promise<T> => this.buffer.json ? this.buffer.json : this.buffer.json = await request.json<T>(),
formData: async (): Promise<FormData> => this.buffer.formData ? this.buffer.formData : this.buffer.formData = await request.formData(),
blob: async (): Promise<Blob> => this.buffer.blob ? this.buffer.blob : this.buffer.blob = await request.blob(),
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
} as RouterRequest<TReq>
if (this.corsEnabled && req.method === 'OPTIONS') {
return new Response(null, {
@@ -404,13 +424,26 @@ export class Router<TEnv = any, TExt = any> {
})
}
const route = this.getRoute(req)
if (!route)
return new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
const handlers = [...this.globalHandlers, ...route.handlers]
const dbg = this.debugMode
let response: Response | undefined
for (const handler of handlers) {
const res = await handler({ env, req, dbg, ctx })
const context = {
...(extCtx ?? {}),
env,
req,
dbg,
ctx
} as RouterContext<TEnv, TCtx, TReq>
const res = await handler(context)
if (res) {
response = res
@@ -421,8 +454,10 @@ export class Router<TEnv = any, TExt = any> {
if (!response)
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
if (this.corsEnabled)
if (this.corsEnabled) {
response = new Response(response.body, response)
this.setCorsHeaders(response.headers)
}
return response
}