@typeonce/ritmo-devtools 0.8.0 → 0.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/ritmo-devtools",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "Headless debug sessions, trace history, text reports, and a live browser monitor for Ritmo runtimes",
5
5
  "author": "Sandro Maglione",
6
6
  "license": "MIT",
@@ -27,6 +27,7 @@
27
27
  "src/**/*.ts",
28
28
  "dist",
29
29
  "README.md",
30
+ "CHANGELOG.md",
30
31
  "LICENSE"
31
32
  ],
32
33
  "bin": {
@@ -50,10 +51,10 @@
50
51
  "provenance": true
51
52
  },
52
53
  "dependencies": {
53
- "@typeonce/ritmo": "^0.8.0"
54
+ "@typeonce/ritmo": "^0.10.0"
54
55
  },
55
56
  "engines": {
56
- "node": ">=20"
57
+ "node": ">=22.15"
57
58
  },
58
59
  "scripts": {
59
60
  "build": "tsc -b tsconfig.json --pretty false",
package/src/Format.ts CHANGED
@@ -281,6 +281,8 @@ const effect = (input: Debug.Effect, options: ValueOptions): string => {
281
281
  return `relation failure e${input.entity} ${input.relation}: ${input.error}`
282
282
  case "requirementViolated":
283
283
  return `skipped ${input.command} e${input.entity}: ${input.component} requires ${input.missing}`
284
+ case "staleTarget":
285
+ return `skipped ${input.command} e${input.entity}: id spawned in an earlier run`
284
286
  }
285
287
  }
286
288
 
package/src/Replay.ts CHANGED
@@ -111,7 +111,7 @@ export type ValidateRecordable<Schedule> =
111
111
  export interface TickRecord {
112
112
  /** The recorder's tick number, counting the recorded schedule's ticks from 1. */
113
113
  readonly tick: number
114
- /** Per source service: what `snapshot()` returned this tick, in call order. Absent when it repeats the previous tick. */
114
+ /** Per source service: what `snapshot()` returned this tick, in call order. Absent when it repeats the previous tick; the first tick of a saved window carries every value. */
115
115
  readonly services?: Readonly<Record<string, ReadonlyArray<unknown>>>
116
116
  /** Events the host sent since the previous recorded tick, in order. */
117
117
  readonly sent?: ReadonlyArray<{ readonly event: string; readonly value: unknown }>
@@ -282,8 +282,18 @@ export const recorder = <S extends Schema.Any, Root, const Recorded extends AnyS
282
282
  for (let index = 0; index < points.length; index++) if (points[index]!.tick <= windowStart) firstNeeded = index
283
283
  if (firstNeeded > 0) {
284
284
  points = points.slice(firstNeeded)
285
- ticks = ticks.filter((record) => record.tick > points[0]!.tick)
286
- checkpoints = checkpoints.filter((checkpoint) => checkpoint.tick >= points[0]!.tick)
285
+ const start = points[0]!.tick
286
+ // Service values are stored only when they change, so the first kept
287
+ // tick takes the latest values of the dropped ones it does not repeat:
288
+ // the window must replay on its own.
289
+ const carried: Record<string, ReadonlyArray<unknown>> = {}
290
+ for (const record of ticks) if (record.tick <= start && record.services !== undefined) Object.assign(carried, record.services)
291
+ ticks = ticks.filter((record) => record.tick > start)
292
+ const first = ticks[0]
293
+ if (first !== undefined && Object.keys(carried).length > 0) {
294
+ ticks[0] = { ...first, services: { ...carried, ...first.services } }
295
+ }
296
+ checkpoints = checkpoints.filter((checkpoint) => checkpoint.tick >= start)
287
297
  }
288
298
  }
289
299
  takePoint()
package/src/Session.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  * trace events, and answers questions about it as text and data:
6
6
  *
7
7
  * - `run(name, { frames, until })` ticks a schedule frame by frame and stops
8
- * at the first system failure, thrown defect, or violated invariant.
8
+ * at the first system failure, thrown defect, or violated invariant (an
9
+ * invariant that throws stops it as `invariant-threw`).
9
10
  * - `journal(filter)` lists what happened, one fact per line, filtered by
10
11
  * frames, entity, component, resource, event, machine, system, or kind.
11
12
  * - `why(entity, component)` lists the latest changes to one component, and
