@yannosay/sinth 5.3.2 → 5.3.4

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.
Files changed (46) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +16 -4
  3. package/dist/browser/sinth.js +630 -81
  4. package/dist/cli/index.js +52 -10
  5. package/dist/cli/skill.d.ts +10 -0
  6. package/dist/cli/skill.js +106 -0
  7. package/dist/cli/templates.js +1 -1
  8. package/dist/compiler/codegen.js +42 -5
  9. package/dist/compiler/elements.d.ts +6 -0
  10. package/dist/compiler/elements.js +12 -0
  11. package/dist/compiler/html.d.ts +2 -0
  12. package/dist/compiler/html.js +7 -0
  13. package/dist/compiler/prerender.js +5 -3
  14. package/dist/deploy/cloudflare.d.ts +2 -0
  15. package/dist/deploy/cloudflare.js +103 -18
  16. package/dist/deploy/platforms.d.ts +20 -0
  17. package/dist/deploy/platforms.js +212 -0
  18. package/dist/deploy/redirects.d.ts +31 -0
  19. package/dist/deploy/redirects.js +102 -0
  20. package/dist/project/build.js +104 -18
  21. package/dist/project/config.d.ts +19 -0
  22. package/dist/project/config.js +66 -8
  23. package/dist/project/env.d.ts +11 -0
  24. package/dist/project/env.js +84 -0
  25. package/dist/project/project.d.ts +7 -1
  26. package/dist/project/project.js +37 -10
  27. package/dist/runtime/index.js +48 -8
  28. package/dist/runtime/router.js +17 -1
  29. package/dist/server/dev.d.ts +4 -0
  30. package/dist/server/dev.js +35 -11
  31. package/dist/server/functions-router.d.ts +60 -0
  32. package/dist/server/functions-router.js +161 -0
  33. package/dist/server/functions.d.ts +8 -12
  34. package/dist/server/functions.js +43 -133
  35. package/dist/server/preview.d.ts +3 -0
  36. package/dist/server/preview.js +8 -1
  37. package/dist/server/static.d.ts +9 -0
  38. package/dist/server/static.js +24 -1
  39. package/lib/ui/index.sinth +533 -24
  40. package/package.json +2 -1
  41. package/schema/sinth.config.schema.json +30 -1
  42. package/skills/agents.md +62 -0
  43. package/skills/sinth/SKILL.md +125 -0
  44. package/skills/sinth/references/language.md +175 -0
  45. package/skills/sinth/references/project-and-deploy.md +87 -0
  46. package/skills/sinth/references/ui.md +95 -0
@@ -1,5 +1,9 @@
1
1
  const SVG_NS = "http://www.w3.org/2000/svg";
2
- const BLOCKED_URL = /^\s*(javascript|vbscript|data:(?!image\/(png|gif|jpe?g|webp|avif|svg\+xml)|video\/|audio\/))/i;
2
+ // Browsers ignore control characters and whitespace inside a URL scheme ("java\tscript:"), so they are
3
+ // removed before the check. Keep in sync with isUnsafeUrl() in compiler/html.ts.
4
+ const BLOCKED_URL = /^(javascript:|vbscript:|data:(?!image\/(png|gif|jpe?g|webp|avif|svg\+xml)[;,]|video\/|audio\/))/i;
5
+ // eslint-disable-next-line no-control-regex
6
+ const URL_NOISE = /[\u0000- \u007f]/g;
3
7
  let rootOwner = createOwner(null);
4
8
  let current = rootOwner;
5
9
  let updating = false;
@@ -184,7 +188,7 @@ export function text(parent, get) {
184
188
  });
185
189
  }
