plainscript-lang 1.0.3-beta → 1.0.3
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 +97 -120
- package/compiler/bundler.js +83 -12
- package/compiler/cli.js +62 -11
- package/compiler/dependency-detector.js +11 -0
- package/compiler/generator.js +280 -15
- package/compiler/lexer.js +2 -0
- package/compiler/parser.js +410 -28
- package/compiler/sourcemap.js +142 -0
- package/compiler/version.js +1 -1
- package/docs/CAPABILITY_GAP_AUDIT.md +17 -15
- package/docs/PLAINSCRIPT-SPEC.md +41 -39
- package/docs/index.html +60 -33
- package/docs/website/script.js +168 -19
- package/docs/website/style.css +187 -41
- 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/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 +1 -1
- package/examples/whatsapp-bot/qr.pln +1 -1
- package/package.json +3 -2
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.
|
|
@@ -575,7 +578,7 @@ const BUILTIN_DECLARATIONS = {
|
|
|
575
578
|
` return { ok: response.ok, status: response.status, headers: Object.fromEntries(response.headers.entries()), data };`,
|
|
576
579
|
`}`,
|
|
577
580
|
].join('\n'),
|
|
578
|
-
//
|
|
581
|
+
// v2.2.0 — provider-neutral AI runtime. `chat` and `embedText` speak
|
|
579
582
|
// OpenAI-compatible APIs, including Groq, OpenRouter, Together, Fireworks,
|
|
580
583
|
// and DeepSeek. A custom `base` and `key` can be supplied per call.
|
|
581
584
|
ai: [
|
|
@@ -989,7 +992,60 @@ const BUILTIN_DECLARATIONS = {
|
|
|
989
992
|
` };`,
|
|
990
993
|
`}`,
|
|
991
994
|
].join('\n'),
|
|
992
|
-
//
|
|
995
|
+
// v2.2.0 -- MongoDB runtime. Connects to MongoDB and provides a
|
|
996
|
+
// collection-oriented surface compatible with the existing SQL statement
|
|
997
|
+
// forms (query, insert, update, delete, execute, transaction).
|
|
998
|
+
mongodb: [
|
|
999
|
+
`let __mongoClient = null;`,
|
|
1000
|
+
`let __mongoDb = null;`,
|
|
1001
|
+
`function __mongoCollection(name) {`,
|
|
1002
|
+
` if (!__mongoDb) throw new Error('MongoDB: not connected. Use "database <uri> using "mongo" [db <name>]" first.');`,
|
|
1003
|
+
` return __mongoDb.collection(name);`,
|
|
1004
|
+
`}`,
|
|
1005
|
+
`async function __mongoOpen(uri, dbName) {`,
|
|
1006
|
+
` if (__mongoClient) return __mongoDb;`,
|
|
1007
|
+
` const { MongoClient } = require('mongodb');`,
|
|
1008
|
+
` __mongoClient = new MongoClient(uri);`,
|
|
1009
|
+
` await __mongoClient.connect();`,
|
|
1010
|
+
` __mongoDb = __mongoClient.db(dbName || undefined);`,
|
|
1011
|
+
` __mongoDb.__query = async function(sql, params) {`,
|
|
1012
|
+
` const m = String(sql).match(/^\\s*SELECT\\s+(.+?)\\s+FROM\\s+(\\w+)(?:\\s+WHERE\\s+(.+))?\\s*$/i);`,
|
|
1013
|
+
` if (!m) throw new Error('MongoDB query: use SELECT fields FROM collection [WHERE condition]');`,
|
|
1014
|
+
` const [, fields, collection, where] = m;`,
|
|
1015
|
+
` const coll = __mongoCollection(collection);`,
|
|
1016
|
+
` let filter = {};`,
|
|
1017
|
+
` if (where) {`,
|
|
1018
|
+
` const parts = where.split('=').map(s => s.trim());`,
|
|
1019
|
+
` if (parts.length === 2) filter[parts[0]] = params[0];`,
|
|
1020
|
+
` }`,
|
|
1021
|
+
` const projection = fields.trim() === '*' ? {} : Object.fromEntries(fields.split(',').map(f => [f.trim(), 1]));`,
|
|
1022
|
+
` return coll.find(filter).project(projection).toArray();`,
|
|
1023
|
+
` };`,
|
|
1024
|
+
` __mongoDb.__write = async function(sql, params) {`,
|
|
1025
|
+
` const m = String(sql).match(/^\\s*INSERT\\s+INTO\\s+(\\w+)\\s*\\(([^)]+)\\)\\s*VALUES\\s*\\(([^)]+)\\)/i);`,
|
|
1026
|
+
` if (!m) throw new Error('MongoDB insert: use INSERT INTO collection (fields) VALUES (?, ...)');`,
|
|
1027
|
+
` const [, collection, fieldsStr, valuesStr] = m;`,
|
|
1028
|
+
` const fields = fieldsStr.split(',').map(f => f.trim());`,
|
|
1029
|
+
` const values = params;`,
|
|
1030
|
+
` const doc = {}; fields.forEach((f, i) => doc[f] = values[i]);`,
|
|
1031
|
+
` const coll = __mongoCollection(collection);`,
|
|
1032
|
+
` const result = await coll.insertOne(doc);`,
|
|
1033
|
+
` return { insertedId: result.insertedId, acknowledged: result.acknowledged };`,
|
|
1034
|
+
` };`,
|
|
1035
|
+
` __mongoDb.__execute = async function(sql, params) {`,
|
|
1036
|
+
` throw new Error('MongoDB execute: use query/insert/update/delete instead');`,
|
|
1037
|
+
` };`,
|
|
1038
|
+
` return __mongoDb;`,
|
|
1039
|
+
`}`,
|
|
1040
|
+
`async function __mongoClose() {`,
|
|
1041
|
+
` if (__mongoClient) {`,
|
|
1042
|
+
` await __mongoClient.close();`,
|
|
1043
|
+
` __mongoClient = null;`,
|
|
1044
|
+
` __mongoDb = null;`,
|
|
1045
|
+
` }`,
|
|
1046
|
+
`}`,
|
|
1047
|
+
].join('\n'),
|
|
1048
|
+
// v1.2 -- Telegram runtime. Polling-based: no webhook endpoint needed.
|
|
993
1049
|
// Exposes `Telegram` (the raw API client) plus a `createTelegramBot(token)`
|
|
994
1050
|
// factory that registers handlers and polls getUpdates in a loop. `BOT` is
|
|
995
1051
|
// assigned by `bot "<token>"`. The token also falls back to the
|
|
@@ -2223,6 +2279,13 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
2223
2279
|
markAsync(context);
|
|
2224
2280
|
return kind === 'query' ? `(await ${call}).rows` : `await ${call}`;
|
|
2225
2281
|
}
|
|
2282
|
+
if (_sqlDriver === 'mongo') {
|
|
2283
|
+
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
|
+
return `await ${_sqlClientVar}.__${kind}(\`${sql}\`, [${args}])`;
|
|
2288
|
+
}
|
|
2226
2289
|
switch (kind) {
|
|
2227
2290
|
case 'query': return `db.prepare(\`${sql}\`).all(${args})`;
|
|
2228
2291
|
case 'write': return `db.prepare(\`${sql}\`).run(${args})`;
|
|
@@ -2231,7 +2294,14 @@ function emitSqlCall(kind, sql, params, indent, context) {
|
|
|
2231
2294
|
}
|
|
2232
2295
|
}
|
|
2233
2296
|
|
|
2234
|
-
function createGenerationContext() {
|
|
2297
|
+
function createGenerationContext(options = {}) {
|
|
2298
|
+
const sourceMap = options.sourceMap || false;
|
|
2299
|
+
const sourceFile = options.sourceFile || 'source.pln';
|
|
2300
|
+
const sourceContent = options.sourceContent || null;
|
|
2301
|
+
const builder = sourceMap ? new SourceMapGenerator({ file: options.outputFile || (sourceFile ? sourceFile.replace(/\.pln$/, '.js') : 'output.js') }) : null;
|
|
2302
|
+
if (builder && sourceFile) {
|
|
2303
|
+
builder.addSource(sourceFile, sourceContent);
|
|
2304
|
+
}
|
|
2235
2305
|
return {
|
|
2236
2306
|
requires: new Set(),
|
|
2237
2307
|
pendingPrelude: [],
|
|
@@ -2240,6 +2310,11 @@ function createGenerationContext() {
|
|
|
2240
2310
|
inFunction: false, // true while generating inside a function-like scope
|
|
2241
2311
|
inHandler: false, // true while generating a route/listener/404 response body
|
|
2242
2312
|
loopDepth: 0, // >0 while generating inside a for-each / for-index / while loop
|
|
2313
|
+
sourceMap,
|
|
2314
|
+
sourceFile,
|
|
2315
|
+
sourceContent,
|
|
2316
|
+
sourceMapBuilder: builder,
|
|
2317
|
+
currentLine: 1,
|
|
2243
2318
|
};
|
|
2244
2319
|
}
|
|
2245
2320
|
|
|
@@ -2271,9 +2346,11 @@ function emitRequire(context, moduleName, alias) {
|
|
|
2271
2346
|
const known = KNOWN_PACKAGES[bareName];
|
|
2272
2347
|
if (known) {
|
|
2273
2348
|
const boundAs = known.match(/const (\w+)/)[1];
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2349
|
+
if (alias !== boundAs) {
|
|
2350
|
+
throw new Error(
|
|
2351
|
+
`"${bareName}" is part of PlainScript's built-in runtime and is already available as "${boundAs}". Remove "as ${alias}".`
|
|
2352
|
+
);
|
|
2353
|
+
}
|
|
2277
2354
|
}
|
|
2278
2355
|
const key = `${npmName}\0${alias}`;
|
|
2279
2356
|
if (context.requires.has(key)) return '';
|
|
@@ -2319,9 +2396,30 @@ function containsYield(statements) {
|
|
|
2319
2396
|
return false;
|
|
2320
2397
|
}
|
|
2321
2398
|
|
|
2322
|
-
function
|
|
2399
|
+
function recordMapping(node, context) {
|
|
2400
|
+
if (context && context.sourceMapBuilder && node && typeof node === 'object' && node.line) {
|
|
2401
|
+
context.sourceMapBuilder.addMapping({
|
|
2402
|
+
generated: { line: context.currentLine, column: 0 },
|
|
2403
|
+
original: { line: node.line, column: node.col || 1 },
|
|
2404
|
+
source: context.sourceFile,
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
function generate(ast, contextOrOptions = createGenerationContext(), options = {}) {
|
|
2410
|
+
if (ast.type !== 'Program') {
|
|
2323
2411
|
throw new Error(`Expected a Program node but got "${ast.type}".`);
|
|
2324
2412
|
}
|
|
2413
|
+
|
|
2414
|
+
let context;
|
|
2415
|
+
let opts = options;
|
|
2416
|
+
if (contextOrOptions && contextOrOptions.requires instanceof Set) {
|
|
2417
|
+
context = contextOrOptions;
|
|
2418
|
+
} else {
|
|
2419
|
+
opts = contextOrOptions || {};
|
|
2420
|
+
context = createGenerationContext(opts);
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2325
2423
|
// v1.0.1 — reset per-program test bookkeeping so repeated generate() calls
|
|
2326
2424
|
// (build pipeline) start clean.
|
|
2327
2425
|
__testCount = 0;
|
|
@@ -2329,8 +2427,27 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2329
2427
|
__inTest = false;
|
|
2330
2428
|
|
|
2331
2429
|
const preludeStart = context.pendingPrelude.length;
|
|
2332
|
-
|
|
2333
|
-
const
|
|
2430
|
+
|
|
2431
|
+
const bodyParts = [];
|
|
2432
|
+
for (const node of ast.body) {
|
|
2433
|
+
recordMapping(node, context);
|
|
2434
|
+
const js = generateStatement(node, '', context);
|
|
2435
|
+
if (js) {
|
|
2436
|
+
bodyParts.push(js);
|
|
2437
|
+
context.currentLine += js.split('\n').length;
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
|
|
2441
|
+
const preludeLines = context.pendingPrelude.slice(preludeStart);
|
|
2442
|
+
if (preludeLines.length > 0 && context.sourceMapBuilder) {
|
|
2443
|
+
for (const m of context.sourceMapBuilder.mappings) {
|
|
2444
|
+
m.generatedLine += preludeLines.length;
|
|
2445
|
+
}
|
|
2446
|
+
}
|
|
2447
|
+
|
|
2448
|
+
const body = bodyParts.join('\n');
|
|
2449
|
+
const lines = preludeLines.concat(body).filter(Boolean);
|
|
2450
|
+
|
|
2334
2451
|
// Top-level functions are the module's public API: export them so a built
|
|
2335
2452
|
// PlainScript file works as a normal CommonJS module (npm packages, require()).
|
|
2336
2453
|
// Harmless for programs that are only executed.
|
|
@@ -2376,7 +2493,16 @@ function generate(ast, context = createGenerationContext()) { if (ast.type !==
|
|
|
2376
2493
|
lines.push(`__runTests();`);
|
|
2377
2494
|
}
|
|
2378
2495
|
|
|
2379
|
-
|
|
2496
|
+
const jsCode = lines.join('\n');
|
|
2497
|
+
if (context.sourceMap && context.sourceMapBuilder) {
|
|
2498
|
+
return {
|
|
2499
|
+
code: jsCode,
|
|
2500
|
+
map: context.sourceMapBuilder,
|
|
2501
|
+
mapObject: context.sourceMapBuilder.toJSON(),
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
return jsCode;
|
|
2380
2506
|
}
|
|
2381
2507
|
|
|
2382
2508
|
// ── v1.0.1 — test DSL bookkeeping ───────────────────────────────────────────
|
|
@@ -2529,9 +2655,19 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2529
2655
|
return `${indent}__check(${JSON.stringify(node.op)}, ${a}, ${b});`;
|
|
2530
2656
|
}
|
|
2531
2657
|
|
|
2532
|
-
//
|
|
2533
|
-
case 'ExportStatement':
|
|
2534
|
-
|
|
2658
|
+
// Enterprise & Intent-Oriented Exporting
|
|
2659
|
+
case 'ExportStatement': {
|
|
2660
|
+
if (node.exportAll && node.fromPath) {
|
|
2661
|
+
return `${indent}Object.assign(module.exports, require(${JSON.stringify(node.fromPath)}));`;
|
|
2662
|
+
}
|
|
2663
|
+
const names = node.names || (node.name ? [node.name] : []);
|
|
2664
|
+
if (node.fromPath) {
|
|
2665
|
+
const exports = names.map(n => `module.exports.${n} = require(${JSON.stringify(node.fromPath)}).${n};`);
|
|
2666
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
2667
|
+
}
|
|
2668
|
+
const exports = names.map(n => `module.exports.${n} = ${n};`);
|
|
2669
|
+
return exports.map(e => `${indent}${e}`).join('\n');
|
|
2670
|
+
}
|
|
2535
2671
|
|
|
2536
2672
|
// v1.0.1 — generators: `yield <expr>` (or bare `yield`).
|
|
2537
2673
|
case 'YieldStatement': {
|
|
@@ -2543,11 +2679,53 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2543
2679
|
: `${indent}yield;`;
|
|
2544
2680
|
}
|
|
2545
2681
|
|
|
2682
|
+
case 'PutStatement': {
|
|
2683
|
+
const target = generateExpr(node.mapVar, context);
|
|
2684
|
+
const key = generateExpr(node.key, context);
|
|
2685
|
+
const val = generateExpr(node.value, context);
|
|
2686
|
+
return `${indent}${target}.set(${key}, ${val});`;
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
case 'UnpackStatement': {
|
|
2690
|
+
const tuple = generateExpr(node.tupleExpr, context);
|
|
2691
|
+
const vars = node.variables.join(', ');
|
|
2692
|
+
return `${indent}let [${vars}] = ${tuple};`;
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2546
2695
|
case 'ExpressionStatement':
|
|
2547
2696
|
return `${indent}${generateExpr(node.expression, context)};`;
|
|
2548
2697
|
|
|
2549
|
-
|
|
2550
|
-
|
|
2698
|
+
// Enterprise & Intent-Oriented Importing
|
|
2699
|
+
case 'ImportStatement': {
|
|
2700
|
+
if (!node.path) return '';
|
|
2701
|
+
const isLocalFile = node.path.startsWith('.') || node.path.startsWith('/') || node.path.startsWith('\\') || node.path.startsWith('@/') || node.path.endsWith('.pln');
|
|
2702
|
+
if (!isLocalFile) {
|
|
2703
|
+
// Third-party npm package import
|
|
2704
|
+
if (node.namespace) {
|
|
2705
|
+
const pkg = emitRequire(context, node.path, node.namespace);
|
|
2706
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2707
|
+
}
|
|
2708
|
+
if (node.defaultImport) {
|
|
2709
|
+
const pkg = emitRequire(context, node.path, node.defaultImport);
|
|
2710
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2711
|
+
}
|
|
2712
|
+
if (node.names && node.names.length > 0) {
|
|
2713
|
+
const reqName = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
2714
|
+
emitRequire(context, node.path, `__pkg_${reqName}`);
|
|
2715
|
+
const destructuring = `const { ${node.names.join(', ')} } = __pkg_${reqName};`;
|
|
2716
|
+
return `${indent}${destructuring}`;
|
|
2717
|
+
}
|
|
2718
|
+
const pkg = emitRequire(context, node.path, null);
|
|
2719
|
+
return pkg ? `${indent}${pkg}` : '';
|
|
2720
|
+
}
|
|
2721
|
+
|
|
2722
|
+
// Local PlainScript module import
|
|
2723
|
+
if (node.namespace) {
|
|
2724
|
+
const modVar = node.path.replace(/[^a-zA-Z0-9_$]/g, '_');
|
|
2725
|
+
return `${indent}const ${node.namespace} = typeof __module_${modVar} !== 'undefined' ? __module_${modVar} : require(${JSON.stringify(node.path)});`;
|
|
2726
|
+
}
|
|
2727
|
+
return '';
|
|
2728
|
+
}
|
|
2551
2729
|
|
|
2552
2730
|
case 'UseStatement': {
|
|
2553
2731
|
const pkg = emitRequire(context, node.module, node.alias);
|
|
@@ -2743,6 +2921,13 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
2743
2921
|
}
|
|
2744
2922
|
return `${indent}res.send(${generateExpr(node.value, context)});`;
|
|
2745
2923
|
|
|
2924
|
+
case 'ReplyFileStatement':
|
|
2925
|
+
if (!_inRoute) {
|
|
2926
|
+
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');
|
|
2927
|
+
}
|
|
2928
|
+
// Use path.resolve to handle relative paths correctly
|
|
2929
|
+
return `${indent}res.sendFile(require('path').resolve(${JSON.stringify(node.filePath)}));`;
|
|
2930
|
+
|
|
2746
2931
|
case 'ReplyJsonStatement': {
|
|
2747
2932
|
const props = node.properties
|
|
2748
2933
|
.map(p => `${JSON.stringify(p.key)}: ${generateExpr(p.value, context)}`)
|
|
@@ -3031,6 +3216,21 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3031
3216
|
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
3032
3217
|
}
|
|
3033
3218
|
|
|
3219
|
+
// v2.2.0 — mongo "<connection>" [db "<name>"]: MongoDB client bound to "db".
|
|
3220
|
+
// Uses the mongodb driver; subsequent query/insert/update/delete/execute
|
|
3221
|
+
// statements compile to MongoDB collection operations.
|
|
3222
|
+
case 'MongoStatement': {
|
|
3223
|
+
_sqlDriver = 'mongo';
|
|
3224
|
+
_sqlClientVar = 'db';
|
|
3225
|
+
markAsync(context);
|
|
3226
|
+
ensureBuiltin(context, 'mongodb');
|
|
3227
|
+
const dbArg = node.dbName ? `, ${generateExpr(node.dbName, context)}` : '';
|
|
3228
|
+
return [
|
|
3229
|
+
emitRequire(context, 'mongodb'),
|
|
3230
|
+
`${indent}const db = await __mongoOpen(${generateExpr(node.connection, context)}${dbArg});`,
|
|
3231
|
+
].filter(Boolean).map(line => line.startsWith('const ') ? `${indent}${line}` : line).join('\n');
|
|
3232
|
+
}
|
|
3233
|
+
|
|
3034
3234
|
case 'QueryStatement':
|
|
3035
3235
|
return `${indent}${emitSqlCall('query', node.sql, node.params, indent, context)};`;
|
|
3036
3236
|
|
|
@@ -3258,6 +3458,20 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3258
3458
|
`${indent}});`,
|
|
3259
3459
|
].join('\n');
|
|
3260
3460
|
|
|
3461
|
+
case 'StringTransformStatement': {
|
|
3462
|
+
const method = { lowercase: 'toLowerCase', uppercase: 'toUpperCase', trim: 'trim' }[node.kind];
|
|
3463
|
+
return `${indent}${node.target} = String(${node.target}).${method}();`;
|
|
3464
|
+
}
|
|
3465
|
+
|
|
3466
|
+
case 'CapitalizeWordsStatement':
|
|
3467
|
+
return `${indent}${node.target} = (${node.target}).map(w => String(w).charAt(0).toUpperCase() + String(w).slice(1));`;
|
|
3468
|
+
|
|
3469
|
+
case 'SplitStatement':
|
|
3470
|
+
return `${indent}${node.target} = String(${node.target}).split(${generateExpr(node.separator, context)});`;
|
|
3471
|
+
|
|
3472
|
+
case 'JoinStatement':
|
|
3473
|
+
return `${indent}(${node.target}) = (${node.target}).join(${generateExpr(node.separator, context)});`;
|
|
3474
|
+
|
|
3261
3475
|
case 'WebSocketServerStatement': {
|
|
3262
3476
|
ensureBuiltin(context, 'websocket');
|
|
3263
3477
|
const handler = (name, params, body) => {
|
|
@@ -3278,6 +3492,10 @@ function generateStatement(node, indent = '', context = createGenerationContext(
|
|
|
3278
3492
|
ensureBuiltin(context, 'websocket');
|
|
3279
3493
|
return `${indent}__wsSend(socket, ${generateExpr(node.value, context)});`;
|
|
3280
3494
|
|
|
3495
|
+
case 'SendToStatement':
|
|
3496
|
+
ensureBuiltin(context, 'websocket');
|
|
3497
|
+
return `${indent}__wsSend(${generateExpr(node.connection, context)}, ${generateExpr(node.value, context)});`;
|
|
3498
|
+
|
|
3281
3499
|
case 'BroadcastStatement':
|
|
3282
3500
|
ensureBuiltin(context, 'websocket');
|
|
3283
3501
|
return `${indent}__wsBroadcast(__wsServer, ${generateExpr(node.value, context)});`;
|
|
@@ -3377,6 +3595,53 @@ function generateLValue(node, context) {
|
|
|
3377
3595
|
|
|
3378
3596
|
function generateExpr(node, context = createGenerationContext()) {
|
|
3379
3597
|
switch (node.type) {
|
|
3598
|
+
case 'DictionaryLiteral': {
|
|
3599
|
+
if (!node.pairs || node.pairs.length === 0) return 'new Map()';
|
|
3600
|
+
const pairs = node.pairs.map(p => `[${generateExpr(p.key, context)}, ${generateExpr(p.value, context)}]`);
|
|
3601
|
+
return `new Map([${pairs.join(', ')}])`;
|
|
3602
|
+
}
|
|
3603
|
+
case 'SetLiteral': {
|
|
3604
|
+
if (!node.elements || node.elements.length === 0) return 'new Set()';
|
|
3605
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3606
|
+
return `new Set([${elements.join(', ')}])`;
|
|
3607
|
+
}
|
|
3608
|
+
case 'SetFromExpression': {
|
|
3609
|
+
return `new Set(${generateExpr(node.iterable, context)})`;
|
|
3610
|
+
}
|
|
3611
|
+
case 'TupleLiteral': {
|
|
3612
|
+
const elements = node.elements.map(e => generateExpr(e, context));
|
|
3613
|
+
return `Object.freeze([${elements.join(', ')}])`;
|
|
3614
|
+
}
|
|
3615
|
+
case 'SetAlgebraExpression': {
|
|
3616
|
+
const left = generateExpr(node.left, context);
|
|
3617
|
+
const right = generateExpr(node.right, context);
|
|
3618
|
+
if (node.op === 'union') {
|
|
3619
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3620
|
+
}
|
|
3621
|
+
if (node.op === 'intersection' || node.op === 'intersect') {
|
|
3622
|
+
return `new Set([...${left}].filter(__x => ${right}.has(__x)))`;
|
|
3623
|
+
}
|
|
3624
|
+
if (node.op === 'difference') {
|
|
3625
|
+
return `new Set([...${left}].filter(__x => !${right}.has(__x)))`;
|
|
3626
|
+
}
|
|
3627
|
+
return `new Set([...${left}, ...${right}])`;
|
|
3628
|
+
}
|
|
3629
|
+
case 'CollectionReflectExpression': {
|
|
3630
|
+
const target = generateExpr(node.target, context);
|
|
3631
|
+
if (node.accessor === 'keys') {
|
|
3632
|
+
return `Array.from(${target}.keys())`;
|
|
3633
|
+
}
|
|
3634
|
+
if (node.accessor === 'values') {
|
|
3635
|
+
return `Array.from(${target}.values())`;
|
|
3636
|
+
}
|
|
3637
|
+
if (node.accessor === 'entries') {
|
|
3638
|
+
return `Array.from(${target}.entries())`;
|
|
3639
|
+
}
|
|
3640
|
+
if (node.accessor === 'size') {
|
|
3641
|
+
return `(${target} instanceof Map || ${target} instanceof Set ? ${target}.size : (${target} && ${target}.size !== undefined ? ${target}.size : ${target}?.length))`;
|
|
3642
|
+
}
|
|
3643
|
+
return `${target}.${node.accessor}`;
|
|
3644
|
+
}
|
|
3380
3645
|
case 'StringLiteral': return JSON.stringify(node.value);
|
|
3381
3646
|
case 'NumberLiteral': return String(node.value);
|
|
3382
3647
|
// v2.1.1 — boolean and null literals are PlainScript keywords.
|
package/compiler/lexer.js
CHANGED
|
@@ -49,6 +49,7 @@ const TOKEN = {
|
|
|
49
49
|
RESPOND: 'RESPOND', // alias for reply
|
|
50
50
|
SEND_BACK: 'SEND_BACK', // alias for reply
|
|
51
51
|
JSON_KW: 'JSON_KW',
|
|
52
|
+
FILE_KW: 'FILE_KW', // for "reply file" and "serve file"
|
|
52
53
|
SERVE: 'SERVE',
|
|
53
54
|
SERVE_STATIC: 'SERVE_STATIC', // alias for serve folder
|
|
54
55
|
SERVE_PUBLIC: 'SERVE_PUBLIC', // alias for serve folder
|
|
@@ -209,6 +210,7 @@ const KEYWORDS = {
|
|
|
209
210
|
respond: TOKEN.RESPOND,
|
|
210
211
|
send_back: TOKEN.SEND_BACK,
|
|
211
212
|
json: TOKEN.JSON_KW,
|
|
213
|
+
file: TOKEN.FILE_KW,
|
|
212
214
|
serve: TOKEN.SERVE,
|
|
213
215
|
serve_static: TOKEN.SERVE_STATIC,
|
|
214
216
|
serve_public: TOKEN.SERVE_PUBLIC,
|