@mizchi/vlmkit-core 0.9.1 → 0.11.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 (57) hide show
  1. package/dist/apng.d.mts +42 -0
  2. package/dist/apng.mjs +199 -0
  3. package/dist/auth-state.d.mts +14 -3
  4. package/dist/auth-state.mjs +30 -6
  5. package/dist/bitmap-font.d.mts +48 -0
  6. package/dist/bitmap-font.mjs +945 -0
  7. package/dist/browser-launch.d.mts +65 -0
  8. package/dist/browser-launch.mjs +194 -0
  9. package/dist/cli-error.d.mts +73 -1
  10. package/dist/cli-error.mjs +164 -32
  11. package/dist/element-compare.mjs +8 -11
  12. package/dist/filmstrip.d.mts +121 -0
  13. package/dist/filmstrip.mjs +181 -0
  14. package/dist/gate-config.d.mts +107 -22
  15. package/dist/gate-config.mjs +138 -9
  16. package/dist/heatmap.d.mts +48 -4
  17. package/dist/heatmap.mjs +157 -12
  18. package/dist/index.d.mts +6 -4
  19. package/dist/index.mjs +4 -2
  20. package/dist/mask.d.mts +66 -2
  21. package/dist/mask.mjs +91 -4
  22. package/dist/page-load.d.mts +83 -0
  23. package/dist/page-load.mjs +116 -0
  24. package/dist/page-open.d.mts +123 -2
  25. package/dist/page-open.mjs +176 -6
  26. package/dist/plugin/args.d.mts +86 -0
  27. package/dist/plugin/args.mjs +162 -0
  28. package/dist/plugin/browser.d.mts +6 -0
  29. package/dist/plugin/browser.mjs +6 -0
  30. package/dist/plugin/cli-entry.d.mts +11 -0
  31. package/dist/plugin/cli-entry.mjs +69 -0
  32. package/dist/plugin/contract.d.mts +270 -0
  33. package/dist/plugin/contract.mjs +51 -0
  34. package/dist/plugin/index.d.mts +82 -0
  35. package/dist/plugin/index.mjs +81 -0
  36. package/dist/plugin/load.d.mts +36 -0
  37. package/dist/plugin/load.mjs +98 -0
  38. package/dist/plugin/registry.d.mts +60 -0
  39. package/dist/plugin/registry.mjs +160 -0
  40. package/dist/plugin/rule-tier.d.mts +65 -0
  41. package/dist/plugin/rule-tier.mjs +77 -0
  42. package/dist/plugin/rules.d.mts +112 -0
  43. package/dist/plugin/rules.mjs +188 -0
  44. package/dist/plugin/runner.d.mts +198 -0
  45. package/dist/plugin/runner.mjs +440 -0
  46. package/dist/png-utils.d.mts +31 -1
  47. package/dist/png-utils.mjs +24 -1
  48. package/dist/rect-overlap.d.mts +41 -0
  49. package/dist/rect-overlap.mjs +28 -0
  50. package/dist/run-ledger.d.mts +56 -2
  51. package/dist/run-ledger.mjs +102 -11
  52. package/dist/types.d.mts +60 -1
  53. package/dist/version.d.mts +20 -0
  54. package/dist/version.mjs +20 -0
  55. package/dist/webp.d.mts +31 -0
  56. package/dist/webp.mjs +105 -0
  57. package/package.json +17 -3
