@yannosay/sinth 4.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/DOCS.md +1359 -0
  3. package/README.md +83 -74
  4. package/bin/sinth.js +2 -1
  5. package/dist/cli/args.d.ts +11 -0
  6. package/dist/cli/args.js +74 -0
  7. package/dist/cli/index.d.ts +1 -0
  8. package/dist/cli/index.js +437 -0
  9. package/dist/cli/templates.d.ts +10 -0
  10. package/dist/cli/templates.js +193 -0
  11. package/dist/cli/ui.d.ts +28 -0
  12. package/dist/cli/ui.js +61 -0
  13. package/dist/cli/update-check.d.ts +2 -0
  14. package/dist/cli/update-check.js +124 -0
  15. package/dist/compiler/ast.d.ts +315 -0
  16. package/dist/compiler/ast.js +4 -0
  17. package/dist/compiler/codegen.d.ts +143 -0
  18. package/dist/compiler/codegen.js +1326 -0
  19. package/dist/compiler/diagnostics.d.ts +36 -0
  20. package/dist/compiler/diagnostics.js +142 -0
  21. package/dist/compiler/elements.d.ts +14 -0
  22. package/dist/compiler/elements.js +78 -0
  23. package/dist/compiler/globals.d.ts +2 -0
  24. package/dist/compiler/globals.js +27 -0
  25. package/dist/compiler/html.d.ts +37 -0
  26. package/dist/compiler/html.js +152 -0
  27. package/dist/compiler/lexer.d.ts +42 -0
  28. package/dist/compiler/lexer.js +404 -0
  29. package/dist/compiler/parser.d.ts +95 -0
  30. package/dist/compiler/parser.js +1374 -0
  31. package/dist/compiler/prerender.d.ts +72 -0
  32. package/dist/compiler/prerender.js +910 -0
  33. package/dist/compiler/script-analysis.d.ts +6 -0
  34. package/dist/compiler/script-analysis.js +106 -0
  35. package/dist/compiler/style.d.ts +39 -0
  36. package/dist/compiler/style.js +463 -0
  37. package/dist/deploy/cloudflare.d.ts +9 -0
  38. package/dist/deploy/cloudflare.js +111 -0
  39. package/dist/index.d.ts +13 -0
  40. package/dist/index.js +23 -0
  41. package/dist/project/build.d.ts +31 -0
  42. package/dist/project/build.js +425 -0
  43. package/dist/project/config.d.ts +33 -0
  44. package/dist/project/config.js +142 -0
  45. package/dist/project/project.d.ts +74 -0
  46. package/dist/project/project.js +535 -0
  47. package/dist/runtime/index.d.ts +68 -0
  48. package/dist/runtime/index.js +912 -0
  49. package/dist/server/client.d.ts +1 -0
  50. package/dist/server/client.js +112 -0
  51. package/dist/server/dev.d.ts +8 -0
  52. package/dist/server/dev.js +244 -0
  53. package/dist/server/preview.d.ts +6 -0
  54. package/dist/server/preview.js +106 -0
  55. package/dist/server/static.d.ts +10 -0
  56. package/dist/server/static.js +136 -0
  57. package/lib/ui/index.sinth +436 -0
  58. package/package.json +33 -15
  59. package/schema/sinth.config.schema.json +54 -0
  60. package/dist/browser/compile.js +0 -62
  61. package/dist/cli.js +0 -509
  62. package/dist/core/builtins.js +0 -117
  63. package/dist/core/cli-compiler.js +0 -683
  64. package/dist/core/compiler.js +0 -1428
  65. package/dist/core/expr.js +0 -125
  66. package/dist/core/head-builder.js +0 -130
  67. package/dist/core/lexer.js +0 -414
  68. package/dist/core/parser.js +0 -1665
  69. package/dist/core/runtime/custom-element.js +0 -81
  70. package/dist/core/runtime/functions.js +0 -99
  71. package/dist/core/runtime/helpers.js +0 -347
  72. package/dist/core/runtime/render.js +0 -136
  73. package/dist/core/style-processor.js +0 -317
  74. package/dist/core/types.js +0 -93
  75. package/dist/resolver.js +0 -175
  76. package/dist/server.js +0 -174
  77. package/dist/update-check.js +0 -109
  78. package/dist/utils.js +0 -80
