@yannosay/sinth 3.0.1 → 4.0.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/README.md CHANGED
@@ -1,10 +1,6 @@
1
1
  # ![Sinth Repo Cover](/.github/assets/repo_cover.png)
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@yannosay/sinth?color=6366f1&label=&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth)
4
- [![npm downloads](https://img.shields.io/npm/dw/@yannosay/sinth?color=818cf8&label=&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth)
5
- [![license](https://img.shields.io/npm/l/@yannosay/sinth?color=a78bfa&label=&style=for-the-badge)](https://github.com/yannosay/sinth/blob/main/LICENSE)
6
- [![Commits](https://img.shields.io/github/commit-activity/m/yannosay/sinth?color=a78bfa&style=for-the-badge)](https://github.com/yannosay/sinth/commits)
7
- [![PRs](https://img.shields.io/github/issues-pr-raw/yannosay/sinth?color=818cf8&style=for-the-badge)](https://github.com/yannosay/sinth/pulls)
3
+ [![npm version](https://img.shields.io/npm/v/@yannosay/sinth?color=6366f1&label=&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth) [![npm downloads](https://img.shields.io/npm/dt/@yannosay/sinth?color=818cf8&label=Downloads&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth) [![license](https://img.shields.io/npm/l/@yannosay/sinth?color=a78bfa&label=&style=for-the-badge)](https://github.com/yannosay/sinth/blob/main/LICENSE) [![Commits](https://img.shields.io/github/commit-activity/m/yannosay/sinth?color=a78bfa&style=for-the-badge)](https://github.com/yannosay/sinth/commits) [![PRs](https://img.shields.io/github/issues-pr-raw/yannosay/sinth?color=818cf8&style=for-the-badge)](https://github.com/yannosay/sinth/pulls)
8
4
 
9
5
  ## Sinth Compiler
10
6
 
@@ -97,4 +93,4 @@ If you have encountered a problem and need assistance, please open an issue in [
97
93
 
98
94
  [AGPL-3.0](https://github.com/Yannosay/sinth/blob/main/LICENSE)
99
95
 
100
- Notice: All generated output you made with Sinth is entirely your intellectual property and free of any license obligations of Sinth.
96
+ **Notice**: All generated output you made with Sinth is entirely your intellectual property and free of any license obligations of Sinth.
package/dist/cli.js CHANGED
@@ -35,6 +35,8 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  const fs = __importStar(require("fs"));
37
37
  const path = __importStar(require("path"));
38
+ const https = __importStar(require("https"));
39
+ const child_process_1 = require("child_process");
38
40
  const types_1 = require("./core/types");
39
41
  const cli_compiler_1 = require("./core/cli-compiler");
40
42
  const server_1 = require("./server");
@@ -46,8 +48,9 @@ function loadConfig(root) {
46
48
  try {
47
49
  return JSON.parse(fs.readFileSync(cfgPath, "utf-8"));
48
50
  }
49
- catch {
51
+ catch (e) {
50
52
  types_1.SinthWarning.emit("Could not parse sinth.config.json");
53
+ console.error(e);
51
54
  }
52
55
  }
53
56
  return {};
@@ -80,7 +83,7 @@ async function main() {
80
83
  (0, update_check_1.checkForUpdate)(pkg4.version);
81
84
  }
82
85
  if (nonSinth.length > 0)
83
- process.stdout.write(`\x1b[33mSkipping non-.sinth files:\x1b[0m ${nonSinth.join(", ")}\n`);
86
+ process.stdout.write(`\u001b[33mSkipping non-.sinth files:\u001b[0m ${nonSinth.join(", ")}\n`);
84
87
  const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
85
88
  const pages = fileArgs.length > 0
86
89
  ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
@@ -104,23 +107,23 @@ async function main() {
104
107
  const out = path.join(outDir, rel);
105
108
  fs.mkdirSync(path.dirname(out), { recursive: true });
106
109
  fs.writeFileSync(out, html);
107
- process.stdout.write(` \x1b[32m✓\x1b[0m ${rel}\n`);
110
+ process.stdout.write(` \u001b[32m✓\u001b[0m ${rel}\n`);
108
111
  built++;
109
112
  }
110
113
  catch (e) {
111
- process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${e.message}\n`);
114
+ process.stderr.write(` \u001b[31m✗\u001b[0m ${path.relative(cwd, p)}\n${e.message}\n`);
112
115
  hadError = true;
113
116
  }
114
117
  }
115
118
  if (sharedRuntimes.length > 0) {
116
119
  const combined = sharedRuntimes.join("\n");
117
120
  fs.writeFileSync(path.join(outDir, "sinth-runtime.js"), combined);
118
- process.stdout.write(` \x1b[32m✓\x1b[0m sinth-runtime.js (shared)\n`);
121
+ process.stdout.write(` \u001b[32m✓\u001b[0m sinth-runtime.js (shared)\n`);
119
122
  }
120
123
  const assetsIn = path.join(cwd, "assets"), assetsOut = path.join(outDir, "assets");
121
124
  if (fs.existsSync(assetsIn)) {
122
125
  (0, cli_compiler_1.copyDir)(assetsIn, assetsOut);
123
- process.stdout.write(` \x1b[32m✓\x1b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
126
+ process.stdout.write(` \u001b[32m✓\u001b[0m assets/ → ${path.relative(cwd, assetsOut)}/\n`);
124
127
  }
125
128
  const libIn = path.join(cwd, "libraries"), libOut = path.join(outDir, "libraries");
126
129
  if (fs.existsSync(libIn)) {
@@ -131,15 +134,16 @@ async function main() {
131
134
  try {
132
135
  fs.unlinkSync(path.join(libOut, f));
133
136
  }
134
- catch { }
137
+ catch (e) {
138
+ console.warn(`Failed to delete ${f}:`, e);
139
+ }
135
140
  }
136
141
  }
137
- process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
142
+ process.stdout.write(` \u001b[32m✓\u001b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
138
143
  }
139
144
  const buildTime = ((Date.now() - buildStart) / 1000).toFixed(2);
140
- process.stdout.write(`\n\x1b[1mBuilt ${built} page(s)\x1b[0m${hadError ? " with errors" : ""} \x1b[2min ${buildTime}s\x1b[0m\n`);
141
- process.exit(hadError ? 1 : 0);
142
- break;
145
+ process.stdout.write(`\n\u001b[1mBuilt ${built} page(s)\u001b[0m${hadError ? " with errors" : ""} \u001b[2min ${buildTime}s\u001b[0m\n`);
146
+ return process.exit(hadError ? 1 : 0);
143
147
  }
144
148
  case "dev": {
145
149
  const pkgPath3 = path.join(__dirname, "..", "package.json");
@@ -152,7 +156,7 @@ async function main() {
152
156
  ? fileArgs.map(f => path.resolve(cwd, f)).filter(f => fs.existsSync(f))
153
157
  : undefined;
154
158
  await (0, server_1.startDevServer)({ ...opts, port, files });
155
- break;
159
+ return;
156
160
  }
157
161
  case "check": {
158
162
  opts.checkOnly = true;
@@ -161,41 +165,39 @@ async function main() {
161
165
  for (const p of pages) {
162
166
  try {
163
167
  (0, cli_compiler_1.compileFile)(p, opts);
164
- process.stdout.write(` \x1b[32m✓\x1b[0m ${path.relative(cwd, p)}\n`);
168
+ process.stdout.write(` \u001b[32m✓\u001b[0m ${path.relative(cwd, p)}\n`);
165
169
  }
166
170
  catch (e) {
167
- process.stderr.write(` \x1b[31m✗\x1b[0m ${path.relative(cwd, p)}\n${e.message}\n`);
171
+ process.stderr.write(` \u001b[31m✗\u001b[0m ${path.relative(cwd, p)}\n${e.message}\n`);
168
172
  hadError = true;
169
173
  }
170
174
  }
171
- process.exit(hadError ? 1 : 0);
175
+ return process.exit(hadError ? 1 : 0);
172
176
  }
173
177
  case "update": {
174
178
  const pkgPath2 = path.join(__dirname, "..", "package.json");
175
179
  const current = fs.existsSync(pkgPath2) ? JSON.parse(fs.readFileSync(pkgPath2, "utf-8")).version : null;
176
- const https = require("https");
177
180
  https.get("https://registry.npmjs.org/@yannosay/sinth/latest", { timeout: 5000 }, (res) => {
178
181
  let data = "";
179
- res.on("data", (chunk) => data += chunk);
182
+ res.on("data", (chunk) => data += chunk.toString());
180
183
  res.on("end", () => {
181
184
  try {
182
185
  const latest = JSON.parse(data).version;
183
186
  if (latest === current) {
184
- process.stdout.write(`\x1b[32mAlready on latest version: ${current} ✓\x1b[0m\n`);
187
+ process.stdout.write(`\u001b[32mAlready on latest version: ${current} ✓\u001b[0m\n`);
185
188
  }
186
189
  else if (latest) {
187
- process.stdout.write(`\x1b[36mUpdating Sinth ${current} → ${latest}...\x1b[0m\n`);
188
- const { execSync } = require("child_process");
189
- execSync("npm install -g @yannosay/sinth@latest", { stdio: "inherit" });
190
- process.stdout.write(`\x1b[32m✓ Sinth updated to ${latest}!\x1b[0m\n`);
190
+ process.stdout.write(`\u001b[36mUpdating Sinth ${current} → ${latest}...\u001b[0m\n`);
191
+ (0, child_process_1.execSync)("npm install -g @yannosay/sinth@latest", { stdio: "inherit" });
192
+ process.stdout.write(`\u001b[32m✓ Sinth updated to ${latest}!\u001b[0m\n`);
191
193
  }
192
194
  }
193
195
  catch {
194
- process.stderr.write("\x1b[31mCould not check for updates.\x1b[0m\n");
196
+ process.stderr.write("\u001b[31mCould not check for updates.\u001b[0m\n");
195
197
  }
196
198
  });
197
- }).on("error", () => process.stderr.write("\x1b[31mCould not reach npm registry.\x1b[0m\n"));
198
- break;
199
+ }).on("error", () => process.stderr.write("\u001b[31mCould not reach npm registry.\u001b[0m\n"));
200
+ return;
199
201
  }
200
202
  case "version":
201
203
  case "--version":
@@ -209,11 +211,12 @@ async function main() {
209
211
  else {
210
212
  process.stdout.write("Sinth Compiler v1.0.0\n");
211
213
  }
212
- break;
214
+ return;
213
215
  }
214
216
  case "init": {
215
217
  await interactiveInit(cwd);
216
- break;
218
+ process.stdin.destroy();
219
+ return process.exit(0);
217
220
  }
218
221
  default: {
219
222
  let version = "1.0.0";
@@ -230,20 +233,22 @@ async function main() {
230
233
  version = pkg.version;
231
234
  break;
232
235
  }
233
- catch { }
236
+ catch {
237
+ // Ignore - use default version
238
+ }
234
239
  }
235
240
  }
236
241
  process.stdout.write(`
237
- \x1b[1mSinth Compiler v${version}\x1b[0m
242
+ \u001b[1mSinth Compiler v${version}\u001b[0m
238
243
 
239
- \x1b[1mCommands:\x1b[0m
244
+ \u001b[1mCommands:\u001b[0m
240
245
  sinth build [files] [--out ./dist] [--prod] [--shared-runtime] Compile .sinth pages
241
246
  sinth dev [files] [--port 3000] Live-reload dev server
242
247
  sinth check Lint without emitting
243
248
  sinth init [name] Scaffold a new project
244
249
  sinth version Print version
245
250
  `);
246
- break;
251
+ return;
247
252
  }
248
253
  }
249
254
  }
@@ -259,31 +264,29 @@ async function interactiveInit(cwd) {
259
264
  terminal: true,
260
265
  escapeCodeTimeout: 50,
261
266
  });
262
- process.stdout.write("\x1b[1m\n✨ Welcome to Sinth project setup!\n\n\x1b[0m");
263
- const rawName = await question(rl, "\x1b[45m\x1b[30m Project name: \x1b[0m ", "my-sinth-project");
267
+ process.stdout.write("\u001b[s\u001b[1m\n✨ Welcome to Sinth project setup!\n\n\u001b[0m");
268
+ const rawName = await question(rl, "\u001b[45m\u001b[30m Project name: \u001b[0m ", "my-sinth-project");
269
+ rl.close();
270
+ process.stdin.pause();
271
+ process.stdin.removeAllListeners();
272
+ process.stdin.read();
264
273
  process.stdout.write("\n");
265
274
  const projectName = rawName.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
266
- rl.close();
267
- const rl2 = readline.createInterface({
268
- input: process.stdin,
269
- output: process.stdout,
270
- terminal: true,
271
- escapeCodeTimeout: 50,
272
- });
273
- const preset = await select(rl2);
274
- rl2.close();
275
+ const preset = await select();
276
+ process.stdout.write("\u001b[u\u001b[0J");
275
277
  const root = path.resolve(cwd, projectName);
276
- process.stdout.write("\n");
277
278
  const start = Date.now();
278
279
  scaffoldByPreset(root, projectName, preset);
279
280
  const elapsed = ((Date.now() - start) / 1000).toFixed(2);
280
281
  process.stdout.write(`
281
- \x1b[32m✓ Sinth project scaffolded at \x1b[4m${projectName}/\x1b[0m\x1b[32m in ${elapsed}s\x1b[0m
282
+ \u001b[1m✨ Success!\u001b[0m
283
+
284
+ \u001b[45m\u001b[30m Project name: \u001b[0m ${projectName}
285
+ \u001b[43m\u001b[30m Preset: \u001b[0m ${preset}
286
+ \u001b[32m✓ ${projectName} scaffolded at \u001b[4m${projectName}/\u001b[0m\u001b[32m in ${elapsed}s\u001b[0m
282
287
 
283
- \x1b[1mNext steps:\x1b[0m
284
- cd ${projectName}
285
- sinth dev
286
- sinth build
288
+ \u001b[47m\u001b[30m Get started: \u001b[0m
289
+ \u001b[100m\u001b[37m sinth dev \u001b[0m to start dev server.
287
290
  `);
288
291
  }
289
292
  function question(rl, prompt, defaultVal) {
@@ -293,30 +296,30 @@ function question(rl, prompt, defaultVal) {
293
296
  });
294
297
  });
295
298
  }
296
- function select(rl) {
299
+ function select() {
297
300
  return new Promise((resolve) => {
298
301
  const items = PRESETS;
299
302
  let selected = 1;
300
303
  const prefix = " ";
301
- const cursor = "\x1b[36m❯\x1b[0m";
304
+ const cursor = "\u001b[36m❯\u001b[0m";
302
305
  const empty = " ";
303
306
  function render(first = false) {
304
307
  if (!first) {
305
- process.stdout.write(`\x1b[${items.length + 1}A`);
308
+ process.stdout.write(`\u001b[${items.length + 1}A`);
306
309
  }
307
- process.stdout.write(`\x1b[43m\x1b[30m Select preset: \x1b[0m\n`);
310
+ process.stdout.write(`\u001b[43m\u001b[30m Select preset: \u001b[0m\n`);
308
311
  for (let i = 0; i < items.length; i++) {
309
312
  const pointer = i === selected ? cursor : empty;
310
313
  const isFull = items[i].value === "full";
311
314
  let label;
312
315
  if (i === selected) {
313
- label = isFull ? `\x1b[1m\x1b[35m${items[i].label}\x1b[0m` : `\x1b[1m${items[i].label}\x1b[0m`;
316
+ label = isFull ? `\u001b[1m\u001b[35m${items[i].label}\u001b[0m` : `\u001b[1m${items[i].label}\u001b[0m`;
314
317
  }
315
318
  else {
316
319
  label = items[i].label;
317
320
  }
318
- const desc = `\x1b[2m- ${items[i].description}\x1b[0m`;
319
- process.stdout.write(`${prefix}${pointer} ${label} ${desc}\x1b[0K\n`);
321
+ const desc = `\u001b[2m- ${items[i].description}\u001b[0m`;
322
+ process.stdout.write(`${prefix}${pointer} ${label} ${desc}\u001b[0K\n`);
320
323
  }
321
324
  }
322
325
  process.stdin.setRawMode(true);
@@ -334,9 +337,9 @@ function select(rl) {
334
337
  }
335
338
  else if (str === "\r" || str === "\n") {
336
339
  process.stdin.setRawMode(false);
337
- process.stdin.pause();
338
- process.stdin.removeListener("data", onData);
339
- process.stdout.write(`\x1b[${items.length - selected}A\x1b[0J`);
340
+ process.stdin.removeAllListeners("data");
341
+ process.stdin.resume();
342
+ process.stdout.write(`\u001b[${items.length + 1}A\u001b[0J`);
340
343
  resolve(items[selected].value);
341
344
  }
342
345
  else if (str === "\u0003") {
@@ -501,6 +504,6 @@ component Card(title, color = "blue") {
501
504
  `);
502
505
  }
503
506
  main().catch(e => {
504
- process.stderr.write(`\x1b[31m${e.message}\x1b[0m\n`);
507
+ process.stderr.write(`\u001b[31m${e.message}\u001b[0m\n`);
505
508
  process.exit(1);
506
509
  });
@@ -122,7 +122,9 @@ function compileFile(filePath, opts) {
122
122
  : [JSON.parse(v.substring(8))];
123
123
  exprs.forEach(e => collectExprVars(e, vars));
124
124
  }
125
- catch { }
125
+ catch {
126
+ void 0;
127
+ }
126
128
  }
127
129
  }
128
130
  });
@@ -248,6 +250,9 @@ function compileFile(filePath, opts) {
248
250
  checkTypeInChild(child, allVarDecls, functionDefs);
249
251
  }
250
252
  }
253
+ for (const vd of pageVarDecls) {
254
+ checkVarInitType(vd, allVarDecls, functionDefs);
255
+ }
251
256
  for (const use of file.uses) {
252
257
  checkTypeInChild(use, allVarDecls, functionDefs);
253
258
  }
@@ -279,6 +284,54 @@ function compileFile(filePath, opts) {
279
284
  return "bool";
280
285
  return null;
281
286
  }
287
+ function checkVarInitType(vd, varDecls, functionDefs) {
288
+ if (!vd.value)
289
+ return;
290
+ if (vd.value.kind === "num") {
291
+ if (vd.varType !== "int")
292
+ throw new types_1.SinthError(`Cannot assign number to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
293
+ return;
294
+ }
295
+ if (vd.value.kind === "bool") {
296
+ if (vd.varType !== "bool")
297
+ throw new types_1.SinthError(`Cannot assign boolean to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
298
+ return;
299
+ }
300
+ if (vd.value.kind !== "str")
301
+ return;
302
+ const raw = vd.value.value;
303
+ if (raw.startsWith("__EXPR__")) {
304
+ let expr;
305
+ try {
306
+ expr = JSON.parse(raw.substring(8));
307
+ }
308
+ catch {
309
+ return;
310
+ }
311
+ const exprType = inferType(expr, varDecls, functionDefs);
312
+ if (exprType && exprType !== vd.varType) {
313
+ throw new types_1.SinthError(`Cannot assign expression of type '${exprType}' to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
314
+ }
315
+ return;
316
+ }
317
+ if (raw.startsWith("__VAR__")) {
318
+ const varName = raw.substring(7);
319
+ const exprType = inferType({ kind: "variable", name: varName }, varDecls, functionDefs);
320
+ if (exprType && exprType !== vd.varType) {
321
+ throw new types_1.SinthError(`Cannot assign variable '${varName}' of type '${exprType}' to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
322
+ }
323
+ return;
324
+ }
325
+ if (raw.startsWith("__ARR__")) {
326
+ if (vd.varType !== "str[]") {
327
+ throw new types_1.SinthError(`Cannot assign array literal to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
328
+ }
329
+ return;
330
+ }
331
+ if (vd.varType !== "str" && vd.varType !== "str[]") {
332
+ throw new types_1.SinthError(`Cannot assign string value to variable '${vd.name}' of type '${vd.varType}'`, vd.loc);
333
+ }
334
+ }
282
335
  function checkCallArgs(fnDef, args, loc, varDecls, functionDefs) {
283
336
  for (let i = 0; i < fnDef.params.length && i < args.length; i++) {
284
337
  const param = fnDef.params[i];
@@ -295,36 +348,94 @@ function compileFile(filePath, opts) {
295
348
  }
296
349
  }
297
350
  }
298
- function checkTypeInExpr(expr, varDecls, functionDefs) {
351
+ function checkTypeInExpr(expr, varDecls, functionDefs, loc) {
299
352
  if (!expr)
300
353
  return;
354
+ if (expr.kind === "assign" && expr.target) {
355
+ const parts = expr.target.split('.');
356
+ const rootVar = parts[0];
357
+ const vd = varDecls.find(v => v.name === rootVar);
358
+ if (vd) {
359
+ let expected = vd.varType;
360
+ if (parts.length > 1) {
361
+ if (expected === "obj")
362
+ expected = "str";
363
+ else if (expected === "str[]" && parts[1] === "length")
364
+ expected = "int";
365
+ }
366
+ const rhsType = inferType(expr.right, varDecls, functionDefs);
367
+ if (rhsType && expected !== rhsType) {
368
+ if (expr.op === "+=" && expected === "str") { /* allow string += any */ }
369
+ else if (expr.op === "-=") {
370
+ if (expected !== "int") {
371
+ throw new types_1.SinthError(`Cannot use '-=' on non‑int variable '${expr.target}'`, loc || { file: "", line: 0, col: 0 });
372
+ }
373
+ else if (rhsType !== "int") {
374
+ throw new types_1.SinthError(`Right operand of '-=' must be int, got '${rhsType}'`, loc || { file: "", line: 0, col: 0 });
375
+ }
376
+ }
377
+ else {
378
+ throw new types_1.SinthError(`Cannot assign value of type '${rhsType}' to variable '${expr.target}' of type '${expected}'`, loc || { file: "", line: 0, col: 0 });
379
+ }
380
+ }
381
+ }
382
+ }
383
+ if (expr.kind === "binary") {
384
+ const leftType = inferType(expr.left, varDecls, functionDefs);
385
+ const rightType = inferType(expr.right, varDecls, functionDefs);
386
+ if (leftType && rightType) {
387
+ const op = expr.op;
388
+ if (["==", "!=", "<", ">", "<=", ">="].includes(op)) {
389
+ if (leftType !== rightType) {
390
+ throw new types_1.SinthError(`Cannot compare values of type '${leftType}' and '${rightType}' with '${op}'`, loc || { file: "", line: 0, col: 0 });
391
+ }
392
+ }
393
+ else if (["and", "or"].includes(op)) {
394
+ if (leftType !== "bool")
395
+ throw new types_1.SinthError(`Left side of '${op}' must be bool, got '${leftType}'`, loc || { file: "", line: 0, col: 0 });
396
+ if (rightType !== "bool")
397
+ throw new types_1.SinthError(`Right side of '${op}' must be bool, got '${rightType}'`, loc || { file: "", line: 0, col: 0 });
398
+ }
399
+ else if (["-", "*", "/", "%"].includes(op)) {
400
+ if (leftType !== "int" || rightType !== "int") {
401
+ throw new types_1.SinthError(`Arithmetic operator '${op}' requires int operands, got '${leftType}' and '${rightType}'`, loc || { file: "", line: 0, col: 0 });
402
+ }
403
+ }
404
+ }
405
+ }
406
+ if (expr.kind === "unary" && expr.op === "not") {
407
+ const operandType = inferType(expr.operand, varDecls, functionDefs);
408
+ if (operandType && operandType !== "bool") {
409
+ throw new types_1.SinthError(`'not' operator requires bool operand, got '${operandType}'`, loc || { file: "", line: 0, col: 0 });
410
+ }
411
+ }
301
412
  if (expr.kind === "call" && expr.callee?.kind === "variable" && expr.callee.name) {
302
413
  const fnDef = functionDefs.find(f => f.name === expr.callee.name);
303
414
  if (fnDef)
304
- checkCallArgs(fnDef, expr.args ?? [], fnDef.loc, varDecls, functionDefs);
415
+ checkCallArgs(fnDef, expr.args ?? [], loc || fnDef.loc, varDecls, functionDefs);
305
416
  }
306
417
  if (expr.left)
307
- checkTypeInExpr(expr.left, varDecls, functionDefs);
418
+ checkTypeInExpr(expr.left, varDecls, functionDefs, loc);
308
419
  if (expr.right)
309
- checkTypeInExpr(expr.right, varDecls, functionDefs);
420
+ checkTypeInExpr(expr.right, varDecls, functionDefs, loc);
310
421
  if (expr.operand)
311
- checkTypeInExpr(expr.operand, varDecls, functionDefs);
422
+ checkTypeInExpr(expr.operand, varDecls, functionDefs, loc);
312
423
  if (expr.args)
313
- expr.args.forEach(a => checkTypeInExpr(a, varDecls, functionDefs));
424
+ expr.args.forEach(a => checkTypeInExpr(a, varDecls, functionDefs, loc));
314
425
  }
315
426
  function checkTypeInChild(child, varDecls, functionDefs) {
316
427
  if (child.kind === "expr" && child.expression) {
317
- checkTypeInExpr(child.expression, varDecls, functionDefs);
428
+ checkTypeInExpr(child.expression, varDecls, functionDefs, child.loc);
318
429
  }
319
430
  if (child.kind === "assign_stmt" && child.expression) {
320
- checkTypeInExpr(child.expression, varDecls, functionDefs);
431
+ checkTypeInExpr(child.expression, varDecls, functionDefs, child.loc);
321
432
  }
322
433
  if (child.kind === "return" && child.expression) {
323
434
  checkTypeInExpr(child.expression, varDecls, functionDefs);
324
435
  }
325
436
  if (child.kind === "if") {
326
437
  const ib = child;
327
- checkTypeInExpr(ib.condition, varDecls, functionDefs);
438
+ checkTypeInExpr(ib.condition, varDecls, functionDefs, ib.loc);
328
439
  ib.body.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
329
440
  ib.elseBody?.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
330
441
  }
@@ -337,9 +448,11 @@ function compileFile(filePath, opts) {
337
448
  if (a.value?.kind === "str" && a.value.value.startsWith("__EXPR__")) {
338
449
  try {
339
450
  const expr = JSON.parse(a.value.value.substring(8));
340
- checkTypeInExpr(expr, varDecls, functionDefs);
451
+ checkTypeInExpr(expr, varDecls, functionDefs, a.loc || u.loc);
452
+ }
453
+ catch {
454
+ void 0;
341
455
  }
342
- catch { }
343
456
  }
344
457
  });
345
458
  u.children.forEach(c => checkTypeInChild(c, varDecls, functionDefs));
@@ -347,15 +460,19 @@ function compileFile(filePath, opts) {
347
460
  }
348
461
  const enableDiffing = file.meta.some(m => m.key === "domdiffing" &&
349
462
  (m.value.kind === "bool" ? m.value.value === true : (m.value.kind === "str" && m.value.value === "true")));
463
+ const REACTIVE = /^if\b|^\{|^[a-zA-Z_$][a-zA-Z0-9_$]*\s*(?:[+\-*/%]?=|<<=|>>=|>>>=|&&=|\|\|=|\?\?=)/;
350
464
  const topLevelLogicIfs = [];
351
465
  file.scripts = file.scripts.filter(s => {
352
466
  const trimmed = s.raw.trim();
353
- if (/^if\s*\(/.test(trimmed) || /^\{/.test(trimmed)) {
467
+ if (REACTIVE.test(trimmed)) {
354
468
  topLevelLogicIfs.push(trimmed);
355
469
  return false;
356
470
  }
357
471
  return true;
358
472
  });
473
+ if (file.initLogic) {
474
+ file.initLogic = file.initLogic.filter(s => !REACTIVE.test(s.trim()));
475
+ }
359
476
  const ctx = {
360
477
  allDefs, functionDefs, customEls, cssLinks, jsLinks,
361
478
  scopeHash: hash,
@@ -381,14 +498,24 @@ function compileFile(filePath, opts) {
381
498
  return { html: h };
382
499
  }
383
500
  const headData = (0, head_builder_1.buildHeadData)(file.meta);
384
- const bodyHTML = file.uses.map(u => (0, compiler_1.renderCompUse)(u, ctx, new Map(), 0)).join("\n");
501
+ const flatUses = [];
502
+ function flattenUses(child) {
503
+ if (child.kind === "use" && child.name === "__IF_ROOT__") {
504
+ child.children.forEach(flattenUses);
505
+ }
506
+ else {
507
+ flatUses.push(child);
508
+ }
509
+ }
510
+ file.uses.forEach(flattenUses);
511
+ const bodyHTML = flatUses.map(u => (0, compiler_1.renderChild)(u, ctx, new Map(), 0)).join("\n");
385
512
  const pageCSS = file.styles.map(s => (0, style_processor_1.processStyleBlock)(s, hash, new Map())).join("\n");
386
513
  const scopedCSS = [pageCSS, ...ctx.extraCSS].filter(c => c.trim()).join("\n");
387
514
  const { componentScripts, pageScripts } = (0, compiler_1.collectScripts)(file, allDefs);
388
515
  // collect all assigned variables for default-value warnings
389
516
  const assignedVars = new Set();
390
517
  for (const s of file.scripts) {
391
- for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+\-]?=)/g))
518
+ for (const m of s.raw.matchAll(/\b([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:[+-]?=)/g))
392
519
  assignedVars.add(m[1]);
393
520
  }
394
521
  for (const v of file.varDecls) {
@@ -424,6 +551,7 @@ function compileFile(filePath, opts) {
424
551
  varDecls: pageVarDecls,
425
552
  bodyHTML,
426
553
  logicBlocks: ctx.logicBlocks,
554
+ initBlocks: ctx.initBlocks,
427
555
  mixedBlocks: ctx.mixedBlocks,
428
556
  assignedVars,
429
557
  exprRegistry: ctx.exprRegistry,
@@ -113,6 +113,7 @@ function inlineFunctionBody(fnDef, args, ctx) {
113
113
  statements.push((0, expr_1.compileIfToJS)(substituted, ctx.loopVars, ctx.namespace, ctx.declaredVars));
114
114
  }
115
115
  else if (substituted.kind === "return") {
116
+ void 0;
116
117
  }
117
118
  else if (substituted.kind === "for") {
118
119
  const fl = substituted;
@@ -268,7 +269,9 @@ function renderAttr(attr, paramMap, ctx) {
268
269
  return `data-sinth-step="${stepExprId}"`;
269
270
  }
270
271
  }
271
- catch { }
272
+ catch {
273
+ void 0;
274
+ }
272
275
  }
273
276
  }
274
277
  if (name === "delay") {
@@ -284,7 +287,9 @@ function renderAttr(attr, paramMap, ctx) {
284
287
  const id = registerExpr(ctx, expr);
285
288
  return `data-sinth-delay-expr-id="${id}"`;
286
289
  }
287
- catch { }
290
+ catch {
291
+ void 0;
292
+ }
288
293
  }
289
294
  const id = registerExpr(ctx, { kind: "variable", name: v });
290
295
  return `data-sinth-delay-expr-id="${id}"`;
@@ -292,9 +297,6 @@ function renderAttr(attr, paramMap, ctx) {
292
297
  if (name === "hide") {
293
298
  if (value === null)
294
299
  return `data-sinth-hide=""`;
295
- if (value && value.kind === "bool") {
296
- return value.value ? `data-sinth-hide=""` : "";
297
- }
298
300
  if (value?.kind === "str") {
299
301
  const v = value.value;
300
302
  if (v === "true")
@@ -340,14 +342,16 @@ function renderAttr(attr, paramMap, ctx) {
340
342
  return `data-sinth-fullscreen-sync="${(0, utils_1.escAttr)(expr.name)}"`;
341
343
  }
342
344
  }
343
- catch { }
345
+ catch {
346
+ void 0;
347
+ }
344
348
  }
345
349
  return `data-sinth-fullscreen-sync="${(0, utils_1.escAttr)(raw)}"`;
346
350
  }
347
351
  return "";
348
352
  }
349
353
  if (name === "checked") {
350
- return value?.kind === "bool" && value.value ? "checked" : "";
354
+ return "";
351
355
  }
352
356
  if (value.kind === "num")
353
357
  return `${name}="${value.value}"`;
@@ -392,7 +396,9 @@ function renderAttr(attr, paramMap, ctx) {
392
396
  return `${ev}="(function(){ ${jsExprs.replace(/"/g, "&quot;")}${bumps}; ${renderFn}(); })()"`;
393
397
  return `${name}="${(0, utils_1.escAttr)(jsExprs)}"`;
394
398
  }
395
- catch { }
399
+ catch {
400
+ void 0;
401
+ }
396
402
  }
397
403
  if (raw.startsWith("__EXPR__")) {
398
404
  const exprJson = raw.substring("__EXPR__".length);
@@ -442,7 +448,9 @@ function renderAttr(attr, paramMap, ctx) {
442
448
  }
443
449
  return `${name}="${(0, utils_1.escAttr)(jsExpr)}"`;
444
450
  }
445
- catch { }
451
+ catch {
452
+ void 0;
453
+ }
446
454
  }
447
455
  raw = (0, utils_1.interpolateAttr)(raw, paramMap);
448
456
  const ev = eventAttrName(name);
@@ -551,6 +559,13 @@ function renderChild(child, ctx, params, depth) {
551
559
  ctx.logicBlocks.push((0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars) + ";");
552
560
  return "";
553
561
  }
562
+ const fnDef = fnName ? ctx.functionDefs.find(f => f.name === fnName) : undefined;
563
+ if (!fnDef) {
564
+ if (!ctx.initBlocks)
565
+ ctx.initBlocks = [];
566
+ ctx.initBlocks.push(`if(!_memo_${fnName}_done){${(0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars)};_memo_${fnName}_done=true;}`);
567
+ return "";
568
+ }
554
569
  const js = (0, expr_1.compileExprToJS)(child.expression, undefined, ctx.namespace, ctx.declaredVars);
555
570
  ctx.logicBlocks.push(`if(!_memo_${fnName}_done){_memo_${fnName}=${js};_memo_${fnName}_done=true;}`);
556
571
  const exprId = registerExpr(ctx, { kind: "variable", name: `_memo_${fnName}` });
@@ -640,7 +655,9 @@ function renderChild(child, ctx, params, depth) {
640
655
  const substituted = substituteExpr(expr, pm);
641
656
  return { ...a, value: { kind: "str", value: "__EXPR__" + JSON.stringify(substituted) } };
642
657
  }
643
- catch { }
658
+ catch {
659
+ void 0;
660
+ }
644
661
  }
645
662
  if (raw.startsWith("__ACTION_JS__")) {
646
663
  return { ...a, value: { kind: "str", value: raw } };
@@ -651,7 +668,9 @@ function renderChild(child, ctx, params, depth) {
651
668
  const substituted = exprs.map(e => substituteExpr(e, pm));
652
669
  return { ...a, value: { kind: "str", value: "__MULTI_EXPR__" + JSON.stringify(substituted) } };
653
670
  }
654
- catch { }
671
+ catch {
672
+ void 0;
673
+ }
655
674
  }
656
675
  for (const [pn, pv] of pm) {
657
676
  if (pv.startsWith("__LIT__"))
@@ -724,11 +743,15 @@ function renderChild(child, ctx, params, depth) {
724
743
  function renderIfBlock(ifBlock, ctx, params, depth) {
725
744
  if (depth > 64)
726
745
  throw new types_1.SinthError("Maximum if-block nesting depth (64) exceeded.", ifBlock.loc);
727
- const condJS = (0, expr_1.compileExprToJS)(ifBlock.condition, undefined, ctx.namespace, ctx.declaredVars);
728
746
  const allChildren = [...ifBlock.body, ...(ifBlock.elseBody ?? [])];
729
747
  const hasAssign = allChildren.some(c => c.kind === "assign_stmt");
748
+ const hasExprAssign = allChildren.some(c => c.kind === "expr" && c.expression?.kind === "assign");
730
749
  const hasComp = allChildren.some(c => c.kind === "use");
731
- if (!hasAssign && !hasComp) {
750
+ if (!hasComp) {
751
+ ctx.logicBlocks.push((0, expr_1.compileIfToJS)(ifBlock, undefined, ctx.namespace, ctx.declaredVars));
752
+ return "";
753
+ }
754
+ if (!hasAssign && !hasExprAssign && !hasComp) {
732
755
  const tplId = ctx.ifIdCounter++;
733
756
  const condId = registerExpr(ctx, ifBlock.condition);
734
757
  const bodyHTML = ifBlock.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
@@ -737,11 +760,6 @@ function renderIfBlock(ifBlock, ctx, params, depth) {
737
760
  return (`<template data-sinth-if-id="${tplId}" data-sinth-if-expr="${condId}"${persistAttr}>${bodyHTML}</template>` +
738
761
  (elseHTML ? `<template data-sinth-else data-sinth-if-id="${tplId}">${elseHTML}</template>` : ""));
739
762
  }
740
- // pure logic
741
- if (hasAssign && !hasComp) {
742
- ctx.logicBlocks.push((0, expr_1.compileIfToJS)(ifBlock));
743
- return "";
744
- }
745
763
  // pure DOM (components need replace/persist/delay handling)
746
764
  if (!hasAssign && hasComp) {
747
765
  const tplId = ctx.ifIdCounter++;
@@ -768,7 +786,7 @@ function renderIfBlock(ifBlock, ctx, params, depth) {
768
786
  return true;
769
787
  return u.attrs.some(a => a.name === "bind" || a.name === "model" || a.name === "fullscreenSync");
770
788
  });
771
- let persistAttr = (ifBlock.persist || hasStatefulComp) ? ` data-sinth-if-persist="true"` : "";
789
+ const persistAttr = (ifBlock.persist || hasStatefulComp) ? ` data-sinth-if-persist="true"` : "";
772
790
  const firstComp = ifBlock.body.find(c => c.kind === "use");
773
791
  if (firstComp) {
774
792
  const idAttr = firstComp.attrs.find(a => a.name === "id");
@@ -1041,7 +1059,9 @@ function renderCompUse(use, ctx, params, depth) {
1041
1059
  if (expr.kind === "variable" && expr.name)
1042
1060
  vName = expr.name;
1043
1061
  }
1044
- catch { }
1062
+ catch {
1063
+ void 0;
1064
+ }
1045
1065
  }
1046
1066
  const varDecl = ctx.varDecls?.find(v => v.name === vName);
1047
1067
  if (!use.attrs.some(a => a.name === "type")) {
@@ -1086,7 +1106,7 @@ function renderCompUse(use, ctx, params, depth) {
1086
1106
  // Resolve bound variable name (same pattern as Input's bind/model)
1087
1107
  let boundVarName = null;
1088
1108
  if (checkedAttr && checkedAttr.value?.kind === "str") {
1089
- let raw = checkedAttr.value.value;
1109
+ const raw = checkedAttr.value.value;
1090
1110
  if (raw.startsWith("__EXPR__")) {
1091
1111
  try {
1092
1112
  const expr = JSON.parse(raw.substring(8));
@@ -1094,7 +1114,9 @@ function renderCompUse(use, ctx, params, depth) {
1094
1114
  boundVarName = expr.name;
1095
1115
  }
1096
1116
  }
1097
- catch { }
1117
+ catch {
1118
+ void 0;
1119
+ }
1098
1120
  }
1099
1121
  else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
1100
1122
  boundVarName = raw;
@@ -1117,14 +1139,16 @@ function renderCompUse(use, ctx, params, depth) {
1117
1139
  }
1118
1140
  }
1119
1141
  if (onChangeAttr && onChangeAttr.value?.kind === "str") {
1120
- let raw = onChangeAttr.value.value;
1142
+ const raw = onChangeAttr.value.value;
1121
1143
  if (raw.startsWith("__EXPR__")) {
1122
1144
  try {
1123
1145
  const expr = JSON.parse(raw.substring(8));
1124
1146
  const jsExpr = (0, expr_1.compileExprToJS)(expr, undefined, ctx.namespace, ctx.declaredVars);
1125
1147
  attrParts.push(`onchange="(function(){ ${jsExpr}; ${renderFn}(); })(event)"`);
1126
1148
  }
1127
- catch { }
1149
+ catch {
1150
+ void 0;
1151
+ }
1128
1152
  }
1129
1153
  else {
1130
1154
  attrParts.push(`onchange="${(0, utils_1.escAttr)(raw)};${renderFn}()"`);
@@ -1218,7 +1242,7 @@ function extractFunctionNames(js) {
1218
1242
  return names;
1219
1243
  }
1220
1244
  function buildRuntime(opts) {
1221
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
1245
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS, initBlocks } = opts;
1222
1246
  const ns = opts.namespace ? "_" + opts.namespace : "";
1223
1247
  const renderFn = "sinthRender" + ns;
1224
1248
  const needsMixed = mixedBlocks.length > 0;
@@ -1282,8 +1306,16 @@ function buildRuntime(opts) {
1282
1306
  if (matches)
1283
1307
  matches.forEach(m => memoVars.add(m));
1284
1308
  }
1309
+ for (const ib of (initBlocks || [])) {
1310
+ let matches = ib.match(/_memo_(\w+)/g);
1311
+ if (matches)
1312
+ matches.forEach(m => memoVars.add(m));
1313
+ matches = ib.match(/_memo_(\w+)_done/g);
1314
+ if (matches)
1315
+ matches.forEach(m => memoVars.add(m));
1316
+ }
1285
1317
  for (const e of exprRegistry) {
1286
- let matches = e.match(/_memo_(\w+)/g);
1318
+ const matches = e.match(/_memo_(\w+)/g);
1287
1319
  if (matches)
1288
1320
  matches.forEach(m => memoVars.add(m));
1289
1321
  }
@@ -1310,8 +1342,8 @@ function buildRuntime(opts) {
1310
1342
  .filter(Boolean)
1311
1343
  .join("\n ");
1312
1344
  const renderBody = (0, render_1.buildRenderBody)({
1313
- bodyHTML, logicBlocks, mixedBlocks,
1314
- needsLogic, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1345
+ bodyHTML, logicBlocks: [], mixedBlocks,
1346
+ needsLogic: false, needsMixed, needsIf, needsFor, needsExpr, needsDelay,
1315
1347
  exprVarUpdates: exprVarUpdates || undefined,
1316
1348
  ns
1317
1349
  });
@@ -1337,8 +1369,9 @@ function buildRuntime(opts) {
1337
1369
  ? `let __X${ns} = [${exprRegistry.map((js) => `function(_ctx){ return ${js}; }`).join(",")}];\n`
1338
1370
  : "";
1339
1371
  let initLogicJS = "";
1340
- if (opts.initLogic && opts.initLogic.length > 0) {
1341
- let logic = opts.initLogic.join("\n");
1372
+ const allInit = [...(opts.initLogic || []), ...(initBlocks || [])];
1373
+ if (allInit.length > 0) {
1374
+ let logic = allInit.join("\n");
1342
1375
  if (opts.namespace && opts.declaredVars) {
1343
1376
  for (const v of opts.declaredVars) {
1344
1377
  const re = new RegExp(`\\b${v}\\b`, 'g');
@@ -1349,7 +1382,8 @@ function buildRuntime(opts) {
1349
1382
  }
1350
1383
  let renderFunc = '';
1351
1384
  if (needsRender) {
1352
- renderFunc = `function ${renderFn}() {\n ${forSyncBlock}${renderBody.replace(/^/gm, " ")}\n}\n${initLogicJS}${renderFn}();`;
1385
+ const logicAtTop = logicBlocks.length > 0 ? logicBlocks.join("\n") + "\n" : "";
1386
+ renderFunc = `function ${renderFn}() {\n ${logicAtTop}${forSyncBlock}${renderBody}\n}\n${initLogicJS}${renderFn}();`;
1353
1387
  }
1354
1388
  if (needsFullscreenSync) {
1355
1389
  renderFunc += `
package/dist/core/expr.js CHANGED
@@ -74,7 +74,10 @@ function compileExprToJS(expr, loopVars, namespace, declaredVars) {
74
74
  return `${t2}${expr.op}`;
75
75
  }
76
76
  case "call": {
77
- const callee = compileExprToJS(expr.callee, loopVars, namespace, declaredVars);
77
+ let callee = compileExprToJS(expr.callee, loopVars, namespace, declaredVars);
78
+ if (expr.memo && callee.startsWith('$')) {
79
+ callee = callee.substring(1);
80
+ }
78
81
  if (callee === "remove") {
79
82
  const arg = expr.args && expr.args[0] ? compileExprToJS(expr.args[0], loopVars, namespace, declaredVars) : "''";
80
83
  return `(function(){ var _el=document.getElementById(${arg}); if(_el)_el.remove(); })()`;
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Parser = void 0;
4
4
  const types_1 = require("./types");
5
- const lexer_1 = require("./lexer");
6
5
  const expr_1 = require("./expr");
6
+ const lexer_1 = require("./lexer");
7
7
  class Parser {
8
8
  constructor(tokens, file) {
9
9
  this.tokens = tokens;
@@ -126,7 +126,9 @@ class Parser {
126
126
  }
127
127
  }
128
128
  this.consume(types_1.TT.RPAREN);
129
- const expr = { kind: "call", callee: { kind: "variable", name: identName }, args };
129
+ const isMemo = identName.startsWith("$");
130
+ const realName = isMemo ? identName.substring(1) : identName;
131
+ const expr = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
130
132
  uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc: this.peek().loc }], loc: this.peek().loc });
131
133
  }
132
134
  else {
@@ -140,12 +142,11 @@ class Parser {
140
142
  this._visited.clear();
141
143
  return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls, initLogic };
142
144
  }
143
- flattenIfToUses(ifNode, scripts, initLogic) {
145
+ flattenIfToUses(ifNode, _scripts, _initLogic) {
144
146
  const bodyHasComp = ifNode.body.some(c => c.kind === "use");
145
147
  const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
146
148
  if (!bodyHasComp && !elseHasComp) {
147
- initLogic.push((0, expr_1.compileIfToJS)(ifNode));
148
- return [];
149
+ return [{ kind: "use", name: "__IF_ROOT__", attrs: [], children: [ifNode], loc: ifNode.loc }];
149
150
  }
150
151
  const syntheticUse = {
151
152
  kind: "use",
@@ -340,15 +341,14 @@ class Parser {
340
341
  }
341
342
  // var or assignment
342
343
  if (tok.type === types_1.TT.IDENT) {
343
- let memo = false;
344
344
  let rawName = this.consume(types_1.TT.IDENT).value;
345
+ let memo = false;
345
346
  if (rawName.startsWith("$")) {
346
347
  memo = true;
347
348
  rawName = rawName.substring(1);
348
349
  }
349
350
  const name = rawName;
350
351
  let varExpr;
351
- // dot notation -> e.g. user.age
352
352
  if (this.check(types_1.TT.DOT)) {
353
353
  this.consume(types_1.TT.DOT);
354
354
  const propName = this.consume(types_1.TT.IDENT).value;
@@ -358,6 +358,8 @@ class Parser {
358
358
  else {
359
359
  varExpr = { kind: "variable", name };
360
360
  }
361
+ if (memo)
362
+ varExpr.memo = true;
361
363
  // apply bracket postfixes (e.g. data[key], data["x"])
362
364
  const indexedExpr = this.parsePostfix(varExpr);
363
365
  // if indexing was applied, we don't allow assignment, just binary RHS (after possible call)
@@ -513,6 +515,12 @@ class Parser {
513
515
  left = this.parseLogical(left);
514
516
  return left;
515
517
  }
518
+ parseConcatRHS() {
519
+ const rhs = this.parseExpression(true);
520
+ if (!rhs)
521
+ throw new types_1.SinthError("Expected expression after +", this.peek().loc);
522
+ return rhs;
523
+ }
516
524
  parsePostfix(base) {
517
525
  let expr = base;
518
526
  while (this.check(types_1.TT.LBRACKET)) {
@@ -895,7 +903,7 @@ class Parser {
895
903
  let leftExpr = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
896
904
  while (this.check(types_1.TT.OP_PLUS)) {
897
905
  this.consume(types_1.TT.OP_PLUS);
898
- let rhs = null;
906
+ let rhs;
899
907
  if (this.check(types_1.TT.STRING)) {
900
908
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
901
909
  }
@@ -904,10 +912,8 @@ class Parser {
904
912
  rhs = { kind: "variable", name: rhsName };
905
913
  }
906
914
  else {
907
- rhs = this.parseExpression(true);
915
+ rhs = this.parseConcatRHS();
908
916
  }
909
- if (!rhs)
910
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
911
917
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
912
918
  }
913
919
  children.push({ kind: "expr", expression: leftExpr, loc });
@@ -1182,7 +1188,8 @@ class Parser {
1182
1188
  }
1183
1189
  const hasIf = actions.some(a => a.kind === "if");
1184
1190
  if (actions.length === 1 && !hasIf) {
1185
- const single = actions[0].expr;
1191
+ const firstAction = actions[0];
1192
+ const single = firstAction.kind === "expr" ? firstAction.expr : { kind: "literal", value: { kind: "str", value: firstAction.js } };
1186
1193
  value = { kind: "str", value: "__EXPR__" + JSON.stringify(single) };
1187
1194
  }
1188
1195
  else {
@@ -1272,7 +1279,7 @@ class Parser {
1272
1279
  this.consume(types_1.TT.RPAREN);
1273
1280
  while (this.check(types_1.TT.OP_PLUS)) {
1274
1281
  this.consume(types_1.TT.OP_PLUS);
1275
- let rhs = null;
1282
+ let rhs;
1276
1283
  if (this.check(types_1.TT.STRING)) {
1277
1284
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1278
1285
  }
@@ -1281,10 +1288,8 @@ class Parser {
1281
1288
  rhs = { kind: "variable", name: rhsName };
1282
1289
  }
1283
1290
  else {
1284
- rhs = this.parseExpression(true);
1291
+ rhs = this.parseConcatRHS();
1285
1292
  }
1286
- if (!rhs)
1287
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1288
1293
  expr = { kind: "binary", left: expr, op: "+", right: rhs };
1289
1294
  }
1290
1295
  children.push({ kind: "expr", expression: expr, loc });
@@ -1295,7 +1300,7 @@ class Parser {
1295
1300
  let leftExpr = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1296
1301
  while (this.check(types_1.TT.OP_PLUS)) {
1297
1302
  this.consume(types_1.TT.OP_PLUS);
1298
- let rhs = null;
1303
+ let rhs;
1299
1304
  if (this.check(types_1.TT.STRING)) {
1300
1305
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1301
1306
  }
@@ -1323,10 +1328,8 @@ class Parser {
1323
1328
  }
1324
1329
  }
1325
1330
  else {
1326
- rhs = this.parseExpression(true);
1331
+ rhs = this.parseConcatRHS();
1327
1332
  }
1328
- if (!rhs)
1329
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1330
1333
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1331
1334
  }
1332
1335
  children.push({ kind: "expr", expression: leftExpr, loc });
@@ -1374,7 +1377,7 @@ class Parser {
1374
1377
  continue;
1375
1378
  }
1376
1379
  if (nextType === types_1.TT.DOT) {
1377
- let rawFirst = this.consume(types_1.TT.IDENT).value;
1380
+ const rawFirst = this.consume(types_1.TT.IDENT).value;
1378
1381
  const isMemo = rawFirst.startsWith("$");
1379
1382
  const firstPart = isMemo ? rawFirst.slice(1) : rawFirst;
1380
1383
  this.consume(types_1.TT.DOT);
@@ -1384,7 +1387,7 @@ class Parser {
1384
1387
  let leftExpr = { kind: "variable", name: fullName };
1385
1388
  while (this.check(types_1.TT.OP_PLUS)) {
1386
1389
  this.consume(types_1.TT.OP_PLUS);
1387
- let rhs = null;
1390
+ let rhs;
1388
1391
  if (this.check(types_1.TT.STRING)) {
1389
1392
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1390
1393
  }
@@ -1399,10 +1402,8 @@ class Parser {
1399
1402
  }
1400
1403
  }
1401
1404
  else {
1402
- rhs = this.parseExpression(true);
1405
+ rhs = this.parseConcatRHS();
1403
1406
  }
1404
- if (!rhs)
1405
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1406
1407
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1407
1408
  }
1408
1409
  children.push({ kind: "expr", expression: leftExpr, loc });
@@ -1440,7 +1441,7 @@ class Parser {
1440
1441
  let leftExpr = { kind: "variable", name };
1441
1442
  while (this.check(types_1.TT.OP_PLUS)) {
1442
1443
  this.consume(types_1.TT.OP_PLUS);
1443
- let rhs = null;
1444
+ let rhs;
1444
1445
  if (this.check(types_1.TT.STRING)) {
1445
1446
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1446
1447
  }
@@ -1455,10 +1456,8 @@ class Parser {
1455
1456
  }
1456
1457
  }
1457
1458
  else {
1458
- rhs = this.parseExpression(true);
1459
+ rhs = this.parseConcatRHS();
1459
1460
  }
1460
- if (!rhs)
1461
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1462
1461
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1463
1462
  }
1464
1463
  children.push({ kind: "expr", expression: leftExpr, loc });
@@ -1470,12 +1469,12 @@ class Parser {
1470
1469
  else if (nextType === types_1.TT.LBRACKET) {
1471
1470
  const name = this.consume(types_1.TT.IDENT).value;
1472
1471
  const varExpr = { kind: "variable", name };
1473
- let indexedExpr = this.parsePostfix(varExpr);
1472
+ const indexedExpr = this.parsePostfix(varExpr);
1474
1473
  if (this.check(types_1.TT.OP_PLUS)) {
1475
1474
  let leftExpr = indexedExpr;
1476
1475
  while (this.check(types_1.TT.OP_PLUS)) {
1477
1476
  this.consume(types_1.TT.OP_PLUS);
1478
- let rhs = null;
1477
+ let rhs;
1479
1478
  if (this.check(types_1.TT.STRING)) {
1480
1479
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1481
1480
  }
@@ -1490,10 +1489,8 @@ class Parser {
1490
1489
  }
1491
1490
  }
1492
1491
  else {
1493
- rhs = this.parseExpression(true);
1492
+ rhs = this.parseConcatRHS();
1494
1493
  }
1495
- if (!rhs)
1496
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1497
1494
  leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1498
1495
  }
1499
1496
  children.push({ kind: "expr", expression: leftExpr, loc });
@@ -1525,7 +1522,7 @@ class Parser {
1525
1522
  let finalExpr = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
1526
1523
  while (this.check(types_1.TT.OP_PLUS)) {
1527
1524
  this.consume(types_1.TT.OP_PLUS);
1528
- let rhs = null;
1525
+ let rhs;
1529
1526
  if (this.check(types_1.TT.STRING)) {
1530
1527
  rhs = { kind: "literal", value: { kind: "str", value: this.consume(types_1.TT.STRING).value } };
1531
1528
  }
@@ -1533,10 +1530,8 @@ class Parser {
1533
1530
  rhs = this.parseExpression();
1534
1531
  }
1535
1532
  else {
1536
- rhs = this.parseExpression(true);
1533
+ rhs = this.parseConcatRHS();
1537
1534
  }
1538
- if (!rhs)
1539
- throw new types_1.SinthError("Expected expression after +", this.peek().loc);
1540
1535
  finalExpr = { kind: "binary", left: finalExpr, op: "+", right: rhs };
1541
1536
  }
1542
1537
  children.push({ kind: "expr", expression: finalExpr, loc });
@@ -44,7 +44,7 @@ function buildRenderBody(opts) {
44
44
  renderBody += ` document.querySelectorAll('template[data-sinth-if-expr]').forEach(function(t) { var p = t.parentElement; while(p && p.tagName !== 'TEMPLATE') p = p.parentElement; if (!p || (!p.hasAttribute('data-sinth-for') && !p.hasAttribute('data-sinth-for-expr'))) sinthIfBlock(t); });\n`;
45
45
  }
46
46
  renderBody += ` document.querySelectorAll('[data-sinth-value]').forEach(function(el) {
47
- try { if (document.activeElement !== el) { let v=el.dataset.sinthValue; el.value = ${X}[v] ? ${X}[v]({}) : ''; } } catch(e) {}
47
+ try { let v=el.dataset.sinthValue; el.value = ${X}[v] ? ${X}[v]({}) : ''; } catch(e) {}
48
48
  });\n`;
49
49
  renderBody += ` document.querySelectorAll('[data-sinth-step]').forEach(function(el) {
50
50
  try { let s=el.dataset.sinthStep; el.step = ${X}[s] ? ${X}[s]({}) : 1; } catch(e) {}
package/dist/server.js CHANGED
@@ -54,7 +54,9 @@ async function startDevServer(opts) {
54
54
  try {
55
55
  c.write("data: reload\n\n");
56
56
  }
57
- catch { }
57
+ catch {
58
+ void 0;
59
+ }
58
60
  }
59
61
  }
60
62
  function compileAll() {
@@ -104,7 +106,9 @@ async function startDevServer(opts) {
104
106
  });
105
107
  watchReady = true;
106
108
  }
107
- catch { }
109
+ catch {
110
+ void 0;
111
+ }
108
112
  if (!watchReady) {
109
113
  const mtimes = new Map();
110
114
  const poller = setInterval(() => {
@@ -121,7 +125,9 @@ async function startDevServer(opts) {
121
125
  break;
122
126
  }
123
127
  }
124
- catch { }
128
+ catch {
129
+ void 0;
130
+ }
125
131
  }
126
132
  }, 500);
127
133
  process.on("exit", () => clearInterval(poller));
@@ -47,7 +47,9 @@ function readCache() {
47
47
  return JSON.parse(fs.readFileSync(CACHE_FILE, "utf-8"));
48
48
  }
49
49
  }
50
- catch { }
50
+ catch {
51
+ void 0;
52
+ }
51
53
  return null;
52
54
  }
53
55
  function writeCache() {
@@ -55,7 +57,9 @@ function writeCache() {
55
57
  fs.mkdirSync(CACHE_DIR, { recursive: true });
56
58
  fs.writeFileSync(CACHE_FILE, JSON.stringify({ lastCheck: Date.now() }));
57
59
  }
58
- catch { }
60
+ catch {
61
+ void 0;
62
+ }
59
63
  }
60
64
  function fetchLatestVersion() {
61
65
  return new Promise((resolve) => {
package/dist/utils.js CHANGED
@@ -9,6 +9,13 @@ exports.litToString = litToString;
9
9
  exports.interpolateAttr = interpolateAttr;
10
10
  exports.renderText = renderText;
11
11
  const types_1 = require("./core/types");
12
+ const PLACEHOLDER_PREFIX = "__SINTH_PH_";
13
+ let _phCounter = 0;
14
+ function createPlaceholder(tag) {
15
+ return `${PLACEHOLDER_PREFIX}${tag}_${_phCounter++}_${Date.now().toString(36)}__`;
16
+ }
17
+ const ESCAPED_LEFT_BRACE = createPlaceholder("LB");
18
+ const ESCAPED_DOLLAR = createPlaceholder("DOLLAR");
12
19
  function fnv1a(s) {
13
20
  let h = 0x811c9dc5;
14
21
  for (let i = 0; i < s.length; i++) {
@@ -41,29 +48,29 @@ function litToString(lit) {
41
48
  }
42
49
  }
43
50
  function interpolateAttr(text, params) {
44
- let s = text.replace(/\\\{/g, "\x00LB\x00");
51
+ let s = text.replace(/\\\{/g, ESCAPED_LEFT_BRACE);
45
52
  s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
46
- return s.replace(/\x00LB\x00/g, "{");
53
+ return s.replace(new RegExp(ESCAPED_LEFT_BRACE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), "{");
47
54
  }
48
55
  function renderText(text, params) {
49
56
  const rawSlots = new Map();
50
- let counter = 0;
51
- let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
57
+ let s = text.replace(/\\\$/g, ESCAPED_DOLLAR);
52
58
  s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
53
59
  const val = params.get(n);
54
60
  if (val === undefined)
55
61
  return `$${n}`;
56
62
  if (n === "slot") {
57
- const ph = `\x00RAW${counter++}\x00`;
63
+ const ph = createPlaceholder("RAW");
58
64
  rawSlots.set(ph, val);
59
65
  return ph;
60
66
  }
61
67
  return val;
62
68
  });
63
69
  s = esc(s);
64
- for (const [ph, val] of rawSlots)
65
- s = s.replace(ph, val);
66
- s = s.replace(/\x00DOLLAR\x00/g, "$");
70
+ for (const [ph, val] of rawSlots) {
71
+ s = s.replace(new RegExp(ph.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), val);
72
+ }
73
+ s = s.replace(new RegExp(ESCAPED_DOLLAR.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), "$");
67
74
  const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
68
75
  let m;
69
76
  while ((m = braceRe.exec(s)) !== null) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "3.0.1",
4
- "description": "A declarative & reactive language that compiles to pure HTML, CSS, and JavaScript.",
3
+ "version": "4.0.0",
4
+ "description": "An easy, powerful, declarative & reactive language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
7
7
  "homepage": "https://sinth.yannosay.com",
@@ -36,12 +36,19 @@
36
36
  ],
37
37
  "scripts": {
38
38
  "build": "tsc",
39
+ "lint": "eslint src --ext .ts",
40
+ "lint:fix": "eslint src --ext .ts --fix",
39
41
  "prepublishOnly": "npm run build"
40
42
  },
41
43
  "devDependencies": {
44
+ "@eslint/js": "^10.0.1",
42
45
  "@types/node": "^25.9.3",
46
+ "@typescript-eslint/eslint-plugin": "^8.61.0",
47
+ "@typescript-eslint/parser": "^8.61.0",
48
+ "eslint": "^10.5.0",
43
49
  "ts-node": "^10.9.0",
44
- "typescript": "^5.3.0"
50
+ "typescript": "^5.3.0",
51
+ "typescript-eslint": "^8.61.0"
45
52
  },
46
53
  "engines": {
47
54
  "node": ">=18.0.0"