@typeonce/oxlint-plugin-ritmo 0.14.0 → 0.16.0

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 (34) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +86 -13
  3. package/dist/index.js +13 -8
  4. package/dist/index.js.map +1 -1
  5. package/dist/rules/handle-runtime-result.d.ts +8 -0
  6. package/dist/rules/handle-runtime-result.d.ts.map +1 -0
  7. package/dist/rules/handle-runtime-result.js +102 -0
  8. package/dist/rules/handle-runtime-result.js.map +1 -0
  9. package/dist/rules/no-brand-cast.d.ts +7 -0
  10. package/dist/rules/no-brand-cast.d.ts.map +1 -0
  11. package/dist/rules/no-brand-cast.js +195 -0
  12. package/dist/rules/no-brand-cast.js.map +1 -0
  13. package/dist/rules/no-float-timers.d.ts +8 -0
  14. package/dist/rules/no-float-timers.d.ts.map +1 -0
  15. package/dist/rules/no-float-timers.js +60 -0
  16. package/dist/rules/no-float-timers.js.map +1 -0
  17. package/dist/rules/use-clock-for-time.js +1 -1
  18. package/dist/rules/use-clock-for-time.js.map +1 -1
  19. package/dist/rules/use-ops-for-math.d.ts +2 -2
  20. package/dist/rules/use-ops-for-math.d.ts.map +1 -1
  21. package/dist/rules/use-ops-for-math.js +199 -35
  22. package/dist/rules/use-ops-for-math.js.map +1 -1
  23. package/package.json +1 -1
  24. package/src/index.ts +13 -8
  25. package/src/rules/handle-runtime-result.ts +108 -0
  26. package/src/rules/no-brand-cast.ts +195 -0
  27. package/src/rules/no-float-timers.ts +64 -0
  28. package/src/rules/use-clock-for-time.ts +1 -1
  29. package/src/rules/use-ops-for-math.ts +207 -35
  30. package/dist/rules/handle-tick-result.d.ts +0 -8
  31. package/dist/rules/handle-tick-result.d.ts.map +0 -1
  32. package/dist/rules/handle-tick-result.js +0 -56
  33. package/dist/rules/handle-tick-result.js.map +0 -1
  34. package/src/rules/handle-tick-result.ts +0 -61
