diff --git a/.eslintrc b/.eslintrc index d2f152d3..1f177dcd 100644 --- a/.eslintrc +++ b/.eslintrc @@ -18,6 +18,7 @@ "rules": { "@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/ban-types": "off", "linebreak-style": ["error", "unix"], "prefer-const": "off", "quotes": ["error", "single", { "allowTemplateLiterals": true }], diff --git a/README.md b/README.md index 6c0697e5..b2e9240c 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,10 @@
-
+
+
-
+
+
-
-
+
+
@@ -48,181 +43,41 @@
---
-Itty is arguably the smallest (~460 bytes) feature-rich JavaScript router available, while enabling dead-simple API code.
-
-Designed originally for [Cloudflare Workers](https://itty.dev/itty-router/runtimes#Cloudflare%20Workers), itty can be used in browsers, service workers, edge functions, or runtimes like [Node](https://itty.dev/itty-router/runtimes#Node), [Bun](https://itty.dev/itty-router/runtimes#Bun), etc.!
+An ultra-tiny API microrouter, for use when [size matters](https://github.com/TigersWay/cloudflare-playground) (e.g. [Cloudflare Workers](https://developers.cloudflare.com/workers/)).
## Features
-- Tiny. [~460](https://deno.bundlejs.com/?q=itty-router/Router) bytes for the Router itself, or [~1.6k](https://bundlephobia.com/package/itty-router) for the entire library (>100x smaller than [express.js](https://www.npmjs.com/package/express)).
-- [Fully-Typed](https://itty.dev/itty-router/typescript).
-- Shorter, simpler route code than most modern routers.
-- Dead-simple [middleware](https://itty.dev/itty-router/middleware) - use ours or write your own.
-- Supports [nested APIs](https://itty.dev/itty-router/nesting).
-- Platform agnostic (based on [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)) - use it [anywhere, in any environment](https://itty.dev/itty-router/runtimes).
-- Parses [route params](https://itty.dev/itty-router/route-patterns#params),
- [optional params](https://itty.dev/itty-router/route-patterns#optional),
- [wildcards](https://itty.dev/itty-router/route-patterns#wildcards),
- [greedy params](https://itty.dev/itty-router/route-patterns#greedy),
- [file formats](https://itty.dev/itty-router/route-patterns#file-formats)
- and [query strings](https://itty.dev/itty-router/route-patterns#query).
-- Extremely extendable/flexible. We leave you in complete control.
-
-## [Full Documentation](https://itty.dev/itty-router)
+- Tiny. We have routers from [~450 bytes](https://itty.dev/itty-router/routers/ittyrouter) to a [~1kB bytes](https://itty.dev/itty-router/routers/autorouter) batteries-included version. For comparison, [express.js](https://www.npmjs.com/package/express) is over 200x as large.
+- Web Standards - Use it [anywhere, in any environment](https://itty.dev/itty-router/runtimes).
+- No assumptions. Return anything you like, pass in any arguments you like.
+- Future-proof. HTTP methods not-yet-invented already work with it.
+- [Route-parsing](https://itty.dev/itty-router/route-patterns) & [query parsing](https://itty.dev/itty-router/route-patterns#query).
+- [Middleware](https://itty.dev/itty-router/middleware) - use ours or write your own.
+- [Nesting](https://itty.dev/itty-router/nesting).
-Complete API documentation is available at [itty.dev/itty-router](https://itty.dev/itty-router), or join our [Discord](https://discord.gg/53vyrZAu9u) channel to chat with community members for quick help!
-
-## Installation
-
-```
-npm install itty-router
-```
-
-## Example
+## Example (Cloudflare Worker or Bun)
```js
-import {
- error, // creates error responses
- json, // creates JSON responses
- Router, // the ~440 byte router itself
- withParams, // middleware: puts params directly on the Request
-} from 'itty-router'
-import { todos } from './external/todos'
-
-// create a new Router
-const router = Router()
-
-router
- // add some middleware upstream on all routes
- .all('*', withParams)
-
- // GET list of todos
- .get('/todos', () => todos)
-
- // GET single todo, by ID
- .get(
- '/todos/:id',
- ({ id }) => todos.getById(id) || error(404, 'That todo was not found')
- )
-
- // 404 for everything else
- .all('*', () => error(404))
-
-// Example: Cloudflare Worker module syntax
-export default {
- fetch: (request, ...args) =>
- router
- .handle(request, ...args)
- .then(json) // send as JSON
- .catch(error), // catch errors
-}
-```
-
-# What's different about itty?
-Itty does a few things very differently from other routers. This allows itty route code to be shorter and more intuitive than most!
-
-### 1. Simpler handler/middleware flow.
-In itty, you simply return (anything) to exit the flow. If any handler ever returns a thing, that's what the `router.handle` returns. If it doesn't, it's considered middleware, and the next handler is called.
+import { AutoRouter } from 'itty-router' // ~1kB
-That's it!
+export default AutoRouter()
+ .get('/hello/:name', ({ name }) => `Hello, ${name}!`)
+ .get('/json', () => [1,2,3])
+ .get('/promises', () => Promise.resolve('foo'))
-```ts
-// not middleware: any handler that returns (anything at all)
-(request) => [1, 4, 5, 1]
-
-// middleware: simply doesn't return
-const withUser = (request) => {
- request.user = 'Halsey'
-}
-
-// a middleware that *might* return
-const onlyHalsey = (request) => {
- if (request.user !== 'Halsey') {
- return error(403, 'Only Halsey is allowed to see this!')
- }
-}
-
-// uses middleware, then returns something
-route.get('/secure', withUser, onlyHalsey,
- ({ user }) => `Hey, ${user} - welcome back!`
-)
+// that's it ^-^
```
-### 2. You don't have to build a response in each route handler.
-We've been stuck in this pattern for over a decade. Almost every router still expects you to build and return a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response)... in every single route.
-
-We think you should be able to do that once, at the end. In most modern APIs for instance, we're serving JSON in the majority of our routes. So why handle that more than once?
-```ts
-router
- // we can still do it the manual way
- .get('/traditional', (request) => json([1, 2, 3]))
-
- // or defer to later
- .get('/easy-mode', (request) => [1, 2, 3])
-
-// later, when handling a request
-router
- .handle(request)
- .then(json) // we can turn any non-Response into valid JSON.
-```
-
-### 3. It's all Promises.
-itty `await`s every handler, looking for a return value. If it gets one, it breaks the flow and returns the value. If it doesn't, it continues processing handlers/routes until it does. This means that every handler can either be synchronous or async - it's all the same.
-
-When paired with the fact that we can simply return raw data and transform it later, this is AWESOME for working with async APIs, database layers, etc. We don't need to transform anything at the route, we can simply return the Promise (to data) itself!
+# [Full Documentation](https://itty.dev/itty-router) @ [itty.dev](https://itty.dev)
-Check this out:
-```ts
-import { myDatabase } from './somewhere'
-
-router
- // assumes getItems() returns a Promise to some data
- .get('/items', () => myDatabase.getItems())
-
-// later, when handling a request
-router
- .handle(request)
- .then(json) // we can turn any non-Response into valid JSON.
-```
-
-### 4. Only one required argument. The rest is up to you.
-itty only requires one argument - a Request-like object with the following shape: `{ url, method }` (usually a native [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request)). Because itty is not opinionated about [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) creation, there is not "response" argument built in. Every other argument you pass to `route.handle` is given to each handler, in the same order.
-
-> ### This makes itty one of the most platform-agnostic routers, *period*, as it's able to match up to any platform's signature.
-
-Here's an example using [Cloudflare Worker](https://workers.cloudflare.com/) arguments:
-```ts
-router
- .get('/my-route', (request, environment, context) => {
- // we can access anything here that was passed to `router.handle`.
- })
-
-// Cloudflare gives us 3 arguments: request, environment, and context.
-// Passing them to `route.handle` gives every route handler (above) access to each.
-export default {
- fetch: (request, env, ctx) => router
- .handle(request, env, ctx)
- .then(json)
- .catch(error)
-}
-```
+Complete API documentation is available at [itty.dev/itty-router](https://itty.dev/itty-router), or join our [Discord](https://discord.gg/53vyrZAu9u) channel to chat with community members for quick help!
## Join the Discussion!
-Have a question? Suggestion? Complaint? Want to send a gift basket?
+Have a question? Suggestion? Idea? Complaint? Want to send a gift basket?
Join us on [Discord](https://discord.gg/53vyrZAu9u)!
-## Testing and Contributing
-
-1. Fork repo
-1. Install dev dependencies via `yarn`
-1. Start test runner/dev mode `yarn dev`
-1. Add your code and tests if needed - do NOT remove/alter existing tests
-1. Commit files
-1. Submit PR (and fill out the template)
-1. I'll add you to the credits! :)
-
## Special Thanks: Contributors
These folks are the real heroes, making open source the powerhouse that it is! Help out and get your name added to this list! <3
@@ -244,6 +99,7 @@ These folks are the real heroes, making open source the powerhouse that it is! H
- [@technoyes](https://github.com/technoyes) - three kind-of-a-big-deal errors fixed. Imagine the look on my face... thanks man!! :)
- [@roojay520](https://github.com/roojay520) - TS interface fixes
- [@jahands](https://github.com/jahands) - v4.x TS fixes
+- and many, many others
#### Documentation
diff --git a/example/bun-autorouter-advanced.ts b/example/bun-autorouter-advanced.ts
new file mode 100644
index 00000000..f26ddc4d
--- /dev/null
+++ b/example/bun-autorouter-advanced.ts
@@ -0,0 +1,35 @@
+import { text } from 'text'
+import { json } from 'json'
+import { AutoRouter } from '../src/AutoRouter'
+import { error } from 'error'
+import { IRequest } from 'IttyRouter'
+import { withParams } from 'withParams'
+
+const router = AutoRouter({
+ port: 3001,
+ missing: () => error(404, 'Are you sure about that?'),
+ format: () => {},
+ before: [
+ (r: any) => { r.date = new Date },
+ ],
+ finally: [
+ (r: Response, request: IRequest) =>
+ console.log(r.status, request.method, request.url, 'delivered in', Date.now() - request.date, 'ms from', request.date.toLocaleString()),
+ ]
+})
+
+const childRouter = AutoRouter({
+ base: '/child',
+ missing: () => {},
+})
+ .get('/:id', ({ id }) => [ Number(id), Number(id) / 2 ])
+
+router
+ .get('/basic', () => new Response('Success!'))
+ .get('/text', () => 'Success!')
+ .get('/params/:foo', ({ foo }) => foo)
+ .get('/json', () => ({ foo: 'bar' }))
+ .get('/throw', (a) => a.b.c)
+ .get('/child/*', childRouter.fetch)
+
+export default router
diff --git a/example/bun-autorouter.ts b/example/bun-autorouter.ts
new file mode 100644
index 00000000..45f389c4
--- /dev/null
+++ b/example/bun-autorouter.ts
@@ -0,0 +1,12 @@
+import { AutoRouter } from '../src/AutoRouter'
+
+const router = AutoRouter({ port: 3001 })
+
+router
+ .get('/basic', () => new Response('Success!'))
+ .get('/text', () => 'Success!')
+ .get('/params/:foo', ({ foo }) => foo)
+ .get('/json', () => ({ foo: 'bar' }))
+ .get('/throw', (a) => a.b.c)
+
+export default router
diff --git a/example/bun-router.ts b/example/bun-router.ts
new file mode 100644
index 00000000..5d2087d3
--- /dev/null
+++ b/example/bun-router.ts
@@ -0,0 +1,26 @@
+import { IRequest } from 'IttyRouter'
+import { Router } from '../src/Router'
+import { error } from '../src/error'
+import { json } from '../src/json'
+import { withParams } from '../src/withParams'
+
+const logger = (response: Response, request: IRequest) => {
+ console.log(response.status, request.url, '@', new Date().toLocaleString())
+}
+
+const router = Router({
+ port: 3001,
+ before: [withParams],
+ finally: [json, logger],
+ catch: error,
+})
+
+router
+ .get('/basic', () => new Response('Success!'))
+ .get('/text', () => 'Success!')
+ .get('/params/:foo', ({ foo }) => foo)
+ .get('/json', () => ({ foo: 'bar' }))
+ .get('/throw', a => a.b.c)
+ .all('*', () => error(404))
+
+export default router
diff --git a/example/request-types.ts b/example/request-types.ts
index 45033bb1..bbe407c1 100644
--- a/example/request-types.ts
+++ b/example/request-types.ts
@@ -1,4 +1,4 @@
-import { IRequest, IRequestStrict, Router } from '../src/Router'
+import { IRequest, IRequestStrict, Router } from '../src/IttyRouter'
type FooRequest = {
foo: string
diff --git a/package.json b/package.json
index a7dcbb2b..552cbbc8 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "itty-router",
- "version": "4.2.2",
+ "version": "4.3.0-next.0",
"description": "A tiny, zero-dependency router, designed to make beautiful APIs in any environment.",
"main": "./index.js",
"module": "./index.mjs",
@@ -11,6 +11,11 @@
"require": "./index.js",
"types": "./index.d.ts"
},
+ "./AutoRouter": {
+ "import": "./AutoRouter.mjs",
+ "require": "./AutoRouter.js",
+ "types": "./AutoRouter.d.ts"
+ },
"./createCors": {
"import": "./createCors.mjs",
"require": "./createCors.js",
@@ -31,6 +36,11 @@
"require": "./html.js",
"types": "./html.d.ts"
},
+ "./IttyRouter": {
+ "import": "./IttyRouter.mjs",
+ "require": "./IttyRouter.js",
+ "types": "./IttyRouter.d.ts"
+ },
"./jpeg": {
"import": "./jpeg.mjs",
"require": "./jpeg.js",
diff --git a/src/AutoRouter.spec.ts b/src/AutoRouter.spec.ts
new file mode 100644
index 00000000..636871f3
--- /dev/null
+++ b/src/AutoRouter.spec.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from 'vitest'
+import { toReq } from '../test'
+import { AutoRouter } from './AutoRouter'
+import { text } from './text'
+import { error } from './error'
+
+describe(`SPECIFIC TESTS: AutoRouter`, () => {
+ const jsonData = [1,2,3]
+
+ describe('BEHAVIORS', () => {
+ describe('DEFAULT', () => {
+ it('returns a generic 404 on route miss', async () => {
+ const router = AutoRouter()
+
+ const response = await router.fetch(toReq('/'))
+ expect(response.status).toBe(404)
+ })
+
+ it('formats unformated responses as JSON', async () => {
+ const router = AutoRouter().get('/', () => jsonData)
+
+ const response = await router.fetch(toReq('/'))
+ const parsed = await response.json()
+ expect(parsed).toEqual(jsonData)
+ })
+
+ it('includes withParams', async () => {
+ const handler = vi.fn(({ id }) => id)
+ const router = AutoRouter().get('/:id', handler)
+
+ await router.fetch(toReq('/foo'))
+ expect(handler).toHaveReturnedWith('foo')
+ })
+
+ it('catches errors by default', async () => {
+ const router = AutoRouter().get('/', a => a.b.c)
+
+ const response = await router.fetch(toReq('/'))
+ expect(response.status).toBe(500)
+ })
+ })
+
+ describe('OPTIONS', () => {
+ it('format: FormatterFunction - replaces default JSON formatting', async () => {
+ const router = AutoRouter({ format: text }).get('/', () => 'foo')
+
+ const response = await router.fetch(toReq('/'))
+ expect(response.headers.get('content-type').includes('text')).toBe(true)
+ })
+
+ it('missing: RouteHandler - replaces default missing error', async () => {
+ const router = AutoRouter({ missing: () => error(418) })
+
+ const response = await router.fetch(toReq('/'))
+ expect(response.status).toBe(418)
+ })
+
+ it('before: RouteHandler - adds upstream middleware', async () => {
+ const handler = vi.fn(r => typeof r.date)
+ const router = AutoRouter({
+ before: [
+ r => { r.date = Date.now() }
+ ]
+ }).get('*', handler)
+
+ await router.fetch(toReq('/'))
+ expect(handler).toHaveReturnedWith('number')
+ })
+
+ describe('finally: (response: Response, request: IRequest, ...args) - ResponseHandler', async () => {
+ it('modifies the response if returning non-null value', async () => {
+ const router = AutoRouter({
+ finally: [ () => true ]
+ }).get('*', () => 314)
+
+ const response = await router.fetch(toReq('/'))
+ expect(response).toBe(true)
+ })
+
+ it('does not modify the response if returning null values', async () => {
+ const router = AutoRouter({
+ finally: [
+ () => {},
+ () => undefined,
+ () => null,
+ ]
+ }).get('*', () => 314)
+
+ const response = await router.fetch(toReq('/'))
+ const parsed = await response.json()
+ expect(response.status).toBe(200)
+ expect(parsed).toBe(314)
+ })
+ })
+ })
+ })
+})
+
diff --git a/src/AutoRouter.ts b/src/AutoRouter.ts
new file mode 100644
index 00000000..5d61b671
--- /dev/null
+++ b/src/AutoRouter.ts
@@ -0,0 +1,42 @@
+import { RouteHandler } from 'IttyRouter'
+import { ResponseHandler, Router, RouterOptions } from './Router'
+import { error } from './error'
+import { json } from './json'
+import { withParams } from './withParams'
+
+type AutoRouterOptions = {
+ missing?: RouteHandler
+ format?: ResponseHandler
+} & RouterOptions
+
+// MORE FINE-GRAINED/SIMPLIFIED CONTROL, BUT CANNOT FULLY REPLACE BEFORE/FINALLY STAGES
+export const AutoRouter = ({
+ format = json,
+ missing = () => error(404),
+ finally: f = [],
+ before = [],
+ ...options }: AutoRouterOptions = {}
+) => Router({
+ before: [
+ withParams,
+ ...before
+ ],
+ catch: error,
+ finally: [
+ (r: any, ...args) => r ?? missing(r, ...args),
+ format,
+ ...f,
+ ],
+ ...options,
+})
+
+// LESS FINE-GRAINED CONTROL, BUT CAN COMPLETELY REPLACE BEFORE/FINALLY STAGES
+// export const AutoRouter2 = ({ ...options }: RouterOptions = {}) => Router({
+// before: [withParams],
+// onError: [error],
+// finally: [
+// (r: any) => r ?? error(404),
+// json,
+// ],
+// ...options,
+// })
diff --git a/src/IttyRouter.ts b/src/IttyRouter.ts
new file mode 100644
index 00000000..91fe8c63
--- /dev/null
+++ b/src/IttyRouter.ts
@@ -0,0 +1,123 @@
+export type GenericTraps = {
+ [key: string]: any
+}
+
+export type RequestLike = {
+ method: string,
+ url: string,
+} & GenericTraps
+
+export type IRequestStrict = {
+ method: string,
+ url: string,
+ route: string,
+ params: {
+ [key: string]: string,
+ },
+ query: {
+ [key: string]: string | string[] | undefined,
+ },
+ proxy?: any,
+} & Request
+
+export type IRequest = IRequestStrict & GenericTraps
+
+export type IttyRouterOptions = {
+ base?: string
+ routes?: RouteEntry[]
+} & Record