@typeonce/oxlint-plugin-ritmo 0.22.0 → 0.24.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.
- package/CHANGELOG.md +82 -0
- package/README.md +88 -22
- package/dist/index.js +13 -6
- package/dist/index.js.map +1 -1
- package/dist/internal/ast.d.ts +43 -0
- package/dist/internal/ast.d.ts.map +1 -1
- package/dist/internal/ast.js +127 -0
- package/dist/internal/ast.js.map +1 -1
- package/dist/rules/handle-runtime-result.d.ts.map +1 -1
- package/dist/rules/handle-runtime-result.js +82 -10
- package/dist/rules/handle-runtime-result.js.map +1 -1
- package/dist/rules/keep-simulation-headless.d.ts +3 -3
- package/dist/rules/keep-simulation-headless.d.ts.map +1 -1
- package/dist/rules/keep-simulation-headless.js +30 -15
- package/dist/rules/keep-simulation-headless.js.map +1 -1
- package/dist/rules/no-float-timers.d.ts +2 -2
- package/dist/rules/no-float-timers.d.ts.map +1 -1
- package/dist/rules/no-float-timers.js +133 -20
- package/dist/rules/no-float-timers.js.map +1 -1
- package/dist/rules/no-infinity-in-simulation-data.d.ts.map +1 -1
- package/dist/rules/no-infinity-in-simulation-data.js +134 -10
- package/dist/rules/no-infinity-in-simulation-data.js.map +1 -1
- package/dist/rules/no-kept-query-values.d.ts +9 -0
- package/dist/rules/no-kept-query-values.d.ts.map +1 -0
- package/dist/rules/no-kept-query-values.js +375 -0
- package/dist/rules/no-kept-query-values.js.map +1 -0
- package/dist/rules/no-state-spread.d.ts.map +1 -1
- package/dist/rules/no-state-spread.js +137 -14
- package/dist/rules/no-state-spread.js.map +1 -1
- package/dist/rules/use-clock-for-time.d.ts.map +1 -1
- package/dist/rules/use-clock-for-time.js +31 -15
- package/dist/rules/use-clock-for-time.js.map +1 -1
- package/dist/rules/use-keyboard-for-game-keys.d.ts +9 -0
- package/dist/rules/use-keyboard-for-game-keys.d.ts.map +1 -0
- package/dist/rules/use-keyboard-for-game-keys.js +81 -0
- package/dist/rules/use-keyboard-for-game-keys.js.map +1 -0
- package/dist/rules/use-ops-for-math.d.ts.map +1 -1
- package/dist/rules/use-ops-for-math.js +11 -7
- package/dist/rules/use-ops-for-math.js.map +1 -1
- package/dist/rules/use-random-for-randomness.d.ts.map +1 -1
- package/dist/rules/use-random-for-randomness.js +11 -13
- package/dist/rules/use-random-for-randomness.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +13 -6
- package/src/internal/ast.ts +125 -0
- package/src/rules/handle-runtime-result.ts +86 -8
- package/src/rules/keep-simulation-headless.ts +32 -12
- package/src/rules/no-float-timers.ts +124 -19
- package/src/rules/no-infinity-in-simulation-data.ts +133 -10
- package/src/rules/no-kept-query-values.ts +353 -0
- package/src/rules/no-state-spread.ts +140 -12
- package/src/rules/use-clock-for-time.ts +31 -14
- package/src/rules/use-keyboard-for-game-keys.ts +85 -0
- package/src/rules/use-ops-for-math.ts +10 -10
- package/src/rules/use-random-for-randomness.ts +9 -11
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,87 @@
|
|
|
1
1
|
# @typeonce/oxlint-plugin-ritmo
|
|
2
2
|
|
|
3
|
+
## 0.24.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 838358f: New rule `ritmo/use-keyboard-for-game-keys`, for every file: reports a `keydown`, `keyup`, or `keypress` listener on `window`, `document`, `document.body`, or `document.documentElement` whose function calls `preventDefault()` on its event. Such a listener takes Enter, Space, and the arrows from a focused button, link, or open dialog, so the page's controls cannot be used by keyboard. Bind the keys with `Keyboard.actions(window, bindings)` and read their `pressed` edges (`Keyboard.presses(window)` for any key), or listen on the UI element the key is for. Turn it on in `.oxlintrc.json`:
|
|
8
|
+
|
|
9
|
+
```diff
|
|
10
|
+
"rules": {
|
|
11
|
+
+ "ritmo/use-keyboard-for-game-keys": "error"
|
|
12
|
+
}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## 0.23.0
|
|
16
|
+
|
|
17
|
+
### Minor Changes
|
|
18
|
+
|
|
19
|
+
- 7ac13e9: `ritmo/no-float-timers` knows more names and shapes of a step's length, and reports `x - dt` only where it is written back, so it counts across ticks.
|
|
20
|
+
|
|
21
|
+
Newly reported, with the rule's message saying to store a `Clock.deadline` and check `Clock.reached`:
|
|
22
|
+
|
|
23
|
+
- other names: `x -= fixedDt`, `x -= dtSeconds`, `x -= STEP_SECONDS` (any case, with or without `_`), `x -= time.delta`, `x = x - step.seconds`, and a bare `x -= delta`;
|
|
24
|
+
- other shapes: `x -= 1 / 60`, `x -= dt * 1`, `elapsedMs += dt * 1000`, `x -= Math.min(dt, 0.1)`, and a `const` that holds a step's length (`const tick = frame.dt; timer -= tick`).
|
|
25
|
+
|
|
26
|
+
No longer reported: `x - dt` / `x + dt` whose value is not written back where `x` came from, such as a look-ahead (`const until = horizon + dt`) or a test (`if (accumulator - dt >= 0)`). Written back means a target of the same name (`x = x - dt`, `let cooldown = Math.max(0, state.cooldown - dt)`, `{ left: buff.left - dt }`, `resources.timer.set(timer - dt)`) or an `update` callback's result (`resources.timer.update((left) => left - dt)`); those are still reported.
|
|
27
|
+
- 99008ef: `ritmo/use-clock-for-time`, `ritmo/use-random-for-randomness`, `ritmo/use-ops-for-math`, and `ritmo/keep-simulation-headless` find a global however the file reaches it, so simulation code that passed before can now be reported. Newly reported, with the rule's existing message saying what to write instead:
|
|
28
|
+
|
|
29
|
+
- through a global object: `globalThis.Math.random()`, `globalThis.crypto.getRandomValues(bytes)`, `globalThis.Date.now()`, `globalThis.performance.now()`, `globalThis.setTimeout(...)`, `self.Math.sin(x)` (fixed to `Ops.sin(x)` like `Math.sin(x)`), `globalThis.localStorage`, `self.innerWidth`;
|
|
30
|
+
- through a `const` that holds the global: `const roll = Math; roll.random()`, `const wait = setTimeout; wait(f, 10)`, `const D = Date; new D()`;
|
|
31
|
+
- destructured: `const { random } = Math`, `const { randomUUID } = crypto`, `const { now } = Date`, `const { now } = performance`, `const { localStorage } = globalThis`, `const { Math: M } = globalThis` (an alias of Math, like `const M = Math`);
|
|
32
|
+
- by `use-clock-for-time`, globals it did not list: `setImmediate(...)`, `process.hrtime()` and `process.hrtime.bigint()`, `performance.timeOrigin`, `performance.mark(...)`, `Temporal.Now`, `Date()` called without `new`, and `getTimezoneOffset()`;
|
|
33
|
+
- by `keep-simulation-headless`, sound: `new Audio(...)` and `new AudioContext()`. Publish what happened as an event and play the sound from a render or host system that reads it (`Game.System.readEvent(Hit)`) and requests the game's audio as a service (`Game.System.service(Audio)`); under a netcode session, from `session.events(Hit)`.
|
|
34
|
+
|
|
35
|
+
Locals, parameters, and imports with these names, fields of other objects (`config.Date.now()`), and types are still not reported. Host code inside a simulation folder that reads one on purpose takes a disable comment with its reason: `// oxlint-disable-next-line ritmo/use-clock-for-time -- this test is the host`.
|
|
36
|
+
- 9baf436: `ritmo/no-infinity-in-simulation-data` reports Infinity and NaN in more of the data a world stores, and no longer reports local scratch.
|
|
37
|
+
|
|
38
|
+
Newly reported, with the message saying to use `null` and a nullable number schema:
|
|
39
|
+
|
|
40
|
+
- `1 / 0` and `Math.min()` / `Math.max()` of nothing: `{ since: 1 / 0 }`, `{ since: Math.min() }`;
|
|
41
|
+
- an element of an array literal: `data.range.set(entity, [0, Infinity])`;
|
|
42
|
+
- a call given one, whose result is stored: `{ dash: make(Infinity) }` (`Math.*` and `Number.*` calls are not reported);
|
|
43
|
+
- a `const` declared as one: `const LIMIT = Infinity`, then `{ max: LIMIT }`;
|
|
44
|
+
- a search seed stored unchecked: `{ distance: best }` after `let best = Infinity`. Store it checked: `{ distance: Number.isFinite(best) ? best : null }`. A comparison with `Infinity` or a `Number.isFinite(best)` anywhere in the file counts as the check.
|
|
45
|
+
|
|
46
|
+
No longer reported: a literal search seed in a `let` (`let nearest = { distance: Infinity, id: -1 }`), a fallback in a function whose fields are only compared (`const hit = sweep ?? { time: Infinity }; if (hit.time < limit) ...`), and values a `for...of` tries (`for (const size of [0, Infinity])`).
|
|
47
|
+
- 56d6c13: `ritmo/no-kept-query-values` follows entities and `data` through more forms. Newly reported, with the message saying to keep `entity.id` and resolve it with `queries.x.get(id)`, or to keep plain values from `queries.x.rows()`:
|
|
48
|
+
|
|
49
|
+
- entities copied or picked into a kept value: `local.list = Array.from(queries.x.each())`, `.map((e) => e)` and `.reduce((best, e) => ...)` results kept in `local` or a module variable, `const [first] = queries.x.each()` then `local.target = first`;
|
|
50
|
+
- `Object.assign(local, { target: queries.x.each()[0] })`;
|
|
51
|
+
- a context destructured or renamed: `({ queries: q })` then `q.x.data`, `({ queries: { x } })` then `x.data`, `({ local: kept })` then `kept.target = ...`, and `(ctx) => { ctx.local.target = ctx.queries.x.each()[0] }`;
|
|
52
|
+
- a system function declared apart and passed to `Game.System(...)` or `Game.Inspector(...)` by name in the same file, keeping an entity in a module variable (`cache.set(1, entity)`).
|
|
53
|
+
|
|
54
|
+
Ids stay unreported in each form (`Array.from(queries.x.each(), (e) => e.id)`, `first?.id`).
|
|
55
|
+
- 7e416f5: New rule `ritmo/no-kept-query-values`: reports an entity from `queries.x.each()` or a query's `data` kept past its run, in `local` state (directly, in a literal, pushed or set into a collection there, or captured by a closure stored there) or in a variable outside the `Game.System` / `Game.Inspector` callback. Kept data throws in the next run, and a kept entity is not checked against its query again. The report says to keep `entity.id` and resolve it with `queries.x.get(id)`, or to keep plain values from `queries.x.rows()`. Add it to `.oxlintrc.json` for every file:
|
|
56
|
+
|
|
57
|
+
```jsonc
|
|
58
|
+
"ritmo/no-kept-query-values": "error"
|
|
59
|
+
```
|
|
60
|
+
- 107196f: `ritmo/handle-runtime-result` finds more dropped and misread results. Newly reported:
|
|
61
|
+
|
|
62
|
+
- a result an arrow returns to a caller that drops it: `updates.forEach((u) => runtime.tick(u))`, `requestAnimationFrame(() => runtime.tick(update))`, also `addEventListener`, `requestIdleCallback`, `setTimeout`, `setInterval`, `setImmediate`, and `queueMicrotask`. Check it in a block body, or write `() => void runtime.tick(update)` to ignore it on purpose;
|
|
63
|
+
- a result left out of a sequence's value: `runtime.tick(update), draw()`;
|
|
64
|
+
- a result tested as a condition, which is always true since a `Result` is an object: `if (!runtime.tick(update))`, `if (runtime.restore(save))`, `runtime.rewind(checkpoint) ? a : b`, the left of `&&` / `||`. Test `.ok` instead: `if (!runtime.tick(update).ok)`;
|
|
65
|
+
- a method destructured from a runtime: `const { tick } = runtime`, then `tick(update)`;
|
|
66
|
+
- a runtime of any name made in the same file: `made.value.tick(update)` and `game.tick(update)` after `const made = Game.Runtime.make(...)` and `const game = made.value`.
|
|
67
|
+
- c3bba11: `ritmo/no-state-spread` reports a `_tag` set over a spread only when the file shows the spread value is a state, and reads more ways of writing the same re-tag.
|
|
68
|
+
|
|
69
|
+
A spread value is a state when it is read from a state machine (`machines.x.get()`, `nextMachines.x.getPending()`) or from an entity state's slot the same function moves (`data.contact.get(entity)` next to `data.contact.transition(...)` or `data.contact.update(entity, { state, data })`), directly or through the variable holding it, or when the same function reads its `_tag` (`if (body._tag === "ground")`, `switch (state._tag)`, `const { _tag } = previous`).
|
|
70
|
+
|
|
71
|
+
Newly reported, with the message saying to move with `data.x.transition(entity, { from, to, data })` or `nextMachines.x.transition({ from, to, data })`, or to write the new state's fields out:
|
|
72
|
+
|
|
73
|
+
- `Object.assign({}, ground, { _tag: "air" })`;
|
|
74
|
+
- `{ ...ground, ...{ _tag: "air" } }`;
|
|
75
|
+
- `const { _tag, ...rest } = ground`, then `{ _tag: "air", ...rest }`.
|
|
76
|
+
|
|
77
|
+
No longer reported: a spread value nothing in the file shows to be a state, such as a plain value tagged for an event (`events.explosion.emit({ ...position, _tag: "Explosion" })`). The compiler already rejects an `update` callback that changes `_tag` and `set` on a state declared with `transitions`.
|
|
78
|
+
|
|
79
|
+
### Patch Changes
|
|
80
|
+
|
|
81
|
+
- 51efba5: `ritmo/no-state-spread` names `nextMachines.mode.transition({ from, to, data })` as the way to move a state machine, the compare-and-set move state machines now have.
|
|
82
|
+
- d2970e8: The `handle-runtime-result` docs say why `runtime.snapshot()` and `runtime.checksum()` return a `Result`: a schema's `encode` may reject a value, and a save cannot hold commands still queued. No change for games.
|
|
83
|
+
- 8db5972: The README's `ritmo/no-brand-cast` example compiles: the random resource is `Descriptor.ConstructedResource(Random.codec)("Game/Rng")`, given `Random.seed(1)` in `Game.Runtime.make`, and the reported line is the raw cast `1 as Random.State`. `Random.resource` never existed.
|
|
84
|
+
|
|
3
85
|
## 0.22.0
|
|
4
86
|
|
|
5
87
|
No changes in this release.
|
package/README.md
CHANGED
|
@@ -4,12 +4,14 @@
|
|
|
4
4
|
|
|
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
|
-
- simulation code that reads the wall clock, `Math.random`, engine-dependent math, or the page;
|
|
7
|
+
- simulation code that reads the wall clock, `Math.random`, engine-dependent math, or the page, or plays sound;
|
|
8
8
|
- timers counted in floats;
|
|
9
9
|
- data that cannot be saved;
|
|
10
10
|
- casts that claim a brand's check without running it;
|
|
11
11
|
- state values that keep a previous state's fields;
|
|
12
|
-
-
|
|
12
|
+
- query entities and data kept past their run;
|
|
13
|
+
- runtime results that are dropped;
|
|
14
|
+
- host key listeners that take keys from the page's buttons, links, and dialogs.
|
|
13
15
|
|
|
14
16
|
Every report says what goes wrong and which Ritmo API to use instead.
|
|
15
17
|
|
|
@@ -29,7 +31,9 @@ Register the plugin and turn the rules on in `.oxlintrc.json`. The simulation ru
|
|
|
29
31
|
"rules": {
|
|
30
32
|
"ritmo/handle-runtime-result": "error",
|
|
31
33
|
"ritmo/prefix-descriptor-and-system-names": "error",
|
|
32
|
-
"ritmo/no-state-spread": "error"
|
|
34
|
+
"ritmo/no-state-spread": "error",
|
|
35
|
+
"ritmo/no-kept-query-values": "error",
|
|
36
|
+
"ritmo/use-keyboard-for-game-keys": "error"
|
|
33
37
|
},
|
|
34
38
|
"overrides": [
|
|
35
39
|
{
|
|
@@ -60,19 +64,23 @@ const started = performance.now()
|
|
|
60
64
|
|
|
61
65
|
| Rule | Where | Catches | Use instead |
|
|
62
66
|
|---|---|---|---|
|
|
63
|
-
| [`use-clock-for-time`](#ritmouse-clock-for-time) | simulation | `Date.now()`, `performance.now()`, `new Date()`, timers | `Clock` |
|
|
67
|
+
| [`use-clock-for-time`](#ritmouse-clock-for-time) | simulation | `Date.now()`, `performance.now()`, `new Date()`, `Temporal.Now`, timers | `Clock` |
|
|
64
68
|
| [`use-random-for-randomness`](#ritmouse-random-for-randomness) | simulation | `Math.random()`, `crypto` randomness | `Random.draw(resources.rng)` |
|
|
65
69
|
| [`use-ops-for-math`](#ritmouse-ops-for-math) | simulation | `Math.sin`, `Math.hypot`, `a ** b`, `const { sin } = Math`, ... | `Ops` |
|
|
66
|
-
| [`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 |
|
|
67
|
-
| [`no-infinity-in-simulation-data`](#ritmono-infinity-in-simulation-data) | simulation | `Infinity` / `NaN` in object literals | `null` |
|
|
68
|
-
| [`no-float-timers`](#ritmono-float-timers) | simulation | `timer -= dt`, `cooldown - time.dt` | `Clock.deadline` / `Clock.reached` |
|
|
70
|
+
| [`keep-simulation-headless`](#ritmokeep-simulation-headless) | simulation | page globals, host I/O, audio, renderer imports | input and data from the host, drawing and sound in a render schedule |
|
|
71
|
+
| [`no-infinity-in-simulation-data`](#ritmono-infinity-in-simulation-data) | simulation | `Infinity` / `NaN` in object and array literals | `null` |
|
|
72
|
+
| [`no-float-timers`](#ritmono-float-timers) | simulation | `timer -= dt`, `cooldown = cooldown - time.dt` | `Clock.deadline` / `Clock.reached` |
|
|
69
73
|
| [`no-brand-cast`](#ritmono-brand-cast) | simulation | `raw as UserId`, `1 as Random.State` | the schema or constructor that brands it |
|
|
70
74
|
| [`handle-runtime-result`](#ritmohandle-runtime-result) | everywhere | a dropped or unchecked `runtime.tick(...)` / `restore(...)` / `rewind(...)` / `snapshot()` / `checksum()` result | check `.ok` |
|
|
71
75
|
| [`prefix-descriptor-and-system-names`](#ritmoprefix-descriptor-and-system-names) | everywhere | `"Position"`, `Game.System("Move", ...)` | `"Game/Position"` |
|
|
72
|
-
| [`no-state-spread`](#ritmono-state-spread) | everywhere | `{ ...ground, _tag: "air", vy }` | `data.state.transition(entity, { from, to, data })`, `nextMachines.x.
|
|
76
|
+
| [`no-state-spread`](#ritmono-state-spread) | everywhere | `{ ...ground, _tag: "air", vy }` | `data.state.transition(entity, { from, to, data })`, `nextMachines.x.transition({ from, to, data })`, or the new state's fields written out |
|
|
77
|
+
| [`no-kept-query-values`](#ritmono-kept-query-values) | everywhere | `local.target = queries.x.each()[0]`, `local.slots = queries.x.data` | `entity.id` and `queries.x.get(id)`, or plain values from `queries.x.rows()` |
|
|
78
|
+
| [`use-keyboard-for-game-keys`](#ritmouse-keyboard-for-game-keys) | everywhere | `window.addEventListener("keydown", (e) => { ...; e.preventDefault() })` | `Keyboard.actions(window, bindings)` and its `pressed` edges, or a listener on the UI element |
|
|
73
79
|
|
|
74
80
|
## Simulation rules
|
|
75
81
|
|
|
82
|
+
The four rules that read globals (`use-clock-for-time`, `use-random-for-randomness`, `use-ops-for-math`, `keep-simulation-headless`) find a global however the file reaches it: by name, as a member of `globalThis`, `self`, or `window` (`globalThis.Date.now()`, `self.Math.sin(x)`), through a `const` that holds it (`const M = Math; M.random()`), or destructured (`const { now } = Date`, `const { Math: { random } } = globalThis`), reported once where the global is read. A local, parameter, or import of the same name, a field of another object (`config.Date.now()`), and a type (`let at: Date`) are not the global. A value passed through a function or another module is not followed.
|
|
83
|
+
|
|
76
84
|
### `ritmo/use-clock-for-time`
|
|
77
85
|
|
|
78
86
|
The wall clock differs on every run, so a simulation that reads it cannot replay, and a timer fires between ticks at a moment no replay can reproduce.
|
|
@@ -88,7 +96,7 @@ const due = Clock.deadline(time, Clock.duration(step, 0.5)) // store
|
|
|
88
96
|
if (Clock.every(time, waveEvery)) spawnWave() // repeats
|
|
89
97
|
```
|
|
90
98
|
|
|
91
|
-
Catches `Date.now()`, `performance.now()`, `new Date()` with no arguments (`new Date(timestamp)` only formats a value it was given), and `setTimeout`, `setInterval`, `requestAnimationFrame`, `requestIdleCallback`, and `queueMicrotask`. When a rule needs today's date (a daily reward), read it in host code and pass it in with `runtime.send(...)` or a resource, so the replay records it.
|
|
99
|
+
Catches `Date.now()`, `performance.now()`, `performance.timeOrigin`, `performance.mark()`, `process.hrtime()` (and `.bigint()`), `Temporal.Now`, `new Date()` with no arguments (`new Date(timestamp)` only formats a value it was given), `Date()` called without `new` (the current time as a string, whatever its arguments), `getTimezoneOffset()` on any date (the host's time zone), and `setTimeout`, `setInterval`, `setImmediate`, `requestAnimationFrame`, `requestIdleCallback`, and `queueMicrotask`. When a rule needs today's date (a daily reward), read it in host code and pass it in with `runtime.send(...)` or a resource, so the replay records it.
|
|
92
100
|
|
|
93
101
|
### `ritmo/use-random-for-randomness`
|
|
94
102
|
|
|
@@ -103,7 +111,7 @@ const crit = random.next() < 0.1
|
|
|
103
111
|
const kind = random.pick(kinds)
|
|
104
112
|
```
|
|
105
113
|
|
|
106
|
-
Catches `Math.random()`, `crypto.getRandomValues()`, and `crypto.randomUUID()
|
|
114
|
+
Catches `Math.random()`, `crypto.getRandomValues()`, and `crypto.randomUUID()`, also destructured (`const { random } = Math`). For an id, the world already has one: use the entity's id (`entity.id`, kept as `Game.Entity.handle(...)`) or a counter in a resource. An id that must be unique across devices or runs (an account item, a save slot) is made in host code, where `crypto.randomUUID()` is fine, and passed in with `runtime.send(...)`.
|
|
107
115
|
|
|
108
116
|
### `ritmo/use-ops-for-math`
|
|
109
117
|
|
|
@@ -126,7 +134,7 @@ Before porting a formula to `Ops`, look for the helper that names it: `Angle.wra
|
|
|
126
134
|
|
|
127
135
|
`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).
|
|
128
136
|
|
|
129
|
-
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.
|
|
137
|
+
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` or `self.Math` used the same ways (`const { Math: M } = globalThis` too). `self.Math.sin(x)` is reported and fixed like `Math.sin(x)`. Call `Ops.sin` directly, and read exact members by name. A local named `Math` is not the global and is not reported.
|
|
130
138
|
|
|
131
139
|
### `ritmo/keep-simulation-headless`
|
|
132
140
|
|
|
@@ -136,6 +144,7 @@ The simulation runs in tests, bots, replays, and on servers, where there is no p
|
|
|
136
144
|
|---|---|
|
|
137
145
|
| Page globals: `window`, `document`, `navigator`, `matchMedia`, ... | Capture input in the host with `Keyboard`, `Gamepad`, `Pointer`, or `Touch` (merged with `Controls`) from `@typeonce/ritmo-browser` and `InputCapture` into a resource that systems read. Pass page state (size, settings) in with `runtime.send(...)` or a resource. |
|
|
138
146
|
| Host I/O: `localStorage`, `fetch`, `location`, ... | Do the I/O in host code and pass the result in with `runtime.send(...)` or a resource. Save and load the world in the host with `runtime.snapshot()` and `runtime.restore(...)`. |
|
|
147
|
+
| Sound: `Audio`, `AudioContext` | Publish what happened as an event (`Game.System.writeEvent(Hit)`), and play the sound from a render or host system that reads it (`Game.System.readEvent(Hit)`) and requests the game's audio as a service (`Game.System.service(Audio)`), so a headless test can provide one that records. Under a netcode session, play it from `session.events(Hit)`, so a rolled-back tick does not play it twice. |
|
|
139
148
|
| Connections to other peers: `WebSocket`, `RTCPeerConnection`, `RTCDataChannel` | For online play, run the simulation under a [`@typeonce/ritmo-netcode`](https://github.com/typeonce-dev/ritmo/blob/main/packages/netcode/README.md) session: host code opens the connection and wraps it in a link, and remote input reaches the simulation through `Netcode.seats`, never `runtime.send(...)`. |
|
|
140
149
|
| Renderer and UI imports, types included: `pixi.js`, `three`, `@typeonce/ritmo-render`, `react`, `preact`, ... | Draw from a render schedule in render code: mirror entities into nodes with `RenderSync` and a `NodeRegistry` from `@typeonce/ritmo-render`, and declare renderer services (a node registry) and their types there; renderer nodes stay in the registry, never in components. The schema and simulation systems name no renderer type, so another renderer can replace this one. |
|
|
141
150
|
|
|
@@ -156,7 +165,9 @@ dash: { remaining: 0, since: null } // since: numbe
|
|
|
156
165
|
{ timer: null } // timer: { remaining: number; duration: number } | null
|
|
157
166
|
```
|
|
158
167
|
|
|
159
|
-
Catches `Infinity`, `-Infinity`, `NaN`,
|
|
168
|
+
Catches `Infinity`, `-Infinity`, `NaN`, `Number.POSITIVE_INFINITY` / `NEGATIVE_INFINITY` / `NaN`, `1 / 0`, and `Math.min()` / `Math.max()` of nothing, as a property value of an object literal or an element of an array literal in simulation files, including values built in helpers before they are spawned. In the same places it also catches a call given one of them (`{ dash: make(Infinity) }`; `Math.*` and `Number.*` calls give finite numbers back), a `const` declared as one (`{ max: LIMIT }`), and a search seed stored unchecked (`{ distance: best }` after `let best = Infinity`), which stays Infinity when the search finds nothing; comparing the seed with `Infinity` or passing it to `Number.isFinite` anywhere in the file counts as the check.
|
|
169
|
+
|
|
170
|
+
Local scratch is not reported: a search seed in a `let`, a literal one too (`let nearest = { distance: Infinity, id: -1 }`); a fallback in a function whose fields are only compared (`const hit = sweep ?? { time: Infinity }`, then `hit.time < limit`); and values a `for...of` tries one by one (`for (const size of [0, Infinity])`). A value passed straight to a write (`resources.best.set(best)`) is not checked.
|
|
160
171
|
|
|
161
172
|
### `ritmo/no-float-timers`
|
|
162
173
|
|
|
@@ -189,7 +200,14 @@ data.enemy.set(entity, { attackAt: Clock.deadline(gameplay, windup) })
|
|
|
189
200
|
|
|
190
201
|
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.
|
|
191
202
|
|
|
192
|
-
Catches a
|
|
203
|
+
Catches a value updated by a step's length in seconds, so it counts across ticks: `x -= dt` and `x += dt`, and `x - dt` / `x + dt` written back where `x` came from: to a target of the same name (`x = x - dt`, `let cooldown = Math.max(0, state.cooldown - dt)`, `{ left: buff.left - dt }`, `resources.timer.set(timer - dt)`), or as an `update` callback's result (`resources.timer.update((left) => left - dt)`).
|
|
204
|
+
|
|
205
|
+
A step's length is:
|
|
206
|
+
- a local, a field (`time.dt`), or a resource read (`resources.deltaTime.get()`) named `dt`, `deltaTime`, `deltaSeconds`, `dtSeconds`, `fixedDt`, `fixedDelta`, `fixedDeltaTime`, `fixedDeltaSeconds`, `fixedStep`, `stepSeconds`, `fixedStepSeconds`, `timeStep`, `fixedTimeStep`, `secondsPerStep`, `secondsPerTick`, `tickSeconds`, or `frameSeconds`, in any case and with or without `_` (`STEP_SECONDS`);
|
|
207
|
+
- `delta` of `time`, `clock`, `frame`, `tick`, or `step`, and `seconds` of `frame`, `tick`, or `step` (`step.seconds`); a bare `delta` only when subtracted (`x -= delta`);
|
|
208
|
+
- `1 / 60` (one over a whole number), one of the above scaled by a number (`dt * 1000`) or clamped (`Math.min(dt, 0.1)`), or a `const` that holds one.
|
|
209
|
+
|
|
210
|
+
Not reported: a rate scaled by `dt` (`position.x += velocity.x * dt`, integration), a step's length added and kept elsewhere (`const until = horizon + dt`, `if (accumulator - dt >= 0)`), a count of whole steps (`cooldown - 1`), and a `delta` that is not time (`pending[axis] += delta`, `pointer.delta`).
|
|
193
211
|
|
|
194
212
|
### `ritmo/no-brand-cast`
|
|
195
213
|
|
|
@@ -199,11 +217,12 @@ A branded type (`UserId`, `Random.State`, `Clock.Deadline<60>`) stands for a che
|
|
|
199
217
|
const UserId = z.string().uuid().brand("UserId")
|
|
200
218
|
type UserId = z.infer<typeof UserId>
|
|
201
219
|
const id = raw as UserId // reported
|
|
202
|
-
const
|
|
220
|
+
const Rng = Descriptor.ConstructedResource(Random.codec)("Game/Rng")
|
|
221
|
+
const made = Game.Runtime.make({ services, resources: { Rng: 1 as Random.State } }) // reported
|
|
203
222
|
|
|
204
223
|
// instead
|
|
205
224
|
const id = UserId.parse(raw) // Effect: Schema.decodeUnknownSync(UserId)(raw)
|
|
206
|
-
const
|
|
225
|
+
const made = Game.Runtime.make({ services, resources: { Rng: Random.seed(1) } })
|
|
207
226
|
```
|
|
208
227
|
|
|
209
228
|
Oxlint has no type information, so the rule reads the brand from the code: a cast (`x as T` or `<T>x`) to
|
|
@@ -218,11 +237,12 @@ Make the value through its check: decode at the boundary with the game's schema,
|
|
|
218
237
|
|
|
219
238
|
### `ritmo/handle-runtime-result`
|
|
220
239
|
|
|
221
|
-
`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.
|
|
240
|
+
`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, and a save cannot hold commands still queued. 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.
|
|
222
241
|
|
|
223
242
|
```ts
|
|
224
243
|
runtime.tick(update) // reported
|
|
225
244
|
runtime.restore(save) // reported
|
|
245
|
+
if (!runtime.restore(save)) showLoadError() // reported: a Result is an object, always true
|
|
226
246
|
runtime.rewind(checkpoint) // reported
|
|
227
247
|
persist(runtime.snapshot()) // reported
|
|
228
248
|
log(`hash ${runtime.checksum()}`) // reported
|
|
@@ -239,7 +259,9 @@ if (saved.ok) persist(saved.value)
|
|
|
239
259
|
void runtime.tick(render) // ignored on purpose
|
|
240
260
|
```
|
|
241
261
|
|
|
242
|
-
|
|
262
|
+
A runtime is a receiver named like one (`runtime`, `game.runtime`, `worldRuntime`), the `.value` of a `Game.Runtime.make(...)` held in a `const` of the same file (`made.value`, or `game` after `const game = made.value`), or a method destructured from one in a `const` (`const { tick } = runtime`).
|
|
263
|
+
|
|
264
|
+
Catches these calls on a runtime used as a statement, as the value an arrow returns to a caller that drops it (`forEach`, `addEventListener`, `requestAnimationFrame`, `requestIdleCallback`, `setTimeout`, `setInterval`, `setImmediate`, `queueMicrotask`), as any but the last expression of a sequence (`runtime.tick(update), draw()`), tested as a condition (`!`, `if`, `while`, `for`, `? :`, the left of `&&` / `||`), 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 (`() => void runtime.tick(update)` ignores it on purpose). A `tick`, `tryTick`, `restore`, or `rewind` result passed to a function is left to that function (a test's `expectOk(runtime.tick(update))`), unless it only prints or encodes (`JSON.stringify`, `String`, `console.*`). A `snapshot()` or `checksum()` result is data on its way somewhere, so passing it to any function unchecked is reported; a helper that takes that `Result` itself gets it once it is named: `const checksum = runtime.checksum(); helper(checksum)`. Other receivers cannot be told from a runtime by syntax and are not reported: game wrappers (`town.restore(...)`) and runtimes reached any other way (`game.tick(...)` with `game` a parameter or an import). Option: `{ "runtimePattern": "^(runtime|world)$" }` (a case-insensitive regular expression for the receiver's name; default `runtime$`).
|
|
243
265
|
|
|
244
266
|
### `ritmo/prefix-descriptor-and-system-names`
|
|
245
267
|
|
|
@@ -261,15 +283,59 @@ Checks the names given to `Descriptor.*`, `*.System`, `*.StateMachine`, `*.Entit
|
|
|
261
283
|
A tagged value, such as the value of a `Descriptor.EntityState` component or of a `Game.StateMachine`, changes state with the new state's own fields. Setting `_tag` over a spread of the previous state keeps every field of that state at runtime, while the new state's type hides them: they come back when the value is saved, compared, or spread again.
|
|
262
284
|
|
|
263
285
|
```ts
|
|
264
|
-
const
|
|
286
|
+
const pop = (contact: Contact): Contact =>
|
|
287
|
+
contact._tag === "ground" ? { ...contact, _tag: "air", vy: 2, coyote: 0 } : contact // reported: `platform` survives in the air
|
|
265
288
|
|
|
266
289
|
// instead
|
|
267
290
|
data.contact.transition(entity, { from: "ground", to: "air", data: { vy: 2, coyote: 0 } })
|
|
268
|
-
nextMachines.mode.
|
|
269
|
-
const
|
|
291
|
+
nextMachines.mode.transition({ from: "Talking", to: "Exploring" }) // a machine's move, not { ...talking, _tag: "Exploring" }
|
|
292
|
+
const pop = (contact: Contact): Contact =>
|
|
293
|
+
contact._tag === "ground" ? { _tag: "air", vy: 2, coyote: 0 } : contact // in a pure function
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The compiler already rejects an `update` callback that changes `_tag` and `set` on a state declared with `transitions`, so the rule guards the rest: a value built in a pure function, or written with `set` to a state declared without `transitions`. It reports a `_tag` set over a spread when the file shows the spread value is a state: read from a state machine (`machines.x.get()`, `nextMachines.x.getPending()`) or from an entity state's slot the same function moves (`data.contact.get(entity)` next to `data.contact.transition(...)` or `data.contact.update(entity, { state, data })`), directly or through the variable holding it, or a value whose `_tag` the same function reads (`if (body._tag === "ground")`, `switch (state._tag)`, `const { _tag } = previous`). It reads `Object.assign({}, ground, { _tag: "air" })` and `{ ...ground, ...{ _tag: "air" } }` the same way, and also reports a rest that took the tag out given a named one (`const { _tag, ...rest } = ground`, then `{ _tag: "air", ...rest }`).
|
|
297
|
+
|
|
298
|
+
Not reported: a value nothing in the file shows to be a state, such as a plain value tagged for an event (`events.explosion.emit({ ...position, _tag: "Explosion" })`); spreading the previous value to change fields of the same state (`{ ...air, vy: air.vy - 1 }`); and a `_tag` written before the spread (`{ _tag: to, ...data }`).
|
|
299
|
+
|
|
300
|
+
### `ritmo/no-kept-query-values`
|
|
301
|
+
|
|
302
|
+
An entity from `queries.x.each()` and a query's `data` live for one run. Kept past it, the data throws in the next run, and the entity is not checked against its query again: a runtime without `debug` keeps reading it after it left the query (gained a `without` component, lost a `with` one), and a debug runtime throws. The rule reports an entity or `data` stored in `local` state (directly, in a field or element of a literal, pushed or set into a collection there, merged in with `Object.assign(local, ...)`, or captured by a closure stored there) or in a variable declared outside the system's function: the callback of `Game.System` or `Game.Inspector`, or a function of the same file passed to one by name (`Game.System(name, spec, run)`). It follows entities copied (`Array.from(queries.x.each())`, `const [first] = queries.x.each()`) or returned by a `map` or `reduce` callback, and a context destructured or renamed (`({ queries: q })`, `({ queries: { x } })`, `({ local: kept })`, `ctx.queries.x`).
|
|
303
|
+
|
|
304
|
+
```ts
|
|
305
|
+
local.target ??= queries.targets.each()[0] // reported
|
|
306
|
+
local.slots = queries.targets.data // reported
|
|
307
|
+
|
|
308
|
+
// instead
|
|
309
|
+
local.target ??= queries.targets.each()[0]?.id
|
|
310
|
+
const found = local.target === undefined ? undefined : queries.targets.get(local.target)
|
|
311
|
+
if (found?.ok) aimAt(queries.targets.data.position.get(found.value))
|
|
312
|
+
local.rows = queries.targets.rows() // plain values, safe to keep
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
Ids (`entity.id`, `.map((entity) => entity.id)`), values read from `data`, and rows are not reported, nor are variables of the run itself (`let best` in the system's body). An entity handed to a service (`services.cache.remember(entity)`) is not judged: the rule cannot see what the service keeps.
|
|
316
|
+
|
|
317
|
+
### `ritmo/use-keyboard-for-game-keys`
|
|
318
|
+
|
|
319
|
+
A `keydown` listener on the whole page runs for every key, whatever has focus, so one that calls `preventDefault()` for Enter, Space, or the arrows also stops them on a focused button, link, tab, or open dialog: a player who reaches a menu by keyboard cannot press it, and Escape does not close a modal `<dialog>`. Games then hide it with `tabIndex = -1` on every button or `blur()` after each click. [`Keyboard.actions`](https://github.com/typeonce-dev/ritmo/blob/main/packages/browser/README.md) leaves keys the page is using to the page (a form field, a control reached by keyboard, an open modal dialog, a key a widget already handled) and keeps them when a control only kept focus after a click.
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
window.addEventListener("keydown", (event) => { // reported
|
|
323
|
+
if (event.key === "Escape") togglePause()
|
|
324
|
+
else if (event.key === " ") jump()
|
|
325
|
+
else return
|
|
326
|
+
event.preventDefault()
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
// instead
|
|
330
|
+
const keys = Keyboard.actions(window, { pause: ["Escape"], jump: [" "] })
|
|
331
|
+
// once per frame, or through InputCapture / Controls:
|
|
332
|
+
const snapshot = keys.snapshot()
|
|
333
|
+
if (snapshot.actions.pause.pressed) togglePause()
|
|
334
|
+
// a key for one piece of UI listens on that element:
|
|
335
|
+
dialog.addEventListener("keydown", (event) => { if (event.key === "ArrowDown") { event.preventDefault(); focusNext() } })
|
|
270
336
|
```
|
|
271
337
|
|
|
272
|
-
|
|
338
|
+
Reports a `keydown`, `keyup`, or `keypress` listener added to `window`, `document`, `document.body`, or `document.documentElement` (also as `globalThis.addEventListener` or a bare `addEventListener`) whose function calls `preventDefault()` on its event, written inline or declared in the same file by name. A listener that leaves the default alone (opening audio on the first key) and a listener on another element are not reported. A listener reached through a class member or another function (`window.addEventListener("keydown", this.onKey)`) is not followed. For "press any key", use `Keyboard.presses(window)`.
|
|
273
339
|
|
|
274
340
|
## Built-in rules that pair well
|
|
275
341
|
|
|
@@ -277,7 +343,7 @@ Some of oxlint's own rules catch Ritmo mistakes too. They are optional; turn on
|
|
|
277
343
|
|
|
278
344
|
| Rule | Catches in a Ritmo game |
|
|
279
345
|
|---|---|
|
|
280
|
-
| `typescript/no-unnecessary-condition` | a `Result` checked as a boolean instead of with `.ok` (`if (!
|
|
346
|
+
| `typescript/no-unnecessary-condition` | a `Result` checked as a boolean instead of with `.ok` where `ritmo/handle-runtime-result` cannot see the runtime (`if (!game.restore(save))` never fires), an object compared to `undefined` |
|
|
281
347
|
| `typescript/switch-exhaustiveness-check` | a switch over a closed set (a role, a kind, a state's `_tag`) that misses a member added later |
|
|
282
348
|
| `typescript/no-floating-promises`, `typescript/no-misused-promises` | host code that never awaits an asset load or a replay upload, or passes an async callback where a plain one is called |
|
|
283
349
|
| `typescript/restrict-template-expressions`, `typescript/no-base-to-string` | `[object Object]` in HUD or log text |
|
package/dist/index.js
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
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,
|
|
7
|
-
* in floats, data that cannot be saved, casts that skip a
|
|
8
|
-
* state values that keep a previous state's fields,
|
|
9
|
-
*
|
|
6
|
+
* clock, `Math.random`, engine-dependent math, or the page, or plays sound,
|
|
7
|
+
* timers counted in floats, data that cannot be saved, casts that skip a
|
|
8
|
+
* brand's check, state values that keep a previous state's fields, query
|
|
9
|
+
* entities and data kept past their run, runtime results that are
|
|
10
|
+
* dropped, and host key listeners that take keys from the page's controls.
|
|
11
|
+
* Every report names the Ritmo API to use instead.
|
|
10
12
|
*
|
|
11
13
|
* Register the plugin in `.oxlintrc.json` with `"jsPlugins":
|
|
12
14
|
* ["@typeonce/oxlint-plugin-ritmo"]`. Its rules are named `ritmo/<rule>`.
|
|
@@ -19,7 +21,8 @@
|
|
|
19
21
|
* `ritmo/keep-simulation-headless`, `ritmo/no-infinity-in-simulation-data`,
|
|
20
22
|
* `ritmo/no-float-timers`, `ritmo/no-brand-cast`.
|
|
21
23
|
* - Every file: `ritmo/handle-runtime-result`,
|
|
22
|
-
* `ritmo/prefix-descriptor-and-system-names`, `ritmo/no-state-spread
|
|
24
|
+
* `ritmo/prefix-descriptor-and-system-names`, `ritmo/no-state-spread`,
|
|
25
|
+
* `ritmo/no-kept-query-values`, `ritmo/use-keyboard-for-game-keys`.
|
|
23
26
|
*
|
|
24
27
|
* @module oxlint-plugin-ritmo
|
|
25
28
|
*/
|
|
@@ -29,9 +32,11 @@ import keepSimulationHeadless from "./rules/keep-simulation-headless.js";
|
|
|
29
32
|
import noBrandCast from "./rules/no-brand-cast.js";
|
|
30
33
|
import noFloatTimers from "./rules/no-float-timers.js";
|
|
31
34
|
import noInfinityInSimulationData from "./rules/no-infinity-in-simulation-data.js";
|
|
35
|
+
import noKeptQueryValues from "./rules/no-kept-query-values.js";
|
|
32
36
|
import noStateSpread from "./rules/no-state-spread.js";
|
|
33
37
|
import prefixDescriptorAndSystemNames from "./rules/prefix-descriptor-and-system-names.js";
|
|
34
38
|
import useClockForTime from "./rules/use-clock-for-time.js";
|
|
39
|
+
import useKeyboardForGameKeys from "./rules/use-keyboard-for-game-keys.js";
|
|
35
40
|
import useOpsForMath from "./rules/use-ops-for-math.js";
|
|
36
41
|
import useRandomForRandomness from "./rules/use-random-for-randomness.js";
|
|
37
42
|
export default definePlugin({
|
|
@@ -46,7 +51,9 @@ export default definePlugin({
|
|
|
46
51
|
"no-brand-cast": noBrandCast,
|
|
47
52
|
"handle-runtime-result": handleRuntimeResult,
|
|
48
53
|
"prefix-descriptor-and-system-names": prefixDescriptorAndSystemNames,
|
|
49
|
-
"no-state-spread": noStateSpread
|
|
54
|
+
"no-state-spread": noStateSpread,
|
|
55
|
+
"no-kept-query-values": noKeptQueryValues,
|
|
56
|
+
"use-keyboard-for-game-keys": useKeyboardForGameKeys
|
|
50
57
|
}
|
|
51
58
|
});
|
|
52
59
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;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,iBAAiB,MAAM,iCAAiC,CAAA;AAC/D,OAAO,aAAa,MAAM,4BAA4B,CAAA;AACtD,OAAO,8BAA8B,MAAM,+CAA+C,CAAA;AAC1F,OAAO,eAAe,MAAM,+BAA+B,CAAA;AAC3D,OAAO,sBAAsB,MAAM,uCAAuC,CAAA;AAC1E,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,iBAAiB,EAAE,aAAa;QAChC,sBAAsB,EAAE,iBAAiB;QACzC,4BAA4B,EAAE,sBAAsB;KACrD;CACF,CAAC,CAAA"}
|
package/dist/internal/ast.d.ts
CHANGED
|
@@ -18,6 +18,49 @@ export declare const isGlobalReference: (context: Context, node: ESTree.Node) =>
|
|
|
18
18
|
* is a local binding that shadows the global.
|
|
19
19
|
*/
|
|
20
20
|
export declare const globalMember: (context: Context, node: ESTree.MemberExpression, object: string) => string | undefined;
|
|
21
|
+
/** Where the type checker reads a name as a type: these never run. */
|
|
22
|
+
export declare const typePositions: Set<string>;
|
|
23
|
+
/** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
|
|
24
|
+
export declare const propertyKey: (node: ESTree.ObjectProperty | ESTree.AssignmentTargetProperty | ESTree.BindingProperty) => string | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* The global `node` refers to, as a path (`Math`, `Math.random`,
|
|
27
|
+
* `Temporal.Now`), or `undefined` when it refers to anything else. It
|
|
28
|
+
* resolves:
|
|
29
|
+
* - a global name that no local, parameter, or import shadows (`Math`;
|
|
30
|
+
* `globalThis`, `self`, and `window` give their own name);
|
|
31
|
+
* - a static member of one (`Math.random`, `Math["random"]`), where a member
|
|
32
|
+
* of `globalThis`, `self`, or `window` is that global (`globalThis.Math`
|
|
33
|
+
* and `self.window.Math` give `Math`);
|
|
34
|
+
* - a `const` that holds one (`const M = Math` makes `M` give `Math`), or a
|
|
35
|
+
* property destructured from one in a `const` (`const { now: n } = Date`
|
|
36
|
+
* makes `n` give `Date.now`).
|
|
37
|
+
*
|
|
38
|
+
* A name in a type (`let at: Date`, `typeof Math`) runs nothing and gives
|
|
39
|
+
* `undefined`. Values passed through functions or other modules are not
|
|
40
|
+
* followed.
|
|
41
|
+
*/
|
|
42
|
+
export declare const globalPath: (context: Context, node: ESTree.Node, seen?: Set<ESTree.Node>) => string | undefined;
|
|
43
|
+
/** A global read at one spot: its path (see `globalPath`), and the path of the global it is a member of. */
|
|
44
|
+
export interface GlobalRead {
|
|
45
|
+
readonly path: string;
|
|
46
|
+
/** The global the read takes a member of (`window` for `window.innerWidth`); none for a bare name. */
|
|
47
|
+
readonly from?: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The global `node` reads where it stands: a member of one
|
|
51
|
+
* (`globalThis.Date.now`, `M.random` after `const M = Math`), a property
|
|
52
|
+
* destructured from one (`now` in `const { now } = Date`), or a global name
|
|
53
|
+
* itself (`setTimeout`). A `const` holding a global (`M`, or `n` after
|
|
54
|
+
* `const { now: n } = Date`) gives `undefined`: the global was read where the
|
|
55
|
+
* `const` was declared, and a rule reports it there.
|
|
56
|
+
*/
|
|
57
|
+
export declare const globalRead: (context: Context, node: ESTree.Node) => GlobalRead | undefined;
|
|
58
|
+
/**
|
|
59
|
+
* The value of the `const` `node` names (`value` in `const x = value`), when
|
|
60
|
+
* a declaration in the file binds it to the whole value. A `let`, a
|
|
61
|
+
* parameter, and a destructured name give `undefined`.
|
|
62
|
+
*/
|
|
63
|
+
export declare const constValue: (context: Context, node: ESTree.Node) => ESTree.Node | undefined;
|
|
21
64
|
/** Whether `node` names the global `name` (not a local binding, property key, or type). */
|
|
22
65
|
export declare const isGlobalIdentifier: (context: Context, node: ESTree.Node, name: string) => boolean;
|
|
23
66
|
/** The method name a call invokes (`x.tick(...)` gives `tick`). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/internal/ast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,8DAA8D;AAC9D,eAAO,MAAM,OAAO,SAAU,MAAM,KAAG,MAC0D,CAAA;AAEjG,+EAA+E;AAC/E,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,gBAAgB,KAAG,MAAM,GAAG,SAIrE,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,KAAG,OAIvE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,YAAY,YAAa,OAAO,QAAQ,MAAM,CAAC,gBAAgB,UAAU,MAAM,KAAG,MAAM,GAAG,SAIvG,CAAA;AAED,2FAA2F;AAC3F,eAAO,MAAM,kBAAkB,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,QAAQ,MAAM,KAAG,OACD,CAAA;AAEtF,mEAAmE;AACnE,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,cAAc,KAAG,MAAM,GAAG,SACa,CAAA;AAEjF,qGAAqG;AACrG,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,IAAI,KAAG,MAAM,GAAG,SAIzD,CAAA;AAED,8EAA8E;AAC9E,eAAO,MAAM,gBAAgB,SAAU,MAAM,CAAC,iBAAiB,KAAG,OAGgD,CAAA;AAElH,gCAAgC;AAChC,eAAO,MAAM,WAAW,SAAU,MAAM,CAAC,IAAI,GAAG,SAAS,KAAG,MAAM,GAAG,SACqC,CAAA"}
|
|
1
|
+
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/internal/ast.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAEtD,8DAA8D;AAC9D,eAAO,MAAM,OAAO,SAAU,MAAM,KAAG,MAC0D,CAAA;AAEjG,+EAA+E;AAC/E,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,gBAAgB,KAAG,MAAM,GAAG,SAIrE,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,KAAG,OAIvE,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,YAAY,YAAa,OAAO,QAAQ,MAAM,CAAC,gBAAgB,UAAU,MAAM,KAAG,MAAM,GAAG,SAIvG,CAAA;AAKD,sEAAsE;AACtE,eAAO,MAAM,aAAa,aAA6G,CAAA;AAEvI,4FAA4F;AAC5F,eAAO,MAAM,WAAW,SAAU,MAAM,CAAC,cAAc,GAAG,MAAM,CAAC,wBAAwB,GAAG,MAAM,CAAC,eAAe,KAAG,MAAM,GAAG,SACpC,CAAA;AAK1F;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,UAAU,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,8BAAkC,MAAM,GAAG,SAkBxG,CAAA;AAiCD,4GAA4G;AAC5G,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,sGAAsG;IACtG,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,KAAG,UAAU,GAAG,SAa7E,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,UAAU,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,KAAG,MAAM,CAAC,IAAI,GAAG,SAO9E,CAAA;AAED,2FAA2F;AAC3F,eAAO,MAAM,kBAAkB,YAAa,OAAO,QAAQ,MAAM,CAAC,IAAI,QAAQ,MAAM,KAAG,OACD,CAAA;AAEtF,mEAAmE;AACnE,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,cAAc,KAAG,MAAM,GAAG,SACa,CAAA;AAEjF,qGAAqG;AACrG,eAAO,MAAM,YAAY,SAAU,MAAM,CAAC,IAAI,KAAG,MAAM,GAAG,SAIzD,CAAA;AAED,8EAA8E;AAC9E,eAAO,MAAM,gBAAgB,SAAU,MAAM,CAAC,iBAAiB,KAAG,OAGgD,CAAA;AAElH,gCAAgC;AAChC,eAAO,MAAM,WAAW,SAAU,MAAM,CAAC,IAAI,GAAG,SAAS,KAAG,MAAM,GAAG,SACqC,CAAA"}
|
package/dist/internal/ast.js
CHANGED
|
@@ -34,6 +34,133 @@ export const globalMember = (context, node, object) => {
|
|
|
34
34
|
return undefined;
|
|
35
35
|
return propertyName(node);
|
|
36
36
|
};
|
|
37
|
+
/** Objects whose members are the globals themselves: `globalThis.Math` is `Math`. */
|
|
38
|
+
const globalObjects = new Set(["globalThis", "self", "window"]);
|
|
39
|
+
/** Where the type checker reads a name as a type: these never run. */
|
|
40
|
+
export const typePositions = new Set(["TSTypeQuery", "TSQualifiedName", "TSTypeReference", "TSClassImplements", "TSInterfaceHeritage"]);
|
|
41
|
+
/** The static name of an object pattern or literal property (`a`, `"a"`), if it has one. */
|
|
42
|
+
export const propertyKey = (node) => !node.computed && node.key.type === "Identifier" ? node.key.name : stringValue(node.key);
|
|
43
|
+
/** The path of member `name` of the global at `object`: a member of `globalThis`, `self`, or `window` is the global itself. */
|
|
44
|
+
const memberOf = (object, name) => (globalObjects.has(object) ? name : `${object}.${name}`);
|
|
45
|
+
/**
|
|
46
|
+
* The global `node` refers to, as a path (`Math`, `Math.random`,
|
|
47
|
+
* `Temporal.Now`), or `undefined` when it refers to anything else. It
|
|
48
|
+
* resolves:
|
|
49
|
+
* - a global name that no local, parameter, or import shadows (`Math`;
|
|
50
|
+
* `globalThis`, `self`, and `window` give their own name);
|
|
51
|
+
* - a static member of one (`Math.random`, `Math["random"]`), where a member
|
|
52
|
+
* of `globalThis`, `self`, or `window` is that global (`globalThis.Math`
|
|
53
|
+
* and `self.window.Math` give `Math`);
|
|
54
|
+
* - a `const` that holds one (`const M = Math` makes `M` give `Math`), or a
|
|
55
|
+
* property destructured from one in a `const` (`const { now: n } = Date`
|
|
56
|
+
* makes `n` give `Date.now`).
|
|
57
|
+
*
|
|
58
|
+
* A name in a type (`let at: Date`, `typeof Math`) runs nothing and gives
|
|
59
|
+
* `undefined`. Values passed through functions or other modules are not
|
|
60
|
+
* followed.
|
|
61
|
+
*/
|
|
62
|
+
export const globalPath = (context, node, seen = new Set()) => {
|
|
63
|
+
// `const a = b, b = a` refers to nothing.
|
|
64
|
+
if (seen.has(node))
|
|
65
|
+
return undefined;
|
|
66
|
+
seen.add(node);
|
|
67
|
+
if (node.type === "MemberExpression") {
|
|
68
|
+
const name = propertyName(node);
|
|
69
|
+
const object = name === undefined ? undefined : globalPath(context, node.object, seen);
|
|
70
|
+
return object === undefined || name === undefined ? undefined : memberOf(object, name);
|
|
71
|
+
}
|
|
72
|
+
if (node.type !== "Identifier" || typePositions.has(node.parent.type))
|
|
73
|
+
return undefined;
|
|
74
|
+
const reference = context.sourceCode.getScope(node).references.find((candidate) => candidate.identifier === node);
|
|
75
|
+
if (reference === undefined)
|
|
76
|
+
return undefined;
|
|
77
|
+
const variable = reference.resolved;
|
|
78
|
+
if (variable === null || variable.defs.length === 0)
|
|
79
|
+
return node.name;
|
|
80
|
+
const [definition] = variable.defs;
|
|
81
|
+
if (variable.defs.length !== 1 || definition?.type !== "Variable")
|
|
82
|
+
return undefined;
|
|
83
|
+
if (definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const")
|
|
84
|
+
return undefined;
|
|
85
|
+
return bindingPath(context, definition.name, seen);
|
|
86
|
+
};
|
|
87
|
+
/** The global a `const` binding holds: the whole value (`M` in `const M = Math`) or a property destructured from it. */
|
|
88
|
+
const bindingPath = (context, binding, seen) => {
|
|
89
|
+
const parent = binding.parent;
|
|
90
|
+
if (parent === null)
|
|
91
|
+
return undefined;
|
|
92
|
+
if (parent.type === "VariableDeclarator" && parent.id === binding)
|
|
93
|
+
return parent.init === null ? undefined : globalPath(context, parent.init, seen);
|
|
94
|
+
if (parent.type === "Property" && parent.value === binding)
|
|
95
|
+
return propertyPath(context, parent, seen);
|
|
96
|
+
if (parent.type === "AssignmentPattern" && parent.left === binding && parent.parent.type === "Property")
|
|
97
|
+
return propertyPath(context, parent.parent, seen);
|
|
98
|
+
// `const { ...rest } = Math`: the rest holds Math's other members.
|
|
99
|
+
if (parent.type === "RestElement" && parent.parent.type === "ObjectPattern")
|
|
100
|
+
return patternPath(context, parent.parent, seen);
|
|
101
|
+
return undefined;
|
|
102
|
+
};
|
|
103
|
+
/** The global an object pattern destructures (`Date` in `const { now } = Date`), also when nested in another pattern. */
|
|
104
|
+
const patternPath = (context, pattern, seen) => {
|
|
105
|
+
const parent = pattern.parent;
|
|
106
|
+
if (parent === null)
|
|
107
|
+
return undefined;
|
|
108
|
+
if (parent.type === "VariableDeclarator" && parent.id === pattern)
|
|
109
|
+
return parent.init === null ? undefined : globalPath(context, parent.init, seen);
|
|
110
|
+
if (parent.type === "AssignmentExpression" && parent.left === pattern)
|
|
111
|
+
return globalPath(context, parent.right, seen);
|
|
112
|
+
if (parent.type === "Property" && parent.value === pattern)
|
|
113
|
+
return propertyPath(context, parent, seen);
|
|
114
|
+
if (parent.type === "AssignmentPattern" && parent.left === pattern && parent.parent.type === "Property")
|
|
115
|
+
return propertyPath(context, parent.parent, seen);
|
|
116
|
+
return undefined;
|
|
117
|
+
};
|
|
118
|
+
/** The global a property of an object pattern reads (`Date.now` for `now` in `const { now } = Date`). */
|
|
119
|
+
const propertyPath = (context, property, seen) => {
|
|
120
|
+
if (property.type !== "Property" || property.parent.type !== "ObjectPattern")
|
|
121
|
+
return undefined;
|
|
122
|
+
const key = propertyKey(property);
|
|
123
|
+
const object = key === undefined ? undefined : patternPath(context, property.parent, seen);
|
|
124
|
+
return object === undefined || key === undefined ? undefined : memberOf(object, key);
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* The global `node` reads where it stands: a member of one
|
|
128
|
+
* (`globalThis.Date.now`, `M.random` after `const M = Math`), a property
|
|
129
|
+
* destructured from one (`now` in `const { now } = Date`), or a global name
|
|
130
|
+
* itself (`setTimeout`). A `const` holding a global (`M`, or `n` after
|
|
131
|
+
* `const { now: n } = Date`) gives `undefined`: the global was read where the
|
|
132
|
+
* `const` was declared, and a rule reports it there.
|
|
133
|
+
*/
|
|
134
|
+
export const globalRead = (context, node) => {
|
|
135
|
+
if (node.type === "MemberExpression") {
|
|
136
|
+
const name = propertyName(node);
|
|
137
|
+
const from = name === undefined ? undefined : globalPath(context, node.object);
|
|
138
|
+
return from === undefined || name === undefined ? undefined : { path: memberOf(from, name), from };
|
|
139
|
+
}
|
|
140
|
+
if (node.type === "Property") {
|
|
141
|
+
const key = node.parent.type === "ObjectPattern" ? propertyKey(node) : undefined;
|
|
142
|
+
const from = key === undefined ? undefined : patternPath(context, node.parent, new Set());
|
|
143
|
+
return from === undefined || key === undefined ? undefined : { path: memberOf(from, key), from };
|
|
144
|
+
}
|
|
145
|
+
if (node.type === "Identifier" && !typePositions.has(node.parent.type) && isGlobalReference(context, node))
|
|
146
|
+
return { path: node.name };
|
|
147
|
+
return undefined;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* The value of the `const` `node` names (`value` in `const x = value`), when
|
|
151
|
+
* a declaration in the file binds it to the whole value. A `let`, a
|
|
152
|
+
* parameter, and a destructured name give `undefined`.
|
|
153
|
+
*/
|
|
154
|
+
export const constValue = (context, node) => {
|
|
155
|
+
if (node.type !== "Identifier")
|
|
156
|
+
return undefined;
|
|
157
|
+
const variable = context.sourceCode.getScope(node).references.find((reference) => reference.identifier === node)?.resolved;
|
|
158
|
+
const definition = variable?.defs.length === 1 ? variable.defs[0] : undefined;
|
|
159
|
+
if (definition?.type !== "Variable" || definition.parent?.type !== "VariableDeclaration" || definition.parent.kind !== "const")
|
|
160
|
+
return undefined;
|
|
161
|
+
const declarator = definition.node;
|
|
162
|
+
return declarator.type === "VariableDeclarator" && declarator.id.type === "Identifier" ? declarator.init ?? undefined : undefined;
|
|
163
|
+
};
|
|
37
164
|
/** Whether `node` names the global `name` (not a local binding, property key, or type). */
|
|
38
165
|
export const isGlobalIdentifier = (context, node, name) => node.type === "Identifier" && node.name === name && isGlobalReference(context, node);
|
|
39
166
|
/** The method name a call invokes (`x.tick(...)` gives `tick`). */
|