plainscript-lang 1.0.362 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +394 -54
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +239 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +453 -107
  6. package/compiler/ir.js +62 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +290 -0
  9. package/compiler/parser.js +820 -113
  10. package/compiler/type-checker.js +440 -0
  11. package/compiler/version.js +1 -1
  12. package/docs/CAPABILITY_GAP_AUDIT.md +19 -3
  13. package/docs/GAME-PROMPT.md +3 -3
  14. package/docs/PLAINSCRIPT-GRAMMAR.md +317 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +264 -5
  16. package/docs/V1.1-TYPED-COLLECTIONS-DESIGN.md +220 -0
  17. package/docs/index.html +5 -5
  18. package/docs/website/script.js +1 -1
  19. package/examples/ai-memory-cli.pln +221 -0
  20. package/examples/ai-memory.json +1 -0
  21. package/examples/ai-providers.pln +1 -1
  22. package/examples/arrays.pln +1 -1
  23. package/examples/async-errors.pln +1 -1
  24. package/examples/auth-api.pln +1 -1
  25. package/examples/auth-sessions.pln +1 -1
  26. package/examples/basics.pln +1 -1
  27. package/examples/bots.pln +1 -1
  28. package/examples/browser-interactive/README.md +1 -1
  29. package/examples/browser-interactive/src/interactive.pln +1 -1
  30. package/examples/cache-and-jobs.pln +1 -1
  31. package/examples/cache-schedule.pln +1 -1
  32. package/examples/canvas-game/README.md +1 -1
  33. package/examples/canvas-game/src/game.pln +1 -1
  34. package/examples/collections.pln +1 -1
  35. package/examples/compound-assignments.pln +24 -0
  36. package/examples/concurrency.pln +2 -2
  37. package/examples/conditions.pln +1 -1
  38. package/examples/database.pln +1 -1
  39. package/examples/day2.pln +1 -1
  40. package/examples/day3.pln +1 -1
  41. package/examples/deployment.pln +1 -1
  42. package/examples/email-send.pln +1 -1
  43. package/examples/error-handling.pln +1 -1
  44. package/examples/expressions.pln +1 -1
  45. package/examples/file-manager-cli.pln +51 -0
  46. package/examples/file-uploads.pln +1 -1
  47. package/examples/files-and-config.pln +1 -1
  48. package/examples/files.pln +1 -1
  49. package/examples/football-backend/app.pln +1 -1
  50. package/examples/functions.pln +1 -1
  51. package/examples/hello.pln +1 -1
  52. package/examples/http-client.pln +1 -1
  53. package/examples/http.pln +1 -1
  54. package/examples/id-verification/app.pln +1 -1
  55. package/examples/interactive-cli.pln +34 -0
  56. package/examples/javascript-library/README.md +1 -1
  57. package/examples/javascript-library/src/interop.pln +1 -1
  58. package/examples/json.pln +1 -1
  59. package/examples/loops.pln +1 -1
  60. package/examples/memoize-demo.pln +31 -0
  61. package/examples/modules/app.pln +1 -1
  62. package/examples/modules/main.pln +1 -1
  63. package/examples/modules/math.pln +1 -1
  64. package/examples/mongo.pln +1 -1
  65. package/examples/normalization-forms.pln +22 -0
  66. package/examples/objects.pln +1 -1
  67. package/examples/ocr.pln +1 -1
  68. package/examples/packages.pln +1 -1
  69. package/examples/random-cli.pln +32 -0
  70. package/examples/record-kinds.pln +1 -1
  71. package/examples/records.pln +1 -1
  72. package/examples/rest-api-fetch.pln +1 -1
  73. package/examples/rest-api.pln +1 -1
  74. package/examples/run-in-parallel.pln +25 -0
  75. package/examples/scheduled-tasks.pln +1 -1
  76. package/examples/search-and-filter.pln +1 -1
  77. package/examples/server.pln +1 -1
  78. package/examples/sessions-and-cookies.pln +1 -1
  79. package/examples/sqlite.pln +1 -1
  80. package/examples/start.pln +1 -1
  81. package/examples/stats-cli.pln +29 -0
  82. package/examples/stdlib.pln +1 -1
  83. package/examples/string-helpers.pln +23 -0
  84. package/examples/string-verbs.pln +1 -1
  85. package/examples/telegram-ai-bot.pln +1 -1
  86. package/examples/telegram-bot.pln +1 -1
  87. package/examples/terminal-cli.pln +11 -0
  88. package/examples/testing.pln +1 -1
  89. package/examples/three-dimensional/README.md +1 -1
  90. package/examples/three-dimensional/src/scene.pln +1 -1
  91. package/examples/todo-cli.pln +98 -0
  92. package/examples/typed-collections.pln +21 -0
  93. package/examples/web-api.pln +1 -1
  94. package/examples/web-app.pln +1 -1
  95. package/examples/websocket-server.pln +1 -1
  96. package/examples/websocket.pln +1 -1
  97. package/examples/whatsapp-bot/pairing.pln +1 -1
  98. package/examples/whatsapp-bot/qr.pln +1 -1
  99. package/package.json +13 -4
