plainscript-lang 0.1.7 → 1.0.0-latest

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +98 -40
  2. package/compiler/bundler.js +1 -1
  3. package/compiler/cli.js +166 -57
  4. package/compiler/generator.js +878 -19
  5. package/compiler/lexer.js +31 -2
  6. package/compiler/parser.js +668 -24
  7. package/compiler/version.js +1 -1
  8. package/docs/CAPABILITY_GAP_AUDIT.md +439 -0
  9. package/docs/PLINJS_SPEC.md +124 -24
  10. package/docs/index.html +555 -2220
  11. package/docs/website/script.js +889 -133
  12. package/docs/website/style.css +652 -1113
  13. package/examples/auth-api.ps +56 -0
  14. package/examples/{cache-and-jobs.pln → cache-and-jobs.ps} +1 -1
  15. package/examples/concurrency.ps +49 -0
  16. package/examples/{database.pln → database.ps} +1 -1
  17. package/examples/{deployment.pln → deployment.ps} +1 -1
  18. package/examples/{email-send.pln → email-send.ps} +1 -1
  19. package/examples/error-handling.ps +54 -0
  20. package/examples/file-uploads.ps +39 -0
  21. package/examples/files-and-config.ps +47 -0
  22. package/examples/http-client.ps +44 -0
  23. package/examples/modules/app.ps +16 -0
  24. package/examples/modules/math.ps +20 -0
  25. package/examples/record-kinds.ps +43 -0
  26. package/examples/{rest-api.pln → rest-api.ps} +1 -1
  27. package/examples/{scheduled-tasks.pln → scheduled-tasks.ps} +1 -1
  28. package/examples/search-and-filter.ps +34 -0
  29. package/examples/sessions-and-cookies.ps +54 -0
  30. package/examples/{websocket-server.pln → websocket-server.ps} +1 -1
  31. package/package.json +2 -2
  32. package/docs/website/index.html +0 -1500
  33. /package/examples/{arrays.pln → arrays.ps} +0 -0
  34. /package/examples/{day2.pln → day2.ps} +0 -0
  35. /package/examples/{day3.pln → day3.ps} +0 -0
  36. /package/examples/{expressions.pln → expressions.ps} +0 -0
  37. /package/examples/football-backend/{app.pln → app.ps} +0 -0
  38. /package/examples/{hello.pln → hello.ps} +0 -0
  39. /package/examples/id-verification/{app.pln → app.ps} +0 -0
  40. /package/examples/{loops.pln → loops.ps} +0 -0
  41. /package/examples/{objects.pln → objects.ps} +0 -0
  42. /package/examples/{rest-api-fetch.pln → rest-api-fetch.ps} +0 -0
  43. /package/examples/{server.pln → server.ps} +0 -0
  44. /package/examples/{start.pln → start.ps} +0 -0
  45. /package/examples/{stdlib.pln → stdlib.ps} +0 -0
  46. /package/examples/{telegram-bot.pln → telegram-bot.ps} +0 -0
  47. /package/examples/{web-app.pln → web-app.ps} +0 -0
  48. /package/examples/whatsapp-bot/{pairing.pln → pairing.ps} +0 -0
  49. /package/examples/whatsapp-bot/{qr.pln → qr.ps} +0 -0
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # PlainScript
2
2
 
3
3
  <p align="center">
4
- <img src="docs/logo.jpg" alt="PlainScript Logo" width="200" />
4
+ <img src="https://github.com/ayoistooslick/plainscript/blob/main/docs/logo.jpg" alt="PlainScript Logo" width="200" />
5
5
  </p>
6
6
 
7
7
  > "When even a simple sentence can be code."
@@ -9,14 +9,14 @@
9
9
 
10
10
  PlainScript is an Intent-Oriented Programming Language (IOPL). You describe **what** you want; the compiler decides **how** to implement it in JavaScript.
11
11
 
12
- **Current version:** v0.1.7 — the `plainscript` npm package with a TypeScript-style production build (`plainscript build` → `dist/`, source names preserved).
12
+ **Current version:** v1.0.0-latest — the `plainscript` npm package with a TypeScript-style production build (`plainscript build` → `dist/`, source names preserved).
13
13
 
14
14
  ---
15
15
 
16
16
  ## Quick start
17
17
 
18
18
  ```bash
19
- npx plainscript new myapp # scaffolds src/app.pln and package.json
19
+ npx plainscript new myapp # scaffolds src/app.ps and package.json
20
20
  cd myapp
21
21
  npm install # installs plainscript as a devDependency plus runtime packages
22
22
  npm run build # compiles src/ -> dist/ (plainscript build)
@@ -27,7 +27,7 @@ Adding PlainScript to an existing project:
27
27
 
28
28
  ```bash
