plainscript-lang 1.0.1 → 1.0.2

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 (52) hide show
  1. package/README.md +154 -147
  2. package/compiler/bundler.js +2 -2
  3. package/compiler/cli.js +58 -58
  4. package/compiler/formatter.js +1 -1
  5. package/compiler/generator.js +753 -67
  6. package/compiler/lexer.js +127 -53
  7. package/compiler/parser.js +953 -151
  8. package/compiler/version.js +1 -1
  9. package/docs/CAPABILITY_GAP_AUDIT.md +130 -29
  10. package/docs/PLAINSCRIPT-SPEC.md +584 -0
  11. package/docs/index.html +33 -42
  12. package/docs/website/script.js +110 -24
  13. package/docs/website/style.css +4 -4
  14. package/examples/arrays.pln +12 -0
  15. package/examples/{auth-api.ps → auth-api.pln} +3 -3
  16. package/examples/{cache-and-jobs.ps → cache-and-jobs.pln} +1 -1
  17. package/examples/{concurrency.ps → concurrency.pln} +8 -8
  18. package/examples/{database.ps → database.pln} +1 -1
  19. package/examples/{deployment.ps → deployment.pln} +2 -2
  20. package/examples/{email-send.ps → email-send.pln} +1 -1
  21. package/examples/{error-handling.ps → error-handling.pln} +8 -7
  22. package/examples/{expressions.ps → expressions.pln} +1 -1
  23. package/examples/{file-uploads.ps → file-uploads.pln} +4 -4
  24. package/examples/{files-and-config.ps → files-and-config.pln} +4 -4
  25. package/examples/football-backend/{app.ps → app.pln} +2 -2
  26. package/examples/{http-client.ps → http-client.pln} +18 -18
  27. package/examples/id-verification/{app.ps → app.pln} +1 -1
  28. package/examples/{loops.ps → loops.pln} +2 -3
  29. package/examples/modules/{app.ps → app.pln} +4 -4
  30. package/examples/modules/{math.ps → math.pln} +1 -1
  31. package/examples/{record-kinds.ps → record-kinds.pln} +4 -4
  32. package/examples/{rest-api-fetch.ps → rest-api-fetch.pln} +1 -1
  33. package/examples/{rest-api.ps → rest-api.pln} +5 -5
  34. package/examples/{scheduled-tasks.ps → scheduled-tasks.pln} +2 -2
  35. package/examples/{search-and-filter.ps → search-and-filter.pln} +5 -5
  36. package/examples/{sessions-and-cookies.ps → sessions-and-cookies.pln} +2 -2
  37. package/examples/start.pln +2 -0
  38. package/examples/{stdlib.ps → stdlib.pln} +2 -2
  39. package/examples/{telegram-bot.ps → telegram-bot.pln} +2 -2
  40. package/examples/{websocket-server.ps → websocket-server.pln} +1 -1
  41. package/package.json +1 -1
  42. package/docs/PLINJS_SPEC.md +0 -1151
  43. package/examples/arrays.ps +0 -13
  44. package/examples/start.ps +0 -2
  45. /package/examples/{day2.ps → day2.pln} +0 -0
  46. /package/examples/{day3.ps → day3.pln} +0 -0
  47. /package/examples/{hello.ps → hello.pln} +0 -0
  48. /package/examples/{objects.ps → objects.pln} +0 -0
  49. /package/examples/{server.ps → server.pln} +0 -0
  50. /package/examples/{web-app.ps → web-app.pln} +0 -0
  51. /package/examples/whatsapp-bot/{pairing.ps → pairing.pln} +0 -0
  52. /package/examples/whatsapp-bot/{qr.ps → qr.pln} +0 -0
