crumpet 0.0.0-stage → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ross Robino
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
1
+ # crumpet
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build and serve full-stack TypeScript apps on [Bun](https://bun.com).
4
+
5
+ crumpet is a thin layer over `Bun.build` and `Bun.serve`. It runs a dev server that reloads the page on save, bundles the server and the client with hashed file names, and can write a Vercel build. It's under 800 lines with no dependencies.
6
+
7
+ It works with anything that has a `fetch` handler: [ovr](https://github.com/rossrobino/ovr) is the main use, and [Hono](https://hono.dev) or a hand-written `fetch` work the same way. crumpet is the Bun version of [domco](https://github.com/rossrobino/domco), which stays the Vite version. The build output has the same shape, so an app can move between the two.
8
+
9
+ > Early release, tested on Bun 1.4.5. The Vercel output is tested locally but hasn't been deployed yet.
10
+
11
+ ## The idea
12
+
13
+ - **Bun's APIs, one for one.** The app's default export is `Bun.serve` options. The `client` option is `Bun.build` options. If Bun has a feature, crumpet doesn't wrap it.
14
+ - **Nothing based on file names.** No pages folder, no HTML files, no config file and no CLI. Entry points are listed in code, and the app renders the whole page.
15
+ - **One `build.ts`.** `bun --watch build.ts` runs the dev server and `bun build.ts` builds. Extra steps go in the same file.
16
+ - **A plain output.** `dist/server/app.js` is a module Bun serves by itself: `bun dist/server/app.js`.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ bun add -d crumpet
22
+ ```
23
+
24
+ ## Set up
25
+
26
+ ```ts
27
+ // build.ts
28
+ import { build } from "crumpet";
29
+
30
+ await build({
31
+ // `bun --watch build.ts` runs the dev server, `bun build.ts` builds
32
+ development: process.execArgv.includes("--watch"),
33
+ server: "src/server/app.ts",
34
+ client: { entrypoints: ["src/client/main.ts", "src/client/main.css"] },
35
+ });
36
+ ```
37
+
38
+ ```json
39
+ {
40
+ "scripts": {
41
+ "dev": "bun --watch build.ts",
42
+ "build": "bun build.ts",
43
+ "start": "bun dist/server/app.js"
44
+ }
45
+ }
46
+ ```
47
+
48
+ The server module's default export is what Bun serves: `fetch`, `routes`, `websocket`, `port` and the rest of `Bun.serve`'s options.
49
+
50
+ ```ts
51
+ // src/server/app.ts
52
+ import { client } from "crumpet";
53
+
54
+ export default {
55
+ fetch() {
56
+ return new Response(
57
+ `<!doctype html><html><head>${client.head()}</head><body><h1>Hello</h1></body></html>`,
58
+ { headers: { "content-type": "text/html" } },
59
+ );
60
+ },
61
+ } satisfies Bun.Serve.Options<undefined>;
62
+ ```
63
+
64
+ With a framework, pass its `fetch`. ovr takes the client's IP as an option:
65
+
66
+ ```ts
67
+ export default {
68
+ fetch: (req, server) => app.fetch(req, { ip: server.requestIP(req)?.address }),
69
+ } satisfies Bun.Serve.Options<undefined>;
70
+ ```
71
+
72
+ ## API
73
+
74
+ ### `build(options)`
75
+
76
+ - `development`: `true` serves the app with the client built in memory and reloads pages on changes. `false`, the default, writes `dist/`.
77
+ - `server`: the app's module.
78
+ - `client`: `Bun.build` options for the client, so `plugins` and `define` apply in dev and in the build. crumpet sets `outdir`, `naming`, `publicPath`, `splitting` and `metafile`.
79
+
80
+ In development the server runs unbundled, `bun --watch` restarts it when server code changes, and crumpet rebuilds the client when client files change. The dev server listens on `localhost` unless the app sets `hostname`.
81
+
82
+ A build writes:
83
+
84
+ ```txt
85
+ dist/
86
+ client/_immutable/ hashed scripts, styles and files
87
+ server/app.js the app, bundled
88
+ server/manifest.json which files each entry point needs
89
+ ```
90
+
91
+ The production server sends everything in `_immutable/` with `Cache-Control: public, immutable, max-age=31536000`.
92
+
93
+ ### `client.head(...entries)`
94
+
95
+ Returns the stylesheet, modulepreload and module script tags for the client entry points, as an HTML string. With no arguments it covers every entry point; pass some to send a page only what it needs:
96
+
97
+ ```ts
98
+ client.head("src/client/main.css", "src/client/dashboard.ts");
99
+ ```
100
+
101
+ ### `client.url(file)`
102
+
103
+ Turns a file import into a URL: hashed in the build, a dev route in dev.
104
+
105
+ ```ts
106
+ import icon from "./icon.svg";
107
+
108
+ `<link rel="icon" href="${client.url(icon)}">`;
109
+ ```
110
+
111
+ ### `vercel(options?)`
112
+
113
+ Writes `.vercel/output/` from `dist/`, using Vercel's [Build Output API](https://vercel.com/docs/build-output-api/v3). Call it after `build()`; it does nothing in development.
114
+
115
+ ```ts
116
+ import { build, vercel } from "crumpet";
117
+
118
+ await build({ development, server, client });
119
+ await vercel({ isr: { expiration: 60 } });
120
+ ```
121
+
122
+ Options: `config` (the function's memory, duration and regions), `isr`, `images` and `trailingSlash`.
123
+
124
+ ## Things to know
125
+
126
+ - **Tailwind** works as a client plugin: `client: { entrypoints, plugins: [tailwind] }` with `bun-plugin-tailwind`.
127
+ - **Don't preload a font under 128 KB that the CSS uses.** Bun inlines files that small into the stylesheet, so the font arrives with the CSS and a preload would download it again.
128
+ - **Types for file imports are the app's.** Bun declares only a few extensions, so declare the rest, such as `*.svg`, in a `.d.ts` file. See [`example/src/env.d.ts`](./example/src/env.d.ts).
129
+ - **Text imports** use `with { type: "text" }`, and path aliases come from tsconfig `paths`. Both are Bun's.
130
+
131
+ ## Example
132
+
133
+ [`example/`](./example) is an ovr app with Tailwind, a font, a text import and the Vercel step.
134
+
135
+ ## Develop
136
+
137
+ ```sh
138
+ bun install
139
+ bun test # runs a small app through build, production and dev
140
+ bun run check # type check
141
+ bun run build # dist/, built with Bun
142
+ ```
143
+
144
+ The Tailwind tests use the example's packages, so run `bun install` in `example/` too.
@@ -0,0 +1,76 @@
1
+ import type { BuildConfig, Server } from "bun";
2
+ import { type VercelOptions } from "./vercel.js";
3
+ export { onVercel, type VercelOptions } from "./vercel.js";
4
+ /**
5
+ * The default export of the app's module: `Bun.serve` options, exactly what
6
+ * Bun serves by itself. crumpet adds its routes and sets `development`.
7
+ */
8
+ type App = Bun.Serve.Options<any>;
9
+ export declare const client: {
10
+ /**
11
+ * @param entries client entry points as passed to `build()`, all of them by default
12
+ * @returns the stylesheet, modulepreload and module script tags they need
13
+ */
14
+ head(...entries: string[]): string;
15
+ /**
16
+ * @param file a file import, such as `import font from "./font.woff2"`
17
+ * @returns its URL: hashed in the build, served by the dev server in dev
18
+ */
19
+ url(file: string): string;
20
+ };
21
+ export type BuildOptions = {
22
+ /**
23
+ * Named after `Bun.serve`'s option, which it also sets.
24
+ *
25
+ * - `true`: serves the app with the client built in memory and reloads
26
+ * pages on changes. Run under `bun --watch`, which restarts it when server
27
+ * code changes.
28
+ * - `false`: writes `dist/` and exits.
29
+ *
30
+ * @default false
31
+ */
32
+ development?: boolean;
33
+ /** The app's module, such as `"src/server/app.tsx"`, whose default export is `Bun.serve` options. */
34
+ server: string;
35
+ /**
36
+ * `Bun.build` options for the client. `entrypoints` are the client entry
37
+ * points, such as `["src/client/main.ts", "src/client/main.css"]`. crumpet
38
+ * sets `outdir`, `naming`, `publicPath`, `splitting` and `metafile` itself.
39
+ */
40
+ client: BuildConfig;
41
+ };
42
+ /**
43
+ * Serves the app in development, or builds it. Called from the app's
44
+ * `build.ts`:
45
+ *
46
+ * ```ts
47
+ * const development = process.execArgv.includes("--watch");
48
+ * await build({ development, server: "src/server/app.tsx", client: { entrypoints: ["src/client/main.ts"] } });
49
+ * ```
50
+ *
51
+ * @returns the dev server in development, nothing after a build
52
+ */
53
+ export declare const build: (options: BuildOptions) => Promise<Server<any> | undefined>;
54
+ /**
55
+ * Writes `.vercel/output/` from `dist/`, Vercel's Build Output API. Call it
56
+ * after `build()`. It does nothing in development, so it needs no condition:
57
+ *
58
+ * ```ts
59
+ * await build({ development, server, client });
60
+ * await vercel({ isr: { expiration: 60 } });
61
+ * ```
62
+ *
63
+ * - `static/`: `dist/client/`, served by Vercel's CDN
64
+ * - `functions/fn.func/`: `dist/server/` and a `main.js` that exports the app
65
+ * for Vercel's Bun runtime
66
+ * - `config.json`: the routes
67
+ */
68
+ export declare const vercel: (options?: VercelOptions) => Promise<void>;
69
+ /**
70
+ * The production server: the default export of the bundle `build()` writes.
71
+ * Bun serves a module's default export when it has `fetch`.
72
+ *
73
+ * @internal used by the generated entry, not by apps
74
+ */
75
+ export declare const production: (app: App) => App;
76
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAe,MAAM,EAAE,MAAM,KAAK,CAAC;AAQ5D,OAAO,EAAE,KAAK,aAAa,EAAoB,MAAM,aAAa,CAAC;AAEnE,OAAO,EAAE,QAAQ,EAAE,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AAE3D;;;GAGG;AACH,KAAK,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AA0ClC,eAAO,MAAM,MAAM;IAClB;;;OAGG;IACH,IAAI,aAAa,MAAM,EAAE;IAwBzB;;;OAGG;IACH,GAAG,OAAO,MAAM;CAKhB,CAAC;AA+DF,MAAM,MAAM,YAAY,GAAG;IAC1B;;;;;;;;;OASG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,qGAAqG;IACrG,MAAM,EAAE,MAAM,CAAC;IACf;;;;OAIG;IACH,MAAM,EAAE,WAAW,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,KAAK,YAAmB,YAAY,qCAIhD,CAAC;AAKF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,MAAM,aAAoB,aAAa,kBAEnD,CAAC;AAyIF;;;;;GAKG;AACH,eAAO,MAAM,UAAU,QAAS,GAAG,KAmB7B,GACL,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ // @bun
2
+ import T from"fs/promises";import l from"path";import{styleText as d}from"util";var M="0.0.3";import R from"fs/promises";import{isIP as J}from"net";import g from"path";import{styleText as P}from"util";var y="__pathname",G=(e,a)=>{let t=new URL(e.url),r=e.headers.get("x-forwarded-proto")?.split(",",1)[0].trim().toLowerCase(),i=(r==="https"||r==="http")&&t.protocol!==r+":";if(!i&&!a)return e;if(i)t.protocol=r;if(a)t.pathname="/"+(t.searchParams.get(y)??""),t.searchParams.delete(y);return new Request(t,e)},H=(e,a)=>{let t=e.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim(),r=t?J(t):0,i=()=>r?{address:t,family:r===6?"IPv6":"IPv4",port:0}:null;if(!a)return{requestIP:i};return new Proxy(a,{get(n,c){if(c==="requestIP")return i;let s=Reflect.get(n,c);return typeof s==="function"?s.bind(n):s}})},K=(e,a={})=>{let t=e.fetch;if(!t)return e;return{...e,fetch:(r,i)=>t.call(e,G(r,a.isr),H(r,i))}},E=async(e={})=>{let a=g.join(".vercel","output"),t=g.join(a,"functions","fn.func"),{isr:r}=e;if(!await Bun.file("dist/server/app.js").exists())throw Error("crumpet: `vercel()` needs `dist/`. Call `build()` first, without `development`.");let i={handler:"main.js",runtime:"bun1.x",supportsResponseStreaming:!0,...e.config},n=[];if(e.trailingSlash===!0)n.push({src:"^/((?:[^/]+/)*[^/\\.]+)$",headers:{Location:"/$1/"},status:308},{src:"^/((?:[^/]+/)*[^/]+\\.\\w+)/$",headers:{Location:"/$1"},status:308});else if(e.trailingSlash===!1)n.push({src:"^/(.*)\\/$",headers:{Location:"/$1"},status:308});n.push({src:"/_immutable/.+",headers:{"Cache-Control":"public, immutable, max-age=31536000"}},{methods:["GET"],handle:"filesystem"},{src:"^/(.*)$",dest:r?`/fn?${y}=$1`:"/fn"});let c=(s,u)=>Bun.write(g.join(a,s),JSON.stringify(u,null,"\t"));await R.rm(a,{recursive:!0,force:!0}),await Promise.all([R.cp("dist/client",g.join(a,"static"),{recursive:!0}),R.cp("dist/server",t,{recursive:!0}),Bun.write(g.join(t,"main.js"),`import { vercel } from "./app.js";
3
+
4
+ export default vercel(${JSON.stringify({isr:Boolean(r)})});
5
+ `),c("config.json",{version:3,framework:{slug:"crumpet",version:M},routes:n,...e.images&&{images:e.images}}),c("functions/fn.func/.vc-config.json",i),c("functions/fn.func/package.json",{type:"module"}),r&&c("functions/fn.prerender-config.json",{group:1,passQuery:!0,...r,allowQuery:[...r.allowQuery??[],y]})]),console.log(`${P("green","\u2713")} wrote ${P("bold",a+g.sep)} ${P("dim",`for ${i.runtime}`)}`)};var W=(e)=>Array.isArray(e.routes)?{}:e.routes,U=typeof __CRUMPET_BUNDLED__<"u",V=U?await Bun.file(new URL("./manifest.json",import.meta.url)).json():void 0,j=V?.entries??{},k=new Map,D="",w="/_crumpet/reload",S="/_crumpet/file/",I=new Set,me={head(...e){let a=e.join(`
6
+ `),t=k.get(a);if(t!==void 0)return t;let r=new Set,i=(n,c)=>{if(!r.has(n))t+=c;r.add(n)};t="";for(let n of e.length?e:Object.keys(j)){let c=j[l.normalize(n)];if(!c)throw Error(`crumpet: "${n}" is not a client entry point.`);for(let s of c.styles)i(s,`<link rel="stylesheet" href="${s}">`);for(let s of c.preloads)i(s,`<link rel="modulepreload" href="${s}">`);for(let s of c.scripts)i(s,`<script type="module" src="${s}"></script>`)}return t+=D,k.set(a,t),t},url(e){if(U||!l.isAbsolute(e))return e;return I.add(e),S+l.relative(process.cwd(),e)}},q=(e)=>({...e,naming:{entry:"_immutable/[name]-[hash].[ext]",chunk:"_immutable/[name]-[hash].[ext]",asset:"_immutable/[name]-[hash].[ext]"},publicPath:"/",splitting:!0,metafile:!0}),v=(e)=>"/"+e.replace(/^\.?\//,""),N=(e)=>{let a=new Map(Object.entries(e.metafile.outputs).map(([i,n])=>[v(i),n])),t=(i,n=new Set)=>{for(let c of a.get(i)?.imports??[]){let s=v(c.path);if(c.kind==="import-statement"&&a.has(s)&&!n.has(s))n.add(s),t(s,n)}return n},r={};for(let[i,n]of a){if(!n.entryPoint)continue;let c=i.endsWith(".css");if(c&&!n.entryPoint.endsWith(".css"))continue;r[l.normalize(n.entryPoint)]=c?{scripts:[],styles:[i],preloads:[]}:{scripts:[i],styles:n.cssBundle?[v(n.cssBundle)]:[],preloads:[...t(i)]}}return r},de=async(e)=>{if(_=Boolean(e.development),_)return X(e);await Y(e)},_=!1,fe=async(e)=>{if(!_)await E(e)},X=async(e)=>{let a=performance.now();if(!process.execArgv.includes("--watch"))console.warn("crumpet: run the dev server with `bun --watch`, or server changes won't restart it.");D=`<script type="module">const c=(r)=>{const w=new WebSocket(location.origin.replace("http","ws")+"${w}");w.onopen=()=>r&&location.reload();w.onmessage=()=>location.reload();w.onclose=()=>setTimeout(c,100,1)};c()</script>`;let t={sourcemap:"inline",...q(e.client),throw:!1},[{default:r},i]=await Promise.all([import(l.resolve(e.server)),Bun.build(t)]),n={},c={[w]:(o,p)=>p.upgrade(o,{data:n})?void 0:new Response(null,{status:400}),[S+"*"]:(o)=>{let p=l.resolve(decodeURIComponent(new URL(o.url).pathname.slice(S.length)));return I.has(p)?new Response(Bun.file(p),{headers:{"cache-control":"no-cache"}}):new Response(null,{status:404})}},s=[...new Set(t.entrypoints.map((o)=>l.resolve(l.dirname(o))))],u=new Set,m=(o,p=!1)=>{if(u.has(o)||o.split(l.sep).includes("node_modules")||!p&&s.some((f)=>o.startsWith(f+l.sep)))return;u.add(o),(async()=>{for await(let f of T.watch(o,{recursive:p}))Q()})().catch(()=>u.delete(o))},O=(o)=>{j=N(o),k.clear();for(let p in o.metafile.inputs)m(l.resolve(l.dirname(p)));return Object.fromEntries(o.outputs.map((p)=>[v(p.path),new Response(p,{headers:{"cache-control":"no-cache"}})]))},h=r.websocket,C={...h,open:(o)=>o.data===n?void o.subscribe(w):h?.open?.(o),message:(o,p)=>o.data===n?void 0:h?.message?.(o,p),close:(o,p,f)=>o.data===n?void 0:h?.close?.(o,p,f),drain:(o)=>o.data===n?void 0:h?.drain?.(o)},z=(o)=>({...c,...o,...W(r)});if(!i.success)console.error(i.logs);for(let o of s)m(o,!0);let b=Bun.serve({hostname:"localhost",...r,development:!0,routes:z(i.success?O(i):{}),websocket:C}),B=!1,x=!1,Q=async()=>{if(B){x=!0;return}B=!0;let o=performance.now();await Bun.sleep(10);let p=!1;do{x=!1;let f=await Bun.build(t);if(p=f.success,!p)console.error(f.logs);else b.reload({...r,development:!0,routes:z(O(f)),websocket:C})}while(x);if(B=!1,p)console.log(d("dim",`client rebuilt in ${Math.round(performance.now()-o)} ms`));b.publish(w,"reload")};return console.log(`
7
+ ${d(["bold","green"],"crumpet dev")} ${d("cyan",b.url.href)} ${d("dim",`ready in ${Math.round(performance.now()-a)} ms`)}
8
+ `),b},ge=(e)=>{let a=Bun.fileURLToPath(new URL("../client/",import.meta.url));return{...e,development:!1,routes:{...Object.fromEntries(V.files.map((t)=>["/"+t,new Response(Bun.file(l.join(a,t)),{headers:t.startsWith("_immutable/")?{"cache-control":"public, immutable, max-age=31536000"}:{}})])),...W(e)}}},Y=async(e)=>{let a=performance.now();await T.rm("dist",{recursive:!0,force:!0});let t=l.resolve(".crumpet-entry.ts"),[r,i]=await Promise.all([Bun.build({minify:!0,...q(e.client),outdir:"dist/client",throw:!0}),Bun.build({entrypoints:[t],files:{[t]:`import app from ${JSON.stringify(l.resolve(e.server))};
9
+ import { onVercel, production } from "crumpet";
10
+
11
+ export default production(app);
12
+ // for the function \`vercel()\` writes
13
+ export const vercel = (options) => onVercel(app, options);
14
+ `},target:"bun",outdir:"dist/client",naming:{entry:"../server/app.js",asset:"_immutable/[name]-[hash].[ext]"},publicPath:"/",define:{__CRUMPET_BUNDLED__:"true"},minify:{syntax:!0}})]),n=l.resolve("dist/client"),c=r.outputs.filter((m)=>m.size===0),s=[...r.outputs,...i.outputs].filter((m)=>m.size>0&&m.path.startsWith(n+l.sep)).map((m)=>l.relative(n,m.path));await Promise.all([...c.map((m)=>Bun.file(m.path).delete()),Bun.write("dist/server/manifest.json",JSON.stringify({entries:N(r),files:[...new Set(s)]}))]);let u=performance.now()-a;await ee([...new Set([...r.outputs,...i.outputs])].filter((m)=>m.size>0).map((m)=>l.relative(process.cwd(),m.path)),u)},A=(e)=>`${(e/1000).toFixed(2)} kB`,Z=/\.(m?js|css|html|json|svg|txt|xml)$/,L=(e)=>e.startsWith("dist/server/")?3:e.endsWith(".js")?2:e.endsWith(".css")?1:0,ee=async(e,a)=>{let t=(await Promise.all(e.map(async(s)=>{let u=await Bun.file(s).bytes();return{file:s,size:A(u.length),bytes:u.length,gzip:Z.test(s)?A(Bun.gzipSync(u).length):""}}))).sort((s,u)=>L(s.file)-L(u.file)||s.bytes-u.bytes),r=(s)=>Math.max(...t.map((u)=>u[s].length)),[i,n,c]=[r("file"),r("size"),r("gzip")];console.log();for(let s of t){let u=l.basename(s.file),m=u.endsWith(".js")?"cyan":u.endsWith(".css")?"magenta":"green";console.log(d("dim",l.dirname(s.file)+"/")+d(m,u)+" ".repeat(i-s.file.length+2)+d("bold",s.size.padStart(n))+(s.gzip?d("dim",` \u2502 gzip: ${s.gzip.padStart(c)}`):""))}console.log(`
15
+ ${d("green","\u2713")} built in ${d("bold",`${Math.round(a)} ms`)}`)};export{de as build,me as client,K as onVercel,ge as production,fe as vercel};
16
+
17
+ //# debugId=42590C36482933DF64756E2164756E21
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/vercel.ts"],
4
+ "sourcesContent": [
5
+ "// crumpet: `build()`, `client` and the dev and production servers, on top of Bun.\nimport type { BuildConfig, BuildOutput, Server } from \"bun\";\n// Bun has no file watcher, recursive delete or rename of its own, and `path` is plain string work\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n// Bun implements Node's styleText, which leaves colors out when the output\n// isn't a terminal or NO_COLOR is set, and adds them with FORCE_COLOR\nimport { styleText } from \"node:util\";\n\nimport { type VercelOptions, vercel as output } from \"./vercel.js\";\n\nexport { onVercel, type VercelOptions } from \"./vercel.js\";\n\n/**\n * The default export of the app's module: `Bun.serve` options, exactly what\n * Bun serves by itself. crumpet adds its routes and sets `development`.\n */\ntype App = Bun.Serve.Options<any>;\n\n/** The app's own Bun routes. A framework instance can have an unrelated `routes` array. */\nconst appRoutes = (app: App) => (Array.isArray(app.routes) ? {} : app.routes);\n\n/** Tags for one client entry point, by kind. */\ntype Entry = { scripts: string[]; styles: string[]; preloads: string[] };\ntype Manifest = Record<string, Entry>;\n\n/** What `build()` writes to `dist/server/manifest.json`. */\ntype Built = {\n\t/** Tags for each client entry point. */\n\tentries: Manifest;\n\t/** Every file in `dist/client/`, relative to it. */\n\tfiles: string[];\n};\n\n/** Defined when `build()` bundles the server. */\ndeclare const __CRUMPET_BUNDLED__: true;\nconst bundled = typeof __CRUMPET_BUNDLED__ !== \"undefined\";\n\n// Read when the bundle starts, next to it, so the client and server builds\n// don't wait on each other. Top-level await: modules that import crumpet run\n// after it, so `client.head()` works even at their top level.\nconst built: Built | undefined = bundled\n\t? await Bun.file(new URL(\"./manifest.json\", import.meta.url)).json()\n\t: undefined;\n\nlet manifest: Manifest = built?.entries ?? {};\n\n/** `client.head()` results, by entry list. Cleared when the manifest changes. */\nconst heads = new Map<string, string>();\n\n/** Set by the dev server: the script that reloads pages, added by `client.head()`. */\nlet devScript = \"\";\n\nconst reloadPath = \"/_crumpet/reload\";\nconst filePath = \"/_crumpet/file/\";\n\n/** Files `client.url()` has returned in dev: the only ones the dev server sends. */\nconst served = new Set<string>();\n\nexport const client = {\n\t/**\n\t * @param entries client entry points as passed to `build()`, all of them by default\n\t * @returns the stylesheet, modulepreload and module script tags they need\n\t */\n\thead(...entries: string[]) {\n\t\tconst key = entries.join(\"\\n\");\n\t\tlet html = heads.get(key);\n\t\tif (html !== undefined) return html;\n\n\t\tconst seen = new Set<string>();\n\t\tconst tag = (url: string, markup: string) => {\n\t\t\tif (!seen.has(url)) html += markup;\n\t\t\tseen.add(url);\n\t\t};\n\t\thtml = \"\";\n\t\tfor (const name of entries.length ? entries : Object.keys(manifest)) {\n\t\t\t// the manifest's names are normalized: `./src/main.ts` is `src/main.ts`\n\t\t\tconst entry = manifest[path.normalize(name)];\n\t\t\tif (!entry) throw new Error(`crumpet: \"${name}\" is not a client entry point.`);\n\t\t\tfor (const url of entry.styles) tag(url, `<link rel=\"stylesheet\" href=\"${url}\">`);\n\t\t\tfor (const url of entry.preloads) tag(url, `<link rel=\"modulepreload\" href=\"${url}\">`);\n\t\t\tfor (const url of entry.scripts) tag(url, `<script type=\"module\" src=\"${url}\"></script>`);\n\t\t}\n\t\thtml += devScript;\n\t\theads.set(key, html);\n\t\treturn html;\n\t},\n\n\t/**\n\t * @param file a file import, such as `import font from \"./font.woff2\"`\n\t * @returns its URL: hashed in the build, served by the dev server in dev\n\t */\n\turl(file: string) {\n\t\tif (bundled || !path.isAbsolute(file)) return file;\n\t\tserved.add(file);\n\t\treturn filePath + path.relative(process.cwd(), file);\n\t},\n};\n\n/** The app's client options with crumpet's own on top. */\nconst clientConfig = (client: BuildConfig): BuildConfig => ({\n\t...client,\n\tnaming: {\n\t\tentry: \"_immutable/[name]-[hash].[ext]\",\n\t\tchunk: \"_immutable/[name]-[hash].[ext]\",\n\t\tasset: \"_immutable/[name]-[hash].[ext]\",\n\t},\n\tpublicPath: \"/\",\n\tsplitting: true,\n\tmetafile: true,\n});\n\n/** `./_immutable/a.js` or `_immutable/a.js` to `/_immutable/a.js` */\nconst url = (file: string) => \"/\" + file.replace(/^\\.?\\//, \"\");\n\n/** Reads which output files each entry point needs from Bun's metafile. */\nconst toManifest = (result: BuildOutput): Manifest => {\n\tconst outputs = new Map(\n\t\tObject.entries(\n\t\t\tresult.metafile!.outputs as Record<\n\t\t\t\tstring,\n\t\t\t\t{\n\t\t\t\t\tentryPoint?: string;\n\t\t\t\t\tcssBundle?: string;\n\t\t\t\t\timports?: { path: string; kind: string }[];\n\t\t\t\t}\n\t\t\t>,\n\t\t).map(([file, out]) => [url(file), out]),\n\t);\n\n\t/** Chunks an output imports statically, all the way down. */\n\tconst chunks = (file: string, found = new Set<string>()) => {\n\t\tfor (const i of outputs.get(file)?.imports ?? []) {\n\t\t\tconst chunk = url(i.path);\n\t\t\tif (i.kind === \"import-statement\" && outputs.has(chunk) && !found.has(chunk)) {\n\t\t\t\tfound.add(chunk);\n\t\t\t\tchunks(chunk, found);\n\t\t\t}\n\t\t}\n\t\treturn found;\n\t};\n\n\tconst m: Manifest = {};\n\tfor (const [file, out] of outputs) {\n\t\tif (!out.entryPoint) continue;\n\t\tconst css = file.endsWith(\".css\");\n\t\t// the CSS a script imports is an output with the script's entry point:\n\t\t// it's that entry's `cssBundle`, not an entry of its own\n\t\tif (css && !out.entryPoint.endsWith(\".css\")) continue;\n\t\tm[path.normalize(out.entryPoint)] = css\n\t\t\t? { scripts: [], styles: [file], preloads: [] }\n\t\t\t: {\n\t\t\t\t\tscripts: [file],\n\t\t\t\t\tstyles: out.cssBundle ? [url(out.cssBundle)] : [],\n\t\t\t\t\tpreloads: [...chunks(file)],\n\t\t\t\t};\n\t}\n\treturn m;\n};\n\nexport type BuildOptions = {\n\t/**\n\t * Named after `Bun.serve`'s option, which it also sets.\n\t *\n\t * - `true`: serves the app with the client built in memory and reloads\n\t * pages on changes. Run under `bun --watch`, which restarts it when server\n\t * code changes.\n\t * - `false`: writes `dist/` and exits.\n\t *\n\t * @default false\n\t */\n\tdevelopment?: boolean;\n\t/** The app's module, such as `\"src/server/app.tsx\"`, whose default export is `Bun.serve` options. */\n\tserver: string;\n\t/**\n\t * `Bun.build` options for the client. `entrypoints` are the client entry\n\t * points, such as `[\"src/client/main.ts\", \"src/client/main.css\"]`. crumpet\n\t * sets `outdir`, `naming`, `publicPath`, `splitting` and `metafile` itself.\n\t */\n\tclient: BuildConfig;\n};\n\n/**\n * Serves the app in development, or builds it. Called from the app's\n * `build.ts`:\n *\n * ```ts\n * const development = process.execArgv.includes(\"--watch\");\n * await build({ development, server: \"src/server/app.tsx\", client: { entrypoints: [\"src/client/main.ts\"] } });\n * ```\n *\n * @returns the dev server in development, nothing after a build\n */\nexport const build = async (options: BuildOptions) => {\n\tdevelopment = Boolean(options.development);\n\tif (development) return dev(options);\n\tawait bundle(options);\n};\n\n/** Set by `build()`: in development there's no `dist/` for `vercel()` to use. */\nlet development = false;\n\n/**\n * Writes `.vercel/output/` from `dist/`, Vercel's Build Output API. Call it\n * after `build()`. It does nothing in development, so it needs no condition:\n *\n * ```ts\n * await build({ development, server, client });\n * await vercel({ isr: { expiration: 60 } });\n * ```\n *\n * - `static/`: `dist/client/`, served by Vercel's CDN\n * - `functions/fn.func/`: `dist/server/` and a `main.js` that exports the app\n * for Vercel's Bun runtime\n * - `config.json`: the routes\n */\nexport const vercel = async (options?: VercelOptions) => {\n\tif (!development) await output(options);\n};\n\n/** Serves the app with a client build in memory. */\nconst dev = async (options: BuildOptions) => {\n\tconst start = performance.now();\n\tif (!process.execArgv.includes(\"--watch\")) {\n\t\tconsole.warn(\n\t\t\t\"crumpet: run the dev server with `bun --watch`, or server changes won't restart it.\",\n\t\t);\n\t}\n\t// Reloads the page when the dev server sends a message, and once it's back\n\t// after a restart: a closed socket retries every 100 ms, and the next one\n\t// that opens reloads. Set here so the production bundle leaves it out.\n\tdevScript = `<script type=\"module\">const c=(r)=>{const w=new WebSocket(location.origin.replace(\"http\",\"ws\")+\"${reloadPath}\");w.onopen=()=>r&&location.reload();w.onmessage=()=>location.reload();w.onclose=()=>setTimeout(c,100,1)};c()</script>`;\n\n\t// the app and the first client build, at the same time; the app is imported\n\t// here so it's in this process's module graph and `bun --watch` restarts on its changes\n\t// `throw: false`: a build that fails is logged, and the last one stays up\n\tconst config: BuildConfig = { sourcemap: \"inline\", ...clientConfig(options.client), throw: false };\n\tconst [{ default: app }, first] = await Promise.all([\n\t\timport(path.resolve(options.server)) as Promise<{ default: App }>,\n\t\tBun.build(config),\n\t]);\n\n\t/** `ws.data` of the reload sockets, to tell them from the app's own. */\n\tconst reload = {};\n\n\tconst fixed = {\n\t\t[reloadPath]: (req: Request, server: Server<unknown>) =>\n\t\t\tserver.upgrade(req, { data: reload }) ? undefined : new Response(null, { status: 400 }),\n\t\t// only files `client.url()` has returned, never the rest of the project\n\t\t[filePath + \"*\"]: (req: Request) => {\n\t\t\tconst file = path.resolve(\n\t\t\t\tdecodeURIComponent(new URL(req.url).pathname.slice(filePath.length)),\n\t\t\t);\n\t\t\treturn served.has(file)\n\t\t\t\t? new Response(Bun.file(file), { headers: { \"cache-control\": \"no-cache\" } })\n\t\t\t\t: new Response(null, { status: 404 });\n\t\t},\n\t};\n\n\t// Client files aren't in the server's module graph, so `bun --watch` doesn't\n\t// see them. The entry points' folders are watched with their subfolders, and\n\t// so is the folder of every other file a build read, wherever it is.\n\tconst roots = [...new Set(config.entrypoints.map((e) => path.resolve(path.dirname(e))))];\n\tconst watched = new Set<string>();\n\tconst watch = (dir: string, recursive = false) => {\n\t\tif (\n\t\t\twatched.has(dir) ||\n\t\t\tdir.split(path.sep).includes(\"node_modules\") ||\n\t\t\t(!recursive && roots.some((root) => dir.startsWith(root + path.sep)))\n\t\t)\n\t\t\treturn;\n\t\twatched.add(dir);\n\t\t(async () => {\n\t\t\tfor await (const _ of fs.watch(dir, { recursive })) void changed();\n\t\t})().catch(() => watched.delete(dir)); // not a folder: a plugin's virtual file\n\t};\n\n\t/** The client build as routes, served from memory without caching. */\n\tconst clientRoutes = (result: BuildOutput) => {\n\t\tmanifest = toManifest(result);\n\t\theads.clear();\n\t\tfor (const input in result.metafile!.inputs) watch(path.resolve(path.dirname(input)));\n\t\treturn Object.fromEntries(\n\t\t\tresult.outputs.map((o) => [\n\t\t\t\turl(o.path),\n\t\t\t\tnew Response(o, { headers: { \"cache-control\": \"no-cache\" } }),\n\t\t\t]),\n\t\t);\n\t};\n\n\t// Bun has one `websocket` handler per server: reload sockets are handled\n\t// here, the app's sockets by the app's handler\n\tconst theirs = app.websocket;\n\tconst websocket: Bun.WebSocketHandler<any> = {\n\t\t...theirs,\n\t\topen: (ws) => (ws.data === reload ? void ws.subscribe(reloadPath) : theirs?.open?.(ws)),\n\t\tmessage: (ws, message) => (ws.data === reload ? undefined : theirs?.message?.(ws, message)),\n\t\tclose: (ws, code, reason) => (ws.data === reload ? undefined : theirs?.close?.(ws, code, reason)),\n\t\tdrain: (ws) => (ws.data === reload ? undefined : theirs?.drain?.(ws)),\n\t};\n\n\tconst routes = (client: Record<string, Response>) => ({ ...fixed, ...client, ...appRoutes(app) });\n\n\tif (!first.success) console.error(first.logs);\n\tfor (const root of roots) watch(root, true);\n\tconst server = Bun.serve({\n\t\t// not the whole network, unless the app says so\n\t\thostname: \"localhost\",\n\t\t...app,\n\t\tdevelopment: true,\n\t\troutes: routes(first.success ? clientRoutes(first) : {}),\n\t\twebsocket,\n\t} as App);\n\n\t// One save can send several events, and a change can come in during a\n\t// rebuild: wait briefly, run one rebuild at a time, then one more if\n\t// anything changed meanwhile, and reload the pages once it's done.\n\tlet building = false;\n\tlet again = false;\n\tconst changed = async () => {\n\t\tif (building) {\n\t\t\tagain = true;\n\t\t\treturn;\n\t\t}\n\t\tbuilding = true;\n\t\tconst started = performance.now();\n\t\t// a save is often two events (write, then rename); wait for the rest of it\n\t\tawait Bun.sleep(10);\n\t\tlet ok = false;\n\t\tdo {\n\t\t\tagain = false;\n\t\t\tconst result = await Bun.build(config);\n\t\t\tok = result.success;\n\t\t\tif (!ok) console.error(result.logs);\n\t\t\telse\n\t\t\t\tserver.reload({\n\t\t\t\t\t...app,\n\t\t\t\t\tdevelopment: true,\n\t\t\t\t\troutes: routes(clientRoutes(result)),\n\t\t\t\t\twebsocket,\n\t\t\t\t} as App);\n\t\t} while (again);\n\t\tbuilding = false;\n\t\tif (ok) {\n\t\t\tconsole.log(styleText(\"dim\", `client rebuilt in ${Math.round(performance.now() - started)} ms`));\n\t\t}\n\t\tserver.publish(reloadPath, \"reload\");\n\t};\n\n\tconsole.log(\n\t\t`\\n${styleText([\"bold\", \"green\"], \"crumpet dev\")} ${styleText(\"cyan\", server.url.href)} ${styleText(\"dim\", `ready in ${Math.round(performance.now() - start)} ms`)}\\n`,\n\t);\n\treturn server;\n};\n\n/**\n * The production server: the default export of the bundle `build()` writes.\n * Bun serves a module's default export when it has `fetch`.\n *\n * @internal used by the generated entry, not by apps\n */\nexport const production = (app: App) => {\n\tconst dir = Bun.fileURLToPath(new URL(\"../client/\", import.meta.url));\n\treturn {\n\t\t...app,\n\t\t// Bun.serve runs in development mode unless NODE_ENV is production\n\t\tdevelopment: false,\n\t\troutes: {\n\t\t\t...Object.fromEntries(\n\t\t\t\tbuilt!.files.map((file) => [\n\t\t\t\t\t\"/\" + file,\n\t\t\t\t\tnew Response(Bun.file(path.join(dir, file)), {\n\t\t\t\t\t\theaders: file.startsWith(\"_immutable/\")\n\t\t\t\t\t\t\t? { \"cache-control\": \"public, immutable, max-age=31536000\" }\n\t\t\t\t\t\t\t: {},\n\t\t\t\t\t}),\n\t\t\t\t]),\n\t\t\t),\n\t\t\t...appRoutes(app),\n\t\t},\n\t} as App;\n};\n\n/**\n * Builds `dist/client/` (hashed files under `_immutable/`) and bundles the app\n * into `dist/server/app.js`, whose default export Bun serves by itself:\n * `bun dist/server/app.js`. The client and the server build at the same time.\n */\nconst bundle = async (options: BuildOptions) => {\n\tconst start = performance.now();\n\tawait fs.rm(\"dist\", { recursive: true, force: true });\n\n\t// only exists in memory, through `Bun.build`'s `files`\n\tconst entry = path.resolve(\".crumpet-entry.ts\");\n\tconst [clientResult, serverResult] = await Promise.all([\n\t\tBun.build({\n\t\t\tminify: true,\n\t\t\t...clientConfig(options.client),\n\t\t\toutdir: \"dist/client\",\n\t\t\t// a build that fails throws, with Bun's own errors\n\t\t\tthrow: true,\n\t\t}),\n\t\tBun.build({\n\t\t\tentrypoints: [entry],\n\t\t\tfiles: {\n\t\t\t\t[entry]: `import app from ${JSON.stringify(path.resolve(options.server))};\nimport { onVercel, production } from \"crumpet\";\n\nexport default production(app);\n// for the function \\`vercel()\\` writes\nexport const vercel = (options) => onVercel(app, options);\n`,\n\t\t\t},\n\t\t\ttarget: \"bun\",\n\t\t\t// the bundle goes to `dist/server/`, and files it imports, such as\n\t\t\t// fonts, straight to `dist/client/_immutable/` with the client's files\n\t\t\toutdir: \"dist/client\",\n\t\t\tnaming: {\n\t\t\t\tentry: \"../server/app.js\",\n\t\t\t\tasset: \"_immutable/[name]-[hash].[ext]\",\n\t\t\t},\n\t\t\tpublicPath: \"/\",\n\t\t\tdefine: { __CRUMPET_BUNDLED__: \"true\" },\n\t\t\t// folds `bundled` and drops dev-only code; names and lines stay readable\n\t\t\tminify: { syntax: true },\n\t\t}),\n\t]);\n\tconst client = path.resolve(\"dist/client\");\n\t// a CSS entry point also writes an empty JavaScript file\n\tconst empty = clientResult.outputs.filter((o) => o.size === 0);\n\tconst files = [...clientResult.outputs, ...serverResult.outputs]\n\t\t.filter((o) => o.size > 0 && o.path.startsWith(client + path.sep))\n\t\t.map((o) => path.relative(client, o.path));\n\n\tawait Promise.all([\n\t\t...empty.map((o) => Bun.file(o.path).delete()),\n\t\tBun.write(\n\t\t\t\"dist/server/manifest.json\",\n\t\t\tJSON.stringify({\n\t\t\t\tentries: toManifest(clientResult),\n\t\t\t\tfiles: [...new Set(files)],\n\t\t\t} satisfies Built),\n\t\t),\n\t]);\n\n\tconst ms = performance.now() - start;\n\tawait report(\n\t\t[...new Set([...clientResult.outputs, ...serverResult.outputs])]\n\t\t\t.filter((o) => o.size > 0)\n\t\t\t.map((o) => path.relative(process.cwd(), o.path)),\n\t\tms,\n\t);\n};\n\nconst kB = (bytes: number) => `${(bytes / 1000).toFixed(2)} kB`;\n\n/** Text files, which servers send compressed. Fonts and images already are. */\nconst compressible = /\\.(m?js|css|html|json|svg|txt|xml)$/;\n\n/** Sorts like Vite: other files, then CSS, then JavaScript, the server last; by size within each. */\nconst order = (file: string) =>\n\tfile.startsWith(\"dist/server/\") ? 3 : file.endsWith(\".js\") ? 2 : file.endsWith(\".css\") ? 1 : 0;\n\n/**\n * Prints each output file with its size, and its gzip size if it's text, then\n * the build time:\n *\n * ```txt\n * dist/client/_immutable/main-vz4hds88.css 26.80 kB │ gzip: 20.13 kB\n * dist/server/app.js 135.06 kB │ gzip: 29.86 kB\n *\n * ✓ built in 24 ms\n * ```\n */\nconst report = async (files: string[], ms: number) => {\n\tconst rows = (\n\t\tawait Promise.all(\n\t\t\tfiles.map(async (file) => {\n\t\t\t\tconst bytes = await Bun.file(file).bytes();\n\t\t\t\treturn {\n\t\t\t\t\tfile,\n\t\t\t\t\tsize: kB(bytes.length),\n\t\t\t\t\tbytes: bytes.length,\n\t\t\t\t\tgzip: compressible.test(file) ? kB(Bun.gzipSync(bytes).length) : \"\",\n\t\t\t\t};\n\t\t\t}),\n\t\t)\n\t).sort((a, b) => order(a.file) - order(b.file) || a.bytes - b.bytes);\n\n\tconst width = (key: \"file\" | \"size\" | \"gzip\") => Math.max(...rows.map((r) => r[key].length));\n\tconst [file, size, gzip] = [width(\"file\"), width(\"size\"), width(\"gzip\")];\n\n\tconsole.log();\n\tfor (const row of rows) {\n\t\tconst name = path.basename(row.file);\n\t\tconst color = name.endsWith(\".js\") ? \"cyan\" : name.endsWith(\".css\") ? \"magenta\" : \"green\";\n\t\tconsole.log(\n\t\t\tstyleText(\"dim\", path.dirname(row.file) + \"/\") +\n\t\t\t\tstyleText(color, name) +\n\t\t\t\t\" \".repeat(file - row.file.length + 2) +\n\t\t\t\tstyleText(\"bold\", row.size.padStart(size)) +\n\t\t\t\t(row.gzip ? styleText(\"dim\", ` │ gzip: ${row.gzip.padStart(gzip)}`) : \"\"),\n\t\t);\n\t}\n\tconsole.log(`\\n${styleText(\"green\", \"✓\")} built in ${styleText(\"bold\", `${Math.round(ms)} ms`)}`);\n};\n",
6
+ "// Vercel output with the Build Output API, ported from @domcojs/vercel.\n// https://vercel.com/docs/build-output-api/v3\nimport { version } from \"../package.json\" with { type: \"json\" };\n// Bun has no recursive copy or delete of its own\nimport fs from \"node:fs/promises\";\nimport { isIP } from \"node:net\";\nimport path from \"node:path\";\nimport { styleText } from \"node:util\";\n\n/** https://vercel.com/docs/build-output-api/v3/primitives#serverless-function-configuration */\ntype FunctionConfig = {\n\t/** The file the function starts from. */\n\thandler: string;\n\t/** @default \"bun1.x\" */\n\truntime: \"bun1.x\" | (string & {});\n\t/** Memory in MB. */\n\tmemory?: number;\n\t/** Longest run time in seconds. */\n\tmaxDuration?: number;\n\t/** Environment variables, added to the project's. */\n\tenvironment?: Record<string, string>[];\n\t/** [Regions](https://vercel.com/docs/regions) the function is deployed to. */\n\tregions?: string[];\n\tsupportsWrapper?: boolean;\n\t/** @default true */\n\tsupportsResponseStreaming?: boolean;\n};\n\n/** https://vercel.com/docs/build-output-api/v3/primitives#prerender-configuration-file */\ntype PrerenderConfig = {\n\t/** Seconds before the cached response is made again, `false` for never. */\n\texpiration: number | false;\n\t/** Responses in the same group are made again at the same time. */\n\tgroup?: number;\n\t/** Value of the `__prerender_bypass` cookie that skips the cache, for Draft Mode. */\n\tbypassToken?: string;\n\t/** Fallback file, relative to the configuration file. */\n\tfallback?: string;\n\t/** Query parameters cached separately. An empty list ignores the query, `undefined` caches every value. */\n\tallowQuery?: string[];\n\t/** Passes the query string to the function. */\n\tpassQuery?: boolean;\n};\n\n/** https://vercel.com/docs/build-output-api/v3/configuration#images */\ntype ImagesConfig = {\n\t/** Image widths that can be asked for. */\n\tsizes: number[];\n\t/** Other domains whose images can be optimized. */\n\tdomains: string[];\n\t/** Like `domains`, with patterns. */\n\tremotePatterns?: {\n\t\tprotocol?: \"http\" | \"https\";\n\t\thostname: string;\n\t\tport?: string;\n\t\tpathname?: string;\n\t}[];\n\t/** Seconds to cache the optimized images. */\n\tminimumCacheTTL?: number;\n\tformats?: (\"image/avif\" | \"image/webp\")[];\n\tdangerouslyAllowSVG?: boolean;\n\tcontentSecurityPolicy?: string;\n\tcontentDispositionType?: string;\n};\n\n/** https://vercel.com/docs/build-output-api/v3/configuration#routes */\nexport type Route = {\n\tsrc?: string;\n\tdest?: string;\n\theaders?: Record<string, string>;\n\tmethods?: string[];\n\tstatus?: number;\n\thandle?: \"filesystem\";\n};\n\nexport type VercelOptions = {\n\t/**\n\t * The function's configuration, on top of\n\t * `{ handler: \"main.js\", runtime: \"bun1.x\", supportsResponseStreaming: true }`.\n\t */\n\tconfig?: Partial<Omit<FunctionConfig, \"handler\">>;\n\t/**\n\t * [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration):\n\t * caches the function's responses, for example `{ expiration: 60 }` for a\n\t * minute. Don't send ETags from the app with it: a 304 for a stale response\n\t * never refreshes the cache.\n\t */\n\tisr?: Omit<PrerenderConfig, \"fallback\" | \"group\">;\n\t/** Turns on image optimization at `/_vercel/image?url=&w=&q=`. */\n\timages?: ImagesConfig;\n\t/**\n\t * - `true`: paths without a trailing slash redirect to the same path with one\n\t * - `false`: paths with a trailing slash redirect to the same path without\n\t * - `undefined`: no redirects\n\t */\n\ttrailingSlash?: boolean;\n};\n\n/** With ISR the client's path comes in this query parameter. See the routes in `vercel()`. */\nconst pathnameParam = \"__pathname\";\n\n/**\n * The request the client made. Vercel ends TLS at its edge and forwards plain\n * HTTP with `X-Forwarded-Proto`, which it always sets itself. With ISR it also\n * moves the path into the query.\n */\nconst request = (req: Request, isr?: boolean) => {\n\tconst url = new URL(req.url);\n\tconst proto = req.headers\n\t\t.get(\"x-forwarded-proto\")\n\t\t?.split(\",\", 1)[0]!\n\t\t.trim()\n\t\t.toLowerCase();\n\tconst forwarded =\n\t\t(proto === \"https\" || proto === \"http\") && url.protocol !== proto + \":\";\n\n\tif (!forwarded && !isr) return req;\n\tif (forwarded) url.protocol = proto!;\n\tif (isr) {\n\t\turl.pathname = \"/\" + (url.searchParams.get(pathnameParam) ?? \"\");\n\t\turl.searchParams.delete(pathnameParam);\n\t}\n\t// the method, headers, body and signal come from `req`\n\treturn new Request(url, req);\n};\n\n/**\n * Bun's server with `requestIP()` returning the client's address, so\n * `server.requestIP(req)` in the app is right on Vercel too. Vercel sets\n * `X-Forwarded-For` at its edge and overwrites what the client sent; the last\n * address is used in case anything was added after the client's.\n * https://vercel.com/docs/headers/request-headers#x-forwarded-for\n */\nconst edge = (req: Request, server?: object) => {\n\tconst address = req.headers.get(\"x-forwarded-for\")?.split(\",\").at(-1)?.trim();\n\tconst family = address ? isIP(address) : 0;\n\tconst requestIP = () =>\n\t\tfamily ? { address, family: family === 6 ? \"IPv6\" : \"IPv4\", port: 0 } : null;\n\n\tif (!server) return { requestIP };\n\treturn new Proxy(server, {\n\t\tget(target, key) {\n\t\t\tif (key === \"requestIP\") return requestIP;\n\t\t\tconst value = Reflect.get(target, key);\n\t\t\t// Bun's methods need the real server as `this`\n\t\t\treturn typeof value === \"function\" ? value.bind(target) : value;\n\t\t},\n\t});\n};\n\n/**\n * The app as Vercel's function runs it: `fetch` gets the request the client\n * made and a server that knows the client's IP. The app's other options stay\n * as they are.\n *\n * @internal used by the function `vercel()` writes, not by apps\n */\nexport const onVercel = (\n\tapp: Bun.Serve.Options<any>,\n\toptions: { isr?: boolean } = {},\n) => {\n\tconst fetch = app.fetch as\n\t\t| ((req: Request, server: unknown) => Response | Promise<Response>)\n\t\t| undefined;\n\tif (!fetch) return app;\n\treturn {\n\t\t...app,\n\t\tfetch: (req: Request, server?: object) =>\n\t\t\t// called on `app`, as Bun does: a framework's `fetch` can use `this`\n\t\t\tfetch.call(app, request(req, options.isr), edge(req, server)),\n\t};\n};\n\n/** `vercel()` without the development check. Documented in `index.ts`. */\nexport const vercel = async (options: VercelOptions = {}) => {\n\tconst out = path.join(\".vercel\", \"output\");\n\tconst fn = path.join(out, \"functions\", \"fn.func\");\n\tconst { isr } = options;\n\n\tif (!(await Bun.file(\"dist/server/app.js\").exists()))\n\t\tthrow new Error(\"crumpet: `vercel()` needs `dist/`. Call `build()` first, without `development`.\");\n\n\tconst config: FunctionConfig = {\n\t\thandler: \"main.js\",\n\t\truntime: \"bun1.x\",\n\t\tsupportsResponseStreaming: true,\n\t\t...options.config,\n\t};\n\n\tconst routes: Route[] = [];\n\tif (options.trailingSlash === true) {\n\t\troutes.push(\n\t\t\t// pages get a slash, files lose it\n\t\t\t{ src: \"^/((?:[^/]+/)*[^/\\\\.]+)$\", headers: { Location: \"/$1/\" }, status: 308 },\n\t\t\t{ src: \"^/((?:[^/]+/)*[^/]+\\\\.\\\\w+)/$\", headers: { Location: \"/$1\" }, status: 308 },\n\t\t);\n\t} else if (options.trailingSlash === false) {\n\t\troutes.push({ src: \"^/(.*)\\\\/$\", headers: { Location: \"/$1\" }, status: 308 });\n\t}\n\troutes.push(\n\t\t{\n\t\t\tsrc: \"/_immutable/.+\",\n\t\t\theaders: { \"Cache-Control\": \"public, immutable, max-age=31536000\" },\n\t\t},\n\t\t// static files first\n\t\t{ methods: [\"GET\"], handle: \"filesystem\" },\n\t\t// Everything else goes to the function. Vercel passes it the client's\n\t\t// path and query. ISR caches by the function's own path and `allowQuery`,\n\t\t// so there the client's path has to be in the query, and the function\n\t\t// moves it back.\n\t\t{ src: \"^/(.*)$\", dest: isr ? `/fn?${pathnameParam}=$1` : \"/fn\" },\n\t);\n\n\tconst json = (file: string, value: unknown) =>\n\t\tBun.write(path.join(out, file), JSON.stringify(value, null, \"\\t\"));\n\n\tawait fs.rm(out, { recursive: true, force: true });\n\tawait Promise.all([\n\t\tfs.cp(\"dist/client\", path.join(out, \"static\"), { recursive: true }),\n\t\tfs.cp(\"dist/server\", fn, { recursive: true }),\n\t\t// `vercel` is the bundle's second export: `onVercel` around the app\n\t\tBun.write(\n\t\t\tpath.join(fn, \"main.js\"),\n\t\t\t`import { vercel } from \"./app.js\";\\n\\nexport default vercel(${JSON.stringify({ isr: Boolean(isr) })});\\n`,\n\t\t),\n\t\tjson(\"config.json\", {\n\t\t\tversion: 3,\n\t\t\tframework: { slug: \"crumpet\", version },\n\t\t\troutes,\n\t\t\t...(options.images && { images: options.images }),\n\t\t}),\n\t\tjson(\"functions/fn.func/.vc-config.json\", config),\n\t\tjson(\"functions/fn.func/package.json\", { type: \"module\" }),\n\t\tisr &&\n\t\t\tjson(\"functions/fn.prerender-config.json\", {\n\t\t\t\tgroup: 1,\n\t\t\t\tpassQuery: true,\n\t\t\t\t...isr,\n\t\t\t\t// without the path every page would be cached as one\n\t\t\t\tallowQuery: [...(isr.allowQuery ?? []), pathnameParam],\n\t\t\t} satisfies PrerenderConfig),\n\t]);\n\n\tconsole.log(\n\t\t`${styleText(\"green\", \"✓\")} wrote ${styleText(\"bold\", out + path.sep)} ${styleText(\"dim\", `for ${config.runtime}`)}`,\n\t);\n};\n"
7
+ ],
8
+ "mappings": ";AAGA,2BACA,oBAGA,oBAAS,2BCHT,2BACA,eAAS,YACT,oBACA,oBAAS,aA4FT,IAAM,EAAgB,aAOhB,EAAU,CAAC,EAAc,IAAkB,CAChD,IAAM,EAAM,IAAI,IAAI,EAAI,GAAG,EACrB,EAAQ,EAAI,QAChB,IAAI,mBAAmB,GACtB,MAAM,IAAK,CAAC,EAAE,GACf,KAAK,EACL,YAAY,EACR,GACJ,IAAU,SAAW,IAAU,SAAW,EAAI,WA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O,iBAAY,EAAI,KAAK,SAAS,CAAI,GAAG,EAAI,GACxE,EAED,QAAQ,IAAI;AAAA,EAAK,EAAU,QAAS,QAAG,cAAc,EAAU,OAAQ,GAAG,KAAK,MAAM,CAAE,MAAM,GAAG",
9
+ "debugId": "42590C36482933DF64756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,98 @@
1
+ /** https://vercel.com/docs/build-output-api/v3/primitives#serverless-function-configuration */
2
+ type FunctionConfig = {
3
+ /** The file the function starts from. */
4
+ handler: string;
5
+ /** @default "bun1.x" */
6
+ runtime: "bun1.x" | (string & {});
7
+ /** Memory in MB. */
8
+ memory?: number;
9
+ /** Longest run time in seconds. */
10
+ maxDuration?: number;
11
+ /** Environment variables, added to the project's. */
12
+ environment?: Record<string, string>[];
13
+ /** [Regions](https://vercel.com/docs/regions) the function is deployed to. */
14
+ regions?: string[];
15
+ supportsWrapper?: boolean;
16
+ /** @default true */
17
+ supportsResponseStreaming?: boolean;
18
+ };
19
+ /** https://vercel.com/docs/build-output-api/v3/primitives#prerender-configuration-file */
20
+ type PrerenderConfig = {
21
+ /** Seconds before the cached response is made again, `false` for never. */
22
+ expiration: number | false;
23
+ /** Responses in the same group are made again at the same time. */
24
+ group?: number;
25
+ /** Value of the `__prerender_bypass` cookie that skips the cache, for Draft Mode. */
26
+ bypassToken?: string;
27
+ /** Fallback file, relative to the configuration file. */
28
+ fallback?: string;
29
+ /** Query parameters cached separately. An empty list ignores the query, `undefined` caches every value. */
30
+ allowQuery?: string[];
31
+ /** Passes the query string to the function. */
32
+ passQuery?: boolean;
33
+ };
34
+ /** https://vercel.com/docs/build-output-api/v3/configuration#images */
35
+ type ImagesConfig = {
36
+ /** Image widths that can be asked for. */
37
+ sizes: number[];
38
+ /** Other domains whose images can be optimized. */
39
+ domains: string[];
40
+ /** Like `domains`, with patterns. */
41
+ remotePatterns?: {
42
+ protocol?: "http" | "https";
43
+ hostname: string;
44
+ port?: string;
45
+ pathname?: string;
46
+ }[];
47
+ /** Seconds to cache the optimized images. */
48
+ minimumCacheTTL?: number;
49
+ formats?: ("image/avif" | "image/webp")[];
50
+ dangerouslyAllowSVG?: boolean;
51
+ contentSecurityPolicy?: string;
52
+ contentDispositionType?: string;
53
+ };
54
+ /** https://vercel.com/docs/build-output-api/v3/configuration#routes */
55
+ export type Route = {
56
+ src?: string;
57
+ dest?: string;
58
+ headers?: Record<string, string>;
59
+ methods?: string[];
60
+ status?: number;
61
+ handle?: "filesystem";
62
+ };
63
+ export type VercelOptions = {
64
+ /**
65
+ * The function's configuration, on top of
66
+ * `{ handler: "main.js", runtime: "bun1.x", supportsResponseStreaming: true }`.
67
+ */
68
+ config?: Partial<Omit<FunctionConfig, "handler">>;
69
+ /**
70
+ * [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration):
71
+ * caches the function's responses, for example `{ expiration: 60 }` for a
72
+ * minute. Don't send ETags from the app with it: a 304 for a stale response
73
+ * never refreshes the cache.
74
+ */
75
+ isr?: Omit<PrerenderConfig, "fallback" | "group">;
76
+ /** Turns on image optimization at `/_vercel/image?url=&w=&q=`. */
77
+ images?: ImagesConfig;
78
+ /**
79
+ * - `true`: paths without a trailing slash redirect to the same path with one
80
+ * - `false`: paths with a trailing slash redirect to the same path without
81
+ * - `undefined`: no redirects
82
+ */
83
+ trailingSlash?: boolean;
84
+ };
85
+ /**
86
+ * The app as Vercel's function runs it: `fetch` gets the request the client
87
+ * made and a server that knows the client's IP. The app's other options stay
88
+ * as they are.
89
+ *
90
+ * @internal used by the function `vercel()` writes, not by apps
91
+ */
92
+ export declare const onVercel: (app: Bun.Serve.Options<any>, options?: {
93
+ isr?: boolean;
94
+ }) => Bun.Serve.Options<any, string>;
95
+ /** `vercel()` without the development check. Documented in `index.ts`. */
96
+ export declare const vercel: (options?: VercelOptions) => Promise<void>;
97
+ export {};
98
+ //# sourceMappingURL=vercel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vercel.d.ts","sourceRoot":"","sources":["../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ub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "crumpet",
3
+ "description": "A full-stack toolchain for Bun",
4
+ "version": "0.0.3",
5
+ "author": {
6
+ "name": "Ross Robino",
7
+ "url": "https://robino.dev"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/rossrobino/crumpet.git"
12
+ },
13
+ "homepage": "https://github.com/rossrobino/crumpet#readme",
14
+ "bugs": "https://github.com/rossrobino/crumpet/issues",
15
+ "license": "MIT",
16
+ "keywords": [
17
+ "bun",
18
+ "full-stack",
19
+ "ssr"
20
+ ],
21
+ "type": "module",
22
+ "engines": {
23
+ "bun": ">=1.4.5"
24
+ },
25
+ "sideEffects": false,
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "src",
37
+ "!src/**/*.test.ts"
38
+ ],
39
+ "scripts": {
40
+ "build": "bun build.ts",
41
+ "check": "bun check",
42
+ "test": "bun test",
43
+ "prepublishOnly": "bun run check && bun test && bun run build"
44
+ },
45
+ "devDependencies": {
46
+ "@robino/tsconfig": "^3.0.0",
47
+ "@types/bun": "^1.4.4",
48
+ "typescript": "^7.0.2"
49
+ }
50
+ }
package/src/index.ts ADDED
@@ -0,0 +1,506 @@
1
+ // crumpet: `build()`, `client` and the dev and production servers, on top of Bun.
2
+ import type { BuildConfig, BuildOutput, Server } from "bun";
3
+ // Bun has no file watcher, recursive delete or rename of its own, and `path` is plain string work
4
+ import fs from "node:fs/promises";
5
+ import path from "node:path";
6
+ // Bun implements Node's styleText, which leaves colors out when the output
7
+ // isn't a terminal or NO_COLOR is set, and adds them with FORCE_COLOR
8
+ import { styleText } from "node:util";
9
+
10
+ import { type VercelOptions, vercel as output } from "./vercel.js";
11
+
12
+ export { onVercel, type VercelOptions } from "./vercel.js";
13
+
14
+ /**
15
+ * The default export of the app's module: `Bun.serve` options, exactly what
16
+ * Bun serves by itself. crumpet adds its routes and sets `development`.
17
+ */
18
+ type App = Bun.Serve.Options<any>;
19
+
20
+ /** The app's own Bun routes. A framework instance can have an unrelated `routes` array. */
21
+ const appRoutes = (app: App) => (Array.isArray(app.routes) ? {} : app.routes);
22
+
23
+ /** Tags for one client entry point, by kind. */
24
+ type Entry = { scripts: string[]; styles: string[]; preloads: string[] };
25
+ type Manifest = Record<string, Entry>;
26
+
27
+ /** What `build()` writes to `dist/server/manifest.json`. */
28
+ type Built = {
29
+ /** Tags for each client entry point. */
30
+ entries: Manifest;
31
+ /** Every file in `dist/client/`, relative to it. */
32
+ files: string[];
33
+ };
34
+
35
+ /** Defined when `build()` bundles the server. */
36
+ declare const __CRUMPET_BUNDLED__: true;
37
+ const bundled = typeof __CRUMPET_BUNDLED__ !== "undefined";
38
+
39
+ // Read when the bundle starts, next to it, so the client and server builds
40
+ // don't wait on each other. Top-level await: modules that import crumpet run
41
+ // after it, so `client.head()` works even at their top level.
42
+ const built: Built | undefined = bundled
43
+ ? await Bun.file(new URL("./manifest.json", import.meta.url)).json()
44
+ : undefined;
45
+
46
+ let manifest: Manifest = built?.entries ?? {};
47
+
48
+ /** `client.head()` results, by entry list. Cleared when the manifest changes. */
49
+ const heads = new Map<string, string>();
50
+
51
+ /** Set by the dev server: the script that reloads pages, added by `client.head()`. */
52
+ let devScript = "";
53
+
54
+ const reloadPath = "/_crumpet/reload";
55
+ const filePath = "/_crumpet/file/";
56
+
57
+ /** Files `client.url()` has returned in dev: the only ones the dev server sends. */
58
+ const served = new Set<string>();
59
+
60
+ export const client = {
61
+ /**
62
+ * @param entries client entry points as passed to `build()`, all of them by default
63
+ * @returns the stylesheet, modulepreload and module script tags they need
64
+ */
65
+ head(...entries: string[]) {
66
+ const key = entries.join("\n");
67
+ let html = heads.get(key);
68
+ if (html !== undefined) return html;
69
+
70
+ const seen = new Set<string>();
71
+ const tag = (url: string, markup: string) => {
72
+ if (!seen.has(url)) html += markup;
73
+ seen.add(url);
74
+ };
75
+ html = "";
76
+ for (const name of entries.length ? entries : Object.keys(manifest)) {
77
+ // the manifest's names are normalized: `./src/main.ts` is `src/main.ts`
78
+ const entry = manifest[path.normalize(name)];
79
+ if (!entry) throw new Error(`crumpet: "${name}" is not a client entry point.`);
80
+ for (const url of entry.styles) tag(url, `<link rel="stylesheet" href="${url}">`);
81
+ for (const url of entry.preloads) tag(url, `<link rel="modulepreload" href="${url}">`);
82
+ for (const url of entry.scripts) tag(url, `<script type="module" src="${url}"></script>`);
83
+ }
84
+ html += devScript;
85
+ heads.set(key, html);
86
+ return html;
87
+ },
88
+
89
+ /**
90
+ * @param file a file import, such as `import font from "./font.woff2"`
91
+ * @returns its URL: hashed in the build, served by the dev server in dev
92
+ */
93
+ url(file: string) {
94
+ if (bundled || !path.isAbsolute(file)) return file;
95
+ served.add(file);
96
+ return filePath + path.relative(process.cwd(), file);
97
+ },
98
+ };
99
+
100
+ /** The app's client options with crumpet's own on top. */
101
+ const clientConfig = (client: BuildConfig): BuildConfig => ({
102
+ ...client,
103
+ naming: {
104
+ entry: "_immutable/[name]-[hash].[ext]",
105
+ chunk: "_immutable/[name]-[hash].[ext]",
106
+ asset: "_immutable/[name]-[hash].[ext]",
107
+ },
108
+ publicPath: "/",
109
+ splitting: true,
110
+ metafile: true,
111
+ });
112
+
113
+ /** `./_immutable/a.js` or `_immutable/a.js` to `/_immutable/a.js` */
114
+ const url = (file: string) => "/" + file.replace(/^\.?\//, "");
115
+
116
+ /** Reads which output files each entry point needs from Bun's metafile. */
117
+ const toManifest = (result: BuildOutput): Manifest => {
118
+ const outputs = new Map(
119
+ Object.entries(
120
+ result.metafile!.outputs as Record<
121
+ string,
122
+ {
123
+ entryPoint?: string;
124
+ cssBundle?: string;
125
+ imports?: { path: string; kind: string }[];
126
+ }
127
+ >,
128
+ ).map(([file, out]) => [url(file), out]),
129
+ );
130
+
131
+ /** Chunks an output imports statically, all the way down. */
132
+ const chunks = (file: string, found = new Set<string>()) => {
133
+ for (const i of outputs.get(file)?.imports ?? []) {
134
+ const chunk = url(i.path);
135
+ if (i.kind === "import-statement" && outputs.has(chunk) && !found.has(chunk)) {
136
+ found.add(chunk);
137
+ chunks(chunk, found);
138
+ }
139
+ }
140
+ return found;
141
+ };
142
+
143
+ const m: Manifest = {};
144
+ for (const [file, out] of outputs) {
145
+ if (!out.entryPoint) continue;
146
+ const css = file.endsWith(".css");
147
+ // the CSS a script imports is an output with the script's entry point:
148
+ // it's that entry's `cssBundle`, not an entry of its own
149
+ if (css && !out.entryPoint.endsWith(".css")) continue;
150
+ m[path.normalize(out.entryPoint)] = css
151
+ ? { scripts: [], styles: [file], preloads: [] }
152
+ : {
153
+ scripts: [file],
154
+ styles: out.cssBundle ? [url(out.cssBundle)] : [],
155
+ preloads: [...chunks(file)],
156
+ };
157
+ }
158
+ return m;
159
+ };
160
+
161
+ export type BuildOptions = {
162
+ /**
163
+ * Named after `Bun.serve`'s option, which it also sets.
164
+ *
165
+ * - `true`: serves the app with the client built in memory and reloads
166
+ * pages on changes. Run under `bun --watch`, which restarts it when server
167
+ * code changes.
168
+ * - `false`: writes `dist/` and exits.
169
+ *
170
+ * @default false
171
+ */
172
+ development?: boolean;
173
+ /** The app's module, such as `"src/server/app.tsx"`, whose default export is `Bun.serve` options. */
174
+ server: string;
175
+ /**
176
+ * `Bun.build` options for the client. `entrypoints` are the client entry
177
+ * points, such as `["src/client/main.ts", "src/client/main.css"]`. crumpet
178
+ * sets `outdir`, `naming`, `publicPath`, `splitting` and `metafile` itself.
179
+ */
180
+ client: BuildConfig;
181
+ };
182
+
183
+ /**
184
+ * Serves the app in development, or builds it. Called from the app's
185
+ * `build.ts`:
186
+ *
187
+ * ```ts
188
+ * const development = process.execArgv.includes("--watch");
189
+ * await build({ development, server: "src/server/app.tsx", client: { entrypoints: ["src/client/main.ts"] } });
190
+ * ```
191
+ *
192
+ * @returns the dev server in development, nothing after a build
193
+ */
194
+ export const build = async (options: BuildOptions) => {
195
+ development = Boolean(options.development);
196
+ if (development) return dev(options);
197
+ await bundle(options);
198
+ };
199
+
200
+ /** Set by `build()`: in development there's no `dist/` for `vercel()` to use. */
201
+ let development = false;
202
+
203
+ /**
204
+ * Writes `.vercel/output/` from `dist/`, Vercel's Build Output API. Call it
205
+ * after `build()`. It does nothing in development, so it needs no condition:
206
+ *
207
+ * ```ts
208
+ * await build({ development, server, client });
209
+ * await vercel({ isr: { expiration: 60 } });
210
+ * ```
211
+ *
212
+ * - `static/`: `dist/client/`, served by Vercel's CDN
213
+ * - `functions/fn.func/`: `dist/server/` and a `main.js` that exports the app
214
+ * for Vercel's Bun runtime
215
+ * - `config.json`: the routes
216
+ */
217
+ export const vercel = async (options?: VercelOptions) => {
218
+ if (!development) await output(options);
219
+ };
220
+
221
+ /** Serves the app with a client build in memory. */
222
+ const dev = async (options: BuildOptions) => {
223
+ const start = performance.now();
224
+ if (!process.execArgv.includes("--watch")) {
225
+ console.warn(
226
+ "crumpet: run the dev server with `bun --watch`, or server changes won't restart it.",
227
+ );
228
+ }
229
+ // Reloads the page when the dev server sends a message, and once it's back
230
+ // after a restart: a closed socket retries every 100 ms, and the next one
231
+ // that opens reloads. Set here so the production bundle leaves it out.
232
+ devScript = `<script type="module">const c=(r)=>{const w=new WebSocket(location.origin.replace("http","ws")+"${reloadPath}");w.onopen=()=>r&&location.reload();w.onmessage=()=>location.reload();w.onclose=()=>setTimeout(c,100,1)};c()</script>`;
233
+
234
+ // the app and the first client build, at the same time; the app is imported
235
+ // here so it's in this process's module graph and `bun --watch` restarts on its changes
236
+ // `throw: false`: a build that fails is logged, and the last one stays up
237
+ const config: BuildConfig = { sourcemap: "inline", ...clientConfig(options.client), throw: false };
238
+ const [{ default: app }, first] = await Promise.all([
239
+ import(path.resolve(options.server)) as Promise<{ default: App }>,
240
+ Bun.build(config),
241
+ ]);
242
+
243
+ /** `ws.data` of the reload sockets, to tell them from the app's own. */
244
+ const reload = {};
245
+
246
+ const fixed = {
247
+ [reloadPath]: (req: Request, server: Server<unknown>) =>
248
+ server.upgrade(req, { data: reload }) ? undefined : new Response(null, { status: 400 }),
249
+ // only files `client.url()` has returned, never the rest of the project
250
+ [filePath + "*"]: (req: Request) => {
251
+ const file = path.resolve(
252
+ decodeURIComponent(new URL(req.url).pathname.slice(filePath.length)),
253
+ );
254
+ return served.has(file)
255
+ ? new Response(Bun.file(file), { headers: { "cache-control": "no-cache" } })
256
+ : new Response(null, { status: 404 });
257
+ },
258
+ };
259
+
260
+ // Client files aren't in the server's module graph, so `bun --watch` doesn't
261
+ // see them. The entry points' folders are watched with their subfolders, and
262
+ // so is the folder of every other file a build read, wherever it is.
263
+ const roots = [...new Set(config.entrypoints.map((e) => path.resolve(path.dirname(e))))];
264
+ const watched = new Set<string>();
265
+ const watch = (dir: string, recursive = false) => {
266
+ if (
267
+ watched.has(dir) ||
268
+ dir.split(path.sep).includes("node_modules") ||
269
+ (!recursive && roots.some((root) => dir.startsWith(root + path.sep)))
270
+ )
271
+ return;
272
+ watched.add(dir);
273
+ (async () => {
274
+ for await (const _ of fs.watch(dir, { recursive })) void changed();
275
+ })().catch(() => watched.delete(dir)); // not a folder: a plugin's virtual file
276
+ };
277
+
278
+ /** The client build as routes, served from memory without caching. */
279
+ const clientRoutes = (result: BuildOutput) => {
280
+ manifest = toManifest(result);
281
+ heads.clear();
282
+ for (const input in result.metafile!.inputs) watch(path.resolve(path.dirname(input)));
283
+ return Object.fromEntries(
284
+ result.outputs.map((o) => [
285
+ url(o.path),
286
+ new Response(o, { headers: { "cache-control": "no-cache" } }),
287
+ ]),
288
+ );
289
+ };
290
+
291
+ // Bun has one `websocket` handler per server: reload sockets are handled
292
+ // here, the app's sockets by the app's handler
293
+ const theirs = app.websocket;
294
+ const websocket: Bun.WebSocketHandler<any> = {
295
+ ...theirs,
296
+ open: (ws) => (ws.data === reload ? void ws.subscribe(reloadPath) : theirs?.open?.(ws)),
297
+ message: (ws, message) => (ws.data === reload ? undefined : theirs?.message?.(ws, message)),
298
+ close: (ws, code, reason) => (ws.data === reload ? undefined : theirs?.close?.(ws, code, reason)),
299
+ drain: (ws) => (ws.data === reload ? undefined : theirs?.drain?.(ws)),
300
+ };
301
+
302
+ const routes = (client: Record<string, Response>) => ({ ...fixed, ...client, ...appRoutes(app) });
303
+
304
+ if (!first.success) console.error(first.logs);
305
+ for (const root of roots) watch(root, true);
306
+ const server = Bun.serve({
307
+ // not the whole network, unless the app says so
308
+ hostname: "localhost",
309
+ ...app,
310
+ development: true,
311
+ routes: routes(first.success ? clientRoutes(first) : {}),
312
+ websocket,
313
+ } as App);
314
+
315
+ // One save can send several events, and a change can come in during a
316
+ // rebuild: wait briefly, run one rebuild at a time, then one more if
317
+ // anything changed meanwhile, and reload the pages once it's done.
318
+ let building = false;
319
+ let again = false;
320
+ const changed = async () => {
321
+ if (building) {
322
+ again = true;
323
+ return;
324
+ }
325
+ building = true;
326
+ const started = performance.now();
327
+ // a save is often two events (write, then rename); wait for the rest of it
328
+ await Bun.sleep(10);
329
+ let ok = false;
330
+ do {
331
+ again = false;
332
+ const result = await Bun.build(config);
333
+ ok = result.success;
334
+ if (!ok) console.error(result.logs);
335
+ else
336
+ server.reload({
337
+ ...app,
338
+ development: true,
339
+ routes: routes(clientRoutes(result)),
340
+ websocket,
341
+ } as App);
342
+ } while (again);
343
+ building = false;
344
+ if (ok) {
345
+ console.log(styleText("dim", `client rebuilt in ${Math.round(performance.now() - started)} ms`));
346
+ }
347
+ server.publish(reloadPath, "reload");
348
+ };
349
+
350
+ console.log(
351
+ `\n${styleText(["bold", "green"], "crumpet dev")} ${styleText("cyan", server.url.href)} ${styleText("dim", `ready in ${Math.round(performance.now() - start)} ms`)}\n`,
352
+ );
353
+ return server;
354
+ };
355
+
356
+ /**
357
+ * The production server: the default export of the bundle `build()` writes.
358
+ * Bun serves a module's default export when it has `fetch`.
359
+ *
360
+ * @internal used by the generated entry, not by apps
361
+ */
362
+ export const production = (app: App) => {
363
+ const dir = Bun.fileURLToPath(new URL("../client/", import.meta.url));
364
+ return {
365
+ ...app,
366
+ // Bun.serve runs in development mode unless NODE_ENV is production
367
+ development: false,
368
+ routes: {
369
+ ...Object.fromEntries(
370
+ built!.files.map((file) => [
371
+ "/" + file,
372
+ new Response(Bun.file(path.join(dir, file)), {
373
+ headers: file.startsWith("_immutable/")
374
+ ? { "cache-control": "public, immutable, max-age=31536000" }
375
+ : {},
376
+ }),
377
+ ]),
378
+ ),
379
+ ...appRoutes(app),
380
+ },
381
+ } as App;
382
+ };
383
+
384
+ /**
385
+ * Builds `dist/client/` (hashed files under `_immutable/`) and bundles the app
386
+ * into `dist/server/app.js`, whose default export Bun serves by itself:
387
+ * `bun dist/server/app.js`. The client and the server build at the same time.
388
+ */
389
+ const bundle = async (options: BuildOptions) => {
390
+ const start = performance.now();
391
+ await fs.rm("dist", { recursive: true, force: true });
392
+
393
+ // only exists in memory, through `Bun.build`'s `files`
394
+ const entry = path.resolve(".crumpet-entry.ts");
395
+ const [clientResult, serverResult] = await Promise.all([
396
+ Bun.build({
397
+ minify: true,
398
+ ...clientConfig(options.client),
399
+ outdir: "dist/client",
400
+ // a build that fails throws, with Bun's own errors
401
+ throw: true,
402
+ }),
403
+ Bun.build({
404
+ entrypoints: [entry],
405
+ files: {
406
+ [entry]: `import app from ${JSON.stringify(path.resolve(options.server))};
407
+ import { onVercel, production } from "crumpet";
408
+
409
+ export default production(app);
410
+ // for the function \`vercel()\` writes
411
+ export const vercel = (options) => onVercel(app, options);
412
+ `,
413
+ },
414
+ target: "bun",
415
+ // the bundle goes to `dist/server/`, and files it imports, such as
416
+ // fonts, straight to `dist/client/_immutable/` with the client's files
417
+ outdir: "dist/client",
418
+ naming: {
419
+ entry: "../server/app.js",
420
+ asset: "_immutable/[name]-[hash].[ext]",
421
+ },
422
+ publicPath: "/",
423
+ define: { __CRUMPET_BUNDLED__: "true" },
424
+ // folds `bundled` and drops dev-only code; names and lines stay readable
425
+ minify: { syntax: true },
426
+ }),
427
+ ]);
428
+ const client = path.resolve("dist/client");
429
+ // a CSS entry point also writes an empty JavaScript file
430
+ const empty = clientResult.outputs.filter((o) => o.size === 0);
431
+ const files = [...clientResult.outputs, ...serverResult.outputs]
432
+ .filter((o) => o.size > 0 && o.path.startsWith(client + path.sep))
433
+ .map((o) => path.relative(client, o.path));
434
+
435
+ await Promise.all([
436
+ ...empty.map((o) => Bun.file(o.path).delete()),
437
+ Bun.write(
438
+ "dist/server/manifest.json",
439
+ JSON.stringify({
440
+ entries: toManifest(clientResult),
441
+ files: [...new Set(files)],
442
+ } satisfies Built),
443
+ ),
444
+ ]);
445
+
446
+ const ms = performance.now() - start;
447
+ await report(
448
+ [...new Set([...clientResult.outputs, ...serverResult.outputs])]
449
+ .filter((o) => o.size > 0)
450
+ .map((o) => path.relative(process.cwd(), o.path)),
451
+ ms,
452
+ );
453
+ };
454
+
455
+ const kB = (bytes: number) => `${(bytes / 1000).toFixed(2)} kB`;
456
+
457
+ /** Text files, which servers send compressed. Fonts and images already are. */
458
+ const compressible = /\.(m?js|css|html|json|svg|txt|xml)$/;
459
+
460
+ /** Sorts like Vite: other files, then CSS, then JavaScript, the server last; by size within each. */
461
+ const order = (file: string) =>
462
+ file.startsWith("dist/server/") ? 3 : file.endsWith(".js") ? 2 : file.endsWith(".css") ? 1 : 0;
463
+
464
+ /**
465
+ * Prints each output file with its size, and its gzip size if it's text, then
466
+ * the build time:
467
+ *
468
+ * ```txt
469
+ * dist/client/_immutable/main-vz4hds88.css 26.80 kB │ gzip: 20.13 kB
470
+ * dist/server/app.js 135.06 kB │ gzip: 29.86 kB
471
+ *
472
+ * ✓ built in 24 ms
473
+ * ```
474
+ */
475
+ const report = async (files: string[], ms: number) => {
476
+ const rows = (
477
+ await Promise.all(
478
+ files.map(async (file) => {
479
+ const bytes = await Bun.file(file).bytes();
480
+ return {
481
+ file,
482
+ size: kB(bytes.length),
483
+ bytes: bytes.length,
484
+ gzip: compressible.test(file) ? kB(Bun.gzipSync(bytes).length) : "",
485
+ };
486
+ }),
487
+ )
488
+ ).sort((a, b) => order(a.file) - order(b.file) || a.bytes - b.bytes);
489
+
490
+ const width = (key: "file" | "size" | "gzip") => Math.max(...rows.map((r) => r[key].length));
491
+ const [file, size, gzip] = [width("file"), width("size"), width("gzip")];
492
+
493
+ console.log();
494
+ for (const row of rows) {
495
+ const name = path.basename(row.file);
496
+ const color = name.endsWith(".js") ? "cyan" : name.endsWith(".css") ? "magenta" : "green";
497
+ console.log(
498
+ styleText("dim", path.dirname(row.file) + "/") +
499
+ styleText(color, name) +
500
+ " ".repeat(file - row.file.length + 2) +
501
+ styleText("bold", row.size.padStart(size)) +
502
+ (row.gzip ? styleText("dim", ` │ gzip: ${row.gzip.padStart(gzip)}`) : ""),
503
+ );
504
+ }
505
+ console.log(`\n${styleText("green", "✓")} built in ${styleText("bold", `${Math.round(ms)} ms`)}`);
506
+ };
package/src/vercel.ts ADDED
@@ -0,0 +1,247 @@
1
+ // Vercel output with the Build Output API, ported from @domcojs/vercel.
2
+ // https://vercel.com/docs/build-output-api/v3
3
+ import { version } from "../package.json" with { type: "json" };
4
+ // Bun has no recursive copy or delete of its own
5
+ import fs from "node:fs/promises";
6
+ import { isIP } from "node:net";
7
+ import path from "node:path";
8
+ import { styleText } from "node:util";
9
+
10
+ /** https://vercel.com/docs/build-output-api/v3/primitives#serverless-function-configuration */
11
+ type FunctionConfig = {
12
+ /** The file the function starts from. */
13
+ handler: string;
14
+ /** @default "bun1.x" */
15
+ runtime: "bun1.x" | (string & {});
16
+ /** Memory in MB. */
17
+ memory?: number;
18
+ /** Longest run time in seconds. */
19
+ maxDuration?: number;
20
+ /** Environment variables, added to the project's. */
21
+ environment?: Record<string, string>[];
22
+ /** [Regions](https://vercel.com/docs/regions) the function is deployed to. */
23
+ regions?: string[];
24
+ supportsWrapper?: boolean;
25
+ /** @default true */
26
+ supportsResponseStreaming?: boolean;
27
+ };
28
+
29
+ /** https://vercel.com/docs/build-output-api/v3/primitives#prerender-configuration-file */
30
+ type PrerenderConfig = {
31
+ /** Seconds before the cached response is made again, `false` for never. */
32
+ expiration: number | false;
33
+ /** Responses in the same group are made again at the same time. */
34
+ group?: number;
35
+ /** Value of the `__prerender_bypass` cookie that skips the cache, for Draft Mode. */
36
+ bypassToken?: string;
37
+ /** Fallback file, relative to the configuration file. */
38
+ fallback?: string;
39
+ /** Query parameters cached separately. An empty list ignores the query, `undefined` caches every value. */
40
+ allowQuery?: string[];
41
+ /** Passes the query string to the function. */
42
+ passQuery?: boolean;
43
+ };
44
+
45
+ /** https://vercel.com/docs/build-output-api/v3/configuration#images */
46
+ type ImagesConfig = {
47
+ /** Image widths that can be asked for. */
48
+ sizes: number[];
49
+ /** Other domains whose images can be optimized. */
50
+ domains: string[];
51
+ /** Like `domains`, with patterns. */
52
+ remotePatterns?: {
53
+ protocol?: "http" | "https";
54
+ hostname: string;
55
+ port?: string;
56
+ pathname?: string;
57
+ }[];
58
+ /** Seconds to cache the optimized images. */
59
+ minimumCacheTTL?: number;
60
+ formats?: ("image/avif" | "image/webp")[];
61
+ dangerouslyAllowSVG?: boolean;
62
+ contentSecurityPolicy?: string;
63
+ contentDispositionType?: string;
64
+ };
65
+
66
+ /** https://vercel.com/docs/build-output-api/v3/configuration#routes */
67
+ export type Route = {
68
+ src?: string;
69
+ dest?: string;
70
+ headers?: Record<string, string>;
71
+ methods?: string[];
72
+ status?: number;
73
+ handle?: "filesystem";
74
+ };
75
+
76
+ export type VercelOptions = {
77
+ /**
78
+ * The function's configuration, on top of
79
+ * `{ handler: "main.js", runtime: "bun1.x", supportsResponseStreaming: true }`.
80
+ */
81
+ config?: Partial<Omit<FunctionConfig, "handler">>;
82
+ /**
83
+ * [Incremental Static Regeneration](https://vercel.com/docs/incremental-static-regeneration):
84
+ * caches the function's responses, for example `{ expiration: 60 }` for a
85
+ * minute. Don't send ETags from the app with it: a 304 for a stale response
86
+ * never refreshes the cache.
87
+ */
88
+ isr?: Omit<PrerenderConfig, "fallback" | "group">;
89
+ /** Turns on image optimization at `/_vercel/image?url=&w=&q=`. */
90
+ images?: ImagesConfig;
91
+ /**
92
+ * - `true`: paths without a trailing slash redirect to the same path with one
93
+ * - `false`: paths with a trailing slash redirect to the same path without
94
+ * - `undefined`: no redirects
95
+ */
96
+ trailingSlash?: boolean;
97
+ };
98
+
99
+ /** With ISR the client's path comes in this query parameter. See the routes in `vercel()`. */
100
+ const pathnameParam = "__pathname";
101
+
102
+ /**
103
+ * The request the client made. Vercel ends TLS at its edge and forwards plain
104
+ * HTTP with `X-Forwarded-Proto`, which it always sets itself. With ISR it also
105
+ * moves the path into the query.
106
+ */
107
+ const request = (req: Request, isr?: boolean) => {
108
+ const url = new URL(req.url);
109
+ const proto = req.headers
110
+ .get("x-forwarded-proto")
111
+ ?.split(",", 1)[0]!
112
+ .trim()
113
+ .toLowerCase();
114
+ const forwarded =
115
+ (proto === "https" || proto === "http") && url.protocol !== proto + ":";
116
+
117
+ if (!forwarded && !isr) return req;
118
+ if (forwarded) url.protocol = proto!;
119
+ if (isr) {
120
+ url.pathname = "/" + (url.searchParams.get(pathnameParam) ?? "");
121
+ url.searchParams.delete(pathnameParam);
122
+ }
123
+ // the method, headers, body and signal come from `req`
124
+ return new Request(url, req);
125
+ };
126
+
127
+ /**
128
+ * Bun's server with `requestIP()` returning the client's address, so
129
+ * `server.requestIP(req)` in the app is right on Vercel too. Vercel sets
130
+ * `X-Forwarded-For` at its edge and overwrites what the client sent; the last
131
+ * address is used in case anything was added after the client's.
132
+ * https://vercel.com/docs/headers/request-headers#x-forwarded-for
133
+ */
134
+ const edge = (req: Request, server?: object) => {
135
+ const address = req.headers.get("x-forwarded-for")?.split(",").at(-1)?.trim();
136
+ const family = address ? isIP(address) : 0;
137
+ const requestIP = () =>
138
+ family ? { address, family: family === 6 ? "IPv6" : "IPv4", port: 0 } : null;
139
+
140
+ if (!server) return { requestIP };
141
+ return new Proxy(server, {
142
+ get(target, key) {
143
+ if (key === "requestIP") return requestIP;
144
+ const value = Reflect.get(target, key);
145
+ // Bun's methods need the real server as `this`
146
+ return typeof value === "function" ? value.bind(target) : value;
147
+ },
148
+ });
149
+ };
150
+
151
+ /**
152
+ * The app as Vercel's function runs it: `fetch` gets the request the client
153
+ * made and a server that knows the client's IP. The app's other options stay
154
+ * as they are.
155
+ *
156
+ * @internal used by the function `vercel()` writes, not by apps
157
+ */
158
+ export const onVercel = (
159
+ app: Bun.Serve.Options<any>,
160
+ options: { isr?: boolean } = {},
161
+ ) => {
162
+ const fetch = app.fetch as
163
+ | ((req: Request, server: unknown) => Response | Promise<Response>)
164
+ | undefined;
165
+ if (!fetch) return app;
166
+ return {
167
+ ...app,
168
+ fetch: (req: Request, server?: object) =>
169
+ // called on `app`, as Bun does: a framework's `fetch` can use `this`
170
+ fetch.call(app, request(req, options.isr), edge(req, server)),
171
+ };
172
+ };
173
+
174
+ /** `vercel()` without the development check. Documented in `index.ts`. */
175
+ export const vercel = async (options: VercelOptions = {}) => {
176
+ const out = path.join(".vercel", "output");
177
+ const fn = path.join(out, "functions", "fn.func");
178
+ const { isr } = options;
179
+
180
+ if (!(await Bun.file("dist/server/app.js").exists()))
181
+ throw new Error("crumpet: `vercel()` needs `dist/`. Call `build()` first, without `development`.");
182
+
183
+ const config: FunctionConfig = {
184
+ handler: "main.js",
185
+ runtime: "bun1.x",
186
+ supportsResponseStreaming: true,
187
+ ...options.config,
188
+ };
189
+
190
+ const routes: Route[] = [];
191
+ if (options.trailingSlash === true) {
192
+ routes.push(
193
+ // pages get a slash, files lose it
194
+ { src: "^/((?:[^/]+/)*[^/\\.]+)$", headers: { Location: "/$1/" }, status: 308 },
195
+ { src: "^/((?:[^/]+/)*[^/]+\\.\\w+)/$", headers: { Location: "/$1" }, status: 308 },
196
+ );
197
+ } else if (options.trailingSlash === false) {
198
+ routes.push({ src: "^/(.*)\\/$", headers: { Location: "/$1" }, status: 308 });
199
+ }
200
+ routes.push(
201
+ {
202
+ src: "/_immutable/.+",
203
+ headers: { "Cache-Control": "public, immutable, max-age=31536000" },
204
+ },
205
+ // static files first
206
+ { methods: ["GET"], handle: "filesystem" },
207
+ // Everything else goes to the function. Vercel passes it the client's
208
+ // path and query. ISR caches by the function's own path and `allowQuery`,
209
+ // so there the client's path has to be in the query, and the function
210
+ // moves it back.
211
+ { src: "^/(.*)$", dest: isr ? `/fn?${pathnameParam}=$1` : "/fn" },
212
+ );
213
+
214
+ const json = (file: string, value: unknown) =>
215
+ Bun.write(path.join(out, file), JSON.stringify(value, null, "\t"));
216
+
217
+ await fs.rm(out, { recursive: true, force: true });
218
+ await Promise.all([
219
+ fs.cp("dist/client", path.join(out, "static"), { recursive: true }),
220
+ fs.cp("dist/server", fn, { recursive: true }),
221
+ // `vercel` is the bundle's second export: `onVercel` around the app
222
+ Bun.write(
223
+ path.join(fn, "main.js"),
224
+ `import { vercel } from "./app.js";\n\nexport default vercel(${JSON.stringify({ isr: Boolean(isr) })});\n`,
225
+ ),
226
+ json("config.json", {
227
+ version: 3,
228
+ framework: { slug: "crumpet", version },
229
+ routes,
230
+ ...(options.images && { images: options.images }),
231
+ }),
232
+ json("functions/fn.func/.vc-config.json", config),
233
+ json("functions/fn.func/package.json", { type: "module" }),
234
+ isr &&
235
+ json("functions/fn.prerender-config.json", {
236
+ group: 1,
237
+ passQuery: true,
238
+ ...isr,
239
+ // without the path every page would be cached as one
240
+ allowQuery: [...(isr.allowQuery ?? []), pathnameParam],
241
+ } satisfies PrerenderConfig),
242
+ ]);
243
+
244
+ console.log(
245
+ `${styleText("green", "✓")} wrote ${styleText("bold", out + path.sep)} ${styleText("dim", `for ${config.runtime}`)}`,
246
+ );
247
+ };