29
29
  npm install --save-dev plainscript
30
- # start writing src/*.pln files — plainscript build auto-discovers them
30
+ # start writing src/*.ps files — plainscript build auto-discovers them
31
31
  ```
32
32
 
33
33
  No global install is needed anywhere — everything runs through npm scripts
@@ -38,17 +38,17 @@ and `npx`.
38
38
  ## CLI
39
39
 
40
40
  ```
41
- plainscript run <file.pln> Install missing dependencies, compile and execute
41
+ plainscript run <file.ps> Install missing dependencies, compile and execute
42
42
  (executes from a scratch dir — nothing is written
43
43
  into your project)
44
- plainscript build [file.pln] Compile to dist/. With no argument, builds every
45
- .pln file under the source root, preserving names
44
+ plainscript build [file.ps] Compile to dist/. With no argument, builds every
45
+ .ps file under the source root, preserving names
46
46
  and folder structure
47
- plainscript check <file.pln> Check syntax only (no output, no execution)
48
- plainscript fmt <file.pln> Format a PlainScript file in-place
47
+ plainscript check <file.ps> Check syntax only (no output, no execution)
48
+ plainscript fmt <file.ps> Format a PlainScript file in-place
49
49
  plainscript new [name] Create a new PlainScript project (npm-ready)
50
50
  plainscript install Install dependencies detected in the project's sources
51
- plainscript start Build src/app.pln and run its dist/ output
51
+ plainscript start Build src/app.ps and run its dist/ output
52
52
  plainscript doctor Check the PlainScript project environment
53
53
  plainscript add <package> Install a package into the project
54
54
  plainscript remove <package> Uninstall a package from the project
@@ -62,13 +62,13 @@ plainscript help Print help text
62
62
  ## Building and configuration
63
63
 
64
64
  `plainscript build` is a deterministic production build, TypeScript-style but for
65
- `.pln` sources — **zero configuration required**:
65
+ `.ps` sources — **zero configuration required**:
66
66
 
67
- - `plainscript build` (no argument) discovers every `.pln` file under `src/` and
67
+ - `plainscript build` (no argument) discovers every `.ps` file under `src/` and
68
68
  compiles each to `dist/` **preserving source file names and folder structure**:
69
- `src/messi.pln` → `dist/messi.js`,
70
- `src/helpers/math.pln` → `dist/helpers/math.js`.
71
- - `plainscript build <file.pln>` compiles a single file into `dist/`.
69
+ `src/messi.ps` → `dist/messi.js`,
70
+ `src/helpers/math.ps` → `dist/helpers/math.js`.
71
+ - `plainscript build <file.ps>` compiles a single file into `dist/`.
72
72
  - Imports are bundled into each output, so every file in `dist/` runs
73
73
  standalone under Node.
74
74
  - Rebuilds are byte-identical — safe to commit, diff, and cache.
@@ -108,11 +108,11 @@ For projects that need custom output or source directories, add a
108
108
  "build": "plainscript build",
109
109
  "prepare": "plainscript build"
110
110
  },
111
- "devDependencies": { "plainscript": "^0.1.7" }
111
+ "devDependencies": { "plainscript": "^1.0.0-latest" }
112
112
  }
113
113
  ```
114
114
 
115
- `src/index.pln` builds to `dist/index.js`; consumers install and `require()`
115
+ `src/index.ps` builds to `dist/index.js`; consumers install and `require()`
116
116
  it like any Node package. There is no PlainScript-specific registry or format —
117
117
  standard `package.json` semantics apply.
118
118
 
@@ -297,6 +297,31 @@ use node-fetch
297
297
  use @scope/package-name
298
298
  ```
299
299
 
