@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/compiler",
3
- "version": "8.5.0",
3
+ "version": "8.7.0",
4
4
  "description": "Jx static HTML compiler, island detector, and site builder",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,7 +37,9 @@
37
37
  "./site-loader": "./src/site/site-loader.ts",
38
38
  "./types": "./src/types.ts",
39
39
  "./db-push": "./src/site/db-push.ts",
40
- "./bundler": "./src/site/bundler.ts"
40
+ "./document-scripts": "./src/site/document-scripts.ts",
41
+ "./bundler": "./src/site/bundler.ts",
42
+ "./bun-plugin": "./src/site/bun-plugin.ts"
41
43
  },
42
44
  "publishConfig": {
43
45
  "provenance": true
@@ -52,11 +54,11 @@
52
54
  "upgrade": "bun update --latest && bun install"
53
55
  },
54
56
  "dependencies": {
55
- "@jxsuite/create": "^1.7.0",
56
- "@jxsuite/erase": "^0.1.0",
57
- "@jxsuite/runtime": "^6.2.2",
58
- "@jxsuite/schema": "^5.5.0",
59
- "@jxsuite/site": "^2.5.1",
57
+ "@jxsuite/create": "^1.8.1",
58
+ "@jxsuite/erase": "^0.3.0",
59
+ "@jxsuite/runtime": "^7.0.0",
60
+ "@jxsuite/schema": "^6.0.0",
61
+ "@jxsuite/site": "^2.7.0",
60
62
  "@vue/reactivity": "3.5.44",
61
63
  "esbuild": "^0.28.2",
62
64
  "lit-html": "^3.3.3",
@@ -64,8 +66,8 @@
64
66
  },
65
67
  "devDependencies": {
66
68
  "@happy-dom/global-registrator": "^21.0.4",
67
- "@jxsuite/connector": "^0.8.7",
68
- "@jxsuite/parser": "^4.3.3",
69
+ "@jxsuite/connector": "^0.8.9",
70
+ "@jxsuite/parser": "^5.0.0",
69
71
  "@jxsuite/test-support": "^0.0.0",
70
72
  "@types/mdast": "^4.0.4"
71
73
  }
package/src/cli.ts CHANGED
@@ -30,6 +30,7 @@ Commands:
30
30
  schema [root] Generate project.schema.json + document.schema.json from project.json#/extensions
31
31
  validate [root] Validate the whole project: project.json, documents, classes, and fragments
32
32
  convert <paths…> Move documents and the project file between .json and .jxn, repairing references
33
+ format [paths…] Format .jxn files and the code they hold (requires @jxsuite/server and Bun)
33
34
  db push [root] Sync the data section's tables to their connections (additive-only)
34
35
 
35
36
  Options:
@@ -41,15 +42,21 @@ Options:
41
42
  --connection db push: restrict to one connection name
42
43
  --strict validate: fail on an overlay or accessibility lint error, not only a schema error
43
44
  --to <format> convert: jxn or json
44
- --drop-comments convert: convert a .jxn file to .json even though it has comments`);
45
+ --drop-comments convert: convert a .jxn file to .json even though it has comments
46
+ --check format: write nothing, and fail when a file would change`);
45
47
  process.exit(0);
46
48
  }
47
49
 
