plainscript-lang 0.1.7-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 (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +815 -0
  3. package/compiler/bundler.js +86 -0
  4. package/compiler/cli.js +843 -0
  5. package/compiler/dependency-detector.js +173 -0
  6. package/compiler/formatter.js +170 -0
  7. package/compiler/generator.js +2032 -0
  8. package/compiler/lexer.js +413 -0
  9. package/compiler/parser.js +2077 -0
  10. package/compiler/version.js +6 -0
  11. package/docs/PLINJS_SPEC.md +1051 -0
  12. package/docs/index.html +2287 -0
  13. package/docs/logo.jpg +0 -0
  14. package/docs/website/index.html +1500 -0
  15. package/docs/website/script.js +197 -0
  16. package/docs/website/style.css +1117 -0
  17. package/examples/arrays.pln +13 -0
  18. package/examples/cache-and-jobs.pln +29 -0
  19. package/examples/database.pln +41 -0
  20. package/examples/day2.pln +7 -0
  21. package/examples/day3.pln +11 -0
  22. package/examples/deployment.pln +12 -0
  23. package/examples/email-send.pln +22 -0
  24. package/examples/expressions.pln +40 -0
  25. package/examples/football-backend/app.pln +90 -0
  26. package/examples/hello.pln +3 -0
  27. package/examples/id-verification/app.pln +29 -0
  28. package/examples/id-verification/make-sample-id.js +123 -0
  29. package/examples/loops.pln +17 -0
  30. package/examples/objects.pln +12 -0
  31. package/examples/rest-api-fetch.pln +94 -0
  32. package/examples/rest-api.pln +68 -0
  33. package/examples/scheduled-tasks.pln +23 -0
  34. package/examples/server.pln +25 -0
  35. package/examples/start.pln +2 -0
  36. package/examples/stdlib.pln +41 -0
  37. package/examples/telegram-bot.pln +42 -0
  38. package/examples/web-app.pln +20 -0
  39. package/examples/websocket-server.pln +27 -0
  40. package/examples/whatsapp-bot/pairing.pln +17 -0
  41. package/examples/whatsapp-bot/qr.pln +8 -0
  42. package/package.json +47 -0
@@ -0,0 +1,843 @@
1
+ #!/usr/bin/env node
2
+ // CLI: compile and run PlainScript (.pln) files.
3
+ //
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
9
+ // plainscript new [name] scaffold a new PlainScript project
10
+ // 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 doctor check the PlainScript project environment
13
+ // plainscript add <package> install a package into the project
14
+ // plainscript remove <package> uninstall a package from the project
15
+ // plainscript update update all installed packages
16
+ // plainscript version print the compiler version
17
+ // plainscript help print this help text
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const { execFileSync } = require('child_process');
22
+ const { tokenize } = require('./lexer');
23
+ const { parse } = require('./parser');
24
+ const { generate, createGenerationContext, wrapAsync } = require('./generator');
25
+ const { bundle, resolveDependencies } = require('./bundler');
26
+ const { format } = require('./formatter');
27
+ const { detectDependencies, PACKAGE_MAP, isBuiltinModule, splitPackageSpec } = require('./dependency-detector');
28
+
29
+ const { VERSION } = require('./version');
30
+
31
+ // ── Terminal colours (disabled when stdout is not a TTY) ──────────────────────
32
+
33
+ const HAS_COLOR = Boolean(process.stdout.isTTY);
34
+ function _c(code, text) { return HAS_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text; }
35
+ const clrGreen = (t) => _c('32', t);
36
+ const clrRed = (t) => _c('31', t);
37
+ const clrYellow = (t) => _c('33', t);
38
+ const clrCyan = (t) => _c('36', t);
39
+ const clrBold = (t) => _c('1', t);
40
+ const clrDim = (t) => _c('2', t);
41
+
42
+ function warn(message) {
43
+ console.warn(clrYellow(`⚠ Warning: ${message}`));
44
+ }
45
+
46
+ // Help text is built once at startup. Colours resolve to empty wrappers when
47
+ // stdout is not a TTY, so piped output (and the test suite) always sees plain
48
+ // text.
49
+ const section = (title) => `\n${clrCyan(clrBold(title))}`;
50
+
51
+ const HELP = `
52
+ ${clrBold(`PlainScript v${VERSION}`)} ${clrDim('· .pln compiles to readable Node.js')}
53
+
54
+ ${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/
58
+
59
+ ${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
64
+
65
+ ${section('PACKAGES')}
66
+ plainscript install Install everything your source needs
67
+ plainscript add <package> Install a package into the project
68
+ plainscript remove <package> Uninstall a package from the project
69
+ plainscript update Update all installed packages
70
+
71
+ ${section('TOOLS')}
72
+ plainscript doctor Check the project environment
73
+ plainscript version Print the compiler version
74
+ plainscript help Print this text
75
+
76
+ ${section('THE LANGUAGE IN EIGHT LINES')}
77
+ remember name as "Ada" show \`Hi \${name}\` variables, printing
78
+ if age is at least 13 ... done and · or · not conditions
79
+ for each p in players ... done while lives is above 0 loops
80
+ make add(a, b) / give a + b / done functions
81
+ web app / route get "/users" ... done / start 3000 web servers
82
+ database "app.db" / query ... done postgres env("URL") databases
83
+ get "<url>" / post "<url>" with body HTTP client
84
+ try ... recover as err ... done retry 3 times every 5s errors
85
+
86
+ ${section('ALSO SHIPPED')}
87
+ Comparisons and stdlib (v1.0) · PlainScript Expressions (v1.1) ·
88
+ JavaScript gateway with ask (v1.1.1) · OCR · Telegram bots ·
89
+ WhatsApp bots (v2.1.1) ·
90
+ email · schedules · WebSocket · cache (v2.1) ·
91
+ sessions · uploads · cookies · rate limits · api keys · OAuth (v2.1.1)
92
+
93
+ ${section('FIRST RUN')}
94
+ plainscript new hello scaffolds hello/ with a live web app
95
+ plainscript run hello/app.pln serves it at http://localhost:3000
96
+ `.trim();
97
+
98
+ // ── npm invocation ────────────────────────────────────────────────────────────
99
+
100
+ // Locate npm's CLI entry script so npm can be spawned through Node.
101
+ // Spawning "npm" directly fails on Windows since Node 18.20/20.12: npm ships
102
+ // as an .cmd shim there, and child_process refuses to spawn .bat/.cmd files
103
+ // for security reasons (CVE-2024-27980). Running npm-cli.js with
104
+ // process.execPath works on every platform and keeps argument arrays
105
+ // injection-safe because no shell is involved.
106
+ function findNpmCli() {
107
+ const candidates = [];
108
+ // Official Node distributions install npm next to the node executable.
109
+ candidates.push(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'));
110
+ try { candidates.push(require.resolve('npm/bin/npm-cli.js')); } catch (_) { /* npm not resolvable */ }
111
+ for (const candidate of candidates) {
112
+ if (fs.existsSync(candidate)) return candidate;
113
+ }
114
+ return null;
115
+ }
116
+
117
+ // Run npm with an argument array. Never uses a shell unless absolutely
118
+ // necessary (Windows fallback without npm-cli.js), so package names can never
119
+ // be interpreted as shell commands.
120
+ function runNpm(args, options = {}) {
121
+ const npmCli = findNpmCli();
122
+ if (npmCli) return execFileSync(process.execPath, [npmCli, ...args], options);
123
+ return execFileSync('npm', args, { ...options, shell: process.platform === 'win32' });
124
+ }
125
+
126
+ // ── Package-name validation ───────────────────────────────────────────────────
127
+
128
+ // Accept standard npm package names including scoped packages (@org/pkg).
129
+ // Rejects anything that could be used for shell injection or path traversal.
130
+ function isValidPackageName(name) {
131
+ return typeof name === 'string' && /^(@[a-z0-9-_.]+\/)?[a-z0-9-_.]+$/i.test(name);
132
+ }
133
+
134
+ // ── Build conventions ────────────────────────────────────────────────────────
135
+ //
136
+ // `plainscript build` follows a TypeScript-style model:
137
+ //
138
+ // Zero configuration (default):
139
+ // - sources are discovered automatically under "src/" (the project root is
140
+ // scanned when no src/ directory exists)
141
+ // - output always goes to "dist/"
142
+ //
143
+ // Optional plainscript.config.json (tsconfig-like):
144
+ // { "compilerOptions": { "outDir": "./build", "rootDir": "./lib",
145
+ // "exclude": ["vendor"] } }
146
+ //
147
+ // Filenames and folder structure are always preserved:
148
+ // src/messi.pln → dist/messi.js
149
+ // src/helpers/math.pln → dist/helpers/math.js
150
+ const SOURCE_DIR = 'src';
151
+ const DEFAULT_OUT_DIR = 'dist';
152
+
153
+ // Read optional plainscript.config.json. Returns { compilerOptions } or null.
154
+ // The file is tsconfig-like: only compilerOptions.outDir, compilerOptions.rootDir,
155
+ // and compilerOptions.exclude are used.
156
+ function readCompilerOptions() {
157
+ const configPath = path.resolve('plainscript.config.json');
158
+ if (!fs.existsSync(configPath)) return null;
159
+ try {
160
+ const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
161
+ return raw.compilerOptions || null;
162
+ } catch (e) {
163
+ console.error(`plainscript.config.json is not valid JSON: ${e.message}`);
164
+ process.exit(1);
165
+ }
166
+ }
167
+
168
+ // Resolve the source root directory.
169
+ // Priority: config rootDir > automatic src/ detection > project root.
170
+ function resolveSrcDir(opts) {
171
+ if (opts && opts.rootDir) return opts.rootDir;
172
+ return fs.existsSync(path.resolve(SOURCE_DIR)) ? SOURCE_DIR : '.';
173
+ }
174
+
175
+ // Resolve the output directory.
176
+ // Priority: config outDir > default "dist".
177
+ function resolveOutDir(opts) {
178
+ if (opts && opts.outDir) return opts.outDir;
179
+ return DEFAULT_OUT_DIR;
180
+ }
181
+
182
+ // Every .pln file under srcDir, recursively, as paths relative to srcDir.
183
+ // Deterministic order (sorted); node_modules, hidden directories, the output
184
+ // directory, and any user-specified exclude patterns are skipped.
185
+ function discoverSources(srcDir, outDir, exclude) {
186
+ const root = path.resolve(srcDir);
187
+ const outAbs = path.resolve(outDir);
188
+ const excludeSet = new Set(['node_modules']);
189
+ // Always exclude the output directory and hidden directories
190
+ excludeSet.add(path.basename(outAbs));
191
+ // Add user-specified excludes
192
+ if (Array.isArray(exclude)) {
193
+ for (const pattern of exclude) excludeSet.add(pattern);
194
+ }
195
+ const found = [];
196
+ (function walk(dir) {
197
+ for (const name of fs.readdirSync(dir).sort()) {
198
+ if (name.startsWith('.')) continue;
199
+ if (excludeSet.has(name)) continue;
200
+ const full = path.join(dir, name);
201
+ let stat;
202
+ try { stat = fs.statSync(full); } catch (_) { continue; }
203
+ if (stat.isDirectory()) {
204
+ walk(full);
205
+ } else if (name.endsWith('.pln')) {
206
+ found.push(path.relative(root, full));
207
+ }
208
+ }
209
+ })(root);
210
+ return found;
211
+ }
212
+
213
+ // ── Helpers ──────────────────────────────────────────────────────────────────
214
+
215
+ // Project builds compile many files in one pass; per-file stage logs would
216
+ // drown the useful output. Set before batch compilation, reset after.
217
+ let QUIET_STAGES = false;
218
+
219
+ function stage(label, fn) {
220
+ const t0 = Date.now();
221
+ try {
222
+ const result = fn();
223
+ const ms = Date.now() - t0;
224
+ if (!QUIET_STAGES) console.log(`${clrGreen('✓')} ${label}${ms > 50 ? clrDim(` (${ms}ms)`) : ''}`);
225
+ return result;
226
+ } catch (err) {
227
+ console.error(`${clrRed('✗')} ${label} failed\n`);
228
+ console.error(err.message);
229
+ process.exit(1);
230
+ }
231
+ }
232
+
233
+ // Map PlainScript package names to their npm package names (same as the compiler's
234
+ // KNOWN_PACKAGES in generator.js).
235
+ // Keep dependency checks in one CLI execution cheap and deterministic.
236
+ const dependencyCache = new Map();
237
+
238
+ // Check whether an npm package is installed in this project's node_modules.
239
+ // Deliberately NOT require.resolve: that would also walk up ancestor
240
+ // directories and global folders, reporting a package as available when this
241
+ // project does not actually have it.
242
+ function isInstalled(npmPkg, cwd = process.cwd()) {
243
+ if (isBuiltinModule(npmPkg)) return true;
244
+ const cacheKey = `${cwd}\0${npmPkg}`;
245
+ if (dependencyCache.has(cacheKey)) return dependencyCache.get(cacheKey);
246
+ const segments = npmPkg.split('/');
247
+ const pkgDir = path.join(cwd, 'node_modules', ...segments);
248
+ const installed =
249
+ fs.existsSync(path.join(pkgDir, 'package.json')) ||
250
+ (segments.length > 1 && fs.existsSync(pkgDir)); // scope placeholder
251
+ dependencyCache.set(cacheKey, installed);
252
+ return installed;
253
+ }
254
+
255
+ function npmNameFor(plainPkg) {
256
+ return PACKAGE_MAP[plainPkg] || plainPkg;
257
+ }
258
+
259
+ function requiredDependencies(files) {
260
+ const packages = new Set();
261
+ for (const { ast } of files) {
262
+ for (const npm of detectDependencies(ast)) packages.add(npm);
263
+ }
264
+ return [...packages];
265
+ }
266
+
267
+ // Ensure a package.json exists in the project directory before invoking npm.
268
+ // Without one, npm walks up the directory tree and may install into an
269
+ // unrelated ancestor project's node_modules instead of this project's. The
270
+ // scaffold is minimal and marked private so it is never published.
271
+ function ensurePackageJson(cwd = process.cwd()) {
272
+ const pkgPath = path.join(cwd, 'package.json');
273
+ if (fs.existsSync(pkgPath)) return;
274
+ fs.writeFileSync(pkgPath, JSON.stringify({
275
+ name: path.basename(cwd),
276
+ version: '0.1.0',
277
+ private: true,
278
+ }, null, 2) + '\n', 'utf8');
279
+ }
280
+
281
+ // v2.1.1 — verify that a freshly installed package actually LOADS on this
282
+ // machine. "better-sqlite3 present in node_modules" does not imply usable:
283
+ // its native binding may be missing for this platform or Node ABI (the
284
+ // Termux failure mode). The check runs in a child process so a hard crash
285
+ // inside the package cannot take the CLI down.
286
+ function verifyPackageUsable(npmPkg, cwd = process.cwd()) {
287
+ const probe =
288
+ `try {` +
289
+ ` const mod = require(${JSON.stringify(npmPkg)});` +
290
+ ` if (${JSON.stringify(npmPkg)} === 'better-sqlite3') {` +
291
+ ` const db = new mod(':memory:');` +
292
+ ` db.close();` +
293
+ ` }` +
294
+ ` process.exit(0);` +
295
+ `} catch (_) { process.exit(1); }`;
296
+ try {
297
+ execFileSync(process.execPath, ['-e', probe], { cwd, stdio: 'ignore' });
298
+ return true;
299
+ } catch (_) {
300
+ return false;
301
+ }
302
+ }
303
+
304
+ function installPackages(packages, cwd = process.cwd()) {
305
+ ensurePackageJson(cwd);
306
+ for (const pkg of packages) {
307
+ const bareName = splitPackageSpec(pkg).name;
308
+ console.log(`${clrCyan('Installing')} ${pkg}...`);
309
+ try {
310
+ runNpm(['install', pkg, '--no-audit', '--no-fund'], {
311
+ cwd,
312
+ stdio: 'ignore',
313
+ });
314
+ dependencyCache.set(`${cwd}\0${bareName}`, true);
315
+ // v2.1.1 — "downloaded" and "usable" are different facts. Report both.
316
+ if (verifyPackageUsable(bareName, cwd)) {
317
+ console.log(`${clrGreen('✓')} ${pkg} installed`);
318
+ } else {
319
+ console.log(
320
+ `${clrYellow('⚠')} ${pkg} downloaded but NOT usable on this platform ` +
321
+ `(its native code could not be loaded). Programs that can fall back ` +
322
+ `(like SQLite) will still work; otherwise fix this package before running.`
323
+ );
324
+ }
325
+ } catch (_) {
326
+ // v2.1.1 — better-sqlite3 is optional at install time: programs opened
327
+ // through the portable engine chain fall back to sql.js, so a native
328
+ // build failure must not abort setup.
329
+ if (bareName === 'better-sqlite3') {
330
+ console.log(
331
+ `${clrYellow('⚠')} ${pkg} could not be installed on this platform. ` +
332
+ `PlainScript will use its WebAssembly SQLite engine instead.`
333
+ );
334
+ continue;
335
+ }
336
+ throw new Error(
337
+ `Could not install "${pkg}". The package may be unavailable or the machine may be offline.\n` +
338
+ `Run manually: npm install ${pkg}`
339
+ );
340
+ }
341
+ }
342
+ }
343
+
344
+ function ensureDependencies(files, install = true) {
345
+ const required = requiredDependencies(files);
346
+ const missing = required.filter(pkg => !isInstalled(splitPackageSpec(pkg).name));
347
+ if (missing.length === 0) return { required, missing };
348
+ if (install) {
349
+ installPackages(missing);
350
+ return { required, missing: [] };
351
+ }
352
+ const lines = missing.map(pkg => ` Package "${pkg}" is not installed.\n Run: npm install ${pkg}`);
353
+ throw new Error(`Missing dependencies:\n\n${lines.join('\n\n')}`);
354
+ }
355
+
356
+ // Compile a PlainScript program to JavaScript.
357
+ //
358
+ // Deterministic only: the lexer/parser/generator pipeline is the single
359
+ // authoritative compiler. Unsupported syntax produces a precise compiler
360
+ // error — there is no second compilation path (v2.1.1).
361
+ function compile(filePath) {
362
+ const absPath = path.resolve(filePath);
363
+ if (!fs.existsSync(absPath)) {
364
+ console.error(`File not found: ${filePath}`);
365
+ process.exit(1);
366
+ }
367
+ const generationContext = createGenerationContext();
368
+
369
+ let files;
370
+ stage('Resolving imports', () => {
371
+ files = resolveDependencies(absPath);
372
+ });
373
+ stage('Building dependency graph', () => files);
374
+ stage('Checking runtime dependencies', () => ensureDependencies(files, true));
375
+ const js = stage('Generating JavaScript', () =>
376
+ files.map(({ ast }) => generate(ast, generationContext)).filter(s => s.trim()).join('\n'));
377
+ return generationContext.needsAsync ? wrapAsync(js) : js;
378
+ }
379
+
380
+ // ── Commands ─────────────────────────────────────────────────────────────────
381
+
382
+ // Node resolves require(...) against the temp file's location, so a scratch
383
+ // file in the OS temp dir could never see the project's node_modules. Passing
384
+ // every node_modules directory between the entry file and the filesystem root
385
+ // through NODE_PATH gives the child the exact same resolution the old
386
+ // project-local temp file had — without ever writing into the project.
387
+ function nodeModulesSearchPaths(entryDir) {
388
+ const paths = [];
389
+ let dir = path.resolve(entryDir);
390
+ while (true) {
391
+ const candidate = path.join(dir, 'node_modules');
392
+ if (fs.existsSync(candidate)) paths.push(candidate);
393
+ const parent = path.dirname(dir);
394
+ if (parent === dir) break;
395
+ dir = parent;
396
+ }
397
+ return paths;
398
+ }
399
+
400
+ async function cmdRun(filePath, extraArgs = []) {
401
+ if (!filePath) {
402
+ console.error('Usage: plainscript run <file.pln>');
403
+ process.exit(1);
404
+ }
405
+ const js = compile(filePath);
406
+ console.log('');
407
+ // Execute from the entry file's directory so relative assets and CWD-based
408
+ // behaviour match a direct `node` invocation.
409
+ const entryDir = path.dirname(path.resolve(filePath));
410
+ const searchPaths = nodeModulesSearchPaths(entryDir);
411
+ const tmpDir = fs.mkdtempSync(path.join(require('os').tmpdir(), 'plainscript-run-'));
412
+ const tmpFile = path.join(tmpDir, 'out.js');
413
+ fs.writeFileSync(tmpFile, js, 'utf8');
414
+ try {
415
+ execFileSync(process.execPath, [tmpFile, ...extraArgs], {
416
+ stdio: 'inherit',
417
+ cwd: entryDir,
418
+ env: { ...process.env, NODE_PATH: searchPaths.join(path.delimiter) },
419
+ });
420
+ } catch (e) {
421
+ fs.rmSync(tmpDir, { recursive: true, force: true });
422
+ console.error('\nThe program exited with an error. See the message above.');
423
+ process.exit(1);
424
+ }
425
+ fs.rmSync(tmpDir, { recursive: true, force: true });
426
+ console.log('\nDone.');
427
+ }
428
+
429
+ // Compile one entry and write it to outDir with its source name preserved,
430
+ // relative to the source root when the file lives inside it.
431
+ function buildOne(filePath, srcDir, outDir) {
432
+ const absFile = path.resolve(filePath);
433
+ if (!fs.existsSync(absFile)) {
434
+ console.error(`File not found: ${filePath}`);
435
+ process.exit(1);
436
+ }
437
+ const js = compile(absFile);
438
+ 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');
441
+ const outPath = path.join(path.resolve(outDir), rel);
442
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
443
+ fs.writeFileSync(outPath, js, 'utf8');
444
+ return path.relative(process.cwd(), outPath) || outPath;
445
+ }
446
+
447
+ // `plainscript build` — TypeScript-style production build:
448
+ //
449
+ // 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)
453
+ //
454
+ // With plainscript.config.json:
455
+ // { "compilerOptions": { "outDir": "./build", "rootDir": "./lib" } }
456
+ // lib/app.pln → build/app.js
457
+ //
458
+ // 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.
460
+ async function cmdBuild(filePath) {
461
+ const opts = readCompilerOptions();
462
+ const srcDir = resolveSrcDir(opts);
463
+ const outDir = resolveOutDir(opts);
464
+ const exclude = opts && opts.exclude;
465
+ if (filePath) {
466
+ const outPath = buildOne(filePath, srcDir, outDir);
467
+ console.log(`\nOutput written to ${outPath}`);
468
+ return;
469
+ }
470
+ const sources = discoverSources(srcDir, outDir, exclude);
471
+ if (sources.length === 0) {
472
+ console.error(`No .pln files found under "${srcDir}".`);
473
+ process.exit(1);
474
+ }
475
+ QUIET_STAGES = true;
476
+ let built;
477
+ try {
478
+ built = sources.map((rel) => ({
479
+ source: path.join(srcDir === '.' ? '' : srcDir, rel),
480
+ outPath: buildOne(path.join(path.resolve(srcDir), rel), srcDir, outDir),
481
+ }));
482
+ } finally {
483
+ QUIET_STAGES = false;
484
+ }
485
+ for (const { source, outPath } of built) {
486
+ console.log(`${clrGreen('✓')} ${source} -> ${outPath}`);
487
+ }
488
+ console.log(`\n${built.length} file(s) compiled to ${outDir}/.`);
489
+ }
490
+
491
+ async function cmdStart(extraArgs = []) {
492
+ const opts = readCompilerOptions();
493
+ const srcDir = resolveSrcDir(opts);
494
+ const outDir = resolveOutDir(opts);
495
+ const entryPath = findEntry(opts);
496
+ if (!entryPath) {
497
+ console.error('No entry file found. Expected "src/app.pln" or "src/index.pln".');
498
+ process.exit(1);
499
+ }
500
+ const outFile = buildOne(entryPath, srcDir, outDir);
501
+ const entryDir = path.dirname(path.resolve(entryPath));
502
+ execFileSync(process.execPath, [path.resolve(outFile), ...extraArgs], {
503
+ stdio: 'inherit',
504
+ cwd: entryDir,
505
+ env: { ...process.env, NODE_PATH: nodeModulesSearchPaths(entryDir).join(path.delimiter) },
506
+ });
507
+ }
508
+
509
+ function cmdNew(projectName) {
510
+ const name = projectName || 'my-plainscript-app';
511
+ const dir = path.resolve(name);
512
+
513
+ if (fs.existsSync(dir)) {
514
+ console.error(`Directory "${name}" already exists.`);
515
+ process.exit(1);
516
+ }
517
+
518
+ fs.mkdirSync(dir);
519
+ fs.mkdirSync(path.join(dir, 'public'));
520
+ fs.mkdirSync(path.join(dir, 'src'));
521
+
522
+ // src/app.pln — starter Express app
523
+ fs.writeFileSync(path.join(dir, 'src', 'app.pln'), `use express
524
+
525
+ remember app as express()
526
+
527
+ serve folder "public"
528
+
529
+ when someone visits "/"
530
+ reply "Hello from PlainScript!"
531
+ done
532
+
533
+ when someone visits "/api/status"
534
+ reply json
535
+ status is "ok"
536
+ version is "1.0"
537
+ done
538
+ done
539
+
540
+ listen on 3000
541
+ show "Server running at http://localhost:3000"
542
+ done
543
+ `);
544
+
545
+ // package.json — plain Node semantics; PlainScript itself is a devDependency and
546
+ // deployment only needs the generated dist/ output.
547
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
548
+ name,
549
+ version: '1.0.0',
550
+ description: `A PlainScript v${VERSION} application`,
551
+ main: 'dist/app.js',
552
+ scripts: {
553
+ build: 'plainscript build',
554
+ start: 'node dist/app.js',
555
+ },
556
+ devDependencies: {
557
+ plainscript: `^${VERSION}`,
558
+ },
559
+ dependencies: {
560
+ express: '^4.18.2',
561
+ },
562
+ }, null, 2) + '\n');
563
+
564
+ // README.md
565
+ fs.writeFileSync(path.join(dir, 'README.md'), `# ${name}
566
+
567
+ A PlainScript v${VERSION} application.
568
+
569
+ ## Getting started
570
+
571
+ \`\`\`bash
572
+ npm install
573
+ npm run build
574
+ npm start
575
+ \`\`\`
576
+
577
+ Then open http://localhost:3000 in your browser.
578
+ `);
579
+
580
+ console.log(`✓ Created project "${name}"`);
581
+ console.log(`\nNext steps:\n cd ${name}\n npm install\n npx plainscript run src/app.pln`);
582
+ }
583
+
584
+ // ── plainscript install ────────────────────────────────────────────────────────────
585
+
586
+ // Locate the project entry for commands that work on a single program (start):
587
+ // conventional defaults inside src/ first, then the project root.
588
+ function findEntry(opts) {
589
+ const srcDir = resolveSrcDir(opts);
590
+ const candidates = [
591
+ path.join(srcDir, 'app.pln'),
592
+ path.join(srcDir, 'index.pln'),
593
+ ];
594
+ if (srcDir !== '.') {
595
+ candidates.push('app.pln', 'index.pln');
596
+ }
597
+ return candidates.find((c) => fs.existsSync(path.resolve(c))) || null;
598
+ }
599
+
600
+ // Parse every discovered source file and return ASTs ready for dependency
601
+ // detection. Parsing each file directly means dependencies are found even
602
+ // when nothing imports a given module yet.
603
+ function collectSourceAsts() {
604
+ const opts = readCompilerOptions();
605
+ const srcDir = resolveSrcDir(opts);
606
+ const outDir = resolveOutDir(opts);
607
+ const exclude = opts && opts.exclude;
608
+ const sources = discoverSources(srcDir, outDir, exclude);
609
+ if (sources.length === 0) {
610
+ console.error(`No .pln source files found under "${srcDir}".`);
611
+ process.exit(1);
612
+ }
613
+ const root = path.resolve(srcDir);
614
+ return sources.map((rel) => ({
615
+ ast: parse(tokenize(fs.readFileSync(path.join(root, rel), 'utf8'))),
616
+ }));
617
+ }
618
+
619
+ function cmdInstall() {
620
+ console.log('Scanning source files...');
621
+ const asts = collectSourceAsts();
622
+
623
+ const requiredPackages = requiredDependencies(asts);
624
+ if (requiredPackages.length === 0) {
625
+ console.log('This project has no external dependencies.');
626
+ return;
627
+ }
628
+
629
+ // Determine which are missing
630
+ const missing = requiredPackages.filter(pkg => !isInstalled(splitPackageSpec(pkg).name));
631
+
632
+ if (missing.length === 0) {
633
+ for (const pkg of requiredPackages) console.log(`${clrGreen('✓')} ${pkg} already installed`);
634
+ console.log('All dependencies are already installed.');
635
+ return;
636
+ }
637
+
638
+ console.log(`Found ${requiredPackages.length} required package(s).`);
639
+ console.log(`Installing ${missing.length} missing package(s)...`);
640
+
641
+ try {
642
+ installPackages(missing);
643
+ } catch (e) {
644
+ console.error(e.message);
645
+ process.exit(1);
646
+ }
647
+ console.log('Done.');
648
+ }
649
+
650
+ function cmdDoctor() {
651
+ console.log('PlainScript doctor\n');
652
+ const check = (label, ok, detail = '') => {
653
+ const suffix = detail ? ` — ${detail}` : '';
654
+ console.log(`${ok ? clrGreen('✓') : clrRed('✗')} ${label}${suffix}`);
655
+ };
656
+ check('Node.js', Boolean(process.version));
657
+ let npmVersion = '';
658
+ try { npmVersion = runNpm(['--version'], { encoding: 'utf8' }).trim(); } catch (_) {}
659
+ check('npm', Boolean(npmVersion), npmVersion);
660
+ check('PlainScript CLI', true);
661
+ check('Compiler', fs.existsSync(path.join(__dirname, 'parser.js')));
662
+ check('Formatter', fs.existsSync(path.join(__dirname, 'formatter.js')));
663
+ check('Runtime', fs.existsSync(path.join(__dirname, 'generator.js')));
664
+ console.log('');
665
+
666
+ // Source discovery check: does the project have any .pln files?
667
+ const opts = readCompilerOptions();
668
+ const srcDir = resolveSrcDir(opts);
669
+ const outDir = resolveOutDir(opts);
670
+ const exclude = opts && opts.exclude;
671
+ const sources = discoverSources(srcDir, outDir, exclude);
672
+ check('Source files', sources.length > 0,
673
+ sources.length > 0 ? `"${srcDir}/" discovered (${sources.length} file(s))` : `no .pln files under "${srcDir}"`);
674
+ if (sources.length === 0) return;
675
+
676
+ // Dependency check: scan every source file for npm imports
677
+ try {
678
+ const root = path.resolve(srcDir);
679
+ const asts = sources.map(rel => ({
680
+ ast: parse(tokenize(fs.readFileSync(path.join(root, rel), 'utf8'))),
681
+ }));
682
+ const required = requiredDependencies(asts);
683
+ const missing = required.filter(pkg => !isInstalled(splitPackageSpec(pkg).name));
684
+ check('Dependencies', missing.length === 0,
685
+ missing.length ? `missing: ${missing.join(', ')}` : 'ready');
686
+ } catch (err) {
687
+ check('Dependencies', false, err.message);
688
+ }
689
+ }
690
+
691
+ function cmdAdd(packageName) {
692
+ if (!packageName) {
693
+ console.error('Usage: plainscript add <package>');
694
+ process.exit(1);
695
+ }
696
+ if (!isValidPackageName(packageName)) {
697
+ console.error(`Invalid package name: "${packageName}".`);
698
+ process.exit(1);
699
+ }
700
+
701
+ console.log(`Installing ${packageName}...`);
702
+ try {
703
+ ensurePackageJson();
704
+ runNpm(['install', packageName, '--save'], { stdio: 'inherit', cwd: process.cwd() });
705
+ } catch (e) {
706
+ console.error(`Failed to install "${packageName}".`);
707
+ process.exit(1);
708
+ }
709
+ console.log(`✓ Installed "${packageName}".`);
710
+ }
711
+
712
+ function cmdRemove(packageName) {
713
+ if (!packageName) {
714
+ console.error('Usage: plainscript remove <package>');
715
+ process.exit(1);
716
+ }
717
+ if (!isValidPackageName(packageName)) {
718
+ console.error(`Invalid package name: "${packageName}".`);
719
+ process.exit(1);
720
+ }
721
+
722
+ console.log(`Uninstalling ${packageName}...`);
723
+ try {
724
+ ensurePackageJson();
725
+ runNpm(['uninstall', packageName], { stdio: 'inherit', cwd: process.cwd() });
726
+ } catch (e) {
727
+ console.error(`Failed to uninstall "${packageName}".`);
728
+ process.exit(1);
729
+ }
730
+ console.log(`✓ Removed "${packageName}".`);
731
+ }
732
+
733
+ function cmdUpdate() {
734
+ console.log('Updating packages...');
735
+ try {
736
+ // Anchor npm to this project: without a local package.json it would walk
737
+ // up the directory tree and update an unrelated ancestor project.
738
+ ensurePackageJson();
739
+ runNpm(['update'], { stdio: 'inherit', cwd: process.cwd() });
740
+ console.log('\n✓ Packages updated.');
741
+ } catch (e) {
742
+ console.error('npm update failed.');
743
+ process.exit(1);
744
+ }
745
+ }
746
+
747
+ // 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
+ }
758
+ const t0 = Date.now();
759
+ try {
760
+ resolveDependencies(absPath);
761
+ const ms = Date.now() - t0;
762
+ console.log(`${clrGreen('✓')} ${filePath} — no errors found.${clrDim(` (${ms}ms)`)}`);
763
+ } catch (err) {
764
+ console.error(err.message);
765
+ process.exit(1);
766
+ }
767
+ }
768
+
769
+ // Format a PlainScript file in-place.
770
+ function cmdFmt(filePath) {
771
+ if (!filePath) {
772
+ console.error('Usage: plainscript fmt <file.pln>');
773
+ process.exit(1);
774
+ }
775
+ const absPath = path.resolve(filePath);
776
+ if (!fs.existsSync(absPath)) {
777
+ console.error(`File not found: ${filePath}`);
778
+ process.exit(1);
779
+ }
780
+ const source = fs.readFileSync(absPath, 'utf8');
781
+ const formatted = format(source);
782
+ if (source === formatted) {
783
+ console.log(`${clrDim('–')} ${filePath} — already formatted.`);
784
+ } else {
785
+ fs.writeFileSync(absPath, formatted, 'utf8');
786
+ console.log(`${clrGreen('✓')} Formatted ${filePath}`);
787
+ }
788
+ }
789
+
790
+ function cmdVersion() {
791
+ console.log(`PlainScript v${VERSION}`);
792
+ }
793
+
794
+ function cmdHelp() {
795
+ console.log(HELP);
796
+ }
797
+
798
+ // ── Entry point ───────────────────────────────────────────────────────────────
799
+
800
+ async function main() {
801
+ const args = process.argv.slice(2);
802
+
803
+ // Global flags — recognized anywhere in the argument list.
804
+ const quiet = args.includes('--quiet');
805
+ const verbose = args.includes('--verbose');
806
+ if (quiet) { stage = stageQuiet; QUIET_STAGES = true; }
807
+ if (verbose) { stage = stageVerbose; VERBOSE = true; }
808
+
809
+ // Filter flags out to get the positional arguments.
810
+ const positional = args.filter(a => !a.startsWith('--'));
811
+ const [, , command, fileArg] = positional.length >= 2
812
+ ? ['', '', positional[0], positional[1]]
813
+ : ['', '', positional[0] || '', ''];
814
+
815
+ switch (command) {
816
+ case 'run': await cmdRun(fileArg, positional.slice(2)); break;
817
+ case 'build': await cmdBuild(fileArg); break;
818
+ case 'check': cmdCheck(fileArg); break;
819
+ case 'fmt': cmdFmt(fileArg); break;
820
+ case 'new': cmdNew(fileArg); break;
821
+ case 'install': cmdInstall(); break;
822
+ case 'start': await cmdStart(positional.slice(2)); break;
823
+ case 'doctor': cmdDoctor(); break;
824
+ case 'add': cmdAdd(fileArg); break;
825
+ case 'remove': cmdRemove(fileArg); break;
826
+ case 'update': cmdUpdate(); break;
827
+ case 'version': cmdVersion(); break;
828
+ case 'help': cmdHelp(); break;
829
+ default:
830
+ // Backwards-compatible: treat the first arg as a file to run directly
831
+ if (command && command.endsWith('.pln')) {
832
+ await cmdRun(command);
833
+ } else {
834
+ console.error(`Unknown command: "${command}". Run "plainscript help" for usage.`);
835
+ process.exit(1);
836
+ }
837
+ }
838
+ }
839
+
840
+ main().catch((err) => {
841
+ console.error(err.message);
842
+ process.exit(1);
843
+ });