plainscript-lang 1.0.3 → 1.0.36

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 (93) hide show
  1. package/README.md +836 -188
  2. package/compiler/cli.js +68 -4
  3. package/compiler/dependency-detector.js +6 -2
  4. package/compiler/generator.js +737 -51
  5. package/compiler/lexer.js +12 -0
  6. package/compiler/parser.js +184 -14
  7. package/compiler/version.js +1 -1
  8. package/docs/CAPABILITY_GAP_AUDIT.md +32 -5
  9. package/docs/GAME-PROMPT.md +915 -0
  10. package/docs/PLAINSCRIPT-SPEC.md +264 -3
  11. package/docs/index.html +41 -33
  12. package/docs/logo-pln.jpg +0 -0
  13. package/docs/visualization-example.svg +32 -0
  14. package/docs/website/script.js +130 -1
  15. package/docs/website/style.css +253 -122
  16. package/examples/ai-providers.pln +1 -1
  17. package/examples/arrays.pln +1 -1
  18. package/examples/async-errors.pln +1 -1
  19. package/examples/auth-api.pln +1 -1
  20. package/examples/auth-sessions.pln +1 -1
  21. package/examples/basics.pln +1 -1
  22. package/examples/bots.pln +1 -1
  23. package/examples/browser-interactive/README.md +29 -0
  24. package/examples/browser-interactive/public/index.html +83 -0
  25. package/examples/browser-interactive/public/interactive.js +27 -0
  26. package/examples/browser-interactive/src/interactive.pln +34 -0
  27. package/examples/cache-and-jobs.pln +1 -1
  28. package/examples/cache-schedule.pln +1 -1
  29. package/examples/canvas-game/README.md +34 -0
  30. package/examples/canvas-game/public/game.js +131 -0
  31. package/examples/canvas-game/public/index.html +48 -0
  32. package/examples/canvas-game/src/game.pln +139 -0
  33. package/examples/collections.pln +1 -1
  34. package/examples/concurrency.pln +1 -1
  35. package/examples/conditions.pln +1 -1
  36. package/examples/database.pln +1 -1
  37. package/examples/day2.pln +1 -1
  38. package/examples/day3.pln +1 -1
  39. package/examples/deployment.pln +1 -1
  40. package/examples/email-send.pln +1 -1
  41. package/examples/error-handling.pln +1 -1
  42. package/examples/expressions.pln +1 -1
  43. package/examples/file-uploads.pln +1 -1
  44. package/examples/files-and-config.pln +1 -1
  45. package/examples/files.pln +1 -1
  46. package/examples/football-backend/app.pln +1 -1
  47. package/examples/functions.pln +1 -1
  48. package/examples/hello.pln +1 -1
  49. package/examples/http-client.pln +1 -1
  50. package/examples/http.pln +1 -1
  51. package/examples/id-verification/app.pln +1 -1
  52. package/examples/javascript-library/README.md +54 -0
  53. package/examples/javascript-library/package-lock.json +21 -0
  54. package/examples/javascript-library/package.json +8 -0
  55. package/examples/javascript-library/public/config.json +4 -0
  56. package/examples/javascript-library/public/index.html +40 -0
  57. package/examples/javascript-library/src/interop.pln +53 -0
  58. package/examples/json.pln +1 -1
  59. package/examples/loops.pln +1 -1
  60. package/examples/modules/app.pln +1 -1
  61. package/examples/modules/main.pln +1 -1
  62. package/examples/modules/math.pln +1 -1
  63. package/examples/mongo.pln +1 -1
  64. package/examples/objects.pln +1 -1
  65. package/examples/ocr.pln +1 -1
  66. package/examples/packages.pln +1 -1
  67. package/examples/record-kinds.pln +1 -1
  68. package/examples/records.pln +1 -1
  69. package/examples/rest-api-fetch.pln +1 -1
  70. package/examples/rest-api.pln +1 -1
  71. package/examples/scheduled-tasks.pln +1 -1
  72. package/examples/search-and-filter.pln +1 -1
  73. package/examples/server.pln +1 -1
  74. package/examples/sessions-and-cookies.pln +1 -1
  75. package/examples/sqlite.pln +1 -1
  76. package/examples/start.pln +1 -1
  77. package/examples/stdlib.pln +1 -1
  78. package/examples/string-verbs.pln +1 -1
  79. package/examples/telegram-ai-bot.pln +1 -1
  80. package/examples/telegram-bot.pln +1 -1
  81. package/examples/testing.pln +1 -1
  82. package/examples/three-dimensional/README.md +51 -0
  83. package/examples/three-dimensional/public/index.html +33 -0
  84. package/examples/three-dimensional/src/scene.pln +34 -0
  85. package/examples/visualization.pln +12 -0
  86. package/examples/web-api.pln +1 -1
  87. package/examples/web-app.pln +1 -1
  88. package/examples/websocket-server.pln +1 -1
  89. package/examples/websocket.pln +1 -1
  90. package/examples/whatsapp-bot/pairing.pln +24 -2
  91. package/examples/whatsapp-bot/qr.pln +18 -2
  92. package/package.json +5 -3
  93. package/docs/logo.jpg +0 -0
@@ -88,6 +88,164 @@ const BUILTIN_DECLARATIONS = {
88
88
  ` }`,
89
89
  `}`,
90
90
  ].join('\n'),