@@ -146,6 +147,8 @@ export type Stop =
146
147
  | { readonly reason: "tickOrder"; readonly frame: number; readonly issues: ReadonlyArray<string> }
147
148
  | { readonly reason: "defect"; readonly frame: number; readonly error: unknown }
148
149
  | { readonly reason: "invariant"; readonly frame: number; readonly invariant: string; readonly message: string }
150
+ /** The invariant itself threw: a bug in the check, not a violation. Fix the check, then run again. */
151
+ | { readonly reason: "invariant-threw"; readonly frame: number; readonly invariant: string; readonly error: unknown }
149
152
  /**
150
153
  * A failed tick result nobody read (for example a setup tick the game ran
151
154
  * before this run): `frame` is the failed tick's, `skipped` the systems
@@ -543,16 +546,22 @@ export const make = <
543
546
  : { reason: "failure", frame, system: typeof error.system === "string" ? error.system : "(unknown)", error: error.error }
544
547
  break
545
548
  }
546
- const violation = (options.invariants ?? []).reduce<{ readonly invariant: string; readonly message: string } | undefined>(
547
- (found, invariant) => {
548
- if (found) return found
549
- const message = inspect(invariant.inspector)
550
- return message === undefined ? undefined : { invariant: invariant.name, message }
551
- },
552
- undefined
553
- )
554
- if (violation) {
555
- stop = { reason: "invariant", frame, ...violation }
549
+ let checked: Stop | undefined
550
+ for (const invariant of options.invariants ?? []) {
551
+ let message: string | undefined
552
+ try {
553
+ message = inspect(invariant.inspector)
554
+ } catch (error) {
555
+ checked = { reason: "invariant-threw", frame, invariant: invariant.name, error }
556
+ break
557
+ }
558
+ if (message !== undefined) {
559
+ checked = { reason: "invariant", frame, invariant: invariant.name, message }
560
+ break
561
+ }
562
+ }
563
+ if (checked) {
564
+ stop = checked
556
565
  break
557
566
  }
558
567
  if (runOptions.until?.(frame)) {
@@ -791,6 +800,8 @@ const renderRun = (result: RunResult, format: Format.ValueOptions): string => {
791
800
  return `${head}, DEFECT at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
792
801
  case "invariant":
793
802
  return `${head}, INVARIANT "${stop.invariant}" violated at f${stop.frame}: ${stop.message}`
803
+ case "invariant-threw":
804
+ return `${head}, INVARIANT "${stop.invariant}" threw at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
794
805
  case "tickOrder":
795
806
  return `${head}, NOT RUN after f${stop.frame}: ${stop.issues.join("; ")}`
796
807
  case "ignored-failure":
package/src/cli.ts CHANGED
@@ -8,12 +8,28 @@
8
8
  * prints every lint of its schedules with its fix, and exits with 1 when one
9
9
  * is a warning. Info-level lints are printed and do not fail.
10
10
  *
11
+ * It also checks simulation coverage: every module that importing `<entry>`
12
+ * loads (inside the directory of `.oxlintrc.json` in the working directory,
13
+ * outside `node_modules`) must have `ritmo/keep-simulation-headless` on in that
14
+ * config, so the oxlint simulation rules check it. Each one that does not is
15
+ * printed as `uncovered-simulation-module` and exits with 1. Only modules
16
+ * loaded by importing the entry are checked: modules imported inside
17
+ * `lintTarget` (such as render schedules passed to `describe`) or loaded later
18
+ * are host code and are not. Type-only imports never load and are not checked.
19
+ * A missing or unreadable config, one with `extends`, or one that never turns
20
+ * the rule on prints why the check was skipped and does not fail.
21
+ *
22
+ * Exit codes: 0 ok, 1 lint warning or uncovered module, 2 usage error.
23
+ * Requires Node 22.15 or later for `module.registerHooks`; on older Node it
24
+ * prints that coverage was not checked.
25
+ *
11
26
  * @module cli
12
27
  * @docGroup devtools
13
28
  */
14
29
  import { resolve } from "node:path"
15
30
  import { pathToFileURL } from "node:url"
16
31
 
32
+ import * as SimulationCoverage from "./internal/simulationCoverage.ts"
17
33
  import * as Lint from "./Lint.ts"
18
34
 
19
35
  const usage = "usage: ritmo-devtools lint <entry>\n <entry> exports lintTarget: () => { runtime, schedules, describe?, hostEvents? } (see the Lint module)"
