Socket
Socket
Sign inDemoInstall

itty-router

Package Overview
Dependencies
Maintainers
2
Versions
265
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

itty-router - npm Package Compare versions

Comparing version 4.1.0-next.4 to 4.1.0

createCors.js.map

6

createCors.d.ts
import { IRequest } from './Router';
export interface CorsOptions {
origins?: string[];
export type CorsOptions = {
origins?: string[] | ((origin: string) => boolean);
maxAge?: number;
methods?: string[];
headers?: any;
}
};
export declare const createCors: (options?: CorsOptions) => {

@@ -9,0 +9,0 @@ corsify: (response: Response) => Response;

@@ -1,1 +0,2 @@

"use strict";exports.createCors=(e={})=>{const{origins:s=["*"],maxAge:o,methods:t=["GET"],headers:n={}}=e;let r;const c={"content-type":"application/json","Access-Control-Allow-Methods":t.join(", "),...n};o&&(c["Access-Control-Max-Age"]=o);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:s,status:o,body:t}=e;return[101,301,302,308].includes(o)||s.get("access-control-allow-origin")?e:new Response(t,{status:o,headers:{...Object.fromEntries(s),...c,...r,"content-type":s.get("content-type")}})},preflight:e=>{const o=[...new Set(["OPTIONS",...t])],n=e.headers.get("origin")||"";if(r=(s.includes(n)||s.includes("*"))&&{"Access-Control-Allow-Origin":n},"OPTIONS"===e.method){const s={...c,"Access-Control-Allow-Methods":o.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...r};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?s:{Allow:o.join(", ")}})}}}};
"use strict";exports.createCors=(e={})=>{const{origins:s=["*"],maxAge:o,methods:t=["GET"],headers:n={}}=e;let r;const c="function"==typeof s?s:e=>s.includes(e)||s.includes("*"),l={"content-type":"application/json","Access-Control-Allow-Methods":t.join(", "),...n};o&&(l["Access-Control-Max-Age"]=o);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:s,status:o,body:t}=e;return[101,301,302,308].includes(o)||s.get("access-control-allow-origin")?e:new Response(t,{status:o,headers:{...Object.fromEntries(s),...l,...r,"content-type":s.get("content-type")}})},preflight:e=>{const s=[...new Set(["OPTIONS",...t])],o=e.headers.get("origin")||"";if(r=c(o)&&{"Access-Control-Allow-Origin":o},"OPTIONS"===e.method){const o={...l,"Access-Control-Allow-Methods":s.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...r};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?o:{Allow:s.join(", ")}})}}}};
//# sourceMappingURL=createCors.js.map

@@ -1,1 +0,2 @@

"use strict";exports.createResponse=(e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:r={},...o}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})};
"use strict";exports.createResponse=(e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r});
//# sourceMappingURL=createResponse.js.map

@@ -1,1 +0,2 @@

"use strict";const r=((r="text/plain; charset=utf-8",e)=>(t,s)=>{const{headers:n={},...o}=s||{};return"Response"===t?.constructor.name?t:new Response(e?e(t):t,{headers:{"content-type":r,...n},...o})})("application/json; charset=utf-8",JSON.stringify),e=r=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[r]||"Unknown Error");exports.error=(t=500,s)=>{if(t instanceof Error){const{message:r,...n}=t;t=t.status||500,s={error:r||e(t),...n}}return s={status:t,..."object"==typeof s?s:{error:s||e(t)}},r(s,{status:t})};
"use strict";const e=((e="text/plain; charset=utf-8",r)=>(t,{headers:s={},...n}={})=>void 0===t||"Response"===t?.constructor.name?t:new Response(r?r(t):t,{headers:{"content-type":e,...s.entries?Object.fromEntries(s):s},...n}))("application/json; charset=utf-8",JSON.stringify),r=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error");exports.error=(t=500,s)=>{if(t instanceof Error){const{message:e,...n}=t;t=t.status||500,s={error:e||r(t),...n}}return s={status:t,..."object"==typeof s?s:{error:s||r(t)}},e(s,{status:t})};
//# sourceMappingURL=error.js.map

@@ -1,1 +0,2 @@

