@rbxts/netweave 0.0.0-stage → 0.1.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.
@@ -0,0 +1,503 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class View
6
+
7
+ The two halves of a namespace. `.server` and `.client` expose the *same* declaration through
8
+ different types: the side that may listen has `listen`, the side that may send has `send`, and
9
+ neither has the other.
10
+
11
+ ```lua
12
+ -- server.luau
13
+ combat.server.fireWeapon:listen(function(ctx, shot) end)
14
+ combat.server.playerState:publish(subject, state)
15
+
16
+ -- client.luau
17
+ combat.client.fireWeapon:send(shot)
18
+ combat.client.playerState:listen(function(state) end)
19
+ ```
20
+
21
+ Guarantee G6 — direction is a class, not a string field — is a **compile-time** guarantee
22
+ because of this. `combat.server.fireWeapon:send(...)` is not a runtime check that fires in
23
+ production; it is an analysis error that never ships.
24
+ ]=]
25
+
26
+ --[[
27
+ `DESIGN-API.md` §7 originally assumed this needed a fallback, because mapping each key of a
28
+ declaration to a *different* type is a mapped type and Luau has none. `spike/inference/` and
29
+ then `spike/declare/views.luau` showed a `type function` can both map a table and branch on a
30
+ singleton tag, so no fallback is needed and G6 survives.
31
+
32
+ Three things in here are the result of measurement rather than taste, and each would look
33
+ arbitrary without the note:
34
+
35
+ 1. `types.copy` on the incoming type. Calling one type function from another leaves the
36
+ parameter generic, and `types.intersectionof` on a generic fails to check — the analyser
37
+ reports it inside netweave's own source, where a user cannot act on it.
38
+ 2. The brand is applied only to tables. `number & { tag }` normalises to `never`, which
39
+ satisfies every parameter rather than none (`src/api/Trust.luau`).
40
+ 3. Methods take `self` as `unknown`, so they are called with `:`. The view object cannot
41
+ refer to its own type while it is being built, and `unknown` accepts it without needing to.
42
+ ]]
43
+
44
+ local Channel = require("./Channel")
45
+ local Context = require("./Context")
46
+ local Transport = require("./Transport")
47
+
48
+ local View = {}
49
+
50
+ --[[
51
+ The brand is constructed here and in `src/api/Trust.luau`, because a type function body cannot
52
+ call across modules — it has only the `types` library. The two must agree, and
53
+ `tests/api_ok.luau` asserts they do by assigning one to the other.
54
+ ]]
55
+ --[[
56
+ The same rule as `Trust.luau`'s `branded`, and a copy rather than a call: a type function's body
57
+ cannot reach a value from another module, so `Trust.Trusted` is not callable from in here. The
58
+ two are held together by `tests/api_ok.luau`, which asserts a handler's parameter is assignable
59
+ to `nw.Untrusted<Req?>` — if either copy drifts, that stops compiling.
60
+
61
+ Why it handles a union: `T?` is one, and testing `value:is("table")` alone left an optional
62
+ payload unbranded, so a `signal` handed its handler a value that satisfied a `Trusted<Req?>`
63
+ parameter (M4 report). Each table component is branded and the union rebuilt, which keeps the
64
+ brand across the `if r then` a game has to write anyway.
65
+ ]]
66
+ -- selene: allow(undefined_variable)
67
+ type function brandedAs(payload: type, name: string): type
68
+ local value = types.copy(payload)
69
+
70
+ local function tagged(inner)
71
+ local tag = types.newtable()
72
+ tag:setproperty(types.singleton(name), types.singleton(true))
73
+ return types.intersectionof(inner, tag)
74
+ end
75
+
76
+ if value:is("table") then
77
+ return tagged(value)
78
+ end
79
+
80
+ if value:is("union") then
81
+ local rebuilt = nil
82
+ local marked = false
83
+
84
+ for _, component in value:components() do
85
+ local part = component
86
+
87
+ if component:is("table") then
88
+ part = tagged(component)
89
+ marked = true
90
+ end
91
+
92
+ rebuilt = if rebuilt then types.unionof(rebuilt, part) else part
93
+ end
94
+
95
+ if marked and rebuilt then
96
+ return rebuilt
97
+ end
98
+ end
99
+
100
+ return value
101
+ end
102
+
103
+ -- selene: allow(undefined_variable)
104
+ type function channelView(channel: type, side: type, ctx: type): type
105
+ --[[ Every `Channel` carries all five of these, `nil` where a class has no response or subject,
106
+ so a property that is absent means the field is not a channel. A schema is a table too, and
107
+ it used to get past the shape test and raise `attempt to index nil` on `__class` — the
108
+ analyzer's message, not netweave's, which luau-lsp 1.70 started pointing out by typing the
109
+ reads `type?`. ]]
110
+ local function field(name: string): type
111
+ local value = if channel:is("table") then channel:readproperty(types.singleton(name)) else nil
112
+
113
+ if not value then
114
+ error(
115
+ "a namespace holds channels, and this field is not one. Declare it with nw.command, "
116
+ .. "nw.intent, nw.signal, nw.query, nw.state or nw.event — a schema on its own is "
117
+ .. "not a channel, and neither is a function."
118
+ )
119
+ end
120
+
121
+ return value
122
+ end
123
+
124
+ local class = field("__class"):value()
125
+ local audience = field("__audience"):value()
126
+ local payload = field("__payload")
127
+ local response = field("__response")
128
+ local subject = field("__subject")
129
+
130
+ local view = types.newtable()
131
+ local server = side:value() == "server"
132
+
133
+ --[[
134
+ Every argument to `types.newfunction` is written inline. Hoisting one into a local seals it,
135
+ and a sealed `{ head = ... }` is then compared exactly against `{ head: {type}?, tail: type? }`
136
+ and rejected for having no `tail` — a diagnostic inside netweave's own source, which is the
137
+ one place a user cannot do anything about (`PLAN-M1` D-7).
138
+ ]]
139
+ local function returns(parameters)
140
+ return types.newfunction({ head = parameters }, { head = {} })
141
+ end
142
+
143
+ --[[
144
+ The context, handed in rather than built here.
145
+
146
+ It was `types.unknown`, and that made `ctx` **unreadable**: a handler could not annotate it —
147
+ `Ctx` is not a supertype of `unknown`, so `function(ctx: nw.Ctx, shot)` was rejected — and it
148
+ could not read through it either. Every handler in the suite was written `function(_ctx, ...)`
149
+ and nobody noticed, because none of them wanted the context. Writing the worked example was
150
+ what noticed: `ctx.player` is the first thing a real handler reaches for.
151
+
152
+ ~~The three Roblox-typed fields stay `unknown`, because a type function body has no way to
153
+ reach `Player`, `Model` or `Humanoid`.~~ **It has one: they can be handed in.** A type
154
+ function's *arguments* are types, so `Views<D>` instantiates the two mappers with
155
+ `Context.Ctx` and the shape arrives with its real classes — the same route `nw.policy`'s own
156
+ signature already took to get `{ player: Player, character: Model? }` into `Channel`'s type
157
+ functions. So `ctx.player.UserId` type-checks in a handler, `ctx.playr` is a typo the analyser
158
+ catches, and the casts the worked example used are gone (`PLAN-M5` phase 1).
159
+
160
+ The cast to `type` is for the analyser reading *this* file: a type function's parameters are
161
+ `unknown` to it, and `types.newfunction` takes a `type`.
162
+ ]]
163
+ local function context(): type
164
+ return ctx :: type
165
+ end
166
+
167
+ local function listener(seen, withContext)
168
+ local handler = if withContext
169
+ then types.newfunction({ head = { context(), seen } }, { head = {} })
170
+ else types.newfunction({ head = { seen } }, { head = {} })
171
+
172
+ view:setproperty(types.singleton("listen"), returns({ types.unknown, handler }))
173
+ end
174
+
175
+ if class == "command" or class == "intent" or class == "signal" then
176
+ if server then
177
+ local seen = payload
178
+
179
+ if class == "command" then
180
+ seen = brandedAs(payload, "__nwTrusted")
181
+ elseif class == "signal" then
182
+ seen = brandedAs(payload, "__nwUntrusted")
183
+ end
184
+
185
+ listener(seen, true)
186
+ else
187
+ view:setproperty(types.singleton("send"), returns({ types.unknown, payload }))
188
+ end
189
+ elseif class == "query" then
190
+ if server then
191
+ local handler = types.newfunction(
192
+ { head = { context(), brandedAs(payload, "__nwTrusted") } },
193
+ { head = { response } }
194
+ )
195
+
196
+ view:setproperty(types.singleton("handle"), returns({ types.unknown, handler }))
197
+ else
198
+ --[[
199
+ Two returns, both optional: a query that timed out has no answer, and one that was
200
+ refused has a reason. The failure is a value rather than something thrown because a
201
+ refused query is an ordinary outcome, and it cannot be ignored because `R?` is not
202
+ usable without a nil check under the solver netweave requires.
203
+
204
+ `nil` is unambiguous here only because `nw.query` refuses a top-level `t.optional`
205
+ `returns`, which is the one shape that would make "no answer" and "the answer is
206
+ nothing" the same value (`DESIGN-API.md` §7, `src/api/Channel.luau`).
207
+ ]]
208
+ view:setproperty(
209
+ types.singleton("invoke"),
210
+ types.newfunction(
211
+ { head = { types.unknown, payload } },
212
+ { head = { types.optional(response), types.optional(types.string) } }
213
+ )
214
+ )
215
+ end
216
+ elseif class == "replicate" then
217
+ --[[
218
+ The server view has **nothing on it**, and that absence is the class's argument made
219
+ mechanical rather than documented. A replicated channel is fed by its `store`; if
220
+ `publish` existed here there would be two ways in, and the one that skipped the baseline
221
+ would leave clients wrong in a way nothing could detect.
222
+
223
+ The client half is `listen`, the same as `state`, because a client that has to know
224
+ whether it was sent a change or a whole value is a client the library has failed.
225
+ ]]
226
+ if not server then
227
+ --[[ Two arguments, and the subject first. A replicated client keeps one value per
228
+ subject, so a listener that could not tell them apart would be useless — and typing
229
+ it here is what stops the signature from taking one argument at analysis and two at
230
+ runtime, which is worse than either. ]]
231
+ view:setproperty(
232
+ types.singleton("listen"),
233
+ returns({
234
+ types.unknown,
235
+ types.newfunction({ head = { subject, payload } }, { head = {} }),
236
+ })
237
+ )
238
+ end
239
+ else
240
+ if server then
241
+ view:setproperty(types.singleton("publish"), returns({ types.unknown, types.unknown, payload }))
242
+
243
+ --[[ G3. `broadcast` is absent unless the declared audience is provably everyone, which
244
+ is why an audience is a value with a singleton scope and not a string. ]]
245
+ if audience == "everyone" then
246
+ view:setproperty(types.singleton("broadcast"), returns({ types.unknown, payload }))
247
+ end
248
+ else
249
+ listener(payload, false)
250
+ end
251
+ end
252
+
253
+ return view
254
+ end
255
+
256
+ --[=[
257
+ @type ServerView<D> D
258
+ @within View
259
+
260
+ Maps a declaration table to what the server may do with each channel.
261
+ ]=]
262
+ -- selene: allow(undefined_variable)
263
+ export type function ServerView(declaration, ctx)
264
+ local result = types.newtable()
265
+
266
+ for key, property in declaration:properties() do
267
+ local channel = property.read
268
+
269
+ if not channel then
270
+ error(
271
+ "a channel in this namespace has no readable type, which means it was declared "
272
+ .. "write-only. Write the namespace as a plain table literal: "
273
+ .. 'nw.namespace("combat", { fireWeapon = nw.command({ ... }) }), with no '
274
+ .. "`write` or `read` modifiers on the fields."
275
+ )
276
+ end
277
+
278
+ result:setproperty(key, channelView(channel, types.singleton("server"), ctx))
279
+ end
280
+
281
+ return result
282
+ end
283
+
284
+ --[=[
285
+ @type ClientView<D> D
286
+ @within View
287
+
288
+ Maps a declaration table to what the client may do with each channel.
289
+ ]=]
290
+ -- selene: allow(undefined_variable)
291
+ export type function ClientView(declaration, ctx)
292
+ local result = types.newtable()
293
+
294
+ for key, property in declaration:properties() do
295
+ local channel = property.read
296
+
297
+ if not channel then
298
+ error(
299
+ "a channel in this namespace has no readable type, which means it was declared "
300
+ .. "write-only. Write the namespace as a plain table literal: "
301
+ .. 'nw.namespace("combat", { fireWeapon = nw.command({ ... }) }), with no '
302
+ .. "`write` or `read` modifiers on the fields."
303
+ )
304
+ end
305
+
306
+ result:setproperty(key, channelView(channel, types.singleton("client"), ctx))
307
+ end
308
+
309
+ return result
310
+ end
311
+
312
+ --[=[
313
+ @type Views<D> { name: string, channels: D, server: ServerView<D>, client: ClientView<D> }
314
+ @within View
315
+
316
+ What `nw.namespace` returns: the declaration itself, and it seen from both sides.
317
+ ]=]
318
+ --[[
319
+ This alias is load-bearing beyond naming the pair, and deleting it breaks G6 silently.
320
+
321
+ Measured in `spike/declare/mod/`: an `export type function` that its own module never references
322
+ does **not** reduce for a module that requires it. It becomes `any`, with no diagnostic — so
323
+ `combat.server.fireWeapon:send(...)` would compile, and every direction violation in
324
+ `tests/api_reject.luau` would stop erroring while the file still claimed to test them.
325
+
326
+ **And there is one way to write it down that does the same thing.** `local ns: Views<D> = <a
327
+ namespace>` — an annotated local with a value assigned into it — makes the file stop reporting
328
+ anything about `ns`, retroactively and to the end of the file. Measured at
329
+ `--flag:LuauSolverV2=true` against the same declarations, counting the two diagnostics a
330
+ direction violation and a wrong-typed handler produce:
331
+
332
+ | written as | diagnostics |
333
+ |---|---|
334
+ | no annotation | 2 |
335
+ | `type V = Views<D>`, never assigned through | 2 |
336
+ | `local v = ns :: Views<D>` | 2 |
337
+ | `local v: Views<D>` with no value | 2 |
338
+ | `local v: typeof(ns) = ns` | 2 |
339
+ | a parameter typed `Views<D>`, called with `ns` | 2 |
340
+ | **`local v: Views<D> = ns`** | **0** |
341
+
342
+ Six spellings keep the guarantees and one removes them, so the answer is to write one of the six
343
+ — a parameter, a cast, or `typeof` — and `tests/api_ok.luau` pins all three. The seventh is
344
+ pinned as a canary at the end of `tests/api_reject.luau`: it holds two statements that should
345
+ error, the header count says they do not, and if the count ever moves to 25 this caution can come
346
+ off. Found by M4's security report, which also found the reason nothing had caught it: no file in
347
+ `tests/` had ever written `Views<` at all.
348
+
349
+ **The parameter row above counted the wrong thing**, and `tests/tutorial_ok.luau` measured what it
350
+ missed (2026-09-10): the two direction diagnostics survive, and the *payloads* of every handler
351
+ written on `ns` before the call do not — `wire(ns)` against `namespace: Views<D>`, or against
352
+ `typeof(ns)`, makes `chosen.slot` in a `:listen` forty lines earlier read as `unknown`. A namespace
353
+ used nowhere else, which is what the row and `api_ok`'s `attach(shots)` both use, does not show it.
354
+ Casting at the call, `wire(ns :: Views<D>)`, keeps every handler typed, and is what the tutorial
355
+ tells a game to write. `PLAN-M5` phase 1 owns finding the instantiation that loses it.
356
+ ]]
357
+ export type Views<D> = {
358
+ name: string,
359
+ channels: D,
360
+ server: ServerView<D, Context.Ctx>,
361
+ client: ClientView<D, Context.Ctx>,
362
+ }
363
+
364
+ --[[
365
+ The runtime objects the types above describe.
366
+
367
+ One table per channel per side, built once at declaration. The methods close over the channel
368
+ record, so dispatch reads the rate, policy, audience and codec straight off the declaration —
369
+ there is no per-packet lookup and nothing to keep in sync.
370
+ ]]
371
+ local function attach(channel: any, handler: any, what: string)
372
+ if type(handler) ~= "function" then
373
+ error(
374
+ `:{what}() takes the function that runs per packet, got {typeof(handler)}. Write it `
375
+ .. `inline — combat.server.fireWeapon:{what}(function(ctx, shot) ... end) — with the `
376
+ .. `colon, so the channel is the receiver.`,
377
+ 3
378
+ )
379
+ end
380
+
381
+ if channel.handler ~= nil then
382
+ error(
383
+ `{channel.qualified} already has a handler. A channel has exactly one: two would `
384
+ .. `split the authorization decision across two places, which is what this library `
385
+ .. `exists to prevent. Fan out inside the handler instead.`,
386
+ 3
387
+ )
388
+ end
389
+
390
+ channel.handler = handler
391
+
392
+ if Transport.installed() then
393
+ Transport.driver(what).dispatch(channel, handler)
394
+ end
395
+ end
396
+
397
+ local function serverView(channel: any): any
398
+ local class = channel.class
399
+
400
+ if class == "command" or class == "intent" or class == "signal" then
401
+ return {
402
+ channel = channel,
403
+
404
+ listen = function(_self: any, handler: any)
405
+ attach(channel, handler, "listen")
406
+ end,
407
+ }
408
+ end
409
+
410
+ if class == "query" then
411
+ return {
412
+ channel = channel,
413
+
414
+ handle = function(_self: any, handler: any)
415
+ attach(channel, handler, "handle")
416
+ end,
417
+ }
418
+ end
419
+
420
+ --[[ Nothing to call. See the type function above: the store is the only way into a replicated
421
+ channel, so a second one would be a way to be wrong. ]]
422
+ if class == "replicate" then
423
+ return { channel = channel }
424
+ end
425
+
426
+ local view: any = {
427
+ channel = channel,
428
+
429
+ publish = function(_self: any, subject: any, value: any)
430
+ Transport.driver("publish").publish(channel, subject, value)
431
+ end,
432
+ }
433
+
434
+ if channel.audience.scope == "everyone" then
435
+ view.broadcast = function(_self: any, value: any)
436
+ Transport.driver("broadcast").broadcast(channel, value)
437
+ end
438
+ end
439
+
440
+ return view
441
+ end
442
+
443
+ local function clientView(channel: any): any
444
+ local class = channel.class
445
+
446
+ if class == "command" or class == "intent" or class == "signal" then
447
+ return {
448
+ channel = channel,
449
+
450
+ send = function(_self: any, value: any)
451
+ Transport.driver("send").send(channel, value)
452
+ end,
453
+ }
454
+ end
455
+
456
+ if class == "query" then
457
+ return {
458
+ channel = channel,
459
+
460
+ invoke = function(_self: any, args: any): (any?, string?)
461
+ return Transport.driver("invoke").invoke(channel, args)
462
+ end,
463
+ }
464
+ end
465
+
466
+ return {
467
+ channel = channel,
468
+
469
+ listen = function(_self: any, handler: any)
470
+ attach(channel, handler, "listen")
471
+ end,
472
+ }
473
+ end
474
+
475
+ --[=[
476
+ @within View
477
+ @function build
478
+ @param channels { [string]: Channel }
479
+ @param side "server" | "client"
480
+ @return { [string]: any }
481
+ @private
482
+
483
+ Builds one side of a namespace. Called by `nw.namespace`.
484
+ ]=]
485
+ function View.build(channels: { [string]: any }, side: "server" | "client"): { [string]: any }
486
+ local built: { [string]: any } = {}
487
+
488
+ for key, channel in channels do
489
+ if not Channel.isChannel(channel) then
490
+ error(
491
+ `{key} is not a channel; declare it with nw.command, nw.intent, nw.signal, `
492
+ .. `nw.query, nw.state or nw.event`,
493
+ 3
494
+ )
495
+ end
496
+
497
+ built[key] = if side == "server" then serverView(channel) else clientView(channel)
498
+ end
499
+
500
+ return table.freeze(built)
501
+ end
502
+
503
+ return View