@zeus-js/compiler 0.1.1-beta.0 → 0.1.1-beta.2

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.
@@ -1,2004 +1,9 @@
1
1
  /**
2
- * compiler v0.1.1-beta.0
2
+ * compiler v0.1.1-beta.2
3
3
  * (c) 2026 baicie
4
4
  * Released under the MIT License.
5
5
  **/
6
- import { declare } from "@babel/helper-plugin-utils";
7
- import { extend } from "@zeus-js/shared";
8
- import * as t from "@babel/types";
9
- import { parseExpression } from "@babel/parser";
10
- import { attrBindingIR, componentIR, dynamicTextIR, elementIR, eventBindingIR, expressionIR, forIR, fragmentIR, hostIR, id, identifierIR, propBindingIR, ref, refBindingIR, showIR, slotIR, staticAttrIR, textIR } from "@zeus-js/compiler-shared";
11
- export * from "@zeus-js/compiler-shared";
12
- //#region packages/core/compiler/src/codegen/support/imports.ts
13
- /**
14
- * Runtime helpers registration and program injection.
15
- *
16
- * Manages the collection of runtime helper imports (template, insert, setAttr,
17
- * createComponent, delegateEvents, etc.) and generates the necessary import
18
- * declarations at the top of the program.
19
- */
20
- const DEFAULT_RENDERER_MODULE = "@zeus-js/runtime-dom";
21
- function getImportKey(moduleName, imported) {
22
- return `${moduleName}:${imported}`;
23
- }
24
- function getRendererConfig(path, renderer = "dom") {
25
- var _hub$file;
26
- const hub = path.hub;
27
- return {
28
- renderer,
29
- moduleName: (hub === null || hub === void 0 || (_hub$file = hub.file) === null || _hub$file === void 0 || (_hub$file = _hub$file.metadata) === null || _hub$file === void 0 || (_hub$file = _hub$file.zeus) === null || _hub$file === void 0 || (_hub$file = _hub$file.config) === null || _hub$file === void 0 ? void 0 : _hub$file.moduleName) || "@zeus-js/runtime-dom"
30
- };
31
- }
32
- function registerImportMethod(path, imported, moduleName = getRendererConfig(path, "dom").moduleName) {
33
- const data = getProgramScopeData(path);
34
- const importMethods = data.importMethods || (data.importMethods = /* @__PURE__ */ new Map());
35
- const key = getImportKey(moduleName, imported);
36
- const cached = importMethods.get(key);
37
- if (cached) return t.cloneNode(cached.local);
38
- const local = getProgramPath(path).scope.generateUidIdentifier(imported);
39
- importMethods.set(key, {
40
- imported,
41
- local,
42
- moduleName
43
- });
44
- return t.cloneNode(local);
45
- }
46
- /**
47
- * Generates import declarations for all collected runtime helpers and
48
- * prepends them to the program body.
49
- */
50
- function appendImportMethods(path) {
51
- const importMethods = path.scope.data.importMethods;
52
- if (!(importMethods === null || importMethods === void 0 ? void 0 : importMethods.size)) return;
53
- const grouped = /* @__PURE__ */ new Map();
54
- for (const record of importMethods.values()) {
55
- const records = grouped.get(record.moduleName);
56
- if (records) records.push(record);
57
- else grouped.set(record.moduleName, [record]);
58
- }
59
- const declarations = [];
60
- for (const [moduleName, records] of grouped) declarations.push(t.importDeclaration(records.map((record) => t.importSpecifier(t.cloneNode(record.local), t.identifier(record.imported))), t.stringLiteral(moduleName)));
61
- path.unshiftContainer("body", declarations);
62
- }
63
- function getProgramScopeData(path) {
64
- return path.scope.getProgramParent().path.scope.data;
65
- }
66
- function getProgramPath(path) {
67
- return path.scope.getProgramParent().path;
68
- }
69
- //#endregion
70
- //#region packages/core/compiler/src/codegen/support/templates.ts
71
- /**
72
- * Template registration, scope data management, and program injection.
73
- *
74
- * Tracks all compiled templates across the program scope, registers template
75
- * variable declarations (tmpl$0, tmpl$1, ...), and generates the template
76
- * registration calls at the top of the program.
77
- */
78
- /**
79
- * Retrieves all registered templates for a given renderer.
80
- */
81
- function getTemplates(path, renderer = "dom") {
82
- var _scopeData$templates$, _scopeData$templates;
83
- return (_scopeData$templates$ = (_scopeData$templates = path.scope.data.templates) === null || _scopeData$templates === void 0 ? void 0 : _scopeData$templates.filter((t) => t.renderer === renderer)) !== null && _scopeData$templates$ !== void 0 ? _scopeData$templates$ : [];
84
- }
85
- function escapeStringForTemplate(value) {
86
- return value.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
87
- }
88
- function isMathMLTemplate(template) {
89
- return /^<(math|annotation|annotation-xml|maction|merror|mfrac|mi|mmultiscripts|mn|mo|mover|mpadded|mphantom|mprescripts|mroot|mrow|ms|mspace|msqrt|mstyle|msub|msubsup|msup|mtable|mtd|mtext|mtr|munder|munderover|semantics|menclose|mfenced)(\s|>)/.test(template);
90
- }
91
- /**
92
- * Generates `var tmpl$0 = template(...), tmpl$1 = template(...)` declarations
93
- * and unshifts them to the top of the program.
94
- */
95
- function appendTemplates(path) {
96
- const templates = getTemplates(path, "dom");
97
- if (!templates.length) return;
98
- const templateMethod = registerImportMethod(path, "template", getRendererConfig(path, "dom").moduleName);
99
- const declarators = templates.map((template) => {
100
- const html = template.templateWithClosingTags || template.template;
101
- const tmpl = {
102
- cooked: html,
103
- raw: escapeStringForTemplate(html)
104
- };
105
- const shouldUseImportNode = Boolean(template.isCE || template.isImportNode);
106
- const isMathML = isMathMLTemplate(html);
107
- const args = [t.templateLiteral([t.templateElement(tmpl, true)], [])];
108
- if (template.isSVG || shouldUseImportNode || isMathML) args.push(t.booleanLiteral(shouldUseImportNode), t.booleanLiteral(Boolean(template.isSVG)), t.booleanLiteral(isMathML));
109
- return t.variableDeclarator(t.cloneNode(template.id), t.addComment(t.callExpression(t.cloneNode(templateMethod), args), "leading", "#__PURE__"));
110
- });
111
- path.node.body.unshift(t.variableDeclaration("var", declarators));
112
- }
113
- //#endregion
114
- //#region packages/core/compiler/src/codegen/support/events.ts
115
- /**
116
- * Event registration and delegation.
117
- *
118
- * Tracks all event handlers encountered during JSX transform and generates
119
- * a single delegateEvents call at the end of the program (if any events
120
- * were found).
121
- */
122
- /**
123
- * Registers an event name in the program scope.
124
- * Events are deduplicated — registering the same event name multiple times
125
- * only keeps it once.
126
- */
127
- function registerEvent(path, eventName) {
128
- const scopeData = path.scope.getProgramParent().path.scope.data;
129
- (scopeData.events || (scopeData.events = /* @__PURE__ */ new Set())).add(eventName);
130
- }
131
- /**
132
- * Generates a delegateEvents(...) call at the end of the program body.
133
- *
134
- * This implements the event delegation pattern: instead of attaching individual
135
- * addEventListener calls, we register event names with the runtime so it can
136
- * attach a single delegated listener at the root.
137
- */
138
- function appendEvents(path) {
139
- const events = path.scope.data.events;
140
- if (!(events === null || events === void 0 ? void 0 : events.size)) return;
141
- path.node.body.push(t.expressionStatement(t.callExpression(registerImportMethod(path, "delegateEvents", getRendererConfig(path, "dom").moduleName), [t.arrayExpression(Array.from(events).map((eventName) => t.stringLiteral(eventName)))])));
142
- }
143
- //#endregion
144
- //#region packages/core/compiler/src/config/index.ts
145
- const DEFAULT_SSR_RENDERER_MODULE = "@zeus-js/runtime-ssr";
146
- const DEFAULT_OPTIONS = {
147
- moduleName: DEFAULT_RENDERER_MODULE,
148
- generate: "dom",
149
- hydratable: false,
150
- delegateEvents: true,
151
- delegatedEvents: [],
152
- builtIns: [],
153
- wrapConditionals: true,
154
- omitNestedClosingTags: false,
155
- omitLastClosingTag: true,
156
- omitQuotes: true,
157
- contextToCustomElements: false,
158
- staticMarker: "@once",
159
- effectWrapper: "effect",
160
- memoWrapper: "memo",
161
- validate: true,
162
- inlineStyles: true
163
- };
164
- /**
165
- * Resolve the compiler options by merging the default options with the provided options.
166
- * @param options - The compiler options to resolve.
167
- * @returns The resolved compiler options.
168
- */
169
- function resolveConfig(options) {
170
- const config = extend({}, DEFAULT_OPTIONS, options);
171
- if (config.generate === "ssr" && (options === null || options === void 0 ? void 0 : options.moduleName) === void 0) config.moduleName = DEFAULT_SSR_RENDERER_MODULE;
172
- return config;
173
- }
174
- //#endregion
175
- //#region packages/core/compiler/src/context/CompilerContext.ts
176
- var CompilerContext = class {
177
- constructor(options, programPath) {
178
- this.options = options;
179
- this.programPath = programPath;
180
- }
181
- runtimeModule() {
182
- return this.options.moduleName || "@zeus-js/runtime-dom";
183
- }
184
- uid(name) {
185
- return this.programPath.scope.generateUidIdentifier(name);
186
- }
187
- importRuntime(imported) {
188
- const moduleName = this.runtimeModule();
189
- const scopeData = this.programPath.scope.data;
190
- const importMethods = scopeData.importMethods || (scopeData.importMethods = /* @__PURE__ */ new Map());
191
- const key = `${moduleName}:${imported}`;
192
- const cached = importMethods.get(key);
193
- if (cached) return t.cloneNode(cached.local);
194
- const local = this.uid(imported);
195
- importMethods.set(key, {
196
- moduleName,
197
- imported,
198
- local
199
- });
200
- return t.cloneNode(local);
201
- }
202
- registerTemplate(html, isSVG = false) {
203
- const scopeData = this.programPath.scope.data;
204
- const templateMap = scopeData.templateMap || (scopeData.templateMap = /* @__PURE__ */ new Map());
205
- const templates = scopeData.templates || (scopeData.templates = []);
206
- const cached = templateMap.get(html);
207
- if (cached) return {
208
- id: t.cloneNode(cached.id),
209
- html,
210
- isSVG: Boolean(cached.isSVG)
211
- };
212
- const id = this.uid("tmpl$");
213
- templateMap.set(html, {
214
- id,
215
- template: html,
216
- templateWithClosingTags: html,
217
- renderer: "dom",
218
- isSVG,
219
- isCE: html.includes("-"),
220
- isImportNode: /^<(img|iframe)(\s|>)/.test(html)
221
- });
222
- templates.push(templateMap.get(html));
223
- return {
224
- id: t.cloneNode(id),
225
- html,
226
- isSVG
227
- };
228
- }
229
- };
230
- function getCompilerContext(path, options) {
231
- return new CompilerContext(options, path.scope.getProgramParent().path);
232
- }
233
- //#endregion
234
- //#region packages/core/compiler/src/context/defineElementSetups.ts
235
- const ZEUS_PUBLIC_MODULE = "@zeus-js/zeus";
236
- function collectDefineElementSetups(path, runtimeModule) {
237
- const setups = /* @__PURE__ */ new WeakSet();
238
- const trustedModules = /* @__PURE__ */ new Set([
239
- DEFAULT_RENDERER_MODULE,
240
- ZEUS_PUBLIC_MODULE,
241
- runtimeModule
242
- ]);
243
- for (const statement of path.node.body) {
244
- if (!t.isImportDeclaration(statement) || !trustedModules.has(statement.source.value)) continue;
245
- for (const specifier of statement.specifiers) {
246
- if (!isDefineElementImport(specifier)) continue;
247
- const binding = path.scope.getBinding(specifier.local.name);
248
- if (!binding || binding.path.node !== specifier) continue;
249
- for (const reference of binding.referencePaths) collectSetupFromReference(reference, setups);
250
- }
251
- }
252
- getProgramScopeData(path).defineElementSetups = setups;
253
- }
254
- function isDefineElementRenderRoot(path) {
255
- var _returnPath$getFuncti;
256
- const setups = getProgramScopeData(path).defineElementSetups;
257
- const functionPath = path.getFunctionParent();
258
- if (!setups || !functionPath || !t.isFunction(functionPath.node) || !setups.has(functionPath.node)) return false;
259
- const root = skipTransparentExpressionWrappers(path);
260
- if (functionPath.isArrowFunctionExpression() && functionPath.node.body === root.node) return true;
261
- const returnPath = root.parentPath;
262
- return Boolean((returnPath === null || returnPath === void 0 ? void 0 : returnPath.isReturnStatement()) && returnPath.node.argument === root.node && ((_returnPath$getFuncti = returnPath.getFunctionParent()) === null || _returnPath$getFuncti === void 0 ? void 0 : _returnPath$getFuncti.node) === functionPath.node);
263
- }
264
- function isDefineElementImport(specifier) {
265
- if (!t.isImportSpecifier(specifier)) return false;
266
- const imported = specifier.imported;
267
- return t.isIdentifier(imported) && imported.name === "defineElement" || t.isStringLiteral(imported) && imported.value === "defineElement";
268
- }
269
- function collectSetupFromReference(reference, setups) {
270
- const call = reference.parentPath;
271
- if (reference.key !== "callee" || !(call === null || call === void 0 ? void 0 : call.isCallExpression()) || call.node.callee !== reference.node) return;
272
- const setup = call.get("arguments")[2];
273
- if (!setup) return;
274
- const setupFunction = resolveSetupFunction(setup, /* @__PURE__ */ new Set());
275
- if (setupFunction) setups.add(setupFunction);
276
- }
277
- function resolveSetupFunction(path, visitedBindings) {
278
- const setupPath = unwrapTransparentExpressionWrappers(path);
279
- if (setupPath.isArrowFunctionExpression() || setupPath.isFunctionExpression()) return setupPath.node;
280
- if (!setupPath.isIdentifier()) return void 0;
281
- const binding = setupPath.scope.getBinding(setupPath.node.name);
282
- if (!(binding === null || binding === void 0 ? void 0 : binding.constant) || visitedBindings.has(binding)) return void 0;
283
- visitedBindings.add(binding);
284
- if (binding.path.isFunctionDeclaration()) return binding.path.node;
285
- if (!binding.path.isVariableDeclarator()) return void 0;
286
- const init = binding.path.get("init");
287
- if (Array.isArray(init) || !init.node) return void 0;
288
- return resolveSetupFunction(init, visitedBindings);
289
- }
290
- function unwrapTransparentExpressionWrappers(path) {
291
- let current = path;
292
- while (isTransparentExpressionWrapper(current.node)) current = current.get("expression");
293
- return current;
294
- }
295
- function skipTransparentExpressionWrappers(path) {
296
- let current = path;
297
- while (current.parentPath && wrapsExpression(current.parentPath, current)) current = current.parentPath;
298
- return current;
299
- }
300
- function wrapsExpression(parent, child) {
301
- const node = parent.node;
302
- return isTransparentExpressionWrapper(node) && node.expression === child.node;
303
- }
304
- function isTransparentExpressionWrapper(node) {
305
- return t.isParenthesizedExpression(node) || t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node) || t.isTSTypeAssertion(node) || t.isTypeCastExpression(node) || t.isTSNonNullExpression(node);
306
- }
307
- //#endregion
308
- //#region packages/core/compiler/src/utils/constant.ts
309
- const VoidElements = [
310
- "area",
311
- "base",
312
- "br",
313
- "col",
314
- "embed",
315
- "hr",
316
- "img",
317
- "input",
318
- "keygen",
319
- "link",
320
- "menuitem",
321
- "meta",
322
- "param",
323
- "source",
324
- "track",
325
- "wbr"
326
- ];
327
- //#endregion
328
- //#region packages/core/compiler/src/utils/html.ts
329
- function escapeHTML(value, attr = false) {
330
- let result = value.replace(/&/g, "&amp;");
331
- if (attr) return result.replace(/"/g, "&quot;").replace(/>/g, "&gt;");
332
- return result.replace(/</g, "&lt;");
333
- }
334
- function trimJSXText(value) {
335
- return value.replace(/\r\n?/g, "\n").split("\n").map((line) => line.trim()).filter(Boolean).join(" ");
336
- }
337
- const rawTextElements = /* @__PURE__ */ new Set([
338
- "script",
339
- "style",
340
- "textarea",
341
- "title"
342
- ]);
343
- function isRawTextElement(tagName) {
344
- return rawTextElements.has(tagName);
345
- }
346
- //#endregion
347
- //#region packages/core/compiler/src/utils/metadata.ts
348
- function setZeusMetadata(state, config) {
349
- const metadata = state.file.metadata;
350
- metadata.zeus = extend({}, metadata.zeus, { config });
351
- return metadata.zeus;
352
- }
353
- //#endregion
354
- //#region packages/core/compiler/src/program.ts
355
- /**
356
- * Program visitor — entry and exit point for the entire transform pass.
357
- *
358
- * - Program.enter: initializes file metadata
359
- * - Program.exit: injects all collected codegen artifacts (templates, events, imports)
360
- */
361
- function enterProgram(config, path, state) {
362
- setZeusMetadata(state, config);
363
- collectDefineElementSetups(path, config.moduleName);
364
- }
365
- function exitProgram(config, path, state) {
366
- if (state.get("skip")) return;
367
- if (config.generate === "dom") {
368
- appendTemplates(path);
369
- if (config.delegateEvents) appendEvents(path);
370
- }
371
- appendImportMethods(path);
372
- }
373
- function createProgramVisitor(config) {
374
- return {
375
- enter(path, state) {
376
- enterProgram(config, path, state);
377
- },
378
- exit(path, state) {
379
- exitProgram(config, path, state);
380
- }
381
- };
382
- }
383
- //#endregion
384
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
385
- function _typeof(o) {
386
- "@babel/helpers - typeof";
387
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
388
- return typeof o;
389
- } : function(o) {
390
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
391
- }, _typeof(o);
392
- }
393
- //#endregion
394
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
395
- function toPrimitive(t, r) {
396
- if ("object" != _typeof(t) || !t) return t;
397
- var e = t[Symbol.toPrimitive];
398
- if (void 0 !== e) {
399
- var i = e.call(t, r || "default");
400
- if ("object" != _typeof(i)) return i;
401
- throw new TypeError("@@toPrimitive must return a primitive value.");
402
- }
403
- return ("string" === r ? String : Number)(t);
404
- }
405
- //#endregion
406
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
407
- function toPropertyKey(t) {
408
- var i = toPrimitive(t, "string");
409
- return "symbol" == _typeof(i) ? i : i + "";
410
- }
411
- //#endregion
412
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
413
- function _defineProperty(e, r, t) {
414
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
415
- value: t,
416
- enumerable: !0,
417
- configurable: !0,
418
- writable: !0
419
- }) : e[r] = t, e;
420
- }
421
- //#endregion
422
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/objectSpread2.js
423
- function ownKeys(e, r) {
424
- var t = Object.keys(e);
425
- if (Object.getOwnPropertySymbols) {
426
- var o = Object.getOwnPropertySymbols(e);
427
- r && (o = o.filter(function(r) {
428
- return Object.getOwnPropertyDescriptor(e, r).enumerable;
429
- })), t.push.apply(t, o);
430
- }
431
- return t;
432
- }
433
- function _objectSpread2(e) {
434
- for (var r = 1; r < arguments.length; r++) {
435
- var t = null != arguments[r] ? arguments[r] : {};
436
- r % 2 ? ownKeys(Object(t), !0).forEach(function(r) {
437
- _defineProperty(e, r, t[r]);
438
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {
439
- Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
440
- });
441
- }
442
- return e;
443
- }
444
- //#endregion
445
- //#region packages/core/compiler/src/adapters/babel/expression.ts
446
- function lowerExpressionIR(path) {
447
- return expressionIR(path.getSource() || path.toString(), sourceSpanFromBabelNode(path.node));
448
- }
449
- function expressionIRFromCode(code, node) {
450
- return expressionIR(code, sourceSpanFromBabelNode(node));
451
- }
452
- function parseExpressionIR(expression) {
453
- var _expression$span;
454
- const start = (_expression$span = expression.span) === null || _expression$span === void 0 ? void 0 : _expression$span.start;
455
- const sourceStart = typeof (start === null || start === void 0 ? void 0 : start.offset) === "number" ? {
456
- startLine: start.line,
457
- startColumn: start.column,
458
- startIndex: start.offset
459
- } : {};
460
- return parseExpression(expression.code, _objectSpread2({
461
- sourceType: "module",
462
- plugins: ["typescript", "jsx"]
463
- }, sourceStart));
464
- }
465
- function sourceSpanFromBabelNode(node) {
466
- if (!(node === null || node === void 0 ? void 0 : node.loc)) return void 0;
467
- return {
468
- start: sourcePosition(node.loc.start.line, node.loc.start.column, node.start),
469
- end: sourcePosition(node.loc.end.line, node.loc.end.column, node.end)
470
- };
471
- }
472
- function sourcePosition(line, column, offset) {
473
- return typeof offset === "number" ? {
474
- line,
475
- column,
476
- offset
477
- } : {
478
- line,
479
- column
480
- };
481
- }
482
- //#endregion
483
- //#region packages/core/compiler/src/codegen/dom/emitBinding.ts
484
- function emitBindings(node, context) {
485
- const statements = [];
486
- for (const attr of node.attrs) {
487
- if (attr.kind === "AttrBinding") statements.push(emitAttrBinding(node, attr, context));
488
- if (attr.kind === "EventBinding") statements.push(emitEventBinding(node, attr, context));
489
- if (attr.kind === "PropBinding") statements.push(emitPropBinding(node, attr, context));
490
- if (attr.kind === "RefBinding") statements.push(emitRefBinding(node, attr, context));
491
- }
492
- if (isRawTextElement(node.tagName) && hasRuntimeRawText$1(node.children)) {
493
- statements.push(emitRawTextBinding(node, context));
494
- return statements;
495
- }
496
- for (const child of node.children) statements.push(...emitChildBinding(child, context));
497
- return statements;
498
- }
499
- function emitRawTextBinding(node, context) {
500
- return t.expressionStatement(t.callExpression(context.importRuntime("bindTextContent"), [t.identifier(node.ref.name), t.arrowFunctionExpression([], emitRawTextValue(node.children))]));
501
- }
502
- function hasRuntimeRawText$1(children) {
503
- return children.some((child) => {
504
- if (child.kind === "Text") return false;
505
- if (child.kind === "Fragment") return hasRuntimeRawText$1(child.children);
506
- return true;
507
- });
508
- }
509
- function emitRawTextValue(children) {
510
- const values = children.flatMap((child) => {
511
- switch (child.kind) {
512
- case "Text": return [t.stringLiteral(child.value)];
513
- case "DynamicText": return [parseExpressionIR(child.expr)];
514
- case "Fragment": return [emitRawTextValue(child.children)];
515
- default: return [];
516
- }
517
- });
518
- if (values.length === 0) return t.stringLiteral("");
519
- if (values.length === 1) return values[0];
520
- return t.arrayExpression(values);
521
- }
522
- function emitChildBinding(node, context) {
523
- switch (node.kind) {
524
- case "DynamicText": return emitDynamicText(node, context);
525
- case "Component": return emitComponentInsert(node, context);
526
- case "Show": return emitMarkerMount(node, context, emitMountShow(node, context));
527
- case "For": return emitMarkerMount(node, context, emitMountFor(node, context));
528
- case "Slot": return emitMarkerInsert(node, context, emitSlot(node, context));
529
- case "Element": return emitBindings(node, context);
530
- case "Fragment": return node.children.flatMap((child) => emitChildBinding(child, context));
531
- default: return [];
532
- }
533
- }
534
- function emitAttrBinding(target, binding, context) {
535
- const name = normalizeAttrName(binding.name);
536
- if (name === "class") return t.expressionStatement(t.callExpression(context.importRuntime("bindClass"), [t.identifier(target.ref.name), emitGetter(parseExpressionIR(binding.expr))]));
537
- if (name === "style") return t.expressionStatement(t.callExpression(context.importRuntime("bindStyle"), [t.identifier(target.ref.name), emitGetter(parseExpressionIR(binding.expr))]));
538
- return t.expressionStatement(t.callExpression(context.importRuntime("bindAttr"), [
539
- t.identifier(target.ref.name),
540
- t.stringLiteral(name),
541
- emitGetter(parseExpressionIR(binding.expr))
542
- ]));
543
- }
544
- function normalizeAttrName(name) {
545
- return name === "className" ? "class" : name;
546
- }
547
- function emitEventBinding(target, binding, context) {
548
- registerEvent(context.programPath, binding.eventName);
549
- return t.expressionStatement(t.callExpression(context.importRuntime("bindEvent"), [
550
- t.identifier(target.ref.name),
551
- t.stringLiteral(binding.eventName),
552
- normalizeEventHandler(parseExpressionIR(binding.handler), context)
553
- ]));
554
- }
555
- function normalizeEventHandler(handler, context) {
556
- if (t.isMemberExpression(handler) || t.isOptionalMemberExpression(handler)) {
557
- const event = context.uid("event$");
558
- return t.arrowFunctionExpression([t.identifier(event.name)], t.optionalCallExpression(t.cloneNode(handler), [t.identifier(event.name)], true));
559
- }
560
- return handler;
561
- }
562
- function emitPropBinding(target, binding, context) {
563
- return t.expressionStatement(t.callExpression(context.importRuntime("bindProp"), [
564
- t.identifier(target.ref.name),
565
- t.stringLiteral(binding.name),
566
- emitGetter(parseExpressionIR(binding.expr))
567
- ]));
568
- }
569
- function emitGetter(expr) {
570
- if (t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr)) return expr;
571
- return t.arrowFunctionExpression([], expr);
572
- }
573
- function emitRefBinding(target, binding, context) {
574
- return t.expressionStatement(t.callExpression(context.importRuntime("bindRef"), [t.identifier(target.ref.name), parseExpressionIR(binding.expr)]));
575
- }
576
- function emitDynamicText(node, context) {
577
- if (!node.domPath || node.domPath.kind !== "Marker") return [];
578
- const textRef = context.uid("text$");
579
- const expression = parseExpressionIR(node.expr);
580
- if (node.once) return [t.variableDeclaration("const", [t.variableDeclarator(textRef, t.callExpression(t.memberExpression(t.identifier("document"), t.identifier("createTextNode")), [t.callExpression(t.identifier("String"), [expression])]))]), t.expressionStatement(t.callExpression(context.importRuntime("insert"), [
581
- t.identifier(node.domPath.parent.name),
582
- textRef,
583
- t.identifier(node.ref.name)
584
- ]))];
585
- return [
586
- t.variableDeclaration("const", [t.variableDeclarator(textRef, t.callExpression(t.memberExpression(t.identifier("document"), t.identifier("createTextNode")), [t.stringLiteral("")]))]),
587
- t.expressionStatement(t.callExpression(context.importRuntime("insert"), [
588
- t.identifier(node.domPath.parent.name),
589
- textRef,
590
- t.identifier(node.ref.name)
591
- ])),
592
- t.expressionStatement(t.callExpression(context.importRuntime("bindText"), [textRef, t.arrowFunctionExpression([], expression)]))
593
- ];
594
- }
595
- function emitComponentInsert(node, context) {
596
- return emitMarkerInsert(node, context, emitComponent$1(node, context));
597
- }
598
- function emitMarkerInsert(node, context, value) {
599
- if (!node.domPath || node.domPath.kind !== "Marker") return [];
600
- return [t.expressionStatement(t.callExpression(context.importRuntime("insert"), [
601
- t.identifier(node.domPath.parent.name),
602
- value,
603
- t.identifier(node.ref.name)
604
- ]))];
605
- }
606
- function emitMarkerMount(node, context, mountCall) {
607
- if (!node.domPath || node.domPath.kind !== "Marker") return [];
608
- return [t.expressionStatement(mountCall)];
609
- }
610
- //#endregion
611
- //#region packages/core/compiler/src/codegen/dom/emitDomPath.ts
612
- function emitPhysicalDomPath(path) {
613
- switch (path.kind) {
614
- case "Root": throw new Error("Root path is emitted from template clone directly");
615
- case "FirstChild": return t.memberExpression(t.identifier(path.parent.name), t.identifier("firstChild"));
616
- case "NextSibling": return t.memberExpression(t.identifier(path.previous.name), t.identifier("nextSibling"));
617
- case "ChildNode": return t.memberExpression(t.memberExpression(t.identifier(path.parent.name), t.identifier("childNodes")), t.numericLiteral(path.index), true);
618
- }
619
- }
620
- //#endregion
621
- //#region packages/core/compiler/src/passes/collectTemplates.ts
622
- function collectTemplates(node, context) {
623
- if (node.kind === "Element") {
624
- context.registerTemplate(renderTemplateHTML(node), node.flags.isSVG);
625
- return;
626
- }
627
- if (node.kind === "Fragment") for (const child of node.children) {
628
- if (child.kind !== "Element") continue;
629
- context.registerTemplate(renderTemplateHTML(child), child.flags.isSVG);
630
- }
631
- }
632
- function normalizeStaticAttrName(name) {
633
- return name === "className" ? "class" : name;
634
- }
635
- function renderTemplateHTML(node) {
636
- const attrs = node.attrs.filter((attr) => attr.kind === "StaticAttribute").map((attr) => {
637
- if (attr.kind !== "StaticAttribute") return "";
638
- const name = normalizeStaticAttrName(attr.name);
639
- if (attr.value === true) return ` ${name}`;
640
- return ` ${name}="${escapeAttr(attr.value)}"`;
641
- }).join("");
642
- if (node.flags.isVoid) return `<${node.tagName}${attrs}>`;
643
- if (isRawTextElement(node.tagName) && hasRuntimeRawText(node.children)) return `<${node.tagName}${attrs}></${node.tagName}>`;
644
- return `<${node.tagName}${attrs}>${node.children.map(renderChildTemplate).join("")}</${node.tagName}>`;
645
- }
646
- function hasRuntimeRawText(children) {
647
- return children.some((child) => {
648
- if (child.kind === "Text") return false;
649
- if (child.kind === "Fragment") return hasRuntimeRawText(child.children);
650
- return true;
651
- });
652
- }
653
- function renderChildTemplate(node) {
654
- switch (node.kind) {
655
- case "Element": return renderTemplateHTML(node);
656
- case "Text": return node.value;
657
- case "DynamicText":
658
- case "Component":
659
- case "Show":
660
- case "For":
661
- case "Slot": return "<!>";
662
- case "Host": return node.child ? renderChildTemplate(node.child) : "";
663
- case "Fragment": return node.children.map(renderChildTemplate).join("");
664
- }
665
- }
666
- function escapeAttr(value) {
667
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
668
- }
669
- //#endregion
670
- //#region packages/core/compiler/src/codegen/dom/emitTemplate.ts
671
- function emitTemplateClone(node, context) {
672
- const html = renderTemplateHTML(node);
673
- const template = context.registerTemplate(html, node.flags.isSVG);
674
- const templateCall = t.callExpression(t.cloneNode(template.id), []);
675
- return t.memberExpression(templateCall, t.identifier("firstChild"));
676
- }
677
- //#endregion
678
- //#region packages/core/compiler/src/codegen/dom/emitElement.ts
679
- function emitElement$1(node, context) {
680
- if (!hasRuntimeWork(node)) return emitTemplateClone(node, context);
681
- const statements = [
682
- t.variableDeclaration("const", [t.variableDeclarator(t.identifier(node.ref.name), emitTemplateClone(node, context))]),
683
- ...emitDomRefDeclarations(node.children, context),
684
- ...emitBindings(node, context),
685
- t.returnStatement(t.identifier(node.ref.name))
686
- ];
687
- return t.callExpression(t.arrowFunctionExpression([], t.blockStatement(statements)), []);
688
- }
689
- function emitDomRefDeclarations(children, context) {
690
- const statements = [];
691
- const declared = /* @__PURE__ */ new Set();
692
- const refNodeMap = collectRefNodeMap(children);
693
- for (const child of children) collectRequiredDomRefDeclaration(child, statements, context, refNodeMap, declared);
694
- return statements;
695
- }
696
- function collectRefNodeMap(children) {
697
- const map = /* @__PURE__ */ new Map();
698
- for (const child of children) collectRefNode(child, map);
699
- return map;
700
- }
701
- function collectRefNode(node, map) {
702
- switch (node.kind) {
703
- case "Element":
704
- map.set(node.ref.name, node);
705
- for (const child of node.children) collectRefNode(child, map);
706
- return;
707
- case "DynamicText":
708
- case "Component":
709
- case "Show":
710
- case "For":
711
- case "Slot":
712
- map.set(node.ref.name, node);
713
- return;
714
- case "Fragment":
715
- for (const child of node.children) collectRefNode(child, map);
716
- return;
717
- case "Host":
718
- if (node.child) collectRefNode(node.child, map);
719
- return;
720
- default: return;
721
- }
722
- }
723
- function collectRequiredDomRefDeclaration(node, statements, context, refNodeMap, declared) {
724
- switch (node.kind) {
725
- case "Element":
726
- if (needsDomRefDeclaration(node)) emitDomRefDeclarationWithDeps(node, statements, context, refNodeMap, declared);
727
- for (const child of node.children) collectRequiredDomRefDeclaration(child, statements, context, refNodeMap, declared);
728
- return;
729
- case "DynamicText":
730
- case "Component":
731
- case "Show":
732
- case "For":
733
- case "Slot":
734
- emitDomRefDeclarationWithDeps(node, statements, context, refNodeMap, declared);
735
- return;
736
- case "Fragment":
737
- for (const child of node.children) collectRequiredDomRefDeclaration(child, statements, context, refNodeMap, declared);
738
- return;
739
- case "Host":
740
- if (node.child) collectRequiredDomRefDeclaration(node.child, statements, context, refNodeMap, declared);
741
- return;
742
- default: return;
743
- }
744
- }
745
- function emitDomRefDeclarationWithDeps(node, statements, context, refNodeMap, declared) {
746
- if (declared.has(node.ref.name)) return;
747
- if (!node.physicalDomPath) throw new Error(`${node.kind} physical DOM path is not assigned`);
748
- emitPhysicalDomPathDependencies(node.physicalDomPath, statements, context, refNodeMap, declared);
749
- statements.push(createDomRefDeclaration(node, context));
750
- declared.add(node.ref.name);
751
- }
752
- function emitPhysicalDomPathDependencies(path, statements, context, refNodeMap, declared) {
753
- switch (path.kind) {
754
- case "Root": return;
755
- case "FirstChild":
756
- emitRefDependency(path.parent, statements, context, refNodeMap, declared);
757
- return;
758
- case "ChildNode":
759
- emitRefDependency(path.parent, statements, context, refNodeMap, declared);
760
- return;
761
- case "NextSibling":
762
- emitRefDependency(path.previous, statements, context, refNodeMap, declared);
763
- return;
764
- }
765
- }
766
- function emitRefDependency(ref, statements, context, refNodeMap, declared) {
767
- const dep = refNodeMap.get(ref.name);
768
- if (!dep) return;
769
- emitDomRefDeclarationWithDeps(dep, statements, context, refNodeMap, declared);
770
- }
771
- function createDomRefDeclaration(node, _context) {
772
- if (!node.physicalDomPath) throw new Error(`${node.kind} physical DOM path is not assigned`);
773
- return t.variableDeclaration("const", [t.variableDeclarator(t.identifier(node.ref.name), emitPhysicalDomPath(node.physicalDomPath))]);
774
- }
775
- function needsDomRefDeclaration(node) {
776
- if (!node.physicalDomPath) return false;
777
- if (node.attrs.some((attr) => attr.kind === "AttrBinding" || attr.kind === "PropBinding" || attr.kind === "EventBinding" || attr.kind === "RefBinding")) return true;
778
- return node.children.some((child) => {
779
- switch (child.kind) {
780
- case "DynamicText":
781
- case "Component":
782
- case "Show":
783
- case "For":
784
- case "Slot": return true;
785
- case "Element": return needsDomRefDeclaration(child);
786
- case "Fragment": return child.children.some((inner) => inner.kind === "Element" ? needsDomRefDeclaration(inner) : inner.kind !== "Text");
787
- case "Host": return child.child ? innerKind(child.child) : false;
788
- default: return false;
789
- }
790
- });
791
- }
792
- function innerKind(node) {
793
- switch (node.kind) {
794
- case "Element": return needsDomRefDeclaration(node);
795
- case "Text": return false;
796
- default: return true;
797
- }
798
- }
799
- function hasRuntimeWork(node) {
800
- return node.attrs.some((attr) => attr.kind === "AttrBinding" || attr.kind === "PropBinding" || attr.kind === "EventBinding" || attr.kind === "RefBinding") || node.children.some(hasChildRuntimeWork);
801
- }
802
- function hasChildRuntimeWork(node) {
803
- switch (node.kind) {
804
- case "DynamicText":
805
- case "Component":
806
- case "Show":
807
- case "For":
808
- case "Slot": return true;
809
- case "Element": return hasRuntimeWork(node);
810
- case "Fragment": return node.children.some(hasChildRuntimeWork);
811
- case "Host": return node.child ? hasChildRuntimeWork(node.child) : false;
812
- default: return false;
813
- }
814
- }
815
- //#endregion
816
- //#region packages/core/compiler/src/codegen/dom/emitFragment.ts
817
- function emitFragment(node, context) {
818
- return t.arrayExpression(node.children.map((child) => emitDOM(child, context)));
819
- }
820
- //#endregion
821
- //#region packages/core/compiler/src/codegen/dom/emitNodeExpression.ts
822
- function emitNodeExpression(node, context) {
823
- switch (node.kind) {
824
- case "Text": return t.stringLiteral(node.value);
825
- case "DynamicText": return parseExpressionIR(node.expr);
826
- case "Element": return emitElement$1(node, context);
827
- case "Component": return emitComponent$1(node, context);
828
- case "Fragment": return emitFragment(node, context);
829
- case "Show": return emitShow$1(node, context);
830
- case "For": return emitFor$1(node, context);
831
- case "Host": return emitHost(node, context);
832
- case "Slot": return emitSlot(node, context);
833
- default: return t.nullLiteral();
834
- }
835
- }
836
- //#endregion
837
- //#region packages/core/compiler/src/codegen/dom/emitComponent.ts
838
- function emitComponent$1(node, context) {
839
- const props = t.objectExpression(node.props.map((prop) => emitComponentProp$1(prop, context)));
840
- return t.callExpression(context.importRuntime("createComponent"), [parseExpressionIR(node.callee), props]);
841
- }
842
- function emitComponentProp$1(prop, context) {
843
- const key = createObjectKey$2(prop.name);
844
- if (Array.isArray(prop.value)) return t.objectMethod("get", key, [], t.blockStatement([t.returnStatement(emitChildrenProp(prop.value, context))]));
845
- const value = parseExpressionIR(prop.value);
846
- if (isStaticPropValue$1(value)) return t.objectProperty(key, value);
847
- return t.objectMethod("get", key, [], t.blockStatement([t.returnStatement(value)]));
848
- }
849
- function emitChildrenProp(children, context) {
850
- const nodes = children.map((child) => emitNodeExpression(child, context));
851
- if (nodes.length === 1) return nodes[0];
852
- return t.arrayExpression(nodes);
853
- }
854
- function isStaticPropValue$1(value) {
855
- return t.isStringLiteral(value) || t.isNumericLiteral(value) || t.isBooleanLiteral(value) || t.isNullLiteral(value);
856
- }
857
- function createObjectKey$2(key) {
858
- return t.isValidIdentifier(key) ? t.identifier(key) : t.stringLiteral(key);
859
- }
860
- //#endregion
861
- //#region packages/core/compiler/src/codegen/dom/emitBuiltin.ts
862
- function emitShow$1(node, context) {
863
- const props = [t.objectProperty(t.identifier("when"), parseExpressionIR(node.when)), t.objectProperty(t.identifier("children"), t.arrowFunctionExpression([], emitChildrenProp(node.children, context)))];
864
- if (node.fallback) props.push(t.objectProperty(t.identifier("fallback"), Array.isArray(node.fallback) ? t.arrowFunctionExpression([], emitChildrenProp(node.fallback, context)) : parseExpressionIR(node.fallback)));
865
- return t.callExpression(context.importRuntime("createComponent"), [context.importRuntime("Show"), t.objectExpression(props)]);
866
- }
867
- function emitMountShow(node, context) {
868
- const path = node.domPath;
869
- if (!path || path.kind !== "Marker") throw new Error("Show DOM path is not assigned");
870
- return t.callExpression(context.importRuntime("mountShow"), [
871
- t.identifier(path.parent.name),
872
- emitMarkerIdentifier(node),
873
- t.arrowFunctionExpression([], parseExpressionIR(node.when)),
874
- t.arrowFunctionExpression([], emitChildrenProp(node.children, context)),
875
- node.fallback ? Array.isArray(node.fallback) ? t.arrowFunctionExpression([], emitChildrenProp(node.fallback, context)) : t.arrowFunctionExpression([], parseExpressionIR(node.fallback)) : t.identifier("undefined")
876
- ]);
877
- }
878
- function emitFor$1(node, context) {
879
- const params = [t.identifier(node.item.name)];
880
- if (node.index) params.push(t.identifier(node.index.name));
881
- const props = [t.objectProperty(t.identifier("each"), parseExpressionIR(node.each)), t.objectProperty(t.identifier("children"), t.arrowFunctionExpression(params, emitChildrenProp(node.body, context)))];
882
- if (node.by) props.push(t.objectProperty(t.identifier("by"), parseExpressionIR(node.by)));
883
- return t.callExpression(context.importRuntime("createComponent"), [context.importRuntime("For"), t.objectExpression(props)]);
884
- }
885
- function emitMountFor(node, context) {
886
- const params = [t.identifier(node.item.name)];
887
- if (node.index) params.push(t.identifier(node.index.name));
888
- const path = node.domPath;
889
- if (!path || path.kind !== "Marker") throw new Error("For DOM path is not assigned");
890
- return t.callExpression(context.importRuntime("mountFor"), [
891
- t.identifier(path.parent.name),
892
- emitMarkerIdentifier(node),
893
- t.arrowFunctionExpression([], parseExpressionIR(node.each)),
894
- node.by ? parseExpressionIR(node.by) : t.identifier("undefined"),
895
- t.arrowFunctionExpression(params, emitChildrenProp(node.body, context))
896
- ]);
897
- }
898
- function emitHost(node, context) {
899
- const props = buildHostProps(node, context);
900
- const hostIdent = context.importRuntime("Host");
901
- if (!node.child) return t.callExpression(hostIdent, [t.objectExpression(props)]);
902
- const childExpr = emitNodeExpression(node.child, context);
903
- const hostCall = t.callExpression(hostIdent, [t.objectExpression(props)]);
904
- return t.callExpression(t.arrowFunctionExpression([], t.blockStatement([t.expressionStatement(hostCall), t.returnStatement(childExpr)])), []);
905
- }
906
- function buildHostProps(node, context) {
907
- const props = [];
908
- for (const attr of node.attrs) {
909
- const key = createObjectKey$1(attr.name);
910
- const expression = parseExpressionIR(attr.expr);
911
- if (isStaticValue(expression) || isGetterExpression(expression)) props.push(t.objectProperty(key, expression));
912
- else props.push(t.objectProperty(key, t.arrowFunctionExpression([], expression)));
913
- }
914
- return props;
915
- }
916
- function isStaticValue(expr) {
917
- return t.isStringLiteral(expr) || t.isNumericLiteral(expr) || t.isBooleanLiteral(expr) || t.isNullLiteral(expr);
918
- }
919
- function isGetterExpression(expr) {
920
- return t.isArrowFunctionExpression(expr) || t.isFunctionExpression(expr);
921
- }
922
- function createObjectKey$1(name) {
923
- return t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name);
924
- }
925
- function emitSlot(node, context) {
926
- return t.callExpression(context.importRuntime("createSlot"), [node.name ? t.stringLiteral(node.name) : t.identifier("undefined"), node.fallback.length > 0 ? t.arrowFunctionExpression([], emitChildrenProp(node.fallback, context)) : t.identifier("undefined")]);
927
- }
928
- function emitMarkerIdentifier(node) {
929
- return t.identifier(node.ref.name);
930
- }
931
- //#endregion
932
- //#region packages/core/compiler/src/codegen/dom/index.ts
933
- function emitDOM(node, context) {
934
- switch (node.kind) {
935
- case "Element": return emitElement$1(node, context);
936
- case "Fragment": return emitFragment(node, context);
937
- case "Component": return emitComponent$1(node, context);
938
- case "Show": return emitShow$1(node, context);
939
- case "For": return emitFor$1(node, context);
940
- case "Host": return emitHost(node, context);
941
- case "Slot": return emitSlot(node, context);
942
- case "DynamicText": return t.arrowFunctionExpression([], parseExpressionIR(node.expr));
943
- default: throw new Error(`Unsupported root IR node: ${node.kind}`);
944
- }
945
- }
946
- //#endregion
947
- //#region packages/core/compiler/src/codegen/ssr/rawText.ts
948
- function getSSRRawTextTag(tagName) {
949
- const normalized = tagName.toLowerCase();
950
- return normalized === "script" || normalized === "style" ? normalized : void 0;
951
- }
952
- //#endregion
953
- //#region packages/core/compiler/src/codegen/ssr/property.ts
954
- const BOOLEAN_PROPERTY_ELEMENTS = {
955
- checked: /* @__PURE__ */ new Set(["input"]),
956
- disabled: /* @__PURE__ */ new Set([
957
- "button",
958
- "fieldset",
959
- "input",
960
- "optgroup",
961
- "option",
962
- "select",
963
- "textarea"
964
- ]),
965
- multiple: /* @__PURE__ */ new Set(["input", "select"]),
966
- readOnly: /* @__PURE__ */ new Set(["input", "textarea"]),
967
- selected: /* @__PURE__ */ new Set(["option"])
968
- };
969
- const VALUE_PROPERTY_ELEMENTS = /* @__PURE__ */ new Set([
970
- "button",
971
- "input",
972
- "option",
973
- "textarea"
974
- ]);
975
- function isSSRPropertySupported(tag, name) {
976
- var _BOOLEAN_PROPERTY_ELE;
977
- const normalizedTag = tag.toLowerCase();
978
- if (name === "tabIndex") return true;
979
- if (name === "htmlFor") return normalizedTag === "label";
980
- if (name === "value") return VALUE_PROPERTY_ELEMENTS.has(normalizedTag);
981
- return Boolean((_BOOLEAN_PROPERTY_ELE = BOOLEAN_PROPERTY_ELEMENTS[name]) === null || _BOOLEAN_PROPERTY_ELE === void 0 ? void 0 : _BOOLEAN_PROPERTY_ELE.has(normalizedTag));
982
- }
983
- //#endregion
984
- //#region packages/core/compiler/src/diagnostics/codes.ts
985
- const CompilerErrorCode = {
986
- UNSUPPORTED_SPREAD_ATTRIBUTE: "ZEUS_UNSUPPORTED_SPREAD_ATTRIBUTE",
987
- UNSUPPORTED_SPREAD_CHILD: "ZEUS_UNSUPPORTED_SPREAD_CHILD",
988
- UNSUPPORTED_FRAGMENT: "ZEUS_UNSUPPORTED_FRAGMENT",
989
- UNSUPPORTED_FRAGMENT_CHILD: "ZEUS_UNSUPPORTED_FRAGMENT_CHILD",
990
- UNSUPPORTED_COMPONENT_PROP: "ZEUS_UNSUPPORTED_COMPONENT_PROP",
991
- EMPTY_EXPRESSION: "ZEUS_EMPTY_EXPRESSION",
992
- INVALID_TRANSFORM_RESULT: "ZEUS_INVALID_TRANSFORM_RESULT",
993
- UNSUPPORTED_NODE: "ZEUS_UNSUPPORTED_NODE",
994
- INVALID_BUILTIN_USAGE: "ZEUS_INVALID_BUILTIN_USAGE",
995
- UNSUPPORTED_SSR_BUILTIN: "ZEUS_UNSUPPORTED_SSR_BUILTIN",
996
- UNSUPPORTED_SSR_PROPERTY: "ZEUS_UNSUPPORTED_SSR_PROPERTY",
997
- UNSUPPORTED_SSR_RAW_TEXT_CHILD: "ZEUS_UNSUPPORTED_SSR_RAW_TEXT_CHILD",
998
- INVALID_REF_USAGE: "ZEUS_INVALID_REF_USAGE"
999
- };
1000
- //#endregion
1001
- //#region packages/core/compiler/src/diagnostics/CompilerDiagnostic.ts
1002
- function createCompilerDiagnostic(input) {
1003
- var _input$severity;
1004
- return _objectSpread2(_objectSpread2(_objectSpread2({
1005
- code: input.code,
1006
- severity: (_input$severity = input.severity) !== null && _input$severity !== void 0 ? _input$severity : "error",
1007
- message: input.message
1008
- }, input.hint === void 0 ? {} : { hint: input.hint }), input.filename === void 0 ? {} : { filename: input.filename }), input.span === void 0 ? {} : { span: input.span });
1009
- }
1010
- function formatCompilerDiagnostic(diagnostic) {
1011
- const hint = diagnostic.hint ? `\nHint: ${diagnostic.hint}` : "";
1012
- return `[${diagnostic.code}] ${diagnostic.message}${hint}`;
1013
- }
1014
- //#endregion
1015
- //#region packages/core/compiler/src/diagnostics/CompilerError.ts
1016
- var CompilerError = class extends Error {
1017
- constructor(options) {
1018
- const diagnostic = createCompilerDiagnostic(_objectSpread2(_objectSpread2({}, options), {}, { severity: "error" }));
1019
- super(formatCompilerDiagnostic(diagnostic));
1020
- this.name = "ZeusCompilerError";
1021
- this.diagnostic = diagnostic;
1022
- this.code = diagnostic.code;
1023
- this.severity = "error";
1024
- this.hint = diagnostic.hint;
1025
- this.filename = diagnostic.filename;
1026
- this.span = diagnostic.span;
1027
- this.loc = diagnostic.span ? {
1028
- line: diagnostic.span.start.line,
1029
- column: diagnostic.span.start.column
1030
- } : void 0;
1031
- }
1032
- };
1033
- //#endregion
1034
- //#region packages/core/compiler/src/codegen/ssr/validate.ts
1035
- function assertSSRSupported(node, filename, rawTextTag) {
1036
- if (rawTextTag && (node.kind === "Element" || node.kind === "Component")) throwUnsupportedSSRRawTextChild(node, rawTextTag, filename);
1037
- switch (node.kind) {
1038
- case "Host":
1039
- case "Slot": throwUnsupportedSSRBuiltin(node, filename);
1040
- case "Element":
1041
- for (const attribute of node.attrs) if (attribute.kind === "PropBinding" && !isSSRPropertySupported(node.tagName, attribute.name)) throwUnsupportedSSRProperty(node, attribute, filename);
1042
- const childRawTextTag = getSSRRawTextTag(node.tagName);
1043
- for (const child of node.children) assertSSRSupported(child, filename, childRawTextTag);
1044
- return;
1045
- case "Fragment":
1046
- for (const child of node.children) assertSSRSupported(child, filename, rawTextTag);
1047
- return;
1048
- case "Component":
1049
- for (const prop of node.props) {
1050
- if (!Array.isArray(prop.value)) continue;
1051
- for (const child of prop.value) assertSSRSupported(child, filename);
1052
- }
1053
- return;
1054
- case "Show":
1055
- for (const child of node.children) assertSSRSupported(child, filename, rawTextTag);
1056
- if (Array.isArray(node.fallback)) for (const child of node.fallback) assertSSRSupported(child, filename, rawTextTag);
1057
- return;
1058
- case "For":
1059
- for (const child of node.body) assertSSRSupported(child, filename, rawTextTag);
1060
- return;
1061
- case "Text":
1062
- case "DynamicText": return;
1063
- }
1064
- }
1065
- function throwUnsupportedSSRRawTextChild(node, tag, filename) {
1066
- throw new CompilerError({
1067
- code: CompilerErrorCode.UNSUPPORTED_SSR_RAW_TEXT_CHILD,
1068
- message: `${node.kind} children are not supported inside <${tag}> SSR raw text.`,
1069
- hint: "Use text expressions, Fragment, Show, or For directly inside the raw-text element.",
1070
- filename,
1071
- span: node.span
1072
- });
1073
- }
1074
- function throwUnsupportedSSRProperty(element, property, filename) {
1075
- var _ref, _property$span;
1076
- throw new CompilerError({
1077
- code: CompilerErrorCode.UNSUPPORTED_SSR_PROPERTY,
1078
- message: `Property "${property.name}" on <${element.tagName}> cannot be serialized by SSR codegen.`,
1079
- hint: "Use an equivalent HTML attribute binding or move this DOM-only property update to client code.",
1080
- filename,
1081
- span: (_ref = (_property$span = property.span) !== null && _property$span !== void 0 ? _property$span : property.expr.span) !== null && _ref !== void 0 ? _ref : element.span
1082
- });
1083
- }
1084
- function throwUnsupportedSSRBuiltin(node, filename) {
1085
- throw new CompilerError({
1086
- code: CompilerErrorCode.UNSUPPORTED_SSR_BUILTIN,
1087
- message: `<${node.kind}> is not supported by SSR codegen.`,
1088
- hint: "Render Web Components on the client; the SSR baseline supports DOM components only.",
1089
- filename,
1090
- span: node.span
1091
- });
1092
- }
1093
- //#endregion
1094
- //#region packages/core/compiler/src/codegen/ssr/index.ts
1095
- function emitSSR(node, context, rawTextTag) {
1096
- switch (node.kind) {
1097
- case "Element": return emitElement(node, context);
1098
- case "Fragment": return emitChildren(node.children, context, rawTextTag);
1099
- case "Text":
1100
- if (rawTextTag) return t.stringLiteral(decodeCompilerEscapedText(node.value));
1101
- return t.callExpression(context.importRuntime("ssrStatic"), [t.stringLiteral(node.value)]);
1102
- case "DynamicText":
1103
- if (rawTextTag) return parseExpressionIR(node.expr);
1104
- return t.callExpression(context.importRuntime("ssrText"), [parseExpressionIR(node.expr)]);
1105
- case "Component": return emitComponent(node, context);
1106
- case "Show": return emitShow(node, context, rawTextTag);
1107
- case "For": return emitFor(node, context, rawTextTag);
1108
- case "Host":
1109
- case "Slot": return throwUnsupportedSSRBuiltin(node);
1110
- default: return throwUnsupportedSSRNode(node);
1111
- }
1112
- }
1113
- function emitShow(node, context, rawTextTag) {
1114
- const args = [t.arrowFunctionExpression([], parseExpressionIR(node.when)), t.arrowFunctionExpression([], emitChildrenValue(node.children, context, rawTextTag))];
1115
- if (node.fallback) {
1116
- const fallback = Array.isArray(node.fallback) ? emitChildrenValue(node.fallback, context, rawTextTag) : parseExpressionIR(node.fallback);
1117
- args.push(t.arrowFunctionExpression([], fallback));
1118
- }
1119
- return t.callExpression(context.importRuntime("ssrShow"), args);
1120
- }
1121
- function emitFor(node, context, rawTextTag) {
1122
- const params = [t.identifier(node.item.name)];
1123
- if (node.index) params.push(t.identifier(node.index.name));
1124
- return t.callExpression(context.importRuntime("ssrFor"), [t.arrowFunctionExpression([], parseExpressionIR(node.each)), t.arrowFunctionExpression(params, emitChildrenValue(node.body, context, rawTextTag))]);
1125
- }
1126
- function emitComponent(node, context) {
1127
- return t.callExpression(context.importRuntime("ssrComponent"), [parseExpressionIR(node.callee), t.objectExpression(node.props.map((prop) => emitComponentProp(prop, context)))]);
1128
- }
1129
- function emitComponentProp(prop, context) {
1130
- const key = createObjectKey(prop.name);
1131
- if (Array.isArray(prop.value)) return t.objectMethod("get", key, [], t.blockStatement([t.returnStatement(emitChildrenValue(prop.value, context))]));
1132
- const value = parseExpressionIR(prop.value);
1133
- if (isStaticPropValue(value)) return t.objectProperty(key, value);
1134
- return t.objectMethod("get", key, [], t.blockStatement([t.returnStatement(value)]));
1135
- }
1136
- function emitElement(node, context) {
1137
- const rawTextTag = getSSRRawTextTag(node.tagName);
1138
- const args = [t.stringLiteral(node.tagName), t.arrayExpression(node.attrs.flatMap((attr) => {
1139
- switch (attr.kind) {
1140
- case "StaticAttribute":
1141
- if (isEventAttributeName$1(attr.name)) return [];
1142
- return [emitStaticAttribute(attr, context)];
1143
- case "AttrBinding": return [emitAttributeBinding(attr, context)];
1144
- case "PropBinding": return [emitPropertyBinding(attr, context)];
1145
- default: return [];
1146
- }
1147
- }))];
1148
- if (node.children.length > 0) args.push(emitChildren(node.children, context, rawTextTag));
1149
- if (node.flags.isVoid) {
1150
- if (node.children.length === 0) args.push(t.identifier("undefined"));
1151
- args.push(t.booleanLiteral(true));
1152
- }
1153
- return t.callExpression(context.importRuntime("ssrElement"), args);
1154
- }
1155
- function emitAttributeBinding(attr, context) {
1156
- const name = normalizeAttributeName(attr.name);
1157
- return t.callExpression(context.importRuntime("ssrAttr"), [t.stringLiteral(name), emitBindingValue(attr.expr)]);
1158
- }
1159
- function emitPropertyBinding(attr, context) {
1160
- return t.callExpression(context.importRuntime("ssrProp"), [t.stringLiteral(attr.name), emitBindingValue(attr.expr)]);
1161
- }
1162
- function emitBindingValue(expression) {
1163
- const value = parseExpressionIR(expression);
1164
- if (t.isArrowFunctionExpression(value) || t.isFunctionExpression(value)) return t.callExpression(value, []);
1165
- return value;
1166
- }
1167
- function emitStaticAttribute(attr, context) {
1168
- return t.callExpression(context.importRuntime("ssrAttr"), [t.stringLiteral(normalizeAttributeName(attr.name)), attr.value === true ? t.booleanLiteral(true) : t.stringLiteral(attr.value)]);
1169
- }
1170
- function emitChildren(children, context, rawTextTag) {
1171
- return t.arrayExpression(children.map((child) => emitSSR(child, context, rawTextTag)));
1172
- }
1173
- function emitChildrenValue(children, context, rawTextTag) {
1174
- if (children.length === 1) return emitSSR(children[0], context, rawTextTag);
1175
- return emitChildren(children, context, rawTextTag);
1176
- }
1177
- function decodeCompilerEscapedText(value) {
1178
- return value.replace(/&lt;/g, "<").replace(/&amp;/g, "&");
1179
- }
1180
- function isStaticPropValue(value) {
1181
- return t.isStringLiteral(value) || t.isNumericLiteral(value) || t.isBooleanLiteral(value) || t.isNullLiteral(value);
1182
- }
1183
- function createObjectKey(name) {
1184
- return t.isValidIdentifier(name) ? t.identifier(name) : t.stringLiteral(name);
1185
- }
1186
- function normalizeAttributeName(name) {
1187
- return name === "className" ? "class" : name;
1188
- }
1189
- function isEventAttributeName$1(name) {
1190
- return name.length > 2 && name.slice(0, 2).toLowerCase() === "on";
1191
- }
1192
- function throwUnsupportedSSRNode(node) {
1193
- const kind = node.kind;
1194
- throw new Error(`Unsupported SSR IR node: ${kind}`);
1195
- }
1196
- //#endregion
1197
- //#region packages/core/compiler/src/adapters/babel/diagnostic.ts
1198
- function createBabelCompilerError(path, options) {
1199
- var _hub$file;
1200
- const hub = path.hub;
1201
- return new CompilerError(_objectSpread2(_objectSpread2({}, options), {}, {
1202
- filename: hub === null || hub === void 0 || (_hub$file = hub.file) === null || _hub$file === void 0 || (_hub$file = _hub$file.opts) === null || _hub$file === void 0 ? void 0 : _hub$file.filename,
1203
- span: sourceSpanFromBabelNode(path.node)
1204
- }));
1205
- }
1206
- //#endregion
1207
- //#region packages/core/compiler/src/parse/jsx.ts
1208
- /**
1209
- * JSX AST parsing utilities.
1210
- *
1211
- * Low-level helpers for extracting and interpreting information from Babel's
1212
- * JSX AST nodes — tag names, attribute names, and path type guards.
1213
- * These do NOT produce IR or Babel AST; they only read the JSX tree.
1214
- */
1215
- function jsxElementNameToString(node) {
1216
- if (t.isJSXMemberExpression(node)) return `${jsxElementNameToString(node.object)}.${node.property.name}`;
1217
- if (t.isJSXIdentifier(node) || t.isIdentifier(node)) return node.name;
1218
- return `${node.namespace.name}:${node.name.name}`;
1219
- }
1220
- function getTagName(node) {
1221
- return jsxElementNameToString(node.openingElement.name);
1222
- }
1223
- function getJSXAttrName(name) {
1224
- if (t.isJSXNamespacedName(name)) return `${name.namespace.name}:${name.name.name}`;
1225
- return name.name;
1226
- }
1227
- function isComponentTag(tagName) {
1228
- return /^[A-Z]/.test(tagName) || tagName.includes(".");
1229
- }
1230
- function toEventName(name) {
1231
- return name.slice(2).toLowerCase();
1232
- }
1233
- //#endregion
1234
- //#region packages/core/compiler/src/lower/lowerAttribute.ts
1235
- function lowerAttribute(path, _context) {
1236
- if (path.isJSXSpreadAttribute() || t.isJSXSpreadAttribute(path.node)) throw createBabelCompilerError(path, {
1237
- code: CompilerErrorCode.UNSUPPORTED_SPREAD_ATTRIBUTE,
1238
- message: "Spread attributes are not supported in Zeus MVP.",
1239
- hint: "Use explicit attributes instead, for example <div id={id} />."
1240
- });
1241
- const node = path.node;
1242
- const name = getJSXAttrName(node.name);
1243
- const value = path.get("value");
1244
- if (!value.node) {
1245
- if (name === "ref") throw createBabelCompilerError(path, {
1246
- code: CompilerErrorCode.EMPTY_EXPRESSION,
1247
- message: "ref attribute requires an expression.",
1248
- hint: "Use <div ref={target} /> instead."
1249
- });
1250
- return staticAttrIR(name, true);
1251
- }
1252
- if (value.isStringLiteral()) {
1253
- if (name === "ref") throw createBabelCompilerError(path, {
1254
- code: CompilerErrorCode.INVALID_REF_USAGE,
1255
- message: "String refs are not supported in Zeus.",
1256
- hint: "Use a state holder or callback ref: <div ref={el} />."
1257
- });
1258
- return staticAttrIR(name, value.node.value);
1259
- }
1260
- if (value.isJSXExpressionContainer()) {
1261
- const expression = value.get("expression");
1262
- if (expression.isJSXEmptyExpression()) throw createBabelCompilerError(path, {
1263
- code: CompilerErrorCode.EMPTY_EXPRESSION,
1264
- message: `Attribute "${name}" expression cannot be empty.`
1265
- });
1266
- if (!expression.isExpression()) return null;
1267
- const expr = lowerExpressionIR(expression);
1268
- if (name === "ref") return refBindingIR(expr);
1269
- if (isEventAttributeName(name)) return eventBindingIR(toEventName(name), expr);
1270
- if (name.startsWith("prop:")) return propBindingIR(name.slice(5), expr);
1271
- return attrBindingIR(name, expr);
1272
- }
1273
- return null;
1274
- }
1275
- function isEventAttributeName(name) {
1276
- return name.length > 2 && name.slice(0, 2).toLowerCase() === "on";
1277
- }
1278
- //#endregion
1279
- //#region packages/core/compiler/src/lower/lowerChildren.ts
1280
- function lowerChildren(children, context) {
1281
- const result = [];
1282
- for (const child of children) {
1283
- if (child.isJSXText()) {
1284
- const text = trimJSXText(child.node.value);
1285
- if (text) result.push(textIR(escapeHTML(text)));
1286
- continue;
1287
- }
1288
- if (child.isJSXExpressionContainer()) {
1289
- const expression = child.get("expression");
1290
- if (expression.isJSXEmptyExpression()) continue;
1291
- if (expression.isExpression()) result.push(dynamicTextIR(lowerExpressionIR(expression), ref(context.uid("anchor$").name)));
1292
- continue;
1293
- }
1294
- if (child.isJSXElement() || child.isJSXFragment()) {
1295
- result.push(lowerJSX(child, context));
1296
- continue;
1297
- }
1298
- }
1299
- return result;
1300
- }
1301
- //#endregion
1302
- //#region packages/core/compiler/src/lower/lowerBuiltin.ts
1303
- const HOST_SKIP_PROPS = /* @__PURE__ */ new Set([
1304
- "key",
1305
- "__slot",
1306
- "__anchor"
1307
- ]);
1308
- function isBuiltinTag(tagName) {
1309
- return tagName === "Show" || tagName === "For" || tagName === "Host" || tagName === "Slot";
1310
- }
1311
- function lowerBuiltin(path, context) {
1312
- const tagName = path.node.openingElement.name;
1313
- if (!t.isJSXIdentifier(tagName)) throw createBabelCompilerError(path, {
1314
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1315
- message: "Built-in JSX nodes do not support member expressions."
1316
- });
1317
- switch (tagName.name) {
1318
- case "Show": return lowerShow(path, context);
1319
- case "For": return lowerFor(path, context);
1320
- case "Host": return lowerHost(path, context);
1321
- case "Slot": return lowerSlot(path, context);
1322
- default: throw createBabelCompilerError(path, {
1323
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1324
- message: `Unsupported built-in <${tagName.name}>.`
1325
- });
1326
- }
1327
- }
1328
- function lowerShow(path, context) {
1329
- const when = requiredExpressionAttr(path, "when");
1330
- const fallback = optionalShowFallbackAttr(path, context);
1331
- return showIR({
1332
- ref: ref(context.uid("show$").name),
1333
- when,
1334
- fallback,
1335
- children: lowerChildren(path.get("children"), context)
1336
- });
1337
- }
1338
- function optionalShowFallbackAttr(path, context) {
1339
- const attr = path.get("openingElement").get("attributes").find((attrPath) => {
1340
- if (!attrPath.isJSXAttribute()) return false;
1341
- return getJSXAttrName(attrPath.node.name) === "fallback";
1342
- });
1343
- if (!(attr === null || attr === void 0 ? void 0 : attr.isJSXAttribute())) return void 0;
1344
- const value = attr.get("value");
1345
- if (!value.node) return expressionIRFromCode("true", attr.node);
1346
- if (value.isStringLiteral()) return expressionIRFromCode(JSON.stringify(value.node.value), value.node);
1347
- if (!value.isJSXExpressionContainer()) return void 0;
1348
- const expression = value.get("expression");
1349
- if (expression.isJSXEmptyExpression()) return void 0;
1350
- if (expression.isJSXElement() || expression.isJSXFragment()) return [lowerJSX(expression, context)];
1351
- if (expression.isExpression()) return lowerExpressionIR(expression);
1352
- }
1353
- function lowerFor(path, context) {
1354
- const each = requiredExpressionAttr(path, "each");
1355
- const by = optionalExpressionAttr(path, "by");
1356
- const render = getOnlyRenderFunction(path);
1357
- const item = getParamIdentifier(render, 0, "item");
1358
- const index = getParamIdentifier(render, 1);
1359
- const bodyPath = render.get("body");
1360
- const body = [];
1361
- if (bodyPath.isJSXElement() || bodyPath.isJSXFragment()) body.push(lowerJSX(bodyPath, context));
1362
- else if (bodyPath.isExpression()) body.push(dynamicTextIR(lowerExpressionIR(bodyPath), ref(context.uid("anchor$").name)));
1363
- return forIR({
1364
- ref: ref(context.uid("for$").name),
1365
- each,
1366
- by,
1367
- item,
1368
- index,
1369
- body
1370
- });
1371
- }
1372
- function lowerSlot(path, context) {
1373
- const name = optionalStringAttr(path, "name");
1374
- return slotIR({
1375
- ref: ref(context.uid("slot$").name),
1376
- name,
1377
- fallback: lowerChildren(path.get("children"), context),
1378
- span: sourceSpanFromBabelNode(path.node)
1379
- });
1380
- }
1381
- function requiredExpressionAttr(path, name) {
1382
- const value = optionalExpressionAttr(path, name);
1383
- if (!value) throw createBabelCompilerError(path, {
1384
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1385
- message: `<${getBuiltinName(path)}> requires "${name}".`
1386
- });
1387
- return value;
1388
- }
1389
- function optionalExpressionAttr(path, name) {
1390
- const attr = path.get("openingElement").get("attributes").find((attrPath) => {
1391
- if (!attrPath.isJSXAttribute()) return false;
1392
- return getJSXAttrName(attrPath.node.name) === name;
1393
- });
1394
- if (!(attr === null || attr === void 0 ? void 0 : attr.isJSXAttribute())) return void 0;
1395
- const value = attr.get("value");
1396
- if (!value.node) return expressionIRFromCode("true", attr.node);
1397
- if (value.isStringLiteral()) return expressionIRFromCode(JSON.stringify(value.node.value), value.node);
1398
- if (!value.isJSXExpressionContainer()) return void 0;
1399
- const expression = value.get("expression");
1400
- if (expression.isExpression()) return lowerExpressionIR(expression);
1401
- }
1402
- function optionalStringAttr(path, name) {
1403
- const attr = path.get("openingElement").get("attributes").find((attrPath) => {
1404
- if (!attrPath.isJSXAttribute()) return false;
1405
- return getJSXAttrName(attrPath.node.name) === name;
1406
- });
1407
- if (!(attr === null || attr === void 0 ? void 0 : attr.isJSXAttribute())) return void 0;
1408
- const value = attr.node.value;
1409
- if (!value) return "";
1410
- if (t.isStringLiteral(value)) return value.value;
1411
- }
1412
- function getOnlyRenderFunction(path) {
1413
- const expressions = path.get("children").filter((child) => child.isJSXExpressionContainer()).map((child) => child.get("expression")).filter((expression) => expression.isArrowFunctionExpression() || expression.isFunctionExpression());
1414
- if (expressions.length !== 1) throw createBabelCompilerError(path, {
1415
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1416
- message: "<For> requires exactly one render function child."
1417
- });
1418
- return expressions[0];
1419
- }
1420
- function getParamIdentifier(path, index, fallback) {
1421
- const param = path.node.params[index];
1422
- if (t.isIdentifier(param)) return identifierIR(param.name, sourceSpanFromBabelNode(param));
1423
- if (fallback) return identifierIR(fallback);
1424
- }
1425
- function getBuiltinName(path) {
1426
- const name = path.node.openingElement.name;
1427
- return t.isJSXIdentifier(name) ? name.name : "Builtin";
1428
- }
1429
- function isEventLikeProp(key) {
1430
- return /^on[A-Z]/.test(key) || key.startsWith("on:");
1431
- }
1432
- function normalizeHostAttrName(name) {
1433
- switch (name) {
1434
- case "className": return "class";
1435
- case "htmlFor": return "for";
1436
- case "tabIndex": return "tabindex";
1437
- case "readOnly": return "readonly";
1438
- default: return name;
1439
- }
1440
- }
1441
- function lowerHost(path, context) {
1442
- const attrs = [];
1443
- const rawChildren = lowerChildren(path.get("children"), context);
1444
- for (const attrPath of path.get("openingElement").get("attributes")) {
1445
- const node = attrPath.node;
1446
- if (t.isJSXSpreadAttribute(node)) throw createBabelCompilerError(attrPath, {
1447
- code: CompilerErrorCode.UNSUPPORTED_COMPONENT_PROP,
1448
- message: "Spread props are not supported on Host in Phase 1."
1449
- });
1450
- if (!attrPath.isJSXAttribute()) continue;
1451
- const name = getJSXAttrName(node.name);
1452
- if (HOST_SKIP_PROPS.has(name)) continue;
1453
- if (name === "children") continue;
1454
- if (name === "ref") {
1455
- const value = attrPath.get("value");
1456
- if (value.isJSXExpressionContainer()) {
1457
- const expr = value.get("expression");
1458
- if (expr.isExpression()) attrs.push({
1459
- id: id(),
1460
- kind: "HostAttr",
1461
- name: "ref",
1462
- expr: lowerExpressionIR(expr)
1463
- });
1464
- }
1465
- continue;
1466
- }
1467
- if (isEventLikeProp(name)) continue;
1468
- const value = attrPath.get("value");
1469
- if (!value.node) attrs.push({
1470
- id: id(),
1471
- kind: "HostAttr",
1472
- name: normalizeHostAttrName(name),
1473
- expr: expressionIRFromCode("true", node)
1474
- });
1475
- else if (value.isStringLiteral()) attrs.push({
1476
- id: id(),
1477
- kind: "HostAttr",
1478
- name: normalizeHostAttrName(name),
1479
- expr: expressionIRFromCode(JSON.stringify(value.node.value), value.node)
1480
- });
1481
- else if (value.isJSXExpressionContainer()) {
1482
- const expression = value.get("expression");
1483
- if (expression.isExpression()) attrs.push({
1484
- id: id(),
1485
- kind: "HostAttr",
1486
- name: normalizeHostAttrName(name),
1487
- expr: lowerExpressionIR(expression)
1488
- });
1489
- }
1490
- }
1491
- return hostIR({
1492
- attrs,
1493
- child: rawChildren.length === 0 ? void 0 : rawChildren.length === 1 ? rawChildren[0] : fragmentIR(rawChildren),
1494
- span: sourceSpanFromBabelNode(path.node)
1495
- });
1496
- }
1497
- //#endregion
1498
- //#region packages/core/compiler/src/lower/lowerComponent.ts
1499
- function lowerComponent(path, context) {
1500
- const tag = convertComponentIdentifier(path.node.openingElement.name);
1501
- const props = [];
1502
- for (const attr of path.get("openingElement").get("attributes")) {
1503
- const node = attr.node;
1504
- if (t.isJSXSpreadAttribute(node)) throw createBabelCompilerError(attr, {
1505
- code: CompilerErrorCode.UNSUPPORTED_COMPONENT_PROP,
1506
- message: "Spread props are not supported in Zeus MVP."
1507
- });
1508
- const name = getJSXAttrName(node.name);
1509
- const value = attr.get("value");
1510
- if (!value.node) {
1511
- props.push({
1512
- name,
1513
- value: expressionIRFromCode("true", node)
1514
- });
1515
- continue;
1516
- }
1517
- if (value.isStringLiteral()) {
1518
- props.push({
1519
- name,
1520
- value: expressionIRFromCode(JSON.stringify(value.node.value), value.node)
1521
- });
1522
- continue;
1523
- }
1524
- if (value.isJSXExpressionContainer()) {
1525
- const expression = value.get("expression");
1526
- if (expression.isJSXEmptyExpression()) throw createBabelCompilerError(attr, {
1527
- code: CompilerErrorCode.EMPTY_EXPRESSION,
1528
- message: `Component prop "${name}" expression cannot be empty.`
1529
- });
1530
- if (expression.isExpression()) props.push({
1531
- name,
1532
- value: lowerExpressionIR(expression)
1533
- });
1534
- }
1535
- }
1536
- const children = lowerChildren(path.get("children"), context);
1537
- if (children.length > 0) props.push({
1538
- name: "children",
1539
- value: children
1540
- });
1541
- return componentIR({
1542
- ref: ref(context.uid("cmp$").name),
1543
- callee: tag,
1544
- props,
1545
- span: sourceSpanFromBabelNode(path.node)
1546
- });
1547
- }
1548
- function convertComponentIdentifier(node) {
1549
- return expressionIRFromCode(componentIdentifierCode(node), node);
1550
- }
1551
- function componentIdentifierCode(node) {
1552
- if (t.isJSXIdentifier(node)) {
1553
- if (node.name === "this") return "this";
1554
- return t.isValidIdentifier(node.name) ? node.name : JSON.stringify(node.name);
1555
- }
1556
- if (t.isJSXMemberExpression(node)) {
1557
- const object = componentIdentifierCode(node.object);
1558
- const property = node.property.name;
1559
- return t.isValidIdentifier(property) ? `${object}.${property}` : `${object}[${JSON.stringify(property)}]`;
1560
- }
1561
- if (t.isJSXNamespacedName(node)) return JSON.stringify(`${node.namespace.name}:${node.name.name}`);
1562
- return JSON.stringify("");
1563
- }
1564
- //#endregion
1565
- //#region packages/core/compiler/src/lower/lowerElement.ts
1566
- function lowerElement(path, context) {
1567
- const tagName = getTagName(path.node);
1568
- if (isBuiltinTag(tagName)) return lowerBuiltin(path, context);
1569
- if (isComponentTag(tagName)) return lowerComponent(path, context);
1570
- const attrs = path.get("openingElement").get("attributes").map((attr) => lowerAttribute(attr, context)).filter(Boolean);
1571
- return elementIR({
1572
- ref: ref(context.uid("el$").name),
1573
- tagName,
1574
- attrs,
1575
- children: VoidElements.includes(tagName) ? [] : lowerChildren(path.get("children"), context),
1576
- span: sourceSpanFromBabelNode(path.node),
1577
- flags: {
1578
- isVoid: VoidElements.includes(tagName),
1579
- isCustomElement: tagName.includes("-")
1580
- }
1581
- });
1582
- }
1583
- //#endregion
1584
- //#region packages/core/compiler/src/lower/lowerFragment.ts
1585
- function lowerFragment(path, context) {
1586
- return fragmentIR(lowerChildren(path.get("children"), context));
1587
- }
1588
- //#endregion
1589
- //#region packages/core/compiler/src/lower/lowerJSX.ts
1590
- function lowerJSX(path, context) {
1591
- if (path.isJSXElement()) return lowerElement(path, context);
1592
- if (path.isJSXFragment()) return lowerFragment(path, context);
1593
- throw new Error("Unsupported JSX node");
1594
- }
1595
- //#endregion
1596
- //#region packages/core/compiler/src/passes/normalizeChildren.ts
1597
- function normalizeChildren(node) {
1598
- visit$2(node);
1599
- return node;
1600
- }
1601
- function visit$2(node) {
1602
- switch (node.kind) {
1603
- case "Element":
1604
- case "Fragment":
1605
- node.children = node.children.filter((child) => {
1606
- if (child.kind === "Text") return child.value.length > 0;
1607
- return true;
1608
- });
1609
- for (const child of node.children) visit$2(child);
1610
- return;
1611
- case "Host":
1612
- if (node.child) visit$2(node.child);
1613
- return;
1614
- case "Component":
1615
- for (const prop of node.props) {
1616
- if (!Array.isArray(prop.value)) continue;
1617
- prop.value = prop.value.filter((child) => {
1618
- if (child.kind === "Text") return child.value.length > 0;
1619
- return true;
1620
- });
1621
- for (const child of prop.value) visit$2(child);
1622
- }
1623
- return;
1624
- case "Slot":
1625
- node.fallback = node.fallback.filter((child) => {
1626
- if (child.kind === "Text") return child.value.length > 0;
1627
- return true;
1628
- });
1629
- for (const child of node.fallback) visit$2(child);
1630
- return;
1631
- case "Show":
1632
- for (const child of node.children) visit$2(child);
1633
- if (Array.isArray(node.fallback)) {
1634
- node.fallback = node.fallback.filter((child) => {
1635
- if (child.kind === "Text") return child.value.length > 0;
1636
- return true;
1637
- });
1638
- for (const child of node.fallback) visit$2(child);
1639
- }
1640
- return;
1641
- case "For":
1642
- for (const child of node.body) visit$2(child);
1643
- return;
1644
- case "Text":
1645
- case "DynamicText": return;
1646
- }
1647
- }
1648
- //#endregion
1649
- //#region packages/core/compiler/src/passes/assignDomPaths.ts
1650
- function assignDomPaths(node) {
1651
- visitNode$1(node);
1652
- return node;
1653
- }
1654
- function visitNode$1(node, parent) {
1655
- switch (node.kind) {
1656
- case "Element":
1657
- assignElementPath(node, parent);
1658
- assignChildPaths(node);
1659
- return;
1660
- case "Fragment":
1661
- for (const child of node.children) visitNode$1(child, parent);
1662
- return;
1663
- case "Component":
1664
- for (const prop of node.props) {
1665
- if (!Array.isArray(prop.value)) continue;
1666
- for (const child of prop.value) visitNode$1(child);
1667
- }
1668
- return;
1669
- case "Show":
1670
- for (const child of node.children) visitNode$1(child);
1671
- if (Array.isArray(node.fallback)) for (const child of node.fallback) visitNode$1(child);
1672
- return;
1673
- case "For":
1674
- for (const child of node.body) visitNode$1(child);
1675
- return;
1676
- case "Host":
1677
- if (node.child) visitNode$1(node.child, parent);
1678
- return;
1679
- case "Slot":
1680
- for (const child of node.fallback) visitNode$1(child);
1681
- return;
1682
- case "Text":
1683
- case "DynamicText": return;
1684
- }
1685
- }
1686
- function assignElementPath(node, parent) {
1687
- if (!parent) {
1688
- node.domPath = { kind: "Root" };
1689
- return;
1690
- }
1691
- const templateChildren = parent.children.filter(isTemplateChild);
1692
- const index = templateChildren.indexOf(node);
1693
- if (index === -1) return;
1694
- if (index === 0) {
1695
- node.domPath = {
1696
- kind: "FirstChild",
1697
- parent: parent.ref
1698
- };
1699
- return;
1700
- }
1701
- const previous = templateChildren[index - 1];
1702
- if (previous.kind === "Element") {
1703
- node.domPath = {
1704
- kind: "NextSibling",
1705
- previous: previous.ref
1706
- };
1707
- return;
1708
- }
1709
- node.domPath = {
1710
- kind: "Child",
1711
- parent: parent.ref,
1712
- index
1713
- };
1714
- }
1715
- function assignChildPaths(parent) {
1716
- let markerIndex = 0;
1717
- for (const child of parent.children) {
1718
- if (isMarkerTemplateNode(child)) {
1719
- assignMarkerPath(child, parent.ref, markerIndex++);
1720
- visitNode$1(child);
1721
- continue;
1722
- }
1723
- visitNode$1(child, parent);
1724
- }
1725
- }
1726
- function assignMarkerPath(node, parent, index) {
1727
- node.domPath = {
1728
- kind: "Marker",
1729
- parent,
1730
- index
1731
- };
1732
- }
1733
- function isTemplateChild(node) {
1734
- return node.kind === "Element" || node.kind === "DynamicText" || node.kind === "Component" || node.kind === "Show" || node.kind === "For" || node.kind === "Slot";
1735
- }
1736
- function isMarkerTemplateNode(node) {
1737
- return node.kind === "DynamicText" || node.kind === "Component" || node.kind === "Show" || node.kind === "For" || node.kind === "Slot";
1738
- }
1739
- //#endregion
1740
- //#region packages/core/compiler/src/passes/assignPhysicalDomPaths.ts
1741
- function assignPhysicalDomPaths(node) {
1742
- visitNode(node);
1743
- return node;
1744
- }
1745
- function visitNode(node, parent) {
1746
- switch (node.kind) {
1747
- case "Element":
1748
- assignElementPhysicalPath(node, parent);
1749
- assignChildrenPhysicalPaths(node);
1750
- return;
1751
- case "Fragment":
1752
- for (const child of node.children) visitNode(child, parent);
1753
- return;
1754
- case "Host":
1755
- if (node.child) visitNode(node.child, parent);
1756
- return;
1757
- case "Show":
1758
- for (const child of node.children) visitNode(child);
1759
- if (Array.isArray(node.fallback)) for (const child of node.fallback) visitNode(child);
1760
- return;
1761
- case "For":
1762
- for (const child of node.body) visitNode(child);
1763
- return;
1764
- case "Slot":
1765
- for (const child of node.fallback) visitNode(child);
1766
- return;
1767
- case "Component":
1768
- for (const prop of node.props) {
1769
- if (!Array.isArray(prop.value)) continue;
1770
- for (const child of prop.value) visitNode(child);
1771
- }
1772
- return;
1773
- case "Text":
1774
- case "DynamicText": return;
1775
- }
1776
- }
1777
- function assignElementPhysicalPath(node, parent) {
1778
- if (!parent) {
1779
- node.physicalDomPath = { kind: "Root" };
1780
- return;
1781
- }
1782
- const physicalChildren = flattenPhysicalChildren(parent.children);
1783
- const index = physicalChildren.indexOf(node);
1784
- if (index < 0) return;
1785
- node.physicalDomPath = createPhysicalPath(parent.ref, physicalChildren, index);
1786
- }
1787
- function assignChildrenPhysicalPaths(parent) {
1788
- const physicalChildren = flattenPhysicalChildren(parent.children);
1789
- for (let index = 0; index < physicalChildren.length; index++) {
1790
- const child = physicalChildren[index];
1791
- if (child.kind === "TextPlaceholder") continue;
1792
- child.physicalDomPath = createPhysicalPath(parent.ref, physicalChildren, index);
1793
- }
1794
- for (const child of parent.children) visitNode(child, parent);
1795
- }
1796
- function createPhysicalPath(parent, children, index) {
1797
- if (index === 0) return {
1798
- kind: "FirstChild",
1799
- parent
1800
- };
1801
- const previous = findPreviousRefNode(children, index);
1802
- if (previous) return {
1803
- kind: "NextSibling",
1804
- previous: previous.ref
1805
- };
1806
- return {
1807
- kind: "ChildNode",
1808
- parent,
1809
- index
1810
- };
1811
- }
1812
- function findPreviousRefNode(children, index) {
1813
- for (let i = index - 1; i >= 0; i--) {
1814
- const node = children[i];
1815
- if (node.kind === "TextPlaceholder") continue;
1816
- return node;
1817
- }
1818
- }
1819
- function flattenPhysicalChildren(children) {
1820
- const result = [];
1821
- for (const child of children) appendPhysicalChild(result, child);
1822
- return result;
1823
- }
1824
- function appendPhysicalChild(result, node) {
1825
- switch (node.kind) {
1826
- case "Text":
1827
- if (node.value.length > 0) result.push({ kind: "TextPlaceholder" });
1828
- return;
1829
- case "Element":
1830
- case "DynamicText":
1831
- case "Component":
1832
- case "Show":
1833
- case "For":
1834
- case "Slot":
1835
- result.push(node);
1836
- return;
1837
- case "Fragment":
1838
- for (const child of node.children) appendPhysicalChild(result, child);
1839
- return;
1840
- case "Host":
1841
- if (node.child) appendPhysicalChild(result, node.child);
1842
- return;
1843
- }
1844
- }
1845
- //#endregion
1846
- //#region packages/core/compiler/src/passes/validateBuiltins.ts
1847
- function validateBuiltins(node, options) {
1848
- visit$1(node, {
1849
- isDefineElementRenderRoot: options.isDefineElementRenderRoot,
1850
- filename: options.filename,
1851
- insideHost: false,
1852
- root: true
1853
- });
1854
- }
1855
- function visit$1(node, state) {
1856
- switch (node.kind) {
1857
- case "Host":
1858
- if (!state.isDefineElementRenderRoot || !state.root) throw new CompilerError({
1859
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1860
- message: "<Host> can only be used as a defineElement root boundary.",
1861
- filename: state.filename,
1862
- span: node.span,
1863
- hint: "Return <Host> directly from the defineElement setup function."
1864
- });
1865
- if (node.child) visit$1(node.child, _objectSpread2(_objectSpread2({}, state), {}, {
1866
- insideHost: true,
1867
- root: false
1868
- }));
1869
- return;
1870
- case "Slot":
1871
- if (!state.insideHost) throw new CompilerError({
1872
- code: CompilerErrorCode.INVALID_BUILTIN_USAGE,
1873
- message: "<Slot> can only be used inside the defineElement Host boundary.",
1874
- filename: state.filename,
1875
- span: node.span,
1876
- hint: "Place <Slot> inside the root <Host> returned by defineElement setup."
1877
- });
1878
- for (const child of node.fallback) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1879
- return;
1880
- case "Element":
1881
- case "Fragment":
1882
- for (const child of node.children) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1883
- return;
1884
- case "Component":
1885
- for (const prop of node.props) {
1886
- if (!Array.isArray(prop.value)) continue;
1887
- for (const child of prop.value) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1888
- }
1889
- return;
1890
- case "Show":
1891
- for (const child of node.children) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1892
- if (Array.isArray(node.fallback)) for (const child of node.fallback) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1893
- return;
1894
- case "For":
1895
- for (const child of node.body) visit$1(child, _objectSpread2(_objectSpread2({}, state), {}, { root: false }));
1896
- return;
1897
- default: return;
1898
- }
1899
- }
1900
- //#endregion
1901
- //#region packages/core/compiler/src/passes/analyzeBindings.ts
1902
- function analyzeBindings(node) {
1903
- const analysis = {
1904
- dynamicText: 0,
1905
- dynamicAttrs: 0,
1906
- events: 0,
1907
- components: 0
1908
- };
1909
- visit(node, analysis);
1910
- return analysis;
1911
- }
1912
- function visit(node, analysis) {
1913
- switch (node.kind) {
1914
- case "Element":
1915
- for (const attr of node.attrs) {
1916
- if (attr.kind === "AttrBinding" || attr.kind === "PropBinding") analysis.dynamicAttrs++;
1917
- if (attr.kind === "EventBinding") analysis.events++;
1918
- }
1919
- for (const child of node.children) visit(child, analysis);
1920
- return;
1921
- case "DynamicText":
1922
- analysis.dynamicText++;
1923
- return;
1924
- case "Component":
1925
- analysis.components++;
1926
- for (const prop of node.props) {
1927
- if (!Array.isArray(prop.value)) continue;
1928
- for (const child of prop.value) visit(child, analysis);
1929
- }
1930
- return;
1931
- case "Fragment":
1932
- for (const child of node.children) visit(child, analysis);
1933
- return;
1934
- case "Host":
1935
- if (node.child) visit(node.child, analysis);
1936
- return;
1937
- case "Slot":
1938
- for (const child of node.fallback) visit(child, analysis);
1939
- return;
1940
- case "Show":
1941
- for (const child of node.children) visit(child, analysis);
1942
- if (Array.isArray(node.fallback)) for (const child of node.fallback) visit(child, analysis);
1943
- return;
1944
- case "For":
1945
- for (const child of node.body) visit(child, analysis);
1946
- return;
1947
- case "Text": return;
1948
- }
1949
- }
1950
- //#endregion
1951
- //#region packages/core/compiler/src/transform/index.ts
1952
- function transformJSX(path, state, config) {
1953
- if (state.get("skip")) return;
1954
- if (!path.isJSXElement() && !path.isJSXFragment()) return;
1955
- const context = getCompilerContext(path, config);
1956
- const ir = lowerJSX(path, context);
1957
- normalizeChildren(ir);
1958
- if (config.generate === "ssr") assertSSRSupported(ir, state.filename);
1959
- validateBuiltins(ir, {
1960
- isDefineElementRenderRoot: isDefineElementRenderRoot(path),
1961
- filename: state.filename
1962
- });
1963
- analyzeBindings(ir);
1964
- if (config.generate === "ssr") {
1965
- path.replaceWith(emitSSR(ir, context));
1966
- return;
1967
- }
1968
- assignDomPaths(ir);
1969
- assignPhysicalDomPaths(ir);
1970
- collectTemplates(ir, context);
1971
- path.replaceWith(emitDOM(ir, context));
1972
- }
1973
- //#endregion
1974
- //#region packages/core/compiler/src/visitor.ts
1975
- function createVisitor(config) {
1976
- return {
1977
- JSXElement(path, state) {
1978
- transformJSX(path, state, config);
1979
- },
1980
- JSXFragment(path, state) {
1981
- transformJSX(path, state, config);
1982
- },
1983
- Program: createProgramVisitor(config)
1984
- };
1985
- }
1986
- //#endregion
1987
- //#region packages/core/compiler/src/index.ts
1988
- function hasParserPlugin(plugins, name) {
1989
- return plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === name);
1990
- }
1991
- var src_default = declare((api, options) => {
1992
- api.assertVersion(8);
1993
- return {
1994
- name: "babel-plugin-zeus-compiler",
1995
- manipulateOptions(_opts, parserOpts) {
1996
- var _parserOpts$plugins;
1997
- (_parserOpts$plugins = parserOpts.plugins) !== null && _parserOpts$plugins !== void 0 || (parserOpts.plugins = []);
1998
- if (!hasParserPlugin(parserOpts.plugins, "jsx")) parserOpts.plugins.push("jsx");
1999
- },
2000
- visitor: createVisitor(resolveConfig(options))
2001
- };
2002
- });
6
+ import { createRequire } from "node:module";
7
+ const transformModule = createRequire(import.meta.url)("@zeus-js/compiler-native").transformModule;
2003
8
  //#endregion
2004
- export { CompilerError, CompilerErrorCode, src_default as default, formatCompilerDiagnostic };
9
+ export { transformModule as default, transformModule };