plainscript-lang 1.0.2 → 1.0.3

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 (74) hide show
  1. package/README.md +173 -738
  2. package/compiler/bundler.js +83 -12
  3. package/compiler/cli.js +74 -27
  4. package/compiler/dependency-detector.js +11 -0
  5. package/compiler/generator.js +372 -35
  6. package/compiler/lexer.js +2 -0
  7. package/compiler/parser.js +410 -28
  8. package/compiler/sourcemap.js +142 -0
  9. package/compiler/version.js +1 -1
  10. package/docs/CAPABILITY_GAP_AUDIT.md +98 -534
  11. package/docs/PLAINSCRIPT-SPEC.md +304 -551
  12. package/docs/index.html +127 -598
  13. package/docs/website/script.js +185 -1006
  14. package/docs/website/style.css +220 -656
  15. package/examples/ai-providers.pln +7 -0
  16. package/examples/arrays.pln +4 -12
  17. package/examples/async-errors.pln +18 -0
  18. package/examples/auth-api.pln +3 -50
  19. package/examples/auth-sessions.pln +32 -0
  20. package/examples/basics.pln +14 -0
  21. package/examples/bots.pln +13 -0
  22. package/examples/cache-and-jobs.pln +6 -28
  23. package/examples/cache-schedule.pln +22 -0
  24. package/examples/collections.pln +15 -0
  25. package/examples/concurrency.pln +12 -43
  26. package/examples/conditions.pln +22 -0
  27. package/examples/database.pln +6 -39
  28. package/examples/day2.pln +6 -6
  29. package/examples/day3.pln +4 -10
  30. package/examples/deployment.pln +3 -9
  31. package/examples/email-send.pln +3 -22
  32. package/examples/error-handling.pln +6 -54
  33. package/examples/expressions.pln +7 -40
  34. package/examples/file-uploads.pln +5 -34
  35. package/examples/files-and-config.pln +5 -46
  36. package/examples/files.pln +12 -0
  37. package/examples/football-backend/app.pln +21 -20
  38. package/examples/functions.pln +17 -0
  39. package/examples/hello.pln +2 -3
  40. package/examples/http-client.pln +3 -44
  41. package/examples/http.pln +11 -0
  42. package/examples/id-verification/app.pln +4 -3
  43. package/examples/id-verification/make-sample-id.js +29 -42
  44. package/examples/json.pln +11 -0
  45. package/examples/loops.pln +13 -11
  46. package/examples/modules/app.pln +3 -16
  47. package/examples/modules/main.pln +4 -0
  48. package/examples/modules/math.pln +5 -16
  49. package/examples/mongo.pln +33 -0
  50. package/examples/objects.pln +3 -11
  51. package/examples/ocr.pln +22 -0
  52. package/examples/packages.pln +6 -0
  53. package/examples/record-kinds.pln +6 -42
  54. package/examples/records.pln +15 -0
  55. package/examples/rest-api-fetch.pln +6 -90
  56. package/examples/rest-api.pln +5 -65
  57. package/examples/scheduled-tasks.pln +4 -23
  58. package/examples/search-and-filter.pln +4 -34
  59. package/examples/server.pln +5 -24
  60. package/examples/sessions-and-cookies.pln +4 -50
  61. package/examples/sqlite.pln +23 -0
  62. package/examples/start.pln +2 -2
  63. package/examples/stdlib.pln +4 -41
  64. package/examples/string-verbs.pln +16 -0
  65. package/examples/telegram-ai-bot.pln +19 -0
  66. package/examples/telegram-bot.pln +4 -40
  67. package/examples/testing.pln +13 -0
  68. package/examples/web-api.pln +27 -0
  69. package/examples/web-app.pln +4 -16
  70. package/examples/websocket-server.pln +5 -26
  71. package/examples/websocket.pln +13 -0
  72. package/examples/whatsapp-bot/pairing.pln +4 -5
  73. package/examples/whatsapp-bot/qr.pln +7 -3
  74. package/package.json +3 -2
package/README.md CHANGED
@@ -1,221 +1,96 @@
1
1
  # PlainScript
2
2
 
