plainscript-lang 1.0.3-beta → 1.0.35
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.
- package/README.md +126 -120
- package/compiler/bundler.js +83 -12
- package/compiler/cli.js +62 -11
- package/compiler/dependency-detector.js +17 -2
- package/compiler/generator.js +699 -63
- package/compiler/lexer.js +2 -0
- package/compiler/parser.js +450 -30
- package/compiler/sourcemap.js +142 -0
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +24 -16
- package/docs/PLAINSCRIPT-SPEC.md +175 -41
- package/docs/index.html +62 -34
- package/docs/logo-pln.jpg +0 -0
- package/docs/visualization-example.svg +32 -0
- package/docs/website/script.js +297 -19
- package/docs/website/style.css +357 -47
- package/examples/ai-providers.pln +1 -1
- package/examples/arrays.pln +1 -1
- package/examples/async-errors.pln +1 -1
- package/examples/auth-api.pln +1 -1
- package/examples/auth-sessions.pln +1 -1
- package/examples/basics.pln +1 -1
- package/examples/bots.pln +1 -1
- package/examples/cache-and-jobs.pln +1 -1
- package/examples/cache-schedule.pln +1 -1
- package/examples/collections.pln +1 -1
- package/examples/concurrency.pln +1 -1
- package/examples/conditions.pln +1 -1
- package/examples/database.pln +1 -1
- package/examples/day2.pln +1 -1
- package/examples/day3.pln +1 -1
- package/examples/deployment.pln +1 -1
- package/examples/email-send.pln +1 -1
- package/examples/error-handling.pln +1 -1
- package/examples/expressions.pln +1 -1
- package/examples/file-uploads.pln +1 -1
- package/examples/files-and-config.pln +1 -1
- package/examples/files.pln +1 -1
- package/examples/football-backend/app.pln +1 -1
- package/examples/functions.pln +1 -1
- package/examples/hello.pln +1 -1
- package/examples/http-client.pln +1 -1
- package/examples/http.pln +1 -1
- package/examples/id-verification/app.pln +1 -1
- package/examples/json.pln +1 -1
- package/examples/loops.pln +1 -1
- package/examples/modules/app.pln +1 -1
- package/examples/modules/main.pln +1 -1
- package/examples/modules/math.pln +1 -1
- package/examples/mongo.pln +33 -0
- package/examples/objects.pln +1 -1
- package/examples/ocr.pln +1 -1
- package/examples/packages.pln +1 -1
- package/examples/record-kinds.pln +1 -1
- package/examples/records.pln +1 -1
- package/examples/rest-api-fetch.pln +1 -1
- package/examples/rest-api.pln +1 -1
- package/examples/scheduled-tasks.pln +1 -1
- package/examples/search-and-filter.pln +1 -1
- package/examples/server.pln +1 -1
- package/examples/sessions-and-cookies.pln +1 -1
- package/examples/sqlite.pln +1 -1
- package/examples/start.pln +1 -1
- package/examples/stdlib.pln +1 -1
- package/examples/string-verbs.pln +16 -0
- package/examples/telegram-ai-bot.pln +1 -1
- package/examples/telegram-bot.pln +1 -1
- package/examples/testing.pln +1 -1
- package/examples/visualization.pln +12 -0
- package/examples/web-api.pln +1 -1
- package/examples/web-app.pln +1 -1
- package/examples/websocket-server.pln +1 -1
- package/examples/websocket.pln +1 -1
- package/examples/whatsapp-bot/pairing.pln +24 -2
- package/examples/whatsapp-bot/qr.pln +18 -2
- package/package.json +4 -2
- package/docs/logo.jpg +0 -0
package/compiler/generator.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Generator: converts a PlainScript AST into JavaScript source code.
|
|
2
2
|
|
|
3
3
|
const { splitPackageSpec } = require('./dependency-detector');
|
|
4
|
+
const { SourceMapGenerator } = require('./sourcemap');
|
|
4
5
|
|
|
5
6
|
// Known runtime packages and their require() statements.
|
|
6
7
|
const KNOWN_PACKAGES = {
|
|
@@ -12,6 +13,8 @@ const KNOWN_PACKAGES = {
|
|
|
12
13
|
chalk: `const chalk = require('chalk');`,
|
|
13
14
|
// v2.1.0 — PostgreSQL driver behind the friendly "postgres" name.
|
|
14
15
|
postgres: `const { Pool } = require('pg');`,
|
|
16
|
+
// v2.2.0 — MongoDB driver.
|
|
17
|
+
mongodb: `const { MongoClient } = require('mongodb');`,
|
|
15
18
|
};
|
|
16
19
|
|
|
17
20
|
// PlainScript module names whose npm package name differs from the PlainScript name.
|
|
@@ -218,6 +221,96 @@ const BUILTIN_DECLARATIONS = {
|
|
|
218
221
|
` });`,
|
|
219
222
|
`}`,
|
|
220
223
|
].join('\n'),
|
|
224
|
+
// v1.0.35 — dependency-free SVG images and visualizations.
|
|
225
|
+
// The image value is an SVG string, so it can be saved, embedded, or returned
|
|
226
|
+
// from a web route without a native graphics dependency.
|
|
227
|
+
visualization: [
|
|
228
|
+
`const __vizFs = require('fs');`,
|
|
229
|
+
`function __svgEscape(value) {`,
|
|
230
|
+
` return String(value == null ? '' : value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');`,
|
|
231
|
+
`}`,
|
|
232
|
+
`function __vizOptions(options) {`,
|
|
233
|
+
` return Object.assign({ width: 720, height: 420, background: '#071b10', foreground: '#e6f1e7', grid: '#284734', accent: '#40c463', muted: '#8da99a' }, options || {});`,
|
|
234
|
+
`}`,
|
|
235
|
+
`function __svgImage(width, height, content, options) {`,
|
|
236
|
+
` const opt = __vizOptions(options);`,
|
|
237
|
+
` const w = Number(width) || opt.width;`,
|
|
238
|
+
` const h = Number(height) || opt.height;`,
|
|
239
|
+
` return '<svg xmlns="http://www.w3.org/2000/svg" width="' + w + '" height="' + h + '" viewBox="0 0 ' + w + ' ' + h + '" role="img">' +`,
|
|
240
|
+
` '<rect width="100%" height="100%" fill="' + __svgEscape(opt.background) + '"/>' + String(content == null ? '' : content) + '</svg>';`,
|
|
241
|
+
`}`,
|
|
242
|
+
`function __vizText(x, y, value, size, fill, anchor, weight) {`,
|
|
243
|
+
` 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>';`,
|
|
244
|
+
`}`,
|
|
245
|
+
`function __barChart(title, labels, values, options) {`,
|
|
246
|
+
` const opt = __vizOptions(options);`,
|
|
247
|
+
` const names = Array.isArray(labels) ? labels : [];`,
|
|
248
|
+
` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
|
|
249
|
+
` const count = Math.max(names.length, nums.length, 1);`,
|
|
250
|
+
` const width = Number(opt.width) || 720;`,
|
|
251
|
+
` const height = Number(opt.height) || 420;`,
|
|
252
|
+
` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
|
|
253
|
+
` const plotWidth = Math.max(1, width - left - right);`,
|
|
254
|
+
` const plotHeight = Math.max(1, height - top - bottom);`,
|
|
255
|
+
` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
|
|
256
|
+
` const barWidth = plotWidth / count * 0.68;`,
|
|
257
|
+
` const gap = plotWidth / count;`,
|
|
258
|
+
` let body = '';`,
|
|
259
|
+
` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
|
|
260
|
+
` for (let tick = 0; tick <= 4; tick++) {`,
|
|
261
|
+
` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
|
|
262
|
+
` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
|
|
263
|
+
` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
|
|
264
|
+
` }`,
|
|
265
|
+
` for (let index = 0; index < count; index++) {`,
|
|
266
|
+
` const value = Math.max(0, nums[index] || 0); const barHeight = value / max * plotHeight;`,
|
|
267
|
+
` const x = left + index * gap + (gap - barWidth) / 2; const y = top + plotHeight - barHeight;`,
|
|
268
|
+
` body += '<rect x="' + x + '" y="' + y + '" width="' + barWidth + '" height="' + barHeight + '" rx="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
|
|
269
|
+
` body += __vizText(left + index * gap + gap / 2, height - 24, names[index] == null ? '' : names[index], 12, opt.muted, 'middle', 400);`,
|
|
270
|
+
` }`,
|
|
271
|
+
` return __svgImage(width, height, body, opt);`,
|
|
272
|
+
`}`,
|
|
273
|
+
`function __lineChart(title, labels, values, options) {`,
|
|
274
|
+
` const opt = __vizOptions(options);`,
|
|
275
|
+
` const names = Array.isArray(labels) ? labels : [];`,
|
|
276
|
+
` const nums = (Array.isArray(values) ? values : []).map(value => Number(value) || 0);`,
|
|
277
|
+
` const count = Math.max(names.length, nums.length, 2);`,
|
|
278
|
+
` const width = Number(opt.width) || 720;`,
|
|
279
|
+
` const height = Number(opt.height) || 420;`,
|
|
280
|
+
` const left = 62; const right = 24; const top = title ? 68 : 28; const bottom = 58;`,
|
|
281
|
+
` const plotWidth = Math.max(1, width - left - right);`,
|
|
282
|
+
` const plotHeight = Math.max(1, height - top - bottom);`,
|
|
283
|
+
` const max = Math.max(1, ...nums.map(value => Math.max(0, value)));`,
|
|
284
|
+
` let body = '';`,
|
|
285
|
+
` if (title) body += __vizText(width / 2, 34, title, 20, opt.foreground, 'middle', 700);`,
|
|
286
|
+
` for (let tick = 0; tick <= 4; tick++) {`,
|
|
287
|
+
` const value = max * tick / 4; const y = top + plotHeight - value / max * plotHeight;`,
|
|
288
|
+
` body += '<line x1="' + left + '" y1="' + y + '" x2="' + (width - right) + '" y2="' + y + '" stroke="' + __svgEscape(opt.grid) + '" stroke-width="1"/>';`,
|
|
289
|
+
` body += __vizText(left - 10, y + 4, Math.round(value), 11, opt.muted, 'end', 400);`,
|
|
290
|
+
` }`,
|
|
291
|
+
` const points = nums.map((value, index) => {`,
|
|
292
|
+
` const x = left + (count === 1 ? plotWidth / 2 : index * plotWidth / (count - 1));`,
|
|
293
|
+
` const y = top + plotHeight - Math.max(0, value) / max * plotHeight;`,
|
|
294
|
+
` return { x, y, label: names[index] == null ? '' : names[index] };`,
|
|
295
|
+
` });`,
|
|
296
|
+
` if (points.length) {`,
|
|
297
|
+
` 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(' ') + '"/>';`,
|
|
298
|
+
` for (const point of points) {`,
|
|
299
|
+
` body += '<circle cx="' + point.x + '" cy="' + point.y + '" r="5" fill="' + __svgEscape(opt.accent) + '"/>';`,
|
|
300
|
+
` body += __vizText(point.x, height - 24, point.label, 12, opt.muted, 'middle', 400);`,
|
|
301
|
+
` }`,
|
|
302
|
+
` }`,
|
|
303
|
+
` return __svgImage(width, height, body, opt);`,
|
|
304
|
+
`}`,
|
|
305
|
+
`function __saveImage(file, image) {`,
|
|
306
|
+
` const target = String(file);`,
|
|
307
|
+
` __vizFs.writeFileSync(target, String(image == null ? '' : image), 'utf8');`,
|
|
308
|
+
` return target;`,
|
|
309
|
+
`}`,
|
|
310
|
+
`function __imageDataUri(image) {`,
|
|
311
|
+
` return 'data:image/svg+xml;base64,' + Buffer.from(String(image == null ? '' : image), 'utf8').toString('base64');`,
|
|
312
|
+
`}`,
|
|
313
|
+
].join('\n'),
|
|
221
314
|
// v1.0.1 — process execution (child processes).
|
|
222
315
|
process: [
|
|
223
316
|
`const { execFile } = require('child_process');`,
|
|
@@ -386,8 +479,9 @@ const BUILTIN_DECLARATIONS = {
|
|
|
386
479
|
// lifecycle and messages.upsert normalization. PlainScript programs only ever
|
|
387
480
|
// see __whatsappStart/__whatsappOnMessage/__whatsappReply.
|
|
388
481
|
whatsapp: [
|
|
389
|
-
`const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {`,
|
|
482
|
+
`const { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload } = (() => {`,
|
|
390
483
|
` let sock = null;`,
|
|
484
|
+
` let __waBaileysPkg = '@qwerty-xcv/baileys';`,
|
|
391
485
|
` const handlers = [];`,
|
|
392
486
|
` const __waSilentLogger = (() => {`,
|
|
393
487
|
` const noop = () => {};`,
|
|
@@ -412,21 +506,95 @@ const BUILTIN_DECLARATIONS = {
|
|
|
412
506
|
` }`,
|
|
413
507
|
` function __waExtractText(content) {`,
|
|
414
508
|
` if (!content) return '';`,
|
|
415
|
-
`
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
509
|
+
` const c = content;`,
|
|
510
|
+
` if (c.conversation != null) return String(c.conversation);`,
|
|
511
|
+
` if (c.extendedTextMessage && c.extendedTextMessage.text != null) return String(c.extendedTextMessage.text);`,
|
|
512
|
+
` if (c.imageMessage && c.imageMessage.caption != null) return String(c.imageMessage.caption);`,
|
|
513
|
+
` if (c.videoMessage && c.videoMessage.caption != null) return String(c.videoMessage.caption);`,
|
|
514
|
+
` if (c.documentMessage && c.documentMessage.caption != null) return String(c.documentMessage.caption);`,
|
|
515
|
+
` if (c.audioMessage && c.audioMessage.caption != null) return String(c.audioMessage.caption);`,
|
|
516
|
+
` if (c.stickerMessage && c.stickerMessage.caption != null) return String(c.stickerMessage.caption);`,
|
|
517
|
+
` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return String(c.buttonsResponseMessage.selectedButtonId);`,
|
|
518
|
+
` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply && c.listResponseMessage.singleSelectReply.selectedRowId != null) return String(c.listResponseMessage.singleSelectReply.selectedRowId);`,
|
|
519
|
+
` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return String(c.templateButtonReplyMessage.selectedId);`,
|
|
520
|
+
` if (c.reactionMessage && c.reactionMessage.text != null) return String(c.reactionMessage.text);`,
|
|
521
|
+
` if (c.contactMessage && c.contactMessage.displayName != null) return String(c.contactMessage.displayName);`,
|
|
522
|
+
` if (c.contactsArrayMessage && c.contactsArrayMessage.contacts) return c.contactsArrayMessage.contacts.map(x => x.displayName || '').join(', ');`,
|
|
523
|
+
` if (c.locationMessage) return String(c.locationMessage.degreesLatitude) + ',' + String(c.locationMessage.degreesLongitude);`,
|
|
524
|
+
` if (c.groupInviteMessage) return String(c.groupInviteMessage.groupJid || '');`,
|
|
525
|
+
` if (c.pollCreationMessage && c.pollCreationMessage.name != null) return String(c.pollCreationMessage.name);`,
|
|
526
|
+
` return '';`,
|
|
527
|
+
` }`,
|
|
528
|
+
` function __waMessageType(content) {`,
|
|
529
|
+
` if (!content) return 'unknown';`,
|
|
530
|
+
` const c = content;`,
|
|
531
|
+
` if (c.conversation != null || c.extendedTextMessage) return 'text';`,
|
|
532
|
+
` if (c.imageMessage) return 'image';`,
|
|
533
|
+
` if (c.videoMessage) return 'video';`,
|
|
534
|
+
` if (c.audioMessage) return 'audio';`,
|
|
535
|
+
` if (c.documentMessage) return 'document';`,
|
|
536
|
+
` if (c.stickerMessage) return 'sticker';`,
|
|
537
|
+
` if (c.buttonsResponseMessage) return 'button';`,
|
|
538
|
+
` if (c.listResponseMessage) return 'list';`,
|
|
539
|
+
` if (c.templateButtonReplyMessage) return 'template-button';`,
|
|
540
|
+
` if (c.interactiveResponseMessage) return 'interactive';`,
|
|
541
|
+
` if (c.reactionMessage) return 'reaction';`,
|
|
542
|
+
` if (c.contactMessage) return 'contact';`,
|
|
543
|
+
` if (c.contactsArrayMessage) return 'contacts';`,
|
|
544
|
+
` if (c.locationMessage) return 'location';`,
|
|
545
|
+
` if (c.liveLocationMessage) return 'live-location';`,
|
|
546
|
+
` if (c.pollCreationMessage) return 'poll';`,
|
|
547
|
+
` if (c.pollUpdateMessage) return 'poll-update';`,
|
|
548
|
+
` if (c.groupInviteMessage) return 'group-invite';`,
|
|
549
|
+
` if (c.protocolMessage) return 'protocol';`,
|
|
550
|
+
` if (c.buttonsMessage) return 'buttons';`,
|
|
551
|
+
` if (c.templateMessage) return 'template';`,
|
|
552
|
+
` if (c.interactiveMessage) return 'interactive';`,
|
|
553
|
+
` return 'other';`,
|
|
554
|
+
` }`,
|
|
555
|
+
` function __waButtonId(content) {`,
|
|
556
|
+
` if (!content) return null;`,
|
|
557
|
+
` const c = content;`,
|
|
558
|
+
` if (c.buttonsResponseMessage && c.buttonsResponseMessage.selectedButtonId != null) return c.buttonsResponseMessage.selectedButtonId;`,
|
|
559
|
+
` if (c.listResponseMessage && c.listResponseMessage.singleSelectReply) return c.listResponseMessage.singleSelectReply.selectedRowId || null;`,
|
|
560
|
+
` if (c.templateButtonReplyMessage && c.templateButtonReplyMessage.selectedId != null) return c.templateButtonReplyMessage.selectedId;`,
|
|
561
|
+
` if (c.interactiveResponseMessage && c.interactiveResponseMessage.nativeFlowResponseMessage) {`,
|
|
562
|
+
` try { return JSON.parse(c.interactiveResponseMessage.nativeFlowResponseMessage.paramsJson).id || null; } catch (_) { return null; }`,
|
|
563
|
+
` }`,
|
|
564
|
+
` return null;`,
|
|
565
|
+
` }`,
|
|
566
|
+
` async function __waDownload(message, dest) {`,
|
|
567
|
+
` if (!sock) throw new Error('WhatsApp: the bot is not connected.');`,
|
|
568
|
+
` const { downloadMediaMessage } = require(__waBaileysPkg);`,
|
|
569
|
+
` const raw = message && message.raw ? message.raw : message;`,
|
|
570
|
+
` const buffer = await downloadMediaMessage(raw, 'buffer', {}, { logger: __waSilentLogger, reuploadRequest: sock.updateMediaMessage });`,
|
|
571
|
+
` if (!dest) return buffer;`,
|
|
572
|
+
` const fs = require('fs'), path = require('path');`,
|
|
573
|
+
` const dir = path.dirname(path.resolve(dest));`,
|
|
574
|
+
` if (dir && dir !== '.') fs.mkdirSync(dir, { recursive: true });`,
|
|
575
|
+
` fs.writeFileSync(dest, buffer);`,
|
|
576
|
+
` return dest;`,
|
|
419
577
|
` }`,
|
|
420
|
-
` async function
|
|
578
|
+
` async function __whatsappDownload(message, dest) {`,
|
|
579
|
+
` if (!message) throw new Error('WhatsApp: there is no message to download.');`,
|
|
580
|
+
` await __waDownload(message, dest);`,
|
|
581
|
+
` console.log('WhatsApp: saved media to ' + dest);`,
|
|
582
|
+
` }`,
|
|
583
|
+
` async function __whatsappReply(chat, value, extra) {`,
|
|
421
584
|
` if (!sock) throw new Error('WhatsApp: cannot reply because the bot is not connected yet.');`,
|
|
422
585
|
` const text = typeof value === 'string' ? value : JSON.stringify(value);`,
|
|
423
|
-
` return sock.sendMessage(chat, { text });`,
|
|
586
|
+
` return sock.sendMessage(chat, Object.assign({ text }, extra || {}));`,
|
|
587
|
+
` }`,
|
|
588
|
+
` async function __whatsappSend(chat, value) {`,
|
|
589
|
+
` if (!sock) throw new Error('WhatsApp: cannot send because the bot is not connected yet.');`,
|
|
590
|
+
` return sock.sendMessage(chat, typeof value === 'string' ? { text: value } : value);`,
|
|
424
591
|
` }`,
|
|
425
592
|
` function __whatsappOnMessage(handler) { handlers.push(handler); }`,
|
|
426
593
|
` async function __whatsappStart(options) {`,
|
|
427
|
-
`
|
|
594
|
+
` __waBaileysPkg = options.baileys || '@qwerty-xcv/baileys';`,
|
|
595
|
+
` const baileys = require(__waBaileysPkg);`,
|
|
428
596
|
` const makeWASocket = baileys.default;`,
|
|
429
|
-
` const { useMultiFileAuthState,
|
|
597
|
+
` const { useMultiFileAuthState, makeCacheableSignalKeyStore, DisconnectReason } = baileys;`,
|
|
430
598
|
` const folder = options.folder || 'plainscript-whatsapp-auth';`,
|
|
431
599
|
` const mode = options.login && options.login.mode === 'pairing' ? 'pairing' : 'qr';`,
|
|
432
600
|
` const pairingPhone = mode === 'pairing' ? __waNormalizePhone(options.login.phone) : null;`,
|
|
@@ -438,35 +606,45 @@ const BUILTIN_DECLARATIONS = {
|
|
|
438
606
|
// Auth/session persistence: useMultiFileAuthState stores credentials in
|
|
439
607
|
// the folder from `auth "<name>"`; saveCreds writes every update back.
|
|
440
608
|
` const { state, saveCreds } = await useMultiFileAuthState(folder);`,
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
//
|
|
444
|
-
//
|
|
609
|
+
// v2.14 — adopt the proven pairing-safe socket settings used by the
|
|
610
|
+
// reference Dual-Crasher build on the qwerty fork: a fixed Baileys protocol
|
|
611
|
+
// version and the exact browser fingerprint that survives WhatsApp's
|
|
612
|
+
// handshake without a 428 connection close.
|
|
445
613
|
` sock = makeWASocket({`,
|
|
446
|
-
`
|
|
447
|
-
` browser: ['
|
|
614
|
+
` version: [2, 2413, 1],`,
|
|
615
|
+
` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
|
|
448
616
|
` printQRInTerminal: false,`,
|
|
449
617
|
` syncFullHistory: false,`,
|
|
450
618
|
` markOnlineOnConnect: false,`,
|
|
619
|
+
` generateHighQualityLinkPreview: true,`,
|
|
451
620
|
` defaultQueryTimeoutMs: 60000,`,
|
|
452
|
-
` keepAliveIntervalMs:
|
|
621
|
+
` keepAliveIntervalMs: 50000,`,
|
|
453
622
|
` logger: __waSilentLogger,`,
|
|
454
623
|
` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
|
|
455
624
|
` });`,
|
|
456
625
|
` sock.ev.on('creds.update', saveCreds);`,
|
|
457
626
|
// Pairing codes are requested two seconds after socket creation — asking
|
|
458
|
-
// earlier aborts the link attempt. PlainScript
|
|
459
|
-
//
|
|
627
|
+
// earlier aborts the link attempt. PlainScript retries a few times (spam)
|
|
628
|
+
// so a dropped request never blocks linking. The number was validated at
|
|
629
|
+
// compile time; no custom suffix is applied.
|
|
460
630
|
` if (mode === 'pairing' && !state.creds.registered) {`,
|
|
461
|
-
`
|
|
462
|
-
`
|
|
463
|
-
` sock
|
|
464
|
-
`
|
|
465
|
-
`
|
|
466
|
-
`
|
|
467
|
-
`
|
|
468
|
-
`
|
|
469
|
-
`
|
|
631
|
+
` let attempts = 0;`,
|
|
632
|
+
` const requestCode = async () => {`,
|
|
633
|
+
` if (!sock || attempts >= 4) return;`,
|
|
634
|
+
` attempts += 1;`,
|
|
635
|
+
` try {`,
|
|
636
|
+
` sock.requestPairingCode(pairingPhone).then((rawCode) => {`,
|
|
637
|
+
` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
|
|
638
|
+
` console.log('WhatsApp pairing code: ' + pretty);`,
|
|
639
|
+
` console.log('Enter it on your phone: WhatsApp > Settings > Linked devices > Link a device > Link with phone number instead.');`,
|
|
640
|
+
` }).catch((error) => {`,
|
|
641
|
+
` console.error('WhatsApp pairing code failed: ' + error.message);`,
|
|
642
|
+
` });`,
|
|
643
|
+
` } catch (_) {}`,
|
|
644
|
+
` };`,
|
|
645
|
+
` setTimeout(async () => {`,
|
|
646
|
+
` await requestCode();`,
|
|
647
|
+
` setTimeout(requestCode, 4000);`,
|
|
470
648
|
` }, 2000);`,
|
|
471
649
|
` }`,
|
|
472
650
|
// Connection lifecycle: the QR code while linking, a friendly note on
|
|
@@ -511,16 +689,23 @@ const BUILTIN_DECLARATIONS = {
|
|
|
511
689
|
` if (key.fromMe) continue;`,
|
|
512
690
|
` const chat = key.remoteJid;`,
|
|
513
691
|
` if (!chat || chat === 'status@broadcast') continue;`,
|
|
692
|
+
` const content = __waUnwrap(msg.message);`,
|
|
514
693
|
` const message = {`,
|
|
515
|
-
` text: __waExtractText(
|
|
694
|
+
` text: __waExtractText(content),`,
|
|
695
|
+
` type: __waMessageType(content),`,
|
|
696
|
+
` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
|
|
697
|
+
` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
|
|
698
|
+
` buttonId: __waButtonId(content),`,
|
|
516
699
|
` chat,`,
|
|
517
700
|
` sender: key.participant || chat,`,
|
|
518
701
|
` name: msg.pushName || null,`,
|
|
519
702
|
` id: key.id || null,`,
|
|
520
703
|
` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
|
|
521
704
|
` isGroup: chat.endsWith('@g.us'),`,
|
|
705
|
+
` raw: msg,`,
|
|
706
|
+
` download: (dest) => __waDownload(msg, dest),`,
|
|
522
707
|
` };`,
|
|
523
|
-
` const ctx = { chat, message, reply: (value) => __whatsappReply(chat, value) };`,
|
|
708
|
+
` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
|
|
524
709
|
` for (const handler of handlers) {`,
|
|
525
710
|
` await handler(ctx);`,
|
|
526
711
|
` }`,
|
|
@@ -535,7 +720,107 @@ const BUILTIN_DECLARATIONS = {
|
|
|
535
720
|
` };`,
|
|
536
721
|
` await connect();`,
|
|
537
722
|
` }`,
|
|
538
|
-
`
|
|
723
|
+
` async function __whatsappPair(phone, onCode, onOpen) {`,
|
|
724
|
+
` const digits = __waNormalizePhone(phone);`,
|
|
725
|
+
` const baileys = require(__waBaileysPkg);`,
|
|
726
|
+
` const makeWASocket = baileys.default;`,
|
|
727
|
+
` const { useMultiFileAuthState, makeCacheableSignalKeyStore } = baileys;`,
|
|
728
|
+
` const { state, saveCreds } = await useMultiFileAuthState('whatsapp-session');`,
|
|
729
|
+
` let pairSock = makeWASocket({`,
|
|
730
|
+
` version: [2, 2413, 1],`,
|
|
731
|
+
` browser: ['Mac Os', 'chrome', '121.0.6167.159'],`,
|
|
732
|
+
` printQRInTerminal: false,`,
|
|
733
|
+
` syncFullHistory: false,`,
|
|
734
|
+
` markOnlineOnConnect: false,`,
|
|
735
|
+
` generateHighQualityLinkPreview: true,`,
|
|
736
|
+
` defaultQueryTimeoutMs: 60000,`,
|
|
737
|
+
` keepAliveIntervalMs: 50000,`,
|
|
738
|
+
` logger: __waSilentLogger,`,
|
|
739
|
+
` auth: { creds: state.creds, keys: makeCacheableSignalKeyStore(state.keys, __waSilentLogger) },`,
|
|
740
|
+
` });`,
|
|
741
|
+
` pairSock.ev.on('creds.update', saveCreds);`,
|
|
742
|
+
` pairSock.ev.on('messages.upsert', async (upsert) => {`,
|
|
743
|
+
` try {`,
|
|
744
|
+
` if (!upsert || upsert.type !== 'notify') return;`,
|
|
745
|
+
` for (const msg of upsert.messages || []) {`,
|
|
746
|
+
` const key = msg.key || {};`,
|
|
747
|
+
` if (key.fromMe) continue;`,
|
|
748
|
+
` const chat = key.remoteJid;`,
|
|
749
|
+
` if (!chat || chat === 'status@broadcast') continue;`,
|
|
750
|
+
` const content = __waUnwrap(msg.message);`,
|
|
751
|
+
` const message = {`,
|
|
752
|
+
` text: __waExtractText(content),`,
|
|
753
|
+
` type: __waMessageType(content),`,
|
|
754
|
+
` mtype: content ? (Object.keys(content)[0] || 'unknown') : 'unknown',`,
|
|
755
|
+
` caption: (content && (content.imageMessage || content.videoMessage || content.documentMessage || content.audioMessage || {}).caption) || null,`,
|
|
756
|
+
` buttonId: __waButtonId(content),`,
|
|
757
|
+
` chat,`,
|
|
758
|
+
` sender: key.participant || chat,`,
|
|
759
|
+
` name: msg.pushName || null,`,
|
|
760
|
+
` id: key.id || null,`,
|
|
761
|
+
` time: Number(msg.messageTimestamp) > 0 ? Number(msg.messageTimestamp) * 1000 : Date.now(),`,
|
|
762
|
+
` isGroup: chat.endsWith('@g.us'),`,
|
|
763
|
+
` raw: msg,`,
|
|
764
|
+
` download: (dest) => __waDownload(msg, dest),`,
|
|
765
|
+
` };`,
|
|
766
|
+
` const ctx = { chat, message, reply: (value, extra) => __whatsappReply(chat, value, extra), send: (to, value) => __whatsappSend(to || chat, value) };`,
|
|
767
|
+
` for (const handler of handlers) {`,
|
|
768
|
+
` await handler(ctx);`,
|
|
769
|
+
` }`,
|
|
770
|
+
` }`,
|
|
771
|
+
` } catch (error) {`,
|
|
772
|
+
` console.error(error);`,
|
|
773
|
+
` }`,
|
|
774
|
+
` });`,
|
|
775
|
+
` if (onCode) {`,
|
|
776
|
+
` await new Promise((resolve) => {`,
|
|
777
|
+
` let attempts = 0;`,
|
|
778
|
+
` const requestCode = async () => {`,
|
|
779
|
+
` if (!pairSock || attempts >= 4) { resolve(); return; }`,
|
|
780
|
+
` attempts += 1;`,
|
|
781
|
+
` try {`,
|
|
782
|
+
` pairSock.requestPairingCode(digits).then((rawCode) => {`,
|
|
783
|
+
` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
|
|
784
|
+
` console.log('WhatsApp pairing code: ' + pretty);`,
|
|
785
|
+
` onCode(pretty);`,
|
|
786
|
+
` resolve();`,
|
|
787
|
+
` }).catch((error) => {`,
|
|
788
|
+
` console.error('WhatsApp pairing code failed: ' + error.message);`,
|
|
789
|
+
` resolve();`,
|
|
790
|
+
` });`,
|
|
791
|
+
` } catch (_) { resolve(); }`,
|
|
792
|
+
` };`,
|
|
793
|
+
` setTimeout(async () => {`,
|
|
794
|
+
` await requestCode();`,
|
|
795
|
+
` setTimeout(requestCode, 4000);`,
|
|
796
|
+
` }, 2000);`,
|
|
797
|
+
` });`,
|
|
798
|
+
` } else {`,
|
|
799
|
+
` await new Promise((resolve) => {`,
|
|
800
|
+
` let attempts = 0;`,
|
|
801
|
+
` const requestCode = async () => {`,
|
|
802
|
+
` if (!pairSock || attempts >= 4) { resolve(); return; }`,
|
|
803
|
+
` attempts += 1;`,
|
|
804
|
+
` try {`,
|
|
805
|
+
` pairSock.requestPairingCode(digits).then((rawCode) => {`,
|
|
806
|
+
` const pretty = String(rawCode || '').replace(/[^A-Za-z0-9]/g, '').replace(/(.{4})(?=.)/g, '$1-');`,
|
|
807
|
+
` console.log('WhatsApp pairing code: ' + pretty);`,
|
|
808
|
+
` resolve();`,
|
|
809
|
+
` }).catch((error) => {`,
|
|
810
|
+
` console.error('WhatsApp pairing code failed: ' + error.message);`,
|
|
811
|
+
` resolve();`,
|
|
812
|
+
` });`,
|
|
813
|
+
` } catch (_) { resolve(); }`,
|
|
814
|
+
` };`,
|
|
815
|
+
` setTimeout(async () => {`,
|
|
816
|
+
` await requestCode();`,
|
|
817
|
+
` setTimeout(requestCode, 4000);`,
|
|
818
|
+
` }, 2000);`,
|
|
819
|
+
` });`,
|
|
820
|
+
` }`,
|
|
821
|
+
` return digits;`,
|
|
822
|
+
` }`,
|
|
823
|
+
` return { __whatsappStart, __whatsappPair, __whatsappOnMessage, __whatsappReply, __whatsappSend, __whatsappDownload };`,
|
|
539
824
|
`})();`,
|
|
540
825
|
].join('\n'),
|
|
541
826
|
// v2.1.1 — HTTP client runtime on the global fetch API (Node.js 18+).
|
|
@@ -575,7 +860,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
575
860
|
` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
|
|
576
861
|
`}`,
|
|
577
862
|
].join('\n'),
|
|
578
|
-
//
|
|
863
|
+
// v2.2.0 — provider-neutral AI runtime. `chat` and `embedText` speak
|
|
579
864
|
// OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
|
|
580
865
|
// and DeepSeek. A custom `base` and `key` can be supplied per call.
|
|
581
866
|
ai: [
|
|
@@ -989,7 +1274,91 @@ const BUILTIN_DECLARATIONS = {
|
|
|
989
1274
|
` };`,
|
|
990
1275
|
`}`,
|
|
991
1276
|
].join('\n'),
|
|
992
|
-
//
|
|
1277
|
+
// v2.2.0 -- MongoDB runtime. Connects to MongoDB and provides a
|
|
1278
|
+
// collection-oriented surface compatible with the existing SQL statement
|
|
1279
|
+
// forms (query, insert, update, delete, execute, transaction).
|
|
1280
|
+
mongodb: [
|
|
1281
|
+
`let __mongoClient = null;`,
|
|
1282
|
+
`let __mongoDb = null;`,
|
|
1283
|
+
`function __mongoCollection(name) {`,
|
|
1284
|
+
` if (!__mongoDb) throw new Error('MongoDB: not connected. Use "database <uri> using "mongo" [db <name>]" first.');`,
|
|
1285
|
+
` return __mongoDb.collection(name);`,
|
|
1286
|
+
`}`,
|
|
1287
|
+
`async function __mongoOpen(uri, dbName) {`,
|
|
1288
|
+
` if (__mongoClient) return __mongoDb;`,
|
|
1289
|
+
` const { MongoClient } = require('mongodb');`,
|
|
1290
|
+
` __mongoClient = new MongoClient(uri);`,
|
|
1291
|
+
` await __mongoClient.connect();`,
|
|
1292
|
+
` __mongoDb = __mongoClient.db(dbName || undefined);`,
|
|
1293
|
+
` __mongoDb.__query = async function(sql, params) {`,
|
|
1294
|
+
` const m = String(sql).match(/^\\s*SELECT\\s+(.+?)\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
|
|
1295
|
+
` if (!m) throw new Error('MongoDB query: use SELECT fields FROM collection [WHERE condition]');`,
|
|
1296
|
+
` const [, fields, collection, where] = m;`,
|
|
1297
|
+
` const coll = __mongoCollection(collection);`,
|
|
1298
|
+
` let filter = {};`,
|
|
1299
|
+
` if (where) {`,
|
|
1300
|
+
` const parts = where.split('=').map(s => s.trim());`,
|
|
1301
|
+
` if (parts.length === 2) filter[parts[0]] = params[0];`,
|
|
1302
|
+
` }`,
|
|
1303
|
+
` const projection = fields.trim() === '*' ? {} : Object.fromEntries(fields.split(',').map(f => [f.trim(), 1]));`,
|
|
1304
|
+
` return coll.find(filter).project(projection).toArray();`,
|
|
1305
|
+
` };`,
|
|
1306
|
+
` __mongoDb.__write = async function(sql, params) {`,
|
|
1307
|
+
` const m = String(sql).match(/^\\s*INSERT\\s+INTO\\s+(\\w+)\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)/i);`,
|
|
1308
|
+
` if (!m) throw new Error('MongoDB insert: use INSERT INTO collection (fields) VALUES (?, ...)');`,
|
|
1309
|
+
` const [, collection, fieldsStr, valuesStr] = m;`,
|
|
1310
|
+
` const fields = fieldsStr.split(',').map(f => f.trim());`,
|
|
1311
|
+
` const values = params;`,
|
|
1312
|
+
` const doc = {}; fields.forEach((f, i) => doc[f] = values[i]);`,
|
|
1313
|
+
` const coll = __mongoCollection(collection);`,
|
|
1314
|
+
` const result = await coll.insertOne(doc);`,
|
|
1315
|
+
` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
|
|
1316
|
+
` };`,
|
|
1317
|
+
` __mongoDb.__update = async function(sql, params) {`,
|
|
1318
|
+
` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
|
|
1319
|
+
` const m = String(sql).match(/^\\s*UPDATE\\s+(\\w+)\\s+SET\\s+(.+?)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
|
|
1320
|
+
` if (!m) throw new Error('MongoDB update: use UPDATE collection SET field = ? WHERE field = ?');`,
|
|
1321
|
+
` const [, collection, setClause, whereClause] = m;`,
|
|
1322
|
+
` const coll = __mongoCollection(collection);`,
|
|
1323
|
+
` const filter = {};`,
|
|
1324
|
+
` if (whereClause) {`,
|
|
1325
|
+
` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
|
|
1326
|
+
` if (wm) filter[wm[1]] = params[1] !== undefined ? params[1] : params[0];`,
|
|
1327
|
+
` }`,
|
|
1328
|
+
` const updateDoc = {};`,
|
|
1329
|
+
` const sm = setClause.match(/(\\w+)\\s*=\\s*\\?/);`,
|
|
1330
|
+
` if (sm) updateDoc[sm[1]] = params[0];`,
|
|
1331
|
+
` const result = await coll.updateMany(filter, { $set: updateDoc });`,
|
|
1332
|
+
` return { rowCount: result.modifiedCount };`,
|
|
1333
|
+
` };`,
|
|
1334
|
+
` __mongoDb.__delete = async function(sql, params) {`,
|
|
1335
|
+
` if (!__mongoDb) throw new Error('MongoDB: not connected');`,
|
|
1336
|
+
` const m = String(sql).match(/^\\s*DELETE\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
|
|
1337
|
+
` if (!m) throw new Error('MongoDB delete: use DELETE FROM collection WHERE field = ?');`,
|
|
1338
|
+
` const [, collection, whereClause] = m;`,
|
|
1339
|
+
` const coll = __mongoCollection(collection);`,
|
|
1340
|
+
` const filter = {};`,
|
|
1341
|
+
` if (whereClause) {`,
|
|
1342
|
+
` const wm = whereClause.match(/(\\w+)\\s*=\\s*\\?/);`,
|
|
1343
|
+
` if (wm) filter[wm[1]] = params[0];`,
|
|
1344
|
+
` }`,
|
|
1345
|
+
` const result = await coll.deleteMany(filter);`,
|
|
1346
|
+
` return { rowCount: result.deletedCount };`,
|
|
1347
|
+
` };`,
|
|
1348
|
+
` __mongoDb.__execute = async function(sql, params) {`,
|
|
1349
|
+
` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
|
|
1350
|
+
` };`,
|
|
1351
|
+
` return __mongoDb;`,
|
|
1352
|
+
`}`,
|
|
1353
|
+
`async function __mongoClose() {`,
|
|
1354
|
+
` if (__mongoClient) {`,
|
|
1355
|
+
` await __mongoClient.close();`,
|
|
1356
|
+
` __mongoClient = null;`,
|
|
1357
|
+
` __mongoDb = null;`,
|
|
1358
|
+
` }`,
|
|
1359
|
+
`}`,
|
|
1360
|
+
].join('\n'),
|
|
1361
|
+
// v1.2 -- Telegram runtime. Polling-based: no webhook endpoint needed.
|
|
993
1362
|
// Exposes `Telegram` (the raw API client) plus a `createTelegramBot(token)`
|
|
994
1363
|
// factory that registers handlers and polls getUpdates in a loop. `BOT` is
|
|
995
1364
|
// assigned by `bot "<token>"`. The token also falls back to the
|
|
@@ -1139,6 +1508,27 @@ const BUILTIN_DECLARATIONS = {
|
|
|
1139
1508
|
print: (args, context) => `console.log(${args.map(arg => generateExpr(arg, context)).join(', ')})`,
|
|
1140
1509
|
readFile: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
|
|
1141
1510
|
writeFile: (args, context) => `fs.writeFileSync(${generateExpr(args[0], context)}, ${generateExpr(args[1], context)}, 'utf8')`,
|
|
1511
|
+
// v2.4.0 — dependency-free SVG image and visualization helpers.
|
|
1512
|
+
svgImage: (args, context) => {
|
|
1513
|
+
ensureBuiltin(context, 'visualization');
|
|
1514
|
+
return `__svgImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1515
|
+
},
|
|
1516
|
+
barChart: (args, context) => {
|
|
1517
|
+
ensureBuiltin(context, 'visualization');
|
|
1518
|
+
return `__barChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1519
|
+
},
|
|
1520
|
+
lineChart: (args, context) => {
|
|
1521
|
+
ensureBuiltin(context, 'visualization');
|
|
1522
|
+
return `__lineChart(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1523
|
+
},
|
|
1524
|
+
saveImage: (args, context) => {
|
|
1525
|
+
ensureBuiltin(context, 'visualization');
|
|
1526
|
+
return `__saveImage(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1527
|
+
},
|
|
1528
|
+
imageDataUri: (args, context) => {
|
|
1529
|
+
ensureBuiltin(context, 'visualization');
|
|
1530
|
+
return `__imageDataUri(${args.map(arg => generateExpr(arg, context)).join(', ')})`;
|
|
1531
|
+
},
|
|
1142
1532
|
fileExists: (args, context) => `fs.existsSync(${generateExpr(args[0], context)})`,
|
|
1143
1533
|
read: (args, context) => `fs.readFileSync(${generateExpr(args[0], context)}, 'utf8')`,
|
|
1144
1534
|
sleep: (args, context) => `Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ${generateExpr(args[0], context)})`,
|
|
@@ -2223,15 +2613,28 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
2223
2613
|
markAsync(context);
|
|
2224
2614
|
return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
|
|
2225
2615
|
}
|
|
2616
|
+
if (_sqlDriver === 'mongo') {
|
|
2617
|
+
markAsync(context);
|
|
2618
|
+
return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
|
|
2619
|
+
}
|
|
2226
2620
|
switch (kind) {
|
|
2227
2621
|
case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
|
|
2228
2622
|
case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
|
|
2623
|
+
case 'update': return `db.prepare(\`${sql}\`).run(${args})`;
|
|
2624
|
+
case 'delete': return `db.prepare(\`${sql}\`).run(${args})`;
|
|
2229
2625
|
case 'execute': return `db.exec(\`${sql}\`)`;
|
|
2230
2626
|
default: throw new Error(`Unknown SQL kind "${kind}".`);
|
|
2231
2627
|
}
|
|
2232
2628
|
}
|
|
2233
2629
|
|
|
2234
|
-
function createGenerationContext() {
|
|
2630
|
+
function createGenerationContext(options = {}) {
|
|
2631
|
+
const sourceMap = options.sourceMap || false;
|
|
2632
|
+
const sourceFile = options.sourceFile || 'source.pln';
|
|
2633
|
+
const sourceContent = options.sourceContent || null;
|
|
2634
|
+
const builder = sourceMap ? new SourceMapGenerator({ file: options.outputFile || (sourceFile ? sourceFile.replace(/\.pln$/, '.js') : 'output.js') }) : null;
|
|
2635
|
+
if (builder && sourceFile) {
|
|
2636
|
+
builder.addSource(sourceFile, sourceContent);
|
|
2637
|
+
}
|
|
2235
2638
|
return {
|
|
2236
2639
|
requires: new Set(),
|
|
2237
2640
|
pendingPrelude: [],
|
|
@@ -2240,6 +2643,11 @@ function createGenerationContext() {
|
|
|
2240
2643
|
inFunction: false, // true while generating inside a function-like scope
|
|
2241
2644
|
inHandler: false, // true while generating a route/listener/404 response body
|
|
2242
2645
|
loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
|
|
2646
|
+
sourceMap,
|
|
2647
|
+
sourceFile,
|
|
2648
|
+
sourceContent,
|
|
2649
|
+
sourceMapBuilder: builder,
|
|
2650
|
+
currentLine: 1,
|
|
2243
2651
|
};
|
|
2244
2652
|
}
|
|
2245
2653
|
|
|
@@ -2271,9 +2679,11 @@ function emitRequire(context, moduleName, alias) {
|
|
|
2271
2679
|
const known = KNOWN_PACKAGES[bareName];
|
|
2272
2680
|
if (known) {
|
|
2273
2681
|
const boundAs = known.match(/const (\w+)/)[1];
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2682
|
+
if (alias !== boundAs) {
|
|
2683
|
+
throw new Error(
|
|
2684
|
+
`"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
|
|
2685
|
+
);
|
|
2686
|
+
}
|
|
2277
2687
|
}
|
|
2278
2688
|
const key = `${npmName}\0${alias}`;
|
|
2279
2689
|
if (context.requires.has(key)) return '';
|
|
@@ -2319,9 +2729,30 @@ function containsYield(statements) {
|
|
|
2319
2729
|
return false;
|
|
2320
2730
|
}
|
|
2321
2731
|
|
|
2322
|
-
function
|
|
2732
|
+
function recordMapping(node, context) {
|
|
2733
|
+
if (context && context.sourceMapBuilder && node && typeof node === 'object' && node.line) {
|
|
2734
|
+
context.sourceMapBuilder.addMapping({
|
|
2735
|
+
generated: { line: context.currentLine, column: 0 },
|
|
2736
|
+
original: { line: node.line, column: node.col || 1 },
|
|
2737
|
+
source: context.sourceFile,
|
|
2738
|
+
});
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
|
|
2742
|
+
function generate(ast, contextOrOptions = createGenerationContext(), options = {}) {
|
|
2743
|
+
if (ast.type !== 'Program') {
|
|
2323
2744
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
2324
2745
|
}
|
|
2746
|
+
|
|
2747
|
+
let context;
|
|
2748
|
+
let opts = options;
|
|
2749
|
+
if (contextOrOptions && contextOrOptions.requires instanceof Set) {
|
|
2750
|
+
context = contextOrOptions;
|
|
2751
|
+
} else {
|
|
2752
|
+
opts = contextOrOptions || {};
|
|
2753
|
+
context = createGenerationContext(opts);
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2325
2756
|
// v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
|
|
2326
2757
|
// (build pipeline) start clean.
|
|
2327
2758
|
__testCount = 0;
|
|
@@ -2329,8 +2760,27 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2329
2760
|
__inTest = false;
|
|
2330
2761
|
|
|
2331
2762
|
const preludeStart = context.pendingPrelude.length;
|
|
2332
|
-
|
|
2333
|
-
const
|
|
2763
|
+
|
|
2764
|
+
const bodyParts = [];
|
|
2765
|
+
for (const node of ast.body) {
|
|
2766
|
+
recordMapping(node, context);
|
|
2767
|
+
const js = generateStatement(node, '', context);
|
|
2768
|
+
if (js) {
|
|
2769
|
+
bodyParts.push(js);
|
|
2770
|
+
context.currentLine += js.split('\n').length;
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
|
|
2774
|
+
const preludeLines = context.pendingPrelude.slice(preludeStart);
|
|
2775
|
+
if (preludeLines.length > 0 && context.sourceMapBuilder) {
|
|
2776
|
+
for (const m of context.sourceMapBuilder.mappings) {
|
|
2777
|
+
m.generatedLine += preludeLines.length;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
|
|
2781
|
+
const body = bodyParts.join('\n');
|
|
2782
|
+
const lines = preludeLines.concat(body).filter(Boolean);
|
|
2783
|
+
|
|
2334
2784
|
// Top-level functions are the module's public API: export them so a built
|
|
2335
2785
|
// PlainScript file works as a normal CommonJS module (npm packages, require()).
|
|
2336
2786
|
// Harmless for programs that are only executed.
|
|
@@ -2376,7 +2826,16 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2376
2826
|
lines.push(`__runTests();`);
|
|
2377
2827
|
}
|
|
2378
2828
|
|
|
2379
|
-
|
|
2829
|
+
const jsCode = lines.join('\n');
|
|
2830
|
+
if (context.sourceMap && context.sourceMapBuilder) {
|
|
2831
|
+
return {
|
|
2832
|
+
code: jsCode,
|
|
2833
|
+
map: context.sourceMapBuilder,
|
|
2834
|
+
mapObject: context.sourceMapBuilder.toJSON(),
|
|
2835
|
+
};
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
return jsCode;
|
|
2380
2839
|
}
|
|
2381
2840
|
|
|
2382
2841
|
// ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
|
|
@@ -2529,9 +2988,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2529
2988
|
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
2530
2989
|
}
|
|
2531
2990
|
|
|
2532
|
-
//
|
|
2533
|
-
case 'ExportStatement':
|
|
2534
|
-
|
|
2991
|
+
// Enterprise & Intent-Oriented Exporting
|
|
2992
|
+
case 'ExportStatement': {
|
|
2993
|
+
if (node.exportAll && node.fromPath) {
|
|
2994
|
+
return `${indent}Object.assign(module.exports, require(${JSON.stringify(node.fromPath)}));`;
|
|
2995
|
+
}
|
|
2996
|
+
const names = node.names || (node.name ? [node.name] : []);
|
|
2997
|
+
if (node.fromPath) {
|
|
2998
|
+
const exports = names.map(n => `module.exports.${n} = require(${JSON.stringify(node.fromPath)}).${n};`);
|
|
2999
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
3000
|
+
}
|
|
3001
|
+
const exports = names.map(n => `module.exports.${n} = ${n};`);
|
|
3002
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
3003
|
+
}
|
|
2535
3004
|
|
|
2536
3005
|
// v1.0.1 — generators: `yield <expr>` (or bare `yield`).
|
|
2537
3006
|
case 'YieldStatement': {
|
|
@@ -2543,11 +3012,53 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2543
3012
|
: `${indent}yield;`;
|
|
2544
3013
|
}
|
|
2545
3014
|
|
|
3015
|
+
case 'PutStatement': {
|
|
3016
|
+
const target = generateExpr(node.mapVar, context);
|
|
3017
|
+
const key = generateExpr(node.key, context);
|
|
3018
|
+
const val = generateExpr(node.value, context);
|
|
3019
|
+
return `${indent}${target}.set(${key}, ${val});`;
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
case 'UnpackStatement': {
|
|
3023
|
+
const tuple = generateExpr(node.tupleExpr, context);
|
|
3024
|
+
const vars = node.variables.join(', ');
|
|
3025
|
+
return `${indent}let [${vars}] = ${tuple};`;
|
|
3026
|
+
}
|
|
3027
|
+
|
|
2546
3028
|
case 'ExpressionStatement':
|
|
2547
3029
|
return `${indent}${generateExpr(node.expression, context)};`;
|
|
2548
3030
|
|
|
2549
|
-
|
|
2550
|
-
|
|
3031
|
+
// Enterprise & Intent-Oriented Importing
|
|
3032
|
+
case 'ImportStatement': {
|
|
3033
|
+
if (!node.path) return '';
|
|
3034
|
+
const isLocalFile = node.path.startsWith('.') || node.path.startsWith('/') || node.path.startsWith('\\') || node.path.startsWith('@/') || node.path.endsWith('.pln');
|
|
3035
|
+
if (!isLocalFile) {
|
|
3036
|
+
// Third-party npm package import
|
|
3037
|
+
if (node.namespace) {
|
|
3038
|
+
const pkg = emitRequire(context, node.path, node.namespace);
|
|
3039
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
3040
|
+
}
|
|
3041
|
+
if (node.defaultImport) {
|
|
3042
|
+
const pkg = emitRequire(context, node.path, node.defaultImport);
|
|
3043
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
3044
|
+
}
|
|
3045
|
+
if (node.names && node.names.length > 0) {
|
|
3046
|
+
const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
3047
|
+
emitRequire(context, node.path, `__pkg_${reqName}`);
|
|
3048
|
+
const destructuring = `const { ${node.names.join(', ')} } = __pkg_${reqName};`;
|
|
3049
|
+
return `${indent}${destructuring}`;
|
|
3050
|
+
}
|
|
3051
|
+
const pkg = emitRequire(context, node.path, null);
|
|
3052
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
3053
|
+
}
|
|
3054
|
+
|
|
3055
|
+
// Local PlainScript module import
|
|
3056
|
+
if (node.namespace) {
|
|
3057
|
+
const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
3058
|
+
return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
|
|
3059
|
+
}
|
|
3060
|
+
return '';
|
|
3061
|
+
}
|
|
2551
3062
|
|
|
2552
3063
|
case 'UseStatement': {
|
|
2553
3064
|
const pkg = emitRequire(context, node.module, node.alias);
|
|
@@ -2743,6 +3254,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2743
3254
|
}
|
|
2744
3255
|
return `${indent}res.send(${generateExpr(node.value, context)});`;
|
|
2745
3256
|
|
|
3257
|
+
case 'ReplyFileStatement':
|
|
3258
|
+
if (!_inRoute) {
|
|
3259
|
+
throw new Error('"reply file" can only be used inside a route handler.\n\nExample:\n route get "/"\n reply file "public/index.html"\n done');
|
|
3260
|
+
}
|
|
3261
|
+
// Use path.resolve to handle relative paths correctly
|
|
3262
|
+
return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
|
|
3263
|
+
|
|
2746
3264
|
case 'ReplyJsonStatement': {
|
|
2747
3265
|
const props = node.properties
|
|
2748
3266
|
.map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
|
|
@@ -3031,13 +3549,30 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3031
3549
|
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
3032
3550
|
}
|
|
3033
3551
|
|
|
3552
|
+
// v2.2.0 — mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
|
|
3553
|
+
// Uses the mongodb driver; subsequent query/insert/update/delete/execute
|
|
3554
|
+
// statements compile to MongoDB collection operations.
|
|
3555
|
+
case 'MongoStatement': {
|
|
3556
|
+
_sqlDriver = 'mongo';
|
|
3557
|
+
_sqlClientVar = 'db';
|
|
3558
|
+
markAsync(context);
|
|
3559
|
+
ensureBuiltin(context, 'mongodb');
|
|
3560
|
+
const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
|
|
3561
|
+
return [
|
|
3562
|
+
emitRequire(context, 'mongodb'),
|
|
3563
|
+
`${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
|
|
3564
|
+
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
3565
|
+
}
|
|
3566
|
+
|
|
3034
3567
|
case 'QueryStatement':
|
|
3035
3568
|
return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
|
|
3036
3569
|
|
|
3037
3570
|
case 'InsertStatement':
|
|
3571
|
+
return `${indent}${emitSqlCall('write', node.sql, node.params, indent, context)};`;
|
|
3038
3572
|
case 'UpdateStatement':
|
|
3573
|
+
return `${indent}${emitSqlCall('update', node.sql, node.params, indent, context)};`;
|
|
3039
3574
|
case 'DeleteStatement':
|
|
3040
|
-
return `${indent}${emitSqlCall('
|
|
3575
|
+
return `${indent}${emitSqlCall('delete', node.sql, node.params, indent, context)};`;
|
|
3041
3576
|
|
|
3042
3577
|
case 'ExecuteStatement':
|
|
3043
3578
|
return `${indent}${emitSqlCall('execute', node.sql, node.params, indent, context)};`;
|
|
@@ -3045,7 +3580,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3045
3580
|
// v2.1.0 — remember <name> as query|insert|update|delete … done
|
|
3046
3581
|
case 'RememberSqlStatement': {
|
|
3047
3582
|
const kind = node.kind === 'query' ? 'query'
|
|
3048
|
-
: node.kind === 'execute' ? 'execute'
|
|
3583
|
+
: node.kind === 'execute' ? 'execute'
|
|
3584
|
+
: node.kind === 'update' ? 'update'
|
|
3585
|
+
: node.kind === 'delete' ? 'delete'
|
|
3586
|
+
: 'write';
|
|
3049
3587
|
return `${indent}let ${node.name} = ${emitSqlCall(kind, node.sql, node.params, indent, context)};`;
|
|
3050
3588
|
}
|
|
3051
3589
|
|
|
@@ -3117,26 +3655,32 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3117
3655
|
|
|
3118
3656
|
// whatsapp bot … done — starts the Baileys runtime with the declared
|
|
3119
3657
|
// auth folder and login mode, then registers every "on message" handler.
|
|
3658
|
+
// When no login line is present (login is null), only registers handlers
|
|
3659
|
+
// without auto-starting — used by hybrid bots that pair on-demand.
|
|
3120
3660
|
case 'WhatsAppBotStatement': {
|
|
3121
3661
|
ensureBuiltin(context, 'whatsapp');
|
|
3122
3662
|
markAsync(context);
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
loginArg
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3663
|
+
const lines = [];
|
|
3664
|
+
if (node.login) {
|
|
3665
|
+
// v2.1.2 — the pairing phone may be a compile-time literal or any
|
|
3666
|
+
// PlainScript expression (e.g. a variable filled by `ask`). Runtime values
|
|
3667
|
+
// are normalized/validated by __waNormalizePhone at startup.
|
|
3668
|
+
let loginArg;
|
|
3669
|
+
if (node.login.mode === 'pairing') {
|
|
3670
|
+
loginArg = node.login.phoneExpr != null
|
|
3671
|
+
? `{ mode: 'pairing', phone: (${generateExpr(node.login.phoneExpr, context)}) }`
|
|
3672
|
+
: `{ mode: 'pairing', phone: ${JSON.stringify(node.login.phone)} }`;
|
|
3673
|
+
} else {
|
|
3674
|
+
loginArg = `{ mode: 'qr' }`;
|
|
3675
|
+
}
|
|
3676
|
+
lines.push(
|
|
3677
|
+
`${indent}await __whatsappStart({`,
|
|
3678
|
+
`${indent} folder: ${JSON.stringify(node.authFolder)},`,
|
|
3679
|
+
`${indent} login: ${loginArg},`,
|
|
3680
|
+
...(node.baileysModule ? [`${indent} baileys: ${JSON.stringify(node.baileysModule)},`] : []),
|
|
3681
|
+
`${indent}});`,
|
|
3682
|
+
);
|
|
3133
3683
|
}
|
|
3134
|
-
const lines = [
|
|
3135
|
-
`${indent}await __whatsappStart({`,
|
|
3136
|
-
`${indent} folder: ${JSON.stringify(node.authFolder)},`,
|
|
3137
|
-
`${indent} login: ${loginArg},`,
|
|
3138
|
-
`${indent}});`,
|
|
3139
|
-
];
|
|
3140
3684
|
for (const handlerNode of node.handlers) {
|
|
3141
3685
|
const generated = generateStatement(handlerNode, indent, context);
|
|
3142
3686
|
if (generated) lines.push(generated);
|
|
@@ -3144,6 +3688,23 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3144
3688
|
return lines.join('\n');
|
|
3145
3689
|
}
|
|
3146
3690
|
|
|
3691
|
+
// pair whatsapp "<phone>" — on-demand WhatsApp pairing session.
|
|
3692
|
+
// When _inTelegram is true, relays the pairing code and connection status
|
|
3693
|
+
// to the Telegram chat via ctx.chatId.
|
|
3694
|
+
case 'WhatsAppPairStatement': {
|
|
3695
|
+
ensureBuiltin(context, 'whatsapp');
|
|
3696
|
+
markAsync(context);
|
|
3697
|
+
const phoneArg = node.phone.type === 'StringLiteral'
|
|
3698
|
+
? JSON.stringify(node.phone.value)
|
|
3699
|
+
: generateExpr(node.phone, context);
|
|
3700
|
+
if (_inTelegram) {
|
|
3701
|
+
return [
|
|
3702
|
+
`${indent}await __whatsappPair(${phoneArg}, (code) => Telegram.sendMessage(ctx.chatId, "WhatsApp pairing code: " + code), () => Telegram.sendMessage(ctx.chatId, "WhatsApp connected."));`,
|
|
3703
|
+
].join('\n');
|
|
3704
|
+
}
|
|
3705
|
+
return `${indent}await __whatsappPair(${phoneArg}, null, null);`;
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3147
3708
|
// on message … done — registers the handler that receives each incoming
|
|
3148
3709
|
// WhatsApp message as a normalized PlainScript record on `message`.
|
|
3149
3710
|
case 'WhatsAppOnMessageStatement': {
|
|
@@ -3169,6 +3730,16 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3169
3730
|
ensureBuiltin(context, 'whatsapp');
|
|
3170
3731
|
return `${indent}console.log(__waCtx.message);`;
|
|
3171
3732
|
|
|
3733
|
+
// v2.14 — download "<path>" — saves the current message's media to a file.
|
|
3734
|
+
// Handler-only by design: outside "on message" there is no message media.
|
|
3735
|
+
case 'WhatsAppDownloadStatement':
|
|
3736
|
+
if (!_inWhatsApp) {
|
|
3737
|
+
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');
|
|
3738
|
+
}
|
|
3739
|
+
ensureBuiltin(context, 'whatsapp');
|
|
3740
|
+
markAsync(context);
|
|
3741
|
+
return `${indent}await __whatsappDownload(__waCtx.message, ${JSON.stringify(node.filePath)});`;
|
|
3742
|
+
|
|
3172
3743
|
// v2.1.0 — mail, cache, scheduling, background jobs, websocket
|
|
3173
3744
|
|
|
3174
3745
|
case 'MailTransportStatement': {
|
|
@@ -3258,6 +3829,20 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3258
3829
|
`${indent}});`,
|
|
3259
3830
|
].join('\n');
|
|
3260
3831
|
|
|
3832
|
+
case 'StringTransformStatement': {
|
|
3833
|
+
const method = { lowercase: 'toLowerCase', uppercase: 'toUpperCase', trim: 'trim' }[node.kind];
|
|
3834
|
+
return `${indent}${node.target} = String(${node.target}).${method}();`;
|
|
3835
|
+
}
|
|
3836
|
+
|
|
3837
|
+
case 'CapitalizeWordsStatement':
|
|
3838
|
+
return `${indent}${node.target} = (${node.target}).map(w => String(w).charAt(0).toUpperCase() + String(w).slice(1));`;
|
|
3839
|
+
|
|
3840
|
+
case 'SplitStatement':
|
|
3841
|
+
return `${indent}${node.target} = String(${node.target}).split(${generateExpr(node.separator, context)});`;
|
|
3842
|
+
|
|
3843
|
+
case 'JoinStatement':
|
|
3844
|
+
return `${indent}(${node.target}) = (${node.target}).join(${generateExpr(node.separator, context)});`;
|
|
3845
|
+
|
|
3261
3846
|
case 'WebSocketServerStatement': {
|
|
3262
3847
|
ensureBuiltin(context, 'websocket');
|
|
3263
3848
|
const handler = (name, params, body) => {
|
|
@@ -3278,6 +3863,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3278
3863
|
ensureBuiltin(context, 'websocket');
|
|
3279
3864
|
return `${indent}__wsSend(socket, ${generateExpr(node.value, context)});`;
|
|
3280
3865
|
|
|
3866
|
+
case 'SendToStatement':
|
|
3867
|
+
ensureBuiltin(context, 'websocket');
|
|
3868
|
+
return `${indent}__wsSend(${generateExpr(node.connection, context)}, ${generateExpr(node.value, context)});`;
|
|
3869
|
+
|
|
3281
3870
|
case 'BroadcastStatement':
|
|
3282
3871
|
ensureBuiltin(context, 'websocket');
|
|
3283
3872
|
return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
|
|
@@ -3377,6 +3966,53 @@ function generateLValue(node, context) {
|
|
|
3377
3966
|
|
|
3378
3967
|
function generateExpr(node, context = createGenerationContext()) {
|
|
3379
3968
|
switch (node.type) {
|
|
3969
|
+
case 'DictionaryLiteral': {
|
|
3970
|
+
if (!node.pairs || node.pairs.length === 0) return 'new Map()';
|
|
3971
|
+
const pairs = node.pairs.map(p => `[${generateExpr(p.key, context)}, ${generateExpr(p.value, context)}]`);
|
|
3972
|
+
return `new Map([${pairs.join(', ')}])`;
|
|
3973
|
+
}
|
|
3974
|
+
case 'SetLiteral': {
|
|
3975
|
+
if (!node.elements || node.elements.length === 0) return 'new Set()';
|
|
3976
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3977
|
+
return `new Set([${elements.join(', ')}])`;
|
|
3978
|
+
}
|
|
3979
|
+
case 'SetFromExpression': {
|
|
3980
|
+
return `new Set(${generateExpr(node.iterable, context)})`;
|
|
3981
|
+
}
|
|
3982
|
+
case 'TupleLiteral': {
|
|
3983
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3984
|
+
return `Object.freeze([${elements.join(', ')}])`;
|
|
3985
|
+
}
|
|
3986
|
+
case 'SetAlgebraExpression': {
|
|
3987
|
+
const left = generateExpr(node.left, context);
|
|
3988
|
+
const right = generateExpr(node.right, context);
|
|
3989
|
+
if (node.op === 'union') {
|
|
3990
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3991
|
+
}
|
|
3992
|
+
if (node.op === 'intersection' || node.op === 'intersect') {
|
|
3993
|
+
return `new Set([...${left}].filter(__x => ${right}.has(__x)))`;
|
|
3994
|
+
}
|
|
3995
|
+
if (node.op === 'difference') {
|
|
3996
|
+
return `new Set([...${left}].filter(__x => !${right}.has(__x)))`;
|
|
3997
|
+
}
|
|
3998
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3999
|
+
}
|
|
4000
|
+
case 'CollectionReflectExpression': {
|
|
4001
|
+
const target = generateExpr(node.target, context);
|
|
4002
|
+
if (node.accessor === 'keys') {
|
|
4003
|
+
return `Array.from(${target}.keys())`;
|
|
4004
|
+
}
|
|
4005
|
+
if (node.accessor === 'values') {
|
|
4006
|
+
return `Array.from(${target}.values())`;
|
|
4007
|
+
}
|
|
4008
|
+
if (node.accessor === 'entries') {
|
|
4009
|
+
return `Array.from(${target}.entries())`;
|
|
4010
|
+
}
|
|
4011
|
+
if (node.accessor === 'size') {
|
|
4012
|
+
return `(${target} instanceof Map || ${target} instanceof Set ? ${target}.size : (${target} && ${target}.size !== undefined ? ${target}.size : ${target}?.length))`;
|
|
4013
|
+
}
|
|
4014
|
+
return `${target}.${node.accessor}`;
|
|
4015
|
+
}
|
|
3380
4016
|
case 'StringLiteral': return JSON.stringify(node.value);
|
|
3381
4017
|
case 'NumberLiteral': return String(node.value);
|
|
3382
4018
|
// v2.1.1 — boolean and null literals are PlainScript keywords.
|