@@ -0,0 +1,270 @@
1
+ import { RunLedgerEntry } from "../run-ledger.mjs";
2
+
3
+ //#region src/plugin/contract.d.ts
4
+ /**
5
+ * Normalized finding severity.
6
+ *
7
+ * Gates disagreed on this vocabulary: most emit `"suspect" | "warn"`,
8
+ * `check integrity` emits `"fail" | "warn"`. `gate-exit.ts` documents the
9
+ * contract in terms of suspects ("a suspect fails the command"), so that is
10
+ * the normal form and adapters map into it. `info` exists for findings a
11
+ * gate wants to report without ever affecting a verdict.
12
+ */
13
+ type FindingSeverity = "suspect" | "warn" | "info";
14
+ declare const FINDING_SEVERITIES: readonly FindingSeverity[];
15
+ /**
16
+ * One normalized finding. `rule` is the gate-local rule id — the same
17
+ * string the gate's own report calls `kind`, so a migration is a rename
18
+ * rather than a re-classification.
19
+ */
20
+ interface Finding {
21
+ /** Gate-local rule id, e.g. `text-collision`. Must exist in the gate's rule table. */
22
+ rule: string;
23
+ severity: FindingSeverity;
24
+ message: string;
25
+ /** CSS selector the finding is attributed to, when the gate can attribute it. */
26
+ selector?: string;
27
+ /** Viewport width the finding was observed at, for multi-viewport gates. */
28
+ viewport?: number;
29
+ /** Arbitrary structured evidence, passed through to JSON output verbatim. */
30
+ evidence?: Record<string, unknown>;
31
+ }
32
+ /**
33
+ * A rule is the unit a user can re-tune or switch off, and the unit a
34
+ * report attributes a finding to.
35
+ *
36
+ * `check layout` already proved this shape works as data (`LayoutRule` +
37
+ * `evaluateLayoutRule`); this generalizes it. Declaring the table up front
38
+ * is what makes rule-granular settings possible: without it, a config
39
+ * saying `"text-collision": "off"` cannot be distinguished from a typo, and
40
+ * suppression has to stay whole-gate (`vlmkit.gates.json` could only
41
+ * silence `check integrity` entirely, or append a flag the gate happened to
42
+ * implement).
43
+ */
44
+ interface RuleDefinition {
45
+ /** Gate-local id. Stable — it appears in configs and reports. */
46
+ id: string;
47
+ /** One-line human name, used in `--rules` listings. */
48
+ title: string;
49
+ /**
50
+ * The rule's *declared* severity: the highest severity a violation of it
51
+ * can carry, and what `--rules` shows a reader deciding whether to tune it.
52
+ *
53
+ * A gate may still emit a lower severity for an individual finding when its
54
+ * evidence is weaker — `check integrity` downgrades a `js-error` to `warn`
55
+ * when the error fired after load, and a `failed-stylesheet` to `warn` when
56
+ * the sheet was cross-origin. The runner preserves that judgment; only an
57
+ * explicit rule setting overrides it.
58
+ */
59
+ severity: FindingSeverity;
60
+ /** Why this rule exists / what a violation means. Shown by `vlmkit rules <gate>`. */
61
+ docs?: string;
62
+ }
63
+ /**
64
+ * Declarative description of a gate's inputs.
65
+ *
66
+ * The CLI can already read flags off argv itself, so this exists for the
67
+ * consumers that cannot: the MCP server needs a JSON schema, and the docs
68
+ * need a flag table. A gate still owns its `parse`, because several gates
69
+ * have argument shapes no generic schema expresses well (`--allow`
70
+ * mini-DSL, `--viewports 1280,768,375`). `inputs` is the machine-readable
71
+ * summary of what `parse` accepts, not a replacement for it.
72
+ */
73
+ interface GateInput {
74
+ /** Flag name without dashes, or `"source"` / `"target"` for positionals. */
75
+ name: string;
76
+ /**
77
+ * Display name in help output, when it differs from `name`. Every gate's
78
+ * documented usage line says `<html-or-url>`, which is a better prompt for
79
+ * a human than the option key the schema needs.
80
+ */
81
+ placeholder?: string;
82
+ kind: "path-or-url" | "path" | "string" | "number" | "boolean" | "string-list" | "number-list";
83
+ description: string;
84
+ required?: boolean;
85
+ /** Positional index; omit for flags. */
86
+ positional?: number;
87
+ /** Closed value set, for `--wait-until`-style flags. */
88
+ choices?: readonly string[];
89
+ /** Repeatable flag (`--allow`, `--only`). */
90
+ repeatable?: boolean;
91
+ /** Default, for help text only. */
92
+ defaultDescription?: string;
93
+ }
94
+ /** Everything the runner hands a gate that the gate should not read from globals. */
95
+ interface GateContext {
96
+ cwd: string;
97
+ /** Raw argv after the command tokens, for gates that need a flag `parse` dropped. */
98
+ argv: readonly string[];
99
+ /** True when the caller asked for JSON, so a gate can skip building prose. */
100
+ json: boolean;
101
+ }
102
+ /**
103
+ * What kind of question a gate answers.
104
+ *
105
+ * These are not CLI groups. `check`/`scan`/`stress`/`verify` say how a command
106
+ * is spelled; a category says what a failure MEANS, which is what a reader
107
+ * picking gates for a project actually needs. `scan scroll` and `check
108
+ * breakpoints` are spelled differently and answer the same kind of question.
109
+ *
110
+ * Kept small on purpose. A taxonomy with a bucket per gate classifies nothing,
111
+ * and the useful cut is the one a person makes when deciding what to run:
112
+ * "is the page broken", "does it behave", "does it look like our system",
113
+ * "is it done", "is my tooling working".
114
+ */
115
+ declare const GATE_CATEGORIES: {
116
+ readonly correctness: "Is the page broken, on its own terms? No reference needed.";
117
+ readonly behavior: "Does it respond correctly to size, scroll, motion and input?";
118
+ readonly "design-system": "Does it conform to the design language the project declares?";
119
+ readonly verdict: "Is this attempt done? Aggregates other signals into one answer.";
120
+ readonly infrastructure: "Is the measurement toolchain itself working?";
121
+ };
122
+ type GateCategory = keyof typeof GATE_CATEGORIES;
123
+ declare const GATE_CATEGORY_ORDER: readonly GateCategory[];
124
+ /**
125
+ * A gate definition.
126
+ *
127
+ * `Report` is the gate's existing report type — migration wraps the
128
+ * existing `run*` / `format*` functions rather than rewriting them, so the
129
+ * measurement code stays untouched and the diff stays reviewable.
130
+ */
131
+ /**
132
+ * What a gate's `format` may ask about the project's rule settings.
133
+ *
134
+ * Deliberately one question rather than the whole `AppliedRules` object: a formatter
135
+ * needs "what is this rule worth now", and handing it the suppressed/retuned lists
136
+ * would invite it to re-derive the runner's decisions and disagree with them.
137
+ */
138
+ interface RuleView {
139
+ /**
140
+ * Effective setting for a rule id, after project config and `--rule`, falling back to the
141
+ * severity the gate DECLARED for it.
142
+ *
143
+ * That fallback is why `setting` exists. `applyRuleSettings` re-tunes a finding only when
144
+ * there is an explicit setting — a gate is free to emit a severity that differs from its
145
+ * table (integrity emits `js-error` as a warn after load and a fail during construction),
146
+ * and that judgement survives. A formatter reading only `effective` cannot reproduce this,
147
+ * and `check integrity` printed the proof: a post-load `js-error` rendered as
148
+ * `DEFECTS (1 fail, 0 warn)` directly above the runner's `exits 0 — 1 warn(s)`.
149
+ */
150
+ effective(ruleId: string): "off" | FindingSeverity;
151
+ /**
152
+ * The EXPLICIT project setting for a rule id, or `undefined` when nobody set one.
153
+ *
154
+ * This is the one a formatter wants: `setting(rule) ?? theSeverityTheFindingWasEmittedAt`
155
+ * is exactly what the runner does to the finding list, so the prose and the exit code
156
+ * cannot disagree.
157
+ */
158
+ setting(ruleId: string): "off" | FindingSeverity | undefined;
159
+ }
160
+ interface GateDefinition<Report = unknown, Options = unknown> {
161
+ /**
162
+ * Stable machine id, `<group>.<leaf>` — `check.integrity`. Used by rule
163
+ * settings, the ledger, and plugin conflict detection. Never localized,
164
+ * never renamed without a deprecation.
165
+ */
166
+ id: string;
167
+ /**
168
+ * CLI path tokens: `["check", "integrity"]`. This is also the key
169
+ * `vlmkit.gates.json` matches, which is why the config can now be
170
+ * validated against the registry instead of trusting the string.
171
+ */
172
+ command: readonly string[];
173
+ title: string;
174
+ /** One-line capability summary — CLI group help, MCP tool description. */
175
+ summary: string;
176
+ /**
177
+ * What KIND of question this gate answers. See `GATE_CATEGORIES`.
178
+ *
179
+ * Deliberately separate from the plugin a gate ships in. A plugin is a unit
180
+ * of distribution — it is where the code lives and what a project installs.
181
+ * A category is a unit of meaning: `check crater` ships in `vlmkit-capture`
182
+ * because that is where the Crater client is, and it is `infrastructure`
183
+ * because that is the question it answers. One plugin may hold gates in
184
+ * several categories, and one category spans plugins — so collapsing the two
185
+ * would force a wrong choice on anyone adding a gate.
186
+ *
187
+ * Optional, and uncategorized gates are listed under "other" rather than
188
+ * rejected: a project's first house gate should not have to pick a taxonomy
189
+ * before it can run.
190
+ */
191
+ category?: GateCategory;
192
+ /** Full `--help` body, minus the shared flags the runner appends. */
193
+ usage?: string;
194
+ /** Rule table. Every `Finding.rule` a gate emits must appear here. */
195
+ rules: readonly RuleDefinition[];
196
+ inputs?: readonly GateInput[];
197
+ /**
198
+ * Parse argv into the gate's options. Throw `UsageError` for bad input —
199
+ * the runner turns that into usage output plus exit 1, so gates stop
200
+ * calling `process.exit` from inside a parser.
201
+ */
202
+ parse: (argv: readonly string[], ctx: GateContext) => Options;
203
+ /** Do the measurement. No printing, no exit codes. */
204
+ run: (options: Options, ctx: GateContext) => Promise<Report> | Report;
205
+ /**
206
+ * Project the report onto the normalized finding list.
207
+ *
208
+ * `options` is passed because a flag can legitimately decide a finding's
209
+ * severity: `check crater --require` promotes an unreachable backend from
210
+ * `info` to `suspect`, which is the whole purpose of the flag. Most gates
211
+ * ignore the second argument.
212
+ */
213
+ findings: (report: Report, options: Options) => readonly Finding[];
214
+ /**
215
+ * Human output. The runner decides whether it is called at all (`--json`).
216
+ *
217
+ * `rules` is how a gate's prose learns what the project's rule settings did. Without
218
+ * it, `--rule x=off` printed `3 finding(s) suppressed by rule settings` and then
219
+ * printed all three anyway, because the prose is rendered from the gate's own report
220
+ * while suppression happens on the normalized finding list. v6's adopting agent hit
221
+ * the re-tuning half of the same gap: "with `component-drift=info` the output still
222
+ * prints `verdict: DRIFT` and still renders the finding with a yellow `!`. […] So the
223
+ * noise I re-tuned away is still in every CI log."
224
+ *
225
+ * Optional, and a gate that ignores it renders exactly as before — so this is not a
226
+ * migration all 27 gates must do at once. A gate whose prose lists findings should
227
+ * consult it; one that only prints a summary has nothing to consult it about.
228
+ */
229
+ format: (report: Report, rules?: RuleView) => string;
230
+ /**
231
+ * One line describing what was measured — not what was wrong. The findings
232
+ * already say what was wrong; this says the context needed to read them
233
+ * ("checked 768, 1024px", "3 container(s), page overflow-x 0px").
234
+ *
235
+ * Two consumers need exactly this and cannot get it from `format` (too long)
236
+ * or from the findings (a clean run has none): `verify markup`, which folds
237
+ * other gates into its verdict and names them in its kickback, and the MCP
238
+ * server's one-line verdict. Optional — the runner falls back to the finding
239
+ * counts, which is correct but tells a reader less.
240
+ */
241
+ headline?: (report: Report) => string;
242
+ /**
243
+ * Ledger headline. Returning `null` opts a gate out. The runner does the
244
+ * appending, so `VLMKIT_NO_LEDGER` and failure-swallowing stay in one place.
245
+ */
246
+ ledger?: (report: Report, options: Options) => RunLedgerEntry | null;
247
+ }
248
+ /** A definition with its type parameters erased, for registries and lists. */
249
+ type AnyGateDefinition = GateDefinition<any, any>;
250
+ /**
251
+ * A plugin is a named bundle of gates. Built-in gates ship as plugins too
252
+ * (`vlmkit-markup` exports one), so "add a gate" is the same operation for
253
+ * this repo and for a third party — there is no privileged built-in path.
254
+ */
255
+ interface VlmkitPlugin {
256
+ /** Unique plugin name, reported in conflict errors and `vlmkit rules --plugins`. */
257
+ name: string;
258
+ version?: string;
259
+ gates: readonly AnyGateDefinition[];
260
+ }
261
+ /** Identity helper that pins the type parameters at the definition site. */
262
+ declare function defineGate<Report, Options>(definition: GateDefinition<Report, Options>): GateDefinition<Report, Options>;
263
+ /** Identity helper for plugin authors; also the documented entry point. */
264
+ declare function definePlugin(plugin: VlmkitPlugin): VlmkitPlugin;
265
+ /** `check integrity` — the human-facing form of `command`. */
266
+ declare function gateCommandString(gate: AnyGateDefinition): string;
267
+ /** Fully-qualified rule reference used in configs: `check.integrity/text-collision`. */
268
+ declare function ruleRef(gateId: string, ruleId: string): string;
269
+ //#endregion
270
+ export { AnyGateDefinition, FINDING_SEVERITIES, Finding, FindingSeverity, GATE_CATEGORIES, GATE_CATEGORY_ORDER, GateCategory, GateContext, GateDefinition, GateInput, RuleDefinition, RuleView, VlmkitPlugin, defineGate, definePlugin, gateCommandString, ruleRef };
@@ -0,0 +1,51 @@
1
+ //#region src/plugin/contract.ts
2
+ const FINDING_SEVERITIES = [
3
+ "suspect",
4
+ "warn",
5
+ "info"
6
+ ];
7
+ /**
8
+ * What kind of question a gate answers.
9
+ *
10
+ * These are not CLI groups. `check`/`scan`/`stress`/`verify` say how a command
11
+ * is spelled; a category says what a failure MEANS, which is what a reader
12
+ * picking gates for a project actually needs. `scan scroll` and `check
13
+ * breakpoints` are spelled differently and answer the same kind of question.
14
+ *
15
+ * Kept small on purpose. A taxonomy with a bucket per gate classifies nothing,
16
+ * and the useful cut is the one a person makes when deciding what to run:
17
+ * "is the page broken", "does it behave", "does it look like our system",
18
+ * "is it done", "is my tooling working".
19
+ */
20
+ const GATE_CATEGORIES = {
21
+ correctness: "Is the page broken, on its own terms? No reference needed.",
22
+ behavior: "Does it respond correctly to size, scroll, motion and input?",
23
+ "design-system": "Does it conform to the design language the project declares?",
24
+ verdict: "Is this attempt done? Aggregates other signals into one answer.",
25
+ infrastructure: "Is the measurement toolchain itself working?"
26
+ };
27
+ const GATE_CATEGORY_ORDER = [
28
+ "correctness",
29
+ "behavior",
30
+ "design-system",
31
+ "verdict",
32
+ "infrastructure"
33
+ ];
34
+ /** Identity helper that pins the type parameters at the definition site. */
35
+ function defineGate(definition) {
36
+ return definition;
37
+ }
38
+ /** Identity helper for plugin authors; also the documented entry point. */
39
+ function definePlugin(plugin) {
40
+ return plugin;
41
+ }
42
+ /** `check integrity` — the human-facing form of `command`. */
43
+ function gateCommandString(gate) {
44
+ return gate.command.join(" ");
45
+ }
46
+ /** Fully-qualified rule reference used in configs: `check.integrity/text-collision`. */
47
+ function ruleRef(gateId, ruleId) {
48
+ return `${gateId}/${ruleId}`;
49
+ }
50
+ //#endregion
51
+ export { FINDING_SEVERITIES, GATE_CATEGORIES, GATE_CATEGORY_ORDER, defineGate, definePlugin, gateCommandString, ruleRef };
@@ -0,0 +1,82 @@
1
+ import { hasFlag, readAll, readChoice, readFlag, readInt, readNumber, readPositionals, tokenizeCommand } from "../arg-reader.mjs";
2
+ import { UsageError } from "../cli-error.mjs";
3
+ import { AnyGateDefinition, FINDING_SEVERITIES, Finding, FindingSeverity, GATE_CATEGORIES, GATE_CATEGORY_ORDER, GateCategory, GateContext, GateDefinition, GateInput, RuleDefinition, RuleView, VlmkitPlugin, defineGate, definePlugin, gateCommandString, ruleRef } from "./contract.mjs";
4
+ import { AppliedRules, RULE_SETTINGS, RuleSetting, RuleSettingEntry, RuleSettings } from "./rules.mjs";
5
+ import { DEFAULT_PAGE_LOAD_TIMEOUT_MS, DEFAULT_PAGE_LOAD_WAIT_UNTIL, PAGE_LOAD_INPUTS, PAGE_LOAD_VALUE_FLAGS, PAGE_LOAD_WAIT_UNTIL, PageLoadOptions, PageLoadWaitUntil, navigationOptions, parsePageLoad, pickPageLoad } from "../page-load.mjs";
6
+ import { firstPositional, firstPositionalOrUndefined, numberList, numberListFloat, optionalInt, runOutputDir, viewportFlag, vlmFlag, withoutOptionalValue } from "./args.mjs";
7
+ import { isCliEntry } from "./cli-entry.mjs";
8
+ import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "../terminal-colors.mjs";
9
+ import { CONFIG_CANDIDATES, CONFIG_FILE, STATE_DIR, debugEnabled, readEnv, resolveStatePath } from "../project-config.mjs";
10
+
11
+ //#region src/plugin/index.d.ts
12
+ /**
13
+ * `@mizchi/vlmkit-core/plugin` — the whole surface a gate plugin needs.
14
+ *
15
+ * A third-party gate has always been able to exist: `defineGate` and
16
+ * `definePlugin` are exported, `vlmkit.config.json` takes a `"plugins"` array,
17
+ * and a plugin's gate gets the same `--help`, `--json`, rule settings, ledger
18
+ * and exit-code contract as `check integrity`. What was missing is a *declared*
19
+ * entry point. An author had to deep-import five internal files
20
+ * (`plugin/contract.ts`, `page-load.ts`, `arg-reader.ts`, `cli-error.ts`,
21
+ * `terminal-colors.ts`) and guess which of them counted as public.
22
+ *
23
+ * Those five are exactly what the 27 bundled gates import — counted, not
24
+ * guessed: 40 imports of the contract, 18 of `page-load`, 15 of `arg-reader`,
25
+ * 11 of `cli-error`, 1 of `terminal-colors`. So this module re-exports that set
26
+ * and nothing else. If a plugin needs something absent here, that is a gap in
27
+ * this file worth reporting rather than a reason to reach past it.
28
+ *
29
+ * ```ts
30
+ * import {
31
+ * defineGate, definePlugin, firstPositional, readInt,
32
+ * PAGE_LOAD_INPUTS, parsePageLoad, UsageError, DIM, RESET,
33
+ * } from "@mizchi/vlmkit-core/plugin";
34
+ * ```
35
+ *
36
+ * ## The four functions
37
+ *
38
+ * A gate is a declaration plus four functions, and the split is what keeps the
39
+ * contract enforceable:
40
+ *
41
+ * - `parse(argv, ctx)` — argv to your own options type. Throw `UsageError`.
42
+ * - `run(options, ctx)` — the measurement. Returns YOUR report shape.
43
+ * - `findings(report, options)` — project the report onto `Finding[]`. The one
44
+ * place per-rule work happens, so the runner can suppress and re-tune.
45
+ * - `format(report, rules?)` — the prose. `rules` is a `RuleView`: ask
46
+ * `effective(ruleId)` what a rule is worth *now* rather than re-deriving the
47
+ * runner's decisions and risking disagreement with them.
48
+ *
49
+ * What a gate deliberately cannot do: print, set an exit code, decide `--json`,
50
+ * or write the ledger. The runner owns all four. A gate that printed would break
51
+ * `--json` for every consumer downstream of it.
52
+ *
53
+ * ## Rules are declared, so they are addressable
54
+ *
55
+ * Every `Finding.rule` must appear in the gate's `rules` table. That is what
56
+ * makes `--rule <gateId>/<ruleId>=off|warn|info|suspect`, `vlmkit rules`, and
57
+ * `vlmkit.gates.json`'s per-page settings work for a plugin gate on day one. An
58
+ * undeclared rule id cannot be documented or configured, so the runner reports
59
+ * it as a gate bug.
60
+ *
61
+ * See `docs/authoring-gates.md` for the field-by-field walkthrough and
62
+ * `examples/gate-plugin/` for a runnable two-gate plugin that imports only this
63
+ * module.
64
+ */
65
+ /**
66
+ * The plugin API's compatibility marker.
67
+ *
68
+ * Bumped only when a change would break an existing plugin — a required field
69
+ * added to `GateDefinition`, a callback's arguments changed, a helper removed.
70
+ * Additive changes (a new optional field, a new export here) do not bump it.
71
+ *
72
+ * A plugin may assert against it to fail with its own message rather than a
73
+ * `TypeError` three frames into the registry:
74
+ *
75
+ * ```ts
76
+ * import { PLUGIN_API_VERSION } from "@mizchi/vlmkit-core/plugin";
77
+ * if (PLUGIN_API_VERSION !== 1) throw new Error("built for plugin API 1");
78
+ * ```
79
+ */
80
+ declare const PLUGIN_API_VERSION: 1;
81
+ //#endregion
82
+ export { type AnyGateDefinition, type AppliedRules, BOLD, CONFIG_CANDIDATES, CONFIG_FILE, CYAN, DEFAULT_PAGE_LOAD_TIMEOUT_MS, DEFAULT_PAGE_LOAD_WAIT_UNTIL, DIM, FINDING_SEVERITIES, type Finding, type FindingSeverity, GATE_CATEGORIES, GATE_CATEGORY_ORDER, GREEN, type GateCategory, type GateContext, type GateDefinition, type GateInput, PAGE_LOAD_INPUTS, PAGE_LOAD_VALUE_FLAGS, PAGE_LOAD_WAIT_UNTIL, PLUGIN_API_VERSION, type PageLoadOptions, type PageLoadWaitUntil, RED, RESET, RULE_SETTINGS, type RuleDefinition, type RuleSetting, type RuleSettingEntry, type RuleSettings, type RuleView, STATE_DIR, UsageError, type VlmkitPlugin, YELLOW, debugEnabled, defineGate, definePlugin, firstPositional, firstPositionalOrUndefined, gateCommandString, hasFlag, hr, isCliEntry, navigationOptions, numberList, numberListFloat, optionalInt, parsePageLoad, pickPageLoad, readAll, readChoice, readEnv, readFlag, readInt, readNumber, readPositionals, resolveStatePath, ruleRef, runOutputDir, tokenizeCommand, viewportFlag, vlmFlag, withoutOptionalValue };
@@ -0,0 +1,81 @@
1
+ import { UsageError } from "../cli-error.mjs";
2
+ import { hasFlag, readAll, readChoice, readFlag, readInt, readNumber, readPositionals, tokenizeCommand } from "../arg-reader.mjs";
3
+ import { isCliEntry } from "./cli-entry.mjs";
4
+ import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "../terminal-colors.mjs";
5
+ import { FINDING_SEVERITIES, GATE_CATEGORIES, GATE_CATEGORY_ORDER, defineGate, definePlugin, gateCommandString, ruleRef } from "./contract.mjs";
6
+ import { RULE_SETTINGS } from "./rules.mjs";
7
+ import { DEFAULT_PAGE_LOAD_TIMEOUT_MS, DEFAULT_PAGE_LOAD_WAIT_UNTIL, PAGE_LOAD_INPUTS, PAGE_LOAD_VALUE_FLAGS, PAGE_LOAD_WAIT_UNTIL, navigationOptions, parsePageLoad, pickPageLoad } from "../page-load.mjs";
8
+ import { CONFIG_CANDIDATES, CONFIG_FILE, STATE_DIR, debugEnabled, readEnv, resolveStatePath } from "../project-config.mjs";
9
+ import { firstPositional, firstPositionalOrUndefined, numberList, numberListFloat, optionalInt, runOutputDir, viewportFlag, vlmFlag, withoutOptionalValue } from "./args.mjs";
10
+ //#region src/plugin/index.ts
11
+ /**
12
+ * `@mizchi/vlmkit-core/plugin` — the whole surface a gate plugin needs.
13
+ *
14
+ * A third-party gate has always been able to exist: `defineGate` and
15
+ * `definePlugin` are exported, `vlmkit.config.json` takes a `"plugins"` array,
16
+ * and a plugin's gate gets the same `--help`, `--json`, rule settings, ledger
17
+ * and exit-code contract as `check integrity`. What was missing is a *declared*
18
+ * entry point. An author had to deep-import five internal files
19
+ * (`plugin/contract.ts`, `page-load.ts`, `arg-reader.ts`, `cli-error.ts`,
20
+ * `terminal-colors.ts`) and guess which of them counted as public.
21
+ *
22
+ * Those five are exactly what the 27 bundled gates import — counted, not
23
+ * guessed: 40 imports of the contract, 18 of `page-load`, 15 of `arg-reader`,
24
+ * 11 of `cli-error`, 1 of `terminal-colors`. So this module re-exports that set
25
+ * and nothing else. If a plugin needs something absent here, that is a gap in
26
+ * this file worth reporting rather than a reason to reach past it.
27
+ *
28
+ * ```ts
29
+ * import {
30
+ * defineGate, definePlugin, firstPositional, readInt,
31
+ * PAGE_LOAD_INPUTS, parsePageLoad, UsageError, DIM, RESET,
32
+ * } from "@mizchi/vlmkit-core/plugin";
33
+ * ```
34
+ *
35
+ * ## The four functions
36
+ *
37
+ * A gate is a declaration plus four functions, and the split is what keeps the
38
+ * contract enforceable:
39
+ *
40
+ * - `parse(argv, ctx)` — argv to your own options type. Throw `UsageError`.
41
+ * - `run(options, ctx)` — the measurement. Returns YOUR report shape.
42
+ * - `findings(report, options)` — project the report onto `Finding[]`. The one
43
+ * place per-rule work happens, so the runner can suppress and re-tune.
44
+ * - `format(report, rules?)` — the prose. `rules` is a `RuleView`: ask
45
+ * `effective(ruleId)` what a rule is worth *now* rather than re-deriving the
46
+ * runner's decisions and risking disagreement with them.
47
+ *
48
+ * What a gate deliberately cannot do: print, set an exit code, decide `--json`,
49
+ * or write the ledger. The runner owns all four. A gate that printed would break
50
+ * `--json` for every consumer downstream of it.
51
+ *
52
+ * ## Rules are declared, so they are addressable
53
+ *
54
+ * Every `Finding.rule` must appear in the gate's `rules` table. That is what
55
+ * makes `--rule <gateId>/<ruleId>=off|warn|info|suspect`, `vlmkit rules`, and
56
+ * `vlmkit.gates.json`'s per-page settings work for a plugin gate on day one. An
57
+ * undeclared rule id cannot be documented or configured, so the runner reports
58
+ * it as a gate bug.
59
+ *
60
+ * See `docs/authoring-gates.md` for the field-by-field walkthrough and
61
+ * `examples/gate-plugin/` for a runnable two-gate plugin that imports only this
62
+ * module.
63
+ */
64
+ /**
65
+ * The plugin API's compatibility marker.
66
+ *
67
+ * Bumped only when a change would break an existing plugin — a required field
68
+ * added to `GateDefinition`, a callback's arguments changed, a helper removed.
69
+ * Additive changes (a new optional field, a new export here) do not bump it.
70
+ *
71
+ * A plugin may assert against it to fail with its own message rather than a
72
+ * `TypeError` three frames into the registry:
73
+ *
74
+ * ```ts
75
+ * import { PLUGIN_API_VERSION } from "@mizchi/vlmkit-core/plugin";
76
+ * if (PLUGIN_API_VERSION !== 1) throw new Error("built for plugin API 1");
77
+ * ```
78
+ */
79
+ const PLUGIN_API_VERSION = 1;
80
+ //#endregion
81
+ export { BOLD, CONFIG_CANDIDATES, CONFIG_FILE, CYAN, DEFAULT_PAGE_LOAD_TIMEOUT_MS, DEFAULT_PAGE_LOAD_WAIT_UNTIL, DIM, FINDING_SEVERITIES, GATE_CATEGORIES, GATE_CATEGORY_ORDER, GREEN, PAGE_LOAD_INPUTS, PAGE_LOAD_VALUE_FLAGS, PAGE_LOAD_WAIT_UNTIL, PLUGIN_API_VERSION, RED, RESET, RULE_SETTINGS, STATE_DIR, UsageError, YELLOW, debugEnabled, defineGate, definePlugin, firstPositional, firstPositionalOrUndefined, gateCommandString, hasFlag, hr, isCliEntry, navigationOptions, numberList, numberListFloat, optionalInt, parsePageLoad, pickPageLoad, readAll, readChoice, readEnv, readFlag, readInt, readNumber, readPositionals, resolveStatePath, ruleRef, runOutputDir, tokenizeCommand, viewportFlag, vlmFlag, withoutOptionalValue };
@@ -0,0 +1,36 @@
1
+ import { VlmkitPlugin } from "./contract.mjs";
2
+
3
+ //#region src/plugin/load.d.ts
4
+ interface LoadedPlugin {
5
+ plugin: VlmkitPlugin;
6
+ /** Specifier as written in the config, for error messages. */
7
+ specifier: string;
8
+ /** What was actually imported. */
9
+ resolved: string;
10
+ }
11
+ /** Injectable so tests do not need a module on disk. */
12
+ type PluginImporter = (specifier: string) => Promise<unknown>;
13
+ /**
14
+ * Validate the imported shape before it reaches the registry. The registry's
15
+ * own validation covers ids and rule tables; this covers "is this even a
16
+ * plugin", where the useful error names the specifier and the missing member
17
+ * rather than surfacing as `gates is not iterable` three frames deeper.
18
+ */
19
+ declare function asPlugin(moduleNamespace: unknown, specifier: string): VlmkitPlugin;
20
+ interface LoadPluginsOptions {
21
+ /** Directory relative specifiers resolve against. Defaults to cwd. */
22
+ baseDir?: string;
23
+ importer?: PluginImporter;
24
+ }
25
+ declare function loadPlugins(specifiers: readonly string[], options?: LoadPluginsOptions): Promise<LoadedPlugin[]>;
26
+ /**
27
+ * Read the `plugins` array out of `vlmkit.config.json`. Absent config or
28
+ * absent key means no plugins — a project that declares none must not pay a
29
+ * config-file requirement.
30
+ */
31
+ declare function readPluginSpecifiers(cwd?: string): {
32
+ specifiers: string[];
33
+ configPath: string | null;
34
+ };
35
+ //#endregion
36
+ export { LoadPluginsOptions, LoadedPlugin, PluginImporter, asPlugin, loadPlugins, readPluginSpecifiers };
@@ -0,0 +1,98 @@
1
+ import { CONFIG_FILE } from "../project-config.mjs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { isAbsolute, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ //#region src/plugin/load.ts
6
+ /**
7
+ * Loading third-party gate plugins.
8
+ *
9
+ * A plugin is an ordinary ES module whose default export (or named `plugin`
10
+ * export) is a `VlmkitPlugin`. Nothing about it is privileged: the bundled
11
+ * gates are loaded through the same `createGateRegistry` call, so a project
12
+ * that adds a house rule gets the same CLI help, the same `--json` shape,
13
+ * the same `vlmkit.gates.json` validation and the same exit-code contract as
14
+ * `check integrity`.
15
+ *
16
+ * Declared in `vlmkit.config.json`:
17
+ *
18
+ * { "plugins": ["./tools/house-gates.ts", "@acme/vlmkit-brand-gates"] }
19
+ *
20
+ * Relative specifiers resolve against the config's directory, not the
21
+ * process cwd — a plugin path that only works when you happen to run from
22
+ * the repo root is a trap in CI.
23
+ */
24
+ function isGateLike(value) {
25
+ const gate = value;
26
+ return Boolean(gate && typeof gate.id === "string" && Array.isArray(gate.command) && typeof gate.parse === "function" && typeof gate.run === "function" && typeof gate.findings === "function" && typeof gate.format === "function" && Array.isArray(gate.rules));
27
+ }
28
+ /**
29
+ * Validate the imported shape before it reaches the registry. The registry's
30
+ * own validation covers ids and rule tables; this covers "is this even a
31
+ * plugin", where the useful error names the specifier and the missing member
32
+ * rather than surfacing as `gates is not iterable` three frames deeper.
33
+ */
34
+ function asPlugin(moduleNamespace, specifier) {
35
+ const ns = moduleNamespace;
36
+ const candidate = ns?.default ?? ns?.plugin;
37
+ if (!candidate || typeof candidate !== "object") throw new Error(`${specifier}: expected a default export (or a named \`plugin\` export) created with definePlugin()`);
38
+ if (typeof candidate.name !== "string" || !candidate.name.trim()) throw new Error(`${specifier}: plugin.name is required`);
39
+ if (!Array.isArray(candidate.gates) || candidate.gates.length === 0) throw new Error(`${specifier}: plugin.gates must be a non-empty array of defineGate() results`);
40
+ const bad = candidate.gates.findIndex((gate) => !isGateLike(gate));
41
+ if (bad >= 0) throw new Error(`${specifier}: gates[${bad}] is not a gate definition — it must carry id, command, rules, parse, run, findings and format (use defineGate()).`);
42
+ return {
43
+ name: candidate.name.trim(),
44
+ ...candidate.version ? { version: candidate.version } : {},
45
+ gates: candidate.gates
46
+ };
47
+ }
48
+ async function loadPlugins(specifiers, options = {}) {
49
+ const baseDir = options.baseDir ?? process.cwd();
50
+ const importer = options.importer ?? ((spec) => import(spec));
51
+ const loaded = [];
52
+ for (const specifier of specifiers) {
53
+ const isPath = specifier.startsWith(".") || isAbsolute(specifier);
54
+ const resolved = isPath ? pathToFileURL(resolve(baseDir, specifier)).href : specifier;
55
+ let ns;
56
+ try {
57
+ ns = await importer(resolved);
58
+ } catch (e) {
59
+ throw new Error(`failed to load gate plugin "${specifier}"` + (isPath ? ` (resolved to ${resolved})` : "") + `: ${e instanceof Error ? e.message : String(e)}`);
60
+ }
61
+ loaded.push({
62
+ plugin: asPlugin(ns, specifier),
63
+ specifier,
64
+ resolved
65
+ });
66
+ }
67
+ return loaded;
68
+ }
69
+ /**
70
+ * Read the `plugins` array out of `vlmkit.config.json`. Absent config or
71
+ * absent key means no plugins — a project that declares none must not pay a
72
+ * config-file requirement.
73
+ */
74
+ function readPluginSpecifiers(cwd = process.cwd()) {
75
+ const configPath = resolve(cwd, CONFIG_FILE);
76
+ if (!existsSync(configPath)) return {
77
+ specifiers: [],
78
+ configPath: null
79
+ };
80
+ let data;
81
+ try {
82
+ data = JSON.parse(readFileSync(configPath, "utf-8"));
83
+ } catch (e) {
84
+ throw new Error(`${CONFIG_FILE} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);
85
+ }
86
+ const raw = data?.plugins;
87
+ if (raw === void 0) return {
88
+ specifiers: [],
89
+ configPath
90
+ };
91
+ if (!Array.isArray(raw) || raw.some((s) => typeof s !== "string" || !s.trim())) throw new Error(`${CONFIG_FILE}: "plugins" must be an array of module specifier strings`);
92
+ return {
93
+ specifiers: raw.map((s) => s.trim()),
94
+ configPath
95
+ };
96
+ }
97
+ //#endregion
98
+ export { asPlugin, loadPlugins, readPluginSpecifiers };