package/CHANGELOG.md CHANGED
@@ -1,5 +1,74 @@
1
1
  # @typeonce/oxlint-plugin-ritmo
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - be9af72: **Breaking: `ritmo/handle-tick-result` is `ritmo/handle-runtime-result`, and it also catches a `Result` passed on unchecked.** Besides a dropped `tick`, `tryTick`, `restore`, or `rewind`, it reports `runtime.snapshot()` and `runtime.checksum()`, and any of them handed to a function, printed in a template string, put in an object or array, or used as an operand without a check: a save function that takes `unknown` otherwise stores the `{ ok, value }` wrapper instead of the world. A variable, a field, a `return`, `.ok`, and `void` keep the `Result` for the code to check; a helper that takes the `Result` gets it once it is named.
8
+
9
+ Fix: rename the rule in `.oxlintrc.json`, then check each new report.
10
+
11
+ ```diff
12
+ -"ritmo/handle-tick-result": "error",
13
+ +"ritmo/handle-runtime-result": "error",
14
+ ```
15
+
16
+ ```diff
17
+ -persist(runtime.snapshot())
18
+ +const saved = runtime.snapshot()
19
+ +if (saved.ok) persist(saved.value)
20
+ ```
21
+
22
+ ### Patch Changes
23
+
24
+ - be9af72: `ritmo/no-float-timers` says what to do with a timer that must stop while the world clock runs (hit-stop, a menu over gameplay): measure it against a second clock that holds, `Clock.resource` advanced by `Clock.system(Game, { name, resource, hold })`, so its deadlines wait with it. Only time scaled by a fraction is a real float, kept with a disable comment that gives the reason. The README and the `Clock.system` JSDoc show the pattern.
25
+ - 9290521: Docs from upgrading two games across several versions:
26
+
27
+ - The skill's state-and-upgrades playbook lists the breaks that still compile, per version, and `SETUP.md` says a new lint rule is off until `.oxlintrc.json` lists it.
28
+ - The 0.13 `Decode` entry has a table from each `Decode` codec to Zod and Effect; handle schemas use `z.unknown().refine(Entity.isHandle(...))`, not `z.custom`.
29
+ - The `Snapshot.version` JSDoc says how to rewrite a format 2 save; `WorldSnapshot.relations` says targets are sorted by id while each target's sources keep their order.
30
+ - `ritmo-devtools lint`'s `uncovered-simulation-module` message names the usual cause: a host module imported at the top of the lint entry instead of inside `lintTarget`. The README shows a debug script reusing `lintTarget`.
31
+ - The `Replay` docs and the 0.15 changelog say how to keep a playtester's save button without the monitor: `recorder.save(reason)` from a key handler.
32
+ - `Touch.Layout` shows how to draw a layout with no `null` zones, and `Pointer.Actions` says to build test doubles with `Pointer.scripted`.
33
+ - The `use-ops-for-math` example uses `Angle.wrap` for a signed turn, and the spatial-grid reference defines its `made` helper.
34
+
35
+ ## 0.15.0
36
+
37
+ ### Minor Changes
38
+
39
+ - 3a195b7: **Cooldowns and timers are deadlines: the step they end on, exact through saves and rollback.** A timer counted down by `dt` drifts by a rounded float every tick, and the float it saves means nothing once the fixed step changes. `Clock.Deadline<Hz>` is the absolute step a duration ends on, a plain number branded with the clock's rate:
40
+
41
+ ```ts
42
+ // ready: Clock.Deadline<60> | null, its schema narrowing with Clock.isDeadline(step)
43
+ const Weapon = Descriptor.ConstructedComponent(
44
+ z.object({ ready: z.unknown().refine(Clock.isDeadline(step)).nullable() })
45
+ )("Game/Weapon");
46
+
47
+ const time = resources.time.get();
48
+ const { ready } = data.weapon.get();
49
+ if (ready === null || Clock.reached(time, ready)) {
50
+ fire();
51
+ data.weapon.set({ ready: Clock.deadline(time, Clock.duration(step, 0.5)) });
52
+ }
53
+ ```
54
+
55
+ - `Clock.deadline(time, duration)`, `Clock.reached(time, deadline)`, and `Clock.remaining(time, deadline)` (whole steps left, for a readout). A deadline of a 60 Hz clock does not compile against a 30 Hz `Time`, and a raw number is not a deadline.
56
+ - `Clock.isDeadline(step)` is the guard for a game's schema, like `Entity.isHandle`: any whole number of steps, 0 or more.
57
+ - New lint rule `ritmo/no-float-timers` for simulation files: reports `timer -= dt`, `cooldown - time.dt`, and the like, and names `Clock.deadline` / `Clock.reached`. `position.x += velocity.x * dt` is integration and is not reported. Turn it on in the simulation override of `.oxlintrc.json`: `"ritmo/no-float-timers": "error"`.
58
+
59
+ - c75daff: **`oxlint --fix` does the whole job for `ritmo/use-ops-for-math`.** The rule points at `Ops` from `@typeonce/ritmo` (it moved from `@typeonce/ritmo-math`), and its fix now adds `import { Ops } from "@typeonce/ritmo"` when the file has none, once per file, after the last import (a `const { Ops } = require("@typeonce/ritmo")` in CommonJS, for vendored code). `x **= y` is fixed to `x = Ops.pow(x, y)` when `x` is a variable. `ritmo/use-random-for-randomness` names `Random` from `@typeonce/ritmo` the same way.
60
+
61
+ **Aliasing `Math` is reported.** `const { sin } = Math`, `const M = Math`, passing `Math` to a function, `globalThis.Math.sin`, and `Math[name]` with a computed key hid a non-exact call from the rule; each is now reported (without a fix). Exact members (`Math.PI`, `Math.abs`, `const { floor } = Math`) stay valid.
62
+
63
+ **New rule `ritmo/no-brand-cast`.** A cast to a branded type (`raw as ItemId` where `ItemId` comes from `.brand()`, `Schema.brand`, `Brand.Branded`, or a Ritmo brand such as `Random.State` or `Clock.Deadline`) skips the check the brand stands for. The rule reports it in simulation code and names the fix: decode through the schema, or the Ritmo constructor (`Random.seed`, `Clock.deadline`, `Game.Entity.handle`). Turn it on in the simulation override:
64
+
65
+ ```json
66
+ {
67
+ "files": ["src/simulation/**"],
68
+ "rules": { "ritmo/no-brand-cast": "error" }
69
+ }
70
+ ```
71
+
3
72
  ## 0.14.0
4
73
 
5
74
  ### Minor Changes
package/README.md CHANGED
@@ -5,7 +5,9 @@
5
5
  Ritmo's types reject wrong calls, and its devtools lints reject wrong runs. These rules catch the source patterns neither can see:
6
6
 
7
7
  - simulation code that reads the wall clock, `Math.random`, engine-dependent math, or the page;
8
+ - timers counted in floats;
8
9
  - data that cannot be saved;
10
+ - casts that claim a brand's check without running it;
9
11
  - state values that keep a previous state's fields;
10
12
  - runtime results that are dropped.
11
13
 
@@ -25,7 +27,7 @@ Register the plugin and turn the rules on in `.oxlintrc.json`. The simulation ru
25
27
  {
26
28
  "jsPlugins": ["@typeonce/oxlint-plugin-ritmo"],
27
29
  "rules": {
28
- "ritmo/handle-tick-result": "error",
30
+ "ritmo/handle-runtime-result": "error",
29
31
  "ritmo/prefix-descriptor-and-system-names": "error",
30
32
  "ritmo/use-cell-value": "error",
31
33
  "ritmo/no-state-spread": "error"
@@ -39,14 +41,16 @@ Register the plugin and turn the rules on in `.oxlintrc.json`. The simulation ru
39
41
  "ritmo/use-random-for-randomness": "error",
40
42
  "ritmo/use-ops-for-math": "error",
41
43
  "ritmo/keep-simulation-headless": "error",
42
- "ritmo/no-infinity-in-simulation-data": "error"
44
+ "ritmo/no-infinity-in-simulation-data": "error",
45
+ "ritmo/no-float-timers": "error",
46
+ "ritmo/no-brand-cast": "error"
43
47
  }
44
48
  }
