plainscript-lang 0.1.7 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +97 -39
  2. package/compiler/bundler.js +1 -1
  3. package/compiler/cli.js +44 -42
  4. package/compiler/generator.js +826 -16
  5. package/compiler/lexer.js +31 -2
  6. package/compiler/parser.js +548 -22
  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 +535 -2205
  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 — 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 — 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 — 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 — 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 — 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 — 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 — 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 — 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 — 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.
@@ -1124,6 +1658,8 @@ function ensureBuiltin(context, moduleName) {
1124
1658
  const ASYNC_CALL_NAMES = new Set([
1125
1659
  // v2.1.0 — cache and email
1126
1660
  'cacheGet', 'cacheSet', 'cacheDelete', 'sendMail',
1661
+ // v2.2.0 — AI/ML calls await their model endpoint
1662
+ 'chat', 'embedText',
1127
1663
  // v1.2 — Telegram helpers (await their API transport)
1128
1664
  'bot', 'sendMessage', 'sendPhoto', 'editMessage', 'getChat', 'getMyChats',
1129
1665
  ]);
@@ -1183,10 +1719,31 @@ function containsAsyncBlock(statements) {
1183
1719
  return false;
1184
1720
  }
1185
1721
 
1186
- function generate(ast, context = createGenerationContext()) {
1187
- if (ast.type !== 'Program') {
1722
+ // True when any statement in a block (recursively, skipping nested function
1723
+ // declarations) contains a `yield`, which marks the enclosing function as a
1724
+ // generator (function*).
1725
+ function containsYield(statements) {
1726
+ for (const stmt of statements || []) {
1727
+ if (stmt.type === 'YieldStatement') return true;
1728
+ if (stmt.type === 'IfStatement') {
1729
+ if (containsYield(stmt.consequent)) return true;
1730
+ if (stmt.alternate && containsYield(stmt.alternate)) return true;
1731
+ } else if (stmt.type !== 'FunctionDeclaration' && stmt.body && Array.isArray(stmt.body)) {
1732
+ if (containsYield(stmt.body)) return true;
1733
+ }
1734
+ }
1735
+ return false;
1736
+ }
1737
+
1738
+ function generate(ast, context = createGenerationContext()) { if (ast.type !== 'Program') {
1188
1739
  throw new Error(`Expected a Program node but got "${ast.type}".`);
1189
1740
  }
1741
+ // v1.0.0 — reset per-program test bookkeeping so repeated generate() calls
1742
+ // (build pipeline) start clean.
1743
+ __testCount = 0;
1744
+ __testCatchers = [];
1745
+ __inTest = false;
1746
+
1190
1747
  const preludeStart = context.pendingPrelude.length;
1191
1748
  const body = ast.body.map(node => generateStatement(node, '', context)).filter(Boolean).join('\n');
1192
1749
  const lines = context.pendingPrelude.slice(preludeStart).concat(body).filter(Boolean);
@@ -1196,12 +1753,53 @@ function generate(ast, context = createGenerationContext()) {
1196
1753
  const exported = ast.body
1197
1754
  .filter(node => node.type === 'FunctionDeclaration')
1198
1755
  .map(node => node.name);
1199
- if (exported.length > 0) {
1756
+ const hasExplicitExport = ast.body.some(node => node.type === 'ExportStatement');
1757
+ // When the author uses explicit `export <name>`, they control the module
1758
+ // surface; skip the automatic function export so it does not clobber it.
1759
+ if (exported.length > 0 && !hasExplicitExport) {
1200
1760
  lines.push(`if (typeof module !== 'undefined') { module.exports = { ${exported.join(', ')} }; }`);
1201
1761
  }
1762
+
1763
+ // v1.0.0 — native test runner. When any "test ... done" block exists, emit
1764
+ // the runner helper, register each test after its function declaration, and
1765
+ // execute them. Each failure prints a message and sets process.exitCode = 1.
1766
+ if (__testCatchers.length > 0) {
1767
+ const runner = [
1768
+ `const __tests = [];`,
1769
+ `function __check(op, a, b) {`,
1770
+ ` const ok = op === 'contains'`,
1771
+ ` ? String(a).includes(String(b))`,
1772
+ ` : op === 'is'`,
1773
+ ` ? a === b`,
1774
+ ` : op === 'raises'`,
1775
+ ` ? (() => { try { a(); } catch (e) { return String(e && e.message || '').includes(String(b)); } return false; })()`,
1776
+ ` : a === b;`,
1777
+ ` if (!ok) throw new Error('check failed: ' + op + ' ' + JSON.stringify(a) + ' vs ' + JSON.stringify(b));`,
1778
+ `}`,
1779
+ `function __runTests() {`,
1780
+ ` let __passed = 0; let __failed = 0;`,
1781
+ ` for (const __t of __tests) {`,
1782
+ ` try { __t.fn(); console.log('PASS ' + __t.name); __passed++; }`,
1783
+ ` catch (__e) { console.error('FAIL ' + __t.name + '\\n ' + (__e && __e.message)); __failed++; process.exitCode = 1; }`,
1784
+ ` }`,
1785
+ ` console.log(__passed + ' passed, ' + __failed + ' failed');`,
1786
+ `}`,
1787
+ ].join('\n');
1788
+ lines.unshift(runner);
1789
+ for (const t of __testCatchers) {
1790
+ lines.push(`__tests.push({ name: ${JSON.stringify(t.name)}, fn: ${t.fnName} });`);
1791
+ }
1792
+ lines.push(`__runTests();`);
1793
+ }
1794
+
1202
1795
  return lines.join('\n');
1203
1796
  }
1204
1797
 
1798
+ // ── v1.0.0 — test DSL bookkeeping ───────────────────────────────────────────
1799
+ let __testCount = 0;
1800
+ let __testCatchers = [];
1801
+ let __inTest = false;
1802
+
1205
1803
  // ── Condition generation ────────────────────────────────────────────────────
1206
1804
 
1207
1805
  function generateCondition(cond, context) {
@@ -1250,6 +1848,78 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1250
1848
  case 'BecomeStatement':
1251
1849
  return `${indent}${generateLValue(node.target, context)} = ${generateExpr(node.value, context)};`;
1252
1850
 
1851
+ // v1.0.0 — record kinds: `define a kind called "Person" with ... done`.
1852
+ // Names are emitted as a JS factory that returns a fresh plain object with
1853
+ // declared defaults. Constructors prompt for required fields at compile
1854
+ // time via `create a Person with ...` (see GenerateExpr CreateKind).
1855
+ case 'DefineKindStatement': {
1856
+ const members = node.fields.map(f =>
1857
+ `${JSON.stringify(f.key)}: ${f.value ? generateExpr(f.value, context) : 'undefined'}`
1858
+ );
1859
+ const defaults = `{ ${members.join(', ')} }`;
1860
+ return [
1861
+ `${indent}function __makeKind_${node.name}(${node.name}Fields) {`,
1862
+ `${indent} const __rec = ${defaults};`,
1863
+ `${indent} if (${node.name}Fields != null) {`,
1864
+ `${indent} for (const __k in ${node.name}Fields) {`,
1865
+ `${indent} if (!(Object.prototype.hasOwnProperty.call(__rec, __k))) throw new Error(${JSON.stringify('"' + node.name + '" has no field named "')} + __k + ${JSON.stringify('".')});`,
1866
+ `${indent} __rec[__k] = ${node.name}Fields[__k];`,
1867
+ `${indent} }`,
1868
+ `${indent} }`,
1869
+ `${indent} return __rec;`,
1870
+ `${indent}}`,
1871
+ `${indent}const ${node.name} = __makeKind_${node.name};`,
1872
+ ].join('\n');
1873
+ }
1874
+
1875
+ // v1.0.0 — load env file "<path>": apply KEY=VALUE pairs to process.env.
1876
+ // Blank lines and `#` comments are skipped; values keep their text.
1877
+ case 'LoadEnvFileStatement': {
1878
+ ensureBuiltin(context, 'dotenv');
1879
+ return `${indent}__loadEnvFile(${JSON.stringify(node.path)});`;
1880
+ }
1881
+
1882
+ // v1.0.0 — native test DSL. `test "<name>" ... done` registers a runnable
1883
+ // unit; all tests are executed after the program body with a tiny runner.
1884
+ case 'TestStatement': {
1885
+ __testCount++;
1886
+ const fnName = `__testFn_${__testCount}`;
1887
+ const prevInTest = __inTest;
1888
+ __inTest = true;
1889
+ const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1890
+ __inTest = prevInTest;
1891
+ __testCatchers.push({ name: node.name, fnName });
1892
+ return `${indent}function ${fnName}() {\n${body}\n${indent}}`;
1893
+ }
1894
+
1895
+ // v1.0.0 — assertion `check <a> (equals|is|contains|raises) <b>`.
1896
+ // For `raises`, `a` is wrapped in a thunk so the expression is evaluated
1897
+ // inside the runner's try/catch (its thrown error is the subject).
1898
+ case 'CheckStatement': {
1899
+ if (!__inTest) {
1900
+ 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');
1901
+ }
1902
+ const a = node.op === 'raises'
1903
+ ? `(() => (${generateExpr(node.a, context)}))`
1904
+ : generateExpr(node.a, context);
1905
+ const b = generateExpr(node.b, context);
1906
+ return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
1907
+ }
1908
+
1909
+ // v1.0.0 — export <name>: mark a top-level symbol for module.exports.
1910
+ case 'ExportStatement':
1911
+ return `${indent}module.exports.${node.name} = ${node.name};`;
1912
+
1913
+ // v1.0.0 — generators: `yield <expr>` (or bare `yield`).
1914
+ case 'YieldStatement': {
1915
+ if (!context.inFunction) {
1916
+ 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');
1917
+ }
1918
+ return node.value != null
1919
+ ? `${indent}yield ${generateExpr(node.value, context)};`
1920
+ : `${indent}yield;`;
1921
+ }
1922
+
1253
1923
  case 'ExpressionStatement':
1254
1924
  return `${indent}${generateExpr(node.expression, context)};`;
1255
1925
 
@@ -1321,12 +1991,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1321
1991
 
1322
1992
  case 'FunctionDeclaration': {
1323
1993
  const isAsync = containsAsyncBlock(node.body) ? 'async ' : '';
1324
- const params = node.params.join(', ');
1994
+ const isGen = containsYield(node.body) ? '*' : '';
1995
+ const paramStr = node.params.map(p => {
1996
+ if (typeof p === 'object') {
1997
+ if (p.defaultValue) return `${p.name} = ${generateExpr(p.defaultValue, context)}`;
1998
+ return p.name;
1999
+ }
2000
+ return p;
2001
+ }).join(', ');
1325
2002
  const prevInFunction = context.inFunction;
1326
2003
  context.inFunction = true;
1327
2004
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1328
2005
  context.inFunction = prevInFunction;
1329
- return `${indent}${isAsync}function ${node.name}(${params}) {\n${body}\n${indent}}`;
2006
+ return `${indent}${isAsync}function${isGen} ${node.name}(${paramStr}) {\n${body}\n${indent}}`;
1330
2007
  }
1331
2008
 
1332
2009
  case 'IfStatement': {
@@ -1442,6 +2119,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1442
2119
  }
1443
2120
  return `${indent}res.status(${generateExpr(node.value, context)});`;
1444
2121
 
2122
+ // v2.2.0 — redirect to "<url>": sends an HTTP redirect from a route.
2123
+ case 'RedirectStatement':
2124
+ if (!_inRoute) {
2125
+ 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');
2126
+ }
2127
+ return `${indent}res.redirect(${generateExpr(node.url, context)});`;
2128
+
1445
2129
  // v2.1.0 — allow cors: enables cross-origin requests on the current app.
1446
2130
  // Applies to routes registered after this statement.
1447
2131
  case 'AllowCorsStatement':
@@ -1550,16 +2234,46 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1550
2234
  // ── v2.1.1 — error handling and retries
1551
2235
 
1552
2236
  case 'TryStatement': {
1553
- const tryBody = node.tryBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1554
- let out = `${indent}try {\n${tryBody}\n${indent}}`;
2237
+ const tryBody = (node.tryBody || node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2238
+ const tryBlock = `${indent}try {\n${tryBody}\n${indent}`;
2239
+ if (node.catches && node.catches.length > 0) {
2240
+ const lines = [tryBlock];
2241
+ for (let i = 0; i < node.catches.length; i++) {
2242
+ const c = node.catches[i];
2243
+ const errorName = c.name || c.param || '__plainError';
2244
+ const catchBody = c.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
2245
+ const isFirst = i === 0;
2246
+ const isLast = i === node.catches.length - 1;
2247
+ if (isFirst) {
2248
+ lines.push(`${indent}} catch (${errorName}) {`);
2249
+ }
2250
+ if (c.errorType) {
2251
+ const cond = isFirst ? 'if' : 'else if';
2252
+ lines.push(`${indent} ${cond} (${errorName} instanceof ${c.errorType}) {`);
2253
+ lines.push(catchBody);
2254
+ lines.push(`${indent} }`);
2255
+ if (isLast) lines.push(`${indent}}`);
2256
+ } else {
2257
+ if (isFirst && isLast) {
2258
+ lines.push(catchBody);
2259
+ lines.push(`${indent}}`);
2260
+ } else {
2261
+ lines.push(`${indent} else {`);
2262
+ lines.push(catchBody);
2263
+ lines.push(`${indent} }`);
2264
+ if (isLast) lines.push(`${indent}}`);
2265
+ }
2266
+ }
2267
+ }
2268
+ return lines.join('\n');
2269
+ }
2270
+ let out = tryBlock;
1555
2271
  if (node.recoverBody) {
1556
2272
  const errorName = node.catchName || '__plainError';
1557
2273
  const recoverBody = node.recoverBody.map(s => generateStatement(s, indent + ' ', context)).join('\n');
1558
2274
  out += ` catch (${errorName}) {\n${recoverBody}\n${indent}}`;
1559
2275
  } else {
1560
- // A bare try {} is invalid JavaScript: without "recover", errors are
1561
- // swallowed through an empty catch block.
1562
- out += ' catch (__plainError) {}';
2276
+ out += `${indent}} catch (__plainError) {}`;
1563
2277
  }
1564
2278
  return out;
1565
2279
  }
@@ -1865,6 +2579,79 @@ function generateStatement(node, indent = '', context = createGenerationContext(
1865
2579
  ensureBuiltin(context, 'websocket');
1866
2580
  return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
1867
2581
 
2582
+ // ── IOPL-native features ──────────────────────────────────────────────
2583
+
2584
+ case 'GatherStatement': {
2585
+ const coll = generateExpr(node.collection, context);
2586
+ const body = generateExpr(node.body, context);
2587
+ return `${indent}${coll} = ${coll}.map(${node.item} => ${body});`;
2588
+ }
2589
+
2590
+ case 'FilterStatement': {
2591
+ const coll = generateExpr(node.collection, context);
2592
+ const cond = generateCondition(node.condition, context);
2593
+ return `${indent}${coll} = ${coll}.filter(${node.item} => ${cond});`;
2594
+ }
2595
+
2596
+ case 'TotalStatement': {
2597
+ const coll = generateExpr(node.collection, context);
2598
+ const body = generateExpr(node.body, context);
2599
+ return `${indent}${coll} = ${coll}.reduce((__sum, ${node.item}) => __sum + ${body}, 0);`;
2600
+ }
2601
+
2602
+ case 'MatchStatement': {
2603
+ const value = generateExpr(node.value, context);
2604
+ const lines = [`${indent}switch (${value}) {`];
2605
+ for (const c of node.cases) {
2606
+ const testVal = generateExpr(c.test, context);
2607
+ lines.push(`${indent} case ${testVal}:`);
2608
+ for (const s of c.body) lines.push(generateStatement(s, indent + ' ', context));
2609
+ lines.push(`${indent} break;`);
2610
+ }
2611
+ if (node.defaultCase) {
2612
+ lines.push(`${indent} default:`);
2613
+ for (const s of node.defaultCase) lines.push(generateStatement(s, indent + ' ', context));
2614
+ lines.push(`${indent} break;`);
2615
+ }
2616
+ lines.push(`${indent}}`);
2617
+ return lines.join('\n');
2618
+ }
2619
+
2620
+ case 'RegexMatchStatement': {
2621
+ const source = generateExpr(node.source, context);
2622
+ const pattern = typeof node.pattern === 'string' ? JSON.stringify(node.pattern) : generateExpr(node.pattern, context);
2623
+ return `${indent}const ${node.name} = ${source}.match(new RegExp(${pattern}));`;
2624
+ }
2625
+
2626
+ case 'EmitStatement': {
2627
+ ensureBuiltin(context, '__emitter');
2628
+ const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
2629
+ const data = node.data ? generateExpr(node.data, context) : '';
2630
+ return `${indent}__emitter.emit(${event}${data ? ', ' + data : ''});`;
2631
+ }
2632
+
2633
+ case 'WhenHappensStatement': {
2634
+ ensureBuiltin(context, '__emitter');
2635
+ const event = typeof node.event === 'string' ? JSON.stringify(node.event) : generateExpr(node.event, context);
2636
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2637
+ return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
2638
+ }
2639
+
2640
+ case 'StreamStatement': {
2641
+ ensureBuiltin(context, '__streamFile');
2642
+ markAsync(context);
2643
+ const filename = generateExpr(node.filename, context);
2644
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2645
+ return `${indent}await __streamFile(${filename}, async (${node.paramName}) => {\n${body}\n${indent}});`;
2646
+ }
2647
+
2648
+ case 'RunParallelStatement': {
2649
+ markAsync(context);
2650
+ const body = (node.body || []).map(s => generateStatement(s, indent + ' ', context)).join('\n');
2651
+ const resultName = node.resultName || '__parallelResults';
2652
+ return `${indent}const ${resultName} = await Promise.all([(async () => {\n${body}\n${indent}})()]);`;
2653
+ }
2654
+
1868
2655
  default:
1869
2656
  throw new Error(`Unknown statement type "${node.type}".`);
1870
2657
  }
@@ -2024,6 +2811,29 @@ function generateExpr(node, context = createGenerationContext()) {
2024
2811
  ensureBuiltin(context, 'fs');
2025
2812
  return `fs.writeFileSync(${generateExpr(node.data, context)}, ${generateExpr(node.file, context)}, 'utf8')`;
2026
2813
 
2814
+ // v1.0.0 — record constructor: `create a Person with name "Ada" and age 17`
2815
+ // calls the kind factory that `define a kind called "Person"` registered.
2816
+ case 'CreateKindExpression': {
2817
+ const fields = node.pairs
2818
+ .map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
2819
+ .join(', ');
2820
+ return `${node.kind}({ ${fields} })`;
2821
+ }
2822
+
2823
+ // v1.0.0 — concurrency combinators: `all of [...]` / `any of [...]` /
2824
+ // `settled of [...]`. All are awaited; `settled` returns status records.
2825
+ case 'ConcurrencyExpression': {
2826
+ markAsync(context);
2827
+ const rhs = generateExpr(node.items, context);
2828
+ if (node.combo === 'any') return `(await Promise.race(${rhs}))`;
2829
+ if (node.combo === 'settled') return `(await Promise.allSettled(${rhs}))`;
2830
+ return `(await Promise.all(${rhs}))`;
2831
+ }
2832
+
2833
+ // v1.0.0 — `spread of <collection>` → a fresh array from an iterable.
2834
+ case 'SpreadExpression':
2835
+ return `[...${generateExpr(node.collection, context)}]`;
2836
+
2027
2837
  default:
2028
2838
  throw new Error(`Unknown expression type "${node.type}".`);
2029
2839
  }