91
+ // v1.0.36 — DOM browser runtime (select/selectAll/parseHTML). Browser
92
+ // globals are guarded so the generated JS explains the problem when it is
93
+ // run under Node instead of failing with a ReferenceError midpoint.
94
+ dom: [
95
+ `function __select(sel) {`,
96
+ ` if (typeof document === 'undefined') throw new Error('select(...) needs a browser (document is not defined in Node).');`,
97
+ ` return document.querySelector(sel);`,
98
+ `}`,
99
+ `function __selectAll(sel) {`,
100
+ ` if (typeof document === 'undefined') throw new Error('selectAll(...) needs a browser (document is not defined in Node).');`,
101
+ ` return [...document.querySelectorAll(sel)];`,
102
+ `}`,
103
+ `function __parseHTML(html) {`,
104
+ ` if (typeof document === 'undefined') throw new Error('parseHTML(...) needs a browser (document is not defined in Node).');`,
105
+ ` const template = document.createElement('template');`,
106
+ ` template.innerHTML = String(html);`,
107
+ ` return template.content;`,
108
+ `}`,
109
+ ].join('\n'),
110
+ // v1.0.36 — input runtime: pointer coordinates, gamepads, dropped files.
111
+ input: [
112
+ `function __localPoint(e, canvas) {`,
113
+ ` if (typeof document === 'undefined') throw new Error('localPoint(...) needs a browser (document is not defined in Node).');`,
114
+ ` const rect = canvas.getBoundingClientRect();`,
115
+ ` return {`,
116
+ ` x: (e.clientX - rect.left) * (canvas.width / rect.width),`,
117
+ ` y: (e.clientY - rect.top) * (canvas.height / rect.height),`,
118
+ ` };`,
119
+ `}`,
120
+ `function __gamepads() {`,
121
+ ` if (typeof navigator === 'undefined' || typeof navigator.getGamepads !== 'function') throw new Error('gamepads() needs a browser with the Gamepad API (navigator.getGamepads).');`,
122
+ ` return navigator.getGamepads().filter(Boolean);`,
123
+ `}`,
124
+ `function __droppedFiles(event) {`,
125
+ ` return [...(event && event.dataTransfer ? event.dataTransfer.files : [])];`,
126
+ `}`,
127
+ ].join('\n'),
128
+ // v1.0.36 — asset-loading runtime (images, JSON, bytes, data URLs). All
129
+ // helpers return promises; the STDLIB entries await them.
130
+ assets: [
131
+ `function __loadImage(url) {`,
132
+ ` if (typeof Image === 'undefined') throw new Error('loadImage(...) needs a browser (global Image is not defined in Node).');`,
133
+ ` return new Promise((resolve, reject) => {`,
134
+ ` const img = new Image();`,
135
+ ` img.onload = () => resolve(img);`,
136
+ ` img.onerror = () => reject(new Error('Could not load image: ' + url));`,
137
+ ` img.src = String(url);`,
138
+ ` });`,
139
+ `}`,
140
+ `async function __fetchJson(url) {`,
141
+ ` if (typeof fetch === 'undefined') throw new Error('fetchJson(...) needs a browser or Node 18+ with global fetch.');`,
142
+ ` const response = await fetch(url);`,
143
+ ` const text = await response.text();`,
144
+ ` let data = null;`,
145
+ ` let parseError = null;`,
146
+ ` try { data = JSON.parse(text); } catch (e) { parseError = e.message; }`,
147
+ ` return { ok: response.ok, status: response.status, data, text, parseError };`,
148
+ `}`,
149
+ `async function __fetchBytes(url) {`,
150
+ ` if (typeof fetch === 'undefined') throw new Error('fetchBytes(...) needs a browser or Node 18+ with global fetch.');`,
151
+ ` const response = await fetch(url);`,
152
+ ` const buffer = await response.arrayBuffer();`,
153
+ ` return { ok: response.ok, status: response.status, data: new Uint8Array(buffer) };`,
154
+ `}`,
155
+ `function __readDataUrl(file) {`,
156
+ ` if (typeof FileReader === 'undefined') throw new Error('readDataUrl(...) needs a browser (FileReader is not defined in Node).');`,
157
+ ` return new Promise((resolve, reject) => {`,
158
+ ` const reader = new FileReader();`,
159
+ ` reader.onload = () => resolve(reader.result);`,
160
+ ` reader.onerror = () => reject(new Error('Could not read the file as a data URL.'));`,
161
+ ` reader.readAsDataURL(file);`,
162
+ ` });`,
163
+ `}`,
164
+ ].join('\n'),
165
+ // v1.0.36 — Web Audio runtime. The AudioContext is created once and shared
166
+ // (browsers cap the number), and resumed on demand because autoplay policies
167
+ // start it suspended.
168
+ audio: [
169
+ `let __plainAudioCtx = null;`,
170
+ `function __audioContext() {`,
171
+ ` if (typeof window === 'undefined' && typeof self === 'undefined') throw new Error('audioContext() / playTone(...) need a browser (Web Audio is not available in Node).');`,
172
+ ` if (!__plainAudioCtx) {`,
173
+ ` const Ctx = window.AudioContext || window.webkitAudioContext;`,
174
+ ` if (!Ctx) throw new Error('Web Audio is not supported in this browser.');`,
175
+ ` __plainAudioCtx = new Ctx();`,
176
+ ` }`,
177
+ ` if (__plainAudioCtx.state === 'suspended') __plainAudioCtx.resume();`,
178
+ ` return __plainAudioCtx;`,
179
+ `}`,
180
+ `function __audioTone(freq, seconds, opts) {`,
181
+ ` const ctx = __audioContext();`,
182
+ ` const o = opts || {};`,
183
+ ` const oscillator = ctx.createOscillator();`,
184
+ ` const gain = ctx.createGain();`,
185
+ ` const duration = seconds || 0.5;`,
186
+ ` oscillator.type = o.type || 'sine';`,
187
+ ` oscillator.frequency.value = freq;`,
188
+ ` gain.gain.value = o.gain || 0.2;`,
189
+ ` oscillator.connect(gain);`,
190
+ ` gain.connect(ctx.destination);`,
191
+ ` const t = ctx.currentTime;`,
192
+ ` if (o.when) oscillator.start(t + o.when); else oscillator.start(t);`,
193
+ ` gain.gain.setValueAtTime(o.gain || 0.2, t);`,
194
+ ` gain.gain.exponentialRampToValueAtTime(0.0001, t + duration);`,
195
+ ` oscillator.stop(t + duration);`,
196
+ `}`,
197
+ `function __loadAudio(url) {`,
198
+ ` if (typeof Audio === 'undefined') throw new Error('loadAudio(...) needs a browser (global Audio is not defined in Node).');`,
199
+ ` return new Promise((resolve, reject) => {`,
200
+ ` const audio = new Audio();`,
201
+ ` audio.oncanplaythrough = () => resolve(audio);`,
202
+ ` audio.onerror = () => reject(new Error('Could not load audio: ' + url));`,
203
+ ` audio.src = String(url);`,
204
+ ` audio.load();`,
205
+ ` });`,
206
+ `}`,
207
+ ].join('\n'),
208
+ // v1.0.36 — WebGL runtime: context selection plus the three compile/link/
209
+ // buffer helpers behind the gl* stdlib entries.
210
+ gl: [
211
+ `function __glContext(canvas) {`,
212
+ ` if (typeof document === 'undefined') throw new Error('webglContext(...) needs a browser (document is not defined in Node).');`,
213
+ ` const gl = canvas.getContext('webgl2') || canvas.getContext('webgl') || canvas.getContext('experimental-webgl');`,
214
+ ` if (!gl) throw new Error('WebGL is not supported in this browser.');`,
215
+ ` return gl;`,
216
+ `}`,
217
+ `function __glShader(gl, type, source) {`,
218
+ ` // Accept both the friendly names ("vertex"/"fragment") and the DOM`,
219
+ ` // constant names ("VERTEX_SHADER"/"FRAGMENT_SHADER").`,
220
+ ` const kind = type === 'vertex' || type === 'VERTEX_SHADER' ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER;`,
221
+ ` const shader = gl.createShader(kind);`,
222
+ ` gl.shaderSource(shader, source);`,
223
+ ` gl.compileShader(shader);`,
224
+ ` if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {`,
225
+ ` const info = gl.getShaderInfoLog(shader);`,
226
+ ` gl.deleteShader(shader);`,
227
+ ` throw new Error('Shader compile error: ' + (info || 'unknown'));`,
228
+ ` }`,
229
+ ` return shader;`,
230
+ `}`,
231
+ `function __glProgram(gl, vertexShader, fragmentShader) {`,
232
+ ` const program = gl.createProgram();`,
233
+ ` gl.attachShader(program, vertexShader);`,
234
+ ` gl.attachShader(program, fragmentShader);`,
235
+ ` gl.linkProgram(program);`,
236
+ ` if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {`,
237
+ ` const info = gl.getProgramInfoLog(program);`,
238
+ ` throw new Error('Program link error: ' + (info || 'unknown'));`,
239
+ ` }`,
240
+ ` return program;`,
241
+ `}`,
242
+ `function __glBuffer(gl, data) {`,
243
+ ` const buffer = gl.createBuffer();`,
244
+ ` gl.bindBuffer(gl.ARRAY_BUFFER, buffer);`,
245
+ ` gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);`,
246
+ ` return buffer;`,
247
+ `}`,
248
+ ].join('\n'),
91
249
  // v1.0.1 — shared runtime helpers for reflection, binary-size, YAML subset
