@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 234 lines 9.04 KB
Raw
1 // Alchemy modifications are licensed under Apache-2.0.
2 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
3 /**
4 * The generated Cloudflare Worker entry (`_worker.js`) for a SvelteKit build.
5 *
6 * A fork of `@sveltejs/adapter-cloudflare`'s `src/worker.js` with three
7 * differences:
8 *
9 * - The `SERVER` / `MANIFEST` / `ASSETS` placeholders are templated directly
10 * with real relative import paths, so there is no publish-time prebundle or
11 * `builder.copy` string replacement.
12 * - `worktop/cfw.cache` is replaced with an inline `caches.default` wrapper
13 * (same lookup/save semantics), dropping the dependency.
14 * - With `notFoundHandling: "single-page-application"`, router-level
15 * not-founds on navigation-shaped requests are deferred to the assets
16 * layer (see below) so the configured `not_found_handling` governs.
17 *
18 * ## SPA not-found deferral (divergence from upstream)
19 *
20 * Upstream's `worker.js` never defers: kit's `server.respond` renders its
21 * own 404 error page for unmatched routes, and the assets-layer
22 * `not_found_handling` only applies to requests the worker never sees
23 * (asset-layer navigations under the `Sec-Fetch-Mode: navigate` preference
24 * flag) or to `env.ASSETS.fetch` misses. That leaves the configured
25 * `single-page-application` fallback unreachable for navigations that DO
26 * invoke the worker (e.g. plain `fetch` without `Sec-Fetch-Mode`).
27 *
28 * With `notFoundHandling: "single-page-application"` the shim therefore
29 * defers to `env.ASSETS.fetch(req)` — where the asset worker applies the
30 * configured `not_found_handling` and serves the generated `index.html`
31 * fallback — when ALL of:
32 *
33 * - `server.respond` returned a 404, AND
34 * - the request is navigation-shaped: `GET`/`HEAD` with `Accept`
35 * containing `text/html` (deliberately excluding kit data/route-resolution
36 * requests and API `fetch`es), AND
37 * - no kit route *pattern* matches the pathname — the most conservative
38 * available signal that the 404 is kit's router-level "no route" error
39 * rather than an intentional endpoint- or page-produced 404 (upstream has
40 * no deferral, so there are no upstream semantics to mirror; kit marks
41 * router 404s with no header). Endpoints only exist on matched routes, so
42 * endpoint 404s are never deferred. A pattern match whose param matchers
43 * fail is treated as matched (kit's own 404 page renders), as is a 404
44 * produced by a user `handle` hook on a path that happens to match a
45 * route pattern.
46 *
47 * `notFoundHandling: "404-page"` keeps exact upstream behavior (no
48 * deferral): upstream documents the `404.html` page as covering asset-layer
49 * misses only, with router-level 404s still rendered by kit.
50 *
51 * The emitted module is *unbundled* — its imports reach into
52 * `.svelte-kit/output/server/**` — and is the input for the rolldown pass
53 * that produces the final workerd-ready modules.
54 */
55 export interface WorkerShimOptions {
56 /**
57 * Relative import path to the generated server-instance module (kit's
58 * `generateServerInstance` output, exporting a pre-built `server`).
59 */
60 readonly serverImport: string;
61 /** Relative import path to the generated route-manifest module. */
62 readonly manifestImport: string;
63 /** Name of the static-assets binding. */
64 readonly assetsBinding: string;
65 /**
66 * The assets-layer `not_found_handling` the build was produced for. With
67 * `"single-page-application"` the shim defers router-level not-founds on
68 * navigation-shaped requests to the assets binding (see the module doc);
69 * any other value emits upstream-parity behavior (no deferral).
70 * @default "none"
71 */
72 readonly notFoundHandling?: "none" | "404-page" | "single-page-application" | undefined;
73 }
74
75 /**
76 * The SPA-deferral helper emitted ahead of the fetch handler: kit's
77 * `find_route` pattern probe, minus param matchers (a pattern match with
78 * failing matchers is conservatively treated as matched).
79 */
80 const spaRouteProbe = /* js */ `
81 // Router-level match probe for the SPA not-found deferral: mirrors kit's
82 // find_route pattern test (without param matchers — a pattern match whose
83 // matchers fail keeps kit's own 404 rendering).
84 const matches_kit_route = (pathname) => {
85 let path = pathname;
86 if (base_path) {
87 if (!path.startsWith(base_path)) return false;
88 path = path.slice(base_path.length) || '/';
89 }
90 for (const route of routes) {
91 if (route.pattern.test(path)) return true;
92 }
93 return false;
94 };
95 `;
96
97 const spaDeferral = (assetsBinding: string): string => /* js */ `
98 // not_found_handling: "single-page-application" — defer router-level
99 // not-founds on navigation-shaped requests (GET/HEAD accepting
100 // text/html) to the assets layer, which serves the generated
101 // index.html fallback. Intentional endpoint/page 404s (matched
102 // routes) are never deferred.
103 if (
104 res.status === 404 &&
105 (req.method === 'GET' || req.method === 'HEAD') &&
106 (req.headers.get('accept') || '').includes('text/html') &&
107 !matches_kit_route(pathname)
108 ) {
109 res = await env.${assetsBinding}.fetch(req);
110 }
111 `;
112
113 export const generateWorkerShim = (options: WorkerShimOptions): string =>
114 /* js */ `
115 import { server } from ${JSON.stringify(options.serverImport)};
116 import { assets, app_path, prerendered, base_path, routes } from ${JSON.stringify(options.manifestImport)};
117 import { env } from 'cloudflare:workers';
118
119 const app_dir = \`/\${app_path}\`;
120 const immutable = \`\${app_dir}/immutable/\`;
121 const version_file = \`\${app_dir}/version.json\`;
122
123 // Inline pragma-cache over \`caches.default\` (replaces the upstream
124 // adapter's external cache dependency).
125 const cache = caches.default;
126
127 const is_cacheable = (res) => {
128 if (res.status === 206) return false;
129 const vary = res.headers.get('vary') || '';
130 if (vary.includes('*')) return false;
131 const control = res.headers.get('cache-control') || '';
132 if (/(private|no-cache|no-store)/i.test(control)) return false;
133 return true;
134 };
135
136 const cache_lookup = async (req) => {
137 const is_head = req.method === 'HEAD';
138 if (is_head) req = new Request(req, { method: 'GET' });
139 let res = await cache.match(req);
140 if (is_head && res) res = new Response(null, res);
141 return res;
142 };
143
144 const cache_save = (req, res, ctx) => {
145 if ((req.method === 'GET' || req.method === 'HEAD') && is_cacheable(res)) {
146 if (res.headers.has('set-cookie')) {
147 res = new Response(res.body, res);
148 res.headers.append('cache-control', 'private=Set-Cookie');
149 }
150 ctx.waitUntil(cache.put(req, res.clone()));
151 }
152 return res;
153 };
154
155 ${options.notFoundHandling === "single-page-application" ? spaRouteProbe : ""}
156 /**
157 * We don't know the origin until we receive a request, but that's guaranteed
158 * to happen before we call \`read\`.
159 */
160 let origin;
161
162 const initialized = server.init({
163 env,
164 read: async (file) => {
165 const url = \`\${origin}/\${file}\`;
166 const response = await env.${options.assetsBinding}.fetch(url);
167 if (!response.ok) {
168 throw new Error(\`read(...) failed: could not fetch \${url} (\${response.status})\`);
169 }
170 return response.body;
171 },
172 });
173
174 export default {
175 async fetch(req, env, ctx) {
176 if (!origin) {
177 origin = new URL(req.url).origin;
178 }
179
180 // always await initialization to prevent race condition with concurrent requests
181 await initialized;
182
183 // skip cache if "cache-control: no-cache" in request
184 let pragma = req.headers.get('cache-control') || '';
185 let res = !pragma.includes('no-cache') && (await cache_lookup(req));
186 if (res) return res;
187
188 let { pathname, search } = new URL(req.url);
189 try {
190 pathname = decodeURIComponent(pathname);
191 } catch {
192 // ignore invalid URI
193 }
194
195 const stripped_pathname = pathname.replace(/\\/$/, '');
196
197 // files in /static, the service worker, and Vite-imported server assets
198 let is_static_asset = false;
199 const filename = stripped_pathname.slice(base_path.length + 1);
200 if (filename) {
201 is_static_asset =
202 assets.has(filename) || assets.has(filename + '/index.html');
203 }
204
205 let location = pathname.at(-1) === '/' ? stripped_pathname : pathname + '/';
206
207 if (
208 is_static_asset ||
209 prerendered.has(pathname) ||
210 pathname === version_file ||
211 pathname.startsWith(immutable)
212 ) {
213 res = await env.${options.assetsBinding}.fetch(req);
214 } else if (location && prerendered.has(location)) {
215 // trailing slash redirect for prerendered pages
216 if (search) location += search;
217 res = new Response('', { status: 308, headers: { location } });
218 } else {
219 // dynamically-generated pages
220 res = await server.respond(req, {
221 platform: { env, ctx, caches, cf: req.cf },
222 getClientAddress() {
223 return req.headers.get('cf-connecting-ip');
224 },
225 });
226 ${options.notFoundHandling === "single-page-application" ? spaDeferral(options.assetsBinding) : ""} }
227
228 // write to the cache only if the response is not an error;
229 // \`cache_save\` handles the Cache-Control and Vary headers
230 pragma = res.headers.get('cache-control') || '';
231 return pragma && res.status < 400 ? cache_save(req, res, ctx) : res;
232 },
233 };
234 `.trimStart();