186
190
  export function sanitizeUrl(value) {
187
- if (BLOCKED_URL.test(value)) {
191
+ if (BLOCKED_URL.test(value.replace(URL_NOISE, ""))) {
188
192
  if (devMode)
189
193
  console.warn(`[sinth] Blocked unsafe URL: ${value.slice(0, 64)}`);
190
194
  return "about:blank#blocked";
@@ -413,27 +417,50 @@ export function model(node, get, set, numeric = false) {
413
417
  return;
414
418
  }
415
419
  const isNumber = numeric || type === "number" || type === "range";
420
+ // The value last written to or read from the field. The field is only overwritten when the bound
421
+ // value changes from it, so typing (an empty number field, "1." on the way to "1.5") is not undone.
422
+ const NONE = {};
423
+ let synced = NONE;
416
424
  effect(() => {
417
425
  const v = get();
426
+ if (Object.is(v, synced))
427
+ return;
428
+ synced = v;
418
429
  const str = v === null || v === undefined ? "" : String(v);
419
430
  if (input.value !== str && !(isNumber && Number(input.value) === v && input.value !== "")) {
420
431
  input.value = str;
421
432
  }
422
433
  });
434
+ const write = (v) => {
435
+ synced = v;
436
+ set(v);
437
+ };
438
+ if (tag === "SELECT" && typeof MutationObserver !== "undefined") {
439
+ // Options rendered by a loop, or loaded later, can appear after the value was applied: select the
440
+ // bound value again once an option for it exists.
441
+ const select = node;
442
+ new MutationObserver(() => {
443
+ if (synced === NONE)
444
+ return;
445
+ const str = synced === null || synced === undefined ? "" : String(synced);
446
+ if (select.value !== str && Array.from(select.options).some(o => o.value === str))
447
+ select.value = str;
448
+ }).observe(select, { childList: true, subtree: true, attributes: true, attributeFilter: ["value"] });
449
+ }
423
450
  const evt = tag === "SELECT" || type === "range" || type === "color" || type === "date" || type === "file" ? "change" : "input";
424
451
  on(node, evt, () => {
425
452
  if (!isNumber) {
426
- set(input.value);
453
+ write(input.value);
427
454
  return;
428
455
  }
429
456
  if (input.value === "")
430
457
  return;
431
458
  const n = Number(input.value);
432
459
  if (!Number.isNaN(n))
433
- set(n);
460
+ write(n);
434
461
  });
435
462
  if (evt === "change" && type === "range")
436
- on(node, "input", () => set(Number(input.value)));
463
+ on(node, "input", () => write(Number(input.value)));
437
464
  }
438
465
  export function ref(node, set) {
439
466
  set(node);
@@ -482,8 +509,10 @@ export function when(parent, branches, options = {}) {
482
509
  const leaving = Array.from(takeRange(start, end).childNodes);
483
510
  for (const n of leaving) {
484
511
  start.parentNode?.insertBefore(n, start);
485
- if (n instanceof Element && options.transition)
512
+ if (n instanceof Element && options.transition) {
486
513
  n.classList.add(`${options.transition}-leave`);
514
+ n.setAttribute("inert", "");
515
+ }
487
516
  }
488
517
  setTimeout(() => {
489
518
  for (const n of leaving)
@@ -673,11 +702,16 @@ export function slot(parent, slots, name, fallback) {
673
702
  fallback(parent);
674
703
  }
675
704
  export function onMount(fn) {
705
+ // The callback runs after the current render, when `current` is no longer this component's
706
+ // owner, so the owner is captured now. A returned cleanup runs when the component is removed.
707
+ const owner = current;
676
708
  queueMicrotask(() => {
709
+ if (owner.disposed)
710
+ return;
677
711
  try {
678
- const cleanup = fn();
712
+ const cleanup = withOwner(owner, fn);
679
713
  if (typeof cleanup === "function")
680
- current.cleanups.push(cleanup);
714
+ owner.cleanups.push(cleanup);
681
715
  settle(cleanup);
682
716
  }
683
717
  catch (err) {
@@ -752,6 +786,8 @@ export function persist(key, get) {
752
786
  });
753
787
  }
754
788
  const memoCache = new Map();
789
+ /** Results kept per memoized function; the oldest are dropped beyond this. */
790
+ const MEMO_LIMIT = 500;
755
791
  export function memo(site, fn, args) {
756
792
  let cache = memoCache.get(site);
757
793
  if (!cache) {
@@ -768,6 +804,8 @@ export function memo(site, fn, args) {
768
804
  if (cache.has(key))
769
805
  return cache.get(key);
770
806
  const value = fn();
807
+ if (cache.size >= MEMO_LIMIT)
808
+ cache.delete(cache.keys().next().value);
771
809
  cache.set(key, value);
772
810
  return value;
773
811
  }
@@ -776,6 +814,8 @@ export function range(a, b, step = 1) {
776
814
  const endN = b === undefined ? a : b;
777
815
  if (step === 0)
778
816
  throw new Error("range() step cannot be 0");
817
+ if (!Number.isFinite(startN) || !Number.isFinite(endN) || !Number.isFinite(step))
818
+ throw new Error("range() needs finite numbers");
779
819
  const out = [];
780
820
  if (step > 0)
781
821
  for (let i = startN; i < endN; i += step)
@@ -114,7 +114,15 @@ function scrollTo(url, restore) {
114
114
  window.scrollTo(0, restore);
115
115
  return;
116
116
  }
117
- const target = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
117
+ let target = null;
118
+ if (url.hash) {
119
+ try {
120
+ target = document.getElementById(decodeURIComponent(url.hash.slice(1)));
121
+ }
122
+ catch {
123
+ target = document.getElementById(url.hash.slice(1));
124
+ }
125
+ }
118
126
  if (target)
119
127
  target.scrollIntoView();
120
128
  else
@@ -132,6 +140,14 @@ async function navigate(url, mode, restore) {
132
140
  location.href = url.href;
133
141
  return;
134
142
  }
143
+ // Follow server redirects (e.g. /about/ -> /about) so the address bar shows the final URL.
144
+ if (res.redirected && res.url) {
145
+ const final = new URL(res.url);
146
+ if (final.origin === location.origin) {
147
+ final.hash = url.hash;
148
+ url = final;
149
+ }
150
+ }
135
151
  const doc = new DOMParser().parseFromString(await res.text(), "text/html");
136
152
  if (id !== token)
137
153
  return;
@@ -5,4 +5,8 @@ export interface DevServerOptions {
5
5
  open: boolean;
6
6
  }
7
7
  export declare function startDevServer(project: Project, opts: DevServerOptions): Promise<void>;
8
+ /**
9
+ * Opens a URL in the default browser. On Windows this avoids `cmd /c start`, which would interpret
10
+ * characters such as & and ^ in the URL as shell syntax.
11
+ */
8
12
  export declare function openBrowser(url: string): void;
@@ -42,9 +42,11 @@ const path = __importStar(require("path"));
42
42
  const diagnostics_1 = require("../compiler/diagnostics");
43
43
  const html_1 = require("../compiler/html");
44
44
  const build_1 = require("../project/build");
45
+ const config_1 = require("../project/config");
45
46
  const ui_1 = require("../cli/ui");
46
47
  const client_1 = require("./client");
47
48
  const functions_1 = require("./functions");
49
+ const redirects_1 = require("../deploy/redirects");
48
50
  const static_1 = require("./static");
49
51
  const CLIENT_URL = "/__sinth/client.js";
50
52
  const HTML = "text/html; charset=utf-8";
@@ -68,7 +70,7 @@ async function startDevServer(project, opts) {
68
70
  let lastError = null;
69
71
  let hashes = [];
70
72
  let building = null;
71
- let pending = false;
73
+ let pending = null;
72
74
  const broadcast = (msg) => {
73
75
  const data = `data: ${JSON.stringify(msg)}\n\n`;
74
76
  for (const res of clients)
@@ -111,14 +113,15 @@ async function startDevServer(project, opts) {
111
113
  };
112
114
  const queueRebuild = (file) => {
113
115
  if (building) {
114
- pending = true;
116
+ pending = file;
115
117
  return;
116
118
  }
117
119
  building = rebuild(file).finally(() => {
118
120
  building = null;
119
- if (pending) {
120
- pending = false;
121
- queueRebuild(file);
121
+ if (pending !== null) {
122
+ const next = pending;
123
+ pending = null;
124
+ queueRebuild(next);
122
125
  }
123
126
  });
124
127
  };
@@ -149,7 +152,7 @@ async function startDevServer(project, opts) {
149
152
  if (mem)
150
153
  return { status: 200, body: mem.contents, type: (0, static_1.mimeType)(sitePath), headers: NO_STORE };
151
154
  const fromPublic = (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.publicDir, sitePath));
152
- const fromStatic = cfg.staticDirs.some(d => sitePath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(project.root, sitePath)) : null;
155
+ const fromStatic = cfg.staticDirs.some(d => sitePath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.srcDir, sitePath)) : null;
153
156
  const file = fromPublic ?? fromStatic;
154
157
  if (file)
155
158
  return { status: 200, body: fs.readFileSync(file), type: (0, static_1.mimeType)(file), headers: NO_STORE };
@@ -157,9 +160,15 @@ async function startDevServer(project, opts) {
157
160
  };
158
161
  const functions = new functions_1.FunctionsHost(project.root);
159
162
  const handle = async (req, res) => {
163
+ if (!(0, static_1.hostAllowed)(req.headers.host, cfg.allowedHosts === true || [...cfg.allowedHosts, opts.host]))
164
+ return (0, static_1.forbiddenHost)(res, req.headers.host);
160
165
  const urlPath = (0, static_1.decodePath)(req.url);
161
166
  if (!urlPath)
162
167
  return (0, static_1.send)(res, 400, "Bad request", "text/plain");
168
+ const sitePath = (0, static_1.stripBase)(urlPath, cfg.base);
169
+ const redirect = sitePath === null ? null : (0, redirects_1.matchRedirect)(cfg.redirects, sitePath, (req.url ?? "").match(/\?[^#]*/)?.[0]);
170
+ if (redirect)
171
+ return (0, static_1.send)(res, redirect.status, "", "text/plain", { Location: redirect.location });
163
172
  if (urlPath === "/__sinth/events") {
164
173
  res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
165
174
  res.write(`data: ${JSON.stringify({ type: "init", pages: hashes, error: lastError, base: cfg.base })}\n\n`);
@@ -214,12 +223,13 @@ async function startDevServer(project, opts) {
214
223
  ui_1.log.warn(`Port ${opts.port} is in use, using ${port} instead`);
215
224
  const timers = new Map();
216
225
  const onChange = (file) => {
217
- if (IGNORED.test(path.relative(project.root, file)) || file.startsWith(cfg.outDir) || !WATCHED_EXT.test(file))
226
+ const isEnv = /^\.env(\..+)?$/.test(path.basename(file)) || path.basename(file) === ".dev.vars";
227
+ if (IGNORED.test(path.relative(project.root, file)) || file.startsWith(cfg.outDir) || (!WATCHED_EXT.test(file) && !isEnv))
218
228
  return;
219
229
  clearTimeout(timers.get(file));
220
230
  timers.set(file, setTimeout(() => {
221
231
  timers.delete(file);
222
- const inStatic = file.startsWith(cfg.publicDir + path.sep) || cfg.staticDirs.some(d => file.startsWith(path.resolve(project.root, d) + path.sep));
232
+ const inStatic = file.startsWith(cfg.publicDir + path.sep) || cfg.staticDirs.some(d => file.startsWith((0, config_1.staticDirPath)(cfg, d) + path.sep));
223
233
  if (inStatic && !file.endsWith(".css") && !file.endsWith(".sinth")) {
224
234
  broadcast({ type: "reload" });
225
235
  return;
@@ -229,6 +239,12 @@ async function startDevServer(project, opts) {
229
239
  ui_1.log.success(`${ui_1.c.gray(path.relative(project.root, file).replace(/\\/g, "/"))} ${ui_1.c.dim("reloaded")}`);
230
240
  return;
231
241
  }
242
+ if (isEnv) {
243
+ functions.invalidate();
244
+ ui_1.log.success(`${ui_1.c.gray(path.basename(file))} ${ui_1.c.dim("reloaded")}`);
245
+ queueRebuild();
246
+ return;
247
+ }
232
248
  if (path.basename(file) === "sinth.config.json") {
233
249
  ui_1.log.warn("sinth.config.json changed. Restart the dev server to apply it.");
234
250
  return;
@@ -275,10 +291,18 @@ async function startDevServer(project, opts) {
275
291
  process.on("SIGINT", shutdown);
276
292
  process.on("SIGTERM", shutdown);
277
293
  }
294
+ /**
295
+ * Opens a URL in the default browser. On Windows this avoids `cmd /c start`, which would interpret
296
+ * characters such as & and ^ in the URL as shell syntax.
297
+ */
278
298
  function openBrowser(url) {
299
+ if (!/^https?:\/\//.test(url))
300
+ return;
279
301
  Promise.resolve().then(() => __importStar(require("child_process"))).then(cp => {
280
- const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
281
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
282
- cp.spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
302
+ const [cmd, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
303
+ : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
304
+ const child = cp.spawn(cmd, args, { stdio: "ignore", detached: true });
305
+ child.on("error", () => ui_1.log.warn(`Could not open a browser. Open ${url} yourself.`));
306
+ child.unref();
283
307
  }).catch(() => undefined);
284
308
  }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Routing for `functions/`, following the Cloudflare Pages Functions conventions. This file has no
3
+ * Node.js imports: the dev and preview servers use it, and `platform: "cloudflare-workers"` bundles
4
+ * it into the deployed Worker, so routes behave the same everywhere.
5
+ */
6
+ export type Segment = {
7
+ kind: "static";
8
+ value: string;
9
+ } | {
10
+ kind: "param";
11
+ name: string;
12
+ } | {
13
+ kind: "catchall";
14
+ name: string;
15
+ };
16
+ export type Params = Record<string, string | string[]>;
17
+ export interface FunctionContext {
18
+ request: Request;
19
+ params: Params;
20
+ env: Record<string, unknown>;
21
+ data: Record<string, unknown>;
22
+ functionPath: string;
23
+ next(input?: Request | string, init?: RequestInit): Promise<Response>;
24
+ waitUntil(promise: Promise<unknown>): void;
25
+ passThroughOnException(): void;
26
+ }
27
+ export type Handler = (context: FunctionContext) => Response | Promise<Response>;
28
+ export type FunctionModule = Record<string, unknown>;
29
+ export interface RouteDef {
30
+ /** Path inside functions/, e.g. "api/users/[id].ts". */
31
+ rel: string;
32
+ segments: Segment[];
33
+ middleware: boolean;
34
+ }
35
+ export interface LoadedRoute extends RouteDef {
36
+ module: FunctionModule;
37
+ }
38
+ export interface DispatchOptions {
39
+ env: Record<string, unknown>;
40
+ /** Serves a static file or page; used by `next()` when no further handler applies. */
41
+ assets(request: Request): Promise<Response>;
42
+ waitUntil(promise: Promise<unknown>): void;
43
+ passThroughOnException?(): void;
44
+ }
45
+ export declare const FUNCTION_FILE: RegExp;
46
+ export declare function isFunctionFile(name: string): boolean;
47
+ export declare function routeDef(rel: string): RouteDef;
48
+ /** More specific routes first: longer paths, then static before [param] before [[catchall]]. */
49
+ export declare function compareRoutes(a: RouteDef, b: RouteDef): number;
50
+ export declare function matchRoute(route: RouteDef, parts: string[], prefixOnly: boolean): Params | null;
51
+ /**
52
+ * URL patterns that can reach a function, for hosts that only invoke code for some paths
53
+ * (Cloudflare Workers `run_worker_first`). Returns ["/*"] when a route can match anything.
54
+ */
55
+ export declare function routePatterns(routes: RouteDef[]): string[];
56
+ /**
57
+ * Runs the middleware chain and the matching route. Returns null when no function applies, so the
58
+ * caller serves the request as a static file.
59
+ */
60
+ export declare function dispatch(routes: LoadedRoute[], request: Request, opts: DispatchOptions): Promise<Response | null>;
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ /**
3
+ * Routing for `functions/`, following the Cloudflare Pages Functions conventions. This file has no
4
+ * Node.js imports: the dev and preview servers use it, and `platform: "cloudflare-workers"` bundles
5
+ * it into the deployed Worker, so routes behave the same everywhere.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.FUNCTION_FILE = void 0;
9
+ exports.isFunctionFile = isFunctionFile;
10
+ exports.routeDef = routeDef;
11
+ exports.compareRoutes = compareRoutes;
12
+ exports.matchRoute = matchRoute;
13
+ exports.routePatterns = routePatterns;
14
+ exports.dispatch = dispatch;
15
+ exports.FUNCTION_FILE = /\.(ts|js|mjs|tsx|jsx)$/;
16
+ const METHOD_EXPORTS = {
17
+ GET: "onRequestGet", POST: "onRequestPost", PUT: "onRequestPut", PATCH: "onRequestPatch",
18
+ DELETE: "onRequestDelete", HEAD: "onRequestHead", OPTIONS: "onRequestOptions",
19
+ };
20
+ function isFunctionFile(name) {
21
+ return exports.FUNCTION_FILE.test(name) && !name.endsWith(".d.ts") && !/\.(test|spec)\./.test(name);
22
+ }
23
+ function routeDef(rel) {
24
+ const parts = rel.replace(exports.FUNCTION_FILE, "").split("/").filter(Boolean);
25
+ const last = parts[parts.length - 1];
26
+ if (last === "index" || last === "_middleware")
27
+ parts.pop();
28
+ const segments = parts.map(p => {
29
+ const catchall = p.match(/^\[\[([A-Za-z_]\w*)\]\]$/);
30
+ if (catchall)
31
+ return { kind: "catchall", name: catchall[1] };
32
+ const param = p.match(/^\[([A-Za-z_]\w*)\]$/);
33
+ if (param)
34
+ return { kind: "param", name: param[1] };
35
+ return { kind: "static", value: p };
36
+ });
37
+ return { rel, segments, middleware: /(^|\/)_middleware\.\w+$/.test(rel) };
38
+ }
39
+ function rank(route) {
40
+ return route.segments.map(s => (s.kind === "static" ? 0 : s.kind === "param" ? 1 : 2));
41
+ }
42
+ /** More specific routes first: longer paths, then static before [param] before [[catchall]]. */
43
+ function compareRoutes(a, b) {
44
+ if (a.segments.length !== b.segments.length)
45
+ return b.segments.length - a.segments.length;
46
+ const ra = rank(a);
47
+ const rb = rank(b);
48
+ for (let i = 0; i < ra.length; i++)
49
+ if (ra[i] !== rb[i])
50
+ return ra[i] - rb[i];
51
+ return a.rel.localeCompare(b.rel);
52
+ }
53
+ function matchRoute(route, parts, prefixOnly) {
54
+ const params = {};
55
+ for (let i = 0; i < route.segments.length; i++) {
56
+ const seg = route.segments[i];
57
+ if (seg.kind === "catchall") {
58
+ if (i >= parts.length)
59
+ return null;
60
+ params[seg.name] = parts.slice(i);
61
+ return params;
62
+ }
63
+ if (i >= parts.length)
64
+ return null;
65
+ if (seg.kind === "static" && seg.value !== parts[i])
66
+ return null;
67
+ if (seg.kind === "param")
68
+ params[seg.name] = parts[i];
69
+ }
70
+ return prefixOnly || route.segments.length === parts.length ? params : null;
71
+ }
72
+ /**
73
+ * URL patterns that can reach a function, for hosts that only invoke code for some paths
74
+ * (Cloudflare Workers `run_worker_first`). Returns ["/*"] when a route can match anything.
75
+ */
76
+ function routePatterns(routes) {
77
+ const out = new Set();
78
+ for (const r of routes) {
79
+ const fixed = [];
80
+ for (const s of r.segments) {
81
+ if (s.kind !== "static")
82
+ break;
83
+ fixed.push(s.value);
84
+ }
85
+ if (!fixed.length)
86
+ return ["/*"];
87
+ const prefix = "/" + fixed.join("/");
88
+ if (fixed.length === r.segments.length && !r.middleware)
89
+ out.add(prefix);
90
+ else {
91
+ out.add(prefix);
92
+ out.add(prefix + "/*");
93
+ }
94
+ }
95
+ return [...out].sort();
96
+ }
97
+ function decodeParts(pathname) {
98
+ try {
99
+ return pathname.split("/").filter(Boolean).map(decodeURIComponent);
100
+ }
101
+ catch {
102
+ return null;
103
+ }
104
+ }
105
+ function handlerFor(mod, method) {
106
+ const h = mod[METHOD_EXPORTS[method] ?? ""] ?? mod.onRequest;
107
+ const list = Array.isArray(h) ? h : h ? [h] : [];
108
+ return list.filter((x) => typeof x === "function");
109
+ }
110
+ /**
111
+ * Runs the middleware chain and the matching route. Returns null when no function applies, so the
112
+ * caller serves the request as a static file.
113
+ */
114
+ async function dispatch(routes, request, opts) {
115
+ const url = new URL(request.url);
116
+ const parts = decodeParts(url.pathname);
117
+ if (!parts)
118
+ return null;
119
+ const chain = [];
120
+ const middleware = routes.filter(r => r.middleware).sort((a, b) => a.segments.length - b.segments.length);
121
+ for (const r of middleware) {
122
+ const params = matchRoute(r, parts, true);
123
+ if (params)
124
+ for (const handler of handlerFor(r.module, request.method))
125
+ chain.push({ handler, params, rel: r.rel });
126
+ }
127
+ for (const r of routes) {
128
+ if (r.middleware)
129
+ continue;
130
+ const params = matchRoute(r, parts, false);
131
+ if (!params)
132
+ continue;
133
+ const handlers = handlerFor(r.module, request.method);
134
+ if (!handlers.length)
135
+ continue;
136
+ for (const handler of handlers)
137
+ chain.push({ handler, params, rel: r.rel });
138
+ break;
139
+ }
140
+ // Matching middleware runs even when no route does: its next() then serves the static file.
141
+ if (!chain.length)
142
+ return null;
143
+ const data = {};
144
+ const run = async (index, req) => {
145
+ const step = chain[index];
146
+ if (!step)
147
+ return opts.assets(req);
148
+ const result = await step.handler({
149
+ request: req, params: step.params, env: opts.env, data,
150
+ functionPath: url.pathname,
151
+ next: (input, init) => run(index + 1, input === undefined ? req : new Request(input, init)),
152
+ waitUntil: p => opts.waitUntil(p),
153
+ passThroughOnException: () => opts.passThroughOnException?.(),
154
+ });
155
+ if (!(result instanceof Response)) {
156
+ throw new Error(`functions/${step.rel} must return a Response (got ${result === undefined ? "undefined" : typeof result})`);
157
+ }
158
+ return result;
159
+ };
160
+ return run(0, request);
161
+ }
@@ -1,4 +1,5 @@
1
1
  import * as http from "http";
2
+ import { RouteDef } from "./functions-router";
2
3
  /**
3
4
  * Server routes in `functions/`, following the Cloudflare Pages Functions conventions so the same
4
5
  * files run in `sinth dev`, `sinth preview` and on Cloudflare Pages after `sinth deploy`:
@@ -11,26 +12,22 @@ import * as http from "http";
11
12
  * A module exports `onRequest` or method handlers such as `onRequestGet` / `onRequestPost`.
12
13
  */
13
14
  export declare const FUNCTIONS_DIR = "functions";
14
- export interface FunctionContext {
15
- request: Request;
16
- params: Record<string, string | string[]>;
17
- env: Record<string, unknown>;
18
- data: Record<string, unknown>;
19
- functionPath: string;
20
- next(input?: Request | string, init?: RequestInit): Promise<Response>;
21
- waitUntil(promise: Promise<unknown>): void;
22
- passThroughOnException(): void;
23
- }
15
+ export type { FunctionContext } from "./functions-router";
24
16
  /** Serves a static file or page for `next()` and `env.ASSETS`. */
25
17
  export type AssetHandler = (request: Request) => Promise<Response>;
18
+ /** Every route file in a functions/ folder, most specific first. */
19
+ export declare function scanFunctions(dir: string): (RouteDef & {
20
+ file: string;
21
+ })[];
26
22
  export declare class FunctionsHost {
27
23
  private readonly root;
24
+ private readonly mode;
28
25
  private routes;
29
26
  private modules;
30
27
  private building;
31
28
  readonly dir: string;
32
29
  private readonly cacheDir;
33
- constructor(root: string);
30
+ constructor(root: string, mode?: "development" | "production");
34
31
  get enabled(): boolean;
35
32
  invalidate(): void;
36
33
  private scan;
@@ -41,7 +38,6 @@ export declare class FunctionsHost {
41
38
  * function applies, so the caller serves the request as a static file.
42
39
  */
43
40
  handle(request: Request, assets: AssetHandler): Promise<Response | null>;
44
- private handlerFor;
45
41
  }
46
42
  /** Converts a Node request into a Fetch API Request. */
47
43
  export declare function toRequest(req: http.IncomingMessage): Promise<Request>;