plainscript-lang 1.0.1 → 1.0.2-latest

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