92
250
  // parsing/emitting, spread of timeouts, and set/map helpers. Injected lazily
93
251
  // when any feature that needs them is used.
@@ -221,6 +379,98 @@ const BUILTIN_DECLARATIONS = {
221
379
  ` });`,
222
380
  `}`,
223
381
  ].join('\n'),
382
+ // v1.0.35 — dependency-free SVG images and visualizations.
383
+ // The image value is an SVG string, so it can be saved, embedded, or returned
384
+ // from a web route without a native graphics dependency.
385
+ visualization: [
386
+ `const __vizFs = require('fs');`,
387
+ `const __vizPath = require('path');`,
388
+ `function __svgEscape(value) {`,
389
+ ` return String(value == null ? '' : value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');`,
390
+ `}`,
391
+ `function __vizOptions(options) {`,
392
+ ` return Object.assign({ width: 720, height: 420, background: '#071b10', foreground: '#e6f1e7', grid: '#284734', accent: '#40c463', muted: '#8da99a' }, options || {});`,
393
+ `}`,
394
+ `function __svgImage(width, height, content, options) {`,
395
+ ` const opt = __vizOptions(options);`,
396
+ ` const w = Number(width) || opt.width;`,
397
+ ` const h = Number(height) || opt.height;`,
398
+ ` return '<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '" role="img">' +`,
399
+ ` '<rect width="100%" height="100%" fill="' + __svgEscape(opt.background) + '"/>' + String(content == null ? '' : content) + '</svg>';`,
400
+ `}`,
401
+ `function __vizText(x, y, value, size, fill, anchor, weight) {`,
402
+ ` return '<text x="' + x + '" y="' + y + '" fill="' + __svgEscape(fill) + '" font-family="Arial, sans-serif" font-size="' + size + '" text-anchor="' + (anchor || 'start') + '" font-weight="' + (weight || 400) + '">' + __svgEscape(value) + '</text>';`,
403
+ `}`,
404
+ `function __barChart(title, labels, values, options) {`,
405
+ ` const opt = __vizOptions(options);`,
406
+ ` const names = Array.isArray(labels) ? labels : [];`,
407
+ ` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
408
+ ` const count = Math.max(names.length, nums.length, 1);`,
409
+ ` const width = Number(opt.width) || 720;`,
410
+ ` const height = Number(opt.height) || 420;`,
411
+ ` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
412
+ ` const plotWidth = Math.max(1, width - left - right);`,
413
+ ` const plotHeight = Math.max(1, height - top - bottom);`,
414
+ ` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
415
+ ` const barWidth = plotWidth / count * 0.68;`,
416
+ ` const gap = plotWidth / count;`,
417
+ ` let body = '';`,
418
+ ` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
419
+ ` for (let tick = 0; tick <= 4; tick++) {`,
420
+ ` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
421
+ ` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
422
+ ` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
423
+ ` }`,
424
+ ` for (let index = 0; index < count; index++) {`,
425
+ ` const value = Math.max(0, nums[index] || 0); const barHeight = value / max * plotHeight;`,
426
+ ` const x = left + index * gap + (gap - barWidth) / 2; const y = top + plotHeight - barHeight;`,
427
+ ` body += '<rect x="' + x + '" y="' + y + '" width="' + barWidth + '" height="' + barHeight + '" rx="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
428
+ ` body += __vizText(left + index * gap + gap / 2, height - 24, names[index] == null ? '' : names[index], 12, opt.muted, 'middle', 400);`,
429
+ ` }`,
430
+ ` return __svgImage(width, height, body, opt);`,
431
+ `}`,
432
+ `function __lineChart(title, labels, values, options) {`,
433
+ ` const opt = __vizOptions(options);`,
434
+ ` const names = Array.isArray(labels) ? labels : [];`,
435
+ ` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
436
+ ` const count = Math.max(names.length, nums.length, 2);`,
437
+ ` const width = Number(opt.width) || 720;`,
438
+ ` const height = Number(opt.height) || 420;`,
439
+ ` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
440
+ ` const plotWidth = Math.max(1, width - left - right);`,
441
+ ` const plotHeight = Math.max(1, height - top - bottom);`,
442
+ ` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
443
+ ` let body = '';`,
444
+ ` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
445
+ ` for (let tick = 0; tick <= 4; tick++) {`,
446
+ ` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
447
+ ` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
448
+ ` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
449
+ ` }`,
450
+ ` const points = nums.map((value, index) => {`,
451
+ ` const x = left + (count === 1 ? plotWidth / 2 : index * plotWidth / (count - 1));`,
452
+ ` const y = top + plotHeight - Math.max(0, value) / max * plotHeight;`,
453
+ ` return { x, y, label: names[index] == null ? '' : names[index] };`,
454
+ ` });`,
455
+ ` if (points.length) {`,
456
+ ` body += '<polyline fill="none" stroke="' + __svgEscape(opt.accent) + '" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" points="' + points.map(point => point.x + ',' + point.y).join(' ') + '"/>';`,
457
+ ` for (const point of points) {`,
458
+ ` body += '<circle cx="' + point.x + '" cy="' + point.y + '" r="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
459
+ ` body += __vizText(point.x, height - 24, point.label, 12, opt.muted, 'middle', 400);`,
460
+ ` }`,
461
+ ` }`,
462
+ ` return __svgImage(width, height, body, opt);`,
463
+ `}`,
464
+ `function __saveImage(file, image) {`,
465
+ ` const target = String(file);`,
466
+ ` __vizFs.mkdirSync(__vizPath.dirname(target), { recursive: true });`,
467
+ ` __vizFs.writeFileSync(target, String(image == null ? '' : image), 'utf8');`,
468
+ ` return target;`,
469
+ `}`,
470
+ `function __imageDataUri(image) {`,
471
+ ` return 'data:image/svg+xml;base64,' + Buffer.from(String(image == null ? '' : image), 'utf8').toString('base64');`,
472
+ `}`,
473
+ ].join('\n'),
224
474
  // v1.0.1 — process execution (child processes).
225
475
  process: [
226
476
  `const { execFile } = require('child_process');`,
@@ -389,8 +639,9 @@ const BUILTIN_DECLARATIONS = {
389
639
  // lifecycle and messages.upsert normalization. PlainScript programs only ever
390
640
  // see __whatsappStart/__whatsappOnMessage/__whatsappReply.
391
641
  whatsapp: [
392
- `const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {`,
642
+ `const { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload } = (() => {`,
393
643
  ` let sock = null;`,
644
+ ` let __waBaileysPkg = '@qwerty-xcv/baileys';`,
394
645
  ` const handlers = [];`,
395
646
  ` const __waSilentLogger = (() => {`,
396
647
  ` const noop = () => {};`,
@@ -415,21 +666,95 @@ const BUILTIN_DECLARATIONS = {
415
666
  ` }`,
416
667
  ` function __waExtractText(content) {`,
417
668
  ` if (!content) return '';`,
418
- ` return String(` +
419
- `(content.conversation || (content.extendedTextMessage || {}).text || ` +
420
- `(content.imageMessage || {}).caption || (content.videoMessage || {}).caption || ` +
421
- `(content.documentMessage || {}).caption) || '');`,
669
+ ` const c = content;`,
670
+ ` if (c.conversation != null) return String(c.conversation);`,
671
+ ` if (c.extendedTextMessage && c.extendedTextMessage.text != null) return String(c.extendedTextMessage.text);`,
672
+ ` if (c.imageMessage && c.imageMessage.caption != null) return String(c.imageMessage.caption);`,
673
+ ` if (c.videoMessage && c.videoMessage.caption != null) return String(c.videoMessage.caption);`,
674
+ ` if (c.documentMessage && c.documentMessage.caption != null) return String(c.documentMessage.caption);`,
675
+ ` if (c.audioMessage && c.audioMessage.caption != null) return String(c.audioMessage.caption);`,
676
+ ` if (c.stickerMessage && c.stickerMessage.caption != null) return String(c.stickerMessage.caption);`,
677
+ ` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return String(c.buttonsResponseMessage.selectedButtonId);`,
678
+ ` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply && c.listResponseMessage.singleSelectReply.selectedRowId != null) return String(c.listResponseMessage.singleSelectReply.selectedRowId);`,
679
+ ` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return String(c.templateButtonReplyMessage.selectedId);`,
680
+ ` if (c.reactionMessage && c.reactionMessage.text != null) return String(c.reactionMessage.text);`,
681
+ ` if (c.contactMessage && c.contactMessage.displayName != null) return String(c.contactMessage.displayName);`,
682
+ ` if (c.contactsArrayMessage && c.contactsArrayMessage.contacts) return c.contactsArrayMessage.contacts.map(x => x.displayName || '').join(', ');`,
683
+ ` if (c.locationMessage) return String(c.locationMessage.degreesLatitude) + ',' + String(c.locationMessage.degreesLongitude);`,
684
+ ` if (c.groupInviteMessage) return String(c.groupInviteMessage.groupJid || '');`,
685
+ ` if (c.pollCreationMessage && c.pollCreationMessage.name != null) return String(c.pollCreationMessage.name);`,
686
+ ` return '';`,
687
+ ` }`,
688
+ ` function __waMessageType(content) {`,
689
+ ` if (!content) return 'unknown';`,
690
+ ` const c = content;`,
691
+ ` if (c.conversation != null || c.extendedTextMessage) return 'text';`,
692
+ ` if (c.imageMessage) return 'image';`,
693
+ ` if (c.videoMessage) return 'video';`,
694
+ ` if (c.audioMessage) return 'audio';`,
695
+ ` if (c.documentMessage) return 'document';`,
696
+ ` if (c.stickerMessage) return 'sticker';`,
697
+ ` if (c.buttonsResponseMessage) return 'button';`,
698
+ ` if (c.listResponseMessage) return 'list';`,
699
+ ` if (c.templateButtonReplyMessage) return 'template-button';`,
700
+ ` if (c.interactiveResponseMessage) return 'interactive';`,
701
+ ` if (c.reactionMessage) return 'reaction';`,
702
+ ` if (c.contactMessage) return 'contact';`,
703
+ ` if (c.contactsArrayMessage) return 'contacts';`,
704
+ ` if (c.locationMessage) return 'location';`,
705
+ ` if (c.liveLocationMessage) return 'live-location';`,
706
+ ` if (c.pollCreationMessage) return 'poll';`,
707
+ ` if (c.pollUpdateMessage) return 'poll-update';`,
708
+ ` if (c.groupInviteMessage) return 'group-invite';`,
709
+ ` if (c.protocolMessage) return 'protocol';`,
710
+ ` if (c.buttonsMessage) return 'buttons';`,
711
+ ` if (c.templateMessage) return 'template';`,
712
+ ` if (c.interactiveMessage) return 'interactive';`,
713
+ ` return 'other';`,
714
+ ` }`,
715
+ ` function __waButtonId(content) {`,
716
+ ` if (!content) return null;`,
717
+ ` const c = content;`,
718
+ ` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return c.buttonsResponseMessage.selectedButtonId;`,
719
+ ` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply) return c.listResponseMessage.singleSelectReply.selectedRowId || null;`,
720
+ ` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return c.templateButtonReplyMessage.selectedId;`,
721
+ ` if (c.interactiveResponseMessage && c.interactiveResponseMessage.nativeFlowResponseMessage) {`,
722
+ ` try { return JSON.parse(c.interactiveResponseMessage.nativeFlowResponseMessage.paramsJson).id || null; } catch (_) { return null; }`,
723
+ ` }`,
724
+ ` return null;`,
725
+ ` }`,
726
+ ` async function __waDownload(message, dest) {`,
727
+ ` if (!sock) throw new Error('WhatsApp: the bot is not connected.');`,
728
+ ` const { downloadMediaMessage } = require(__waBaileysPkg);`,
729
+ ` const raw = message && message.raw ? message.raw : message;`,
730
+ ` const buffer = await downloadMediaMessage(raw, 'buffer', {}, { logger: __waSilentLogger, reuploadRequest: sock.updateMediaMessage });`,
731
+ ` if (!dest) return buffer;`,
732
+ ` const fs = require('fs'), path = require('path');`,
733
+ ` const dir = path.dirname(path.resolve(dest));`,
734
+ ` if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });`,
735
+ ` fs.writeFileSync(dest, buffer);`,
736
+ ` return dest;`,
422
737
  ` }`,
423
- ` async function __whatsappReply(chat, value) {`,
738
+ ` async function __whatsappDownload(message, dest) {`,
739
+ ` if (!message) throw new Error('WhatsApp: there is no message to download.');`,
740
+ ` await __waDownload(message, dest);`,
741
+ ` console.log('WhatsApp: saved media to ' + dest);`,
742
+ ` }`,
743
+ ` async function __whatsappReply(chat, value, extra) {`,
424
744
  ` if (!sock) throw new Error('WhatsApp: cannot reply because the bot is not connected yet.');`,
425
745
  ` const text = typeof value === 'string' ? value : JSON.stringify(value);`,
426
- ` return sock.sendMessage(chat, { text });`,
746
+ ` return sock.sendMessage(chat, Object.assign({ text }, extra || {}));`,
747
+ ` }`,
748
+ ` async function __whatsappSend(chat, value) {`,
749
+ ` if (!sock) throw new Error('WhatsApp: cannot send because the bot is not connected yet.');`,
750
+ ` return sock.sendMessage(chat, typeof value === 'string' ? { text: value } : value);`,
427
751
  ` }`,
428
752
  ` function __whatsappOnMessage(handler) { handlers.push(handler); }`,
429
753
  ` async function __whatsappStart(options) {`,
430
- ` const baileys = require('@whiskeysockets/baileys');`,
754
+ ` __waBaileysPkg = options.baileys || '@qwerty-xcv/baileys';`,
755
+ ` const baileys = require(__waBaileysPkg);`,
431
756
  ` const makeWASocket = baileys.default;`,
432
- ` const { useMultiFileAuthState, fetchLatestBaileysVersion, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
757
+ ` const { useMultiFileAuthState, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
433
758
  ` const folder = options.folder || 'plainscript-whatsapp-auth';`,
434
759
  ` const mode = options.login && options.login.mode === 'pairing' ? 'pairing' : 'qr';`,
435
760
  ` const pairingPhone = mode === 'pairing' ? __waNormalizePhone(options.login.phone) : null;`,
@@ -441,35 +766,45 @@ const BUILTIN_DECLARATIONS = {
441
766
  // Auth/session persistence: useMultiFileAuthState stores credentials in
442
767
  // the folder from `auth "<name>"`; saveCreds writes every update back.
443
768
  ` const { state, saveCreds } = await useMultiFileAuthState(folder);`,
444
- ` let version;`,
445
- ` try { version = (await fetchLatestBaileysVersion()).version; } catch (_) {}`,
446
- // Proven socket settings: these exact options are required for pairing
447
- // codes to survive WhatsApp's handshake without a 428 connection close.
769
+ // v2.14 — adopt the proven pairing-safe socket settings used by the
770
+ // reference Dual-Crasher build on the qwerty fork: a fixed Baileys protocol
771
+ // version and the exact browser fingerprint that survives WhatsApp's
772
+ // handshake without a 428 connection close.
448
773
  ` sock = makeWASocket({`,
449
- ` ...(version ? { version } : {}),`,
450
- ` browser: ['Ubuntu', 'Edge', '20.0.04'],`,
774
+ ` version: [2, 2413, 1],`,
775
+ ` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
451
776
  ` printQRInTerminal: false,`,
452
777
  ` syncFullHistory: false,`,
453
778
  ` markOnlineOnConnect: false,`,
779
+ ` generateHighQualityLinkPreview: true,`,
454
780
  ` defaultQueryTimeoutMs: 60000,`,
455
- ` keepAliveIntervalMs: 30000,`,
781
+ ` keepAliveIntervalMs: 50000,`,
456
782
  ` logger: __waSilentLogger,`,
457
783
  ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
458
784
  ` });`,
459
785
  ` sock.ev.on('creds.update', saveCreds);`,
460
786
  // Pairing codes are requested two seconds after socket creation — asking
461
- // earlier aborts the link attempt. PlainScript calls requestPairingCode(phone)
462
- // with no custom suffix; the number was validated at compile time.
787
+ // earlier aborts the link attempt. PlainScript retries a few times (spam)
788
+ // so a dropped request never blocks linking. The number was validated at
789
+ // compile time; no custom suffix is applied.
463
790
  ` if (mode === 'pairing' && !state.creds.registered) {`,
464
- ` setTimeout(() => {`,
465
- ` if (!sock) return;`,
466
- ` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
467
- ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
468
- ` console.log('WhatsApp pairing code: ' + pretty);`,
469
- ` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
470
- ` }).catch((error) => {`,
471
- ` console.error('WhatsApp pairing code failed: ' + error.message);`,
472
- ` });`,
791
+ ` let attempts = 0;`,
792
+ ` const requestCode = async () => {`,
793
+ ` if (!sock || attempts >= 4) return;`,
794
+ ` attempts += 1;`,
795
+ ` try {`,
796
+ ` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
797
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
798
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
799
+ ` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
800
+ ` }).catch((error) => {`,
801
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
802
+ ` });`,
803
+ ` } catch (_) {}`,
804
+ ` };`,
805
+ ` setTimeout(async () => {`,
806
+ ` await requestCode();`,
807
+ ` setTimeout(requestCode, 4000);`,
473
808
  ` }, 2000);`,
474
809
  ` }`,
475
810
  // Connection lifecycle: the QR code while linking, a friendly note on
@@ -514,16 +849,23 @@ const BUILTIN_DECLARATIONS = {
514
849
  ` if (key.fromMe) continue;`,
515
850
  ` const chat = key.remoteJid;`,
516
851
  ` if (!chat || chat === 'status@broadcast') continue;`,
852
+ ` const content = __waUnwrap(msg.message);`,
517
853
  ` const message = {`,
518
- ` text: __waExtractText(__waUnwrap(msg.message)),`,
854
+ ` text: __waExtractText(content),`,
855
+ ` type: __waMessageType(content),`,
856
+ ` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
857
+ ` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
858
+ ` buttonId: __waButtonId(content),`,
519
859
  ` chat,`,
520
860
  ` sender: key.participant || chat,`,
521
861
  ` name: msg.pushName || null,`,
522
862
  ` id: key.id || null,`,
523
863
  ` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
524
864
  ` isGroup: chat.endsWith('@g.us'),`,
865
+ ` raw: msg,`,
866
+ ` download: (dest) => __waDownload(msg, dest),`,
525
867
  ` };`,
526
- ` const ctx = { chat, message, reply: (value) => __whatsappReply(chat, value) };`,
868
+ ` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
527
869
  ` for (const handler of handlers) {`,
528
870
  ` await handler(ctx);`,
529
871
  ` }`,
@@ -538,7 +880,107 @@ const BUILTIN_DECLARATIONS = {
538
880
  ` };`,
539
881
  ` await connect();`,
540
882
  ` }`,
541
- ` return { __whatsappStart, __whatsappOnMessage, __whatsappReply };`,
883
+ ` async function __whatsappPair(phone, onCode, onOpen) {`,
884
+ ` const digits = __waNormalizePhone(phone);`,
885
+ ` const baileys = require(__waBaileysPkg);`,
886
+ ` const makeWASocket = baileys.default;`,
887
+ ` const { useMultiFileAuthState, makeCacheableSignalKeyStore } = baileys;`,
888
+ ` const { state, saveCreds } = await useMultiFileAuthState('whatsapp-session');`,
889
+ ` let pairSock = makeWASocket({`,
890
+ ` version: [2, 2413, 1],`,
891
+ ` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
892
+ ` printQRInTerminal: false,`,
893
+ ` syncFullHistory: false,`,
894
+ ` markOnlineOnConnect: false,`,
895
+ ` generateHighQualityLinkPreview: true,`,
896
+ ` defaultQueryTimeoutMs: 60000,`,
897
+ ` keepAliveIntervalMs: 50000,`,
898
+ ` logger: __waSilentLogger,`,
899
+ ` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
900
+ ` });`,
901
+ ` pairSock.ev.on('creds.update', saveCreds);`,
902
+ ` pairSock.ev.on('messages.upsert', async (upsert) => {`,
903
+ ` try {`,
904
+ ` if (!upsert || upsert.type !== 'notify') return;`,
905
+ ` for (const msg of upsert.messages || []) {`,
906
+ ` const key = msg.key || {};`,
907
+ ` if (key.fromMe) continue;`,
908
+ ` const chat = key.remoteJid;`,
909
+ ` if (!chat || chat === 'status@broadcast') continue;`,
910
+ ` const content = __waUnwrap(msg.message);`,
911
+ ` const message = {`,
912
+ ` text: __waExtractText(content),`,
913
+ ` type: __waMessageType(content),`,
914
+ ` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
915
+ ` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
916
+ ` buttonId: __waButtonId(content),`,
917
+ ` chat,`,
918
+ ` sender: key.participant || chat,`,
919
+ ` name: msg.pushName || null,`,
920
+ ` id: key.id || null,`,
921
+ ` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
922
+ ` isGroup: chat.endsWith('@g.us'),`,
923
+ ` raw: msg,`,
924
+ ` download: (dest) => __waDownload(msg, dest),`,
925
+ ` };`,
926
+ ` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
927
+ ` for (const handler of handlers) {`,
928
+ ` await handler(ctx);`,
929
+ ` }`,
930
+ ` }`,
931
+ ` } catch (error) {`,
932
+ ` console.error(error);`,
933
+ ` }`,
934
+ ` });`,
935
+ ` if (onCode) {`,
936
+ ` await new Promise((resolve) => {`,
937
+ ` let attempts = 0;`,
938
+ ` const requestCode = async () => {`,
939
+ ` if (!pairSock || attempts >= 4) { resolve(); return; }`,
940
+ ` attempts += 1;`,
941
+ ` try {`,
942
+ ` pairSock.requestPairingCode(digits).then((rawCode) => {`,
943
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
944
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
945
+ ` onCode(pretty);`,
946
+ ` resolve();`,
947
+ ` }).catch((error) => {`,
948
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
949
+ ` resolve();`,
950
+ ` });`,
951
+ ` } catch (_) { resolve(); }`,
952
+ ` };`,
953
+ ` setTimeout(async () => {`,
954
+ ` await requestCode();`,
955
+ ` setTimeout(requestCode, 4000);`,
956
+ ` }, 2000);`,
957
+ ` });`,
958
+ ` } else {`,
959
+ ` await new Promise((resolve) => {`,
960
+ ` let attempts = 0;`,
961
+ ` const requestCode = async () => {`,
962
+ ` if (!pairSock || attempts >= 4) { resolve(); return; }`,
963
+ ` attempts += 1;`,
964
+ ` try {`,
965
+ ` pairSock.requestPairingCode(digits).then((rawCode) => {`,
966
+ ` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
967
+ ` console.log('WhatsApp pairing code: ' + pretty);`,
968
+ ` resolve();`,
969
+ ` }).catch((error) => {`,
970
+ ` console.error('WhatsApp pairing code failed: ' + error.message);`,
971
+ ` resolve();`,
972
+ ` });`,
973
+ ` } catch (_) { resolve(); }`,
974
+ ` };`,
975
+ ` setTimeout(async () => {`,
976
+ ` await requestCode();`,
977
+ ` setTimeout(requestCode, 4000);`,
978
+ ` }, 2000);`,
979
+ ` });`,
980
+ ` }`,
981
+ ` return digits;`,
982
+ ` }`,
983
+ ` return { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload };`,
542
984
  `})();`,
543
985
  ].join('\n'),
544
986
  // v2.1.1 — HTTP client runtime on the global fetch API (Node.js 18+).
@@ -1032,6 +1474,37 @@ const BUILTIN_DECLARATIONS = {
1032
1474
  ` const result = await coll.insertOne(doc);`,
1033
1475
  ` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
1034
1476
  ` };`,
1477
+ ` __mongoDb.__update = async function(sql, params) {`,
1478
+ ` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
1479
+ ` const m = String(sql).match(/^\\s*UPDATE\\s+(\\w+)\\s+SET\\s+(.+?)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
1480
+ ` if (!m) throw new Error('MongoDB update: use UPDATE collection SET field = ? WHERE field = ?');`,
1481
+ ` const [, collection, setClause, whereClause] = m;`,
1482
+ ` const coll = __mongoCollection(collection);`,
1483
+ ` const filter = {};`,
1484
+ ` if (whereClause) {`,
1485
+ ` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1486
+ ` if (wm) filter[wm[1]] = params[1] !== undefined ? params[1] : params[0];`,
1487
+ ` }`,
1488
+ ` const updateDoc = {};`,
1489
+ ` const sm = setClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1490
+ ` if (sm) updateDoc[sm[1]] = params[0];`,
1491
+ ` const result = await coll.updateMany(filter, { $set: updateDoc });`,
1492
+ ` return { rowCount: result.modifiedCount };`,
1493
+ ` };`,
1494
+ ` __mongoDb.__delete = async function(sql, params) {`,
1495
+ ` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
1496
+ ` const m = String(sql).match(/^\\s*DELETE\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
1497
+ ` if (!m) throw new Error('MongoDB delete: use DELETE FROM collection WHERE field = ?');`,
1498
+ ` const [, collection, whereClause] = m;`,
1499
+ ` const coll = __mongoCollection(collection);`,
1500
+ ` const filter = {};`,
1501
+ ` if (whereClause) {`,
1502
+ ` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
1503
+ ` if (wm) filter[wm[1]] = params[0];`,
1504
+ ` }`,
1505
+ ` const result = await coll.deleteMany(filter);`,
1506
+ ` return { rowCount: result.deletedCount };`,
1507
+ ` };`,
1035
1508
  ` __mongoDb.__execute = async function(sql, params) {`,
1036
1509
  ` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
1037
1510
  ` };`,
@@ -1195,6 +1668,27 @@ const BUILTIN_DECLARATIONS = {
1195
1668
  print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
1196
1669
  readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1197
1670
  writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
1671
+ // v2.4.0 — dependency-free SVG image and visualization helpers.
1672
+ svgImage: (args, context) => {
1673
+ ensureBuiltin(context, 'visualization');
1674
+ return `__svgImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1675
+ },
1676
+ barChart: (args, context) => {
1677
+ ensureBuiltin(context, 'visualization');
1678
+ return `__barChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1679
+ },
1680
+ lineChart: (args, context) => {
1681
+ ensureBuiltin(context, 'visualization');
1682
+ return `__lineChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1683
+ },
1684
+ saveImage: (args, context) => {
1685
+ ensureBuiltin(context, 'visualization');
1686
+ return `__saveImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1687
+ },
1688
+ imageDataUri: (args, context) => {
1689
+ ensureBuiltin(context, 'visualization');
1690
+ return `__imageDataUri(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
1691
+ },
1198
1692
  fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
1199
1693
  read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
1200
1694
  sleep: (args, context) => `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${generateExpr(args[0], context)})`,
@@ -2160,6 +2654,115 @@ const BUILTIN_DECLARATIONS = {
2160
2654
  blob: (args, context) => `new Blob(${args.map(a => generateExpr(a, context)).join(', ')})`,
2161
2655
  file: (args, context) => `new File(${args.map(a => generateExpr(a, context)).join(', ')})`,
2162
2656
  formData: (_args) => `new FormData()`,
2657
+
2658
+ // ── v1.0.36 — browser DOM (IOPL-native). All helpers guard their browser
2659
+ // global, so the generated output throws a clear teaching error under Node.
2660
+ select: (args, context) => {
2661
+ ensureBuiltin(context, 'dom');
2662
+ requireOneArg('select', args);
2663
+ return `__select(${generateExpr(args[0], context)})`;
2664
+ },
2665
+ selectAll: (args, context) => {
2666
+ ensureBuiltin(context, 'dom');
2667
+ requireOneArg('selectAll', args);
2668
+ return `__selectAll(${generateExpr(args[0], context)})`;
2669
+ },
2670
+ parseHTML: (args, context) => {
2671
+ ensureBuiltin(context, 'dom');
2672
+ requireOneArg('parseHTML', args);
2673
+ return `__parseHTML(${generateExpr(args[0], context)})`;
2674
+ },
2675
+
2676
+ // ── v1.0.36 — browser input (IOPL-native).
2677
+ localPoint: (args, context) => {
2678
+ ensureBuiltin(context, 'input');
2679
+ requireArgs('localPoint', args, 2, 'localPoint(event, canvas)');
2680
+ return `__localPoint(${args.map(a => generateExpr(a, context)).join(', ')})`;
2681
+ },
2682
+ gamepads: (_args, context) => {
2683
+ ensureBuiltin(context, 'input');
2684
+ return `__gamepads()`;
2685
+ },
2686
+ droppedFiles: (args, context) => {
2687
+ ensureBuiltin(context, 'input');
2688
+ requireOneArg('droppedFiles', args);
2689
+ return `__droppedFiles(${generateExpr(args[0], context)})`;
2690
+ },
2691
+
2692
+ // ── v1.0.36 — browser assets (IOPL-native). Each awaitable helper is
2693
+ // awaited here, so the surrounding function/handler is marked async.
2694
+ loadImage: (args, context) => {
2695
+ ensureBuiltin(context, 'assets');
2696
+ requireOneArg('loadImage', args);
2697
+ markAsync(context);
2698
+ return `(await __loadImage(${generateExpr(args[0], context)}))`;
2699
+ },
2700
+ loadAudio: (args, context) => {
2701
+ ensureBuiltin(context, 'assets');
2702
+ requireOneArg('loadAudio', args);
2703
+ markAsync(context);
2704
+ return `(await __loadAudio(${generateExpr(args[0], context)}))`;
2705
+ },
2706
+ fetchJson: (args, context) => {
2707
+ ensureBuiltin(context, 'assets');
2708
+ requireOneArg('fetchJson', args);
2709
+ markAsync(context);
2710
+ return `(await __fetchJson(${generateExpr(args[0], context)}))`;
2711
+ },
2712
+ fetchBytes: (args, context) => {
2713
+ ensureBuiltin(context, 'assets');
2714
+ requireOneArg('fetchBytes', args);
2715
+ markAsync(context);
2716
+ return `(await __fetchBytes(${generateExpr(args[0], context)}))`;
2717
+ },
2718
+ readDataUrl: (args, context) => {
2719
+ ensureBuiltin(context, 'assets');
2720
+ requireOneArg('readDataUrl', args);
2721
+ markAsync(context);
2722
+ return `(await __readDataUrl(${generateExpr(args[0], context)}))`;
2723
+ },
2724
+
2725
+ // ── v1.0.36 — Web Audio (IOPL-native).
2726
+ audioContext: (_args, context) => {
2727
+ ensureBuiltin(context, 'audio');
2728
+ return `__audioContext()`;
2729
+ },
2730
+ playTone: (args, context) => {
2731
+ ensureBuiltin(context, 'audio');
2732
+ requireArgs('playTone', args, 1, 'playTone(440)');
2733
+ return `__audioTone(${args.map(a => generateExpr(a, context)).join(', ')})`;
2734
+ },
2735
+
2736
+ // ── v1.0.36 — WebSocket send helper (works with any WebSocket-like object,
2737
+ // browser or Node): strings go through verbatim, everything else is JSON.
2738
+ webSocketSend: (args, context) => {
2739
+ requireArgs('webSocketSend', args, 2, 'webSocketSend(socket, { type: "move", x: 10 })');
2740
+ const ws = generateExpr(args[0], context);
2741
+ const value = generateExpr(args[1], context);
2742
+ return `${ws}.send(typeof (${value}) === 'string' ? (${value}) : JSON.stringify(${value}))`;
2743
+ },
2744
+
2745
+ // ── v1.0.36 — WebGL (IOPL-native).
2746
+ webglContext: (args, context) => {
2747
+ ensureBuiltin(context, 'gl');
2748
+ requireOneArg('webglContext', args);
2749
+ return `__glContext(${generateExpr(args[0], context)})`;
2750
+ },
2751
+ glShader: (args, context) => {
2752
+ ensureBuiltin(context, 'gl');
2753
+ requireArgs('glShader', args, 3, 'glShader(gl, "vertex", "void main() {}")');
2754
+ return `__glShader(${args.map(a => generateExpr(a, context)).join(', ')})`;
2755
+ },
2756
+ glProgram: (args, context) => {
2757
+ ensureBuiltin(context, 'gl');
2758
+ requireArgs('glProgram', args, 3, 'glProgram(gl, vertexShader, fragmentShader)');
2759
+ return `__glProgram(${args.map(a => generateExpr(a, context)).join(', ')})`;
2760
+ },
2761
+ glBuffer: (args, context) => {
2762
+ ensureBuiltin(context, 'gl');
2763
+ requireArgs('glBuffer', args, 2, 'glBuffer(gl, new Float32Array([0, 0, 1, 0, 0, 1]))');
2764
+ return `__glBuffer(${args.map(a => generateExpr(a, context)).join(', ')})`;
2765
+ },
2163
2766
  };
2164
2767
 
2165
2768
  // Mark the enclosing program async when a call awaits at the top level, and
@@ -2281,14 +2884,13 @@ function emitSqlCall(kind, sql, params, indent, context) {
2281
2884
  }
2282
2885
  if (_sqlDriver === 'mongo') {
2283
2886
  markAsync(context);
2284
- // For MongoDB, we delegate to helper functions that parse SQL-like syntax
2285
- // into MongoDB operations. This is a simplified approach.
2286
- // All MongoDB operations are async, so always await them.
2287
2887
  return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
2288
2888
  }
2289
2889
  switch (kind) {
2290
2890
  case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
2291
2891
  case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
2892
+ case 'update': return `db.prepare(\`${sql}\`).run(${args})`;
2893
+ case 'delete': return `db.prepare(\`${sql}\`).run(${args})`;
2292
2894
  case 'execute': return `db.exec(\`${sql}\`)`;
2293
2895
  default: throw new Error(`Unknown SQL kind "${kind}".`);
2294
2896
  }
@@ -3235,9 +3837,11 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3235
3837
  return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
3236
3838
 
3237
3839
  case 'InsertStatement':
3840
+ return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
3238
3841
  case 'UpdateStatement':
3842
+ return `${indent}${emitSqlCall('update', node.sql, node.params, indent, context)};`;
3239
3843
  case 'DeleteStatement':
3240
- return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
3844
+ return `${indent}${emitSqlCall('delete', node.sql, node.params, indent, context)};`;
3241
3845
 
3242
3846
  case 'ExecuteStatement':
3243
3847
  return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
@@ -3245,7 +3849,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3245
3849
  // v2.1.0 — remember <name> as query|insert|update|delete … done
3246
3850
  case 'RememberSqlStatement': {
3247
3851
  const kind = node.kind === 'query' ? 'query'
3248
- : node.kind === 'execute' ? 'execute' : 'write';
3852
+ : node.kind === 'execute' ? 'execute'
3853
+ : node.kind === 'update' ? 'update'
3854
+ : node.kind === 'delete' ? 'delete'
3855
+ : 'write';
3249
3856
  return `${indent}let ${node.name} = ${emitSqlCall(kind, node.sql, node.params, indent, context)};`;
3250
3857
  }
3251
3858
 
@@ -3317,26 +3924,32 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3317
3924
 
3318
3925
  // whatsapp bot … done — starts the Baileys runtime with the declared
3319
3926
  // auth folder and login mode, then registers every "on message" handler.
3927
+ // When no login line is present (login is null), only registers handlers
3928
+ // without auto-starting — used by hybrid bots that pair on-demand.
3320
3929
  case 'WhatsAppBotStatement': {
3321
3930
  ensureBuiltin(context, 'whatsapp');
3322
3931
  markAsync(context);
3323
- // v2.1.2 — the pairing phone may be a compile-time literal or any
3324
- // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
3325
- // are normalized/validated by __waNormalizePhone at startup.
3326
- let loginArg;
3327
- if (node.login.mode === 'pairing') {
3328
- loginArg = node.login.phoneExpr != null
3329
- ? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
3330
- : `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
3331
- } else {
3332
- loginArg = `{ mode: 'qr' }`;
3932
+ const lines = [];
3933
+ if (node.login) {
3934
+ // v2.1.2 — the pairing phone may be a compile-time literal or any
3935
+ // PlainScript expression (e.g. a variable filled by `ask`). Runtime values
3936
+ // are normalized/validated by __waNormalizePhone at startup.
3937
+ let loginArg;
3938
+ if (node.login.mode === 'pairing') {
3939
+ loginArg = node.login.phoneExpr != null
3940
+ ? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
3941
+ : `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
3942
+ } else {
3943
+ loginArg = `{ mode: 'qr' }`;
3944
+ }
3945
+ lines.push(
3946
+ `${indent}await __whatsappStart({`,
3947
+ `${indent} folder: ${JSON.stringify(node.authFolder)},`,
3948
+ `${indent} login: ${loginArg},`,
3949
+ ...(node.baileysModule ? [`${indent} baileys: ${JSON.stringify(node.baileysModule)},`] : []),
3950
+ `${indent}});`,
3951
+ );
3333
3952
  }
3334
- const lines = [
3335
- `${indent}await __whatsappStart({`,
3336
- `${indent} folder: ${JSON.stringify(node.authFolder)},`,
3337
- `${indent} login: ${loginArg},`,
3338
- `${indent}});`,
3339
- ];
3340
3953
  for (const handlerNode of node.handlers) {
3341
3954
  const generated = generateStatement(handlerNode, indent, context);
3342
3955
  if (generated) lines.push(generated);
@@ -3344,6 +3957,23 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3344
3957
  return lines.join('\n');
3345
3958
  }
3346
3959
 
3960
+ // pair whatsapp "<phone>" — on-demand WhatsApp pairing session.
3961
+ // When _inTelegram is true, relays the pairing code and connection status
3962
+ // to the Telegram chat via ctx.chatId.
3963
+ case 'WhatsAppPairStatement': {
3964
+ ensureBuiltin(context, 'whatsapp');
3965
+ markAsync(context);
3966
+ const phoneArg = node.phone.type === 'StringLiteral'
3967
+ ? JSON.stringify(node.phone.value)
3968
+ : generateExpr(node.phone, context);
3969
+ if (_inTelegram) {
3970
+ return [
3971
+ `${indent}await __whatsappPair(${phoneArg}, (code) => Telegram.sendMessage(ctx.chatId, "WhatsApp pairing code: " + code), () => Telegram.sendMessage(ctx.chatId, "WhatsApp connected."));`,
3972
+ ].join('\n');
3973
+ }
3974
+ return `${indent}await __whatsappPair(${phoneArg}, null, null);`;
3975
+ }
3976
+
3347
3977
  // on message … done — registers the handler that receives each incoming
3348
3978
  // WhatsApp message as a normalized PlainScript record on `message`.
3349
3979
  case 'WhatsAppOnMessageStatement': {
@@ -3369,6 +3999,16 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3369
3999
  ensureBuiltin(context, 'whatsapp');
3370
4000
  return `${indent}console.log(__waCtx.message);`;
3371
4001
 
4002
+ // v2.14 — download "<path>" — saves the current message's media to a file.
4003
+ // Handler-only by design: outside "on message" there is no message media.
4004
+ case 'WhatsAppDownloadStatement':
4005
+ if (!_inWhatsApp) {
4006
+ throw new Error('"download" can only be used inside an "on message" block to save the current message\'s media.\n\nExample:\n whatsapp bot\n on message\n if message.type is "image"\n download "media/photo.jpg"\n reply "Saved your photo!"\n done\n done\n done');
4007
+ }
4008
+ ensureBuiltin(context, 'whatsapp');
4009
+ markAsync(context);
4010
+ return `${indent}await __whatsappDownload(__waCtx.message, ${JSON.stringify(node.filePath)});`;
4011
+
3372
4012
  // v2.1.0 — mail, cache, scheduling, background jobs, websocket
3373
4013
 
3374
4014
  case 'MailTransportStatement': {
@@ -3437,6 +4077,39 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3437
4077
  ].join('\n');
3438
4078
  }
3439
4079
 
4080
+ // v1.0.36 — every frame … done: one requestAnimationFrame loop. The next
4081
+ // frame is scheduled after the body so the body always runs once per
4082
+ // frame; an awaiting body makes the callback async automatically.
4083
+ case 'EveryFrameStatement': {
4084
+ const prevInHandler = context.inHandler;
4085
+ context.inHandler = true;
4086
+ const block = generateBlock(node.body, indent + ' ', context);
4087
+ context.inHandler = prevInHandler;
4088
+ const handlerAsync = block.emitted ? 'async ' : '';
4089
+ return [
4090
+ `${indent}requestAnimationFrame(${handlerAsync}function __frame(__frameTime) {`,
4091
+ block.out,
4092
+ `${indent} requestAnimationFrame(__frame);`,
4093
+ `${indent}});`,
4094
+ ].join('\n');
4095
+ }
4096
+
4097
+ // v1.0.36 — after <n> <unit> … done: one-shot setTimeout. The delay is an
4098
+ // expression scaled by the unit; an awaiting body makes the callback async.
4099
+ case 'AfterStatement': {
4100
+ const delay = generateExpr(node.delay, context);
4101
+ const prevInHandler = context.inHandler;
4102
+ context.inHandler = true;
4103
+ const block = generateBlock(node.body, indent + ' ', context);
4104
+ context.inHandler = prevInHandler;
4105
+ const handlerAsync = block.emitted ? 'async ' : '';
4106
+ return [
4107
+ `${indent}setTimeout(${handlerAsync}() => {`,
4108
+ block.out,
4109
+ `${indent}}, ${delay} * ${node.unit});`,
4110
+ ].join('\n');
4111
+ }
4112
+
3440
4113
  case 'ScheduleStatement': {
3441
4114
  ensureBuiltin(context, 'scheduler');
3442
4115
  const body = node.body.map(s => generateStatement(s, indent + ' ', context)).join('\n');
@@ -3558,6 +4231,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
3558
4231
  return `${indent}__emitter.on(${event}, (${node.paramName}) => {\n${body}\n${indent}});`;
3559
4232
  }
3560
4233
 
4234
+ // v1.0.36 — when <target> "<event>" happens [as <name>] … done: DOM event
4235
+ // listener. The handler param defaults to "event"; an awaiting body makes
4236
+ // the callback async automatically.
4237
+ case 'WhenTargetedStatement': {
4238
+ const prevInHandler = context.inHandler;
4239
+ context.inHandler = true;
4240
+ const block = generateBlock(node.body, indent + ' ', context);
4241
+ context.inHandler = prevInHandler;
4242
+ const handlerAsync = block.emitted ? 'async ' : '';
4243
+ const param = node.paramName || 'event';
4244
+ return `${indent}${generateExpr(node.target, context)}.addEventListener(${JSON.stringify(node.event)}, ${handlerAsync}function (${param}) {\n${block.out}\n${indent}});`;
4245
+ }
4246
+
3561
4247
  case 'StreamStatement': {
3562
4248
  ensureBuiltin(context, '__streamFile');
3563
4249
  markAsync(context);