@jxsuite/compiler 8.5.0 → 8.6.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.6.0",
4
4
  "description": "Jx static HTML compiler, island detector, and site builder",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -52,11 +52,11 @@
52
52
  "upgrade": "bun update --latest && bun install"
53
53
  },
54
54
  "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",
55
+ "@jxsuite/create": "^1.8.0",
56
+ "@jxsuite/erase": "^0.2.0",
57
+ "@jxsuite/runtime": "^6.3.0",
58
+ "@jxsuite/schema": "^5.6.0",
59
+ "@jxsuite/site": "^2.6.0",
60
60
  "@vue/reactivity": "3.5.44",
61
61
  "esbuild": "^0.28.2",
62
62
  "lit-html": "^3.3.3",
@@ -64,8 +64,8 @@
64
64
  },
65
65
  "devDependencies": {
66
66
  "@happy-dom/global-registrator": "^21.0.4",
67
- "@jxsuite/connector": "^0.8.7",
68
- "@jxsuite/parser": "^4.3.3",
67
+ "@jxsuite/connector": "^0.8.8",
68
+ "@jxsuite/parser": "^4.3.4",
69
69
  "@jxsuite/test-support": "^0.0.0",
70
70
  "@types/mdast": "^4.0.4"
71
71
  }
package/src/shared.ts CHANGED
@@ -6,6 +6,11 @@
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";
9
14
  import {
10
15
  COLOR_SCHEME_ATTR,
11
16
  COLOR_SCHEME_STORAGE_KEY,
@@ -28,7 +33,6 @@ import { compileOperandSource, evaluateExpression, isMutating } from "@jxsuite/r
28
33
  import { runStatements } from "@jxsuite/runtime/statements";
29
34
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
30
35
  import {
31
- bodyReturnsValue,
32
36
  childrenContainArray,
33
37
  hasStructuredBody,
34
38
  isExpressionDef,
@@ -47,7 +51,6 @@ import {
47
51
  isString,
48
52
  isTagExpression,
49
53
  isTemplateString,
50
- paramNames,
51
54
  tagNameCandidates,
52
55
  maskCode,
53
56
  } from "@jxsuite/schema/guards";
@@ -718,6 +721,27 @@ function collectAssignedStateKeys(node: JxDocumentValue | undefined, into: Set<s
718
721
  }
719
722
  }
720
723
 
724
+ /**
725
+ * Refuse a Function declaration that names both a `body` and a `$src` (spec.md §5.3 4d). The pair
726
+ * has no meaning: each tier used to keep a different half, so a document that built in one target
727
+ * did something else in another. Every place the compiler lowers a Function declaration calls this
728
+ * first, so no target lets the pair through, and `where` names the declaration for the build
729
+ * error.
730
+ *
731
+ * @param where What the declaration is, for the message: `state entry "save"`.
732
+ * @param def The value found there; anything but a Function declaration is left alone.
733
+ */
734
+ export function refuseBodyWithSrc(
735
+ where: string,
736
+ def: JxDocumentValue | JxStateDefinition | undefined,
737
+ ): void {
738
+ if (isFunctionDef(def) && declaresBodyAndSrc(def)) {
739
+ throw new Error(
740
+ `${where} declares both "body" and "$src"; they are mutually exclusive (spec.md §5.3 4d). Keep one.`,
741
+ );
742
+ }
743
+ }
744
+
721
745
  /**
722
746
  * @param {Record<string, JxStateDefinition>} [defs]
723
747
  * @param {JxScope | null} [parentScope]
@@ -757,6 +781,9 @@ export function buildInitialScope(
757
781
  }
758
782
  }
759
783
 
784
+ // The same verdict every other tier reads (spec.md §5.3 4b, 4d).
785
+ const roles = classifyFunctionEntries({ state: defs });
786
+
760
787
  for (const [key, def] of Object.entries(defs)) {
761
788
  if (!isNonNullObject(def) || Array.isArray(def)) {
762
789
  setOwnScopeValue(scope, key, cloneValue(def));
@@ -780,7 +807,7 @@ export function buildInitialScope(
780
807
  // Template-string entries are deferred to a third pass: whether one is resolvable depends on the
781
808
  // Runtime-only marks the loop below adds, and key order must not decide the answer.
782
809
  const templateDefs: [string, string][] = [];
783
- // Computed (`bodyReturnsValue`) entries are deferred for the same reason. A computed is stored in
810
+ // Entries the classifier calls computed are deferred for the same reason. A computed is stored in
784
811
  // The scope as its already-evaluated *result*, so a template reading it sees an ordinary string
785
812
  // And prerender bakes it — destroying the binding rather than merely staling it (issue #124).
786
813
  const computedBodies: [string, string][] = [];
@@ -820,6 +847,7 @@ export function buildInitialScope(
820
847
  continue;
821
848
  }
822
849
  if (isFunctionDef(def)) {
850
+ refuseBodyWithSrc(`state entry "${key}"`, def);
823
851
  if (hasStructuredBody(def)) {
824
852
  // Structured body (spec §20): a side-effecting handler in the build-time scope. Build-time
825
853
  // Code may call it bare, so the scope it runs against falls back to this one.
@@ -828,27 +856,19 @@ export function buildInitialScope(
828
856
  void runStatements(body, s ?? scope, event ?? null);
829
857
  });
830
858
  } else if (isString(def.body)) {
831
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
832
859
  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 (
860
+ // One parameter list in every tier (spec.md §5.3 4d): `state` first, then the other declared
861
+ // Names in order, so a call site's `(state, event)` binds by position.
862
+ /* SAFETY: `new Function` returns an ordinary function of exactly those parameters; a call
863
+ never checks its arguments, and what the body returns is one more scope member. */
864
+ const fn = new Function(...handlerParamNames(def), body) as (
843
865
  ...args: (JxScope | Event | undefined)[]
844
866
  ) => 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));