"use strict";const t=((t="text/plain; charset=utf-8",e)=>(s,n)=>{const{headers:r={},...o}=n||{};return"Response"===s?.constructor.name?s:new Response(e?e(s):s,{headers:{"content-type":t,...r},...o})})("text/html");exports.html=t;
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r}))("text/html");exports.html=e;
//# sourceMappingURL=html.js.map

@@ -1,2 +0,1 @@

export * from './flow';
export * from './Router';

@@ -3,0 +2,0 @@ export * from './StatusError';

@@ -1,1 +0,2 @@

"use strict";const e=(e={})=>{const{origins:t=["*"],maxAge:o,methods:r=["GET"],headers:s={}}=e;let n;const a={"content-type":"application/json","Access-Control-Allow-Methods":r.join(", "),...s};o&&(a["Access-Control-Max-Age"]=o);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:t,status:o,body:r}=e;return[101,301,302,308].includes(o)||t.get("access-control-allow-origin")?e:new Response(r,{status:o,headers:{...Object.fromEntries(t),...a,...n,"content-type":t.get("content-type")}})},preflight:e=>{const o=[...new Set(["OPTIONS",...r])],s=e.headers.get("origin")||"";if(n=(t.includes(s)||t.includes("*"))&&{"Access-Control-Allow-Origin":s},"OPTIONS"===e.method){const t={...a,"Access-Control-Allow-Methods":o.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...n};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?t:{Allow:o.join(", ")}})}}}},t=(e="text/plain; charset=utf-8",t)=>(o,r)=>{const{headers:s={},...n}=r||{};return"Response"===o?.constructor.name?o:new Response(t?t(o):o,{headers:{"content-type":e,...s},...n})},o=t("application/json; charset=utf-8",JSON.stringify),r=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),s=(e=500,t)=>{if(e instanceof Error){const{message:o,...s}=e;e=e.status||500,t={error:o||r(e),...s}}return t={status:e,..."object"==typeof t?t:{error:t||r(e)}},o(t,{status:e})},n=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,o)=>{let r;return void 0!==(r=t[o])?r.bind?.(e)||r:t?.params?.[o]}})};class a extends Error{status;constructor(e=500,t){super("object"==typeof t?t.error:t),"object"==typeof t&&Object.assign(this,t),this.status=e}}const c=t("text/html"),p=t("image/jpeg"),l=t("image/png"),i=t("image/webp");exports.Router=({base:e="",routes:t=[]}={})=>({__proto__:new Proxy({},{get:(o,r,s,n)=>(o,...a)=>t.push([r.toUpperCase(),RegExp(`^${(n=(e+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&s}),routes:t,async handle(e,...o){let r,s,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=void 0===a[e]?t:[a[e],t].flat();for(let[a,c,p,l]of t)if((a===e.method||"ALL"===a)&&(s=n.pathname.match(c))){e.params=s.groups||{},e.route=l;for(let t of p)if(void 0!==(r=await t(e.proxy||e,...o)))return r}}}),exports.StatusError=a,exports.createCors=e,exports.createResponse=t,exports.error=s,exports.flow=(t,r={})=>{const{format:a=o,cors:c,handleErrors:p=s,handleNotFound:l=(()=>s(404))}=r;let i;return"function"==typeof l&&t.all("*",l),c&&(i=e(!0===c?void 0:c),t.routes.unshift(["ALL",/^(.*)?\/*$/,[i.preflight,n],"*"])),async(...e)=>{let o=t.handle(...e);return o=a?o.then(a):o,o=p?o.catch(p):o,c?o.then(i?.corsify):o}},exports.html=c,exports.jpeg=p,exports.json=o,exports.png=l,exports.status=(e,t)=>new Response(null,{...t,status:e}),exports.text=(e,t)=>new Response(String(e),t),exports.webp=i,exports.withContent=async e=>{e.headers.get("content-type")?.includes("json")&&(e.content=await e.json())},exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,o])=>o?(e[t]=o,e):e),{})},exports.withParams=n;
"use strict";class e extends Error{status;constructor(e=500,t){super("object"==typeof t?t.error:t),"object"==typeof t&&Object.assign(this,t),this.status=e}}const t=(e="text/plain; charset=utf-8",t)=>(s,{headers:o={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...o.entries?Object.fromEntries(o):o},...r}),s=t("application/json; charset=utf-8",JSON.stringify),o=e=>({400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error"}[e]||"Unknown Error"),r=t("text/plain; charset=utf-8",String),n=t("text/html"),a=t("image/jpeg"),c=t("image/png"),p=t("image/webp");exports.Router=({base:e="",routes:t=[],...s}={})=>({__proto__:new Proxy({},{get:(s,o,r,n)=>"handle"==o?r.fetch:(s,...a)=>t.push([o.toUpperCase?.(),RegExp(`^${(n=(e+s).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),a,n])&&r}),routes:t,...s,async fetch(e,...s){let o,r,n=new URL(e.url),a=e.query={__proto__:null};for(let[e,t]of n.searchParams)a[e]=a[e]?[].concat(a[e],t):t;for(let[a,c,p,i]of t)if((a==e.method||"ALL"==a)&&(r=n.pathname.match(c))){e.params=r.groups||{},e.route=i;for(let t of p)if(null!=(o=await t(e.proxy??e,...s)))return o}}}),exports.StatusError=e,exports.createCors=(e={})=>{const{origins:t=["*"],maxAge:s,methods:o=["GET"],headers:r={}}=e;let n;const a="function"==typeof t?t:e=>t.includes(e)||t.includes("*"),c={"content-type":"application/json","Access-Control-Allow-Methods":o.join(", "),...r};s&&(c["Access-Control-Max-Age"]=s);return{corsify:e=>{if(!e)throw new Error("No fetch handler responded and no upstream to proxy to specified.");const{headers:t,status:s,body:o}=e;return[101,301,302,308].includes(s)||t.get("access-control-allow-origin")?e:new Response(o,{status:s,headers:{...Object.fromEntries(t),...c,...n,"content-type":t.get("content-type")}})},preflight:e=>{const t=[...new Set(["OPTIONS",...o])],s=e.headers.get("origin")||"";if(n=a(s)&&{"Access-Control-Allow-Origin":s},"OPTIONS"===e.method){const s={...c,"Access-Control-Allow-Methods":t.join(", "),"Access-Control-Allow-Headers":e.headers.get("Access-Control-Request-Headers"),...n};return new Response(null,{headers:e.headers.get("Origin")&&e.headers.get("Access-Control-Request-Method")&&e.headers.get("Access-Control-Request-Headers")?s:{Allow:t.join(", ")}})}}}},exports.createResponse=t,exports.error=(e=500,t)=>{if(e instanceof Error){const{message:s,...r}=e;e=e.status||500,t={error:s||o(e),...r}}return t={status:e,..."object"==typeof t?t:{error:t||o(e)}},s(t,{status:e})},exports.html=n,exports.jpeg=a,exports.json=s,exports.png=c,exports.status=(e,t)=>new Response(null,{...t,status:e}),exports.text=r,exports.webp=p,exports.withContent=async t=>{if(t.headers.get("content-type")?.includes("json"))try{t.content=await t.json()}catch(t){throw new e(400,t.message)}},exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[t,s])=>s?(e[t]=s,e):e),{})},exports.withParams=e=>{e.proxy=new Proxy(e.proxy||e,{get:(t,s)=>void 0!==t[s]?t[s].bind?.(e)||t[s]:t?.params?.[s]})};
//# sourceMappingURL=index.js.map

