@zeus-js/compiler 0.1.0 → 0.1.1-beta.1

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