plainscript-lang 1.0.1 → 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 +69 -73
  4. package/compiler/dependency-detector.js +5 -0
  5. package/compiler/formatter.js +1 -1
  6. package/compiler/generator.js +931 -89
  7. package/compiler/lexer.js +129 -53
  8. package/compiler/parser.js +995 -152
  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 +101 -608
  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.
@@ -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')`,
@@ -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,6 +1363,26 @@ 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
 
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
+
1264
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) =>
@@ -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) => {
@@ -1412,7 +1672,7 @@ const STDLIB = {
1412
1672
  // Generators / iterables
1413
1673
  spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
1414
1674
 
1415
- // v1.0.1 — 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,6 +1780,385 @@ 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
2164
  // Mark the enclosing program async when a call awaits at the top level, and
@@ -1568,6 +2229,14 @@ function requireOneArg(name, args) {
1568
2229
  }
1569
2230
  }
1570
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
+
1571
2240
  // Set to true while generating inside a route handler body.
1572
2241
  // Remaps PlainScript's "request" → "req" and "response" → "res".
1573
2242
  let _inRoute = false;
@@ -1609,6 +2278,13 @@ function emitSqlCall(kind, sql, params, indent, context) {
1609
2278
  markAsync(context);
1610
2279
  return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
1611
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
+ }
1612
2288
  switch (kind) {
1613
2289
  case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
1614
2290
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
@@ -1806,8 +2482,16 @@ function generateCondition(cond, context) {
1806
2482
 
1807
2483
  function generateStatement(node, indent = '', context = createGenerationContext()) {
1808
2484
  switch (node.type) {
1809
- 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
+ }
1810
2493
  return `${indent}let ${node.name} = ${generateExpr(node.value, context)};`;
2494
+ }
1811
2495
 
1812
2496
  case 'ShowStatement':
1813
2497
  return `${indent}console.log(${generateExpr(node.value, context)});`;
@@ -1815,18 +2499,49 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1815
2499
  case 'GiveStatement':
1816
2500
  return `${indent}return ${generateExpr(node.value, context)};`;
1817
2501
 
1818
- case 'BecomeStatement':
1819
- 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
+ }
1820
2526
 
1821
2527
  // v1.0.1 — record kinds: `define a kind called "Person" with ... done`.
1822
2528
  // Names are emitted as a JS factory that returns a fresh plain object with
1823
2529
  // declared defaults. Constructors prompt for required fields at compile
1824
2530
  // time via `create a Person with ...` (see GenerateExpr CreateKind).
2531
+ // v1.0.2 — supports `extends` for inheritance.
1825
2532
  case 'DefineKindStatement': {
1826
- const members = node.fields.map(f =>
1827
- `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
1828
- );
1829
- 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
+ }
1830
2545
  return [
1831
2546
  `${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
1832
2547
  `${indent} const __rec = ${defaults};`,
@@ -1901,47 +2616,6 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1901
2616
  return pkg ? `${indent}${pkg}` : '';
1902
2617
  }
1903
2618
 
1904
- // v1.1.1 — JavaScript Gateway (RFC-0011)
1905
-
1906
- // remember <name> as javascript … done (named — always produces a value)
1907
- // javascript … done (statement-level block)
1908
- case 'JavaScriptBlock': {
1909
- // Validate the raw JavaScript at compile time so JS syntax errors are
1910
- // reported as such, with the PlainScript context that produced them.
1911
- try {
1912
- new vm.Script(`(async () => {\n${node.body}\n})`);
1913
- } catch (e) {
1914
- const label = node.name ? `assigned to "${node.name}"` : 'block';
1915
- throw new Error(
1916
- `JavaScript error inside the "javascript" ${label}: ${e.message}`
1917
- );
1918
- }
1919
- // Does the body use top-level `await`? Top-level await only parses
1920
- // inside an async function, so a plain Script rejects it. Synchronous
1921
- // statement-level blocks need no wrapper; async ones do.
1922
- let hasTopLevelAwait = false;
1923
- try {
1924
- new vm.Script(node.body);
1925
- } catch (_) {
1926
- hasTopLevelAwait = true;
1927
- }
1928
- // Named blocks always bind a value, so they keep the async IIFE. The
1929
- // body is emitted verbatim: JavaScript indentation, template literals,
1930
- // and line structure are preserved as written (RFC-0011 §31).
1931
- if (node.name) {
1932
- markAsync(context);
1933
- return `${indent}let ${node.name} = await (async () => {\n${node.body}\n${indent}})();`;
1934
- }
1935
- // Statement-level blocks inside functions/routes/loops, or that need
1936
- // top-level await, retain the async-context wrapper.
1937
- if (context.inFunction || hasTopLevelAwait) {
1938
- markAsync(context);
1939
- return `${indent}await (async () => {\n${node.body}\n${indent}})();`;
1940
- }
1941
- // Synchronous statement-level block: emit its body directly/verbatim.
1942
- return `${indent}${node.body}`;
1943
- }
1944
-
1945
2619
  // ask name / ask "<prompt>" as name
1946
2620
  case 'AskStatement': {
1947
2621
  ensureBuiltin(context, 'ask');
@@ -1967,6 +2641,21 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1967
2641
  const isAsync = block.emitted ? 'async ' : '';
1968
2642
  const isGen = containsYield(node.body) ? '*' : '';
1969
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
1970
2659
  if (typeof p === 'object') {
1971
2660
  if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
1972
2661
  return p.name;
@@ -2037,9 +2726,51 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2037
2726
  return `${indent}continue;`;
2038
2727
  }
2039
2728
 
2729
+ case 'DebuggerStatement':
2730
+ return `${indent}debugger;`;
2731
+
2040
2732
  case 'ThrowStatement':
2041
2733
  return `${indent}throw ${generateExpr(node.value, context)};`;
2042
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
+
2043
2774
  // v0.3 — Express runtime
2044
2775
 
2045
2776
  case 'ListenStatement': {
@@ -2074,6 +2805,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2074
2805
  }
2075
2806
  return `${indent}res.send(${generateExpr(node.value, context)});`;
2076
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
+
2077
2815
  case 'ReplyJsonStatement': {
2078
2816
  const props = node.properties
2079
2817
  .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
@@ -2265,8 +3003,8 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2265
3003
  case 'TryStatement': {
2266
3004
  const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2267
3005
  const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
3006
+ const lines = [tryBlock];
2268
3007
  if (node.catches && node.catches.length > 0) {
2269
- const lines = [tryBlock];
2270
3008
  for (let i = 0; i < node.catches.length; i++) {
2271
3009
  const c = node.catches[i];
2272
3010
  const errorName = c.name || c.param || '__plainError';
@@ -2294,17 +3032,22 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2294
3032
  }
2295
3033
  }
2296
3034
  }
2297
- return lines.join('\n');
2298
- }
2299
- let out = tryBlock;
2300
- if (node.recoverBody) {
3035
+ } else if (node.recoverBody) {
2301
3036
  const errorName = node.catchName || '__plainError';
2302
3037
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2303
- out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
3038
+ lines.push(`${indent}} catch (${errorName}) {`);
3039
+ lines.push(recoverBody);
3040
+ lines.push(`${indent}}`);
2304
3041
  } else {
2305
- out += `${indent}} catch (__plainError) {}`;
3042
+ lines.push(`${indent}} catch (__plainError) {}`);
2306
3043
  }
2307
- 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');
2308
3051
  }
2309
3052
 
2310
3053
  case 'RetryStatement': {
@@ -2357,6 +3100,21 @@ function generateStatement(node, indent = '', context = createGenerationContext(
2357
3100
  ].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
2358
3101
  }
2359
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
+
2360
3118
  case 'QueryStatement':
2361
3119
  return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
2362
3120
 
@@ -2695,6 +3453,9 @@ function generateLValue(node, context) {
2695
3453
  if (node.type === 'FirstItem') return `${generateExpr(node.collection, context)}[0]`;
2696
3454
  if (node.type === 'NumberedItem') return `${generateExpr(node.collection, context)}[${node.index}]`;
2697
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(', ')} }`;
2698
3459
  throw new Error(`Invalid assignment target "${node.type}".`);
2699
3460
  }
2700
3461
 
@@ -2741,6 +3502,18 @@ function generateExpr(node, context = createGenerationContext()) {
2741
3502
  // Inside route handlers, remap PlainScript's request/response to req/res
2742
3503
  if (_inRoute && node.name === 'request') return 'req';
2743
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
+ }
2744
3517
  // Inside WhatsApp "on message" handlers, PlainScript's "message" is the
2745
3518
  // normalized record of the current delivery.
2746
3519
  if (_inWhatsApp && node.name === 'message') return '__waCtx.message';
@@ -2777,12 +3550,24 @@ function generateExpr(node, context = createGenerationContext()) {
2777
3550
  return `{ ${props} }`;
2778
3551
  }
2779
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
+
2780
3559
  case 'IndexExpression':
2781
3560
  return `${generateExpr(node.object, context)}[${generateExpr(node.index, context)}]`;
2782
3561
 
2783
3562
  case 'MemberExpression':
2784
3563
  return `${generateExpr(node.object, context)}.${node.property}`;
2785
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
+
2786
3571
  case 'CallExpression': {
2787
3572
  // Method call: receiver.method(args). Member access invoked with parens —
2788
3573
  // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
@@ -2869,6 +3654,63 @@ function generateExpr(node, context = createGenerationContext()) {
2869
3654
  case 'SpreadExpression':
2870
3655
  return `[...${generateExpr(node.collection, context)}]`;
2871
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
+
2872
3714
  default:
2873
3715
  throw new Error(`Unknown expression type "${node.type}".`);
2874
3716
  }