300
+ ### TypeScript-parity capabilities (1.0.0-latest)
301
+
302
+ The full capability-gap audit lives in [`docs/CAPABILITY_GAP_AUDIT.md`](https://github.com/ayoistooslick/plainscript/blob/main/docs/CAPABILITY_GAP_AUDIT.md).
303
+ These features close it in PlainScript's own grammar:
304
+
305
+ - **Record kinds (classes):** `define a kind called "Person" with name is "" done`
306
+ + `create a Person with name "Ada" and age 17`. Plain-object instances; unknown
307
+ fields throw.
308
+ - **Concurrency:** `all of [...]`, `any of [...]`, `settled of [...]`,
309
+ `withTimeout(promise, ms)`.
310
+ - **Generators:** `yield` inside `make ... done`; consumed with `for each` or
311
+ `spread of`.
312
+ - **Reflection:** `typeOf`, `fieldsOf`, `valueOf`, `hasField`, `sizeOf`.
313
+ - **Binary:** `base64Encode/Decode`, `textToBytes/bytesToText`, `sha256/sha1/md5`.
314
+ - **Config:** `yamlDecode/yamlEncode`, `load env file ".env"`.
315
+ - **CLI & processes:** `args()`, `runCommand(cmd, [args])`.
316
+ - **Filesystem & paths:** `fileSize`, `fileType`, `lastModified`, `walkFolder`,
317
+ `joinPath`, `baseName`, `folderOf`, `extensionOf`.
318
+ - **Streams:** `writeLine`, `appendLine`.
319
+ - **Collections:** `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet`.
320
+ - **Dynamic modules:** `loadModule("./m")`.
321
+ - **Native tests:** `test "name" ... done` with `check a equals b`,
322
+ `check a contains b`, `check a is b`, `check <expr> raises "msg"`.
323
+ - **Exports:** `export <name>`.
324
+
300
325
  ---
301
326
 
302
327
  ## Backend Services
@@ -558,7 +583,9 @@ start env("PORT")
558
583
  ```
559
584
 
560
585
  `param("id")`, `query("page")` and `header("x-token")` read request data;
561
- `group` composes path prefixes; `status <n>` sets the response code.
586
+ `body()` / `body("field")` read the JSON request body; `group` composes path
587
+ prefixes; `status <n>` sets the response code and `redirect to "<url>"` issues a
588
+ redirect.
562
589
 
563
590
  ### Databases with parameters and transactions
564
591
 
@@ -620,22 +647,53 @@ websocket server on 8080
620
647
  done
621
648
  ```
622
649
 
623
- ### Cache (Redis)
650
+ ### Cache (Redis with in-memory fallback)
624
651
 
625
652
  ```plainscript
626
- cache env("REDIS_URL")
653
+ cache env("REDIS_URL") // omit for an in-memory Map store with TTL
627
654
  remember token as cacheGet("token")
628
655
  cacheSet("greeting", "hi", 60)
629
656
  cacheDelete("greeting")
630
657
  ```
631
658
 
659
+ Without a configured Redis, `cacheGet`/`cacheSet`/`cacheDelete` transparently fall
660
+ back to an in-memory store, so naive caching works out of the box.
661
+
662
+ ### AI / ML
663
+
664
+ ```plainscript
665
+ remember reply as chat("gpt-4o-mini", [
666
+ { role: "user", content: "Say hello in two words" }
667
+ ])
668
+
669
+ remember vec as embedText("text-embedding-3-small", "PlainScript rocks")
670
+ remember score as similarity(vec, embedText("text-embedding-3-small", "I love PlainScript"))
671
+
672
+ remember tags as ai_tags("PlainScript is an intent-oriented language")
673
+ remember article as ai_post("Welcome to PlainScript", ["why IOPL", "quick start"])
674
+ ```
675
+
676
+ `chat` and `embedText` are async OpenAI-compatible calls (from `OPENAI_API_KEY`,
677
+ override with `options.apiKey`/`options.baseURL`); `similarity` returns -1..1.
678
+
679
+ ### Pagination
680
+
681
+ ```plainscript
682
+ remember page as paginate(allUsers, 2, 10)
683
+ show page.items # second page of 10
684
+ show page.hasNext # true if another page exists
685
+ ```
686
+
687
+ `paginate(list, page, perPage)` returns
688
+ `{ items, count, page, pages, perPage, hasNext, hasPrev }`.
689
+
632
690
  ---
633
691
 
634
692
  ## Multi-file projects
635
693
 
636
694
  ```plainscript
637
- import "./math.pln"
638
- import "./utils.pln"
695
+ import "./math.ps"
696
+ import "./utils.ps"
639
697
 
640
698
  show PI
641
699
 
@@ -731,7 +789,7 @@ plainscript install # Install all detected dependencies
731
789
  plainscript add express # Add a package
732
790
  plainscript remove express # Remove a package
733
791
  plainscript update # Update all packages
734
- plainscript start # Build src/app.pln and run its dist/ output
792
+ plainscript start # Build src/app.ps and run its dist/ output
735
793
  plainscript doctor # Check project environment
736
794
  ```
737
795
 
@@ -774,27 +832,27 @@ plainscript/
774
832
  │ └── cli.js — command-line entry point
775
833
  │
776
834
  ├── examples/
777
- │ ├── hello.pln
778
- │ ├── day2.pln
779
- │ ├── day3.pln
780
- │ ├── arrays.pln
781
- │ ├── objects.pln
782
- │ ├── loops.pln
783
- │ ├── expressions.pln
784
- │ ├── stdlib.pln
785
- │ ├── server.pln
786
- │ ├── web-app.pln
787
- │ ├── start.pln
788
- │ ├── database.pln
789
- │ ├── deployment.pln
835
+ │ ├── hello.ps
836
+ │ ├── day2.ps
837
+ │ ├── day3.ps
838
+ │ ├── arrays.ps
839
+ │ ├── objects.ps
840
+ │ ├── loops.ps
841
+ │ ├── expressions.ps
842
+ │ ├── stdlib.ps
843
+ │ ├── server.ps
844
+ │ ├── web-app.ps
845
+ │ ├── start.ps
846
+ │ ├── database.ps
847
+ │ ├── deployment.ps
790
848
  │ ├── football-backend/ — acceptance example (SQLite + auth + sessions)
791
- │ │ └── app.pln
849
+ │ │ └── app.ps
792
850
  │ ├── id-verification/ — acceptance example (uploads + OCR matching)
793
- │ │ ├── app.pln
851
+ │ │ ├── app.ps
794
852
  │ │ └── make-sample-id.js
795
853
  │ └── whatsapp-bot/ — WhatsApp bots (QR and pairing linking)
796
- │ ├── qr.pln
797
- │ └── pairing.pln
854
+ │ ├── qr.ps
855
+ │ └── pairing.ps
798
856
  │
799
857
  ├── tests/
800
858
  │ ├── compiler.test.js — language, CLI and formatter coverage
@@ -46,7 +46,7 @@ function resolveDependencies(entryPath) {
46
46
 
47
47
  // Parse the file to discover its own imports.
48
48
  // Annotate any tokenise/parse error with the filename so callers see
49
- // "file.pln — Line N, Column N: …" rather than a bare positional message.
49
+ // "file.ps — Line N, Column N: …" rather than a bare positional message.
50
50
  const source = fs.readFileSync(absPath, 'utf8');
51
51
  let tokens, ast;
52
52
  try {
package/compiler/cli.js CHANGED
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
- // CLI: compile and run PlainScript (.pln) files.
2
+ // CLI: compile and run PlainScript (.ps) files.
3
3
  //
4
4
  // Usage:
5
- // plainscript run <file.pln> install missing dependencies, compile and execute
6
- // plainscript build [file.pln] compile src/ (or one file) to dist/, names preserved
7
- // plainscript check <file.pln> check syntax only (no JS generated, no execution)
8
- // plainscript fmt <file.pln> format a PlainScript file in-place
5
+ // plainscript run <file.ps> install missing dependencies, compile and execute
6
+ // plainscript build [file.ps] compile src/ (or one file) to dist/, names preserved
7
+ // plainscript check [target] fully validate source(s): imports + generate + JS syntax
8
+ // (target: a .ps file, a directory, or none to scan the project)
9
+ // plainscript fmt <file.ps> format a PlainScript file in-place
9
10
  // plainscript new [name] scaffold a new PlainScript project
10
11
  // plainscript install install dependencies detected in the project's sources
11
- // plainscript start build src/app.pln (or index.pln) and run its dist output
12
+ // plainscript start build src/app.ps (or index.ps) and run its dist output
12
13
  // plainscript doctor check the PlainScript project environment
13
14
  // plainscript add <package> install a package into the project
14
15
  // plainscript remove <package> uninstall a package from the project
@@ -18,6 +19,7 @@
18
19
 
19
20
  const fs = require('fs');
20
21
  const path = require('path');
22
+ const vm = require('vm');
21
23
  const { execFileSync } = require('child_process');
22
24
  const { tokenize } = require('./lexer');
23
25
  const { parse } = require('./parser');
@@ -49,18 +51,20 @@ function warn(message) {
49
51
  const section = (title) => `\n${clrCyan(clrBold(title))}`;
50
52
 
51
53
  const HELP = `
52
- ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .pln compiles to readable Node.js')}
54
+ ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .ps compiles to readable Node.js')}
53
55
 
54
56
  ${section('START')}
55
- plainscript new [name] Scaffold a new project with a working app.pln
56
- plainscript run <file.pln> Install missing deps, compile, execute
57
- plainscript start Build src/app.pln and run it from dist/
57
+ plainscript new [name] Scaffold a new project with a working app.ps
58
+ plainscript run <file.ps> Install missing deps, compile, execute
59
+ plainscript start Build src/app.ps and run it from dist/
58
60
 
59
61
  ${section('BUILD & CHECK')}
60
- plainscript build Compile every .pln under src/ into dist/
61
- plainscript build <file.pln> Compile one file into dist/ (name preserved)
62
- plainscript check <file.pln> Syntax-check only — fastest feedback loop
63
- plainscript fmt <file.pln> Format a file in place
62
+ plainscript build Compile every .ps under src/ into dist/
63
+ plainscript build <file.ps> Compile one file into dist/ (name preserved)
64
+ plainscript check [target] Validate imports + generate + JS output (no writes)
65
+ target: a .ps file, a directory, or none = project scan
66
+ --json emits deterministic machine-readable output
67
+ plainscript fmt <file.ps> Format a file in place
64
68
 
65
69
  ${section('PACKAGES')}
66
70
  plainscript install Install everything your source needs
@@ -89,10 +93,12 @@ ${section('ALSO SHIPPED')}
89
93
  WhatsApp bots (v2.1.1) ·
90
94
  email · schedules · WebSocket · cache (v2.1) ·
91
95
  sessions · uploads · cookies · rate limits · api keys · OAuth (v2.1.1)
96
+ JSON body · redirect · AI chat/embeddings · vector similarity ·
97
+ paginate · collection & string primitives (v2.2)
92
98
 
93
99
  ${section('FIRST RUN')}
94
100
  plainscript new hello scaffolds hello/ with a live web app
95
- plainscript run hello/app.pln serves it at http://localhost:3000
101
+ plainscript run hello/app.ps serves it at http://localhost:3000
96
102
  `.trim();
97
103
 
98
104
  // ── npm invocation ────────────────────────────────────────────────────────────
@@ -145,8 +151,8 @@ function isValidPackageName(name) {
145
151
  // "exclude": ["vendor"] } }
146
152
  //
147
153
  // Filenames and folder structure are always preserved:
148
- // src/messi.pln → dist/messi.js
149
- // src/helpers/math.pln → dist/helpers/math.js
154
+ // src/messi.ps → dist/messi.js
155
+ // src/helpers/math.ps → dist/helpers/math.js
150
156
  const SOURCE_DIR = 'src';
151
157
  const DEFAULT_OUT_DIR = 'dist';
152
158
 
@@ -179,7 +185,7 @@ function resolveOutDir(opts) {
179
185
  return DEFAULT_OUT_DIR;
180
186
  }
181
187
 
182
- // Every .pln file under srcDir, recursively, as paths relative to srcDir.
188
+ // Every .ps file under srcDir, recursively, as paths relative to srcDir.
183
189
  // Deterministic order (sorted); node_modules, hidden directories, the output
184
190
  // directory, and any user-specified exclude patterns are skipped.
185
191
  function discoverSources(srcDir, outDir, exclude) {
@@ -202,7 +208,7 @@ function discoverSources(srcDir, outDir, exclude) {
202
208
  try { stat = fs.statSync(full); } catch (_) { continue; }
203
209
  if (stat.isDirectory()) {
204
210
  walk(full);
205
- } else if (name.endsWith('.pln')) {
211
+ } else if (name.endsWith('.ps')) {
206
212
  found.push(path.relative(root, full));
207
213
  }
208
214
  }
@@ -399,7 +405,7 @@ function nodeModulesSearchPaths(entryDir) {
399
405
 
400
406
  async function cmdRun(filePath, extraArgs = []) {
401
407
  if (!filePath) {
402
- console.error('Usage: plainscript run <file.pln>');
408
+ console.error('Usage: plainscript run <file.ps>');
403
409
  process.exit(1);
404
410
  }
405
411
  const js = compile(filePath);
@@ -436,8 +442,8 @@ function buildOne(filePath, srcDir, outDir) {
436
442
  }
437
443
  const js = compile(absFile);
438
444
  const srcRoot = path.resolve(srcDir);
439
- let rel = path.relative(srcRoot, absFile).replace(/\.pln$/, '.js');
440
- if (rel.startsWith('..') || path.isAbsolute(rel)) rel = path.basename(absFile).replace(/\.pln$/, '.js');
445
+ let rel = path.relative(srcRoot, absFile).replace(/\.ps$/, '.js');
446
+ if (rel.startsWith('..') || path.isAbsolute(rel)) rel = path.basename(absFile).replace(/\.ps$/, '.js');
441
447
  const outPath = path.join(path.resolve(outDir), rel);
442
448
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
443
449
  fs.writeFileSync(outPath, js, 'utf8');
@@ -447,16 +453,16 @@ function buildOne(filePath, srcDir, outDir) {
447
453
  // `plainscript build` — TypeScript-style production build:
448
454
  //
449
455
  // Zero config (default):
450
- // messi.pln → dist/messi.js (project-root sources)
451
- // src/index.pln → dist/index.js (src/ is the source root)
452
- // src/a/b.pln → dist/a/b.js (structure preserved)
456
+ // messi.ps → dist/messi.js (project-root sources)
457
+ // src/index.ps → dist/index.js (src/ is the source root)
458
+ // src/a/b.ps → dist/a/b.js (structure preserved)
453
459
  //
454
460
  // With plainscript.config.json:
455
461
  // { "compilerOptions": { "outDir": "./build", "rootDir": "./lib" } }
456
- // lib/app.pln → build/app.js
462
+ // lib/app.ps → build/app.js
457
463
  //
458
464
  // With an explicit file argument only that entry is compiled; without one,
459
- // every .pln under the discovered source root builds to the output directory.
465
+ // every .ps under the discovered source root builds to the output directory.
460
466
  async function cmdBuild(filePath) {
461
467
  const opts = readCompilerOptions();
462
468
  const srcDir = resolveSrcDir(opts);
@@ -469,7 +475,7 @@ async function cmdBuild(filePath) {
469
475
  }
470
476
  const sources = discoverSources(srcDir, outDir, exclude);
471
477
  if (sources.length === 0) {
472
- console.error(`No .pln files found under "${srcDir}".`);
478
+ console.error(`No .ps files found under "${srcDir}".`);
473
479
  process.exit(1);
474
480
  }
475
481
  QUIET_STAGES = true;
@@ -494,7 +500,7 @@ async function cmdStart(extraArgs = []) {
494
500
  const outDir = resolveOutDir(opts);
495
501
  const entryPath = findEntry(opts);
496
502
  if (!entryPath) {
497
- console.error('No entry file found. Expected "src/app.pln" or "src/index.pln".');
503
+ console.error('No entry file found. Expected "src/app.ps" or "src/index.ps".');
498
504
  process.exit(1);
499
505
  }
500
506
  const outFile = buildOne(entryPath, srcDir, outDir);
@@ -519,8 +525,8 @@ function cmdNew(projectName) {
519
525
  fs.mkdirSync(path.join(dir, 'public'));
520
526
  fs.mkdirSync(path.join(dir, 'src'));
521
527
 
522
- // src/app.pln — starter Express app
523
- fs.writeFileSync(path.join(dir, 'src', 'app.pln'), `use express
528
+ // src/app.ps — starter Express app
529
+ fs.writeFileSync(path.join(dir, 'src', 'app.ps'), `use express
524
530
 
525
531
  remember app as express()
526
532
 
@@ -546,7 +552,7 @@ done
546
552
  // deployment only needs the generated dist/ output.
547
553
  fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
548
554
  name,
549
- version: '1.0.0',
555
+ version: '1.0.0-latest',
550
556
  description: `A PlainScript v${VERSION} application`,
551
557
  main: 'dist/app.js',
552
558
  scripts: {
@@ -554,7 +560,7 @@ done
554
560
  start: 'node dist/app.js',
555
561
  },
556
562
  devDependencies: {
557
- plainscript: `^${VERSION}`,
563
+ 'plainscript-lang': `^${VERSION}`,
558
564
  },
559
565
  dependencies: {
560
566
  express: '^4.18.2',
@@ -578,7 +584,7 @@ Then open http://localhost:3000 in your browser.
578
584
  `);
579
585
 
580
586
  console.log(`✓ Created project "${name}"`);
581
- console.log(`\nNext steps:\n cd ${name}\n npm install\n npx plainscript run src/app.pln`);
587
+ console.log(`\nNext steps:\n cd ${name}\n npm install\n npx plainscript run src/app.ps`);
582
588
  }
583
589
 
584
590
  // ── plainscript install ────────────────────────────────────────────────────────────
@@ -588,11 +594,11 @@ Then open http://localhost:3000 in your browser.
588
594
  function findEntry(opts) {
589
595
  const srcDir = resolveSrcDir(opts);
590
596
  const candidates = [
591
- path.join(srcDir, 'app.pln'),
592
- path.join(srcDir, 'index.pln'),
597
+ path.join(srcDir, 'app.ps'),
598
+ path.join(srcDir, 'index.ps'),
593
599
  ];
594
600
  if (srcDir !== '.') {
595
- candidates.push('app.pln', 'index.pln');
601
+ candidates.push('app.ps', 'index.ps');
596
602
  }
597
603
  return candidates.find((c) => fs.existsSync(path.resolve(c))) || null;
598
604
  }
@@ -607,7 +613,7 @@ function collectSourceAsts() {
607
613
  const exclude = opts && opts.exclude;
608
614
  const sources = discoverSources(srcDir, outDir, exclude);
609
615
  if (sources.length === 0) {
610
- console.error(`No .pln source files found under "${srcDir}".`);
616
+ console.error(`No .ps source files found under "${srcDir}".`);
611
617
  process.exit(1);
612
618
  }
613
619
  const root = path.resolve(srcDir);
@@ -663,14 +669,14 @@ function cmdDoctor() {
663
669
  check('Runtime', fs.existsSync(path.join(__dirname, 'generator.js')));
664
670
  console.log('');
665
671
 
666
- // Source discovery check: does the project have any .pln files?
672
+ // Source discovery check: does the project have any .ps files?
667
673
  const opts = readCompilerOptions();
668
674
  const srcDir = resolveSrcDir(opts);
669
675
  const outDir = resolveOutDir(opts);
670
676
  const exclude = opts && opts.exclude;
671
677
  const sources = discoverSources(srcDir, outDir, exclude);
672
678
  check('Source files', sources.length > 0,
673
- sources.length > 0 ? `"${srcDir}/" discovered (${sources.length} file(s))` : `no .pln files under "${srcDir}"`);
679
+ sources.length > 0 ? `"${srcDir}/" discovered (${sources.length} file(s))` : `no .ps files under "${srcDir}"`);
674
680
  if (sources.length === 0) return;
675
681
 
676
682
  // Dependency check: scan every source file for npm imports
@@ -745,31 +751,133 @@ function cmdUpdate() {
745
751
  }
746
752
 
747
753
  // Check syntax of a PlainScript file without generating JavaScript or executing.
748
- function cmdCheck(filePath) {
749
- if (!filePath) {
750
- console.error('Usage: plainscript check <file.pln>');
751
- process.exit(1);
752
- }
753
- const absPath = path.resolve(filePath);
754
- if (!fs.existsSync(absPath)) {
755
- console.error(`File not found: ${filePath}`);
756
- process.exit(1);
757
- }
754
+ // Full validation of a single .ps entry: resolve imports, parse+generate every
755
+ // file in dependency order, and verify the emitted JavaScript is syntactically
756
+ // valid — all without writing anything to disk. Returns a deterministic
757
+ // result record; `deps` are the npm packages the sources require.
758
+ function validateSource(absPath) {
759
+ const rel = path.relative(process.cwd(), absPath) || absPath;
758
760
  const t0 = Date.now();
759
761
  try {
760
- resolveDependencies(absPath);
761
- const ms = Date.now() - t0;
762
- console.log(`${clrGreen('✓')} ${filePath} — no errors found.${clrDim(` (${ms}ms)`)}`);
762
+ // resolveDependencies parses each file too, so a parse error anywhere in
763
+ // the import graph surfaces here with a "file.ps — Line:Col" prefix.
764
+ const files = resolveDependencies(absPath);
765
+ const context = createGenerationContext();
766
+ let js = files.map(({ ast }) => generate(ast, context)).filter(s => s.trim()).join('\n');
767
+ if (context.needsAsync) js = wrapAsync(js);
768
+
769
+ // The compiler must never emit broken JavaScript. Parsing the output with
770
+ // the V8 compiler catches generator regressions at check time.
771
+ new vm.Script(js);
772
+
773
+ // Collect unique npm dependencies across the file and its imports.
774
+ const deps = [];
775
+ for (const { absPath: f } of files) {
776
+ let source;
777
+ try { source = fs.readFileSync(f, 'utf8'); } catch (_) { continue; }
778
+ for (const d of detectDependencies(source)) {
779
+ if (!deps.includes(d)) deps.push(d);
780
+ }
781
+ }
782
+ return { file: rel, ok: true, deps, ms: Date.now() - t0 };
763
783
  } catch (err) {
764
- console.error(err.message);
784
+ return { file: rel, ok: false, error: err.message, ms: Date.now() - t0 };
785
+ }
786
+ }
787
+
788
+ // `plainscript check [target] [--json]`
789
+ //
790
+ // Fully validates one .ps file, every .ps under a directory, or (with no
791
+ // target) the project sources, deterministically and non-interactively:
792
+ // resolve imports, parse + generate, and confirm the JS output parses. Never
793
+ // prompts, never writes files, never installs packages.
794
+ //
795
+ // plainscript check validate every .ps in the project source root
796
+ // plainscript check app.ps validate one file (and its imports)
797
+ // plainscript check src/ validate every .ps under a directory
798
+ // plainscript check --json machine-readable JSON on stdout
799
+ function cmdCheck(target, json) {
800
+ const opts = readCompilerOptions();
801
+ const srcDir = resolveSrcDir(opts);
802
+ const outDir = resolveOutDir(opts);
803
+ const exclude = opts && opts.exclude;
804
+
805
+ let sources;
806
+ if (target) {
807
+ const abs = path.resolve(target);
808
+ if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
809
+ sources = discoverSources(abs, outDir, exclude).map(r => path.join(abs, r));
810
+ } else if (/\.ps$/.test(target) && !fs.existsSync(abs)) {
811
+ if (json) {
812
+ console.log(JSON.stringify({
813
+ plainscript: VERSION, ok: false,
814
+ sources: [], summary: { total: 0, passed: 0, failed: 1 },
815
+ errors: [{ file: target, error: `File not found: ${target}` }],
816
+ }));
817
+ } else {
818
+ console.error(`File not found: ${target}`);
819
+ }
820
+ process.exit(1);
821
+ } else {
822
+ sources = [abs];
823
+ }
824
+ } else {
825
+ const root = path.resolve(srcDir);
826
+ sources = discoverSources(srcDir, outDir, exclude).map(r => path.join(root, r));
827
+ if (sources.length === 0) {
828
+ const msg = `No .ps files found under "${srcDir}".`;
829
+ if (json) console.log(JSON.stringify({ plainscript: VERSION, ok: false, sources: [], summary: { total: 0, passed: 0, failed: 1 }, errors: [{ file: srcDir, error: msg }] }));
830
+ else console.error(msg);
831
+ process.exit(1);
832
+ }
833
+ }
834
+
835
+ sources.sort(); // deterministic regardless of filesystem order
836
+ const results = sources.map(validateSource);
837
+ const passed = results.filter(r => r.ok);
838
+ const failed = results.filter(r => !r.ok);
839
+
840
+ if (json) {
841
+ const dependencySummary = [];
842
+ const depIndex = new Map();
843
+ for (const r of passed) {
844
+ for (const d of r.deps) {
845
+ if (!depIndex.has(d)) { depIndex.set(d, []); dependencySummary.push(d); }
846
+ depIndex.get(d).push(r.file);
847
+ }
848
+ }
849
+ console.log(JSON.stringify({
850
+ plainscript: VERSION,
851
+ ok: failed.length === 0,
852
+ sources: results,
853
+ summary: { total: results.length, passed: passed.length, failed: failed.length },
854
+ dependencySummary: dependencySummary.map(d => ({ package: d, usedBy: depIndex.get(d) })),
855
+ }));
856
+ process.exit(failed.length ? 1 : 0);
857
+ }
858
+
859
+ for (const r of results) {
860
+ if (r.ok) {
861
+ console.log(`${clrGreen('✓')} ${r.file} — ok${clrDim(` (${r.ms}ms)`)}`);
862
+ } else {
863
+ console.log(`${clrRed('✗')} ${r.file}`);
864
+ console.error(r.error);
865
+ }
866
+ }
867
+
868
+ if (failed.length > 0) {
869
+ console.error(`\n${failed.length} of ${results.length} file(s) failed validation.`);
765
870
  process.exit(1);
766
871
  }
872
+ if (results.length > 0) {
873
+ console.log(clrGreen(`\n✓ ${results.length} file(s) validated.`));
874
+ }
767
875
  }
768
876
 
769
877
  // Format a PlainScript file in-place.
770
878
  function cmdFmt(filePath) {
771
879
  if (!filePath) {
772
- console.error('Usage: plainscript fmt <file.pln>');
880
+ console.error('Usage: plainscript fmt <file.ps>');
773
881
  process.exit(1);
774
882
  }
775
883
  const absPath = path.resolve(filePath);
@@ -803,6 +911,7 @@ async function main() {
803
911
  // Global flags — recognized anywhere in the argument list.
804
912
  const quiet = args.includes('--quiet');
805
913
  const verbose = args.includes('--verbose');
914
+ const json = args.includes('--json');
806
915
  if (quiet) { stage = stageQuiet; QUIET_STAGES = true; }
807
916
  if (verbose) { stage = stageVerbose; VERBOSE = true; }
808
917
 
@@ -815,7 +924,7 @@ async function main() {
815
924
  switch (command) {
816
925
  case 'run': await cmdRun(fileArg, positional.slice(2)); break;
817
926
  case 'build': await cmdBuild(fileArg); break;
818
- case 'check': cmdCheck(fileArg); break;
927
+ case 'check': cmdCheck(fileArg, json); break;
819
928
  case 'fmt': cmdFmt(fileArg); break;
820
929
  case 'new': cmdNew(fileArg); break;
821
930
  case 'install': cmdInstall(); break;
@@ -828,7 +937,7 @@ async function main() {
828
937
  case 'help': cmdHelp(); break;
829
938
  default:
830
939
  // Backwards-compatible: treat the first arg as a file to run directly
831
- if (command && command.endsWith('.pln')) {
940
+ if (command && command.endsWith('.ps')) {
832
941
  await cmdRun(command);
833
942
  } else {
834
943
  console.error(`Unknown command: "${command}". Run "plainscript help" for usage.`);