plainscript-lang 1.0.0 → 1.0.2-latest

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 (106) hide show
  1. package/README.md +194 -729
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +182 -79
  4. package/compiler/dependency-detector.js +5 -0
  5. package/compiler/formatter.js +1 -1
  6. package/compiler/generator.js +1083 -206
  7. package/compiler/lexer.js +130 -54
  8. package/compiler/parser.js +1117 -156
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +98 -435
  11. package/docs/PLAINSCRIPT-SPEC.md +335 -0
  12. package/docs/index.html +103 -605
  13. package/docs/website/script.js +59 -943
  14. package/docs/website/style.css +74 -656
  15. package/examples/ai-providers.pln +7 -0
  16. package/examples/arrays.pln +4 -0
  17. package/examples/async-errors.pln +18 -0
  18. package/examples/auth-api.pln +9 -0
  19. package/examples/auth-sessions.pln +32 -0
  20. package/examples/basics.pln +14 -0
  21. package/examples/bots.pln +13 -0
  22. package/examples/cache-and-jobs.pln +7 -0
  23. package/examples/cache-schedule.pln +22 -0
  24. package/examples/collections.pln +15 -0
  25. package/examples/concurrency.pln +18 -0
  26. package/examples/conditions.pln +22 -0
  27. package/examples/database.pln +8 -0
  28. package/examples/day2.pln +7 -0
  29. package/examples/day3.pln +5 -0
  30. package/examples/deployment.pln +6 -0
  31. package/examples/email-send.pln +3 -0
  32. package/examples/error-handling.pln +7 -0
  33. package/examples/expressions.pln +7 -0
  34. package/examples/file-uploads.pln +10 -0
  35. package/examples/files-and-config.pln +6 -0
  36. package/examples/files.pln +12 -0
  37. package/examples/football-backend/{app.ps → app.pln} +22 -21
  38. package/examples/functions.pln +17 -0
  39. package/examples/hello.pln +2 -0
  40. package/examples/http-client.pln +3 -0
  41. package/examples/http.pln +11 -0
  42. package/examples/id-verification/{app.ps → app.pln} +5 -4
  43. package/examples/id-verification/make-sample-id.js +29 -42
  44. package/examples/json.pln +11 -0
  45. package/examples/loops.pln +18 -0
  46. package/examples/modules/app.pln +3 -0
  47. package/examples/modules/main.pln +4 -0
  48. package/examples/modules/math.pln +9 -0
  49. package/examples/mongo.pln +33 -0
  50. package/examples/objects.pln +4 -0
  51. package/examples/ocr.pln +22 -0
  52. package/examples/packages.pln +6 -0
  53. package/examples/record-kinds.pln +7 -0
  54. package/examples/records.pln +15 -0
  55. package/examples/rest-api-fetch.pln +10 -0
  56. package/examples/rest-api.pln +8 -0
  57. package/examples/scheduled-tasks.pln +4 -0
  58. package/examples/search-and-filter.pln +4 -0
  59. package/examples/server.pln +6 -0
  60. package/examples/sessions-and-cookies.pln +8 -0
  61. package/examples/sqlite.pln +23 -0
  62. package/examples/start.pln +2 -0
  63. package/examples/stdlib.pln +4 -0
  64. package/examples/telegram-ai-bot.pln +19 -0
  65. package/examples/telegram-bot.pln +6 -0
  66. package/examples/testing.pln +13 -0
  67. package/examples/web-api.pln +27 -0
  68. package/examples/web-app.pln +8 -0
  69. package/examples/websocket-server.pln +6 -0
  70. package/examples/websocket.pln +13 -0
  71. package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +4 -5
  72. package/examples/whatsapp-bot/qr.pln +12 -0
  73. package/package.json +3 -2
  74. package/docs/PLINJS_SPEC.md +0 -1151
  75. package/examples/arrays.ps +0 -13
  76. package/examples/auth-api.ps +0 -56
  77. package/examples/cache-and-jobs.ps +0 -29
  78. package/examples/concurrency.ps +0 -49
  79. package/examples/database.ps +0 -41
  80. package/examples/day2.ps +0 -7
  81. package/examples/day3.ps +0 -11
  82. package/examples/deployment.ps +0 -12
  83. package/examples/email-send.ps +0 -22
  84. package/examples/error-handling.ps +0 -54
  85. package/examples/expressions.ps +0 -40
  86. package/examples/file-uploads.ps +0 -39
  87. package/examples/files-and-config.ps +0 -47
  88. package/examples/hello.ps +0 -3
  89. package/examples/http-client.ps +0 -44
  90. package/examples/loops.ps +0 -17
  91. package/examples/modules/app.ps +0 -16
  92. package/examples/modules/math.ps +0 -20
  93. package/examples/objects.ps +0 -12
  94. package/examples/record-kinds.ps +0 -43
  95. package/examples/rest-api-fetch.ps +0 -94
  96. package/examples/rest-api.ps +0 -68
  97. package/examples/scheduled-tasks.ps +0 -23
  98. package/examples/search-and-filter.ps +0 -34
  99. package/examples/server.ps +0 -25
  100. package/examples/sessions-and-cookies.ps +0 -54
  101. package/examples/start.ps +0 -2
  102. package/examples/stdlib.ps +0 -41
  103. package/examples/telegram-bot.ps +0 -42
  104. package/examples/web-app.ps +0 -20
  105. package/examples/websocket-server.ps +0 -27
  106. package/examples/whatsapp-bot/qr.ps +0 -8
@@ -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.
@@ -13,6 +12,8 @@ const KNOWN_PACKAGES = {
13
12
  chalk: `const chalk = require('chalk');`,
14
13
  // v2.1.0 — PostgreSQL driver behind the friendly "postgres" name.
15
14
  postgres: `const { Pool } = require('pg');`,
15
+ // v2.2.0 — MongoDB driver.
16
+ mongodb: `const { MongoClient } = require('mongodb');`,
16
17
  };
17
18
 
18
19
  // PlainScript module names whose npm package name differs from the PlainScript name.