@@ -1,1151 +0,0 @@
1
- # PlainScript Language Specification (v1.0.1)
2
-
3
- Version: 2.1.1
4
- Status: Stable
5
- File Extension: .ps
6
-
7
- Tagline: "When even a simple sentence can be code."
8
-
9
- ---
10
-
11
- ## Mission
12
-
13
- PlainScript is an Intent-Oriented Programming Language (IOPL).
14
-
15
- Its goal is to let developers describe WHAT they want while the compiler decides HOW JavaScript should implement it.
16
-
17
- PlainScript is designed to be: beginner-friendly, readable, predictable, consistent, and easy to teach.
18
-
19
- Every keyword should be understandable by a 12-year-old.
20
-
21
- ---
22
-
23
- ## Core Principles
24
-
25
- 1. One way to do everything.
26
- 2. Readability over fewer characters.
27
- 3. Keywords never have aliases.
28
- 4. Error messages should teach.
29
- 5. JavaScript is an implementation detail.
30
- 6. Code should read like documentation.
31
-
32
- ---
33
-
34
- ## Comments
35
-
36
- // This is a comment
37
-
38
- ---
39
-
40
- ## Variables
41
-
42
- Declare:
43
-
44
- remember name as "Ayokunle"
45
- remember age as 16
46
-
47
- Reassign:
48
-
49
- age becomes 17
50
-
51
- ---
52
-
53
- ## Printing
54
-
55
- show "Hello"
56
- show("Hello")
57
- show age
58
- show(players[0])
59
- show user.name
60
-
61
- Both keyword form (`show expr`) and call form (`show(expr)`) are valid and produce identical output.
62
-
63
- ---
64
-
65
- ## Conditions
66
-
67
- if age is 18
68
- show "Adult"
69
- otherwise
70
- show "Minor"
71
- done
72
-
73
- ### Comparison Operators
74
-
75
- | PlainScript | JavaScript |
76
- |------------------------------|--------------------|
77
- | `is` / `is equal to` | `===` |
78
- | `is not` | `!==` |
79
- | `is greater than` | `>` |
80
- | `is above` | `>` |
81
- | `is less than` | `<` |
82
- | `is below` | `<` |
83
- | `is at least` | `>=` |
84
- | `is at most` | `<=` |
85
- | `is empty` | `.length === 0` |
86
- | `is not empty` | `.length > 0` |
87
- | `contains "x"` | `.includes("x")` |
88
- | `starts with "x"` | `.startsWith("x")` |
89
- | `ends with "x"` | `.endsWith("x")` |
90
- | `between A and B` | `>= A && <= B` |
91
-
92
- ---
93
-
94
- ## Functions
95
-
96
- make greet()
97
- show "Hello"
98
- done
99
-
100
- greet()
101
-
102
- make add(a, b)
103
- give a + b
104
- done
105
-
106
- show add(5, 7)
107
-
108
- ---
109
-
110
- ## Arrays
111
-
112
- remember players as [
113
- "Haaland",
114
- "Foden",
115
- "Rodri"
116
- ]
117
-
118
- show players[0]
119
- players[1] becomes "Palmer"
120
-
121
- ---
122
-
123
- ## Objects
124
-
125
- remember user as
126
- name is "Ayokunle"
127
- age is 17
128
- country is "Nigeria"
129
- done
130
-
131
- show user.name
132
- user.age becomes 18
133
-
134
- ---
135
-
136
- ## Loops
137
-
138
- For each:
139
-
140
- for each player in players
141
- show player
142
- done
143
-
144
- For every (alias for for each):
145
-
146
- for every item in basket
147
- show item
148
- done
149
-
150
- While:
151
-
152
- while age is less than 18
153
- age becomes age + 1
154
- done
155
-
156
- ---
157
-
158
- ## Record Kinds, Classes & Concurrency (v1.0.1)
159
-
160
- These features close the capability-gap audit (`docs/CAPABILITY_GAP_AUDIT.md`) in
161
- PlainScript's own intent-oriented grammar.
162
-
163
- ### Record kinds (classes)
164
-
165
- Declare a schema with defaults, then build instances.
166
-
167
- define a kind called "Person" with
168
- name is ""
169
- age is 0
170
- done
171
-
172
- remember ada as create a Person with name "Ada" and age 17
173
- show name of ada # "Ada"
174
- show ada.age # 17
175
-
176
- - `create a <Kind> with <field> <value> and <field> <value> ...` builds an
177
- instance. `and` separates field pairs.
178
- - Unknown constructor fields throw at runtime (`"Person" has no field named "x"`).
179
- - Instances are plain objects: they serialize with `jsonEncode`, pass unchanged
180
- to `send mail`, DB statements, routes, etc.
181
- - For optional extensions, compose with `merge(a, b)` instead of `extends`.
182
- Methods are plain `make` functions receiving the record.
183
-
184
- ### Concurrency combinators
185
-
186
- remember both as all of [pageFetch(), apiFetch()]
187
- remember winner as any of [slow(), fast()]
188
- remember results as settled of [maybeFails(), other()]
189
-
190
- - `all of [...]` → `Promise.all` (all must resolve).
191
- - `any of [...]` → `Promise.race` (first to settle).
192
- - `settled of [...]` → `Promise.allSettled`; each item is a record with
193
- `status` (`fulfilled`/`rejected`), `value`, and `reason`.
194
- - `withTimeout(promise, ms)` rejects the promise after `ms` if it has not settled.
195
-
196
- ### Generators
197
-
198
- make countUp(n)
199
- remember i as 0
200
- while i is less than n
201
- i becomes i + 1
202
- yield i
203
- done
204
- done
205
-
206
- show spread of countUp(3) # [ 1, 2, 3 ]
207
-
208
- A `make ... done` containing `yield` compiles to a generator (`function*`).
209
- Sequences are consumed lazily with `for each` or eagerly with `spread of`.
210
-
211
- ### Reflection, binary & configuration (stdlib)
212
-
213
- | PlainScript | Behaviour |
214
- |-------------------------------------------|------------------------------------------|
215
- | `typeOf(x)` | `text\|number\|boolean\|array\|record\|null\|function\|undefined` |
216
- | `fieldsOf(x)` / `sizeOf(x)` | record keys / length |
217
- | `valueOf(x, key, fallback)` / `hasField` | safe access / key check |
218
- | `base64Encode(s)` / `base64Decode(s)` | base64 round-trip |
219
- | `textToBytes(s)` / `bytesToText(b)` | UTF-8 bytes round-trip |
220
- | `sha256(s)` / `sha1(s)` / `md5(s)` | hex digests (`crypto`) |
221
- | `yamlDecode(s)` / `yamlEncode(v)` | dependency-free YAML subset |
222
- | `load env file "path"` (statement) | applies `KEY=value` to `process.env` |
223
- | `args()` | `process.argv.slice(2)` |
224
- | `runCommand(cmd, [args])` | awaits `{ ok, code, stdout, stderr }` |
225
- | `withTimeout(promise, ms)` | rejects on timeout |
226
- | `loadModule("./m")` | dynamic `require` at runtime |
227
- | `walkFolder(dir)` | recursive list of file paths |
228
- | `fileSize(p)` / `fileType(p)` / `lastModified(p)` | fs metadata |
229
- | `joinPath` / `baseName` / `folderOf` / `extensionOf` | path helpers |
230
- | `writeLine(f, t)` / `appendLine(f, t)` | newline-terminated appends |
231
- | `keyMap()` + `mapSet/mapGet/mapHas/mapDelete` | JS `Map` helpers |
232
- | `newSet()` + `addToSet/removeFromSet/setHas` | JS `Set` helpers |
233
-
234
- ### Native test DSL
235
-
236
- test "addition"
237
- check add(2, 3) equals 5
238
- check "hello" contains "ell"
239
- check typeOf({}) equals "record"
240
- check jsonDecode("not json") raises "JSON"
241
- done
242
-
243
- A built-in runner registers every `test "name" ... done` block, prints
244
- `PASS`/`FAIL`, reports a count, and exits `1` if any assertion fails. `check`
245
- is only valid inside a `test` block.
246
-
247
- ### Exports
248
-
249
- remember configVersion as 3
250
- export configVersion
251
-
252
- `export <name>` marks a top-level symbol for `module.exports`. When any explicit
253
- `export` exists, the automatic top-level function export is suppressed so the
254
- author controls the module surface.
255
-
256
- ---
257
-
258
- ## Standard Library
259
-
260
- All built-in functions are available without any `use` or `import` statement.
261
-
262
- ### Strings & Numbers
263
-
264
- | PlainScript | JavaScript equivalent |
265
- |-----------------|-------------------------|
266
- | `length(x)` | `(x).length` |
267
- | `uppercase(x)` | `(x).toUpperCase()` |
268
- | `lowercase(x)` | `(x).toLowerCase()` |
269
- | `random()` | `Math.random()` |
270
- | `round(x)` | `Math.round(x)` |
271
-
272
- ### String Templates
273
-
274
- Backtick-delimited strings preserve whitespace and support `${expression}` interpolation. They compile to JavaScript template literals.
275
-
276
- remember name as "World"
277
- remember greeting as `Hello ${name}!`
278
- show greeting
279
-
280
- remember body as `{"key": "value"}`
281
- remember response as await fetch "https://api.example.com" with
282
- method is "POST"
283
- body is body
284
- headers is { "Content-Type": "application/json" }
285
- done
286
-
287
- Multiline templates preserve line breaks:
288
-
289
- remember email as `Dear ${customer},
290
-
291
- Thank you for your order #${orderId}.
292
-
293
- Best regards,
294
- The Team`
295
-
296
- Notes:
297
- - Interpolation `${expr}` compiles directly to JavaScript `${expr}` — it is not evaluated at compile time.
298
- - Literal dollar signs that are not followed by `{` are preserved as-is (e.g. `` `$5` ``).
299
- - Escape sequences work in both string forms: double-quoted strings decode `\n`, `\t`, `\r`, `\0`, `\\`, `\"`, and `\'` (an unknown escape keeps the escaped character itself); inside backtick templates an escaped backtick stays literal instead of closing the string.
300
- - Embedded backtick characters within the template content are escaped in the output.
301
-
302
- ### I/O & Files
303
-
304
- | PlainScript | JavaScript equivalent |
305
- |------------------------------|--------------------------------------------------|
306
- | `print(x)` | `console.log(x)` |
307
- | `readFile(path)` | `require('fs').readFileSync(path, 'utf8')` |
308
- | `writeFile(path, content)` | `require('fs').writeFileSync(path, content, 'utf8')` |
309
- | `fileExists(path)` | `require('fs').existsSync(path)` |
310
-
311
- ### Time & System
312
-
313
- | PlainScript | JavaScript equivalent |
314
- |----------------|----------------------------------------|
315
- | `time()` | `Date.now()` |
316
- | `date()` | `new Date().toISOString()` |
317
- | `sleep(ms)` | `Atomics.wait(...)` (synchronous) |
318
- | `uuid()` | `require('crypto').randomUUID()` |
319
- | `env(key)` | `process.env[key]` |
320
- | `exit(code)` | `process.exit(code)` |
321
-
322
- ### JSON
323
-
324
- | PlainScript | JavaScript equivalent |
325
- |--------------------|-----------------------------|
326
- | `jsonEncode(x)` | `JSON.stringify(x)` |
327
- | `jsonDecode(s)` | `JSON.parse(s)` |
328
-
329
- ---
330
-
331
- ## PlainScript Imports
332
-
333
- Split a project across multiple `.ps` files:
334
-
335
- import "./math.ps"
336
- import "./utils.ps"
337
-
338
- Rules:
339
-
340
- - Paths must be relative (start with `./` or `../`).
341
- - Files are compiled in dependency order (deepest first).
342
- - Duplicate imports are silently de-duplicated.
343
- - Circular imports produce a friendly compiler error.
344
- - Missing files produce a friendly compiler error.
345
-
346
- Example project layout:
347
-
348
- app.ps
349
- math.ps
350
- utils.ps
351
-
352
- `math.ps`:
353
-
354
- remember PI as 3.14
355
-
356
- `app.ps`:
357
-
358
- import "./math.ps"
359
- show PI
360
-
361
- Output: one combined JavaScript file with `math.ps` code before `app.ps` code.
362
-
363
- ---
364
-
365
- ## Runtime Packages
366
-
367
- Supported packages:
368
-
369
- use express → const express = require('express');
370
- use sqlite → const Database = require('better-sqlite3');
371
- use fs → const fs = require('fs');
372
- use path → const path = require('path');
373
-
374
- Any npm package can be declared, including hyphenated and scoped names
375
- (RFC-0011 §5.1):
376
-
377
- use axios → const axios = require('axios');
378
- use node-fetch → require('node-fetch'); // side effect only
379
- use @scope/package-name → require('@scope/package-name');
380
-
381
- ### Aliases and version ranges
382
-
383
- A package that is not a valid JavaScript identifier gets no binding by
384
- default — declare an alias to bind it to a variable:
385
-
386
- use node-fetch as fetch → const fetch = require('node-fetch');
387
- use left-pad as pad → const pad = require('left-pad');
388
- use @scope/pkg as scoped → const scoped = require('@scope/pkg');
389
-
390
- Rules:
391
-
392
- - The alias must be a valid JavaScript identifier; anything else fails with a
393
- clear error.
394
- - Built-in runtime packages (`express`, `sqlite`, `fs`, `path`, `axios`,
395
- `chalk`) keep their canonical bindings; aliasing them is an error.
396
- - A package can be required once per alias; the plain form and an aliased
397
- form of the same package may coexist.
398
-
399
- Version ranges are part of the specifier and flow through to installation;
400
- `require()` always uses the bare name:
401
-
402
- use left-pad@^1.3.0 → require('left-pad'); // npm install left-pad@^1.3.0
403
- use sqlite@7 → const Database = require('better-sqlite3');
404
- use dotenv@16 as env → const env = require('dotenv');
405
-
406
- `plainscript install`, `plainscript run`, and `plainscript build` check installed-ness by bare
407
- package name but install with the full `name@range` specifier.
408
-
409
- ### Runtime dependency detection and installation
410
-
411
- The compiler exposes a reusable dependency detector that reads PlainScript source
412
- without duplicate results. It scans every `use` statement and runtime
413
- shorthand, returning a unique list of npm package names in first-seen order.
414
-
415
- PlainScript module names are mapped to npm packages:
416
-
417
- | PlainScript module | npm package |
418
- |--------------|-------------|
419
- | `express` | `express` |
420
- | `sqlite` | `better-sqlite3` |
421
- | `web app` | `express` |
422
- | `axios` | `axios` |
423
- | `chalk` | `chalk` |
424
- | `ocr` | `tesseract.js` |
425
-
426
- Node built-in modules, including `fs` and `path`, are ignored because they do
427
- not need to be installed. A source file with no runtime package uses returns
428
- an empty list.
429
-
430
- Version ranges survive detection: `use left-pad@^1.3.0` is reported as
431
- `left-pad@^1.3.0`, and friendly names map through the range (`use sqlite@7`
432
- is reported as `better-sqlite3@7`).
433
-
434
- Built-in modules are never installed. Missing npm packages are installed by
435
- `plainscript install`, `plainscript run`, and `plainscript build`; package checks are cached for
436
- the duration of one CLI command so repeated imports do not rescan the
437
- filesystem.
438
-
439
- ### Deployment workflow
440
-
441
- ```bash
442
- npm install --save-dev plainscript-lang
443
- plainscript install
444
- plainscript build app.ps
445
- plainscript run app.ps
446
- ```
447
-
448
- `plainscript start` builds `src/app.ps` (or `src/index.ps`) into the output
449
- directory and runs it. `plainscript doctor` reports missing tools, source files,
450
- or dependencies. Generated JavaScript remains standard
451
- Node.js-compatible JavaScript and runtime `require()` declarations are emitted
452
- once in deterministic order.
453
-
454
- ---
455
-
456
- ## Express Server
457
-
458
- Classic style:
459
-
460
- use express
461
-
462
- remember app as express()
463
-
464
- serve folder "public"
465
-
466
- when someone visits "/"
467
- reply "Hello from PlainScript!"
468
- done
469
-
470
- when someone visits "/api/status"
471
- reply json
472
- status is "ok"
473
- version is "1.0"
474
- done
475
- done
476
-
477
- listen on 3000
478
- show "Server running at http://localhost:3000"
479
- done
480
-
481
- Shorthand style:
482
-
483
- web app
484
-
485
- route "/"
486
- reply "Hello from PlainScript!"
487
- done
488
-
489
- start 3000
490
-
491
- ### Routes
492
-
493
- when someone visits "<path>"
494
- ...
495
- done
496
-
497
- route "<path>"
498
- ...
499
- done
500
-
501
- Both compile to: `app.get(path, (req, res) => { ... })`
502
-
503
- Inside route bodies:
504
-
505
- - `request` → `req`
506
- - `response` → `res`
507
-
508
- ### Sending Responses
509
-
510
- reply "Hello" → res.send("Hello")
511
- reply user → res.send(user)
512
-
513
- ### JSON Responses
514
-
515
- reply json
516
- name is "PlainScript"
517
- version is "1.0"
518
- done
519
-
520
- Compiles to: `res.json({ "name": "PlainScript", "version": "1.0" })`
521
-
522
- ### Static Files
523
-
524
- serve folder "public"
525
-
526
- Compiles to: `app.use(express.static("public"))`
527
-
528
- ### Listening
529
-
530
- listen on 3000
531
- show "Running"
532
- done
533
-
534
- Compiles to: `app.listen(3000, () => { ... })`
535
-
536
- ### Start (shorthand)
537
-
538
- start 3000
539
-
540
- Compiles to: `app.listen(3000)`
541
-
542
- ---
543
-
544
- ## SQLite
545
-
546
- Classic style:
547
-
548
- use sqlite
549
-
550
- remember db as sqlite("database.db")
551
-
552
- Compiles to: `new Database("database.db")`
553
-
554
- Shorthand style:
555
-
556
- database "app.db"
557
-
558
- execute
559
- CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)
560
- done
561
-
562
- insert
563
- INSERT INTO users (name) VALUES ('Alice')
564
- done
565
-
566
- query
567
- SELECT * FROM users
568
- done
569
-
570
- ### SQL Block Commands
571
-
572
- | PlainScript | Compiles to |
573
- |--------------------|----------------------------------|
574
- | `database "f.db"` | `const db = new Database("f.db")`|
575
- | `query ... done` | `db.prepare(...).all()` |
576
- | `insert ... done` | `db.prepare(...).run()` |
577
- | `update ... done` | `db.prepare(...).run()` |
578
- | `delete ... done` | `db.prepare(...).run()` |
579
- | `execute ... done` | `db.exec(...)` |
580
-
581
- ---
582
-
583
- ## HTTP Routing
584
-
585
- Method routes extend the basic route shorthand. The plain form stays GET.
586
-
587
- route get|post|put|patch|delete "<path>" ... done
588
- group "<prefix>" ... done
589
-
590
- Groups compose: a route inside two groups accumulates both prefixes.
591
- `param("id")`, `query("page")` and `header("x-token")` read request data and
592
- are compile-time errors outside routes. `status <expr>` sets the response
593
- code; `status becomes n` keeps its ordinary variable meaning. `allow cors`
594
- enables permissive CORS middleware (including OPTIONS preflight). Inside a
595
- `web app` block the body is parsed as JSON automatically.
596
-
597
- remember missing as validate(body of request, ["name", "email"])
598
-
599
- returns the list of missing field names.
600
-
601
- ## Databases
602
-
603
- SQL placeholders are written `{likeThis}` and bind to PlainScript variables of the
604
- same name. Results are captured with `remember`:
605
-
606
- database "app.db"
607
- remember who as "ana"
608
- insert
609
- INSERT INTO users (name) VALUES ({who})
610
- done
611
- remember adults as query
612
- SELECT * FROM users WHERE age >= {minAge}
613
- done
614
- transaction
615
- insert
616
- INSERT INTO users (name) VALUES ('bo')
617
- done
618
- done
619
-
620
- A `transaction ... done` block runs all enclosed writes atomically.
621
-
622
- PostgreSQL swaps the driver for every later SQL statement:
623
-
624
- postgres env("DATABASE_URL")
625
-
626
- compiles to `new Pool({ connectionString })`; queries become awaited pool
627
- queries with `$n` markers, and `remember x as query` captures `.rows`.
628
-
629
- ## Filesystem and Helpers
630
-
631
- Filesystem: `copyFile`, `moveFile`, `deleteFile`, `makeFolder`,
632
- `deleteFolder`, `listFolder`, `appendFile`, `readBytes`, `writeBytes`.
633
-
634
- Text/numbers: `trim`, `replace`, `split`, `join`, `number`, `text`, `floor`,
635
- `ceiling`. Collections: `sort` (unified ordering across types), `reverse`,
636
- `unique`, `sum`, `smallest`, `largest`, `keys`, `values`, `hasKey`, `merge`.
637
-
638
- ## Email
639
-
640
- mail transport
641
- host is "smtp.gmail.com"
642
- port is 587
643
- user is env("EMAIL_USER")
644
- pass is env("EMAIL_PASS")
645
- done
646
-
647
- send mail
648
- from is "hello@plainscript.dev"
649
- to is "you@example.com"
650
- subject is "Hello"
651
- text is "Body"
652
- done
653
-
654
- Uses nodemailer; `user`/`pass` become the SMTP `auth`.
655
-
656
- ## Scheduling and Background Jobs
657
-
658
- every 5 minutes
659
- show "tick"
660
- done
661
-
662
- schedule "0 2 * * *"
663
- show "nightly cleanup"
664
- done
665
-
666
- run background resizeImage("photo.png")
667
-
668
- `every` accepts seconds/minutes/hours/days (plural or singular). `schedule`
669
- accepts any standard cron expression (powered by croner). `run background`
670
- fires the call without blocking; errors are logged, never raised.
671
-
672
- ## WebSocket Servers
673
-
674
- websocket server on 8080
675
- when socket connects
676
- send socket "Welcome!"
677
- done
678
- when socket sends message
679
- broadcast message
680
- done
681
- when socket disconnects
682
- done
683
- done
684
-
685
- Handlers are optional. `send socket <value>` replies to one client,
686
- `broadcast <value>` to all connected clients. Uses the ws package.
687
-
688
- ## Cache
689
-
690
- cache "redis://localhost:6379"
691
-
692
- connects Redis once. Then:
693
-
694
- | PlainScript | Compiles to |
695
- |------------------------------|--------------------------------|
696
- | `cacheGet("k")` | `client.get(k)` |
697
- | `cacheSet("k", v)` | `client.set(k, v)` |
698
- | `cacheSet("k", v, 60)` | `client.set(k, v, { EX: 60 })` |
699
- | `cacheDelete("k")` | `client.del(k)` |
700
-
701
- All three are async and require a configured cache first.
702
-
703
- ---
704
-
705
- ## Backend Services
706
-
707
- All statements below compile deterministically. Implementation packages
708
- (`better-sqlite3`, `sql.js`, `multer`) are detected and installed
709
- automatically; they never appear in PlainScript source.
710
-
711
- ### Portable databases
712
-
713
- database "app.db" // probe native, fall back to WebAssembly
714
- database "app.db" using "native" // require better-sqlite3
715
- database "app.db" using "wasm" // require sql.js
716
-
717
- - The default probes the native driver (`better-sqlite3`) by opening an
718
- in-memory database; if that fails, the program continues on the pure-
719
- JavaScript WebAssembly engine (`sql.js`).
720
- - `using "native"` / `using "wasm"` pin the engine; anything else fails at
721
- compile time.
722
- - The WebAssembly engine writes the whole database file after every mutating
723
- statement, so data survives restarts. In-memory databases (`":memory:"`)
724
- are never persisted.
725
- - Transactions run their body exactly once on both engines.
726
-
727
- ### HTTP client
728
-
729
- get "<url>"
730
- post <url> with <body>
731
- put <url> with <body>
732
- patch <url> with <body>
733
- delete "<url>"
734
-
735
- Optional clauses on any method: `headers { key is "value" ... }` (inline
736
- object or block form) and `timeout <milliseconds>`. Requests are values, so
737
- they compose:
738
-
739
- remember r as get "https://api.example.com/users"
740
-
741
- The response is a record:
742
-
743
- | Field | Meaning |
744
- |------------|------------------------------------------------------|
745
- | `ok of r` | `true` for 2xx status codes |
746
- | `status` | HTTP status number |
747
- | `headers` | response headers as a record |
748
- | `data` | parsed JSON body when the content type says `json`, otherwise the raw text |
749
-
750
- Bodies sent to `post`/`put`/`patch`: records and arrays are serialised as
751
- JSON; strings and buffers are sent verbatim. The default timeout is 30
752
- seconds; a timeout aborts the request and rejects. `wait for fetch(...)`
753
- awaits a raw promise.
754
-
755
- ### Passwords and tokens
756
-
757
- | PlainScript | Behaviour |
758
- |----------------------------------------|----------------------------------------------|
759
- | `hashPassword(pw)` | scrypt hash with per-password salt |
760
- | `checkPassword(pw, storedHash)` | constant-time verification, returns boolean |
761
- | `createToken(payload, secret [, ttl])` | HMAC-signed token, default TTL 3600 seconds |
762
- | `readToken(token, secret)` | verified payload or null (tamper/expiry) |
763
-
764
- ### Sessions
765
-
766
- web app
767
- enable sessions "a-long-random-secret"
768
- route post "/login"
769
- user of session of request becomes username of body of request
770
- reply "welcome"
771
- done
772
- route post "/logout"
773
- destroy session
774
- reply "bye"
775
- done
776
-
777
- - The session rides an HMAC-signed cookie named `plainscript.sid`
778
- (`HttpOnly`, `SameSite=Lax`).
779
- - `session of request` is the session record; assign fields onto it with
780
- `becomes`.
781
- - Reading `session of request` outside a route, or without
782
- `enable sessions`, is a teaching error.
783
- - The store lives in memory: restarting the process signs everyone out.
784
-
785
- ### File uploads
786
-
787
- accept uploads limit "5 MB" allow ["image/png", "image/jpeg"] folder "uploads"
788
-
789
- All clauses are optional; the statement must appear before the routes it
790
- protects. Inside routes:
791
-
792
- | PlainScript | Result |
793
- |---------------------|-------------------------------------------------------|
794
- | `upload("field")` | first file under the field, or null |
795
- | `uploads("field")` | array of files under the field |
796
-
797
- Each file is a record: `name` (original name), `type` (MIME), `size` (bytes),
798
- `data` (buffer, memory storage) and `path` (string, folder storage). A file
799
- over the limit is rejected with HTTP **413**; a disallowed MIME type with
800
- HTTP **415**. With `folder`, uploaded files are written to disk (the folder
801
- is created if needed).
802
-
803
- ### Cookies
804
-
805
- set cookie "theme" to "dark" expires in 7 days
806
- show cookie("theme")
807
- clear cookie "theme"
808
-
809
- `expires in` accepts seconds/minutes/hours/days. Cookie accessors are
810
- route-only.
811
-
812
- ### Rate limiting
813
-
814
- limit requests to 100 per minute
815
-
816
- Sliding window keyed by client IP; requests past the quota receive HTTP 429.
817
- Units: seconds, minutes, hours.
818
-
819
- ### API-key protection
820
-
821
- require api key from env("API_KEY")
822
-
823
- Requests must carry the expected value in the `x-api-key` header; everything
824
- else receives HTTP 401. When the configured key is unset, every request is
825
- rejected (fail closed). Middleware applies to routes registered after it.
826
-
827
- ### Google OAuth
828
-
829
- google oauth
830
- id is env("GOOGLE_ID")
831
- secret is env("GOOGLE_SECRET")
832
- callback is "https://myapp.dev/auth/google/callback"
833
- landing is "/dashboard"
834
- done
835
-
836
- Registers two endpoints: `/auth/google` redirects to Google's consent screen
837
- with a signed `state`; `/auth/google/callback` validates the state, swaps the
838
- code for tokens, fetches the profile and stores the user on the session
839
- before redirecting to `landing`.
840
-
841
- ### Custom 404
842
-
843
- when nothing matches
844
- status 404
845
- reply json
846
- error is "No such road"
847
- done
848
- done
849
-
850
- Registers the final handler at its source position — place it after your
851
- routes.
852
-
853
- ### Error handling
854
-
855
- try
856
- remember data as jsonDecode(raw)
857
- recover as err
858
- show "bad json: " + message of err
859
- done
860
-
861
- `recover` is optional; without it errors are swallowed. `err` is the thrown
862
- value (use `message of err` for Error objects).
863
-
864
- ### Retries
865
-
866
- retry 3 times every 5 seconds
867
- wait for fetch("https://flaky.api")
868
- done
869
-
870
- `every` is optional (default delay one second); zero seconds retries
871
- immediately. The body runs until it succeeds or attempts run out; failures
872
- are logged with the last error.
873
-
874
- ---
875
-
876
- ## OCR
877
-
878
- Extract text from an image file with Tesseract.js:
879
-
880
- ocr "scan.png" as text
881
- show text
882
-
883
- With a language pack:
884
-
885
- ocr "brief.png" as inhalt using "deu"
886
-
887
- Semantics:
888
-
889
- - `ocr "<image>" as <variable>` mirrors `ask "<prompt>" as <name>`: the
890
- extracted text is bound to `<variable>`.
891
- - The image may be any expression that evaluates to an image path, buffer,
892
- or URL accepted by Tesseract.js.
893
- - `using "<lang>"` selects the Tesseract language pack (`"eng"` by default;
894
- combinations like `"deu+eng"` are allowed).
895
- - The statement is async — top-level use wraps the program in the async
896
- runtime, and using it inside a function makes that function async.
897
- - `tesseract.js` is an implementation dependency: it never appears in PlainScript
898
- source, but `plainscript install`, `plainscript run`, and `plainscript build` fetch it
899
- automatically through dependency detection.
900
-
901
- Generated JavaScript shape:
902
-
903
- ```js
904
- const { createWorker } = require('tesseract.js');
905
-
906
- async function __ocr(imagePath, lang) {
907
- const worker = await createWorker(lang || 'eng');
908
- try {
909
- const { data } = await worker.recognize(imagePath);
910
- return data.text;
911
- } finally {
912
- await worker.terminate();
913
- }
914
- }
915
-
916
- let text = await __ocr("scan.png");
917
- ```
918
-
919
- ---
920
-
921
- ## WhatsApp Bots
922
-
923
- A `whatsapp bot` block declares one WhatsApp connection and its message
924
- handlers. The implementation package (`@whiskeysockets/baileys`, with
925
- `qrcode-terminal` for QR rendering) is detected, installed, and hidden —
926
- it never appears in PlainScript source.
927
-
928
- whatsapp bot
929
- auth "session" // credential folder
930
- login pairing "2348012345678" // or: login qr
931
- // or: login pairing phone
932
-
933
- on message
934
- log message
935
-
936
- if message.text is "/start"
937
- reply "Welcome!"
938
- done
939
-
940
- if message.text is "/help"
941
- reply `Available commands:
942
- /start /help`
943
- done
944
- done
945
- done
946
-
947
- Interactive linking — the number may come from any value:
948
-
949
- ask "WhatsApp number: " as phone
950
-
951
- whatsapp bot
952
- auth "session"
953
- login pairing phone
954
- done
955
-
956
- Syntax:
957
-
958
- - The block opens with `whatsapp bot` and closes with `done`. It may contain
959
- at most one `auth`, one `login`, and any number of `on message` handlers;
960
- anything else is a teaching error.
961
- - `auth "<folder>"` selects the credential folder created by
962
- `useMultiFileAuthState` and reused across restarts. Optional; defaults to
963
- `"plainscript-whatsapp-auth"`.
964
- - `login qr` links by scanning a terminal QR code; it is the default when the
965
- clause is omitted. `login pairing "<number>"` requests an enter-on-phone
966
- pairing code instead. Pairing numbers are validated at compile time: after
967
- stripping separators and a leading plus (`+234 801-234-5678`) they must be
968
- 8–15 digits.
969
- - `login pairing` also accepts any PlainScript value
970
- (`login pairing phone`) — typically a variable filled by `ask`. Values are
971
- normalized and validated when the bot starts; invalid input fails with the
972
- same teaching message before any connection attempt.
973
- - `on message ... done` registers one handler for incoming messages. Inside:
974
- - `message` refers to the normalized record `{ text, chat, sender, name,
975
- id, time, isGroup }` of the current delivery.
976
- - `log message` prints the record to the console; using it outside an
977
- `on message` body is a compile-time teaching error.
978
- - `reply <value>` answers the current chat — strings verbatim, other values
979
- as JSON.
980
-
981
- Runtime semantics:
982
-
983
- - Only `messages.upsert` events of type `notify` are delivered; the bot's own
984
- outgoing messages (`fromMe`) and `status@broadcast` are filtered out before
985
- handlers run.
986
- - Ephemeral and view-once wrappers are unwrapped; text falls back through
987
- caption fields for media messages.
988
- - Group chats set `sender` to the participant JID and `isGroup` to true;
989
- replies go to the group chat.
990
- - Handler errors are logged and never crash the process.
991
- - On transient disconnects the socket reconnects after 3 seconds; a remote
992
- sign-out stops cleanly instead of looping.
993
-
994
- Generated JavaScript shape (abridged):
995
-
996
- ```js
997
- const { __whatsappStart, __whatsappOnMessage, __whatsappReply } = (() => {
998
- // makeWASocket + useMultiFileAuthState + fetchLatestBaileysVersion live in
999
- // here, behind require('@whiskeysockets/baileys')
1000
- })();
1001
- await __whatsappStart({ folder: "session", login: { mode: 'pairing', phone: "2348012345678" } });
1002
- // value form: login: { mode: 'pairing', phone: (phone) }
1003
- __whatsappOnMessage(async (__waCtx) => {
1004
- console.log(__waCtx.message);
1005
- if (__waCtx.message.text === "/start") {
1006
- await __whatsappReply(__waCtx.chat, "Welcome!");
1007
- }
1008
- });
1009
- ```
1010
-
1011
- ---
1012
-
1013
- ## Developer Experience
1014
-
1015
- ### Formatter
1016
-
1017
- Format a PlainScript file in-place:
1018
-
1019
- plainscript fmt app.ps
1020
-
1021
- Formatting rules:
1022
-
1023
- - 4-space consistent indentation
1024
- - Trailing whitespace removed from every line
1025
- - One blank line between top-level blocks
1026
- - Multiple consecutive blank lines collapsed into one
1027
- - Multi-line array elements indented relative to their enclosing block
1028
-
1029
- ### Syntax Checker
1030
-
1031
- Check syntax without generating JavaScript or running anything:
1032
-
1033
- plainscript check app.ps
1034
-
1035
- Exits with code 0 if no errors are found. Exits with code 1 and prints a
1036
- friendly error (with line, column, and suggestion where possible) if the
1037
- file contains a syntax error.
1038
-
1039
- ### VS Code Extension
1040
-
1041
- Install `plainscript-vscode` for:
1042
-
1043
- - Syntax highlighting
1044
- - File icon for `.ps` files
1045
- - Auto-closing pairs: `()` `[]` `{}` `""`
1046
- - Comment toggling (`//`)
1047
- - Bracket matching
1048
- - Code folding
1049
- - Snippets for common patterns
1050
-
1051
- See `plainscript-vscode/README.md` for installation instructions.
1052
-
1053
- ### Acode Editor
1054
-
1055
- Acode support (`plainscript-acode/`) provides syntax highlighting and `.ps` file
1056
- recognition in the [Acode](https://acode.app) Android editor, using Acode's
1057
- modern CodeMirror 6 `editorLanguages` API.
1058
-
1059
- Install it by zipping the `plainscript-acode/` folder contents (`plugin.json`,
1060
- `main.js`, `stream-spec.js`, `README.md`) and selecting the zip in Acode:
1061
- Settings → Plugins → "+".
1062
-
1063
- Acode support highlights keywords, comparisons, strings, numbers, comments,
1064
- route paths, `use` package names, stdlib calls, expression words, number
1065
- words, and JavaScript/SQL blocks. It does **not** provide LSP diagnostics,
1066
- autocomplete, or compiler execution. The tokenizer in `stream-spec.js` is
1067
- pure CommonJS and is exercised by the test suite (`tests/compiler.test.js`).
1068
-
1069
- See `plainscript-acode/README.md` for details.
1070
-
1071
- ---
1072
-
1073
- ## Project Management
1074
-
1075
- PlainScript follows a zero-configuration model. Source files live in `src/` (or the
1076
- project root when `src/` doesn't exist) and `plainscript build` discovers them
1077
- automatically, preserving file names and directory structure into `dist/`.
1078
-
1079
- For projects that need custom output or source directories, add an optional
1080
- `plainscript.config.json` with a `compilerOptions` block:
1081
-
1082
- ```json
1083
- {
1084
- "compilerOptions": {
1085
- "outDir": "./build",
1086
- "rootDir": "./lib",
1087
- "exclude": ["vendor"]
1088
- }
1089
- }
1090
- ```
1091
-
1092
- ### Commands
1093
-
1094
- | Command | Behaviour |
1095
- |-------------------------|------------------------------------------------------|
1096
- | `plainscript run <file.ps>` | Install dependencies, compile and execute |
1097
- | `plainscript build [file]` | Compile to dist/ preserving names; no arg builds all|
1098
- | `plainscript check <file.ps>` | Check syntax only (no output, no execution) |
1099
- | `plainscript fmt <file.ps>` | Format a PlainScript file in-place |
1100
- | `plainscript new [name]` | Create a new PlainScript project |
1101
- | `plainscript install` | Detect and install dependencies from source files |
1102
- | `plainscript start` | Build src/app.ps and run its dist/ output |
1103
- | `plainscript doctor` | Check the PlainScript project environment |
1104
- | `plainscript add <pkg>` | Install a package into the project |
1105
- | `plainscript remove <pkg>` | Uninstall a package from the project |
1106
- | `plainscript update` | Runs `npm update` for all installed packages |
1107
- | `plainscript version` | Print the compiler version |
1108
- | `plainscript help` | Print help text |
1109
-
1110
- ### Dependency Validation
1111
-
1112
- Before compiling, PlainScript checks that every package referenced by `use` is installed.
1113
- If a package is missing, the compiler prints a friendly error and stops:
1114
-
1115
- Package "express" is not installed.
1116
- Run: plainscript add express
1117
-
1118
- ---
1119
-
1120
- ## Reserved Keywords
1121
-
1122
- remember becomes show
1123
- make give
1124
- if otherwise done
1125
- for each every in
1126
- while
1127
- use import
1128
- when someone visits
1129
- listen on
1130
- reply json
1131
- serve folder
1132
- is greater less than
1133
- above below at least most
1134
- not empty contains
1135
- starts ends with
1136
- between and
1137
- web route start
1138
- database query insert update delete execute
1139
- ask ocr using
1140
- true false null
1141
- try recover retry times wait
1142
- accept uploads session sessions destroy
1143
- cookie expires limit allow folder
1144
- rate requests enable oauth google
1145
- require api key matches nothing
1146
- note
1147
-
1148
- ---
1149
-
1150
- This document is the single source of truth for PlainScript v1.0.1.
1151
- Every compiler implementation must follow this specification.