1
0

39 Commits

Author SHA1 Message Date
7faffa3dd9 3.3.0 2025-07-24 21:57:37 +02:00
a08adf3c03 add basic helper function 2025-07-24 21:56:26 +02:00
2e594d09f5 update bearer regex 2025-07-24 21:56:11 +02:00
d1c84cf6f6 3.2.10 2024-10-26 23:08:28 +02:00
ba67b34a0d update pipelines 2024-10-26 23:08:10 +02:00
2d5bdfe40e update readme 2024-10-26 23:07:54 +02:00
7bb935fa53 update publish pipeline 2024-10-26 21:55:21 +02:00
49d5806d89 3.2.9 2024-10-26 21:42:49 +02:00
73a0d4a4f9 update dependencies, build for esm 2024-10-26 21:42:35 +02:00
24a85e9814 3.2.8 2024-09-28 02:29:17 +02:00
dfdc50ba8a update dev dependencies 2024-09-28 02:29:04 +02:00
67bba2a339 3.2.7 2024-09-28 02:25:54 +02:00
c21e91bcb6 npm audit fix 2024-09-28 02:25:46 +02:00
fe2f8ec227 3.2.6 2024-09-28 02:19:32 +02:00
0e78ec4787 return cors headers for 404 response as well 2024-09-28 02:19:07 +02:00
fd7dce7256 3.2.5 2024-09-28 01:53:00 +02:00
1d72a15ca6 update readme 2024-09-28 01:51:05 +02:00
a740f1b103 audit fix 2024-07-15 22:14:32 +02:00
21dc38b676 update keywords 2024-02-24 21:03:35 +01:00
9df19a50cd change to module 2024-02-24 20:59:03 +01:00
7dce99214d switch to vitest 2024-02-24 20:55:23 +01:00
5aedc0248d 3.2.4 2024-01-20 23:39:07 +01:00
3aecc4ca5f update npmignore 2024-01-20 23:38:58 +01:00
e04bcfb395 3.2.3 2024-01-20 23:32:28 +01:00
f2ba5f5bc5 update npmignore 2024-01-20 23:32:17 +01:00
306c046adb update test 2024-01-20 02:49:45 +01:00
2dab64be19 rename job 2024-01-20 02:37:12 +01:00
175deddc9c fix import 2024-01-20 02:36:32 +01:00
ff638ad04f add testing github action 2024-01-20 02:35:06 +01:00
b118c28dc7 3.2.2 2024-01-20 02:28:22 +01:00
9451f466fc move test file to tests directory 2024-01-20 02:27:50 +01:00
71fcd6c3c0 3.2.1 2024-01-20 02:25:07 +01:00
e55392d890 remove connect and trace method 2024-01-20 02:24:38 +01:00
3aaecd8877 3.2.0 2024-01-20 02:22:15 +01:00
d8d13c4339 add npm test command 2024-01-20 02:19:22 +01:00
09d5586cc6 add more tests 2024-01-20 02:15:55 +01:00
110bfdd95c even more tests 2024-01-20 02:15:55 +01:00
c68a979614 working on testing 2024-01-20 02:15:55 +01:00
a4fd646d6b remove connect and trace methods 2024-01-20 02:15:34 +01:00
13 changed files with 1221 additions and 3741 deletions

View File

@@ -11,3 +11,7 @@ indent_style = tab
[README.md]
indent_style = space
indent_size = 4
[{package,package-lock}.json]
indent_style = space
indent_size = 2

View File

@@ -1,8 +1,9 @@
name: Publish (main)
name: Publish
run-name: Publish ${{ github.ref_name }}
on:
release:
types: [published]
types: [ published ]
jobs:
publish:
@@ -13,19 +14,27 @@ jobs:
with:
node-version: latest
registry-url: https://registry.npmjs.org/
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
- name: Publish to npmjs
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
run: npm publish --tag latest --access public
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || '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 latest --access public
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: npm publish --tag ${{ contains(github.ref_name, '-') && 'pre' || 'latest' }} --access public