45
49
  ]
46
50
  }
47
51
  ```
48
52
 
49
- Rules are named `ritmo/<rule>`. `ritmo/use-ops-for-math` and `ritmo/use-cell-value` fix themselves with `oxlint --fix` (`use-ops-for-math` once `Ops` is imported in the file).
53
+ Rules are named `ritmo/<rule>`. `ritmo/use-ops-for-math` and `ritmo/use-cell-value` fix themselves with `oxlint --fix`.
50
54
 
51
55
  A deliberate exception, such as a host-time module inside a simulation folder, takes a disable comment with the reason:
52
56
 
@@ -59,10 +63,12 @@ const started = performance.now()
59
63
  |---|---|---|---|
60
64
  | [`use-clock-for-time`](#ritmouse-clock-for-time) | simulation | `Date.now()`, `performance.now()`, `new Date()`, timers | `Clock` |
61
65
  | [`use-random-for-randomness`](#ritmouse-random-for-randomness) | simulation | `Math.random()`, `crypto` randomness | `Random.draw(resources.rng)` |
62
- | [`use-ops-for-math`](#ritmouse-ops-for-math) | simulation | `Math.sin`, `Math.hypot`, `a ** b`, ... | `Ops` |
66
+ | [`use-ops-for-math`](#ritmouse-ops-for-math) | simulation | `Math.sin`, `Math.hypot`, `a ** b`, `const { sin } = Math`, ... | `Ops` |
63
67
  | [`keep-simulation-headless`](#ritmokeep-simulation-headless) | simulation | page globals, host I/O, renderer imports | input and data from the host, drawing in a render schedule |
64
68
  | [`no-infinity-in-simulation-data`](#ritmono-infinity-in-simulation-data) | simulation | `Infinity` / `NaN` in object literals | `null` |
65
- | [`handle-tick-result`](#ritmohandle-tick-result) | everywhere | a dropped `runtime.tick(...)` / `restore(...)` / `rewind(...)` result | check `.ok` |
69
+ | [`no-float-timers`](#ritmono-float-timers) | simulation | `timer -= dt`, `cooldown - time.dt` | `Clock.deadline` / `Clock.reached` |
70
+ | [`no-brand-cast`](#ritmono-brand-cast) | simulation | `raw as UserId`, `1 as Random.State` | the schema or constructor that brands it |
71
+ | [`handle-runtime-result`](#ritmohandle-runtime-result) | everywhere | a dropped or unchecked `runtime.tick(...)` / `restore(...)` / `rewind(...)` / `snapshot()` / `checksum()` result | check `.ok` |
66
72
  | [`prefix-descriptor-and-system-names`](#ritmoprefix-descriptor-and-system-names) | everywhere | `"Position"`, `Game.System("Move", ...)` | `"Game/Position"` |
67
73
  | [`use-cell-value`](#ritmouse-cell-value) | everywhere | `cell.present ? cell.get() : undefined` | `cell.value()` |
68
74
  | [`no-state-spread`](#ritmono-state-spread) | everywhere | `{ ...ground, _tag: "air", vy }` | `cell.transition({ from, to, data })`, `nextMachines.x.set({ _tag, ...fields })`, or the new state's fields written out |
@@ -80,7 +86,7 @@ setTimeout(() => spawnWave(), 500) // reported
80
86
  // instead
81
87
  const time = resources.time.get()
82
88
  if (Clock.elapsed(time) > 3) open() // seconds since the start
83
- const due = time.step + Clock.steps(Clock.duration(step, 0.5)) // store it, compare each tick
89
+ const due = Clock.deadline(time, Clock.duration(step, 0.5)) // store it, Clock.reached(time, due) each tick
84
90
  if (Clock.every(time, waveEvery)) spawnWave() // repeats
85
91
  ```
86
92
 
@@ -103,19 +109,26 @@ Catches `Math.random()`, `crypto.getRandomValues()`, and `crypto.randomUUID()`.
103
109
 
104
110
  ### `ritmo/use-ops-for-math`
105
111
 