48
- // Its positionals are paths and not a project root, so it does not join the split below.
49
- if (command === "convert") {
50
+ // Their positionals are paths and not a project root, so they do not join the split below.
51
+ if (command === "convert" || command === "format") {
50
52
  try {
51
- const { runConvert } = await import("./site/convert-command.ts");
52
- runConvert(process.cwd(), args.slice(1));
53
+ if (command === "convert") {
54
+ const { runConvert } = await import("./site/convert-command.ts");
55
+ runConvert(process.cwd(), args.slice(1));
56
+ } else {
57
+ const { runFormat } = await import("./site/format-command.ts");
58
+ runFormat(process.cwd(), args.slice(1));
59
+ }
53
60
  } catch (error) {
54
61
  console.error(errorMessage(error));
55
62
  process.exit(1);
package/src/shared.ts CHANGED
@@ -6,6 +6,12 @@
6
6
  * compilation targets (static, client, element, server).
7
7
  */
8
8
 
9
+ import {
10
+ classifyFunctionEntries,
11
+ declaresBodyAndSrc,
12
+ handlerParamNames,
13
+ } from "@jxsuite/schema/function-role";
14
+ import type { FunctionRole } from "@jxsuite/schema/function-role";
9
15
  import {
10
16
  COLOR_SCHEME_ATTR,
11
17
  COLOR_SCHEME_STORAGE_KEY,
@@ -24,11 +30,17 @@ import {
24
30
  splitSelectorList,
25
31
  } from "@jxsuite/runtime";
26
32
  import { spliceNestingSelector } from "@jxsuite/runtime/css";
27
- import { compileOperandSource, evaluateExpression, isMutating } from "@jxsuite/runtime/expression";
33
+ import {
34
+ compileOperandSource,
35
+ evaluateExpression,
36
+ formulaScopeReads,
37
+ inheritableFormulas,
38
+ isMutating,
39
+ isPureNamedFormula,
40
+ } from "@jxsuite/runtime/expression";
28
41
  import { runStatements } from "@jxsuite/runtime/statements";
29
42
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
30
43
  import {
31
- bodyReturnsValue,
32
44
  childrenContainArray,
33
45
  hasStructuredBody,
34
46
  isExpressionDef,
@@ -47,7 +59,6 @@ import {
47
59
  isString,
48
60
  isTagExpression,
49
61
  isTemplateString,
50
- paramNames,
51
62
  tagNameCandidates,
52
63
  maskCode,
53
64
  } from "@jxsuite/schema/guards";
@@ -59,8 +70,10 @@ import type { JxScope } from "@jxsuite/runtime/types";
59
70
  import type {
60
71
  CemParameter,
61
72
  JsonValue,
73
+ JxDocument,
62
74
  JxDocumentValue,
63
75
  JxElement,
76
+ JxExpressionDef,
64
77
  JxMappedArray,
65
78
  JxMutableNode,
66
79
  JxPrototypeDef,
@@ -391,6 +404,117 @@ export function isClassJsonSrc(src?: unknown): src is string {
391
404
  return typeof src === "string" && src.endsWith(".class.json");
392
405
  }
393
406
 
407
+ /** White space between tokens of a body, as JSON serializes it: itself, or an escaped line end. */
408
+ const BODY_SPACE = String.raw`(?:\s|\\[nrt])*`;
409
+
410
+ /**
411
+ * `state` handed on whole in a body: assigned or destructured (`const { fmt } = state;`) or spread
412
+ * (`{ ...state }`). Whatever takes it can read any entry by a name the scan below never sees, so
413
+ * such a fragment counts as reading every key. What must follow it (punctuation, a line end, the
414
+ * end of the body) keeps prose out (`a = state of mind`), and `state.x` and `state[…]` are member
415
+ * reads, judged by name.
416
+ */
417
+ const STATE_HANDED_ON = new RegExp(
418
+ String.raw`(?:=|\.\.\.)${BODY_SPACE}state[ \t]*(?:[;,)}\]"]|\\[nr])`,
419
+ );
420
+
421
+ /**
422
+ * Whether a serialized document fragment still reads a given state key: as a `${state.key}`
423
+ * template, a `state.key` or `state?.key` inside a handler or computed body, a literal-keyed
424
+ * `state["key"]`, or a `#/state/key` $ref. A fragment that hands `state` on whole
425
+ * ({@link STATE_HANDED_ON}) reads every key.
426
+ *
427
+ * What it cannot see is a key that is computed (`state[name]`), and a read made by code outside the
428
+ * document (a `$src` module), which callers account for themselves.
429
+ *
430
+ * @param {string} haystack - JSON-serialized document fragment
431
+ * @param {string} key
432
+ * @returns {boolean}
433
+ */
434
+ export function referencesStateKey(haystack: string, key: string): boolean {
435
+ const escaped = key.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
436
+ /* The name must end where the key does. `(?![\w$])` and not `\b`: a key may end in `$`, after
437
+ which `\b` sees no boundary before `(` and a read of `state.fmt$(…)` went unseen. */
438
+ const member = String.raw`\bstate${BODY_SPACE}\??\.${BODY_SPACE}${escaped}(?![\w$])`;
439
+ /* A quote inside a body is `\"` once the document is serialized; `'` and a backtick are bare. */
440
+ const quote = "(?:\\\\\"|['`])";
441
+ const bracket = String.raw`\bstate${BODY_SPACE}(?:\?\.)?\[${BODY_SPACE}${quote}${escaped}${quote}`;
442
+ const pointer = String.raw`#/state/${escaped}(?=["/])`;
443
+ return (
444
+ new RegExp(`${member}|${bracket}|${pointer}`).test(haystack) || STATE_HANDED_ON.test(haystack)
445
+ );
446
+ }
447
+
448
+ /* The predicate lives beside the expression engine, where the runtime reads it too: a component
449
+ inherits the same formulas in the interpreter as in a build (spec.md §13.4). */
450
+ export { isPureNamedFormula } from "@jxsuite/runtime/expression";
451
+
452
+ /**
453
+ * A component document as a project compiles it (spec.md §13.4): the project's closed pure named
454
+ * formulas the component reads, under its own `state`.
455
+ *
456
+ * Inheritance is from the PROJECT, never from the page an instance stands on, so a definition is
457
+ * the same document on every page and its one emitted module serves them all. Only what the
458
+ * component reads is merged, so a component that calls no project formula is byte-for-byte what it
459
+ * was, and each formula it does call is written once, into that component's own module:
460
+ *
461
+ * - A formula is read when the document names it ({@link referencesStateKey}), or when another merged
462
+ * formula's body calls it.
463
+ * - An entry the component declares is never replaced. That includes one a merged formula calls: the
464
+ * call resolves in the component's scope, so it reaches the component's entry.
465
+ * - While the component declares a `$src` Function every inheritable formula is merged, because that
466
+ * module's reads cannot be seen (the rule compiler.md §3 states for a page).
467
+ *
468
+ * @param {T} doc - The component definition
469
+ * @param {Record<string, JxStateDefinition> | null | undefined} projectState - `project.json`
470
+ * `state`
471
+ * @returns {T} `doc` itself when it inherits nothing
472
+ */
473
+ export function inheritProjectFormulas<T extends JxElement | JxDocument>(
474
+ doc: T,
475
+ projectState: Record<string, JxStateDefinition> | null | undefined,
476
+ ): T {
477
+ const available = inheritableFormulas(projectState);
478
+ const own = doc.state ?? {};
479
+ const names = Object.keys(available).filter((key) => !(key in own));
480
+ if (names.length === 0) {
481
+ return doc;
482
+ }
483
+ const text = JSON.stringify(doc);
484
+ const opaque = Object.values(own).some(
485
+ (entry) => isNonNullObject(entry) && !Array.isArray(entry) && isString(entry.$src),
486
+ );
487
+ const taken = new Set(names.filter((key) => opaque || referencesStateKey(text, key)));
488
+ // What a taken formula calls is taken with it. A Set visits members added while it is walked.
489
+ for (const key of taken) {
490
+ /* SAFETY: every member of `available` passed `isPureNamedFormula`, an expression entry. */
491
+ for (const read of formulaScopeReads(available[key] as JxExpressionDef)) {
492
+ if (!(read in own)) {
493
+ taken.add(read);
494
+ }
495
+ }
496
+ }
497
+ if (taken.size === 0) {
498
+ return doc;
499
+ }
500
+ const inherited = Object.fromEntries(
501
+ names.filter((k) => taken.has(k)).map((k) => [k, available[k]!]),
502
+ );
503
+ return { ...doc, state: { ...inherited, ...own } };
504
+ }
505
+
506
+ /**
507
+ * A node as the text a read of its pure named formulas is looked for in: the whole node, without
508
+ * the formulas themselves. One formula calling another is not a read that reaches the browser
509
+ * unless something else reads the caller, and the caller is then found on its own.
510
+ */
511
+ function withoutPureFormulas(def: JxElement | JxMutableNode): string {
512
+ const state = Object.fromEntries(
513
+ Object.entries(def.state ?? {}).filter(([, entry]) => !isPureNamedFormula(entry)),
514
+ );
515
+ return JSON.stringify({ ...def, state });
516
+ }
517
+
394
518
  /**
395
519
  * Determine whether a node (or any of its descendants) requires client-side JavaScript.
396
520
  *
@@ -403,6 +527,8 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
403
527
  }
404
528
 
405
529
  if (def.state) {
530
+ /** Built on the first formula met, since most nodes with state declare none. */
531
+ let readers: string | undefined;
406
532
  for (const [k, d] of Object.entries(def.state)) {
407
533
  // Skip injected context (read-only, not reactive)
408
534
  if (k === "$site" || k === "$page") {
@@ -415,6 +541,16 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
415
541
  if (d.timing === "compiler") {
416
542
  continue;
417
543
  }
544
+ /* A pure named formula is a function, not state: it makes the node dynamic only when
545
+ something on the node still reads it (compiler.md §3). A page whose every call was
546
+ resolved at build time keeps no reader, so the declaration alone ships nothing. */
547
+ if (isPureNamedFormula(d)) {
548
+ readers ??= withoutPureFormulas(def);
549
+ if (referencesStateKey(readers, k)) {
550
+ return true;
551
+ }
552
+ continue;
553
+ }
418
554
  if (d.$prototype) {
419
555
  return true;
420
556
  }
@@ -594,6 +730,19 @@ function runtimeOnlyKeysOf(scope: JxScope): Set<string> | undefined {
594
730
  return (scope as { [RUNTIME_ONLY_KEYS]?: Set<string> })[RUNTIME_ONLY_KEYS];
595
731
  }
596
732
 
733
+ /**
734
+ * Whether prerender holds a state entry to be runtime-only: its real value exists only after
735
+ * hydration, or some handler in the document writes it (see `buildInitialScope`). A scope built
736
+ * anywhere else has no marks and answers false.
737
+ *
738
+ * @param {JxScope} scope - The build-time scope, or a row scope whose prototype chain reaches it
739
+ * @param {string} key - A top-level state key
740
+ * @returns {boolean}
741
+ */
742
+ export function isRuntimeOnlyStateKey(scope: JxScope, key: string): boolean {
743
+ return runtimeOnlyKeysOf(scope)?.has(key) ?? false;
744
+ }
745
+
597
746
  /**
598
747
  * `state.x = …`, `state.x += …`, `state.x++` — every form a string handler body can use to write a
599
748
  * state entry. `===`/`!==`/`<=`/`>=` are excluded by the `(?!=)` guard and by the operator set.
@@ -718,6 +867,129 @@ function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<s
718
867
  }
719
868
  }
720
869
 
870
+ /**
871
+ * Refuse a Function declaration that names both a `body` and a `$src` (spec.md §5.3 4d). The pair
872
+ * has no meaning: each tier used to keep a different half, so a document that built in one target
873
+ * did something else in another. Every place the compiler lowers a Function declaration calls this
874
+ * first, so no target lets the pair through, and `where` names the declaration for the build
875
+ * error.
876
+ *
877
+ * @param where What the declaration is, for the message: `state entry "save"`.
878
+ * @param def The value found there; anything but a Function declaration is left alone.
879
+ */
880
+ export function refuseBodyWithSrc(
881
+ where: string,
882
+ def: JxDocumentValue | JxStateDefinition | undefined,
883
+ ): void {
884
+ if (isFunctionDef(def) && declaresBodyAndSrc(def)) {
885
+ throw new Error(
886
+ `${where} declares both "body" and "$src"; they are mutually exclusive (spec.md §5.3 4d). Keep one.`,
887
+ );
888
+ }
889
+ }
890
+
891
+ /** What a document's `$src` Function entries import, split by when the module loads. */
892
+ export interface SrcImports {
893
+ /** Statically imported modules → the `import { … }` clause members each one supplies. */
894
+ eager: Map<string, Set<string>>;
895
+ /** `$lazy` modules → the (export, local binding) pairs each one supplies. */
896
+ lazy: Map<string, { binding: string; exportName: string }[]>;
897
+ }
898
+
899
+ /** The module text for a document's `$src` imports: static `import` lines, then lazy loaders. */
900
+ export interface SrcImportText {
901
+ imports: string[];
902
+ loaders: string[];
903
+ }
904
+
905
+ /**
906
+ * The `$src` modules a document's Function entries import (spec.md §5.3 4d), for every compiled
907
+ * target. A `$lazy` entry is split off from the eager imports, because its module loads on the
908
+ * first call rather than with the page. One reader of `$lazy` is the point: two emitters of one
909
+ * feature is how the client target came to ignore it and ship a static import.
910
+ *
911
+ * Refuses a lazy entry the document uses as a computed value: a computed reads its value
912
+ * synchronously and a lazy binding can only hand back a promise, so binding it would render
913
+ * `[object Promise]`.
914
+ *
915
+ * @param defs The document's `state`.
916
+ * @param roles The document's verdicts from `classifyFunctionEntries`.
917
+ */
918
+ export function collectFunctionImports(
919
+ defs: Record<string, JxStateDefinition>,
920
+ roles: ReadonlyMap<string, FunctionRole>,
921
+ ): SrcImports {
922
+ const imports: SrcImports = { eager: new Map(), lazy: new Map() };
923
+ for (const [key, def] of Object.entries(defs)) {
924
+ refuseBodyWithSrc(`state entry "${key}"`, def);
925
+ if (!isFunctionDef(def) || !def.$src) {
926
+ continue;
927
+ }
928
+ if (def.$lazy === true) {
929
+ if (roles.get(key) === "computed") {
930
+ throw new Error(
931
+ `"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
932
+ `A lazily loaded function resolves to a promise; a computed must resolve now. ` +
933
+ `Remove "$lazy", or call ${key}() from a handler instead of binding its value.`,
934
+ );
935
+ }
936
+ let bindings = imports.lazy.get(def.$src);
937
+ if (!bindings) {
938
+ bindings = [];
939
+ imports.lazy.set(def.$src, bindings);
940
+ }
941
+ bindings.push({ binding: key, exportName: srcExportName(key, def) });
942
+ continue;
943
+ }
944
+ let names = imports.eager.get(def.$src);
945
+ if (!names) {
946
+ names = new Set();
947
+ imports.eager.set(def.$src, names);
948
+ }
949
+ names.add(srcImportBinding(key, def));
950
+ }
951
+ return imports;
952
+ }
953
+
954
+ /**
955
+ * The module text for {@link collectFunctionImports}: the static `import` lines, and the memoized
956
+ * dynamic loaders for `$lazy` entries. A static import is a download, a parse and an evaluate on
957
+ * every page that renders the component, whether or not anybody calls the function: jxsuite.com's
958
+ * search client is 70 kB of MiniSearch fetched by every visitor, most of whom never open search.
959
+ * The local binding keeps its name so every call site is unchanged; what changes is that it now
960
+ * returns a promise.
961
+ *
962
+ * @param imports What the document imports.
963
+ * @param rewriteSrc Maps a bundleable specifier (`npm:…`, `./relative`) to its `/assets/` bundle
964
+ * URL; the site build bundles them after all documents compile (spec.md §12).
965
+ */
966
+ export function emitSrcImports(
967
+ imports: SrcImports,
968
+ rewriteSrc?: (specifier: string) => string,
969
+ ): SrcImportText {
970
+ const importLines: string[] = [];
971
+ for (const [src, names] of imports.eager) {
972
+ importLines.push(
973
+ `import { ${[...names].join(", ")} } from '${rewriteSrc ? rewriteSrc(src) : src}';`,
974
+ );
975
+ }
976
+ const loaders: string[] = [];
977
+ let index = 0;
978
+ for (const [src, entries] of imports.lazy) {
979
+ const mod = `_jxLazy${index}`;
980
+ index += 1;
981
+ loaders.push(
982
+ `let ${mod};`,
983
+ `const ${mod}Load = () => (${mod} ??= import('${rewriteSrc ? rewriteSrc(src) : src}'));`,
984
+ ...entries.map(
985
+ ({ binding, exportName }) =>
986
+ `const ${binding} = (...args) => ${mod}Load().then((m) => m.${exportName}(...args));`,
987
+ ),
988
+ );
989
+ }
990
+ return { imports: importLines, loaders };
991
+ }
992
+
721
993
  /**
722
994
  * @param {Record<string, JxStateDefinition>} [defs]
723
995
  * @param {JxScope | null} [parentScope]
@@ -757,6 +1029,9 @@ export function buildInitialScope(
757
1029
  }
758
1030
  }
759
1031
 
1032
+ // The same verdict every other tier reads (spec.md §5.3 4b, 4d).
1033
+ const roles = classifyFunctionEntries({ state: defs });
1034
+
760
1035
  for (const [key, def] of Object.entries(defs)) {
761
1036
  if (!isNonNullObject(def) || Array.isArray(def)) {
762
1037
  setOwnScopeValue(scope, key, cloneValue(def));
@@ -780,7 +1055,7 @@ export function buildInitialScope(
780
1055
  // Template-string entries are deferred to a third pass: whether one is resolvable depends on the
781
1056
  // Runtime-only marks the loop below adds, and key order must not decide the answer.
782
1057
  const templateDefs: [string, string][] = [];
783
- // Computed (`bodyReturnsValue`) entries are deferred for the same reason. A computed is stored in
1058
+ // Entries the classifier calls computed are deferred for the same reason. A computed is stored in
784
1059
  // The scope as its already-evaluated *result*, so a template reading it sees an ordinary string
785
1060
  // And prerender bakes it — destroying the binding rather than merely staling it (issue #124).
786
1061
  const computedBodies: [string, string][] = [];
@@ -820,6 +1095,7 @@ export function buildInitialScope(
820
1095
  continue;
821
1096
  }
822
1097
  if (isFunctionDef(def)) {
1098
+ refuseBodyWithSrc(`state entry "${key}"`, def);
823
1099
  if (hasStructuredBody(def)) {
824
1100
  // Structured body (spec §20): a side-effecting handler in the build-time scope. Build-time
825
1101
  // Code may call it bare, so the scope it runs against falls back to this one.
@@ -828,27 +1104,19 @@ export function buildInitialScope(
828
1104
  void runStatements(body, s ?? scope, event ?? null);
829
1105
  });
830
1106
  } else if (isString(def.body)) {
831
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
832
1107
  const { body } = def;
833
- // Declared names bind by name, not by position (spec.md §5.3 4d): a parameter literally
834
- // Named `state` receives the scope, anything else receives the event. `state` is prepended
835
- // When undeclared so a body may always reference it. Unconditionally prepending it instead —
836
- // The older behaviour here — produced a duplicate parameter for the `["state", "event"]`
837
- // Form that examples/components/task-manager.json uses, leaving `state` undefined.
838
- const params = declared.includes("state") ? declared : ["state", ...declared];
839
- /* SAFETY: `new Function` returns an ordinary function of exactly `params`; `invoke` below is
840
- its only caller and passes the scope or the event in each position, and what the body
841
- returns is one more scope member. */
842
- const fn = new Function(...params, body) as (
1108
+ // One parameter list in every tier (spec.md §5.3 4d): `state` first, then the other declared
1109
+ // Names in order, so a call site's `(state, event)` binds by position.
1110
+ /* SAFETY: `new Function` returns an ordinary function of exactly those parameters; a call
1111
+ never checks its arguments, and what the body returns is one more scope member. */
1112
+ const fn = new Function(...handlerParamNames(def), body) as (
843
1113
  ...args: (JxScope | Event | undefined)[]
844
1114
  ) => JxScope[string];
845
- const invoke = (state: JxScope, event?: Event) =>
846
- fn(...params.map((name) => (name === "state" ? state : event)));
847
- if (bodyReturnsValue(body)) {
848
- defineLazyScopeValue(scope, key, () => invoke(scope));
1115
+ if (roles.get(key) === "computed") {
1116
+ defineLazyScopeValue(scope, key, () => fn(scope));
849
1117
  computedBodies.push([key, body]);
850
1118
  } else {
851
- setOwnScopeValue(scope, key, invoke);
1119
+ setOwnScopeValue(scope, key, fn);
852
1120
  }
853
1121
  } else {
854
1122
  // Bodyless `$src` Function — the real implementation is only loaded in the browser, so this
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Lets Bun import a `.jxn` document as the module it carries (spec.md §23.2), so a document's
3
+ * functions can be unit tested where they are written.
4
+ *
5
+ * Importing this file registers the plugin. A project names it in `bunfig.toml`:
6
+ *
7
+ * [test];
8
+ * preload = ["@jxsuite/compiler/bun-plugin"];
9
+ *
10
+ * After that `import { bump } from "./components/counter.jxn"` is the document's client module,
11
+ * exactly as the build's bundler resolves the same import, and `./pages/index.jxn?server` is its
12
+ * server module. The query is a test's spelling only: nothing a browser runs can import a server
13
+ * module, and the build refuses one that tries.
14
+ *
15
+ * A module's own relative imports resolve from the document's directory, because the module is
16
+ * loaded at the document's path.
17
+ *
18
+ * @docs framework/concepts/functions
19
+ */
20
+
21
+ import { readFileSync } from "node:fs";
22
+ import type { BunPlugin } from "bun";
23
+ import type { ScriptSide } from "@jxsuite/schema/document-scripts";
24
+ import { parseNativeDocument } from "@jxsuite/schema/jxn";
25
+
26
+ /** What an import of a document's server module ends with. */
27
+ const SERVER_QUERY = "?server";
28
+
29
+ /** Matches an import of a `.jxn` document, with or without the server query. */
30
+ const JXN_MODULE = /\.jxn(?:\?server)?$/;
31
+
32
+ /**
33
+ * The text of one of a document's modules.
34
+ *
35
+ * @param modulePath The document's absolute path, ending in `?server` for its server module.
36
+ * @throws {Error} When the document carries no module for that side.
37
+ */
38
+ export function documentModuleText(modulePath: string): string {
39
+ const side: ScriptSide = modulePath.endsWith(SERVER_QUERY) ? "server" : "client";
40
+ const documentPath = side === "server" ? modulePath.slice(0, -SERVER_QUERY.length) : modulePath;
41
+ const text = parseNativeDocument(readFileSync(documentPath, "utf8"), documentPath).$script?.[
42
+ side
43
+ ];
44
+ if (text === undefined) {
45
+ throw new Error(`${documentPath} has no ${side} script, so there is nothing to import from it`);
46
+ }
47
+ return text;
48
+ }
49
+
50
+ /** The plugin itself, for a process that would rather register it than preload this file. */
51
+ export const documentScriptsPlugin: BunPlugin = {
52
+ name: "jx-document-scripts",
53
+ setup: (build) => {
54
+ build.onLoad({ filter: JXN_MODULE }, ({ path }) => ({
55
+ contents: documentModuleText(path),
56
+ loader: "ts",
57
+ }));
58
+ },
59
+ };
60
+
61
+ void Bun.plugin(documentScriptsPlugin);
@@ -38,8 +38,15 @@ function bunTarget(target: BundleTargetName): "browser" | "node" | "bun" {
38
38
  return target;
39
39
  }
40
40
 
41
- /** Bundle one file with `Bun.build` and return the output's text. */
42
- async function buildFile(entryPath: string, request: BackendBuild): Promise<string> {
41
+ /**
42
+ * Bundle one file with `Bun.build` and return the output's text. With `contents`, the file is the
43
+ * text given and nothing is read from `entryPath`.
44
+ */
45
+ async function buildFile(
46
+ entryPath: string,
47
+ request: BackendBuild,
48
+ contents?: string,
49
+ ): Promise<string> {
43
50
  const config: BuildConfig = {
44
51
  entrypoints: [entryPath],
45
52
  external: request.external,
@@ -55,6 +62,11 @@ async function buildFile(entryPath: string, request: BackendBuild): Promise<stri
55
62
  if (request.define) {
56
63
  config.define = request.define;
57
64
  }
65
+ if (contents !== undefined) {
66
+ // An in-memory file: Bun never asks a plugin to resolve an entry point, so a module that is not
67
+ // On disk can only be an entry this way.
68
+ config.files = { [entryPath]: contents };
69
+ }
58
70
  const result = await Bun.build(config);
59
71
  if (!result.success || result.outputs.length === 0) {
60
72
  const logs = result.logs.map(String).join("\n");
@@ -70,7 +82,7 @@ export async function build(request: BackendBuild): Promise<string> {
70
82
  }
71
83
  const { entry } = request;
72
84
  if ("path" in entry) {
73
- return buildFile(entry.path, request);
85
+ return buildFile(entry.path, request, entry.contents);
74
86
  }
75
87
  // Bun.build has no stdin input: write a transient entry in `resolveDir` so resolution matches
76
88
  // The stdin/resolveDir behaviour, and always remove it.
@@ -5,7 +5,7 @@
5
5
  import { createRequire } from "node:module";
6
6
  import { join } from "node:path";
7
7
  import type { BuildOptions } from "esbuild";
8
- import type { BackendBuild, BundleTargetName } from "./bundler-backend.ts";
8
+ import type { BackendBuild, BundlePlugin, BundleTargetName } from "./bundler-backend.ts";
9
9
 
10
10
  /** Which bundler this backend runs. */
11
11
  export function backendName(): "bun" | "esbuild" {
@@ -22,6 +22,26 @@ function esbuildPlatform(target: BundleTargetName): "browser" | "node" {
22
22
  return target === "node" || target === "bun" ? "node" : "browser";
23
23
  }
24
24
 
25
+ /** Escape a string for use as a literal inside a `RegExp`. */
26
+ function literalPattern(text: string): RegExp {
27
+ return new RegExp(`^${text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)}$`);
28
+ }
29
+
30
+ /**
31
+ * A plugin that makes `path` a module whose text is `contents`, whether or not a file is there.
32
+ * esbuild asks plugins to resolve an entry point, so answering for the one path is enough.
33
+ */
34
+ function inMemoryEntry(path: string, contents: string): BundlePlugin {
35
+ const filter = literalPattern(path);
36
+ return {
37
+ name: "jx-in-memory-entry",
38
+ setup: (plugin) => {
39
+ plugin.onResolve({ filter }, () => ({ path }));
40
+ plugin.onLoad({ filter }, () => ({ contents, loader: "ts" }));
41
+ },
42
+ };
43
+ }
44
+
25
45
  /** Bundle to one ESM module and return its text. Throws with esbuild's diagnostics on failure. */
26
46
  export async function build(request: BackendBuild): Promise<string> {
27
47
  // Dynamic import keeps esbuild (a native-binary dependency) off the load path until a bundle runs.
@@ -45,6 +65,9 @@ export async function build(request: BackendBuild): Promise<string> {
45
65
  }
46
66
  if ("path" in entry) {
47
67
  options.entryPoints = [entry.path];
68
+ if (entry.contents !== undefined) {
69
+ options.plugins = [inMemoryEntry(entry.path, entry.contents), ...request.plugins];
70
+ }
48
71
  } else {
49
72
  options.stdin = {
50
73
  contents: entry.source,