@yannosay/sinth 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sinth.ts DELETED
@@ -1,3699 +0,0 @@
1
- #!/usr/bin/env node
2
- // Sinth Compiler
3
-
4
- import * as fs from "fs";
5
- import * as path from "path";
6
- import * as http from "http";
7
-
8
-
9
- interface Loc { file: string; line: number; col: number }
10
-
11
- enum TT {
12
- LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
13
- LBRACKET, RBRACKET,
14
- STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_LIT,
15
- RAW_BLOCK,
16
- IDENT,
17
- KW_IMPORT, KW_AS, KW_CSS,
18
- KW_COMPONENT, KW_STYLE, KW_SCRIPT,
19
- KW_GLOBAL, KW_PAGE, KW_LANG,
20
- KW_CUSTOM_EL, KW_CUSTOM,
21
- KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
22
- OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
23
- OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
24
- EOF,
25
- }
26
-
27
- interface Token { type: TT; value: string; loc: Loc }
28
-
29
- type LitStr = { kind: "str"; value: string };
30
- type LitNum = { kind: "num"; value: number };
31
- type LitBool = { kind: "bool"; value: boolean };
32
- type LitNull = { kind: "null" };
33
- type Literal = LitStr | LitNum | LitBool | LitNull;
34
-
35
- type UnaryOp = "not" | "-";
36
- type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
37
- type AssignOp = "=" | "+=" | "-=";
38
- type PostfixOp = "++" | "--";
39
-
40
- interface Expression {
41
- kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index";
42
- value?: Literal;
43
- name?: string;
44
- op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
45
- operand?: Expression;
46
- left?: Expression;
47
- right?: Expression;
48
- target?: string;
49
- object?: Expression;
50
- key?: Expression;
51
- }
52
-
53
- interface Attr { name: string; value: Literal | null; loc: Loc }
54
- interface TextNode { kind: "text"; value: string; loc: Loc }
55
- interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
56
- interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
57
- interface AssignStmt { kind: "assign_stmt"; expression: Expression; loc: Loc }
58
- interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
59
- interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
60
- interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
61
-
62
-
63
- type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt;
64
-
65
- interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
66
-
67
- interface StyleBlock {
68
- global: boolean;
69
- lang: "css" | "scss";
70
- raw: string;
71
- target?: string;
72
- extraAttrs: Record<string, string>;
73
- loc: Loc;
74
- }
75
-
76
- interface ScriptBlock { raw: string; attrs: Record<string, string>; loc: Loc }
77
- interface CompDef { name: string; params: ParamDecl[]; body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[]; loc: Loc }
78
- interface CustomElDecl { sinthName: string; tagName: string; params: ParamDecl[]; loc: Loc }
79
- interface CustomElInfo { tagName: string; params: ParamDecl[] }
80
-
81
- type VarType = "int" | "str" | "bool" | "str[]" | "obj";
82
- interface VarDeclaration { kind: "var"; name: string; varType: VarType; value: Literal | null; loc: Loc }
83
-
84
- type ImportNode =
85
- | { kind: "sinth"; path: string; loc: Loc }
86
- | { kind: "css"; path: string; loc: Loc }
87
- | { kind: "js"; name: string; alias?: string; loc: Loc };
88
-
89
- interface MetaEntry { key: string; value: Literal; loc: Loc }
90
-
91
- interface SinthFile {
92
- filePath: string;
93
- isPage: boolean;
94
- imports: ImportNode[];
95
- meta: MetaEntry[];
96
- defs: CompDef[];
97
- uses: CompUse[];
98
- styles: StyleBlock[];
99
- scripts: ScriptBlock[];
100
- customEls: CustomElDecl[];
101
- varDecls: VarDeclaration[];
102
- }
103
-
104
- interface MixedBlockEntry {
105
- id: string;
106
- conditionJS: string;
107
- ifJS: string;
108
- ifHTML: string;
109
- elseJS: string;
110
- elseHTML: string;
111
- replaceId?: string;
112
- }
113
-
114
- interface CompileCtx {
115
- allDefs: Map<string, CompDef>;
116
- customEls: Map<string, CustomElInfo>;
117
- cssLinks: string[];
118
- jsLinks: { src: string; attrs: Record<string, string> }[];
119
- scopeHash: string;
120
- pageFile: string;
121
- extraCSS: string[];
122
- mixedBlocks: MixedBlockEntry[];
123
- mixedCounter: number;
124
- logicBlocks: string[];
125
- ifIdCounter: number;
126
- exprRegistry: string[];
127
- exprMap: Map<string, number>;
128
- loopVars?: Set<string>;
129
- }
130
-
131
- class SinthError extends Error {
132
- constructor(
133
- public readonly rawMsg: string,
134
- public readonly loc?: Loc,
135
- public readonly sourceLine?: string,
136
- ) {
137
- super(SinthError.buildMessage(rawMsg, loc, sourceLine));
138
- Object.setPrototypeOf(this, SinthError.prototype);
139
- }
140
-
141
- static buildMessage(msg: string, loc?: Loc, sourceLine?: string): string {
142
- let s = `Error: ${msg}`;
143
- if (loc) {
144
- s += `\n at: ${loc.file} (line ${loc.line}, col ${loc.col})`;
145
- if (sourceLine !== undefined) {
146
- const lineNum = String(loc.line).padStart(4);
147
- const pointer = " ".repeat(Math.max(0, loc.col - 1)) + "^";
148
- s += `\n${lineNum} | ${sourceLine}\n | ${pointer}`;
149
- }
150
- }
151
- return s;
152
- }
153
-
154
- withSource(lines: string[]): SinthError {
155
- if (!this.loc || this.sourceLine !== undefined) return this;
156
- const line = lines[this.loc.line - 1] ?? "";
157
- return new SinthError(this.rawMsg, this.loc, line);
158
- }
159
- }
160
-
161
- class SinthWarning {
162
- static emit(msg: string, loc?: Loc): void {
163
- const where = loc ? `\n at: ${loc.file}:${loc.line}` : "";
164
- process.stderr.write(`\x1b[33mWarning:\x1b[0m ${msg}${where}\n`);
165
- }
166
- }
167
-
168
- function fnv1a(s: string): string {
169
- let h = 0x811c9dc5;
170
- for (let i = 0; i < s.length; i++) {
171
- h ^= s.charCodeAt(i);
172
- h = Math.imul(h, 0x01000193) >>> 0;
173
- }
174
- return h.toString(16).padStart(8, "0").slice(0, 8);
175
- }
176
-
177
- function camelToKebab(s: string): string {
178
- const vp = s.match(/^(Webkit|Moz|Ms)(.+)$/);
179
- if (vp) return `-${vp[1].toLowerCase()}-${camelToKebab(vp[2])}`;
180
- return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
181
- }
182
-
183
- function tagNameToPascal(tag: string): string {
184
- return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
185
- }
186
-
187
- function esc(s: string): string {
188
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
189
- }
190
-
191
- function escAttr(s: string): string {
192
- return esc(s).replace(/"/g, "&quot;");
193
- }
194
-
195
- function litToString(lit: Literal): string {
196
- switch (lit.kind) {
197
- case "str": return lit.value;
198
- case "num": return String(lit.value);
199
- case "bool": return String(lit.value);
200
- case "null": return "";
201
- }
202
- }
203
-
204
- // lexer
205
- const KEYWORDS: Record<string, TT> = {
206
- "import": TT.KW_IMPORT,
207
- "as": TT.KW_AS,
208
- "css": TT.KW_CSS,
209
- "component": TT.KW_COMPONENT,
210
- "style": TT.KW_STYLE,
211
- "script": TT.KW_SCRIPT,
212
- "global": TT.KW_GLOBAL,
213
- "page": TT.KW_PAGE,
214
- "lang": TT.KW_LANG,
215
- "true": TT.BOOL_TRUE,
216
- "false": TT.BOOL_FALSE,
217
- "null": TT.NULL_LIT,
218
- "custom-element": TT.KW_CUSTOM_EL,
219
- "custom": TT.KW_CUSTOM,
220
- "if": TT.KW_IF,
221
- "else": TT.KW_ELSE,
222
- "for": TT.KW_FOR,
223
- "in": TT.KW_IN,
224
- "remove": TT.KW_REMOVE,
225
- };
226
-
227
- export class Lexer {
228
- private pos = 0;
229
- private line = 1;
230
- private col = 1;
231
- private rawBlockPending = false;
232
-
233
- constructor(public readonly src: string, private readonly file: string) {}
234
-
235
- tokenize(): Token[] {
236
- const tokens: Token[] = [];
237
- while (true) {
238
- this.skipWS();
239
- if (this.pos >= this.src.length) break;
240
-
241
- const loc = this.loc();
242
- const ch = this.src[this.pos];
243
-
244
- if (ch === "(") { tokens.push(this.single(TT.LPAREN, loc)); continue; }
245
- if (ch === ")") { tokens.push(this.single(TT.RPAREN, loc)); continue; }
246
- if (ch === "}") { tokens.push(this.single(TT.RBRACE, loc)); continue; }
247
- if (ch === ",") { tokens.push(this.single(TT.COMMA, loc)); continue; }
248
- if (ch === ".") { tokens.push(this.single(TT.DOT, loc)); continue; }
249
- if (ch === ":") { tokens.push(this.single(TT.COLON, loc)); continue; }
250
- if (ch === "[") { tokens.push(this.single(TT.LBRACKET, loc)); continue; }
251
- if (ch === "]") { tokens.push(this.single(TT.RBRACKET, loc)); continue; }
252
-
253
- // two-character operators ->
254
- if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
255
- if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
256
- if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
257
- if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
258
-
259
- if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
260
- if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
261
- if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
262
- if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
263
- if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
264
- if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
265
- if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
266
- if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
267
- tokens.push(this.single(TT.OP_MINUS, loc)); continue;
268
- }
269
-
270
- if (ch === "{") {
271
- if (this.rawBlockPending) {
272
- this.rawBlockPending = false;
273
- tokens.push(this.readRawBlock(loc));
274
- } else {
275
- tokens.push(this.single(TT.LBRACE, loc));
276
- }
277
- continue;
278
- }
279
-
280
- if (ch === '"' || ch === "'") { tokens.push(this.readString(loc)); continue; }
281
-
282
- if (this.isDigit(ch) || (ch === "-" && this.isDigit(this.src[this.pos + 1] ?? ""))) {
283
- tokens.push(this.readNumber(loc)); continue;
284
- }
285
-
286
- if (this.isIdentStart(ch)) {
287
- const tok = this.readIdent(loc);
288
- if (
289
- tok.type === TT.KW_STYLE ||
290
- tok.type === TT.KW_SCRIPT ||
291
- tok.type === TT.KW_COMPONENT ||
292
- tok.type === TT.KW_CUSTOM_EL ||
293
- tok.type === TT.KW_CUSTOM
294
- ) {
295
- this.rawBlockPending = true;
296
- }
297
- tokens.push(tok);
298
- continue;
299
- }
300
-
301
- throw new SinthError(`Unexpected character '${ch}'`, loc);
302
- }
303
- tokens.push({ type: TT.EOF, value: "", loc: this.loc() });
304
- return tokens;
305
- }
306
-
307
- private skipWS(): void {
308
- while (this.pos < this.src.length) {
309
- const ch = this.src[this.pos];
310
- if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") { this.adv(); continue; }
311
-
312
- // sinth comments: -- line or --[ nestable block for when doing longgerrr comments]--
313
- if (ch === "-" && this.src[this.pos + 1] === "-") {
314
- if (this.src[this.pos + 2] === "[") {
315
- this.adv(); this.adv(); this.adv();
316
- let depth = 1;
317
- while (this.pos < this.src.length && depth > 0) {
318
- if (this.src[this.pos] === "-" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "[") {
319
- depth++; this.adv(); this.adv(); this.adv();
320
- } else if (this.src[this.pos] === "]" && this.src[this.pos + 1] === "-" && this.src[this.pos + 2] === "-") {
321
- depth--; this.adv(); this.adv(); this.adv();
322
- } else {
323
- this.adv();
324
- }
325
- }
326
- if (depth > 0) throw new SinthError("Unterminated block comment --[ ... ]--", this.loc());
327
- } else {
328
- while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
329
- }
330
- continue;
331
- }
332
- break;
333
- }
334
- }
335
-
336
- private readRawBlock(loc: Loc): Token {
337
- this.adv(); // consume '{'
338
- const start = this.pos;
339
- let depth = 1;
340
-
341
- while (this.pos < this.src.length && depth > 0) {
342
- const ch = this.src[this.pos];
343
- if (ch === '"' || ch === "'" || ch === "`") { this.skipRawString(ch); continue; }
344
- if (ch === "/" && this.src[this.pos + 1] === "/") {
345
- while (this.pos < this.src.length && this.src[this.pos] !== "\n") this.adv();
346
- continue;
347
- }
348
- if (ch === "/" && this.src[this.pos + 1] === "*") {
349
- this.adv(); this.adv();
350
- while (this.pos < this.src.length - 1 &&
351
- !(this.src[this.pos] === "*" && this.src[this.pos + 1] === "/")) { this.adv(); }
352
- this.adv(); this.adv();
353
- continue;
354
- }
355
- if (ch === "{") { depth++; this.adv(); }
356
- else if (ch === "}") {
357
- depth--;
358
- if (depth > 0) this.adv();
359
- } else {
360
- this.adv();
361
- }
362
- }
363
-
364
- const content = this.src.substring(start, this.pos);
365
- this.adv(); // consume closing '}'
366
- return { type: TT.RAW_BLOCK, value: content, loc };
367
- }
368
-
369
- private skipRawString(quote: string): void {
370
- this.adv();
371
- while (this.pos < this.src.length) {
372
- const c = this.src[this.pos];
373
- if (c === "\\") { this.adv(); this.adv(); continue; }
374
- if (c === quote) { this.adv(); return; }
375
- if (quote === "`" && c === "$" && this.src[this.pos + 1] === "{") {
376
- this.adv(); this.adv();
377
- let d = 1;
378
- while (this.pos < this.src.length && d > 0) {
379
- if (this.src[this.pos] === "{") d++;
380
- else if (this.src[this.pos] === "}") d--;
381
- this.adv();
382
- }
383
- continue;
384
- }
385
- this.adv();
386
- }
387
- }
388
-
389
- private readString(loc: Loc): Token {
390
- const quote = this.src[this.pos];
391
- this.adv();
392
- let result = "";
393
- while (this.pos < this.src.length && this.src[this.pos] !== quote) {
394
- if (this.src[this.pos] === "\\") {
395
- this.adv();
396
- const e = this.src[this.pos];
397
- switch (e) {
398
- case "\\": result += "\\"; break;
399
- case '"': result += '"'; break;
400
- case "'": result += "'"; break;
401
- case "n": result += "\n"; break;
402
- case "r": result += "\r"; break;
403
- case "t": result += "\t"; break;
404
- case "$": result += "$"; break;
405
- case "{": result += "{"; break;
406
- case "u": {
407
- this.adv();
408
- if (this.src[this.pos] === "{") {
409
- this.adv();
410
- let hex = "";
411
- while (this.src[this.pos] !== "}") { hex += this.src[this.pos]; this.adv(); }
412
- result += String.fromCodePoint(parseInt(hex, 16));
413
- } else {
414
- const hex = this.src.substring(this.pos, this.pos + 4);
415
- result += String.fromCharCode(parseInt(hex, 16));
416
- this.pos += 3; this.col += 3;
417
- }
418
- break;
419
- }
420
- default: throw new SinthError(`Unknown escape sequence \\${e}`, loc);
421
- }
422
- this.adv();
423
- } else {
424
- result += this.src[this.pos];
425
- this.adv();
426
- }
427
- }
428
- if (this.pos >= this.src.length) throw new SinthError("Unterminated string literal", loc);
429
- this.adv();
430
- return { type: TT.STRING, value: result, loc };
431
- }
432
-
433
- private readNumber(loc: Loc): Token {
434
- let s = "";
435
- if (this.src[this.pos] === "-") { s += "-"; this.adv(); }
436
- while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
437
- if (this.src[this.pos] === "." && this.isDigit(this.src[this.pos + 1] ?? "")) {
438
- s += "."; this.adv();
439
- while (this.isDigit(this.src[this.pos] ?? "")) { s += this.src[this.pos]; this.adv(); }
440
- }
441
- return { type: TT.NUMBER, value: s, loc };
442
- }
443
-
444
- private readIdent(loc: Loc): Token {
445
- let s = "";
446
- while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
447
- s += this.src[this.pos]; this.adv();
448
- }
449
- const kw = KEYWORDS[s];
450
- return { type: kw !== undefined ? kw : TT.IDENT, value: s, loc };
451
- }
452
-
453
- private adv(): void {
454
- const ch = this.src[this.pos++];
455
- if (ch === "\n") { this.line++; this.col = 1; } else { this.col++; }
456
- }
457
-
458
- private single(type: TT, loc: Loc): Token {
459
- this.adv();
460
- return { type, value: this.src[this.pos - 1], loc };
461
- }
462
-
463
- private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
464
- private isDigit(c: string) { return c >= "0" && c <= "9"; }
465
- private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
466
- private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
467
- }
468
-
469
- // parser
470
-
471
- export class Parser {
472
- private pos = 0;
473
- private loopVar: string | null = null;
474
- /** Accumulated var declarations for type-checking in bodies. */
475
- private _varDecls: VarDeclaration[] = [];
476
-
477
- constructor(private tokens: Token[], private file: string) {}
478
-
479
-
480
- // top-level file parse
481
- parse(): SinthFile {
482
- let isPage = false;
483
- const imports: ImportNode[] = [];
484
- const meta: MetaEntry[] = [];
485
- const defs: CompDef[] = [];
486
- const uses: CompUse[] = [];
487
- const styles: StyleBlock[] = [];
488
- const scripts: ScriptBlock[] = [];
489
- const customEls: CustomElDecl[] = [];
490
- const varDecls: VarDeclaration[] = [];
491
- this._varDecls = varDecls;
492
-
493
- if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
494
-
495
- while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
496
-
497
- while (this.isMetaStart()) {
498
- const entry = this.parseMeta();
499
- meta.push(entry);
500
- if (entry.key === "title") isPage = true;
501
- }
502
-
503
-
504
- while (this.check(TT.IDENT) && this.peek().value === "var") {
505
- const vd = this.parseVarDeclaration();
506
- if (vd) { varDecls.push(vd); }
507
- }
508
-
509
-
510
- while (!this.check(TT.EOF)) {
511
- if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
512
- else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
513
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
514
- else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
515
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
516
- const vd = this.parseVarDeclaration();
517
- if (vd) varDecls.push(vd);
518
- }
519
- else if (this.check(TT.KW_IF)) {
520
- const ifNode = this.parseIfBlock();
521
- uses.push(...this.flattenIfToUses(ifNode, scripts));
522
- }
523
- else if (this.check(TT.KW_FOR)) {
524
- const forNode = this.parseForLoop();
525
- uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
526
- }
527
- else if (this.check(TT.IDENT)) {
528
- const savedPos = this.pos;
529
- const identName = this.peek().value;
530
- const nextType = this.tokens[this.pos + 1]?.type;
531
-
532
- // detect accidental top-level expressions (guess == target" instead of "if guess == target")
533
- const isComparison = [TT.OP_EQEQ, TT.OP_NEQ, TT.OP_LT, TT.OP_GT, TT.OP_LTEQ, TT.OP_GTEQ].includes(nextType);
534
- const isLogicAndOr = nextType === TT.IDENT && (this.tokens[this.pos + 1]?.value === "and" || this.tokens[this.pos + 1]?.value === "or");
535
-
536
- if (isComparison || isLogicAndOr) {
537
- throw new SinthError(
538
- `Unexpected expression '${identName} ...' at top level. Did you mean to wrap this in an 'if' block?`,
539
- this.peek().loc,
540
- );
541
- }
542
-
543
- // top-level assignment: ident = expr
544
- if (nextType === TT.EQUALS ||
545
- (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) ||
546
- (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
547
- this.consume(TT.IDENT); // consume name
548
- let op: AssignOp = "=";
549
- if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
550
- else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
551
- this.consume(TT.EQUALS);
552
- const expr = this.parseExpression();
553
- if (expr) {
554
- const js = `${identName} ${op} ${compileExprToJS(expr)};
555
- sinthRender();`;
556
- scripts.push({ raw: js, attrs: {}, loc: this.peek().loc });
557
- }
558
- continue;
559
- }
560
-
561
- // component usage
562
- this.pos = savedPos;
563
- uses.push(this.parseCompUse());
564
- }
565
- else throw new SinthError(
566
- `Unexpected token '${this.peek().value}' (${TT[this.peek().type]}) at top level`,
567
- this.peek().loc,
568
- );
569
- }
570
-
571
- return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
572
- }
573
-
574
- private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
575
- const bodyHasComp = ifNode.body.some(c => c.kind === "use");
576
- const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
577
- if (!bodyHasComp && !elseHasComp) {
578
- scripts.push({ raw: compileIfToJS(ifNode), attrs: {}, loc: ifNode.loc });
579
- return [];
580
- }
581
- const syntheticUse: CompUse = {
582
- kind: "use",
583
- name: "__IF_ROOT__",
584
- attrs: [],
585
- children: [ifNode],
586
- loc: ifNode.loc,
587
- };
588
- return [syntheticUse];
589
- }
590
-
591
- // imports
592
-
593
- private parseImport(): ImportNode {
594
- const loc = this.consume(TT.KW_IMPORT).loc;
595
- if (this.check(TT.KW_CSS)) {
596
- this.consume(TT.KW_CSS);
597
- return { kind: "css", path: this.consume(TT.STRING).value, loc };
598
- }
599
- if (this.check(TT.STRING)) {
600
- return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
601
- }
602
- if (this.check(TT.IDENT)) {
603
- const name = this.consume(TT.IDENT).value;
604
- let alias: string | undefined;
605
- if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
606
- return { kind: "js", name, alias, loc };
607
- }
608
- throw new SinthError(`Expected import path, library name, or 'css'`, loc);
609
- }
610
-
611
- // metadata
612
-
613
- private isMetaStart(): boolean {
614
- if (!this.check(TT.IDENT)) return false;
615
- return this.tokens[this.pos + 1]?.type === TT.EQUALS;
616
- }
617
-
618
- private parseMeta(): MetaEntry {
619
- const loc = this.peek().loc;
620
- const key = this.consume(TT.IDENT).value;
621
- this.consume(TT.EQUALS);
622
- return { key, value: this.parseLiteral(), loc };
623
- }
624
-
625
- // var declarations
626
-
627
- private parseVarDeclaration(): VarDeclaration | null {
628
- const loc = this.peek().loc;
629
- this.consume(TT.IDENT); // consume 'var'
630
-
631
- const typeTok = this.consume(TT.IDENT);
632
- let typeStr = typeTok.value;
633
- if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
634
- this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
635
- typeStr = "str[]";
636
- }
637
- if (!["int", "str", "bool", "str[]", "obj"].includes(typeStr)) {
638
- throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
639
- }
640
-
641
- const nameTok = this.consume(TT.IDENT);
642
- let val: Literal | null = null;
643
-
644
- if (this.check(TT.EQUALS)) {
645
- this.consume(TT.EQUALS);
646
- if (this.check(TT.LBRACKET)) {
647
- val = this.parseArrayLiteral();
648
- } else if (this.check(TT.IDENT)) {
649
- const refName = this.consume(TT.IDENT).value;
650
- val = { kind: "str", value: `__VAR__${refName}` };
651
- } else {
652
- val = this.parseLiteral();
653
- }
654
- }
655
-
656
- return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
657
- }
658
-
659
- private parseArrayLiteral(): Literal {
660
- this.consume(TT.LBRACKET);
661
- const items: any[] = [];
662
- while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
663
- if (this.check(TT.LBRACE)) {
664
- items.push(this.parseObjectLiteral());
665
- } else if (this.check(TT.STRING)) {
666
- items.push(this.consume(TT.STRING).value);
667
- } else if (this.check(TT.NUMBER)) {
668
- items.push(parseFloat(this.consume(TT.NUMBER).value));
669
- } else if (this.check(TT.BOOL_TRUE)) {
670
- this.consume(TT.BOOL_TRUE);
671
- items.push(true);
672
- } else if (this.check(TT.BOOL_FALSE)) {
673
- this.consume(TT.BOOL_FALSE);
674
- items.push(false);
675
- } else if (this.check(TT.NULL_LIT)) {
676
- this.consume(TT.NULL_LIT);
677
- items.push(null);
678
- }
679
- if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
680
- }
681
- this.consume(TT.RBRACKET);
682
- return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
683
- }
684
-
685
- private parseObjectLiteral(): Record<string, any> {
686
- this.consume(TT.LBRACE);
687
- const obj: Record<string, any> = {};
688
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
689
- const key = this.consume(TT.IDENT).value;
690
- this.consume(TT.COLON);
691
- if (this.check(TT.STRING)) {
692
- obj[key] = this.consume(TT.STRING).value;
693
- } else if (this.check(TT.NUMBER)) {
694
- obj[key] = parseFloat(this.consume(TT.NUMBER).value);
695
- } else if (this.check(TT.BOOL_TRUE)) {
696
- this.consume(TT.BOOL_TRUE);
697
- obj[key] = true;
698
- } else if (this.check(TT.BOOL_FALSE)) {
699
- this.consume(TT.BOOL_FALSE);
700
- obj[key] = false;
701
- } else if (this.check(TT.NULL_LIT)) {
702
- this.consume(TT.NULL_LIT);
703
- obj[key] = null;
704
- } else {
705
- throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
706
- }
707
- if (this.check(TT.COMMA)) this.consume(TT.COMMA);
708
- }
709
- this.consume(TT.RBRACE);
710
- return obj;
711
- }
712
-
713
- // expression parsing
714
-
715
- parseExpression(): Expression | null {
716
- const tok = this.peek();
717
-
718
- // Unary 'not'
719
- if (tok.type === TT.IDENT && tok.value === "not") {
720
- this.consume(TT.IDENT);
721
- const operand = this.parseExpression();
722
- if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
723
- const unaryExpr: Expression = { kind: "unary", op: "not", operand };
724
- return this.parseBinaryRHS(this.parsePostfix(unaryExpr));
725
- }
726
-
727
- if (this.check(TT.LPAREN)) {
728
- this.consume(TT.LPAREN);
729
- const inner = this.parseExpression();
730
- if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
731
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
732
- this.consume(TT.RPAREN);
733
- return this.parseBinaryRHS(this.parsePostfix(inner));
734
- }
735
-
736
- // literal
737
- if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
738
- this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
739
- const lit = this.parseLiteral();
740
- const base: Expression = { kind: "literal", value: lit };
741
- return this.parseBinaryRHS(this.parsePostfix(base));
742
- }
743
-
744
- // var or assignment
745
- if (tok.type === TT.IDENT) {
746
- const name = this.consume(TT.IDENT).value;
747
- let varExpr: Expression;
748
-
749
- // dot notation -> user.age
750
- if (this.check(TT.DOT)) {
751
- this.consume(TT.DOT);
752
- const propName = this.consume(TT.IDENT).value;
753
- const fullName = `${name}.${propName}`;
754
- varExpr = { kind: "variable", name: fullName };
755
- } else {
756
- varExpr = { kind: "variable", name };
757
- }
758
-
759
- // apply bracket postfixes (e.g. data[key], data["x"])
760
- const indexedExpr = this.parsePostfix(varExpr);
761
-
762
- // if indexing was applied, we don't allow assignment, just binary RHS
763
- if (indexedExpr !== varExpr) {
764
- return this.parseBinaryRHS(indexedExpr);
765
- }
766
-
767
- // no indexing – check for assignment operators
768
- const nextType = this.tokens[this.pos]?.type;
769
- if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
770
- this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
771
- const rhs = this.parseExpression();
772
- if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
773
- return { kind: "assign", target: varExpr.name!, op: "+=", right: rhs };
774
- }
775
- if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
776
- this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
777
- const rhs = this.parseExpression();
778
- if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
779
- return { kind: "assign", target: varExpr.name!, op: "-=", right: rhs };
780
- }
781
- if (nextType === TT.EQUALS) {
782
- this.consume(TT.EQUALS);
783
- const rhs = this.parseExpression();
784
- if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
785
- return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
786
- }
787
-
788
- return this.parseBinaryRHS(varExpr);
789
- }
790
-
791
- return null;
792
- }
793
-
794
- private parseBinaryRHS(left: Expression): Expression {
795
- const t = this.peek().type;
796
- let op: BinaryOp | null = null;
797
- if (t === TT.OP_EQEQ) op = "==";
798
- else if (t === TT.OP_NEQ) op = "!=";
799
- else if (t === TT.OP_LT) op = "<";
800
- else if (t === TT.OP_GT) op = ">";
801
- else if (t === TT.OP_LTEQ) op = "<=";
802
- else if (t === TT.OP_GTEQ) op = ">=";
803
- else if (t === TT.OP_PLUS) op = "+";
804
- else if (t === TT.OP_MINUS) op = "-";
805
- else if (t === TT.OP_STAR) op = "*";
806
- else if (t === TT.OP_SLASH) op = "/";
807
- else if (t === TT.IDENT && this.peek().value === "and") op = "and";
808
- else if (t === TT.IDENT && this.peek().value === "or") op = "or";
809
-
810
- if (!op) return left;
811
- this.pos++;
812
-
813
- const right = this.parseExpression();
814
- if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
815
- return { kind: "binary", left, op, right };
816
- }
817
-
818
- private parsePostfix(base: Expression): Expression {
819
- let expr = base;
820
- while (this.check(TT.LBRACKET)) {
821
- this.consume(TT.LBRACKET);
822
- const key = this.parseExpression();
823
- if (!key) throw new SinthError("Expected expression inside [...]", this.peek().loc);
824
- this.consume(TT.RBRACKET);
825
- expr = { kind: "index", object: expr, key };
826
- }
827
- return expr;
828
- }
829
-
830
-
831
- // component definitions
832
-
833
- private parseCompDef(): CompDef {
834
- const loc = this.consume(TT.KW_COMPONENT).loc;
835
- const name = this.consume(TT.IDENT).value;
836
- const params = this.parseParamDecls();
837
- const rawTok = this.consume(TT.RAW_BLOCK);
838
- const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
839
- return { name, params, body, styles, scripts, loc };
840
- }
841
-
842
- private parseCustomEl(): CustomElDecl {
843
- const loc = this.peek().loc;
844
- if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
845
- else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
846
- const tagName = this.consume(TT.IDENT).value;
847
- const sinthName = tagNameToPascal(tagName);
848
- const params = this.parseParamDecls();
849
- return { sinthName, tagName, params, loc };
850
- }
851
-
852
- private parseParamDecls(): ParamDecl[] {
853
- const params: ParamDecl[] = [];
854
- if (!this.check(TT.LPAREN)) return params;
855
- this.consume(TT.LPAREN);
856
- while (!this.check(TT.RPAREN)) {
857
- const ploc = this.peek().loc;
858
- const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
859
- const pname = nameTok.value;
860
- let defaultVal: Literal | undefined;
861
- if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
862
- params.push({ name: pname, defaultVal, loc: ploc });
863
- if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
864
- }
865
- this.consume(TT.RPAREN);
866
- return params;
867
- }
868
-
869
- private parseCompBody(
870
- raw: string,
871
- loc: Loc,
872
- ): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
873
- const tokens = new Lexer(raw, loc.file).tokenize();
874
- const sub = new Parser(tokens, loc.file);
875
- sub._varDecls = this._varDecls;
876
- return sub.parseBodyContents();
877
- }
878
-
879
- private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
880
- const body: Child[] = [], styles: StyleBlock[] = [], scripts: ScriptBlock[] = [];
881
- while (!this.check(TT.EOF)) {
882
- if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
883
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
884
- else if (this.check(TT.STRING)) {
885
- const loc = this.peek().loc;
886
- body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
887
- }
888
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
889
- const vd = this.parseVarDeclaration();
890
- if (vd) this._varDecls.push(vd);
891
- continue;
892
- }
893
- else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
894
- else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
895
- else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
896
- else throw new SinthError(
897
- `Unexpected token '${this.peek().value}' in component body`,
898
- this.peek().loc,
899
- );
900
- }
901
- return { body, styles, scripts };
902
- }
903
-
904
- // if / else blocks
905
-
906
- private parseIfBlock(): IfBlock {
907
- const loc = this.consume(TT.KW_IF).loc;
908
- const condition = this.parseExpression();
909
- if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
910
-
911
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after if condition", this.peek().loc);
912
- this.consume(TT.LBRACE);
913
- const body = this.parseUnifiedBody();
914
- this.consume(TT.RBRACE);
915
-
916
- let elseBody: Child[] | undefined;
917
- if (this.check(TT.KW_ELSE)) {
918
- this.consume(TT.KW_ELSE);
919
- if (this.check(TT.KW_IF)) {
920
- elseBody = [this.parseIfBlock()];
921
- } else {
922
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after else", this.peek().loc);
923
- this.consume(TT.LBRACE);
924
- elseBody = this.parseUnifiedBody();
925
- this.consume(TT.RBRACE);
926
- }
927
- }
928
-
929
- return { kind: "if", condition, body, elseBody, loc };
930
- }
931
-
932
- private parseUnifiedBody(): Child[] {
933
- const children: Child[] = [];
934
-
935
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
936
- if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
937
- if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
938
- if (this.check(TT.LPAREN)) {
939
- const loc = this.peek().loc;
940
- const expr = this.parseExpression();
941
- if (expr) {
942
- children.push({ kind: "expr", expression: expr, loc });
943
- }
944
- continue;
945
- }
946
- if (this.check(TT.STRING)) {
947
- const loc = this.peek().loc;
948
- children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
949
- continue;
950
- }
951
-
952
- if (this.check(TT.KW_REMOVE)) {
953
- const loc = this.consume(TT.KW_REMOVE).loc;
954
- if (this.check(TT.STRING)) {
955
- const target = this.consume(TT.STRING).value;
956
- children.push({ kind: "remove", target, loc });
957
- } else {
958
- throw new SinthError(
959
- `Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
960
- this.peek().loc,
961
- );
962
- }
963
- continue;
964
- }
965
- if (this.check(TT.IDENT) && this.peek().value === "var") {
966
- const vd = this.parseVarDeclaration();
967
- if (vd) this._varDecls.push(vd);
968
- continue;
969
- }
970
-
971
- if (this.check(TT.IDENT)) {
972
- const loc = this.peek().loc;
973
- const name = this.peek().value;
974
- const nextType = this.tokens[this.pos + 1]?.type;
975
- const nextNextType = this.tokens[this.pos + 2]?.type;
976
-
977
- if (nextType === TT.DOT && (nextNextType === TT.EQUALS ||
978
- (nextNextType === TT.OP_PLUS && this.tokens[this.pos + 3]?.type === TT.EQUALS) ||
979
- (nextNextType === TT.OP_MINUS && this.tokens[this.pos + 3]?.type === TT.EQUALS))) {
980
- let fullName = this.consume(TT.IDENT).value;
981
- this.consume(TT.DOT);
982
- fullName = fullName + "." + this.consume(TT.IDENT).value;
983
-
984
- let op: AssignOp = "=";
985
- const afterDotType = this.tokens[this.pos]?.type;
986
- if (afterDotType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
987
- this.consume(TT.OP_PLUS); op = "+=";
988
- } else if (afterDotType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
989
- this.consume(TT.OP_MINUS); op = "-=";
990
- }
991
- this.consume(TT.EQUALS);
992
- const rhs = this.parseExpression();
993
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
994
- const assignExpr: Expression = { kind: "assign", target: fullName, op, right: rhs };
995
- children.push({ kind: "assign_stmt", expression: assignExpr, loc });
996
- continue;
997
- }
998
-
999
- // assignment: ident = expr | ident += expr | ident -= expr
1000
- const isSimpleAssign = nextType === TT.EQUALS;
1001
- const isPlusAssign = nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
1002
- const isMinusAssign = nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
1003
-
1004
- if (isSimpleAssign || isPlusAssign || isMinusAssign) {
1005
- this.consume(TT.IDENT); // consume name
1006
- let op: AssignOp = "=";
1007
- if (isPlusAssign) { this.consume(TT.OP_PLUS); op = "+="; }
1008
- else if (isMinusAssign) { this.consume(TT.OP_MINUS); op = "-="; }
1009
- this.consume(TT.EQUALS);
1010
- const rhs = this.parseExpression();
1011
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
1012
- const assignExpr: Expression = { kind: "assign", target: name, op, right: rhs };
1013
- children.push({ kind: "assign_stmt", expression: assignExpr, loc });
1014
- continue;
1015
- }
1016
-
1017
- // Component usage: ident( or ident{ or ident RAW_BLOCK
1018
- if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1019
- children.push(this.parseCompUse());
1020
- continue;
1021
- }
1022
-
1023
- // var expression
1024
- // check dot notation variable reference (user.age without assignment)
1025
- if (nextType === TT.DOT) {
1026
- let fullName = this.consume(TT.IDENT).value;
1027
- this.consume(TT.DOT);
1028
- fullName = fullName + "." + this.consume(TT.IDENT).value;
1029
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1030
- continue;
1031
- }
1032
-
1033
- // bracket notation: ident[...]
1034
- if (nextType === TT.LBRACKET) {
1035
- this.consume(TT.IDENT);
1036
- const varExpr: Expression = { kind: "variable", name };
1037
- const indexedExpr = this.parsePostfix(varExpr);
1038
- children.push({ kind: "expr", expression: indexedExpr, loc });
1039
- continue;
1040
- }
1041
-
1042
-
1043
- // simple variable reference
1044
- this.consume(TT.IDENT);
1045
- children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1046
- continue;
1047
- }
1048
-
1049
- throw new SinthError(
1050
- `Unexpected token '${this.peek().value}' in if/else body`,
1051
- this.peek().loc,
1052
- );
1053
-
1054
- // reject implicit concatenation only after expression children
1055
- if (children.length > 0) {
1056
- const lastChild = children[children.length - 1];
1057
- if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1058
- const nextTT = this.tokens[this.pos]?.type;
1059
- if (
1060
- nextTT === TT.STRING || nextTT === TT.NUMBER ||
1061
- nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1062
- (nextTT === TT.IDENT &&
1063
- this.tokens[this.pos]?.value !== "var" &&
1064
- this.tokens[this.pos]?.value !== "if" &&
1065
- this.tokens[this.pos]?.value !== "for" &&
1066
- this.tokens[this.pos]?.value !== "else" &&
1067
- this.tokens[this.pos]?.value !== "and" &&
1068
- this.tokens[this.pos]?.value !== "or")
1069
- ) {
1070
- throw new SinthError(
1071
- `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1072
- this.peek().loc,
1073
- );
1074
- }
1075
- }
1076
- }
1077
- }
1078
-
1079
- return children;
1080
- }
1081
-
1082
- // for loops
1083
-
1084
- private parseForLoop(): ForLoop {
1085
- const loc = this.consume(TT.KW_FOR).loc;
1086
- const firstVar = this.consume(TT.IDENT).value;
1087
- let keyVar: string | undefined;
1088
- let itemVar: string;
1089
- let indexVar: string | undefined;
1090
- if (this.check(TT.COMMA)) {
1091
- this.consume(TT.COMMA);
1092
- const secondVar = this.consume(TT.IDENT).value;
1093
- if (this.check(TT.COMMA)) {
1094
- // three variables: key, value, index
1095
- this.consume(TT.COMMA);
1096
- keyVar = firstVar;
1097
- itemVar = secondVar;
1098
- indexVar = this.consume(TT.IDENT).value;
1099
- } else {
1100
- // two variables – tentatively value, index; fix after seeing source type
1101
- itemVar = firstVar;
1102
- indexVar = secondVar;
1103
- }
1104
- } else {
1105
- // one variable: item only
1106
- itemVar = firstVar;
1107
- }
1108
- if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1109
- this.consume(TT.KW_IN);
1110
- const arrayVar = this.consume(TT.IDENT).value;
1111
-
1112
- // If two variables and the source is an object, swap to key, value
1113
- if (keyVar === undefined && indexVar !== undefined) {
1114
- const srcDecl = this._varDecls.find(d => d.name === arrayVar);
1115
- if (srcDecl && srcDecl.varType === "obj") {
1116
- keyVar = itemVar; // first → key
1117
- itemVar = indexVar; // second → value
1118
- indexVar = undefined;
1119
- }
1120
- }
1121
-
1122
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
1123
- this.consume(TT.LBRACE);
1124
- this.loopVar = itemVar;
1125
- const body = this.parseChildList();
1126
- this.loopVar = null;
1127
- this.consume(TT.RBRACE);
1128
-
1129
- return { kind: "for", keyVar, itemVar, indexVar, arrayVar, body, loc };
1130
- }
1131
-
1132
- // component usages
1133
-
1134
- private parseCompUse(): CompUse {
1135
- const loc = this.peek().loc;
1136
- const name = this.consume(TT.IDENT).value;
1137
- const attrs: Attr[] = [];
1138
-
1139
- if (this.check(TT.LPAREN)) {
1140
- this.consume(TT.LPAREN);
1141
- while (!this.check(TT.RPAREN)) {
1142
- const aloc = this.peek().loc;
1143
- const aname = this.consume(TT.IDENT).value;
1144
- let value: Literal | null = null;
1145
- if (this.check(TT.COLON)) {
1146
- this.consume(TT.COLON);
1147
- if (this.isEventAttr(aname)) {
1148
- if (this.check(TT.STRING)) {
1149
- value = this.parseLiteral();
1150
- } else {
1151
- const savedPos = this.pos;
1152
- const expr = this.parseExpression();
1153
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI))) {
1154
- const exprs: Expression[] = [expr];
1155
- while (this.check(TT.OP_SEMI)) {
1156
- this.consume(TT.OP_SEMI);
1157
- const next = this.parseExpression();
1158
- if (next) exprs.push(next);
1159
- else break;
1160
- }
1161
- if (exprs.length === 1) {
1162
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(exprs[0]) };
1163
- } else {
1164
- value = { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(exprs) };
1165
- }
1166
- } else {
1167
- this.pos = savedPos;
1168
- value = this.parseLiteral();
1169
- }
1170
- }
1171
- } else {
1172
- if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
1173
- this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
1174
- this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
1175
- value = this.parseLiteral();
1176
- } else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
1177
- const savedPos = this.pos;
1178
- const expr = this.parseExpression();
1179
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
1180
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
1181
- } else {
1182
- this.pos = savedPos;
1183
- if (this.check(TT.IDENT)) {
1184
- value = { kind: "str", value: this.consume(TT.IDENT).value };
1185
- } else {
1186
- value = this.parseLiteral();
1187
- }
1188
- }
1189
- } else {
1190
- value = this.parseLiteral();
1191
- }
1192
- }
1193
- }
1194
- attrs.push({ name: aname, value, loc: aloc });
1195
- if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
1196
- }
1197
- this.consume(TT.RPAREN);
1198
- }
1199
-
1200
- const children: Child[] = [];
1201
- if (this.check(TT.RAW_BLOCK)) {
1202
- const rawTok = this.consume(TT.RAW_BLOCK);
1203
- const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
1204
- const sub = new Parser(tokens, rawTok.loc.file);
1205
- sub._varDecls = this._varDecls;
1206
- children.push(...sub.parseChildList());
1207
- } else if (this.check(TT.LBRACE)) {
1208
- this.consume(TT.LBRACE);
1209
- children.push(...this.parseChildList());
1210
- this.consume(TT.RBRACE);
1211
- }
1212
-
1213
- return { kind: "use", name, attrs, children, loc };
1214
- }
1215
-
1216
- private isEventAttr(name: string): boolean {
1217
- return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
1218
- }
1219
-
1220
- private parseChildList(): Child[] {
1221
- const children: Child[] = [];
1222
- while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1223
- if (this.check(TT.LPAREN)) {
1224
- const loc = this.peek().loc;
1225
- const expr = this.parseExpression();
1226
- if (expr) {
1227
- children.push({ kind: "expr", expression: expr, loc });
1228
- }
1229
- continue;
1230
- }
1231
- if (this.check(TT.STRING)) {
1232
- const loc = this.peek().loc;
1233
- let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1234
- while (this.check(TT.OP_PLUS)) {
1235
- this.consume(TT.OP_PLUS);
1236
- let rhs: Expression | null = null;
1237
- if (this.check(TT.STRING)) {
1238
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1239
- } else if (this.check(TT.IDENT)) {
1240
- const rhsName = this.consume(TT.IDENT).value;
1241
- if (this.check(TT.DOT)) {
1242
- this.consume(TT.DOT);
1243
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1244
- } else if (this.check(TT.LBRACKET)) {
1245
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1246
- rhs = this.parsePostfix(rhsVar);
1247
- } else {
1248
- rhs = { kind: "variable", name: rhsName };
1249
- }
1250
- } else {
1251
- rhs = this.parseExpression();
1252
- }
1253
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1254
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1255
- }
1256
- children.push({ kind: "expr", expression: leftExpr, loc });
1257
- }
1258
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
1259
- const vd = this.parseVarDeclaration();
1260
- if (vd) this._varDecls.push(vd);
1261
- continue;
1262
- }
1263
- else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); }
1264
- else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); }
1265
- else if (this.check(TT.IDENT)) {
1266
- const loc = this.peek().loc;
1267
- const rawName = this.peek().value;
1268
- const nextType = this.tokens[this.pos + 1]?.type;
1269
-
1270
- if (nextType === TT.DOT) {
1271
- let fullName = this.consume(TT.IDENT).value;
1272
- this.consume(TT.DOT);
1273
- fullName = fullName + "." + this.consume(TT.IDENT).value;
1274
- const afterDotType = this.tokens[this.pos]?.type;
1275
-
1276
- if (afterDotType === TT.OP_PLUS) {
1277
- let leftExpr: Expression = { kind: "variable", name: fullName };
1278
- while (this.check(TT.OP_PLUS)) {
1279
- this.consume(TT.OP_PLUS);
1280
- let rhs: Expression | null = null;
1281
- if (this.check(TT.STRING)) {
1282
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1283
- } else if (this.check(TT.IDENT)) {
1284
- const rhsName = this.consume(TT.IDENT).value;
1285
- if (this.check(TT.DOT)) {
1286
- this.consume(TT.DOT);
1287
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1288
- } else if (this.check(TT.LBRACKET)) {
1289
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1290
- rhs = this.parsePostfix(rhsVar);
1291
- } else {
1292
- rhs = { kind: "variable", name: rhsName };
1293
- }
1294
- } else {
1295
- rhs = this.parseExpression();
1296
- }
1297
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1298
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1299
- }
1300
- children.push({ kind: "expr", expression: leftExpr, loc });
1301
- } else if (this.loopVar && fullName.split('.')[0] === this.loopVar) {
1302
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1303
- } else if (afterDotType === TT.LPAREN || afterDotType === TT.LBRACE || afterDotType === TT.RAW_BLOCK) {
1304
- throw new SinthError(`Unexpected dot notation before component usage`, loc);
1305
- } else {
1306
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1307
- }
1308
- } else if (nextType === TT.OP_PLUS) {
1309
- const name = this.consume(TT.IDENT).value;
1310
- let leftExpr: Expression = { kind: "variable", name };
1311
- while (this.check(TT.OP_PLUS)) {
1312
- this.consume(TT.OP_PLUS);
1313
- let rhs: Expression | null = null;
1314
- if (this.check(TT.STRING)) {
1315
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1316
- } else if (this.check(TT.IDENT)) {
1317
- const rhsName = this.consume(TT.IDENT).value;
1318
- if (this.check(TT.DOT)) {
1319
- this.consume(TT.DOT);
1320
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1321
- } else if (this.check(TT.LBRACKET)) {
1322
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1323
- rhs = this.parsePostfix(rhsVar);
1324
- } else {
1325
- rhs = { kind: "variable", name: rhsName };
1326
- }
1327
- } else {
1328
- rhs = this.parseExpression();
1329
- }
1330
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1331
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1332
- }
1333
- children.push({ kind: "expr", expression: leftExpr, loc });
1334
- } else if (this.loopVar && rawName === this.loopVar) {
1335
- this.consume(TT.IDENT);
1336
- children.push({ kind: "expr", expression: { kind: "variable", name: rawName }, loc });
1337
- } else if (nextType === TT.LBRACKET) {
1338
- const name = this.consume(TT.IDENT).value;
1339
- const varExpr: Expression = { kind: "variable", name };
1340
- let indexedExpr = this.parsePostfix(varExpr);
1341
- // support concatenation: data[prop] + "..."
1342
- if (this.check(TT.OP_PLUS)) {
1343
- let leftExpr: Expression = indexedExpr;
1344
- while (this.check(TT.OP_PLUS)) {
1345
- this.consume(TT.OP_PLUS);
1346
- let rhs: Expression | null = null;
1347
- if (this.check(TT.STRING)) {
1348
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1349
- } else if (this.check(TT.IDENT)) {
1350
- const rhsName = this.consume(TT.IDENT).value;
1351
- if (this.check(TT.DOT)) {
1352
- this.consume(TT.DOT);
1353
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1354
- } else if (this.check(TT.LBRACKET)) {
1355
- const rhsVar: Expression = { kind: "variable", name: rhsName };
1356
- rhs = this.parsePostfix(rhsVar);
1357
- } else {
1358
- rhs = { kind: "variable", name: rhsName };
1359
- }
1360
- } else {
1361
- rhs = this.parseExpression();
1362
- }
1363
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1364
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1365
- }
1366
- children.push({ kind: "expr", expression: leftExpr, loc });
1367
- } else {
1368
- children.push({ kind: "expr", expression: indexedExpr, loc });
1369
- }
1370
- } else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1371
- children.push(this.parseCompUse());
1372
- } else {
1373
- const name = this.consume(TT.IDENT).value;
1374
- children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1375
- }
1376
- }
1377
- else throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1378
- // reject implicit concatenation only after expression children
1379
- if (children.length > 0) {
1380
- const lastChild = children[children.length - 1];
1381
- if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1382
- const nextTT = this.tokens[this.pos]?.type;
1383
- if (
1384
- nextTT === TT.STRING || nextTT === TT.NUMBER ||
1385
- nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1386
- (nextTT === TT.IDENT &&
1387
- this.tokens[this.pos]?.value !== "var" &&
1388
- this.tokens[this.pos]?.value !== "if" &&
1389
- this.tokens[this.pos]?.value !== "for" &&
1390
- this.tokens[this.pos]?.value !== "else" &&
1391
- this.tokens[this.pos]?.value !== "and" &&
1392
- this.tokens[this.pos]?.value !== "or")
1393
- ) {
1394
- throw new SinthError(
1395
- `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1396
- this.peek().loc,
1397
- );
1398
- }
1399
- }
1400
- }
1401
- }
1402
- return children;
1403
- }
1404
-
1405
- // style & script blocks
1406
-
1407
- private parseStyleBlock(): StyleBlock {
1408
- const loc = this.consume(TT.KW_STYLE).loc;
1409
- let global = false, lang: "css" | "scss" = "css", target: string | undefined;
1410
- const extraAttrs: Record<string, string> = {};
1411
-
1412
- while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1413
- if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
1414
- else if (this.check(TT.KW_LANG)) {
1415
- this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
1416
- const lv = this.consume(TT.STRING).value;
1417
- if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
1418
- lang = lv as "css" | "scss";
1419
- }
1420
- else if (this.check(TT.IDENT)) {
1421
- if (this.tokens[this.pos + 1]?.type !== TT.EQUALS) {
1422
- target = this.consume(TT.IDENT).value;
1423
- } else {
1424
- const k = this.consume(TT.IDENT).value;
1425
- this.consume(TT.EQUALS);
1426
- extraAttrs[k] = this.consume(TT.STRING).value;
1427
- }
1428
- }
1429
- else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
1430
- }
1431
-
1432
- return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, target, extraAttrs, loc };
1433
- }
1434
-
1435
- private parseScriptBlock(): ScriptBlock {
1436
- const loc = this.consume(TT.KW_SCRIPT).loc;
1437
- const attrs: Record<string, string> = {};
1438
- while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1439
- const key = this.consume(TT.IDENT).value;
1440
- if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
1441
- else { attrs[key] = "true"; }
1442
- }
1443
- return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
1444
- }
1445
-
1446
- private parseLiteral(): Literal {
1447
- const tok = this.peek();
1448
- if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
1449
- if (this.check(TT.LBRACE)) {
1450
- const obj = this.parseObjectLiteral();
1451
- return { kind: "str", value: JSON.stringify(obj) };
1452
- }
1453
- if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
1454
- if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
1455
- if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
1456
- if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
1457
- if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
1458
- throw new SinthError(`Expected literal value, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
1459
- }
1460
-
1461
- private peek(): Token { return this.tokens[this.pos]; }
1462
- private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
1463
- private consume(t: TT): Token {
1464
- const tok = this.tokens[this.pos];
1465
- if (tok.type !== t) {
1466
- throw new SinthError(
1467
- `Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
1468
- tok.loc,
1469
- );
1470
- }
1471
- this.pos++;
1472
- return tok;
1473
- }
1474
- }
1475
-
1476
- // import resolver
1477
-
1478
- interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
1479
-
1480
- interface ResolvedImports {
1481
- allDefs: Map<string, CompDef>;
1482
- customEls: Map<string, CustomElInfo>;
1483
- cssLinks: string[];
1484
- jsLinks: { src: string; attrs: Record<string, string> }[];
1485
- }
1486
-
1487
- const IMPORT_STACK: string[] = [];
1488
-
1489
- function parseFile(filePath: string): SinthFile {
1490
- if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
1491
- const src = fs.readFileSync(filePath, "utf-8");
1492
- const srcLines = src.split("\n");
1493
- try {
1494
- const tokens = new Lexer(src, filePath).tokenize();
1495
- return new Parser(tokens, filePath).parse();
1496
- } catch (e) {
1497
- if (e instanceof SinthError) throw e.withSource(srcLines);
1498
- throw e;
1499
- }
1500
- }
1501
-
1502
- function resolveImports(
1503
- file: SinthFile,
1504
- cfg: ResolverConfig,
1505
- visited: Set<string> = new Set(),
1506
- ): ResolvedImports {
1507
- const allDefs = new Map<string, CompDef>();
1508
- const customEls = new Map<string, CustomElInfo>();
1509
- const cssLinks: string[] = [];
1510
- const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
1511
-
1512
- for (const def of file.defs) {
1513
- if (BUILTIN_MAP[def.name]) {
1514
- throw new SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
1515
- }
1516
- if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
1517
- allDefs.set(def.name, def);
1518
- }
1519
-
1520
- for (const el of file.customEls) {
1521
- customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
1522
- }
1523
-
1524
- if (!file.isPage && file.meta.length > 0) {
1525
- for (const m of file.meta) {
1526
- SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
1527
- }
1528
- }
1529
-
1530
- for (const imp of file.imports) {
1531
- if (imp.kind === "css") {
1532
- const r = resolveRelative(imp.path, file.filePath);
1533
- if (!cssLinks.includes(r)) cssLinks.push(r);
1534
-
1535
- } else if (imp.kind === "js") {
1536
- const src = resolveLibrary(imp.name, cfg);
1537
- jsLinks.push({ src, attrs: {} });
1538
-
1539
- for (const libDir of cfg.libraryPaths) {
1540
- const companion = path.join(libDir, imp.name + ".sinth");
1541
- if (fs.existsSync(companion) && !visited.has(companion)) {
1542
- visited.add(companion);
1543
- IMPORT_STACK.push(companion);
1544
- const sub = resolveImports(parseFile(companion), cfg, visited);
1545
- IMPORT_STACK.pop();
1546
- for (const [n, d] of sub.allDefs) allDefs.set(n, d);
1547
- for (const [n, e] of sub.customEls) customEls.set(n, e);
1548
- }
1549
- }
1550
-
1551
- } else if (imp.kind === "sinth") {
1552
- const resolved = resolveSinthPath(imp.path, file.filePath, cfg);
1553
-
1554
- if (IMPORT_STACK.includes(resolved)) {
1555
- throw new SinthError(
1556
- `Circular import: ${[...IMPORT_STACK, resolved].join(" → ")}`
1557
- );
1558
- }
1559
- if (visited.has(resolved)) continue;
1560
- visited.add(resolved);
1561
-
1562
- IMPORT_STACK.push(resolved);
1563
- const imported = parseFile(resolved);
1564
- IMPORT_STACK.pop();
1565
-
1566
- const sub = resolveImports(imported, cfg, visited);
1567
- for (const [name, def] of sub.allDefs) {
1568
- if (allDefs.has(name)) throw new SinthError(`Component '${name}' defined in multiple imported files.`);
1569
- allDefs.set(name, def);
1570
- }
1571
- for (const [n, e] of sub.customEls) customEls.set(n, e);
1572
- for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
1573
- for (const j of sub.jsLinks) jsLinks.push(j);
1574
- }
1575
- }
1576
-
1577
- return { allDefs, customEls, cssLinks, jsLinks };
1578
- }
1579
-
1580
- function resolveRelative(p: string, fromFile: string): string {
1581
- if (p.startsWith("./") || p.startsWith("../")) return path.resolve(path.dirname(fromFile), p);
1582
- return p;
1583
- }
1584
-
1585
- function resolveLibrary(name: string, cfg: ResolverConfig): string {
1586
- const base = name.endsWith(".js") ? name : name + ".js";
1587
- for (const libDir of cfg.libraryPaths) {
1588
- const c = path.join(libDir, base);
1589
- if (fs.existsSync(c)) return c;
1590
- }
1591
- return `/libraries/${base}`;
1592
- }
1593
-
1594
- function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
1595
- if (p.startsWith("./") || p.startsWith("../")) {
1596
- const r = path.resolve(path.dirname(fromFile), p);
1597
- if (fs.existsSync(r)) return r;
1598
- const w = r.endsWith(".sinth") ? "" : r + ".sinth";
1599
- if (w && fs.existsSync(w)) return w;
1600
- throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
1601
- }
1602
-
1603
- const relToFile = path.resolve(path.dirname(fromFile), p);
1604
- if (fs.existsSync(relToFile)) return relToFile;
1605
- const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
1606
- if (fs.existsSync(relToFileExt)) return relToFileExt;
1607
-
1608
- for (const libDir of cfg.libraryPaths) {
1609
- const c1 = path.join(libDir, p);
1610
- if (fs.existsSync(c1)) return c1;
1611
- const c2 = c1.endsWith(".sinth") ? c1 : c1 + ".sinth";
1612
- if (fs.existsSync(c2)) return c2;
1613
- }
1614
-
1615
- throw new SinthError(
1616
- `Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`
1617
- );
1618
- }
1619
-
1620
- // built-in component map
1621
-
1622
- interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
1623
-
1624
- const BUILTIN_MAP: Record<string, BuiltinInfo> = {
1625
- // structural
1626
- Main: { tag: "main" },
1627
- Header: { tag: "header" },
1628
- Footer: { tag: "footer" },
1629
- Nav: { tag: "nav" },
1630
- Section: { tag: "section" },
1631
- Article: { tag: "article" },
1632
- Aside: { tag: "aside" },
1633
- Div: { tag: "div" },
1634
- Span: { tag: "span" },
1635
- Hero: { tag: "section", defaultClass: "hero" },
1636
- Container: { tag: "div", defaultClass: "container" },
1637
- Grid: { tag: "div", defaultClass: "grid" },
1638
- Flex: { tag: "div", defaultClass: "flex" },
1639
- Stack: { tag: "div", defaultClass: "stack" },
1640
- Row: { tag: "div", defaultClass: "row" },
1641
- Column: { tag: "div", defaultClass: "col" },
1642
- CardGrid: { tag: "div", defaultClass: "card-grid" },
1643
- // typography
1644
- Heading: { tag: "h1" },
1645
- SubHeading: { tag: "p", defaultClass: "subheading" },
1646
- Paragraph: { tag: "p" },
1647
- Lead: { tag: "p", defaultClass: "lead" },
1648
- Small: { tag: "small" },
1649
- Strong: { tag: "strong" },
1650
- Em: { tag: "em" },
1651
- Code: { tag: "code" },
1652
- Pre: { tag: "pre" },
1653
- Blockquote: { tag: "blockquote" },
1654
- Mark: { tag: "mark" },
1655
- Label: { tag: "label" },
1656
- Abbr: { tag: "abbr" },
1657
- Del: { tag: "del" },
1658
- Ins: { tag: "ins" },
1659
- Sub: { tag: "sub" },
1660
- Sup: { tag: "sup" },
1661
- Data: { tag: "data" },
1662
- Time: { tag: "time" },
1663
- Bdi: { tag: "bdi" },
1664
- Bdo: { tag: "bdo" },
1665
- Cite: { tag: "cite" },
1666
- Dfn: { tag: "dfn" },
1667
- Kbd: { tag: "kbd" },
1668
- Samp: { tag: "samp" },
1669
- Var: { tag: "var" },
1670
- Address: { tag: "address" },
1671
- Ruby: { tag: "ruby" },
1672
- Rt: { tag: "rt" },
1673
- Rp: { tag: "rp" },
1674
- // interactive
1675
- Button: { tag: "button" },
1676
- Link: { tag: "a" },
1677
- NavLink: { tag: "a" },
1678
- Select: { tag: "select" },
1679
- Form: { tag: "form" },
1680
- Fieldset: { tag: "fieldset" },
1681
- Legend: { tag: "legend" },
1682
- Details: { tag: "details" },
1683
- Summary: { tag: "summary" },
1684
- Dialog: { tag: "dialog" },
1685
- Textarea: { tag: "textarea" },
1686
- Datalist: { tag: "datalist" },
1687
- Optgroup: { tag: "optgroup" },
1688
- Option: { tag: "option" },
1689
- Progress: { tag: "progress" },
1690
- Meter: { tag: "meter" },
1691
- Output: { tag: "output" },
1692
- Map: { tag: "map" },
1693
- // media
1694
- Picture: { tag: "picture" },
1695
- Video: { tag: "video" },
1696
- Audio: { tag: "audio" },
1697
- Figure: { tag: "figure" },
1698
- Figcaption: { tag: "figcaption" },
1699
- Canvas: { tag: "canvas" },
1700
- Svg: { tag: "svg" },
1701
- IFrame: { tag: "iframe" },
1702
- Object: { tag: "object" },
1703
- // void elements
1704
- Img: { tag: "img", voidEl: true },
1705
- Logo: { tag: "img", voidEl: true },
1706
- Input: { tag: "input", voidEl: true },
1707
- Checkbox: { tag: "input", voidEl: true },
1708
- Hr: { tag: "hr", voidEl: true },
1709
- Br: { tag: "br", voidEl: true },
1710
- Wbr: { tag: "wbr", voidEl: true },
1711
- Source: { tag: "source", voidEl: true },
1712
- Embed: { tag: "embed", voidEl: true },
1713
- Col: { tag: "col", voidEl: true },
1714
- Area: { tag: "area", voidEl: true },
1715
- // lists
1716
- Ul: { tag: "ul" }, Ol: { tag: "ol" }, Li: { tag: "li" },
1717
- Dl: { tag: "dl" }, Dt: { tag: "dt" }, Dd: { tag: "dd" },
1718
- // tables
1719
- Table: { tag: "table" },
1720
- Caption: { tag: "caption" },
1721
- Thead: { tag: "thead" },
1722
- Tbody: { tag: "tbody" },
1723
- Tfoot: { tag: "tfoot" },
1724
- Tr: { tag: "tr" },
1725
- Th: { tag: "th" },
1726
- Td: { tag: "td" },
1727
- Colgroup: { tag: "colgroup" },
1728
- // utility
1729
- Template: { tag: "template" },
1730
- Slot: { tag: "slot" },
1731
- NoScript: { tag: "noscript" },
1732
- RawHTML: { tag: "__RAW__" },
1733
- };
1734
-
1735
- const VOID_TAGS = new Set([
1736
- "area","base","br","col","embed","hr","img","input",
1737
- "link","meta","param","source","track","wbr",
1738
- ]);
1739
-
1740
- const EVENT_RE = /^on[A-Z]/;
1741
- function eventAttrName(name: string): string | null {
1742
- return EVENT_RE.test(name) ? name.toLowerCase() : null;
1743
- }
1744
-
1745
- // preprocessor
1746
-
1747
- /**
1748
- * for who's reading this: This maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
1749
- * these are used inside component style blocks, for example: onHover { color: "blue" }
1750
- */
1751
- const SINTH_PSEUDO_CLASS: Record<string, string> = {
1752
- onHover: ":hover",
1753
- onFocus: ":focus",
1754
- onActive: ":active",
1755
- onVisited: ":visited",
1756
- onChecked: ":checked",
1757
- onDisabled: ":disabled",
1758
- onEnabled: ":enabled",
1759
- onRequired: ":required",
1760
- onOptional: ":optional",
1761
- onValid: ":valid",
1762
- onInvalid: ":invalid",
1763
- onPlaceholderShown:":placeholder-shown",
1764
- onFocusWithin: ":focus-within",
1765
- onFocusVisible: ":focus-visible",
1766
- onFirst: ":first-child",
1767
- onLast: ":last-child",
1768
- onFirstOfType: ":first-of-type",
1769
- onLastOfType: ":last-of-type",
1770
- onEmpty: ":empty",
1771
- onTarget: ":target",
1772
- onLink: ":link",
1773
- };
1774
-
1775
- const SINTH_PSEUDO_ELEMENT: Record<string, string> = {
1776
- before: "::before",
1777
- after: "::after",
1778
- placeholder: "::placeholder",
1779
- selection: "::selection",
1780
- firstLine: "::first-line",
1781
- firstLetter: "::first-letter",
1782
- marker: "::marker",
1783
- backdrop: "::backdrop",
1784
- };
1785
-
1786
- function sinthCompToSelector(name: string): string {
1787
- const info = BUILTIN_MAP[name];
1788
- if (!info) return name.toLowerCase();
1789
- if (info.defaultClass) {
1790
- const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
1791
- return `${info.tag}${classes}`;
1792
- }
1793
- return info.tag;
1794
- }
1795
-
1796
- /**
1797
- * supported conversions:
1798
- * - component names as selectors: `Paragraph { ... }` → `p { ... }`
1799
- * - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
1800
- * - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
1801
- * - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
1802
- * - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
1803
- */
1804
- function preprocessSinthStyle(raw: string): string {
1805
- const lines = raw.split("\n");
1806
- const result: string[] = [];
1807
-
1808
- for (const line of lines) {
1809
- const trimmed = line.trim();
1810
- const indent = line.match(/^(\s*)/)?.[1] ?? "";
1811
-
1812
- if (!trimmed) { result.push(line); continue; }
1813
-
1814
- if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) { continue; }
1815
- // Standard comments pass through
1816
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
1817
- result.push(line); continue;
1818
- }
1819
-
1820
- const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
1821
- if (mediaMatch) {
1822
- const params = parseSinthMediaParams(mediaMatch[1]);
1823
- result.push(`${indent}@media (${params}) {`);
1824
- continue;
1825
- }
1826
-
1827
- const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
1828
- if (blockMatch) {
1829
- const keyword = blockMatch[1];
1830
-
1831
- const pseudoCls = SINTH_PSEUDO_CLASS[keyword];
1832
- if (pseudoCls) {
1833
- result.push(`${indent}&${pseudoCls} {`);
1834
- continue;
1835
- }
1836
-
1837
- const pseudoEl = SINTH_PSEUDO_ELEMENT[keyword];
1838
- if (pseudoEl) {
1839
- result.push(`${indent}&${pseudoEl} {`);
1840
- continue;
1841
- }
1842
-
1843
- if (/^[A-Z]/.test(keyword) && BUILTIN_MAP[keyword]) {
1844
- result.push(`${indent}${sinthCompToSelector(keyword)} {`);
1845
- continue;
1846
- }
1847
- }
1848
-
1849
- const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
1850
- if (varPropMatch) {
1851
- result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
1852
- continue;
1853
- }
1854
-
1855
- result.push(line);
1856
- }
1857
-
1858
- return result.join("\n");
1859
- }
1860
-
1861
- function parseSinthMediaParams(params: string): string {
1862
- const parts = params.split(",").map(p => {
1863
- const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
1864
- if (!m) return p.trim();
1865
- return `${camelToKebab(m[1])}: ${m[2].trim()}`;
1866
- });
1867
- return parts.join(") and (");
1868
- }
1869
-
1870
- // style processor
1871
-
1872
-
1873
- function convertCSSProps(css: string): string {
1874
- return css.split("\n").map(line => {
1875
- const trimmed = line.trim();
1876
- if (!trimmed) return line;
1877
- if (trimmed === "}" || trimmed.startsWith("}")) return line;
1878
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) return line;
1879
- if (trimmed.startsWith("@")) return line;
1880
- if (trimmed.includes("{")) return line;
1881
-
1882
- const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
1883
- if (!m) return line;
1884
-
1885
- const [, indent, rawProp, , rawVal] = m;
1886
-
1887
- const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
1888
- const hasQuotedVal = /^["']/.test(rawVal.trim());
1889
- if (!hasCamelCase && !hasQuotedVal) return line;
1890
-
1891
- let val = rawVal.trim();
1892
- if (val.endsWith(";")) val = val.slice(0, -1).trimEnd();
1893
- if ((val.startsWith('"') && val.endsWith('"')) ||
1894
- (val.startsWith("'") && val.endsWith("'"))) {
1895
- val = val.slice(1, -1);
1896
- }
1897
-
1898
- return `${indent}${camelToKebab(rawProp)}: ${val};`;
1899
- }).join("\n");
1900
- }
1901
-
1902
- function processStyleBlock(
1903
- block: StyleBlock,
1904
- hash: string,
1905
- params: Map<string, string> = new Map(),
1906
- ): string {
1907
- let raw = block.raw;
1908
-
1909
- // 1. interpolate {param} placeholders
1910
- if (params.size > 0) raw = interpolateAttr(raw, params);
1911
-
1912
- // 2. sinth style preprocessing
1913
- raw = preprocessSinthStyle(raw);
1914
-
1915
- // 3. warn if & in plain CSS
1916
- if (block.lang === "css" && raw.includes("&")) {
1917
- SinthWarning.emit(
1918
- `'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`,
1919
- block.loc,
1920
- );
1921
- }
1922
-
1923
- // 4. camelCase → kebab-case
1924
- let css = convertCSSProps(raw);
1925
-
1926
- // 5. SCSS compilation
1927
- if (block.lang === "scss") {
1928
- try {
1929
- // eslint-disable-next-line @typescript-eslint/no-require-imports
1930
- const sass: { compileString: (src: string) => { css: string } } = require("sass");
1931
- css = sass.compileString(css).css;
1932
- } catch (e: unknown) {
1933
- const err = e as { code?: string; message?: string };
1934
- if (err.code === "MODULE_NOT_FOUND" || err.message?.includes("Cannot find module")) {
1935
- throw new SinthError("SCSS requires the 'sass' package. Install with: npm install sass");
1936
- }
1937
- throw new SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
1938
- }
1939
- }
1940
-
1941
- // 6. if target component given, wrap content in its CSS selector
1942
- if (block.target) {
1943
- const selector = sinthCompToSelector(block.target);
1944
- css = `${selector} {\n${css}\n}`;
1945
- }
1946
-
1947
- // 7. scope (except it's global)
1948
- if (!block.global) css = scopeCSS(css, hash);
1949
-
1950
- return css;
1951
- }
1952
-
1953
- function scopeCSS(css: string, hash: string): string {
1954
- return processRules(css, `[data-s="${hash}"]`);
1955
- }
1956
-
1957
- function processRules(css: string, attr: string): string {
1958
- let out = "", i = 0;
1959
-
1960
- while (i < css.length) {
1961
- if (/\s/.test(css[i])) { out += css[i++]; continue; }
1962
-
1963
- if (css[i] === "/" && css[i + 1] === "*") {
1964
- const end = css.indexOf("*/", i + 2);
1965
- if (end === -1) { out += css.substring(i); break; }
1966
- out += css.substring(i, end + 2);
1967
- i = end + 2;
1968
- continue;
1969
- }
1970
-
1971
- const braceIdx = findCSSBrace(css, i);
1972
- if (braceIdx === -1) { out += css.substring(i); break; }
1973
-
1974
- const selector = css.substring(i, braceIdx).trim();
1975
- const { content, end } = extractCSSBlock(css, braceIdx);
1976
-
1977
- if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
1978
- out += `${selector} {${content}}\n`;
1979
- } else if (/^@(media|supports|layer|container)/.test(selector)) {
1980
- out += `${selector} {\n${processRules(content, attr)}\n}\n`;
1981
- } else if (selector.startsWith("@")) {
1982
- out += `${selector} {${content}}\n`;
1983
- } else if (selector.length > 0) {
1984
- out += `${scopeSelectors(selector, attr)} {${content}}\n`;
1985
- }
1986
-
1987
- i = end;
1988
- }
1989
- return out;
1990
- }
1991
-
1992
- function scopeSelectors(selList: string, attr: string): string {
1993
- return selList
1994
- .split(",")
1995
- .map(s => {
1996
- s = s.trim();
1997
- if (!s) return "";
1998
- if (/^(html|body|:root)(\s|$|{|,)/.test(s)) return s;
1999
- const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
2000
- if (m && m[1].trim()) {
2001
- return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
2002
- }
2003
- return `${attr} ${s}, ${s}${attr}`;
2004
- })
2005
- .filter(Boolean)
2006
- .join(",\n");
2007
- }
2008
-
2009
- function findCSSBrace(css: string, from: number): number {
2010
- let i = from;
2011
- while (i < css.length) {
2012
- if (css[i] === '"' || css[i] === "'") {
2013
- const q = css[i++];
2014
- while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
2015
- i++;
2016
- } else if (css[i] === "{") {
2017
- return i;
2018
- } else { i++; }
2019
- }
2020
- return -1;
2021
- }
2022
-
2023
- function extractCSSBlock(css: string, openBrace: number): { content: string; end: number } {
2024
- let i = openBrace + 1, depth = 1;
2025
- while (i < css.length && depth > 0) {
2026
- if (css[i] === '"' || css[i] === "'") {
2027
- const q = css[i++];
2028
- while (i < css.length && css[i] !== q) { if (css[i] === "\\") i++; i++; }
2029
- i++;
2030
- } else if (css[i] === "/" && css[i + 1] === "*") {
2031
- i += 2;
2032
- while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/")) i++;
2033
- i += 2;
2034
- } else if (css[i] === "{") { depth++; i++; }
2035
- else if (css[i] === "}") { depth--; if (depth > 0) i++; else break; }
2036
- else { i++; }
2037
- }
2038
- return { content: css.substring(openBrace + 1, i), end: i + 1 };
2039
- }
2040
-
2041
-
2042
- // expression -> js compiler
2043
-
2044
- function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
2045
- switch (expr.kind) {
2046
- case "literal":
2047
- if (!expr.value) return "null";
2048
- if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
2049
- if (expr.value.kind === "num") return String((expr.value as LitNum).value);
2050
- if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
2051
- return "null";
2052
- case "variable":
2053
- if (loopVars && expr.name && loopVars.has(expr.name)) {
2054
- return `_ctx.${expr.name}`;
2055
- }
2056
- return expr.name ?? "undefined";
2057
- case "binary": {
2058
- const l = compileExprToJS(expr.left!, loopVars);
2059
- const r = compileExprToJS(expr.right!, loopVars);
2060
- const o = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op!;
2061
- return `(${l} ${o} ${r})`;
2062
- }
2063
- case "unary": {
2064
- const o = expr.op === "not" ? "!" : expr.op!;
2065
- return `${o}(${compileExprToJS(expr.operand!, loopVars)})`;
2066
- }
2067
- case "assign": {
2068
- const v = expr.right ? compileExprToJS(expr.right, loopVars) : "null";
2069
- return `${expr.target} ${expr.op} ${v}`;
2070
- }
2071
- case "index":
2072
- return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
2073
- case "postfix":
2074
- return `${expr.target}${expr.op}`;
2075
- default:
2076
- return "";
2077
- }
2078
- }
2079
-
2080
- function compileIfToJS(ifBlock: IfBlock): string {
2081
- const cond = compileExprToJS(ifBlock.condition);
2082
- const ifJS = bodyToJS(ifBlock.body);
2083
- const elseJS = ifBlock.elseBody ? bodyToJS(ifBlock.elseBody) : "";
2084
- let js = `if (${cond}) {\n${ifJS}}\n`;
2085
- if (elseJS) js += `else {\n${elseJS}}\n`;
2086
- return js;
2087
- }
2088
-
2089
- function bodyToJS(children: Child[]): string {
2090
- return children
2091
- .filter(c => c.kind === "assign_stmt" || c.kind === "if")
2092
- .map(c => {
2093
- if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
2094
- if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
2095
- return "";
2096
- })
2097
- .join("");
2098
- }
2099
-
2100
- // the HTML generator
2101
-
2102
- /**
2103
- * CSS property names that are allowed as inline style shorthand attributes on
2104
- * any Sinth component: Paragraph(color: "red", fontSize: "1.2rem") { "Hi" }
2105
- */
2106
- const INLINE_STYLE_PROPS = new Set([
2107
- "color","backgroundColor","backgroundImage","backgroundSize","backgroundPosition",
2108
- "fontSize","fontWeight","fontFamily","fontStyle","fontVariant","lineHeight","letterSpacing","textAlign",
2109
- "textDecoration","textTransform","whiteSpace","wordBreak","wordWrap","textOverflow",
2110
- "margin","marginTop","marginBottom","marginLeft","marginRight",
2111
- "padding","paddingTop","paddingBottom","paddingLeft","paddingRight",
2112
- "width","height","minWidth","maxWidth","minHeight","maxHeight",
2113
- "display","flexDirection","flexWrap","flex","flexGrow","flexShrink","flexBasis",
2114
- "justifyContent","alignItems","alignContent","alignSelf","gap","rowGap","columnGap",
2115
- "gridTemplateColumns","gridTemplateRows","gridColumn","gridRow","gridArea",
2116
- "position","top","right","bottom","left","zIndex",
2117
- "border","borderTop","borderBottom","borderLeft","borderRight",
2118
- "borderWidth","borderStyle","borderColor","borderRadius",
2119
- "outline","outlineWidth","outlineStyle","outlineColor","outlineOffset",
2120
- "boxShadow","textShadow","opacity","visibility",
2121
- "overflow","overflowX","overflowY","objectFit","objectPosition",
2122
- "cursor","userSelect","pointerEvents","resize",
2123
- "transform","transition","animation","animationDuration","animationDelay",
2124
- "listStyle","listStyleType","listStylePosition",
2125
- "verticalAlign","float","clear",
2126
- "content","quotes",
2127
- ]);
2128
-
2129
- function resolveBuiltinTag(
2130
- name: string,
2131
- attrs: Attr[],
2132
- ): { tag: string; defaultClass?: string; voidEl: boolean } {
2133
- if (name === "Heading") {
2134
- const la = attrs.find(a => a.name === "level");
2135
- const lv = la?.value?.kind === "num" ? Math.min(6, Math.max(1, la.value.value)) : 1;
2136
- if (!la) SinthWarning.emit(`Heading used without 'level' attribute, defaulting to h1`);
2137
- return { tag: `h${lv}`, voidEl: false };
2138
- }
2139
- const info = BUILTIN_MAP[name];
2140
- if (info) return { tag: info.tag, defaultClass: info.defaultClass, voidEl: info.voidEl ?? false };
2141
- SinthWarning.emit(`Unknown component '${name}', treating as <${name.toLowerCase()}>`);
2142
- return { tag: name.toLowerCase(), voidEl: false };
2143
- }
2144
-
2145
- function registerExpr(ctx: CompileCtx, expr: Expression): number {
2146
- const jsExpr = compileExprToJS(expr, ctx.loopVars);
2147
- const existing = ctx.exprMap.get(jsExpr);
2148
- if (existing !== undefined) return existing;
2149
- const id = ctx.exprRegistry.length;
2150
- ctx.exprRegistry.push(jsExpr);
2151
- ctx.exprMap.set(jsExpr, id);
2152
- return id;
2153
- }
2154
-
2155
-
2156
- function renderAttr(attr: Attr, paramMap: Map<string, string>, ctx?: CompileCtx): string {
2157
- const { name, value } = attr;
2158
- if (value === null) return name;
2159
- if (value.kind === "null") return "";
2160
- if (value.kind === "bool") return value.value ? name : "";
2161
-
2162
- if (name === "model" && value?.kind === "str") {
2163
- const vName = interpolateAttr(value.value, paramMap);
2164
- return `oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)" value="${escAttr(vName)}"`;
2165
- }
2166
-
2167
-
2168
-
2169
- if (name === "delay") {
2170
- if (value.kind === "num") {
2171
- return `data-sinth-delay="${value.value}" style="display:none"`;
2172
- }
2173
- const v = litToString(value);
2174
- if (/^\d+$/.test(v)) return `data-sinth-delay="${escAttr(v)}" style="display:none"`;
2175
- if (v.startsWith("__EXPR__")) {
2176
- try {
2177
- const expr: Expression = JSON.parse(v.substring(8));
2178
- const id = registerExpr(ctx, expr);
2179
- return `data-sinth-delay-expr-id="${id}" style="display:none"`;
2180
- } catch {}
2181
- }
2182
- // plain variable name – register as expression
2183
- const id = registerExpr(ctx, { kind: "variable", name: v });
2184
- return `data-sinth-delay-expr-id="${id}" style="display:none"`;
2185
- }
2186
-
2187
- if (name === "checked") {
2188
- return (value as any)?.kind === "bool" && (value as any).value ? "checked" : "";
2189
- }
2190
-
2191
- if (value.kind === "num") return `${name}="${value.value}"`;
2192
-
2193
- let raw = value.value;
2194
-
2195
- if (raw.startsWith("__MULTI_EXPR__")) {
2196
- const exprJson = raw.substring("__MULTI_EXPR__".length);
2197
- try {
2198
- const exprs: Expression[] = JSON.parse(exprJson);
2199
- const jsExprs = exprs.map(e => compileExprToJS(e)).join("; ");
2200
- const ev = eventAttrName(name);
2201
- if (ev) return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2202
- return `${name}="${escAttr(jsExprs)}"`;
2203
- } catch { }
2204
- }
2205
- if (raw.startsWith("__EXPR__")) {
2206
- const exprJson = raw.substring("__EXPR__".length);
2207
- try {
2208
- const expr: Expression = JSON.parse(exprJson);
2209
- const jsExpr = compileExprToJS(expr);
2210
- const ev = eventAttrName(name);
2211
- if (ev) return `${ev}="(function(){ ${jsExpr.replace(/"/g, "&quot;")}; sinthRender(); })()"`;
2212
- return `${name}="${escAttr(jsExpr)}"`;
2213
- } catch { }
2214
- }
2215
-
2216
- raw = interpolateAttr(raw, paramMap);
2217
-
2218
- const ev = eventAttrName(name);
2219
- if (ev) {
2220
- const call = raw.includes("(") ? raw : raw + "()";
2221
- return `${ev}="${escAttr(call)};sinthRender()"`;
2222
- }
2223
- return `${name}="${escAttr(raw)}"`;
2224
- }
2225
-
2226
- function renderText(text: string, params: Map<string, string>): string {
2227
- const rawSlots = new Map<string, string>();
2228
- let counter = 0;
2229
-
2230
- let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
2231
-
2232
- s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
2233
- const val = params.get(n);
2234
- if (val === undefined) return `$${n}`;
2235
- if (n === "slot") {
2236
- const ph = `\x00RAW${counter++}\x00`;
2237
- rawSlots.set(ph, val);
2238
- return ph;
2239
- }
2240
- return val;
2241
- });
2242
-
2243
- s = esc(s);
2244
-
2245
- for (const [ph, val] of rawSlots) s = s.replace(ph, val);
2246
- s = s.replace(/\x00DOLLAR\x00/g, "$");
2247
-
2248
- const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
2249
- let m: RegExpExecArray | null;
2250
- while ((m = braceRe.exec(s)) !== null) {
2251
- SinthWarning.emit(
2252
- `Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
2253
- );
2254
- }
2255
-
2256
- return s;
2257
- }
2258
-
2259
- function interpolateAttr(text: string, params: Map<string, string>): string {
2260
- let s = text.replace(/\\\{/g, "\x00LB\x00");
2261
- s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
2262
- return s.replace(/\x00LB\x00/g, "{");
2263
- }
2264
-
2265
-
2266
- function renderChild(
2267
- child: Child,
2268
- ctx: CompileCtx,
2269
- params: Map<string, string>,
2270
- depth: number,
2271
- ): string {
2272
- if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
2273
-
2274
- switch (child.kind) {
2275
- case "text":
2276
- return renderText(child.value, params);
2277
-
2278
- case "expr": {
2279
- if (child.expression.kind === "literal" && child.expression.value) {
2280
- return esc(litToString(child.expression.value));
2281
- }
2282
- if (child.expression.kind === "variable" && child.expression.name && !ctx.loopVars?.has(child.expression.name)) {
2283
- const exprId = registerExpr(ctx, child.expression);
2284
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
2285
- }
2286
- const exprId = registerExpr(ctx, child.expression);
2287
- return `<span class="sinth-expr" data-expr-id="${exprId}"></span>`;
2288
- }
2289
-
2290
- case "assign_stmt": {
2291
- ctx.logicBlocks.push(compileExprToJS(child.expression) + ";");
2292
- return "";
2293
- }
2294
-
2295
- case "remove": {
2296
- return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
2297
- }
2298
-
2299
- case "if":
2300
- return renderIfBlock(child, ctx, params, depth);
2301
-
2302
- case "for": {
2303
- // collect loop‑variable names
2304
- const loopVars = new Set<string>();
2305
- loopVars.add(child.itemVar);
2306
- if (child.keyVar) loopVars.add(child.keyVar);
2307
- if (child.indexVar) loopVars.add(child.indexVar);
2308
- // set them on ctx for compilation of the body
2309
- const prev = ctx.loopVars;
2310
- ctx.loopVars = loopVars;
2311
- const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2312
- ctx.loopVars = prev; // restore
2313
- const keyAttr = child.keyVar ? ` data-sinth-key="${escAttr(child.keyVar)}"` : "";
2314
- const idxAttr = child.indexVar ? ` data-sinth-index="${escAttr(child.indexVar)}"` : "";
2315
- return (
2316
- `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}"${keyAttr}${idxAttr}>${bodyHTML}</template>`
2317
- );
2318
- }
2319
-
2320
- case "use":
2321
- return renderCompUse(child, ctx, params, depth);
2322
- }
2323
- }
2324
-
2325
- function renderIfBlock(
2326
- ifBlock: IfBlock,
2327
- ctx: CompileCtx,
2328
- params: Map<string, string>,
2329
- depth: number,
2330
- ): string {
2331
- if (depth > 64) throw new SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
2332
-
2333
- const condJS = compileExprToJS(ifBlock.condition);
2334
- const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
2335
- const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
2336
- const hasComp = allChildren.some(c => c.kind === "use");
2337
-
2338
- // pure logic
2339
- if (hasAssign && !hasComp) {
2340
- ctx.logicBlocks.push(compileIfToJS(ifBlock));
2341
- return "";
2342
- }
2343
-
2344
- // pure DOM
2345
- if (!hasAssign && hasComp) {
2346
- const tplId = ctx.ifIdCounter++;
2347
- const condId = registerExpr(ctx, ifBlock.condition);
2348
- const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2349
- const elseHTML = (ifBlock.elseBody ?? []).map(c => renderChild(c, ctx, params, depth + 1)).join("");
2350
- let replaceAttr = "";
2351
- const firstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
2352
- if (firstComp) {
2353
- const idAttr = firstComp.attrs.find(a => a.name === "id");
2354
- const replAttr = firstComp.attrs.find(a => a.name === "replace");
2355
- const wantsReplace = replAttr && (replAttr.value === null || (replAttr.value?.kind === "bool" && replAttr.value.value));
2356
- if (idAttr && idAttr.value?.kind === "str" && wantsReplace) {
2357
- replaceAttr = ` data-sinth-if-replace="${escAttr(idAttr.value.value)}"`;
2358
- }
2359
- }
2360
- return (
2361
- `<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${replaceAttr}>${bodyHTML}</template>` +
2362
- (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : "")
2363
- );
2364
- }
2365
-
2366
- // mixed
2367
- const id = `__sm${ctx.mixedCounter++}__`;
2368
-
2369
- const ifAssignJS = ifBlock.body
2370
- .filter(c => c.kind === "assign_stmt")
2371
- .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
2372
- .join("\n");
2373
-
2374
- const ifHTML = ifBlock.body
2375
- .filter(c => c.kind !== "assign_stmt")
2376
- .map(c => renderChild(c, ctx, params, depth + 1))
2377
- .join("");
2378
-
2379
- const elseAssignJS = (ifBlock.elseBody ?? [])
2380
- .filter(c => c.kind === "assign_stmt")
2381
- .map(c => ` ${compileExprToJS((c as AssignStmt).expression)};`)
2382
- .join("\n");
2383
-
2384
- const elseHTML = (ifBlock.elseBody ?? [])
2385
- .filter(c => c.kind !== "assign_stmt")
2386
- .map(c => renderChild(c, ctx, params, depth + 1))
2387
- .join("");
2388
-
2389
- let replaceId: string | undefined;
2390
- const ifFirstComp = ifBlock.body.find(c => c.kind === "use") as CompUse | undefined;
2391
- const elseFirstComp = (ifBlock.elseBody ?? []).find(c => c.kind === "use") as CompUse | undefined;
2392
- if (ifFirstComp) {
2393
- const ifId = ifFirstComp.attrs.find(a => a.name === "id")?.value;
2394
- const ifReplace = ifFirstComp.attrs.find(a => a.name === "replace");
2395
- const ifReplaceVal = ifReplace?.value;
2396
- const ifWantsReplace = ifReplace && (ifReplaceVal === null || (ifReplaceVal?.kind === "bool" && ifReplaceVal.value));
2397
-
2398
- if (ifId && ifId.kind === "str" && ifWantsReplace) {
2399
- if (elseFirstComp) {
2400
- const elseId = elseFirstComp.attrs.find(a => a.name === "id")?.value;
2401
- const elseReplace = elseFirstComp.attrs.find(a => a.name === "replace");
2402
- const elseReplaceVal = elseReplace?.value;
2403
- const elseWantsReplace = elseReplace && (elseReplaceVal === null || (elseReplaceVal?.kind === "bool" && elseReplaceVal.value));
2404
-
2405
- if (elseId && elseId.kind === "str" && elseId.value === ifId.value && elseWantsReplace) {
2406
- replaceId = ifId.value;
2407
- }
2408
- }
2409
- }
2410
- }
2411
-
2412
- const condId = registerExpr(ctx, ifBlock.condition);
2413
- ctx.mixedBlocks.push({ id, conditionJS: String(condId), ifJS: ifAssignJS, ifHTML, elseJS: elseAssignJS, elseHTML, replaceId });
2414
-
2415
- return `<span id="${replaceId || id}" data-sinth-mixed></span>`;
2416
- }
2417
-
2418
- function renderCompUse(
2419
- use: CompUse,
2420
- ctx: CompileCtx,
2421
- params: Map<string, string>,
2422
- depth: number,
2423
- ): string {
2424
- // transparent wrapper inserted by flattenIfToUses()
2425
- if (use.name === "__IF_ROOT__") {
2426
- return use.children.map(c => renderChild(c, ctx, params, depth)).join("");
2427
- }
2428
-
2429
- // RawHTML
2430
- if (use.name === "RawHTML") {
2431
- const ca = use.attrs.find(a => a.name === "content");
2432
- if (!ca || !ca.value) return "";
2433
- return interpolateAttr(litToString(ca.value), params);
2434
- }
2435
-
2436
- // user-defined component
2437
- const userDef = ctx.allDefs.get(use.name);
2438
- if (userDef) return expandUserComp(use, userDef, ctx, params, depth + 1);
2439
-
2440
- // custom element
2441
- const customEl = ctx.customEls.get(use.name);
2442
- if (customEl) {
2443
- const attrParts = [`data-s="${ctx.scopeHash}"`];
2444
- for (const attr of use.attrs) {
2445
- const r = renderAttr(attr, params, ctx);
2446
- if (r) attrParts.push(r);
2447
- }
2448
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2449
- return `<${customEl.tagName} ${attrParts.join(" ")}>${inner}</${customEl.tagName}>`;
2450
- }
2451
-
2452
- // built-in component
2453
- const { tag, defaultClass, voidEl } = resolveBuiltinTag(use.name, use.attrs);
2454
- const isVoid = voidEl || VOID_TAGS.has(tag);
2455
-
2456
- const attrParts: string[] = [`data-s="${ctx.scopeHash}"`];
2457
- let userClass: string | undefined;
2458
- const inlineStyleParts: string[] = [];
2459
-
2460
- for (const attr of use.attrs) {
2461
- if (attr.name === "level" && use.name === "Heading") continue;
2462
-
2463
- if (INLINE_STYLE_PROPS.has(attr.name) && attr.value) {
2464
- const val = attr.value.kind === "str"
2465
- ? interpolateAttr(attr.value.value, params)
2466
- : litToString(attr.value);
2467
- inlineStyleParts.push(`${camelToKebab(attr.name)}: ${val}`);
2468
- continue;
2469
- }
2470
-
2471
- if (attr.name === "class") {
2472
- if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
2473
- continue;
2474
- }
2475
- const rendered = renderAttr(attr, params, ctx);
2476
- if (rendered) attrParts.push(rendered);
2477
- }
2478
-
2479
- const classes = [defaultClass, userClass].filter(Boolean).join(" ");
2480
- if (classes) attrParts.push(`class="${escAttr(classes)}"`);
2481
- if (inlineStyleParts.length > 0) attrParts.push(`style="${escAttr(inlineStyleParts.join("; "))}"`);
2482
- if (tag === "button" && !use.attrs.some(a => a.name === "type")) attrParts.push(`type="button"`);
2483
- if (use.name === "Input") {
2484
- const bindAttr = use.attrs.find(a => a.name === "bind");
2485
- const modelAttr = use.attrs.find(a => a.name === "model");
2486
- const bindOrModel = bindAttr || modelAttr;
2487
- if (bindOrModel?.value?.kind === "str") {
2488
- let vName = bindOrModel.value.value;
2489
- if (vName.startsWith("__EXPR__")) {
2490
- try {
2491
- const expr: Expression = JSON.parse(vName.substring(8));
2492
- if (expr.kind === "variable" && expr.name) vName = expr.name;
2493
- } catch {}
2494
- }
2495
- if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="text"`);
2496
- attrParts.push(`oninput="(function(e){ ${vName} = e.target.value; sinthRender(); })(event)"`);
2497
- attrParts.push(`data-sinth-value="${escAttr(vName)}"`);
2498
- }
2499
- }
2500
- if (use.name === "Checkbox") {
2501
- if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
2502
- const bindAttr = use.attrs.find(a => a.name === "bind");
2503
- if (bindAttr?.value?.kind === "str") {
2504
- let vName = bindAttr.value.value;
2505
- if (vName.startsWith("__EXPR__")) {
2506
- try {
2507
- const expr: Expression = JSON.parse(vName.substring(8));
2508
- if (expr.kind === "variable" && expr.name) vName = expr.name;
2509
- } catch {}
2510
- }
2511
- attrParts.push(`onchange="(function(e){ ${vName} = e.target.checked; sinthRender(); })(event)"`);
2512
- attrParts.push(`data-sinth-checked="${escAttr(vName)}"`);
2513
- }
2514
- }
2515
-
2516
- const attrStr = attrParts.length ? " " + attrParts.join(" ") : "";
2517
-
2518
- if (isVoid) {
2519
- if (use.children.length > 0) SinthWarning.emit(`<${tag}> is void and cannot have children.`, use.loc);
2520
- return `<${tag}${attrStr}>`;
2521
- }
2522
-
2523
- const inner = use.children.map(c => renderChild(c, ctx, params, depth + 1)).join("");
2524
- return `<${tag}${attrStr}>${inner}</${tag}>`;
2525
- }
2526
-
2527
- function expandUserComp(
2528
- use: CompUse,
2529
- def: CompDef,
2530
- ctx: CompileCtx,
2531
- params: Map<string, string>,
2532
- depth: number,
2533
- ): string {
2534
- if (use.name === def.name && depth > 1) {
2535
- throw new SinthError(`Recursive component '${def.name}' is not allowed.`, use.loc);
2536
- }
2537
-
2538
- const local = new Map<string, string>();
2539
-
2540
- for (const p of def.params) {
2541
- if (p.defaultVal !== undefined) local.set(p.name, litToString(p.defaultVal));
2542
- }
2543
-
2544
- for (const attr of use.attrs) {
2545
- if (attr.value === null) {
2546
- local.set(attr.name, "true");
2547
- } else if (attr.value.kind !== "null") {
2548
- const raw = litToString(attr.value);
2549
- local.set(attr.name, attr.value.kind === "str" ? interpolateAttr(raw, params) : raw);
2550
- }
2551
- }
2552
-
2553
- for (const p of def.params) {
2554
- if (!local.has(p.name)) {
2555
- throw new SinthError(
2556
- `Component '${def.name}' requires parameter '${p.name}' but it was not provided.`,
2557
- use.loc,
2558
- );
2559
- }
2560
- }
2561
-
2562
- const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
2563
- local.set("slot", slotHTML);
2564
-
2565
- for (const block of def.styles) {
2566
- ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
2567
- }
2568
-
2569
- return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
2570
- }
2571
-
2572
- // script collector
2573
-
2574
- function collectScripts(
2575
- file: SinthFile,
2576
- allDefs: Map<string, CompDef>,
2577
- ): { componentScripts: string[]; pageScripts: { raw: string; attrs: Record<string, string> }[] } {
2578
- const componentScripts: string[] = [];
2579
- const pageScripts: { raw: string; attrs: Record<string, string> }[] = [];
2580
- const seenFunctions = new Set<string>();
2581
-
2582
- for (const [, def] of allDefs) {
2583
- for (const block of def.scripts) {
2584
- for (const fn of extractFunctionNames(block.raw)) {
2585
- if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' defined in multiple component scripts.`);
2586
- seenFunctions.add(fn);
2587
- }
2588
- componentScripts.push(`(function(){\n${block.raw}\n})();`);
2589
- }
2590
- }
2591
-
2592
- for (const block of file.scripts) {
2593
- for (const fn of extractFunctionNames(block.raw)) {
2594
- if (seenFunctions.has(fn)) throw new SinthError(`Function '${fn}' conflicts with a component script.`);
2595
- seenFunctions.add(fn);
2596
- }
2597
- pageScripts.push({ raw: block.raw, attrs: block.attrs });
2598
- }
2599
-
2600
- return { componentScripts, pageScripts };
2601
- }
2602
-
2603
- function extractFunctionNames(js: string): string[] {
2604
- const names: string[] = [];
2605
- const re = /^\s*(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/gm;
2606
- let m: RegExpExecArray | null;
2607
- while ((m = re.exec(js)) !== null) names.push(m[1]);
2608
- return names;
2609
- }
2610
-
2611
-
2612
- // head gen
2613
-
2614
- interface HeadData {
2615
- title?: string; fav?: string;
2616
- lang: string; charset: string; viewport: string;
2617
- metaTags: { name: string; content: string }[];
2618
- metaProps: { property: string; content: string }[];
2619
- }
2620
-
2621
- function buildHeadData(meta: MetaEntry[]): HeadData {
2622
- let title: string | undefined, fav: string | undefined;
2623
- let lang = "en", charset = "UTF-8", viewport = "width=device-width, initial-scale=1.0";
2624
- const metaTags: { name: string; content: string }[] = [];
2625
- const metaProps: { property: string; content: string }[] = [];
2626
-
2627
- for (const m of meta) {
2628
- const val = litToString(m.value);
2629
- switch (m.key) {
2630
- case "title": title = val; break;
2631
- case "fav": fav = val; break;
2632
- case "lang": lang = val; break;
2633
- case "charset": charset = val; break;
2634
- case "viewport": viewport = val; break;
2635
- case "descr": metaTags.push({ name: "description", content: val }); break;
2636
- case "author": metaTags.push({ name: "author", content: val }); break;
2637
- case "keywords": metaTags.push({ name: "keywords", content: val }); break;
2638
- case "robots": metaTags.push({ name: "robots", content: val }); break;
2639
- default:
2640
- if (m.key.startsWith("og") || m.key.startsWith("twitter")) {
2641
- const prop = m.key
2642
- .replace(/^og([A-Z])/, (_: string, c: string) => `og:${c.toLowerCase()}`)
2643
- .replace(/^twitter([A-Z])/, (_: string, c: string) => `twitter:${c.toLowerCase()}`);
2644
- metaProps.push({ property: prop, content: val });
2645
- } else {
2646
- metaTags.push({ name: camelToKebab(m.key), content: val });
2647
- }
2648
- }
2649
- }
2650
-
2651
- return { title, fav, lang, charset, viewport, metaTags, metaProps };
2652
- }
2653
-
2654
- function faviconType(p: string): string {
2655
- switch (path.extname(p).toLowerCase()) {
2656
- case ".ico": return "image/x-icon";
2657
- case ".png": return "image/png";
2658
- case ".svg": return "image/svg+xml";
2659
- case ".gif": return "image/gif";
2660
- case ".webp": return "image/webp";
2661
- case ".jpg":
2662
- case ".jpeg": return "image/jpeg";
2663
- default:
2664
- SinthWarning.emit(`Unknown favicon extension '${path.extname(p)}', defaulting to image/x-icon`);
2665
- return "image/x-icon";
2666
- }
2667
- }
2668
-
2669
- function renderHead(
2670
- hd: HeadData,
2671
- cssLinks: string[],
2672
- jsLinks: { src: string; attrs: Record<string, string> }[],
2673
- scopedCSS: string,
2674
- companionJS: string | undefined,
2675
- ): string {
2676
- const lines: string[] = [];
2677
- lines.push(` <meta charset="${escAttr(hd.charset)}">`);
2678
- lines.push(` <meta name="viewport" content="${escAttr(hd.viewport)}">`);
2679
- if (hd.title) lines.push(` <title>${esc(hd.title)}</title>`);
2680
- if (hd.fav) lines.push(` <link rel="icon" href="${escAttr(hd.fav)}" type="${faviconType(hd.fav)}">`);
2681
- for (const m of hd.metaTags) lines.push(` <meta name="${escAttr(m.name)}" content="${escAttr(m.content)}">`);
2682
- for (const m of hd.metaProps) lines.push(` <meta property="${escAttr(m.property)}" content="${escAttr(m.content)}">`);
2683
- for (const css of cssLinks) lines.push(` <link rel="stylesheet" href="${escAttr(css)}">`);
2684
- if (scopedCSS.trim()) lines.push(` <style>\n${scopedCSS}\n </style>`);
2685
- for (const js of jsLinks) {
2686
- const extra = Object.entries(js.attrs)
2687
- .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
2688
- .join(" ");
2689
- lines.push(` <script src="${escAttr(js.src)}"${extra ? " " + extra : ""}></script>`);
2690
- }
2691
- if (companionJS) lines.push(` <script src="${escAttr(companionJS)}"></script>`);
2692
- return `<head>\n${lines.join("\n")}\n</head>`;
2693
- }
2694
-
2695
-
2696
- // sinth runtime
2697
-
2698
- function buildRuntime(opts: {
2699
- varDecls: VarDeclaration[];
2700
- bodyHTML: string;
2701
- logicBlocks: string[];
2702
- mixedBlocks: MixedBlockEntry[];
2703
- assignedVars: Set<string>;
2704
- exprRegistry: string[];
2705
- sharedRuntime: boolean;
2706
- }): string | { page: string; shared: string } {
2707
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
2708
-
2709
- const needsExpr = bodyHTML.includes("sinth-expr");
2710
- const needsIf = bodyHTML.includes("data-sinth-if");
2711
- const needsFor = bodyHTML.includes("data-sinth-for");
2712
- 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"));
2713
- const needsMixed = mixedBlocks.length > 0;
2714
- const needsLogic = logicBlocks.length > 0;
2715
- const needsRender = needsExpr || needsIf || needsFor || needsMixed || needsLogic;
2716
-
2717
- const varLines = varDecls.map(v => {
2718
- if (!v.value) {
2719
- if (!assignedVars.has(v.name)) {
2720
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2721
- SinthWarning.emit(
2722
- `Variable '${v.name}' is declared but never assigned. Defaulting to ${defaults[v.varType] ?? "undefined"}.`,
2723
- v.loc,
2724
- );
2725
- }
2726
- const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2727
- return `var ${v.name} = ${defaults[v.varType] ?? "undefined"};`;
2728
- }
2729
- const val = litToString(v.value);
2730
- if (val.startsWith("__VAR__")) return `var ${v.name} = ${val.slice(7)};`;
2731
- if (val.startsWith("__ARR__")) return `var ${v.name} = ${val.slice(7)};`;
2732
- if (v.varType === "obj") return `var ${v.name} = ${val};`;
2733
- if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2734
- if (v.varType === "str[]" && typeof val === 'string' && val.startsWith("__ARR__")) {
2735
- try {
2736
- const arr = JSON.parse(val.slice(7));
2737
- return `var ${v.name} = ${JSON.stringify(arr)};`;
2738
- } catch { return `var ${v.name} = ${val.slice(7)};`; }
2739
- }
2740
- return `var ${v.name} = ${val};`;
2741
- }).join("\n");
2742
-
2743
- if (!needsRender && !needsDelay) {
2744
- return varLines ? `// Sinth compiled runtime\n${varLines}` : "";
2745
- }
2746
-
2747
- let helpers = "";
2748
-
2749
- if (needsExpr || needsIf || needsFor) {
2750
- helpers += `
2751
- function sinthExpr(el) {
2752
- try {
2753
- var exprFn = __X[el.dataset.exprId];
2754
- if (exprFn) el.textContent = exprFn({});
2755
- } catch(e) {}
2756
- }
2757
- `;
2758
- }
2759
-
2760
- if (needsIf || needsMixed) {
2761
- helpers += `
2762
- function sinthReplaceInsert(t, anchor, ifId, replaceId) {
2763
- if (anchor) {
2764
- var cur = anchor.nextSibling;
2765
- while (cur && cur !== t) { var nx = cur.nextSibling; cur.remove(); cur = nx; }
2766
- } else {
2767
- anchor = document.createElement('span');
2768
- anchor.style.display = 'none';
2769
- anchor.dataset.sinthIfAnchor = ifId;
2770
- t.parentNode.insertBefore(anchor, t);
2771
- }
2772
- var _rp = null, _rpParent = null, _rpNext = null;
2773
- if (replaceId) {
2774
- _rp = document.getElementById(replaceId);
2775
- if (_rp) {
2776
- _rpParent = _rp.parentNode;
2777
- _rpNext = _rp.nextSibling;
2778
- _rp.parentNode.removeChild(_rp);
2779
- anchor._sinthReplaced = _rp;
2780
- anchor._sinthReplacedParent = _rpParent;
2781
- anchor._sinthReplacedNext = _rpNext;
2782
- }
2783
- }
2784
- var frag = document.createRange().createContextualFragment(t.innerHTML);
2785
- frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2786
- if (${needsDelay}) {
2787
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2788
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2789
- }
2790
- var fragFirst = frag.firstChild;
2791
- var fragLast = frag.lastChild;
2792
- if (_rpParent && _rpNext) {
2793
- _rpParent.insertBefore(frag, _rpNext);
2794
- } else if (_rpParent) {
2795
- _rpParent.appendChild(frag);
2796
- } else {
2797
- t.parentNode.insertBefore(frag, t);
2798
- }
2799
- if (replaceId && anchor) {
2800
- anchor._sinthInsertedFirst = fragFirst;
2801
- anchor._sinthInsertedLast = fragLast;
2802
- }
2803
- return anchor;
2804
- }
2805
- `;
2806
- }
2807
-
2808
- if (needsDelay) {
2809
- helpers += `
2810
- function sinthDelay(el) {
2811
- if (el.dataset.sinthDelayDone) { el.style.display = ''; return; }
2812
- el.dataset.sinthDelayDone = '1';
2813
- var ms = parseInt(el.dataset.sinthDelay) || 0;
2814
- el.style.display = 'none';
2815
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2816
- else el.style.display = '';
2817
- }
2818
- function sinthDelayExpr(el) {
2819
- try {
2820
- var fn = __X[el.dataset.sinthDelayExprId];
2821
- var ms = fn ? parseInt(fn()) || 0 : 0;
2822
- el.style.display = '';
2823
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
2824
- } catch(e) {}
2825
- }
2826
- `;
2827
- }
2828
-
2829
- if (needsIf) {
2830
- helpers += `
2831
- function sinthIfBlock(t) {
2832
- var ifId = t.dataset.sinthIfId;
2833
- var anchor = t.parentNode.querySelector('[data-sinth-if-anchor="' + ifId + '"]');
2834
- var condFn = __X[t.dataset.sinthIfExpr];
2835
- var cond = condFn ? condFn() : false;
2836
- if (cond) {
2837
- anchor = sinthReplaceInsert(t, anchor, ifId, t.dataset.sinthIfReplace);
2838
- } else {
2839
- if (anchor) {
2840
- if (anchor._sinthReplaced) {
2841
- var insFirst = anchor._sinthInsertedFirst;
2842
- var insLast = anchor._sinthInsertedLast;
2843
- var rpParent = anchor._sinthReplacedParent;
2844
- var rpNext = anchor._sinthReplacedNext;
2845
- if (insFirst && insLast) {
2846
- var cur = insFirst;
2847
- while (cur && cur !== insLast) {
2848
- var next = cur.nextSibling;
2849
- cur.remove();
2850
- cur = next;
2851
- }
2852
- if (insLast) insLast.remove();
2853
- }
2854
- if (rpParent && rpNext) {
2855
- rpParent.insertBefore(anchor._sinthReplaced, rpNext);
2856
- } else if (rpParent) {
2857
- rpParent.appendChild(anchor._sinthReplaced);
2858
- }
2859
- } else {
2860
- var cur2 = anchor.nextSibling;
2861
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2862
- }
2863
- anchor.remove();
2864
- }
2865
- var elseT = t.nextElementSibling;
2866
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
2867
- var elseIfId = elseT.dataset.sinthIfId;
2868
- var ea = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + elseIfId + '"]');
2869
- if (ea) {
2870
- var cur3 = ea.nextSibling;
2871
- while (cur3 && cur3 !== t) { var nx3 = cur3.nextSibling; cur3.remove(); cur3 = nx3; }
2872
- } else {
2873
- ea = document.createElement('span');
2874
- ea.style.display = 'none';
2875
- ea.dataset.sinthIfAnchor = '__else__' + elseIfId;
2876
- t.parentNode.insertBefore(ea, t);
2877
- }
2878
- var ef = document.createRange().createContextualFragment(elseT.innerHTML);
2879
- ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
2880
- if (${needsDelay}) {
2881
- ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2882
- ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2883
- }
2884
- t.parentNode.insertBefore(ef, t);
2885
- } else {
2886
- var ea2 = t.parentNode.querySelector('[data-sinth-if-anchor="__else__' + ifId + '"]');
2887
- if (ea2) {
2888
- var ec = ea2.nextSibling;
2889
- while (ec && ec !== t) { var en = ec.nextSibling; ec.remove(); ec = en; }
2890
- ea2.remove();
2891
- }
2892
- }
2893
- }
2894
- }
2895
- `;
2896
- }
2897
-
2898
- if (needsFor) {
2899
- helpers += `
2900
- function hashString(str) {
2901
- var hash = 0, i, chr;
2902
- for (i = 0; i < str.length; i++) {
2903
- chr = str.charCodeAt(i);
2904
- hash = ((hash << 5) - hash) + chr;
2905
- hash |= 0;
2906
- }
2907
- return String(hash);
2908
- }
2909
- function sinthForBlock(t) {
2910
- var source = window[t.dataset.sinthFor];
2911
- if (source === undefined) source = [];
2912
- var newHash = '';
2913
- try { newHash = hashString(JSON.stringify(source)); } catch(e) { newHash = ''; }
2914
- if (t.dataset.sinthForHash && t.dataset.sinthForHash === newHash) {
2915
- return;
2916
- }
2917
- t.dataset.sinthForHash = newHash;
2918
- var isObj = (typeof source === 'object' && source !== null && !Array.isArray(source));
2919
- var entries;
2920
- if (isObj) {
2921
- entries = Object.entries(source);
2922
- } else {
2923
- if (!Array.isArray(source)) source = [];
2924
- entries = source.map(function(item, index) { return [index, item]; });
2925
- }
2926
- var anchor = t.parentNode ? t.parentNode.querySelector('[data-sinth-for-anchor="' + t.dataset.sinthFor + '"]') : null;
2927
- if (anchor) {
2928
- var cur2 = anchor.nextSibling;
2929
- while (cur2 && cur2 !== t) { var nx2 = cur2.nextSibling; cur2.remove(); cur2 = nx2; }
2930
- anchor.remove();
2931
- }
2932
- var fa = document.createElement('span');
2933
- fa.style.display = 'none';
2934
- fa.dataset.sinthForAnchor = t.dataset.sinthFor;
2935
- t.parentNode && t.parentNode.insertBefore(fa, t);
2936
- var _loopIdx = 0;
2937
- entries.forEach(function(entry) {
2938
- var _k = entry[0];
2939
- var _v = entry[1];
2940
- var _item = (t.dataset && t.dataset.sinthItem) ? t.dataset.sinthItem : '__item__';
2941
- var _key = t.dataset && t.dataset.sinthKey ? t.dataset.sinthKey : null;
2942
- var _idx = t.dataset && t.dataset.sinthIndex ? t.dataset.sinthIndex : null;
2943
- _loopIdx++;
2944
- if (t.dataset.sinthIfReplace) {
2945
- var _rp = document.getElementById(t.dataset.sinthIfReplace);
2946
- if (_rp) _rp.parentNode.removeChild(_rp);
2947
- }
2948
- var frag = document.createRange().createContextualFragment(t.innerHTML);
2949
- frag.querySelectorAll('.sinth-expr').forEach(function(el) {
2950
- try {
2951
- var exprFn = __X[el.dataset.exprId];
2952
- if (!exprFn) return;
2953
- var _ctx = {};
2954
- if (_item) _ctx[_item] = _v;
2955
- if (_key) _ctx[_key] = _k;
2956
- if (_idx) _ctx[_idx] = _loopIdx - 1;
2957
- el.textContent = exprFn(_ctx);
2958
- el.classList.remove('sinth-expr');
2959
- } catch(e) {}
2960
- });
2961
- frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
2962
- var condFn = __X[ifT.dataset.sinthIfExpr];
2963
- var _ctx = {};
2964
- if (_item) _ctx[_item] = _v;
2965
- if (_key) _ctx[_key] = _k;
2966
- if (_idx) _ctx[_idx] = _loopIdx - 1;
2967
- var cond = false;
2968
- try { if (condFn) cond = condFn(_ctx); } catch(e) {}
2969
- if (cond) {
2970
- var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
2971
- ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2972
- try {
2973
- var exprFn2 = __X[el2.dataset.exprId];
2974
- if (exprFn2) el2.textContent = exprFn2(_ctx);
2975
- } catch(e) {}
2976
- });
2977
- ifT.parentNode.insertBefore(ifContent, ifT);
2978
- } else {
2979
- var elseT = ifT.nextElementSibling;
2980
- if (elseT && elseT.hasAttribute('data-sinth-else')) {
2981
- var elseContent = document.createRange().createContextualFragment(elseT.innerHTML);
2982
- elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
2983
- try {
2984
- var exprFn2 = __X[el2.dataset.exprId];
2985
- if (exprFn2) el2.textContent = exprFn2(_ctx);
2986
- } catch(e) {}
2987
- });
2988
- ifT.parentNode.insertBefore(elseContent, ifT);
2989
- }
2990
- }
2991
- });
2992
- if (${needsDelay}) {
2993
- frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
2994
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
2995
- }
2996
- t.parentNode && t.parentNode.insertBefore(frag, t);
2997
- });
2998
- }
2999
- `;
3000
- }
3001
-
3002
- if (needsMixed) {
3003
- helpers += `
3004
- function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
3005
- var condFn = __X[condId];
3006
- var cond = condFn ? condFn() : false;
3007
- if (cond) {
3008
- if (ifJS) eval(ifJS);
3009
- el.innerHTML = ifHTML;
3010
- } else {
3011
- if (elseJS) eval(elseJS);
3012
- el.innerHTML = elseHTML;
3013
- }
3014
- el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
3015
- el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
3016
- if (${needsDelay}) {
3017
- el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3018
- el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3019
- }
3020
- }
3021
- `;
3022
- }
3023
-
3024
- const exprArrayJS = exprRegistry.length > 0
3025
- ? `var __X = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
3026
- : "";
3027
-
3028
- let renderBody = "";
3029
- renderBody += ` var _sx = window.scrollX, _sy = window.scrollY;\n`;
3030
-
3031
- if (needsLogic) {
3032
- renderBody += logicBlocks.map(b => b.replace(/^/gm, " ")).join("\n") + "\n";
3033
- }
3034
-
3035
- if (needsMixed) {
3036
- for (const mb of mixedBlocks) {
3037
- renderBody += ` (function() {
3038
- var __el = document.getElementById(${JSON.stringify(mb.replaceId || mb.id)});
3039
- if (__el) sinthMixedBlock(__el, ${mb.conditionJS}, ${JSON.stringify(mb.ifJS)}, ${JSON.stringify(mb.ifHTML)}, ${JSON.stringify(mb.elseJS)}, ${JSON.stringify(mb.elseHTML)});
3040
- })();\n`;
3041
- }
3042
- }
3043
-
3044
- renderBody += ` document.querySelectorAll('[data-sinth-remove]').forEach(function(el) {
3045
- var target = document.getElementById(el.dataset.sinthRemove);
3046
- if (target) target.remove();
3047
- });\n`;
3048
-
3049
- if (needsIf) {
3050
- renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);\n`;
3051
- }
3052
- if (needsFor) {
3053
- renderBody += ` document.querySelectorAll('template[data-sinth-for]').forEach(sinthForBlock);\n`;
3054
- }
3055
- renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
3056
- try { el.value = window[el.dataset.sinthValue] || ''; } catch(e) {}
3057
- });\n`;
3058
- renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
3059
- try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
3060
- });\n`;
3061
- if (needsExpr) {
3062
- renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
3063
- }
3064
- if (needsDelay) {
3065
- renderBody += ` setTimeout(function() {
3066
- document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
3067
- document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
3068
- }, 0);\n`;
3069
- }
3070
- renderBody += ` window.scrollTo(_sx, _sy);\n`;
3071
-
3072
- const renderFunc = needsRender ? `function sinthRender() {\n${renderBody}}\nsinthRender();` : "";
3073
-
3074
- const pageCode = `// Sinth page runtime
3075
- ${varLines}
3076
- ${exprArrayJS}
3077
- ${renderFunc}`;
3078
-
3079
- if (opts.sharedRuntime && helpers.trim()) {
3080
- const sharedCode = `// Sinth shared runtime
3081
- ${helpers}`;
3082
- return { page: pageCode, shared: sharedCode };
3083
- }
3084
-
3085
- return `// Sinth compiled runtime
3086
- ${varLines}
3087
- ${helpers}
3088
- ${exprArrayJS}
3089
- ${renderFunc}`;
3090
- }
3091
-
3092
- // main compilation pipeline
3093
-
3094
- interface CompileOptions {
3095
- projectRoot: string;
3096
- outDir: string;
3097
- libraryPaths: string[];
3098
- minify: boolean;
3099
- checkOnly: boolean;
3100
- sharedRuntime: boolean;
3101
- }
3102
-
3103
- function compileFile(filePath: string, opts: CompileOptions): { html: string; shared?: string } | null {
3104
- const absPath = path.resolve(filePath);
3105
- const file = parseFile(absPath);
3106
-
3107
- const cfg: ResolverConfig = { projectRoot: opts.projectRoot, libraryPaths: opts.libraryPaths };
3108
- const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
3109
- const hash = fnv1a(absPath);
3110
-
3111
- const allVarDecls: VarDeclaration[] = file.varDecls;
3112
-
3113
- const ctx: CompileCtx = {
3114
- allDefs, customEls, cssLinks, jsLinks,
3115
- scopeHash: hash,
3116
- pageFile: absPath,
3117
- extraCSS: [],
3118
- mixedBlocks: [],
3119
- mixedCounter: 0,
3120
- logicBlocks: [],
3121
- ifIdCounter: 0,
3122
- exprRegistry: [],
3123
- exprMap: new Map(),
3124
- };
3125
-
3126
- if (!file.isPage) {
3127
- const body = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
3128
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash)).join("\n");
3129
- const allCSS = [pageCSS, ...ctx.extraCSS].join("\n");
3130
- const h = `${body}\n<style>\n${allCSS}\n</style>`;
3131
- return { html: h };
3132
- }
3133
-
3134
- const headData = buildHeadData(file.meta);
3135
- const bodyHTML = file.uses.map(u => renderCompUse(u, ctx, new Map(), 0)).join("\n");
3136
- const pageCSS = file.styles.map(s => processStyleBlock(s, hash, new Map())).join("\n");
3137
- const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
3138
- const { componentScripts, pageScripts } = collectScripts(file, allDefs);
3139
-
3140
- // collect all assigned variables for default-value warnings
3141
- const assignedVars = new Set<string>();
3142
- for (const s of file.scripts) {
3143
- for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g)) assignedVars.add(m[1]);
3144
- }
3145
- for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
3146
-
3147
- // companion JS file (needs same name as .sinth, adds support for JS libraries)
3148
- const companionJS = (() => {
3149
- const base = absPath.replace(/\.sinth$/, ".js");
3150
- return fs.existsSync(base) ? path.basename(base) : undefined;
3151
- })();
3152
-
3153
- const relativeCssLinks = cssLinks.map(css => {
3154
- const rel = path.relative(path.dirname(absPath), css).replace(/\\/g, "/");
3155
- return rel.startsWith(".") ? rel : "./" + rel;
3156
- });
3157
- const relativeJsLinks = jsLinks.map(js => ({
3158
- ...js,
3159
- src: (() => {
3160
- const rel = path.relative(path.dirname(absPath), js.src).replace(/\\/g, "/");
3161
- return rel.startsWith(".") ? rel : "./" + rel;
3162
- })(),
3163
- }));
3164
-
3165
- const runtimeResult = buildRuntime({
3166
- varDecls: allVarDecls,
3167
- bodyHTML,
3168
- logicBlocks: ctx.logicBlocks,
3169
- mixedBlocks: ctx.mixedBlocks,
3170
- assignedVars,
3171
- exprRegistry: ctx.exprRegistry,
3172
- sharedRuntime: opts.sharedRuntime,
3173
- });
3174
- const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
3175
- const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
3176
-
3177
- const sharedRuntimeTag = opts.sharedRuntime && sharedJS
3178
- ? `<script src="./sinth-runtime.js"></script>`
3179
- : "";
3180
-
3181
- const head = renderHead(headData, relativeCssLinks, relativeJsLinks, scopedCSS, companionJS);
3182
- const scriptTags: string[] = [];
3183
- if (componentScripts.length > 0) {
3184
- scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
3185
- }
3186
-
3187
- for (const s of pageScripts) {
3188
- const extra = Object.entries(s.attrs)
3189
- .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
3190
- .join(" ");
3191
- const globalised = s.raw.replace(/\b(let|const)\b/g, "var");
3192
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalised}\n</script>`);
3193
- }
3194
-
3195
- const html = [
3196
- "<!DOCTYPE html>",
3197
- `<html lang="${escAttr(headData.lang)}">`,
3198
- head,
3199
- `<body data-s="${hash}">`,
3200
- bodyHTML,
3201
- sharedRuntimeTag,
3202
- runtimeJS.trim() ? `<script>\n${runtimeJS}\n</script>` : "",
3203
- scriptTags.join("\n"),
3204
- "</body>",
3205
- "</html>",
3206
- ].filter(Boolean).join("\n");
3207
-
3208
- const finalHTML = opts.minify ? minifyHTML(html) : html;
3209
- return sharedJS ? { html: finalHTML, shared: sharedJS } : { html: finalHTML };
3210
- }
3211
-
3212
- function minifyHTML(html: string): string {
3213
- return html.replace(/>\s+</g, "><").replace(/\n\s*\n/g, "\n").trim();
3214
- }
3215
-
3216
- // file discovery & asset copy
3217
-
3218
- function findSinthPages(dir: string, outDir?: string): string[] {
3219
- const results: string[] = [];
3220
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
3221
- if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
3222
- const full = path.join(dir, entry.name);
3223
- if (outDir && path.resolve(full) === path.resolve(outDir)) continue;
3224
- if (entry.isDirectory()) results.push(...findSinthPages(full, outDir));
3225
- else if (entry.name.endsWith(".sinth")) results.push(full);
3226
- }
3227
- return results;
3228
- }
3229
-
3230
- function copyDir(src: string, dest: string): void {
3231
- if (!fs.existsSync(src)) return;
3232
- fs.mkdirSync(dest, { recursive: true });
3233
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
3234
- const sp = path.join(src, entry.name);
3235
- const dp = path.join(dest, entry.name);
3236
- if (entry.isDirectory()) copyDir(sp, dp);
3237
- else fs.copyFileSync(sp, dp);
3238
- }
3239
- }
3240
-
3241
-
3242
- // dev server
3243
-
3244
- const LIVE_RELOAD_SCRIPT = `<script>
3245
- (function(){
3246
- var es = new EventSource('/__sinth_sse__');
3247
- es.onmessage = function() { location.reload(); };
3248
- es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
3249
- })();
3250
- </script>`;
3251
-
3252
- async function startDevServer(opts: CompileOptions & { port: number; files?: string[] }): Promise<void> {
3253
- const clients: http.ServerResponse[] = [];
3254
- const cache = new Map<string, string>();
3255
-
3256
- function notify(): void {
3257
- for (const c of clients) { try { c.write("data: reload\n\n"); } catch {} }
3258
- }
3259
-
3260
- function compileAll(): void {
3261
- cache.clear();
3262
- const pages = (opts.files && opts.files.length > 0)
3263
- ? opts.files.filter(f => fs.existsSync(f))
3264
- : findSinthPages(opts.projectRoot, opts.outDir);
3265
- for (const p of pages) {
3266
- try {
3267
- const result = compileFile(p, { ...opts, checkOnly: false });
3268
- if (!result) continue;
3269
- const html = result.html;
3270
- const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
3271
- const url = "/" + rel;
3272
- cache.set(url, html + LIVE_RELOAD_SCRIPT);
3273
- if (rel === "index.html" || rel.endsWith("/index.html")) {
3274
- cache.set("/", html + LIVE_RELOAD_SCRIPT);
3275
- }
3276
- } catch (e: unknown) {
3277
- process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
3278
- }
3279
- }
3280
- }
3281
-
3282
- compileAll();
3283
-
3284
- const resolvedOut = path.resolve(opts.outDir);
3285
- let watchReady = false;
3286
- const pending = new Map<string, NodeJS.Timeout>();
3287
- const DEBOUNCE_MS = 300;
3288
-
3289
- try {
3290
- fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
3291
- if (!filename) return;
3292
- const abs = path.resolve(opts.projectRoot, filename);
3293
- if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
3294
- if (pending.has(abs)) {
3295
- clearTimeout(pending.get(abs)!);
3296
- }
3297
- pending.set(abs, setTimeout(() => {
3298
- pending.delete(abs);
3299
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
3300
- compileAll(); notify();
3301
- }, DEBOUNCE_MS));
3302
- });
3303
- watchReady = true;
3304
- } catch {}
3305
-
3306
- if (!watchReady) {
3307
- const mtimes = new Map<string, number>();
3308
- const poller = setInterval(() => {
3309
- const pages = (opts.files && opts.files.length > 0)
3310
- ? opts.files : findSinthPages(opts.projectRoot, opts.outDir);
3311
- for (const p of pages) {
3312
- try {
3313
- const mtime = fs.statSync(p).mtimeMs;
3314
- if (mtimes.get(p) !== mtime) {
3315
- mtimes.set(p, mtime);
3316
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
3317
- compileAll(); notify(); break;
3318
- }
3319
- } catch {}
3320
- }
3321
- }, 500);
3322
- process.on("exit", () => clearInterval(poller));
3323
- }
3324
-
3325
- const EXT_TYPES: Record<string, string> = {
3326
- ".css": "text/css", ".js": "application/javascript",
3327
- ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
3328
- ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
3329
- ".gif": "image/gif", ".webp": "image/webp",
3330
- ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
3331
- ".json": "application/json", ".xml": "application/xml",
3332
- };
3333
-
3334
- const server = http.createServer((req, res) => {
3335
- const reqUrl = (req.url ?? "/").split("?")[0];
3336
-
3337
- if (reqUrl === "/__sinth_sse__") {
3338
- res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
3339
- clients.push(res);
3340
- req.on("close", () => { const i = clients.indexOf(res); if (i !== -1) clients.splice(i, 1); });
3341
- return;
3342
- }
3343
-
3344
- const cached = cache.get(reqUrl) ??
3345
- cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
3346
- if (cached) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(cached); return; }
3347
-
3348
- let filePath = path.join(opts.projectRoot, reqUrl);
3349
- if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
3350
- if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
3351
- const ctype = EXT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
3352
- res.writeHead(200, { "Content-Type": ctype });
3353
- res.end(fs.readFileSync(filePath));
3354
- return;
3355
- }
3356
-
3357
- res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found");
3358
- });
3359
-
3360
- server.listen(opts.port, () => {
3361
- process.stdout.write(
3362
- `\x1b[32m[sinth dev]\x1b[0m Serving at \x1b[4mhttp://localhost:${opts.port}\x1b[0m\n`
3363
- );
3364
- });
3365
- }
3366
-
3367
-
3368
- // cli entry point
3369
-
3370
- function loadConfig(root: string): Record<string, unknown> {
3371
- const cfgPath = path.join(root, "sinth.config.json");
3372
- if (fs.existsSync(cfgPath)) {
3373
- try { return JSON.parse(fs.readFileSync(cfgPath, "utf-8")) as Record<string, unknown>; }
3374
- catch { SinthWarning.emit("Could not parse sinth.config.json"); }
3375
- }
3376
- return {};
3377
- }
3378
-
3379
- async function main(): Promise<void> {
3380
- const [,, command, ...args] = process.argv;
3381
- const cwd = process.cwd();
3382
- const cfg = loadConfig(cwd);
3383
-
3384
- const outDirIdx = args.indexOf("--out");
3385
- const outDir = outDirIdx !== -1 ? args[outDirIdx + 1] : (cfg.outDir as string | undefined) ?? path.join(cwd, "dist");
3386
- const portIdx = args.indexOf("--port");
3387
- const port = portIdx !== -1 ? parseInt(args[portIdx + 1], 10) : (cfg.port as number | undefined) ?? 3000;
3388
- const minify = args.includes("--prod") || Boolean(cfg.minify);
3389
- const sharedRuntime = args.includes("--shared-runtime") || Boolean(cfg.sharedRuntime);
3390
- const libraryPaths = (cfg.libraryPaths as string[] | undefined) ?? [path.join(cwd, "libraries")];
3391
-
3392
- const flagValues = new Set<string>();
3393
- if (outDirIdx !== -1) flagValues.add(args[outDirIdx + 1]);
3394
- if (portIdx !== -1) flagValues.add(args[portIdx + 1]);
3395
- const cleanArgs = args.filter(a => !a.startsWith("--") && !flagValues.has(a));
3396
-
3397
- const opts: CompileOptions = { projectRoot: cwd, outDir, libraryPaths, minify, checkOnly: false, sharedRuntime };
3398
-
3399
- switch (command) {
3400
- case "build": {
3401
- const nonSinth = cleanArgs.filter(a => !a.endsWith(".sinth"));
3402
- if (nonSinth.length > 0) process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
3403
-
3404
- const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
3405
- const pages = fileArgs.length > 0
3406
- ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
3407
- : findSinthPages(cwd, outDir);
3408
-
3409
- if (pages.length === 0) { process.stdout.write("No .sinth files found.\n"); process.exit(0); }
3410
-
3411
- let hadError = false, built = 0;
3412
-
3413
- const sharedRuntimes: string[] = [];
3414
- for (const p of pages) {
3415
- try {
3416
- const result = compileFile(p, opts);
3417
- if (!result) continue;
3418
- const html = result.html;
3419
- if (result.shared) {
3420
- sharedRuntimes.push(result.shared);
3421
- }
3422
- const rel = path.relative(cwd, p).replace(/\.sinth$/, ".html");
3423
- const out = path.join(outDir, rel);
3424
- fs.mkdirSync(path.dirname(out), { recursive: true });
3425
- fs.writeFileSync(out, html);
3426
- process.stdout.write(` \x1b[32m✓\x1b[0m ${rel}\n`);
3427
- built++;
3428
- } catch (e: unknown) {
3429
- process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
3430
- hadError = true;
3431
- }
3432
- }
3433
-
3434
- if (sharedRuntimes.length > 0) {
3435
- const combined = sharedRuntimes.join("\n");
3436
- fs.writeFileSync(path.join(outDir, "sinth-runtime.js"), combined);
3437
- process.stdout.write(` \x1b[32m✓\x1b[0m sinth-runtime.js (shared)\n`);
3438
- }
3439
-
3440
- // copies to output
3441
- const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
3442
- if (fs.existsSync(assetsIn)) {
3443
- copyDir(assetsIn, assetsOut);
3444
- process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
3445
- }
3446
-
3447
- const libIn = path.join(cwd, "libraries"), libOut = path.join(outDir, "libraries");
3448
- if (fs.existsSync(libIn)) {
3449
- copyDir(libIn, libOut);
3450
- const libFiles = fs.readdirSync(libOut, { recursive: true }) as string[];
3451
- for (const f of libFiles) {
3452
- if (f.endsWith(".sinth") || f.endsWith(".html")) {
3453
- try { fs.unlinkSync(path.join(libOut, f)); } catch {}
3454
- }
3455
- }
3456
- process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
3457
- }
3458
-
3459
- process.stdout.write(`\n\x1b[1mBuilt ${built} page(s)\x1b[0m${hadError ? " with errors" : ""}\n`);
3460
- process.exit(hadError ? 1 : 0);
3461
- break;
3462
- }
3463
-
3464
- case "dev": {
3465
- const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
3466
- const files = fileArgs.length > 0
3467
- ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
3468
- : undefined;
3469
- await startDevServer({ ...opts, port, files });
3470
- break;
3471
- }
3472
-
3473
- case "check": {
3474
- opts.checkOnly = true;
3475
- const pages = findSinthPages(cwd, outDir);
3476
- let hadError = false;
3477
- for (const p of pages) {
3478
- try {
3479
- compileFile(p, opts);
3480
- process.stdout.write(` \x1b[32m✓\x1b[0m ${path.relative(cwd, p)}\n`);
3481
- } catch (e: unknown) {
3482
- process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${(e as Error).message}\n`);
3483
- hadError = true;
3484
- }
3485
- }
3486
- process.exit(hadError ? 1 : 0);
3487
- break;
3488
- }
3489
-
3490
- case "version":
3491
- case "--version":
3492
- case "-v": {
3493
- const pkgPath = path.join(__dirname, "..", "package.json");
3494
- if (fs.existsSync(pkgPath)) {
3495
- const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
3496
- process.stdout.write(`Sinth Compiler v${pkg.version}\n`);
3497
- } else {
3498
- process.stdout.write("Sinth Compiler v1.0.0\n");
3499
- }
3500
- break;
3501
- }
3502
-
3503
- case "init": {
3504
- const projectName = cleanArgs[0] || "my-sinth-project";
3505
- scaffoldProject(path.resolve(cwd, projectName));
3506
- break;
3507
- }
3508
-
3509
- default: {
3510
- let version = "1.0.0";
3511
- const paths = [
3512
- path.resolve(__dirname, "..", "package.json"),
3513
- path.resolve(__dirname, "package.json"),
3514
- path.resolve(process.cwd(), "package.json"),
3515
- path.resolve(process.cwd(), "..", "package.json"),
3516
- ];
3517
- for (const p of paths) {
3518
- if (fs.existsSync(p)) {
3519
- try {
3520
- const pkg = JSON.parse(fs.readFileSync(p, "utf-8"));
3521
- version = pkg.version;
3522
- break;
3523
- } catch {}
3524
- }
3525
- }
3526
- process.stdout.write(`
3527
- \x1b[1mSinth Compiler v${version}\x1b[0m
3528
-
3529
- \x1b[1mCommands:\x1b[0m
3530
- sinth build [files] [--out ./dist] [--prod] Compile .sinth pages
3531
- sinth dev [files] [--port 3000] Live-reload dev server
3532
- sinth check Lint without emitting
3533
- sinth init [name] Scaffold a new project
3534
- sinth version Print version
3535
- `);
3536
- break;
3537
- }
3538
- }
3539
- }
3540
-
3541
- // project scaffholding
3542
-
3543
- function scaffoldProject(root: string): void {
3544
- for (const d of ["pages", "components", "styles", "libraries", "assets"]) {
3545
- fs.mkdirSync(path.join(root, d), { recursive: true });
3546
- }
3547
-
3548
- fs.writeFileSync(path.join(root, "pages", "index.sinth"), `-- My Sinth Site
3549
- page
3550
-
3551
- import "../components/Navbar.sinth"
3552
- import css "../styles/reset.css"
3553
-
3554
- title = "My Site"
3555
- fav = "assets/favicon.ico"
3556
- descr = "Built with Sinth v1.0.0."
3557
-
3558
- var int score = 0
3559
- var str message = "Click to begin"
3560
-
3561
- Navbar
3562
-
3563
- Hero {
3564
- Heading(level: 1) { "Welcome to Sinth" }
3565
- Paragraph { "A declarative, component-based web UI language." }
3566
- Button(onClick: "handleClick") { "Get Started" }
3567
- Paragraph(id: "score-display") { message }
3568
- }
3569
-
3570
- Main {
3571
- Section {
3572
- Heading(level: 2) { "Features" }
3573
- CardGrid {
3574
- -- Add Card components here
3575
- }
3576
- }
3577
- }
3578
-
3579
- style {
3580
- section.hero {
3581
- padding: "4rem 2rem"
3582
- textAlign: "center"
3583
- backgroundColor: "#f0f4ff"
3584
- }
3585
- main {
3586
- maxWidth: "1100px"
3587
- margin: "0 auto"
3588
- padding: "2rem"
3589
- }
3590
- }
3591
-
3592
- script {
3593
- function handleClick() {
3594
- score += 1
3595
- message = "Score: " + score
3596
- sinthRender()
3597
- }
3598
- }
3599
- `);
3600
-
3601
- fs.writeFileSync(path.join(root, "components", "Navbar.sinth"), `-- Navbar component
3602
-
3603
- component Navbar {
3604
- Header {
3605
- Nav {
3606
- Link(href: "/", class: "logo") { "MySite" }
3607
- Div(class: "nav-links") {
3608
- NavLink(href: "/") { "Home" }
3609
- NavLink(href: "/about") { "About" }
3610
- }
3611
- }
3612
- }
3613
-
3614
- style {
3615
- header {
3616
- display: "flex"
3617
- alignItems: "center"
3618
- padding: "1rem 2rem"
3619
- backgroundColor: "#1a1a2e"
3620
- color: "white"
3621
- }
3622
- .logo {
3623
- fontSize: "1.5rem"
3624
- fontWeight: "700"
3625
- color: "white"
3626
- textDecoration: "none"
3627
- }
3628
- .nav-links {
3629
- marginLeft: "auto"
3630
- display: "flex"
3631
- gap: "1.5rem"
3632
- }
3633
- .nav-links a {
3634
- color: "rgba(255,255,255,0.8)"
3635
- textDecoration: "none"
3636
- }
3637
- }
3638
- }
3639
- `);
3640
-
3641
- fs.writeFileSync(path.join(root, "components", "Card.sinth"), `-- Card component
3642
-
3643
- component Card(title, color = "blue") {
3644
- Div(class: "card") {
3645
- Heading(level: 3) { "$title" }
3646
- Div(class: "card-body") { "$slot" }
3647
- }
3648
-
3649
- style {
3650
- .card {
3651
- backgroundColor: "#f7f7f7"
3652
- borderRadius: "1rem"
3653
- padding: "1.5rem"
3654
- marginBottom: "1rem"
3655
- }
3656
- .card:hover {
3657
- boxShadow: "0 4px 16px rgba(0,0,0,0.1)"
3658
- }
3659
- .card-body {
3660
- marginTop: "0.75rem"
3661
- }
3662
- }
3663
- }
3664
- `);
3665
-
3666
- fs.writeFileSync(path.join(root, "styles", "reset.css"),
3667
- `*, *::before, *::after { box-sizing: border-box; }\nbody { margin: 0; font-family: system-ui, sans-serif; line-height: 1.6; }\nimg { max-width: 100%; display: block; }\n`
3668
- );
3669
-
3670
- fs.writeFileSync(path.join(root, "sinth.config.json"),
3671
- JSON.stringify({ outDir: "./dist", libraryPaths: ["./libraries"], minify: false }, null, 2)
3672
- );
3673
-
3674
- fs.writeFileSync(path.join(root, ".gitignore"), "dist/\nnode_modules/\n");
3675
-
3676
- fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({
3677
- name: path.basename(root).toLowerCase().replace(/\s+/g, "-"),
3678
- version: "1.0.0",
3679
- scripts: { build: "sinth build", dev: "sinth dev" },
3680
- devDependencies: { "ts-node": "^10.0.0", typescript: "^5.0.0", sass: "^1.70.0" },
3681
- }, null, 2));
3682
-
3683
- process.stdout.write(`
3684
- \x1b[32m✓ Sinth project scaffolded at ${path.basename(root)}/\x1b[0m
3685
-
3686
- \x1b[1mNext steps:\x1b[0m
3687
- cd ${path.basename(root)}
3688
- sinth dev
3689
- sinth build
3690
- `);
3691
- }
3692
-
3693
-
3694
-
3695
-
3696
- main().catch(e => {
3697
- process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
3698
- process.exit(1);
3699
- });