106
- The spec lets engines approximate `Math.sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `expm1`, `log`, `log2`, `log10`, `log1p`, `cbrt`, `pow`, `hypot`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, and `a ** b`, and they do: Chrome, Safari, macOS, and Linux disagree in the last bit, and a simulation grows that bit into a different run. [`Ops`](https://github.com/typeonce-dev/ritmo/blob/main/packages/math/README.md#determinism-across-devices) from `@typeonce/ritmo-math` has each of them as a port that returns the same bits everywhere.
112
+ The spec lets engines approximate `Math.sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `expm1`, `log`, `log2`, `log10`, `log1p`, `cbrt`, `pow`, `hypot`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, and `a ** b`, and they do: Chrome, Safari, macOS, and Linux disagree in the last bit, and a simulation grows that bit into a different run. [`Ops`](https://github.com/typeonce-dev/ritmo/blob/main/packages/core/README.md) from `@typeonce/ritmo` has each of them as a port that returns the same bits everywhere.
107
113
 
108
114
  ```ts
109
115
  const turn = Math.atan2(Math.sin(b - a), Math.cos(b - a)) // reported
110
116
  const beauty = base * repeat ** n // reported
111
117
 
112
118
  // instead
113
- import { Ops } from "@typeonce/ritmo-math"
114
- const turn = Ops.atan2(Ops.sin(b - a), Ops.cos(b - a))
119
+ import { Ops } from "@typeonce/ritmo"
120
+ import { Angle } from "@typeonce/ritmo-math"
121
+ const turn = Angle.wrap(b - a) // the signed turn from a to b, exact
115
122
  const beauty = base * Ops.pow(repeat, n)
116
123
  ```
117
124
 
118
- `Math.sqrt`, `abs`, `min`, `max`, `floor`, `ceil`, `round`, `trunc`, `sign`, `+ - * /`, and `x ** 2` are exact everywhere and are not reported. With `Ops` imported in the file, `oxlint --fix` rewrites the calls.
125
+ Before porting a formula to `Ops`, look for the helper that names it: `Angle.wrap` and `Angle.turnToward` in [`@typeonce/ritmo-math`](https://github.com/typeonce-dev/ritmo/blob/main/packages/math/README.md) need no transcendental call at all.
126
+
127
+ `Math.sqrt`, `abs`, `min`, `max`, `floor`, `ceil`, `round`, `trunc`, `sign`, `+ - * /`, and `x ** 2` are exact everywhere and are not reported (`Math.PI`, `Math["floor"]`, and `const { abs, PI } = Math` neither).
128
+
129
+ `oxlint --fix` does the whole change in one run: it rewrites `Math.sin(x)` to `Ops.sin(x)`, `a ** b` to `Ops.pow(a, b)`, and `x **= y` to `x = Ops.pow(x, y)`, and adds `import { Ops } from "@typeonce/ritmo"` once, after the last import (`const { Ops } = require("@typeonce/ritmo")` in a CommonJS file). It uses `Ops` where the file already imports it, under any name (`import { Ops as M }`, `import * as Ops from "@typeonce/ritmo/Ops"`). It leaves the report unfixed where a rewrite could change the code: `body.speed **= y` (the rewrite would evaluate `body` twice), and a file or function where the name `Ops` already means something else (a type-only import included).
130
+
131
+ The global Math handed on as a value hides the calls made through it from the rule, so it is reported too (without a fix): an alias (`const M = Math`), a destructured function or rest element (`const { sin } = Math`), an argument (`apply(Math, "sin", x)`), a computed key (`Math[name]`), and `globalThis.Math` used the same ways. Call `Ops.sin` directly, and read exact members by name. A local named `Math` is not the global and is not reported.
119
132
 
120
133
  ### `ritmo/keep-simulation-headless`
121
134
 
@@ -147,16 +160,74 @@ dash: { remaining: 0, since: null } // since: numbe
147
160
 
148
161
  Catches `Infinity`, `-Infinity`, `NaN`, and `Number.POSITIVE_INFINITY` / `NEGATIVE_INFINITY` / `NaN` as a property value in any object literal in simulation files, including values built in helpers before they are spawned. Search seeds in locals (`let best = Infinity`) are not reported.
149
162
 
163
+ ### `ritmo/no-float-timers`
164
+
165
+ A timer counted down by `dt` adds a rounded float every tick, so it ends a step early or late, and the float it saves means nothing once the fixed step changes. A deadline is the step the timer ends on: written once, exact, and valid after a restore or a rollback, since the clock it is measured against is saved and rewound with it.
166
+
167
+ ```ts
168
+ cooldown.remaining -= dt // reported
169
+ data.buff.set({ ...buff, left: buff.left - time.dt }) // reported
170
+
171
+ // instead: ready: Clock.Deadline<60> | null, its schema narrowing with Clock.isDeadline(step)
172
+ const cooldown = Clock.duration(step, 0.5)
173
+ const time = resources.time.get()
174
+ const { ready } = data.weapon.get()
175
+ if (ready === null || Clock.reached(time, ready)) {
176
+ fire()
177
+ data.weapon.set({ ready: Clock.deadline(time, cooldown) })
178
+ }
179
+ const bar = ready === null ? 0 : Clock.remaining(time, ready) / Clock.steps(cooldown) // a readout
180
+ ```
181
+
182
+ A timer that must stop while the world clock keeps running (gameplay frozen in hit-stop, a menu over the level) is measured against a second clock that holds, instead of against the world clock:
183
+
184
+ ```ts
185
+ const GameplayTime = Clock.resource("Game/GameplayTime", step)
186
+ const gameplayClock = Clock.system(Game, { name: "Game/GameplayClock", resource: GameplayTime, hold: [inHitStop] })
187
+
188
+ // A deadline on GameplayTime waits while inHitStop passes, and saves and rolls back like any deadline
189
+ data.enemy.set({ attackAt: Clock.deadline(gameplay, windup) })
190
+ ```
191
+
192
+ Time scaled by a fraction (a 0.3x slow motion) has no whole step to end on, so a float is right there: keep it and disable the line with the reason (`// oxlint-disable-next-line ritmo/no-float-timers -- scaled by slow motion`). A value counted up by `dt` is reported too, since it drifts the same way: `Clock.elapsed(time)` is the exact seconds of a clock.
193
+
194
+ Catches a stored value (a local or a field) plus or minus a tick's seconds on their own: `dt`, `deltaTime`, or `deltaSeconds`, as a local, a field (`time.dt`), or a resource read (`resources.deltaTime.get()`), in `x -= dt`, `x += dt`, and `x - dt` / `x + dt` anywhere (`Math.max(0, x - dt)`, an object literal). A rate scaled by `dt` (`position.x += velocity.x * dt`) is integration and is not reported, nor is a count of whole steps (`cooldown - 1`), nor a `delta` that is not time (a pointer's).
195
+
196
+ ### `ritmo/no-brand-cast`
197
+
198
+ A branded type (`UserId`, `Random.State`, `Clock.Deadline<60>`) stands for a check the value passed. A cast claims the brand without running the check, so an invalid value travels as a valid one: a save holding it fails to load, or the simulation computes with it.
199
+
200
+ ```ts
201
+ const UserId = z.string().uuid().brand("UserId")
202
+ type UserId = z.infer<typeof UserId>
203
+ const id = raw as UserId // reported
204
+ const rng = Random.resource("Game/Rng", 1 as Random.State) // reported
205
+
206
+ // instead
207
+ const id = UserId.parse(raw) // Effect: Schema.decodeUnknownSync(UserId)(raw)
208
+ const rng = Random.resource("Game/Rng", Random.seed(1))
209
+ ```
210
+
211
+ Oxlint has no type information, so the rule reads the brand from the code: a cast (`x as T` or `<T>x`) to
212
+ - a brand helper: `Brand.Branded<...>`, Effect's `Brand.Brand<...>`, Zod's `z.BRAND<...>` / `z.$brand<...>`, or a `Brand<...>` / `Branded<...>` of any library;
213
+ - an object type with a brand key: `T & { readonly __brand: "UserId" }` (also `_brand`, `__type`), or a key declared as `declare const brand: unique symbol`;
214
+ - a type alias or interface in the same file that is one of these, or the type of a schema in the same file built with `.brand(...)` / `Schema.brand(...)` (`z.infer<typeof UserId>`, `typeof Gold.Type`, `Schema.Schema.Type<typeof Gold>`);
215
+ - a branded Ritmo export imported from `@typeonce/ritmo` (or a subpath such as `@typeonce/ritmo/Clock`): `Clock.Deadline`, `Clock.Step`, `Clock.Duration`, `Clock.ClockResource`, `Entity.Handle`, `Entity.EntityId`, `Random.State`, `Checkpoint.Checkpoint`, `Checkpoint.Rewindable`.
216
+
217
+ Make the value through its check: decode at the boundary with the game's schema, or with Ritmo's constructor or guard (`Random.seed` / `Random.result`, `Clock.deadline` / `Clock.isDeadline`, `Game.Entity.handle` / `Entity.isHandle`). `as const`, `satisfies`, and casts to types without a brand are not reported, nor are brands imported from another file of the game (the rule cannot see them).
218
+
150
219
  ## Rules for every file
151
220
 
152
- ### `ritmo/handle-tick-result`
221
+ ### `ritmo/handle-runtime-result`
153
222
 
154
- `runtime.tick(...)` returns a `Result`: a system that fails stops the tick, and the failure comes back here. `runtime.restore(...)` returns one too: an invalid save leaves the previous world in place. So does `runtime.rewind(...)`: a checkpoint the runtime let go of changes nothing, and the ticks meant to run again run on top of the present. Dropping any of them hides the failure.
223
+ `runtime.tick(...)` returns a `Result`: a system that fails stops the tick, and the failure comes back here. `runtime.restore(...)` returns one too: an invalid save leaves the previous world in place. So does `runtime.rewind(...)`: a checkpoint the runtime let go of changes nothing, and the ticks meant to run again run on top of the present. `runtime.snapshot()` and `runtime.checksum()` return one because a schema's `encode` may reject a value. Dropping any of them hides the failure, and so does passing one on where any value is accepted: a save function that takes `unknown` stores the `{ ok, value }` wrapper, not the world.
155
224
 
156
225
  ```ts
157
226
  runtime.tick(update) // reported
158
227
  runtime.restore(save) // reported
159
228
  runtime.rewind(checkpoint) // reported
229
+ persist(runtime.snapshot()) // reported
230
+ log(`hash ${runtime.checksum()}`) // reported
160
231
 
161
232
  // instead
162
233
  const ran = runtime.tick(update)
@@ -165,10 +236,12 @@ const restored = runtime.restore(save)
165
236
  if (!restored.ok) showLoadError(restored.error)
166
237
  const rewound = runtime.rewind(checkpoint)
167
238
  if (!rewound.ok) resync(rewound.error) // Released or OtherRuntime
239
+ const saved = runtime.snapshot()
240
+ if (saved.ok) persist(saved.value)
168
241
  void runtime.tick(render) // ignored on purpose
169
242
  ```
170
243
 
171
- Catches `tick(...)`, `tryTick(...)`, `restore(...)`, and `rewind(...)` used as a statement on a receiver named like a runtime (`runtime`, `game.runtime`, `worldRuntime`). Game wrappers with other names (`town.restore(...)`) are not reported. Option: `{ "runtimePattern": "^(runtime|world)$" }` (a case-insensitive regular expression for the receiver's name; default `runtime$`).
244
+ Catches these calls on a receiver named like a runtime (`runtime`, `game.runtime`, `worldRuntime`) used as a statement, or passed on unchecked: as a call argument, inside a template string, an object or array literal, a spread, or an operand, also through `??`, `? :`, and `as`. A variable, a field, a `return`, `.ok`, and `void` keep the `Result` for the code to check. A helper that takes the `Result` itself gets it once it is named: `const checksum = runtime.checksum(); helper(checksum)`. Game wrappers with other names (`town.restore(...)`) are not reported. Option: `{ "runtimePattern": "^(runtime|world)$" }` (a case-insensitive regular expression for the receiver's name; default `runtime$`).
172
245
 
173
246
  ### `ritmo/prefix-descriptor-and-system-names`
174
247
 
package/dist/index.js CHANGED
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Types catch wrong calls and devtools catch wrong runs; these rules catch
5
5
  * the source patterns neither can see: simulation code that reads the wall
6
- * clock, `Math.random`, engine-dependent math, or the page, data that cannot
7
- * be saved, state values that keep a previous state's fields, and runtime
8
- * results that are dropped. Every report names the
9
- * Ritmo API to use instead.
6
+ * clock, `Math.random`, engine-dependent math, or the page, timers counted
7
+ * in floats, data that cannot be saved, casts that skip a brand's check,
8
+ * state values that keep a previous state's fields, and runtime results that
9
+ * are dropped. Every report names the Ritmo API to use instead.
10
10
  *
11
11
  * Register the plugin in `.oxlintrc.json` with `"jsPlugins":
12
12
  * ["@typeonce/oxlint-plugin-ritmo"]`. Its rules are named `ritmo/<rule>`.
@@ -16,16 +16,19 @@
16
16
  *
17
17
  * - Simulation files: `ritmo/use-clock-for-time`,
18
18
  * `ritmo/use-random-for-randomness`, `ritmo/use-ops-for-math`,
19
- * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`.
20
- * - Every file: `ritmo/handle-tick-result`,
19
+ * `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`,
20
+ * `ritmo/no-float-timers`, `ritmo/no-brand-cast`.
21
+ * - Every file: `ritmo/handle-runtime-result`,
21
22
  * `ritmo/prefix-descriptor-and-system-names`, `ritmo/use-cell-value`,
22
23
  * `ritmo/no-state-spread`.
23
24
  *
24
25
  * @module oxlint-plugin-ritmo
25
26
  */
26
27
  import { definePlugin } from "@oxlint/plugins";
27
- import handleTickResult from "./rules/handle-tick-result.js";
28
+ import handleRuntimeResult from "./rules/handle-runtime-result.js";
28
29
  import keepSimulationHeadless from "./rules/keep-simulation-headless.js";
30
+ import noBrandCast from "./rules/no-brand-cast.js";
31
+ import noFloatTimers from "./rules/no-float-timers.js";
29
32
  import noInfinityInSimulationData from "./rules/no-infinity-in-simulation-data.js";
30
33
  import noStateSpread from "./rules/no-state-spread.js";
31
34
  import prefixDescriptorAndSystemNames from "./rules/prefix-descriptor-and-system-names.js";
@@ -41,7 +44,9 @@ export default definePlugin({
41
44
  "use-ops-for-math": useOpsForMath,
42
45
  "keep-simulation-headless": keepSimulationHeadless,
43
46
  "no-infinity-in-simulation-data": noInfinityInSimulationData,
44
- "handle-tick-result": handleTickResult,
47
+ "no-float-timers": noFloatTimers,
48
+ "no-brand-cast": noBrandCast,
49
+ "handle-runtime-result": handleRuntimeResult,
45
50
  "prefix-descriptor-and-system-names": prefixDescriptorAndSystemNames,
46
51
  "use-cell-value": useCellValue,
47
52
  "no-state-spread": noStateSpread
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAE9C,OAAO,gBAAgB,MAAM,+BAA+B,CAAA;AAC5D,OAAO,sBAAsB,MAAM,qCAAqC,CAAA;AACxE,OAAO,0BAA0B,MAAM,2CAA2C,CAAA;AAClF,OAAO,aAAa,MAAM,4BAA4B,CAAA;AACtD,OAAO,8BAA8B,MAAM,+CAA+C,CAAA;AAC1F,OAAO,YAAY,MAAM,2BAA2B,CAAA;AACpD,OAAO,eAAe,MAAM,+BAA+B,CAAA;AAC3D,OAAO,aAAa,MAAM,6BAA6B,CAAA;AACvD,OAAO,sBAAsB,MAAM,sCAAsC,CAAA;AAEzE,eAAe,YAAY,CAAC;IAC1B,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;IACvB,KAAK,EAAE;QACL,oBAAoB,EAAE,eAAe;QACrC,2BAA2B,EAAE,sBAAsB;QACnD,kBAAkB,EAAE,aAAa;QACjC,0BAA0B,EAAE,sBAAsB;QAClD,gCAAgC,EAAE,0BAA0B;QAC5D,oBAAoB,EAAE,gBAAgB;QACtC,oCAAoC,EAAE,8BAA8B;QACpE,gBAAgB,EAAE,YAAY;QAC9B,iBAAiB,EAAE,aAAa;KACjC;CACF,CAAC,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAE9C,OAAO,mBAAmB,MAAM,kCAAkC,CAAA;AAClE,OAAO,sBAAsB,MAAM,qCAAqC,CAAA;AACxE,OAAO,WAAW,MAAM,0BAA0B,CAAA;AAClD,OAAO,aAAa,MAAM,4BAA4B,CAAA;AACtD,OAAO,0BAA0B,MAAM,2CAA2C,CAAA;AAClF,OAAO,aAAa,MAAM,4BAA4B,CAAA;AACtD,OAAO,8BAA8B,MAAM,+CAA+C,CAAA;AAC1F,OAAO,YAAY,MAAM,2BAA2B,CAAA;AACpD,OAAO,eAAe,MAAM,+BAA+B,CAAA;AAC3D,OAAO,aAAa,MAAM,6BAA6B,CAAA;AACvD,OAAO,sBAAsB,MAAM,sCAAsC,CAAA;AAEzE,eAAe,YAAY,CAAC;IAC1B,IAAI,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE;IACvB,KAAK,EAAE;QACL,oBAAoB,EAAE,eAAe;QACrC,2BAA2B,EAAE,sBAAsB;QACnD,kBAAkB,EAAE,aAAa;QACjC,0BAA0B,EAAE,sBAAsB;QAClD,gCAAgC,EAAE,0BAA0B;QAC5D,iBAAiB,EAAE,aAAa;QAChC,eAAe,EAAE,WAAW;QAC5B,uBAAuB,EAAE,mBAAmB;QAC5C,oCAAoC,EAAE,8BAA8B;QACpE,gBAAgB,EAAE,YAAY;QAC9B,iBAAiB,EAAE,aAAa;KACjC;CACF,CAAC,CAAA"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The `Result` of `runtime.tick(...)`, `tryTick(...)`, `restore(...)`,
3
+ * `rewind(...)`, `snapshot()`, and `checksum()` is checked: dropping it, or
4
+ * passing it on where any value is accepted, hides the failure.
5
+ */
6
+ declare const _default: import("@oxlint/plugins").Rule;
7
+ export default _default;
8
+ //# sourceMappingURL=handle-runtime-result.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-runtime-result.d.ts","sourceRoot":"","sources":["../../src/rules/handle-runtime-result.ts"],"names":[],"mappings":"AAiCA;;;;GAIG"}
@@ -0,0 +1,102 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+ import { calledMethod, docsUrl, receiverName } from "../internal/ast.js";
3
+ /** The runtime methods that return a `Result`, and whether they take arguments. */
4
+ const methods = new Map([
5
+ ["tick", "arguments"],
6
+ ["tryTick", "arguments"],
7
+ ["restore", "arguments"],
8
+ ["rewind", "arguments"],
9
+ ["snapshot", "none"],
10
+ ["checksum", "none"]
11
+ ]);
12
+ /**
13
+ * Wrappers a result passes through on its way to where it is used: the
14
+ * check looks at where the wrapper goes (`x ?? runtime.snapshot()`,
15
+ * `runtime.snapshot() as unknown`).
16
+ */
17
+ const passesThrough = new Set(["ConditionalExpression", "LogicalExpression", "ParenthesizedExpression", "TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "ChainExpression"]);
18
+ /**
19
+ * Where a result goes unchecked: handed to a function, printed, or put
20
+ * inside another value. A variable, a field, a return, `.ok`, and `void`
21
+ * keep it as a `Result` the code still has to look at.
22
+ */
23
+ const unchecked = new Set(["CallExpression", "NewExpression", "TemplateLiteral", "Property", "ArrayExpression", "SpreadElement", "BinaryExpression", "JSXExpressionContainer"]);
24
+ /**
25
+ * The `Result` of `runtime.tick(...)`, `tryTick(...)`, `restore(...)`,
26
+ * `rewind(...)`, `snapshot()`, and `checksum()` is checked: dropping it, or
27
+ * passing it on where any value is accepted, hides the failure.
28
+ */
29
+ export default defineRule({
30
+ meta: {
31
+ type: "problem",
32
+ docs: {
33
+ description: "Check the Result of runtime.tick, tryTick, restore, rewind, snapshot, and checksum instead of dropping it or passing it on unchecked.",
34
+ url: docsUrl("handle-runtime-result")
35
+ },
36
+ messages: {
37
+ tick: "The result of `{{call}}(...)` is dropped. A system that fails stops the tick and returns the failure here, so it goes unnoticed and the world is left half-updated. Check it: `const ran = {{call}}(...); if (!ran.ok) ...` (`ran.error` names the system and why). Write `void {{call}}(...)` to ignore it on purpose.",
38
+ restore: "The result of `{{call}}(...)` is dropped. A save that fails to load leaves the previous world in place, unnoticed. Check it: `const restored = {{call}}(data); if (!restored.ok) ...` (`restored.error` says what was invalid). Write `void {{call}}(...)` to ignore it on purpose.",
39
+ rewind: "The result of `{{call}}(...)` is dropped. A checkpoint the runtime let go of (older than its window, or taken before a rewind to an older one or a restore) changes nothing, so the ticks run next are run on top of the present instead of again, unnoticed. Check it: `const rewound = {{call}}(checkpoint); if (!rewound.ok) ...` (`rewound.error` says why), and resynchronize, for example by loading a peer's save. Write `void {{call}}(...)` to ignore it on purpose.",
40
+ dropped: "The result of `{{call}}()` is dropped, so the call does nothing. Read it: `const saved = {{call}}(); if (saved.ok) ...`.",
41
+ unchecked: "`{{call}}(...)` returns a `Result`, and it is passed on unchecked: code that accepts any value (a save, a log, `JSON.stringify`) gets the `{ ok, value }` wrapper instead of the value, and a failure goes unnoticed. Check it first: `const result = {{call}}(...); if (result.ok) use(result.value)`. A helper that takes the `Result` itself gets it once it is named: `const result = {{call}}(...); helper(result)`."
42
+ },
43
+ schema: [
44
+ {
45
+ type: "object",
46
+ properties: {
47
+ runtimePattern: {
48
+ type: "string",
49
+ description: "A regular expression (case-insensitive) the receiver's name must match to be treated as a Ritmo runtime. Defaults to `runtime$`."
50
+ }
51
+ },
52
+ additionalProperties: false
53
+ }
54
+ ]
55
+ },
56
+ create(context) {
57
+ const options = (context.options[0] ?? {});
58
+ const runtime = new RegExp(options.runtimePattern ?? "runtime$", "i");
59
+ return {
60
+ CallExpression(call) {
61
+ if (call.callee.type !== "MemberExpression")
62
+ return;
63
+ const method = calledMethod(call);
64
+ const takes = method === undefined ? undefined : methods.get(method);
65
+ if (takes === undefined)
66
+ return;
67
+ // `run.tick()` and `replay.rewind()` without arguments are other libraries' methods.
68
+ if (takes === "arguments" && call.arguments.length === 0)
69
+ return;
70
+ if (takes === "none" && call.arguments.length > 0)
71
+ return;
72
+ const receiver = receiverName(call.callee.object);
73
+ if (receiver === undefined || !runtime.test(receiver))
74
+ return;
75
+ const data = { call: context.sourceCode.getText(call.callee) };
76
+ let node = call;
77
+ let parent = node.parent;
78
+ while (parent != null && passesThrough.has(parent.type)) {
79
+ node = parent;
80
+ parent = node.parent;
81
+ }
82
+ if (parent == null)
83
+ return;
84
+ if (parent.type === "ExpressionStatement") {
85
+ const messageId = takes === "none" ? "dropped" : method === "restore" || method === "rewind" ? method : "tick";
86
+ context.report({ node: parent, messageId, data });
87
+ return;
88
+ }
89
+ if (!unchecked.has(parent.type))
90
+ return;
91
+ // The callee of a call is a method read on the result, not a hand-off (`runtime.snapshot().toString()` would not compile anyway).
92
+ if (parent.type === "CallExpression" && parent.callee === node)
93
+ return;
94
+ // A property key is not a use of the value.
95
+ if (parent.type === "Property" && parent.value !== node)
96
+ return;
97
+ context.report({ node: call, messageId: "unchecked", data });
98
+ }
99
+ };
100
+ }
101
+ });
102
+ //# sourceMappingURL=handle-runtime-result.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-runtime-result.js","sourceRoot":"","sources":["../../src/rules/handle-runtime-result.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAG5C,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAMxE,mFAAmF;AACnF,MAAM,OAAO,GAAG,IAAI,GAAG,CAA+B;IACpD,CAAC,MAAM,EAAE,WAAW,CAAC;IACrB,CAAC,SAAS,EAAE,WAAW,CAAC;IACxB,CAAC,SAAS,EAAE,WAAW,CAAC;IACxB,CAAC,QAAQ,EAAE,WAAW,CAAC;IACvB,CAAC,UAAU,EAAE,MAAM,CAAC;IACpB,CAAC,UAAU,EAAE,MAAM,CAAC;CACrB,CAAC,CAAA;AAEF;;;;GAIG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,uBAAuB,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,qBAAqB,EAAE,iBAAiB,CAAC,CAAC,CAAA;AAE7L;;;;GAIG;AACH,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,gBAAgB,EAAE,eAAe,EAAE,i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AAI,KAAK,gBAAgB,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI;oBAAE,OAAM;gBACtE,4CAA4C;gBAC5C,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,IAAI,MAAM,CAAC,KAAK,KAAK,IAAI;oBAAE,OAAM;gBAC/D,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAA;YAC9D,CAAC;SACF,CAAA;IACH,CAAC;CACF,CAAC,CAAA"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Simulation code never casts a value to a branded type: a brand stands for a
3
+ * check, and the cast claims it without running it.
4
+ */
5
+ declare const _default: import("@oxlint/plugins").Rule;
6
+ export default _default;
7
+ //# sourceMappingURL=no-brand-cast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-brand-cast.d.ts","sourceRoot":"","sources":["../../src/rules/no-brand-cast.ts"],"names":[],"mappings":"AAmDA;;;GAGG"}