plainscript-lang 0.1.7 → 1.0.0-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 (49) hide show
  1. package/README.md +98 -40
  2. package/compiler/bundler.js +1 -1
  3. package/compiler/cli.js +166 -57
  4. package/compiler/generator.js +878 -19
  5. package/compiler/lexer.js +31 -2
  6. package/compiler/parser.js +668 -24
  7. package/compiler/version.js +1 -1
  8. package/docs/CAPABILITY_GAP_AUDIT.md +439 -0
  9. package/docs/PLINJS_SPEC.md +124 -24
  10. package/docs/index.html +555 -2220
  11. package/docs/website/script.js +889 -133
  12. package/docs/website/style.css +652 -1113
  13. package/examples/auth-api.ps +56 -0
  14. package/examples/{cache-and-jobs.pln → cache-and-jobs.ps} +1 -1
  15. package/examples/concurrency.ps +49 -0
  16. package/examples/{database.pln → database.ps} +1 -1
  17. package/examples/{deployment.pln → deployment.ps} +1 -1
  18. package/examples/{email-send.pln → email-send.ps} +1 -1
  19. package/examples/error-handling.ps +54 -0
  20. package/examples/file-uploads.ps +39 -0
  21. package/examples/files-and-config.ps +47 -0
  22. package/examples/http-client.ps +44 -0
  23. package/examples/modules/app.ps +16 -0
  24. package/examples/modules/math.ps +20 -0
  25. package/examples/record-kinds.ps +43 -0
  26. package/examples/{rest-api.pln → rest-api.ps} +1 -1
  27. package/examples/{scheduled-tasks.pln → scheduled-tasks.ps} +1 -1
  28. package/examples/search-and-filter.ps +34 -0
  29. package/examples/sessions-and-cookies.ps +54 -0
  30. package/examples/{websocket-server.pln → websocket-server.ps} +1 -1
  31. package/package.json +2 -2
  32. package/docs/website/index.html +0 -1500
  33. /package/examples/{arrays.pln → arrays.ps} +0 -0
  34. /package/examples/{day2.pln → day2.ps} +0 -0
  35. /package/examples/{day3.pln → day3.ps} +0 -0
  36. /package/examples/{expressions.pln → expressions.ps} +0 -0
  37. /package/examples/football-backend/{app.pln → app.ps} +0 -0
  38. /package/examples/{hello.pln → hello.ps} +0 -0
  39. /package/examples/id-verification/{app.pln → app.ps} +0 -0
  40. /package/examples/{loops.pln → loops.ps} +0 -0
  41. /package/examples/{objects.pln → objects.ps} +0 -0
  42. /package/examples/{rest-api-fetch.pln → rest-api-fetch.ps} +0 -0
  43. /package/examples/{server.pln → server.ps} +0 -0
  44. /package/examples/{start.pln → start.ps} +0 -0
  45. /package/examples/{stdlib.pln → stdlib.ps} +0 -0
  46. /package/examples/{telegram-bot.pln → telegram-bot.ps} +0 -0
  47. /package/examples/{web-app.pln → web-app.ps} +0 -0
  48. /package/examples/whatsapp-bot/{pairing.pln → pairing.ps} +0 -0
  49. /package/examples/whatsapp-bot/{qr.pln → qr.ps} +0 -0