@@ -40,7 +41,7 @@ const BUILTIN_DECLARATIONS = {
40
41
  fs: `const fs = require('fs');`,
41
42
  path: `const path = require('path');`,
42
43
  crypto: `const crypto = require('crypto');`,
43
- // v1.0.0 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
44
+ // v1.0.1 — env-file runtime. Applies KEY=VALUE pairs from a .env file to
44
45
  // process.env. Blank lines and `#` comment lines are skipped.
45
46
  dotenv: [
46
47
  `function __loadEnvFile(path) {`,
@@ -86,7 +87,7 @@ const BUILTIN_DECLARATIONS = {
86
87
  ` }`,
87
88
  `}`,
88
89
  ].join('\n'),
89
- // v1.0.0 — shared runtime helpers for reflection, binary-size, YAML subset
90
+ // v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
90
91
  // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
91
92
  // when any feature that needs them is used.
92
93
  core: [
@@ -219,7 +220,7 @@ const BUILTIN_DECLARATIONS = {
219
220
  ` });`,
220
221
  `}`,
221
222
  ].join('\n'),
222
- // v1.0.0 — process execution (child processes).
223
+ // v1.0.1 — process execution (child processes).
223
224
  process: [
224
225
  `const { execFile } = require('child_process');`,
225
226
  `function __runCommand(command, args) {`,
@@ -230,7 +231,7 @@ const BUILTIN_DECLARATIONS = {
230
231
  ` });`,
231
232
  `}`,
232
233
  ].join('\n'),
233
- // v1.0.0 — Map helpers.
234
+ // v1.0.1 — Map helpers.
234
235
  mapset: [
235
236
  `function __mapSet(map, key, value) { map.set(key, value); return map; }`,
236
237
  ].join('\n'),
@@ -277,7 +278,7 @@ const BUILTIN_DECLARATIONS = {
277
278
  ` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
278
279
  `}`,
279
280
  ].join('\n'),
280
- // v1.0.0 — dynamic module loader.
281
+ // v1.0.1 — dynamic module loader.
281
282
  loadmodule: [
282
283
  `function __loadModule(spec) {`,
283
284
  ` const path = require('path');`,
@@ -286,7 +287,7 @@ const BUILTIN_DECLARATIONS = {
286
287
  ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
287
288
  `}`,
288
289
  ].join('\n'),
289
- // v1.0.0 — recursive directory walker (returns full paths, files first).
290
+ // v1.0.1 — recursive directory walker (returns full paths, files first).
290
291
  walk: [
291
292
  `function __walkFolder(dir) {`,
292
293
  ` const fs = require('fs');`,
@@ -576,21 +577,32 @@ const BUILTIN_DECLARATIONS = {
576
577
  ` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
577
578
  `}`,
578
579
  ].join('\n'),
579
- // v2.2.0 — AI/ML runtime. `chat` and `embeddings` talk to any OpenAI-compatible
580
- // completions/embeddings endpoint (API key and base URL from options or env),
581
- // while `similarity` is pure vector math and runs fully offline.
580
+ // 1.0.2-latest — provider-neutral AI runtime. `chat` and `embedText` speak
581
+ // OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
582
+ // and DeepSeek. A custom `base` and `key` can be supplied per call.
582
583
  ai: [
583
- `function __aiTags() {`,
584
- ` return { key: process.env.OPENAI_API_KEY, base: (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\\/$/, '') };`,
584
+ `function __aiTags(options = {}) {`,
585
+ ` const provider = String(options.provider || process.env.PLAINSCRIPT_AI_PROVIDER || 'openai').toLowerCase();`,
586
+ ` const providers = {`,
587
+ ` openai: { key: process.env.OPENAI_API_KEY, base: process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1' },`,
588
+ ` groq: { key: process.env.GROQ_API_KEY, base: process.env.GROQ_BASE_URL || 'https://api.groq.com/openai/v1' },`,
589
+ ` openrouter: { key: process.env.OPENROUTER_API_KEY, base: process.env.OPENROUTER_BASE_URL || 'https://openrouter.ai/api/v1' },`,
590
+ ` together: { key: process.env.TOGETHER_API_KEY, base: process.env.TOGETHER_BASE_URL || 'https://api.together.xyz/v1' },`,
591
+ ` fireworks: { key: process.env.FIREWORKS_API_KEY, base: process.env.FIREWORKS_BASE_URL || 'https://api.fireworks.ai/inference/v1' },`,
592
+ ` deepseek: { key: process.env.DEEPSEEK_API_KEY, base: process.env.DEEPSEEK_BASE_URL || 'https://api.deepseek.com/v1' },`,
593
+ ` };`,
594
+ ` const selected = providers[provider] || { key: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY'], base: process.env[provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_BASE_URL'] };`,
595
+ ` return { provider, key: options.key || selected.key, base: (options.base || selected.base || '').replace(/\\/$/, '') };`,
585
596
  `}`,
586
- `async function __aiPost(tags, path, body) {`,
597
+ `async function __aiPost(tags, path, body, options = {}) {`,
587
598
  ` if (typeof fetch !== 'function') {`,
588
599
  ` throw new Error('AI calls need Node.js 18 or newer (global fetch is missing): ' + process.version);`,
589
600
  ` }`,
590
- ` if (!tags.key) throw new Error('No API key for AI. Set env OPENAI_API_KEY.');`,
601
+ ` if (!tags.key) throw new Error('No API key for AI provider ' + tags.provider + '. Set ' + tags.provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_') + '_API_KEY or pass key in chat options.');`,
602
+ ` const headers = Object.assign({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key }, options.headers || {});`,
591
603
  ` const response = await fetch(tags.base + path, {`,
592
604
  ` method: 'POST',`,
593
- ` headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key },`,
605
+ ` headers,`,
594
606
  ` body: JSON.stringify(body),`,
595
607
  ` });`,
596
608
  ` const text = await response.text();`,
@@ -600,19 +612,21 @@ const BUILTIN_DECLARATIONS = {
600
612
  ` return data;`,
601
613
  `}`,
602
614
  `async function __aiChat(model, messages, options) {`,
603
- ` const tags = __aiTags();`,
604
- ` if (options && options.key) tags.key = options.key;`,
605
- ` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
615
+ ` options = options || {};`,
616
+ ` const tags = __aiTags(options);`,
606
617
  ` if (typeof messages === 'string') messages = [{ role: 'user', content: messages }];`,
607
- ` const data = await __aiPost(tags, '/chat/completions', { model: model, messages: messages });`,
618
+ ` const body = { model: model, messages: messages };`,
619
+ ` if (options.temperature != null) body.temperature = options.temperature;`,
620
+ ` if (options.maxTokens != null) body.max_tokens = options.maxTokens;`,
621
+ ` if (options.responseFormat != null) body.response_format = options.responseFormat;`,
622
+ ` const data = await __aiPost(tags, '/chat/completions', body, options);`,
608
623
  ` const choice = data.choices && data.choices[0];`,
609
624
  ` return choice && choice.message ? choice.message.content : '';`,
610
625
  `}`,
611
626
  `async function __aiEmbed(model, text, options) {`,
612
- ` const tags = __aiTags();`,
613
- ` if (options && options.key) tags.key = options.key;`,
614
- ` if (options && options.base) tags.base = (options.base || '').replace(/\\/$/, '');`,
615
- ` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) });`,
627
+ ` options = options || {};`,
628
+ ` const tags = __aiTags(options);`,
629
+ ` const data = await __aiPost(tags, '/embeddings', { model: model, input: String(text) }, options);`,
616
630
  ` return (data.data && data.data[0] && data.data[0].embedding) || [];`,
617
631
  `}`,
618
632
  `function __aiSimilarity(a, b) {`,
@@ -977,7 +991,60 @@ const BUILTIN_DECLARATIONS = {
977
991
  ` };`,
978
992
  `}`,
979
993
  ].join('\n'),
980
- // v1.2 — Telegram runtime. Polling-based: no webhook endpoint needed.
994
+ // v2.2.0 -- MongoDB runtime. Connects to MongoDB and provides a
995
+ // collection-oriented surface compatible with the existing SQL statement
996
+ // forms (query, insert, update, delete, execute, transaction).
997
+ mongodb: [
998
+ `let __mongoClient = null;`,
999
+ `let __mongoDb = null;`,
1000
+ `function __mongoCollection(name) {`,
1001
+ ` if (!__mongoDb) throw new Error('MongoDB: not connected. Use "database <uri> using "mongo" [db <name>]" first.');`,
1002
+ ` return __mongoDb.collection(name);`,
1003
+ `}`,
1004
+ `async function __mongoOpen(uri, dbName) {`,
1005
+ ` if (__mongoClient) return __mongoDb;`,
1006
+ ` const { MongoClient } = require('mongodb');`,
1007
+ ` __mongoClient = new MongoClient(uri);`,
1008
+ ` await __mongoClient.connect();`,
1009
+ ` __mongoDb = __mongoClient.db(dbName || undefined);`,
1010
+ ` __mongoDb.__query = async function(sql, params) {`,
1011
+ ` const m = String(sql).match(/^\\s*SELECT\\s+(.+?)\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
1012
+ ` if (!m) throw new Error('MongoDB query: use SELECT fields FROM collection [WHERE condition]');`,
1013
+ ` const [, fields, collection, where] = m;`,
1014
+ ` const coll = __mongoCollection(collection);`,
1015
+ ` let filter = {};`,
1016
+ ` if (where) {`,
1017
+ ` const parts = where.split('=').map(s => s.trim());`,
1018
+ ` if (parts.length === 2) filter[parts[0]] = params[0];`,
1019
+ ` }`,
1020
+ ` const projection = fields.trim() === '*' ? {} : Object.fromEntries(fields.split(',').map(f => [f.trim(), 1]));`,
1021
+ ` return coll.find(filter).project(projection).toArray();`,
1022
+ ` };`,
1023
+ ` __mongoDb.__write = async function(sql, params) {`,
1024
+ ` const m = String(sql).match(/^\\s*INSERT\\s+INTO\\s+(\\w+)\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)/i);`,
1025
+ ` if (!m) throw new Error('MongoDB insert: use INSERT INTO collection (fields) VALUES (?, ...)');`,
1026
+ ` const [, collection, fieldsStr, valuesStr] = m;`,
1027
+ ` const fields = fieldsStr.split(',').map(f => f.trim());`,
1028
+ ` const values = params;`,
1029
+ ` const doc = {}; fields.forEach((f, i) => doc[f] = values[i]);`,
1030
+ ` const coll = __mongoCollection(collection);`,
1031
+ ` const result = await coll.insertOne(doc);`,
1032
+ ` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
1033
+ ` };`,
1034
+ ` __mongoDb.__execute = async function(sql, params) {`,
1035
+ ` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
1036
+ ` };`,
1037
+ ` return __mongoDb;`,
1038
+ `}`,
1039
+ `async function __mongoClose() {`,
1040
+ ` if (__mongoClient) {`,
1041
+ ` await __mongoClient.close();`,
1042
+ ` __mongoClient = null;`,
1043
+ ` __mongoDb = null;`,
1044
+ ` }`,
1045
+ `}`,
1046
+ ].join('\n'),
1047
+ // v1.2 -- Telegram runtime. Polling-based: no webhook endpoint needed.
981
1048
  // Exposes `Telegram` (the raw API client) plus a `createTelegramBot(token)`
982
1049
  // factory that registers handlers and polls getUpdates in a loop. `BOT` is
983
1050
  // assigned by `bot "<token>"`. The token also falls back to the
@@ -1014,15 +1081,16 @@ const BUILTIN_DECLARATIONS = {
1014
1081
  ` if (!resolved) throw new Error('Telegram: bot token is missing. Use: bot "YOUR_BOT_TOKEN"');`,
1015
1082
  ` token = resolved; // bind the API transport to this bot's credential`,
1016
1083
  ` let offset = 0;`,
1017
- ` const onText = async (chatId, text) => {`,
1084
+ ` const onText = async (chatId, text, rawMessage = {}) => {`,
1085
+ ` const baseContext = { chatId, chat: rawMessage.chat || { id: chatId }, message: rawMessage, text, args: text.split(' ').slice(1), matches: [] };`,
1018
1086
  ` for (const { matcher, handler } of handlers.pattern) {`,
1019
1087
  ` const match = text.match(matcher);`,
1020
- ` if (match) { await handler({ chatId, text, matches: match }); return; }`,
1088
+ ` if (match) { await handler({ ...baseContext, matches: match }); return; }`,
1021
1089
  ` }`,
1022
1090
  ` const first = text.split(' ')[0];`,
1023
1091
  ` for (const { matcher, handler } of handlers.command) {`,
1024
1092
  ` if (first === matcher) {`,
1025
- ` await handler({ chatId, text, args: text.split(' ').slice(1) });`,
1093
+ ` await handler(baseContext);`,
1026
1094
  ` return;`,
1027
1095
  ` }`,
1028
1096
  ` }`,
@@ -1030,7 +1098,7 @@ const BUILTIN_DECLARATIONS = {
1030
1098
  ` const onCallback = async (data, message) => {`,
1031
1099
  ` for (const { matcher, handler } of handlers.callback) {`,
1032
1100
  ` if (data === matcher) {`,
1033
- ` await handler({ data, message, chatId: message.chat.id });`,
1101
+ ` await handler({ data, message, chatId: message.chat.id, chat: message.chat, text: message.text || '', args: [], matches: [] });`,
1034
1102
  ` return;`,
1035
1103
  ` }`,
1036
1104
  ` }`,
@@ -1050,7 +1118,7 @@ const BUILTIN_DECLARATIONS = {
1050
1118
  ` const chat = (update.message || (update.callback_query || {}).message || {}).chat;`,
1051
1119
  ` if (chat) chats.set(chat.id, chat);`,
1052
1120
  ` if (update.message && update.message.text != null) {`,
1053
- ` await onText(update.message.chat.id, update.message.text);`,
1121
+ ` await onText(update.message.chat.id, update.message.text, update.message);`,
1054
1122
  ` } else if (update.callback_query && update.callback_query.data != null) {`,
1055
1123
  ` await onCallback(update.callback_query.data, update.callback_query.message);`,
1056
1124
  ` }`,
@@ -1095,15 +1163,33 @@ const BUILTIN_DECLARATIONS = {
1095
1163
  };
1096
1164
 
1097
1165
  // 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(', ')})`,
1166
+ // v0.1–v0.4 original stdlib
1167
+ const STDLIB = {
1168
+ length: (args, context) => `(${generateExpr(args[0], context)}).length`,
1169
+ uppercase: (args, context) => `(${generateExpr(args[0], context)}).toUpperCase()`,
1170
+ lowercase: (args, context) => `(${generateExpr(args[0], context)}).toLowerCase()`,
1171
+ random: (_args) => `Math.random()`,
1172
+ round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1173
+ // Symbol creation
1174
+ symbol: (args, context) => `Symbol(${args.length > 0 ? generateExpr(args[0], context) : 'undefined'})`,
1175
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
1176
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
1177
+ // Well-known symbols
1178
+ symbolIterator: (_args) => `Symbol.iterator`,
1179
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
1180
+ symbolMatch: (_args) => `Symbol.match`,
1181
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
1182
+ symbolReplace: (_args) => `Symbol.replace`,
1183
+ symbolSearch: (_args) => `Symbol.search`,
1184
+ symbolSplit: (_args) => `Symbol.split`,
1185
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
1186
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
1187
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
1188
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
1189
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
1190
+ symbolSpecies: (_args) => `Symbol.species`,
1191
+ // Runtime constructors
1192
+ sqlite: (args, context) => `new Database(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1107
1193
  // v0.6 — runtime standard library
1108
1194
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1109
1195
  readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
@@ -1121,7 +1207,7 @@ const STDLIB = {
1121
1207
  // v1.2 — Telegram runtime helpers
1122
1208
  bot: (args, context) => {
1123
1209
  ensureBuiltin(context, 'telegram');
1124
- if (!context.inFunction) context.needsAsync = true;
1210
+ markAsync(context);
1125
1211
  return `BOT = await Telegram.createTelegramBot(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1126
1212
  },
1127
1213
  sendMessage: (args, context) => {
@@ -1144,6 +1230,22 @@ const STDLIB = {
1144
1230
  ensureBuiltin(context, 'telegram');
1145
1231
  return `Telegram.editMessage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1146
1232
  },
1233
+ telegramCall: (args, context) => {
1234
+ ensureBuiltin(context, 'telegram');
1235
+ requireArgs('telegramCall', args, 1, 'telegramCall("getMe", {})');
1236
+ markAsync(context);
1237
+ const method = generateExpr(args[0], context);
1238
+ const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
1239
+ return `await Telegram.call(${method}, ${params})`;
1240
+ },
1241
+ telegramApi: (args, context) => {
1242
+ ensureBuiltin(context, 'telegram');
1243
+ requireArgs('telegramApi', args, 1, 'telegramApi("getMe", {})');
1244
+ markAsync(context);
1245
+ const method = generateExpr(args[0], context);
1246
+ const params = args.length > 1 ? generateExpr(args[1], context) : '{}';
1247
+ return `await Telegram.call(${method}, ${params})`;
1248
+ },
1147
1249
  // v2.1.0 — HTTP request accessors. Only meaningful inside a route handler,
1148
1250
  // where Express provides req/res.
1149
1251
  param: (args, context) => routeAccessor('param', 'params', args, context),
@@ -1261,7 +1363,27 @@ const STDLIB = {
1261
1363
  padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1262
1364
  padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1263
1365
 
1264
- // ── v1.0.0 — nullable / regex / date helpers (IOPL-native).
1366
+ // ── v2.3.0 — Proxy and Reflect (IOPL-native).
1367
+ // Proxy creation: proxy(target, handler)
1368
+ proxy: (args, context) => `new Proxy(${args.map(a => generateExpr(a, context)).join(', ')})`,
1369
+ // Proxy revocable: proxyRevocable(target, handler) -> { proxy, revoke }
1370
+ proxyRevocable: (args, context) => `Proxy.revocable(${args.map(a => generateExpr(a, context)).join(', ')})`,
1371
+ // Reflect methods
1372
+ reflectApply: (args, context) => `Reflect.apply(${args.map(a => generateExpr(a, context)).join(', ')})`,
1373
+ reflectConstruct: (args, context) => `Reflect.construct(${args.map(a => generateExpr(a, context)).join(', ')})`,
1374
+ reflectDefineProperty: (args, context) => `Reflect.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1375
+ reflectDeleteProperty: (args, context) => `Reflect.deleteProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1376
+ reflectGet: (args, context) => `Reflect.get(${args.map(a => generateExpr(a, context)).join(', ')})`,
1377
+ reflectGetOwnPropertyDescriptor: (args, context) => `Reflect.getOwnPropertyDescriptor(${args.map(a => generateExpr(a, context)).join(', ')})`,
1378
+ reflectGetPrototypeOf: (args, context) => `Reflect.getPrototypeOf(${generateExpr(args[0], context)})`,
1379
+ reflectHas: (args, context) => `Reflect.has(${args.map(a => generateExpr(a, context)).join(', ')})`,
1380
+ reflectIsExtensible: (args, context) => `Reflect.isExtensible(${generateExpr(args[0], context)})`,
1381
+ reflectOwnKeys: (args, context) => `Reflect.ownKeys(${generateExpr(args[0], context)})`,
1382
+ reflectPreventExtensions: (args, context) => `Reflect.preventExtensions(${generateExpr(args[0], context)})`,
1383
+ reflectSet: (args, context) => `Reflect.set(${args.map(a => generateExpr(a, context)).join(', ')})`,
1384
+ reflectSetPrototypeOf: (args, context) => `Reflect.setPrototypeOf(${args.map(a => generateExpr(a, context)).join(', ')})`,
1385
+
1386
+ // ── v1.0.1 — nullable / regex / date helpers (IOPL-native).
1265
1387
  // first non-null, non-undefined argument — IOPL null-coalescing.
1266
1388
  coalesce: (args, context) =>
1267
1389
  `(() => { 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 +1400,144 @@ const STDLIB = {
1278
1400
  return `__formatDate(${value}, ${pattern})`;
1279
1401
  },
1280
1402
 
1403
+ // ── v1.0.2 — Native Date/DateTime/Regex support (IOPL-native, no JS gateway needed).
1404
+ // Create a new Date object. With no args: now. With 1 arg: parse ISO string or timestamp.
1405
+ // With multiple args: year, month (1-12), day, hour, min, sec, ms.
1406
+ newDate: (args, context) => {
1407
+ if (!args || args.length === 0) return `new Date()`;
1408
+ if (args.length === 1) return `new Date(${generateExpr(args[0], context)})`;
1409
+ return `new Date(${args.map(a => generateExpr(a, context)).join(', ')})`;
1410
+ },
1411
+ // Current timestamp in milliseconds.
1412
+ now: (_args) => `Date.now()`,
1413
+ // Current timestamp in seconds (Unix epoch).
1414
+ nowSec: (_args) => `Math.floor(Date.now() / 1000)`,
1415
+ // Date → ISO string (e.g., "2026-08-28T12:34:56.789Z").
1416
+ toISO: (args, context) => `${generateExpr(args[0], context)}.toISOString()`,
1417
+ // Date → locale date string.
1418
+ toLocaleDate: (args, context) => `${generateExpr(args[0], context)}.toLocaleDateString()`,
1419
+ // Date → locale time string.
1420
+ toLocaleTime: (args, context) => `${generateExpr(args[0], context)}.toLocaleTimeString()`,
1421
+ // Date → locale string.
1422
+ toLocale: (args, context) => `${generateExpr(args[0], context)}.toLocaleString()`,
1423
+ // Date → UTC string.
1424
+ toUTC: (args, context) => `${generateExpr(args[0], context)}.toUTCString()`,
1425
+ // Get timestamp (milliseconds) from a Date.
1426
+ timestamp: (args, context) => `${generateExpr(args[0], context)}.getTime()`,
1427
+ // Get year (full, e.g., 2026).
1428
+ year: (args, context) => `${generateExpr(args[0], context)}.getFullYear()`,
1429
+ // Get month (1-12).
1430
+ month: (args, context) => `${generateExpr(args[0], context)}.getMonth() + 1`,
1431
+ // Get day of month (1-31).
1432
+ day: (args, context) => `${generateExpr(args[0], context)}.getDate()`,
1433
+ // Get day of week (0-6, Sun=0).
1434
+ dayOfWeek: (args, context) => `${generateExpr(args[0], context)}.getDay()`,
1435
+ // Get hours (0-23).
1436
+ hours: (args, context) => `${generateExpr(args[0], context)}.getHours()`,
1437
+ // Get minutes (0-59).
1438
+ minutes: (args, context) => `${generateExpr(args[0], context)}.getMinutes()`,
1439
+ // Get seconds (0-59).
1440
+ seconds: (args, context) => `${generateExpr(args[0], context)}.getSeconds()`,
1441
+ // Get milliseconds (0-999).
1442
+ milliseconds: (args, context) => `${generateExpr(args[0], context)}.getMilliseconds()`,
1443
+ // Get timezone offset in minutes.
1444
+ tzOffset: (args, context) => `${generateExpr(args[0], context)}.getTimezoneOffset()`,
1445
+ // Add time to a Date (returns new Date). Unit: ms, s, m, h, d, w, mo, y.
1446
+ addTime: (args, context) => {
1447
+ if (args.length < 3) throw new Error('addTime(date, amount, unit) requires 3 arguments');
1448
+ const date = generateExpr(args[0], context);
1449
+ const amount = generateExpr(args[1], context);
1450
+ const unit = generateExpr(args[2], context);
1451
+ 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; })()`;
1452
+ },
1453
+ // Subtract time from a Date (returns new Date).
1454
+ subTime: (args, context) => {
1455
+ if (args.length < 3) throw new Error('subTime(date, amount, unit) requires 3 arguments');
1456
+ const date = generateExpr(args[0], context);
1457
+ const amount = generateExpr(args[1], context);
1458
+ const unit = generateExpr(args[2], context);
1459
+ 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; })()`;
1460
+ },
1461
+ // Difference between two dates in given unit (ms, s, m, h, d, w).
1462
+ diffTime: (args, context) => {
1463
+ if (args.length < 3) throw new Error('diffTime(date1, date2, unit) requires 3 arguments');
1464
+ const d1 = generateExpr(args[0], context);
1465
+ const d2 = generateExpr(args[1], context);
1466
+ const unit = generateExpr(args[2], context);
1467
+ 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)); })()`;
1468
+ },
1469
+ // Start of day (00:00:00.000) for a Date.
1470
+ startOfDay: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setHours(0,0,0,0); return dt; })()`,
1471
+ // End of day (23:59:59.999) for a Date.
1472
+ endOfDay: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setHours(23,59,59,999); return dt; })()`,
1473
+ // Start of month (1st, 00:00:00.000).
1474
+ startOfMonth: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setDate(1); dt.setHours(0,0,0,0); return dt; })()`,
1475
+ // End of month (last day, 23:59:59.999).
1476
+ 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; })()`,
1477
+ // Start of year (Jan 1, 00:00:00.000).
1478
+ startOfYear: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setMonth(0,1); dt.setHours(0,0,0,0); return dt; })()`,
1479
+ // End of year (Dec 31, 23:59:59.999).
1480
+ endOfYear: (args, context) => `(() => { const dt = new Date(${generateExpr(args[0], context)}); dt.setMonth(11,31); dt.setHours(23,59,59,999); return dt; })()`,
1481
+ // Check if a Date is valid (not NaN).
1482
+ isValidDate: (args, context) => `!isNaN(${generateExpr(args[0], context)}.getTime())`,
1483
+ // Format a Date with a custom pattern (YYYY, MM, DD, HH, mm, ss, SSS).
1484
+ format: (args, context) => {
1485
+ ensureBuiltin(context, 'core');
1486
+ const value = generateExpr(args[0], context);
1487
+ const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
1488
+ return `__formatDate(${value}, ${pattern})`;
1489
+ },
1490
+
1491
+ // Regex creation and matching.
1492
+ // Create a RegExp from a pattern string. Optional flags (e.g., "gi").
1493
+ regex: (args, context) => {
1494
+ if (!args || args.length === 0) throw new Error('regex(pattern, flags?) requires at least a pattern');
1495
+ const pattern = generateExpr(args[0], context);
1496
+ const flags = args.length > 1 ? generateExpr(args[1], context) : 'undefined';
1497
+ return `new RegExp(${pattern}, ${flags})`;
1498
+ },
1499
+ // Test if a string matches a regex pattern.
1500
+ matches: (args, context) => {
1501
+ if (args.length < 2) throw new Error('matches(text, pattern, flags?) requires at least text and pattern');
1502
+ const text = generateExpr(args[0], context);
1503
+ const pattern = generateExpr(args[1], context);
1504
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1505
+ return `new RegExp(${pattern}, ${flags}).test(${text})`;
1506
+ },
1507
+ // Extract first match of regex in string (returns array or null).
1508
+ regexMatch: (args, context) => {
1509
+ if (args.length < 2) throw new Error('regexMatch(text, pattern, flags?) requires at least text and pattern');
1510
+ const text = generateExpr(args[0], context);
1511
+ const pattern = generateExpr(args[1], context);
1512
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1513
+ return `${text}.match(new RegExp(${pattern}, ${flags}))`;
1514
+ },
1515
+ // Extract all matches of regex in string (returns array).
1516
+ regexMatchAll: (args, context) => {
1517
+ if (args.length < 2) throw new Error('regexMatchAll(text, pattern, flags?) requires at least text and pattern');
1518
+ const text = generateExpr(args[0], context);
1519
+ const pattern = generateExpr(args[1], context);
1520
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1521
+ return `((${flags}) === undefined ? Array.from(${text}.matchAll(new RegExp(${pattern}, 'g'))) : Array.from(${text}.matchAll(new RegExp(${pattern}, ${flags} + 'g'))))`;
1522
+ },
1523
+ // Replace using regex (with capture groups support).
1524
+ replaceRegex: (args, context) => {
1525
+ if (args.length < 3) throw new Error('replaceRegex(text, pattern, replacement, flags?) requires at least 3 arguments');
1526
+ const text = generateExpr(args[0], context);
1527
+ const pattern = generateExpr(args[1], context);
1528
+ const replacement = generateExpr(args[2], context);
1529
+ const flags = args.length > 3 ? generateExpr(args[3], context) : 'undefined';
1530
+ return `${text}.replace(new RegExp(${pattern}, ${flags}), ${replacement})`;
1531
+ },
1532
+ // Split string by regex pattern.
1533
+ splitRegex: (args, context) => {
1534
+ if (args.length < 2) throw new Error('splitRegex(text, pattern, flags?) requires at least text and pattern');
1535
+ const text = generateExpr(args[0], context);
1536
+ const pattern = generateExpr(args[1], context);
1537
+ const flags = args.length > 2 ? generateExpr(args[2], context) : 'undefined';
1538
+ return `${text}.split(new RegExp(${pattern}, ${flags}))`;
1539
+ },
1540
+
1281
1541
  // ── v2.1.0 — cache (Redis) accessors. All async.
1282
1542
 
1283
1543
  cacheGet: (args, context) => {
@@ -1351,7 +1611,7 @@ const STDLIB = {
1351
1611
  return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1352
1612
  },
1353
1613
 
1354
- // ── v1.0.0 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
1614
+ // ── v1.0.1 — capability-gap stdlib (reflection, binary, concurrency, ...) ──
1355
1615
 
1356
1616
  // Reflection
1357
1617
  typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
@@ -1412,7 +1672,7 @@ const STDLIB = {
1412
1672
  // Generators / iterables
1413
1673
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
1414
1674
 
1415
- // v1.0.0 — dynamic module loading (the runtime companion to `import "./x.ps"`).
1675
+ // v1.0.1 — dynamic module loading (the runtime companion to `import "./x.pt"`).
1416
1676
  // Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
1417
1677
  // `require.resolve` from the program root.
1418
1678
  loadModule: (args, context) => {
@@ -1425,20 +1685,42 @@ const STDLIB = {
1425
1685
  // offline cosine similarity over any two equal-length numeric vectors.
1426
1686
  chat: (args, context) => {
1427
1687
  ensureBuiltin(context, 'ai');
1688
+ requireArgs('chat', args, 2, 'chat("model", "message")');
1428
1689
  markAsync(context);
1429
1690
  const model = generateExpr(args[0], context);
1430
1691
  const messages = generateExpr(args[1], context);
1431
1692
  const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1432
1693
  return `await __aiChat(${model}, ${messages}, ${options})`;
1433
1694
  },
1695
+ chatWith: (args, context) => {
1696
+ ensureBuiltin(context, 'ai');
1697
+ requireArgs('chatWith', args, 3, 'chatWith("groq", "model", "message")');
1698
+ markAsync(context);
1699
+ const provider = generateExpr(args[0], context);
1700
+ const model = generateExpr(args[1], context);
1701
+ const messages = generateExpr(args[2], context);
1702
+ const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
1703
+ return `await __aiChat(${model}, ${messages}, Object.assign({}, ${options}, { provider: ${provider} }))`;
1704
+ },
1434
1705
  embedText: (args, context) => {
1435
1706
  ensureBuiltin(context, 'ai');
1707
+ requireArgs('embedText', args, 2, 'embedText("model", "text")');
1436
1708
  markAsync(context);
1437
1709
  const model = generateExpr(args[0], context);
1438
1710
  const text = generateExpr(args[1], context);
1439
1711
  const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1440
1712
  return `await __aiEmbed(${model}, ${text}, ${options})`;
1441
1713
  },
1714
+ embedWith: (args, context) => {
1715
+ ensureBuiltin(context, 'ai');
1716
+ requireArgs('embedWith', args, 3, 'embedWith("groq", "model", "text")');
1717
+ markAsync(context);
1718
+ const provider = generateExpr(args[0], context);
1719
+ const model = generateExpr(args[1], context);
1720
+ const text = generateExpr(args[2], context);
1721
+ const options = args.length > 3 && args[3] != null ? generateExpr(args[3], context) : '{}';
1722
+ return `await __aiEmbed(${model}, ${text}, Object.assign({}, ${options}, { provider: ${provider} }))`;
1723
+ },
1442
1724
  similarity: (args, context) => {
1443
1725
  ensureBuiltin(context, 'ai');
1444
1726
  return `__aiSimilarity(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
@@ -1498,11 +1780,422 @@ const STDLIB = {
1498
1780
  ensureBuiltin(context, 'fs');
1499
1781
  return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
1500
1782
  },
1783
+
1784
+ // ── v1.0.2 — Extended Math functions (IOPL-native).
1785
+ abs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
1786
+ min: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
1787
+ max: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
1788
+ sqrt: (args, context) => `Math.sqrt(${generateExpr(args[0], context)})`,
1789
+ pow: (args, context) => `Math.pow(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1790
+ floor: (args, context) => `Math.floor(${generateExpr(args[0], context)})`,
1791
+ ceil: (args, context) => `Math.ceil(${generateExpr(args[0], context)})`,
1792
+ round: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
1793
+ trunc: (args, context) => `Math.trunc(${generateExpr(args[0], context)})`,
1794
+ sign: (args, context) => `Math.sign(${generateExpr(args[0], context)})`,
1795
+ random: (_args) => `Math.random()`,
1796
+ randomInt: (args, context) => `Math.floor(Math.random() * (${generateExpr(args[1], context)} - ${generateExpr(args[0], context)} + 1)) + ${generateExpr(args[0], context)}`,
1797
+ clamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
1798
+ lerp: (args, context) => `${generateExpr(args[0], context)} + (${generateExpr(args[1], context)} - ${generateExpr(args[0], context)}) * ${generateExpr(args[2], context)}`,
1799
+ PI: (_args) => `Math.PI`,
1800
+ E: (_args) => `Math.E`,
1801
+ ln2: (_args) => `Math.LN2`,
1802
+ ln10: (_args) => `Math.LN10`,
1803
+ log2e: (_args) => `Math.LOG2E`,
1804
+ log10e: (_args) => `Math.LOG10E`,
1805
+ sin: (args, context) => `Math.sin(${generateExpr(args[0], context)})`,
1806
+ cos: (args, context) => `Math.cos(${generateExpr(args[0], context)})`,
1807
+ tan: (args, context) => `Math.tan(${generateExpr(args[0], context)})`,
1808
+ asin: (args, context) => `Math.asin(${generateExpr(args[0], context)})`,
1809
+ acos: (args, context) => `Math.acos(${generateExpr(args[0], context)})`,
1810
+ atan: (args, context) => `Math.atan(${generateExpr(args[0], context)})`,
1811
+ atan2: (args, context) => `Math.atan2(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1812
+ sinh: (args, context) => `Math.sinh(${generateExpr(args[0], context)})`,
1813
+ cosh: (args, context) => `Math.cosh(${generateExpr(args[0], context)})`,
1814
+ tanh: (args, context) => `Math.tanh(${generateExpr(args[0], context)})`,
1815
+ exp: (args, context) => `Math.exp(${generateExpr(args[0], context)})`,
1816
+ expm1: (args, context) => `Math.expm1(${generateExpr(args[0], context)})`,
1817
+ log: (args, context) => `Math.log(${generateExpr(args[0], context)})`,
1818
+ log1p: (args, context) => `Math.log1p(${generateExpr(args[0], context)})`,
1819
+ log2: (args, context) => `Math.log2(${generateExpr(args[0], context)})`,
1820
+ log10: (args, context) => `Math.log10(${generateExpr(args[0], context)})`,
1821
+ hypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
1822
+ cbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
1823
+
1824
+ // ── v1.0.2 — Extended String functions (IOPL-native).
1825
+ trim: (args, context) => `String(${generateExpr(args[0], context)}).trim()`,
1826
+ trimStart: (args, context) => `String(${generateExpr(args[0], context)}).trimStart()`,
1827
+ trimEnd: (args, context) => `String(${generateExpr(args[0], context)}).trimEnd()`,
1828
+ toUpperCase: (args, context) => `String(${generateExpr(args[0], context)}).toUpperCase()`,
1829
+ toLowerCase: (args, context) => `String(${generateExpr(args[0], context)}).toLowerCase()`,
1830
+ charAt: (args, context) => `String(${generateExpr(args[0], context)}).charAt(${generateExpr(args[1], context)})`,
1831
+ charCodeAt: (args, context) => `String(${generateExpr(args[0], context)}).charCodeAt(${generateExpr(args[1], context)})`,
1832
+ codePointAt: (args, context) => `String(${generateExpr(args[0], context)}).codePointAt(${generateExpr(args[1], context)})`,
1833
+ slice: (args, context) => `String(${generateExpr(args[0], context)}).slice(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1834
+ substring: (args, context) => `String(${generateExpr(args[0], context)}).substring(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1835
+ substr: (args, context) => `String(${generateExpr(args[0], context)}).substr(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1836
+ indexOf: (args, context) => `String(${generateExpr(args[0], context)}).indexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1837
+ lastIndexOf: (args, context) => `String(${generateExpr(args[0], context)}).lastIndexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1838
+ includes: (args, context) => `String(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1839
+ startsWith: (args, context) => `String(${generateExpr(args[0], context)}).startsWith(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1840
+ endsWith: (args, context) => `String(${generateExpr(args[0], context)}).endsWith(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1841
+ repeat: (args, context) => `String(${generateExpr(args[0], context)}).repeat(${generateExpr(args[1], context)})`,
1842
+ padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1843
+ padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1844
+ split: (args, context) => {
1845
+ const sep = args.length > 1 ? generateExpr(args[1], context) : '","';
1846
+ return `String(${generateExpr(args[0], context)}).split(${sep})`;
1847
+ },
1848
+ join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
1849
+ replaceAll: (args, context) => `String(${generateExpr(args[0], context)}).replaceAll(${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
1850
+ match: (args, context) => `String(${generateExpr(args[0], context)}).match(${generateExpr(args[1], context)})`,
1851
+ matchAll: (args, context) => `Array.from(String(${generateExpr(args[0], context)}).matchAll(${generateExpr(args[1], context)}))`,
1852
+ search: (args, context) => `String(${generateExpr(args[0], context)}).search(${generateExpr(args[1], context)})`,
1853
+ toString: (args, context) => `String(${generateExpr(args[0], context)}).toString()`,
1854
+ stringValueOf: (args, context) => `String(${generateExpr(args[0], context)}).valueOf()`,
1855
+
1856
+ // ── v1.0.2 — Extended Array/Collection functions (IOPL-native).
1857
+ push: (args, context) => `(${generateExpr(args[0], context)}).push(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1858
+ pop: (args, context) => `(${generateExpr(args[0], context)}).pop()`,
1859
+ shift: (args, context) => `(${generateExpr(args[0], context)}).shift()`,
1860
+ unshift: (args, context) => `(${generateExpr(args[0], context)}).unshift(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1861
+ splice: (args, context) => `(${generateExpr(args[0], context)}).splice(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1862
+ concat: (args, context) => `(${generateExpr(args[0], context)}).concat(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1863
+ slice: (args, context) => `(${generateExpr(args[0], context)}).slice(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1864
+ copyWithin: (args, context) => `(${generateExpr(args[0], context)}).copyWithin(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1865
+ 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) : ''})`,
1866
+ find: (args, context) => `(${generateExpr(args[0], context)}).find(${generateExpr(args[1], context)})`,
1867
+ findIndex: (args, context) => `(${generateExpr(args[0], context)}).findIndex(${generateExpr(args[1], context)})`,
1868
+ findLast: (args, context) => `(${generateExpr(args[0], context)}).findLast(${generateExpr(args[1], context)})`,
1869
+ findLastIndex: (args, context) => `(${generateExpr(args[0], context)}).findLastIndex(${generateExpr(args[1], context)})`,
1870
+ indexOf: (args, context) => `(${generateExpr(args[0], context)}).indexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1871
+ lastIndexOf: (args, context) => `(${generateExpr(args[0], context)}).lastIndexOf(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1872
+ includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1873
+ join: (args, context) => `(${generateExpr(args[0], context)}).join(${args.length > 1 ? generateExpr(args[1], context) : '","'})`,
1874
+ reverse: (args, context) => `[...${generateExpr(args[0], context)}].reverse()`,
1875
+ sort: (args, context) => `[...${generateExpr(args[0], context)}].sort(${args.length > 1 ? generateExpr(args[1], context) : '(a, b) => (a < b ? -1 : a > b ? 1 : 0)'})`,
1876
+ flat: (args, context) => `(${generateExpr(args[0], context)}).flat(${args.length > 1 ? generateExpr(args[1], context) : ''})`,
1877
+ flatMap: (args, context) => `(${generateExpr(args[0], context)}).flatMap(${generateExpr(args[1], context)})`,
1878
+ map: (args, context) => `(${generateExpr(args[0], context)}).map(${generateExpr(args[1], context)})`,
1879
+ filter: (args, context) => `(${generateExpr(args[0], context)}).filter(${generateExpr(args[1], context)})`,
1880
+ reduce: (args, context) => `(${generateExpr(args[0], context)}).reduce(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1881
+ reduceRight: (args, context) => `(${generateExpr(args[0], context)}).reduceRight(${generateExpr(args[1], context)}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1882
+ forEach: (args, context) => `(${generateExpr(args[0], context)}).forEach(${generateExpr(args[1], context)})`,
1883
+ some: (args, context) => `(${generateExpr(args[0], context)}).some(${generateExpr(args[1], context)})`,
1884
+ every: (args, context) => `(${generateExpr(args[0], context)}).every(${generateExpr(args[1], context)})`,
1885
+ at: (args, context) => `(${generateExpr(args[0], context)}).at(${generateExpr(args[1], context)})`,
1886
+ with: (args, context) => `(${generateExpr(args[0], context)}).with(${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
1887
+ toSorted: (args, context) => `(${generateExpr(args[0], context)}).toSorted(${args.length > 1 ? generateExpr(args[1], context) : '(a, b) => (a < b ? -1 : a > b ? 1 : 0)'})`,
1888
+ toReversed: (args, context) => `(${generateExpr(args[0], context)}).toReversed()`,
1889
+ toSpliced: (args, context) => `(${generateExpr(args[0], context)}).toSpliced(${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`,
1890
+ keys: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
1891
+ values: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
1892
+ entries: (args, context) => `Object.entries(${generateExpr(args[0], context)})`,
1893
+
1894
+ // ── v1.0.2 — Extended Object functions (IOPL-native).
1895
+ assign: (args, context) => `Object.assign(${args.map(a => generateExpr(a, context)).join(', ')})`,
1896
+ create: (args, context) => `Object.create(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1897
+ defineProperty: (args, context) => `Object.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1898
+ defineProperties: (args, context) => `Object.defineProperties(${args.map(a => generateExpr(a, context)).join(', ')})`,
1899
+ getOwnPropertyDescriptor: (args, context) => `Object.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1900
+ getOwnPropertyDescriptors: (args, context) => `Object.getOwnPropertyDescriptors(${generateExpr(args[0], context)})`,
1901
+ getOwnPropertyNames: (args, context) => `Object.getOwnPropertyNames(${generateExpr(args[0], context)})`,
1902
+ getOwnPropertySymbols: (args, context) => `Object.getOwnPropertySymbols(${generateExpr(args[0], context)})`,
1903
+ getPrototypeOf: (args, context) => `Object.getPrototypeOf(${generateExpr(args[0], context)})`,
1904
+ setPrototypeOf: (args, context) => `Object.setPrototypeOf(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1905
+ objectIs: (args, context) => `Object.is(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1906
+ isExtensible: (args, context) => `Object.isExtensible(${generateExpr(args[0], context)})`,
1907
+ isFrozen: (args, context) => `Object.isFrozen(${generateExpr(args[0], context)})`,
1908
+ isSealed: (args, context) => `Object.isSealed(${generateExpr(args[0], context)})`,
1909
+ preventExtensions: (args, context) => `Object.preventExtensions(${generateExpr(args[0], context)})`,
1910
+ freeze: (args, context) => `Object.freeze(${generateExpr(args[0], context)})`,
1911
+ seal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
1912
+ hasOwn: (args, context) => `Object.hasOwn(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1913
+
1914
+ // ── v1.0.2 — Promise/Async utilities (IOPL-native).
1915
+ Promise: {
1916
+ resolve: (args, context) => `Promise.resolve(${generateExpr(args[0], context)})`,
1917
+ reject: (args, context) => `Promise.reject(${generateExpr(args[0], context)})`,
1918
+ all: (args, context) => `Promise.all(${generateExpr(args[0], context)})`,
1919
+ allSettled: (args, context) => `Promise.allSettled(${generateExpr(args[0], context)})`,
1920
+ race: (args, context) => `Promise.race(${generateExpr(args[0], context)})`,
1921
+ any: (args, context) => `Promise.any(${generateExpr(args[0], context)})`,
1922
+ },
1923
+ // Note: These are accessed as Promise.resolve, Promise.all, etc.
1924
+ // We'll add helper functions for them.
1925
+ promiseResolve: (args, context) => `Promise.resolve(${generateExpr(args[0], context)})`,
1926
+ promiseReject: (args, context) => `Promise.reject(${generateExpr(args[0], context)})`,
1927
+ promiseAll: (args, context) => `Promise.all(${generateExpr(args[0], context)})`,
1928
+ promiseAllSettled: (args, context) => `Promise.allSettled(${generateExpr(args[0], context)})`,
1929
+ promiseRace: (args, context) => `Promise.race(${generateExpr(args[0], context)})`,
1930
+ promiseAny: (args, context) => `Promise.any(${generateExpr(args[0], context)})`,
1931
+ promiseWithResolvers: (args, context) => `Promise.withResolvers()`,
1932
+ await: (args, context) => {
1933
+ markAsync(context);
1934
+ return `await ${generateExpr(args[0], context)}`;
1935
+ },
1936
+ // Async sleep (returns a promise that resolves after ms).
1937
+ sleepAsync: (args, context) => {
1938
+ markAsync(context);
1939
+ return `new Promise(r => setTimeout(r, ${generateExpr(args[0], context)}))`;
1940
+ },
1941
+ // Timeout wrapper for promises.
1942
+ timeout: (args, context) => {
1943
+ markAsync(context);
1944
+ const ms = args.length > 1 ? generateExpr(args[1], context) : '30000';
1945
+ return `Promise.race([${generateExpr(args[0], context)}, new Promise((_, r) => setTimeout(() => r(new Error('Timed out')), ${ms}))])`;
1946
+ },
1947
+
1948
+ // ── v1.0.2 — JSON utilities (IOPL-native).
1949
+ jsonParse: (args, context) => `JSON.parse(${generateExpr(args[0], context)})`,
1950
+ stringify: (args, context) => `JSON.stringify(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''}${args.length > 2 ? ', ' + generateExpr(args[2], context) : ''})`,
1951
+
1952
+ // ── v1.0.2 — Type checking utilities (IOPL-native).
1953
+ isArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
1954
+ isInteger: (args, context) => `Number.isInteger(${generateExpr(args[0], context)})`,
1955
+ isNaN: (args, context) => `Number.isNaN(${generateExpr(args[0], context)})`,
1956
+ isFinite: (args, context) => `Number.isFinite(${generateExpr(args[0], context)})`,
1957
+ isSafeInteger: (args, context) => `Number.isSafeInteger(${generateExpr(args[0], context)})`,
1958
+ parseInt: (args, context) => `parseInt(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1959
+ parseFloat: (args, context) => `parseFloat(${generateExpr(args[0], context)})`,
1960
+
1961
+ // ── v1.0.2 — Array static methods (IOPL-native).
1962
+ arrayFrom: (args, context) => `Array.from(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1963
+ arrayOf: (args, context) => `Array.of(${args.map(a => generateExpr(a, context)).join(', ')})`,
1964
+ arrayIsArray: (args, context) => `Array.isArray(${generateExpr(args[0], context)})`,
1965
+
1966
+ // ── v1.0.2 — Object static methods (IOPL-native).
1967
+ objectFromEntries: (args, context) => `Object.fromEntries(${generateExpr(args[0], context)})`,
1968
+ objectGetOwnPropertySymbols: (args, context) => `Object.getOwnPropertySymbols(${generateExpr(args[0], context)})`,
1969
+ objectGetOwnPropertyDescriptors: (args, context) => `Object.getOwnPropertyDescriptors(${generateExpr(args[0], context)})`,
1970
+ objectGetPrototypeOf: (args, context) => `Object.getPrototypeOf(${generateExpr(args[0], context)})`,
1971
+ objectSetPrototypeOf: (args, context) => `Object.setPrototypeOf(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1972
+ objectIs: (args, context) => `Object.is(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1973
+ objectCreate: (args, context) => `Object.create(${generateExpr(args[0], context)}${args.length > 1 ? ', ' + generateExpr(args[1], context) : ''})`,
1974
+ objectAssign: (args, context) => `Object.assign(${args.map(a => generateExpr(a, context)).join(', ')})`,
1975
+ objectKeys: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
1976
+ objectValues: (args, context) => `Object.values(${generateExpr(args[0], context)})`,
1977
+ objectEntries: (args, context) => `Object.entries(${generateExpr(args[0], context)})`,
1978
+ objectHasOwn: (args, context) => `Object.hasOwn(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1979
+ objectDefineProperty: (args, context) => `Object.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
1980
+ objectDefineProperties: (args, context) => `Object.defineProperties(${args.map(a => generateExpr(a, context)).join(', ')})`,
1981
+ objectGetOwnPropertyDescriptor: (args, context) => `Object.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1982
+ objectGetOwnPropertyNames: (args, context) => `Object.getOwnPropertyNames(${generateExpr(args[0], context)})`,
1983
+ objectIsExtensible: (args, context) => `Object.isExtensible(${generateExpr(args[0], context)})`,
1984
+ objectIsFrozen: (args, context) => `Object.isFrozen(${generateExpr(args[0], context)})`,
1985
+ objectIsSealed: (args, context) => `Object.isSealed(${generateExpr(args[0], context)})`,
1986
+ objectPreventExtensions: (args, context) => `Object.preventExtensions(${generateExpr(args[0], context)})`,
1987
+ objectFreeze: (args, context) => `Object.freeze(${generateExpr(args[0], context)})`,
1988
+ objectSeal: (args, context) => `Object.seal(${generateExpr(args[0], context)})`,
1989
+
1990
+ // ── v1.0.2 — Symbol support (IOPL-native).
1991
+ symbol: (args, context) => `Symbol(${args.length > 0 ? generateExpr(args[0], context) : 'undefined'})`,
1992
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
1993
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
1994
+ symbolIterator: (_args) => `Symbol.iterator`,
1995
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
1996
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
1997
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
1998
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
1999
+ symbolMatch: (_args) => `Symbol.match`,
2000
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
2001
+ symbolReplace: (_args) => `Symbol.replace`,
2002
+ symbolSearch: (_args) => `Symbol.search`,
2003
+ symbolSplit: (_args) => `Symbol.split`,
2004
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
2005
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
2006
+
2007
+ // ── v1.0.2 — Math static methods (IOPL-native).
2008
+ mathAbs: (args, context) => `Math.abs(${generateExpr(args[0], context)})`,
2009
+ mathMin: (args, context) => `Math.min(${args.map(a => generateExpr(a, context)).join(', ')})`,
2010
+ mathMax: (args, context) => `Math.max(${args.map(a => generateExpr(a, context)).join(', ')})`,
2011
+ mathSqrt: (args, context) => `Math.sqrt(${generateExpr(args[0], context)})`,
2012
+ mathPow: (args, context) => `Math.pow(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2013
+ mathFloor: (args, context) => `Math.floor(${generateExpr(args[0], context)})`,
2014
+ mathCeil: (args, context) => `Math.ceil(${generateExpr(args[0], context)})`,
2015
+ mathRound: (args, context) => `Math.round(${generateExpr(args[0], context)})`,
2016
+ mathTrunc: (args, context) => `Math.trunc(${generateExpr(args[0], context)})`,
2017
+ mathSign: (args, context) => `Math.sign(${generateExpr(args[0], context)})`,
2018
+ mathRandom: (_args) => `Math.random()`,
2019
+ mathClamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
2020
+ mathPI: (_args) => `Math.PI`,
2021
+ mathE: (_args) => `Math.E`,
2022
+ mathLN2: (_args) => `Math.LN2`,
2023
+ mathLN10: (_args) => `Math.LN10`,
2024
+ mathLOG2E: (_args) => `Math.LOG2E`,
2025
+ mathLOG10E: (_args) => `Math.LOG10E`,
2026
+ mathSin: (args, context) => `Math.sin(${generateExpr(args[0], context)})`,
2027
+ mathCos: (args, context) => `Math.cos(${generateExpr(args[0], context)})`,
2028
+ mathTan: (args, context) => `Math.tan(${generateExpr(args[0], context)})`,
2029
+ mathAsin: (args, context) => `Math.asin(${generateExpr(args[0], context)})`,
2030
+ mathAcos: (args, context) => `Math.acos(${generateExpr(args[0], context)})`,
2031
+ mathAtan: (args, context) => `Math.atan(${generateExpr(args[0], context)})`,
2032
+ mathAtan2: (args, context) => `Math.atan2(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2033
+ mathSinh: (args, context) => `Math.sinh(${generateExpr(args[0], context)})`,
2034
+ mathCosh: (args, context) => `Math.cosh(${generateExpr(args[0], context)})`,
2035
+ mathTanh: (args, context) => `Math.tanh(${generateExpr(args[0], context)})`,
2036
+ mathExp: (args, context) => `Math.exp(${generateExpr(args[0], context)})`,
2037
+ mathExpm1: (args, context) => `Math.expm1(${generateExpr(args[0], context)})`,
2038
+ mathLog: (args, context) => `Math.log(${generateExpr(args[0], context)})`,
2039
+ mathLog1p: (args, context) => `Math.log1p(${generateExpr(args[0], context)})`,
2040
+ mathLog2: (args, context) => `Math.log2(${generateExpr(args[0], context)})`,
2041
+ mathLog10: (args, context) => `Math.log10(${generateExpr(args[0], context)})`,
2042
+ mathHypot: (args, context) => `Math.hypot(${args.map(a => generateExpr(a, context)).join(', ')})`,
2043
+ mathCbrt: (args, context) => `Math.cbrt(${generateExpr(args[0], context)})`,
2044
+
2045
+ // ── v1.0.2 — TypedArray support (IOPL-native).
2046
+ int8Array: (args, context) => `new Int8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2047
+ uint8Array: (args, context) => `new Uint8Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2048
+ uint8ClampedArray: (args, context) => `new Uint8ClampedArray(${args.map(a => generateExpr(a, context)).join(', ')})`,
2049
+ int16Array: (args, context) => `new Int16Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2050
+ uint16Array: (args, context) => `new Uint16Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2051
+ int32Array: (args, context) => `new Int32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2052
+ uint32Array: (args, context) => `new Uint32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2053
+ float32Array: (args, context) => `new Float32Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2054
+ float64Array: (args, context) => `new Float64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2055
+ bigInt64Array: (args, context) => `new BigInt64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2056
+ bigUint64Array: (args, context) => `new BigUint64Array(${args.map(a => generateExpr(a, context)).join(', ')})`,
2057
+ dataView: (args, context) => `new DataView(${args.map(a => generateExpr(a, context)).join(', ')})`,
2058
+ arrayBuffer: (args, context) => `new ArrayBuffer(${args.map(a => generateExpr(a, context)).join(', ')})`,
2059
+
2060
+ // ── v1.0.2 — Global objects access (IOPL-native).
2061
+ globalThis: (_args) => `globalThis`,
2062
+ console: (_args) => `console`,
2063
+ process: (_args) => `process`,
2064
+ Buffer: (_args) => `Buffer`,
2065
+
2066
+ // ── v2.3.0 — EventSource / Server-Sent Events (IOPL-native).
2067
+ eventSource: (args, context) => `new EventSource(${args.map(a => generateExpr(a, context)).join(', ')})`,
2068
+
2069
+ // ── v2.2.0 — URL and URLSearchParams (IOPL-native).
2070
+ url: (args, context) => `new URL(${generateExpr(args[0], context)}${args[1] ? `, ${generateExpr(args[1], context)}` : ''})`,
2071
+ urlSearchParams: (args, context) => `new URLSearchParams(${args.length ? generateExpr(args[0], context) : ''})`,
2072
+
2073
+ // ── v2.2.0 — Intl / Internationalization (IOPL-native).
2074
+ dateTimeFormat: (args, context) => `new Intl.DateTimeFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2075
+ numberFormat: (args, context) => `new Intl.NumberFormat(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2076
+ collator: (args, context) => `new Intl.Collator(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2077
+
2078
+ // ── v2.2.0 — Crypto / Web Crypto API (IOPL-native).
2079
+ cryptoRandomUUID: (_args) => `crypto.randomUUID()`,
2080
+ cryptoGetRandomValues: (args, context) => `crypto.getRandomValues(${generateExpr(args[0], context)})`,
2081
+ cryptoSubtleDigest: (args, context) => `crypto.subtle.digest(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2082
+ cryptoSubtleEncrypt: (args, context) => `crypto.subtle.encrypt(${args.map(a => generateExpr(a, context)).join(', ')})`,
2083
+ cryptoSubtleDecrypt: (args, context) => `crypto.subtle.decrypt(${args.map(a => generateExpr(a, context)).join(', ')})`,
2084
+ cryptoSubtleSign: (args, context) => `crypto.subtle.sign(${args.map(a => generateExpr(a, context)).join(', ')})`,
2085
+ cryptoSubtleVerify: (args, context) => `crypto.subtle.verify(${args.map(a => generateExpr(a, context)).join(', ')})`,
2086
+ cryptoSubtleGenerateKey: (args, context) => `crypto.subtle.generateKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2087
+ cryptoSubtleDeriveKey: (args, context) => `crypto.subtle.deriveKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2088
+ cryptoSubtleImportKey: (args, context) => `crypto.subtle.importKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2089
+ cryptoSubtleExportKey: (args, context) => `crypto.subtle.exportKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2090
+ cryptoSubtleWrapKey: (args, context) => `crypto.subtle.wrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2091
+ cryptoSubtleUnwrapKey: (args, context) => `crypto.subtle.unwrapKey(${args.map(a => generateExpr(a, context)).join(', ')})`,
2092
+
2093
+ // ── v2.2.0 — WeakMap / WeakSet / WeakRef / FinalizationRegistry (IOPL-native).
2094
+ weakMap: (_args) => `new WeakMap()`,
2095
+ weakSet: (_args) => `new WeakSet()`,
2096
+ weakRef: (args, context) => `new WeakRef(${generateExpr(args[0], context)})`,
2097
+ finalizationRegistry: (args, context) => `new FinalizationRegistry(${generateExpr(args[0], context)})`,
2098
+
2099
+ // ── v2.2.0 — Proxy / Reflect (IOPL-native).
2100
+ proxy: (args, context) => `new Proxy(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2101
+ reflectGet: (args, context) => `Reflect.get(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2102
+ reflectSet: (args, context) => `Reflect.set(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${generateExpr(args[2], context)})`,
2103
+ reflectHas: (args, context) => `Reflect.has(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2104
+ reflectDeleteProperty: (args, context) => `Reflect.deleteProperty(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2105
+ reflectConstruct: (args, context) => `Reflect.construct(${args.map(a => generateExpr(a, context)).join(', ')})`,
2106
+ reflectApply: (args, context) => `Reflect.apply(${args.map(a => generateExpr(a, context)).join(', ')})`,
2107
+ reflectOwnKeys: (args, context) => `Reflect.ownKeys(${generateExpr(args[0], context)})`,
2108
+ reflectDefineProperty: (args, context) => `Reflect.defineProperty(${args.map(a => generateExpr(a, context)).join(', ')})`,
2109
+ reflectGetOwnPropertyDescriptor: (args, context) => `Reflect.getOwnPropertyDescriptor(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2110
+
2111
+ // ── v2.2.0 — Symbol (IOPL-native).
2112
+ symbol: (args, context) => `Symbol(${args.length ? generateExpr(args[0], context) : 'undefined'})`,
2113
+ symbolFor: (args, context) => `Symbol.for(${generateExpr(args[0], context)})`,
2114
+ symbolKeyFor: (args, context) => `Symbol.keyFor(${generateExpr(args[0], context)})`,
2115
+ symbolIterator: (_args) => `Symbol.iterator`,
2116
+ symbolAsyncIterator: (_args) => `Symbol.asyncIterator`,
2117
+ symbolToStringTag: (_args) => `Symbol.toStringTag`,
2118
+ symbolHasInstance: (_args) => `Symbol.hasInstance`,
2119
+ symbolIsConcatSpreadable: (_args) => `Symbol.isConcatSpreadable`,
2120
+ symbolMatch: (_args) => `Symbol.match`,
2121
+ symbolMatchAll: (_args) => `Symbol.matchAll`,
2122
+ symbolReplace: (_args) => `Symbol.replace`,
2123
+ symbolSearch: (_args) => `Symbol.search`,
2124
+ symbolSplit: (_args) => `Symbol.split`,
2125
+ symbolToPrimitive: (_args) => `Symbol.toPrimitive`,
2126
+ symbolUnscopables: (_args) => `Symbol.unscopables`,
2127
+
2128
+ // ── v2.2.0 — BigInt (IOPL-native).
2129
+ bigInt: (args, context) => `BigInt(${generateExpr(args[0], context)})`,
2130
+ bigIntAsIntN: (args, context) => `BigInt.asIntN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2131
+ bigIntAsUintN: (args, context) => `BigInt.asUintN(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
2132
+
2133
+ // ── v2.2.0 — Atomics / SharedArrayBuffer (IOPL-native).
2134
+ atomicsAdd: (args, context) => `Atomics.add(${args.map(a => generateExpr(a, context)).join(', ')})`,
2135
+ atomicsSub: (args, context) => `Atomics.sub(${args.map(a => generateExpr(a, context)).join(', ')})`,
2136
+ atomicsAnd: (args, context) => `Atomics.and(${args.map(a => generateExpr(a, context)).join(', ')})`,
2137
+ atomicsOr: (args, context) => `Atomics.or(${args.map(a => generateExpr(a, context)).join(', ')})`,
2138
+ atomicsXor: (args, context) => `Atomics.xor(${args.map(a => generateExpr(a, context)).join(', ')})`,
2139
+ atomicsExchange: (args, context) => `Atomics.exchange(${args.map(a => generateExpr(a, context)).join(', ')})`,
2140
+ atomicsCompareExchange: (args, context) => `Atomics.compareExchange(${args.map(a => generateExpr(a, context)).join(', ')})`,
2141
+ atomicsLoad: (args, context) => `Atomics.load(${args.map(a => generateExpr(a, context)).join(', ')})`,
2142
+ atomicsStore: (args, context) => `Atomics.store(${args.map(a => generateExpr(a, context)).join(', ')})`,
2143
+ atomicsWait: (args, context) => `Atomics.wait(${args.map(a => generateExpr(a, context)).join(', ')})`,
2144
+ atomicsNotify: (args, context) => `Atomics.notify(${args.map(a => generateExpr(a, context)).join(', ')})`,
2145
+ atomicsIsLockFree: (args, context) => `Atomics.isLockFree(${generateExpr(args[0], context)})`,
2146
+ sharedArrayBuffer: (args, context) => `new SharedArrayBuffer(${generateExpr(args[0], context)})`,
2147
+
2148
+ // ── v2.2.0 — Error subclasses (IOPL-native).
2149
+ error: (args, context) => `new Error(${args.length ? generateExpr(args[0], context) : ''})`,
2150
+ typeError: (args, context) => `new TypeError(${args.length ? generateExpr(args[0], context) : ''})`,
2151
+ rangeError: (args, context) => `new RangeError(${args.length ? generateExpr(args[0], context) : ''})`,
2152
+ referenceError: (args, context) => `new ReferenceError(${args.length ? generateExpr(args[0], context) : ''})`,
2153
+ syntaxError: (args, context) => `new SyntaxError(${args.length ? generateExpr(args[0], context) : ''})`,
2154
+ evalError: (args, context) => `new EvalError(${args.length ? generateExpr(args[0], context) : ''})`,
2155
+ uriError: (args, context) => `new URIError(${args.length ? generateExpr(args[0], context) : ''})`,
2156
+ aggregateError: (args, context) => `new AggregateError(${args.map(a => generateExpr(a, context)).join(', ')})`,
2157
+
2158
+ // ── v2.2.0 — Blob / File / FormData (IOPL-native, browser-compatible).
2159
+ blob: (args, context) => `new Blob(${args.map(a => generateExpr(a, context)).join(', ')})`,
2160
+ file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2161
+ formData: (_args) => `new FormData()`,
1501
2162
  };
1502
2163
 
1503
- // Mark the enclosing program async when a call awaits at the top level.
2164
+ // Mark the enclosing program async when a call awaits at the top level, and
2165
+ // record that this scope emitted an `await` so handler and function bodies can
2166
+ // decide their own async-ness at generation time (see generateBlock). Routing
2167
+ // every await-emitting construct through this single function removes the need
2168
+ // for a separate hand-maintained registry of async statement types — so a new
2169
+ // async keyword can never silently break when used inside a route, listener, or
2170
+ // function.
1504
2171
  function markAsync(context) {
1505
- if (!context.inFunction) context.needsAsync = true;
2172
+ context.emittedAwait = true;
2173
+ // Only a construct that awaits at the true top level needs the program
2174
+ // wrapped in an async IIFE. Awaits emitted inside a user function (inFunction)
2175
+ // or inside a route/listener/404 handler (inHandler) are handled by marking
2176
+ // that function/handler async instead — they must not drag the whole program
2177
+ // into an async wrapper, or "top-level use wraps the whole program" would be
2178
+ // the only safe nesting level for a new async keyword.
2179
+ if (!context.inFunction && !context.inHandler) context.needsAsync = true;
2180
+ }
2181
+
2182
+ // Generate a body of statements and report whether it emitted an `await`.
2183
+ //
2184
+ // This is the single source of truth for whether a route handler, listener,
2185
+ // 404 handler, or user function must be declared `async`. Previously this was
2186
+ // decided by a separate AST walker (containsAsyncBlock) that had to be kept in
2187
+ // sync by hand with every construct that compiles down to `await` — the exact
2188
+ // fragility that made "top-level use wraps the whole program" the only place
2189
+ // certain keywords (like ocr) were guaranteed to work. By observing the output
2190
+ // of generation instead, whatever a body contains is handled correctly, even if
2191
+ // it uses a brand-new async keyword.
2192
+ function generateBlock(statements, indent, context) {
2193
+ const prev = context.emittedAwait;
2194
+ context.emittedAwait = false;
2195
+ const out = statements.map(s => generateStatement(s, indent, context)).join('\n');
2196
+ const emitted = context.emittedAwait;
2197
+ context.emittedAwait = prev;
2198
+ return { out, emitted };
1506
2199
  }
1507
2200
 
1508
2201
  // v2.1.0 — generate a request accessor (param/query/header). These compile to
@@ -1536,6 +2229,14 @@ function requireOneArg(name, args) {
1536
2229
  }
1537
2230
  }
1538
2231
 
2232
+ function requireArgs(name, args, minimum, example) {
2233
+ if (args.length < minimum) {
2234
+ throw new Error(
2235
+ `"${name}" needs at least ${minimum} argument${minimum === 1 ? '' : 's'}.\n\nExample:\n ${example}`
2236
+ );
2237
+ }
2238
+ }
2239
+
1539
2240
  // Set to true while generating inside a route handler body.
1540
2241
  // Remaps PlainScript's "request" → "req" and "response" → "res".
1541
2242
  let _inRoute = false;
@@ -1574,8 +2275,16 @@ function emitSqlCall(kind, sql, params, indent, context) {
1574
2275
  let n = 0;
1575
2276
  const pgSql = String(sql).replace(/\?/g, () => (++n <= params.length ? `$${n}` : '?'));
1576
2277
  const call = `${_sqlClientVar}.query(\`${pgSql}\`, [${args}])`;
2278
+ markAsync(context);
1577
2279
  return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
1578
2280
  }
2281
+ if (_sqlDriver === 'mongo') {
2282
+ markAsync(context);
2283
+ // For MongoDB, we delegate to helper functions that parse SQL-like syntax
2284
+ // into MongoDB operations. This is a simplified approach.
2285
+ // All MongoDB operations are async, so always await them.
2286
+ return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
2287
+ }
1579
2288
  switch (kind) {
1580
2289
  case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
1581
2290
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
@@ -1589,7 +2298,10 @@ function createGenerationContext() {
1589
2298
  requires: new Set(),
1590
2299
  pendingPrelude: [],
1591
2300
  needsAsync: false, // true when top-level code emits await (js blocks / ask)
2301
+ emittedAwait: false, // true when the current generateBlock emitted an await
1592
2302
  inFunction: false, // true while generating inside a function-like scope
2303
+ inHandler: false, // true while generating a route/listener/404 response body
2304
+ loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
1593
2305
  };
1594
2306
  }
1595
2307
 
@@ -1653,72 +2365,6 @@ function ensureBuiltin(context, moduleName) {
1653
2365
  }
1654
2366
  }
1655
2367
 
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
2368
  // True when any statement in a block (recursively, skipping nested function
1723
2369
  // declarations) contains a `yield`, which marks the enclosing function as a
1724
2370
  // generator (function*).
@@ -1738,7 +2384,7 @@ function containsYield(statements) {
1738
2384
  function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
1739
2385
  throw new Error(`Expected a Program node but got "${ast.type}".`);
1740
2386
  }
1741
- // v1.0.0 — reset per-program test bookkeeping so repeated generate() calls
2387
+ // v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
1742
2388
  // (build pipeline) start clean.
1743
2389
  __testCount = 0;
1744
2390
  __testCatchers = [];
@@ -1760,7 +2406,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
1760
2406
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
1761
2407
  }
1762
2408
 
1763
- // v1.0.0 — native test runner. When any "test ... done" block exists, emit
2409
+ // v1.0.1 — native test runner. When any "test ... done" block exists, emit
1764
2410
  // the runner helper, register each test after its function declaration, and
1765
2411
  // execute them. Each failure prints a message and sets process.exitCode = 1.
1766
2412
  if (__testCatchers.length > 0) {
@@ -1795,7 +2441,7 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
1795
2441
  return lines.join('\n');
1796
2442
  }
1797
2443
 
1798
- // ── v1.0.0 — test DSL bookkeeping ───────────────────────────────────────────
2444
+ // ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
1799
2445
  let __testCount = 0;
1800
2446
  let __testCatchers = [];
1801
2447
  let __inTest = false;
@@ -1836,8 +2482,16 @@ function generateCondition(cond, context) {
1836
2482
 
1837
2483
  function generateStatement(node, indent = '', context = createGenerationContext()) {
1838
2484
  switch (node.type) {
1839
- case 'RememberStatement':
2485
+ case 'RememberStatement': {
2486
+ // Handle destructuring: remember [a, b] as arr / remember {x, y} as obj
2487
+ if (node.name && typeof node.name === 'object' && (node.name.type === 'ArrayPattern' || node.name.type === 'ObjectPattern')) {
2488
+ const pattern = node.name.type === 'ArrayPattern'
2489
+ ? `[${node.name.elements.map(e => generateLValue(e, context)).join(', ')}]`
2490
+ : `{ ${node.name.properties.map(p => p.key).join(', ')} }`;
2491
+ return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
2492
+ }
1840
2493
  return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
2494
+ }
1841
2495
 
1842
2496
  case 'ShowStatement':
1843
2497
  return `${indent}console.log(${generateExpr(node.value, context)});`;
@@ -1845,18 +2499,49 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1845
2499
  case 'GiveStatement':
1846
2500
  return `${indent}return ${generateExpr(node.value, context)};`;
1847
2501
 
1848
- case 'BecomeStatement':
1849
- return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
2502
+ case 'BecomeStatement': {
2503
+ // Handle destructuring: [a, b] = arr / {x, y} = obj
2504
+ if (node.target && typeof node.target === 'object' && (node.target.type === 'ArrayPattern' || node.target.type === 'ObjectPattern')) {
2505
+ const pattern = node.target.type === 'ArrayPattern'
2506
+ ? `[${node.target.elements.map(e => generateLValue(e, context)).join(', ')}]`
2507
+ : `{ ${node.target.properties.map(p => generateLValue(p, context)).join(', ')} }`;
2508
+ return `${indent}let ${pattern} = ${generateExpr(node.value, context)};`;
2509
+ }
2510
+ const target = generateLValue(node.target, context);
2511
+ const value = generateExpr(node.value, context);
2512
+ const op = node.op || '=';
2513
+ if (op === '=') {
2514
+ return `${indent}${target} = ${value};`;
2515
+ }
2516
+ // Logical assignment: x ||= y, x &&= y, x ??= y
2517
+ // In JS: x ||= y -> x || (x = y)
2518
+ // We need to handle this carefully for member expressions
2519
+ const opMap = { '||=': '||', '&&=': '&&', '??=': '??' };
2520
+ const jsOp = opMap[op];
2521
+ if (jsOp) {
2522
+ return `${indent}${target} ${jsOp} (${target} = ${value});`;
2523
+ }
2524
+ return `${indent}${target} ${op} ${value};`;
2525
+ }
1850
2526
 
1851
- // v1.0.0 — record kinds: `define a kind called "Person" with ... done`.
2527
+ // v1.0.1 — record kinds: `define a kind called "Person" with ... done`.
1852
2528
  // Names are emitted as a JS factory that returns a fresh plain object with
1853
2529
  // declared defaults. Constructors prompt for required fields at compile
1854
2530
  // time via `create a Person with ...` (see GenerateExpr CreateKind).
2531
+ // v1.0.2 — supports `extends` for inheritance.
1855
2532
  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(', ')} }`;
2533
+ let defaults = '';
2534
+ if (node.extends) {
2535
+ // Inherit from parent kind by spreading its defaults
2536
+ defaults = `{ ...__makeKind_${node.extends}({}), ${node.fields.map(f =>
2537
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
2538
+ ).join(', ')} }`;
2539
+ } else {
2540
+ const members = node.fields.map(f =>
2541
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
2542
+ );
2543
+ defaults = `{ ${members.join(', ')} }`;
2544
+ }
1860
2545
  return [
1861
2546
  `${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
1862
2547
  `${indent} const __rec = ${defaults};`,
@@ -1872,14 +2557,14 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1872
2557
  ].join('\n');
1873
2558
  }
1874
2559
 
1875
- // v1.0.0 — load env file "<path>": apply KEY=VALUE pairs to process.env.
2560
+ // v1.0.1 — load env file "<path>": apply KEY=VALUE pairs to process.env.
1876
2561
  // Blank lines and `#` comments are skipped; values keep their text.
1877
2562
  case 'LoadEnvFileStatement': {
1878
2563
  ensureBuiltin(context, 'dotenv');
1879
2564
  return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
1880
2565
  }
1881
2566
 
1882
- // v1.0.0 — native test DSL. `test "<name>" ... done` registers a runnable
2567
+ // v1.0.1 — native test DSL. `test "<name>" ... done` registers a runnable
1883
2568
  // unit; all tests are executed after the program body with a tiny runner.
1884
2569
  case 'TestStatement': {
1885
2570
  __testCount++;
@@ -1892,7 +2577,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1892
2577
  return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
1893
2578
  }
1894
2579
 
1895
- // v1.0.0 — assertion `check <a> (equals|is|contains|raises) <b>`.
2580
+ // v1.0.1 — assertion `check <a> (equals|is|contains|raises) <b>`.
1896
2581
  // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
1897
2582
  // inside the runner's try/catch (its thrown error is the subject).
1898
2583
  case 'CheckStatement': {
@@ -1906,11 +2591,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1906
2591
  return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
1907
2592
  }
1908
2593
 
1909
- // v1.0.0 — export <name>: mark a top-level symbol for module.exports.
2594
+ // v1.0.1 — export <name>: mark a top-level symbol for module.exports.
1910
2595
  case 'ExportStatement':
1911
2596
  return `${indent}module.exports.${node.name} = ${node.name};`;
1912
2597
 
1913
- // v1.0.0 — generators: `yield <expr>` (or bare `yield`).
2598
+ // v1.0.1 — generators: `yield <expr>` (or bare `yield`).
1914
2599
  case 'YieldStatement': {
1915
2600
  if (!context.inFunction) {
1916
2601
  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 +2616,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1931
2616
  return pkg ? `${indent}${pkg}` : '';
1932
2617
  }
1933
2618
 
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
2619
  // ask name / ask "<prompt>" as name
1976
2620
  case 'AskStatement': {
1977
2621
  ensureBuiltin(context, 'ask');
1978
- if (!context.inFunction) context.needsAsync = true;
2622
+ markAsync(context);
1979
2623
  const prompt = node.prompt != null ? JSON.stringify(node.prompt) : '"> "';
1980
2624
  return `${indent}let ${node.variable} = await __ask(${prompt});`;
1981
2625
  }
@@ -1983,27 +2627,42 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1983
2627
  // v2.0.1 — ocr "<image>" as <variable> [using "<lang>"]
1984
2628
  case 'OcrStatement': {
1985
2629
  ensureBuiltin(context, 'ocr');
1986
- if (!context.inFunction) context.needsAsync = true;
2630
+ markAsync(context);
1987
2631
  const image = generateExpr(node.image, context);
1988
2632
  const langArg = node.lang != null ? `, ${JSON.stringify(node.lang)}` : '';
1989
2633
  return `${indent}let ${node.variable} = await __ocr(${image}${langArg});`;
1990
2634
  }
1991
2635
 
1992
2636
  case 'FunctionDeclaration': {
1993
- const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2637
+ const prevInFunction = context.inFunction;
2638
+ context.inFunction = true;
2639
+ const block = generateBlock(node.body, indent + ' ', context);
2640
+ context.inFunction = prevInFunction;
2641
+ const isAsync = block.emitted ? 'async ' : '';
1994
2642
  const isGen = containsYield(node.body) ? '*' : '';
1995
2643
  const paramStr = node.params.map(p => {
2644
+ // Rest parameter: ...args
2645
+ if (p && p.type === 'RestElement') {
2646
+ return `...${p.name}`;
2647
+ }
2648
+ // Destructuring: [a, b] or {x, y}
2649
+ if (p && (p.type === 'ArrayPattern' || p.type === 'ObjectPattern')) {
2650
+ const pattern = p.type === 'ArrayPattern'
2651
+ ? `[${p.elements.map(e => generateLValue(e, context)).join(', ')}]`
2652
+ : `{ ${p.properties.map(prop => generateLValue(prop, context)).join(', ')} }`;
2653
+ if (p.defaultValue) {
2654
+ return `${pattern} = ${generateExpr(p.defaultValue, context)}`;
2655
+ }
2656
+ return pattern;
2657
+ }
2658
+ // Regular parameter
1996
2659
  if (typeof p === 'object') {
1997
2660
  if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
1998
2661
  return p.name;
1999
2662
  }
2000
2663
  return p;
2001
2664
  }).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}}`;
2665
+ return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${block.out}\n${indent}}`;
2007
2666
  }
2008
2667
 
2009
2668
  case 'IfStatement': {
@@ -2018,50 +2677,151 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2018
2677
  }
2019
2678
 
2020
2679
  case 'ForEachStatement': {
2680
+ context.loopDepth++;
2021
2681
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2682
+ context.loopDepth--;
2022
2683
  return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
2023
2684
  }
2024
2685
 
2686
+ case 'ForIndexStatement': {
2687
+ context.loopDepth++;
2688
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2689
+ context.loopDepth--;
2690
+ // for index <name> in <collection> — zero-based index over a list.
2691
+ if (node.over != null) {
2692
+ const coll = generateExpr(node.over, context);
2693
+ return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
2694
+ }
2695
+ const start = generateExpr(node.start, context);
2696
+ const end = generateExpr(node.end, context);
2697
+ // Explicit step uses the user's sign; otherwise the increment follows
2698
+ // the direction of the bounds (from 5 to 1 counts down automatically).
2699
+ const inc = node.step ? generateExpr(node.step, context)
2700
+ : `(${start} <= ${end} ? 1 : -1)`;
2701
+ // Direction-aware: "from 5 to 1" counts down even without an explicit
2702
+ // "by", while "from 1 to 5" counts up.
2703
+ const test = `(${start} <= ${end} ? ${node.name} <= ${end} : ${node.name} >= ${end})`;
2704
+ return `${indent}for (let ${node.name} = ${start}; ${test}; ${node.name} += ${inc}) {\n${body}\n${indent}}`;
2705
+ }
2706
+
2025
2707
  case 'WhileStatement': {
2026
2708
  const condition = generateCondition(node.condition, context);
2027
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2709
+ context.loopDepth++;
2710
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2711
+ context.loopDepth--;
2028
2712
  return `${indent}while (${condition}) {\n${body}\n${indent}}`;
2029
2713
  }
2030
2714
 
2715
+ case 'BreakStatement': {
2716
+ if (context.loopDepth <= 0) {
2717
+ 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');
2718
+ }
2719
+ return `${indent}break;`;
2720
+ }
2721
+
2722
+ case 'ContinueStatement': {
2723
+ if (context.loopDepth <= 0) {
2724
+ 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');
2725
+ }
2726
+ return `${indent}continue;`;
2727
+ }
2728
+
2729
+ case 'DebuggerStatement':
2730
+ return `${indent}debugger;`;
2731
+
2732
+ case 'ThrowStatement':
2733
+ return `${indent}throw ${generateExpr(node.value, context)};`;
2734
+
2735
+ case 'ReturnStatement':
2736
+ return `${indent}return${node.value ? ' ' + generateExpr(node.value, context) : ''};`;
2737
+
2738
+ case 'BreakStatement': {
2739
+ if (context.loopDepth <= 0) {
2740
+ 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');
2741
+ }
2742
+ return `${indent}break;`;
2743
+ }
2744
+
2745
+ case 'ContinueStatement': {
2746
+ if (context.loopDepth <= 0) {
2747
+ 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');
2748
+ }
2749
+ return `${indent}continue;`;
2750
+ }
2751
+
2752
+ case 'SwitchStatement': {
2753
+ const discriminant = generateExpr(node.discriminant, context);
2754
+ const cases = node.cases.map(c => {
2755
+ const test = generateExpr(c.test, context);
2756
+ const body = c.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2757
+ return `${indent} case ${test}:\n${body}\n${indent} break;`;
2758
+ }).join('\n');
2759
+ let out = `${indent}switch (${discriminant}) {\n${cases}`;
2760
+ if (node.defaultCase) {
2761
+ const defaultBody = node.defaultCase.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2762
+ out += `\n${indent} default:\n${defaultBody}\n${indent} break;`;
2763
+ }
2764
+ out += `\n${indent}}`;
2765
+ return out;
2766
+ }
2767
+
2768
+ case 'ClassDeclaration': {
2769
+ const superClass = node.superClass ? ` extends ${generateExpr(node.superClass, context)}` : '';
2770
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2771
+ return `${indent}class ${node.name}${superClass} {\n${body}\n${indent}}`;
2772
+ }
2773
+
2031
2774
  // v0.3 — Express runtime
2032
2775
 
2033
2776
  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}});`;
2777
+ const prevInHandler = context.inHandler;
2778
+ context.inHandler = true;
2779
+ const block = generateBlock(node.body, indent + ' ', context);
2780
+ context.inHandler = prevInHandler;
2781
+ const handlerAsync = block.emitted ? 'async ' : '';
2782
+ return `${indent}app.listen(${generateExpr(node.port, context)}, ${handlerAsync}() => {\n${block.out}\n${indent}});`;
2037
2783
  }
2038
2784
 
2039
2785
  case 'RouteStatement': {
2040
2786
  _inRoute = true;
2041
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2042
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2787
+ const prevInHandler = context.inHandler;
2788
+ context.inHandler = true;
2789
+ const block = generateBlock(node.body, indent + ' ', context);
2790
+ context.inHandler = prevInHandler;
2043
2791
  _inRoute = false;
2044
- return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
2792
+ const handlerAsync = block.emitted ? 'async ' : '';
2793
+ return `${indent}app.get(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
2045
2794
  }
2046
2795
 
2047
2796
  case 'ReplyStatement':
2048
2797
  if (_inTelegram) {
2798
+ markAsync(context);
2049
2799
  return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)});`;
2050
2800
  }
2051
2801
  if (_inWhatsApp) {
2802
+ markAsync(context);
2052
2803
  ensureBuiltin(context, 'whatsapp');
2053
2804
  return `${indent}await __whatsappReply(__waCtx.chat, ${generateExpr(node.value, context)});`;
2054
2805
  }
2055
2806
  return `${indent}res.send(${generateExpr(node.value, context)});`;
2056
2807
 
2808
+ case 'ReplyFileStatement':
2809
+ if (!_inRoute) {
2810
+ throw new Error('"reply file" can only be used inside a route handler.\n\nExample:\n route get "/"\n reply file "public/index.html"\n done');
2811
+ }
2812
+ // Use path.resolve to handle relative paths correctly
2813
+ return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
2814
+
2057
2815
  case 'ReplyJsonStatement': {
2058
2816
  const props = node.properties
2059
2817
  .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
2060
2818
  .join(', ');
2061
2819
  if (_inTelegram) {
2820
+ markAsync(context);
2062
2821
  return `${indent}await Telegram.sendMessage(ctx.chatId, JSON.stringify({ ${props} }));`;
2063
2822
  }
2064
2823
  if (_inWhatsApp) {
2824
+ markAsync(context);
2065
2825
  ensureBuiltin(context, 'whatsapp');
2066
2826
  return `${indent}await __whatsappReply(__waCtx.chat, JSON.stringify({ ${props} }));`;
2067
2827
  }
@@ -2074,6 +2834,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2074
2834
  // button is rendered as [text, data] and rows are merged into that list.
2075
2835
  case 'ReplyWithButtonsStatement': {
2076
2836
  ensureBuiltin(context, 'telegram');
2837
+ markAsync(context);
2077
2838
  const pairs = node.buttons.flat().map(({ text, data }) => [text, data]);
2078
2839
  return `${indent}await Telegram.sendMessage(ctx.chatId, ${generateExpr(node.value, context)}, ${JSON.stringify(pairs)});`;
2079
2840
  }
@@ -2095,10 +2856,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2095
2856
 
2096
2857
  case 'SimpleRouteStatement': {
2097
2858
  _inRoute = true;
2098
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2099
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2859
+ const prevInHandler = context.inHandler;
2860
+ context.inHandler = true;
2861
+ const block = generateBlock(node.body, indent + ' ', context);
2862
+ context.inHandler = prevInHandler;
2100
2863
  _inRoute = false;
2101
- return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${body}\n${indent}});`;
2864
+ const handlerAsync = block.emitted ? 'async ' : '';
2865
+ return `${indent}app.${node.method}(${JSON.stringify(routePath(node.path))}, ${handlerAsync}(req, res) => {\n${block.out}\n${indent}});`;
2102
2866
  }
2103
2867
 
2104
2868
  // v2.1.0 — group "<prefix>" ... done: composes routes under a shared
@@ -2225,10 +2989,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2225
2989
  // in registration order).
2226
2990
  case 'NotFoundStatement': {
2227
2991
  _inRoute = true;
2228
- const handlerAsync = containsAsyncBlock(node.body) ? 'async ' : '';
2229
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2992
+ const prevInHandler = context.inHandler;
2993
+ context.inHandler = true;
2994
+ const block = generateBlock(node.body, indent + ' ', context);
2995
+ context.inHandler = prevInHandler;
2230
2996
  _inRoute = false;
2231
- return `${indent}app.use((${handlerAsync}req, res) => {\n${body}\n${indent}});`;
2997
+ const handlerAsync = block.emitted ? 'async ' : '';
2998
+ return `${indent}app.use((${handlerAsync}req, res) => {\n${block.out}\n${indent}});`;
2232
2999
  }
2233
3000
 
2234
3001
  // ── v2.1.1 — error handling and retries
@@ -2236,8 +3003,8 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2236
3003
  case 'TryStatement': {
2237
3004
  const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2238
3005
  const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
3006
+ const lines = [tryBlock];
2239
3007
  if (node.catches && node.catches.length > 0) {
2240
- const lines = [tryBlock];
2241
3008
  for (let i = 0; i < node.catches.length; i++) {
2242
3009
  const c = node.catches[i];
2243
3010
  const errorName = c.name || c.param || '__plainError';
@@ -2265,17 +3032,22 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2265
3032
  }
2266
3033
  }
2267
3034
  }
2268
- return lines.join('\n');
2269
- }
2270
- let out = tryBlock;
2271
- if (node.recoverBody) {
3035
+ } else if (node.recoverBody) {
2272
3036
  const errorName = node.catchName || '__plainError';
2273
3037
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2274
- out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
3038
+ lines.push(`${indent}} catch (${errorName}) {`);
3039
+ lines.push(recoverBody);
3040
+ lines.push(`${indent}}`);
2275
3041
  } else {
2276
- out += `${indent}} catch (__plainError) {}`;
3042
+ lines.push(`${indent}} catch (__plainError) {}`);
2277
3043
  }
2278
- return out;
3044
+ if (node.finallyBody) {
3045
+ const finallyBody = node.finallyBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
3046
+ lines.push(`${indent}finally {`);
3047
+ lines.push(finallyBody);
3048
+ lines.push(`${indent}}`);
3049
+ }
3050
+ return lines.join('\n');
2279
3051
  }
2280
3052
 
2281
3053
  case 'RetryStatement': {
@@ -2321,13 +3093,28 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2321
3093
  case 'PostgresStatement': {
2322
3094
  _sqlDriver = 'pg';
2323
3095
  _sqlClientVar = 'db';
2324
- if (!context.inFunction) context.needsAsync = true;
3096
+ markAsync(context);
2325
3097
  return [
2326
3098
  emitRequire(context, 'postgres'),
2327
3099
  `${indent}const db = new Pool({ connectionString: ${generateExpr(node.connection, context)} });`,
2328
3100
  ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
2329
3101
  }
2330
3102
 
3103
+ // v2.2.0 — mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
3104
+ // Uses the mongodb driver; subsequent query/insert/update/delete/execute
3105
+ // statements compile to MongoDB collection operations.
3106
+ case 'MongoStatement': {
3107
+ _sqlDriver = 'mongo';
3108
+ _sqlClientVar = 'db';
3109
+ markAsync(context);
3110
+ ensureBuiltin(context, 'mongodb');
3111
+ const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
3112
+ return [
3113
+ emitRequire(context, 'mongodb'),
3114
+ `${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
3115
+ ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
3116
+ }
3117
+
2331
3118
  case 'QueryStatement':
2332
3119
  return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
2333
3120
 
@@ -2352,7 +3139,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2352
3139
  if (_sqlDriver === 'pg') {
2353
3140
  const prevClient = _sqlClientVar;
2354
3141
  _sqlClientVar = '__txClient';
2355
- if (!context.inFunction) context.needsAsync = true;
3142
+ markAsync(context);
2356
3143
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2357
3144
  _sqlClientVar = prevClient;
2358
3145
  return [
@@ -2385,7 +3172,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2385
3172
 
2386
3173
  case 'TelegramCommandStatement': {
2387
3174
  ensureBuiltin(context, 'telegram');
2388
- if (!context.inFunction) context.needsAsync = true;
3175
+ markAsync(context);
2389
3176
  _inTelegram = true;
2390
3177
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2391
3178
  _inTelegram = false;
@@ -2397,7 +3184,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2397
3184
 
2398
3185
  case 'TelegramCallbackStatement': {
2399
3186
  ensureBuiltin(context, 'telegram');
2400
- if (!context.inFunction) context.needsAsync = true;
3187
+ markAsync(context);
2401
3188
  _inTelegram = true;
2402
3189
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2403
3190
  _inTelegram = false;
@@ -2406,7 +3193,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2406
3193
 
2407
3194
  case 'TelegramStartStatement': {
2408
3195
  ensureBuiltin(context, 'telegram');
2409
- if (!context.inFunction) context.needsAsync = true;
3196
+ markAsync(context);
2410
3197
  return `${indent}await BOT.start();`;
2411
3198
  }
2412
3199
 
@@ -2445,7 +3232,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2445
3232
  // WhatsApp message as a normalized PlainScript record on `message`.
2446
3233
  case 'WhatsAppOnMessageStatement': {
2447
3234
  ensureBuiltin(context, 'whatsapp');
2448
- if (!context.inFunction) context.needsAsync = true;
3235
+ markAsync(context);
2449
3236
  const prevInWhatsApp = _inWhatsApp;
2450
3237
  _inWhatsApp = true;
2451
3238
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -2548,7 +3335,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2548
3335
 
2549
3336
  case 'RunBackgroundStatement':
2550
3337
  return [
2551
- `${indent}setImmediate(() => {`,
3338
+ `${indent}setImmediate(async () => {`,
2552
3339
  `${indent} try {`,
2553
3340
  `${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
2554
3341
  `${indent} } catch (error) { console.error(error); }`,
@@ -2666,6 +3453,9 @@ function generateLValue(node, context) {
2666
3453
  if (node.type === 'FirstItem') return `${generateExpr(node.collection, context)}[0]`;
2667
3454
  if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
2668
3455
  if (node.type === 'LastItem') return `${generateExpr(node.collection, context)}[${generateExpr(node.collection, context)}.length - 1]`;
3456
+ // Destructuring patterns
3457
+ if (node.type === 'ArrayPattern') return `[${node.elements.map(e => generateLValue(e, context)).join(', ')}]`;
3458
+ if (node.type === 'ObjectPattern') return `{ ${node.properties.map(p => p.key).join(', ')} }`;
2669
3459
  throw new Error(`Invalid assignment target "${node.type}".`);
2670
3460
  }
2671
3461
 
@@ -2712,6 +3502,18 @@ function generateExpr(node, context = createGenerationContext()) {
2712
3502
  // Inside route handlers, remap PlainScript's request/response to req/res
2713
3503
  if (_inRoute && node.name === 'request') return 'req';
2714
3504
  if (_inRoute && node.name === 'response') return 'res';
3505
+ if (_inTelegram) {
3506
+ const telegramContext = {
3507
+ message: 'ctx.message',
3508
+ chat: 'ctx.chat',
3509
+ chatId: 'ctx.chatId',
3510
+ text: 'ctx.text',
3511
+ args: 'ctx.args',
3512
+ matches: 'ctx.matches',
3513
+ data: 'ctx.data',
3514
+ };
3515
+ if (telegramContext[node.name]) return telegramContext[node.name];
3516
+ }
2715
3517
  // Inside WhatsApp "on message" handlers, PlainScript's "message" is the
2716
3518
  // normalized record of the current delivery.
2717
3519
  if (_inWhatsApp && node.name === 'message') return '__waCtx.message';
@@ -2748,13 +3550,31 @@ function generateExpr(node, context = createGenerationContext()) {
2748
3550
  return `{ ${props} }`;
2749
3551
  }
2750
3552
 
3553
+ case 'ConditionalExpression':
3554
+ return `(${generateExpr(node.condition, context)} ? ${generateExpr(node.consequent, context)} : ${generateExpr(node.alternate, context)})`;
3555
+
3556
+ case 'NullishCoalesceExpression':
3557
+ return `(${generateExpr(node.left, context)} ?? ${generateExpr(node.right, context)})`;
3558
+
2751
3559
  case 'IndexExpression':
2752
3560
  return `${generateExpr(node.object, context)}[${generateExpr(node.index, context)}]`;
2753
3561
 
2754
3562
  case 'MemberExpression':
2755
3563
  return `${generateExpr(node.object, context)}.${node.property}`;
2756
3564
 
3565
+ case 'OptionalChainExpression':
3566
+ return `${generateExpr(node.object, context)}?.${node.property}`;
3567
+
3568
+ case 'OptionalCallExpression':
3569
+ return `${generateExpr(node.callee.object, context)}?.${node.callee.property}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
3570
+
2757
3571
  case 'CallExpression': {
3572
+ // Method call: receiver.method(args). Member access invoked with parens —
3573
+ // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
3574
+ if (node.callee) {
3575
+ const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
3576
+ return `${generateExpr(node.callee, context)}(${args})`;
3577
+ }
2758
3578
  if (STDLIB[node.name]) {
2759
3579
  if (node.name === 'readFile' || node.name === 'writeFile' ||
2760
3580
  node.name === 'fileExists' || node.name === 'read') {
@@ -2811,7 +3631,7 @@ function generateExpr(node, context = createGenerationContext()) {
2811
3631
  ensureBuiltin(context, 'fs');
2812
3632
  return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
2813
3633
 
2814
- // v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`
3634
+ // v1.0.1 — record constructor: `create a Person with name "Ada" and age 17`
2815
3635
  // calls the kind factory that `define a kind called "Person"` registered.
2816
3636
  case 'CreateKindExpression': {
2817
3637
  const fields = node.pairs
@@ -2820,7 +3640,7 @@ function generateExpr(node, context = createGenerationContext()) {
2820
3640
  return `${node.kind}({ ${fields} })`;
2821
3641
  }
2822
3642
 
2823
- // v1.0.0 — concurrency combinators: `all of [...]` / `any of [...]` /
3643
+ // v1.0.1 — concurrency combinators: `all of [...]` / `any of [...]` /
2824
3644
  // `settled of [...]`. All are awaited; `settled` returns status records.
2825
3645
  case 'ConcurrencyExpression': {
2826
3646
  markAsync(context);
@@ -2830,10 +3650,67 @@ function generateExpr(node, context = createGenerationContext()) {
2830
3650
  return `(await Promise.all(${rhs}))`;
2831
3651
  }
2832
3652
 
2833
- // v1.0.0 — `spread of <collection>` → a fresh array from an iterable.
3653
+ // v1.0.1 — `spread of <collection>` → a fresh array from an iterable.
2834
3654
  case 'SpreadExpression':
2835
3655
  return `[...${generateExpr(node.collection, context)}]`;
2836
3656
 
3657
+ case 'SpreadElement':
3658
+ return `...${generateExpr(node.argument, context)}`;
3659
+
3660
+ case 'SpreadProperty':
3661
+ return `...${generateExpr(node.argument, context)}`;
3662
+
3663
+ case 'ArrayPattern':
3664
+ // Array destructuring pattern: [a, b] = value
3665
+ return `[${node.elements.map(e => generateExpr(e, context)).join(', ')}]`;
3666
+
3667
+ case 'ObjectPattern':
3668
+ // Object destructuring pattern: {x, y} = value
3669
+ return `{ ${node.properties.map(p => generateExpr(p, context)).join(', ')} }`;
3670
+
3671
+ case 'RestElement':
3672
+ return `...${node.name}`;
3673
+
3674
+ case 'BigIntLiteral':
3675
+ return `${node.value}n`;
3676
+
3677
+ case 'UndefinedLiteral':
3678
+ return 'undefined';
3679
+
3680
+ case 'ThisExpression':
3681
+ return 'this';
3682
+
3683
+ case 'ImportMetaExpression':
3684
+ return 'import.meta';
3685
+
3686
+ case 'SuperExpression':
3687
+ return 'super';
3688
+
3689
+ case 'SuperProperty':
3690
+ return `super.${node.property}`;
3691
+
3692
+ case 'NewExpression':
3693
+ return `new ${generateExpr(node.callee, context)}(${node.args.map(arg => generateExpr(arg, context)).join(', ')})`;
3694
+
3695
+ case 'AwaitExpression': {
3696
+ markAsync(context);
3697
+ return `(await ${generateExpr(node.value, context)})`;
3698
+ }
3699
+
3700
+ case 'UnaryExpression': {
3701
+ // Handle typeof, void, delete operators
3702
+ if (['typeof', 'void', 'delete'].includes(node.operator)) {
3703
+ const operand = node.operand.type === 'BinaryExpression'
3704
+ ? `(${generateExpr(node.operand, context)})`
3705
+ : generateExpr(node.operand, context);
3706
+ return `${node.operator} ${operand}`;
3707
+ }
3708
+ // Regular unary minus
3709
+ return `${node.operator}${node.operand.type === 'BinaryExpression'
3710
+ ? `(${generateExpr(node.operand, context)})`
3711
+ : generateExpr(node.operand, context)}`;
3712
+ }
3713
+
2837
3714
  default:
2838
3715
  throw new Error(`Unknown expression type "${node.type}".`);
2839
3716
  }