@typeonce/ritmo-devtools 0.14.0 → 0.15.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 (88) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +296 -55
  3. package/dist/Desync.d.ts +17 -3
  4. package/dist/Desync.d.ts.map +1 -1
  5. package/dist/Desync.js +17 -15
  6. package/dist/Desync.js.map +1 -1
  7. package/dist/Determinism.d.ts +17 -6
  8. package/dist/Determinism.d.ts.map +1 -1
  9. package/dist/Determinism.js +11 -3
  10. package/dist/Determinism.js.map +1 -1
  11. package/dist/Format.d.ts +43 -8
  12. package/dist/Format.d.ts.map +1 -1
  13. package/dist/Format.js +63 -31
  14. package/dist/Format.js.map +1 -1
  15. package/dist/Fuzz.d.ts +268 -0
  16. package/dist/Fuzz.d.ts.map +1 -0
  17. package/dist/Fuzz.js +355 -0
  18. package/dist/Fuzz.js.map +1 -0
  19. package/dist/Invariant.d.ts +6 -2
  20. package/dist/Invariant.d.ts.map +1 -1
  21. package/dist/Invariant.js.map +1 -1
  22. package/dist/PlaywrightEngine.d.ts +29 -0
  23. package/dist/PlaywrightEngine.d.ts.map +1 -0
  24. package/dist/PlaywrightEngine.js +193 -0
  25. package/dist/PlaywrightEngine.js.map +1 -0
  26. package/dist/Replay.d.ts +40 -22
  27. package/dist/Replay.d.ts.map +1 -1
  28. package/dist/Replay.js +20 -27
  29. package/dist/Replay.js.map +1 -1
  30. package/dist/Session.d.ts +214 -17
  31. package/dist/Session.d.ts.map +1 -1
  32. package/dist/Session.js +563 -57
  33. package/dist/Session.js.map +1 -1
  34. package/dist/Verify.d.ts +147 -0
  35. package/dist/Verify.d.ts.map +1 -0
  36. package/dist/Verify.js +151 -0
  37. package/dist/Verify.js.map +1 -0
  38. package/dist/cli.js +136 -8
  39. package/dist/cli.js.map +1 -1
  40. package/dist/index.d.ts +3 -2
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +3 -2
  43. package/dist/index.js.map +1 -1
  44. package/dist/internal/dependencyScan.d.ts +44 -0
  45. package/dist/internal/dependencyScan.d.ts.map +1 -0
  46. package/dist/internal/dependencyScan.js +313 -0
  47. package/dist/internal/dependencyScan.js.map +1 -0
  48. package/dist/internal/fuzzNetwork.d.ts +56 -0
  49. package/dist/internal/fuzzNetwork.d.ts.map +1 -0
  50. package/dist/internal/fuzzNetwork.js +96 -0
  51. package/dist/internal/fuzzNetwork.js.map +1 -0
  52. package/dist/internal/values.d.ts +9 -1
  53. package/dist/internal/values.d.ts.map +1 -1
  54. package/dist/internal/values.js +11 -1
  55. package/dist/internal/values.js.map +1 -1
  56. package/dist/internal/verifyRunner.d.ts +19 -0
  57. package/dist/internal/verifyRunner.d.ts.map +1 -0
  58. package/dist/internal/verifyRunner.js +47 -0
  59. package/dist/internal/verifyRunner.js.map +1 -0
  60. package/dist/internal/version.d.ts +1 -1
  61. package/dist/internal/version.js +1 -1
  62. package/package.json +28 -3
  63. package/src/Desync.ts +34 -17
  64. package/src/Determinism.ts +46 -11
  65. package/src/Format.ts +99 -34
  66. package/src/Fuzz.ts +544 -0
  67. package/src/Invariant.ts +6 -2
  68. package/src/PlaywrightEngine.ts +229 -0
  69. package/src/Replay.ts +87 -43
  70. package/src/Session.ts +806 -72
  71. package/src/Verify.ts +273 -0
  72. package/src/cli.ts +131 -8
  73. package/src/index.ts +3 -2
  74. package/src/internal/dependencyScan.ts +356 -0
  75. package/src/internal/fuzzNetwork.ts +130 -0
  76. package/src/internal/values.ts +20 -1
  77. package/src/internal/verifyRunner.ts +46 -0
  78. package/src/internal/version.ts +1 -1
  79. package/dist/Monitor.d.ts +0 -101
  80. package/dist/Monitor.d.ts.map +0 -1
  81. package/dist/Monitor.js +0 -602
  82. package/dist/Monitor.js.map +0 -1
  83. package/dist/internal/monitor.d.ts +0 -126
  84. package/dist/internal/monitor.d.ts.map +0 -1
  85. package/dist/internal/monitor.js +0 -279
  86. package/dist/internal/monitor.js.map +0 -1
  87. package/src/Monitor.ts +0 -713
  88. package/src/internal/monitor.ts +0 -370