@@ -1,1 +0,2 @@

"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:r={},...o}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})})("image/jpeg");exports.jpeg=e;
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r}))("image/jpeg");exports.jpeg=e;
//# sourceMappingURL=jpeg.js.map

@@ -1,1 +0,2 @@

"use strict";const t=((t="text/plain; charset=utf-8",e)=>(s,n)=>{const{headers:o={},...r}=n||{};return"Response"===s?.constructor.name?s:new Response(e?e(s):s,{headers:{"content-type":t,...o},...r})})("application/json; charset=utf-8",JSON.stringify);exports.json=t;
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...o}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...o}))("application/json; charset=utf-8",JSON.stringify);exports.json=e;
//# sourceMappingURL=json.js.map
{
"name": "itty-router",
"version": "4.1.0-next.4",
"version": "4.1.0",
"description": "A tiny, zero-dependency router, designed to make beautiful APIs in any environment.",

@@ -29,7 +29,2 @@ "main": "./index.js",

},
"./flow": {
"import": "./flow.mjs",
"require": "./flow.js",
"types": "./flow.d.ts"
},
"./html": {

@@ -102,3 +97,2 @@ "import": "./html.mjs",

"keywords": [
"itty",
"api",

@@ -108,3 +102,3 @@ "router",

"workers",
"bun",
"worker",
"serverless",

@@ -115,4 +109,3 @@ "cors",

"serviceworker",
"http",
"nodejs"
"nested"
],

@@ -119,0 +112,0 @@ "scripts": {

@@ -1,1 +0,2 @@

"use strict";const e=((e="text/plain; charset=utf-8",t)=>(n,s)=>{const{headers:r={},...o}=s||{};return"Response"===n?.constructor.name?n:new Response(t?t(n):n,{headers:{"content-type":e,...r},...o})})("image/png");exports.png=e;
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r}))("image/png");exports.png=e;
//# sourceMappingURL=png.js.map
<p align="center">
<a href="https://itty.dev/itty-router">
<img src="https://github.com/kwhitley/itty-router/assets/865416/7751dac0-2dc8-4754-8b39-d08fc2144b4f" alt="Itty Router" />
<img src="https://github.com/kwhitley/itty-router/assets/865416/15a90b05-344d-4135-a3f8-52a4d117250e" alt="Itty Router" />
</a>
<p>
---
<h2 align="center"><a href="https://itty.dev/itty-router">v4.x Documentation @ itty.dev</a>

