@jxsuite/compiler 8.5.0 → 8.7.0

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.
@@ -6,9 +6,17 @@
6
6
  */
7
7
 
8
8
  import { erasedDocument } from "../erased.ts";
9
+ import { qualifyScripts } from "@jxsuite/schema/document-scripts";
10
+ import {
11
+ classifyFunctionEntries,
12
+ declaresParameters,
13
+ handlerParamNames,
14
+ } from "@jxsuite/schema/function-role";
9
15
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
10
16
  import {
11
17
  ATTR_HELPER,
18
+ DEFAULT_LIT_HTML_SRC,
19
+ DEFAULT_REACTIVITY_SRC,
12
20
  attrHelperSource,
13
21
  booleanAttrValue,
14
22
  definitionHasSlot,
@@ -22,20 +30,21 @@ import {
22
30
  compileOperandSource,
23
31
  compileStatements,
24
32
  emitFormulaFn,
33
+ collectFunctionImports,
34
+ emitSrcImports,
35
+ refuseBodyWithSrc,
25
36
  emitRequestFetch,
26
37
  emitServerCall,
27
38
  escapeHtml,
39
+ inheritProjectFormulas,
28
40
  isMutating,
29
41
  isSchemaOnly,
30
42
  rewriteState,
31
43
  serverCallHelperSource,
32
- srcExportName,
33
- srcImportBinding,
34
44
  tagNameToClassName,
35
45
  templateValueSource,
36
46
  } from "../shared.ts";
37
47
  import {
38
- bodyReturnsValue,
39
48
  hasStructuredBody,
40
49
  isExpressionDef,
41
50
  isBoolean,
@@ -49,7 +58,6 @@ import {
49
58
  isServerFnDef,
50
59
  isString,
51
60
  isTagExpression,
52
- paramNames,
53
61
  } from "@jxsuite/schema/guards";
54
62
  import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
55
63
  import { resolveShadowMode } from "../shadow.ts";
@@ -101,6 +109,20 @@ export interface CompileElementOptions {
101
109
  * so the base has to be known when it is compiled. Handed to every `$elements` dependency too.
102
110
  */
103
111
  serverBaseUrl?: string;
112
+ /**
113
+ * The project root, when the component is compiled as part of a project. With it, an entry naming
114
+ * its own document's script (`$src: "#client"`) reaches `rewriteSrc` qualified by the document's
115
+ * project-relative path (spec.md §23.2), for every `$elements` dependency too. Without it such a
116
+ * `$src` is emitted as written, and nothing can import it.
117
+ */
118
+ projectRoot?: string;
119
+ /**
120
+ * The project's `state`, when the component is compiled as part of a project. The component, and
121
+ * every `$elements` dependency, inherits the pure named formulas it reads from it (spec.md
122
+ * §13.4), each written into that component's own module. Without it a component is its own
123
+ * document.
124
+ */
125
+ projectState?: Record<string, JxStateDefinition> | undefined;
104
126
  }
105
127
 
106
128
  /**
@@ -148,6 +170,10 @@ export async function compileElement(
148
170
  }
149
171
  // Function bodies as JavaScript before anything analyses them (spec.md §23.1).
150
172
  doc = erasedDocument(doc, filePath);
173
+ if (opts.projectRoot !== undefined) {
174
+ const { relative } = await import("node:path");
175
+ doc = qualifyScripts(doc, relative(opts.projectRoot, filePath));
176
+ }
151
177
  } else {
152
178
  doc = erasedDocument(srcPath, srcPath.tagName ?? "a component");
153
179
  filePath = null;
@@ -159,6 +185,8 @@ export async function compileElement(
159
185
  }
160
186
  }
161
187
 
188
+ doc = inheritProjectFormulas(doc, opts.projectState);
189
+
162
190
  const { tagName } = doc;
163
191
  if (!tagName || !tagName.includes("-")) {
164
192
  throw new Error(`compileElement: tagName "${tagName}" must contain a hyphen`);
@@ -233,8 +261,8 @@ export async function compileElementPage(
233
261
  ) {
234
262
  const {
235
263
  title = "Jx App",
236
- reactivitySrc = "https://esm.sh/@vue/reactivity@3.5.13",
237
- litHtmlSrc = "https://esm.sh/lit-html@3.3.0",
264
+ reactivitySrc = DEFAULT_REACTIVITY_SRC,
265
+ litHtmlSrc = DEFAULT_LIT_HTML_SRC,
238
266
  } = opts;
239
267
 
240
268
  const result = await compileElement(sourcePath, opts);
@@ -307,75 +335,6 @@ function extractInitialValue(def: JxStateDefinition) {
307
335
  return JSON.stringify(def);
308
336
  }
309
337
 
310
- /** Lifecycle hooks the generated element calls itself, so they are never `$ref`'d (spec.md §16.4). */
311
- const LIFECYCLE_KEYS = new Set(["onMount", "onUnmount", "onAdopted"]);
312
-
313
- /**
314
- * Collect the state keys a document uses as a _callable_, at any depth: bound to an `on*` event,
315
- * invoked by an `$expression` `call` node, or called as `state.key(…)` from a template string or
316
- * another function's body.
317
- *
318
- * A bodyless `$src` Function carries no body to classify by, and unlike the interpreter — which
319
- * introspects the imported function — a compiler only has the document to go on. Anything not used
320
- * as a callable has its return value read reactively, and so becomes a computed (spec.md §5.3 4b).
321
- * Defaulting the other way round would turn a called helper into a value and break its call site.
322
- *
323
- * @param {JxDocument} doc
324
- * @returns {Set<string>}
325
- */
326
- function collectCallableRefs(doc: JxDocument) {
327
- const keys = new Set<string>();
328
- const seen = new Set<object>();
329
-
330
- const addStateRef = (ref: string) => {
331
- if (ref.startsWith("#/state/")) {
332
- /* SAFETY: `String.prototype.split` always returns at least one element (the whole string
333
- when the separator is absent), so index 0 is present. */
334
- keys.add(ref.slice("#/state/".length).split("/")[0] as string);
335
- }
336
- };
337
-
338
- const visit = (node: JxDocumentValue | undefined) => {
339
- if (isString(node)) {
340
- // `${state.formatDate(d)}` in a template, or `state.helper(x)` in another function's body.
341
- for (const call of node.matchAll(/\bstate\.([A-Za-z_$][\w$]*)\s*\(/g)) {
342
- /* SAFETY: the pattern's one capture group is not optional, so every match fills
343
- index 1 with the called member's name. */
344
- keys.add(call[1] as string);
345
- }
346
- return;
347
- }
348
- if (!isNonNullObject(node) || seen.has(node)) {
349
- return;
350
- }
351
- seen.add(node);
352
- if (Array.isArray(node)) {
353
- for (const item of node) {
354
- visit(item);
355
- }
356
- return;
357
- }
358
- /* SAFETY: `node` is a non-null, non-array object reached from `doc.children` or `doc.state`,
359
- and every such object in a parsed Jx document is a JSON object whose members are document
360
- values; the view only reads members, and each is checked before use. */
361
- const record = node as Readonly<Record<string, JxDocumentValue | undefined>>;
362
- // An `$expression` `call` node names its callee in `target` (spec.md §19.4c).
363
- if (record.operator === "call" && isRef(record.target)) {
364
- addStateRef(record.target.$ref);
365
- }
366
- for (const [key, val] of Object.entries(record)) {
367
- if (key.startsWith("on") && key !== "observedAttributes" && isRef(val)) {
368
- addStateRef(val.$ref);
369
- }
370
- visit(val);
371
- }
372
- };
373
-
374
- visit(doc.children);
375
- visit(doc.state);
376
- return keys;
377
- }
378
-
379
338
  /**
380
339
  * Generate a complete ES module string for a custom element.
381
340
  *
@@ -403,49 +362,12 @@ export function emitElementModule(
403
362
  }
404
363
 
405
364
  // Collect $src imports from state entries before emitting other imports
406
- const srcImportMap = new Map<string, string[]>();
407
- /** `$lazy` `$src` modules → the (export, local binding) pairs each one supplies. */
408
- const lazySrcMap = new Map<string, { binding: string; exportName: string }[]>();
409
365
  const defs = doc.state ?? {};
410
- const callableRefs = collectCallableRefs(doc);
411
- for (const [key, def] of Object.entries(defs)) {
412
- if (isFunctionDef(def) && def.$src) {
413
- const srcPath = def.$src;
414
- if (def.$lazy === true) {
415
- /*
416
- * A computed reads its value synchronously, and a lazy binding can only ever hand back a
417
- * promise. Silently producing `computed(() => Promise)` would render "[object Promise]" in
418
- * whatever the template bound it to, so this is a build error rather than a surprise.
419
- */
420
- if (!callableRefs.has(key) && !LIFECYCLE_KEYS.has(key)) {
421
- throw new Error(
422
- `"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
423
- `A lazily loaded function resolves to a promise; a computed must resolve now. ` +
424
- `Remove "$lazy", or call ${key}() from a handler instead of binding its value.`,
425
- );
426
- }
427
- let lazyBindings = lazySrcMap.get(srcPath);
428
- if (!lazyBindings) {
429
- lazyBindings = [];
430
- lazySrcMap.set(srcPath, lazyBindings);
431
- }
432
- lazyBindings.push({ binding: key, exportName: srcExportName(key, def) });
433
- continue;
434
- }
435
- let bindings = srcImportMap.get(srcPath);
436
- if (!bindings) {
437
- bindings = [];
438
- srcImportMap.set(srcPath, bindings);
439
- }
440
- bindings.push(srcImportBinding(key, def));
441
- }
442
- }
443
- for (const [srcPath, names] of srcImportMap) {
444
- // Bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/ bundle URL;
445
- // The site build bundles them after all documents compile (spec.md §12).
446
- const importPath = rewriteSrc ? rewriteSrc(srcPath) : srcPath;
447
- lines.push(`import { ${names.join(", ")} } from '${importPath}';`);
448
- }
366
+ const roles = classifyFunctionEntries(doc);
367
+ const srcImports = emitSrcImports(collectFunctionImports(defs, roles), rewriteSrc);
368
+ // Bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/ bundle URL;
369
+ // The site build bundles them after all documents compile (spec.md §12).
370
+ lines.push(...srcImports.imports);
449
371
 
450
372
  // `$prototype: "Request"` entries each get an auto-fetch effect in connectedCallback, plus the
451
373
  // Machinery to stop those effects again on disconnect. Both are emitted only when one exists, so
@@ -479,29 +401,9 @@ export function emitElementModule(
479
401
  lines.push(slotHelperSource());
480
402
  }
481
403
 
482
- /*
483
- * `$lazy` swaps the static import for a memoized dynamic one. A static import is a download, a
484
- * parse and an evaluate on every page that renders the component, whether or not anybody calls
485
- * the function: jxsuite.com's search client is 70 kB of MiniSearch fetched by every visitor, most
486
- * of whom never open search. The local binding keeps its name so every call site is unchanged;
487
- * what changes is that it now returns a promise.
488
- */
489
- let lazyIndex = 0;
490
- for (const [srcPath, entries] of lazySrcMap) {
491
- const importPath = rewriteSrc ? rewriteSrc(srcPath) : srcPath;
492
- const mod = `_jxLazy${lazyIndex}`;
493
- lazyIndex += 1;
494
- lines.push(
495
- `let ${mod};`,
496
- `const ${mod}Load = () => (${mod} ??= import('${importPath}'));`,
497
- ...entries.map(
498
- ({ binding, exportName }) =>
499
- `const ${binding} = (...args) => ${mod}Load().then((m) => m.${exportName}(...args));`,
500
- ),
501
- );
502
- }
503
-
404
+ // `$lazy` entries load on their first call instead of with the page (spec.md §5.3 4d).
504
405
  lines.push(
406
+ ...srcImports.loaders,
505
407
  "",
506
408
  `class ${className} extends HTMLElement {`,
507
409
  // One registry for every effect the element creates — render, dynamic host styles, Request
@@ -509,6 +411,7 @@ export function emitElementModule(
509
411
  // And a single list keeps every effect on the same lifecycle instead of leaking the ones nobody
510
412
  // Held a handle to.
511
413
  " #effects = [];",
414
+ " #rendered = false;",
512
415
  ...(shadow === null ? [] : [" #root = null;"]),
513
416
  "",
514
417
  // Constructor: build reactive state
@@ -533,20 +436,7 @@ export function emitElementModule(
533
436
  computedEntries.push([key, def]);
534
437
  }
535
438
  } else if (isFunctionDef(def)) {
536
- if (def.$src && !isString(def.body)) {
537
- // Bodyless `$src` entry — classify by document usage, not by an absent body. `body` and
538
- // `$src` are mutually exclusive (spec.md §5.3 4d), so this is the only shape a
539
- // Spec-conformant external Function takes.
540
- if (callableRefs.has(key) || LIFECYCLE_KEYS.has(key)) {
541
- functionEntries.push([key, def]);
542
- } else {
543
- computedEntries.push([key, def]);
544
- }
545
- } else if (isString(def.body) && bodyReturnsValue(def.body)) {
546
- computedEntries.push([key, def]);
547
- } else {
548
- functionEntries.push([key, def]);
549
- }
439
+ (roles.get(key) === "computed" ? computedEntries : functionEntries).push([key, def]);
550
440
  } else if (isString(def) && def.includes("${")) {
551
441
  /* A TEMPLATE STRING IS A COMPUTED, and the runtime has always said so — `runtime.ts`'s
552
442
  second state pass is `if (typeof def === "string" && def.includes("${")) state[key] =
@@ -607,45 +497,20 @@ export function emitElementModule(
607
497
  " };",
608
498
  );
609
499
  } else {
610
- const args = def.parameters ? paramNames(def.parameters) : (def.arguments ?? ["state"]);
611
- const paramList = args.join(", ");
612
- const body = isString(def.body) ? def.body : "";
613
- // Every call site invokes a state function as `(state, event)` — the template's
614
- // `s.fn(s, e)`, `onMount`, `onUnmount`. Declared names that already start with `state` line
615
- // Up positionally, so they are emitted directly. Any other declaration — including the
616
- // `"parameters": ["event"]` form that examples/components/{todo-app,fetch-demo}.json use — is
617
- // Mapped onto the arguments by name, the way the client target does it
618
- // (compile-client.ts), with `state` bound as the outer parameter so a body referencing bare
619
- // `state` resolves regardless of the declared arity.
620
- if (args[0] === "state") {
621
- if (def.$src) {
622
- // $src function — wrap imported function so it receives state
623
- lines.push(
624
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => ${key}(${paramList});`,
625
- );
626
- } else {
627
- lines.push(
628
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => {`,
629
- ` ${body}`,
630
- " };",
631
- );
632
- }
500
+ /* One calling convention (spec.md §4.3, §5.3 4d): every event site and lifecycle call invokes
501
+ `s.fn(s, e)`, so a string body is built with `state` first and its other declared names after
502
+ it, which binds `state` by name and the event by position. A `$src` entry is its import,
503
+ called as its call site calls it. Nothing here maps a name onto an argument. */
504
+ const target = refAccessor("this.state", escapeToken(key));
505
+ if (def.$src) {
506
+ lines.push(` ${target} = ${key};`);
633
507
  } else {
634
- const callArgs = args.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
635
- if (def.$src) {
636
- lines.push(
637
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => ${key}(${callArgs});`,
638
- );
639
- } else {
640
- lines.push(
641
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => {`,
642
- ` const _fn = (${paramList}) => {`,
643
- ` ${body}`,
644
- " };",
645
- ` return _fn(${callArgs});`,
646
- " };",
647
- );
648
- }
508
+ const body = isString(def.body) ? def.body : "";
509
+ lines.push(
510
+ ` ${target} = (${handlerParamNames(def).join(", ")}) => {`,
511
+ ` ${body}`,
512
+ " };",
513
+ );
649
514
  }
650
515
  }
651
516
  }
@@ -859,8 +724,19 @@ export function emitElementModule(
859
724
  * `data-jx-prerendered` goes and before the clear: a prerendered instance's children are its
860
725
  * markup, and capture recovers what the prerender placed from its brackets instead.
861
726
  */
727
+ /*
728
+ * Everything from here to the render effect happens to an instance ONCE. `connectedCallback` runs
729
+ * again each time the element is put back in a document (a list reordered with `append`, a panel
730
+ * moved between containers), and `disconnectedCallback` only stopped the effects: the tree lit
731
+ * drew is still there, and so is the part lit cached on the container for it. Clearing the
732
+ * container a second time removed the nodes that part still points at, so the render that
733
+ * followed updated a detached tree and the element stayed empty for good. A second capture is
734
+ * wrong for its own reason: by then the host's children are the component's own render, not
735
+ * what the author slotted.
736
+ */
737
+ lines.push(" const _first = !this.#rendered;", " this.#rendered = true;");
862
738
  if (hasSlot) {
863
- lines.push(` const _slotted = ${SLOT_CAPTURE_HELPER}(this);`);
739
+ lines.push(` const _slotted = _first ? ${SLOT_CAPTURE_HELPER}(this) : null;`);
864
740
  }
865
741
  lines.push(
866
742
  " if (this.hasAttribute('data-jx-prerendered')) {",
@@ -876,7 +752,7 @@ export function emitElementModule(
876
752
  * `require-trusted-types-for 'script'`, and this one is emitted into every light-DOM element
877
753
  * module a site ships.
878
754
  */
879
- " this.replaceChildren();",
755
+ " if (_first) this.replaceChildren();",
880
756
  " this.#effects.push(effect(() => render(this.template(), this)));",
881
757
  );
882
758
  } else {
@@ -895,15 +771,17 @@ export function emitElementModule(
895
771
  */
896
772
  lines.push(
897
773
  " const _root = this.#renderRoot();",
898
- " for (const _n of [..._root.childNodes]) {",
899
- " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
774
+ " if (_first) {",
775
+ " for (const _n of [..._root.childNodes]) {",
776
+ " if (!(_n.nodeType === 1 && _n.tagName === 'LINK')) _n.remove();",
777
+ " }",
900
778
  " }",
901
779
  " this.#effects.push(effect(() => render(this.template(), _root)));",
902
780
  );
903
781
  }
904
782
  if (hasSlot) {
905
783
  // Once, after the first render: a slot a later render draws stays literal (spec.md §8.5).
906
- lines.push(` ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
784
+ lines.push(` if (_first) ${SLOT_DISTRIBUTE_HELPER}(this, _slotted);`);
907
785
  }
908
786
  lines.push(
909
787
  // Lifecycle: onMount (spec §16.4) — same microtask contract as the runtime
@@ -1213,6 +1091,7 @@ ${no}
1213
1091
  if (!key.startsWith("on") || key === "observedAttributes") {
1214
1092
  continue;
1215
1093
  }
1094
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1216
1095
  const eventName = key.slice(2).toLowerCase();
1217
1096
  if (isBoundRef(val)) {
1218
1097
  parts.push(
@@ -1412,6 +1291,7 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1412
1291
  if (!key.startsWith("on")) {
1413
1292
  continue;
1414
1293
  }
1294
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1415
1295
  const eventName = key.slice(2).toLowerCase();
1416
1296
  if (isRef(val)) {
1417
1297
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${refToExpr(val.$ref)}(s, e); }}"`);
@@ -1421,6 +1301,9 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1421
1301
  statePrefix: "s",
1422
1302
  });
1423
1303
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${compiled}; }}"`);
1304
+ } else if (isFunctionDef(val)) {
1305
+ // A map root binds an inline handler as any other element does, with the iteration published.
1306
+ parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${inlineHandlerBody(val)} }}"`);
1424
1307
  }
1425
1308
  }
1426
1309
 
@@ -1573,15 +1456,12 @@ function inlineHandlerBody(def: JxFunctionDef) {
1573
1456
  });
1574
1457
  }
1575
1458
  const body = isString(def.body) ? def.body : "";
1576
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
1577
- if (declared.length > 0) {
1578
- // The call site supplies only `(e)`, so map the declared names onto the arguments the handler
1579
- // Actually has — `state` to the `s` alias, anything else to the event. Binding by name means the
1580
- // Body needs no textual rewriting, and a declared `event` stops silently resolving to the
1581
- // Deprecated `window.event` global (any other declared name threw ReferenceError outright).
1582
- const args = declared.map((name: string) => (name === "state" ? "s" : "e")).join(", ");
1583
- // The newline ends a last-line comment before the brace does.
1584
- return `((${declared.join(", ")}) => { ${body}\n})(${args});`;
1459
+ if (declaresParameters(def)) {
1460
+ /* The same list every tier builds a body with, called `(s, e)` like any other handler: `state`
1461
+ binds by name, the first other declared name is the event, and a declared `event` stops
1462
+ silently resolving to the deprecated `window.event` global. The newline ends a last-line
1463
+ comment before the brace does. */
1464
+ return `((${handlerParamNames(def).join(", ")}) => { ${body}\n})(s, e);`;
1585
1465
  }
1586
1466
  return `${rewriteState(body, "s", { bare: true })}\n`;
1587
1467
  }
@@ -123,12 +123,15 @@ export function compileSiteServer(
123
123
  */
124
124
  const localeBlock = localeNegotiationMiddleware(i18n);
125
125
 
126
+ const gateBlock =
127
+ entries.length === 0 && mounts.length === 0 ? "" : buildRequestGate(base, baseUrl);
128
+
126
129
  return `// Generated by @jxsuite/compiler — do not edit manually
127
130
  import { Hono } from 'hono'
128
131
  ${imports}${mountBlock.imports}
129
132
 
130
133
  const app = new Hono()
131
- ${localeBlock}${mountBlock.routes}${routes}
134
+ ${localeBlock}${gateBlock}${mountBlock.routes}${routes}
132
135
  ${adapterBlock}
133
136
  export default app
134
137
  `;
@@ -176,15 +179,59 @@ function buildMountBlock(mounts: SiteMountSpec[], connectors: SiteConnectorSpec[
176
179
  return { imports: `\n${importLines.join("\n")}`, routes: `${lines.join("\n")}\n` };
177
180
  }
178
181
 
182
+ /** The subtree every extension mount lives under (`extension-registry.ts` enforces it). */
183
+ const JX_ROUTE_ROOT = "/_jx";
184
+
185
+ /**
186
+ * Emit the request gate: middleware in front of every server function and extension mount
187
+ * (compiler.md §6.4), registered before them so a refused request never reaches a handler.
188
+ *
189
+ * It reads Fetch Metadata the way the dev server's gate does (`packages/server/src/net-guard.ts`),
190
+ * with one difference: a navigation is let through whatever its method, because an identity
191
+ * provider answering with `response_mode=form_post` is a cross-site POST navigation to the auth
192
+ * mount. A form a hostile page submits arrives the same way, and is refused one layer down: every
193
+ * route that takes a body requires `application/json`, which no HTML form can send.
194
+ *
195
+ * @param {string} base - The deployment base
196
+ * @param {string} baseUrl - The server-function prefix, already under the base
197
+ * @returns {string}
198
+ */
199
+ function buildRequestGate(base: string, baseUrl: string): string {
200
+ const root = withBase(base, JX_ROUTE_ROOT);
201
+ const prefixes = baseUrl === root || baseUrl.startsWith(`${root}/`) ? [root] : [root, baseUrl];
202
+ const uses = prefixes.map((prefix) => `app.use('${prefix}/*', jxGate)`).join("\n");
203
+ return `// Request gate (specs/compiler.md §6.4): another site may link here, never call here.
204
+ const jxGate = async (c, next) => {
205
+ const site = c.req.header('sec-fetch-site')
206
+ const foreign = site !== undefined && site !== 'same-origin' && site !== 'none'
207
+ if (foreign && c.req.header('sec-fetch-mode') !== 'navigate') {
208
+ return c.json({ ok: false, error: 'Cross-site request refused' }, 403, {
209
+ 'Cache-Control': 'no-store',
210
+ 'X-Content-Type-Options': 'nosniff',
211
+ })
212
+ }
213
+ await next()
214
+ c.header('X-Content-Type-Options', 'nosniff')
215
+ c.header('Cross-Origin-Resource-Policy', 'same-origin')
216
+ if (!c.res.headers.has('Cache-Control')) c.header('Cache-Control', 'no-store')
217
+ }
218
+ ${uses}
219
+ `;
220
+ }
221
+
179
222
  /** @param {string} exportName @param {string} baseUrl */
180
223
  function buildRoute(exportName: string, baseUrl: string) {
181
224
  return `
182
225
  app.post('${baseUrl}/${exportName}', async (c) => {
226
+ if (!/^application\\/([\\w.-]+\\+)?json\\b/i.test(c.req.header('content-type') ?? '')) {
227
+ return c.json({ ok: false, error: 'Expected an application/json body' }, 415)
228
+ }
183
229
  const args = await c.req.json().catch(() => ({}))
184
230
  try {
185
231
  return c.json((await ${exportName}(args, c.env)) ?? null)
186
232
  } catch (e) {
187
- return c.json({ ok: false, error: e?.message ?? 'Server error' }, 500)
233
+ console.error('jx: server function ${exportName} threw:', e)
234
+ return c.json({ ok: false, error: 'Server error' }, 500)
188
235
  }
189
236
  })`;
190
237
  }