plainscript-lang 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +157 -150
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +172 -65
  4. package/compiler/formatter.js +1 -1
  5. package/compiler/generator.js +905 -184
  6. package/compiler/lexer.js +128 -54
  7. package/compiler/parser.js +1075 -155
  8. package/compiler/version.js +1 -1
  9. package/docs/CAPABILITY_GAP_AUDIT.md +131 -30
  10. package/docs/PLAINSCRIPT-SPEC.md +584 -0
  11. package/docs/index.html +48 -52
  12. package/docs/website/script.js +110 -24
  13. package/docs/website/style.css +4 -4
  14. package/examples/arrays.pln +12 -0
  15. package/examples/{auth-api.ps → auth-api.pln} +3 -3
  16. package/examples/{cache-and-jobs.ps → cache-and-jobs.pln} +1 -1
  17. package/examples/{concurrency.ps → concurrency.pln} +8 -8
  18. package/examples/{database.ps → database.pln} +1 -1
  19. package/examples/{deployment.ps → deployment.pln} +2 -2
  20. package/examples/{email-send.ps → email-send.pln} +1 -1
  21. package/examples/{error-handling.ps → error-handling.pln} +8 -7
  22. package/examples/{expressions.ps → expressions.pln} +1 -1
  23. package/examples/{file-uploads.ps → file-uploads.pln} +4 -4
  24. package/examples/{files-and-config.ps → files-and-config.pln} +4 -4
  25. package/examples/football-backend/{app.ps → app.pln} +2 -2
  26. package/examples/{http-client.ps → http-client.pln} +18 -18
  27. package/examples/id-verification/{app.ps → app.pln} +1 -1
  28. package/examples/{loops.ps → loops.pln} +2 -3
  29. package/examples/modules/{app.ps → app.pln} +4 -4
  30. package/examples/modules/{math.ps → math.pln} +1 -1
  31. package/examples/{record-kinds.ps → record-kinds.pln} +4 -4
  32. package/examples/{rest-api-fetch.ps → rest-api-fetch.pln} +1 -1
  33. package/examples/{rest-api.ps → rest-api.pln} +5 -5
  34. package/examples/{scheduled-tasks.ps → scheduled-tasks.pln} +2 -2
  35. package/examples/{search-and-filter.ps → search-and-filter.pln} +5 -5
  36. package/examples/{sessions-and-cookies.ps → sessions-and-cookies.pln} +2 -2
  37. package/examples/start.pln +2 -0
  38. package/examples/{stdlib.ps → stdlib.pln} +2 -2
  39. package/examples/{telegram-bot.ps → telegram-bot.pln} +2 -2
  40. package/examples/{websocket-server.ps → websocket-server.pln} +1 -1
  41. package/package.json +2 -2
  42. package/docs/PLINJS_SPEC.md +0 -1151
  43. package/examples/arrays.ps +0 -13
  44. package/examples/start.ps +0 -2
  45. /package/examples/{day2.ps → day2.pln} +0 -0
  46. /package/examples/{day3.ps → day3.pln} +0 -0
  47. /package/examples/{hello.ps → hello.pln} +0 -0
  48. /package/examples/{objects.ps → objects.pln} +0 -0
  49. /package/examples/{server.ps → server.pln} +0 -0
  50. /package/examples/{web-app.ps → web-app.pln} +0 -0
  51. /package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +0 -0
  52. /package/examples/whatsapp-bot/{qr.ps → qr.pln} +0 -0
@@ -1,6 +1,5 @@
1
1
  // Generator: converts a PlainScript AST into JavaScript source code.
2
2
 
3
- const vm = require('vm');
4
3
  const { splitPackageSpec } = require('./dependency-detector');
5
4
 
6
5
  // Known runtime packages and their require() statements.
