@jxsuite/compiler 11.1.2 → 11.2.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/dist/cli.js +254 -206
- package/dist/compiler.js +183 -135
- package/package.json +10 -18
- package/src/cli.ts +25 -3
- package/src/compiler.ts +13 -0
- package/src/shared.ts +521 -64
- package/src/site/asset-mounts.ts +2 -5
- package/src/site/build-time-request.ts +144 -0
- package/src/site/component-set.ts +117 -6
- package/src/site/db-push.ts +22 -2
- package/src/site/format-host.ts +2 -1
- package/src/site/i18n.ts +10 -137
- package/src/site/layout-resolver.ts +20 -3
- package/src/site/pages-discovery.ts +90 -4
- package/src/site/preview-server.ts +39 -10
- package/src/site/project-sections.ts +34 -2
- package/src/site/prototype-resolver.ts +74 -19
- package/src/site/schema-command.ts +4 -0
- package/src/site/section-push.ts +132 -0
- package/src/site/site-build.ts +353 -139
- package/src/site/validate-command.ts +146 -12
- package/src/site/well-known.ts +2 -2
- package/src/switch-cases.ts +176 -0
- package/src/targets/compile-client.ts +324 -72
- package/src/targets/compile-element.ts +165 -17
- package/src/targets/compile-static.ts +28 -4
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
* Produces clean HTML with `data-bind` marker attributes and a small JS bootstrapper using
|
|
5
5
|
* vue/reactivity's `effect` + `computed`.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
* "Array") use lit-html for efficient rendering.
|
|
7
|
+
* Function entries the classifier calls computed become computed() on state. Mapped arrays
|
|
8
|
+
* ($prototype: "Array") use lit-html for efficient rendering.
|
|
9
9
|
*
|
|
10
10
|
* Output pattern: HTML: pre-rendered with data-bind, :prop="key", @event="key" JS: state (reactive
|
|
11
11
|
* state + computed signals), bind (DOM getters), on (event handlers), hydrate()
|
|
@@ -25,10 +25,16 @@ import {
|
|
|
25
25
|
ATTR_HELPER,
|
|
26
26
|
refuseBodyWithSrc,
|
|
27
27
|
attrHelperSource,
|
|
28
|
+
caseLoaderSource,
|
|
29
|
+
formulaGuardSource,
|
|
30
|
+
hasCallableEntries,
|
|
31
|
+
cookieHelperSource,
|
|
32
|
+
emitCookieBinding,
|
|
28
33
|
collectClientClasses,
|
|
29
34
|
emitExternalClassResolution,
|
|
30
35
|
externalClassHelperSource,
|
|
31
36
|
isClientExternalClass,
|
|
37
|
+
refuseBuiltInCompilerTiming,
|
|
32
38
|
booleanAttrValue,
|
|
33
39
|
DEFAULT_LIT_HTML_SRC,
|
|
34
40
|
DEFAULT_REACTIVITY_SRC,
|
|
@@ -40,12 +46,13 @@ import {
|
|
|
40
46
|
contentPropertyText,
|
|
41
47
|
createCompileContext,
|
|
42
48
|
emitFormulaFn,
|
|
49
|
+
emitStatementsFn,
|
|
43
50
|
emitRequestFetch,
|
|
44
51
|
emitServerCall,
|
|
45
52
|
escapeHtml,
|
|
46
53
|
isMutating,
|
|
47
54
|
isRefObject,
|
|
48
|
-
|
|
55
|
+
isPureTypeDef,
|
|
49
56
|
isTemplateString,
|
|
50
57
|
KEYED_LIST_HELPER,
|
|
51
58
|
KEYED_LIST_IMPORTS,
|
|
@@ -60,7 +67,11 @@ import {
|
|
|
60
67
|
LIT_PART_GUARD,
|
|
61
68
|
PREFORMATTED_TAGS,
|
|
62
69
|
pureSchemeOf,
|
|
70
|
+
fillSlotted,
|
|
71
|
+
slottedChildren,
|
|
63
72
|
isExpandedInstance,
|
|
73
|
+
isLiteralNode,
|
|
74
|
+
renderStaticNode,
|
|
64
75
|
resolveStaticValue,
|
|
65
76
|
serverCallHelperSource,
|
|
66
77
|
collectFunctionImports,
|
|
@@ -125,8 +136,11 @@ interface ClientCounter {
|
|
|
125
136
|
/** Lit-rendered regions (`_listN`, `_childrenN`). */
|
|
126
137
|
l: number;
|
|
127
138
|
m: number;
|
|
139
|
+
/** Component-instance prop bindings (`_pN`): one per bound `$props` entry (spec.md §13.3). */
|
|
140
|
+
p: number;
|
|
128
141
|
/** Whether any region is rendered through lit-html. */
|
|
129
142
|
needsLit: boolean;
|
|
143
|
+
needsFormulaGuard: boolean;
|
|
130
144
|
/** Bound style declarations (`_sN`). */
|
|
131
145
|
s: number;
|
|
132
146
|
/** `$switch` regions (`_swN`). */
|
|
@@ -148,8 +162,51 @@ interface HandlerDef {
|
|
|
148
162
|
/** The parameters the body is built with: `state` first, then the event under some name. */
|
|
149
163
|
args: string[];
|
|
150
164
|
body?: string | undefined;
|
|
165
|
+
/** A structured body (spec §20.2): emitted as an `async` function so a `call` can suspend it. */
|
|
166
|
+
async?: boolean;
|
|
151
167
|
}
|
|
152
168
|
|
|
169
|
+
/** What {@link compileClient} reads. */
|
|
170
|
+
export interface CompileClientOptions {
|
|
171
|
+
title?: string;
|
|
172
|
+
reactivitySrc?: string;
|
|
173
|
+
litHtmlSrc?: string;
|
|
174
|
+
/** The build's whole import map, written in place of the two sources above (compiler.md §12). */
|
|
175
|
+
runtimeImports?: Record<string, string> | undefined;
|
|
176
|
+
modulePath?: string;
|
|
177
|
+
projectStyle?: JxStyle | null;
|
|
178
|
+
prePaintScheme?: boolean;
|
|
179
|
+
rewriteSrc?: (specifier: string) => string;
|
|
180
|
+
/**
|
|
181
|
+
* The route prefix a `timing: "server"` entry posts to, deployment base included
|
|
182
|
+
* (`serverRoutePrefix`). The call is written into the module, and no later pass rewrites a
|
|
183
|
+
* module, so the base has to be known when it is compiled.
|
|
184
|
+
*/
|
|
185
|
+
serverBaseUrl?: string;
|
|
186
|
+
/**
|
|
187
|
+
* The URL a `timing: "client"` external class's module is served at (compiler.md §3, §12). Only a
|
|
188
|
+
* site build has one; without it such an entry is a compile error.
|
|
189
|
+
*/
|
|
190
|
+
resolveClass?: (def: JxPrototypeDef) => string;
|
|
191
|
+
/**
|
|
192
|
+
* Generated case tag to the module specifier (relative to this page module) that defines it. A
|
|
193
|
+
* `$switch` case lowered to one of these tags loads its module the first time its key is active
|
|
194
|
+
* (spec.md §14.1). Only a site build has any.
|
|
195
|
+
*/
|
|
196
|
+
caseModules?: ReadonlyMap<string, string>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The external-case state of the compilation in progress. The emitters are synchronous and reach a
|
|
201
|
+
* `$switch` through helpers that take no options, so it is held here, set on entry and restored in
|
|
202
|
+
* `finally`.
|
|
203
|
+
*/
|
|
204
|
+
let caseState: {
|
|
205
|
+
modules: ReadonlyMap<string, string>;
|
|
206
|
+
needsLoader: boolean;
|
|
207
|
+
warned: Set<string>;
|
|
208
|
+
} | null = null;
|
|
209
|
+
|
|
153
210
|
/**
|
|
154
211
|
* Compile a Jx document to pre-rendered HTML + reactive JS module.
|
|
155
212
|
*
|
|
@@ -164,31 +221,17 @@ interface HandlerDef {
|
|
|
164
221
|
* }} opts
|
|
165
222
|
* @returns {{ html: string; files: { path: string; content: string }[] }}
|
|
166
223
|
*/
|
|
167
|
-
export function compileClient(
|
|
168
|
-
|
|
169
|
-
opts:
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
rewriteSrc?: (specifier: string) => string;
|
|
179
|
-
/**
|
|
180
|
-
* The route prefix a `timing: "server"` entry posts to, deployment base included
|
|
181
|
-
* (`serverRoutePrefix`). The call is written into the module, and no later pass rewrites a
|
|
182
|
-
* module, so the base has to be known when it is compiled.
|
|
183
|
-
*/
|
|
184
|
-
serverBaseUrl?: string;
|
|
185
|
-
/**
|
|
186
|
-
* The URL a `timing: "client"` external class's module is served at (compiler.md §3, §12). Only
|
|
187
|
-
* a site build has one; without it such an entry is a compile error.
|
|
188
|
-
*/
|
|
189
|
-
resolveClass?: (def: JxPrototypeDef) => string;
|
|
190
|
-
},
|
|
191
|
-
) {
|
|
224
|
+
export function compileClient(raw: JxDocument, opts: CompileClientOptions = {}) {
|
|
225
|
+
const previous = caseState;
|
|
226
|
+
caseState = { modules: opts.caseModules ?? new Map(), needsLoader: false, warned: new Set() };
|
|
227
|
+
try {
|
|
228
|
+
return compileClientDocument(raw, opts);
|
|
229
|
+
} finally {
|
|
230
|
+
caseState = previous;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function compileClientDocument(raw: JxDocument, opts: CompileClientOptions) {
|
|
192
235
|
const {
|
|
193
236
|
title = "Jx App",
|
|
194
237
|
reactivitySrc = DEFAULT_REACTIVITY_SRC,
|
|
@@ -207,7 +250,9 @@ export function compileClient(
|
|
|
207
250
|
h: 0,
|
|
208
251
|
l: 0,
|
|
209
252
|
m: 0,
|
|
253
|
+
needsFormulaGuard: hasCallableEntries(raw.state ?? {}),
|
|
210
254
|
needsLit: false,
|
|
255
|
+
p: 0,
|
|
211
256
|
s: 0,
|
|
212
257
|
sw: 0,
|
|
213
258
|
t: 0,
|
|
@@ -217,11 +262,14 @@ export function compileClient(
|
|
|
217
262
|
const handlers = new Map<string, HandlerDef>(); // Key → { body, args }
|
|
218
263
|
|
|
219
264
|
// Classify state entries into reactive state, computed, bind, on, and init blocks
|
|
265
|
+
let autoFetch = false;
|
|
220
266
|
const stateEntries: [string, JsonValue | undefined][] = []; // [key, initValue] → reactive({...})
|
|
221
267
|
const computedEntries: [string, string][] = []; // [key, bodyExpr] → state.key = computed(...)
|
|
222
268
|
const bindEntries: [string, string][] = []; // [key, bodyExpr] → bind = {...}
|
|
223
269
|
const onEntries: [string, HandlerDef][] = []; // [key, { args, body }] → on = {...}
|
|
224
270
|
const initBlocks: string[] = []; // Lines emitted after state for prototype init
|
|
271
|
+
const stateCallables = new Set<string>(); // String-body callables also assigned to `state[key]`
|
|
272
|
+
let needsCookie = false; // A Cookie entry makes the module carry the cookie helper
|
|
225
273
|
const serverCalls: string[] = []; // One block per `timing: "server"` entry, after the computed block
|
|
226
274
|
|
|
227
275
|
const defs = raw.state ?? {};
|
|
@@ -264,13 +312,17 @@ export function compileClient(
|
|
|
264
312
|
if (Array.isArray(body)) {
|
|
265
313
|
// Structured body (spec §20) → an event handler compiled from statements.
|
|
266
314
|
// With parameters, a positional callable like a named formula.
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
315
|
+
if (Array.isArray(def.parameters) && def.parameters.length > 0) {
|
|
316
|
+
// A callable has no event: it dispatches from the page's root element (spec.md §20.3).
|
|
317
|
+
const compiled = compileStatements(body, {
|
|
318
|
+
dispatchTarget: "document.body.firstElementChild",
|
|
319
|
+
eventParam: "e",
|
|
320
|
+
statePrefix: "state",
|
|
321
|
+
});
|
|
322
|
+
initBlocks.push(`state[${JSON.stringify(key)}] = ${emitStatementsFn(def, compiled)};`);
|
|
272
323
|
} else {
|
|
273
|
-
|
|
324
|
+
const compiled = compileStatements(body, { eventParam: "e", statePrefix: "state" });
|
|
325
|
+
onEntries.push([key, { args: ["state", "e"], async: true, body: compiled }]);
|
|
274
326
|
}
|
|
275
327
|
} else if (def.$src) {
|
|
276
328
|
if (roles.get(key) === "computed") {
|
|
@@ -287,14 +339,15 @@ export function compileClient(
|
|
|
287
339
|
// Body contains return → computed
|
|
288
340
|
computedEntries.push([key, `() => { ${body} }`]);
|
|
289
341
|
} else {
|
|
290
|
-
//
|
|
342
|
+
// A callable: `state[key]` for a template or `call` site, `on[key]` for an event binding.
|
|
343
|
+
stateCallables.add(key);
|
|
291
344
|
onEntries.push([key, { args: handlerParamNames(def), body }]);
|
|
292
345
|
}
|
|
293
346
|
continue;
|
|
294
347
|
}
|
|
295
348
|
|
|
296
349
|
// Pure schema-only type def → skip
|
|
297
|
-
if (
|
|
350
|
+
if (isPureTypeDef(def)) {
|
|
298
351
|
continue;
|
|
299
352
|
}
|
|
300
353
|
|
|
@@ -305,6 +358,7 @@ export function compileClient(
|
|
|
305
358
|
}
|
|
306
359
|
|
|
307
360
|
if (isPrototypeDef(def)) {
|
|
361
|
+
refuseBuiltInCompilerTiming(key, def);
|
|
308
362
|
// $prototype: "LocalStorage" / "SessionStorage"
|
|
309
363
|
if (def.$prototype === "LocalStorage" || def.$prototype === "SessionStorage") {
|
|
310
364
|
const storeName = def.$prototype === "LocalStorage" ? "localStorage" : "sessionStorage";
|
|
@@ -319,13 +373,17 @@ export function compileClient(
|
|
|
319
373
|
if (def.$prototype === "Request") {
|
|
320
374
|
stateEntries.push([key, null]);
|
|
321
375
|
initBlocks.push(emitRequestFetch(key, def));
|
|
376
|
+
if (!def.manual) {
|
|
377
|
+
autoFetch = true;
|
|
378
|
+
}
|
|
322
379
|
continue;
|
|
323
380
|
}
|
|
324
381
|
|
|
325
382
|
// $prototype: "Cookie"
|
|
326
383
|
if (def.$prototype === "Cookie") {
|
|
327
384
|
stateEntries.push([key, null]);
|
|
328
|
-
initBlocks.push(
|
|
385
|
+
initBlocks.push(emitCookieBinding(key, def));
|
|
386
|
+
needsCookie = true;
|
|
329
387
|
continue;
|
|
330
388
|
}
|
|
331
389
|
|
|
@@ -365,6 +423,18 @@ export function compileClient(
|
|
|
365
423
|
onEntries.push([key, def]);
|
|
366
424
|
}
|
|
367
425
|
}
|
|
426
|
+
/* A handler a `$props` value names has to be a function on `state`, where the page binding and a
|
|
427
|
+
row's `.prop=` read it (`state.<key>` was `undefined`). It is the element target's unbound
|
|
428
|
+
`(state, event)` shape. A key an earlier rule already put on `state` is assigned once. */
|
|
429
|
+
const propRefKeys = collectPropRefKeys(raw);
|
|
430
|
+
for (const [key, def] of onEntries) {
|
|
431
|
+
const target = `state[${JSON.stringify(key)}] =`;
|
|
432
|
+
if (propRefKeys.has(key) && !initBlocks.some((block) => block.startsWith(target))) {
|
|
433
|
+
initBlocks.push(
|
|
434
|
+
`${target} (state, e) => { const fn = ${def.async ? "async " : ""}(${def.args.join(", ")}) => { ${def.body ?? ""}\n}; return fn(state, e); };`,
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
368
438
|
|
|
369
439
|
// Generate the JS module
|
|
370
440
|
const srcImports = collectFunctionImports(defs, roles);
|
|
@@ -373,6 +443,7 @@ export function compileClient(
|
|
|
373
443
|
computedEntries,
|
|
374
444
|
bindEntries,
|
|
375
445
|
onEntries,
|
|
446
|
+
stateCallables,
|
|
376
447
|
initBlocks,
|
|
377
448
|
serverCalls,
|
|
378
449
|
srcImports,
|
|
@@ -381,6 +452,8 @@ export function compileClient(
|
|
|
381
452
|
opts.rewriteSrc,
|
|
382
453
|
clientClasses,
|
|
383
454
|
mappedArrayFeatures(raw),
|
|
455
|
+
autoFetch,
|
|
456
|
+
{ needsCookie },
|
|
384
457
|
);
|
|
385
458
|
|
|
386
459
|
// The page's import map: lit-html always, since compiled custom elements need it.
|
|
@@ -456,6 +529,11 @@ function buildClientNode(
|
|
|
456
529
|
return "";
|
|
457
530
|
}
|
|
458
531
|
|
|
532
|
+
// Spliced content is data (spec.md §8.4): written as static, escaped markup and bound to nothing.
|
|
533
|
+
if (isLiteralNode(def)) {
|
|
534
|
+
return renderStaticNode(def, context.scope, null, null, context.preformatted === true);
|
|
535
|
+
}
|
|
536
|
+
|
|
459
537
|
const nextContext = createCompileContext(
|
|
460
538
|
def,
|
|
461
539
|
context.scope,
|
|
@@ -521,6 +599,7 @@ function buildClientNode(
|
|
|
521
599
|
Array.isArray(body)
|
|
522
600
|
? {
|
|
523
601
|
args: ["state", "e"],
|
|
602
|
+
async: true,
|
|
524
603
|
body: compileStatements(body, { eventParam: "e", statePrefix: "state" }),
|
|
525
604
|
}
|
|
526
605
|
: {
|
|
@@ -632,6 +711,28 @@ function buildClientNode(
|
|
|
632
711
|
}
|
|
633
712
|
}
|
|
634
713
|
|
|
714
|
+
/* A component instance's `$props`: each is written onto the element as a property, when the
|
|
715
|
+
module hydrates and again whenever what it reads changes (spec.md §13.3). The property name
|
|
716
|
+
is the directive's value, because an attribute name folds case and cannot hold `-` or `.`. */
|
|
717
|
+
if (isString(def.tagName) && def.tagName.includes("-") && isNonNullObject(def.$props)) {
|
|
718
|
+
for (const [name, val] of Object.entries(def.$props)) {
|
|
719
|
+
if (name.startsWith("#")) {
|
|
720
|
+
continue;
|
|
721
|
+
}
|
|
722
|
+
const key = `_p${counter.p}`;
|
|
723
|
+
counter.p += 1;
|
|
724
|
+
if (isRefObject(val)) {
|
|
725
|
+
bindings.set(key, `() => ${mapRefToClientExpr(val.$ref)}`);
|
|
726
|
+
} else if (isTemplateString(val)) {
|
|
727
|
+
bindings.set(key, `() => \`${val}\``);
|
|
728
|
+
} else {
|
|
729
|
+
bindings.set(key, `() => (${JSON.stringify(val)})`);
|
|
730
|
+
}
|
|
731
|
+
bindAttrs.push(`:prop.${key}="${escapeHtml(name)}"`);
|
|
732
|
+
needsBind = true;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
635
736
|
// Build static attrs
|
|
636
737
|
const staticAttrs = buildAttrs(def, nextContext.scope);
|
|
637
738
|
const dataBindAttr = needsBind ? " data-bind" : "";
|
|
@@ -654,16 +755,10 @@ function buildClientNode(
|
|
|
654
755
|
const discriminant = isRefObject(source.$switch)
|
|
655
756
|
? stateRead(source.$switch.$ref)
|
|
656
757
|
: `\`${String(source.$switch)}\``;
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
.filter(([, caseDef]) => caseDef && !isRefObject(caseDef))
|
|
662
|
-
.map(
|
|
663
|
-
([key, caseDef]) =>
|
|
664
|
-
`${JSON.stringify(key)}: html\`${emitChildLit(caseDef, nextContext.preformatted)}\``,
|
|
665
|
-
);
|
|
666
|
-
bindings.set(swKey, `() => ({${caseEntries.join(", ")}})[String(${discriminant})] ?? html\`\``);
|
|
758
|
+
bindings.set(
|
|
759
|
+
swKey,
|
|
760
|
+
`() => ${emitSwitchLookup(source, discriminant, nextContext.preformatted)}`,
|
|
761
|
+
);
|
|
667
762
|
bindAttrs.push(`:render="${swKey}"`);
|
|
668
763
|
const bindAttrStrSwitch = ` ${bindAttrs.join(" ")}`;
|
|
669
764
|
return `<${tag}${staticAttrs} data-bind${bindAttrStrSwitch}></${tag}>`;
|
|
@@ -684,6 +779,16 @@ function buildClientNode(
|
|
|
684
779
|
? source.innerHTML
|
|
685
780
|
: resolveStaticValue(source.innerHTML, nextContext.scope);
|
|
686
781
|
inner = resolved == null ? source.innerHTML : String(resolved);
|
|
782
|
+
/* The children written inside a page-level instance are compiled here, in the page's scope, so
|
|
783
|
+
their bindings join the page's table (spec.md §15.2). */
|
|
784
|
+
const slotted = slottedChildren(source);
|
|
785
|
+
if (slotted) {
|
|
786
|
+
/* SAFETY: a slotted child is one the instance was written with, which `buildClientNode` reads
|
|
787
|
+
as it reads any child; a repeater among them is the same pseudo-element the tree holds. */
|
|
788
|
+
inner = fillSlotted(inner, slotted, (c) =>
|
|
789
|
+
buildClientNode(c as JxMutableNode, nextContext, bindings, handlers, counter),
|
|
790
|
+
);
|
|
791
|
+
}
|
|
687
792
|
} else if (contentText !== undefined) {
|
|
688
793
|
inner = contentText;
|
|
689
794
|
} else if (isMappedArray(source.children)) {
|
|
@@ -750,6 +855,63 @@ function buildClientNode(
|
|
|
750
855
|
return `<${tag}${staticAttrs}${dataBindAttr}${bindAttrStr}>${inner}</${tag}>`;
|
|
751
856
|
}
|
|
752
857
|
|
|
858
|
+
/**
|
|
859
|
+
* The lookup a `$switch` renders as: an object of lit templates keyed by case, indexed by the
|
|
860
|
+
* discriminant's string, with the empty template for a key no case holds (spec.md §14.1). The one
|
|
861
|
+
* emitter of it: the container's `:render` binding and a switch inside a lit region (a mapped row,
|
|
862
|
+
* another switch's case) both call it.
|
|
863
|
+
*
|
|
864
|
+
* @param {JxMutableNode} node - The element holding `$switch` and `cases`
|
|
865
|
+
* @param {string} discriminant - The expression the key is read from
|
|
866
|
+
* @param {boolean} preformatted - Whether the switch sits inside a `<pre>`
|
|
867
|
+
* @returns {string}
|
|
868
|
+
*/
|
|
869
|
+
function emitSwitchLookup(
|
|
870
|
+
node: JxMutableNode,
|
|
871
|
+
discriminant: string,
|
|
872
|
+
preformatted: boolean,
|
|
873
|
+
): string {
|
|
874
|
+
const templates: string[] = [];
|
|
875
|
+
const modules: string[] = [];
|
|
876
|
+
// Parsed JSON, so a case slot can hold `null` or a bare value the declared type leaves out.
|
|
877
|
+
for (const [key, caseDef] of Object.entries<JxMutableNode | JsonPrimitive>(node.cases ?? {})) {
|
|
878
|
+
if (!caseDef) {
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
if (isRefObject(caseDef)) {
|
|
882
|
+
// Only a site build compiles an external case, by lowering it to a registered tag first.
|
|
883
|
+
warnExternalCase(key, caseDef.$ref);
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
templates.push(`${JSON.stringify(key)}: html\`${emitChildLit(caseDef, preformatted)}\``);
|
|
887
|
+
const specifier =
|
|
888
|
+
isNonNullObject(caseDef) && isString(caseDef.tagName)
|
|
889
|
+
? caseState?.modules.get(caseDef.tagName)
|
|
890
|
+
: undefined;
|
|
891
|
+
if (specifier !== undefined) {
|
|
892
|
+
modules.push(`${JSON.stringify(key)}: ${JSON.stringify(specifier)}`);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
const lookup = `({${templates.join(", ")}})`;
|
|
896
|
+
if (modules.length > 0 && caseState) {
|
|
897
|
+
caseState.needsLoader = true;
|
|
898
|
+
return `_jxSwitch(${lookup}, {${modules.join(", ")}}, String(${discriminant})) ?? html\`\``;
|
|
899
|
+
}
|
|
900
|
+
return `${lookup}[String(${discriminant})] ?? html\`\``;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** Warn, once per compilation, that an external case reached a target outside a site build. */
|
|
904
|
+
function warnExternalCase(key: string, ref: string): void {
|
|
905
|
+
const id = `${key}\u0000${ref}`;
|
|
906
|
+
if (caseState && !caseState.warned.has(id)) {
|
|
907
|
+
caseState.warned.add(id);
|
|
908
|
+
console.warn(
|
|
909
|
+
`Jx $switch: case "${key}" (${ref}) is an external document, which only a site build ` +
|
|
910
|
+
`compiles; it renders an empty container.`,
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
753
915
|
// ─── Lit-html map template generation ─────────────────────────────────────────
|
|
754
916
|
|
|
755
917
|
/**
|
|
@@ -886,7 +1048,7 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
|
|
|
886
1048
|
attrs += ` @${eventName}=\${(e) => { state.$map = { item, index }; on.${key}(e); }}`;
|
|
887
1049
|
} else if (hasStructuredBody(val)) {
|
|
888
1050
|
const compiled = compileStatements(val.body, { eventParam: "e", statePrefix: "state" });
|
|
889
|
-
attrs += ` @${eventName}=\${(e) => { state.$map = { item, index }; ${compiled} }}`;
|
|
1051
|
+
attrs += ` @${eventName}=\${async (e) => { state.$map = { item, index }; ${compiled} }}`;
|
|
890
1052
|
} else if (isFunctionDef(val)) {
|
|
891
1053
|
/*
|
|
892
1054
|
* SAFETY: hasStructuredBody above took every statement-array body, so `body` is source text
|
|
@@ -949,7 +1111,13 @@ function emitLitMapTemplate(def: JxMutableNode | null | undefined, preformatted
|
|
|
949
1111
|
|
|
950
1112
|
// Inner content
|
|
951
1113
|
let inner = "";
|
|
952
|
-
if (def
|
|
1114
|
+
if (def.$switch) {
|
|
1115
|
+
// A switch in a lit region renders its lookup as the element's content, a template hole.
|
|
1116
|
+
const discriminant = isRefObject(def.$switch)
|
|
1117
|
+
? mapRefToClientExpr(def.$switch.$ref)
|
|
1118
|
+
: `\`${mapRefsToLit(String(def.$switch))}\``;
|
|
1119
|
+
inner = `\${${emitSwitchLookup(def, discriminant, inPre)}}`;
|
|
1120
|
+
} else if (def.textContent !== undefined) {
|
|
953
1121
|
const tc = String(def.textContent);
|
|
954
1122
|
if (isTemplateString(tc)) {
|
|
955
1123
|
inner = `${mapRefsToLit(tc)}${guard}`;
|
|
@@ -1105,6 +1273,8 @@ function bareMapRefsToLit(body: string): string {
|
|
|
1105
1273
|
* @param {[string, string][]} computedEntries
|
|
1106
1274
|
* @param {[string, string][]} bindEntries
|
|
1107
1275
|
* @param {[string, any][]} onEntries
|
|
1276
|
+
* @param {Set<string>} stateCallables Keys of callable string-body entries, assigned to `state`
|
|
1277
|
+
* before the init blocks; their `on` entry delegates to that function.
|
|
1108
1278
|
* @param {string[]} initBlocks
|
|
1109
1279
|
* @param {string[]} serverCalls
|
|
1110
1280
|
* @param {SrcImports} srcImports
|
|
@@ -1117,6 +1287,7 @@ function emitClientModule(
|
|
|
1117
1287
|
computedEntries: [string, string][],
|
|
1118
1288
|
bindEntries: [string, string][],
|
|
1119
1289
|
onEntries: [string, HandlerDef][],
|
|
1290
|
+
stateCallables: ReadonlySet<string>,
|
|
1120
1291
|
initBlocks: string[],
|
|
1121
1292
|
serverCalls: string[],
|
|
1122
1293
|
srcImports: SrcImports,
|
|
@@ -1125,6 +1296,8 @@ function emitClientModule(
|
|
|
1125
1296
|
rewriteSrc: ((specifier: string) => string) | undefined,
|
|
1126
1297
|
clientClasses: ClientClasses,
|
|
1127
1298
|
lists: MappedArrayFeatures,
|
|
1299
|
+
needsEffectCleanup: boolean,
|
|
1300
|
+
features: { needsCookie?: boolean } = {},
|
|
1128
1301
|
) {
|
|
1129
1302
|
const lines: string[] = [];
|
|
1130
1303
|
const { needsLit, textParts } = counter;
|
|
@@ -1141,6 +1314,9 @@ function emitClientModule(
|
|
|
1141
1314
|
if (lists.keyed) {
|
|
1142
1315
|
reactivityImports.push("stop", "shallowRef");
|
|
1143
1316
|
}
|
|
1317
|
+
if (needsEffectCleanup) {
|
|
1318
|
+
reactivityImports.push("onEffectCleanup");
|
|
1319
|
+
}
|
|
1144
1320
|
lines.push(`import { ${reactivityImports.join(", ")} } from '@vue/reactivity';`);
|
|
1145
1321
|
|
|
1146
1322
|
// Lit-html imports (only when arrays are present)
|
|
@@ -1159,6 +1335,15 @@ function emitClientModule(
|
|
|
1159
1335
|
/* The boolean-attribute rule, inlined because this module loads with `@vue/reactivity` and
|
|
1160
1336
|
nothing else — see `attrHelperSource`. The hydration script below is its only caller. */
|
|
1161
1337
|
lines.push(...src.imports, ...clientClasses.imports, ...src.loaders, "", attrHelperSource());
|
|
1338
|
+
if (caseState?.needsLoader) {
|
|
1339
|
+
lines.push(caseLoaderSource());
|
|
1340
|
+
}
|
|
1341
|
+
if (counter.needsFormulaGuard) {
|
|
1342
|
+
lines.push(formulaGuardSource());
|
|
1343
|
+
}
|
|
1344
|
+
if (features.needsCookie) {
|
|
1345
|
+
lines.push(cookieHelperSource());
|
|
1346
|
+
}
|
|
1162
1347
|
/* The list rules (compiler.md §4.7), carried only by a module whose document filters, sorts or
|
|
1163
1348
|
keys a list. */
|
|
1164
1349
|
if (lists.arranged || lists.keyed) {
|
|
@@ -1184,6 +1369,16 @@ function emitClientModule(
|
|
|
1184
1369
|
}
|
|
1185
1370
|
lines.push("});", "");
|
|
1186
1371
|
|
|
1372
|
+
/* A callable string body is `state[key]` before any init block runs, so a `Request` URL, a
|
|
1373
|
+
computed or a template that calls `state.key(…)` finds it whatever the key order. */
|
|
1374
|
+
for (const [key, def] of onEntries) {
|
|
1375
|
+
if (stateCallables.has(key)) {
|
|
1376
|
+
lines.push(
|
|
1377
|
+
`${refAccessor("state", escapeToken(key))} = (${def.args.join(", ")}) => { ${def.body}\n};`,
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1187
1382
|
// Prototype init blocks (Request fetch, LocalStorage read, etc.)
|
|
1188
1383
|
if (initBlocks.length > 0) {
|
|
1189
1384
|
for (const block of initBlocks) {
|
|
@@ -1225,9 +1420,15 @@ function emitClientModule(
|
|
|
1225
1420
|
if (onEntries.length > 0) {
|
|
1226
1421
|
lines.push("const on = {");
|
|
1227
1422
|
for (const [key, def] of onEntries) {
|
|
1423
|
+
if (stateCallables.has(key)) {
|
|
1424
|
+
lines.push(
|
|
1425
|
+
` ${objectKey(key)}: (e) => ${refAccessor("state", escapeToken(key))}(state, e),`,
|
|
1426
|
+
);
|
|
1427
|
+
continue;
|
|
1428
|
+
}
|
|
1228
1429
|
// Every entry's list starts with `state`, and the event is the one argument after it.
|
|
1229
1430
|
lines.push(
|
|
1230
|
-
` ${objectKey(key)}: (e) => { const fn = (${def.args.join(", ")}) => { ${def.body}\n}; fn(state, e); },`,
|
|
1431
|
+
` ${objectKey(key)}: (e) => { const fn = ${def.async ? "async " : ""}(${def.args.join(", ")}) => { ${def.body}\n}; fn(state, e); },`,
|
|
1231
1432
|
);
|
|
1232
1433
|
}
|
|
1233
1434
|
lines.push("};");
|
|
@@ -1266,6 +1467,10 @@ function emitClientModule(
|
|
|
1266
1467
|
}
|
|
1267
1468
|
lines.push(
|
|
1268
1469
|
" effect(() => { el.style[parts[1]] = bind[key](); });",
|
|
1470
|
+
" } else if (parts[0] === 'prop' && parts.length > 1) {",
|
|
1471
|
+
" const name = key;",
|
|
1472
|
+
" const k = parts[1];",
|
|
1473
|
+
" effect(() => { el[name] = bind[k](); });",
|
|
1269
1474
|
" } else if (parts[0] === 'attr' && parts.length > 1) {",
|
|
1270
1475
|
// A binding that flips back has to take the attribute WITH it: the element is being re-used, so
|
|
1271
1476
|
// Anything left behind is the state the page just said it had left. Same decision as the
|
|
@@ -1318,8 +1523,8 @@ function emitClientModule(
|
|
|
1318
1523
|
}
|
|
1319
1524
|
|
|
1320
1525
|
// ─── Prototype init emitters ─────────────────────────────────────────────────
|
|
1321
|
-
// Request auto-fetch
|
|
1322
|
-
//
|
|
1526
|
+
// Request auto-fetch (`emitRequestFetch`) and the cookie binding (`emitCookieBinding`) live in
|
|
1527
|
+
// Shared.ts, so the element target can emit the same effects against `this.state`.
|
|
1323
1528
|
|
|
1324
1529
|
/**
|
|
1325
1530
|
* @param {string} key
|
|
@@ -1351,26 +1556,6 @@ function emitStorageInit(
|
|
|
1351
1556
|
return lines.join("\n");
|
|
1352
1557
|
}
|
|
1353
1558
|
|
|
1354
|
-
/**
|
|
1355
|
-
* @param {string} key
|
|
1356
|
-
* @param {string} cookieName
|
|
1357
|
-
* @param {JsonValue} defaultVal
|
|
1358
|
-
* @returns {string}
|
|
1359
|
-
*/
|
|
1360
|
-
function emitCookieInit(key: string, cookieName: string, defaultVal: JsonValue) {
|
|
1361
|
-
const lines: string[] = [
|
|
1362
|
-
`// ${key}: Cookie (name: "${cookieName}")`,
|
|
1363
|
-
"{",
|
|
1364
|
-
` const _m = document.cookie.match(new RegExp("(?:^|; )${cookieName}=([^;]*)"));`,
|
|
1365
|
-
` try { state.${key} = _m ? JSON.parse(decodeURIComponent(_m[1])) : ${JSON.stringify(
|
|
1366
|
-
defaultVal,
|
|
1367
|
-
)}; }`,
|
|
1368
|
-
` catch { state.${key} = _m ? _m[1] : ${JSON.stringify(defaultVal)}; }`,
|
|
1369
|
-
"}",
|
|
1370
|
-
];
|
|
1371
|
-
return lines.join("\n");
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
1559
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
1375
1560
|
|
|
1376
1561
|
/**
|
|
@@ -1409,9 +1594,76 @@ function mapRefToClientExpr(written: string) {
|
|
|
1409
1594
|
if (ref.startsWith("#/state/")) {
|
|
1410
1595
|
return refAccessor("state", ref.slice("#/state/".length));
|
|
1411
1596
|
}
|
|
1597
|
+
// The remaining schemes mirror `refToExpr` in compile-element.ts, as the runtime lowers them.
|
|
1598
|
+
if (ref.startsWith("parent#/")) {
|
|
1599
|
+
return refAccessor("state", ref.slice("parent#/".length));
|
|
1600
|
+
}
|
|
1601
|
+
if (ref.startsWith("window#/")) {
|
|
1602
|
+
return refAccessor("window", ref.slice("window#/".length));
|
|
1603
|
+
}
|
|
1604
|
+
if (ref.startsWith("document#/")) {
|
|
1605
|
+
return refAccessor("document", ref.slice("document#/".length));
|
|
1606
|
+
}
|
|
1412
1607
|
return refAccessor("state", ref);
|
|
1413
1608
|
}
|
|
1414
1609
|
|
|
1610
|
+
/**
|
|
1611
|
+
* The head state key of every `#/state/`, `parent#/` or bare `$ref` a component instance's `$props`
|
|
1612
|
+
* names, anywhere in the document: the keys whose handler entries a prop may deliver.
|
|
1613
|
+
*
|
|
1614
|
+
* @param {JxMutableNode | JsonPrimitive | undefined} node
|
|
1615
|
+
* @returns {Set<string>}
|
|
1616
|
+
*/
|
|
1617
|
+
function collectPropRefKeys(node: JxMutableNode | JsonPrimitive | undefined): Set<string> {
|
|
1618
|
+
const keys = new Set<string>();
|
|
1619
|
+
const pending: unknown[] = [node];
|
|
1620
|
+
while (pending.length > 0) {
|
|
1621
|
+
const value = pending.pop();
|
|
1622
|
+
if (Array.isArray(value)) {
|
|
1623
|
+
const items: unknown[] = value;
|
|
1624
|
+
pending.push(...items);
|
|
1625
|
+
} else if (isNonNullObject(value)) {
|
|
1626
|
+
/* SAFETY: authored document JSON; only the members destructured here are read, each as the
|
|
1627
|
+
schema types it. */
|
|
1628
|
+
const { $props: props, cases, children, map } = value as JxMutableNode;
|
|
1629
|
+
if (isNonNullObject(props) && !Array.isArray(props)) {
|
|
1630
|
+
for (const prop of Object.values(props)) {
|
|
1631
|
+
const head = isRefObject(prop) ? propRefHead(prop.$ref) : undefined;
|
|
1632
|
+
if (head) {
|
|
1633
|
+
keys.add(head);
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
pending.push(children, map);
|
|
1638
|
+
if (isNonNullObject(cases) && !Array.isArray(cases)) {
|
|
1639
|
+
const branches: unknown[] = Object.values(cases);
|
|
1640
|
+
pending.push(...branches);
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
return keys;
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/**
|
|
1648
|
+
* The head state key a prop's `$ref` reads, or `undefined` for a pointer that names no state entry
|
|
1649
|
+
* (`$map/`, `window#/`, `document#/` or another document).
|
|
1650
|
+
*
|
|
1651
|
+
* @param {string} written
|
|
1652
|
+
* @returns {string | undefined}
|
|
1653
|
+
*/
|
|
1654
|
+
function propRefHead(written: string): string | undefined {
|
|
1655
|
+
const ref = canonicalMapRef(written);
|
|
1656
|
+
let path = ref;
|
|
1657
|
+
if (ref.startsWith("#/state/")) {
|
|
1658
|
+
path = ref.slice("#/state/".length);
|
|
1659
|
+
} else if (ref.startsWith("parent#/")) {
|
|
1660
|
+
path = ref.slice("parent#/".length);
|
|
1661
|
+
} else if (ref.includes("#/") || ref.startsWith("$map/")) {
|
|
1662
|
+
return undefined;
|
|
1663
|
+
}
|
|
1664
|
+
return refSegments(path)[0];
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1415
1667
|
/**
|
|
1416
1668
|
* The read of the state a `$ref` names, for a binding whose value arrives later: a `$switch`
|
|
1417
1669
|
* discriminant and a repeater's `items`. A server entry or a `Request` is `null` until it answers,
|