867
+ if (roles.get(key) === "computed") {
868
+ defineLazyScopeValue(scope, key, () => fn(scope));
849
869
  computedBodies.push([key, body]);
850
870
  } else {
851
- setOwnScopeValue(scope, key, invoke);
871
+ setOwnScopeValue(scope, key, fn);
852
872
  }
853
873
  } else {
854
874
  // Bodyless `$src` Function — the real implementation is only loaded in the browser, so this
@@ -9,9 +9,13 @@
9
9
  * in every project, because deciding not to optimize an image says nothing about when to fetch it.
10
10
  * The **variant** pass (`images.optimize`) is the expensive half and is the one the master switch
11
11
  * turns off.
12
+ *
13
+ * A third, cheap pass runs on every image too: a picture whose own file names a **focal point**
14
+ * (studio.md §22.6, an IPTC Image Region read by `@jxsuite/site/xmp-packet`) is given it as its
15
+ * `object-position`, unless the author set one, so any `object-fit` crop keeps that point in view.
12
16
  */
13
17
 
14
- import { existsSync } from "node:fs";
18
+ import { existsSync, readFileSync, statSync } from "node:fs";
15
19
  import { basename, extname, resolve } from "node:path";
16
20
  import {
17
21
  buildSrcset,
@@ -25,6 +29,8 @@ import { imgLoadingAttrs } from "./img-loading.ts";
25
29
  import { resolveAssetUrl } from "@jxsuite/schema/asset-paths";
26
30
  import { isNodeObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
27
31
  import { errorMessage } from "@jxsuite/schema/parse";
32
+ import { extractXmp, xmpFormatOf } from "@jxsuite/site/xmp-containers";
33
+ import { readMediaRecord } from "@jxsuite/site/xmp-packet";
28
34
 
29
35
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
30
36
  import type { ImageConfig, ImageManifest, ImageVariant } from "./image-optimizer.ts";
@@ -234,6 +240,78 @@ function resolveImagePath(src: string, projectRoot: string, mounts?: readonly As
234
240
  return resolve(projectRoot, src);
235
241
  }
236
242
 
243
+ /** Focal points already read, keyed by the file's path, modified time and size. */
244
+ const focusCache = new Map<string, string | null>();
245
+
246
+ /** A fraction as a CSS percentage, to one decimal place. */
247
+ function percent(fraction: number): string {
248
+ return `${Math.round(fraction * 1000) / 10}%`;
249
+ }
250
+
251
+ /**
252
+ * The `object-position` a picture's own focal point asks for, or `null` when the file names none,
253
+ * cannot hold one, or cannot be read. A file whose metadata does not parse is a picture, not a
254
+ * broken build: it is drawn as it was before it had a focal point.
255
+ */
256
+ function focusPosition(absolute: string): string | null {
257
+ const format = xmpFormatOf(absolute);
258
+ if (format === null) {
259
+ return null;
260
+ }
261
+ let stamp: string;
262
+ try {
263
+ const stat = statSync(absolute);
264
+ stamp = `${absolute}|${stat.mtimeMs}|${stat.size}`;
265
+ } catch {
266
+ return null;
267
+ }
268
+ const cached = focusCache.get(stamp);
269
+ if (cached !== undefined) {
270
+ return cached;
271
+ }
272
+ let position: string | null = null;
273
+ try {
274
+ const bytes = new Uint8Array(readFileSync(absolute));
275
+ const { focus } = readMediaRecord(extractXmp(bytes, format));
276
+ position = focus === null ? null : `${percent(focus.x)} ${percent(focus.y)}`;
277
+ } catch {
278
+ position = null;
279
+ }
280
+ focusCache.set(stamp, position);
281
+ return position;
282
+ }
283
+
284
+ /**
285
+ * Give an `<img>` its file's focal point as `object-position`. The author's own `objectPosition`
286
+ * wins, a style written as something other than an object is left alone, and a bound, remote or
287
+ * inline `src` names no file to read.
288
+ */
289
+ function applyFocalPoint(
290
+ node: JxMutableNode | JxDocument,
291
+ src: JxAttributeValue | undefined,
292
+ projectRoot: string,
293
+ mounts: readonly AssetMount[],
294
+ ): void {
295
+ if (!isString(src) || src === "" || src.includes("${")) {
296
+ return;
297
+ }
298
+ if (EXTERNAL_PREFIXES.some((prefix) => src.startsWith(prefix))) {
299
+ return;
300
+ }
301
+ const { style } = node;
302
+ if (style !== undefined && !isNonNullObject(style)) {
303
+ return;
304
+ }
305
+ if (style?.objectPosition !== undefined) {
306
+ return;
307
+ }
308
+ const [path = ""] = src.split(/[?#]/);
309
+ const position = focusPosition(resolveImagePath(path, projectRoot, mounts));
310
+ if (position !== null) {
311
+ node.style = { ...style, objectPosition: position };
312
+ }
313
+ }
314
+
237
315
  /**
238
316
  * Transform image nodes in a Jx document tree.
239
317
  *
@@ -576,6 +654,7 @@ async function transformImgNode(
576
654
  attrs.src = node.src;
577
655
  delete node.src;
578
656
  }
657
+ applyFocalPoint(node, attrs.src, projectRoot, mounts);
579
658
 
580
659
  const variants = config.optimize
581
660
  ? await resolveVariants(
@@ -11,9 +11,15 @@
11
11
  * state + computed signals), bind (DOM getters), on (event handlers), hydrate()
12
12
  */
13
13
 
14
+ import {
15
+ classifyFunctionEntries,
16
+ declaresParameters,
17
+ handlerParamNames,
18
+ } from "@jxsuite/schema/function-role";
14
19
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
15
20
  import {
16
21
  ATTR_HELPER,
22
+ refuseBodyWithSrc,
17
23
  attrHelperSource,
18
24
  booleanAttrValue,
19
25
  DEFAULT_LIT_HTML_SRC,
@@ -42,7 +48,6 @@ import {
42
48
  templateValueSource,
43
49
  } from "../shared.ts";
44
50
  import {
45
- bodyReturnsValue,
46
51
  hasStructuredBody,
47
52
  isBoolean,
48
53
  isExpandedSignal,
@@ -56,7 +61,6 @@ import {
56
61
  isServerFnDef,
57
62
  isString,
58
63
  isTagExpression,
59
- paramNames,
60
64
  tagNameCandidates,
61
65
  } from "@jxsuite/schema/guards";
62
66
  import type { CompileContext } from "../shared.ts";
@@ -87,7 +91,8 @@ type RepeaterSlot = Omit<JxMappedArray, "items"> & { items?: JxMappedArray["item
87
91
 
88
92
  /** A compiled event handler entry: parameter names + function body. */
89
93
  interface HandlerDef {
90
- args?: string[] | undefined;
94
+ /** The parameters the body is built with: `state` first, then the event under some name. */
95
+ args: string[];
91
96
  body?: string | undefined;
92
97
  }
93
98
 
@@ -132,6 +137,8 @@ export function compileClient(
132
137
  } = opts;
133
138
 
134
139
  const context = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {});
140
+ // One verdict per Function entry, from the document (spec.md §5.3 4b, 4d).
141
+ const roles = classifyFunctionEntries(raw);
135
142
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
136
143
 
137
144
  // Collectors for bindings and handlers
@@ -184,7 +191,6 @@ export function compileClient(
184
191
 
185
192
  // $prototype: "Function"
186
193
  if (isFunctionDef(def)) {
187
- const args = def.parameters ? paramNames(def.parameters) : def.arguments;
188
194
  const { body } = def;
189
195
  if (Array.isArray(body)) {
190
196
  // Structured body (spec §20) → an event handler compiled from statements.
@@ -205,14 +211,22 @@ export function compileClient(
205
211
  }
206
212
  names.add(srcImportBinding(key, def));
207
213
 
208
- // $src functions always produce computed entries (they return values)
209
- computedEntries.push([key, `() => { return ${key}(state); }`]);
210
- } else if (isString(body) && bodyReturnsValue(body)) {
214
+ if (roles.get(key) === "computed") {
215
+ // Only read, never called: its return value is what the page uses.
216
+ computedEntries.push([key, `() => { return ${key}(state); }`]);
217
+ } else {
218
+ /* Used as a callable: `state[key]` is the import, for a template or `call` site, and
219
+ `on[key]` adapts it for an event binding, which calls it `(state, event)` whatever it
220
+ declares (spec.md §4.3, §5.3 4d), as the interpreter does. */
221
+ initBlocks.push(`state[${JSON.stringify(key)}] = ${key};`);
222
+ onEntries.push([key, { args: ["state", "event"], body: `return ${key}(state, event);` }]);
223
+ }
224
+ } else if (isString(body) && roles.get(key) === "computed") {
211
225
  // Body contains return → computed
212
226
  computedEntries.push([key, `() => { ${body} }`]);
213
227
  } else {
214
228
  // No return → event handler
215
- onEntries.push([key, { args: args ?? ["state"], body }]);
229
+ onEntries.push([key, { args: handlerParamNames(def), body }]);
216
230
  }
217
231
  continue;
218
232
  }
@@ -428,6 +442,7 @@ function buildClientNode(
428
442
  if (!prop.startsWith("on") || prop === "observedAttributes") {
429
443
  continue;
430
444
  }
445
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
431
446
  const eventName = prop.slice(2).toLowerCase();
432
447
  if (isRefObject(val)) {
433
448
  const key = refToBindingKey(val.$ref);
@@ -447,9 +462,7 @@ function buildClientNode(
447
462
  body: compileStatements(body, { eventParam: "e", statePrefix: "state" }),
448
463
  }
449
464
  : {
450
- args: val.parameters
451
- ? paramNames(val.parameters)
452
- : (val.arguments ?? ["state", "event"]),
465
+ args: declaresParameters(val) ? handlerParamNames(val) : ["state", "event"],
453
466
  body,
454
467
  },
455
468
  );
@@ -760,6 +773,7 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
760
773
  if (!prop.startsWith("on") || prop === "observedAttributes") {
761
774
  continue;
762
775
  }
776
+ refuseBodyWithSrc(`inline "${prop}" handler`, val);
763
777
  const eventName = prop.slice(2).toLowerCase();
764
778
  if (isRefObject(val)) {
765
779
  const key = refToBindingKey(val.$ref);
@@ -773,9 +787,14 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
773
787
  * or absent. An absent one (a `$src` function) reaches replaceAll and throws, as it always
774
788
  * has: a repeater handler is emitted inline and needs inline source.
775
789
  */
776
- const body = mapRefsToLit(val.body as string);
777
- // The newline ends a last-line comment before the brace does.
778
- attrs += ` @${eventName}=\${(e) => { ${body}\n}}`;
790
+ const body = bareMapRefsToLit(val.body as string);
791
+ /* Published like the sibling branches, so a body reads `state.$map`; with a declaration the
792
+ body is built with the same list every tier uses and called `(state, e)`. The newline ends a
793
+ last-line comment before the brace does. */
794
+ const call = declaresParameters(val)
795
+ ? `((${handlerParamNames(val).join(", ")}) => { ${body}\n})(state, e);`
796
+ : `${body}\n`;
797
+ attrs += ` @${eventName}=\${(e) => { state.$map = { item, index }; ${call}}}`;
779
798
  } else if (isNonNullObject(val) && "$expression" in val) {
780
799
  /*
781
800
  * SAFETY: an `on*` member carrying `$expression` is a Shape 5 expression entry, whose
@@ -878,6 +897,17 @@ function mapRefsToLit(str: string) {
878
897
  return str.replaceAll("$map.", "");
879
898
  }
880
899
 
900
+ /**
901
+ * {@link mapRefsToLit} for a handler body, which also publishes `state.$map` before it runs: a bare
902
+ * `$map.item` becomes the callback's `item`, and a `state.$map.item` the author wrote is left to
903
+ * read the published context, rather than losing its `$map.` to `state.item`.
904
+ *
905
+ * @param body The handler body source.
906
+ */
907
+ function bareMapRefsToLit(body: string): string {
908
+ return body.replaceAll(/(?<![\w$.])\$map\./gu, "");
909
+ }
910
+
881
911
  // ─── JS module generation ─────────────────────────────────────────────────────
882
912
 
883
913
  /**
@@ -1003,12 +1033,9 @@ function emitClientModule(
1003
1033
  if (onEntries.length > 0) {
1004
1034
  lines.push("const on = {");
1005
1035
  for (const [key, def] of onEntries) {
1006
- const argNames = def.args ?? ["state"];
1007
- const callArgs = argNames.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
1036
+ // Every entry's list starts with `state`, and the event is the one argument after it.
1008
1037
  lines.push(
1009
- ` ${objectKey(key)}: (e) => { const fn = (${argNames.join(", ")}) => { ${def.body}\n}; fn(${
1010
- callArgs
1011
- }); },`,
1038
+ ` ${objectKey(key)}: (e) => { const fn = (${def.args.join(", ")}) => { ${def.body}\n}; fn(state, e); },`,
1012
1039
  );
1013
1040
  }
1014
1041
  lines.push("};");