@@ -40,7 +39,7 @@ const BUILTIN_DECLARATIONS = {
40
39
  fs: `const fs = require('fs');`,
41
40
  path: `const path = require('path');`,
42
41
  crypto: `const crypto = require('crypto');`,
43
- // v1.0.0 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
42
+ // v1.0.1 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
44
43
  // process.env. Blank lines and `#` comment lines are skipped.
45
44
  dotenv: [
46
45
  `function __loadEnvFile(path) {`,
@@ -86,7 +85,7 @@ const BUILTIN_DECLARATIONS = {
86
85
  ` }`,
87
86
  `}`,
88
87
  ].join('\n'),
89
- // v1.0.0 — shared runtime helpers for reflection, binary-size, YAML subset
88
+ // v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
90
89
  // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
91
90
  // when any feature that needs them is used.
92
91
  core: [
@@ -219,7 +218,7 @@ const BUILTIN_DECLARATIONS = {
219
218
  ` });`,
220
219
  `}`,
221
220
  ].join('\n'),
222
- // v1.0.0 — process execution (child processes).
221
+ // v1.0.1 — process execution (child processes).
223
222
  process: [
224
223
  `const { execFile } = require('child_process');`,
225
224
  `function __runCommand(command, args) {`,
@@ -230,7 +229,7 @@ const BUILTIN_DECLARATIONS = {
230
229
  ` });`,
231
230
  `}`,
232
231
  ].join('\n'),
233
- // v1.0.0 — Map helpers.
232
+ // v1.0.1 — Map helpers.
234
233
  mapset: [
235
234
  `function __mapSet(map, key, value) { map.set(key, value); return map; }`,
236
235
  ].join('\n'),
@@ -277,7 +276,7 @@ const BUILTIN_DECLARATIONS = {
277
276
  ` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
278
277
  `}`,
279
278
  ].join('\n'),
280
- // v1.0.0 — dynamic module loader.
279
+ // v1.0.1 — dynamic module loader.
281
280
  loadmodule: [
282
281
  `function __loadModule(spec) {`,
283
282
  ` const path = require('path');`,
@@ -286,7 +285,7 @@ const BUILTIN_DECLARATIONS = {
286
285
  ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
287
286
  `}`,
288
287
  ].join('\n'),
289
- // v1.0.0 — recursive directory walker (returns full paths, files first).
288
+ // v1.0.1 — recursive directory walker (returns full paths, files first).
290
289
  walk: [
291
290
  `function __walkFolder(dir) {`,
292
291
  ` const fs = require('fs');`,
@@ -1095,15 +1094,33 @@ const BUILTIN_DECLARATIONS = {
1095
1094
  };
1096
1095
 
1097
1096
  // Built-in stdlib functions: PlainScript name → JS code generator.
1098
- // v0.1–v0.4 original stdlib
1099
- const STDLIB = {
1100
- length: (args, context) => `(${generateExpr(args[0], context)}).length`,
1101
- uppercase: (args, context) => `(${generateExpr(args[0], context)}).toUpperCase()`,
1102
- lowercase: (args, context) => `(${generateExpr(args[0], context)}).toLowerCase()`,
1103
- random: (_args) => `Math.random()`,
1104
- round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1105
- // Runtime constructors
1106
- sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1097
+ // v0.1–v0.4 original stdlib
1098
+ const STDLIB = {
1099
+ length: (args, context) => `(${generateExpr(args[0], context)}).length`,
1100
+ uppercase: (args, context) => `(${generateExpr(args[0], context)}).toUpperCase()`,
1101
+ lowercase: (args, context) => `(${generateExpr(args[0], context)}).toLowerCase()`,
1102
+ random: (_args) => `Math.random()`,
1103
+ round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1104
+ // Symbol creation
1105
+ symbol: (args, context) => `Symbol(${args.length > 0 ? generateExpr(args[0], context) : 'undefined'})`,
1106
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
1107
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
1108
+ // Well-known symbols
1109
+ symbolIterator: (_args) => `Symbol.iterator`,
1110
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
1111
+ symbolMatch: (_args) => `Symbol.match`,
1112
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
1113
+ symbolReplace: (_args) => `Symbol.replace`,
1114
+ symbolSearch: (_args) => `Symbol.search`,
1115
+ symbolSplit: (_args) => `Symbol.split`,
1116
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
1117
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
1118
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
1119
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
1120
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
1121
+ symbolSpecies: (_args) => `Symbol.species`,
1122
+ // Runtime constructors
1123
+ sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1107
1124
  // v0.6 — runtime standard library
1108
1125
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1109
1126
  readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
@@ -1121,7 +1138,7 @@ const STDLIB = {
1121
1138
  // v1.2 — Telegram runtime helpers
1122
1139
  bot: (args, context) => {
1123
1140
  ensureBuiltin(context, 'telegram');
1124
- if (!context.inFunction) context.needsAsync = true;
1141
+ markAsync(context);
1125
1142
  return `BOT = await Telegram.createTelegramBot(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1126
1143
  },
1127
1144
  sendMessage: (args, context) => {
@@ -1261,7 +1278,27 @@ const STDLIB = {
1261
1278
  padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1262
1279
  padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1263
1280
 
1264
- // ── v1.0.0 — nullable / regex / date helpers (IOPL-native).
1281
+ // ── v2.3.0 — Proxy and Reflect (IOPL-native).
1282
+ // Proxy creation: proxy(target, handler)
1283
+ proxy: (args, context) => `new Proxy(${args.map(a => generateExpr(a, context)).join(', ')})`,
1284
+ // Proxy revocable: proxyRevocable(target, handler) -> { proxy, revoke }
1285
+ proxyRevocable: (args, context) => `Proxy.revocable(${args.map(a => generateExpr(a, context)).join(', ')})`,
1286
+ // Reflect methods
1287
+ reflectApply: (args, context) => `Reflect.apply(${args.map(a => generateExpr(a, context)).join(', ')})`,
1288
+ reflectConstruct: (args, context) => `Reflect.construct(${args.map(a => generateExpr(a, context)).join(', ')})`,
1289
+ reflectDefineProperty: (args, context) => `Reflect.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1290
+ reflectDeleteProperty: (args, context) => `Reflect.deleteProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1291
+ reflectGet: (args, context) => `Reflect.get(${args.map(a => generateExpr(a, context)).join(', ')})`,
1292
+ reflectGetOwnPropertyDescriptor: (args, context) => `Reflect.getOwnPropertyDescriptor(${args.map(a => generateExpr(a, context)).join(', ')})`,
1293
+ reflectGetPrototypeOf: (args, context) => `Reflect.getPrototypeOf(${generateExpr(args[0], context)})`,
1294
+ reflectHas: (args, context) => `Reflect.has(${args.map(a => generateExpr(a, context)).join(', ')})`,
1295
+ reflectIsExtensible: (args, context) => `Reflect.isExtensible(${generateExpr(args[0], context)})`,
1296
+ reflectOwnKeys: (args, context) => `Reflect.ownKeys(${generateExpr(args[0], context)})`,
1297
+ reflectPreventExtensions: (args, context) => `Reflect.preventExtensions(${generateExpr(args[0], context)})`,
1298
+ reflectSet: (args, context) => `Reflect.set(${args.map(a => generateExpr(a, context)).join(', ')})`,
1299
+ reflectSetPrototypeOf: (args, context) => `Reflect.setPrototypeOf(${args.map(a => generateExpr(a, context)).join(', ')})`,
1300
+
1301
+ // ── v1.0.1 — nullable / regex / date helpers (IOPL-native).
1265
1302
  // first non-null, non-undefined argument — IOPL null-coalescing.
1266
1303
  coalesce: (args, context) =>
1267
1304
  `(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
@@ -1278,6 +1315,144 @@ const STDLIB = {
1278
1315
  return `__formatDate(${value}, ${pattern})`;
1279
1316
  },
1280
1317
 
1318
+ // ── v1.0.2 — Native Date/DateTime/Regex support (IOPL-native, no JS gateway needed).
1319
+ // Create a new Date object. With no args: now. With 1 arg: parse ISO string or timestamp.
1320
+ // With multiple args: year, month (1-12), day, hour, min, sec, ms.
1321
+ newDate: (args, context) => {
1322
+ if (!args || args.length === 0) return `new Date()`;
1323
+ if (args.length === 1) return `new Date(${generateExpr(args[0], context)})`;
1324
+ return `new Date(${args.map(a => generateExpr(a, context)).join(', ')})`;
1325
+ },
1326
+ // Current timestamp in milliseconds.
1327
+ now: (_args) => `Date.now()`,
1328
+ // Current timestamp in seconds (Unix epoch).
1329
+ nowSec: (_args) => `Math.floor(Date.now() / 1000)`,
1330
+ // Date → ISO string (e.g., "2026-08-28T12:34:56.789Z").
1331
+ toISO: (args, context) => `${generateExpr(args[0], context)}.toISOString()`,
1332
+ // Date → locale date string.
1333
+ toLocaleDate: (args, context) => `${generateExpr(args[0], context)}.toLocaleDateString()`,
1334
+ // Date → locale time string.
1335
+ toLocaleTime: (args, context) => `${generateExpr(args[0], context)}.toLocaleTimeString()`,
1336
+ // Date → locale string.
1337
+ toLocale: (args, context) => `${generateExpr(args[0], context)}.toLocaleString()`,
1338
+ // Date → UTC string.
1339
+ toUTC: (args, context) => `${generateExpr(args[0], context)}.toUTCString()`,
1340
+ // Get timestamp (milliseconds) from a Date.
1341
+ timestamp: (args, context) => `${generateExpr(args[0], context)}.getTime()`,
1342
+ // Get year (full, e.g., 2026).
1343
+ year: (args, context) => `${generateExpr(args[0], context)}.getFullYear()`,
1344
+ // Get month (1-12).
1345
+ month: (args, context) => `${generateExpr(args[0], context)}.getMonth() + 1`,
1346
+ // Get day of month (1-31).
1347
+ day: (args, context) => `${generateExpr(args[0], context)}.getDate()`,
1348
+ // Get day of week (0-6, Sun=0).
1349
+ dayOfWeek: (args, context) => `${generateExpr(args[0], context)}.getDay()`,
1350
+ // Get hours (0-23).
1351
+ hours: (args, context) => `${generateExpr(args[0], context)}.getHours()`,
1352
+ // Get minutes (0-59).
1353
+ minutes: (args, context) => `${generateExpr(args[0], context)}.getMinutes()`,
1354
+ // Get seconds (0-59).
1355
+ seconds: (args, context) => `${generateExpr(args[0], context)}.getSeconds()`,
1356
+ // Get milliseconds (0-999).
1357
+ milliseconds: (args, context) => `${generateExpr(args[0], context)}.getMilliseconds()`,
1358
+ // Get timezone offset in minutes.
1359
+ tzOffset: (args, context) => `${generateExpr(args[0], context)}.getTimezoneOffset()`,
1360
+ // Add time to a Date (returns new Date). Unit: ms, s, m, h, d, w, mo, y.
1361
+ addTime: (args, context) => {
1362
+ if (args.length < 3) throw new Error('addTime(date, amount, unit) requires 3 arguments');
1363
+ const date = generateExpr(args[0], context);
1364
+ const amount = generateExpr(args[1], context);
1365
+ const unit = generateExpr(args[2], context);
1366
+ return `(() => { const base = new Date(${date}.getTime()); const u = String(${unit}).toLowerCase(); const mult = { ms:1, s:1000, m:60000, h:3600000, d:86400000, w:604800000, mo:2592000000, y:31536000000 }; const result = new Date(base.getTime()); result.setTime(result.getTime() + ${amount} * (mult[u] || 1)); return result; })()`;
1367
+ },
1368
+ // Subtract time from a Date (returns new Date).
1369
+ subTime: (args, context) => {
1370
+ if (args.length < 3) throw new Error('subTime(date, amount, unit) requires 3 arguments');
1371
+ const date = generateExpr(args[0], context);
1372
+ const amount = generateExpr(args[1], context);
1373
+ const unit = generateExpr(args[2], context);
1374
+ return `(() => { const base = new Date(${date}.getTime()); const u = String(${unit}).toLowerCase(); const mult = { ms:1, s:1000, m:60000, h:3600000, d:86400000, w:604800000, mo:2592000000, y:31536000000 }; const result = new Date(base.getTime()); result.setTime(result.getTime() - ${amount} * (mult[u] || 1)); return result; })()`;
1375
+ },
1376
+ // Difference between two dates in given unit (ms, s, m, h, d, w).
1377
+ diffTime: (args, context) => {
1378
+ if (args.length < 3) throw new Error('diffTime(date1, date2, unit) requires 3 arguments');
1379
+ const d1 = generateExpr(args[0], context);
1380
+ const d2 = generateExpr(args[1], context);
1381
+ const unit = generateExpr(args[2], context);
1382
+ return `(() => { const u = String(${unit}).toLowerCase(); const mult = { ms:1, s:1000, m:60000, h:3600000, d:86400000, w:604800000 }; return Math.floor((${d1}.getTime() - ${d2}.getTime()) / (mult[u] || 1)); })()`;
1383
+ },
1384
+ // Start of day (00:00:00.000) for a Date.
1385
+ startOfDay: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setHours(0,0,0,0); return dt; })()`,
1386
+ // End of day (23:59:59.999) for a Date.
1387
+ endOfDay: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setHours(23,59,59,999); return dt; })()`,
1388
+ // Start of month (1st, 00:00:00.000).
1389
+ startOfMonth: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setDate(1); dt.setHours(0,0,0,0); return dt; })()`,
1390
+ // End of month (last day, 23:59:59.999).
1391
+ endOfMonth: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setMonth(dt.getMonth()+1, 0); dt.setHours(23,59,59,999); return dt; })()`,
1392
+ // Start of year (Jan 1, 00:00:00.000).
1393
+ startOfYear: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setMonth(0,1); dt.setHours(0,0,0,0); return dt; })()`,
1394
+ // End of year (Dec 31, 23:59:59.999).
1395
+ endOfYear: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setMonth(11,31); dt.setHours(23,59,59,999); return dt; })()`,
1396
+ // Check if a Date is valid (not NaN).
1397
+ isValidDate: (args, context) => `!isNaN(${generateExpr(args[0], context)}.getTime())`,
1398
+ // Format a Date with a custom pattern (YYYY, MM, DD, HH, mm, ss, SSS).
1399
+ format: (args, context) => {
1400
+ ensureBuiltin(context, 'core');
1401
+ const value = generateExpr(args[0], context);
1402
+ const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
1403
+ return `__formatDate(${value}, ${pattern})`;
1404
+ },
1405
+
1406
+ // Regex creation and matching.
1407
+ // Create a RegExp from a pattern string. Optional flags (e.g., "gi").
1408
+ regex: (args, context) => {
1409
+ if (!args || args.length === 0) throw new Error('regex(pattern, flags?) requires at least a pattern');
1410
+ const pattern = generateExpr(args[0], context);
1411
+ const flags = args.length > 1 ? generateExpr(args[1], context) : 'undefined';
1412
+ return `new RegExp(${pattern}, ${flags})`;
1413
+ },
1414
+ // Test if a string matches a regex pattern.
1415
+ matches: (args, context) => {
1416
+ if (args.length < 2) throw new Error('matches(text, pattern, flags?) requires at least text and pattern');
1417
+ const text = generateExpr(args[0], context);
1418
+ const pattern = generateExpr(args[1], context);
1419
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1420
+ return `new RegExp(${pattern}, ${flags}).test(${text})`;
1421
+ },
1422
+ // Extract first match of regex in string (returns array or null).
1423
+ regexMatch: (args, context) => {
1424
+ if (args.length < 2) throw new Error('regexMatch(text, pattern, flags?) requires at least text and pattern');
1425
+ const text = generateExpr(args[0], context);
1426
+ const pattern = generateExpr(args[1], context);
1427
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1428
+ return `${text}.match(new RegExp(${pattern}, ${flags}))`;
1429
+ },
1430
+ // Extract all matches of regex in string (returns array).
1431
+ regexMatchAll: (args, context) => {
1432
+ if (args.length < 2) throw new Error('regexMatchAll(text, pattern, flags?) requires at least text and pattern');
1433
+ const text = generateExpr(args[0], context);
1434
+ const pattern = generateExpr(args[1], context);
1435
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1436
+ return `((${flags}) === undefined ? Array.from(${text}.matchAll(new RegExp(${pattern}, 'g'))) : Array.from(${text}.matchAll(new RegExp(${pattern}, ${flags} + 'g'))))`;
1437
+ },
1438
+ // Replace using regex (with capture groups support).
1439
+ replaceRegex: (args, context) => {
1440
+ if (args.length < 3) throw new Error('replaceRegex(text, pattern, replacement, flags?) requires at least 3 arguments');
1441
+ const text = generateExpr(args[0], context);
1442
+ const pattern = generateExpr(args[1], context);
1443
+ const replacement = generateExpr(args[2], context);
1444
+ const flags = args.length > 3 ? generateExpr(args[3], context) : 'undefined';
1445
+ return `${text}.replace(new RegExp(${pattern}, ${flags}), ${replacement})`;
1446
+ },
1447
+ // Split string by regex pattern.
1448
+ splitRegex: (args, context) => {
1449
+ if (args.length < 2) throw new Error('splitRegex(text, pattern, flags?) requires at least text and pattern');
1450
+ const text = generateExpr(args[0], context);
1451
+ const pattern = generateExpr(args[1], context);
1452
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1453
+ return `${text}.split(new RegExp(${pattern}, ${flags}))`;
1454
+ },
1455
+
1281
1456
  // ── v2.1.0 — cache (Redis) accessors. All async.
1282
1457
 
1283
1458
  cacheGet: (args, context) => {
@@ -1351,7 +1526,7 @@ const STDLIB = {
1351
1526
  return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1352
1527
  },
1353
1528
 
1354
- // ── v1.0.0 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
1529
+ // ── v1.0.1 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
1355
1530
 
1356
1531
  // Reflection
1357
1532
  typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
@@ -1412,7 +1587,7 @@ const STDLIB = {
1412
1587
  // Generators / iterables
1413
1588
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
1414
1589
 
1415
- // v1.0.0 — dynamic module loading (the runtime companion to `import "./x.ps"`).
1590
+ // v1.0.1 — dynamic module loading (the runtime companion to `import "./x.pt"`).
1416
1591
  // Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
1417
1592
  // `require.resolve` from the program root.
1418
1593
  loadModule: (args, context) => {
@@ -1498,11 +1673,422 @@ const STDLIB = {
1498
1673
  ensureBuiltin(context, 'fs');
1499
1674
  return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
1500
1675
  },
1676
+
1677
+ // ── v1.0.2 — Extended Math functions (IOPL-native).
1678
+ abs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
1679
+ min: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
1680
+ max: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
1681
+ sqrt: (args, context) => `Math.sqrt(${generateExpr(args[0], context)})`,
1682
+ pow: (args, context) => `Math.pow(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1683
+ floor: (args, context) => `Math.floor(${generateExpr(args[0], context)})`,
1684
+ ceil: (args, context) => `Math.ceil(${generateExpr(args[0], context)})`,
1685
+ round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1686
+ trunc: (args, context) => `Math.trunc(${generateExpr(args[0], context)})`,
1687
+ sign: (args, context) => `Math.sign(${generateExpr(args[0], context)})`,
1688
+ random: (_args) => `Math.random()`,
1689
+ randomInt: (args, context) => `Math.floor(Math.random() * (${generateExpr(args[1], context)} - ${generateExpr(args[0], context)} + 1)) + ${generateExpr(args[0], context)}`,
1690
+ clamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
1691
+ lerp: (args, context) => `${generateExpr(args[0], context)} + (${generateExpr(args[1], context)} - ${generateExpr(args[0], context)}) * ${generateExpr(args[2], context)}`,
1692
+ PI: (_args) => `Math.PI`,
1693
+ E: (_args) => `Math.E`,
1694
+ ln2: (_args) => `Math.LN2`,
1695
+ ln10: (_args) => `Math.LN10`,
1696
+ log2e: (_args) => `Math.LOG2E`,
1697
+ log10e: (_args) => `Math.LOG10E`,
1698
+ sin: (args, context) => `Math.sin(${generateExpr(args[0], context)})`,
1699
+ cos: (args, context) => `Math.cos(${generateExpr(args[0], context)})`,
1700
+ tan: (args, context) => `Math.tan(${generateExpr(args[0], context)})`,
1701
+ asin: (args, context) => `Math.asin(${generateExpr(args[0], context)})`,
1702
+ acos: (args, context) => `Math.acos(${generateExpr(args[0], context)})`,
1703
+ atan: (args, context) => `Math.atan(${generateExpr(args[0], context)})`,
1704
+ atan2: (args, context) => `Math.atan2(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1705
+ sinh: (args, context) => `Math.sinh(${generateExpr(args[0], context)})`,
1706
+ cosh: (args, context) => `Math.cosh(${generateExpr(args[0], context)})`,
1707
+ tanh: (args, context) => `Math.tanh(${generateExpr(args[0], context)})`,
1708
+ exp: (args, context) => `Math.exp(${generateExpr(args[0], context)})`,
1709
+ expm1: (args, context) => `Math.expm1(${generateExpr(args[0], context)})`,
1710
+ log: (args, context) => `Math.log(${generateExpr(args[0], context)})`,
1711
+ log1p: (args, context) => `Math.log1p(${generateExpr(args[0], context)})`,
1712
+ log2: (args, context) => `Math.log2(${generateExpr(args[0], context)})`,
1713
+ log10: (args, context) => `Math.log10(${generateExpr(args[0], context)})`,
1714
+ hypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
1715
+ cbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
1716
+
1717
+ // ── v1.0.2 — Extended String functions (IOPL-native).
1718
+ trim: (args, context) => `String(${generateExpr(args[0], context)}).trim()`,
1719
+ trimStart: (args, context) => `String(${generateExpr(args[0], context)}).trimStart()`,
1720
+ trimEnd: (args, context) => `String(${generateExpr(args[0], context)}).trimEnd()`,
1721
+ toUpperCase: (args, context) => `String(${generateExpr(args[0], context)}).toUpperCase()`,
1722
+ toLowerCase: (args, context) => `String(${generateExpr(args[0], context)}).toLowerCase()`,
1723
+ charAt: (args, context) => `String(${generateExpr(args[0], context)}).charAt(${generateExpr(args[1], context)})`,
1724
+ charCodeAt: (args, context) => `String(${generateExpr(args[0], context)}).charCodeAt(${generateExpr(args[1], context)})`,
1725
+ codePointAt: (args, context) => `String(${generateExpr(args[0], context)}).codePointAt(${generateExpr(args[1], context)})`,
1726
+ slice: (args, context) => `String(${generateExpr(args[0], context)}).slice(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1727
+ substring: (args, context) => `String(${generateExpr(args[0], context)}).substring(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1728
+ substr: (args, context) => `String(${generateExpr(args[0], context)}).substr(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1729
+ indexOf: (args, context) => `String(${generateExpr(args[0], context)}).indexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1730
+ lastIndexOf: (args, context) => `String(${generateExpr(args[0], context)}).lastIndexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1731
+ includes: (args, context) => `String(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1732
+ startsWith: (args, context) => `String(${generateExpr(args[0], context)}).startsWith(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1733
+ endsWith: (args, context) => `String(${generateExpr(args[0], context)}).endsWith(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1734
+ repeat: (args, context) => `String(${generateExpr(args[0], context)}).repeat(${generateExpr(args[1], context)})`,
1735
+ padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1736
+ padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1737
+ split: (args, context) => {
1738
+ const sep = args.length > 1 ? generateExpr(args[1], context) : '","';
1739
+ return `String(${generateExpr(args[0], context)}).split(${sep})`;
1740
+ },
1741
+ join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
1742
+ replaceAll: (args, context) => `String(${generateExpr(args[0], context)}).replaceAll(${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
1743
+ match: (args, context) => `String(${generateExpr(args[0], context)}).match(${generateExpr(args[1], context)})`,
1744
+ matchAll: (args, context) => `Array.from(String(${generateExpr(args[0], context)}).matchAll(${generateExpr(args[1], context)}))`,
1745
+ search: (args, context) => `String(${generateExpr(args[0], context)}).search(${generateExpr(args[1], context)})`,
1746
+ toString: (args, context) => `String(${generateExpr(args[0], context)}).toString()`,
1747
+ stringValueOf: (args, context) => `String(${generateExpr(args[0], context)}).valueOf()`,
1748
+
1749
+ // ── v1.0.2 — Extended Array/Collection functions (IOPL-native).
1750
+ push: (args, context) => `(${generateExpr(args[0], context)}).push(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1751
+ pop: (args, context) => `(${generateExpr(args[0], context)}).pop()`,
1752
+ shift: (args, context) => `(${generateExpr(args[0], context)}).shift()`,
1753
+ unshift: (args, context) => `(${generateExpr(args[0], context)}).unshift(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1754
+ splice: (args, context) => `(${generateExpr(args[0], context)}).splice(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1755
+ concat: (args, context) => `(${generateExpr(args[0], context)}).concat(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1756
+ slice: (args, context) => `(${generateExpr(args[0], context)}).slice(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1757
+ copyWithin: (args, context) => `(${generateExpr(args[0], context)}).copyWithin(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1758
+ fill: (args, context) => `(${generateExpr(args[0], context)}).fill(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''}${args.length > 3 ? ', ' + generateExpr(args[3], context) : ''})`,
1759
+ find: (args, context) => `(${generateExpr(args[0], context)}).find(${generateExpr(args[1], context)})`,
1760
+ findIndex: (args, context) => `(${generateExpr(args[0], context)}).findIndex(${generateExpr(args[1], context)})`,
1761
+ findLast: (args, context) => `(${generateExpr(args[0], context)}).findLast(${generateExpr(args[1], context)})`,
1762
+ findLastIndex: (args, context) => `(${generateExpr(args[0], context)}).findLastIndex(${generateExpr(args[1], context)})`,
1763
+ indexOf: (args, context) => `(${generateExpr(args[0], context)}).indexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1764
+ lastIndexOf: (args, context) => `(${generateExpr(args[0], context)}).lastIndexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1765
+ includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1766
+ join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
1767
+ reverse: (args, context) => `[...${generateExpr(args[0], context)}].reverse()`,
1768
+ sort: (args, context) => `[...${generateExpr(args[0], context)}].sort(${args.length > 1 ? generateExpr(args[1], context) : '(a, b) => (a < b ? -1 : a > b ? 1 : 0)'})`,
1769
+ flat: (args, context) => `(${generateExpr(args[0], context)}).flat(${args.length > 1 ? generateExpr(args[1], context) : ''})`,
1770
+ flatMap: (args, context) => `(${generateExpr(args[0], context)}).flatMap(${generateExpr(args[1], context)})`,
1771
+ map: (args, context) => `(${generateExpr(args[0], context)}).map(${generateExpr(args[1], context)})`,
1772
+ filter: (args, context) => `(${generateExpr(args[0], context)}).filter(${generateExpr(args[1], context)})`,
1773
+ reduce: (args, context) => `(${generateExpr(args[0], context)}).reduce(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1774
+ reduceRight: (args, context) => `(${generateExpr(args[0], context)}).reduceRight(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1775
+ forEach: (args, context) => `(${generateExpr(args[0], context)}).forEach(${generateExpr(args[1], context)})`,
1776
+ some: (args, context) => `(${generateExpr(args[0], context)}).some(${generateExpr(args[1], context)})`,
1777
+ every: (args, context) => `(${generateExpr(args[0], context)}).every(${generateExpr(args[1], context)})`,
1778
+ at: (args, context) => `(${generateExpr(args[0], context)}).at(${generateExpr(args[1], context)})`,
1779
+ with: (args, context) => `(${generateExpr(args[0], context)}).with(${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
1780
+ toSorted: (args, context) => `(${generateExpr(args[0], context)}).toSorted(${args.length > 1 ? generateExpr(args[1], context) : '(a, b) => (a < b ? -1 : a > b ? 1 : 0)'})`,
1781
+ toReversed: (args, context) => `(${generateExpr(args[0], context)}).toReversed()`,
1782
+ toSpliced: (args, context) => `(${generateExpr(args[0], context)}).toSpliced(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1783
+ keys: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
1784
+ values: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
1785
+ entries: (args, context) => `Object.entries(${generateExpr(args[0], context)})`,
1786
+
1787
+ // ── v1.0.2 — Extended Object functions (IOPL-native).
1788
+ assign: (args, context) => `Object.assign(${args.map(a => generateExpr(a, context)).join(', ')})`,
1789
+ create: (args, context) => `Object.create(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1790
+ defineProperty: (args, context) => `Object.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1791
+ defineProperties: (args, context) => `Object.defineProperties(${args.map(a => generateExpr(a, context)).join(', ')})`,
1792
+ getOwnPropertyDescriptor: (args, context) => `Object.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1793
+ getOwnPropertyDescriptors: (args, context) => `Object.getOwnPropertyDescriptors(${generateExpr(args[0], context)})`,
1794
+ getOwnPropertyNames: (args, context) => `Object.getOwnPropertyNames(${generateExpr(args[0], context)})`,
1795
+ getOwnPropertySymbols: (args, context) => `Object.getOwnPropertySymbols(${generateExpr(args[0], context)})`,
1796
+ getPrototypeOf: (args, context) => `Object.getPrototypeOf(${generateExpr(args[0], context)})`,
1797
+ setPrototypeOf: (args, context) => `Object.setPrototypeOf(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1798
+ objectIs: (args, context) => `Object.is(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1799
+ isExtensible: (args, context) => `Object.isExtensible(${generateExpr(args[0], context)})`,
1800
+ isFrozen: (args, context) => `Object.isFrozen(${generateExpr(args[0], context)})`,
1801
+ isSealed: (args, context) => `Object.isSealed(${generateExpr(args[0], context)})`,
1802
+ preventExtensions: (args, context) => `Object.preventExtensions(${generateExpr(args[0], context)})`,
1803
+ freeze: (args, context) => `Object.freeze(${generateExpr(args[0], context)})`,
1804
+ seal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
1805
+ hasOwn: (args, context) => `Object.hasOwn(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1806
+
1807
+ // ── v1.0.2 — Promise/Async utilities (IOPL-native).
1808
+ Promise: {
1809
+ resolve: (args, context) => `Promise.resolve(${generateExpr(args[0], context)})`,
1810
+ reject: (args, context) => `Promise.reject(${generateExpr(args[0], context)})`,
1811
+ all: (args, context) => `Promise.all(${generateExpr(args[0], context)})`,
1812
+ allSettled: (args, context) => `Promise.allSettled(${generateExpr(args[0], context)})`,
1813
+ race: (args, context) => `Promise.race(${generateExpr(args[0], context)})`,
1814
+ any: (args, context) => `Promise.any(${generateExpr(args[0], context)})`,
1815
+ },
1816
+ // Note: These are accessed as Promise.resolve, Promise.all, etc.
1817
+ // We'll add helper functions for them.
1818
+ promiseResolve: (args, context) => `Promise.resolve(${generateExpr(args[0], context)})`,
1819
+ promiseReject: (args, context) => `Promise.reject(${generateExpr(args[0], context)})`,
1820
+ promiseAll: (args, context) => `Promise.all(${generateExpr(args[0], context)})`,
1821
+ promiseAllSettled: (args, context) => `Promise.allSettled(${generateExpr(args[0], context)})`,
1822
+ promiseRace: (args, context) => `Promise.race(${generateExpr(args[0], context)})`,
1823
+ promiseAny: (args, context) => `Promise.any(${generateExpr(args[0], context)})`,
1824
+ promiseWithResolvers: (args, context) => `Promise.withResolvers()`,
1825
+ await: (args, context) => {
1826
+ markAsync(context);
1827
+ return `await ${generateExpr(args[0], context)}`;
1828
+ },
1829
+ // Async sleep (returns a promise that resolves after ms).
1830
+ sleepAsync: (args, context) => {
1831
+ markAsync(context);
1832
+ return `new Promise(r => setTimeout(r, ${generateExpr(args[0], context)}))`;
1833
+ },
1834
+ // Timeout wrapper for promises.
1835
+ timeout: (args, context) => {
1836
+ markAsync(context);
1837
+ const ms = args.length > 1 ? generateExpr(args[1], context) : '30000';
1838
+ return `Promise.race([${generateExpr(args[0], context)}, new Promise((_, r) => setTimeout(() => r(new Error('Timed out')), ${ms}))])`;
1839
+ },
1840
+
1841
+ // ── v1.0.2 — JSON utilities (IOPL-native).
1842
+ jsonParse: (args, context) => `JSON.parse(${generateExpr(args[0], context)})`,
1843
+ stringify: (args, context) => `JSON.stringify(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1844
+
1845
+ // ── v1.0.2 — Type checking utilities (IOPL-native).
1846
+ isArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
1847
+ isInteger: (args, context) => `Number.isInteger(${generateExpr(args[0], context)})`,
1848
+ isNaN: (args, context) => `Number.isNaN(${generateExpr(args[0], context)})`,
1849
+ isFinite: (args, context) => `Number.isFinite(${generateExpr(args[0], context)})`,
1850
+ isSafeInteger: (args, context) => `Number.isSafeInteger(${generateExpr(args[0], context)})`,
1851
+ parseInt: (args, context) => `parseInt(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1852
+ parseFloat: (args, context) => `parseFloat(${generateExpr(args[0], context)})`,
1853
+
1854
+ // ── v1.0.2 — Array static methods (IOPL-native).
1855
+ arrayFrom: (args, context) => `Array.from(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1856
+ arrayOf: (args, context) => `Array.of(${args.map(a => generateExpr(a, context)).join(', ')})`,
1857
+ arrayIsArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
1858
+
1859
+ // ── v1.0.2 — Object static methods (IOPL-native).
1860
+ objectFromEntries: (args, context) => `Object.fromEntries(${generateExpr(args[0], context)})`,
1861
+ objectGetOwnPropertySymbols: (args, context) => `Object.getOwnPropertySymbols(${generateExpr(args[0], context)})`,
1862
+ objectGetOwnPropertyDescriptors: (args, context) => `Object.getOwnPropertyDescriptors(${generateExpr(args[0], context)})`,
1863
+ objectGetPrototypeOf: (args, context) => `Object.getPrototypeOf(${generateExpr(args[0], context)})`,
1864
+ objectSetPrototypeOf: (args, context) => `Object.setPrototypeOf(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1865
+ objectIs: (args, context) => `Object.is(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1866
+ objectCreate: (args, context) => `Object.create(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1867
+ objectAssign: (args, context) => `Object.assign(${args.map(a => generateExpr(a, context)).join(', ')})`,
1868
+ objectKeys: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
1869
+ objectValues: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
1870
+ objectEntries: (args, context) => `Object.entries(${generateExpr(args[0], context)})`,
1871
+ objectHasOwn: (args, context) => `Object.hasOwn(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1872
+ objectDefineProperty: (args, context) => `Object.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1873
+ objectDefineProperties: (args, context) => `Object.defineProperties(${args.map(a => generateExpr(a, context)).join(', ')})`,
1874
+ objectGetOwnPropertyDescriptor: (args, context) => `Object.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1875
+ objectGetOwnPropertyNames: (args, context) => `Object.getOwnPropertyNames(${generateExpr(args[0], context)})`,
1876
+ objectIsExtensible: (args, context) => `Object.isExtensible(${generateExpr(args[0], context)})`,
1877
+ objectIsFrozen: (args, context) => `Object.isFrozen(${generateExpr(args[0], context)})`,
1878
+ objectIsSealed: (args, context) => `Object.isSealed(${generateExpr(args[0], context)})`,
1879
+ objectPreventExtensions: (args, context) => `Object.preventExtensions(${generateExpr(args[0], context)})`,
1880
+ objectFreeze: (args, context) => `Object.freeze(${generateExpr(args[0], context)})`,
1881
+ objectSeal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
1882
+
1883
+ // ── v1.0.2 — Symbol support (IOPL-native).
1884
+ symbol: (args, context) => `Symbol(${args.length > 0 ? generateExpr(args[0], context) : 'undefined'})`,
1885
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
1886
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
1887
+ symbolIterator: (_args) => `Symbol.iterator`,
1888
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
1889
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
1890
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
1891
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
1892
+ symbolMatch: (_args) => `Symbol.match`,
1893
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
1894
+ symbolReplace: (_args) => `Symbol.replace`,
1895
+ symbolSearch: (_args) => `Symbol.search`,
1896
+ symbolSplit: (_args) => `Symbol.split`,
1897
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
1898
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
1899
+
1900
+ // ── v1.0.2 — Math static methods (IOPL-native).
1901
+ mathAbs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
1902
+ mathMin: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
1903
+ mathMax: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
1904
+ mathSqrt: (args, context) => `Math.sqrt(${generateExpr(args[0], context)})`,
1905
+ mathPow: (args, context) => `Math.pow(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1906
+ mathFloor: (args, context) => `Math.floor(${generateExpr(args[0], context)})`,
1907
+ mathCeil: (args, context) => `Math.ceil(${generateExpr(args[0], context)})`,
1908
+ mathRound: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1909
+ mathTrunc: (args, context) => `Math.trunc(${generateExpr(args[0], context)})`,
1910
+ mathSign: (args, context) => `Math.sign(${generateExpr(args[0], context)})`,
1911
+ mathRandom: (_args) => `Math.random()`,
1912
+ mathClamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
1913
+ mathPI: (_args) => `Math.PI`,
1914
+ mathE: (_args) => `Math.E`,
1915
+ mathLN2: (_args) => `Math.LN2`,
1916
+ mathLN10: (_args) => `Math.LN10`,
1917
+ mathLOG2E: (_args) => `Math.LOG2E`,
1918
+ mathLOG10E: (_args) => `Math.LOG10E`,
1919
+ mathSin: (args, context) => `Math.sin(${generateExpr(args[0], context)})`,
1920
+ mathCos: (args, context) => `Math.cos(${generateExpr(args[0], context)})`,
1921
+ mathTan: (args, context) => `Math.tan(${generateExpr(args[0], context)})`,
1922
+ mathAsin: (args, context) => `Math.asin(${generateExpr(args[0], context)})`,
1923
+ mathAcos: (args, context) => `Math.acos(${generateExpr(args[0], context)})`,
1924
+ mathAtan: (args, context) => `Math.atan(${generateExpr(args[0], context)})`,
1925
+ mathAtan2: (args, context) => `Math.atan2(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1926
+ mathSinh: (args, context) => `Math.sinh(${generateExpr(args[0], context)})`,
1927
+ mathCosh: (args, context) => `Math.cosh(${generateExpr(args[0], context)})`,
1928
+ mathTanh: (args, context) => `Math.tanh(${generateExpr(args[0], context)})`,
1929
+ mathExp: (args, context) => `Math.exp(${generateExpr(args[0], context)})`,
1930
+ mathExpm1: (args, context) => `Math.expm1(${generateExpr(args[0], context)})`,
1931
+ mathLog: (args, context) => `Math.log(${generateExpr(args[0], context)})`,
1932
+ mathLog1p: (args, context) => `Math.log1p(${generateExpr(args[0], context)})`,
1933
+ mathLog2: (args, context) => `Math.log2(${generateExpr(args[0], context)})`,
1934
+ mathLog10: (args, context) => `Math.log10(${generateExpr(args[0], context)})`,
1935
+ mathHypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
1936
+ mathCbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
1937
+
1938
+ // ── v1.0.2 — TypedArray support (IOPL-native).
1939
+ int8Array: (args, context) => `new Int8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1940
+ uint8Array: (args, context) => `new Uint8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1941
+ uint8ClampedArray: (args, context) => `new Uint8ClampedArray(${args.map(a => generateExpr(a, context)).join(', ')})`,
1942
+ int16Array: (args, context) => `new Int16Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1943
+ uint16Array: (args, context) => `new Uint16Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1944
+ int32Array: (args, context) => `new Int32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1945
+ uint32Array: (args, context) => `new Uint32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1946
+ float32Array: (args, context) => `new Float32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1947
+ float64Array: (args, context) => `new Float64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1948
+ bigInt64Array: (args, context) => `new BigInt64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1949
+ bigUint64Array: (args, context) => `new BigUint64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
1950
+ dataView: (args, context) => `new DataView(${args.map(a => generateExpr(a, context)).join(', ')})`,
1951
+ arrayBuffer: (args, context) => `new ArrayBuffer(${args.map(a => generateExpr(a, context)).join(', ')})`,
1952
+
1953
+ // ── v1.0.2 — Global objects access (IOPL-native).
1954
+ globalThis: (_args) => `globalThis`,
1955
+ console: (_args) => `console`,
1956
+ process: (_args) => `process`,
1957
+ Buffer: (_args) => `Buffer`,
1958
+
1959
+ // ── v2.3.0 — EventSource / Server-Sent Events (IOPL-native).
1960
+ eventSource: (args, context) => `new EventSource(${args.map(a => generateExpr(a, context)).join(', ')})`,
1961
+
1962
+ // ── v2.2.0 — URL and URLSearchParams (IOPL-native).
1963
+ url: (args, context) => `new URL(${generateExpr(args[0], context)}${args[1] ? `, ${generateExpr(args[1], context)}` : ''})`,
1964
+ urlSearchParams: (args, context) => `new URLSearchParams(${args.length ? generateExpr(args[0], context) : ''})`,
1965
+
1966
+ // ── v2.2.0 — Intl / Internationalization (IOPL-native).
1967
+ dateTimeFormat: (args, context) => `new Intl.DateTimeFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1968
+ numberFormat: (args, context) => `new Intl.NumberFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1969
+ collator: (args, context) => `new Intl.Collator(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1970
+
1971
+ // ── v2.2.0 — Crypto / Web Crypto API (IOPL-native).
1972
+ cryptoRandomUUID: (_args) => `crypto.randomUUID()`,
1973
+ cryptoGetRandomValues: (args, context) => `crypto.getRandomValues(${generateExpr(args[0], context)})`,
1974
+ cryptoSubtleDigest: (args, context) => `crypto.subtle.digest(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1975
+ cryptoSubtleEncrypt: (args, context) => `crypto.subtle.encrypt(${args.map(a => generateExpr(a, context)).join(', ')})`,
1976
+ cryptoSubtleDecrypt: (args, context) => `crypto.subtle.decrypt(${args.map(a => generateExpr(a, context)).join(', ')})`,
1977
+ cryptoSubtleSign: (args, context) => `crypto.subtle.sign(${args.map(a => generateExpr(a, context)).join(', ')})`,
1978
+ cryptoSubtleVerify: (args, context) => `crypto.subtle.verify(${args.map(a => generateExpr(a, context)).join(', ')})`,
1979
+ cryptoSubtleGenerateKey: (args, context) => `crypto.subtle.generateKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1980
+ cryptoSubtleDeriveKey: (args, context) => `crypto.subtle.deriveKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1981
+ cryptoSubtleImportKey: (args, context) => `crypto.subtle.importKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1982
+ cryptoSubtleExportKey: (args, context) => `crypto.subtle.exportKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1983
+ cryptoSubtleWrapKey: (args, context) => `crypto.subtle.wrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1984
+ cryptoSubtleUnwrapKey: (args, context) => `crypto.subtle.unwrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
1985
+
1986
+ // ── v2.2.0 — WeakMap / WeakSet / WeakRef / FinalizationRegistry (IOPL-native).
1987
+ weakMap: (_args) => `new WeakMap()`,
1988
+ weakSet: (_args) => `new WeakSet()`,
1989
+ weakRef: (args, context) => `new WeakRef(${generateExpr(args[0], context)})`,
1990
+ finalizationRegistry: (args, context) => `new FinalizationRegistry(${generateExpr(args[0], context)})`,
1991
+
1992
+ // ── v2.2.0 — Proxy / Reflect (IOPL-native).
1993
+ proxy: (args, context) => `new Proxy(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1994
+ reflectGet: (args, context) => `Reflect.get(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1995
+ reflectSet: (args, context) => `Reflect.set(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
1996
+ reflectHas: (args, context) => `Reflect.has(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1997
+ reflectDeleteProperty: (args, context) => `Reflect.deleteProperty(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1998
+ reflectConstruct: (args, context) => `Reflect.construct(${args.map(a => generateExpr(a, context)).join(', ')})`,
1999
+ reflectApply: (args, context) => `Reflect.apply(${args.map(a => generateExpr(a, context)).join(', ')})`,
2000
+ reflectOwnKeys: (args, context) => `Reflect.ownKeys(${generateExpr(args[0], context)})`,
2001
+ reflectDefineProperty: (args, context) => `Reflect.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
2002
+ reflectGetOwnPropertyDescriptor: (args, context) => `Reflect.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2003
+
2004
+ // ── v2.2.0 — Symbol (IOPL-native).
2005
+ symbol: (args, context) => `Symbol(${args.length ? generateExpr(args[0], context) : 'undefined'})`,
2006
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
2007
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
2008
+ symbolIterator: (_args) => `Symbol.iterator`,
2009
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
2010
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
2011
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
2012
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
2013
+ symbolMatch: (_args) => `Symbol.match`,
2014
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
2015
+ symbolReplace: (_args) => `Symbol.replace`,
2016
+ symbolSearch: (_args) => `Symbol.search`,
2017
+ symbolSplit: (_args) => `Symbol.split`,
2018
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
2019
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
2020
+
2021
+ // ── v2.2.0 — BigInt (IOPL-native).
2022
+ bigInt: (args, context) => `BigInt(${generateExpr(args[0], context)})`,
2023
+ bigIntAsIntN: (args, context) => `BigInt.asIntN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2024
+ bigIntAsUintN: (args, context) => `BigInt.asUintN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2025
+
2026
+ // ── v2.2.0 — Atomics / SharedArrayBuffer (IOPL-native).
2027
+ atomicsAdd: (args, context) => `Atomics.add(${args.map(a => generateExpr(a, context)).join(', ')})`,
2028
+ atomicsSub: (args, context) => `Atomics.sub(${args.map(a => generateExpr(a, context)).join(', ')})`,
2029
+ atomicsAnd: (args, context) => `Atomics.and(${args.map(a => generateExpr(a, context)).join(', ')})`,
2030
+ atomicsOr: (args, context) => `Atomics.or(${args.map(a => generateExpr(a, context)).join(', ')})`,
2031
+ atomicsXor: (args, context) => `Atomics.xor(${args.map(a => generateExpr(a, context)).join(', ')})`,
2032
+ atomicsExchange: (args, context) => `Atomics.exchange(${args.map(a => generateExpr(a, context)).join(', ')})`,
2033
+ atomicsCompareExchange: (args, context) => `Atomics.compareExchange(${args.map(a => generateExpr(a, context)).join(', ')})`,
2034
+ atomicsLoad: (args, context) => `Atomics.load(${args.map(a => generateExpr(a, context)).join(', ')})`,
2035
+ atomicsStore: (args, context) => `Atomics.store(${args.map(a => generateExpr(a, context)).join(', ')})`,
2036
+ atomicsWait: (args, context) => `Atomics.wait(${args.map(a => generateExpr(a, context)).join(', ')})`,
2037
+ atomicsNotify: (args, context) => `Atomics.notify(${args.map(a => generateExpr(a, context)).join(', ')})`,
2038
+ atomicsIsLockFree: (args, context) => `Atomics.isLockFree(${generateExpr(args[0], context)})`,
2039
+ sharedArrayBuffer: (args, context) => `new SharedArrayBuffer(${generateExpr(args[0], context)})`,
2040
+
2041
+ // ── v2.2.0 — Error subclasses (IOPL-native).
2042
+ error: (args, context) => `new Error(${args.length ? generateExpr(args[0], context) : ''})`,
2043
+ typeError: (args, context) => `new TypeError(${args.length ? generateExpr(args[0], context) : ''})`,
2044
+ rangeError: (args, context) => `new RangeError(${args.length ? generateExpr(args[0], context) : ''})`,
2045
+ referenceError: (args, context) => `new ReferenceError(${args.length ? generateExpr(args[0], context) : ''})`,
2046
+ syntaxError: (args, context) => `new SyntaxError(${args.length ? generateExpr(args[0], context) : ''})`,
2047
+ evalError: (args, context) => `new EvalError(${args.length ? generateExpr(args[0], context) : ''})`,
2048
+ uriError: (args, context) => `new URIError(${args.length ? generateExpr(args[0], context) : ''})`,
2049
+ aggregateError: (args, context) => `new AggregateError(${args.map(a => generateExpr(a, context)).join(', ')})`,
2050
+
2051
+ // ── v2.2.0 — Blob / File / FormData (IOPL-native, browser-compatible).
2052
+ blob: (args, context) => `new Blob(${args.map(a => generateExpr(a, context)).join(', ')})`,
2053
+ file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2054
+ formData: (_args) => `new FormData()`,
1501
2055
  };
1502
2056
 
1503
- // Mark the enclosing program async when a call awaits at the top level.
2057
+ // Mark the enclosing program async when a call awaits at the top level, and
2058
+ // record that this scope emitted an `await` so handler and function bodies can
2059
+ // decide their own async-ness at generation time (see generateBlock). Routing
2060
+ // every await-emitting construct through this single function removes the need
2061
+ // for a separate hand-maintained registry of async statement types — so a new
2062
+ // async keyword can never silently break when used inside a route, listener, or
2063
+ // function.
1504
2064
  function markAsync(context) {
1505
- if (!context.inFunction) context.needsAsync = true;
2065
+ context.emittedAwait = true;
2066
+ // Only a construct that awaits at the true top level needs the program
2067
+ // wrapped in an async IIFE. Awaits emitted inside a user function (inFunction)
2068
+ // or inside a route/listener/404 handler (inHandler) are handled by marking
2069
+ // that function/handler async instead — they must not drag the whole program
2070
+ // into an async wrapper, or "top-level use wraps the whole program" would be
2071
+ // the only safe nesting level for a new async keyword.
2072
+ if (!context.inFunction && !context.inHandler) context.needsAsync = true;
2073
+ }
2074
+
2075
+ // Generate a body of statements and report whether it emitted an `await`.
2076
+ //
2077
+ // This is the single source of truth for whether a route handler, listener,
2078
+ // 404 handler, or user function must be declared `async`. Previously this was
2079
+ // decided by a separate AST walker (containsAsyncBlock) that had to be kept in
2080
+ // sync by hand with every construct that compiles down to `await` — the exact
2081
+ // fragility that made "top-level use wraps the whole program" the only place
2082
+ // certain keywords (like ocr) were guaranteed to work. By observing the output
2083
+ // of generation instead, whatever a body contains is handled correctly, even if
2084
+ // it uses a brand-new async keyword.
2085
+ function generateBlock(statements, indent, context) {
2086
+ const prev = context.emittedAwait;
2087
+ context.emittedAwait = false;
2088
+ const out = statements.map(s => generateStatement(s, indent, context)).join('\n');
2089
+ const emitted = context.emittedAwait;
2090
+ context.emittedAwait = prev;
2091
+ return { out, emitted };
1506
2092
  }
1507
2093
 
1508
2094
  // v2.1.0 — generate a request accessor (param/query/header). These compile to
@@ -1574,6 +2160,7 @@ function emitSqlCall(kind, sql, params, indent, context) {
1574
2160
  let n = 0;
1575
2161
  const pgSql = String(sql).replace(/\?/g, () => (++n <= params.length ? `$${n}` : '?'));
1576
2162
  const call = `${_sqlClientVar}.query(\`${pgSql}\`, [${args}])`;
2163
+ markAsync(context);
1577
2164
  return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
1578
2165
  }
1579
2166
  switch (kind) {
@@ -1589,7 +2176,10 @@ function createGenerationContext() {
1589
2176
  requires: new Set(),
1590
2177
  pendingPrelude: [],
1591
2178
  needsAsync: false, // true when top-level code emits await (js blocks / ask)
2179
+ emittedAwait: false, // true when the current generateBlock emitted an await
1592
2180
  inFunction: false, // true while generating inside a function-like scope
2181
+ inHandler: false, // true while generating a route/listener/404 response body
2182
+ loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
1593
2183
  };
1594
2184
  }
1595
2185
 
@@ -1653,72 +2243,6 @@ function ensureBuiltin(context, moduleName) {
1653
2243
  }
1654
2244
  }
1655
2245
 
1656
- // Builtins whose calls await. A statement containing one of these anywhere in
1657
- // its expressions must compile into an async context.
1658
- const ASYNC_CALL_NAMES = new Set([
1659
- // v2.1.0 — cache and email
1660
- 'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
1661
- // v2.2.0 — AI/ML calls await their model endpoint
1662
- 'chat', 'embedText',
1663
- // v1.2 — Telegram helpers (await their API transport)
1664
- 'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
1665
- ]);
1666
-
1667
- // Collect async builtin call names reachable from an AST fragment.
1668
- function findAsyncCalls(node, found) {
1669
- if (!node || typeof node !== 'object') return found;
1670
- if (Array.isArray(node)) {
1671
- for (const item of node) findAsyncCalls(item, found);
1672
- return found;
1673
- }
1674
- if (node.type === 'CallExpression' && ASYNC_CALL_NAMES.has(node.name)) {
1675
- found.add(node.name);
1676
- }
1677
- // v2.1.1 — HTTP client calls await; "wait for <expr>" awaits explicitly.
1678
- if (node.type === 'HttpCall' || node.type === 'AwaitExpression') {
1679
- found.add(node.type);
1680
- }
1681
- for (const value of Object.values(node)) {
1682
- if (value && typeof value === 'object') findAsyncCalls(value, found);
1683
- }
1684
- return found;
1685
- }
1686
-
1687
- // True when any statement in the block emits `await` (a JavaScript block,
1688
- // `ask`, or `ocr`), including inside nested if / loop bodies. Nested PlainScript
1689
- // function declarations are handled independently, so they are not descended
1690
- // into.
1691
- function containsAsyncBlock(statements) {
1692
- for (const stmt of statements || []) {
1693
- if (stmt.type === 'AskStatement' || stmt.type === 'JavaScriptBlock' || stmt.type === 'OcrStatement') return true;
1694
- // v2.1.0 — transactions always await; PostgreSQL SQL statements await;
1695
- // mail sends, cache setup and websocket handlers await.
1696
- if (stmt.type === 'TransactionStatement') return true;
1697
- if (stmt.type === 'SendMailStatement' || stmt.type === 'CacheStatement') return true;
1698
- // v2.1.1 — opening the database awaits (native/wasm engine probe);
1699
- // retry loops pause between attempts; try/recover recurse.
1700
- if (stmt.type === 'DatabaseStatement' || stmt.type === 'RetryStatement') return true;
1701
- if (stmt.type === 'TryStatement') {
1702
- if (containsAsyncBlock(stmt.tryBody)) return true;
1703
- if (stmt.recoverBody && containsAsyncBlock(stmt.recoverBody)) return true;
1704
- continue;
1705
- }
1706
- if (_sqlDriver === 'pg' && (
1707
- stmt.type === 'QueryStatement' || stmt.type === 'InsertStatement' ||
1708
- stmt.type === 'UpdateStatement' || stmt.type === 'DeleteStatement' ||
1709
- stmt.type === 'ExecuteStatement' || stmt.type === 'RememberSqlStatement'
1710
- )) return true;
1711
- if (findAsyncCalls(stmt, new Set()).size > 0) return true;
1712
- if (stmt.type === 'IfStatement') {
1713
- if (containsAsyncBlock(stmt.consequent)) return true;
1714
- if (stmt.alternate && containsAsyncBlock(stmt.alternate)) return true;
1715
- } else if (stmt.type !== 'FunctionDeclaration' && stmt.body) {
1716
- if (containsAsyncBlock(stmt.body)) return true;
1717
- }
1718
- }
1719
- return false;
1720
- }
1721
-
1722
2246
  // True when any statement in a block (recursively, skipping nested function
1723
2247
  // declarations) contains a `yield`, which marks the enclosing function as a
1724
2248
  // generator (function*).
@@ -1738,7 +2262,7 @@ function containsYield(statements) {
1738
2262
  function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
1739
2263
  throw new Error(`Expected a Program node but got "${ast.type}".`);
1740
2264
  }
1741
- // v1.0.0 — reset per-program test bookkeeping so repeated generate() calls
2265
+ // v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
1742
2266
  // (build pipeline) start clean.
1743
2267
  __testCount = 0;
1744
2268
  __testCatchers = [];
@@ -1760,7 +2284,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
1760
2284
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
1761
2285
  }
1762
2286
 
1763
- // v1.0.0 — native test runner. When any "test ... done" block exists, emit
2287
+ // v1.0.1 — native test runner. When any "test ... done" block exists, emit
1764
2288
  // the runner helper, register each test after its function declaration, and
1765
2289
  // execute them. Each failure prints a message and sets process.exitCode = 1.
1766
2290
  if (__testCatchers.length > 0) {
@@ -1795,7 +2319,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
1795
2319
  return lines.join('\n');
1796
2320
  }
1797
2321
 
1798
- // ── v1.0.0 — test DSL bookkeeping ───────────────────────────────────────────
2322
+ // ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
1799
2323
  let __testCount = 0;
1800
2324
  let __testCatchers = [];
1801
2325
  let __inTest = false;
@@ -1836,8 +2360,16 @@ function generateCondition(cond, context) {
1836
2360
 
1837
2361
  function generateStatement(node, indent = '', context = createGenerationContext()) {
1838
2362
  switch (node.type) {
1839
- case 'RememberStatement':
2363
+ case 'RememberStatement': {
2364
+ // Handle destructuring: remember [a, b] as arr / remember {x, y} as obj
2365
+ if (node.name && typeof node.name === 'object' && (node.name.type === 'ArrayPattern' || node.name.type === 'ObjectPattern')) {
2366
+ const pattern = node.name.type === 'ArrayPattern'
2367
+ ? `[${node.name.elements.map(e => generateLValue(e, context)).join(', ')}]`
2368
+ : `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
2369
+ return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
2370
+ }
1840
2371
  return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
2372
+ }
1841
2373
 
1842
2374
  case 'ShowStatement':
1843
2375
  return `${indent}console.log(${generateExpr(node.value, context)});`;
@@ -1845,18 +2377,49 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1845
2377
  case 'GiveStatement':
1846
2378
  return `${indent}return ${generateExpr(node.value, context)};`;
1847
2379
 
1848
- case 'BecomeStatement':
1849
- return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
2380
+ case 'BecomeStatement': {
2381
+ // Handle destructuring: [a, b] = arr / {x, y} = obj
2382
+ if (node.target && typeof node.target === 'object' && (node.target.type === 'ArrayPattern' || node.target.type === 'ObjectPattern')) {
2383
+ const pattern = node.target.type === 'ArrayPattern'
2384
+ ? `[${node.target.elements.map(e => generateLValue(e, context)).join(', ')}]`
2385
+ : `{ ${node.target.properties.map(p => generateLValue(p, context)).join(', ')} }`;
2386
+ return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
2387
+ }
2388
+ const target = generateLValue(node.target, context);
2389
+ const value = generateExpr(node.value, context);
2390
+ const op = node.op || '=';
2391
+ if (op === '=') {
2392
+ return `${indent}${target} = ${value};`;
2393
+ }
2394
+ // Logical assignment: x ||= y, x &&= y, x ??= y
2395
+ // In JS: x ||= y -> x || (x = y)
2396
+ // We need to handle this carefully for member expressions
2397
+ const opMap = { '||=': '||', '&&=': '&&', '??=': '??' };
2398
+ const jsOp = opMap[op];
2399
+ if (jsOp) {
2400
+ return `${indent}${target} ${jsOp} (${target} = ${value});`;
2401
+ }
2402
+ return `${indent}${target} ${op} ${value};`;
2403
+ }
1850
2404
 
1851
- // v1.0.0 — record kinds: `define a kind called "Person" with ... done`.
2405
+ // v1.0.1 — record kinds: `define a kind called "Person" with ... done`.
1852
2406
  // Names are emitted as a JS factory that returns a fresh plain object with
1853
2407
  // declared defaults. Constructors prompt for required fields at compile
1854
2408
  // time via `create a Person with ...` (see GenerateExpr CreateKind).
2409
+ // v1.0.2 — supports `extends` for inheritance.
1855
2410
  case 'DefineKindStatement': {
1856
- const members = node.fields.map(f =>
1857
- `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
1858
- );
1859
- const defaults = `{ ${members.join(', ')} }`;
2411
+ let defaults = '';
2412
+ if (node.extends) {
2413
+ // Inherit from parent kind by spreading its defaults
2414
+ defaults = `{ ...__makeKind_${node.extends}({}), ${node.fields.map(f =>
2415
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
2416
+ ).join(', ')} }`;
2417
+ } else {
2418
+ const members = node.fields.map(f =>
2419
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
2420
+ );
2421
+ defaults = `{ ${members.join(', ')} }`;
2422
+ }
1860
2423
  return [
1861
2424
  `${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
1862
2425
  `${indent} const __rec = ${defaults};`,
@@ -1872,14 +2435,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1872
2435
  ].join('\n');
1873
2436
  }
1874
2437
 
1875
- // v1.0.0 — load env file "<path>": apply KEY=VALUE pairs to process.env.
2438
+ // v1.0.1 — load env file "<path>": apply KEY=VALUE pairs to process.env.
1876
2439
  // Blank lines and `#` comments are skipped; values keep their text.
1877
2440
  case 'LoadEnvFileStatement': {
1878
2441
  ensureBuiltin(context, 'dotenv');
1879
2442
  return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
1880
2443
  }
1881
2444
 
1882
- // v1.0.0 — native test DSL. `test "<name>" ... done` registers a runnable
2445
+ // v1.0.1 — native test DSL. `test "<name>" ... done` registers a runnable
1883
2446
  // unit; all tests are executed after the program body with a tiny runner.
1884
2447
  case 'TestStatement': {
1885
2448
  __testCount++;
@@ -1892,7 +2455,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1892
2455
  return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
1893
2456
  }
1894
2457
 
1895
- // v1.0.0 — assertion `check <a> (equals|is|contains|raises) <b>`.
2458
+ // v1.0.1 — assertion `check <a> (equals|is|contains|raises) <b>`.
1896
2459
  // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
1897
2460
  // inside the runner's try/catch (its thrown error is the subject).
1898
2461
  case 'CheckStatement': {
@@ -1906,11 +2469,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1906
2469
  return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
1907
2470
  }
1908
2471
 
1909
- // v1.0.0 — export <name>: mark a top-level symbol for module.exports.
2472
+ // v1.0.1 — export <name>: mark a top-level symbol for module.exports.
1910
2473
  case 'ExportStatement':
1911
2474
  return `${indent}module.exports.${node.name} = ${node.name};`;
1912
2475
 
1913
- // v1.0.0 — generators: `yield <expr>` (or bare `yield`).
2476
+ // v1.0.1 — generators: `yield <expr>` (or bare `yield`).
1914
2477
  case 'YieldStatement': {
1915
2478
  if (!context.inFunction) {
1916
2479
  throw new Error('"yield" can only be used inside a function created with "make".\n\nExample:\n make countUp(n)\n let i = 0\n while i less than n\n i = i + 1\n yield i\n done\n done');
@@ -1931,51 +2494,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1931
2494
  return pkg ? `${indent}${pkg}` : '';
1932
2495
  }
1933
2496
 
1934
- // v1.1.1 — JavaScript Gateway (RFC-0011)
1935
-
1936
- // remember <name> as javascript … done (named — always produces a value)
1937
- // javascript … done (statement-level block)
1938
- case 'JavaScriptBlock': {
1939
- // Validate the raw JavaScript at compile time so JS syntax errors are
1940
- // reported as such, with the PlainScript context that produced them.
1941
- try {
1942
- new vm.Script(`(async () => {\n${node.body}\n})`);
1943
- } catch (e) {
1944
- const label = node.name ? `assigned to "${node.name}"` : 'block';
1945
- throw new Error(
1946
- `JavaScript error inside the "javascript" ${label}: ${e.message}`
1947
- );
1948
- }
1949
- // Does the body use top-level `await`? Top-level await only parses
1950
- // inside an async function, so a plain Script rejects it. Synchronous
1951
- // statement-level blocks need no wrapper; async ones do.
1952
- let hasTopLevelAwait = false;
1953
- try {
1954
- new vm.Script(node.body);
1955
- } catch (_) {
1956
- hasTopLevelAwait = true;
1957
- }
1958
- // Named blocks always bind a value, so they keep the async IIFE. The
1959
- // body is emitted verbatim: JavaScript indentation, template literals,
1960
- // and line structure are preserved as written (RFC-0011 §31).
1961
- if (node.name) {
1962
- if (!context.inFunction) context.needsAsync = true;
1963
- return `${indent}let ${node.name} = await (async () => {\n${node.body}\n${indent}})();`;
1964
- }
1965
- // Statement-level blocks inside functions/routes/loops, or that need
1966
- // top-level await, retain the async-context wrapper.
1967
- if (context.inFunction || hasTopLevelAwait) {
1968
- if (!context.inFunction) context.needsAsync = true;
1969
- return `${indent}await (async () => {\n${node.body}\n${indent}})();`;
1970
- }
1971
- // Synchronous statement-level block: emit its body directly/verbatim.
1972
- return `${indent}${node.body}`;
1973
- }
1974
-
1975
2497
  // ask name / ask "<prompt>" as name
1976
2498
  case 'AskStatement': {
1977
2499
  ensureBuiltin(context, 'ask');
1978
- if (!context.inFunction) context.needsAsync = true;
2500
+ markAsync(context);
1979
2501
  const prompt = node.prompt != null ? JSON.stringify(node.prompt) : '"> "';
1980
2502
  return `${indent}let ${node.variable} = await __ask(${prompt});`;
1981
2503
  }
@@ -1983,27 +2505,42 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1983
2505
  // v2.0.1 — ocr "<image>" as <variable> [using "<lang>"]
1984
2506
  case 'OcrStatement': {
1985
2507
  ensureBuiltin(context, 'ocr');
1986
- if (!context.inFunction) context.needsAsync = true;
2508
+ markAsync(context);
1987
2509
  const image = generateExpr(node.image, context);
1988
2510
  const langArg = node.lang != null ? `, ${JSON.stringify(node.lang)}` : '';
1989
2511
  return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
1990
2512
  }
1991
2513
 
1992
2514
  case 'FunctionDeclaration': {
1993
- const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2515
+ const prevInFunction = context.inFunction;
2516
+ context.inFunction = true;
2517
+ const block = generateBlock(node.body, indent + ' ', context);
2518
+ context.inFunction = prevInFunction;
2519
+ const isAsync = block.emitted ? 'async ' : '';
1994
2520
  const isGen = containsYield(node.body) ? '*' : '';
1995
2521
  const paramStr = node.params.map(p => {
2522
+ // Rest parameter: ...args
2523
+ if (p && p.type === 'RestElement') {
2524
+ return `...${p.name}`;
2525
+ }
2526
+ // Destructuring: [a, b] or {x, y}
2527
+ if (p && (p.type === 'ArrayPattern' || p.type === 'ObjectPattern')) {
2528
+ const pattern = p.type === 'ArrayPattern'
2529
+ ? `[${p.elements.map(e => generateLValue(e, context)).join(', ')}]`
2530
+ : `{ ${p.properties.map(prop => generateLValue(prop, context)).join(', ')} }`;
2531
+ if (p.defaultValue) {
2532
+ return `${pattern} = ${generateExpr(p.defaultValue, context)}`;
2533
+ }
2534
+ return pattern;
2535
+ }
2536
+ // Regular parameter
1996
2537
  if (typeof p === 'object') {
1997
2538
  if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
1998
2539
  return p.name;
1999
2540
  }
2000
2541
  return p;
2001
2542
  }).join(', ');
2002
- const prevInFunction = context.inFunction;
2003
- context.inFunction = true;
2004
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2005
- context.inFunction = prevInFunction;
2006
- return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${body}\n${indent}}`;
2543
+ return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${block.out}\n${indent}}`;
2007
2544
  }
2008
2545
 
2009
2546
  case 'IfStatement': {
@@ -2018,37 +2555,129 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2018
2555
  }
2019
2556
 
2020
2557
  case 'ForEachStatement': {
2558
+ context.loopDepth++;
2021
2559
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2560
+ context.loopDepth--;
2022
2561
  return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
2023
2562
  }
2024
2563
 
2564
+ case 'ForIndexStatement': {
2565
+ context.loopDepth++;
2566
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2567
+ context.loopDepth--;
2568
+ // for index <name> in <collection> — zero-based index over a list.
2569
+ if (node.over != null) {
2570
+ const coll = generateExpr(node.over, context);
2571
+ return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
2572
+ }
2573
+ const start = generateExpr(node.start, context);
2574
+ const end = generateExpr(node.end, context);
2575
+ // Explicit step uses the user's sign; otherwise the increment follows
2576
+ // the direction of the bounds (from 5 to 1 counts down automatically).
2577
+ const inc = node.step ? generateExpr(node.step, context)
2578
+ : `(${start} <= ${end} ? 1 : -1)`;
2579
+ // Direction-aware: "from 5 to 1" counts down even without an explicit
2580
+ // "by", while "from 1 to 5" counts up.
2581
+ const test = `(${start} <= ${end} ? ${node.name} <= ${end} : ${node.name} >= ${end})`;
2582
+ return `${indent}for (let ${node.name} = ${start}; ${test}; ${node.name} += ${inc}) {\n${body}\n${indent}}`;
2583
+ }
2584
+
2025
2585
  case 'WhileStatement': {
2026
2586
  const condition = generateCondition(node.condition, context);
2027
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2587
+ context.loopDepth++;
2588
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2589
+ context.loopDepth--;
2028
2590
  return `${indent}while (${condition}) {\n${body}\n${indent}}`;
2029
2591
  }
2030
2592
 
2593
+ case 'BreakStatement': {
2594
+ if (context.loopDepth <= 0) {
2595
+ throw new Error('"break" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if done(item)\n break\n done\n done');
2596
+ }
2597
+ return `${indent}break;`;
2598
+ }
2599
+
2600
+ case 'ContinueStatement': {
2601
+ if (context.loopDepth <= 0) {
2602
+ throw new Error('"continue" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if skip(item)\n continue\n done\n done');
2603
+ }
2604
+ return `${indent}continue;`;
2605
+ }
2606
+
2607
+ case 'DebuggerStatement':
2608
+ return `${indent}debugger;`;
2609
+
2610
+ case 'ThrowStatement':
2611
+ return `${indent}throw ${generateExpr(node.value, context)};`;
2612
+
2613
+ case 'ReturnStatement':
2614
+ return `${indent}return${node.value ? ' ' + generateExpr(node.value, context) : ''};`;
2615
+
2616
+ case 'BreakStatement': {
2617
+ if (context.loopDepth <= 0) {
2618
+ throw new Error('"break" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if done(item)\n break\n done\n done');
2619
+ }
2620
+ return `${indent}break;`;
2621
+ }
2622
+
2623
+ case 'ContinueStatement': {
2624
+ if (context.loopDepth <= 0) {
2625
+ throw new Error('"continue" can only be used inside a loop (for each, for index, or while).\n\nExample:\n for each item in list\n if skip(item)\n continue\n done\n done');
2626
+ }
2627
+ return `${indent}continue;`;
2628
+ }
2629
+
2630
+ case 'SwitchStatement': {
2631
+ const discriminant = generateExpr(node.discriminant, context);
2632
+ const cases = node.cases.map(c => {
2633
+ const test = generateExpr(c.test, context);
2634
+ const body = c.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2635
+ return `${indent} case ${test}:\n${body}\n${indent} break;`;
2636
+ }).join('\n');
2637
+ let out = `${indent}switch (${discriminant}) {\n${cases}`;
2638
+ if (node.defaultCase) {
2639
+ const defaultBody = node.defaultCase.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2640
+ out += `\n${indent} default:\n${defaultBody}\n${indent} break;`;
2641
+ }
2642
+ out += `\n${indent}}`;
2643
+ return out;
2644
+ }
2645
+
2646
+ case 'ClassDeclaration': {
2647
+ const superClass = node.superClass ? ` extends ${generateExpr(node.superClass, context)}` : '';
2648
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2649
+ return `${indent}class ${node.name}${superClass} {\n${body}\n${indent}}`;
2650
+ }
2651
+
2031
2652
  // v0.3 — Express runtime
2032
2653
 
2033
2654
  case 'ListenStatement': {
2034
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2035
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2036
- return `${indent}app.listen(${generateExpr(node.port, context)}, ${handlerAsync}() => {\n${body}\n${indent}});`;
2655
+ const prevInHandler = context.inHandler;
2656
+ context.inHandler = true;
2657
+ const block = generateBlock(node.body, indent + ' ', context);
2658
+ context.inHandler = prevInHandler;
2659
+ const handlerAsync = block.emitted ? 'async ' : '';
2660
+ return `${indent}app.listen(${generateExpr(node.port, context)}, ${handlerAsync}() => {\n${block.out}\n${indent}});`;
2037
2661
  }
2038
2662
 
2039
2663
  case 'RouteStatement': {
2040
2664
  _inRoute = true;
2041
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2042
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2665
+ const prevInHandler = context.inHandler;
2666
+ context.inHandler = true;
2667
+ const block = generateBlock(node.body, indent + ' ', context);
2668
+ context.inHandler = prevInHandler;
2043
2669
  _inRoute = false;
2044
- return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
2670
+ const handlerAsync = block.emitted ? 'async ' : '';
2671
+ return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
2045
2672
  }
2046
2673
 
2047
2674
  case 'ReplyStatement':
2048
2675
  if (_inTelegram) {
2676
+ markAsync(context);
2049
2677
  return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)});`;
2050
2678
  }
2051
2679
  if (_inWhatsApp) {
2680
+ markAsync(context);
2052
2681
  ensureBuiltin(context, 'whatsapp');
2053
2682
  return `${indent}await __whatsappReply(__waCtx.chat, ${generateExpr(node.value, context)});`;
2054
2683
  }
@@ -2059,9 +2688,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2059
2688
  .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
2060
2689
  .join(', ');
2061
2690
  if (_inTelegram) {
2691
+ markAsync(context);
2062
2692
  return `${indent}await Telegram.sendMessage(ctx.chatId, JSON.stringify({ ${props} }));`;
2063
2693
  }
2064
2694
  if (_inWhatsApp) {
2695
+ markAsync(context);
2065
2696
  ensureBuiltin(context, 'whatsapp');
2066
2697
  return `${indent}await __whatsappReply(__waCtx.chat, JSON.stringify({ ${props} }));`;
2067
2698
  }
@@ -2074,6 +2705,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2074
2705
  // button is rendered as [text, data] and rows are merged into that list.
2075
2706
  case 'ReplyWithButtonsStatement': {
2076
2707
  ensureBuiltin(context, 'telegram');
2708
+ markAsync(context);
2077
2709
  const pairs = node.buttons.flat().map(({ text, data }) => [text, data]);
2078
2710
  return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)}, ${JSON.stringify(pairs)});`;
2079
2711
  }
@@ -2095,10 +2727,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2095
2727
 
2096
2728
  case 'SimpleRouteStatement': {
2097
2729
  _inRoute = true;
2098
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2099
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2730
+ const prevInHandler = context.inHandler;
2731
+ context.inHandler = true;
2732
+ const block = generateBlock(node.body, indent + ' ', context);
2733
+ context.inHandler = prevInHandler;
2100
2734
  _inRoute = false;
2101
- return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
2735
+ const handlerAsync = block.emitted ? 'async ' : '';
2736
+ return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
2102
2737
  }
2103
2738
 
2104
2739
  // v2.1.0 — group "<prefix>" ... done: composes routes under a shared
@@ -2225,10 +2860,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2225
2860
  // in registration order).
2226
2861
  case 'NotFoundStatement': {
2227
2862
  _inRoute = true;
2228
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2229
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2863
+ const prevInHandler = context.inHandler;
2864
+ context.inHandler = true;
2865
+ const block = generateBlock(node.body, indent + ' ', context);
2866
+ context.inHandler = prevInHandler;
2230
2867
  _inRoute = false;
2231
- return `${indent}app.use((${handlerAsync}req, res) => {\n${body}\n${indent}});`;
2868
+ const handlerAsync = block.emitted ? 'async ' : '';
2869
+ return `${indent}app.use((${handlerAsync}req, res) => {\n${block.out}\n${indent}});`;
2232
2870
  }
2233
2871
 
2234
2872
  // ── v2.1.1 — error handling and retries
@@ -2236,8 +2874,8 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2236
2874
  case 'TryStatement': {
2237
2875
  const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2238
2876
  const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
2877
+ const lines = [tryBlock];
2239
2878
  if (node.catches && node.catches.length > 0) {
2240
- const lines = [tryBlock];
2241
2879
  for (let i = 0; i < node.catches.length; i++) {
2242
2880
  const c = node.catches[i];
2243
2881
  const errorName = c.name || c.param || '__plainError';
@@ -2265,17 +2903,22 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2265
2903
  }
2266
2904
  }
2267
2905
  }
2268
- return lines.join('\n');
2269
- }
2270
- let out = tryBlock;
2271
- if (node.recoverBody) {
2906
+ } else if (node.recoverBody) {
2272
2907
  const errorName = node.catchName || '__plainError';
2273
2908
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2274
- out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
2909
+ lines.push(`${indent}} catch (${errorName}) {`);
2910
+ lines.push(recoverBody);
2911
+ lines.push(`${indent}}`);
2275
2912
  } else {
2276
- out += `${indent}} catch (__plainError) {}`;
2913
+ lines.push(`${indent}} catch (__plainError) {}`);
2277
2914
  }
2278
- return out;
2915
+ if (node.finallyBody) {
2916
+ const finallyBody = node.finallyBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2917
+ lines.push(`${indent}finally {`);
2918
+ lines.push(finallyBody);
2919
+ lines.push(`${indent}}`);
2920
+ }
2921
+ return lines.join('\n');
2279
2922
  }
2280
2923
 
2281
2924
  case 'RetryStatement': {
@@ -2321,7 +2964,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2321
2964
  case 'PostgresStatement': {
2322
2965
  _sqlDriver = 'pg';
2323
2966
  _sqlClientVar = 'db';
2324
- if (!context.inFunction) context.needsAsync = true;
2967
+ markAsync(context);
2325
2968
  return [
2326
2969
  emitRequire(context, 'postgres'),
2327
2970
  `${indent}const db = new Pool({ connectionString: ${generateExpr(node.connection, context)} });`,
@@ -2352,7 +2995,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2352
2995
  if (_sqlDriver === 'pg') {
2353
2996
  const prevClient = _sqlClientVar;
2354
2997
  _sqlClientVar = '__txClient';
2355
- if (!context.inFunction) context.needsAsync = true;
2998
+ markAsync(context);
2356
2999
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2357
3000
  _sqlClientVar = prevClient;
2358
3001
  return [
@@ -2385,7 +3028,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2385
3028
 
2386
3029
  case 'TelegramCommandStatement': {
2387
3030
  ensureBuiltin(context, 'telegram');
2388
- if (!context.inFunction) context.needsAsync = true;
3031
+ markAsync(context);
2389
3032
  _inTelegram = true;
2390
3033
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2391
3034
  _inTelegram = false;
@@ -2397,7 +3040,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2397
3040
 
2398
3041
  case 'TelegramCallbackStatement': {
2399
3042
  ensureBuiltin(context, 'telegram');
2400
- if (!context.inFunction) context.needsAsync = true;
3043
+ markAsync(context);
2401
3044
  _inTelegram = true;
2402
3045
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2403
3046
  _inTelegram = false;
@@ -2406,7 +3049,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2406
3049
 
2407
3050
  case 'TelegramStartStatement': {
2408
3051
  ensureBuiltin(context, 'telegram');
2409
- if (!context.inFunction) context.needsAsync = true;
3052
+ markAsync(context);
2410
3053
  return `${indent}await BOT.start();`;
2411
3054
  }
2412
3055
 
@@ -2445,7 +3088,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2445
3088
  // WhatsApp message as a normalized PlainScript record on `message`.
2446
3089
  case 'WhatsAppOnMessageStatement': {
2447
3090
  ensureBuiltin(context, 'whatsapp');
2448
- if (!context.inFunction) context.needsAsync = true;
3091
+ markAsync(context);
2449
3092
  const prevInWhatsApp = _inWhatsApp;
2450
3093
  _inWhatsApp = true;
2451
3094
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -2548,7 +3191,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2548
3191
 
2549
3192
  case 'RunBackgroundStatement':
2550
3193
  return [
2551
- `${indent}setImmediate(() => {`,
3194
+ `${indent}setImmediate(async () => {`,
2552
3195
  `${indent} try {`,
2553
3196
  `${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
2554
3197
  `${indent} } catch (error) { console.error(error); }`,
@@ -2666,6 +3309,9 @@ function generateLValue(node, context) {
2666
3309
  if (node.type === 'FirstItem') return `${generateExpr(node.collection, context)}[0]`;
2667
3310
  if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
2668
3311
  if (node.type === 'LastItem') return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
3312
+ // Destructuring patterns
3313
+ if (node.type === 'ArrayPattern') return `[${node.elements.map(e => generateLValue(e, context)).join(', ')}]`;
3314
+ if (node.type === 'ObjectPattern') return `{ ${node.properties.map(p => p.key).join(', ')} }`;
2669
3315
  throw new Error(`Invalid assignment target "${node.type}".`);
2670
3316
  }
2671
3317
 
@@ -2748,13 +3394,31 @@ function generateExpr(node, context = createGenerationContext()) {
2748
3394
  return `{ ${props} }`;
2749
3395
  }
2750
3396
 
3397
+ case 'ConditionalExpression':
3398
+ return `(${generateExpr(node.condition, context)} ? ${generateExpr(node.consequent, context)} : ${generateExpr(node.alternate, context)})`;
3399
+
3400
+ case 'NullishCoalesceExpression':
3401
+ return `(${generateExpr(node.left, context)} ?? ${generateExpr(node.right, context)})`;
3402
+
2751
3403
  case 'IndexExpression':
2752
3404
  return `${generateExpr(node.object, context)}[${generateExpr(node.index, context)}]`;
2753
3405
 
2754
3406
  case 'MemberExpression':
2755
3407
  return `${generateExpr(node.object, context)}.${node.property}`;
2756
3408
 
3409
+ case 'OptionalChainExpression':
3410
+ return `${generateExpr(node.object, context)}?.${node.property}`;
3411
+
3412
+ case 'OptionalCallExpression':
3413
+ return `${generateExpr(node.callee.object, context)}?.${node.callee.property}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
3414
+
2757
3415
  case 'CallExpression': {
3416
+ // Method call: receiver.method(args). Member access invoked with parens —
3417
+ // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
3418
+ if (node.callee) {
3419
+ const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
3420
+ return `${generateExpr(node.callee, context)}(${args})`;
3421
+ }
2758
3422
  if (STDLIB[node.name]) {
2759
3423
  if (node.name === 'readFile' || node.name === 'writeFile' ||
2760
3424
  node.name === 'fileExists' || node.name === 'read') {
@@ -2811,7 +3475,7 @@ function generateExpr(node, context = createGenerationContext()) {
2811
3475
  ensureBuiltin(context, 'fs');
2812
3476
  return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
2813
3477
 
2814
- // v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`
3478
+ // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`
2815
3479
  // calls the kind factory that `define a kind called "Person"` registered.
2816
3480
  case 'CreateKindExpression': {
2817
3481
  const fields = node.pairs
@@ -2820,7 +3484,7 @@ function generateExpr(node, context = createGenerationContext()) {
2820
3484
  return `${node.kind}({ ${fields} })`;
2821
3485
  }
2822
3486
 
2823
- // v1.0.0 — concurrency combinators: `all of [...]` / `any of [...]` /
3487
+ // v1.0.1 — concurrency combinators: `all of [...]` / `any of [...]` /
2824
3488
  // `settled of [...]`. All are awaited; `settled` returns status records.
2825
3489
  case 'ConcurrencyExpression': {
2826
3490
  markAsync(context);
@@ -2830,10 +3494,67 @@ function generateExpr(node, context = createGenerationContext()) {
2830
3494
  return `(await Promise.all(${rhs}))`;
2831
3495
  }
2832
3496
 
2833
- // v1.0.0 — `spread of <collection>` → a fresh array from an iterable.
3497
+ // v1.0.1 — `spread of <collection>` → a fresh array from an iterable.
2834
3498
  case 'SpreadExpression':
2835
3499
  return `[...${generateExpr(node.collection, context)}]`;
2836
3500
 
3501
+ case 'SpreadElement':
3502
+ return `...${generateExpr(node.argument, context)}`;
3503
+
3504
+ case 'SpreadProperty':
3505
+ return `...${generateExpr(node.argument, context)}`;
3506
+
3507
+ case 'ArrayPattern':
3508
+ // Array destructuring pattern: [a, b] = value
3509
+ return `[${node.elements.map(e => generateExpr(e, context)).join(', ')}]`;
3510
+
3511
+ case 'ObjectPattern':
3512
+ // Object destructuring pattern: {x, y} = value
3513
+ return `{ ${node.properties.map(p => generateExpr(p, context)).join(', ')} }`;
3514
+
3515
+ case 'RestElement':
3516
+ return `...${node.name}`;
3517
+
3518
+ case 'BigIntLiteral':
3519
+ return `${node.value}n`;
3520
+
3521
+ case 'UndefinedLiteral':
3522
+ return 'undefined';
3523
+
3524
+ case 'ThisExpression':
3525
+ return 'this';
3526
+
3527
+ case 'ImportMetaExpression':
3528
+ return 'import.meta';
3529
+
3530
+ case 'SuperExpression':
3531
+ return 'super';
3532
+
3533
+ case 'SuperProperty':
3534
+ return `super.${node.property}`;
3535
+
3536
+ case 'NewExpression':
3537
+ return `new ${generateExpr(node.callee, context)}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
3538
+
3539
+ case 'AwaitExpression': {
3540
+ markAsync(context);
3541
+ return `(await ${generateExpr(node.value, context)})`;
3542
+ }
3543
+
3544
+ case 'UnaryExpression': {
3545
+ // Handle typeof, void, delete operators
3546
+ if (['typeof', 'void', 'delete'].includes(node.operator)) {
3547
+ const operand = node.operand.type === 'BinaryExpression'
3548
+ ? `(${generateExpr(node.operand, context)})`
3549
+ : generateExpr(node.operand, context);
3550
+ return `${node.operator} ${operand}`;
3551
+ }
3552
+ // Regular unary minus
3553
+ return `${node.operator}${node.operand.type === 'BinaryExpression'
3554
+ ? `(${generateExpr(node.operand, context)})`
3555
+ : generateExpr(node.operand, context)}`;
3556
+ }
3557
+
2837
3558
  default:
2838
3559
  throw new Error(`Unknown expression type "${node.type}".`);
2839
3560
  }