@@ -36,7 +52,10 @@ const main = async (args: ReadonlyArray<string>): Promise<number> => {
36
52
  console.error(usage)
37
53
  return 2
38
54
  }
55
+ const loads = SimulationCoverage.recordLoads()
39
56
  const loaded: unknown = await import(pathToFileURL(resolve(entry)).href)
57
+ // Snapshot before lintTarget runs: modules it imports (render schedules to describe) are host code.
58
+ const simulationModules = loads?.()
40
59
  const make = isRecord(loaded) ? loaded["lintTarget"] : undefined
41
60
  if (typeof make !== "function") {
42
61
  console.error(`${entry} must export lintTarget: a function returning { runtime, schedules, describe? } (see the Lint module)`)
@@ -49,7 +68,14 @@ const main = async (args: ReadonlyArray<string>): Promise<number> => {
49
68
  }
50
69
  const report = Lint.run(target)
51
70
  console.log(report.text)
52
- return report.data.ok ? 0 : 1
71
+ if (simulationModules === undefined) {
72
+ console.log("simulation coverage not checked: needs Node 22.15 or later (module.registerHooks)")
73
+ return report.data.ok ? 0 : 1
74
+ }
75
+ const coverage = SimulationCoverage.check(process.cwd(), resolve(entry), simulationModules)
76
+ const text = SimulationCoverage.format(coverage)
77
+ if (text !== "") console.log(text)
78
+ return report.data.ok && (!coverage.checked || coverage.uncovered.length === 0) ? 0 : 1
53
79
  }
54
80
 