package/src/Verify.ts ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Determinism checked across engines: one replay, played in this process and
3
+ * in other JavaScript engines (real browsers), must reach the same world
4
+ * after every tick. `Ops` promises the same bits on every engine and a
5
+ * replay recorded in one browser should verify in another; this is the
6
+ * check that runs both claims.
7
+ *
8
+ * - `acrossEngines(make, file, { engines })` plays the replay twice here
9
+ * (the reference, and a repeat of it), compares the reference with the
10
+ * recording's checkpoints, then with each engine's per-tick checksums. On
11
+ * the first tick an engine differs, it loads both worlds at that tick and
12
+ * names every differing value, as `Desync.compare` does.
13
+ * - An `Engine` is any place that can run the game: `PlaywrightEngine`
14
+ * (Node host) runs Chromium, WebKit, and Firefox headless. For another
15
+ * host (a webview, a console devkit), run `trace` and `snapshotAt` there
16
+ * and wrap them as an `Engine`.
17
+ *
18
+ * `ritmo-devtools verify <entry> <replay> --engines node,chromium,webkit,firefox`
19
+ * is this module from the command line. With no engines it is the quick
20
+ * check in this process alone (two runs and the recording), the one a test
21
+ * runs; with browsers it is the one to run before trusting a replay or a
22
+ * lockstep match across them.
23
+ *
24
+ * This module calls no platform API: engines are injected.
25
+ *
26
+ * @module Verify
27
+ * @docGroup devtools
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const engines = PlaywrightEngine.make({ entry: "src/replay-target.ts", browsers: ["chromium", "webkit"] })
32
+ * const verified = await Verify.acrossEngines(replayTarget, file, { engines: engines.engines })
33
+ * await engines.close()
34
+ * if (!verified.ok) console.log(verified.error.text)
35
+ * ```
36
+ */
37
+ import * as Result from "@typeonce/ritmo/Result"
38
+ import type { Schema } from "@typeonce/ritmo/Schema"
39
+ import type * as Snapshot from "@typeonce/ritmo/Snapshot"
40
+
41
+ import * as Desync from "./Desync.ts"
42
+ import * as Format from "./Format.ts"
43
+ import * as Rendered from "./Rendered.ts"
44
+ import * as Replay from "./Replay.ts"
45
+
46
+ /** The world's checksum (`runtime.checksum()`) after each replayed tick, in tick order, the start's tick first. */
47
+ export type Hashes = ReadonlyArray<{ readonly tick: number; readonly hash: string }>
48
+
49
+ /** The engine cannot run here: the tool or browser that runs it is not installed. */
50
+ export interface EngineMissing {
51
+ readonly _tag: "EngineMissing"
52
+ readonly engine: string
53
+ /** What is missing. */
54
+ readonly reason: string
55
+ /** The command that installs it. */
56
+ readonly install: string
57
+ }
58
+
59
+ /** The engine started and could not finish: the game did not load or threw, or the replay did not open there. */
60
+ export interface EngineFailed {
61
+ readonly _tag: "EngineFailed"
62
+ readonly engine: string
63
+ readonly message: string
64
+ }
65
+
66
+ /** Why an engine produced no result. */
67
+ export type EngineError = EngineMissing | EngineFailed
68
+
69
+ /**
70
+ * A JavaScript engine that runs the game, other than this process:
71
+ * `PlaywrightEngine` for browsers, or one a host builds from `trace` and
72
+ * `snapshotAt` run there.
73
+ */
74
+ export interface Engine {
75
+ /** Its name in reports (`chromium`, `webkit`). */
76
+ readonly name: string
77
+ /** Plays the whole replay and returns the world's checksum after every tick: `trace` run there. */
78
+ readonly trace: (file: Replay.ReplayFile) => Promise<Result.Result<Hashes, EngineError>>
79
+ /** Plays the replay to the end of `tick` and returns the world: `snapshotAt` run there. */
80
+ readonly snapshotAt: (file: Replay.ReplayFile, tick: number) => Promise<Result.Result<Snapshot.WorldSnapshot, EngineError>>
81
+ }
82
+
83
+ /** The replay played to its end: the checksum after every tick. What an `Engine` runs in its own engine. */
84
+ export const trace = <S extends Schema.Any, Root>(
85
+ make: (playback: Replay.Playback) => Replay.Target<S, Root>,
86
+ file: Replay.ReplayFile
87
+ ): Result.Result<Hashes, Replay.ReplayError> => {
88
+ const opened = Replay.session(make, file)
89
+ if (!opened.ok) return opened
90
+ opened.value.play()
91
+ return Result.success([...opened.value.hashes()].sort(([left], [right]) => left - right).map(([tick, hash]) => ({ tick, hash })))
92
+ }
93
+
94
+ /** The world at the end of `tick` (a recorder tick number, or the start's tick), as plain data. What an `Engine` runs to explain a difference. */
95
+ export const snapshotAt = <S extends Schema.Any, Root>(
96
+ make: (playback: Replay.Playback) => Replay.Target<S, Root>,
97
+ file: Replay.ReplayFile,
98
+ tick: number
99
+ ): Result.Result<Snapshot.WorldSnapshot, Replay.ReplayError> => {
100
+ const opened = Replay.session(make, file)
101
+ if (!opened.ok) return opened
102
+ opened.value.play({ to: tick })
103
+ const snapshot = opened.value.snapshot()
104
+ return snapshot.ok ? snapshot : Result.failure({ _tag: "SnapshotFailed", error: snapshot.error })
105
+ }
106
+
107
+ /** The engine reached the same world as the reference after every tick. */
108
+ export interface Agreed {
109
+ readonly _tag: "Agreed"
110
+ readonly engine: string
111
+ /** Ticks compared, the start's tick not counted. */
112
+ readonly ticks: number
113
+ }
114
+
115
+ /**
116
+ * The first tick whose world differs. `against` is `"node"` (the reference
117
+ * run in this process; for `engine: "node"`, a second run there) or
118
+ * `"recording"` (the file's checkpoints, which hold only hashes, so
119
+ * `differences` is empty).
120
+ */
121
+ export interface Diverged {
122
+ readonly _tag: "Diverged"
123
+ readonly engine: string
124
+ readonly against: "node" | "recording"
125
+ readonly tick: number
126
+ /** Every differing value at `tick`, the reference's world as `mine`, the engine's as `theirs`. */
127
+ readonly differences: ReadonlyArray<Desync.Difference>
128
+ /** Why `differences` is empty, when it is: the worlds could not be loaded, or they are equal as saves (the hash covers more). */
129
+ readonly unexplained: string | undefined
130
+ }
131
+
132
+ /** What one engine's check found. */
133
+ export type Outcome = Agreed | Diverged | EngineError
134
+
135
+ /** Every engine agreed: the replay is deterministic here, matches its recording, and plays the same everywhere. */
136
+ export interface Verified {
137
+ readonly schedule: string
138
+ /** Ticks compared, the start's tick not counted. */
139
+ readonly ticks: number
140
+ /** `node` first, then each engine. */
141
+ readonly engines: ReadonlyArray<string>
142
+ }
143
+
144
+ /** The replay did not open in this process: the reference could not run, so nothing was compared. */
145
+ export interface ReplayInvalid {
146
+ readonly _tag: "ReplayInvalid"
147
+ readonly error: Replay.ReplayError
148
+ readonly text: string
149
+ }
150
+
151
+ /** Some engine did not agree: `outcomes` has one entry per engine, `node` first; narrow each by `_tag`. */
152
+ export interface NotVerified {
153
+ readonly _tag: "NotVerified"
154
+ readonly outcomes: ReadonlyArray<Outcome>
155
+ readonly text: string
156
+ }
157
+
158
+ /** Why `acrossEngines` failed. */
159
+ export type VerifyError = ReplayInvalid | NotVerified
160
+
161
+ /** Which engines `acrossEngines` compares with this process. */
162
+ export interface Options {
163
+ /** Engines checked against this process, in report order. None checks this process alone. */
164
+ readonly engines?: ReadonlyArray<Engine>
165
+ }
166
+
167
+ const firstDifference = (reference: Hashes, other: Hashes): number | undefined => {
168
+ const mine = new Map(reference.map(({ tick, hash }) => [tick, hash] as const))
169
+ const theirs = new Map(other.map(({ tick, hash }) => [tick, hash] as const))
170
+ return [...new Set([...mine.keys(), ...theirs.keys()])].sort((left, right) => left - right).find((tick) => mine.get(tick) !== theirs.get(tick))
171
+ }
172
+
173
+ /**
174
+ * Plays `file` in this process twice and in each engine, and returns
175
+ * `Verified` when every run reaches the same world after every tick as the
176
+ * reference run here, and the reference matches the recording's
177
+ * checkpoints. Otherwise it fails with `NotVerified`, one outcome per engine:
178
+ * `Diverged` names the first differing tick and every differing value
179
+ * there, and an engine that is not installed or did not finish is reported
180
+ * as `EngineMissing` / `EngineFailed`, never skipped.
181
+ *
182
+ * `make` is the game's replay factory, the one `Replay.session` takes;
183
+ * each engine loads the same one.
184
+ */
185
+ export const acrossEngines = async <S extends Schema.Any, Root>(
186
+ make: (playback: Replay.Playback) => Replay.Target<S, Root>,
187
+ file: Replay.ReplayFile,
188
+ options: Options = {}
189
+ ): Promise<Result.Result<Rendered.Rendered<Verified>, VerifyError>> => {
190
+ const reference = trace(make, file)
191
+ if (!reference.ok) {
192
+ return Result.failure({ _tag: "ReplayInvalid", error: reference.error, text: `the replay does not open here: ${JSON.stringify(reference.error)}` })
193
+ }
194
+ const here = (tick: number) => snapshotAt(make, file, tick)
195
+ const ticks = reference.value.length - 1
196
+ const outcomes: Array<Outcome> = []
197
+
198
+ const repeat = trace(make, file)
199
+ const repeated = repeat.ok ? firstDifference(reference.value, repeat.value) : undefined
200
+ // As `Replay.session` does, the recording is compared on the replayed ticks, not on the start it restores.
201
+ const checkpoints = file.checkpoints.filter(({ tick }) => tick > file.start.tick)
202
+ const recorded = firstDifference(reference.value.filter(({ tick }) => checkpoints.some((checkpoint) => checkpoint.tick === tick)), checkpoints)
203
+ if (!repeat.ok) {
204
+ outcomes.push({ _tag: "EngineFailed", engine: "node", message: `a second run did not open: ${JSON.stringify(repeat.error)}` })
205
+ } else if (repeated !== undefined) {
206
+ outcomes.push(await explain("node", "node", repeated, here, async (tick) => here(tick)))
207
+ } else if (recorded !== undefined) {
208
+ outcomes.push({ _tag: "Diverged", engine: "node", against: "recording", tick: recorded, differences: [], unexplained: "the recording holds only a hash at this tick" })
209
+ } else {
210
+ outcomes.push({ _tag: "Agreed", engine: "node", ticks })
211
+ }
212
+
213
+ outcomes.push(...await Promise.all((options.engines ?? []).map(async (engine): Promise<Outcome> => {
214
+ const traced = await engine.trace(file)
215
+ if (!traced.ok) return traced.error
216
+ const tick = firstDifference(reference.value, traced.value)
217
+ if (tick === undefined) return { _tag: "Agreed", engine: engine.name, ticks }
218
+ return explain(engine.name, "node", tick, here, (at) => engine.snapshotAt(file, at))
219
+ })))
220
+
221
+ if (outcomes.every((outcome) => outcome._tag === "Agreed")) {
222
+ const engines = outcomes.map((outcome) => outcome.engine)
223
+ return Result.success(Rendered.make(
224
+ { schedule: file.schedule, ticks, engines },
225
+ `verified ${ticks} ticks of ${file.schedule} on ${engines.join(", ")}: every engine reaches the same world as node after every tick, and node matches the recording`
226
+ ))
227
+ }
228
+ return Result.failure({ _tag: "NotVerified", outcomes, text: [`NOT verified: ${ticks} ticks of ${file.schedule}`, ...outcomes.map(describe)].join("\n") })
229
+ }
230
+
231
+ /** Loads both worlds at `tick` and lists what differs. */
232
+ const explain = async (
233
+ engine: string,
234
+ against: "node",
235
+ tick: number,
236
+ mine: (tick: number) => Result.Result<Snapshot.WorldSnapshot, Replay.ReplayError>,
237
+ theirs: (tick: number) => Promise<Result.Result<Snapshot.WorldSnapshot, Replay.ReplayError | EngineError>>
238
+ ): Promise<Diverged> => {
239
+ const left = mine(tick)
240
+ const right = await theirs(tick)
241
+ if (!left.ok || !right.ok) {
242
+ const error = left.ok ? right.ok ? undefined : right.error : left.error
243
+ return { _tag: "Diverged", engine, against, tick, differences: [], unexplained: `the worlds at this tick could not be loaded: ${JSON.stringify(error)}` }
244
+ }
245
+ const differences = Desync.compare(left.value, right.value).data
246
+ return {
247
+ _tag: "Diverged", engine, against, tick, differences,
248
+ unexplained: differences.length === 0 ? "the saves are equal: the checksum covers something a snapshot does not show" : undefined
249
+ }
250
+ }
251
+
252
+ const where = ({ path, entity }: Desync.Difference): string =>
253
+ entity === undefined ? path : `${Format.entity(entity)}${path.slice(`entity ${entity}`.length)}`
254
+
255
+ /** One outcome as text: the first line names the engine, the tick, and the first difference. */
256
+ const describe = (outcome: Outcome): string => {
257
+ switch (outcome._tag) {
258
+ case "Agreed":
259
+ return `${outcome.engine}: agrees with ${outcome.engine === "node" ? "a second node run and the recording" : "node"} over ${outcome.ticks} ticks`
260
+ case "EngineMissing":
261
+ return `${outcome.engine}: not installed (${outcome.reason}): ${outcome.install}`
262
+ case "EngineFailed":
263
+ return `${outcome.engine}: failed: ${outcome.message}`
264
+ case "Diverged": {
265
+ const reference = outcome.engine === outcome.against ? "a second node run" : outcome.against
266
+ const [first] = outcome.differences
267
+ const head = `tick ${outcome.tick}: ${outcome.engine} differs from ${reference}${first === undefined ? "" : ` in ${where(first)} (${Format.value(first.mine)} -> ${Format.value(first.theirs)})`}`
268
+ if (outcome.unexplained !== undefined) return `${head}\n ${outcome.unexplained}`
269
+ return [head, ` ${outcome.differences.length} difference${outcome.differences.length === 1 ? "" : "s"} (${reference} -> ${outcome.engine}):`,
270
+ ...outcome.differences.map((difference) => ` ${where(difference)}: ${Format.value(difference.mine)} -> ${Format.value(difference.theirs)}`)].join("\n")
271
+ }
272
+ }
273
+ }
package/src/cli.ts CHANGED
@@ -3,8 +3,10 @@
3
3
  * `ritmo-devtools`: devtools from the command line.
4
4
  *
5
5
  * ritmo-devtools lint <entry>
6
+ * ritmo-devtools verify <entry> <replay> [--engines node,chromium,webkit,firefox] [--json]
7
+ * ritmo-devtools scan <entry> [--json]
6
8
  *
7
- * Imports `<entry>` (a module exporting `lintTarget`, see the `Lint` module),
9
+ * `lint` imports `<entry>` (a module exporting `lintTarget`, see the `Lint` module),
8
10
  * prints every lint of its schedules with its fix, and exits with 1 when one
9
11
  * is a warning. Info-level lints are printed and do not fail.
10
12
  *
@@ -19,20 +21,53 @@
19
21
  * A missing or unreadable config, one with `extends`, or one that never turns
20
22
  * the rule on prints why the check was skipped and does not fail.
21
23
  *
22
- * Exit codes: 0 ok, 1 lint warning or uncovered module, 2 usage error.
24
+ * `verify` imports `<entry>` (a module exporting `replayTarget`, the
25
+ * `make(playback)` factory `Replay.session` takes), plays the replay file in
26
+ * Node and in each listed browser engine, and prints the first tick whose
27
+ * checksum differs from Node's, with every value that differs there (see the
28
+ * `Verify` module). Node always runs, as the reference; `--engines node` (the
29
+ * default) needs no other dependency. Browser engines need `playwright` and
30
+ * `vite` (see the `PlaywrightEngine` module); one that is not installed is
31
+ * printed with its install command and fails the check. `--json` prints the
32
+ * result as JSON instead of text.
33
+ *
34
+ * `scan` resolves every file `<entry>` (the simulation entry) imports,
35
+ * `node_modules` included, and runs the oxlint rules `ritmo/use-ops-for-math`,
36
+ * `ritmo/use-clock-for-time`, and `ritmo/use-random-for-randomness` over them,
37
+ * so a dependency that calls `Math.sin`, `Date.now`, or `Math.random` shows
38
+ * before a desync does. Findings are printed per package with what to do next;
39
+ * `--json` prints them as JSON instead. It is a hint, not a verdict: it exits
40
+ * with 0 with or without findings. It needs `rolldown` (Vite 8 includes it)
41
+ * and the game's `oxlint` with `@typeonce/oxlint-plugin-ritmo`; a missing one
42
+ * is printed with its install command and exits with 2.
43
+ *
44
+ * Exit codes: 0 ok (and every `scan` that ran), 1 lint warning, uncovered
45
+ * module, or an engine that differs or did not run, 2 usage error (for `scan`
46
+ * also an unreadable entry, an import that does not resolve, or a missing tool).
23
47
  * Requires Node 22.15 or later for `module.registerHooks`; on older Node it
24
48
  * prints that coverage was not checked.
25
49
  *
26
50
  * @module cli
27
51
  * @docGroup devtools
28
52
  */
53
+ import { readFileSync } from "node:fs"
29
54
  import { resolve } from "node:path"
30
55
  import { pathToFileURL } from "node:url"
31
56
 
57
+ import * as DependencyScan from "./internal/dependencyScan.ts"
32
58
  import * as SimulationCoverage from "./internal/simulationCoverage.ts"
33
59
  import * as Lint from "./Lint.ts"
60
+ import * as Replay from "./Replay.ts"
61
+ import * as Verify from "./Verify.ts"
34
62
 
35
- const usage = "usage: ritmo-devtools lint <entry>\n <entry> exports lintTarget: () => { runtime, schedules, describe?, hostEvents? } (see the Lint module)"
63
+ const usage = [
64
+ "usage: ritmo-devtools lint <entry>",
65
+ " ritmo-devtools verify <entry> <replay> [--engines node,chromium,webkit,firefox] [--json]",
66
+ " ritmo-devtools scan <entry> [--json]",
67
+ " lint: <entry> exports lintTarget: () => { runtime, schedules, describe?, hostEvents? } (see the Lint module)",
68
+ " verify: <entry> exports replayTarget: (playback) => { runtime, schedules, hostClock } (see the Verify module)",
69
+ " scan: <entry> is the simulation's entry module; every file it imports, node_modules included, is checked for Math, clock, and randomness calls"
70
+ ].join("\n")
36
71
 
37
72
  const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null
38
73
 
@@ -47,11 +82,15 @@ const isTarget = (value: unknown): value is Lint.Target<any, any> =>
47
82
  && (value["hostEvents"] === undefined || Array.isArray(value["hostEvents"]))
48
83
 
49
84
  const main = async (args: ReadonlyArray<string>): Promise<number> => {
50
- const [command, entry] = args
51
- if (command !== "lint" || entry === undefined) {
52
- console.error(usage)
53
- return 2
54
- }
85
+ const [command, ...rest] = args
86
+ if (command === "lint" && rest.length === 1) return lint(rest[0]!)
87
+ if (command === "verify") return verify(rest)
88
+ if (command === "scan") return scan(rest)
89
+ console.error(usage)
90
+ return 2
91
+ }
92
+
93
+ const lint = async (entry: string): Promise<number> => {
55
94
  const loads = SimulationCoverage.recordLoads()
56
95
  const loaded: unknown = await import(pathToFileURL(resolve(entry)).href)
57
96
  // Snapshot before lintTarget runs: modules it imports (render schedules to describe) are host code.
@@ -78,4 +117,88 @@ const main = async (args: ReadonlyArray<string>): Promise<number> => {
78
117
  return report.data.ok && (!coverage.checked || coverage.uncovered.length === 0) ? 0 : 1
79
118
  }
80
119
 
120
+ const engineNames = ["node", "chromium", "webkit", "firefox"] as const
121
+
122
+ const verify = async (args: ReadonlyArray<string>): Promise<number> => {
123
+ const positional: Array<string> = []
124
+ let engines: ReadonlyArray<string> = ["node"]
125
+ let json = false
126
+ for (let index = 0; index < args.length; index++) {
127
+ const arg = args[index]!
128
+ if (arg === "--json") json = true
129
+ else if (arg === "--engines") engines = (args[++index] ?? "").split(",").filter((name) => name !== "")
130
+ else if (arg.startsWith("--engines=")) engines = arg.slice("--engines=".length).split(",").filter((name) => name !== "")
131
+ else positional.push(arg)
132
+ }
133
+ const [entry, replay] = positional
134
+ if (entry === undefined || replay === undefined || positional.length !== 2) {
135
+ console.error(usage)
136
+ return 2
137
+ }
138
+ const unknown = engines.filter((name) => !(engineNames as ReadonlyArray<string>).includes(name))
139
+ if (engines.length === 0 || unknown.length > 0) {
140
+ console.error(`--engines takes a comma-separated list of ${engineNames.join(", ")}${unknown.length > 0 ? `; unknown: ${unknown.join(", ")}` : ""}`)
141
+ return 2
142
+ }
143
+ let data: unknown
144
+ try {
145
+ data = JSON.parse(readFileSync(resolve(replay), "utf8"))
146
+ } catch (error) {
147
+ console.error(`${replay} could not be read as JSON: ${error instanceof Error ? error.message : String(error)}`)
148
+ return 2
149
+ }
150
+ const file = Replay.parse(data)
151
+ if (!file.ok) {
152
+ console.error(`${replay} is not a replay file: ${file.error._tag === "InvalidReplay" ? file.error.message : file.error._tag}`)
153
+ return 2
154
+ }
155
+ const loaded: unknown = await import(pathToFileURL(resolve(entry)).href)
156
+ const make = isRecord(loaded) ? loaded["replayTarget"] : undefined
157
+ if (typeof make !== "function") {
158
+ console.error(`${entry} must export replayTarget: (playback) => { runtime, schedules, hostClock } (see the Verify module)`)
159
+ return 2
160
+ }
161
+ // The browser adapter, and with it playwright and vite, loads only when a browser is listed.
162
+ const browsers = engines.filter((name) => name !== "node")
163
+ const PlaywrightEngine = browsers.length > 0 ? await import("./PlaywrightEngine.ts") : undefined
164
+ const playwright = PlaywrightEngine?.make({ entry, browsers: browsers.filter(PlaywrightEngine.isBrowser) })
165
+ let result: Awaited<ReturnType<typeof Verify.acrossEngines>>
166
+ try {
167
+ // The entry's type is checked where it is written; here only its shape is known.
168
+ result = await Verify.acrossEngines(make as (playback: Replay.Playback) => Replay.Target<any, any>, file.value, { engines: playwright?.engines ?? [] })
169
+ } catch (error) {
170
+ console.error(`replayTarget in ${entry} threw: ${error instanceof Error ? error.stack ?? error.message : String(error)}`)
171
+ return 2
172
+ } finally {
173
+ await playwright?.close()
174
+ }
175
+ console.log(json ? JSON.stringify(result.ok ? { ok: true, ...result.value.data } : { ok: false, ...withoutText(result.error) }, null, 2) : result.ok ? result.value.text : result.error.text)
176
+ return result.ok ? 0 : 1
177
+ }
178
+
179
+ const scan = async (args: ReadonlyArray<string>): Promise<number> => {
180
+ const json = args.includes("--json")
181
+ const positional = args.filter((arg) => arg !== "--json")
182
+ if (positional.length !== 1 || positional[0]!.startsWith("-")) {
183
+ console.error(usage)
184
+ return 2
185
+ }
186
+ const result = await DependencyScan.run(positional[0]!, process.cwd())
187
+ if (!result.ok) {
188
+ const error = result.error
189
+ console.error(error._tag === "ToolMissing"
190
+ ? `scan needs ${error.tool}, which is not installed: ${error.install}`
191
+ : error._tag === "ResolveFailed"
192
+ ? `the imports of ${positional[0]} could not be resolved: ${error.message}`
193
+ : error._tag === "LintFailed"
194
+ ? `oxlint did not run: ${error.message}`
195
+ : error.message)
196
+ return 2
197
+ }
198
+ console.log(json ? JSON.stringify(result.value, null, 2) : DependencyScan.format(result.value))
199
+ return 0
200
+ }
201
+
202
+ const withoutText = ({ text: _text, ...error }: Verify.VerifyError) => error
203
+
81
204
  process.exitCode = await main(process.argv.slice(2))
package/src/index.ts CHANGED
@@ -1,13 +1,14 @@
1
- /** Debug sessions, trace history, text reports, and a live browser monitor for ritmo runtimes. */
1
+ /** Headless debug sessions, trace history, text reports, replays, and fuzzing for ritmo runtimes. */
2
2
  export * as Format from "./Format.ts"
3
+ export * as Fuzz from "./Fuzz.ts"
3
4
  export * as Desync from "./Desync.ts"
4
5
  export * as Determinism from "./Determinism.ts"
5
6
  export * as Invariant from "./Invariant.ts"
6
7
  export * as Lint from "./Lint.ts"
7
- export * as Monitor from "./Monitor.ts"
8
8
  export * as Replay from "./Replay.ts"
9
9
  export * as Rendered from "./Rendered.ts"
10
10
  export * as Session from "./Session.ts"
11
+ export * as Verify from "./Verify.ts"
11
12
 
12
13
  /** The package's identifier. */
13
14
  export const packageTag = "devtools" as const