plainscript-lang 1.0.361 → 1.0.363

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 (97) hide show
  1. package/README.md +383 -55
  2. package/compiler/bundler.js +78 -3
  3. package/compiler/cli.js +224 -30
  4. package/compiler/formatter.js +21 -1
  5. package/compiler/generator.js +490 -114
  6. package/compiler/ir.js +61 -0
  7. package/compiler/lexer.js +42 -7
  8. package/compiler/lsp.js +234 -0
  9. package/compiler/parser.js +780 -110
  10. package/compiler/type-checker.js +246 -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 +308 -0
  15. package/docs/PLAINSCRIPT-SPEC.md +231 -5
  16. package/docs/index.html +5 -5
  17. package/docs/website/script.js +1 -1
  18. package/examples/ai-memory-cli.pln +221 -0
  19. package/examples/ai-memory.json +1 -0
  20. package/examples/ai-providers.pln +1 -1
  21. package/examples/arrays.pln +1 -1
  22. package/examples/async-errors.pln +1 -1
  23. package/examples/auth-api.pln +1 -1
  24. package/examples/auth-sessions.pln +1 -1
  25. package/examples/basics.pln +1 -1
  26. package/examples/bots.pln +1 -1
  27. package/examples/browser-interactive/README.md +1 -1
  28. package/examples/browser-interactive/src/interactive.pln +1 -1
  29. package/examples/cache-and-jobs.pln +1 -1
  30. package/examples/cache-schedule.pln +1 -1
  31. package/examples/canvas-game/README.md +1 -1
  32. package/examples/canvas-game/src/game.pln +1 -1
  33. package/examples/collections.pln +1 -1
  34. package/examples/compound-assignments.pln +24 -0
  35. package/examples/concurrency.pln +2 -2
  36. package/examples/conditions.pln +1 -1
  37. package/examples/database.pln +1 -1
  38. package/examples/day2.pln +1 -1
  39. package/examples/day3.pln +1 -1
  40. package/examples/deployment.pln +1 -1
  41. package/examples/email-send.pln +1 -1
  42. package/examples/error-handling.pln +1 -1
  43. package/examples/expressions.pln +1 -1
  44. package/examples/file-manager-cli.pln +51 -0
  45. package/examples/file-uploads.pln +1 -1
  46. package/examples/files-and-config.pln +1 -1
  47. package/examples/files.pln +1 -1
  48. package/examples/football-backend/app.pln +1 -1
  49. package/examples/functions.pln +1 -1
  50. package/examples/hello.pln +1 -1
  51. package/examples/http-client.pln +1 -1
  52. package/examples/http.pln +1 -1
  53. package/examples/id-verification/app.pln +1 -1
  54. package/examples/interactive-cli.pln +34 -0
  55. package/examples/javascript-library/README.md +1 -1
  56. package/examples/javascript-library/src/interop.pln +1 -1
  57. package/examples/json.pln +1 -1
  58. package/examples/loops.pln +1 -1
  59. package/examples/memoize-demo.pln +31 -0
  60. package/examples/modules/app.pln +1 -1
  61. package/examples/modules/main.pln +1 -1
  62. package/examples/modules/math.pln +1 -1
  63. package/examples/mongo.pln +1 -1
  64. package/examples/normalization-forms.pln +22 -0
  65. package/examples/objects.pln +1 -1
  66. package/examples/ocr.pln +1 -1
  67. package/examples/packages.pln +1 -1
  68. package/examples/random-cli.pln +32 -0
  69. package/examples/record-kinds.pln +1 -1
  70. package/examples/records.pln +1 -1
  71. package/examples/rest-api-fetch.pln +1 -1
  72. package/examples/rest-api.pln +1 -1
  73. package/examples/run-in-parallel.pln +25 -0
  74. package/examples/scheduled-tasks.pln +1 -1
  75. package/examples/search-and-filter.pln +1 -1
  76. package/examples/server.pln +1 -1
  77. package/examples/sessions-and-cookies.pln +1 -1
  78. package/examples/sqlite.pln +1 -1
  79. package/examples/start.pln +1 -1
  80. package/examples/stats-cli.pln +29 -0
  81. package/examples/stdlib.pln +1 -1
  82. package/examples/string-helpers.pln +23 -0
  83. package/examples/string-verbs.pln +1 -1
  84. package/examples/telegram-ai-bot.pln +1 -1
  85. package/examples/telegram-bot.pln +1 -1
  86. package/examples/terminal-cli.pln +11 -0
  87. package/examples/testing.pln +1 -1
  88. package/examples/three-dimensional/README.md +1 -1
  89. package/examples/three-dimensional/src/scene.pln +1 -1
  90. package/examples/todo-cli.pln +98 -0
  91. package/examples/web-api.pln +1 -1
  92. package/examples/web-app.pln +1 -1
  93. package/examples/websocket-server.pln +1 -1
  94. package/examples/websocket.pln +1 -1
  95. package/examples/whatsapp-bot/pairing.pln +1 -1
  96. package/examples/whatsapp-bot/qr.pln +1 -1
  97. package/package.json +16 -6
