@tilua-types/sunc 11.1.5 → 11.2.1

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.
package/README.md CHANGED
@@ -1,129 +1,257 @@
1
- # @tilua-types/sunc
2
-
3
- The script-executor environment as tilua types — what an executor injects
4
- into a script: `getgenv`, `writefile`, `hookfunction`, `getconnections`,
5
- `Drawing`, `request` and the rest, each in a namespace by what it does.
6
-
7
- Names and shapes follow [sUNC](https://docs.sunc.io) (senS' Unified Naming
8
- Convention) and the [UNC standard](https://github.com/unified-naming-convention/NamingStandard)
9
- it grew out of. Where the two disagree, sUNC's shape is the one written down;
10
- where only UNC has a name (`crypt`, `rconsole`, mouse input), it is kept,
11
- since executors still expose it.
12
-
13
- Depends on [`@tilua-types/roblox`](../roblox), which is loaded along with it:
14
- nearly every one of these takes or returns an engine type.
15
-
16
- ```bash
17
- npm i -D @tilua-types/sunc
18
- ```
19
-
20
- ```json
21
- { "types": ["sunc"], "paths": {}, "sourceMap": null }
22
- ```
23
-
24
- ## Namespaces
25
-
26
- No function is a global of its own. Each is in a namespace, a name the
27
- namespace already says is not said again, and every name is lowercase, as
28
- sUNC's are:
29
-
30
- ```luau
31
- const genv = env.getgenv()
32
- fs.write("log.txt", fs.read("in.txt"))
33
- const original = closure.hook(target, (...args) => print("called"))
34
- http.request({ Url: url })
35
- ```
36
-
37
- The namespaces are not the executor's — no executor has `fs` or `closure`.
38
- The compiler reads each from the library's runtime, which builds it as the
39
- script starts from whatever the executor has, under whichever spelling it
40
- has. A function the executor has under none of them is `nil`, so every
41
- member is optional and a script says what it needs before it calls it:
42
-
43
- ```luau
44
- if (fs.write) fs.write("log.txt", text)
45
- const hui = instance.gethui
46
- const parent = hui ? hui() : game:GetService("CoreGui")
47
- ```
48
-
49
- | Namespace | Functions (what the executor calls them) |
50
- | --- | --- |
51
- | `env` | `getgenv`, `getrenv`, `getreg`, `getgc`, `filtergc` |
52
- | `closure` | `hook` (`hookfunction`, `replaceclosure`), `restore` (`restorefunction`), `clone` (`clonefunction`), `newcclosure`, `iscclosure`, `islclosure`, `isexecutorclosure` (`isourclosure`, `checkclosure`), `checkcaller`, `hash` (`getfunctionhash`), `bytecode` (`getfunctionbytecode`) |
53
- | `metatable` | `getraw` / `setraw` (`getrawmetatable` / `setrawmetatable`), `isreadonly`, `setreadonly`, `hook` (`hookmetamethod`), `getnamecallmethod` |
54
- | `scripts` | `calling` (`getcallingscript`), `all` (`getscripts`), `running` (`getrunningscripts`), `loadedmodules`, `fromthread` (`getscriptfromthread`), `env` (`getsenv`), `bytecode` (`getscriptbytecode`, `dumpstring`), `closure` (`getscriptclosure`, `getscriptfunction`), `hash` (`getscripthash`), `decompile` |
55
- | `identity` | `get` / `set` (`getthreadidentity`, `getidentity`, `getthreadcontext`, and the setters) |
56
- | `instance` | `cloneref`, `compare` (`compareinstances`), `all` (`getinstances`), `nilparented` (`getnilinstances`), `gethui`, `gethidden` / `sethidden` (`gethiddenproperty` / `sethiddenproperty`), `isscriptable`, `setscriptable`, `getcallback` (`getcallbackvalue`), `fireclickdetector`, `fireproximityprompt`, `firetouch` (`firetouchinterest`), `getobjects`, `isnetworkowner`, `save` (`saveinstance`) |
57
- | `cache` | `invalidate`, `replace`, `iscached` |
58
- | `signal` | `connections` (`getconnections`), `fire` (`firesignal`), `replicate` (`replicatesignal`) |
59
- | `fs` | `read`, `write`, `append`, `delete` (`delfile`), `isfile`, `list` (`listfiles`), `makefolder`, `deletefolder` (`delfolder`), `isfolder`, `dofile`, `loadfile`, `getcustomasset` |
60
- | `http` | `request` (`request`, `http_request`, `http.request`, `syn.request`, `fluxus.request`) |
61
- | `websocket` | `connect` (`WebSocket.connect`) |
62
- | `encoding` | `base64encode` / `base64decode` (also `crypt.base64encode`, `crypt.base64_encode`, `crypt.base64.encode`, `base64.encode`), `lz4compress`, `lz4decompress` |
63
- | `crypt` | `encrypt`, `decrypt`, `hash`, `generatebytes`, `generatekey` |
64
- | `drawing` | `new` (`Drawing.new`), `fonts` (`Drawing.Fonts`), `clear` (`cleardrawcache`), `getproperty` / `setproperty` (`getrenderproperty` / `setrenderproperty`), `isdrawing` (`isrenderobj`) |
65
- | `rconsole` | `create`, `destroy`, `clear`, `print`, `settitle`, `input` (`rconsole…`, `console…`, `rconsolename`) |
66
- | `input` | `isactive` (`isrbxactive`, `isgameactive`), `mouse1click` … `mousescroll`, `keypress`, `keyrelease`, `keyclick` |
67
- | `executor` | `identify` (`identifyexecutor`, `getexecutorname`), `hwid` (`gethwid`), `setfpscap`, `getfpscap`, `messagebox` |
68
- | `clipboard` | `set` (`setclipboard`, `toclipboard`), `setrbx` (`setrbxclipboard`) |
69
- | `teleport` | `queue` (`queue_on_teleport`, `queueonteleport`, `queueteleport`, `syn.queue_on_teleport`) |
70
- | `actor` | `all` (`getactors`), `run` (`run_on_actor`), `isparallel` |
71
-
72
- The executor's own globals are out of a script's reach: `readfile` or
73
- `getrawmetatable` written in a script is reported, and is `nil` there, as if
74
- the script began with `local readfile = nil`. The executor's environment is
75
- not touched — other scripts share it — so `env.getgenv().readfile` is still
76
- there for whoever means it.
77
-
78
- `debug` is the one exception: it is Lua's own global already, and the
79
- library adds `getconstants`, `getupvalues`, `getprotos` and the rest to it.
80
-
81
- ## What you get
82
-
83
- - **Typed.** `fs.read` gives a `string`, `fs.list` a `string[]`,
84
- `env.getgenv()` a `{ [string]: unknown }` you can write to.
85
- - **`drawing.new` knows its shapes.** The argument picks the type:
86
- `drawing.new("Circle").Radius` is a number, `drawing.new("Line").From` is a
87
- `Vector2`, and asking a line for its radius is an error.
88
- - **Hooks keep the type they replace.** `closure.hook(f, hook)` returns `f`'s
89
- own type, so the saved original is still called the way `f` was.
90
- - **One value.** What Luau answers as several values is one array:
91
- `const [name, version] = executor.identify()`.
92
- - **Signals.** `signal.connections(part.Touched)` gives `Connection[]`, each
93
- with `Function`, `Thread`, `Fire`, `Disconnect` and the rest.
94
- - **Bodies Luau cannot write.** A Luau table has no key whose value is nil.
95
- Given a function, `http.request` hands it placeholders for one, and writes
96
- them out as the request goes:
97
-
98
- ```luau
99
- http.request(types => ({
100
- Url: url,
101
- Method: "POST",
102
- -- {"meta":{},"name":"x","tags":[],"team":null}
103
- Body: { name: "x", team: types.null, gone: types.undefined, tags: [], meta: {} },
104
- }))
105
- ```
106
-
107
- `types.null` is JSON's `null`; `types.undefined` is left out of an object
108
- and `null` in an array, as JavaScript's. A `Body` that is a table is sent
109
- as JSON — `[]` an array and `{}` an object, as `HttpService:JSONEncode`
110
- writes them under tilua — with `Content-Type: application/json` unless the
111
- headers name one; a string is sent as it is.
112
-
113
- ## Caveats
114
-
115
- No executor implements all of this, and several names mean slightly different
116
- things between them — the types say what the standard says, not what any one
117
- executor does. Nothing here exists in a normal Roblox game: a script using
118
- these runs only under an executor.
119
-
120
- <!-- compatibility:start -->
121
- ## Compatibility
122
-
123
- `@tilua-types/sunc@11.1.5` works with these tilua packages. *Released with* is the
124
- version it was built and tested against.
125
-
126
- | Package | Range | Released with | |
127
- | --- | --- | --- | --- |
128
- | `@tilua-types/roblox` | `^11.0.0` | 11.0.0 | dependency |
129
- <!-- compatibility:end -->
1
+ # @tilua-types/sunc
2
+
3
+ The script-executor environment as tilua types — what an executor injects
4
+ into a script: `getgenv`, `writefile`, `hookfunction`, `getconnections`,
5
+ `Drawing`, `request` and the rest, each in a namespace by what it does.
6
+
7
+ Names and shapes follow [sUNC](https://docs.sunc.io) (senS' Unified Naming
8
+ Convention) and the [UNC standard](https://github.com/unified-naming-convention/NamingStandard)
9
+ it grew out of. Where the two disagree, sUNC's shape is the one written down;
10
+ where only UNC has a name (`crypt`, `rconsole`, mouse input), it is kept,
11
+ since executors still expose it.
12
+
13
+ Depends on [`@tilua-types/roblox`](../roblox), which is loaded along with it:
14
+ nearly every one of these takes or returns an engine type. The runtime also
15
+ carries [`@tilua-types/crypto`](../crypto)'s, for the HMACs and AES-GCM of
16
+ [what the project keeps](#what-the-project-keeps).
17
+
18
+ ```bash
19
+ npm i -D @tilua-types/sunc
20
+ ```
21
+
22
+ ```json
23
+ { "types": ["sunc"], "paths": {}, "sourceMap": null }
24
+ ```
25
+
26
+ ## Namespaces
27
+
28
+ No function is a global of its own. Each is in a namespace, a name the
29
+ namespace already says is not said again, and every name is lowercase, as
30
+ sUNC's are:
31
+
32
+ ```luau
33
+ const genv = env.getgenv()
34
+ fs.write("log.txt", fs.read("in.txt"))
35
+ const original = closure.hook(target, (...args) => print("called"))
36
+ http.request({ Url: url })
37
+ ```
38
+
39
+ The namespaces are not the executor's — no executor has `fs` or `closure`.
40
+ The compiler reads each from the library's runtime, which builds it as the
41
+ script starts from whatever the executor has, under whichever spelling it
42
+ has. A function the executor has under none of them is `nil`, so every
43
+ member is optional and a script says what it needs before it calls it:
44
+
45
+ ```luau
46
+ if (fs.write) fs.write("log.txt", text)
47
+ const hui = instance.gethui
48
+ const parent = hui ? hui() : game:GetService("CoreGui")
49
+ ```
50
+
51
+ | Namespace | Functions (what the executor calls them) |
52
+ | --- | --- |
53
+ | `env` | `getgenv`, `getrenv`, `getreg`, `getgc`, `filtergc`; `getmain` (the library's own) |
54
+ | `closure` | `hook` (`hookfunction`, `replaceclosure`), `restore` (`restorefunction`), `clone` (`clonefunction`), `newcclosure`, `iscclosure`, `islclosure`, `isexecutorclosure` (`isourclosure`, `checkclosure`), `checkcaller`, `hash` (`getfunctionhash`), `bytecode` (`getfunctionbytecode`) |
55
+ | `metatable` | `getraw` / `setraw` (`getrawmetatable` / `setrawmetatable`), `isreadonly`, `setreadonly`, `hook` (`hookmetamethod`), `getnamecallmethod` |
56
+ | `scripts` | `calling` (`getcallingscript`), `all` (`getscripts`), `running` (`getrunningscripts`), `loadedmodules`, `fromthread` (`getscriptfromthread`), `env` (`getsenv`), `bytecode` (`getscriptbytecode`, `dumpstring`), `closure` (`getscriptclosure`, `getscriptfunction`), `hash` (`getscripthash`), `decompile` |
57
+ | `identity` | `get` / `set` (`getthreadidentity`, `getidentity`, `getthreadcontext`, and the setters) |
58
+ | `instance` | `cloneref`, `compare` (`compareinstances`), `all` (`getinstances`), `nilparented` (`getnilinstances`), `gethui`, `gethidden` / `sethidden` (`gethiddenproperty` / `sethiddenproperty`), `isscriptable`, `setscriptable`, `getcallback` (`getcallbackvalue`), `fireclickdetector`, `fireproximityprompt`, `firetouch` (`firetouchinterest`), `getobjects`, `isnetworkowner`, `save` (`saveinstance`) |
59
+ | `cache` | `invalidate`, `replace`, `iscached` |
60
+ | `signal` | `connections` (`getconnections`), `fire` (`firesignal`), `replicate` (`replicatesignal`) |
61
+ | `fs` | `read`, `write`, `append`, `delete` (`delfile`), `isfile`, `list` (`listfiles`), `makefolder`, `deletefolder` (`delfolder`), `isfolder`, `dofile`, `loadfile`, `getcustomasset` |
62
+ | `http` | `request` (`request`, `http_request`, `http.request`, `syn.request`, `fluxus.request`); `to`, `clearcache` (the library's own) |
63
+ | `websocket` | `connect` (`WebSocket.connect`) |
64
+ | `encoding` | `base64encode` / `base64decode` (also `crypt.base64encode`, `crypt.base64_encode`, `crypt.base64.encode`, `base64.encode`), `lz4compress`, `lz4decompress` |
65
+ | `crypt` | `encrypt`, `decrypt`, `hash`, `generatebytes`, `generatekey` |
66
+ | `drawing` | `new` (`Drawing.new`), `fonts` (`Drawing.Fonts`), `clear` (`cleardrawcache`), `getproperty` / `setproperty` (`getrenderproperty` / `setrenderproperty`), `isdrawing` (`isrenderobj`) |
67
+ | `rconsole` | `create`, `destroy`, `clear`, `print`, `settitle`, `input` (`rconsole…`, `console…`, `rconsolename`) |
68
+ | `input` | `isactive` (`isrbxactive`, `isgameactive`), `mouse1click` … `mousescroll`, `keypress`, `keyrelease`, `keyclick` |
69
+ | `executor` | `identify` (`identifyexecutor`, `getexecutorname`), `hwid` (`gethwid`), `setfpscap`, `getfpscap`, `messagebox`; `fingerprint` (the library's own) |
70
+ | `clipboard` | `set` (`setclipboard`, `toclipboard`), `setrbx` (`setrbxclipboard`) |
71
+ | `teleport` | `queue` (`queue_on_teleport`, `queueonteleport`, `queueteleport`, `syn.queue_on_teleport`) |
72
+ | `actor` | `all` (`getactors`), `run` (`run_on_actor`), `isparallel` |
73
+
74
+ The executor's own globals are out of a script's reach: `readfile` or
75
+ `getrawmetatable` written in a script is reported, and is `nil` there, as if
76
+ the script began with `local readfile = nil`. The executor's environment is
77
+ not touched — other scripts share it — so `env.getgenv().readfile` is still
78
+ there for whoever means it.
79
+
80
+ `debug` is the one exception: it is Lua's own global already, and the
81
+ library adds `getconstants`, `getupvalues`, `getprotos` and the rest to it.
82
+
83
+ ## What you get
84
+
85
+ - **Typed.** `fs.read` gives a `string`, `fs.list` a `string[]`,
86
+ `env.getgenv()` a `{ [string]: unknown }` you can write to.
87
+ - **`drawing.new` knows its shapes.** The argument picks the type:
88
+ `drawing.new("Circle").Radius` is a number, `drawing.new("Line").From` is a
89
+ `Vector2`, and asking a line for its radius is an error.
90
+ - **Hooks keep the type they replace.** `closure.hook(f, hook)` returns `f`'s
91
+ own type, so the saved original is still called the way `f` was.
92
+ - **One value.** What Luau answers as several values is one array:
93
+ `const [name, version] = executor.identify()`.
94
+ - **Signals.** `signal.connections(part.Touched)` gives `Connection[]`, each
95
+ with `Function`, `Thread`, `Fire`, `Disconnect` and the rest.
96
+ - **Bodies Luau cannot write.** A Luau table has no key whose value is nil.
97
+ Given a function, `http.request` hands it placeholders for one, and writes
98
+ them out as the request goes:
99
+
100
+ ```luau
101
+ http.request(types => ({
102
+ Url: url,
103
+ Method: "POST",
104
+ -- {"meta":{},"name":"x","tags":[],"team":null}
105
+ Body: { name: "x", team: types.null, gone: types.undefined, tags: [], meta: {} },
106
+ }))
107
+ ```
108
+
109
+ `types.null` is JSON's `null`; `types.undefined` is left out of an object
110
+ and `null` in an array, as JavaScript's. A `Body` that is a table is sent
111
+ as JSON — `[]` an array and `{}` an object, as `HttpService:JSONEncode`
112
+ writes them under tilua — with `Content-Type: application/json` unless the
113
+ headers name one; a string is sent as it is.
114
+
115
+ ## What the project keeps
116
+
117
+ `env.getmain()` is a table every script of the project shares, for whatever
118
+ they keep between runs — the executor's `getgenv()` is shared by everything
119
+ it runs, and this is the part of it that is the project's:
120
+
121
+ ```luau
122
+ const main = env.getmain()
123
+ main.runs = ((main.runs as number | nil) ?? 0) + 1
124
+ ```
125
+
126
+ It is kept in the first of `getgenv()`, `shared` and `_G` there is, under a
127
+ name of 24 hex digits: the HMAC of `executor.fingerprint()` under the
128
+ project's secret. Another script sees one more random-looking key, and only
129
+ the project's own scripts, on this machine, know which it is — as the bridge
130
+ names its remotes.
131
+
132
+ `executor.fingerprint(salt?)` is that machine hash, for a script's own use,
133
+ made the way [FingerprintJS](https://github.com/fingerprintjs/fingerprintjs)
134
+ makes a browser's: many components, each read the same way on every run, put
135
+ together and hashed (an HMAC, in hex; another `salt`, another hash).
136
+ `executor.components()` answers them by name, each one the executor could
137
+ read:
138
+
139
+ | Component | What it is |
140
+ | --- | --- |
141
+ | `hwid` | the executor's `gethwid` |
142
+ | `clientid` | Roblox's id for the client install (`RbxAnalyticsService:GetClientId`) |
143
+ | `executor` | the executor's name |
144
+ | `capabilities` | which of this library's functions the executor has |
145
+ | `genv` | how many of the names sUNC and UNC define (`hookfunction`, `getrawmetatable`, `readfile`, ...) are a function in `getgenv()`; nothing else a script put there counts |
146
+ | `math` | what the CPU and C library make of awkward floating-point arguments, as FingerprintJS's `math` |
147
+ | `quirks` | what the executor's own functions answer for a fixed input — its base64 of edge bytes, its LZ4, its SHA-256 — where executors differ |
148
+ | `locale` | the system's locale (`LocalizationService.SystemLocaleId`) |
149
+ | `timezone` | the offset from UTC in January and in July: the timezone and its daylight saving, the same all year |
150
+ | `platform` | touch, keyboard, mouse, the platform, a ten-foot interface |
151
+
152
+ What answers differently from run to run is left out, as FingerprintJS
153
+ leaves it out, since what is kept under the fingerprint would be lost with
154
+ it: a benchmark of the CPU (timing is never the same twice), the window's
155
+ size and the client's settings, and versions — Roblox's and the executor's
156
+ change every week. `capabilities`, `genv` and `quirks` do change when the
157
+ executor adds functions or changes how one answers; what was kept is lost
158
+ then, as a browser's fingerprint changes when the browser does.
159
+
160
+ ### The secret
161
+
162
+ The compiler writes the project's secret into the runtime. It is the
163
+ config's `suncSecret` when that is set; otherwise one is made the first time
164
+ the project is built and kept in `.tilua/sunc.secret`, beside the
165
+ `tilua.config.json` at or above the folder the compiler runs in, so every
166
+ build shares what the last one kept. Delete it and what was kept is lost:
167
+ the names and the disk cache's key change with it. Outside a project (no
168
+ config above) it is new each build.
169
+
170
+ ```json
171
+ { "types": ["sunc"], "suncSecret": "..." }
172
+ ```
173
+
174
+ The secret is in the script it is built into, as the bridge's is: what keeps
175
+ it from another script is that the other script does not have this one's
176
+ source.
177
+
178
+ ## `http.to`: a request builder, cached as a browser caches
179
+
180
+ ```luau
181
+ const to = http.to
182
+ if (not to) error("this executor cannot send requests")
183
+ const api = to("https://api.example.com"):header("Authorization", token)
184
+
185
+ const users = api:path("/users"):query({ page: 1 }):get()
186
+ if (users.ok) print(users:json(), users.fromCache)
187
+
188
+ const made = api:path("/users"):json(types => ({ name: "x", team: types.null })):post()
189
+ ```
190
+
191
+ Every method answers a new builder and leaves the one it was called on as
192
+ it was, so `api` above can be kept and built on. `path`, `query` (one name
193
+ and value, or a table, put in the order of its names), `header` (nil takes
194
+ one away; set again in another case, it is one header), `headers`, `cookie`,
195
+ `method`, `body(text, contentType?)`, `json(value)` (or `json(types => ...)`,
196
+ with `http.request`'s placeholders), `cache(mode)`, and `build()`, the
197
+ request as the executor's `request` takes it. `send()` sends it with its
198
+ method, and `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` and
199
+ `options()` with theirs. The answer has `status`, `statusText`, `ok`,
200
+ `headers` (by name in lower case), `body`, `url`, `fromCache` and `json()`.
201
+
202
+ ### The cache
203
+
204
+ A GET is cached the way a browser's own cache does (RFC 9111):
205
+
206
+ - **How long:** the response's `Cache-Control: max-age`, else `Expires`
207
+ against `Date`, else a tenth of the time since `Last-Modified` (a day at
208
+ most). `Age` and the time the request took count against it.
209
+ - **Not kept:** `no-store` (the response's or the request's), `Vary: *`, a
210
+ status a browser would not keep, and an answer neither fresh for any time
211
+ nor able to be revalidated.
212
+ - **Revalidated:** once stale, or always with `no-cache`, a response with an
213
+ `ETag` or `Last-Modified` is asked again with `If-None-Match` /
214
+ `If-Modified-Since`; a 304 answers from what was kept and refreshes it.
215
+ `must-revalidate` forbids the request's `max-stale`.
216
+ - **The request's own** `Cache-Control` — `no-store`, `no-cache`,
217
+ `max-age`, `max-stale`, `min-fresh`, `only-if-cached` — and
218
+ `Pragma: no-cache` are honoured.
219
+ - **`Vary`:** an entry answers only a request with the same values of the
220
+ headers it names, and of `Authorization` always, so one URL asked with two
221
+ tokens is two answers.
222
+ - **Writes forget:** a POST, PUT, PATCH or DELETE that succeeds forgets what
223
+ was kept for its URL.
224
+
225
+ `:cache(mode)` takes fetch's modes: `"default"`, `"no-store"`, `"reload"`
226
+ (always asked, and kept), `"no-cache"` (always revalidated),
227
+ `"force-cache"` (what is kept, stale or not) and `"only-if-cached"` (never
228
+ asked; a 504 when nothing is kept). `http.clearcache()` forgets everything.
229
+
230
+ What is kept is in memory, beside `env.getmain()` — so every script of the
231
+ project shares it, the least recently used of more than 128 going — and on
232
+ disk when the executor has `readfile`, `writefile`, `isfile`, `isfolder`,
233
+ `makefolder` and `delfile`. On disk each URL is one file in one folder, both
234
+ named by HMACs of the secret and the machine, and each sealed with AES-GCM
235
+ under a key from the same, bound to its file name: another script sees
236
+ random names and cannot read them, and a file copied to another machine
237
+ does not open. Sealing is @tilua-types/crypto's, in Luau: about 0.1 s for a
238
+ 100 KB body, paid on each store and on the first read after a restart.
239
+
240
+ ## Caveats
241
+
242
+ No executor implements all of this, and several names mean slightly different
243
+ things between them — the types say what the standard says, not what any one
244
+ executor does. Nothing here exists in a normal Roblox game: a script using
245
+ these runs only under an executor.
246
+
247
+ <!-- compatibility:start -->
248
+ ## Compatibility
249
+
250
+ `@tilua-types/sunc@11.2.1` works with these tilua packages. *Released with* is the
251
+ version it was built and tested against.
252
+
253
+ | Package | Range | Released with | |
254
+ | --- | --- | --- | --- |
255
+ | `@tilua-types/crypto` | `^1.1.3` | 1.1.3 | dependency |
256
+ | `@tilua-types/roblox` | `^12.0.0` | 12.0.0 | dependency |
257
+ <!-- compatibility:end -->
package/index.d.tilua CHANGED
@@ -73,6 +73,13 @@ declare env: {
73
73
  & ((kind: "function", filter: FunctionFilter, returnOne?: false) => AnyFunction[])
74
74
  & ((kind: "table", filter: TableFilter, returnOne: true) => { [unknown]: unknown } | nil)
75
75
  & ((kind: "table", filter: TableFilter, returnOne?: false) => { [unknown]: unknown }[]),
76
+ -- A table of this project's, shared by every script of it the executor
77
+ -- runs, for whatever they keep between them. It is kept in the first of
78
+ -- `getgenv()`, `shared` and `_G` there is, under a name made from the
79
+ -- project's secret and this machine's `executor.fingerprint()`, so no
80
+ -- other script can look it up by name. The library's own, not the
81
+ -- executor's: always there.
82
+ getmain: () => { [string]: unknown },
76
83
  }
77
84
 
78
85
  -- ============================================================
@@ -288,9 +295,11 @@ declare fs: {
288
295
  -- http, websocket
289
296
  -- ============================================================
290
297
 
298
+ type HttpMethod = "GET" | "POST" | "PATCH" | "PUT" | "DELETE" | "HEAD" | "OPTIONS"
299
+
291
300
  type HttpRequest = {
292
301
  Url: string,
293
- Method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" | "HEAD" | "OPTIONS",
302
+ Method?: HttpMethod,
294
303
  Body?: string,
295
304
  Headers?: { [string]: string },
296
305
  Cookies?: { [string]: string },
@@ -322,12 +331,89 @@ type HttpTypes = {
322
331
  -- say otherwise — or a string, sent as it is.
323
332
  type HttpBuiltRequest = {
324
333
  Url: string,
325
- Method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" | "HEAD" | "OPTIONS",
334
+ Method?: HttpMethod,
326
335
  Body?: string | { [string]: unknown } | unknown[],
327
336
  Headers?: { [string]: string },
328
337
  Cookies?: { [string]: string },
329
338
  }
330
339
 
340
+ -- How a builder's GET uses the cache, as fetch's `cache` option:
341
+ --
342
+ -- - `"default"`: what is kept while it is fresh; once stale, asked again
343
+ -- with `If-None-Match` / `If-Modified-Since`, and a 304 answered from
344
+ -- what was kept;
345
+ -- - `"no-store"`: the cache is neither read nor written;
346
+ -- - `"reload"`: always asked anew, and what comes back is kept;
347
+ -- - `"no-cache"`: what is kept is always checked with the server first;
348
+ -- - `"force-cache"`: what is kept, stale or not, and asked only without;
349
+ -- - `"only-if-cached"`: what is kept, stale or not, and never asked: a 504
350
+ -- without.
351
+ type HttpCacheMode = "default" | "no-store" | "reload" | "no-cache" | "force-cache" | "only-if-cached"
352
+
353
+ type HttpQueryValue = string | number | boolean
354
+
355
+ -- What a builder's request answers.
356
+ type HttpResult = {
357
+ -- The URL asked, its query included.
358
+ readonly url: string,
359
+ readonly status: number,
360
+ readonly statusText: string,
361
+ -- A status from 200 to 299.
362
+ readonly ok: boolean,
363
+ -- By name in lower case: `headers["content-type"]`.
364
+ readonly headers: { [string]: string },
365
+ readonly body: string,
366
+ -- Answered from the cache, or by a 304 that said what was kept is still
367
+ -- good.
368
+ readonly fromCache: boolean,
369
+ -- The body read as JSON, `[]` an array and `{}` an object. Errors when it
370
+ -- is not JSON.
371
+ json: (self: HttpResult) => unknown,
372
+ }
373
+
374
+ -- A request being built. Every method answers a new builder and leaves this
375
+ -- one as it was, so a builder with a base URL and headers can be kept and
376
+ -- built on:
377
+ --
378
+ -- const api = http.to("https://api.example.com"):header("Authorization", token)
379
+ -- const users = api:path("/users"):query({ page: 1 }):get()
380
+ -- const made = api:path("/users"):json({ name: "x" }):post()
381
+ type HttpBuilder = {
382
+ -- The URL with `path` added after a `/`: `to("https://a/v1"):path("users")`
383
+ -- asks `https://a/v1/users`.
384
+ path: (self: HttpBuilder, path: string) => HttpBuilder,
385
+ -- Query parameters added, encoded. A table's go in the order of their
386
+ -- names, so the same table is always the same URL, and one cache entry.
387
+ query: ((self: HttpBuilder, name: string, value: HttpQueryValue) => HttpBuilder)
388
+ & ((self: HttpBuilder, params: { [string]: HttpQueryValue }) => HttpBuilder),
389
+ -- A header set, whatever case it was set in before; nil takes it away.
390
+ header: (self: HttpBuilder, name: string, value: string | nil) => HttpBuilder,
391
+ headers: (self: HttpBuilder, headers: { [string]: string }) => HttpBuilder,
392
+ cookie: (self: HttpBuilder, name: string, value: string) => HttpBuilder,
393
+ method: (self: HttpBuilder, method: HttpMethod) => HttpBuilder,
394
+ -- A body sent as it is, and its `Content-Type` when given.
395
+ body: (self: HttpBuilder, body: string, contentType?: string) => HttpBuilder,
396
+ -- A body sent as JSON, with `Content-Type: application/json` unless one
397
+ -- was set. Given a function, it is called with the placeholders
398
+ -- `http.request(types => ...)` has, for a key whose value is nil.
399
+ json: ((self: HttpBuilder, value: { [string]: unknown } | unknown[]) => HttpBuilder)
400
+ & ((self: HttpBuilder, build: (types: HttpTypes) => { [string]: unknown } | unknown[]) => HttpBuilder),
401
+ cache: (self: HttpBuilder, mode: HttpCacheMode) => HttpBuilder,
402
+ -- The request as the executor's `request` takes it, without sending it.
403
+ build: (self: HttpBuilder) => HttpRequest,
404
+ -- Send it, with the method it has (GET unless `method` said otherwise),
405
+ -- or with the one named. Each yields until the response arrives, or the
406
+ -- cache answers.
407
+ send: (self: HttpBuilder) => HttpResult,
408
+ get: (self: HttpBuilder) => HttpResult,
409
+ post: (self: HttpBuilder) => HttpResult,
410
+ put: (self: HttpBuilder) => HttpResult,
411
+ patch: (self: HttpBuilder) => HttpResult,
412
+ delete: (self: HttpBuilder) => HttpResult,
413
+ head: (self: HttpBuilder) => HttpResult,
414
+ options: (self: HttpBuilder) => HttpResult,
415
+ }
416
+
331
417
  declare http: {
332
418
  -- Yields until the response arrives. Given a function, calls it with the
333
419
  -- placeholders and sends the request it builds:
@@ -340,6 +426,17 @@ declare http: {
340
426
  -- (`request`, `http_request`, `http.request`, `syn.request`, `fluxus.request`)
341
427
  request?: ((options: HttpRequest) => HttpResponse)
342
428
  & ((build: (types: HttpTypes) => HttpBuiltRequest) => HttpResponse),
429
+ -- A request builder for `url`, whose GETs are cached as a browser caches
430
+ -- them: by the response's `Cache-Control`, `Expires`, `ETag`,
431
+ -- `Last-Modified` and `Vary`, and the request's own `Cache-Control`.
432
+ -- What is kept is in memory, shared by the project's scripts beside
433
+ -- `env.getmain()`, and on disk when the executor has a filesystem, sealed
434
+ -- with AES-GCM in files only this project on this machine can name or
435
+ -- read. A POST, PUT, PATCH or DELETE that succeeds forgets its URL.
436
+ -- There when `request` is.
437
+ to?: (url: string) => HttpBuilder,
438
+ -- Forget everything the cache has kept, in memory and on disk.
439
+ clearcache: () => void,
343
440
  }
344
441
 
345
442
  type WebSocketConnection = {
@@ -530,6 +627,16 @@ declare executor: {
530
627
  identify?: () => [string, string],
531
628
  -- An id for the machine the executor runs on. (`gethwid`)
532
629
  hwid?: () => string,
630
+ -- A hash, in hex, of what tells this machine and executor from another,
631
+ -- made as FingerprintJS makes a browser's: every one of `components()`
632
+ -- there is, put together. The same on every run; another `salt` gives
633
+ -- another hash of the same. The library's own: always there.
634
+ fingerprint: (salt?: string) => string,
635
+ -- What the fingerprint is made of, by name, each one this executor could
636
+ -- read: `hwid`, `clientid`, `executor`, `capabilities`, `genv`, `math`,
637
+ -- `quirks`, `locale`, `timezone`, `platform`. Only what answers the same
638
+ -- on every run: nothing timed, nothing a player changes, no version.
639
+ components: () => { [string]: string },
533
640
  -- (`setfpscap`, `getfpscap`)
534
641
  setfpscap?: (fps: number) => void,
535
642
  getfpscap?: () => number,
package/lowering.mjs CHANGED
@@ -26,8 +26,25 @@
26
26
  *
27
27
  * `debug` is Lua's own global, which the library only adds to: it is left as
28
28
  * it is.
29
+ *
30
+ * Three things are written into the runtime as it is emitted:
31
+ *
32
+ * - `__SECRET__`, the project's secret, which names what the project keeps
33
+ * in the executor (`env.getmain()`, the HTTP cache, its folder and files)
34
+ * and seals the files. It is the config's `suncSecret` when that is set;
35
+ * otherwise one made once for the project — the folder of the
36
+ * `tilua.config.json` at or above where the compiler runs — and kept in
37
+ * its `.tilua/sunc.secret`, so every build of the project shares what an
38
+ * earlier one kept. Outside a project it is new each process.
39
+ * - `__SUNC_NAMES__`, the executor's globals the runtime reads, as a Luau
40
+ * list: the `genv` component of the fingerprint counts how many of them
41
+ * `getgenv()` has as functions.
42
+ * - `__CRYPTO__`, @tilua-types/crypto's runtime as a function that builds
43
+ * it, for the HMACs and AES-GCM above.
29
44
  */
30
- import { readFileSync } from "node:fs"
45
+ import { randomBytes } from "node:crypto"
46
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
47
+ import { createRequire } from "node:module"
31
48
  import { dirname, join } from "node:path"
32
49
  import { fileURLToPath } from "node:url"
33
50
 
@@ -59,11 +76,56 @@ const EXECUTOR_GLOBALS = (() => {
59
76
  return names
60
77
  })()
61
78
 
79
+ const crypto = readFileSync(createRequire(import.meta.url).resolve("@tilua-types/crypto/runtime/crypto.luau"), "utf8")
80
+
81
+ /** The config's `suncSecret`, as the last site lowered saw it. */
82
+ let configured = ""
83
+
84
+ /** The project the compiler runs in: the nearest folder at or above the
85
+ * working one with a `tilua.config.json`. */
86
+ function projectFolder() {
87
+ for (let folder = process.cwd(); ; folder = dirname(folder)) {
88
+ if (existsSync(join(folder, "tilua.config.json")) || existsSync(join(folder, "tilua.config.jsonc"))) return folder
89
+ if (dirname(folder) === folder) return undefined
90
+ }
91
+ }
92
+
93
+ /** @type {string | undefined} */
94
+ let made
95
+
96
+ function secret() {
97
+ if (configured) return configured
98
+ if (made) return made
99
+ const folder = projectFolder()
100
+ const file = folder && join(folder, ".tilua", "sunc.secret")
101
+ if (file && existsSync(file)) {
102
+ const kept = readFileSync(file, "utf8").trim()
103
+ if (/^[0-9a-f]{64}$/.test(kept)) return (made = kept)
104
+ }
105
+ made = randomBytes(32).toString("hex")
106
+ if (file) {
107
+ mkdirSync(dirname(file), { recursive: true })
108
+ writeFileSync(file, `${made}\n`)
109
+ }
110
+ return made
111
+ }
112
+
113
+ /** The runtime as it is emitted, asked for only by a build that uses it. */
114
+ const runtime = {
115
+ get sunc() {
116
+ return sunc
117
+ .replace("__SECRET__", () => JSON.stringify(secret()))
118
+ .replace("__SUNC_NAMES__", () => `{ ${[...EXECUTOR_GLOBALS].sort().map(name => JSON.stringify(name)).join(", ")} }`)
119
+ .replace("__CRYPTO__", () => `(function()\n${crypto}\nreturn __NAME__\nend)`)
120
+ },
121
+ }
122
+
62
123
  /** @type {LoweringPlugin} */
63
124
  const plugin = {
64
- runtime: { sunc },
125
+ runtime,
65
126
 
66
- globalValue({ name, use }) {
127
+ globalValue({ name, use, options }) {
128
+ if (typeof options.suncSecret === "string") configured = options.suncSecret
67
129
  if (NAMESPACES.has(name)) return `${use("sunc")}.${name}`
68
130
  if (EXECUTOR_GLOBALS.has(name)) return "nil"
69
131
  return undefined