@@ -0,0 +1,1326 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isStatementExpr = exports.ModuleCompiler = void 0;
4
+ exports.collectExports = collectExports;
5
+ exports.containsAwait = containsAwait;
6
+ exports.compileModule = compileModule;
7
+ const diagnostics_1 = require("./diagnostics");
8
+ const elements_1 = require("./elements");
9
+ const globals_1 = require("./globals");
10
+ const parser_1 = require("./parser");
11
+ Object.defineProperty(exports, "isStatementExpr", { enumerable: true, get: function () { return parser_1.isStatementExpr; } });
12
+ const lexer_1 = require("./lexer");
13
+ const script_analysis_1 = require("./script-analysis");
14
+ const style_1 = require("./style");
15
+ const html_1 = require("./html");
16
+ class Scope {
17
+ parent;
18
+ kind;
19
+ names = new Map();
20
+ constructor(parent, kind = "block") {
21
+ this.parent = parent;
22
+ this.kind = kind;
23
+ }
24
+ define(name, b) {
25
+ this.names.set(name, b);
26
+ }
27
+ has(name) {
28
+ return this.names.has(name);
29
+ }
30
+ lookup(name) {
31
+ return this.names.get(name) ?? this.parent?.lookup(name);
32
+ }
33
+ all() {
34
+ const out = new Set(this.names.keys());
35
+ if (this.parent)
36
+ for (const n of this.parent.all())
37
+ out.add(n);
38
+ return [...out];
39
+ }
40
+ inComponent() {
41
+ return this.kind === "component" || !!this.parent?.inComponent();
42
+ }
43
+ }
44
+ const T = (base, array = 0) => ({ base, array, nullable: false });
45
+ function typeName(t) {
46
+ return t.base + "[]".repeat(t.array) + (t.nullable ? "?" : "");
47
+ }
48
+ function sameKind(a, b) {
49
+ const norm = (t) => (t.base === "int" ? "num" : t.base);
50
+ if (a.base === "any" || b.base === "any")
51
+ return true;
52
+ if (a.array !== b.array)
53
+ return a.base === "obj" && a.array === 0 && b.array > 0;
54
+ if (norm(a) === norm(b))
55
+ return true;
56
+ if (a.base === "obj" && b.base === "obj")
57
+ return true;
58
+ if (a.base === "fn" || b.base === "fn")
59
+ return a.base === b.base;
60
+ return false;
61
+ }
62
+ function collectExports(file) {
63
+ const exports = { components: new Map(), functions: new Map(), vars: new Map() };
64
+ for (const c of file.components) {
65
+ if (c.exported)
66
+ exports.components.set(c.name, { name: c.name, params: c.params, customTag: c.customTag });
67
+ }
68
+ for (const f of file.functions) {
69
+ exports.functions.set(f.name, { name: f.name, params: f.params, returnType: f.returnType, ui: f.returnType?.base === "ui" });
70
+ }
71
+ for (const v of file.vars)
72
+ exports.vars.set(v.name, { name: v.name, kind: v.kind, type: v.type ?? undefined });
73
+ const base = file.path.replace(/\\/g, "/").split("/").pop()?.replace(/\.sinth$/, "") ?? "";
74
+ const named = file.components.find(c => c.name === base || c.name.toLowerCase() === base.toLowerCase());
75
+ exports.defaultComponent = named?.name ?? (file.components.length === 1 ? file.components[0].name : undefined);
76
+ return exports;
77
+ }
78
+ const EVENT_NAME_MAP = { doubleclick: "dblclick", dblclick: "dblclick" };
79
+ function eventName(attr) {
80
+ const raw = attr.slice(2).toLowerCase();
81
+ return EVENT_NAME_MAP[raw] ?? raw;
82
+ }
83
+ const SIZE_ATTR_TAGS = new Set(["img", "video", "canvas", "iframe", "svg", "embed", "object", "source", "input", "rect", "image", "td", "th", "col", "table"]);
84
+ const DIRECTIVE_ATTRS = new Set(["model", "bind", "ref", "hide", "show", "html", "delay", "key", "..."]);
85
+ const PROP_ATTRS = new Set(["value", "checked", "selected", "indeterminate", "muted", "volume", "currentTime"]);
86
+ class ModuleCompiler {
87
+ file;
88
+ imports;
89
+ opts;
90
+ out = [];
91
+ css = [];
92
+ uid = 0;
93
+ interactive = false;
94
+ uses = new Set();
95
+ componentInfo = {};
96
+ usesState = false;
97
+ diagnostics = new diagnostics_1.DiagnosticBag();
98
+ moduleScope = new Scope(null, "module");
99
+ importLines = [];
100
+ exportsInfo;
101
+ fileHash;
102
+ pageCssVars = [];
103
+ constructor(file, imports, opts) {
104
+ this.file = file;
105
+ this.imports = imports;
106
+ this.opts = opts;
107
+ this.exportsInfo = collectExports(file);
108
+ this.fileHash = (0, html_1.hashString)(file.path.replace(/\\/g, "/")).slice(0, 6);
109
+ }
110
+ id(prefix) {
111
+ return `$$${prefix}${++this.uid}`;
112
+ }
113
+ fail(code, message, loc, hint) {
114
+ throw new diagnostics_1.SinthError(code, message, loc, hint);
115
+ }
116
+ compile() {
117
+ const file = this.file;
118
+ this.importLines.push(`import * as $$ from ${JSON.stringify(this.opts.runtime)};`);
119
+ this.declareImports();
120
+ for (const ext of file.externs)
121
+ this.moduleScope.define(ext.name, { kind: "global", js: ext.name });
122
+ for (const p of file.params ?? [])
123
+ this.moduleScope.define(p, { kind: "const", js: p, type: T("str") });
124
+ for (const c of file.components)
125
+ this.defineComponent(this.moduleScope, c.name, c.name, { name: c.name, params: c.params, customTag: c.customTag }, `${file.path}#${c.name}`, c.loc);
126
+ for (const f of file.functions) {
127
+ this.moduleScope.define(f.name, { kind: "function", js: f.name, fn: { name: f.name, params: f.params, returnType: f.returnType, ui: f.returnType?.base === "ui" }, loc: f.loc });
128
+ }
129
+ const scriptNames = [];
130
+ for (const s of file.scripts)
131
+ scriptNames.push(...(0, script_analysis_1.analyzeScript)(s.raw, s.loc, false).declared);
132
+ for (const n of scriptNames)
133
+ if (!this.moduleScope.has(n))
134
+ this.moduleScope.define(n, { kind: "global", js: n });
135
+ if (file.scripts.length)
136
+ this.interactive = true;
137
+ const body = [];
138
+ for (const p of file.params ?? [])
139
+ body.push(`const ${p} = $$.param(${JSON.stringify(p)});`);
140
+ for (const v of file.vars) {
141
+ this.checkDuplicate(this.moduleScope, v.name, v.loc);
142
+ body.push(this.genVarDecl(v, this.moduleScope, true));
143
+ }
144
+ for (const s of file.scripts)
145
+ body.push(s.raw.trim());
146
+ for (const f of file.functions)
147
+ body.push("export " + this.genFunction(f, this.moduleScope));
148
+ const base = this.interactive;
149
+ for (const c of file.components) {
150
+ this.interactive = false;
151
+ this.uses = new Set();
152
+ body.push(this.genComponent(c));
153
+ this.componentInfo[c.name] = { interactive: this.interactive, uses: [...this.uses] };
154
+ }
155
+ this.interactive = false;
156
+ this.uses = new Set();
157
+ const stateVars = file.vars.filter(v => v.kind === "var");
158
+ if (file.vars.length) {
159
+ const accessors = file.vars.map(v => v.kind === "computed"
160
+ ? `get ${v.name}() { return ${v.name}(); }`
161
+ : v.kind === "const"
162
+ ? `get ${v.name}() { return ${v.name}; }`
163
+ : `get ${v.name}() { return ${v.name}; }, set ${v.name}($$v) { ${v.name} = $$v; }`);
164
+ body.push(`export const $$vars = { ${accessors.join(", ")} };`);
165
+ }
166
+ if (file.isPage) {
167
+ const ctx = { scope: new Scope(this.moduleScope, "function"), svg: false };
168
+ const renderBody = [];
169
+ for (const v of stateVars)
170
+ if (v.persist)
171
+ renderBody.push(`$$.persist(${JSON.stringify(this.persistKey(v.name))}, () => ${v.name});`);
172
+ renderBody.push(...this.genLifecycle(file.lifecycle, file.watchers, ctx.scope));
173
+ renderBody.push(this.genNodes(file.body, "$$root", ctx));
174
+ body.push(`export function render($$root) {\n${indent(renderBody.filter(Boolean).join("\n"))}\n}`);
175
+ body.push(`export function state() { return { ${stateVars.map(v => `${JSON.stringify(v.name)}: ${v.name}`).join(", ")} }; }`);
176
+ const restore = stateVars.map(v => `if (${JSON.stringify(v.name)} in $$s) ${v.name} = $$s[${JSON.stringify(v.name)}];`);
177
+ body.push(`export function restore($$s) {${restore.length ? "\n" + indent(restore.join("\n")) + "\n" : " "}}`);
178
+ if (stateVars.length || file.lifecycle.length || file.watchers.length)
179
+ this.usesState = true;
180
+ if (stateVars.some(v => v.persist) || file.lifecycle.length || file.watchers.length)
181
+ this.interactive = true;
182
+ }
183
+ else if (file.body.length) {
184
+ const first = file.body[0];
185
+ this.diagnostics.warn("W0101", "Markup outside a component in a non-page file is ignored", first.loc, "Add 'page' at the top of the file, or wrap the markup in a component");
186
+ }
187
+ for (const c of file.components) {
188
+ if (!c.customTag)
189
+ continue;
190
+ const params = c.params.map(p => `[${JSON.stringify(p.name)}, ${JSON.stringify(p.type ? typeName(p.type) : "str")}]`).join(", ");
191
+ body.push(`$$.defineElement(${JSON.stringify(c.customTag)}, ${c.name}, [${params}]);`);
192
+ this.interactive = true;
193
+ }
194
+ const pageInfo = file.isPage ? { interactive: this.interactive, uses: [...this.uses] } : undefined;
195
+ let moduleBase = base;
196
+ for (const s of file.styles) {
197
+ this.interactive = false;
198
+ this.addStyle(s, undefined, this.moduleScope, file.isPage ? "page" : "module");
199
+ if (this.interactive)
200
+ moduleBase = true;
201
+ }
202
+ if (file.components.some(c => c.customTag))
203
+ moduleBase = true;
204
+ if (this.css.length)
205
+ this.importLines.push(`import ${JSON.stringify("sinth-css:" + this.file.path)};`);
206
+ const js = [...this.importLines, "", ...body].join("\n") + "\n";
207
+ const anyInteractive = moduleBase || !!pageInfo?.interactive || Object.values(this.componentInfo).some(i => i.interactive);
208
+ return {
209
+ js, css: this.css.join("\n\n"), exports: this.exportsInfo, interactive: anyInteractive, base: moduleBase,
210
+ components: this.componentInfo, page: pageInfo, usesState: this.usesState, diagnostics: this.diagnostics,
211
+ };
212
+ }
213
+ persistKey(name) {
214
+ return `${this.opts.persistPrefix}:${name}`;
215
+ }
216
+ checkDuplicate(scope, name, loc) {
217
+ if (scope.has(name))
218
+ this.fail("E0202", `'${name}' is already declared in this scope`, loc);
219
+ }
220
+ defineComponent(scope, name, js, sig, ref, loc) {
221
+ scope.define(name, { kind: "component", js, comp: sig, ref, loc });
222
+ }
223
+ declareImports() {
224
+ let n = 0;
225
+ for (const imp of this.imports) {
226
+ const d = imp.decl;
227
+ const spec = JSON.stringify(imp.specifier);
228
+ switch (imp.kind) {
229
+ case "style":
230
+ if (!/^(https?:)?\/\//.test(imp.specifier))
231
+ this.importLines.push(`import ${spec};`);
232
+ break;
233
+ case "script":
234
+ case "font":
235
+ if (d.namespace)
236
+ this.moduleScope.define(d.namespace, { kind: "global", js: d.namespace });
237
+ for (const s of d.named)
238
+ this.moduleScope.define(s.alias, { kind: "global", js: s.alias });
239
+ break;
240
+ case "json": {
241
+ const name = d.defaultName ?? d.namespace;
242
+ if (name) {
243
+ this.importLines.push(`const ${name} = ${JSON.stringify(imp.json)};`);
244
+ this.moduleScope.define(name, { kind: "const", js: name, type: T(Array.isArray(imp.json) ? "obj" : "obj") });
245
+ }
246
+ else if (d.named.length) {
247
+ const data = (imp.json ?? {});
248
+ for (const s of d.named) {
249
+ if (!(s.name in data))
250
+ this.fail("E0603", `'${s.name}' does not exist in ${d.source}`, s.loc);
251
+ this.importLines.push(`const ${s.alias} = ${JSON.stringify(data[s.name])};`);
252
+ this.moduleScope.define(s.alias, { kind: "const", js: s.alias });
253
+ }
254
+ }
255
+ break;
256
+ }
257
+ case "module": {
258
+ this.interactive = true;
259
+ const parts = [];
260
+ if (d.defaultName)
261
+ parts.push(d.defaultName);
262
+ if (d.namespace)
263
+ parts.push(`* as ${d.namespace}`);
264
+ if (d.named.length)
265
+ parts.push(`{ ${d.named.map(s => (s.name === s.alias ? s.name : `${s.name} as ${s.alias}`)).join(", ")} }`);
266
+ this.importLines.push(parts.length ? `import ${parts.join(", ")} from ${spec};` : `import ${spec};`);
267
+ for (const name of [d.defaultName, d.namespace, ...d.named.map(s => s.alias)]) {
268
+ if (name)
269
+ this.moduleScope.define(name, { kind: "import", js: name });
270
+ }
271
+ break;
272
+ }
273
+ case "sinth": {
274
+ const ex = imp.exports;
275
+ if (!ex)
276
+ break;
277
+ const ns = `$$m${++n}`;
278
+ this.importLines.push(`import * as ${ns} from ${spec};`);
279
+ const bindAll = d.sideEffect || (!d.named.length && !d.defaultName && !d.namespace);
280
+ const bindName = (name, alias, loc) => {
281
+ const comp = ex.components.get(name);
282
+ const fn = ex.functions.get(name);
283
+ const v = ex.vars.get(name);
284
+ if (comp)
285
+ this.defineComponent(this.moduleScope, alias, `${ns}.${name}`, comp, `${imp.specifier}#${name}`, loc);
286
+ else if (fn)
287
+ this.moduleScope.define(alias, { kind: "function", js: `${ns}.${name}`, fn });
288
+ else if (v) {
289
+ const kind = v.kind === "computed" ? "computed" : v.kind === "const" ? "const" : "state";
290
+ this.moduleScope.define(alias, { kind, js: `${ns}.$$vars.${name}`, type: v.type });
291
+ }
292
+ else {
293
+ const all = [...ex.components.keys(), ...ex.functions.keys(), ...ex.vars.keys()];
294
+ const s = (0, diagnostics_1.suggest)(name, all);
295
+ this.fail("E0602", `'${d.source}' has no export named '${name}'`, loc, s ? `Did you mean '${s}'?` : all.length ? `Available: ${all.join(", ")}` : undefined);
296
+ }
297
+ };
298
+ if (bindAll) {
299
+ for (const name of ex.components.keys())
300
+ bindName(name, name, d.loc);
301
+ }
302
+ if (d.defaultName) {
303
+ if (!ex.defaultComponent)
304
+ this.fail("E0604", `'${d.source}' has no default component`, d.loc, "Name the component like the file, or use: import { Name } from \"...\"");
305
+ bindName(ex.defaultComponent, d.defaultName, d.loc);
306
+ }
307
+ if (d.namespace)
308
+ this.moduleScope.define(d.namespace, { kind: "global", js: ns, comp: undefined });
309
+ for (const s of d.named)
310
+ bindName(s.name, s.alias, s.loc);
311
+ break;
312
+ }
313
+ }
314
+ }
315
+ }
316
+ resolveNamespacedComponent(name) {
317
+ const [ns, member] = name.split(".");
318
+ if (!member)
319
+ return undefined;
320
+ const imp = this.imports.find(i => i.kind === "sinth" && i.decl.namespace === ns);
321
+ const nsBinding = this.moduleScope.lookup(ns);
322
+ const sig = imp?.exports?.components.get(member);
323
+ if (!sig || !nsBinding)
324
+ return undefined;
325
+ return { kind: "component", js: `${nsBinding.js}.${member}`, comp: sig, ref: `${imp?.specifier}#${member}` };
326
+ }
327
+ genVarDecl(v, scope, moduleLevel) {
328
+ const type = v.type ?? (v.init ? this.inferType(v.init, scope) : undefined);
329
+ if (v.type?.base === "int") {
330
+ this.diagnostics.warn("W0201", "'int' is deprecated; use 'num'", v.loc);
331
+ }
332
+ if (v.type && v.init)
333
+ this.checkAssignable(v.type, v.init, scope, v.loc, `'${v.name}'`);
334
+ let init = v.init ? this.expr(v.init, scope) : defaultFor(v.type);
335
+ let line;
336
+ if (v.kind === "computed") {
337
+ line = `const ${v.name} = () => ${init};`;
338
+ scope.define(v.name, { kind: "computed", js: `${v.name}()`, type });
339
+ }
340
+ else if (v.kind === "const") {
341
+ line = `const ${v.name} = ${init};`;
342
+ scope.define(v.name, { kind: "const", js: v.name, type });
343
+ }
344
+ else {
345
+ if (v.persist) {
346
+ if (!moduleLevel && !scope.inComponent())
347
+ this.fail("E0210", "'persist' is only allowed on page or component variables", v.loc);
348
+ init = `$$.persisted(${JSON.stringify(this.persistKey(v.name))}, ${init})`;
349
+ this.interactive = true;
350
+ }
351
+ line = `let ${v.name} = ${init};`;
352
+ scope.define(v.name, { kind: moduleLevel ? "state" : "local", js: v.name, type });
353
+ }
354
+ return line;
355
+ }
356
+ genFunction(f, parent) {
357
+ const scope = new Scope(parent, "function");
358
+ const params = this.genParams(f.params, scope);
359
+ if (f.view) {
360
+ const ctx = { scope, svg: false, scopeClass: undefined };
361
+ const locals = f.body.map(s => this.stmt(s, scope)).join("\n");
362
+ const view = this.genNodes(f.view, "$$parent", ctx);
363
+ return `function ${f.name}($$parent${params ? ", " + params : ""}) {\n${indent([locals, view].filter(Boolean).join("\n"))}\n}`;
364
+ }
365
+ const body = this.stmts(f.body, scope, f.returnType);
366
+ return `${f.async || containsAwait(f.body) ? "async " : ""}function ${f.name}(${params}) {\n${indent(body)}\n}`;
367
+ }
368
+ genParams(params, scope) {
369
+ return params.map(p => {
370
+ scope.define(p.name, { kind: "local", js: p.name, type: p.type });
371
+ if (p.rest)
372
+ return `...${p.name}`;
373
+ return p.defaultValue ? `${p.name} = ${this.expr(p.defaultValue, scope)}` : p.name;
374
+ }).join(", ");
375
+ }
376
+ genComponent(c) {
377
+ const scope = new Scope(this.moduleScope, "component");
378
+ const scopeClass = `s-${(0, html_1.hashString)(this.file.path.replace(/\\/g, "/") + "#" + c.name).slice(0, 7)}`;
379
+ for (const p of c.params) {
380
+ this.checkDuplicate(scope, p.name, p.loc);
381
+ scope.define(p.name, { kind: "param", js: `$$p.${p.name}`, type: p.type, defaultValue: p.defaultValue, bindable: p.bindable });
382
+ }
383
+ const lines = [];
384
+ for (const v of c.vars) {
385
+ this.checkDuplicate(scope, v.name, v.loc);
386
+ lines.push(this.genVarDecl(v, scope, false));
387
+ if (v.persist)
388
+ lines.push(`$$.persist(${JSON.stringify(this.persistKey(c.name + "." + v.name))}, () => ${v.name});`);
389
+ }
390
+ for (const f of c.functions) {
391
+ scope.define(f.name, { kind: "function", js: f.name, fn: { name: f.name, params: f.params, returnType: f.returnType, ui: f.returnType?.base === "ui" } });
392
+ }
393
+ for (const s of c.scripts) {
394
+ const info = (0, script_analysis_1.analyzeScript)(s.raw, s.loc, true);
395
+ if (info.hasImports)
396
+ this.fail("E0501", "Component script blocks cannot contain 'import' statements", s.loc, "Use a top-level 'import' in the .sinth file instead");
397
+ for (const n of info.declared)
398
+ if (!scope.has(n))
399
+ scope.define(n, { kind: "local", js: n });
400
+ this.interactive = true;
401
+ }
402
+ for (const f of c.functions)
403
+ lines.push(this.genFunction(f, scope));
404
+ for (const s of c.scripts)
405
+ lines.push(s.raw.trim());
406
+ if (c.lifecycle.length || c.watchers.length)
407
+ this.interactive = true;
408
+ lines.push(...this.genLifecycle(c.lifecycle, c.watchers, scope));
409
+ const styleVars = {};
410
+ for (const s of c.styles)
411
+ Object.assign(styleVars, this.addStyle(s, s.global ? undefined : scopeClass, scope, c.name));
412
+ const varEntries = Object.entries(styleVars);
413
+ const rootHook = (roots) => {
414
+ const out = [];
415
+ if (roots[0])
416
+ out.push(`if ($$a) $$a(${roots[0]});`);
417
+ if (varEntries.length && roots.length) {
418
+ out.push(`$$.cssVars([${roots.join(", ")}], { ${varEntries.map(([k, e]) => `${JSON.stringify(k)}: () => ${this.expr(e, scope)}`).join(", ")} });`);
419
+ }
420
+ return out.join("\n");
421
+ };
422
+ const ctx = { scope, comp: c, scopeClass, slotsVar: "$$s", svg: false, rootHook };
423
+ const roots = [];
424
+ lines.push(this.genNodes(c.body, "$$parent", ctx, roots));
425
+ lines.push(rootHook(roots));
426
+ return `export function ${c.name}($$parent, $$p, $$s, $$a) {\n${indent(lines.filter(Boolean).join("\n"))}\n}`;
427
+ }
428
+ genLifecycle(lifecycle, watchers, scope) {
429
+ const out = [];
430
+ for (const l of lifecycle) {
431
+ const inner = new Scope(scope, "function");
432
+ const body = this.stmts(l.body, inner);
433
+ const asyncKw = containsAwait(l.body) ? "async " : "";
434
+ out.push(l.kind === "mount" ? `$$.onMount(${asyncKw}() => {\n${indent(body)}\n});` : `$$.onDestroy(() => {\n${indent(body)}\n});`);
435
+ }
436
+ for (const w of watchers) {
437
+ const inner = new Scope(scope, "function");
438
+ inner.define("value", { kind: "local", js: "value" });
439
+ inner.define("previous", { kind: "local", js: "previous" });
440
+ const asyncKw = containsAwait(w.body) ? "async " : "";
441
+ out.push(`$$.watch(() => ${this.expr(w.expr, scope)}, ${asyncKw}(value, previous) => {\n${indent(this.stmts(w.body, inner))}\n});`);
442
+ }
443
+ return out;
444
+ }
445
+ addStyle(s, scopeClass, scope, label) {
446
+ const reactiveNames = new Set(scope.all().filter(n => {
447
+ const b = scope.lookup(n);
448
+ return b && (b.kind === "param" || b.kind === "state" || b.kind === "computed" || b.kind === "local" || b.kind === "const");
449
+ }));
450
+ const varPrefix = `--sv-${(0, html_1.hashString)(this.file.path + label).slice(0, 5)}-`;
451
+ const result = (0, style_1.compileStyle)(s.raw, s.lang, { scope: scopeClass, reactiveNames, varPrefix, loc: s.loc, sinthSyntax: s.lang === "sinth" }, this.opts.scss);
452
+ if (result.css.trim())
453
+ this.css.push(`/* ${label} */\n${result.css}`);
454
+ const vars = {};
455
+ for (const e of result.expressions) {
456
+ const sub = parseInlineExpr(e.source, { file: s.loc.file, line: e.line, col: 1 });
457
+ this.expr(sub, scope);
458
+ vars[e.cssVar] = sub;
459
+ }
460
+ if (result.expressions.length && !scopeClass) {
461
+ this.interactive = true;
462
+ if (scope === this.moduleScope)
463
+ this.pageCssVars.push(...Object.entries(vars));
464
+ }
465
+ return vars;
466
+ }
467
+ genNodes(nodes, parent, ctx, roots) {
468
+ const out = [];
469
+ if (this.pageCssVars.length && parent === "$$root") {
470
+ out.push(`$$.cssVars([document.documentElement], { ${this.pageCssVars.map(([k, e]) => `${JSON.stringify(k)}: () => ${this.expr(e, ctx.scope)}`).join(", ")} });`);
471
+ }
472
+ for (const node of nodes)
473
+ out.push(this.genNode(node, parent, ctx, roots));
474
+ return out.filter(Boolean).join("\n");
475
+ }
476
+ genNode(node, parent, ctx, roots) {
477
+ switch (node.k) {
478
+ case "text":
479
+ return this.genText(node.expr, parent, ctx);
480
+ case "element":
481
+ return this.genElement(node, parent, ctx, roots);
482
+ case "if":
483
+ return this.genIf(node, parent, ctx, !!roots);
484
+ case "for":
485
+ return this.genFor(node, parent, ctx, !!roots);
486
+ case "slot": {
487
+ if (!ctx.slotsVar)
488
+ this.fail("E0310", "'$slot' can only be used inside a component", node.loc);
489
+ const fb = node.fallback.length ? `, ($$f) => {\n${indent(this.genNodes(node.fallback, "$$f", ctx))}\n}` : "";
490
+ return `$$.slot(${parent}, ${ctx.slotsVar}, ${JSON.stringify(node.name)}${fb});`;
491
+ }
492
+ case "stmt":
493
+ return this.stmt(node.stmt, ctx.scope);
494
+ case "var":
495
+ this.checkDuplicate(ctx.scope, node.decl.name, node.loc);
496
+ return this.genVarDecl(node.decl, ctx.scope, false);
497
+ }
498
+ }
499
+ genText(expr, parent, ctx) {
500
+ if (expr.k === "lit")
501
+ return expr.value === null ? "" : `${parent}.append(${JSON.stringify(String(expr.value))});`;
502
+ if (expr.k === "call") {
503
+ const b = this.calleeBinding(expr.callee, ctx.scope);
504
+ if (b?.fn?.ui)
505
+ return this.genUiCall(expr, b, parent, ctx);
506
+ }
507
+ const js = this.expr(expr, ctx.scope);
508
+ if (this.isConstantExpr(expr, ctx.scope))
509
+ return `${parent}.append($$.toText(${js}));`;
510
+ return `$$.text(${parent}, () => ${js});`;
511
+ }
512
+ genUiCall(expr, b, parent, ctx) {
513
+ const fn = b.fn;
514
+ const args = this.genCallArgs(expr.args, fn, ctx.scope, expr.loc);
515
+ return `${b.js}(${parent}${args ? ", " + args : ""});`;
516
+ }
517
+ isConstantExpr(expr, scope) {
518
+ switch (expr.k) {
519
+ case "lit": return true;
520
+ case "id": {
521
+ const b = scope.lookup(expr.name);
522
+ return b?.kind === "const" && !b.js.includes(".");
523
+ }
524
+ case "binary": return this.isConstantExpr(expr.left, scope) && this.isConstantExpr(expr.right, scope);
525
+ case "unary": return expr.op !== "await" && this.isConstantExpr(expr.arg, scope);
526
+ case "tpl": return expr.parts.every(p => typeof p === "string" || this.isConstantExpr(p, scope));
527
+ case "cond": return this.isConstantExpr(expr.test, scope) && this.isConstantExpr(expr.then, scope) && this.isConstantExpr(expr.else, scope);
528
+ default: return false;
529
+ }
530
+ }
531
+ isStaticNode(node, ctx) {
532
+ if (node.k === "text")
533
+ return node.expr.k === "lit";
534
+ if (node.k !== "element")
535
+ return false;
536
+ if (elements_1.SPECIAL_ELEMENTS.has(node.name))
537
+ return false;
538
+ if (!elements_1.ELEMENTS[node.name] || (ctx.scope.lookup(node.name)?.kind === "component" && ctx.comp?.name !== node.name))
539
+ return false;
540
+ if (node.slots.length)
541
+ return false;
542
+ for (const a of node.attrs) {
543
+ if (a.handler || a.name === "..." || a.name === "model" || a.name === "bind" || a.name === "ref" || a.name === "hide" || a.name === "show" || a.name === "html" || a.name === "delay")
544
+ return false;
545
+ if (a.value && !(a.value.k === "lit" || (a.name === "style" && isLiteralObject(a.value))))
546
+ return false;
547
+ if (a.name === "level" && a.value && a.value.k !== "lit")
548
+ return false;
549
+ }
550
+ return node.children.every(c => this.isStaticNode(c, ctx));
551
+ }
552
+ staticHtml(node, ctx) {
553
+ if (node.k === "text")
554
+ return node.expr.k === "lit" && node.expr.value !== null ? (0, html_1.escapeHtml)(String(node.expr.value)) : "";
555
+ if (node.k !== "element")
556
+ return "";
557
+ const { tag, attrs } = this.elementShape(node, ctx);
558
+ const attrStr = Object.entries(attrs).map(([k, v]) => (v === "" && elements_1.BOOLEAN_ATTRS.has(k) ? ` ${k}` : ` ${k}="${(0, html_1.escapeAttr)(v)}"`)).join("");
559
+ if (elements_1.VOID_TAGS.has(tag))
560
+ return `<${tag}${attrStr}>`;
561
+ return `<${tag}${attrStr}>${node.children.map(c => this.staticHtml(c, ctx)).join("")}</${tag}>`;
562
+ }
563
+ headingTag(node) {
564
+ const level = node.attrs.find(a => a.name === "level");
565
+ if (!level || !level.value)
566
+ return elements_1.ELEMENTS[node.name]?.tag ?? "h1";
567
+ if (level.value.k !== "lit" || typeof level.value.value !== "number")
568
+ this.fail("E0320", "Heading 'level' must be a number literal from 1 to 6", level.loc);
569
+ const n = level.value.value;
570
+ if (!Number.isInteger(n) || n < 1 || n > 6)
571
+ this.fail("E0320", `Heading level must be between 1 and 6, got ${n}`, level.loc);
572
+ return `h${n}`;
573
+ }
574
+ elementShape(node, ctx) {
575
+ const info = elements_1.ELEMENTS[node.name];
576
+ const tag = node.name === "Heading" ? this.headingTag(node) : info.tag;
577
+ const attrs = { ...(info.attrs ?? {}) };
578
+ const classes = [];
579
+ if (info.className)
580
+ classes.push(info.className);
581
+ if (ctx.scopeClass)
582
+ classes.push(ctx.scopeClass);
583
+ const styles = [];
584
+ for (const a of node.attrs) {
585
+ if (a.name === "level" && node.name === "Heading")
586
+ continue;
587
+ if (a.handler || DIRECTIVE_ATTRS.has(a.name))
588
+ continue;
589
+ if (/^on[a-z]+$/.test(a.name)) {
590
+ this.fail("E0334", `Inline event attribute '${a.name}' is not allowed`, a.loc, `Use '${"on" + a.name[2].toUpperCase() + a.name.slice(3)}: ...' with a Sinth handler instead`);
591
+ }
592
+ if (a.value === null) {
593
+ attrs[(0, elements_1.attrNameToHtml)(a.name)] = "";
594
+ continue;
595
+ }
596
+ if (a.name === "class" && a.value.k === "lit") {
597
+ if (a.value.value)
598
+ classes.push(String(a.value.value));
599
+ continue;
600
+ }
601
+ if (a.name === "style" && isLiteralObject(a.value)) {
602
+ styles.push(literalObjectToCss(a.value));
603
+ continue;
604
+ }
605
+ if (a.value.k !== "lit")
606
+ continue;
607
+ if (this.isStyleProp(a.name, tag)) {
608
+ if (a.value.value !== null && a.value.value !== false)
609
+ styles.push(`${kebabCss(a.name)}: ${a.value.value}`);
610
+ continue;
611
+ }
612
+ const v = a.value.value;
613
+ if (v === false || v === null)
614
+ continue;
615
+ attrs[(0, elements_1.attrNameToHtml)(a.name)] = v === true ? "" : String(v);
616
+ }
617
+ if (classes.length)
618
+ attrs.class = classes.join(" ");
619
+ if (styles.length)
620
+ attrs.style = [attrs.style, ...styles].filter(Boolean).join("; ");
621
+ return { tag, attrs, svg: !!info.svg };
622
+ }
623
+ isStyleProp(name, tag) {
624
+ if (!elements_1.INLINE_STYLE_PROPS.has(name))
625
+ return false;
626
+ if ((name === "width" || name === "height") && SIZE_ATTR_TAGS.has(tag))
627
+ return false;
628
+ return true;
629
+ }
630
+ genElement(node, parent, ctx, roots) {
631
+ const binding = node.name.includes(".") ? this.resolveNamespacedComponent(node.name) : ctx.scope.lookup(node.name);
632
+ const selfWrapsBuiltin = ctx.comp?.name === node.name && !!elements_1.ELEMENTS[node.name];
633
+ if (binding?.kind === "component" && binding.comp && !selfWrapsBuiltin)
634
+ return this.genComponentUse(node, binding, parent, ctx, roots);
635
+ if (node.name === "Fragment")
636
+ return this.genNodes(node.children, parent, ctx);
637
+ if (node.name === "RawHTML" || node.name === "Html")
638
+ return this.genRawHtml(node, parent, ctx);
639
+ const info = elements_1.ELEMENTS[node.name];
640
+ if (!info) {
641
+ const candidates = [...Object.keys(elements_1.ELEMENTS), ...ctx.scope.all().filter(n => /^[A-Z]/.test(n))];
642
+ const s = (0, diagnostics_1.suggest)(node.name, candidates);
643
+ this.fail("E0301", `Unknown component '${node.name}'`, node.loc, s ? `Did you mean '${s}'?` : "Import it, e.g. import { " + node.name + " } from \"./components/" + node.name + ".sinth\"");
644
+ }
645
+ if (node.slots.length)
646
+ this.fail("E0311", "slot(...) fills can only be used inside components that declare $slot", node.slots[0].loc);
647
+ if (this.isStaticNode(node, ctx)) {
648
+ const html = this.staticHtml(node, ctx);
649
+ if (roots) {
650
+ const v = this.id("e");
651
+ roots.push(v);
652
+ return `const ${v} = $$.tpl(${JSON.stringify(html)}${info.svg ? ", true" : ""}).firstChild;\n${parent}.appendChild(${v});`;
653
+ }
654
+ return `${parent}.appendChild($$.tpl(${JSON.stringify(html)}${info.svg || ctx.svg ? ", true" : ""}));`;
655
+ }
656
+ const { tag, attrs } = this.elementShape(node, ctx);
657
+ const v = this.id("e");
658
+ roots?.push(v);
659
+ const lines = [];
660
+ const isSvg = !!info.svg || ctx.svg;
661
+ lines.push(`const ${v} = ${isSvg ? `$$.svg(${JSON.stringify(tag)})` : `$$.el(${JSON.stringify(tag)})`};`);
662
+ for (const [k, val] of Object.entries(attrs))
663
+ lines.push(`${v}.setAttribute(${JSON.stringify(k)}, ${JSON.stringify(val)});`);
664
+ lines.push(...this.genDynamicAttrs(node, v, tag, ctx));
665
+ const childCtx = { ...ctx, svg: isSvg && tag !== "foreignObject" };
666
+ const htmlAttr = node.attrs.find(a => a.name === "html");
667
+ if (htmlAttr && node.children.length)
668
+ this.fail("E0330", "An element with 'html' cannot also have children", htmlAttr.loc);
669
+ if (elements_1.VOID_TAGS.has(tag) && node.children.length)
670
+ this.fail("E0331", `<${tag}> is a void element and cannot have children`, node.loc);
671
+ if (node.children.length)
672
+ lines.push(this.genNodes(node.children, v, childCtx));
673
+ lines.push(`${parent}.appendChild(${v});`);
674
+ return lines.filter(Boolean).join("\n");
675
+ }
676
+ genRawHtml(node, parent, ctx) {
677
+ const content = node.attrs.find(a => a.name === "content" || a.name === "html");
678
+ if (!content?.value)
679
+ this.fail("E0332", `${node.name} requires a 'content' attribute`, node.loc);
680
+ if (content.value.k !== "lit") {
681
+ this.diagnostics.warn("W0301", `${node.name} renders dynamic content as unescaped HTML. Only use it with trusted content`, content.loc);
682
+ }
683
+ return `$$.html(${parent}, () => ${this.expr(content.value, ctx.scope)});`;
684
+ }
685
+ genDynamicAttrs(node, v, tag, ctx) {
686
+ const lines = [];
687
+ const scope = ctx.scope;
688
+ for (const a of node.attrs) {
689
+ if (a.name === "level" && node.name === "Heading")
690
+ continue;
691
+ if (a.handler) {
692
+ this.interactive = true;
693
+ lines.push(`$$.on(${v}, ${JSON.stringify(eventName(a.name))}, ${this.genHandler(a, scope)}${a.modifiers.length ? ", " + JSON.stringify(a.modifiers) : ""});`);
694
+ continue;
695
+ }
696
+ if (a.name === "...")
697
+ this.fail("E0333", "Spread attributes are only supported on components", a.loc);
698
+ if (a.value === null)
699
+ continue;
700
+ const val = a.value;
701
+ switch (a.name) {
702
+ case "model":
703
+ case "bind": {
704
+ this.interactive = true;
705
+ if (val.k !== "id" && val.k !== "member" && val.k !== "index")
706
+ this.fail("E0340", `'${a.name}' needs a variable to bind to`, a.loc);
707
+ const get = this.expr(val, scope);
708
+ const target = this.assignTarget(val, scope, a.loc);
709
+ const t = this.inferType(val, scope);
710
+ const numeric = !!t && (t.base === "num" || t.base === "int") && t.array === 0;
711
+ lines.push(`$$.model(${v}, () => ${get}, ($$v) => { ${target} = $$v; }${numeric ? ", true" : ""});`);
712
+ continue;
713
+ }
714
+ case "ref":
715
+ this.interactive = true;
716
+ if (val.k !== "id" && val.k !== "member")
717
+ this.fail("E0341", "'ref' needs a variable to store the element in", a.loc);
718
+ lines.push(`$$.ref(${v}, ($$v) => { ${this.assignTarget(val, scope, a.loc)} = $$v; });`);
719
+ continue;
720
+ case "hide":
721
+ lines.push(`$$.show(${v}, () => !(${this.expr(val, scope)}));`);
722
+ continue;
723
+ case "show":
724
+ lines.push(`$$.show(${v}, () => ${this.expr(val, scope)});`);
725
+ continue;
726
+ case "html":
727
+ if (val.k !== "lit")
728
+ this.diagnostics.warn("W0301", "'html' renders dynamic content as unescaped HTML. Only use it with trusted content", a.loc);
729
+ lines.push(`$$.html(${v}, () => ${this.expr(val, scope)});`);
730
+ continue;
731
+ case "delay":
732
+ lines.push(`$$.show(${v}, () => false);`, `setTimeout(() => { ${v}.style.display = ""; }, Number(${this.expr(val, scope)}) || 0);`);
733
+ this.interactive = true;
734
+ continue;
735
+ case "key":
736
+ continue;
737
+ default:
738
+ break;
739
+ }
740
+ if (val.k === "lit")
741
+ continue;
742
+ if (a.name === "style" && isLiteralObject(val))
743
+ continue;
744
+ const js = this.expr(val, scope);
745
+ if (a.name === "class")
746
+ lines.push(`$$.cls(${v}, () => ${js});`);
747
+ else if (a.name === "style")
748
+ lines.push(`$$.style(${v}, () => ${js});`);
749
+ else if (this.isStyleProp(a.name, tag))
750
+ lines.push(`$$.styleProp(${v}, ${JSON.stringify(a.name)}, () => ${js});`);
751
+ else if (PROP_ATTRS.has(a.name))
752
+ lines.push(`$$.prop(${v}, ${JSON.stringify(a.name)}, () => ${js});`);
753
+ else
754
+ lines.push(`$$.attr(${v}, ${JSON.stringify((0, elements_1.attrNameToHtml)(a.name))}, () => ${js});`);
755
+ }
756
+ return lines;
757
+ }
758
+ genHandler(a, scope) {
759
+ const stmts = a.handler;
760
+ const inner = new Scope(scope, "function");
761
+ inner.define("e", { kind: "local", js: "e" });
762
+ inner.define("event", { kind: "local", js: "e" });
763
+ if (stmts.length === 1 && stmts[0].k === "expr") {
764
+ const ex = stmts[0].expr;
765
+ if (ex.k === "arrow")
766
+ return this.expr(ex, scope);
767
+ if (ex.k === "lit" || ex.k === "tpl") {
768
+ const raw = ex.k === "lit" ? String(ex.value) : "";
769
+ const name = raw.replace(/\(\s*\)\s*;?$/, "");
770
+ this.fail("E0351", "Event handlers cannot be strings", ex.loc, /^[A-Za-z_$][\w$]*$/.test(name) ? `Write ${a.name}: ${name}() instead of ${a.name}: "${raw}"` : `Write the handler as code, e.g. ${a.name}: count += 1`);
771
+ }
772
+ if (ex.k === "id" || ex.k === "member") {
773
+ const b = ex.k === "id" ? scope.lookup(ex.name) : undefined;
774
+ if (ex.k === "id" && !b)
775
+ this.unknownName(ex.name, ex.loc, scope);
776
+ if (ex.k === "id" && b && (b.kind === "state" || b.kind === "local" || b.kind === "param") && b.type && b.type.base !== "fn" && b.type.base !== "any") {
777
+ this.fail("E0350", `'${ex.name}' is a ${typeName(b.type)}, not a function, so it cannot be used as an event handler`, ex.loc);
778
+ }
779
+ if (b?.fn) {
780
+ const first = b.fn.params[0];
781
+ if (first && (first.name === "e" || first.name === "event"))
782
+ return `(e) => ${this.expr(ex, inner)}(e)`;
783
+ const missing = b.fn.params.find(p => !p.optional && !p.rest);
784
+ if (missing)
785
+ this.fail("E0315", `Missing argument '${missing.name}' for function '${b.fn.name}'`, ex.loc, `Call it with arguments, e.g. onClick: ${b.fn.name}(...)`);
786
+ return `() => ${this.expr(ex, inner)}()`;
787
+ }
788
+ return `(e) => ${this.expr(ex, inner)}(e)`;
789
+ }
790
+ }
791
+ const body = this.stmts(stmts, inner);
792
+ return `${containsAwait(stmts) ? "async " : ""}(e) => {\n${indent(body)}\n}`;
793
+ }
794
+ genComponentUse(node, b, parent, ctx, roots) {
795
+ const sig = b.comp;
796
+ if (b.ref)
797
+ this.uses.add(b.ref);
798
+ const scope = ctx.scope;
799
+ const props = [];
800
+ const passed = new Set();
801
+ const fallthrough = [];
802
+ for (const a of node.attrs) {
803
+ if (a.name === "...") {
804
+ props.push(`...${this.expr(a.value, scope)}`);
805
+ continue;
806
+ }
807
+ const param = sig.params.find(p => p.name === a.name);
808
+ if (!param) {
809
+ const s = (0, diagnostics_1.suggest)(a.name, sig.params.map(p => p.name));
810
+ if (s && !a.handler && !["class", "style", "id"].includes(a.name)) {
811
+ this.diagnostics.warn("W0310", `'${node.name}' has no parameter '${a.name}'; it is passed to the root element instead`, a.loc, `Did you mean '${s}'?`);
812
+ }
813
+ fallthrough.push(a);
814
+ continue;
815
+ }
816
+ passed.add(param.name);
817
+ if (a.handler) {
818
+ props.push(`${JSON.stringify(param.name)}: ${this.genHandler(a, scope)}`);
819
+ continue;
820
+ }
821
+ const value = a.value ?? { k: "lit", value: true, loc: a.loc };
822
+ if (param.type)
823
+ this.checkAssignable(param.type, value, scope, a.loc, `parameter '${param.name}' of '${node.name}'`);
824
+ const js = this.expr(value, scope);
825
+ if (param.bindable && (value.k === "id" || value.k === "member" || value.k === "index")) {
826
+ const target = this.assignTarget(value, scope, a.loc);
827
+ props.push(`get ${JSON.stringify(param.name)}() { return ${js}; }, set ${JSON.stringify(param.name)}($$v) { ${target} = $$v; }`);
828
+ continue;
829
+ }
830
+ props.push(this.isConstantExpr(value, scope) ? `${JSON.stringify(param.name)}: ${js}` : `get ${JSON.stringify(param.name)}() { return ${js}; }`);
831
+ }
832
+ for (const p of sig.params) {
833
+ if (!passed.has(p.name) && !p.optional && !p.rest) {
834
+ this.fail("E0360", `Missing required parameter '${p.name}' for component '${node.name}'`, node.loc, `Pass it like: ${node.name}(${p.name}: ...)`);
835
+ }
836
+ }
837
+ const slotEntries = [];
838
+ if (node.children.length)
839
+ slotEntries.push(`default: ($$f) => {\n${indent(this.genNodes(node.children, "$$f", { ...ctx, svg: false }))}\n}`);
840
+ for (const sf of node.slots)
841
+ slotEntries.push(`${JSON.stringify(sf.name)}: ($$f) => {\n${indent(this.genNodes(sf.children, "$$f", ctx))}\n}`);
842
+ let ft = "";
843
+ if (fallthrough.length) {
844
+ const fv = "$$t";
845
+ const fake = { ...node, attrs: fallthrough, name: "Div" };
846
+ const lines = this.genDynamicAttrs(fake, fv, "div", ctx);
847
+ for (const a of fallthrough) {
848
+ if (a.handler || !a.value || a.value.k !== "lit")
849
+ continue;
850
+ if (a.name === "class")
851
+ lines.push(`${fv}.classList.add(...${JSON.stringify(String(a.value.value).split(/\s+/).filter(Boolean))});`);
852
+ else if (a.value.value !== false && a.value.value !== null)
853
+ lines.push(`${fv}.setAttribute(${JSON.stringify((0, elements_1.attrNameToHtml)(a.name))}, ${JSON.stringify(a.value.value === true ? "" : String(a.value.value))});`);
854
+ }
855
+ for (const a of fallthrough)
856
+ if (a.value === null && !a.handler)
857
+ lines.push(`${fv}.setAttribute(${JSON.stringify((0, elements_1.attrNameToHtml)(a.name))}, "");`);
858
+ ft = `, (${fv}) => {\n${indent(lines.join("\n"))}\n}`;
859
+ }
860
+ const call = `$$.component(${parent}, ${b.js}, { ${props.join(", ")} }, { ${slotEntries.join(", ")} }${ft});`;
861
+ if (roots) {
862
+ const v = this.id("c");
863
+ roots.push(v);
864
+ return `const ${v} = ${call}`;
865
+ }
866
+ return call;
867
+ }
868
+ genIf(node, parent, ctx, topLevel = false) {
869
+ const branches = node.branches.map(br => {
870
+ const test = br.test ? `() => ${this.expr(br.test, ctx.scope)}` : "null";
871
+ const inner = { ...ctx, scope: new Scope(ctx.scope, "block") };
872
+ const p = this.id("b");
873
+ const branchRoots = [];
874
+ const body = this.genNodes(br.body, p, inner, topLevel ? branchRoots : undefined);
875
+ const hook = topLevel && ctx.rootHook ? ctx.rootHook(branchRoots) : "";
876
+ return `[${test}, (${p}) => {\n${indent([body, hook].filter(Boolean).join("\n"))}\n}]`;
877
+ });
878
+ const opts = [];
879
+ if (node.persist)
880
+ opts.push("persist: true");
881
+ if (node.delay)
882
+ opts.push(`delay: () => ${this.expr(node.delay, ctx.scope)}`);
883
+ if (node.transition)
884
+ opts.push(`transition: ${JSON.stringify(node.transition)}`);
885
+ return `$$.when(${parent}, [\n${indent(branches.join(",\n"))}\n]${opts.length ? `, { ${opts.join(", ")} }` : ""});`;
886
+ }
887
+ genFor(node, parent, ctx, topLevel = false) {
888
+ const iter = this.expr(node.iter, ctx.scope);
889
+ const l = this.id("l");
890
+ const loopScope = new Scope(ctx.scope, "loop");
891
+ const fields = ["item", "index", "key"];
892
+ node.names.forEach((n, i) => {
893
+ const iterType = this.inferType(node.iter, ctx.scope);
894
+ const type = i === 1 ? T("num") : i === 0 && iterType && iterType.array > 0 ? { ...iterType, array: iterType.array - 1 } : undefined;
895
+ loopScope.define(n, { kind: "loop", js: `${l}.${fields[i]}`, type });
896
+ });
897
+ const p = this.id("b");
898
+ const itemRoots = [];
899
+ const body = this.genNodes(node.body, p, { ...ctx, scope: loopScope }, topLevel ? itemRoots : undefined) + (topLevel && ctx.rootHook ? "\n" + ctx.rootHook(itemRoots) : "");
900
+ const keyFn = node.keyExpr ? `(${l}) => ${this.expr(node.keyExpr, loopScope)}` : "undefined";
901
+ const filterFn = node.filter ? `(${l}) => ${this.expr(node.filter, loopScope)}` : "undefined";
902
+ const empty = node.empty ? `($$f) => {\n${indent(this.genNodes(node.empty, "$$f", ctx))}\n}` : "";
903
+ const extra = [keyFn, filterFn, empty].filter(Boolean);
904
+ while (extra.length && extra[extra.length - 1] === "undefined")
905
+ extra.pop();
906
+ return `$$.each(${parent}, () => ${iter}, (${p}, ${l}) => {\n${indent(body)}\n}${extra.length ? ", " + extra.join(", ") : ""});`;
907
+ }
908
+ stmts(stmts, scope, returnType) {
909
+ return stmts.map(s => this.stmt(s, scope, returnType)).filter(Boolean).join("\n");
910
+ }
911
+ stmt(s, scope, returnType) {
912
+ switch (s.k) {
913
+ case "expr": {
914
+ if (s.expr.k === "call") {
915
+ const b = this.calleeBinding(s.expr.callee, scope);
916
+ if (b?.fn?.ui)
917
+ this.fail("E0370", `'${b.fn.name}' returns UI and can only be used inside markup`, s.loc);
918
+ }
919
+ return `${this.expr(s.expr, scope)};`;
920
+ }
921
+ case "var":
922
+ this.checkDuplicate(scope, s.decl.name, s.loc);
923
+ return this.genVarDecl(s.decl, scope, false);
924
+ case "if": {
925
+ const thenScope = new Scope(scope);
926
+ let code = `if (${this.expr(s.test, scope)}) {\n${indent(this.stmts(s.then, thenScope, returnType))}\n}`;
927
+ if (s.else) {
928
+ const elseScope = new Scope(scope);
929
+ if (s.else.length === 1 && s.else[0].k === "if")
930
+ code += ` else ${this.stmt(s.else[0], elseScope, returnType)}`;
931
+ else
932
+ code += ` else {\n${indent(this.stmts(s.else, elseScope, returnType))}\n}`;
933
+ }
934
+ return code;
935
+ }
936
+ case "for": {
937
+ const inner = new Scope(scope, "block");
938
+ for (const n of s.names)
939
+ inner.define(n, { kind: "local", js: n });
940
+ const pattern = `[${s.names.join(", ")}]`;
941
+ const filter = s.filter ? `if (!(${this.expr(s.filter, inner)})) continue;\n` : "";
942
+ return `for (const ${pattern} of $$.iter(${this.expr(s.iter, scope)})) {\n${indent(filter + this.stmts(s.body, inner, returnType))}\n}`;
943
+ }
944
+ case "while":
945
+ return `while (${this.expr(s.test, scope)}) {\n${indent(this.stmts(s.body, new Scope(scope), returnType))}\n}`;
946
+ case "return":
947
+ if (s.value && returnType && returnType.base !== "any") {
948
+ if (returnType.base === "void")
949
+ this.fail("E0380", "This function is declared '-> void' and cannot return a value", s.loc);
950
+ this.checkAssignable(returnType, s.value, scope, s.loc, "the return value");
951
+ }
952
+ return s.value ? `return ${this.expr(s.value, scope)};` : "return;";
953
+ case "break":
954
+ return "break;";
955
+ case "continue":
956
+ return "continue;";
957
+ }
958
+ }
959
+ calleeBinding(callee, scope) {
960
+ if (callee.k === "id")
961
+ return scope.lookup(callee.name);
962
+ return undefined;
963
+ }
964
+ unknownName(name, loc, scope) {
965
+ const s = (0, diagnostics_1.suggest)(name, scope.all()) ?? [...globals_1.JS_GLOBALS].find(g => g.toLowerCase() === name.toLowerCase() || (0, diagnostics_1.levenshtein)(g, name) === 1);
966
+ this.fail("E0302", `Unknown name '${name}'`, loc, s ? `Did you mean '${s}'?` : `Declare it with 'var', import it, or declare a browser global with 'extern ${name}'`);
967
+ }
968
+ resolveId(name, loc, scope) {
969
+ const b = scope.lookup(name);
970
+ if (b)
971
+ return b;
972
+ const rt = globals_1.RUNTIME_GLOBALS.get(name);
973
+ if (rt)
974
+ return { kind: "global", js: rt };
975
+ if (globals_1.JS_GLOBALS.has(name))
976
+ return { kind: "global", js: name };
977
+ return this.unknownName(name, loc, scope);
978
+ }
979
+ bindingJs(b, scope) {
980
+ if (b.kind === "param" && b.defaultValue) {
981
+ return `(${b.js} === undefined ? ${this.expr(b.defaultValue, scope)} : ${b.js})`;
982
+ }
983
+ if (b.kind === "state" || b.kind === "computed")
984
+ this.usesState = true;
985
+ return b.js;
986
+ }
987
+ assignTarget(target, scope, loc) {
988
+ if (target.k === "id") {
989
+ const b = this.resolveId(target.name, target.loc, scope);
990
+ switch (b.kind) {
991
+ case "param":
992
+ if (b.bindable)
993
+ return b.js;
994
+ this.fail("E0390", `Cannot assign to parameter '${target.name}'; parameters are read-only`, loc, `Copy it into a variable (var ${target.name}Value = ${target.name}) or declare it as 'bind ${target.name}' for two-way binding`);
995
+ break;
996
+ case "const":
997
+ this.fail("E0391", `Cannot assign to constant '${target.name}'`, loc);
998
+ break;
999
+ case "computed":
1000
+ this.fail("E0392", `Cannot assign to computed value '${target.name}'`, loc);
1001
+ break;
1002
+ case "function":
1003
+ case "component":
1004
+ this.fail("E0393", `Cannot assign to ${b.kind} '${target.name}'`, loc);
1005
+ break;
1006
+ case "loop":
1007
+ this.fail("E0394", `Cannot assign to loop variable '${target.name}'`, loc, "Change the list instead, e.g. items[index] = newValue");
1008
+ break;
1009
+ default:
1010
+ break;
1011
+ }
1012
+ if (b.kind === "state")
1013
+ this.usesState = true;
1014
+ return b.js;
1015
+ }
1016
+ return this.expr(target, scope);
1017
+ }
1018
+ genCallArgs(args, fn, scope, loc) {
1019
+ const params = fn.params;
1020
+ const ordered = [];
1021
+ let positional = 0;
1022
+ let sawNamed = false;
1023
+ const rest = params.find(p => p.rest);
1024
+ const restArgs = [];
1025
+ for (const a of args) {
1026
+ if (a.spread)
1027
+ return args.map(x => (x.spread ? "..." : "") + this.expr(x.value, scope)).join(", ");
1028
+ if (a.name) {
1029
+ sawNamed = true;
1030
+ const idx = params.findIndex(p => p.name === a.name);
1031
+ if (idx === -1) {
1032
+ const s = (0, diagnostics_1.suggest)(a.name, params.map(p => p.name));
1033
+ this.fail("E0311", `'${fn.name}' has no parameter named '${a.name}'`, a.loc, s ? `Did you mean '${s}'?` : undefined);
1034
+ }
1035
+ if (ordered[idx])
1036
+ this.fail("E0312", `Parameter '${a.name}' was passed twice`, a.loc);
1037
+ ordered[idx] = a.value;
1038
+ }
1039
+ else {
1040
+ if (sawNamed)
1041
+ this.fail("E0313", "Positional arguments cannot follow named arguments", a.loc);
1042
+ if (positional >= params.length || params[positional].rest) {
1043
+ if (rest) {
1044
+ restArgs.push(a.value);
1045
+ continue;
1046
+ }
1047
+ this.fail("E0314", `Too many arguments for '${fn.name}': expected at most ${params.length}, got ${args.length}`, a.loc);
1048
+ }
1049
+ ordered[positional++] = a.value;
1050
+ }
1051
+ }
1052
+ params.forEach((p, i) => {
1053
+ if (p.rest)
1054
+ return;
1055
+ const given = ordered[i];
1056
+ if (!given && !p.optional) {
1057
+ this.fail("E0315", `Missing argument '${p.name}' for function '${fn.name}'`, loc, `Expected: ${fn.name}(${params.map(x => x.name + (x.optional ? "?" : "")).join(", ")})`);
1058
+ }
1059
+ if (given && p.type)
1060
+ this.checkAssignable(p.type, given, scope, given.loc, `argument '${p.name}' of '${fn.name}'`);
1061
+ });
1062
+ let last = ordered.length - 1;
1063
+ while (last >= 0 && !ordered[last])
1064
+ last--;
1065
+ const out = [];
1066
+ for (let i = 0; i <= last; i++)
1067
+ out.push(ordered[i] ? this.expr(ordered[i], scope) : "undefined");
1068
+ for (const r of restArgs)
1069
+ out.push(this.expr(r, scope));
1070
+ return out.join(", ");
1071
+ }
1072
+ expr(e, scope) {
1073
+ switch (e.k) {
1074
+ case "lit":
1075
+ return e.value === null ? "null" : JSON.stringify(e.value);
1076
+ case "tpl":
1077
+ return "`" + e.parts.map(p => (typeof p === "string" ? p.replace(/[`\\$]/g, m => "\\" + m) : "${$$.toText(" + this.expr(p, scope) + ")}")).join("") + "`";
1078
+ case "id":
1079
+ return this.bindingJs(this.resolveId(e.name, e.loc, scope), scope);
1080
+ case "member":
1081
+ return `${this.expr(e.object, scope)}${e.optional ? "?." : "."}${e.prop}`;
1082
+ case "index":
1083
+ return `${this.expr(e.object, scope)}${e.optional ? "?.[" : "["}${this.expr(e.index, scope)}]`;
1084
+ case "call": {
1085
+ const b = this.calleeBinding(e.callee, scope);
1086
+ if (e.callee.k === "id" && !b)
1087
+ this.resolveId(e.callee.name, e.callee.loc, scope);
1088
+ if (b?.kind === "component")
1089
+ this.fail("E0371", `'${e.callee.k === "id" ? e.callee.name : ""}' is a component; use it as markup, not as a function call`, e.loc);
1090
+ if (b?.fn?.ui)
1091
+ this.fail("E0370", `'${b.fn.name}' returns UI and can only be used inside markup`, e.loc);
1092
+ const callee = this.expr(e.callee, scope);
1093
+ const args = b?.fn ? this.genCallArgs(e.args, b.fn, scope, e.loc) : e.args.map(a => (a.spread ? "..." : "") + this.expr(a.value, scope)).join(", ");
1094
+ if (!b?.fn && e.args.some(a => a.name))
1095
+ this.fail("E0316", "Named arguments are only supported for Sinth functions", e.args.find(a => a.name)?.loc);
1096
+ const call = `${callee}${e.optional ? "?." : ""}(${args})`;
1097
+ if (e.memo)
1098
+ return `$$.memo(${JSON.stringify(this.fileHash + ":" + e.loc.line + ":" + e.loc.col)}, () => ${call}, [${args}])`;
1099
+ return call;
1100
+ }
1101
+ case "new":
1102
+ return `new ${this.expr(e.callee, scope)}(${e.args.map(a => (a.spread ? "..." : "") + this.expr(a.value, scope)).join(", ")})`;
1103
+ case "unary": {
1104
+ const arg = this.expr(e.arg, scope);
1105
+ if (e.op === "typeof" || e.op === "await")
1106
+ return `(${e.op} ${arg})`;
1107
+ return `(${e.op}${arg})`;
1108
+ }
1109
+ case "binary": {
1110
+ this.checkBinary(e, scope);
1111
+ const op = e.op === "==" ? "===" : e.op === "!=" ? "!==" : e.op;
1112
+ return `(${this.expr(e.left, scope)} ${op} ${this.expr(e.right, scope)})`;
1113
+ }
1114
+ case "cond":
1115
+ return `(${this.expr(e.test, scope)} ? ${this.expr(e.then, scope)} : ${this.expr(e.else, scope)})`;
1116
+ case "assign": {
1117
+ const target = this.assignTarget(e.target, scope, e.loc);
1118
+ if (e.target.k === "id") {
1119
+ const t = this.resolveId(e.target.name, e.loc, scope).type;
1120
+ if (t) {
1121
+ if (e.op === "=")
1122
+ this.checkAssignable(t, e.value, scope, e.value.loc, `'${e.target.name}'`);
1123
+ else if (e.op === "+=" && t.base === "num" && t.array === 0) {
1124
+ const vt = this.inferType(e.value, scope);
1125
+ if (vt && vt.base === "str" && vt.array === 0)
1126
+ this.fail("E0400", `Cannot add a str to num variable '${e.target.name}'`, e.value.loc);
1127
+ }
1128
+ }
1129
+ }
1130
+ return `${target} ${e.op} ${this.expr(e.value, scope)}`;
1131
+ }
1132
+ case "update":
1133
+ return e.prefix ? `++${this.assignTarget(e.target, scope, e.loc)}` : `${this.assignTarget(e.target, scope, e.loc)}++`;
1134
+ case "array":
1135
+ return `[${e.items.map(i => (i.spread ? "..." : "") + this.expr(i.value, scope)).join(", ")}]`;
1136
+ case "object":
1137
+ return `({ ${e.props.map(p => {
1138
+ if (p.spread)
1139
+ return `...${this.expr(p.value, scope)}`;
1140
+ if (p.computedKey)
1141
+ return `[${this.expr(p.computedKey, scope)}]: ${this.expr(p.value, scope)}`;
1142
+ return `${JSON.stringify(p.key)}: ${this.expr(p.value, scope)}`;
1143
+ }).join(", ")} })`;
1144
+ case "arrow": {
1145
+ const inner = new Scope(scope, "function");
1146
+ const params = this.genParams(e.params, inner);
1147
+ const isAsync = e.async || (Array.isArray(e.body) ? containsAwait(e.body) : exprHasAwait(e.body));
1148
+ if (Array.isArray(e.body))
1149
+ return `${isAsync ? "async " : ""}(${params}) => {\n${indent(this.stmts(e.body, inner))}\n}`;
1150
+ return `${isAsync ? "async " : ""}(${params}) => (${this.expr(e.body, inner)})`;
1151
+ }
1152
+ case "range":
1153
+ return `$$.range(${e.args.map(a => this.expr(a, scope)).join(", ")})`;
1154
+ }
1155
+ }
1156
+ checkBinary(e, scope) {
1157
+ if (!["==", "!=", "<", ">", "<=", ">="].includes(e.op))
1158
+ return;
1159
+ const l = this.inferType(e.left, scope);
1160
+ const r = this.inferType(e.right, scope);
1161
+ if (!l || !r || l.array || r.array || l.nullable || r.nullable)
1162
+ return;
1163
+ const isNum = (t) => t.base === "num" || t.base === "int";
1164
+ if ((isNum(l) && r.base === "str") || (l.base === "str" && isNum(r))) {
1165
+ this.fail("E0401", `Cannot compare ${typeName(l)} and ${typeName(r)} with '${e.op}'`, e.loc, "Convert one side first, e.g. Number(value) or String(value)");
1166
+ }
1167
+ }
1168
+ inferType(e, scope) {
1169
+ switch (e.k) {
1170
+ case "lit":
1171
+ if (typeof e.value === "string")
1172
+ return T("str");
1173
+ if (typeof e.value === "number")
1174
+ return T("num");
1175
+ if (typeof e.value === "boolean")
1176
+ return T("bool");
1177
+ return undefined;
1178
+ case "tpl":
1179
+ return T("str");
1180
+ case "id": {
1181
+ const b = scope.lookup(e.name);
1182
+ return b?.type;
1183
+ }
1184
+ case "binary": {
1185
+ if (["==", "!=", "<", ">", "<=", ">="].includes(e.op))
1186
+ return T("bool");
1187
+ if (e.op === "+") {
1188
+ const l = this.inferType(e.left, scope);
1189
+ const r = this.inferType(e.right, scope);
1190
+ if ((l?.base === "str" && !l.array) || (r?.base === "str" && !r.array))
1191
+ return T("str");
1192
+ if (l && r && (l.base === "num" || l.base === "int") && (r.base === "num" || r.base === "int") && !l.array && !r.array)
1193
+ return T("num");
1194
+ return undefined;
1195
+ }
1196
+ if (["-", "*", "/", "%", "**"].includes(e.op))
1197
+ return T("num");
1198
+ return undefined;
1199
+ }
1200
+ case "unary":
1201
+ if (e.op === "!")
1202
+ return T("bool");
1203
+ if (e.op === "-" || e.op === "+")
1204
+ return T("num");
1205
+ if (e.op === "typeof")
1206
+ return T("str");
1207
+ return undefined;
1208
+ case "cond": {
1209
+ const a = this.inferType(e.then, scope);
1210
+ const b = this.inferType(e.else, scope);
1211
+ return a && b && typeName(a) === typeName(b) ? a : undefined;
1212
+ }
1213
+ case "array": {
1214
+ if (!e.items.length)
1215
+ return undefined;
1216
+ const first = this.inferType(e.items[0].value, scope);
1217
+ if (!first || e.items.some(i => i.spread || typeName(this.inferType(i.value, scope) ?? T("any")) !== typeName(first)))
1218
+ return T("any", 1);
1219
+ return { ...first, array: first.array + 1 };
1220
+ }
1221
+ case "object":
1222
+ return T("obj");
1223
+ case "call": {
1224
+ const b = this.calleeBinding(e.callee, scope);
1225
+ if (b?.fn?.returnType && b.fn.returnType.base !== "void")
1226
+ return b.fn.returnType;
1227
+ if (e.callee.k === "member" && ["toUpperCase", "toLowerCase", "trim", "join", "toFixed", "padStart", "padEnd", "slice", "replace", "toString"].includes(e.callee.prop)) {
1228
+ const ot = this.inferType(e.callee.object, scope);
1229
+ if (e.callee.prop === "slice" && ot?.array)
1230
+ return ot;
1231
+ if (e.callee.prop !== "slice" || ot?.base === "str")
1232
+ return T("str");
1233
+ }
1234
+ return undefined;
1235
+ }
1236
+ case "member":
1237
+ if (e.prop === "length")
1238
+ return T("num");
1239
+ return undefined;
1240
+ default:
1241
+ return undefined;
1242
+ }
1243
+ }
1244
+ checkAssignable(target, value, scope, loc, what) {
1245
+ if (value.k === "lit" && value.value === null) {
1246
+ if (!target.nullable && target.base !== "obj" && target.base !== "any" && target.array === 0) {
1247
+ this.diagnostics.warn("W0401", `Assigning null to non-nullable ${typeName(target)} ${what}`, loc, `Declare it as '${typeName(target)}?' to allow null`);
1248
+ }
1249
+ return;
1250
+ }
1251
+ const actual = this.inferType(value, scope);
1252
+ if (!actual)
1253
+ return;
1254
+ if (target.base === "ui" || target.base === "void")
1255
+ return;
1256
+ if (!sameKind(target, actual)) {
1257
+ this.fail("E0403", `Type mismatch: cannot assign ${typeName(actual)} to ${typeName(target)} ${what}`, loc);
1258
+ }
1259
+ }
1260
+ }
1261
+ exports.ModuleCompiler = ModuleCompiler;
1262
+ function defaultFor(t) {
1263
+ if (!t)
1264
+ return "null";
1265
+ if (t.nullable)
1266
+ return "null";
1267
+ if (t.array)
1268
+ return "[]";
1269
+ switch (t.base) {
1270
+ case "str": return "\"\"";
1271
+ case "num":
1272
+ case "int": return "0";
1273
+ case "bool": return "false";
1274
+ default: return "null";
1275
+ }
1276
+ }
1277
+ function isLiteralObject(e) {
1278
+ return e.k === "object" && e.props.every(p => !p.spread && !p.computedKey && p.value.k === "lit");
1279
+ }
1280
+ function kebabCss(name) {
1281
+ return name.replace(/^(Webkit|Moz|Ms)/, m => "-" + m.toLowerCase()).replace(/[A-Z]/g, m => "-" + m.toLowerCase());
1282
+ }
1283
+ function literalObjectToCss(e) {
1284
+ return e.props
1285
+ .filter(p => p.value.k === "lit" && p.value.value !== null && p.value.value !== false)
1286
+ .map(p => `${kebabCss(p.key)}: ${String(p.value.value)}`)
1287
+ .join("; ");
1288
+ }
1289
+ function exprHasAwait(e) {
1290
+ switch (e.k) {
1291
+ case "unary": return e.op === "await" || exprHasAwait(e.arg);
1292
+ case "binary": return exprHasAwait(e.left) || exprHasAwait(e.right);
1293
+ case "assign": return exprHasAwait(e.value);
1294
+ case "cond": return exprHasAwait(e.test) || exprHasAwait(e.then) || exprHasAwait(e.else);
1295
+ case "call": return exprHasAwait(e.callee) || e.args.some(a => exprHasAwait(a.value));
1296
+ case "member": return exprHasAwait(e.object);
1297
+ case "index": return exprHasAwait(e.object) || exprHasAwait(e.index);
1298
+ case "array": return e.items.some(i => exprHasAwait(i.value));
1299
+ case "object": return e.props.some(p => exprHasAwait(p.value));
1300
+ case "tpl": return e.parts.some(p => typeof p !== "string" && exprHasAwait(p));
1301
+ default: return false;
1302
+ }
1303
+ }
1304
+ function containsAwait(stmts) {
1305
+ return stmts.some(s => {
1306
+ switch (s.k) {
1307
+ case "expr": return exprHasAwait(s.expr);
1308
+ case "var": return !!s.decl.init && exprHasAwait(s.decl.init);
1309
+ case "if": return exprHasAwait(s.test) || containsAwait(s.then) || (!!s.else && containsAwait(s.else));
1310
+ case "for": return exprHasAwait(s.iter) || containsAwait(s.body);
1311
+ case "while": return exprHasAwait(s.test) || containsAwait(s.body);
1312
+ case "return": return !!s.value && exprHasAwait(s.value);
1313
+ default: return false;
1314
+ }
1315
+ });
1316
+ }
1317
+ function indent(code) {
1318
+ return code.split("\n").map(l => (l ? " " + l : l)).join("\n");
1319
+ }
1320
+ function parseInlineExpr(src, loc) {
1321
+ const parser = parser_1.Parser.fromTokens((0, lexer_1.tokenize)(src, loc.file, loc), loc.file);
1322
+ return parser.parseExpr();
1323
+ }
1324
+ function compileModule(file, imports, opts) {
1325
+ return new ModuleCompiler(file, imports, opts).compile();
1326
+ }