@@ -36,4 +35,4 @@ <br /></h2>

<p align="center">
<a href="https://discord.com/channels/832353585802903572" target="_blank">
<img src="https://img.shields.io/discord/832353585802903572?style=flat-square" alt="join us on discord" />
<a href="https://discord.gg/53vyrZAu9u" target="_blank">
<img src="https://img.shields.io/discord/832353585802903572?label=Discord&logo=Discord&style=flat-square&logoColor=fff" alt="join us on discord" />
</a>

@@ -53,11 +52,14 @@ <a href="https://github.com/kwhitley/itty-router" target="_blank">

Itty aims to be the world's smallest (~440 bytes), feature-rich JavaScript router, enabling beautiful API code with a near-zero bundlesize. Designed originally for [Cloudflare Workers](https://itty.dev/itty-router/runtimes#Cloudflare%20Workers), itty can be used in browsers, Service Workers, edge functions, or standalone runtimes like [Node](https://itty.dev/itty-router/runtimes#Node), [Bun](https://itty.dev/itty-router/runtimes#Bun), etc.!
Itty is arguably the smallest (~450 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.!
## Features
- Tiny. The Router itself is ~440 bytes gzipped, and the **entire** library is under 1.6k!
- Easy to use. We believe route code should be self-evident, obvious, and read more like poetry than code.
- Agnostic. We leave **you** with full control over response types, matching order, upstream/downstream effects, etc.
- Works [anywhere, in any environment](https://itty.dev/itty-router/runtimes).
- [Fully typed/TypeScript support](https://itty.dev/itty-router/typescript), including hinting.
- Tiny. [~450](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),

@@ -67,21 +69,9 @@ [optional params](https://itty.dev/itty-router/route-patterns#optional),

[greedy params](https://itty.dev/itty-router/route-patterns#greedy),
and [file formats](https://itty.dev/itty-router/route-patterns#file-formats).
- Automatic [query parsing](https://itty.dev/itty-router/route-patterns#query).
- Easy [error handling](https://itty.dev/itty-router/errors), including throwing errors with HTTP status codes!
- Easy [Response](https://itty.dev/itty-router/responses) creation, with helpers for major formats (e.g.
[json](https://itty.dev/itty-router/api#json),
[html](https://itty.dev/itty-router/api#html),
[png](https://itty.dev/itty-router/api#png),
[jpeg](https://itty.dev/itty-router/api#jpeg), etc.)
- Deep APIs via [router nesting](https://itty.dev/itty-router/nesting).
- Full [middleware](https://itty.dev/itty-router/middleware) support. Includes the following by default:
- [withParams](https://itty.dev/itty-router/api#withParams) - access the params directly off the `Request` (instead of `request.params`).
- [withCookies](https://itty.dev/itty-router/api#withCookies) - access cookies in a convenient Object format.
- [withContent](https://itty.dev/itty-router/api#withContent) - auto-parse Request bodies as `request.content`.
- [CORS](https://itty.dev/itty-router/cors) - because we love you.
- Fully readable regex... yeah right! 😆
[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)
Complete documentation/API is available at [itty.dev](https://itty.dev/itty-router), or join our [Discord](https://discord.com/channels/832353585802903572) channel to chat with community members for quick help!
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!

@@ -134,2 +124,91 @@ ## Installation

# What's different about itty? <a name="a-different-kind-of-router"></a>
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.
That's it!
```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!`
)
```
### 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!
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)
}
```
## Join the Discussion!

@@ -139,3 +218,3 @@

Join us on [Discord](https://discord.com/channels/832353585802903572)!
Join us on [Discord](https://discord.gg/53vyrZAu9u)!

@@ -142,0 +221,0 @@ ## Testing and Contributing

@@ -24,7 +24,12 @@ export type GenericTraps = {

routes?: RouteEntry[];
};
} & Record<string, any>;
export type RouteHandler<I = IRequest, A extends any[] = any[]> = {
(request: I, ...args: A): any;
};
export type RouteEntry = [string, RegExp, RouteHandler[], string];
export type RouteEntry = [
httpMethod: string,
match: RegExp,
handlers: RouteHandler[],
path?: string
];
export type Route = <RequestType = IRequest, Args extends any[] = any[], RT = RouterType>(path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RT;

@@ -39,2 +44,3 @@ export type UniversalRoute<RequestType = IRequest, Args extends any[] = any[]> = (path: string, ...handlers: RouteHandler<RequestType, Args>[]) => RouterType<UniversalRoute<RequestType, Args>, Args>;

routes: RouteEntry[];
fetch: <A extends any[] = Args>(request: RequestLike, ...extra: Equal<R, Args> extends true ? A : Args) => Promise<any>;
handle: <A extends any[] = Args>(request: RequestLike, ...extra: Equal<R, Args> extends true ? A : Args) => Promise<any>;

@@ -49,4 +55,4 @@ all: R;

put: R;
} & CustomRoutes<R>;
export declare const Router: <RequestType = IRequest, Args extends any[] = any[], RouteType = Equal<RequestType, IRequest> extends true ? Route : UniversalRoute<RequestType, Args>>({ base, routes }?: RouterOptions) => RouterType<RouteType, Args>;
} & CustomRoutes<R> & Record<string, any>;
export declare const Router: <RequestType = IRequest, Args extends any[] = any[], RouteType = Equal<RequestType, IRequest> extends true ? Route : UniversalRoute<RequestType, Args>>({ base, routes, ...other }?: RouterOptions) => RouterType<RouteType, Args>;
export {};

@@ -1,1 +0,2 @@

"use strict";exports.Router=({base:e="",routes:r=[]}={})=>({__proto__:new Proxy({},{get:(o,t,a,p)=>(o,...l)=>r.push([t.toUpperCase(),RegExp(`^${(p=(e+o).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,p])&&a}),routes:r,async handle(e,...o){let t,a,p=new URL(e.url),l=e.query={__proto__:null};for(let[e,r]of p.searchParams)l[e]=void 0===l[e]?r:[l[e],r].flat();for(let[l,s,u,$]of r)if((l===e.method||"ALL"===l)&&(a=p.pathname.match(s))){e.params=a.groups||{},e.route=$;for(let r of u)if(void 0!==(t=await r(e.proxy||e,...o)))return t}}});
"use strict";exports.Router=({base:e="",routes:r=[],...t}={})=>({__proto__:new Proxy({},{get:(t,o,a,p)=>"handle"==o?a.fetch:(t,...l)=>r.push([o.toUpperCase?.(),RegExp(`^${(p=(e+t).replace(/\/+(\/|$)/g,"$1")).replace(/(\/?\.?):(\w+)\+/g,"($1(?<$2>*))").replace(/(\/?\.?):(\w+)/g,"($1(?<$2>[^$1/]+?))").replace(/\./g,"\\.").replace(/(\/?)\*/g,"($1.*)?")}/*$`),l,p])&&a}),routes:r,...t,async fetch(e,...t){let o,a,p=new URL(e.url),l=e.query={__proto__:null};for(let[e,r]of p.searchParams)l[e]=l[e]?[].concat(l[e],r):r;for(let[l,c,s,u]of r)if((l==e.method||"ALL"==l)&&(a=p.pathname.match(c))){e.params=a.groups||{},e.route=u;for(let r of s)if(null!=(o=await r(e.proxy??e,...t)))return o}}});
//# sourceMappingURL=Router.js.map
"use strict";exports.status=(s,t)=>new Response(null,{...t,status:s});
//# sourceMappingURL=status.js.map
"use strict";class t extends Error{status;constructor(t=500,s){super("object"==typeof s?s.error:s),"object"==typeof s&&Object.assign(this,s),this.status=t}}exports.StatusError=t;
//# sourceMappingURL=StatusError.js.map

@@ -1,1 +0,1 @@

export declare const text: (message: any, options?: ResponseInit) => Response;
export declare const text: import("./createResponse").ResponseFormatter;

@@ -1,1 +0,2 @@

"use strict";exports.text=(e,t)=>new Response(String(e),t);
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r}))("text/plain; charset=utf-8",String);exports.text=e;
//# sourceMappingURL=text.js.map

@@ -1,1 +0,2 @@

"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:r={},...o}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...r},...o})})("image/webp");exports.webp=e;
"use strict";const e=((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...r}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...r}))("image/webp");exports.webp=e;
//# sourceMappingURL=webp.js.map

@@ -1,1 +0,2 @@

"use strict";exports.websocket=(e,t={})=>((e="text/plain; charset=utf-8",t)=>(s,n)=>{const{headers:o={},...r}=n||{};return"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...o},...r})})()(null,{status:101,webSocket:e,...t});
"use strict";exports.websocket=(e,t={})=>((e="text/plain; charset=utf-8",t)=>(s,{headers:n={},...o}={})=>void 0===s||"Response"===s?.constructor.name?s:new Response(t?t(s):s,{headers:{"content-type":e,...n.entries?Object.fromEntries(n):n},...o}))()(null,{status:101,webSocket:e,...t});
//# sourceMappingURL=websocket.js.map

@@ -1,2 +0,5 @@

import { IRequest } from './Router';
import { IRequest, IRequestStrict } from './Router';
export type HasContent<ContentType> = {
content: ContentType;
} & IRequestStrict;
export declare const withContent: (request: IRequest) => Promise<void>;

@@ -1,1 +0,2 @@

"use strict";exports.withContent=async t=>{t.headers.get("content-type")?.includes("json")&&(t.content=await t.json())};
"use strict";class t extends Error{status;constructor(t=500,s){super("object"==typeof s?s.error:s),"object"==typeof s&&Object.assign(this,s),this.status=t}}exports.withContent=async s=>{if(s.headers.get("content-type")?.includes("json"))try{s.content=await s.json()}catch(s){throw new t(400,s.message)}};
//# sourceMappingURL=withContent.js.map
"use strict";exports.withCookies=e=>{e.cookies=(e.headers.get("Cookie")||"").split(/;\s*/).map((e=>e.split(/=(.+)/))).reduce(((e,[s,i])=>i?(e[s]=i,e):e),{})};
//# sourceMappingURL=withCookies.js.map

@@ -1,1 +0,2 @@

"use strict";exports.withParams=r=>{r.proxy=new Proxy(r.proxy||r,{get:(t,e)=>{let o;return void 0!==(o=t[e])?o.bind?.(r)||o:t?.params?.[e]}})};
"use strict";exports.withParams=r=>{r.proxy=new Proxy(r.proxy||r,{get:(o,s)=>void 0!==o[s]?o[s].bind?.(r)||o[s]:o?.params?.[s]})};
//# sourceMappingURL=withParams.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc