@yannosay/sinth 4.1.0 → 5.1.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +89 -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 +555 -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 -63
  61. package/dist/cli.js +0 -509
  62. package/dist/core/builtins.js +0 -117
  63. package/dist/core/cli-compiler.js +0 -705
  64. package/dist/core/compiler.js +0 -1489
  65. package/dist/core/expr.js +0 -129
  66. package/dist/core/head-builder.js +0 -130
  67. package/dist/core/lexer.js +0 -410
  68. package/dist/core/parser.js +0 -1646
  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
@@ -1,1489 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.INLINE_STYLE_PROPS = void 0;
4
- exports.eventAttrName = eventAttrName;
5
- exports.resolveBuiltinTag = resolveBuiltinTag;
6
- exports.registerExpr = registerExpr;
7
- exports.renderAttr = renderAttr;
8
- exports.renderChild = renderChild;
9
- exports.renderIfBlock = renderIfBlock;
10
- exports.renderCompUse = renderCompUse;
11
- exports.expandUserComp = expandUserComp;
12
- exports.collectScripts = collectScripts;
13
- exports.extractFunctionNames = extractFunctionNames;
14
- exports.buildRuntime = buildRuntime;
15
- const types_1 = require("./types");
16
- const utils_1 = require("../utils");
17
- const expr_1 = require("./expr");
18
- const helpers_1 = require("./runtime/helpers");
19
- const render_1 = require("./runtime/render");
20
- const builtins_1 = require("./builtins");
21
- const style_processor_1 = require("./style-processor");
22
- const EVENT_RE = /^on[A-Z]/;
23
- function eventAttrName(name) {
24
- return EVENT_RE.test(name) ? name.toLowerCase() : null;
25
- }
26
- /**
27
- * CSS property names that are allowed as inline style shorthand attributes on
28
- * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
29
- */
30
- exports.INLINE_STYLE_PROPS = new Set([
31
- "color", "backgroundColor", "backgroundImage", "backgroundSize", "backgroundPosition",
32
- "fontSize", "fontWeight", "fontFamily", "fontStyle", "fontVariant", "lineHeight", "letterSpacing", "textAlign",
33
- "textDecoration", "textTransform", "whiteSpace", "wordBreak", "wordWrap", "textOverflow",
34
- "margin", "marginTop", "marginBottom", "marginLeft", "marginRight",
35
- "padding", "paddingTop", "paddingBottom", "paddingLeft", "paddingRight",
36
- "width", "height", "minWidth", "maxWidth", "minHeight", "maxHeight",
37
- "display", "flexDirection", "flexWrap", "flex", "flexGrow", "flexShrink", "flexBasis",
38
- "justifyContent", "alignItems", "alignContent", "alignSelf", "gap", "rowGap", "columnGap",
39
- "gridTemplateColumns", "gridTemplateRows", "gridColumn", "gridRow", "gridArea",
40
- "position", "top", "right", "bottom", "left", "zIndex",
41
- "border", "borderTop", "borderBottom", "borderLeft", "borderRight",
42
- "borderWidth", "borderStyle", "borderColor", "borderRadius",
43
- "outline", "outlineWidth", "outlineStyle", "outlineColor", "outlineOffset",
44
- "boxShadow", "textShadow", "opacity", "visibility",
45
- "overflow", "overflowX", "overflowY", "objectFit", "objectPosition",
46
- "cursor", "userSelect", "pointerEvents", "resize",
47
- "transform", "transition", "animation", "animationDuration", "animationDelay",
48
- "listStyle", "listStyleType", "listStylePosition",
49
- "verticalAlign", "float", "clear",
50
- "content", "quotes",
51
- ]);
52
- function inlineFunctionBody(fnDef, args, ctx) {
53
- const paramMap = new Map();
54
- for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
55
- paramMap.set(fnDef.params[i].name, (0, expr_1.compileExprToJS)(args[i], ctx.loopVars, ctx.namespace, ctx.declaredVars));
56
- }
57
- const subExpr = (expr) => {
58
- if (expr.kind === "variable" && expr.name && paramMap.has(expr.name)) {
59
- return { kind: "variable", name: paramMap.get(expr.name) };
60
- }
61
- if (expr.kind === "binary") {
62
- return { ...expr, left: expr.left ? subExpr(expr.left) : undefined, right: expr.right ? subExpr(expr.right) : undefined };
63
- }
64
- if (expr.kind === "unary") {
65
- return { ...expr, operand: expr.operand ? subExpr(expr.operand) : undefined };
66
- }
67
- if (expr.kind === "assign") {
68
- if (expr.target && paramMap.has(expr.target)) {
69
- return { ...expr, target: paramMap.get(expr.target), right: expr.right ? subExpr(expr.right) : undefined };
70
- }
71
- return { ...expr, right: expr.right ? subExpr(expr.right) : undefined };
72
- }
73
- if (expr.kind === "postfix" && expr.target && paramMap.has(expr.target)) {
74
- return { ...expr, target: paramMap.get(expr.target), op: expr.op };
75
- }
76
- if (expr.kind === "index") {
77
- return { ...expr, object: expr.object ? subExpr(expr.object) : undefined, key: expr.key ? subExpr(expr.key) : undefined };
78
- }
79
- if (expr.kind === "call") {
80
- return { ...expr, callee: expr.callee ? subExpr(expr.callee) : undefined, args: expr.args?.map(a => subExpr(a)) };
81
- }
82
- return expr;
83
- };
84
- const subChild = (child) => {
85
- switch (child.kind) {
86
- case "assign_stmt":
87
- return { ...child, expression: subExpr(child.expression) };
88
- case "if": {
89
- const ib = child;
90
- return {
91
- ...ib,
92
- condition: subExpr(ib.condition),
93
- body: ib.body.map(subChild),
94
- elseBody: ib.elseBody?.map(subChild),
95
- };
96
- }
97
- case "return":
98
- return { ...child, expression: child.expression ? subExpr(child.expression) : undefined };
99
- default:
100
- return child;
101
- }
102
- };
103
- const statements = [];
104
- for (const c of fnDef.body) {
105
- const substituted = subChild(c);
106
- if (substituted.kind === "assign_stmt") {
107
- statements.push((0, expr_1.compileExprToJS)(substituted.expression, ctx.loopVars, ctx.namespace, ctx.declaredVars));
108
- }
109
- else if (substituted.kind === "expr") {
110
- statements.push((0, expr_1.compileExprToJS)(substituted.expression, ctx.loopVars, ctx.namespace, ctx.declaredVars));
111
- }
112
- else if (substituted.kind === "if") {
113
- statements.push((0, expr_1.compileIfToJS)(substituted, ctx.loopVars, ctx.namespace, ctx.declaredVars));
114
- }
115
- else if (substituted.kind === "return") {
116
- void 0;
117
- }
118
- else if (substituted.kind === "for") {
119
- const fl = substituted;
120
- const innerLoopVars = new Set();
121
- if (ctx.loopVars) {
122
- for (const v of ctx.loopVars) {
123
- if (v !== fl.itemVar && v !== fl.indexVar && v !== fl.keyVar) {
124
- innerLoopVars.add(v);
125
- }
126
- }
127
- }
128
- const bodyStmts = fl.body.map((bc) => {
129
- const s = subChild(bc);
130
- if (s.kind === "assign_stmt")
131
- return (0, expr_1.compileExprToJS)(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars);
132
- if (s.kind === "if")
133
- return (0, expr_1.compileIfToJS)(s, innerLoopVars, ctx.namespace, ctx.declaredVars);
134
- if (s.kind === "expr")
135
- return (0, expr_1.compileExprToJS)(s.expression, innerLoopVars, ctx.namespace, ctx.declaredVars);
136
- return "";
137
- }).filter(Boolean).join("; ");
138
- const nsArrayVar = (ctx.namespace && ctx.declaredVars && ctx.declaredVars.has(fl.arrayVar)) ? ctx.namespace + "_" + fl.arrayVar : fl.arrayVar;
139
- if (fl.indexVar) {
140
- const alreadyDeclared = fnDef.body.some((bc) => bc.kind === "var" && bc.name === fl.indexVar);
141
- if (!alreadyDeclared) {
142
- statements.push(`let ${fl.indexVar} = 0;`);
143
- }
144
- statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} ${fl.indexVar} = ${fl.indexVar} + 1; }`);
145
- }
146
- else {
147
- statements.push(`for (let ${fl.itemVar} of ${nsArrayVar}) { ${bodyStmts} }`);
148
- }
149
- }
150
- else if (substituted.kind === "var") {
151
- const vd = substituted;
152
- let initJS;
153
- if (vd.value) {
154
- const lit = vd.value;
155
- if (lit.kind === "str") {
156
- if (lit.value.startsWith("__VAR__")) {
157
- const varName = lit.value.slice(7);
158
- initJS = paramMap.has(varName) ? paramMap.get(varName) : varName;
159
- }
160
- else if (lit.value.startsWith("__ARR__")) {
161
- initJS = lit.value.slice(7);
162
- }
163
- else if (lit.value.startsWith("__EXPR__")) {
164
- try {
165
- const innerExpr = JSON.parse(lit.value.substring(8));
166
- initJS = (0, expr_1.compileExprToJS)(subExpr(innerExpr), ctx.loopVars, ctx.namespace, ctx.declaredVars);
167
- }
168
- catch {
169
- initJS = JSON.stringify(lit.value);
170
- }
171
- }
172
- else {
173
- initJS = JSON.stringify(lit.value);
174
- }
175
- }
176
- else if (lit.kind === "num") {
177
- initJS = String(lit.value);
178
- }
179
- else if (lit.kind === "bool") {
180
- initJS = String(lit.value);
181
- }
182
- else if (lit.kind === "null") {
183
- initJS = "null";
184
- }
185
- else {
186
- initJS = "null";
187
- }
188
- }
189
- else {
190
- const defaults = { str: '""', int: "0", num: "0", bool: "false", "str[]": "[]", obj: "{}" };
191
- initJS = defaults[vd.varType] ?? "undefined";
192
- }
193
- statements.push(`let ${vd.name} = ${initJS};`);
194
- }
195
- }
196
- if (statements.length === 0)
197
- return null;
198
- return statements.join("; ");
199
- }
200
- function resolveBuiltinTag(name, attrs) {
201
- if (name === "Heading") {
202
- const la = attrs.find(a => a.name === "level");
203
- const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
204
- if (!la)
205
- types_1.SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
206
- return { tag: `h${lv}`, voidEl: false };
207
- }
208
- const info = builtins_1.BUILTIN_MAP[name];
209
- if (info)
210
- return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
211
- types_1.SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
212
- return { tag: name.toLowerCase(), voidEl: false };
213
- }
214
- function registerExpr(ctx, expr) {
215
- let jsExpr = (0, expr_1.compileExprToJS)(expr, ctx.loopVars, ctx.namespace, ctx.declaredVars);
216
- if (ctx.scopePrefix && ctx.scopeVar && expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
217
- jsExpr = `_ctx.${ctx.scopePrefix}${expr.name}`;
218
- }
219
- const existing = ctx.exprMap.get(jsExpr);
220
- if (existing !== undefined)
221
- return existing;
222
- const id = ctx.exprRegistry.length;
223
- ctx.exprRegistry.push(jsExpr);
224
- ctx.exprMap.set(jsExpr, id);
225
- return id;
226
- }
227
- function emitCEAction(ctx, eventName, handlerBody) {
228
- if (!ctx.ceActionHandlers)
229
- ctx.ceActionHandlers = [];
230
- const idx = ctx.ceActionHandlers.length;
231
- ctx.ceActionHandlers.push(`function(e, host) { ${handlerBody} }`);
232
- return `data-sinth-ce-${eventName}="${idx}"`;
233
- }
234
- function resolveExprWithParams(expr, ctx, paramMap) {
235
- const paramNames = new Set(paramMap.keys());
236
- const combinedVars = new Set();
237
- if (ctx.declaredVars) {
238
- for (const v of ctx.declaredVars)
239
- combinedVars.add(v);
240
- }
241
- for (const p of paramNames) {
242
- combinedVars.add(p);
243
- }
244
- return (0, expr_1.compileExprToJS)(expr, ctx.loopVars, ctx.namespace, combinedVars);
245
- }
246
- function renderAttr(attr, paramMap, ctx) {
247
- const { name, value } = attr;
248
- const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
249
- if (value === null)
250
- return name;
251
- if (value.kind === "null")
252
- return "";
253
- if (value.kind === "bool")
254
- return value.value ? name : "";
255
- if (name === "model" && value?.kind === "str") {
256
- let vName = (0, utils_1.interpolateAttr)(value.value, paramMap);
257
- if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
258
- vName = `${ctx.scopePrefix}${vName}`;
259
- }
260
- if (ctx.namespace)
261
- vName = ctx.namespace + "_" + vName;
262
- const varDecl = ctx?.varDecls?.find(v => v.name === vName);
263
- const rhs = (varDecl && (varDecl.varType === "int" || varDecl.varType === "num"))
264
- ? `Number(e.target.value) || 0`
265
- : `e.target.value`;
266
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
267
- const handlerBody = `${vName} = ${rhs}; ${renderCall}`;
268
- if (ctx.scopePrefix) {
269
- const oninputAttr = emitCEAction(ctx, 'input', handlerBody);
270
- return `${oninputAttr} value="${(0, utils_1.escAttr)(vName)}"`;
271
- }
272
- return `oninput="(function(e){ ${handlerBody} })(event)" value="${(0, utils_1.escAttr)(vName)}"`;
273
- }
274
- if (name === "step" && value?.kind === "str") {
275
- const raw = value.value;
276
- if (raw.startsWith("__EXPR__")) {
277
- try {
278
- const expr = JSON.parse(raw.substring(8));
279
- if (expr.kind === "variable" && expr.name) {
280
- const stepExprId = registerExpr(ctx, expr);
281
- return `data-sinth-step="${stepExprId}"`;
282
- }
283
- }
284
- catch {
285
- void 0;
286
- }
287
- }
288
- }
289
- if (name === "delay") {
290
- if (value.kind === "num") {
291
- return `data-sinth-delay="${value.value}"`;
292
- }
293
- const v = (0, utils_1.litToString)(value);
294
- if (/^\d+$/.test(v))
295
- return `data-sinth-delay="${(0, utils_1.escAttr)(v)}"`;
296
- if (v.startsWith("__EXPR__")) {
297
- try {
298
- const expr = JSON.parse(v.substring(8));
299
- const id = registerExpr(ctx, expr);
300
- return `data-sinth-delay-expr-id="${id}"`;
301
- }
302
- catch {
303
- void 0;
304
- }
305
- }
306
- const id = registerExpr(ctx, { kind: "variable", name: v });
307
- return `data-sinth-delay-expr-id="${id}"`;
308
- }
309
- if (name === "hide") {
310
- if (value === null)
311
- return `data-sinth-hide=""`;
312
- if (value?.kind === "str") {
313
- const v = value.value;
314
- if (v === "true")
315
- return `data-sinth-hide=""`;
316
- if (v === "false")
317
- return "";
318
- if (v.startsWith("__EXPR__")) {
319
- try {
320
- const expr = JSON.parse(v.substring(8));
321
- const id = registerExpr(ctx, expr);
322
- return `data-sinth-hide="${id}"`;
323
- }
324
- catch {
325
- return "";
326
- }
327
- }
328
- }
329
- return "";
330
- }
331
- if (name === "fullscreen") {
332
- if (value?.kind === "str") {
333
- const v = value.value;
334
- if (v.startsWith("__EXPR__")) {
335
- try {
336
- const expr = JSON.parse(v.substring(8));
337
- const id = registerExpr(ctx, expr);
338
- return `data-sinth-fullscreen="${id}"`;
339
- }
340
- catch {
341
- return "";
342
- }
343
- }
344
- }
345
- return "";
346
- }
347
- if (name === "fullscreenSync") {
348
- if (value?.kind === "str") {
349
- const raw = value.value;
350
- if (raw.startsWith("__EXPR__")) {
351
- try {
352
- const expr = JSON.parse(raw.substring(8));
353
- if (expr.kind === "variable" && expr.name) {
354
- return `data-sinth-fullscreen-sync="${(0, utils_1.escAttr)(expr.name)}"`;
355
- }
356
- }
357
- catch {
358
- void 0;
359
- }
360
- }
361
- return `data-sinth-fullscreen-sync="${(0, utils_1.escAttr)(raw)}"`;
362
- }
363
- return "";
364
- }
365
- if (name === "checked") {
366
- return "";
367
- }
368
- if (value.kind === "num")
369
- return `${name}="${value.value}"`;
370
- let raw = value.value;
371
- if (raw.startsWith("__ACTION_JS__")) {
372
- let js = raw.substring("__ACTION_JS__".length).replace(/;\s*$/, '');
373
- if (ctx.namespace && ctx.declaredVars) {
374
- for (const v of ctx.declaredVars) {
375
- const regex = new RegExp(`\\b${v}\\b`, 'g');
376
- js = js.replace(regex, ctx.namespace + '_' + v);
377
- }
378
- }
379
- const ev = eventAttrName(name);
380
- if (ev)
381
- return `${ev}="(function(){ ${js.replace(/"/g, "&quot;")}; ${renderFn}(); })()"`;
382
- return `${name}="${(0, utils_1.escAttr)(js)}"`;
383
- }
384
- if (raw.startsWith("__MULTI_EXPR__")) {
385
- const exprJson = raw.substring("__MULTI_EXPR__".length);
386
- try {
387
- const exprs = JSON.parse(exprJson);
388
- let jsExprs = exprs.map(e => (0, expr_1.compileExprToJS)(e, undefined, ctx.namespace, ctx.declaredVars)).join("; ");
389
- jsExprs = jsExprs.replace(/;\s*$/, '');
390
- if (ctx.namespace && ctx.declaredVars) {
391
- for (const v of ctx.declaredVars) {
392
- const regex = new RegExp(`\\b${v}\\b`, 'g');
393
- jsExprs = jsExprs.replace(regex, ctx.namespace + '_' + v);
394
- }
395
- }
396
- const ev = eventAttrName(name);
397
- let bumps = "";
398
- if (ctx.diffingEnabled) {
399
- const targets = [];
400
- for (const e of exprs) {
401
- if (e.kind === "assign" && e.target)
402
- targets.push(e.target);
403
- }
404
- if (targets.length)
405
- bumps = ";" + targets.map(t => `window._bump&&window._bump('${t.replace(/'/g, "\\'")}')`).join(";");
406
- }
407
- if (ev)
408
- return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; ${renderFn}(); })()"`;
409
- return `${name}="${(0, utils_1.escAttr)(jsExprs)}"`;
410
- }
411
- catch {
412
- void 0;
413
- }
414
- }
415
- if (raw.startsWith("__EXPR__")) {
416
- const exprJson = raw.substring("__EXPR__".length);
417
- try {
418
- let expr = JSON.parse(exprJson);
419
- if (paramMap.size > 0) {
420
- expr = substituteParamsInExpr(expr, paramMap);
421
- }
422
- const ev = eventAttrName(name);
423
- if (ev && expr.kind === "call" && expr.callee?.kind === "variable") {
424
- const fnName = expr.callee.name;
425
- const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
426
- if (fnDef) {
427
- const inlinedJS = inlineFunctionBody(fnDef, expr.args ?? [], ctx);
428
- if (inlinedJS) {
429
- const handlerJS = inlinedJS.replace(/;\s*$/, '');
430
- return `${ev}="(function(){ ${handlerJS.replace(/"/g, "&quot;")}; ${renderFn}(); })()"`;
431
- }
432
- }
433
- }
434
- let jsExpr = resolveExprWithParams(expr, ctx, paramMap);
435
- if (ctx.namespace && !ctx.scopePrefix) {
436
- const combinedVars = new Set();
437
- if (ctx.declaredVars) {
438
- for (const v of ctx.declaredVars)
439
- combinedVars.add(v);
440
- }
441
- for (const p of paramMap.keys()) {
442
- combinedVars.add(p);
443
- }
444
- for (const v of combinedVars) {
445
- const regex = new RegExp(`\\b${v}\\b`, 'g');
446
- jsExpr = jsExpr.replace(regex, ctx.namespace + '_' + v);
447
- }
448
- }
449
- if (ctx.scopePrefix && ctx.scopeVar) {
450
- if (expr.kind === "variable" && expr.name && ctx.varDecls?.some(v => v.name === expr.name)) {
451
- jsExpr = `${ctx.scopePrefix}${expr.name}`;
452
- }
453
- else if (expr.kind === "assign" && expr.target && ctx.varDecls?.some(v => v.name === expr.target)) {
454
- jsExpr = jsExpr.replace(new RegExp(`^${expr.target}\\b`), `${ctx.scopePrefix}${expr.target}`);
455
- }
456
- }
457
- if (ev && expr.kind === "variable" && expr.name && ctx.functionDefs.some(f => f.name === expr.name)) {
458
- jsExpr = jsExpr + "()";
459
- }
460
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
461
- let bump = "";
462
- if (ctx.diffingEnabled && expr.kind === "assign" && expr.target) {
463
- bump = `;window._bump&&window._bump('${expr.target.replace(/'/g, "\\'")}')`;
464
- }
465
- if (ev) {
466
- const handlerBody = `${jsExpr.replace(/;\s*$/, '')}${bump}; ${renderCall}`;
467
- if (ctx.scopePrefix) {
468
- return emitCEAction(ctx, ev, handlerBody);
469
- }
470
- return `${ev}="(function(){ ${handlerBody.replace(/"/g, "&quot;")} })()"`;
471
- }
472
- return `${name}="${(0, utils_1.escAttr)(jsExpr)}"`;
473
- }
474
- catch {
475
- void 0;
476
- }
477
- }
478
- raw = (0, utils_1.interpolateAttr)(raw, paramMap);
479
- const ev = eventAttrName(name);
480
- if (ev) {
481
- const call = raw.includes("(") ? raw : raw + "()";
482
- return `${ev}="${(0, utils_1.escAttr)(call)};${renderFn}()"`;
483
- }
484
- return `${name}="${(0, utils_1.escAttr)(raw)}"`;
485
- }
486
- function substituteParamsInExpr(expr, params) {
487
- if (expr.kind === "variable" && expr.name && params.has(expr.name)) {
488
- const val = params.get(expr.name);
489
- if (val.startsWith("__LIT__")) {
490
- return { kind: "literal", value: { kind: "str", value: val.slice(7) } };
491
- }
492
- if (val.startsWith("__EXPR__")) {
493
- try {
494
- return JSON.parse(val.substring(8));
495
- }
496
- catch {
497
- return expr;
498
- }
499
- }
500
- return { kind: "literal", value: { kind: "str", value: val } };
501
- }
502
- if (expr.kind === "binary") {
503
- return {
504
- ...expr,
505
- left: expr.left ? substituteParamsInExpr(expr.left, params) : undefined,
506
- right: expr.right ? substituteParamsInExpr(expr.right, params) : undefined,
507
- };
508
- }
509
- if (expr.kind === "unary" && expr.operand) {
510
- return { ...expr, operand: substituteParamsInExpr(expr.operand, params) };
511
- }
512
- return expr;
513
- }
514
- function exprDeps(expr, declaredVars) {
515
- const deps = new Set();
516
- function walk(e) {
517
- if (!e)
518
- return;
519
- if (e.kind === "variable" && e.name && declaredVars.has(e.name))
520
- deps.add(e.name);
521
- if (e.kind === "binary") {
522
- walk(e.left);
523
- walk(e.right);
524
- }
525
- if (e.kind === "unary")
526
- walk(e.operand);
527
- if (e.kind === "call") {
528
- e.args?.forEach(walk);
529
- }
530
- if (e.kind === "index") {
531
- walk(e.object);
532
- walk(e.key);
533
- }
534
- if (e.kind === "assign") {
535
- if (e.target && declaredVars.has(e.target))
536
- deps.add(e.target);
537
- walk(e.right);
538
- }
539
- }
540
- walk(expr);
541
- return [...deps].join(",");
542
- }
543
- function renderChild(child, ctx, params, depth) {
544
- if (depth > 64)
545
- throw new types_1.SinthError("Maximum component nesting depth (64) exceeded.");
546
- switch (child.kind) {
547
- case "text":
548
- return (0, utils_1.renderText)(child.value, params);
549
- case "expr": {
550
- if (!child.expression)
551
- return "";
552
- if (params.size > 0) {
553
- child = { ...child, expression: substituteParamsInExpr(child.expression, params) };
554
- }
555
- if (child.expression.kind === "variable" && child.expression.name && params.has(child.expression.name)) {
556
- const val = params.get(child.expression.name);
557
- if (val.startsWith("__LIT__")) {
558
- return (0, utils_1.esc)(val.slice(7));
559
- }
560
- if (val.startsWith("__RAW__")) {
561
- return val.slice(7);
562
- }
563
- if (val.startsWith("__VAR__")) {
564
- const exprId = registerExpr(ctx, { kind: "variable", name: val.slice(7) });
565
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
566
- }
567
- if (val.startsWith("__EXPR__")) {
568
- try {
569
- const expr = JSON.parse(val.substring(8));
570
- const exprId = registerExpr(ctx, expr);
571
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
572
- }
573
- catch {
574
- return (0, utils_1.esc)(val);
575
- }
576
- }
577
- return (0, utils_1.esc)(val);
578
- }
579
- if (child.expression.kind === "call" && child.expression.callee?.kind === "variable") {
580
- const fnName = child.expression.callee.name;
581
- const isMemo = child.expression.memo === true;
582
- if (isMemo) {
583
- if (fnName && fnName.includes(".")) {
584
- types_1.SinthWarning.emit(`'$' on '${fnName}()' has no effect — dotted calls cannot be memoized.`);
585
- ctx.logicBlocks.push((0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars) + ";");
586
- return "";
587
- }
588
- const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
589
- if (!fnDef) {
590
- if (!ctx.initBlocks)
591
- ctx.initBlocks = [];
592
- ctx.initBlocks.push(`if(!_memo_${fnName}_done){${(0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars)};_memo_${fnName}_done=true;}`);
593
- return "";
594
- }
595
- const js = (0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars);
596
- ctx.logicBlocks.push(`if(!_memo_${fnName}_done){_memo_${fnName}=${js};_memo_${fnName}_done=true;}`);
597
- const exprId = registerExpr(ctx, { kind: "variable", name: `_memo_${fnName}` });
598
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
599
- }
600
- if (fnName && fnName.includes(".")) {
601
- ctx.logicBlocks.push((0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars) + ";");
602
- return "";
603
- }
604
- if (fnName === "remove" && child.expression.args && child.expression.args.length === 1) {
605
- const arg = child.expression.args[0];
606
- if (arg.kind === "literal" && arg.value?.kind === "str") {
607
- return `<span data-sinth-remove="${(0, utils_1.esc)(arg.value.value)}"></span>`;
608
- }
609
- }
610
- const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
611
- if (fnDef && fnDef.returnType === "ui") {
612
- const callArgs = child.expression.args ?? [];
613
- const localParams = new Map();
614
- for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
615
- localParams.set(fnDef.params[i].name, "__EXPR__" + JSON.stringify(callArgs[i]));
616
- }
617
- if (!ctx.fnCallCounters)
618
- ctx.fnCallCounters = new Map();
619
- const fnCallIdx = (ctx.fnCallCounters.get(fnName) ?? 0) + 1;
620
- ctx.fnCallCounters.set(fnName, fnCallIdx);
621
- const scopePrefix = `_fn_${fnName}_${fnCallIdx}_`;
622
- for (const bodyChild of fnDef.body) {
623
- if (bodyChild.kind === "var") {
624
- const vd = bodyChild;
625
- const scopedName = scopePrefix + vd.name;
626
- localParams.set(vd.name, "__VAR__" + scopedName);
627
- if (!ctx.varDecls)
628
- ctx.varDecls = [];
629
- ctx.varDecls.push({
630
- kind: "var",
631
- name: scopedName,
632
- varType: vd.varType,
633
- value: vd.value,
634
- loc: vd.loc,
635
- });
636
- if (ctx.declaredVars)
637
- ctx.declaredVars.add(scopedName);
638
- }
639
- }
640
- for (let i = 0; i < fnDef.params.length && i < callArgs.length; i++) {
641
- const param = fnDef.params[i];
642
- const argExpr = callArgs[i];
643
- const isSimpleVar = argExpr && argExpr.kind === "variable" && argExpr.name && !argExpr.name.includes(".");
644
- if (!isSimpleVar && argExpr) {
645
- const scopedName = scopePrefix + param.name;
646
- localParams.set(param.name, "__VAR__" + scopedName);
647
- if (!ctx.varDecls)
648
- ctx.varDecls = [];
649
- ctx.varDecls.push({
650
- kind: "var",
651
- name: scopedName,
652
- varType: param.paramType || "num",
653
- value: { kind: "str", value: "__EXPR__" + JSON.stringify(argExpr) },
654
- loc: param.loc,
655
- });
656
- if (ctx.declaredVars)
657
- ctx.declaredVars.add(scopedName);
658
- }
659
- }
660
- const substituteExpr = (expr, pm) => {
661
- if (expr.kind === "variable" && pm.has(expr.name)) {
662
- const pv = pm.get(expr.name);
663
- if (pv.startsWith("__LIT__"))
664
- return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
665
- if (pv.startsWith("__EXPRID__")) {
666
- const id = parseInt(pv.slice(10), 10);
667
- return { kind: "expr_ref", exprId: id };
668
- }
669
- if (pv.startsWith("__EXPR__")) {
670
- try {
671
- return JSON.parse(pv.substring(8));
672
- }
673
- catch {
674
- return expr;
675
- }
676
- }
677
- return { kind: "variable", name: pv.slice(7) };
678
- }
679
- if (expr.kind === "binary")
680
- return { ...expr, left: substituteExpr(expr.left, pm), right: substituteExpr(expr.right, pm) };
681
- if (expr.kind === "unary")
682
- return { ...expr, operand: substituteExpr(expr.operand, pm) };
683
- if (expr.kind === "call")
684
- return { ...expr, callee: substituteExpr(expr.callee, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
685
- if (expr.kind === "index")
686
- return { ...expr, object: substituteExpr(expr.object, pm), key: substituteExpr(expr.key, pm) };
687
- if (expr.kind === "assign") {
688
- const target = expr.target;
689
- if (target && pm.has(target)) {
690
- const pv = pm.get(target);
691
- if (pv.startsWith("__VAR__")) {
692
- return { ...expr, target: pv.slice(7), right: expr.right ? substituteExpr(expr.right, pm) : undefined };
693
- }
694
- if (pv.startsWith("__EXPR__")) {
695
- try {
696
- const argExpr = JSON.parse(pv.substring(8));
697
- if (argExpr.kind === "variable" && argExpr.name) {
698
- return { ...expr, target: argExpr.name, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
699
- }
700
- }
701
- catch {
702
- void 0;
703
- }
704
- }
705
- }
706
- return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
707
- }
708
- return expr;
709
- };
710
- const substituteChild = (c, pm) => {
711
- if (c.kind === "expr")
712
- return { ...c, expression: substituteExpr(c.expression, pm) };
713
- if (c.kind === "assign_stmt")
714
- return { ...c, expression: substituteExpr(c.expression, pm) };
715
- if (c.kind === "return" && c.expression)
716
- return { ...c, expression: substituteExpr(c.expression, pm) };
717
- if (c.kind === "if") {
718
- const ib = c;
719
- return { ...ib, condition: substituteExpr(ib.condition, pm), body: ib.body.map(bc => substituteChild(bc, pm)), elseBody: ib.elseBody?.map(bc => substituteChild(bc, pm)) };
720
- }
721
- if (c.kind === "for") {
722
- const fl = c;
723
- return { ...fl, body: fl.body.map(bc => substituteChild(bc, pm)) };
724
- }
725
- if (c.kind === "use") {
726
- const u = c;
727
- const sa = u.attrs.map(a => {
728
- if (a.value?.kind === "str") {
729
- let raw = a.value.value;
730
- if (raw.startsWith("__EXPR__")) {
731
- try {
732
- const expr = JSON.parse(raw.substring(8));
733
- const substituted = substituteExpr(expr, pm);
734
- return { ...a, value: { kind: "str", value: "__EXPR__" + JSON.stringify(substituted) } };
735
- }
736
- catch {
737
- void 0;
738
- }
739
- }
740
- if (raw.startsWith("__ACTION_JS__")) {
741
- return { ...a, value: { kind: "str", value: raw } };
742
- }
743
- if (raw.startsWith("__MULTI_EXPR__")) {
744
- try {
745
- const exprs = JSON.parse(raw.substring("__MULTI_EXPR__".length));
746
- const substituted = exprs.map(e => substituteExpr(e, pm));
747
- return { ...a, value: { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
748
- }
749
- catch {
750
- void 0;
751
- }
752
- }
753
- for (const [pn, pv] of pm) {
754
- if (pv.startsWith("__LIT__"))
755
- raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
756
- if (pv.startsWith("__VAR__"))
757
- raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
758
- }
759
- return { ...a, value: { kind: "str", value: raw } };
760
- }
761
- return a;
762
- });
763
- return { ...u, attrs: sa, children: u.children.map(cc => substituteChild(cc, pm)) };
764
- }
765
- return c;
766
- };
767
- return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
768
- }
769
- }
770
- if (child.expression.kind === "expr_ref" && child.expression.exprId !== undefined) {
771
- return `<span class="sinth-expr" data-expr-id="${child.expression.exprId}"></span>`;
772
- }
773
- if (child.expression.kind === "literal" && child.expression.value) {
774
- return (0, utils_1.esc)((0, utils_1.litToString)(child.expression.value));
775
- }
776
- if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
777
- const exprId = registerExpr(ctx, child.expression);
778
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
779
- }
780
- let expr = child.expression;
781
- if (params.size > 0) {
782
- expr = substituteParamsInExpr(expr, params);
783
- }
784
- const exprId = registerExpr(ctx, expr);
785
- return `<span class="sinth-expr" data-expr-id="${exprId}"${ctx.diffingEnabled ? ` data-sinth-deps="${exprDeps(child.expression, ctx.declaredVars ?? new Set())}"` : ""}></span>`;
786
- }
787
- case "assign_stmt": {
788
- ctx.logicBlocks.push((0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars) + ";");
789
- return "";
790
- }
791
- case "remove": {
792
- return `<span data-sinth-remove="${(0, utils_1.esc)(child.target)}"></span>`;
793
- }
794
- case "return":
795
- return "";
796
- case "var":
797
- return "";
798
- case "if":
799
- return renderIfBlock(child, ctx, params, depth);
800
- case "for": {
801
- const loopVars = new Set();
802
- loopVars.add(child.itemVar);
803
- if (child.keyVar)
804
- loopVars.add(child.keyVar);
805
- if (child.indexVar)
806
- loopVars.add(child.indexVar);
807
- const prev = ctx.loopVars;
808
- ctx.loopVars = loopVars;
809
- const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
810
- ctx.loopVars = prev;
811
- const keyAttr = child.keyVar ? ` data-sinth-key="${(0, utils_1.escAttr)(child.keyVar)}"` : "";
812
- const idxAttr = child.indexVar ? ` data-sinth-index="${(0, utils_1.escAttr)(child.indexVar)}"` : "";
813
- return (`<template data-sinth-for="${(0, utils_1.escAttr)(child.arrayVar)}" data-sinth-item="${(0, utils_1.escAttr)(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`);
814
- }
815
- case "use":
816
- return renderCompUse(child, ctx, params, depth);
817
- case "component_expr":
818
- return child.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
819
- }
820
- }
821
- function renderIfBlock(ifBlock, ctx, params, depth) {
822
- if (depth > 64)
823
- throw new types_1.SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
824
- const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
825
- const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
826
- const hasExprAssign = allChildren.some(c => c.kind === "expr" && c.expression?.kind === "assign");
827
- const hasComp = allChildren.some(c => c.kind === "use");
828
- if (!hasComp) {
829
- ctx.logicBlocks.push((0, expr_1.compileIfToJS)(ifBlock, undefined, ctx.namespace, ctx.declaredVars));
830
- return "";
831
- }
832
- if (!hasAssign && !hasExprAssign && !hasComp) {
833
- const tplId = ctx.ifIdCounter++;
834
- const condId = registerExpr(ctx, ifBlock.condition);
835
- const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
836
- const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
837
- const persistAttr = ifBlock.persist ? ` data-sinth-if-persist="true"` : "";
838
- return (`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${persistAttr}>${bodyHTML}</template>` +
839
- (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : ""));
840
- }
841
- // pure DOM (components need replace/persist/delay handling)
842
- if (!hasAssign && hasComp) {
843
- const tplId = ctx.ifIdCounter++;
844
- const condId = registerExpr(ctx, ifBlock.condition);
845
- const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
846
- const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
847
- let replaceAttr = "";
848
- const hasStatefulComp = ifBlock.body.some(c => {
849
- if (c.kind !== "use")
850
- return false;
851
- const u = c;
852
- if (u.name === "__IF_ROOT__")
853
- return false;
854
- if (ctx.customEls.has(u.name))
855
- return true;
856
- return u.attrs.some(a => a.name === "bind" || a.name === "model" || a.name === "fullscreenSync");
857
- }) || (ifBlock.elseBody ?? []).some(c => {
858
- if (c.kind !== "use")
859
- return false;
860
- const u = c;
861
- if (u.name === "__IF_ROOT__")
862
- return false;
863
- if (ctx.customEls.has(u.name))
864
- return true;
865
- return u.attrs.some(a => a.name === "bind" || a.name === "model" || a.name === "fullscreenSync");
866
- });
867
- const persistAttr = (ifBlock.persist || hasStatefulComp) ? ` data-sinth-if-persist="true"` : "";
868
- const firstComp = ifBlock.body.find(c => c.kind === "use");
869
- if (firstComp) {
870
- const idAttr = firstComp.attrs.find(a => a.name === "id");
871
- const replAttr = firstComp.attrs.find(a => a.name === "replace");
872
- const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
873
- if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
874
- replaceAttr = ` data-sinth-if-replace="${(0, utils_1.escAttr)(idAttr.value.value)}"`;
875
- }
876
- }
877
- let delayAttr = "";
878
- let delayHideAttr = "";
879
- if (firstComp) {
880
- const delayA = firstComp.attrs.find(a => a.name === "delay");
881
- const hideA = firstComp.attrs.find(a => a.name === "hide");
882
- if (delayA && hideA && hideA.value && hideA.value.kind === "bool" && !hideA.value.value) {
883
- if (delayA.value?.kind === "num") {
884
- delayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
885
- }
886
- else if (delayA.value?.kind === "str") {
887
- const v = (0, utils_1.litToString)(delayA.value);
888
- if (/^\d+$/.test(v))
889
- delayAttr = ` data-sinth-if-delay="${v}"`;
890
- }
891
- delayHideAttr = ` data-sinth-if-delay-hide="false"`;
892
- }
893
- }
894
- let elseDelayAttr = "";
895
- let elseDelayHideAttr = "";
896
- const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use");
897
- if (elseFirstComp) {
898
- const delayA = elseFirstComp.attrs.find(a => a.name === "delay");
899
- const hideA = elseFirstComp.attrs.find(a => a.name === "hide");
900
- if (delayA && hideA && hideA.value && hideA.value.kind === "bool" && !hideA.value.value) {
901
- if (delayA.value?.kind === "num") {
902
- elseDelayAttr = ` data-sinth-if-delay="${delayA.value.value}"`;
903
- }
904
- else if (delayA.value?.kind === "str") {
905
- const v = (0, utils_1.litToString)(delayA.value);
906
- if (/^\d+$/.test(v))
907
- elseDelayAttr = ` data-sinth-if-delay="${v}"`;
908
- }
909
- elseDelayHideAttr = ` data-sinth-if-delay-hide="false"`;
910
- }
911
- }
912
- return (`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}${delayAttr}${delayHideAttr}${persistAttr}>${bodyHTML}</template>` +
913
- (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}"${elseDelayAttr}${elseDelayHideAttr}>${elseHTML}</template>` : ""));
914
- }
915
- // mixed
916
- const id = `__sm${ctx.mixedCounter++}__`;
917
- const ifAssignJS = ifBlock.body
918
- .filter(c => c.kind === "assign_stmt")
919
- .map(c => {
920
- const e = c.expression;
921
- const js = (0, expr_1.compileExprToJS)(e, undefined, ctx.namespace, ctx.declaredVars);
922
- let bump = "";
923
- if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
924
- bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
925
- }
926
- return ` ${js};${bump}`;
927
- })
928
- .join("\n");
929
- const ifHTML = ifBlock.body
930
- .filter(c => c.kind !== "assign_stmt")
931
- .map(c => renderChild(c, ctx, params, depth + 1))
932
- .join("");
933
- const elseAssignJS = (ifBlock.elseBody ?? [])
934
- .filter(c => c.kind === "assign_stmt")
935
- .map(c => {
936
- const e = c.expression;
937
- const js = (0, expr_1.compileExprToJS)(e, undefined, ctx.namespace, ctx.declaredVars);
938
- let bump = "";
939
- if (ctx.diffingEnabled && e.kind === "assign" && e.target) {
940
- bump = `;window._bump&&window._bump('${e.target.replace(/'/g, "\\'")}')`;
941
- }
942
- return ` ${js};${bump}`;
943
- })
944
- .join("\n");
945
- const elseHTML = (ifBlock.elseBody ?? [])
946
- .filter(c => c.kind !== "assign_stmt")
947
- .map(c => renderChild(c, ctx, params, depth + 1))
948
- .join("");
949
- let replaceId;
950
- const ifFirstComp = ifBlock.body.find(c => c.kind === "use");
951
- const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use");
952
- if (ifFirstComp) {
953
- const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
954
- const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
955
- const ifReplaceVal = ifReplace?.value;
956
- const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
957
- if (ifId && ifId.kind === "str" && ifWantsReplace) {
958
- if (elseFirstComp) {
959
- const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
960
- const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
961
- const elseReplaceVal = elseReplace?.value;
962
- const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
963
- if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
964
- replaceId = ifId.value;
965
- }
966
- }
967
- }
968
- }
969
- const condId = registerExpr(ctx, ifBlock.condition);
970
- const hasFullscreen = ifHTML.includes("data-sinth-fullscreen") || elseHTML.includes("data-sinth-fullscreen");
971
- ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
972
- if (hasFullscreen) {
973
- return `<span id="${replaceId || id}" data-sinth-mixed data-sinth-mixed-fullscreen="${condId}"></span>`;
974
- }
975
- return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
976
- }
977
- function renderCompUse(use, ctx, params, depth) {
978
- const renderFn = ctx.namespace ? "sinthRender_" + ctx.namespace : "sinthRender";
979
- if (use.name === "__IF_ROOT__") {
980
- return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
981
- }
982
- if (use.name === "RawHTML") {
983
- const ca = use.attrs.find(a => a.name === "content");
984
- if (!ca || !ca.value)
985
- return "";
986
- return (0, utils_1.interpolateAttr)((0, utils_1.litToString)(ca.value), params);
987
- }
988
- // user-defined component
989
- const userDef = ctx.allDefs.get(use.name);
990
- if (userDef)
991
- return expandUserComp(use, userDef, ctx, params, depth + 1);
992
- // custom element
993
- // const customEl = ctx.customEls.get(use.name);
994
- // if (customEl) {
995
- // const attrParts = [`data-s="${ctx.scopeHash}"`];
996
- // for (const attr of use.attrs) {
997
- // if (attr.name === "bind" || attr.name === "model") continue;
998
- // const r = renderAttr(attr, params, ctx);
999
- // if (r) attrParts.push(r);
1000
- // }
1001
- // const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1002
- // return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
1003
- // }
1004
- // built-in component
1005
- const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
1006
- const isVoid = voidEl || builtins_1.VOID_TAGS.has(tag);
1007
- let attrParts = [`data-s="${ctx.scopeHash}"`];
1008
- let userClass;
1009
- const inlineStyleParts = [];
1010
- for (const attr of use.attrs) {
1011
- if (attr.name === "level" && use.name === "Heading")
1012
- continue;
1013
- if (exports.INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
1014
- if (attr.value.kind === "str" && attr.value.value.startsWith("__EXPR__")) {
1015
- try {
1016
- const expr = JSON.parse(attr.value.value.substring(8));
1017
- const exprId = registerExpr(ctx, expr);
1018
- inlineStyleParts.push(`${(0, utils_1.camelToKebab)(attr.name)}:__EXPR__${exprId}`);
1019
- }
1020
- catch {
1021
- inlineStyleParts.push(`${(0, utils_1.camelToKebab)(attr.name)}: ${(0, utils_1.interpolateAttr)(attr.value.value, params)}`);
1022
- }
1023
- }
1024
- else {
1025
- const val = attr.value.kind === "str"
1026
- ? (0, utils_1.interpolateAttr)(attr.value.value, params)
1027
- : (0, utils_1.litToString)(attr.value);
1028
- inlineStyleParts.push(`${(0, utils_1.camelToKebab)(attr.name)}: ${val}`);
1029
- }
1030
- continue;
1031
- }
1032
- if (attr.name === "class") {
1033
- if (attr.value?.kind === "str")
1034
- userClass = (0, utils_1.interpolateAttr)(attr.value.value, params);
1035
- continue;
1036
- }
1037
- if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label"))
1038
- continue;
1039
- if (attr.name === "hide") {
1040
- const rendered = renderAttr(attr, params, ctx);
1041
- if (rendered)
1042
- attrParts.push(rendered);
1043
- continue;
1044
- }
1045
- const rendered = renderAttr(attr, params, ctx);
1046
- if (rendered)
1047
- attrParts.push(rendered);
1048
- }
1049
- const classes = [defaultClass, userClass].filter(Boolean).join(" ");
1050
- if (classes)
1051
- attrParts.push(`class="${(0, utils_1.escAttr)(classes)}"`);
1052
- if (inlineStyleParts.length > 0) {
1053
- const staticParts = [];
1054
- const exprParts = [];
1055
- for (const p of inlineStyleParts) {
1056
- if (p.includes(':__EXPR__')) {
1057
- exprParts.push(p.replace('__EXPR__', ''));
1058
- }
1059
- else {
1060
- staticParts.push(p);
1061
- }
1062
- }
1063
- if (staticParts.length > 0)
1064
- attrParts.push(`style="${(0, utils_1.escAttr)(staticParts.join("; "))}"`);
1065
- if (exprParts.length > 0)
1066
- attrParts.push(`data-sinth-style="${(0, utils_1.escAttr)(exprParts.join(";"))}"`);
1067
- }
1068
- if (tag === "button" && !use.attrs.some(a => a.name === "type"))
1069
- attrParts.push(`type="button"`);
1070
- const delayAttrVal = use.attrs.find(a => a.name === "delay");
1071
- if (delayAttrVal) {
1072
- const delayMs = delayAttrVal.value?.kind === "num" ? delayAttrVal.value.value : 1000;
1073
- const eventNames = ["onClick", "onChange", "onInput", "onSubmit"];
1074
- let hasEvent = false;
1075
- for (const en of eventNames) {
1076
- const evName = en.toLowerCase();
1077
- const idx = attrParts.findIndex(p => p.startsWith(evName + "="));
1078
- if (idx >= 0) {
1079
- hasEvent = true;
1080
- const current = attrParts[idx];
1081
- const match = current.match(/\(function\(\)\{\s*(.+?);\s*sinthRender\(\)/);
1082
- if (match) {
1083
- const action = match[1];
1084
- const qid = `__sq${ctx.ifIdCounter++}`;
1085
- const hideAttr = use.attrs.find(a => a.name === "hide");
1086
- const hideVal = hideAttr
1087
- ? (hideAttr.value === null
1088
- ? true
1089
- : (hideAttr.value.kind === "bool"
1090
- ? hideAttr.value.value
1091
- : (hideAttr.value.kind === "str" && hideAttr.value.value !== "false")))
1092
- : true;
1093
- ctx.actionButtons.push({ qid, delayMs, hide: hideVal });
1094
- const delayIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay"));
1095
- if (delayIdx >= 0)
1096
- attrParts.splice(delayIdx, 1);
1097
- const hideIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-hide"));
1098
- if (hideIdx >= 0)
1099
- attrParts.splice(hideIdx, 1);
1100
- const doneIdx = attrParts.findIndex(p => p.startsWith("data-sinth-delay-done"));
1101
- if (doneIdx >= 0)
1102
- attrParts.splice(doneIdx, 1);
1103
- attrParts.push(`data-sinth-queue-id="${qid}"`);
1104
- if (hideVal) {
1105
- attrParts.push(`style="display:none"`);
1106
- }
1107
- attrParts[idx] = `${evName}="${(0, utils_1.escAttr)(`(function(e){ var el=document.querySelector('[data-sinth-queue-id=${qid}]'); if(!el)return; var hide=${hideVal}; if(hide)el.style.display='none'; var q=window._sinthQ=q||{}; var sq=q.${qid}=q.${qid}||[]; sq.push(function(){ if(hide)el.style.display=''; ${action}; ${renderFn}(); }); if(sq.length===1){ (function p(first){ if(!sq||sq.length===0){delete q.${qid};return;} var a=sq[0]; sq.shift(); var d=first?${delayMs}:0; setTimeout(function(){ a(); if(sq.length>0)setTimeout(function(){p(false)},${delayMs}); },d); })(true); } })()`)}"`;
1108
- }
1109
- }
1110
- }
1111
- if (!hasEvent) {
1112
- if (use.attrs.some(a => a.name === "hide")) {
1113
- const hideAttr = use.attrs.find(a => a.name === "hide");
1114
- const hideVal = hideAttr.value;
1115
- const isHidden = (hideVal === null) ||
1116
- (hideVal?.kind === "bool" && hideVal.value) ||
1117
- (hideVal?.kind === "str" && hideVal.value !== "false");
1118
- attrParts.push(`data-sinth-delay-hide="${isHidden ? "true" : "false"}"`);
1119
- if (!isHidden) {
1120
- attrParts.push(`data-sinth-delay-done="1"`);
1121
- }
1122
- }
1123
- else {
1124
- attrParts.push(`data-sinth-delay-hide="true"`);
1125
- }
1126
- }
1127
- }
1128
- if (use.name === "Input") {
1129
- const bindAttr = use.attrs.find(a => a.name === "bind");
1130
- const modelAttr = use.attrs.find(a => a.name === "model");
1131
- const bindOrModel = bindAttr || modelAttr;
1132
- if (bindOrModel?.value?.kind === "str") {
1133
- let vName = bindOrModel.value.value;
1134
- if (vName.startsWith("__EXPR__")) {
1135
- try {
1136
- const expr = JSON.parse(vName.substring(8));
1137
- if (expr.kind === "variable" && expr.name)
1138
- vName = expr.name;
1139
- }
1140
- catch {
1141
- void 0;
1142
- }
1143
- }
1144
- const varDecl = ctx.varDecls?.find(v => v.name === vName);
1145
- if (!use.attrs.some(a => a.name === "type")) {
1146
- if (varDecl && (varDecl.varType === "int" || varDecl.varType === "num")) {
1147
- attrParts.push(`type="number"`);
1148
- }
1149
- else {
1150
- attrParts.push(`type="text"`);
1151
- }
1152
- }
1153
- if (varDecl && (varDecl.varType === "int" || varDecl.varType === "num") && !use.attrs.some(a => a.name === "step")) {
1154
- attrParts.push(`step="1"`);
1155
- }
1156
- const rhs = (varDecl && (varDecl.varType === "int" || varDecl.varType === "num"))
1157
- ? `Number(e.target.value) || 0`
1158
- : `e.target.value`;
1159
- const initialVal = varDecl?.value ? (0, utils_1.litToString)(varDecl.value).replace(/"/g, '&quot;') : "";
1160
- let resolvedName = vName;
1161
- if (ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === vName)) {
1162
- resolvedName = `${ctx.scopePrefix}${vName}`;
1163
- }
1164
- if (ctx.namespace)
1165
- resolvedName = ctx.namespace + "_" + resolvedName;
1166
- const renderCall = ctx.scopeVar ? `${ctx.scopeVar}._render()` : renderFn + "()";
1167
- const handlerBody = `${resolvedName} = ${rhs}; ${renderCall}`;
1168
- if (ctx.scopePrefix) {
1169
- attrParts.push(emitCEAction(ctx, 'input', handlerBody));
1170
- }
1171
- else {
1172
- attrParts.push(`oninput="(function(e){ ${handlerBody} })(event)"`);
1173
- }
1174
- attrParts.push(`value="${(0, utils_1.escAttr)(initialVal)}"`);
1175
- const valueExprId = registerExpr(ctx, { kind: "variable", name: vName });
1176
- attrParts.push(`data-sinth-value="${valueExprId}"`);
1177
- }
1178
- }
1179
- if (use.name === "Checkbox") {
1180
- if (!use.attrs.some(a => a.name === "type"))
1181
- attrParts.push(`type="checkbox"`);
1182
- const checkedAttr = use.attrs.find(a => a.name === "checked");
1183
- const onChangeAttr = use.attrs.find(a => a.name === "onChange");
1184
- // Resolve bound variable name (same pattern as Input's bind/model)
1185
- let boundVarName = null;
1186
- if (checkedAttr && checkedAttr.value?.kind === "str") {
1187
- const raw = checkedAttr.value.value;
1188
- if (raw.startsWith("__EXPR__")) {
1189
- try {
1190
- const expr = JSON.parse(raw.substring(8));
1191
- if (expr.kind === "variable" && expr.name) {
1192
- boundVarName = expr.name;
1193
- }
1194
- }
1195
- catch {
1196
- void 0;
1197
- }
1198
- }
1199
- else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
1200
- boundVarName = raw;
1201
- }
1202
- }
1203
- let resolvedName = boundVarName;
1204
- if (resolvedName && ctx.scopePrefix && ctx.scopeVar && ctx.varDecls?.some(v => v.name === resolvedName)) {
1205
- resolvedName = `${ctx.scopePrefix}${resolvedName}`;
1206
- }
1207
- if (resolvedName && ctx.namespace)
1208
- resolvedName = ctx.namespace + "_" + resolvedName;
1209
- if (checkedAttr && checkedAttr.value) {
1210
- if (checkedAttr.value.kind === "bool") {
1211
- if (checkedAttr.value.value)
1212
- attrParts.push(`checked`);
1213
- }
1214
- else if (checkedAttr.value.kind === "str" && boundVarName) {
1215
- const checkedExprId = registerExpr(ctx, { kind: "variable", name: boundVarName });
1216
- attrParts.push(`data-sinth-checked="${checkedExprId}"`);
1217
- }
1218
- }
1219
- if (onChangeAttr && onChangeAttr.value?.kind === "str") {
1220
- const raw = onChangeAttr.value.value;
1221
- if (raw.startsWith("__EXPR__")) {
1222
- try {
1223
- const expr = JSON.parse(raw.substring(8));
1224
- const jsExpr = (0, expr_1.compileExprToJS)(expr, undefined, ctx.namespace, ctx.declaredVars);
1225
- attrParts.push(`onchange="(function(){ ${jsExpr}; ${renderFn}(); })(event)"`);
1226
- }
1227
- catch {
1228
- void 0;
1229
- }
1230
- }
1231
- else {
1232
- attrParts.push(`onchange="${(0, utils_1.escAttr)(raw)};${renderFn}()"`);
1233
- }
1234
- }
1235
- else if (!onChangeAttr && resolvedName) {
1236
- attrParts.push(`onchange="(function(e){ ${resolvedName} = e.target.checked; ${renderFn}(); })(event)"`);
1237
- }
1238
- const labelAttr = use.attrs.find(a => a.name === "label");
1239
- const labelText = labelAttr?.value?.kind === "str" ? (0, utils_1.esc)((0, utils_1.interpolateAttr)(labelAttr.value.value, params)) : "";
1240
- if (labelText) {
1241
- const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
1242
- return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
1243
- }
1244
- }
1245
- attrParts = attrParts.filter(p => !p.startsWith("bind="));
1246
- const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
1247
- if (isVoid) {
1248
- if (use.children.length > 0)
1249
- types_1.SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
1250
- return `<${tag}${attrStr}>`;
1251
- }
1252
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1253
- return `<${tag}${attrStr}>${inner}</${tag}>`;
1254
- }
1255
- function expandUserComp(use, def, ctx, params, depth) {
1256
- if (use.name === def.name && depth > 4) {
1257
- throw new types_1.SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
1258
- }
1259
- const local = new Map();
1260
- for (const p of def.params) {
1261
- if (p.defaultVal !== undefined)
1262
- local.set(p.name, (0, utils_1.litToString)(p.defaultVal));
1263
- }
1264
- for (const attr of use.attrs) {
1265
- if (attr.value === null) {
1266
- local.set(attr.name, "true");
1267
- }
1268
- else if (attr.value.kind !== "null") {
1269
- const raw = (0, utils_1.litToString)(attr.value);
1270
- if (raw.startsWith("__EXPR__")) {
1271
- local.set(attr.name, raw);
1272
- }
1273
- else {
1274
- local.set(attr.name, attr.value.kind === "str" ? (0, utils_1.interpolateAttr)(raw, params) : raw);
1275
- }
1276
- }
1277
- }
1278
- for (const p of def.params) {
1279
- if (!local.has(p.name)) {
1280
- throw new types_1.SinthError(`Component '${def.name}' requires parameter '${p.name}' but it was not provided.`, use.loc);
1281
- }
1282
- }
1283
- const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
1284
- local.set("slot", "__RAW__" + slotHTML);
1285
- for (const block of def.styles) {
1286
- ctx.extraCSS.push((0, style_processor_1.processStyleBlock)(block, ctx.scopeHash, local));
1287
- }
1288
- return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
1289
- }
1290
- function collectScripts(file, allDefs) {
1291
- const componentScripts = [];
1292
- const pageScripts = [];
1293
- const seenFunctions = new Set();
1294
- for (const [, def] of allDefs) {
1295
- for (const block of def.scripts) {
1296
- for (const fn of extractFunctionNames(block.raw)) {
1297
- if (seenFunctions.has(fn))
1298
- throw new types_1.SinthError(`Function '${fn}' defined in multiple component scripts.`);
1299
- seenFunctions.add(fn);
1300
- }
1301
- componentScripts.push(`(function(){\n${block.raw}\n})();`);
1302
- }
1303
- }
1304
- for (const block of file.scripts) {
1305
- for (const fn of extractFunctionNames(block.raw)) {
1306
- if (seenFunctions.has(fn))
1307
- throw new types_1.SinthError(`Function '${fn}' conflicts with a component script.`);
1308
- seenFunctions.add(fn);
1309
- }
1310
- pageScripts.push({ raw: block.raw, attrs: block.attrs });
1311
- }
1312
- return { componentScripts, pageScripts };
1313
- }
1314
- function extractFunctionNames(js) {
1315
- const names = [];
1316
- const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
1317
- let m;
1318
- while ((m = re.exec(js)) !== null)
1319
- names.push(m[1]);
1320
- return names;
1321
- }
1322
- function buildRuntime(opts) {
1323
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS, initBlocks } = opts;
1324
- const ns = opts.namespace ? "_" + opts.namespace : "";
1325
- const renderFn = "sinthRender" + ns;
1326
- const needsMixed = mixedBlocks.length > 0;
1327
- const needsDynamicAttrs = bodyHTML.includes("data-sinth-style") || bodyHTML.includes("data-sinth-value") || bodyHTML.includes("data-sinth-step") || bodyHTML.includes("data-sinth-checked");
1328
- const needsExpr = bodyHTML.includes("sinth-expr") || needsMixed || needsDynamicAttrs;
1329
- const needsIf = bodyHTML.includes("data-sinth-if") || needsMixed;
1330
- const needsFor = bodyHTML.includes("data-sinth-for") || bodyHTML.includes("data-sinth-for-expr");
1331
- const needsDelay = bodyHTML.includes("data-sinth-delay") || bodyHTML.includes("data-sinth-delay-expr-id") || mixedBlocks.some(mb => mb.ifHTML.includes("data-sinth-delay") || mb.ifHTML.includes("data-sinth-delay-expr-id") || mb.elseHTML.includes("data-sinth-delay") || mb.elseHTML.includes("data-sinth-delay-expr-id"));
1332
- const needsLogic = logicBlocks.length > 0;
1333
- const needsFullscreen = bodyHTML.includes("data-sinth-fullscreen");
1334
- const needsFullscreenSync = bodyHTML.includes("data-sinth-fullscreen-sync");
1335
- const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic || bodyHTML.includes("data-sinth-hide") || needsFullscreen || needsFullscreenSync || needsDelay || needsDynamicAttrs;
1336
- const varLines = varDecls.map(v => {
1337
- const vn = ns ? ns.slice(1) + "_" + v.name : v.name;
1338
- if (!v.value) {
1339
- if (!assignedVars.has(v.name)) {
1340
- const defaults = { str: '""', int: "0", num: "0", bool: "false", "str[]": "[]" };
1341
- types_1.SinthWarning.emit(`Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`, v.loc);
1342
- }
1343
- const defaults = { str: '""', int: "0", num: "0", bool: "false", "str[]": "[]" };
1344
- return `var ${vn} = ${defaults[v.varType] ?? "undefined"};`;
1345
- }
1346
- const val = (0, utils_1.litToString)(v.value);
1347
- if (val.startsWith("__VAR__"))
1348
- return `var ${vn} = ${val.slice(7)};`;
1349
- if (val.startsWith("__ARR__"))
1350
- return `var ${vn} = ${val.slice(7)};`;
1351
- if (val.startsWith("__EXPR__")) {
1352
- try {
1353
- const expr = JSON.parse(val.substring(8));
1354
- const js = (0, expr_1.compileExprToJS)(expr, undefined, opts.namespace, opts.declaredVars);
1355
- const id = exprRegistry.length;
1356
- exprRegistry.push(js);
1357
- return `var ${vn} = __X${ns}[${id}]({});`;
1358
- }
1359
- catch {
1360
- return `var ${vn} = ${val};`;
1361
- }
1362
- }
1363
- if (v.varType === "obj")
1364
- return `var ${vn} = ${val};`;
1365
- if (v.varType === "str")
1366
- return `var ${vn} = ${JSON.stringify(val)};`;
1367
- if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
1368
- try {
1369
- const arr = JSON.parse(val.slice(7));
1370
- return `var ${vn} = ${JSON.stringify(arr)};`;
1371
- }
1372
- catch {
1373
- return `var ${vn} = ${val.slice(7)};`;
1374
- }
1375
- }
1376
- return `var ${vn} = ${val};`;
1377
- }).join("\n");
1378
- const memoVars = new Set();
1379
- for (const lb of logicBlocks) {
1380
- let matches = lb.match(/_memo_(\w+)/g);
1381
- if (matches)
1382
- matches.forEach(m => memoVars.add(m));
1383
- matches = lb.match(/_memo_(\w+)_done/g);
1384
- if (matches)
1385
- matches.forEach(m => memoVars.add(m));
1386
- }
1387
- for (const ib of (initBlocks || [])) {
1388
- let matches = ib.match(/_memo_(\w+)/g);
1389
- if (matches)
1390
- matches.forEach(m => memoVars.add(m));
1391
- matches = ib.match(/_memo_(\w+)_done/g);
1392
- if (matches)
1393
- matches.forEach(m => memoVars.add(m));
1394
- }
1395
- for (const e of exprRegistry) {
1396
- const matches = e.match(/_memo_(\w+)/g);
1397
- if (matches)
1398
- matches.forEach(m => memoVars.add(m));
1399
- }
1400
- const memoVarDecls = [...memoVars].map(m => `var ${m};`).join("\n");
1401
- if (!needsRender) {
1402
- const out = [varLines, memoVarDecls].filter(Boolean).join("\n");
1403
- return out ? `// Sinth Compiled Runtime\n${out}` : "";
1404
- }
1405
- const helpers = (0, helpers_1.generateHelpers)({ needsExpr, needsIf, needsFor, needsDelay, needsMixed, ns });
1406
- const renderBody = (0, render_1.buildRenderBody)({
1407
- bodyHTML, logicBlocks: [], mixedBlocks,
1408
- needsLogic: false, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1409
- ns
1410
- });
1411
- let forDataJS = "";
1412
- let forSyncBlock = "";
1413
- if (needsFor) {
1414
- const forArrays = new Set();
1415
- const forRegex = /data-sinth-for="([^"]+)"/g;
1416
- let m;
1417
- while ((m = forRegex.exec(bodyHTML)) !== null) {
1418
- forArrays.add(m[1]);
1419
- }
1420
- if (forArrays.size > 0) {
1421
- forDataJS = `var _sinthForData = {};\n`;
1422
- forSyncBlock = [...forArrays].map(v => {
1423
- const bare = v.replace(/&quot;/g, '"');
1424
- const namespaced = opts.namespace ? opts.namespace + "_" + bare : bare;
1425
- return `_sinthForData['${bare}'] = ${namespaced};`;
1426
- }).join("\n ") + "\n ";
1427
- }
1428
- }
1429
- const exprArrayJS = exprRegistry.length > 0
1430
- ? `let __X${ns} = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1431
- : "";
1432
- let initLogicJS = "";
1433
- const allInit = [...(opts.initLogic || []), ...(initBlocks || [])];
1434
- if (allInit.length > 0) {
1435
- let logic = allInit.join("\n");
1436
- if (opts.namespace && opts.declaredVars) {
1437
- for (const v of opts.declaredVars) {
1438
- const re = new RegExp(`\\b${v}\\b`, 'g');
1439
- logic = logic.replace(re, opts.namespace + "_" + v);
1440
- }
1441
- }
1442
- initLogicJS = logic + "\n";
1443
- }
1444
- let renderFunc = '';
1445
- if (needsRender) {
1446
- const logicAtTop = logicBlocks.length > 0 ? logicBlocks.join("\n") + "\n" : "";
1447
- renderFunc = `function ${renderFn}() {\n ${logicAtTop}${forSyncBlock}${renderBody}\n}\n${initLogicJS}${renderFn}();`;
1448
- }
1449
- if (needsFullscreenSync) {
1450
- renderFunc += `
1451
- (function() {
1452
- let syncedEls = document.querySelectorAll('[data-sinth-fullscreen-sync]');
1453
- if (syncedEls.length > 0) {
1454
- let vars = [];
1455
- syncedEls.forEach(function(el) { vars.push(el.dataset.sinthFullscreenSync); });
1456
- document.addEventListener('fullscreenchange', function() {
1457
- let state = !!document.fullscreenElement;
1458
- vars.forEach(function(varName) {
1459
- switch(varName) {
1460
- ${[...new Set(varDecls.filter(v => v.name).map(v => {
1461
- const vn3 = ns ? ns.slice(1) + "_" + v.name : v.name;
1462
- return `case '${v.name}': ${vn3} = state; break;`;
1463
- }))].join('\n ')}
1464
- }
1465
- });
1466
- ${renderFn}();
1467
- });
1468
- }
1469
- })();`;
1470
- }
1471
- const pageCode = `// Sinth Page Runtime
1472
- ${forDataJS}
1473
- ${exprArrayJS}
1474
- ${memoVarDecls}
1475
- ${varLines}
1476
- ${renderFunc}`;
1477
- if (opts.sharedRuntime && helpers.trim()) {
1478
- const sharedCode = `// Sinth Shared Runtime
1479
- ${helpers}`;
1480
- return { page: pageCode, shared: sharedCode };
1481
- }
1482
- return `// Sinth Compiled Runtime
1483
- ${forDataJS}
1484
- ${functionsJS ? functionsJS + "\n" : ""}${helpers}
1485
- ${exprArrayJS}
1486
- ${memoVarDecls}
1487
- ${varLines}
1488
- ${renderFunc}`;
1489
- }