@@ -38,7 +38,27 @@ const JS_RESERVED = new Set([
38
38
 
39
39
  const BUILTIN_DECLARATIONS = {
40
40
  fs: `const fs = require('fs');`,
41
+ path: `const path = require('path');`,
41
42
  crypto: `const crypto = require('crypto');`,
43
+ // v1.0.0-latest — env-file runtime. Applies KEY=VALUE pairs from a .env file to
44
+ // process.env. Blank lines and `#` comment lines are skipped.
45
+ dotenv: [
46
+ `function __loadEnvFile(path) {`,
47
+ ` const fs = require('fs');`,
48
+ ` let raw;`,
49
+ ` try { raw = fs.readFileSync(path, 'utf8'); } catch (e) { return; }`,
50
+ ` for (const line of raw.split(/\\r?\\n/)) {`,
51
+ ` const trimmed = line.trim();`,
52
+ ` if (!trimmed || trimmed.startsWith('#')) continue;`,
53
+ ` const eq = trimmed.indexOf('=');`,
54
+ ` if (eq < 0) continue;`,
55
+ ` const k = trimmed.slice(0, eq).trim();`,
56
+ ` let v = trimmed.slice(eq + 1).trim();`,
57
+ ` if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith('\\'') && v.endsWith('\\''))) v = v.slice(1, -1);`,
58
+ ` if (process.env[k] === undefined) process.env[k] = v;`,
59
+ ` }`,
60
+ `}`,
61
+ ].join('\n'),
42
62
  // v1.1.1 — ask runtime (RFC-0011 §14)
43
63
  ask: [
44
64
  `const readline = require('readline');`,
@@ -66,6 +86,224 @@ const BUILTIN_DECLARATIONS = {
66
86
  ` }`,
67
87
  `}`,
68
88
  ].join('\n'),
89
+ // v1.0.0-latest — shared runtime helpers for reflection, binary-size, YAML subset
90
+ // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
91
+ // when any feature that needs them is used.
92
+ core: [
93
+ `function __typeOf(x) {`,
94
+ ` if (x === null) return 'null';`,
95
+ ` if (x === undefined) return 'undefined';`,
96
+ ` const t = typeof x;`,
97
+ ` if (t === 'string') return 'text';`,
98
+ ` if (t === 'number') return 'number';`,
99
+ ` if (t === 'boolean') return 'boolean';`,
100
+ ` if (Array.isArray(x)) return 'array';`,
101
+ ` if (t === 'object') return 'record';`,
102
+ ` if (t === 'function') return 'function';`,
103
+ ` return t;`,
104
+ `}`,
105
+ `function __sizeOf(x) {`,
106
+ ` if (x == null) return 0;`,
107
+ ` if (typeof x === 'string' || Array.isArray(x)) return x.length;`,
108
+ ` if (x instanceof Map || x instanceof Set) return x.size;`,
109
+ ` if (typeof x === 'object') return Object.keys(x).length;`,
110
+ ` return 0;`,
111
+ `}`,
112
+ `function __formatDate(x, pattern) {`,
113
+ ` const p = pattern || 'YYYY-MM-DD HH:mm:ss';`,
114
+ ` let d = x instanceof Date ? x : new Date(x);`,
115
+ ` if (Number.isNaN(d.getTime())) return '';`,
116
+ ` const pad = (n, l) => String(n).padStart(l || 2, '0');`,
117
+ ` const map = {`,
118
+ ` YYYY: String(d.getFullYear()),`,
119
+ ` MM: pad(d.getMonth() + 1),`,
120
+ ` DD: pad(d.getDate()),`,
121
+ ` HH: pad(d.getHours()),`,
122
+ ` mm: pad(d.getMinutes()),`,
123
+ ` ss: pad(d.getSeconds()),`,
124
+ ` };`,
125
+ ` return p.replace(/YYYY|MM|DD|HH|mm|ss/g, k => map[k]);`,
126
+ `}`,
127
+ `function __yamlStringify(v, indent) {`,
128
+ ` const pad = ' '.repeat(indent || 0);`,
129
+ ` if (v === null || v === undefined) return 'null';`,
130
+ ` if (typeof v === 'string') return '"' + String(v).replace(/\\\\/g, '\\\\\\\\').replace(/"/g, '\\\\"') + '"';`,
131
+ ` if (typeof v === 'number' || typeof v === 'boolean') return String(v);`,
132
+ ` if (Array.isArray(v)) {`,
133
+ ` const childPad = pad + ' ';`,
134
+ ` return v.map(x => {`,
135
+ ` if (typeof x === 'object' && x !== null && !Array.isArray(x)) {`,
136
+ ` const inner = __yamlStringify(x, indent + 2).split('\\n')[0];`,
137
+ ` return pad + '- ' + inner + __yamlStringify(x, indent + 4).split('\\n').slice(1).map(l => '\\n' + l).join('');`,
138
+ ` }`,
139
+ ` return pad + '- ' + __yamlStringify(x, indent + 2);`,
140
+ ` }).join('\\n');`,
141
+ ` }`,
142
+ ` if (typeof v === 'object') {`,
143
+ ` return Object.keys(v).map(k => {`,
144
+ ` const val = __yamlStringify(v[k], 0);`,
145
+ ` if (typeof v[k] === 'object' && v[k] !== null && !Array.isArray(v[k])) {`,
146
+ ` return pad + k + ':\\n' + __yamlStringify(v[k], indent + 2);`,
147
+ ` }`,
148
+ ` return pad + k + ': ' + val;`,
149
+ ` }).join('\\n');`,
150
+ ` }`,
151
+ ` return String(v);`,
152
+ `}`,
153
+ `function __yamlParse(text) {`,
154
+ ` const lines = String(text).split(/\\r?\\n/);`,
155
+ ` const root = {};`,
156
+ ` let seq = null;`,
157
+ ` let seqIndent = -1;`,
158
+ ` const stack = [{ indent: -1, node: root }];`,
159
+ ` for (const line0 of lines) {`,
160
+ ` const trimmed = line0.trim();`,
161
+ ` if (!trimmed || trimmed.startsWith('#')) continue;`,
162
+ ` const indent = line0.length - line0.trimStart().length;`,
163
+ ` const scalar = (s) => {`,
164
+ ` const t = s.trim();`,
165
+ ` if (t.length >= 2 && ((t[0] === '"' && t[t.length - 1] === '"') || (t[0] === "'" && t[t.length - 1] === "'"))) return t.slice(1, -1);`,
166
+ ` if (t === 'true') return true;`,
167
+ ` if (t === 'false') return false;`,
168
+ ` if (t === 'null' || t === '~') return null;`,
169
+ ` if (t !== '' && !isNaN(Number(t))) return Number(t);`,
170
+ ` return t;`,
171
+ ` };`,
172
+ ` const m = trimmed.match(/^([^:#]+):(.*)$/);`,
173
+ ` if (m) {`,
174
+ ` const key = m[1].replace(/^['"]|['"]$/g, '').trim();`,
175
+ ` const rest = m[2].trim();`,
176
+ ` while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();`,
177
+ ` const parent = stack[stack.length - 1].node;`,
178
+ ` if (rest === '' || rest === '|') { const node = {}; parent[key] = node; stack.push({ indent, node }); }`,
179
+ ` else if (rest === '[]') { parent[key] = []; }`,
180
+ ` else { parent[key] = scalar(rest); }`,
181
+ ` continue;`,
182
+ ` }`,
183
+ ` const lm = trimmed.match(/^-\\s*(.*)$/);`,
184
+ ` if (lm) {`,
185
+ ` while (seq && seqIndent >= indent) { seq = null; seqIndent = -1; }`,
186
+ ` while (!seq && stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();`,
187
+ ` const parent = stack[stack.length - 1].node;`,
188
+ ` if (lm[1] && lm[1].includes(':')) {`,
189
+ ` const km = lm[1].match(/^([^:]+):\\s*(.*)$/);`,
190
+ ` if (seq) {`,
191
+ ` const m2 = {}; seq[seq.length - 1] = typeof seq[seq.length - 1] === 'object' && seq[seq.length - 1] !== null ? seq[seq.length - 1] : m2;`,
192
+ ` const node = seq[seq.length - 1];`,
193
+ ` node[km[1].trim()] = km[2] ? scalar(km[2]) : {};`,
194
+ ` } else {`,
195
+ ` const node = {}; parent[km[1].trim()] = km[2] ? scalar(km[2]) : node; stack.push({ indent, node });`,
196
+ ` }`,
197
+ ` } else if (seq) {`,
198
+ ` seq.push(scalar(lm[1]));`,
199
+ ` } else if (Array.isArray(parent)) {`,
200
+ ` parent.push(scalar(lm[1])); seq = parent; seqIndent = indent;`,
201
+ ` } else {`,
202
+ ` const lastKey = Object.keys(parent)[Object.keys(parent).length - 1];`,
203
+ ` const arr = [];`,
204
+ ` if (lastKey != null) parent[lastKey] = arr; else parent.__rootArray = arr;`,
205
+ ` arr.push(scalar(lm[1]));`,
206
+ ` seq = arr; seqIndent = indent;`,
207
+ ` }`,
208
+ ` continue;`,
209
+ ` }`,
210
+ ` }`,
211
+ ` if (root.__rootArray) return root.__rootArray;`,
212
+ ` return root;`,
213
+ `}`,
214
+ `function __withTimeout(promise, ms) {`,
215
+ ` const timeout = ms == null ? 10000 : ms;`,
216
+ ` return new Promise((resolve, reject) => {`,
217
+ ` const timer = setTimeout(() => reject(new Error('Timed out after ' + timeout + 'ms.')), timeout);`,
218
+ ` Promise.resolve(promise).then(v => { clearTimeout(timer); resolve(v); }, e => { clearTimeout(timer); reject(e); });`,
219
+ ` });`,
220
+ `}`,
221
+ ].join('\n'),
222
+ // v1.0.0-latest — process execution (child processes).
223
+ process: [
224
+ `const { execFile } = require('child_process');`,
225
+ `function __runCommand(command, args) {`,
226
+ ` return new Promise((resolve) => {`,
227
+ ` execFile(command, args || [], { maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => {`,
228
+ ` resolve({ ok: !error, code: error ? (error.code == null ? -1 : error.code) : 0, stdout: String(stdout), stderr: String(stderr) });`,
229
+ ` });`,
230
+ ` });`,
231
+ `}`,
232
+ ].join('\n'),
233
+ // v1.0.0-latest — Map helpers.
234
+ mapset: [
235
+ `function __mapSet(map, key, value) { map.set(key, value); return map; }`,
236
+ ].join('\n'),
237
+ // v2.2.0 — collection primitives (flatten / pick / omit / groupBy).
238
+ coll: [
239
+ `function __flatten(list) {`,
240
+ ` const out = [];`,
241
+ ` (function rec(x) {`,
242
+ ` if (Array.isArray(x)) { for (const i of x) rec(i); }`,
243
+ ` else out.push(x);`,
244
+ ` })(list);`,
245
+ ` return out;`,
246
+ `}`,
247
+ `function __pick(obj) {`,
248
+ ` const out = {};`,
249
+ ` for (let i = 1; i < arguments.length; i++) {`,
250
+ ` const k = arguments[i];`,
251
+ ` if (obj != null && Object.prototype.hasOwnProperty.call(obj, k)) out[k] = obj[k];`,
252
+ ` }`,
253
+ ` return out;`,
254
+ `}`,
255
+ `function __omit(obj) {`,
256
+ ` const skip = new Set([].slice.call(arguments, 1));`,
257
+ ` const out = {};`,
258
+ ` if (obj != null) for (const k of Object.keys(obj)) if (!skip.has(k)) out[k] = obj[k];`,
259
+ ` return out;`,
260
+ `}`,
261
+ `function __groupBy(list, keyFn) {`,
262
+ ` const out = {};`,
263
+ ` for (const item of (list || [])) {`,
264
+ ` const k = typeof keyFn === 'function' ? keyFn(item) : (item == null ? undefined : item[keyFn]);`,
265
+ ` (out[k] = out[k] || []).push(item);`,
266
+ ` }`,
267
+ ` return out;`,
268
+ `}`,
269
+ `function __paginate(list, page, perPage) {`,
270
+ ` const items = (list || []);`,
271
+ ` const total = items.length;`,
272
+ ` perPage = Math.max(1, perPage == null ? 10 : Number(perPage));`,
273
+ ` const pages = Math.max(1, Math.ceil(total / perPage));`,
274
+ ` page = Math.min(Math.max(1, page == null ? 1 : Number(page)), pages);`,
275
+ ` const start = (page - 1) * perPage;`,
276
+ ` const slice = items.slice(start, start + perPage);`,
277
+ ` return { items: slice, count: total, page, pages, perPage, hasNext: page < pages, hasPrev: page > 1 };`,
278
+ `}`,
279
+ ].join('\n'),
280
+ // v1.0.0-latest — dynamic module loader.
281
+ loadmodule: [
282
+ `function __loadModule(spec) {`,
283
+ ` const path = require('path');`,
284
+ ` const target = (spec[0] === '.' ) ? path.resolve(process.cwd(), spec) : spec;`,
285
+ ` try { return require(target); }`,
286
+ ` catch (e) { if (spec[0] !== '.') return require(spec); throw e; }`,
287
+ `}`,
288
+ ].join('\n'),
289
+ // v1.0.0-latest — recursive directory walker (returns full paths, files first).
290
+ walk: [
291
+ `function __walkFolder(dir) {`,
292
+ ` const fs = require('fs');`,
293
+ ` const path = require('path');`,
294
+ ` const out = [];`,
295
+ ` function rec(d) {`,
296
+ ` for (const entry of fs.readdirSync(d)) {`,
297
+ ` const full = path.join(d, entry);`,
298
+ ` const st = fs.statSync(full);`,
299
+ ` if (st.isDirectory()) rec(full);`,
300
+ ` else out.push(full);`,
301
+ ` }`,
302
+ ` }`,
303
+ ` rec(dir);`,
304
+ ` return out;`,
305
+ `}`,
306
+ ].join('\n'),
69
307
  // v2.1.0 — request validation runtime. Returns the names of required
70
308
  // fields whose value is missing (undefined/null/empty string) in data.
71
309
  validation: [
@@ -120,11 +358,28 @@ const BUILTIN_DECLARATIONS = {
120
358
  // created by the "cache" statement; accessors fail with a teaching error
121
359
  // when no cache was configured.
122
360
  cache: [
123
- `let __cache = null;`,
361
+ `let __cache = null; // optional Redis client, set by the "cache" statement`,
362
+ `const __memCache = new Map(); // in-memory fallback cache: key -> { value, exp }`,
124
363
  `function __cacheClient() {`,
125
- ` if (!__cache) throw new Error('Cache: no cache configured. Add a cache "<redis-url>" statement first.');`,
126
364
  ` return __cache;`,
127
365
  `}`,
366
+ `async function __cacheGet(key) {`,
367
+ ` if (__cache) return __cache.get(key);`,
368
+ ` const entry = __memCache.get(key);`,
369
+ ` if (!entry) return null;`,
370
+ ` if (entry.exp != null && Date.now() > entry.exp) { __memCache.delete(key); return null; }`,
371
+ ` return entry.value;`,
372
+ `}`,
373
+ `async function __cacheSet(key, value, ttlSeconds) {`,
374
+ ` if (__cache) return __cache.set(key, value, ttlSeconds == null ? undefined : { EX: ttlSeconds });`,
375
+ ` const exp = ttlSeconds == null ? null : Date.now() + ttlSeconds * 1000;`,
376
+ ` __memCache.set(key, { value, exp });`,
377
+ ` return 'OK';`,
378
+ `}`,
379
+ `async function __cacheDelete(key) {`,
380
+ ` if (__cache) return __cache.del(key);`,
381
+ ` return __memCache.delete(key) ? 1 : 0;`,
382
+ `}`,
128
383
  ].join('\n'),
129
384
  // v2.1.1 — WhatsApp runtime (@whiskeysockets/baileys behind the
130
385
  // "whatsapp bot" block). Everything Baileys-shaped stays in here: socket
@@ -321,6 +576,53 @@ const BUILTIN_DECLARATIONS = {
321
576
  ` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
322
577
  `}`,
323
578
  ].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.
582
+ ai: [
583
+ `function __aiTags() {`,
584
+ ` return { key: process.env.OPENAI_API_KEY, base: (process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1').replace(/\\/$/, '') };`,
585
+ `}`,
586
+ `async function __aiPost(tags, path, body) {`,
587
+ ` if (typeof fetch !== 'function') {`,
588
+ ` throw new Error('AI calls need Node.js 18 or newer (global fetch is missing): ' + process.version);`,
589
+ ` }`,
590
+ ` if (!tags.key) throw new Error('No API key for AI. Set env OPENAI_API_KEY.');`,
591
+ ` const response = await fetch(tags.base + path, {`,
592
+ ` method: 'POST',`,
593
+ ` headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + tags.key },`,
594
+ ` body: JSON.stringify(body),`,
595
+ ` });`,
596
+ ` const text = await response.text();`,
597
+ ` let data = text;`,
598
+ ` try { data = JSON.parse(text); } catch (_) {}`,
599
+ ` if (!response.ok) throw new Error('AI request failed (' + response.status + '): ' + (data && data.error && data.error.message ? data.error.message : text));`,
600
+ ` return data;`,
601
+ `}`,
602
+ `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(/\\/$/, '');`,
606
+ ` if (typeof messages === 'string') messages = [{ role: 'user', content: messages }];`,
607
+ ` const data = await __aiPost(tags, '/chat/completions', { model: model, messages: messages });`,
608
+ ` const choice = data.choices && data.choices[0];`,
609
+ ` return choice && choice.message ? choice.message.content : '';`,
610
+ `}`,
611
+ `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) });`,
616
+ ` return (data.data && data.data[0] && data.data[0].embedding) || [];`,
617
+ `}`,
618
+ `function __aiSimilarity(a, b) {`,
619
+ ` if (!Array.isArray(a) || !Array.isArray(b) || !a.length || a.length !== b.length) return 0;`,
620
+ ` let dot = 0, na = 0, nb = 0;`,
621
+ ` for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }`,
622
+ ` if (na === 0 || nb === 0) return 0;`,
623
+ ` return dot / (Math.sqrt(na) * Math.sqrt(nb));`,
624
+ `}`,
625
+ ].join('\n'),
324
626
  // v2.1.1 — file upload runtime (multer behind "accept uploads"). Files are
325
627
  // held in memory by default or written to disk when a folder is given.
326
628
  // Normalised records expose: name, type, size, data (buffer) and path.
@@ -558,6 +860,16 @@ const BUILTIN_DECLARATIONS = {
558
860
  retry: [
559
861
  `const __retrySleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));`,
560
862
  ].join('\n'),
863
+ // IOPL-native — event emitter runtime.
864
+ __emitter: 'const __emitter = new (require("events").EventEmitter)();',
865
+ // IOPL-native — line-by-line file streaming runtime.
866
+ __streamFile: [
867
+ `async function __streamFile(path, fn) {`,
868
+ ` const fs = require('fs');`,
869
+ ` const rl = require('readline').createInterface({ input: fs.createReadStream(path), crlfDelay: Infinity });`,
870
+ ` for await (const line of rl) await fn(line);`,
871
+ `}`,
872
+ ].join('\n'),
561
873
  // v2.1.1 — SQLite runtime with a portable engine chain. Default order:
562
874
  // better-sqlite3 (native binding) first, sql.js (WebAssembly) as fallback.
563
875
  // Both engines are wrapped in the same tiny synchronous surface that PlainScript
@@ -837,6 +1149,18 @@ const STDLIB = {
837
1149
  param: (args, context) => routeAccessor('param', 'params', args, context),
838
1150
  query: (args, context) => routeAccessor('query', 'query', args, context),
839
1151
  header: (args, context) => routeAccessor('header', 'headers', args, context),
1152
+ // The parsed JSON request body (from `web app`'s express.json()). With no
1153
+ // argument returns the whole body record; with one, that field's value.
1154
+ body: (args, context) => {
1155
+ if (!_inRoute) {
1156
+ throw new Error(
1157
+ `"body(...)" can only be used inside a route handler.\n\nExample:\n route post "/items"\n show body("name")\n done`
1158
+ );
1159
+ }
1160
+ const base = 'req.body';
1161
+ if (!args || args.length === 0) return base;
1162
+ return `${base}[${generateExpr(args[0], context)}]`;
1163
+ },
840
1164
  // v2.1.0 — request validation. Returns the list of missing required fields.
841
1165
  validate: (args, context) => {
842
1166
  ensureBuiltin(context, 'validation');
@@ -892,12 +1216,74 @@ const STDLIB = {
892
1216
  hasKey: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
893
1217
  merge: (args, context) => `{ ...${generateExpr(args[0], context)}, ...${generateExpr(args[1], context)} }`,
894
1218
 
1219
+ // ── v2.2.0 — collection & string primitives (IOPL-native, dependency-free).
1220
+ // A numeric range [start..end], stepping by 1 (or `step` when given).
1221
+ range: (args, context) => {
1222
+ const start = generateExpr(args[0], context);
1223
+ const end = args.length > 1 ? generateExpr(args[1], context) : null;
1224
+ const step = args.length > 2 ? generateExpr(args[2], context) : null;
1225
+ if (end === null) return `Array.from({ length: Math.max(0, ${start}) }, (_, i) => i)`;
1226
+ const s = step === null ? `(${start} <= ${end} ? 1 : -1)` : `Math.abs(${step}) * (${start} <= ${end} ? 1 : -1)`;
1227
+ return `Array.from((() => { const __r = []; for (let __i = ${start}; ${start} <= ${end} ? __i < ${end} : __i > ${end}; __i += ${s}) __r.push(__i); return __r; })())`;
1228
+ },
1229
+ clamp: (args, context) => `Math.min(Math.max(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}), ${generateExpr(args[2], context)})`,
1230
+ first: (args, context) => `(${generateExpr(args[0], context)})[0]`,
1231
+ last: (args, context) => `(${generateExpr(args[0], context)})[(${generateExpr(args[0], context)}).length - 1]`,
1232
+ flatten: (args, context) => {
1233
+ ensureBuiltin(context, 'coll');
1234
+ return `__flatten(${generateExpr(args[0], context)})`;
1235
+ },
1236
+ includes: (args, context) => `(${generateExpr(args[0], context)}).includes(${generateExpr(args[1], context)})`,
1237
+ paginate: (args, context) => {
1238
+ ensureBuiltin(context, 'coll');
1239
+ return `__paginate(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, ${args.length > 2 ? generateExpr(args[2], context) : '10'})`;
1240
+ },
1241
+ pick: (args, context) => {
1242
+ ensureBuiltin(context, 'coll');
1243
+ return `__pick(${generateExpr(args[0], context)}, ${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`;
1244
+ },
1245
+ omit: (args, context) => {
1246
+ ensureBuiltin(context, 'coll');
1247
+ return `__omit(${generateExpr(args[0], context)}, ${args.slice(1).map(a => generateExpr(a, context)).join(', ')})`;
1248
+ },
1249
+ groupBy: (args, context) => {
1250
+ ensureBuiltin(context, 'coll');
1251
+ return `__groupBy(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1252
+ },
1253
+ startsWith: (args, context) => `String(${generateExpr(args[0], context)}).startsWith(String(${generateExpr(args[1], context)}))`,
1254
+ endsWith: (args, context) => `String(${generateExpr(args[0], context)}).endsWith(String(${generateExpr(args[1], context)}))`,
1255
+ truncate: (args, context) => {
1256
+ const text = `String(${generateExpr(args[0], context)})`;
1257
+ const n = generateExpr(args[1], context);
1258
+ const suffix = args.length > 2 ? generateExpr(args[2], context) : '"…"';
1259
+ return `(${text}.length <= ${n} ? ${text} : ${text}.slice(0, ${n}) + ${suffix})`;
1260
+ },
1261
+ padStart: (args, context) => `String(${generateExpr(args[0], context)}).padStart(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1262
+ padEnd: (args, context) => `String(${generateExpr(args[0], context)}).padEnd(${generateExpr(args[1], context)}, String(${args.length > 2 ? generateExpr(args[2], context) : '" "'}))`,
1263
+
1264
+ // ── v1.0.0-latest — nullable / regex / date helpers (IOPL-native).
1265
+ // first non-null, non-undefined argument — IOPL null-coalescing.
1266
+ coalesce: (args, context) =>
1267
+ `(() => { const __vals = [${args.map(a => generateExpr(a, context)).join(', ')}]; for (const __v of __vals) if (__v !== null && __v !== undefined) return __v; return undefined; })()`,
1268
+ // regex-aware replace (replace() is literal-only).
1269
+ regexReplace: (args, context) =>
1270
+ `String(${generateExpr(args[0], context)}).replace(new RegExp(${generateExpr(args[1], context)}, 'g'), ${args.length > 2 ? generateExpr(args[2], context) : '""'})`,
1271
+ // ISO/date-string → milliseconds since the Unix epoch (NaN on failure).
1272
+ parseDate: (args, context) => `Date.parse(String(${generateExpr(args[0], context)}))`,
1273
+ // milliseconds/Date → formatted text (YYYY-MM-DD HH:mm:ss by default).
1274
+ formatDate: (args, context) => {
1275
+ ensureBuiltin(context, 'core');
1276
+ const value = generateExpr(args[0], context);
1277
+ const pattern = args.length > 1 ? generateExpr(args[1], context) : '"YYYY-MM-DD HH:mm:ss"';
1278
+ return `__formatDate(${value}, ${pattern})`;
1279
+ },
1280
+
895
1281
  // ── v2.1.0 — cache (Redis) accessors. All async.
896
1282
 
897
1283
  cacheGet: (args, context) => {
898
1284
  ensureBuiltin(context, 'cache');
899
1285
  markAsync(context);
900
- return `await __cacheClient().get(String(${generateExpr(args[0], context)}))`;
1286
+ return `await __cacheGet(String(${generateExpr(args[0], context)}))`;
901
1287
  },
902
1288
  cacheSet: (args, context) => {
903
1289
  ensureBuiltin(context, 'cache');
@@ -905,14 +1291,14 @@ const STDLIB = {
905
1291
  const key = `String(${generateExpr(args[0], context)})`;
906
1292
  const value = `String(${generateExpr(args[1], context)})`;
907
1293
  if (args.length > 2) {
908
- return `await __cacheClient().set(${key}, ${value}, { EX: ${generateExpr(args[2], context)} })`;
1294
+ return `await __cacheSet(${key}, ${value}, ${generateExpr(args[2], context)})`;
909
1295
  }
910
- return `await __cacheClient().set(${key}, ${value})`;
1296
+ return `await __cacheSet(${key}, ${value})`;
911
1297
  },
912
1298
  cacheDelete: (args, context) => {
913
1299
  ensureBuiltin(context, 'cache');
914
1300
  markAsync(context);
915
- return `await __cacheClient().del(String(${generateExpr(args[0], context)}))`;
1301
+ return `await __cacheDelete(String(${generateExpr(args[0], context)}))`;
916
1302
  },
917
1303
 
918
1304
  // v2.1.0 — email sending helper (statement form uses this too).
@@ -964,6 +1350,154 @@ const STDLIB = {
964
1350
  ensureBuiltin(context, 'auth');
965
1351
  return `readToken(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
966
1352
  },
1353
+
1354
+ // ── v1.0.0-latest — capability-gap stdlib (reflection, binary, concurrency, ...) ──
1355
+
1356
+ // Reflection
1357
+ typeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__typeOf(${generateExpr(args[0], context)})`; },
1358
+ fieldsOf: (args, context) => `Object.keys(${generateExpr(args[0], context)})`,
1359
+ hasField: (args, context) => `Object.prototype.hasOwnProperty.call(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`,
1360
+ valueOf: (args, context) => {
1361
+ const [rec, key] = args.map(a => generateExpr(a, context));
1362
+ const fallback = args[2] != null ? generateExpr(args[2], context) : 'undefined';
1363
+ return `((__tmp) => (__tmp != null && Object.prototype.hasOwnProperty.call(__tmp, ${key})) ? __tmp[${key}] : ${fallback})(${rec})`;
1364
+ },
1365
+ sizeOf: (args, context) => { ensureBuiltin(context, 'core'); return `__sizeOf(${generateExpr(args[0], context)})`; },
1366
+
1367
+ // Binary
1368
+ base64Encode: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)})).toString('base64')`,
1369
+ base64Decode: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)}), 'base64').toString('utf8')`,
1370
+ textToBytes: (args, context) => `Buffer.from(String(${generateExpr(args[0], context)}), 'utf8')`,
1371
+ bytesToText: (args, context) => `Buffer.from(${generateExpr(args[0], context)}).toString('utf8')`,
1372
+ sha256: (args, context) => {
1373
+ ensureBuiltin(context, 'crypto');
1374
+ return `crypto.createHash('sha256').update(String(${generateExpr(args[0], context)})).digest('hex')`;
1375
+ },
1376
+ sha1: (args, context) => {
1377
+ ensureBuiltin(context, 'crypto');
1378
+ return `crypto.createHash('sha1').update(String(${generateExpr(args[0], context)})).digest('hex')`;
1379
+ },
1380
+ md5: (args, context) => {
1381
+ ensureBuiltin(context, 'crypto');
1382
+ return `crypto.createHash('md5').update(String(${generateExpr(args[0], context)})).digest('hex')`;
1383
+ },
1384
+
1385
+ // Serialization — minimal dependency-free YAML subset (see __yamlParse).
1386
+ yamlDecode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlParse(${generateExpr(args[0], context)})`; },
1387
+ yamlEncode: (args, context) => { ensureBuiltin(context, 'core'); return `__yamlStringify(${generateExpr(args[0], context)})`; },
1388
+
1389
+ // Configuration
1390
+ loadEnvFile: (_args, context) => {
1391
+ ensureBuiltin(context, 'dotenv');
1392
+ return `__loadEnvFile(${generateExpr(_args[0], context)})`;
1393
+ },
1394
+
1395
+ // CLI + process
1396
+ args: (_args) => `process.argv.slice(2)`,
1397
+ runCommand: (args, context) => {
1398
+ ensureBuiltin(context, 'process');
1399
+ markAsync(context);
1400
+ const bin = args[0] != null ? generateExpr(args[0], context) : 'undefined';
1401
+ const rest = args.slice(1).map(a => generateExpr(a, context));
1402
+ const call = `__runCommand(${bin}${rest.length ? ', [' + rest.join(', ') + ']' : ''})`;
1403
+ return `(await ${call})`;
1404
+ },
1405
+ withTimeout: (args, context) => {
1406
+ ensureBuiltin(context, 'core');
1407
+ markAsync(context);
1408
+ const ms = args[1] != null ? `, ${generateExpr(args[1], context)}` : '';
1409
+ return `(await __withTimeout(${generateExpr(args[0], context)}${ms}))`;
1410
+ },
1411
+
1412
+ // Generators / iterables
1413
+ spread: (args, context) => `[...${generateExpr(args[0], context)}]`,
1414
+
1415
+ // v1.0.0-latest — dynamic module loading (the runtime companion to `import "./x.ps"`).
1416
+ // Resolves relative to the bundler's CWD so `loadModule("./m")` behaves like
1417
+ // `require.resolve` from the program root.
1418
+ loadModule: (args, context) => {
1419
+ ensureBuiltin(context, 'loadmodule');
1420
+ return `__loadModule(${generateExpr(args[0], context)})`;
1421
+ },
1422
+
1423
+ // ── v2.2.0 — AI/ML. `chat`/`embedText` call an OpenAI-compatible endpoint
1424
+ // (key from OPENAI_API_KEY, base from OPENAI_BASE_URL); `similarity` runs
1425
+ // offline cosine similarity over any two equal-length numeric vectors.
1426
+ chat: (args, context) => {
1427
+ ensureBuiltin(context, 'ai');
1428
+ markAsync(context);
1429
+ const model = generateExpr(args[0], context);
1430
+ const messages = generateExpr(args[1], context);
1431
+ const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1432
+ return `await __aiChat(${model}, ${messages}, ${options})`;
1433
+ },
1434
+ embedText: (args, context) => {
1435
+ ensureBuiltin(context, 'ai');
1436
+ markAsync(context);
1437
+ const model = generateExpr(args[0], context);
1438
+ const text = generateExpr(args[1], context);
1439
+ const options = args.length > 2 && args[2] != null ? generateExpr(args[2], context) : 'undefined';
1440
+ return `await __aiEmbed(${model}, ${text}, ${options})`;
1441
+ },
1442
+ similarity: (args, context) => {
1443
+ ensureBuiltin(context, 'ai');
1444
+ return `__aiSimilarity(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)})`;
1445
+ },
1446
+
1447
+ // Map / Set
1448
+ keyMap: (_args) => `new Map()`,
1449
+ mapSet: (args, context) => { ensureBuiltin(context, 'mapset'); return `__mapSet(${args.map(a => generateExpr(a, context)).join(', ')})`; },
1450
+ mapGet: (args, context) => `(${generateExpr(args[0], context)}).get(${generateExpr(args[1], context)})`,
1451
+ mapHas: (args, context) => `(${generateExpr(args[0], context)}).has(${generateExpr(args[1], context)})`,
1452
+ mapDelete: (args, context) => `(${generateExpr(args[0], context)}).delete(${generateExpr(args[1], context)})`,
1453
+ newSet: (_args) => `new Set()`,
1454
+ addToSet: (args, context) => `(${generateExpr(args[0], context)}).add(${generateExpr(args[1], context)})`,
1455
+ removeFromSet: (args, context) => `(${generateExpr(args[0], context)}).delete(${generateExpr(args[1], context)})`,
1456
+ setHas: (args, context) => `(${generateExpr(args[0], context)}).has(${generateExpr(args[1], context)})`,
1457
+
1458
+ // Filesystem metadata, walking, and path helpers
1459
+ fileSize: (args, context) => {
1460
+ ensureBuiltin(context, 'fs');
1461
+ return `fs.statSync(${generateExpr(args[0], context)}).size`;
1462
+ },
1463
+ fileType: (args, context) => {
1464
+ ensureBuiltin(context, 'fs');
1465
+ return `fs.statSync(${generateExpr(args[0], context)}).isDirectory() ? 'directory' : 'file'`;
1466
+ },
1467
+ lastModified: (args, context) => {
1468
+ ensureBuiltin(context, 'fs');
1469
+ return `new Date(fs.statSync(${generateExpr(args[0], context)}).mtimeMs).toISOString()`;
1470
+ },
1471
+ walkFolder: (args, context) => {
1472
+ ensureBuiltin(context, 'walk');
1473
+ return `__walkFolder(${generateExpr(args[0], context)})`;
1474
+ },
1475
+ joinPath: (_args, context) => {
1476
+ ensureBuiltin(context, 'path');
1477
+ return `path.join(${_args.map(a => generateExpr(a, context)).join(', ')})`;
1478
+ },
1479
+ baseName: (_args, context) => {
1480
+ ensureBuiltin(context, 'path');
1481
+ return `path.basename(${generateExpr(_args[0], context)})`;
1482
+ },
1483
+ folderOf: (_args, context) => {
1484
+ ensureBuiltin(context, 'path');
1485
+ return `path.dirname(${generateExpr(_args[0], context)})`;
1486
+ },
1487
+ extensionOf: (_args, context) => {
1488
+ ensureBuiltin(context, 'path');
1489
+ return `path.extname(${generateExpr(_args[0], context)})`;
1490
+ },
1491
+
1492
+ // Streams
1493
+ writeLine: (args, context) => {
1494
+ ensureBuiltin(context, 'fs');
1495
+ return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
1496
+ },
1497
+ appendLine: (args, context) => {
1498
+ ensureBuiltin(context, 'fs');
1499
+ return `fs.appendFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)} + '\\n', 'utf8')`;
1500
+ },
967
1501
  };
968
1502
 
969
1503
  // Mark the enclosing program async when a call awaits at the top level.
@@ -1056,6 +1590,7 @@ function createGenerationContext() {
1056
1590
  pendingPrelude: [],
1057
1591
  needsAsync: false, // true when top-level code emits await (js blocks / ask)
1058
1592
  inFunction: false, // true while generating inside a function-like scope
1593
+ loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
1059
1594
  };
1060
1595
  }
1061
1596
 
@@ -1124,6 +1659,8 @@ function ensureBuiltin(context, moduleName) {
1124
1659
  const ASYNC_CALL_NAMES = new Set([
1125
1660
  // v2.1.0 — cache and email
1126
1661
  'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
1662
+ // v2.2.0 — AI/ML calls await their model endpoint
1663
+ 'chat', 'embedText',
1127
1664
  // v1.2 — Telegram helpers (await their API transport)
1128
1665
  'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
1129
1666
  ]);
@@ -1176,17 +1713,38 @@ function containsAsyncBlock(statements) {
1176
1713
  if (stmt.type === 'IfStatement') {
1177
1714
  if (containsAsyncBlock(stmt.consequent)) return true;
1178
1715
  if (stmt.alternate && containsAsyncBlock(stmt.alternate)) return true;
1179
- } else if (stmt.type !== 'FunctionDeclaration' && stmt.body) {
1716
+ } else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
1180
1717
  if (containsAsyncBlock(stmt.body)) return true;
1181
1718
  }
1182
1719
  }
1183
1720
  return false;
1184
1721
  }
1185
1722
 
1186
- function generate(ast, context = createGenerationContext()) {
1187
- if (ast.type !== 'Program') {
1723
+ // True when any statement in a block (recursively, skipping nested function
1724
+ // declarations) contains a `yield`, which marks the enclosing function as a
1725
+ // generator (function*).
1726
+ function containsYield(statements) {
1727
+ for (const stmt of statements || []) {
1728
+ if (stmt.type === 'YieldStatement') return true;
1729
+ if (stmt.type === 'IfStatement') {
1730
+ if (containsYield(stmt.consequent)) return true;
1731
+ if (stmt.alternate && containsYield(stmt.alternate)) return true;
1732
+ } else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
1733
+ if (containsYield(stmt.body)) return true;
1734
+ }
1735
+ }
1736
+ return false;
1737
+ }
1738
+
1739
+ function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
1188
1740
  throw new Error(`Expected a Program node but got "${ast.type}".`);
1189
1741
  }
1742
+ // v1.0.0-latest — reset per-program test bookkeeping so repeated generate() calls
1743
+ // (build pipeline) start clean.
1744
+ __testCount = 0;
1745
+ __testCatchers = [];
1746
+ __inTest = false;
1747
+
1190
1748
  const preludeStart = context.pendingPrelude.length;
1191
1749
  const body = ast.body.map(node => generateStatement(node, '', context)).filter(Boolean).join('\n');
1192
1750
  const lines = context.pendingPrelude.slice(preludeStart).concat(body).filter(Boolean);
@@ -1196,12 +1754,53 @@ function generate(ast, context = createGenerationContext()) {
1196
1754
  const exported = ast.body
1197
1755
  .filter(node => node.type === 'FunctionDeclaration')
1198
1756
  .map(node => node.name);
1199
- if (exported.length > 0) {
1757
+ const hasExplicitExport = ast.body.some(node => node.type === 'ExportStatement');
1758
+ // When the author uses explicit `export <name>`, they control the module
1759
+ // surface; skip the automatic function export so it does not clobber it.
1760
+ if (exported.length > 0 && !hasExplicitExport) {
1200
1761
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
1201
1762
  }
1763
+
1764
+ // v1.0.0-latest — native test runner. When any "test ... done" block exists, emit
1765
+ // the runner helper, register each test after its function declaration, and
1766
+ // execute them. Each failure prints a message and sets process.exitCode = 1.
1767
+ if (__testCatchers.length > 0) {
1768
+ const runner = [
1769
+ `const __tests = [];`,
1770
+ `function __check(op, a, b) {`,
1771
+ ` const ok = op === 'contains'`,
1772
+ ` ? String(a).includes(String(b))`,
1773
+ ` : op === 'is'`,
1774
+ ` ? a === b`,
1775
+ ` : op === 'raises'`,
1776
+ ` ? (() => { try { a(); } catch (e) { return String(e && e.message || '').includes(String(b)); } return false; })()`,
1777
+ ` : a === b;`,
1778
+ ` if (!ok) throw new Error('check failed: ' + op + ' ' + JSON.stringify(a) + ' vs ' + JSON.stringify(b));`,
1779
+ `}`,
1780
+ `function __runTests() {`,
1781
+ ` let __passed = 0; let __failed = 0;`,
1782
+ ` for (const __t of __tests) {`,
1783
+ ` try { __t.fn(); console.log('PASS ' + __t.name); __passed++; }`,
1784
+ ` catch (__e) { console.error('FAIL ' + __t.name + '\\n ' + (__e && __e.message)); __failed++; process.exitCode = 1; }`,
1785
+ ` }`,
1786
+ ` console.log(__passed + ' passed, ' + __failed + ' failed');`,
1787
+ `}`,
1788
+ ].join('\n');
1789
+ lines.unshift(runner);
1790
+ for (const t of __testCatchers) {
1791
+ lines.push(`__tests.push({ name: ${JSON.stringify(t.name)}, fn: ${t.fnName} });`);
1792
+ }
1793
+ lines.push(`__runTests();`);
1794
+ }
1795
+
1202
1796
  return lines.join('\n');
1203
1797
  }
1204
1798
 
1799
+ // ── v1.0.0-latest — test DSL bookkeeping ───────────────────────────────────────────
1800
+ let __testCount = 0;
1801
+ let __testCatchers = [];
1802
+ let __inTest = false;
1803
+
1205
1804
  // ── Condition generation ────────────────────────────────────────────────────
1206
1805
 
1207
1806
  function generateCondition(cond, context) {
@@ -1250,6 +1849,78 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1250
1849
  case 'BecomeStatement':
1251
1850
  return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
1252
1851
 
1852
+ // v1.0.0-latest — record kinds: `define a kind called "Person" with ... done`.
1853
+ // Names are emitted as a JS factory that returns a fresh plain object with
1854
+ // declared defaults. Constructors prompt for required fields at compile
1855
+ // time via `create a Person with ...` (see GenerateExpr CreateKind).
1856
+ case 'DefineKindStatement': {
1857
+ const members = node.fields.map(f =>
1858
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
1859
+ );
1860
+ const defaults = `{ ${members.join(', ')} }`;
1861
+ return [
1862
+ `${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
1863
+ `${indent} const __rec = ${defaults};`,
1864
+ `${indent} if (${node.name}Fields != null) {`,
1865
+ `${indent} for (const __k in ${node.name}Fields) {`,
1866
+ `${indent} if (!(Object.prototype.hasOwnProperty.call(__rec, __k))) throw new Error(${JSON.stringify('"' + node.name + '" has no field named "')} + __k + ${JSON.stringify('".')});`,
1867
+ `${indent} __rec[__k] = ${node.name}Fields[__k];`,
1868
+ `${indent} }`,
1869
+ `${indent} }`,
1870
+ `${indent} return __rec;`,
1871
+ `${indent}}`,
1872
+ `${indent}const ${node.name} = __makeKind_${node.name};`,
1873
+ ].join('\n');
1874
+ }
1875
+
1876
+ // v1.0.0-latest — load env file "<path>": apply KEY=VALUE pairs to process.env.
1877
+ // Blank lines and `#` comments are skipped; values keep their text.
1878
+ case 'LoadEnvFileStatement': {
1879
+ ensureBuiltin(context, 'dotenv');
1880
+ return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
1881
+ }
1882
+
1883
+ // v1.0.0-latest — native test DSL. `test "<name>" ... done` registers a runnable
1884
+ // unit; all tests are executed after the program body with a tiny runner.
1885
+ case 'TestStatement': {
1886
+ __testCount++;
1887
+ const fnName = `__testFn_${__testCount}`;
1888
+ const prevInTest = __inTest;
1889
+ __inTest = true;
1890
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1891
+ __inTest = prevInTest;
1892
+ __testCatchers.push({ name: node.name, fnName });
1893
+ return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
1894
+ }
1895
+
1896
+ // v1.0.0-latest — assertion `check <a> (equals|is|contains|raises) <b>`.
1897
+ // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
1898
+ // inside the runner's try/catch (its thrown error is the subject).
1899
+ case 'CheckStatement': {
1900
+ if (!__inTest) {
1901
+ throw new Error('"check" can only be used inside a "test ... done" block.\n\nExample:\n test "addition"\n check 2 + 2 equals 4\n done');
1902
+ }
1903
+ const a = node.op === 'raises'
1904
+ ? `(() => (${generateExpr(node.a, context)}))`
1905
+ : generateExpr(node.a, context);
1906
+ const b = generateExpr(node.b, context);
1907
+ return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
1908
+ }
1909
+
1910
+ // v1.0.0-latest — export <name>: mark a top-level symbol for module.exports.
1911
+ case 'ExportStatement':
1912
+ return `${indent}module.exports.${node.name} = ${node.name};`;
1913
+
1914
+ // v1.0.0-latest — generators: `yield <expr>` (or bare `yield`).
1915
+ case 'YieldStatement': {
1916
+ if (!context.inFunction) {
1917
+ 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');
1918
+ }
1919
+ return node.value != null
1920
+ ? `${indent}yield ${generateExpr(node.value, context)};`
1921
+ : `${indent}yield;`;
1922
+ }
1923
+
1253
1924
  case 'ExpressionStatement':
1254
1925
  return `${indent}${generateExpr(node.expression, context)};`;
1255
1926
 
@@ -1321,12 +1992,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1321
1992
 
1322
1993
  case 'FunctionDeclaration': {
1323
1994
  const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1324
- const params = node.params.join(', ');
1995
+ const isGen = containsYield(node.body) ? '*' : '';
1996
+ const paramStr = node.params.map(p => {
1997
+ if (typeof p === 'object') {
1998
+ if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
1999
+ return p.name;
2000
+ }
2001
+ return p;
2002
+ }).join(', ');
1325
2003
  const prevInFunction = context.inFunction;
1326
2004
  context.inFunction = true;
1327
2005
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1328
2006
  context.inFunction = prevInFunction;
1329
- return `${indent}${isAsync}function ${node.name}(${params}) {\n${body}\n${indent}}`;
2007
+ return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${body}\n${indent}}`;
1330
2008
  }
1331
2009
 
1332
2010
  case 'IfStatement': {
@@ -1341,16 +2019,58 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1341
2019
  }
1342
2020
 
1343
2021
  case 'ForEachStatement': {
2022
+ context.loopDepth++;
1344
2023
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2024
+ context.loopDepth--;
1345
2025
  return `${indent}for (const ${node.item} of ${generateExpr(node.collection, context)}) {\n${body}\n${indent}}`;
1346
2026
  }
1347
2027
 
2028
+ case 'ForIndexStatement': {
2029
+ context.loopDepth++;
2030
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2031
+ context.loopDepth--;
2032
+ // for index <name> in <collection> — zero-based index over a list.
2033
+ if (node.over != null) {
2034
+ const coll = generateExpr(node.over, context);
2035
+ return `${indent}for (let ${node.name} = 0; ${node.name} < ${coll}.length; ${node.name}++) {\n${body}\n${indent}}`;
2036
+ }
2037
+ const start = generateExpr(node.start, context);
2038
+ const end = generateExpr(node.end, context);
2039
+ // Explicit step uses the user's sign; otherwise the increment follows
2040
+ // the direction of the bounds (from 5 to 1 counts down automatically).
2041
+ const inc = node.step ? generateExpr(node.step, context)
2042
+ : `(${start} <= ${end} ? 1 : -1)`;
2043
+ // Direction-aware: "from 5 to 1" counts down even without an explicit
2044
+ // "by", while "from 1 to 5" counts up.
2045
+ const test = `(${start} <= ${end} ? ${node.name} <= ${end} : ${node.name} >= ${end})`;
2046
+ return `${indent}for (let ${node.name} = ${start}; ${test}; ${node.name} += ${inc}) {\n${body}\n${indent}}`;
2047
+ }
2048
+
1348
2049
  case 'WhileStatement': {
1349
2050
  const condition = generateCondition(node.condition, context);
1350
- const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2051
+ context.loopDepth++;
2052
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2053
+ context.loopDepth--;
1351
2054
  return `${indent}while (${condition}) {\n${body}\n${indent}}`;
1352
2055
  }
1353
2056
 
2057
+ case 'BreakStatement': {
2058
+ if (context.loopDepth <= 0) {
2059
+ 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');
2060
+ }
2061
+ return `${indent}break;`;
2062
+ }
2063
+
2064
+ case 'ContinueStatement': {
2065
+ if (context.loopDepth <= 0) {
2066
+ 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');
2067
+ }
2068
+ return `${indent}continue;`;
2069
+ }
2070
+
2071
+ case 'ThrowStatement':
2072
+ return `${indent}throw ${generateExpr(node.value, context)};`;
2073
+
1354
2074
  // v0.3 — Express runtime
1355
2075
 
1356
2076
  case 'ListenStatement': {
@@ -1442,6 +2162,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1442
2162
  }
1443
2163
  return `${indent}res.status(${generateExpr(node.value, context)});`;
1444
2164
 
2165
+ // v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route.
2166
+ case 'RedirectStatement':
2167
+ if (!_inRoute) {
2168
+ throw new Error('"redirect to" can only be used inside a route handler.\n\nExample:\n route get "/old"\n redirect to "/new"\n done');
2169
+ }
2170
+ return `${indent}res.redirect(${generateExpr(node.url, context)});`;
2171
+
1445
2172
  // v2.1.0 — allow cors: enables cross-origin requests on the current app.
1446
2173
  // Applies to routes registered after this statement.
1447
2174
  case 'AllowCorsStatement':
@@ -1550,16 +2277,46 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1550
2277
  // ── v2.1.1 — error handling and retries
1551
2278
 
1552
2279
  case 'TryStatement': {
1553
- const tryBody = node.tryBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1554
- let out = `${indent}try {\n${tryBody}\n${indent}}`;
2280
+ const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2281
+ const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
2282
+ if (node.catches && node.catches.length > 0) {
2283
+ const lines = [tryBlock];
2284
+ for (let i = 0; i < node.catches.length; i++) {
2285
+ const c = node.catches[i];
2286
+ const errorName = c.name || c.param || '__plainError';
2287
+ const catchBody = c.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2288
+ const isFirst = i === 0;
2289
+ const isLast = i === node.catches.length - 1;
2290
+ if (isFirst) {
2291
+ lines.push(`${indent}} catch (${errorName}) {`);
2292
+ }
2293
+ if (c.errorType) {
2294
+ const cond = isFirst ? 'if' : 'else if';
2295
+ lines.push(`${indent} ${cond} (${errorName} instanceof ${c.errorType}) {`);
2296
+ lines.push(catchBody);
2297
+ lines.push(`${indent} }`);
2298
+ if (isLast) lines.push(`${indent}}`);
2299
+ } else {
2300
+ if (isFirst && isLast) {
2301
+ lines.push(catchBody);
2302
+ lines.push(`${indent}}`);
2303
+ } else {
2304
+ lines.push(`${indent} else {`);
2305
+ lines.push(catchBody);
2306
+ lines.push(`${indent} }`);
2307
+ if (isLast) lines.push(`${indent}}`);
2308
+ }
2309
+ }
2310
+ }
2311
+ return lines.join('\n');
2312
+ }
2313
+ let out = tryBlock;
1555
2314
  if (node.recoverBody) {
1556
2315
  const errorName = node.catchName || '__plainError';
1557
2316
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1558
2317
  out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
1559
2318
  } else {
1560
- // A bare try {} is invalid JavaScript: without "recover", errors are
1561
- // swallowed through an empty catch block.
1562
- out += ' catch (__plainError) {}';
2319
+ out += `${indent}} catch (__plainError) {}`;
1563
2320
  }
1564
2321
  return out;
1565
2322
  }
@@ -1834,7 +2591,7 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1834
2591
 
1835
2592
  case 'RunBackgroundStatement':
1836
2593
  return [
1837
- `${indent}setImmediate(() => {`,
2594
+ `${indent}setImmediate(async () => {`,
1838
2595
  `${indent} try {`,
1839
2596
  `${indent} Promise.resolve(${generateExpr(node.call, context)}).catch((error) => console.error(error));`,
1840
2597
  `${indent} } catch (error) { console.error(error); }`,
@@ -1865,6 +2622,79 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1865
2622
  ensureBuiltin(context, 'websocket');
1866
2623
  return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
1867
2624
 
2625
+ // ── IOPL-native features ──────────────────────────────────────────────
2626
+
2627
+ case 'GatherStatement': {
2628
+ const coll = generateExpr(node.collection, context);
2629
+ const body = generateExpr(node.body, context);
2630
+ return `${indent}${coll} = ${coll}.map(${node.item} => ${body});`;
2631
+ }
2632
+
2633
+ case 'FilterStatement': {
2634
+ const coll = generateExpr(node.collection, context);
2635
+ const cond = generateCondition(node.condition, context);
2636
+ return `${indent}${coll} = ${coll}.filter(${node.item} => ${cond});`;
2637
+ }
2638
+
2639
+ case 'TotalStatement': {
2640
+ const coll = generateExpr(node.collection, context);
2641
+ const body = generateExpr(node.body, context);
2642
+ return `${indent}${coll} = ${coll}.reduce((__sum, ${node.item}) => __sum + ${body}, 0);`;
2643
+ }
2644
+
2645
+ case 'MatchStatement': {
2646
+ const value = generateExpr(node.value, context);
2647
+ const lines = [`${indent}switch (${value}) {`];
2648
+ for (const c of node.cases) {
2649
+ const testVal = generateExpr(c.test, context);
2650
+ lines.push(`${indent} case ${testVal}:`);
2651
+ for (const s of c.body) lines.push(generateStatement(s, indent + ' ', context));
2652
+ lines.push(`${indent} break;`);
2653
+ }
2654
+ if (node.defaultCase) {
2655
+ lines.push(`${indent} default:`);
2656
+ for (const s of node.defaultCase) lines.push(generateStatement(s, indent + ' ', context));
2657
+ lines.push(`${indent} break;`);
2658
+ }
2659
+ lines.push(`${indent}}`);
2660
+ return lines.join('\n');
2661
+ }
2662
+
2663
+ case 'RegexMatchStatement': {
2664
+ const source = generateExpr(node.source, context);
2665
+ const pattern = typeof node.pattern === 'string' ? JSON.stringify(node.pattern) : generateExpr(node.pattern, context);
2666
+ return `${indent}const ${node.name} = ${source}.match(new RegExp(${pattern}));`;
2667
+ }
2668
+
2669
+ case 'EmitStatement': {
2670
+ ensureBuiltin(context, '__emitter');
2671
+ const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
2672
+ const data = node.data ? generateExpr(node.data, context) : '';
2673
+ return `${indent}__emitter.emit(${event}${data ? ', ' + data : ''});`;
2674
+ }
2675
+
2676
+ case 'WhenHappensStatement': {
2677
+ ensureBuiltin(context, '__emitter');
2678
+ const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
2679
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2680
+ return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
2681
+ }
2682
+
2683
+ case 'StreamStatement': {
2684
+ ensureBuiltin(context, '__streamFile');
2685
+ markAsync(context);
2686
+ const filename = generateExpr(node.filename, context);
2687
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2688
+ return `${indent}await __streamFile(${filename}, async (${node.paramName}) => {\n${body}\n${indent}});`;
2689
+ }
2690
+
2691
+ case 'RunParallelStatement': {
2692
+ markAsync(context);
2693
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2694
+ const resultName = node.resultName || '__parallelResults';
2695
+ return `${indent}const ${resultName} = await Promise.all([(async () => {\n${body}\n${indent}})()]);`;
2696
+ }
2697
+
1868
2698
  default:
1869
2699
  throw new Error(`Unknown statement type "${node.type}".`);
1870
2700
  }
@@ -1968,6 +2798,12 @@ function generateExpr(node, context = createGenerationContext()) {
1968
2798
  return `${generateExpr(node.object, context)}.${node.property}`;
1969
2799
 
1970
2800
  case 'CallExpression': {
2801
+ // Method call: receiver.method(args). Member access invoked with parens —
2802
+ // e.g. path.join("a", "b"), mrz.parse(line), fs.existsSync(("x")).
2803
+ if (node.callee) {
2804
+ const args = node.args.map(arg => generateExpr(arg, context)).join(', ');
2805
+ return `${generateExpr(node.callee, context)}(${args})`;
2806
+ }
1971
2807
  if (STDLIB[node.name]) {
1972
2808
  if (node.name === 'readFile' || node.name === 'writeFile' ||
1973
2809
  node.name === 'fileExists' || node.name === 'read') {
@@ -2024,6 +2860,29 @@ function generateExpr(node, context = createGenerationContext()) {
2024
2860
  ensureBuiltin(context, 'fs');
2025
2861
  return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
2026
2862
 
2863
+ // v1.0.0-latest — record constructor: `create a Person with name "Ada" and age 17`
2864
+ // calls the kind factory that `define a kind called "Person"` registered.
2865
+ case 'CreateKindExpression': {
2866
+ const fields = node.pairs
2867
+ .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
2868
+ .join(', ');
2869
+ return `${node.kind}({ ${fields} })`;
2870
+ }
2871
+
2872
+ // v1.0.0-latest — concurrency combinators: `all of [...]` / `any of [...]` /
2873
+ // `settled of [...]`. All are awaited; `settled` returns status records.
2874
+ case 'ConcurrencyExpression': {
2875
+ markAsync(context);
2876
+ const rhs = generateExpr(node.items, context);
2877
+ if (node.combo === 'any') return `(await Promise.race(${rhs}))`;
2878
+ if (node.combo === 'settled') return `(await Promise.allSettled(${rhs}))`;
2879
+ return `(await Promise.all(${rhs}))`;
2880
+ }
2881
+
2882
+ // v1.0.0-latest — `spread of <collection>` → a fresh array from an iterable.
2883
+ case 'SpreadExpression':
2884
+ return `[...${generateExpr(node.collection, context)}]`;
2885
+
2027
2886
  default:
2028
2887
  throw new Error(`Unknown expression type "${node.type}".`);
2029
2888
  }