@@ -118,10 +118,78 @@ function resolveDependencies(entryPath) {
118
118
  return order;
119
119
  }
120
120
 
121
- // Compile all files in dependency order into one JavaScript string.
122
- function bundle(entryPath, options = {}) {
121
+ // Collects the names a file's own ExportStatements put on its module surface.
122
+ function getExportNames(ast) {
123
+ const names = [];
124
+ for (const node of ast.body) {
125
+ if (node.type !== 'ExportStatement' || node.fromPath) continue;
126
+ names.push(...(node.names || (node.name ? [node.name] : [])));
127
+ }
128
+ return names;
129
+ }
130
+
131
+ // Builds the export surface map for a resolved dependency graph:
132
+ // local import path (as written) -> exported names of that module. Used by
133
+ // namespace imports ("bring all from X as ns") which need the export surface
134
+ // to build live getter objects, and consumed by the shared generation context.
135
+ function buildSurfaces(files) {
136
+ const surfaces = new Map();
137
+ const astByAbs = new Map(files.map(f => [f.absPath, f.ast]));
138
+
139
+ for (const { absPath, ast } of files) {
140
+ const dir = path.dirname(absPath);
141
+ for (const node of ast.body) {
142
+ if (node.type === 'ImportStatement' && node.path && isLocalImportPath(node.path) && node.namespace) {
143
+ const resolvedAbs = resolveImportPath(dir, node.path);
144
+ const depAst = astByAbs.get(resolvedAbs);
145
+ if (depAst) {
146
+ // Union of explicit exports plus auto-exported function declarations
147
+ const explicit = getExportNames(depAst);
148
+ const funcs = depAst.body
149
+ .filter(n => n.type === 'FunctionDeclaration' && n.name)
150
+ .map(n => n.name);
151
+ const hasExplicit = depAst.body.some(n => n.type === 'ExportStatement');
152
+ const surface = hasExplicit ? explicit : [...new Set([...explicit, ...funcs])];
153
+ if (!surfaces.has(absPath)) surfaces.set(absPath, []);
154
+ surfaces.set(node.path, surface);
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ // Propagate re-exported surfaces (export ... from "...") until fixpoint so
161
+ // chains of re-exports resolve too.
162
+ for (let pass = 0; pass <= files.length; pass += 1) {
163
+ let changed = false;
164
+ for (const { absPath, ast } of files) {
165
+ for (const node of ast.body) {
166
+ if (node.type !== 'ExportStatement' || !node.fromPath || !isLocalImportPath(node.fromPath)) continue;
167
+ const resolvedAbs = resolveImportPath(path.dirname(absPath), node.fromPath);
168
+ if (!astByAbs.has(resolvedAbs)) continue;
169
+ const depSurface = surfaces.get(node.fromPath) || [];
170
+ const own = surfaces.get(absPath) || [];
171
+ const merged = [...new Set([...own, ...depSurface])];
172
+ if (merged.length !== own.length) {
173
+ surfaces.set(absPath, merged);
174
+ changed = true;
175
+ }
176
+ }
177
+ }
178
+ if (!changed) break;
179
+ }
180
+ return surfaces;
181
+ }
182
+
183
+ // Generates JavaScript for a whole resolved dependency graph with ONE shared
184
+ // generation context. This is the single authoritative multi-file pipeline:
185
+ // `bundle`, the CLI's compile stage, and validateSource all go through it so
186
+ // bundled programs behave identically no matter which command produced them.
187
+ function generateBundle(entryPath, options = {}) {
123
188
  const files = resolveDependencies(entryPath);
124
189
  const context = createGenerationContext(options);
190
+ context.bundled = true;
191
+ context.importSurfaces = buildSurfaces(files);
192
+
125
193
  const parts = files.map(({ absPath, ast }) => {
126
194
  const relPath = path.relative(process.cwd(), absPath).replace(/\\/g, '/') || path.basename(absPath);
127
195
  context.sourceFile = relPath;
@@ -134,6 +202,13 @@ function bundle(entryPath, options = {}) {
134
202
  const res = generate(ast, context);
135
203
  return typeof res === 'string' ? res : (res && res.code ? res.code : '');
136
204
  }).filter(js => js && js.trim() !== '');
205
+
206
+ return { files, context, parts };
207
+ }
208
+
209
+ // Compile all files in dependency order into one JavaScript string.
210
+ function bundle(entryPath, options = {}) {
211
+ const { context, parts } = generateBundle(entryPath, options);
137
212
  let js = parts.join('\n');
138
213
  if (context.needsAsync) {
139
214
  js = wrapAsync(js);
@@ -154,4 +229,4 @@ function bundle(entryPath, options = {}) {
154
229
  return js;
155
230
  }
156
231
 
157
- module.exports = { bundle, resolveDependencies };
232
+ module.exports = { bundle, generateBundle, buildSurfaces, resolveDependencies };
package/compiler/cli.js CHANGED
@@ -25,7 +25,9 @@ const { execFileSync } = require('child_process');
25
25
  const { tokenize } = require('./lexer');
26
26
  const { parse } = require('./parser');
27
27
  const { generate, createGenerationContext, wrapAsync } = require('./generator');
28
- const { bundle, resolveDependencies } = require('./bundler');
28
+ const { serializeIR } = require('./ir');
29
+ const { checkTypes } = require('./type-checker');
30
+ const { bundle, generateBundle, buildSurfaces, resolveDependencies } = require('./bundler');
29
31
  const { format } = require('./formatter');
30
32
  const { detectDependencies, PACKAGE_MAP, isBuiltinModule, splitPackageSpec } = require('./dependency-detector');
31
33
 
@@ -57,6 +59,7 @@ ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .pln compiles to readable Nod
57
59
  ${section('START')}
58
60
  plainscript new [name] Scaffold a new project with a working app.pln
59
61
  plainscript run <file.pln> Install missing deps, compile, execute
62
+ plainscript test [target] Run PlainScript test files
60
63
  plainscript start Build src/app.pln and run it from dist/
61
64
 
62
65
  ${section('BUILD & CHECK')}
@@ -67,6 +70,7 @@ ${section('BUILD & CHECK')}
67
70
  plainscript check [target] Validate imports + generate + JS output (no writes)
68
71
  target: a .pln file, a directory, or none = project scan
69
72
  --json emits deterministic machine-readable output
73
+ plainscript ir <file.pln> Print the backend-neutral compiler IR as JSON
70
74
  plainscript fmt <file.pln> Format a file in place
71
75
 
72
76
  ${section('PACKAGES')}
@@ -224,6 +228,24 @@ function discoverSources(srcDir, outDir, exclude) {
224
228
  // Project builds compile many files in one pass; per-file stage logs would
225
229
  // drown the useful output. Set before batch compilation, reset after.
226
230
  let QUIET_STAGES = false;
231
+ let VERBOSE = false;
232
+ // `--quiet` also disables the post-build per-file summary lines; keep the
233
+ // command-line intent separately so a batch build's internal silencing can be
234
+ // lifted without re-enabling chatter the user explicitly asked to mute.
235
+ let REQUESTED_QUIET = false;
236
+
237
+ // `--quiet` swaps out the banner-printing stage with a no-chatter one;
238
+ // `--verbose` always prints the timing detail.
239
+ function stageQuiet(label, fn) {
240
+ return fn();
241
+ }
242
+
243
+ function stageVerbose(label, fn) {
244
+ const t0 = Date.now();
245
+ const result = fn();
246
+ console.log(`${clrGreen('✓')} ${label} (${Date.now() - t0}ms)`);
247
+ return result;
248
+ }
227
249
 
228
250
  function stage(label, fn) {
229
251
  const t0 = Date.now();
@@ -381,6 +403,11 @@ function compile(filePath, options = {}) {
381
403
  });
382
404
  stage('Building dependency graph', () => files);
383
405
  stage('Checking runtime dependencies', () => ensureDependencies(files, true));
406
+ // Shared bundle pipeline: one context across the whole dependency graph so
407
+ // namespace imports get export surfaces and exports defer to end-of-file,
408
+ // exactly as in `bundle()`.
409
+ generationContext.bundled = true;
410
+ generationContext.importSurfaces = buildSurfaces(files);
384
411
  const parts = stage('Generating JavaScript', () =>
385
412
  files.map(({ absPath: fileAbs, ast }) => {
386
413
  const relPath = path.relative(process.cwd(), fileAbs).replace(/\\/g, '/') || path.basename(fileAbs);
@@ -404,6 +431,58 @@ function compile(filePath, options = {}) {
404
431
  }
405
432
  }
406
433
 
434
+ // Clean top-level failure surface: uncaught errors and unhandled rejections
435
+ // print one concise line instead of a Node module-loader stack trace, and the
436
+ // most common raw JavaScript runtime errors are translated into PlainScript
437
+ // wording with an actionable hint (v1.0.364). A raised user error keeps its
438
+ // exact message; only JS-native error shapes are translated. Guarded so
439
+ // browser-target builds (no process) and library consumers are untouched.
440
+ // With --sourcemap/-m the (source-mapped) stack is appended, giving real
441
+ // .pln line numbers for runtime failures.
442
+ const cleanErrorPrelude = [
443
+ `if (typeof process !== 'undefined' && typeof process.on === 'function') {`,
444
+ ` const __plainTranslate = (m) => {`,
445
+ ` const h = m.match(/^(.+?) is not a function$/);`,
446
+ ` if (h) {`,
447
+ ` const r = h[1];`,
448
+ ` const hint = /^[A-Za-z_$][\\w$]*$/.test(r)`,
449
+ ` ? 'check that ' + r + ' is defined with "make ' + r + '(...)" before calling it'`,
450
+ ` : 'check that the value is a function before calling it';`,
451
+ ` return 'Runtime error: ' + r + ' is not a function.\\n hint: ' + hint;`,
452
+ ` }`,
453
+ ` const pr = m.match(/^Cannot read propert(?:y|ies) of (undefined|null)(?: \\(reading '([^']*)'\\))?$/);`,
454
+ ` const prOld = m.match(/^Cannot read propert(?:y|ies) '([^']*)' of (undefined|null)$/);`,
455
+ ` if (pr || prOld) {`,
456
+ ` const prop = pr ? pr[2] : prOld[1];`,
457
+ ` const missing = (pr ? pr[1] : prOld[2]) === 'null' ? 'null' : 'undefined';`,
458
+ ` const access = prop != null && prop !== '' ? (/^\\d+$/.test(prop) ? 'x?.[' + prop + ']' : 'x?.' + prop) : 'x?.prop';`,
459
+ ` const where = prop != null && prop !== '' ? " '" + prop + "'" : '';`,
460
+ ` return 'Runtime error: tried to read' + where + ' from a missing value (' + missing + ').\\n hint: guard the access first (if x is null) or use optional access (' + access + ')';`,
461
+ ` }`,
462
+ ` if (m.includes(' is not iterable')) {`,
463
+ ` return 'Runtime error: a value is not iterable.\\n hint: loops, spread and destructuring need an array, string, or Map/Set';`,
464
+ ` }`,
465
+ ` if (m.endsWith('is not valid JSON')) {`,
466
+ ` return 'Runtime error: invalid JSON - ' + m + '\\n hint: decode untrusted text inside "try ... recover" to handle bad input';`,
467
+ ` }`,
468
+ ` return null;`,
469
+ ` };`,
470
+ ` const __plainReport = (e, rejection) => {`,
471
+ ` const m = (e && typeof e === 'object' && e.message != null) ? String(e.message) : String(e);`,
472
+ ` const t = __plainTranslate(m);`,
473
+ ` const head = rejection ? 'Unhandled rejection: ' : '';`,
474
+ ` console.error(head + (t !== null ? t : 'Error: ' + m));`,
475
+ ` if (process.execArgv && process.execArgv.includes('--enable-source-maps') && e && e.stack) {`,
476
+ ` console.error(e.stack);`,
477
+ ` }`,
478
+ ` process.exit(1);`,
479
+ ` };`,
480
+ ` process.on('uncaughtException', (e) => __plainReport(e, false));`,
481
+ ` process.on('unhandledRejection', (e) => __plainReport(e, true));`,
482
+ `}`,
483
+ ].join('\n');
484
+ js = cleanErrorPrelude + '\n' + js;
485
+
407
486
  if (options.sourceMap && generationContext.sourceMapBuilder) {
408
487
  return {
409
488
  code: js,
@@ -432,6 +511,14 @@ function nodeModulesSearchPaths(entryDir) {
432
511
  if (parent === dir) break;
433
512
  dir = parent;
434
513
  }
514
+ // `plainscript run` executes generated code from an OS temporary directory.
515
+ // A staged file outside the compiler project has no ancestor relationship
516
+ // with the compiler's own dependencies, so keep this installation as a
517
+ // fallback after project-local paths have had priority.
518
+ const compilerModules = path.resolve(__dirname, '..', 'node_modules');
519
+ if (fs.existsSync(compilerModules) && !paths.includes(compilerModules)) {
520
+ paths.push(compilerModules);
521
+ }
435
522
  return paths;
436
523
  }
437
524
 
@@ -440,7 +527,12 @@ async function cmdRun(filePath, extraArgs = []) {
440
527
  console.error('Usage: plainscript run <file.pln>');
441
528
  process.exit(1);
442
529
  }
443
- const isSourcemap = process.argv.includes('--sourcemap') || process.argv.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
530
+ // Only recognize sourcemap flags before a `--` separator; anything after it
531
+ // belongs to the program itself.
532
+ const __argv2 = process.argv.slice(2);
533
+ const __sep = __argv2.indexOf('--');
534
+ const __cliOnly = __sep === -1 ? __argv2 : __argv2.slice(0, __sep);
535
+ const isSourcemap = __cliOnly.includes('--sourcemap') || __cliOnly.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
444
536
  let js;
445
537
  if (isSourcemap) {
446
538
  const res = compile(filePath, { sourceMap: true, outputFile: 'out.js' });
@@ -448,7 +540,7 @@ async function cmdRun(filePath, extraArgs = []) {
448
540
  } else {
449
541
  js = compile(filePath);
450
542
  }
451
- console.log('');
543
+ if (!QUIET_STAGES) console.log('');
452
544
  // Execute from the entry file's directory so relative assets and CWD-based
453
545
  // behaviour match a direct `node` invocation.
454
546
  const entryDir = path.dirname(path.resolve(filePath));
@@ -469,7 +561,65 @@ async function cmdRun(filePath, extraArgs = []) {
469
561
  process.exit(1);
470
562
  }
471
563
  fs.rmSync(tmpDir, { recursive: true, force: true });
472
- console.log('\nDone.');
564
+ if (!QUIET_STAGES) console.log('\nDone.');
565
+ }
566
+
567
+ function discoverTestFiles(root) {
568
+ const files = [];
569
+ function walk(dir) {
570
+ if (!fs.existsSync(dir)) return;
571
+ for (const name of fs.readdirSync(dir).sort()) {
572
+ if (name.startsWith('.')) continue;
573
+ const full = path.join(dir, name);
574
+ const stat = fs.statSync(full);
575
+ if (stat.isDirectory()) walk(full);
576
+ else if (name.endsWith('.test.pln') || name.endsWith('.spec.pln')) files.push(full);
577
+ }
578
+ }
579
+ walk(root);
580
+ return files;
581
+ }
582
+
583
+ // Run native PlainScript test files through the same real CLI path as users.
584
+ // Explicit files/directories are supported; with no target, conventional
585
+ // tests/**/*.test.pln and tests/**/*.spec.pln files are discovered.
586
+ function cmdTest(target) {
587
+ let files;
588
+ if (target) {
589
+ const abs = path.resolve(target);
590
+ if (!fs.existsSync(abs)) {
591
+ console.error(`Test target not found: ${target}`);
592
+ process.exit(1);
593
+ }
594
+ files = fs.statSync(abs).isDirectory() ? discoverTestFiles(abs) : [abs];
595
+ } else {
596
+ files = discoverTestFiles(path.resolve('tests'));
597
+ if (files.length === 0) files = discoverTestFiles(path.resolve('test'));
598
+ }
599
+ if (files.length === 0) {
600
+ console.error('No PlainScript test files found. Name files *.test.pln or *.spec.pln, or pass a file explicitly.');
601
+ process.exit(1);
602
+ }
603
+ let failed = 0;
604
+ for (const file of files) {
605
+ const relative = path.relative(process.cwd(), file) || file;
606
+ try {
607
+ execFileSync(process.execPath, [__filename, 'run', file], {
608
+ stdio: 'inherit',
609
+ cwd: process.cwd(),
610
+ env: process.env,
611
+ });
612
+ if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${relative}`);
613
+ } catch (_) {
614
+ failed++;
615
+ console.error(`${clrRed('✗')} ${relative}`);
616
+ }
617
+ }
618
+ if (failed) {
619
+ console.error(`\n${failed} of ${files.length} PlainScript test file(s) failed.`);
620
+ process.exit(1);
621
+ }
622
+ if (!QUIET_STAGES) console.log(`\n${files.length} PlainScript test file(s) passed.`);
473
623
  }
474
624
 
475
625
  // Compile one entry and write it to outDir with its source name preserved,
@@ -506,7 +656,7 @@ function buildOne(filePath, srcDir, outDir, options = {}) {
506
656
 
507
657
  // `plainscript build <file.pln> -o <out.js>` - compile one entry to an explicit
508
658
  // output path (same compilation pipeline as buildOne, including source maps
509
- // when requested). Valuable for browser payloads such as the v1.0.362
659
+ // when requested). Valuable for browser payloads such as the v1.0.363
510
660
  // requestAnimationFrame / addEventListener helpers, which are meant to run as
511
661
  // a single script tag.
512
662
  function writeOneFile(filePath, outputFile) {
@@ -517,7 +667,12 @@ function writeOneFile(filePath, outputFile) {
517
667
  }
518
668
  const outPath = path.resolve(outputFile);
519
669
 
520
- const isSourcemap = process.argv.includes('--sourcemap') || process.argv.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
670
+ // Only recognize sourcemap flags before a `--` separator; anything after it
671
+ // belongs to the program itself.
672
+ const __argv2 = process.argv.slice(2);
673
+ const __sep = __argv2.indexOf('--');
674
+ const __cliOnly = __sep === -1 ? __argv2 : __argv2.slice(0, __sep);
675
+ const isSourcemap = __cliOnly.includes('--sourcemap') || __cliOnly.includes('-m') || process.env.PLAINSCRIPT_SOURCEMAP === 'true';
521
676
 
522
677
  let code, mapObject;
523
678
  if (isSourcemap) {
@@ -580,12 +735,12 @@ async function cmdBuild(filePath, outputPath) {
580
735
  outPath: buildOne(path.join(path.resolve(srcDir), rel), srcDir, outDir),
581
736
  }));
582
737
  } finally {
583
- QUIET_STAGES = false;
738
+ QUIET_STAGES = REQUESTED_QUIET;
584
739
  }
585
740
  for (const { source, outPath } of built) {
586
- console.log(`${clrGreen('✓')} ${source} -> ${outPath}`);
741
+ if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${source} -> ${outPath}`);
587
742
  }
588
- console.log(`\n${built.length} file(s) compiled to ${outDir}/.`);
743
+ if (!QUIET_STAGES) console.log(`\n${built.length} file(s) compiled to ${outDir}/.`);
589
744
  }
590
745
 
591
746
  async function cmdStart(extraArgs = []) {
@@ -631,7 +786,7 @@ done
631
786
  route get "/api/status"
632
787
  reply json
633
788
  status is "ok"
634
- version is "1.0.362"
789
+ version is "${VERSION}"
635
790
  done
636
791
  done
637
792
 
@@ -845,15 +1000,37 @@ function cmdUpdate() {
845
1000
  // file in dependency order, and verify the emitted JavaScript is syntactically
846
1001
  // valid - all without writing anything to disk. Returns a deterministic
847
1002
  // result record; `deps` are the npm packages the sources require.
1003
+ function annotateSourceTree(node, sourceFile, seen = new Set()) {
1004
+ if (!node || typeof node !== 'object' || seen.has(node)) return;
1005
+ seen.add(node);
1006
+ if (node.type) node.sourceFile = sourceFile;
1007
+ for (const value of Object.values(node)) {
1008
+ if (Array.isArray(value)) value.forEach(item => annotateSourceTree(item, sourceFile, seen));
1009
+ else if (value && typeof value === 'object') annotateSourceTree(value, sourceFile, seen);
1010
+ }
1011
+ }
1012
+
848
1013
  function validateSource(absPath) {
849
1014
  const rel = path.relative(process.cwd(), absPath) || absPath;
850
1015
  const t0 = Date.now();
851
1016
  try {
852
1017
  // resolveDependencies parses each file too, so a parse error anywhere in
853
1018
  // the import graph surfaces here with a "file.pln - Line:Col" prefix.
854
- const files = resolveDependencies(absPath);
855
- const context = createGenerationContext();
856
- let js = files.map(({ ast }) => generate(ast, context)).filter(s => s.trim()).join('\n');
1019
+ const { context, parts, files } = generateBundle(absPath);
1020
+ const typedBodies = files.map(file => {
1021
+ const relFile = path.relative(process.cwd(), file.absPath) || file.absPath;
1022
+ annotateSourceTree(file.ast, relFile);
1023
+ return file.ast ? file.ast.body : [];
1024
+ });
1025
+ const typedAst = { type: 'Program', body: typedBodies.flat() };
1026
+ const typeResult = checkTypes(typedAst);
1027
+ if (typeResult.diagnostics.length > 0) {
1028
+ const details = typeResult.diagnostics.map(item =>
1029
+ `${item.file || rel}:${item.range.start.line + 1}:${item.range.start.character + 1} ${item.code} ${item.message}`
1030
+ ).join('\n');
1031
+ throw new Error(`Static type checking failed:\n${details}`);
1032
+ }
1033
+ let js = parts.filter(s => s.trim()).join('\n');
857
1034
  if (context.needsAsync) js = wrapAsync(js);
858
1035
 
859
1036
  // The compiler must never emit broken JavaScript. Parsing the output with
@@ -948,7 +1125,7 @@ function cmdCheck(target, json) {
948
1125
 
949
1126
  for (const r of results) {
950
1127
  if (r.ok) {
951
- console.log(`${clrGreen('✓')} ${r.file} - ok${clrDim(` (${r.ms}ms)`)}`);
1128
+ if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${r.file} - ok${clrDim(` (${r.ms}ms)`)}`);
952
1129
  } else {
953
1130
  console.log(`${clrRed('✗')} ${r.file}`);
954
1131
  console.error(r.error);
@@ -959,7 +1136,7 @@ function cmdCheck(target, json) {
959
1136
  console.error(`\n${failed.length} of ${results.length} file(s) failed validation.`);
960
1137
  process.exit(1);
961
1138
  }
962
- if (results.length > 0) {
1139
+ if (results.length > 0 && !QUIET_STAGES) {
963
1140
  console.log(clrGreen(`\n✓ ${results.length} file(s) validated.`));
964
1141
  }
965
1142
  }
@@ -988,7 +1165,20 @@ function cmdFmt(filePath) {
988
1165
  function cmdVersion() {
989
1166
  console.log(`PlainScript v${VERSION}`);
990
1167
  }
991
-
1168
+ function cmdIR(filePath) {
1169
+ if (!filePath) {
1170
+ console.error('Usage: plainscript ir <file.pln>');
1171
+ process.exit(1);
1172
+ }
1173
+ const absPath = path.resolve(filePath);
1174
+ if (!fs.existsSync(absPath)) {
1175
+ console.error(`File not found: ${filePath}`);
1176
+ process.exit(1);
1177
+ }
1178
+ const source = fs.readFileSync(absPath, 'utf8');
1179
+ const ast = parse(tokenize(source));
1180
+ process.stdout.write(serializeIR(ast));
1181
+ }
992
1182
  function cmdHelp() {
993
1183
  console.log(HELP);
994
1184
  }
@@ -998,32 +1188,47 @@ function cmdHelp() {
998
1188
  async function main() {
999
1189
  const args = process.argv.slice(2);
1000
1190
 
1001
- // Global flags - recognized anywhere in the argument list.
1002
- const quiet = args.includes('--quiet');
1003
- const verbose = args.includes('--verbose');
1004
- const json = args.includes('--json');
1191
+ // `--` ends CLI flag parsing: everything after it belongs to the compiled
1192
+ // program (`plainscript run app.pln -- --port 8080`). Without this, programs
1193
+ // could never receive their own dash-prefixed arguments because the CLI
1194
+ // consumed every "--" flag anywhere in the list.
1195
+ const sepIdx = args.indexOf('--');
1196
+ const cliArgs = sepIdx === -1 ? args : args.slice(0, sepIdx);
1197
+ const progArgs = sepIdx === -1 ? [] : args.slice(sepIdx + 1);
1198
+
1199
+ // Global flags - recognized anywhere before `--`.
1200
+ const quiet = cliArgs.includes('--quiet');
1201
+ const verbose = cliArgs.includes('--verbose');
1202
+ const json = cliArgs.includes('--json');
1005
1203
  if (quiet) { stage = stageQuiet; QUIET_STAGES = true; }
1006
1204
  if (verbose) { stage = stageVerbose; VERBOSE = true; }
1205
+ if (quiet) REQUESTED_QUIET = true;
1206
+
1207
+ // Standard version flags - print and exit before any command dispatch.
1208
+ // `--version` anywhere (it is already filtered from program args); `-v`
1209
+ // only as a standalone command so `run app.pln -v` still passes -v through
1210
+ // to the compiled program.
1211
+ if (cliArgs.includes('--version') || (args.length === 1 && args[0] === '-v')) { cmdVersion(); return; }
1007
1212
 
1008
1213
  // Filter flags out to get the positional arguments.
1009
- const positional = args.filter(a => !a.startsWith('--'));
1214
+ const positional = cliArgs.filter(a => !a.startsWith('--'));
1010
1215
  const [, , command, fileArg] = positional.length >= 2
1011
1216
  ? ['', '', positional[0], positional[1]]
1012
1217
  : ['', '', positional[0] || '', ''];
1013
1218
 
1014
1219
  switch (command) {
1015
- case 'run': await cmdRun(fileArg, positional.slice(2)); break;
1220
+ case 'run': await cmdRun(fileArg, [...positional.slice(2), ...progArgs]); break;
1016
1221
  case 'build': {
1017
- // v1.0.362 - optional -o/--output <path>. "-o" is a single-dash flag, so
1222
+ // v1.0.363 - optional -o/--output <path>. "-o" is a single-dash flag, so
1018
1223
  // it survives the "--filtered" positional list; pull it out here before
1019
1224
  // building the positional file argument for cmdBuild.
1020
1225
  let outputPath = null;
1021
1226
  const positionalOnly = [];
1022
- for (let i = 0; i < args.length; i++) {
1023
- const a = args[i];
1227
+ for (let i = 0; i < cliArgs.length; i++) {
1228
+ const a = cliArgs[i];
1024
1229
  if (a === '-o' || a === '--output') {
1025
- if (i + 1 < args.length && !args[i + 1].startsWith('-')) {
1026
- outputPath = args[++i];
1230
+ if (i + 1 < cliArgs.length && !cliArgs[i + 1].startsWith('-')) {
1231
+ outputPath = cliArgs[++i];
1027
1232
  } else {
1028
1233
  console.error('Usage: plainscript build <file.pln> -o <output.js>');
1029
1234
  process.exit(1);
@@ -1036,15 +1241,19 @@ async function main() {
1036
1241
  break;
1037
1242
  }
1038
1243
  case 'check': cmdCheck(fileArg, json); break;
1244
+ case 'ir': cmdIR(fileArg); break;
1245
+ case 'test': cmdTest(fileArg); break;
1039
1246
  case 'fmt': cmdFmt(fileArg); break;
1040
1247
  case 'new': cmdNew(fileArg); break;
1041
1248
  case 'install': cmdInstall(); break;
1042
- case 'start': await cmdStart(positional.slice(2)); break;
1249
+ case 'start': await cmdStart([...positional.slice(2), ...progArgs]); break;
1043
1250
  case 'doctor': cmdDoctor(); break;
1044
1251
  case 'add': cmdAdd(fileArg); break;
1045
1252
  case 'remove': cmdRemove(fileArg); break;
1046
1253
  case 'update': cmdUpdate(); break;
1047
- case 'version': cmdVersion(); break;
1254
+ case 'version':
1255
+ case '--version':
1256
+ case '-v': cmdVersion(); break;
1048
1257
  case 'help': cmdHelp(); break;
1049
1258
  default:
1050
1259
  // Backwards-compatible: treat the first arg as a file to run directly
@@ -1060,4 +1269,4 @@ async function main() {
1060
1269
  main().catch((err) => {
1061
1270
  console.error(err.message);
1062
1271
  process.exit(1);
1063
- });
1272
+ });
@@ -10,15 +10,20 @@
10
10
  const INDENT = ' '; // 4 spaces
11
11
 
12
12
  // Keywords whose line CLOSES a block (printed at depth - 1).
13
- const DEDENT_WORDS = new Set(['done', 'otherwise', 'recover']);
13
+ const DEDENT_WORDS = new Set(['done', 'end', 'otherwise', 'recover']);
14
14
 
15
15
  // Patterns whose line OPENS a new block (next line indented).
16
16
  const INDENT_STARTERS = [
17
17
  /^make\s+\S+\s*\(/, // make name(...)
18
+ /^to\s+\S+/, // to add a and b together ...
18
19
  /^if\s+/, // if ...
19
20
  /^otherwise\b/, // otherwise
20
21
  /^for\s+each\s+/, // for each ...
22
+ /^for\s+every\s+/, // for every ... in ...
23
+ /^for\s+index\s+/, // for index i from ... to ...
21
24
  /^while\s+/, // while ...
25
+ /^repeat\s+\d+\s+times\b/, // repeat N times ...
26
+ /^repeat\s+(with|while|until)\b/, // repeat with/while/until ...
22
27
  /^when\s+someone\s+visits/, // when someone visits ...
23
28
  /^when\s+someone\s+(sends|clicks)\b/, // when someone sends / clicks (Telegram)
24
29
  /^when\s+socket\b/, // when socket connects / sends message / disconnects (v2.1)
@@ -37,6 +42,14 @@ const INDENT_STARTERS = [
37
42
  /^recover\b/, // recover [as name] (v2.1.1 error handling)
38
43
  /^retry\s+\d+\s+times\b/, // retry N times ... (v2.1.1 retries)
39
44
  /^every\s+\d+\s+(seconds?|minutes?|hours?|days?)\b/, // every 5 minutes (v2.1)
45
+ /^every\s+N\s+(seconds?|minutes?|hours?|days?)\b/, // every N seconds (variable)
46
+ /^every\s+frame\b/, // every frame (v2.1.1 game loop)
47
+ /^after\s+\d+\s+(milliseconds?|seconds?|minutes?|hours?|days?|frames?)\b/, // after 3 seconds
48
+ /^run\s+in\s+parallel\b/, // run in parallel ... done as results
49
+ /^switch\s+\S+\s+against\b/, // switch expr against ... done
50
+ /^match\s+\S+\s+against\b/, // match expr against ... done
51
+ /^stream\s+/, // stream "file" as line ...
52
+ /^test\s+"/, // test "name"
40
53
  /^schedule\s+"/, // schedule "..." (v2.1 cron)
41
54
  /^websocket\s+server\b/, // websocket server (v2.1)
42
55
  /^whatsapp\s+bot\s*$/, // whatsapp bot (v2.1.1 WhatsApp runtime)
@@ -45,6 +58,13 @@ const INDENT_STARTERS = [
45
58
  /^send\s+mail\s*$/, // send mail (v2.1)
46
59
  /^google\s+oauth\s*$/, // google oauth (v2.1.1 Google sign-in)
47
60
  /^query\b/, // query SQL block (v0.6 SQLite DX)
61
+ /^postgres\b/, // postgres "conn" (connection, no body)
62
+ /^mongo\b/, // mongo "conn" (connection, no body)
63
+ /^enable\s+sessions\b/, // enable sessions "secret"
64
+ /^require\s+api\s+key\b/, // require api key from ...
65
+ /^limit\s+requests\b/, // limit requests to N per minute
66
+ /^accept\s+uploads\b/, // accept uploads ...
67
+ /^when\s+[^\s]+(\s+"[^"]*")?\s+happens\b/, // when target "<event>" happens (v2.1.1)
48
68
  /^insert\b/, // insert SQL block
49
69
  /^update\b/, // update SQL block
50
70
  /^delete\b(?!\s*["'])/, // delete SQL block (v2.1.1: NOT `delete "<url>"`,