package/README.md CHANGED
@@ -29,6 +29,7 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
29
29
  - [CLI Reference](#cli-reference)
30
30
  - [Building & Configuration](#building--configuration)
31
31
  - [Language Tour](#language-tour)
32
+ - [Closing blocks with `end`](#closing-blocks-with-end)
32
33
  - [Variables](#variables)
33
34
  - [String Templates](#string-templates)
34
35
  - [Conditions](#conditions)
@@ -40,8 +41,11 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
40
41
  - [Loops](#loops)
41
42
  - [Natural-Language Expressions](#natural-language-expressions)
42
43
  - [Logical Assignment](#logical-assignment)
44
+ - [Compound Assignment](#compound-assignment)
45
+ - [Assignment aliases](#assignment-aliases)
43
46
  - [Error handling, async, and events](#error-handling-async-and-events)
44
47
  - [Record Kinds, Concurrency & More](#record-kinds-concurrency--more)
48
+ - [Concurrency: `run in parallel`](#concurrency-run-in-parallel)
45
49
  - [Backend Services](#backend-services)
46
50
  - [Databases](#databases)
47
51
  - [HTTP Client](#http-client)
@@ -52,6 +56,10 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
52
56
  - [Google OAuth](#google-oauth)
53
57
  - [Error Handling & Retries](#error-handling--retries)
54
58
  - [Runtime Standard Library](#runtime-standard-library)
59
+ - [Interactive Terminal & CLI Primitives](#interactive-terminal--cli-primitives)
60
+ - [Statistics & Vectors](#statistics--vectors)
61
+ - [Randomness](#randomness)
62
+ - [Memoization & Parsing Helpers](#memoization--parsing-helpers)
55
63
  - [Web Applications](#web-applications)
56
64
  - [Browser games and interactive apps](#browser-games-and-interactive-apps)
57
65
  - [Additional Backend Capabilities](#additional-backend-capabilities)
@@ -63,6 +71,7 @@ Describe *what* you want. The compiler decides *how* to implement it in JavaScri
63
71
  - [Cache](#cache)
64
72
  - [AI / ML](#ai--ml)
65
73
  - [Pagination](#pagination)
74
+ - [AI-Readiness: On-Device Intelligence](#ai-readiness-on-device-intelligence)
66
75
  - [Multi-File Projects](#multi-file-projects)
67
76
  - [Express Integration](#express-integration)
68
77
  - [WhatsApp Bots](#whatsapp-bots)
@@ -122,7 +131,7 @@ done
122
131
  </tr>
123
132
  </table>
124
133
 
125
- **Current version:** `v1.0.361` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
134
+ **Current version:** `v1.0.363` - the `plainscript-lang` npm package, with a TypeScript-style production build (`plainscript build` → `dist/`, source names and structure preserved).
126
135
 
127
136
  ---
128
137
 
@@ -172,7 +181,7 @@ whatsapp bot
172
181
  auth "session"
173
182
  login qr
174
183
  done
175
- ```
184
+ ```plainscript
176
185
 
177
186
  For a local adapter, install it from the project directory (for example,
178
187
  `npm install ./vendor/baileys`) and ensure it exposes the Baileys default
@@ -187,8 +196,11 @@ socket export plus `useMultiFileAuthState`, `makeCacheableSignalKeyStore`, and
187
196
  | Command | Description |
188
197
  |---|---|
189
198
  | `plainscript run <file.pln>` | Installs missing dependencies, compiles, and executes. Runs from a scratch directory - nothing is written into your project. |
199
+ | `plainscript test [target]` | Runs a PlainScript test file or all `*.test.pln` / `*.spec.pln` files under `tests/` (or `test/`). |
200
+ | `plainscript ir <file.pln>` | Emits the stable, backend-neutral compiler IR as JSON for tooling and diagnostics. |
201
+ | `plainscript-lsp` | Runs the stdio Language Server Protocol service for editor diagnostics, hover, completion, definitions, and symbols. |
190
202
  | `plainscript build [file.pln]` | Compiles to `dist/`. With no argument, builds every `.pln` file under the source root, preserving names and folder structure. |
191
- | `plainscript check <file.pln>` | Checks syntax only. No output, no execution. |
203
+ | `plainscript check <file.pln>` | Checks syntax and dependencies only. Reports a per-file `✓` line (or an error). Never executes your program. |
192
204
  | `plainscript fmt <file.pln>` | Formats a PlainScript file in place. |
193
205
  | `plainscript new [name]` | Creates a new PlainScript project, npm-ready. |
194
206
  | `plainscript install` | Installs dependencies detected across the project's sources. |
@@ -199,6 +211,18 @@ socket export plus `useMultiFileAuthState`, `makeCacheableSignalKeyStore`, and
199
211
  | `plainscript update` | Updates all installed npm packages. |
200
212
  | `plainscript version` | Prints the compiler version. |
201
213
  | `plainscript help` | Prints help text. |
214
+ | `--quiet` | Global flag for `run` / `build` / `check`: suppresses progress banners and per-file summary lines, printing only errors and output. |
215
+ | `--verbose` | Global flag for `run` / `build` / `check`: prints each compile stage with its timing detail. |
216
+
217
+ `--quiet` and `--verbose` are recognized anywhere in the argument list and
218
+ apply to `run`, `build`, and `check`, e.g. `plainscript build --quiet` or
219
+ `plainscript check src/app.pln --verbose`.
220
+
221
+ `run` keeps project-local `node_modules` first. Because generated JavaScript is
222
+ executed from a temporary directory, the CLI then falls back to the
223
+ PlainScript installation's own dependencies (for example, `sql.js` or a
224
+ usable `better-sqlite3`) rather than requiring generated files to be written
225
+ into the project.
202
226
 
203
227
  ---
204
228
 
@@ -237,7 +261,7 @@ For projects that need custom output or source directories, add a `plainscript.c
237
261
  "build": "plainscript build",
238
262
  "prepare": "plainscript build"
239
263
  },
240
- "devDependencies": { "plainscript-lang": "^1.0.361" }
264
+ "devDependencies": { "plainscript-lang": "^1.0.363" }
241
265
  }
242
266
  ```
243
267
 
@@ -248,23 +272,43 @@ For projects that need custom output or source directories, add a `plainscript.c
248
272
  ## Language Tour
249
273
 
250
274
  PlainScript is a fixed vocabulary of English verbs compiled to JavaScript. Every
251
- construct follows the same rhythm: a word opens a block, `done` closes it, and
252
- `give` returns a value - a sentence you could say to a colleague ("if the score
253
- is at least 80, show accepted, otherwise review") is valid source. The sections
254
- below keep the code first, with a short note on what each construct is *for* and
255
- the constraint that matters when you use it.
275
+ construct follows the same rhythm: a word opens a block, `done` — or its synonym
276
+ `end` — closes it, and `give` returns a value - a sentence you could say to a
277
+ colleague ("if the score is at least 80, show accepted, otherwise review") is
278
+ valid source. The sections below keep the code first, with a short note on what
279
+ each construct is *for* and the constraint that matters when you use it.
256
280
 
257
- ### Variables
281
+ ### Closing blocks with `end`
282
+
283
+ Every block can be closed with either `done` or its synonym `end`; the compiler
284
+ treats them identically, so the two spellings mix freely in one file:
258
285
 
286
+ ```plainscript
287
+ to greet name together
288
+ show "hello, " + name
289
+ end
290
+ greet("Ada")
291
+
292
+ when 1 is 1
293
+ show "math still works"
294
+ end
259
295
  ```
296
+
297
+ `end` is accepted wherever `done` is - functions, `if` / `when` /
298
+ `otherwise`, loops, `list with` / `record with`, and every other block.
299
+
300
+ ### Variables
301
+
302
+ ```plainscript
260
303
  let name be "Ayokunle"
261
304
  let age be 16
262
305
  set age to 17
263
306
  ```
264
307
 
265
308
  `remember name as "Ada"` and `let name be "Ada"` are two spellings of the same
266
- declaration; `set name to ...`, `name becomes ...`, and `name is now ...` all
267
- reassign it. Numbers, strings, and booleans behave like JavaScript primitives;
309
+ declaration; `set name to ...`, `change name to ...`, `name becomes ...`, and
310
+ `name is now ...` all reassign it (the full family of assignment aliases is
311
+ listed below). Numbers, strings, and booleans behave like JavaScript primitives;
268
312
  lists, records, dictionaries, and sets are *references*, so pointing two names
269
313
  at the same list means they see the same data.
270
314
 
@@ -272,7 +316,7 @@ at the same list means they see the same data.
272
316
 
273
317
  Backtick-delimited strings preserve whitespace and support `${expression}` interpolation:
274
318
 
275
- ```
319
+ ```plainscript
276
320
  let name be "World"
277
321
  let greeting be `Hello ${name}!`
278
322
  show greeting
@@ -296,8 +340,8 @@ comparison is itself a value: `score is at least 80` is `true` or `false`, so it
296
340
  can be stored, printed, passed to a function, or joined with `and` / `or` /
297
341
  `not`. When you need a *value* rather than a block, use `choosing` (below).
298
342
 
299
- ```
300
- when age is at least 18
343
+ ```plainscript
344
+ if age is at least 18
301
345
  show "Adult"
302
346
  otherwise
303
347
  show "Teenager"
@@ -341,7 +385,7 @@ All comparison operators:
341
385
  `choosing` is the value form of `if`: pick between two expressions and keep the
342
386
  whole thing inline - in an argument, a `give`, or a list element.
343
387
 
344
- ```
388
+ ```plainscript
345
389
  remember verdict as choosing score is at least 90 then "A" otherwise "B"
346
390
  show choosing score is below 60 then "low" otherwise "ok"
347
391
  ```
@@ -351,7 +395,7 @@ condition is true and `<b>` otherwise.
351
395
 
352
396
  ### Functions
353
397
 
354
- ```
398
+ ```plainscript
355
399
  to add a and b together
356
400
  give back a + b
357
401
  done
@@ -369,6 +413,62 @@ function is a value like any other, so it can be stored with `remember`, passed
369
413
  as an argument, or returned from another function. Arguments are optional with
370
414
  defaults: `make label(name as "guest")`.
371
415
 
416
+ ### Typed data contracts
417
+
418
+ PlainScript supports contextual `type` declarations for records and typed
419
+ function parameters. The compiler records the contract in the AST and emitted
420
+ programs validate typed arguments at runtime with clear field-level errors.
421
+ Primitive types are `number`, `text`, `boolean`, `object`, and `null`; contracts
422
+ also support `optional`, `list of`, `dictionary of`, and `or` unions.
423
+
424
+ ```plainscript
425
+ type User
426
+ id is number
427
+ name is text
428
+ active is optional boolean
429
+ done
430
+
431
+ make greet(user as User)
432
+ give `Hello ${user.name}`
433
+ done
434
+
435
+ show greet({ id: 1, name: "Ada" })
436
+ ```
437
+
438
+ Missing required fields and incompatible values fail before the function body
439
+ runs. The static checker now reports unknown fields, missing required fields,
440
+ incompatible literal values, unknown contract names, arity errors, and invalid
441
+ member access to editor tooling. Whole-program inference and exhaustiveness
442
+ checking remain future work.
443
+
444
+ ### Language-server tooling
445
+
446
+ The compiler IR and static checker are available through a stdio LSP server:
447
+
448
+ ```bash
449
+ plainscript-lsp
450
+ ```
451
+
452
+ The server implements `initialize`, document open/change/close notifications,
453
+ `textDocument/publishDiagnostics`, hover, completion, definition, and document
454
+ symbol requests. Editors should launch it as a standard LSP process and send
455
+ JSON-RPC messages using the normal `Content-Length` framing.
456
+
457
+ ### Intent declarations
458
+
459
+ `intend` declares a callable function while preserving the author's semantic
460
+ intent in the AST and compiler IR. It currently has the same execution rules
461
+ as `make`, making it safe to use today while leaving room for contract,
462
+ documentation, and semantic-analysis tooling.
463
+
464
+ ```plainscript
465
+ intend greet(name)
466
+ give `Hello ${name}`
467
+ done
468
+
469
+ show greet("Ada")
470
+ ```
471
+
372
472
  ### Lambdas
373
473
 
374
474
  A lambda is a function without a name, written where a value is expected -
@@ -376,7 +476,7 @@ A lambda is a function without a name, written where a value is expected -
376
476
  one-expression body and the `do ... done` form when the body has several
377
477
  statements:
378
478
 
379
- ```
479
+ ```plainscript
380
480
  remember add as (a, b) -> a + b
381
481
  show add(2, 3)
382
482
 
@@ -402,7 +502,7 @@ is a plain object. Both are ordinary values, so lists hold records, records
402
502
  hold lists, and lambdas can live anywhere a value can. Read and write them with
403
503
  `.name`, `[index]`, or the natural-language forms later in this tour.
404
504
 
405
- ```
505
+ ```plainscript
406
506
  let players be list with "Haaland", "Foden", "Rodri"
407
507
  show players[0]
408
508
  set players[1] to "Palmer"
@@ -419,7 +519,7 @@ show user.name
419
519
  JavaScript's `Map` and `Set` have direct spellings, and tuples are fixed-size
420
520
  arrays you usually unpack all at once:
421
521
 
422
- ```
522
+ ```plainscript
423
523
  remember lookup as dictionary with "alpha" is 1 and "beta" is 2 done
424
524
  show lookup.get("beta") // 2
425
525
 
@@ -440,7 +540,7 @@ and JSON data arrives as nested lists and records.
440
540
  <condition> ... done` repeats until the condition is false. Counted loops come
441
541
  in sentence form too:
442
542
 
443
- ```
543
+ ```plainscript
444
544
  repeat 5 times
445
545
  show "tick"
446
546
  done
@@ -455,7 +555,7 @@ done
455
555
  flips the `while` sense, and `for index i from 0 to 9` gives a zero-based
456
556
  counter when you need positions.
457
557
 
458
- ```
558
+ ```plainscript
459
559
  for each player in players
460
560
  show player
461
561
  done
@@ -475,7 +575,7 @@ Collections, properties, and files read like sentences.
475
575
 
476
576
  **Items**
477
577
 
478
- ```
578
+ ```plainscript
479
579
  let players be list with "Haaland", "Foden", "Rodri"
480
580
 
481
581
  show first player from players // players[0]
@@ -488,7 +588,7 @@ Number words from `one` to `twenty` map to one-based positions - `player one`
488
588
 
489
589
  **Collections**
490
590
 
491
- ```
591
+ ```plainscript
492
592
  show players length // players.length
493
593
  add("Palmer" to players) // players.push("Palmer")
494
594
  remove("Rodri" from players) // players.splice(players.indexOf("Rodri"), 1)
@@ -500,7 +600,7 @@ done
500
600
 
501
601
  **Properties**
502
602
 
503
- ```
603
+ ```plainscript
504
604
  show name of user // user.name
505
605
  show city of address of customer // customer.address.city
506
606
  name of user is now "Ayo" // user.name = "Ayo"
@@ -510,7 +610,7 @@ name of user is now "Ayo" // user.name = "Ayo"
510
610
 
511
611
  **Files**
512
612
 
513
- ```
613
+ ```plainscript
514
614
  let data be read("users.txt") // fs.readFileSync("users.txt", 'utf8')
515
615
  write(data to "users.txt") // fs.writeFileSync(data, "users.txt", 'utf8')
516
616
  ```
@@ -523,16 +623,70 @@ The word-style assignment operators keep the common "fill the empty value"
523
623
  pattern on one line - PlainScript for `flag = flag || true` and
524
624
  `val = val ?? "default"`:
525
625
 
626
+ ```plainscript
627
+ let flag be false
628
+ flag or becomes true
629
+ show flag
630
+
631
+ let val be null
632
+ val nullish becomes "default"
633
+ show val
526
634
  ```
635
+
636
+ ### Compound Assignment
637
+
638
+ The arithmetic compound operators map straight to their JavaScript
639
+ counterparts. `+=`, `-=`, `*=`, `/=`, and `%=` all work, and the legacy `++=`
640
+ spelling is still accepted as `+=`:
641
+
642
+ ```plainscript
643
+ let score be 10
644
+ score += 5 // 15
645
+ score -= 3 // 12
646
+ score *= 2 // 24
647
+ score /= 4 // 6
648
+ score %= 7 // 6
649
+ show score
650
+
651
+ let counter be 0
652
+ counter ++= 1 // legacy spelling of +=
653
+ show counter
654
+ ```
655
+
656
+ The word-style logical forms join them and compile to the same JavaScript as
657
+ their symbols: `or becomes` is `||=`, `and becomes` is `&&=`, and `nullish
658
+ becomes` is `??=` (the symbolic spellings work too):
659
+
660
+ ```plainscript
527
661
  let flag be false
528
- flag or is now true
662
+ flag or becomes true // flag = flag || true
529
663
  show flag
530
664
 
665
+ let tally be 5
666
+ tally and becomes 2 // tally = tally && 2
667
+ show tally
668
+
531
669
  let val be null
532
- val nullish is now "default"
670
+ val nullish becomes "default" // val = val ?? "default"
533
671
  show val
534
672
  ```
535
673
 
674
+ ### Assignment aliases
675
+
676
+ `becomes` has a full family of synonyms in both orders. The prefix forms
677
+ `set name to 17` and `change name to 17`, the postfix forms `name set to 17` and
678
+ `name change to 17`, plus the existing `name is now 17` all compile to the same
679
+ reassignment as `name becomes 17`:
680
+
681
+ ```plainscript
682
+ let name be "Ada"
683
+ change name to "Ada Lovelace"
684
+ name set to "A. L."
685
+ name change to "AL"
686
+ set name to "Ada"
687
+ show name
688
+ ```
689
+
536
690
  ### Error handling, async, and events
537
691
 
538
692
  Programs that fail should say so. `raise <value>` throws an error, `try` /
@@ -587,9 +741,15 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
587
741
 
588
742
  | Category | Features |
589
743
  |---|---|
590
- | Record kinds (classes) | `to define a kind called "Person" with name "" end`, then `create a Person with name "Ada" and age 17`. Plain-object instances; unknown fields throw. |
591
- | Concurrency | `all of [...]`, `any of [...]`, `settled of [...]`, `withTimeout(promise, ms)` |
592
- | Generators | `yield` inside `define ... end`; consumed with `for each` or `spread of` |
744
+ | Record kinds (classes) | `define a kind called "Person" with name "" and age 0 done`, then `create a Person with name "Ada" and age 17`. Plain-object instances; unknown fields throw. |
745
+ | Concurrency | `all of [...]`, `any of [...]`, `settled of [...]`, `withTimeout(promise, ms)`, `run in parallel ... done as <name>` |
746
+ | Compound assignment | `+= -= *= /= %=` plus legacy `++=`, and the word forms `or becomes` (||=), `and becomes` (&&=), `nullish becomes` (??=) |
747
+ | Assignment aliases | prefix `set name to` / `change name to`, postfix `name set to` / `name change to`, plus `name becomes` / `name is now` |
748
+ | Interactive CLI | `ask`, `confirm`, `choose`, `clearTerminal`, `terminalWidth`, `terminalHeight`, `stderr` |
749
+ | Statistics &amp; vectors | `mean`, `median`, `variance`, `deviation`, `dotProduct`, `magnitude`, `normalize` |
750
+ | Randomness | `randomInteger`, `randomChoice`, `weightedChoice`, `shuffle`, `sample` |
751
+ | Memoization &amp; parsing | `memoize`, `parseBoolean`, `characters` |
752
+ | Generators | `yield` inside `make name(...) ... done`; consumed with `for each` or `spread of` |
593
753
  | Reflection | `typeOf`, `fieldsOf`, `valueOf`, `hasField`, `sizeOf` |
594
754
  | Binary | `base64Encode/Decode`, `textToBytes/bytesToText`, `sha256/sha1/md5` |
595
755
  | Config | `yamlDecode/yamlEncode`, `load env file ".env"` |
@@ -598,11 +758,36 @@ PlainScript 1.0.2 closes most of the gap with TypeScript-class languages using i
598
758
  | Streams | `writeLine`, `appendLine` |
599
759
  | Collections | `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet` |
600
760
  | Dynamic modules | `loadModule("./m")` |
601
- | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"` |
761
+ | Native tests | `test "name" ... end` with `check a equals b`, `check a contains b`, `check a is b`, `check <expr> raises "msg"`; run files with `plainscript test` |
602
762
  | Exports | `export <name>` |
603
763
 
604
764
  </details>
605
765
 
766
+ ### Concurrency: `run in parallel`
767
+
768
+ `run in parallel ... done as <name>` runs the block's statements concurrently
769
+ and collects each statement's value in order into the named list - the
770
+ statement-level equivalent of `all of [...]`:
771
+
772
+ ```plainscript
773
+ make square(n)
774
+ give n * n
775
+ end
776
+
777
+ run in parallel
778
+ square(3)
779
+ square(4)
780
+ done as results
781
+
782
+ show join(results, ", ") // 9, 4
783
+ ```
784
+
785
+ Each statement in the block becomes one concurrent task; the collected list has
786
+ one entry per statement in body order, so expression statements (typically
787
+ calls) contribute their return values. This is a single-process, promise-based
788
+ concurrency feature (implemented with `Promise.all`) - it runs concurrent
789
+ tasks, not worker threads.
790
+
606
791
  **How the pieces fit together.** PlainScript is deliberately small: a handful
607
792
  of verbs (`remember`, `give`, `if` / `otherwise`, `done`) plus the collections
608
793
  and functions you just met. Everything is a value - numbers and strings,
@@ -624,13 +809,13 @@ Everything in this section is compiled by the deterministic compiler - no rule
624
809
 
625
810
  Portable databases (SQLite native or WebAssembly):
626
811
 
627
- ```
812
+ ```plainscript
628
813
  database "app.db" // probes better-sqlite3, falls back to sql.js
629
814
  ```
630
815
 
631
- `plainscript install` verifies that `better-sqlite3` actually loads. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
816
+ `plainscript install` verifies that `better-sqlite3` actually loads. Since 1.0.363 the native engine ships as an **optional dependency**: installing `plainscript-lang` can never fail because a native binary is missing for the platform (e.g. Android/Termux), and programs that never open a database start without it. If the native module cannot be used, PlainScript warns and continues on the pure-JavaScript WebAssembly engine (`sql.js`) - the same program runs unchanged. An engine can be forced explicitly:
632
817
 
633
- ```
818
+ ```plainscript
634
819
  database "app.db" using "native" // hard requirement: better-sqlite3
635
820
  database "app.db" using "wasm" // hard requirement: sql.js
636
821
  ```
@@ -639,7 +824,7 @@ The WebAssembly engine persists the whole database to disk after every write, so
639
824
 
640
825
  ### HTTP Client
641
826
 
642
- ```
827
+ ```plainscript
643
828
  let r be get "https://api.example.com/users"
644
829
  when ok of r
645
830
  show status of r
@@ -655,7 +840,7 @@ Methods: `get`, `post … with <body>`, `put`, `patch`, `delete "<url>"`. Respon
655
840
 
656
841
  ### Authentication
657
842
 
658
- ```
843
+ ```plainscript
659
844
  let hash be hashPassword("correct horse")
660
845
  when checkPassword(password of body of request, hash)
661
846
  let token be createToken(user, env("TOKEN_SECRET"), 3600)
@@ -668,12 +853,12 @@ let payload be readToken(token, env("TOKEN_SECRET"))
668
853
 
669
854
  ### Sessions &amp; Cookies
670
855
 
671
- ```
856
+ ```plainscript
672
857
  web app
673
858
  enable sessions "a-long-random-secret"
674
859
 
675
860
  route post "/login"
676
- user of session of request is username of body of request
861
+ user of session of request becomes username of body of request
677
862
  show "welcome"
678
863
  done
679
864
 
@@ -689,15 +874,18 @@ done
689
874
 
690
875
  Sessions ride an HMAC-signed `HttpOnly` cookie (`plainscript.sid`). The store is in-memory: restarting the server signs everyone out.
691
876
 
692
- ```
693
- set cookie "theme" to "dark" expires in 7 days
694
- show cookie("theme")
695
- clear cookie "theme"
877
+ ```plainscript
878
+ web app
879
+ route get "/theme"
880
+ set cookie "theme" to "dark" expires in 7 days
881
+ show cookie("theme")
882
+ clear cookie "theme"
883
+ done
696
884
  ```
697
885
 
698
886
  ### File Uploads
699
887
 
700
- ```
888
+ ```plainscript
701
889
  accept uploads limit "5 MB" allow list with "image/png", "image/jpeg" folder "uploads"
702
890
 
703
891
  route post "/scan"
@@ -711,15 +899,15 @@ Files arrive as records with `name`, `type`, `size`, `data` (buffer), and `path`
711
899
 
712
900
  ### Rate Limiting
713
901
 
714
- ```
715
- rate limit 100 requests per minute
902
+ ```plainscript
903
+ limit requests to 100 per minute
716
904
  ```
717
905
 
718
906
  Sliding window per client IP; the quota-exceeded response is HTTP 429.
719
907
 
720
908
  ### Google OAuth
721
909
 
722
- ```
910
+ ```plainscript
723
911
  google oauth
724
912
  id is env("GOOGLE_ID")
725
913
  secret is env("GOOGLE_SECRET")
@@ -732,7 +920,7 @@ Registers `/auth/google` (redirect) and `/auth/google/callback` (code-for-token
732
920
 
733
921
  ### Error Handling &amp; Retries
734
922
 
735
- ```
923
+ ```plainscript
736
924
  try
737
925
  let data be jsonDecode(raw)
738
926
  recover as err
@@ -746,10 +934,10 @@ done
746
934
 
747
935
  Custom 404 handling:
748
936
 
749
- ```
937
+ ```plainscript
750
938
  when nothing matches
751
939
  status 404
752
- show json
940
+ reply json
753
941
  error is "No such road"
754
942
  done
755
943
  done
@@ -770,7 +958,7 @@ first version of a program usually needs no dependency at all:
770
958
  | `writeFile("path", data)` | Write text to a file |
771
959
  | `read("path")` | Read a file as UTF-8 text |
772
960
  | `fileExists("path")` | Check if a file exists |
773
- | `sleep(ms)` | Sleep synchronously |
961
+ | `sleep(ms)` | Pause asynchronously; awaited when used as a bare statement, and composes concurrently inside `all of [...]` / `wait for sleep(...)` |
774
962
  | `time()` | Current Unix timestamp (`Date.now()`) |
775
963
  | `date()` | ISO date string |
776
964
  | `jsonEncode(value)` | `JSON.stringify` |
@@ -786,6 +974,115 @@ first version of a program usually needs no dependency at all:
786
974
 
787
975
  ---
788
976
 
977
+ ## Interactive Terminal &amp; CLI Primitives
978
+
979
+ PlainScript programs are first-class CLI citizens. `ask` reads a line, `confirm`
980
+ asks a yes/no question, and `choose` offers an option list - each takes an
981
+ optional prompt. `confirm` returns a boolean and `choose` returns the selected
982
+ option; both are async prompts, so a program that uses them compiles to async
983
+ JavaScript and can be driven non-interactively when answers are piped in:
984
+
985
+ ```plainscript
986
+ ask "What is your name? " as guest
987
+ show "hello, " + guest
988
+
989
+ remember ok as confirm("Shall we continue")
990
+ if ok is true
991
+ show "choice: " + choose("Drink?", list with "tea", "coffee", "juice")
992
+ end
993
+ ```
994
+
995
+ `clearTerminal()` clears the screen, `terminalWidth()` and `terminalHeight()`
996
+ report the terminal size, and `stderr(...)` prints to standard error so a
997
+ program's real output on stdout stays clean:
998
+
999
+ ```plainscript
1000
+ stderr("starting terminal census")
1001
+ show "width: " + terminalWidth()
1002
+ show "height: " + terminalHeight()
1003
+ clearTerminal()
1004
+ show "screen cleared"
1005
+ ```
1006
+
1007
+ ---
1008
+
1009
+ ## Statistics &amp; Vectors
1010
+
1011
+ Numeric arrays get the usual statistical summaries, and equal-length numeric
1012
+ arrays become vectors for the linear-algebra primitives behind the AI-style
1013
+ helpers (see [AI-Readiness](#ai-readiness-on-device-intelligence)):
1014
+
1015
+ ```plainscript
1016
+ remember data as [2, 4, 4, 4, 5, 5, 7, 9]
1017
+ show "mean: " + mean(data)
1018
+ show "median: " + median(data)
1019
+ show "variance: " + round(variance(data) * 100) / 100
1020
+ show "deviation: " + round(deviation(data) * 100) / 100
1021
+ ```
1022
+
1023
+ `mean`, `median`, `variance`, and `deviation` each take one list. The vector
1024
+ helpers are `dotProduct(a, b)` (how aligned two lists are), `magnitude(v)` (the
1025
+ Euclidean length), and `normalize(v)` (scales a list to unit length):
1026
+
1027
+ ```plainscript
1028
+ remember a as [1, 2, 3]
1029
+ remember b as [4, 5, 6]
1030
+ show dotProduct(a, b) // 32
1031
+ show magnitude(a) // 3.7416573867739413
1032
+ show join(normalize(a), ", ")
1033
+ ```
1034
+
1035
+ ---
1036
+
1037
+ ## Randomness
1038
+
1039
+ Deterministic programs are the default, but games, simulations, and sampling
1040
+ reach for the random family when they need variety:
1041
+
1042
+ ```plainscript
1043
+ show randomInteger(1, 6) // a die roll
1044
+ let suits be list with "hearts", "spades", "clubs", "diamonds"
1045
+ show randomChoice(suits) // one random suit
1046
+ show weightedChoice(["common", "rare", "legendary"], [0.7, 0.25, 0.05])
1047
+ show join(shuffle(suits), " ") // shuffled copy
1048
+ show join(sample(suits, 2), " ") // two random suits, no repeats
1049
+ ```
1050
+
1051
+ `randomInteger(min, max)` is inclusive on both ends; `randomChoice(list)` picks
1052
+ one element; `weightedChoice(items, weights)` picks according to a parallel
1053
+ list of weights; `shuffle(list)` returns a shuffled copy; and `sample(list, n)`
1054
+ returns `n` distinct elements.
1055
+
1056
+ ---
1057
+
1058
+ ## Memoization &amp; Parsing Helpers
1059
+
1060
+ `memoize` wraps a function so repeated calls with the same arguments hit a
1061
+ cache - handy for expensive pure functions and for memoized inference in the
1062
+ AI-style patterns below:
1063
+
1064
+ ```plainscript
1065
+ make slowSquare(n)
1066
+ give n * n
1067
+ end
1068
+
1069
+ remember fastSquare as memoize(slowSquare)
1070
+ show fastSquare(9)
1071
+ show fastSquare(9) // served from the cache
1072
+ ```
1073
+
1074
+ `parseBoolean` normalizes `"true"`, `"yes"`, `"1"`, and `"on"` (case- and
1075
+ whitespace-insensitive) to `true` and everything else to `false`, and
1076
+ `characters` splits a string into its individual characters:
1077
+
1078
+ ```plainscript
1079
+ show parseBoolean("yes") // true
1080
+ show parseBoolean("off") // false
1081
+ show join(characters("abc"), "-") // a-b-c
1082
+ ```
1083
+
1084
+ ---
1085
+
789
1086
  ## Web Applications
790
1087
 
791
1088
  `web app` starts the HTTP stack available to every program. `route <method>
@@ -802,7 +1099,7 @@ route "/"
802
1099
  done
803
1100
 
804
1101
  route "/api/status"
805
- show json
1102
+ reply json
806
1103
  status is "ok"
807
1104
  version is "2.0"
808
1105
  done
@@ -991,6 +1288,37 @@ show page.hasNext # true if another page exists
991
1288
 
992
1289
  ---
993
1290
 
1291
+ ## AI-Readiness: On-Device Intelligence
1292
+
1293
+ The statistics, vector, randomness, memoization, and persistent-JSON primitives
1294
+ in this release compose into AI-style systems - retrieval scoring, ranking,
1295
+ weighted sampling, memoized inference, and durable memory - built entirely
1296
+ with the deterministic compiler and **no external AI provider, no API key, and
1297
+ no network call**. `examples/ai-memory-cli.pln` is a walking example: it stores
1298
+ "facts" as a JSON file, vectorizes a query with `dotProduct` / `magnitude` /
1299
+ `normalize`, and retrieves the best-matching fact by cosine similarity.
1300
+ `examples/stats-cli.pln` exercises the statistical side over an arbitrary
1301
+ sample from the command line:
1302
+
1303
+ ```plainscript
1304
+ let a be [1, 0, 1] // bag-of-words vector for a stored fact
1305
+ let b be [1, 1, 0] // bag-of-words vector for the query
1306
+ show "raw overlap: " + dotProduct(a, b)
1307
+ let unit be normalize(a) // unit vector: magnitude becomes 1
1308
+ show "unit norm: " + round(magnitude(unit) * 100) / 100
1309
+ ```
1310
+
1311
+ The CLI helpers keep these tools scriptable - for example, storing and
1312
+ querying the memory file:
1313
+
1314
+ ```bash
1315
+ plainscript run examples/ai-memory-cli.pln remember "Ada loves math and jazz"
1316
+ plainscript run examples/ai-memory-cli.pln query "who likes math"
1317
+ plainscript run examples/ai-memory-cli.pln list
1318
+ ```
1319
+
1320
+ ---
1321
+
994
1322
  ## Multi-File Projects
995
1323
 
996
1324
  Programs grow into files. `import "./math.pln"` pulls a whole file into the
@@ -1035,7 +1363,7 @@ when someone visits "/"
1035
1363
  done
1036
1364
 
1037
1365
  when someone visits "/api/status"
1038
- show json
1366
+ reply json
1039
1367
  status is "ok"
1040
1368
  version is "0.3"
1041
1369
  done
@@ -1097,7 +1425,7 @@ See [`examples/whatsapp-bot/`](./examples/whatsapp-bot/) for ready-to-link progr
1097
1425
  | PlainScript | Compiles to |
1098
1426
  |---|---|
1099
1427
  | `use express` | `const express = require('express');` |
1100
- | `use sqlite` | `const Database = require('better-sqlite3');` |
1428
+ | `use sqlite` | `let Database; … require('better-sqlite3')` (lazily loaded - the native engine is an optional backend) |
1101
1429
  | `use fs` | `const fs = require('fs');` |
1102
1430
  | `use path` | `const path = require('path');` |
1103
1431
 
@@ -1192,4 +1520,4 @@ Released under the [MIT License](./LICENSE).
1192
1520
 
1193
1521
  <sub>"When even a simple sentence can be code."</sub>
1194
1522
 
1195
- </div>
1523
+ </div>