55
81
  process.exitCode = await main(process.argv.slice(2))
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Simulation coverage for the `ritmo-devtools lint` CLI (Node only): which
3
+ * modules the simulation loads that the oxlint simulation rules
4
+ * (`ritmo/keep-simulation-headless` and its neighbours) do not cover.
5
+ *
6
+ * @internal
7
+ */
8
+ import { readFileSync, realpathSync } from "node:fs"
9
+ import * as Module from "node:module"
10
+ import { dirname, isAbsolute, join, matchesGlob, relative, sep } from "node:path"
11
+ import { fileURLToPath } from "node:url"
12
+
13
+ const configName = ".oxlintrc.json"
14
+ const rule = "ritmo/keep-simulation-headless"
15
+
16
+ /** Starts recording every `file:` module Node loads from now on. `undefined` when this Node has no `module.registerHooks` (before 22.15). */
17
+ export const recordLoads = (): (() => ReadonlyArray<string>) | undefined => {
18
+ if (typeof Module.registerHooks !== "function") return undefined
19
+ const urls = new Set<string>()
20
+ Module.registerHooks({
21
+ load: (url, context, nextLoad) => {
22
+ if (url.startsWith("file:")) urls.add(url)
23
+ return nextLoad(url, context)
24
+ }
25
+ })
26
+ return () => [...urls]
27
+ }
28
+
29
+ export type Coverage =
30
+ | { readonly checked: false; readonly reason: string }
31
+ | { readonly checked: true; readonly uncovered: ReadonlyArray<string> }
32
+
33
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
34
+ typeof value === "object" && value !== null && !Array.isArray(value)
35
+
36
+ /** Removes `//` and `/* *\/` comments outside strings, then trailing commas before `}` or `]`. */
37
+ const stripJsonc = (text: string): string => {
38
+ let out = ""
39
+ let index = 0
40
+ while (index < text.length) {
41
+ const char = text[index]!
42
+ if (char === "\"") {
43
+ let end = index + 1
44
+ while (end < text.length && text[end] !== "\"") end += text[end] === "\\" ? 2 : 1
45
+ out += text.slice(index, end + 1)
46
+ index = end + 1
47
+ } else if (char === "/" && text[index + 1] === "/") {
48
+ while (index < text.length && text[index] !== "\n") index++
49
+ } else if (char === "/" && text[index + 1] === "*") {
50
+ const end = text.indexOf("*/", index + 2)
51
+ index = end === -1 ? text.length : end + 2
52
+ } else {
53
+ out += char
54
+ index++
55
+ }
56
+ }
57
+ return out.replace(/("(?:[^"\\]|\\.)*")|,(\s*[}\]])/g, (match, string: string | undefined, close: string | undefined) =>
58
+ string !== undefined ? match : close!)
59
+ }
60
+
61
+ /** `true` on, `false` off, `undefined` when the value does not set the rule. */
62
+ const severity = (value: unknown): boolean | undefined => {
63
+ const level = Array.isArray(value) ? value[0] : value
64
+ if (level === "error" || level === "warn" || level === 1 || level === 2) return true
65
+ if (level === "off" || level === 0) return false
66
+ return undefined
67
+ }
68
+
69
+ const globs = (value: unknown): ReadonlyArray<string> =>
70
+ Array.isArray(value) ? value.filter((glob): glob is string => typeof glob === "string") : []
71
+
72
+ const matches = (file: string, patterns: ReadonlyArray<string>): boolean =>
73
+ patterns.some((pattern) => matchesGlob(file, pattern))
74
+
75
+ /**
76
+ * Reads `.oxlintrc.json` in `cwd` and returns the loaded modules inside its
77
+ * directory (outside `node_modules`, not the entry) where `ritmo/keep-simulation-headless`
78
+ * is not on, as posix paths relative to the config, sorted.
79
+ */
80
+ export const check = (cwd: string, entry: string, loaded: ReadonlyArray<string>): Coverage => {
81
+ const configPath = join(cwd, configName)
82
+ let text: string
83
+ try {
84
+ text = readFileSync(configPath, "utf8")
85
+ } catch {
86
+ return { checked: false, reason: `no ${configName} in ${cwd}` }
87
+ }
88
+ let config: unknown
89
+ try {
90
+ config = JSON.parse(stripJsonc(text))
91
+ } catch {
92
+ return { checked: false, reason: `${configName} is not valid JSON with comments` }
93
+ }
94
+ if (!isRecord(config)) return { checked: false, reason: `${configName} is not an object` }
95
+ if (config["extends"] !== undefined) return { checked: false, reason: `${configName} uses "extends", which this check does not follow` }
96
+ const topLevel = isRecord(config["rules"]) ? severity(config["rules"][rule]) : undefined
97
+ const overrides = (Array.isArray(config["overrides"]) ? config["overrides"] : []).filter(isRecord).map((override) => ({
98
+ files: globs(override["files"]),
99
+ setting: isRecord(override["rules"]) ? severity(override["rules"][rule]) : undefined
100
+ }))
101
+ if (topLevel !== true && !overrides.some((override) => override.setting === true)) {
102
+ return { checked: false, reason: `no rules in ${configName} turn on ${rule}` }
103
+ }
104
+ const ignored = globs(config["ignorePatterns"])
105
+ const root = realpathSync(dirname(configPath))
106
+ const entryPath = realpathSync(entry)
107
+ const uncovered = new Set<string>()
108
+ for (const url of loaded) {
109
+ let file: string
110
+ try {
111
+ file = realpathSync(fileURLToPath(url))
112
+ } catch {
113
+ continue
114
+ }
115
+ const path = relative(root, file)
116
+ if (file === entryPath || path === "" || path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path)) continue
117
+ const posix = path.split(sep).join("/")
118
+ if (posix.split("/").includes("node_modules")) continue
119
+ let on = topLevel === true
120
+ for (const override of overrides) {
121
+ if (override.setting !== undefined && matches(posix, override.files)) on = override.setting
122
+ }
123
+ if (!on || matches(posix, ignored)) uncovered.add(posix)
124
+ }
125
+ return { checked: true, uncovered: [...uncovered].sort() }
126
+ }
127
+
128
+ /** The CLI text for a coverage result: a "not checked" line, or one block per uncovered module. */
129
+ export const format = (coverage: Coverage): string =>
130
+ !coverage.checked
131
+ ? `simulation coverage not checked: ${coverage.reason}`
132
+ : coverage.uncovered.map((file) =>
133
+ `uncovered-simulation-module ${file}\n`
134
+ + ` The simulation loads this file, but the simulation rules in ${configName} do not cover it.\n`
135
+ + ` Add it to the simulation override's "files", or stop importing values from it.`
136
+ ).join("\n")
@@ -3,4 +3,4 @@
3
3
  * `package.json` by `scripts/sync-version.ts` (run by \`pnpm version-packages\`)
4
4
  * and checked by a test.
5
5
  */
6
- export const libraryVersion = "0.8.0"
6
+ export const libraryVersion = "0.10.0"