31
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Release
run-name: Release ${{ github.ref_name }}
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: latest
registry-url: https://registry.npmjs.org/
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build
- name: Create release
run: gh release create ${{ github.ref_name }} --draft --generate-notes ${{ contains(github.ref_name, '-') && '--prerelease --latest=false' || '--latest' }}
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

26
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,26 @@
name: Test
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: latest
registry-url: https://registry.npmjs.org/
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Build
run: npm run build

View File

@@ -1,7 +1,10 @@
.github/
src/
test/
.nvmrc
MIGRATION.md
tsconfig.json
.editorconfig
.github/
.gitignore
.nvmrc
coverage/
jest.config.ts
MIGRATION.md
src/
tests/
tsconfig.json

View File

@@ -4,8 +4,6 @@ Cloudflare Workers Router is a super lightweight router (1.0K gzipped) with midd
When I was trying out Cloudflare Workers I almost immediately noticed how fast it was compared to other serverless offerings. So I wanted to build a full-fledged API to see how it performs doing real work, but since I wasn't able to find a router that suited my needs I created my own.
I worked a lot with [Express.js](https://expressjs.com/) in the past and really enjoyed their middleware approach, but since none of the available Cloudflare Worker routers offered middleware support at the time, I felt the need to create this router.
## Contents
@@ -20,8 +18,9 @@ I worked a lot with [Express.js](https://expressjs.com/) in the past and really
- ZERO dependencies
- Lightweight (1.0K gzipped)
- Fully written in TypeScript
- Integrated Debug-Mode & CORS helper
- Built specifically around Middlewares
- Debug-Mode, CORS and Bearer helpers
- Allows accessing request body multiple times
## Usage
@@ -240,7 +239,6 @@ Key | Type | Default Value
### Supported Methods
- `router.any(url, [...handlers])`
- `router.connect(url, [...handlers])`
- `router.delete(url, [...handlers])`
- `router.get(url, [...handlers])`
- `router.head(url, [...handlers])`
@@ -248,7 +246,6 @@ Key | Type | Default Value
- `router.patch(url, [...handlers])`
- `router.post(url, [...handlers])`
- `router.put(url, [...handlers])`
- `router.trace(url, [...handlers])`
#### `url` (string)
@@ -296,7 +293,7 @@ wrangler init <name>
Use of TypeScript is strongly encouraged :)
```bash
npm i -D @tsndr/cloudflare-worker-router
npm i @tsndr/cloudflare-worker-router
```

View File

@@ -1,9 +0,0 @@
import type { Config } from 'jest'
const config: Config = {
preset: 'ts-jest',
testEnvironment: 'node',
verbose: true
}
export default config

4726
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,23 @@
{
"name": "@tsndr/cloudflare-worker-router",
"version": "3.1.3",
"version": "3.3.0",
"description": "",
"main": "index.js",
"type": "module",
"exports": "./index.js",
"types": "index.d.ts",
"scripts": {
"build": "tsc"
"build": "tsc",
"test": "vitest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tsndr/cloudflare-worker-router.git"
},
"keywords": [
"api",
"cloudflare",
"cloudflare-worker",
"cloudflare-workers",
"express",
"expressjs",
"framework",
"middleware",
"router",
@@ -31,12 +32,9 @@
},
"homepage": "https://github.com/tsndr/cloudflare-worker-router#readme",
"devDependencies": {
"@cloudflare/workers-types": "^4.20231025.0",
"@jest/globals": "^29.7.0",
"@types/jest": "^29.5.11",
"jest": "^29.7.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.2",
"typescript": "^5.2.2"
"@cloudflare/workers-types": "^4.20241022.0",
"@edge-runtime/vm": "^4.0.3",
"typescript": "^5.6.3",
"vitest": "^2.1.3"
}
}

View File

@@ -52,6 +52,7 @@ export type RouterRequest<ReqExt> = ReqExt & {
formData(): Promise<FormData>
blob(): Promise<Blob>
bearer(): string | undefined
basic(): [string, string]
cf?: IncomingRequestCfProperties
}
@@ -175,17 +176,6 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
return this
}
/**
* Register CONNECT route
*
* @param {string} url
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public connect(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
return this.register('CONNECT', url, handlers)
}
/**
* Register DELETE route
*
@@ -263,17 +253,6 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
return this.register('PUT', url, handlers)
}
/**
* Register TRACE route
*
* @param {string} url
* @param {RouterHandler[]} handlers
* @returns {Router}
*/
public trace(url: string, ...handlers: RouterHandler<Env, CtxExt, ReqExt>[]): Router<Env, CtxExt, ReqExt> {
return this.register('TRACE', url, handlers)
}
/**
* Register route, ignoring method
*
@@ -417,7 +396,8 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
json: async <T>(): Promise<T> => buffer.json ? buffer.json : buffer.json = await request.clone().json<T>(),
formData: async (): Promise<FormData> => buffer.formData ? buffer.formData : buffer.formData = await request.clone().formData(),
blob: async (): Promise<Blob> => buffer.blob ? buffer.blob : buffer.blob = await request.clone().blob(),
bearer: () => request.headers.get('Authorization')?.replace(/^(B|b)earer /, '').trim()
bearer: () => request.headers.get('Authorization')?.replace(/^[Bb]earer\s/, '').trim(),
basic: () => (atob(request.headers.get('Authorization')?.replace(/^[Bb]asic\s/, '').trim() ?? '') || undefined)?.split(':')
} as RouterRequest<ReqExt>
if (this.corsEnabled && req.method === 'OPTIONS') {
@@ -428,34 +408,37 @@ export class Router<Env = any, CtxExt = {}, ReqExt = {}> {
}
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 context = {
...(ctxExt ?? {}),
env,
req,
dbg,
ctx
} as RouterContext<Env, CtxExt, ReqExt>
if (!route)
response = new Response(this.debugMode ? 'Route not found!' : null, { status: 404 })
const res = await handler(context)
if (!response) {
const handlers = [
...this.globalHandlers,
...(route?.handlers ?? [])
]
if (res) {
response = res
break
for (const handler of handlers) {
const context = {
...(ctxExt ?? {}),
env,
req,
dbg: this.debugMode,
ctx
} as RouterContext<Env, CtxExt, ReqExt>
const res = await handler(context)
if (res) {
response = res
break
}
}
}
if (!response)
return new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
response = new Response(this.debugMode ? 'Handler did not return a Response!' : null, { status: 404 })
if (this.corsEnabled) {
response = new Response(response.body, response)

View File

@@ -1,5 +1,5 @@
import { describe, expect, test } from '@jest/globals'
import { Router } from '.'
import { describe, expect, test } from 'vitest'
import { Router } from '../src/index'
describe('Router', () => {
test('use', async () => {
@@ -261,6 +261,21 @@ describe('Router', () => {
expect(await response.text()).toBe(testToken)
})
test('basic', async () => {
const router = new Router()
const testCredentials = ['user', 'password']
const testBasicAuth = btoa(testCredentials.join(':'))
const testRequest = new Request('https://example.com/', { headers: { 'Authorization': `Basic ${testBasicAuth}` }})
router.get('/', ({ req }) => Response.json(req.basic()))
const response = await router.handle(testRequest, {})
expect(response.status).toEqual(200)
expect(await response.json()).toMatchObject(testCredentials)
})
})
describe('Middleware', () => {

View File

@@ -1,7 +1,7 @@
{
"compilerOptions": {
"outDir": ".",
"module": "commonjs",
"module": "esnext",
"target": "esnext",
"lib": ["esnext"],
"declaration": true,

9
vite.config.ts Normal file
View File

@@ -0,0 +1,9 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'edge-runtime',
reporters: ['verbose'],
watch: false
}
})