3
3
  [![CI](https://github.com/ayoistooslick/plainscript/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/ayoistooslick/plainscript/actions/workflows/npm-publish.yml)
4
- [![npm version](https://badge.fury.io/js/plainscript-lang.svg?icon=si%3Anpm)](https://www.npmjs.com/package/plainscript-lang)
5
- [![Downloads](https://img.shields.io/badge/downloads-1.1GB/month-green)](https://www.npmjs.com/package/plainscript-lang)
6
4
 
7
- <p align="center">
8
- <img src="https://github.com/ayoistooslick/plainscript/blob/main/docs/logo.jpg" alt="PlainScript Logo" width="200" />
9
- </p>
5
+ PlainScript is a programming language that reads like English and runs on Node.js. You write `.pln` files, and PlainScript turns them into JavaScript you can run anywhere.
10
6
 
11
- > "When even a simple sentence can be code."
12
- > Don't forget to star the repo
13
-
14
- PlainScript is an Intent-Oriented Programming Language (IOPL). You describe **what** you want; the compiler decides **how** to implement it in JavaScript.
15
-
16
- **Current version:** v1.0.2 — the `plainscript` npm package with a TypeScript-style production build (`plainscript build` → `dist/`, source names preserved).
17
-
18
- ---
19
-
20
- ## Quick start
7
+ ## Get started in 60 seconds
21
8
 
22
9
  ```bash
23
- npx plainscript new myapp # scaffolds src/app.pln and package.json
24
- cd myapp
25
- npm install # installs plainscript as a devDependency plus runtime packages
26
- npm run build # compiles src/ -> dist/ (plainscript build)
27
- node dist/app.js # or: npm start
10
+ npx plainscript new hello
11
+ cd hello
12
+ npm install
13
+ npx plainscript check
14
+ npm run build
15
+ npm start
28
16
  ```
29
17
 
30
- Adding PlainScript to an existing project:
18
+ Run a single file without saving any build output:
31
19
 
32
20
  ```bash
33
- npm install --save-dev plainscript-lang
34
- # start writing src/*.pln files — plainscript build auto-discovers them
35
- ```
36
-
37
- No global install is needed anywhere — everything runs through npm scripts
38
- and `npx`.
39
-
40
- ---
41
-
42
- ## CLI
43
-
21
+ npx plainscript run examples/basics.pln
44
22
  ```
45
- plainscript run <file.pln> Install missing dependencies, compile and execute
46
- (executes from a scratch dir — nothing is written
47
- into your project)
48
- plainscript build [file.pln] Compile to dist/. With no argument, builds every
49
- .pln file under the source root, preserving names
50
- and folder structure
51
- plainscript check <file.pln> Check syntax only (no output, no execution)
52
- plainscript fmt <file.pln> Format a PlainScript file in-place
53
- plainscript new [name] Create a new PlainScript project (npm-ready)
54
- plainscript install Install dependencies detected in the project's sources
55
- plainscript start Build src/app.pln and run its dist/ output
56
- plainscript doctor Check the PlainScript project environment
57
- plainscript add <package> Install a package into the project
58
- plainscript remove <package> Uninstall a package from the project
59
- plainscript update Update all installed npm packages
60
- plainscript version Print the compiler version
61
- plainscript help Print help text
62
- ```
63
-
64
- ---
65
23
 
66
- ## Building and configuration
24
+ ## Commands
67
25
 
68
- `plainscript build` is a deterministic production build, TypeScript-style but for
69
- `.pln` sources — **zero configuration required**:
26
+ | Command | What it does |
27
+ | --- | --- |
28
+ | `plainscript new [name]` | Create a new project |
29
+ | `plainscript check` | Validate your code |
30
+ | `plainscript build` | Compile to JavaScript in `dist/` |
31
+ | `plainscript run <file>` | Check, install, and run a file |
32
+ | `plainscript start` | Build and start `src/app.pln` |
33
+ | `plainscript fmt <file>` | Format your code |
34
+ | `plainscript add <package>` | Add an npm package |
35
+ | `plainscript remove <package>` | Remove an npm package |
36
+ | `plainscript update` | Update installed packages |
37
+ | `plainscript doctor` | Check your project setup |
38
+ | `plainscript version` | Print version |
70
39
 
71
- - `plainscript build` (no argument) discovers every `.pln` file under `src/` and
72
- compiles each to `dist/` **preserving source file names and folder structure**:
73
- `src/messi.pln` → `dist/messi.js`,
74
- `src/helpers/math.pln` → `dist/helpers/math.js`.
75
- - `plainscript build <file.pln>` compiles a single file into `dist/`.
76
- - Imports are bundled into each output, so every file in `dist/` runs
77
- standalone under Node.
78
- - Rebuilds are byte-identical — safe to commit, diff, and cache.
40
+ Run `plainscript check` after every change — it validates your code and catches errors early.
79
41
 
80
- Source discovery skips `node_modules`, hidden directories, and the output
81
- directory itself. When no `src/` directory exists, the project root is scanned
82
- instead.
42
+ ## Syntax
83
43
 
84
- ### Optional `plainscript.config.json`
85
-
86
- For projects that need custom output or source directories, add a
87
- `plainscript.config.json` with a `compilerOptions` block (like `tsconfig.json`):
88
-
89
- ```json
90
- {
91
- "compilerOptions": {
92
- "outDir": "./build",
93
- "rootDir": "./lib",
94
- "exclude": ["vendor"]
95
- }
96
- }
97
- ```
98
-
99
- ### Publishing a library written in PlainScript
100
-
101
- ```json
102
- {
103
- "name": "my-plainscript-library",
104
- "main": "dist/index.js",
105
- "scripts": {
106
- "build": "plainscript build",
107
- "prepare": "plainscript build"
108
- },
109
- "devDependencies": { "plainscript-lang": "^1.0.2" }
110
- }
111
- ```
112
-
113
- `src/index.pln` builds to `dist/index.js`; consumers install and `require()`
114
- it like any Node package. There is no PlainScript-specific registry or format —
115
- standard `package.json` semantics apply.
116
-
117
- ---
118
-
119
- ## Language features
120
-
121
- ### Variables
44
+ ### Variables and output
122
45
 
123
46
  ```plainscript
124
- let name be "Ayokunle"
125
- let age be 16
126
- set age to 17
127
- ```
128
-
129
- ### String Templates
130
-
131
- Backtick-delimited strings preserve whitespace and support `${expression}` interpolation:
132
-
133
- ```plainscript
134
- let name be "World"
135
- let greeting be `Hello ${name}!`
47
+ remember name as "Ada"
48
+ let count is 3
49
+ let greeting is `Hello, ${name}!`
136
50
  show greeting
137
-
138
- let email be `Dear ${customer},
139
-
140
- Thank you for your order #${orderId}.
141
-
142
- Best regards,
143
- The Team`
51
+ count becomes count + 1
144
52
  ```
145
53
 
146
- Interpolation compiles directly to JavaScript template literals — it is not evaluated at compile time. Literal dollar signs without `{` are preserved as-is.
54
+ `remember name as value` declares a variable. `show`, `print`, and `display` all print output.
147
55
 
148
56
  ### Conditions
149
57
 
150
58
  ```plainscript
151
- when age is at least 18
152
- show "Adult"
59
+ if score is at least 80 and status is not "blocked"
60
+ show "accepted"
153
61
  otherwise
154
- show "Teenager"
62
+ show "review"
155
63
  done
64
+ ```
156
65
 
157
- when name contains "PlainScript"
158
- show "Found it"
159
- done
66
+ You can use `is`, `more than`, `fewer than`, `contains`, `starts with`, `ends with`, `and`, `or`, and `not`.
160
67
 
161
- when score between 90 and 100
162
- show "A grade"
163
- done
68
+ ### Lists and records
69
+
70
+ ```plainscript
71
+ remember players as list with "Ada", "Grace", "Lin"
72
+ show players at position 1
73
+
74
+ remember user as record with name "Ada" and active true done
75
+ show user.name
164
76
  ```
165
77
 
166
- English alternatives: `same as` (`===`), `different from` (`!==`), `more than` (`>`), `fewer than` (`<`).
167
-
168
- All comparison operators:
169
-
170
- | PlainScript | JavaScript |
171
- |------------------------|--------------------|
172
- | `is` / `is equal to` | `===` |
173
- | `same as` | `===` |
174
- | `is not` | `!==` |
175
- | `different from` | `!==` |
176
- | `is greater than` / `is above` | `>` |
177
- | `more than` | `>` |
178
- | `is less than` / `is below` | `<` |
179
- | `fewer than` | `<` |
180
- | `is at least` | `>=` |
181
- | `is at most` | `<=` |
182
- | `is empty` | `.length === 0` |
183
- | `is not empty` | `.length > 0` |
184
- | `contains "x"` | `.includes("x")` |
185
- | `made of "x"` | `.includes("x")` |
186
- | `starts with "x"` | `.startsWith("x")` |
187
- | `starts as "x"` | `.startsWith("x")` |
188
- | `ends with "x"` | `.endsWith("x")` |
189
- | `ends as "x"` | `.endsWith("x")` |
190
- | `between A and B` | `>= A && <= B` |
191
- | `has field "x"` | `"x" in obj` |
192
- | `at position key` | `obj[key]` |
78
+ You can also use plain JavaScript arrays and objects: `[1, 2, 3]` and `{name: "Ada"}`.
193
79
 
194
80
  ### Functions
195
81
 
196
82
  ```plainscript
197
- to add a and b together
198
- give back a + b
83
+ make add(a, b)
84
+ give a + b
199
85
  done
200
- show add(5, 7)
201
86
 
202
- to multiply x and y together
203
- give back x * y
204
- done
87
+ show add(2, 3)
205
88
  ```
206
89
 
207
- ### Arrays & Objects
208
-
209
90
  ```plainscript
210
- let players be list with "Haaland", "Foden", "Rodri"
211
- show players[0]
212
- set players[1] to "Palmer"
213
-
214
- let user be record with
215
- name "Ayokunle"
216
- age 17
91
+ make greet(name as "friend")
92
+ give `Hello, ${name}`
217
93
  done
218
- show user.name
219
94
  ```
220
95
 
221
96
  ### Loops
@@ -225,656 +100,216 @@ for each player in players
225
100
  show player
226
101
  done
227
102
 
228
- for every item in basket // alias for "for each"
229
- show item
103
+ for index position from 0 to 2
104
+ show position
230
105
  done
231
106
 
232
- while age is less than 18
233
- set age to age + 1
107
+ while attempts is less than 3
108
+ attempts becomes attempts + 1
234
109
  done
235
110
  ```
236
111
 
237
- ### PlainScript Expressions
238
-
239
- Collections, properties, and files read like sentences.
240
-
241
- **Items**
112
+ ### Record kinds
242
113
 
243
114
  ```plainscript
244
- let players be list with "Haaland", "Foden", "Rodri"
245
-
246
- show first player from players // players[0]
247
- show last player from players // players[players.length - 1]
248
- show player two from players // players[1]
249
- first player from players is now "Haaland" // players[0] = "Haaland"
250
- ```
251
-
252
- Number words from `one` to `twenty` map to one-based positions: `player one` is the first item.
253
-
254
- **Collections**
255
-
256
- ```plainscript
257
- show players length // players.length
258
- add("Palmer" to players) // players.push("Palmer")
259
- remove("Rodri" from players) // players.splice(players.indexOf("Rodri"), 1)
260
-
261
- when players contains "Foden" // players.includes("Foden")
262
- show "Found"
115
+ define a kind called "Player" with
116
+ name is ""
117
+ goals is 0
263
118
  done
264
- ```
265
-
266
- English alternatives: `made of` (`.includes()`), `starts as` (`.startsWith()`), `ends as` (`.endsWith()`), `has field` (`in`), `at position` (`[]`).
267
-
268
- **Properties**
269
119
 
270
- ```plainscript
271
- show name of user // user.name
272
- show city of address of customer // customer.address.city
273
- name of user is now "Ayo" // user.name = "Ayo"
120
+ remember player as create a Player with name "Ada" and goals 4
274
121
  ```
275
122
 
276
- `of` chains right-to-left: `city of address of customer` reads the city of the address of the customer.
277
-
278
- **Files**
123
+ ### Compound data structures
279
124
 
280
125
  ```plainscript
281
- let data be read("users.txt") // fs.readFileSync("users.txt", 'utf8')
282
- write(data to "users.txt") // fs.writeFileSync(data, "users.txt", 'utf8')
283
- ```
126
+ // Dictionaries
127
+ remember userMap as dictionary with "name" is "Ada" and "role" is "admin" done
128
+ put "role" as "editor" in userMap
129
+ remember mapKeys as keys of userMap
284
130
 
285
- The older `readFile()` / `writeFile()` forms still work and are unchanged.
131
+ // Sets
132
+ remember tags as set with "admin", "editor", "user" done
133
+ remember newTags as union of tags and (set with "moderator" done)
286
134
 
287
- ### Logical Assignment
288
-
289
- ```plainscript
290
- let flag be false
291
- flag or is now true
292
- show flag
293
-
294
- let val be null
295
- val nullish is now "default"
296
- show val
135
+ // Tuples
136
+ remember point as tuple with 10, 20, 30 done
137
+ unpack point into x, y, z
297
138
  ```
298
139
 
299
- ### TypeScript-parity capabilities (1.0.2)
300
-
301
- The full capability-gap audit lives in [`docs/CAPABILITY_GAP_AUDIT.md`](https://github.com/ayoistooslick/plainscript/blob/main/docs/CAPABILITY_GAP_AUDIT.md).
302
- These features close it in PlainScript's own grammar:
303
-
304
- - **Record kinds (classes):** `to define a kind called "Person" with name "" end`
305
- + `create a Person with name "Ada" and age 17`. Plain-object instances; unknown
306
- fields throw.
307
- - **Concurrency:** `all of [...]`, `any of [...]`, `settled of [...]`,
308
- `withTimeout(promise, ms)`.
309
- - **Generators:** `yield` inside `define ... end`; consumed with `for each` or
310
- `spread of`.
311
- - **Reflection:** `typeOf`, `fieldsOf`, `valueOf`, `hasField`, `sizeOf`.
312
- - **Binary:** `base64Encode/Decode`, `textToBytes/bytesToText`, `sha256/sha1/md5`.
313
- - **Config:** `yamlDecode/yamlEncode`, `load env file ".env"`.
314
- - **CLI & processes:** `args()`, `runCommand(cmd, [args])`.
315
- - **Filesystem & paths:** `fileSize`, `fileType`, `lastModified`, `walkFolder`,
316
- `joinPath`, `baseName`, `folderOf`, `extensionOf`.
317
- - **Streams:** `writeLine`, `appendLine`.
318
- - **Collections:** `keyMap/mapSet/mapGet/mapHas/mapDelete`, `newSet/addToSet`.
319
- - **Dynamic modules:** `loadModule("./m")`.
320
- - **Native tests:** `test "name" ... end` with `check a equals b`,
321
- `check a contains b`, `check a is b`, `check <expr> raises "msg"`.
322
- - **Exports:** `export <name>`.
323
-
324
- ---
325
-
326
- ## Backend Services
327
-
328
- Everything below is compiled by the deterministic compiler — no rules, no AI,
329
- no hidden codegen.
330
-
331
- ### Portable databases (SQLite native or WebAssembly)
140
+ ### Imports and exports
332
141
 
333
142
  ```plainscript
334
- database "app.db" // probes better-sqlite3, falls back to sql.js
335
- ```
143
+ // Import specific functions
144
+ bring circleArea and squareArea from "./math.pln"
336
145
 
337
- `plainscript install` verifies that `better-sqlite3` actually loads; if the native
338
- module cannot be used, PlainScript warns and continues on the pure-JavaScript
339
- WebAssembly engine (`sql.js`) — the same program runs unchanged. Force an
340
- engine explicitly:
146
+ // Import with a namespace
147
+ bring all from "./math.pln" as math
148
+ show math.circleArea(5)
341
149
 
342
- ```plainscript
343
- database "app.db" using "native" // hard requirement: better-sqlite3
344
- database "app.db" using "wasm" // hard requirement: sql.js
345
- ```
346
-
347
- The WebAssembly engine persists the whole database to disk after every write,
348
- so data survives restarts either way.
150
+ // Import an npm package
151
+ bring axios from "axios"
349
152
 
350
- ### HTTP client
153
+ // Use @/ to import from src/
154
+ bring button from "@/components/button.pln"
351
155
 
352
- ```plainscript
353
- let r be get "https://api.example.com/users"
354
- when ok of r
355
- show status of r
356
- show data of r
357
- done
358
-
359
- let created be post url with body
360
- headers record with accept "application/json" done
361
- timeout 5000
156
+ // Re-export everything from another file
157
+ export all from "./submodule.pln"
362
158
  ```
363
159
 
364
- Methods: `get`, `post … with <body>`, `put`, `patch`, `delete "<url>"`.
365
- Responses are records: `ok`, `status`, `headers`, `data` (JSON is parsed
366
- automatically). The default timeout is 30 seconds. `wait for fetch(...)`
367
- awaits raw promises when you need it.
160
+ ## AI providers
368
161
 
369
- ### Passwords and tokens (built-in auth)
162
+ PlainScript can call AI models from any provider that supports the OpenAI API format. Your API keys stay in environment variables.
370
163
 
371
164
  ```plainscript
372
- let hash be hashPassword("correct horse")
373
- when checkPassword(password of body of request, hash)
374
- let token be createToken(user, env("TOKEN_SECRET"), 3600)
375
- done
376
-
377
- let payload be readToken(token, env("TOKEN_SECRET"))
165
+ remember answer as chat("llama-3.3-70b-versatile", "Summarize PlainScript", {
166
+ provider: "groq",
167
+ key: env("GROQ_API_KEY"),
168
+ temperature: 0.2
169
+ })
170
+ show answer
378
171
  ```
379
172
 
380
- `hashPassword`/`checkPassword` use scrypt; tokens are HMAC-signed with an
381
- expiry and fail closed on tampering or timeout.
173
+ Supported providers: `groq`, `openai`, `openrouter`, `together`, `fireworks`, `deepseek`. You can also point to any custom OpenAI-compatible endpoint with `base`, `key`, and `headers`.
382
174
 
383
- ### Sessions
175
+ ## Telegram bots
384
176
 
385
177
  ```plainscript
386
- web app
387
- enable sessions "a-long-random-secret"
388
-
389
- route post "/login"
390
- user of session of request is username of body of request
391
- show "welcome"
178
+ bot env("TELEGRAM_BOT_TOKEN")
179
+ when someone sends "/start"
180
+ reply "Welcome"
392
181
  done
393
-
394
- route get "/me"
395
- show user of session of request
396
- done
397
-
398
- route post "/logout"
399
- destroy session
400
- show "bye"
182
+ when someone sends matching "/ask (.+)"
183
+ remember answer as chatWith("groq", "llama-3.3-70b-versatile", message)
184
+ reply answer
401
185
  done
186
+ start telegram bot
402
187
  ```
403
188
 
404
- Sessions ride an HMAC-signed `HttpOnly` cookie (`plainscript.sid`). The store is
405
- in-memory: restarting the server signs everyone out.
406
-
407
- ### File uploads
189
+ Inside a handler, `message`, `args`, `matches`, `chat`, and `chatId` give you access to the current update.
408
190
 
409
- ```plainscript
410
- accept uploads limit "5 MB" allow list with "image/png", "image/jpeg" folder "uploads"
191
+ ## Standard library
411
192
 
412
- route post "/scan"
413
- let file be upload("doc")
414
- ocr path of file as text
415
- show "scanned: " + text
416
- done
417
- ```
418
-
419
- Files arrive as records with `name`, `type`, `size`, `data` (buffer) and
420
- `path` (string, when a folder is set). Oversized files get HTTP 413, wrong
421
- types 415. `uploads("docs")` returns every file under a field name.
422
-
423
- ### Cookies
424
-
425
- ```plainscript
426
- set cookie "theme" to "dark" expires in 7 days
427
- show cookie("theme")
428
- clear cookie "theme"
429
- ```
430
-
431
- ### Rate limiting
432
-
433
- ```plainscript
434
- rate limit 100 requests per minute
435
- ```
436
-
437
- Sliding window per client IP; the quota-exceeded response is HTTP 429.
438
-
439
- ### Google OAuth
440
-
441
- ```plainscript
442
- google oauth
443
- id is env("GOOGLE_ID")
444
- secret is env("GOOGLE_SECRET")
445
- callback is "https://myapp.dev/auth/google/callback"
446
- landing is "/dashboard"
447
- done
448
- ```
449
-
450
- Registers `/auth/google` (redirect) and `/auth/google/callback`
451
- (code-for-token exchange + profile fetch); after login the session holds the
452
- user and the browser lands on `landing`.
453
-
454
- ### Custom 404
193
+ No imports needed — these work out of the box:
455
194
 
456
195
  ```plainscript
457
- when nothing matches
458
- status 404
459
- show json
460
- error is "No such road"
461
- done
462
- done
196
+ remember encoded as jsonEncode(user)
197
+ remember decoded as jsonDecode(encoded)
198
+ remember contents as readFile("notes.txt")
199
+ writeFile("notes.txt", contents)
200
+ remember digest as sha256("plain text")
201
+ remember currentTime as time()
202
+ remember identifier as uuid()
463
203
  ```
464
204
 
465
- ### Error handling and retries
466
-
467
- ```plainscript
468
- try
469
- let data be jsonDecode(raw)
470
- recover as err
471
- show "bad json: " + message of err
472
- done
473
-
474
- retry 3 times every 5 seconds
475
- wait for fetch("https://flaky.api")
476
- done
477
- ```
205
+ Other built-in helpers cover strings, collections, file paths, HTTP, caching, environment variables, and crypto.
478
206
 
479
- ---
480
-
481
- ## Runtime Standard Library
482
-
483
- No imports needed. These functions are built into the compiler:
484
-
485
- | PlainScript | Description |
486
- |--------------------------|------------------------------------|
487
- | `show(x)` | Print a value (`console.log`) |
488
- | `readFile("path")` | Read a file as UTF-8 text |
489
- | `writeFile("path", data)` | Write text to a file |
490
- | `read("path")` | Read a file as UTF-8 text |
491
- | `fileExists("path")` | Check if a file exists |
492
- | `sleep(ms)` | Sleep synchronously |
493
- | `time()` | Current Unix timestamp (`Date.now()`) |
494
- | `date()` | ISO date string |
495
- | `jsonEncode(value)` | `JSON.stringify` |
496
- | `jsonDecode(string)` | `JSON.parse` |
497
- | `env("KEY")` | Read environment variable |
498
- | `exit(code)` | Exit the process |
499
- | `uuid()` | Generate a UUID v4 |
500
- | `length(x)` | Length of array/string |
501
- | `uppercase(x)` | Convert to uppercase |
502
- | `lowercase(x)` | Convert to lowercase |
503
- | `random()` | Random number 0–1 |
504
- | `round(x)` | Round to nearest integer |
505
-
506
- ---
507
-
508
- ## Web Apps
509
-
510
- ```plainscript
511
- web app
512
-
513
- route "/"
514
- show "Hello from PlainScript!"
515
- done
516
-
517
- route "/api/status"
518
- show json
519
- status is "ok"
520
- version is "2.0"
521
- done
522
- done
523
-
524
- start 3000
525
- ```
526
-
527
- ---
528
-
529
- ## SQLite Database
530
-
531
- ```plainscript
532
- database "app.db"
533
-
534
- execute
535
- CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)
536
- done
537
-
538
- insert
539
- INSERT INTO users (name) VALUES ('Alice')
540
- done
541
-
542
- let rows be query
543
- SELECT * FROM users
544
- done
545
- ```
546
-
547
- ---
548
-
549
- ## Backend Capabilities
550
-
551
- Everything a backend needs, as first-class deterministic language features —
552
- no rules, no AI, no hidden codegen.
553
-
554
- ### HTTP routing
207
+ ## Web apps
555
208
 
556
209
  ```plainscript
557
210
  web app
558
211
  allow cors
559
212
 
560
- group "/api"
561
-
562
- route get "/users"
563
- let users be query
564
- SELECT * FROM users
565
- done
566
- show users
567
- done
568
-
569
- route post "/users"
570
- let missing be validate(body of request, list with "name", "email")
571
- when length of missing is greater than 0
572
- status 400
573
- show missing
574
- otherwise
575
- show "created"
576
- done
213
+ route get "/health"
214
+ reply json
215
+ ok is true
577
216
  done
578
-
579
217
  done
580
218
 
581
- start env("PORT")
582
- ```
583
-
584
- `param("id")`, `query("page")` and `header("x-token")` read request data;
585
- `body()` / `body("field")` read the JSON request body; `group` composes path
586
- prefixes; `status <n>` sets the response code and `redirect to "<url>"` issues a
587
- redirect.
588
-
589
- ### Databases with parameters and transactions
590
-
591
- ```plainscript
592
- database "app.db" // or: postgres env("DATABASE_URL")
593
-
594
- transaction
595
- insert
596
- INSERT INTO users (name) VALUES ({who})
219
+ route post "/echo"
220
+ remember body as body of request
221
+ reply json
222
+ received is body
597
223
  done
598
224
  done
225
+
226
+ start 3000
599
227
  ```
600
228
 
601
- Placeholders `{likeThis}` bind to PlainScript variables. `postgres "..."` switches
602
- every SQL statement to node-postgres pool queries (`$n`, awaited).
229
+ Routes support `get`, `post`, `put`, `patch`, and `delete`. Read request data with `body of request`, `param("id")`, `query("page")`, and `header("x-name")`.
603
230
 
604
- ### Email
231
+ ## HTTP client
605
232
 
606
233
  ```plainscript
607
- mail transport
608
- host is "smtp.gmail.com"
609
- port is 587
610
- user is env("EMAIL_USER")
611
- pass is env("EMAIL_PASS")
612
- done
613
-
614
- send mail
615
- from is "hello@plainscript.dev"
616
- to is "you@example.com"
617
- subject is "Hello from PlainScript"
618
- text is "Sent from a PlainScript program."
619
- done
234
+ remember response as get "https://example.com/data" timeout 5000
235
+ remember created as post "https://example.com/data" with {name: "Ada"} headers {contentType: "application/json"}
236
+ show response.status
620
237
  ```
621
238
 
622
- ### Cron and background jobs
239
+ ## SQLite
623
240
 
624
241
  ```plainscript
625
- every 5 minutes
626
- show "heartbeat"
627
- done
242
+ database "app.db" using "wasm"
243
+ remember name as "Ada"
628
244
 
629
- schedule "0 2 * * *"
630
- show "nightly cleanup"
245
+ execute
246
+ CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER)
631
247
  done
632
248
 
633
- to resize name
634
- show `resizing ${name}`
249
+ insert
250
+ INSERT INTO people (name, age) VALUES ({name}, 36)
635
251
  done
636
252
 
637
- run background resize("photo.png")
638
- ```
639
-
640
- ### WebSocket servers
641
-
642
- ```plainscript
643
- websocket server on 8080
644
- when socket connects
645
- send socket "Welcome!"
646
- done
647
- when socket sends message
648
- broadcast message
649
- done
253
+ remember people as query
254
+ SELECT name, age FROM people
650
255
  done
651
256
  ```
652
257
 
653
- ### Cache (Redis with in-memory fallback)
654
-
655
- ```plainscript
656
- cache env("REDIS_URL") // omit for an in-memory Map store with TTL
657
- let token be cacheGet("token")
658
- cacheSet("greeting", "hi", 60)
659
- cacheDelete("greeting")
660
- ```
661
-
662
- Without a configured Redis, `cacheGet`/`cacheSet`/`cacheDelete` transparently fall
663
- back to an in-memory store, so naive caching works out of the box.
664
-
665
- ### AI / ML
666
-
667
- ```plainscript
668
- let reply be chat("gpt-4o-mini", list with
669
- record with role "user" and content "Say hello in two words"
670
- done)
671
-
672
- let vec be embedText("text-embedding-3-small", "PlainScript rocks")
673
- let score be similarity(vec, embedText("text-embedding-3-small", "I love PlainScript"))
674
-
675
- let tags be ai_tags("PlainScript is an intent-oriented language")
676
- let article be ai_post("Welcome to PlainScript", list with "why IOPL", "quick start")
677
- ```
678
-
679
- `chat` and `embedText` are async OpenAI-compatible calls (from `OPENAI_API_KEY`,
680
- override with `options.apiKey`/`options.baseURL`); `similarity` returns -1..1.
258
+ Use `using "native"` for a Node.js SQLite backend, or `using "wasm"` for in-memory. SQL placeholders like `{name}` bind to PlainScript variables.
681
259
 
682
- ### Pagination
260
+ ## Errors, async, and concurrency
683
261
 
684
262
  ```plainscript
685
- let page be paginate(allUsers, 2, 10)
686
- show page.items # second page of 10
687
- show page.hasNext # true if another page exists
688
- ```
689
-
690
- `paginate(list, page, perPage)` returns
691
- `record with items, count, page, pages, perPage, hasNext, hasPrev done`.
692
-
693
- ---
694
-
695
- ## Multi-file projects
696
-
697
- ```plainscript
698
- import "./math.pln"
699
- import "./utils.pln"
700
-
701
- show PI
702
-
703
- show double(5)
704
- ```
705
-
706
- Imports are bundled per entry: `plainscript build` gives every source file its own
707
- standalone output under `dist/`, with imported code inlined.
708
-
709
- ---
710
-
711
- ## Express server
712
-
713
- ```plainscript
714
- use express
715
-
716
- let app be express()
717
-
718
- serve folder "public"
719
-
720
- when someone visits "/"
721
- show "Hello from PlainScript!"
722
- done
723
-
724
- when someone visits "/api/status"
725
- show json
726
- status is "ok"
727
- version is "0.3"
728
- done
729
- done
263
+ try
264
+ remember result as get "https://example.com" timeout 5000
265
+ recover as error
266
+ show message of error
267
+ finally
268
+ show "finished"
730
269
 
731
- listen on 3000
732
- show "Server running at http://localhost:3000"
270
+ retry 3 times every 1 second
271
+ show "attempt"
733
272
  done
734
273
  ```
735
274
 
736
- ---
737
-
738
- ## WhatsApp Bots
275
+ Run promises in parallel with `allOf()`, `anyOf()`, and `settledOf()`. Schedule recurring work with `every 5 minutes ... done`.
739
276
 
740
- Full WhatsApp connectivity through Baileys — the implementation package is
741
- installed automatically and never appears in your source:
277
+ ## Testing
742
278
 
743
279
  ```plainscript
744
- whatsapp bot
745
- auth "session" // credential folder, persists
746
- // across restarts
747
- login qr // or: login pairing "2348012345678"
748
-
749
- on message
750
- log message // print the normalized record
751
-
752
- when message.text is "/start"
753
- show "Welcome!"
754
- done
755
-
756
- when message.text is "/help"
757
- show `Available commands:
758
- /start /help`
759
- done
760
- done
761
- done
762
- ```
763
-
764
- - `login qr` prints a scannable QR code; `login pairing "<number>"` prints an
765
- enter-on-phone code instead. Pairing numbers are validated at compile time
766
- (digits only after normalization, 8–15).
767
- - `login pairing` also accepts any value — prompt for the number
768
- at runtime instead of hard-coding it:
769
-
770
- ```plainscript
771
- ask "WhatsApp number: " as phone
772
-
773
- whatsapp bot
774
- auth "session"
775
- login pairing phone
280
+ test "addition works"
281
+ check add(2, 3) equals 5
776
282
  done
777
283
  ```
778
284
 
779
- - Inside `on message`, `message` holds `record with text, chat, sender, name, id,
780
- time, isGroup done`; `print` answers the current chat.
781
- - The bot ignores its own messages and status broadcasts and keeps working in
782
- groups; transient disconnects reconnect after 3 seconds.
285
+ Assertions: `equals`, `is`, `contains`, and `raises`.
783
286
 
784
- See `examples/whatsapp-bot/` for ready-to-link programs.
287
+ ## Examples
785
288
 
786
- ---
787
-
788
- ## Project management
789
-
790
- ```bash
791
- plainscript install # Install all detected dependencies
792
- plainscript add express # Add a package
793
- plainscript remove express # Remove a package
794
- plainscript update # Update all packages
795
- plainscript start # Build src/app.pln and run its dist/ output
796
- plainscript doctor # Check project environment
797
- ```
798
-
799
- ---
800
-
801
- ## Supported packages
802
-
803
- | PlainScript | Compiles to |
804
- |---------------------------|--------------------------------------|
805
- | `use express` | `const express = require('express');` |
806
- | `use sqlite` | `const Database = require('better-sqlite3');` |
807
- | `use fs` | `const fs = require('fs');` |
808
- | `use path` | `const path = require('path');` |
809
-
810
- Any npm package can be used, including hyphenated names like `node-fetch` and
811
- scoped packages like `@scope/package-name`.
812
-
813
- ---
814
-
815
- ## Running the tests
816
-
817
- ```bash
818
- npm test
819
- ```
289
+ The `examples/` folder has working code for every feature:
820
290
 
821
- ---
291
+ | Topic | Files |
292
+ | --- | --- |
293
+ | Basics | `examples/basics.pln`, `examples/conditions.pln` |
294
+ | Loops, functions, records | `examples/loops.pln`, `examples/functions.pln`, `examples/records.pln` |
295
+ | Natural string verbs | `examples/string-verbs.pln` |
296
+ | JSON, files, HTTP | `examples/json.pln`, `examples/files.pln`, `examples/http.pln` |
297
+ | Database, web routes | `examples/sqlite.pln`, `examples/web-api.pln` |
298
+ | Auth and sessions | `examples/auth-sessions.pln` |
299
+ | Async and errors | `examples/async-errors.pln`, `examples/concurrency.pln` |
300
+ | WebSockets, cache | `examples/websocket.pln`, `examples/cache-schedule.pln` |
301
+ | Bots | `examples/bots.pln`, `examples/telegram-bot.pln`, `examples/whatsapp-bot/` |
302
+ | OCR, uploads | `examples/ocr.pln`, `examples/id-verification/` |
303
+ | Tests, modules | `examples/testing.pln`, `examples/modules/` |
304
+ | Starter projects | `templates/` |
822
305
 
823
306
  ## Project structure
824
307
 
308
+ ```text
309
+ compiler/ compiler, parser, and CLI
310
+ examples/ feature demos and examples
311
+ tests/ test suite
312
+ docs/ website and docs
313
+ plainscript-vscode/ VS Code extension
314
+ editors/mt-manager/ TextMate grammar
825
315
  ```
826
- plainscript/
827
- ├── compiler/
828
- │ ├── lexer.js — tokenises PlainScript source into tokens
829
- │ ├── parser.js — builds an AST from tokens
830
- │ ├── generator.js — generates JavaScript from the AST
831
- │ ├── bundler.js — resolves imports and bundles files
832
- │ ├── formatter.js — normalises PlainScript source style
833
- │ ├── dependency-detector.js— detects npm packages from source
834
- │ ├── version.js — single compiler version constant
835
- │ └── cli.js — command-line entry point
836
- │
837
- ├── examples/
838
- │ ├── hello.pln
839
- │ ├── day2.pln
840
- │ ├── day3.pln
841
- │ ├── arrays.pln
842
- │ ├── objects.pln
843
- │ ├── loops.pln
844
- │ ├── expressions.pln
845
- │ ├── stdlib.pln
846
- │ ├── server.pln
847
- │ ├── web-app.pln
848
- │ ├── start.pln
849
- │ ├── database.pln
850
- │ ├── deployment.pln
851
- │ ├── football-backend/ — acceptance example (SQLite + auth + sessions)
852
- │ │ └── app.pln
853
- │ ├── id-verification/ — acceptance example (uploads + OCR matching)
854
- │ │ ├── app.pln
855
- │ │ └── make-sample-id.js
856
- │ └── whatsapp-bot/ — WhatsApp bots (QR and pairing linking)
857
- │ ├── qr.pln
858
- │ └── pairing.pln
859
- │
860
- ├── tests/
861
- │ ├── compiler.test.js — language, CLI and formatter coverage
862
- │ ├── build.test.js — build model, config and packaging coverage
863
- │ ├── backend.test.js — web/database/email/cache runtime tests
864
- │ ├── telegram.test.js — Telegram bot runtime tests
865
- │ ├── ocr.test.js — OCR statement tests
866
- │ ├── runtime.test.js — uploads, database and bot feature suite
867
- │ ├── whatsapp.test.js — WhatsApp bot runtime tests
868
- │ └── acceptance.test.js — boots the example projects over live HTTP
869
- │
870
- ├── docs/
871
- │ ├── PLAINSCRIPT-SPEC.md
872
- │ └── index.html
873
- │
874
- ├── editors/
875
- │ └── mt-manager/
876
- │ └── plainscript.mtsx — MT Manager syntax highlighting
877
- │
878
- ├── package.json
879
- └── README.md
880
- ```