@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,705 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.compileFile = compileFile;
37
- exports.minifyHTML = minifyHTML;
38
- exports.findSinthPages = findSinthPages;
39
- exports.copyDir = copyDir;
40
- const path = __importStar(require("path"));
41
- const fs = __importStar(require("fs"));
42
- const types_1 = require("./types");
43
- const utils_1 = require("../utils");
44
- const resolver_1 = require("../resolver");
45
- const functions_1 = require("./runtime/functions");
46
- const style_processor_1 = require("./style-processor");
47
- const head_builder_1 = require("./head-builder");
48
- const custom_element_1 = require("./runtime/custom-element");
49
- const compiler_1 = require("./compiler");
50
- function compileFile(filePath, opts) {
51
- const absPath = path.resolve(filePath);
52
- const file = (0, resolver_1.parseFile)(absPath);
53
- const cfg = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
54
- const { allDefs, customEls, cssLinks, jsLinks } = (0, resolver_1.resolveImports)(file, cfg);
55
- const hash = "_" + (0, utils_1.fnv1a)(absPath);
56
- const allVarDecls = file.varDecls;
57
- const functionDefs = file.functions;
58
- const fnLocalVarNames = new Set();
59
- const collectFnVars = (child) => {
60
- if (child.kind === "var") {
61
- fnLocalVarNames.add(child.name);
62
- }
63
- else if (child.kind === "if") {
64
- child.body.forEach(collectFnVars);
65
- child.elseBody?.forEach(collectFnVars);
66
- }
67
- else if (child.kind === "for") {
68
- child.body.forEach(collectFnVars);
69
- }
70
- else if (child.kind === "use") {
71
- child.children.forEach(collectFnVars);
72
- }
73
- };
74
- for (const fn of file.functions) {
75
- fn.body.forEach(collectFnVars);
76
- }
77
- const pageVarDecls = allVarDecls.filter(v => !fnLocalVarNames.has(v.name));
78
- const declaredVars = new Set(pageVarDecls.map(v => v.name));
79
- const declaredFuncs = new Set(file.functions.map(f => f.name));
80
- function collectExprVars(expr, vars) {
81
- if (!expr)
82
- return;
83
- if (expr.kind === "variable" && expr.name && !declaredFuncs.has(expr.name)) {
84
- const rootVar = expr.name.split('.')[0];
85
- vars.add(rootVar);
86
- }
87
- if (expr.kind === "assign" && expr.target) {
88
- const rootVar = expr.target.split('.')[0];
89
- vars.add(rootVar);
90
- }
91
- if (expr.left)
92
- collectExprVars(expr.left, vars);
93
- if (expr.right)
94
- collectExprVars(expr.right, vars);
95
- if (expr.operand)
96
- collectExprVars(expr.operand, vars);
97
- if (expr.object)
98
- collectExprVars(expr.object, vars);
99
- if (expr.key)
100
- collectExprVars(expr.key, vars);
101
- if (expr.args)
102
- expr.args.forEach(a => collectExprVars(a, vars));
103
- }
104
- function collectChildVars(child, vars) {
105
- if (child.kind === "expr" || child.kind === "assign_stmt" || child.kind === "return") {
106
- collectExprVars(child.expression, vars);
107
- }
108
- if (child.kind === "if") {
109
- collectExprVars(child.condition, vars);
110
- child.body.forEach(c => collectChildVars(c, vars));
111
- child.elseBody?.forEach(c => collectChildVars(c, vars));
112
- }
113
- if (child.kind === "for") {
114
- child.body.forEach(c => collectChildVars(c, vars));
115
- }
116
- if (child.kind === "use") {
117
- child.attrs.forEach(a => {
118
- if (a.name === "id")
119
- return;
120
- if (a.value?.kind === "str") {
121
- const v = a.value.value;
122
- if (v.startsWith("__EXPR__") || v.startsWith("__MULTI_EXPR__")) {
123
- try {
124
- const exprs = v.startsWith("__MULTI_EXPR__")
125
- ? JSON.parse(v.substring("__MULTI_EXPR__".length))
126
- : [JSON.parse(v.substring(8))];
127
- exprs.forEach(e => collectExprVars(e, vars));
128
- }
129
- catch {
130
- void 0;
131
- }
132
- }
133
- }
134
- });
135
- child.children.forEach(c => collectChildVars(c, vars));
136
- }
137
- }
138
- const pageVars = new Set();
139
- file.uses.forEach(u => collectChildVars(u, pageVars));
140
- const pageLoopVars = new Set();
141
- const gatherLoopVars = (child) => {
142
- if (child.kind === "for") {
143
- const fl = child;
144
- if (fl.itemVar)
145
- pageLoopVars.add(fl.itemVar);
146
- if (fl.keyVar)
147
- pageLoopVars.add(fl.keyVar);
148
- if (fl.indexVar)
149
- pageLoopVars.add(fl.indexVar);
150
- fl.body.forEach(gatherLoopVars);
151
- }
152
- else if (child.kind === "if") {
153
- child.body.forEach(gatherLoopVars);
154
- child.elseBody?.forEach(gatherLoopVars);
155
- }
156
- else if (child.kind === "use") {
157
- child.children.forEach(gatherLoopVars);
158
- }
159
- };
160
- file.uses.forEach(gatherLoopVars);
161
- for (const v of pageVars) {
162
- if (pageLoopVars.has(v))
163
- continue;
164
- const rootVar = v;
165
- if (declaredVars.has(rootVar) || fnLocalVarNames.has(rootVar))
166
- continue;
167
- let foundInFn = false;
168
- for (const fn of file.functions) {
169
- if (fn.params.some(p => p.name === rootVar)) {
170
- foundInFn = true;
171
- break;
172
- }
173
- const fnLoopVars = new Set();
174
- const gatherFnLoopVars = (child) => {
175
- if (child.kind === "for") {
176
- const fl = child;
177
- if (fl.itemVar)
178
- fnLoopVars.add(fl.itemVar);
179
- if (fl.keyVar)
180
- fnLoopVars.add(fl.keyVar);
181
- if (fl.indexVar)
182
- fnLoopVars.add(fl.indexVar);
183
- fl.body.forEach(gatherFnLoopVars);
184
- }
185
- else if (child.kind === "if") {
186
- child.body.forEach(gatherFnLoopVars);
187
- child.elseBody?.forEach(gatherFnLoopVars);
188
- }
189
- else if (child.kind === "use") {
190
- child.children.forEach(gatherFnLoopVars);
191
- }
192
- };
193
- fn.body.forEach(gatherFnLoopVars);
194
- if (fnLoopVars.has(rootVar)) {
195
- foundInFn = true;
196
- break;
197
- }
198
- }
199
- if (!foundInFn) {
200
- throw new types_1.SinthError(`Variable '${rootVar}' is used but never declared. Add 'var str ${rootVar}' or 'var int ${rootVar}' before using it.`);
201
- }
202
- }
203
- for (const fn of file.functions) {
204
- const fnParamNames = new Set(fn.params.map(p => p.name));
205
- const fnBodyVars = new Set();
206
- fn.body.forEach(c => collectChildVars(c, fnBodyVars));
207
- const fnLoopVars = new Set();
208
- const gatherFnLoopVars = (child) => {
209
- if (child.kind === "for") {
210
- const fl = child;
211
- if (fl.itemVar)
212
- fnLoopVars.add(fl.itemVar);
213
- if (fl.keyVar)
214
- fnLoopVars.add(fl.keyVar);
215
- if (fl.indexVar)
216
- fnLoopVars.add(fl.indexVar);
217
- fl.body.forEach(gatherFnLoopVars);
218
- }
219
- else if (child.kind === "if") {
220
- child.body.forEach(gatherFnLoopVars);
221
- child.elseBody?.forEach(gatherFnLoopVars);
222
- }
223
- else if (child.kind === "use") {
224
- child.children.forEach(gatherFnLoopVars);
225
- }
226
- };
227
- fn.body.forEach(gatherFnLoopVars);
228
- const fnLocalDeclared = new Set();
229
- const collectFnLocalDeclared = (child) => {
230
- if (child.kind === "var") {
231
- fnLocalDeclared.add(child.name);
232
- }
233
- else if (child.kind === "if") {
234
- child.body.forEach(collectFnLocalDeclared);
235
- child.elseBody?.forEach(collectFnLocalDeclared);
236
- }
237
- else if (child.kind === "for") {
238
- child.body.forEach(collectFnLocalDeclared);
239
- }
240
- else if (child.kind === "use") {
241
- child.children.forEach(collectFnLocalDeclared);
242
- }
243
- };
244
- fn.body.forEach(collectFnLocalDeclared);
245
- for (const v of fnBodyVars) {
246
- if (fnLoopVars.has(v))
247
- continue;
248
- const rootVar = v;
249
- if (!fnParamNames.has(rootVar) && !declaredVars.has(rootVar) && !declaredFuncs.has(rootVar) && !fnLocalDeclared.has(rootVar)) {
250
- throw new types_1.SinthError(`Variable '${rootVar}' used in function '${fn.name}' is not declared. It must be a parameter or a page-level variable.`);
251
- }
252
- }
253
- for (const child of fn.body) {
254
- checkTypeInChild(child, allVarDecls, functionDefs);
255
- }
256
- }
257
- for (const vd of pageVarDecls) {
258
- checkVarInitType(vd, allVarDecls, functionDefs);
259
- }
260
- for (const use of file.uses) {
261
- checkTypeInChild(use, allVarDecls, functionDefs);
262
- }
263
- function inferType(expr, varDecls, functionDefs) {
264
- if (expr.kind === "literal" && expr.value) {
265
- if (expr.value.kind === "str")
266
- return "str";
267
- if (expr.value.kind === "num")
268
- return "num";
269
- if (expr.value.kind === "bool")
270
- return "bool";
271
- return null;
272
- }
273
- if (expr.kind === "variable" && expr.name) {
274
- const vd = varDecls.find(v => v.name === expr.name);
275
- if (vd)
276
- return vd.varType === "str[]" ? "str[]" : vd.varType;
277
- return null;
278
- }
279
- if (expr.kind === "call" && expr.callee?.kind === "variable" && expr.callee.name) {
280
- const fd = functionDefs.find(f => f.name === expr.callee.name);
281
- if (fd?.returnType)
282
- return fd.returnType;
283
- return null;
284
- }
285
- if (expr.kind === "binary") {
286
- const leftType = inferType(expr.left, varDecls, functionDefs);
287
- const rightType = inferType(expr.right, varDecls, functionDefs);
288
- const isNum = (t) => t === "int" || t === "num";
289
- if (leftType && rightType && isNum(leftType) && isNum(rightType)) {
290
- return "num";
291
- }
292
- if (expr.op === "+") {
293
- return "str";
294
- }
295
- return null;
296
- }
297
- if (expr.kind === "unary") {
298
- if (expr.op === "not")
299
- return "bool";
300
- if (expr.op === "-") {
301
- const operandType = inferType(expr.operand, varDecls, functionDefs);
302
- if (operandType === "int" || operandType === "num")
303
- return "num";
304
- return null;
305
- }
306
- }
307
- return null;
308
- }
309
- function checkVarInitType(vd, varDecls, functionDefs) {
310
- if (!vd.value)
311
- return;
312
- if (vd.value.kind === "num") {
313
- if (vd.varType !== "int" && vd.varType !== "num")
314
- throw new types_1.SinthError(`Cannot assign number to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
315
- return;
316
- }
317
- if (vd.value.kind === "bool") {
318
- if (vd.varType !== "bool")
319
- throw new types_1.SinthError(`Cannot assign boolean to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
320
- return;
321
- }
322
- if (vd.value.kind !== "str")
323
- return;
324
- const raw = vd.value.value;
325
- if (raw.startsWith("__EXPR__")) {
326
- let expr;
327
- try {
328
- expr = JSON.parse(raw.substring(8));
329
- }
330
- catch {
331
- return;
332
- }
333
- const exprType = inferType(expr, varDecls, functionDefs);
334
- if (exprType && exprType !== vd.varType) {
335
- throw new types_1.SinthError(`Cannot assign expression of type '${exprType}' to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
336
- }
337
- return;
338
- }
339
- if (raw.startsWith("__VAR__")) {
340
- const varName = raw.substring(7);
341
- const exprType = inferType({ kind: "variable", name: varName }, varDecls, functionDefs);
342
- if (exprType && exprType !== vd.varType) {
343
- throw new types_1.SinthError(`Cannot assign variable '${varName}' of type '${exprType}' to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
344
- }
345
- return;
346
- }
347
- if (raw.startsWith("__ARR__")) {
348
- if (vd.varType !== "str[]") {
349
- throw new types_1.SinthError(`Cannot assign array literal to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
350
- }
351
- return;
352
- }
353
- if (vd.varType !== "str" && vd.varType !== "str[]") {
354
- throw new types_1.SinthError(`Cannot assign string value to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
355
- }
356
- }
357
- function checkCallArgs(fnDef, args, loc, varDecls, functionDefs) {
358
- for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
359
- const param = fnDef.params[i];
360
- const arg = args[i];
361
- if (!param.paramType)
362
- continue;
363
- const argType = inferType(arg, varDecls, functionDefs);
364
- if (argType && argType !== param.paramType && !(param.paramType === "num" && argType === "int") && !(param.paramType === "int" && argType === "num")) {
365
- if ((param.paramType === "int" || param.paramType === "num") && argType === "str" && arg.kind === "literal" && arg.value?.kind === "str") {
366
- if (!isNaN(Number(arg.value.value)))
367
- continue;
368
- }
369
- throw new types_1.SinthError(`Function '${fnDef.name}' parameter '${param.name}' expects '${param.paramType}' but got '${argType}'`, loc);
370
- }
371
- }
372
- }
373
- function checkTypeInExpr(expr, varDecls, functionDefs, loc) {
374
- if (!expr)
375
- return;
376
- if (expr.kind === "assign" && expr.target) {
377
- const parts = expr.target.split('.');
378
- const rootVar = parts[0];
379
- const vd = varDecls.find(v => v.name === rootVar);
380
- if (vd) {
381
- let expected = vd.varType;
382
- if (parts.length > 1) {
383
- if (expected === "obj")
384
- expected = "str";
385
- else if (expected === "str[]" && parts[1] === "length")
386
- expected = "num";
387
- }
388
- const rhsType = inferType(expr.right, varDecls, functionDefs);
389
- if (rhsType && expected !== rhsType) {
390
- if (expr.op === "+=" && expected === "str") { /* allow string += any */ }
391
- else if (expr.op === "-=") {
392
- if (expected !== "int" && expected !== "num") {
393
- throw new types_1.SinthError(`Cannot use '-=' on non‑numeric variable '${expr.target}'`, loc || { file: "", line: 0, col: 0 });
394
- }
395
- else if (rhsType !== "int" && rhsType !== "num") {
396
- throw new types_1.SinthError(`Right operand of '-=' must be int or num, got '${rhsType}'`, loc || { file: "", line: 0, col: 0 });
397
- }
398
- }
399
- else {
400
- throw new types_1.SinthError(`Cannot assign value of type '${rhsType}' to variable '${expr.target}' of type '${expected}'`, loc || { file: "", line: 0, col: 0 });
401
- }
402
- }
403
- }
404
- }
405
- if (expr.kind === "binary") {
406
- const leftType = inferType(expr.left, varDecls, functionDefs);
407
- const rightType = inferType(expr.right, varDecls, functionDefs);
408
- if (leftType && rightType) {
409
- const op = expr.op;
410
- if (["==", "!=", "<", ">", "<=", ">="].includes(op)) {
411
- if (leftType !== rightType) {
412
- throw new types_1.SinthError(`Cannot compare values of type '${leftType}' and '${rightType}' with '${op}'`, loc || { file: "", line: 0, col: 0 });
413
- }
414
- }
415
- else if (["and", "or"].includes(op)) {
416
- if (leftType !== "bool")
417
- throw new types_1.SinthError(`Left side of '${op}' must be bool, got '${leftType}'`, loc || { file: "", line: 0, col: 0 });
418
- if (rightType !== "bool")
419
- throw new types_1.SinthError(`Right side of '${op}' must be bool, got '${rightType}'`, loc || { file: "", line: 0, col: 0 });
420
- }
421
- else if (["-", "*", "/", "%"].includes(op)) {
422
- if ((leftType !== "int" && leftType !== "num") || (rightType !== "int" && rightType !== "num")) {
423
- throw new types_1.SinthError(`Arithmetic operator '${op}' requires int or num operands, got '${leftType}' and '${rightType}'`, loc || { file: "", line: 0, col: 0 });
424
- }
425
- }
426
- }
427
- }
428
- if (expr.kind === "unary" && expr.op === "not") {
429
- const operandType = inferType(expr.operand, varDecls, functionDefs);
430
- if (operandType && operandType !== "bool") {
431
- throw new types_1.SinthError(`'not' operator requires bool operand, got '${operandType}'`, loc || { file: "", line: 0, col: 0 });
432
- }
433
- }
434
- if (expr.kind === "call" && expr.callee?.kind === "variable" && expr.callee.name) {
435
- const fnDef = functionDefs.find(f => f.name === expr.callee.name);
436
- if (fnDef)
437
- checkCallArgs(fnDef, expr.args ?? [], loc || fnDef.loc, varDecls, functionDefs);
438
- }
439
- if (expr.left)
440
- checkTypeInExpr(expr.left, varDecls, functionDefs, loc);
441
- if (expr.right)
442
- checkTypeInExpr(expr.right, varDecls, functionDefs, loc);
443
- if (expr.operand)
444
- checkTypeInExpr(expr.operand, varDecls, functionDefs, loc);
445
- if (expr.args)
446
- expr.args.forEach(a => checkTypeInExpr(a, varDecls, functionDefs, loc));
447
- }
448
- function checkTypeInChild(child, varDecls, functionDefs) {
449
- if (child.kind === "expr" && child.expression) {
450
- checkTypeInExpr(child.expression, varDecls, functionDefs, child.loc);
451
- }
452
- if (child.kind === "assign_stmt" && child.expression) {
453
- checkTypeInExpr(child.expression, varDecls, functionDefs, child.loc);
454
- }
455
- if (child.kind === "return" && child.expression) {
456
- checkTypeInExpr(child.expression, varDecls, functionDefs);
457
- }
458
- if (child.kind === "if") {
459
- const ib = child;
460
- checkTypeInExpr(ib.condition, varDecls, functionDefs, ib.loc);
461
- ib.body.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
462
- ib.elseBody?.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
463
- }
464
- if (child.kind === "for") {
465
- child.body.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
466
- }
467
- if (child.kind === "use") {
468
- const u = child;
469
- u.attrs.forEach(a => {
470
- if (a.value?.kind === "str" && a.value.value.startsWith("__EXPR__")) {
471
- try {
472
- const expr = JSON.parse(a.value.value.substring(8));
473
- checkTypeInExpr(expr, varDecls, functionDefs, a.loc || u.loc);
474
- }
475
- catch {
476
- void 0;
477
- }
478
- }
479
- });
480
- u.children.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
481
- }
482
- }
483
- const enableDiffing = file.meta.some(m => m.key === "domdiffing" &&
484
- (m.value.kind === "bool" ? m.value.value === true : (m.value.kind === "str" && m.value.value === "true")));
485
- const REACTIVE = /^if\b|^\{|^[a-zA-Z_$][a-zA-Z0-9_$]*\s*(?:[+\-*/%]?=|<<=|>>=|>>>=|&&=|\|\|=|\?\?=)/;
486
- const topLevelLogicIfs = [];
487
- file.scripts = file.scripts.filter(s => {
488
- const trimmed = s.raw.trim();
489
- if (REACTIVE.test(trimmed)) {
490
- topLevelLogicIfs.push(trimmed);
491
- return false;
492
- }
493
- return true;
494
- });
495
- if (file.initLogic) {
496
- file.initLogic = file.initLogic.filter(s => !REACTIVE.test(s.trim()));
497
- }
498
- const ctx = {
499
- allDefs, functionDefs, customEls, cssLinks, jsLinks,
500
- scopeHash: hash,
501
- pageFile: absPath,
502
- extraCSS: [],
503
- mixedBlocks: [],
504
- mixedCounter: 0,
505
- logicBlocks: [...topLevelLogicIfs],
506
- ifIdCounter: 0,
507
- exprRegistry: [],
508
- exprMap: new Map(),
509
- varDecls: pageVarDecls,
510
- actionButtons: [],
511
- diffingEnabled: enableDiffing,
512
- declaredVars: declaredVars,
513
- namespace: hash,
514
- };
515
- if (!file.isPage) {
516
- const body = file.uses.map(u => (0, compiler_1.renderCompUse)(u, ctx, new Map(), 0)).join("\n");
517
- const pageCSS = file.styles.map(s => (0, style_processor_1.processStyleBlock)(s, hash)).join("\n");
518
- const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
519
- const h = `${body}\n<style>\n${allCSS}\n</style>`;
520
- return { html: h };
521
- }
522
- const headData = (0, head_builder_1.buildHeadData)(file.meta);
523
- const flatUses = [];
524
- function flattenUses(child) {
525
- if (child.kind === "use" && child.name === "__IF_ROOT__") {
526
- child.children.forEach(flattenUses);
527
- }
528
- else {
529
- flatUses.push(child);
530
- }
531
- }
532
- file.uses.forEach(flattenUses);
533
- const bodyHTML = flatUses.map(u => (0, compiler_1.renderChild)(u, ctx, new Map(), 0)).join("\n");
534
- const pageCSS = file.styles.map(s => (0, style_processor_1.processStyleBlock)(s, hash, new Map())).join("\n");
535
- const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
536
- const { componentScripts, pageScripts } = (0, compiler_1.collectScripts)(file, allDefs);
537
- // collect all assigned variables for default-value warnings
538
- const assignedVars = new Set();
539
- for (const s of file.scripts) {
540
- for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+-]?=)/g))
541
- assignedVars.add(m[1]);
542
- }
543
- for (const v of file.varDecls) {
544
- if (v.value)
545
- assignedVars.add(v.name);
546
- }
547
- // warn about reserved browser globals
548
- const RESERVED_GLOBALS = new Set(["name", "location", "history", "status", "closed", "length", "top", "self", "parent", "frames", "origin"]);
549
- for (const v of file.varDecls) {
550
- if (RESERVED_GLOBALS.has(v.name)) {
551
- types_1.SinthWarning.emit(`Variable '${v.name}' shadows a reserved browser global. This may cause unexpected behavior. Consider renaming.`, v.loc);
552
- }
553
- }
554
- // compile function definitions to JS
555
- const compiledFunctions = functionDefs.map(f => (0, functions_1.compileFunctionDef)(f, ctx)).join("\n");
556
- // companion JS file (needs same name as .sinth, adds support for JS libraries)
557
- const companionJS = (() => {
558
- const base = absPath.replace(/\.sinth$/, ".js");
559
- return fs.existsSync(base) ? path.basename(base) : undefined;
560
- })();
561
- const relativeCssLinks = cssLinks.map(css => {
562
- const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
563
- return rel.startsWith(".") ? rel : "./" + rel;
564
- });
565
- const relativeJsLinks = jsLinks.map(js => ({
566
- ...js,
567
- src: (() => {
568
- const rel = path.relative(path.dirname(absPath), js.src).replace(/\\/g, "/");
569
- return rel.startsWith(".") ? rel : "./" + rel;
570
- })(),
571
- }));
572
- const runtimeResult = (0, compiler_1.buildRuntime)({
573
- varDecls: pageVarDecls,
574
- bodyHTML,
575
- logicBlocks: ctx.logicBlocks,
576
- initBlocks: ctx.initBlocks,
577
- mixedBlocks: ctx.mixedBlocks,
578
- assignedVars,
579
- exprRegistry: ctx.exprRegistry,
580
- sharedRuntime: opts.sharedRuntime,
581
- functionsJS: compiledFunctions,
582
- namespace: hash,
583
- declaredVars: ctx.declaredVars,
584
- initLogic: file.initLogic,
585
- });
586
- const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
587
- const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
588
- let finalRuntimeJS = runtimeJS;
589
- if (enableDiffing) {
590
- finalRuntimeJS = runtimeJS.replace('sinthRender();', 'var _bump=function(v){_bump._v[v]=(_bump._v[v]||0)+1;};' +
591
- '_bump._v={};' +
592
- 'window._bump=_bump;' +
593
- 'var _exprCache=new WeakMap();' +
594
- 'var _origSinthExpr=sinthExpr;' +
595
- 'sinthExpr=function(el){' +
596
- 'var deps=el.dataset.sinthDeps;' +
597
- 'if(deps!=null){' +
598
- 'var list=deps.split(",").filter(Boolean);' +
599
- 'if(list.length){' +
600
- 'var h="";' +
601
- 'for(var i=0;i<list.length;i++){var v=list[i].trim();h+=v+":"+(_bump._v[v]||0)+";";}' +
602
- 'var old=_exprCache.get(el);' +
603
- 'if(old===h)return;' +
604
- '_exprCache.set(el,h);' +
605
- '}else{' +
606
- 'if(_exprCache.has(el))return;' +
607
- '_exprCache.set(el,1);' +
608
- '}' +
609
- '}' +
610
- '_origSinthExpr(el);' +
611
- '};' +
612
- 'sinthRender();');
613
- }
614
- const head = (0, head_builder_1.renderHead)(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
615
- const scriptTags = [];
616
- if (componentScripts.length > 0) {
617
- scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
618
- }
619
- for (const s of pageScripts) {
620
- const extra = Object.entries(s.attrs)
621
- .map(([k, v]) => v === "true" ? k : `${k}="${(0, utils_1.escAttr)(v)}"`)
622
- .join(" ");
623
- const globalised = s.raw.replace(/\b(let|const)\b/g, "let");
624
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
625
- }
626
- const sharedRuntimeTag = (() => {
627
- if (!opts.sharedRuntime || !sharedJS)
628
- return "";
629
- const relPath = path.relative(opts.projectRoot, absPath);
630
- const htmlOutputDir = path.dirname(relPath.replace(/\.sinth$/, '.html'));
631
- const relativeRuntimePath = path.relative(htmlOutputDir, '.').replace(/\\/g, '/');
632
- const runtimeSrc = relativeRuntimePath ? `${relativeRuntimePath}/sinth-runtime.js` : './sinth-runtime.js';
633
- return `<script src="${runtimeSrc}"></script>`;
634
- })();
635
- let actionInitScript = '';
636
- if (ctx.actionButtons.length > 0) {
637
- actionInitScript = '<script>' +
638
- ctx.actionButtons.map(b => `setTimeout(function(){ var el=document.querySelector('[data-sinth-queue-id="${b.qid}"]'); if(el)el.style.display=''; },${b.delayMs});`).join('') +
639
- '</script>';
640
- }
641
- const html = [
642
- "<!DOCTYPE html>",
643
- `<html lang="${(0, utils_1.escAttr)(headData.lang)}">`,
644
- head,
645
- `<body data-s="${hash}">`,
646
- bodyHTML,
647
- actionInitScript,
648
- sharedRuntimeTag,
649
- finalRuntimeJS.trim() ? `<script>\n${finalRuntimeJS}\n</script>` : "",
650
- scriptTags.join("\n"),
651
- "</body>",
652
- "</html>",
653
- ].filter(Boolean).join("\n");
654
- for (const cel of file.customEls) {
655
- if (cel.exportTag) {
656
- try {
657
- const compJs = (0, custom_element_1.compileCustomElement)(cel, opts, hash, ctx);
658
- const relPath = path.relative(opts.projectRoot, path.dirname(absPath));
659
- const outPath = path.join(opts.outDir, relPath, cel.exportTag + ".js");
660
- if (!opts.checkOnly) {
661
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
662
- fs.writeFileSync(outPath, compJs);
663
- process.stdout.write(` \x1b[32m✓\x1b[0m ${cel.exportTag}.js (custom element)\n`);
664
- }
665
- }
666
- catch (e) {
667
- types_1.SinthWarning.emit(`Failed to compile custom element '${cel.exportTag}': ${e.message}`, cel.loc);
668
- }
669
- }
670
- }
671
- const finalHTML = opts.minify ? minifyHTML(html) : html;
672
- return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
673
- }
674
- function minifyHTML(html) {
675
- return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
676
- }
677
- // file discovery & asset copy
678
- function findSinthPages(dir, outDir) {
679
- const results = [];
680
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
681
- if (entry.name.startsWith(".") || entry.name === "node_modules")
682
- continue;
683
- const full = path.join(dir, entry.name);
684
- if (outDir && path.resolve(full) === path.resolve(outDir))
685
- continue;
686
- if (entry.isDirectory())
687
- results.push(...findSinthPages(full, outDir));
688
- else if (entry.name.endsWith(".sinth"))
689
- results.push(full);
690
- }
691
- return results;
692
- }
693
- function copyDir(src, dest) {
694
- if (!fs.existsSync(src))
695
- return;
696
- fs.mkdirSync(dest, { recursive: true });
697
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
698
- const sp = path.join(src, entry.name);
699
- const dp = path.join(dest, entry.name);
700
- if (entry.isDirectory())
701
- copyDir(sp, dp);
702
- else
703
- fs.copyFileSync(sp, dp);
704
- }
705
- }