football-docs 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.
package/README.md CHANGED
@@ -29,6 +29,9 @@ MCP ([Model Context Protocol](https://modelcontextprotocol.io)) is a standard fo
29
29
 
30
30
  ## Quick start
31
31
 
32
+ The server needs Node.js 22.13 or newer. It uses Node's built-in SQLite, so no
33
+ native module is compiled at install time.
34
+
32
35
  ### Claude Code
33
36
 
34
37
  ```bash
@@ -84,7 +87,7 @@ Add to `claude_desktop_config.json`:
84
87
 
85
88
  | Tool | Description |
86
89
  |------|-------------|
87
- | `search_docs` | Full-text search across all provider docs. Filter by provider. Results include provenance (source URL, version). |
90
+ | `search_docs` | Full-text search across all provider docs. Filter by provider. Results include provenance (source URL, version), mark partial matches, and name query terms that no indexed doc mentions. |
88
91
  | `resolve_provider_id` | Resolve provider names and aliases to canonical indexed provider keys before searching. |
89
92
  | `get_provider_docs` | Retrieve docs for a resolved provider, optionally filtered by topic or category. |
90
93
  | `list_providers` | List all indexed providers and their doc coverage. |
@@ -135,7 +138,7 @@ development and tests always use the working tree's docs.
135
138
 
136
139
  ## Example queries
137
140
 
138
- - "What is Opta qualifier 76?" (big chance)
141
+ - "What is Opta qualifier 214?" (big chance)
139
142
  - "How does StatsBomb represent shot events?"
140
143
  - "Compare Opta and Wyscout coordinate systems"
141
144
  - "What player ID fields does Transfermarkt expose?"
@@ -148,12 +151,12 @@ development and tests always use the working tree's docs.
148
151
  | Provider | Chunks | Categories |
149
152
  |----------|--------|------------|
150
153
  | fast-forward | 250 | overview, getting-started, data-model, coordinate-system, orientations, layouts, transformations, distributed-compute, api-reference, 12 provider format pages |
151
- | StatsBomb | 237 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-lineups, xg-model, iq-metrics, player/team stats, player-mapping, identity-surfaces, data-provenance |
154
+ | StatsBomb | 244 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-lineups, xg-model, iq-metrics, player/team stats, player-mapping, identity-surfaces, data-provenance |
152
155
  | unravelsports | 202 | overview, installation, quickstart, concepts, graph converters, pressing intensity, formation detection, models, utils, american-football |
153
156
  | Wyscout | 165 | event-types, data-model, coordinate-system, api-access, api-endpoints, charting-analysis-metrics, glossary, identity-surfaces, data-provenance |
154
157
  | kloppy | 126 | data-model, usage, provider-mapping, tracking-rendering, event-derived-metrics |
155
158
  | floodlight | 144 | core data objects, io parsers (Tracab, DFL, Kinexon, Opta, SkillCorner, StatsBomb, StatsPerform, Second Spectrum), transforms, metrics, models, visualisation, guides |
156
- | SportMonks | 567 | full v3 endpoint reference (fixtures, livescores, leagues, seasons, states, types, statistics, brackets), syntax and includes, filtering, rate limits, error codes, changelog, plus curated event-types, data-model, api-access, charting-season-stories, identity-surfaces, data-provenance |
159
+ | SportMonks | 568 | full v3 endpoint reference (fixtures, livescores, leagues, seasons, states, types, statistics, brackets), syntax and includes, filtering, rate limits, error codes, changelog, plus curated event-types, data-model, api-access, charting-season-stories, identity-surfaces, data-provenance |
157
160
  | databallpy | 63 | data-model, overview, usage |
158
161
  | mplsoccer | 65 | overview, pitch-types, visualizations |
159
162
  | Impect | 79 | overview, data-model, event-types, coordinate-system, concepts, kpi-definitions, identity-surfaces, data-provenance |
@@ -174,7 +177,7 @@ development and tests always use the working tree's docs.
174
177
  | Soccerdonna | 5 | identity-surfaces, data-provenance |
175
178
  | Transfermarkt | 5 | identity-surfaces, data-provenance |
176
179
 
177
- **2,852 searchable chunks** across 26 providers and tools.
180
+ **2,860 searchable chunks** across 26 providers and tools.
178
181
 
179
182
  ESPN coverage consists of curated, dated observations of ESPN-hosted soccer
180
183
  endpoints, checked for eng.1 and esp.1. These observations are not an official API
@@ -205,6 +208,9 @@ trusting them.
205
208
  | BeSoccer | The vendor's published Postman collection — request vocabulary and parameters | `src/__tests__/provider-truth.test.ts` |
206
209
  | Driblab | The vendor's published API guide — endpoint paths and methods. Field and group names are not in CI: the guide disagrees with the live API on them, so the docs follow the live API, checked by hand on 2026-09-22 | `src/__tests__/provider-truth.test.ts` |
207
210
  | Impect | The public [open-data](https://github.com/ImpectAPI/open-data) repository | `src/__tests__/impect-open-data-validation.test.ts` |
211
+ | StatsBomb | ID and name pairs observed in a sample of the public [open data](https://github.com/statsbomb/open-data) (three matches per competition-season, at a pinned commit). IDs the sample lacks must be listed in both the Open Data Events specification and kloppy's parser. Regenerate with `pnpm statsbomb:truth` | `src/__tests__/statsbomb-truth.test.ts` |
212
+ | Opta | Stats Perform's F24 appendices, which have no machine-readable form. `data/opta-truth.json` holds each ID the docs use, with its label, checked by hand. The test also rejects the wrong meanings earlier docs gave some IDs (`WRONG_MEANINGS` in `src/opta-truth.ts`) | `src/__tests__/opta-truth.test.ts` |
213
+ | SportMonks | Type and state IDs as SportMonks publishes them on its definitions pages and in the types spreadsheet linked from its Types page (`data/sportmonks-types-truth.json`, fetched 2026-09-30). Not the full list: the complete one needs an API key | `src/__tests__/sportmonks-truth.test.ts` |
208
214
  | Reep | The public OpenAPI spec (endpoint paths and methods), and one release's manifest and column schema (CSV table list, columns used in the SQL examples, licence and exclusions) | `src/__tests__/provider-truth.test.ts`, `src/__tests__/reep.test.ts` |
209
215
 
210
216
  ESPN has a separate observation check in `src/__tests__/espn.test.ts`. It validates
@@ -393,10 +399,8 @@ workflow run without the workflow asking for it.
393
399
  Two consequences worth knowing:
394
400
 
395
401
  - **The release job runs on Node 24.** Trusted publishing needs npm >= 11.5.1 and
396
- Node 22 still ships npm 10. The whole job uses one Node version, because
397
- switching mid-job would leave `better-sqlite3`'s native binding built for the
398
- wrong ABI and `pnpm ingest` would fail on it. Node 24 is in the CI matrix for
399
- the same reason: a release must not be the first time the suite meets it.
402
+ Node 22 still ships npm 10. Node 24 is in the CI matrix so that a release is
403
+ not the first time the suite meets it.
400
404
  - **The release job does not cache dependencies.** This is the tree that gets
401
405
  published, so it is resolved fresh from the lockfile rather than rehydrated
402
406
  from a cache that earlier runs could have poisoned.
package/bin/serve.js CHANGED
@@ -2,6 +2,16 @@
2
2
  import { resolve, dirname } from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
 
5
+ // node:sqlite prints an ExperimentalWarning on Node 22 and 24. It is expected
6
+ // here, and MCP clients show a server's stderr to users, so drop that one warning.
7
+ const emitWarning = process.emitWarning;
8
+ process.emitWarning = (warning, ...args) => {
9
+ const type = typeof args[0] === "string" ? args[0] : args[0]?.type;
10
+ const message = typeof warning === "string" ? warning : warning?.message;
11
+ if (type === "ExperimentalWarning" && message?.includes("SQLite")) return;
12
+ return emitWarning.call(process, warning, ...args);
13
+ };
14
+
5
15
  const __dirname = dirname(fileURLToPath(import.meta.url));
6
16
  const { main } = await import(pathToFileURL(resolve(__dirname, "..", "dist", "index.js")).href);
7
17
 
package/data/docs.db CHANGED
Binary file
@@ -6,8 +6,8 @@
6
6
  * on what a usable file looks like, so the schema, the metadata keys and the
7
7
  * validation all live here.
8
8
  */
9
- import Database from "better-sqlite3";
10
9
  import { z } from "zod";
10
+ import { type Database } from "./sqlite.js";
11
11
  /** Bump when the table layout changes. Servers only use data with their own version. */
12
12
  export declare const DATA_SCHEMA_VERSION = 1;
13
13
  /**
@@ -67,16 +67,16 @@ export declare function compareVersions(a: string, b: string): number;
67
67
  * Read and check the meta table. Returns null when the file predates the table
68
68
  * (older releases, and the in-memory databases some tests build).
69
69
  */
70
- export declare function readMeta(db: Database.Database): DataMeta | null;
70
+ export declare function readMeta(db: Database): DataMeta | null;
71
71
  export interface MetaInput {
72
72
  dataStamp: string;
73
73
  commit: string | null;
74
74
  providersJson: string;
75
75
  }
76
76
  /** Replace the meta table's contents. Used by ingest. */
77
- export declare function writeMeta(db: Database.Database, input: MetaInput): void;
77
+ export declare function writeMeta(db: Database, input: MetaInput): void;
78
78
  /** Settings for any docs database this process opens, bundled or downloaded. */
79
- export declare function hardenConnection(db: Database.Database): void;
79
+ export declare function hardenConnection(db: Database): void;
80
80
  export type ValidationResult = {
81
81
  ok: true;
82
82
  meta: DataMeta;
@@ -6,8 +6,8 @@
6
6
  * on what a usable file looks like, so the schema, the metadata keys and the
7
7
  * validation all live here.
8
8
  */
9
- import Database from "better-sqlite3";
10
9
  import { z } from "zod";
10
+ import { openDatabase, pragmaValue, transaction } from "./sqlite.js";
11
11
  /** Bump when the table layout changes. Servers only use data with their own version. */
12
12
  export const DATA_SCHEMA_VERSION = 1;
13
13
  /**
@@ -126,7 +126,7 @@ export function readMeta(db) {
126
126
  /** Replace the meta table's contents. Used by ingest. */
127
127
  export function writeMeta(db, input) {
128
128
  const insert = db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)");
129
- db.transaction(() => {
129
+ transaction(db, () => {
130
130
  db.prepare("DELETE FROM meta").run();
131
131
  insert.run("schema_version", String(DATA_SCHEMA_VERSION));
132
132
  insert.run("min_server_version", MIN_SERVER_VERSION);
@@ -134,7 +134,7 @@ export function writeMeta(db, input) {
134
134
  if (input.commit)
135
135
  insert.run("commit", input.commit);
136
136
  insert.run("providers_json", input.providersJson);
137
- })();
137
+ });
138
138
  }
139
139
  /** FTS5's internal tables. Their SQL is written by SQLite, not by us. */
140
140
  const FTS_SHADOW_TABLE = /^docs_fts_(data|idx|content|docsize|config)$/;
@@ -154,7 +154,7 @@ let referenceSchema;
154
154
  /** The exact sqlite_master rows a database built from SCHEMA_SQL has. */
155
155
  function expectedSchema() {
156
156
  if (!referenceSchema) {
157
- const reference = new Database(":memory:");
157
+ const reference = openDatabase(":memory:");
158
158
  reference.exec(SCHEMA_SQL);
159
159
  referenceSchema = JSON.stringify(schemaRows(reference));
160
160
  reference.close();
@@ -163,8 +163,8 @@ function expectedSchema() {
163
163
  }
164
164
  /** Settings for any docs database this process opens, bundled or downloaded. */
165
165
  export function hardenConnection(db) {
166
- db.pragma("trusted_schema = OFF");
167
- db.pragma("cell_size_check = ON");
166
+ db.exec("PRAGMA trusted_schema = OFF");
167
+ db.exec("PRAGMA cell_size_check = ON");
168
168
  }
169
169
  /**
170
170
  * Decide whether a file is a docs index this server can use: the exact schema,
@@ -175,10 +175,10 @@ export function hardenConnection(db) {
175
175
  export function validateDatabase(path, serverVersion, options = {}) {
176
176
  let db;
177
177
  try {
178
- db = new Database(path, { readonly: true, fileMustExist: true });
178
+ db = openDatabase(path, { readonly: true });
179
179
  hardenConnection(db);
180
180
  if (options.integrity) {
181
- const check = db.pragma("quick_check", { simple: true });
181
+ const check = pragmaValue(db, "quick_check");
182
182
  if (check !== "ok")
183
183
  return { ok: false, reason: `integrity check failed (${String(check)})` };
184
184
  }
package/dist/index.d.ts CHANGED
@@ -10,9 +10,9 @@
10
10
  * location (XDG_DATA_HOME or ~/.local/share).
11
11
  */
12
12
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
13
- import Database from "better-sqlite3";
13
+ import { type Database } from "./sqlite.js";
14
14
  export { sanitiseFtsQuery } from "./tools.js";
15
- export declare function openDb(): Database.Database;
16
- export declare function openQueueDb(): Database.Database;
15
+ export declare function openDb(): Database;
16
+ export declare function openQueueDb(): Database;
17
17
  export declare function createFootballDocsServer(): McpServer;
18
18
  export declare function main(): Promise<void>;
package/dist/index.js CHANGED
@@ -15,12 +15,12 @@ import { dirname, resolve } from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18
- import Database from "better-sqlite3";
19
18
  import { z } from "zod";
20
19
  import { hardenConnection } from "./data-format.js";
21
20
  import { cleanDataDir, dataModeFor, defaultDataDir, IndexChooser } from "./data-source.js";
22
21
  import { checkForUpdate } from "./data-update.js";
23
22
  import { ENTITY_TYPES } from "./reep.js";
23
+ import { openDatabase } from "./sqlite.js";
24
24
  import { compareProviders, getProviderDocs, listProviders, requestUpdate, resolveEntity, resolveProviderId, searchDocs, } from "./tools.js";
25
25
  export { sanitiseFtsQuery } from "./tools.js";
26
26
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -51,9 +51,9 @@ export function openDb() {
51
51
  if (!existsSync(path)) {
52
52
  throw new Error(`Docs database not found at ${path}. Run 'npm run ingest' first to build the index.`);
53
53
  }
54
- const db = new Database(path, { readonly: true });
54
+ const db = openDatabase(path, { readonly: true });
55
55
  hardenConnection(db);
56
- const columns = db.pragma("table_info(docs)");
56
+ const columns = db.prepare("PRAGMA table_info(docs)").all();
57
57
  const hasProvenance = columns.some((column) => column.name === "source_type");
58
58
  if (!hasProvenance) {
59
59
  db.close();
@@ -63,8 +63,8 @@ export function openDb() {
63
63
  }
64
64
  export function openQueueDb() {
65
65
  mkdirSync(QUEUE_DB_DIR, { recursive: true });
66
- const db = new Database(QUEUE_DB_PATH);
67
- db.pragma("journal_mode = WAL");
66
+ const db = openDatabase(QUEUE_DB_PATH);
67
+ db.exec("PRAGMA journal_mode = WAL");
68
68
  db.exec(`
69
69
  CREATE TABLE IF NOT EXISTS requests (
70
70
  id TEXT PRIMARY KEY,
@@ -101,7 +101,7 @@ export function createFootballDocsServer() {
101
101
  name: "nutmeg-football-docs",
102
102
  version: PKG_VERSION,
103
103
  });
104
- server.tool("search_docs", "Search football data provider documentation. Use for finding event types, qualifier IDs, API endpoints, coordinate systems, data models, and cross-provider mappings. Returns the most relevant documentation chunks.", {
104
+ server.tool("search_docs", "Search football data provider documentation. Use for finding event types, qualifier IDs, API endpoints, coordinate systems, data models, and cross-provider mappings. Returns the most relevant documentation chunks. Results that do not contain every query term are marked \"partial\", and the reply names any query term that no indexed doc mentions: if the question is about that term, it is not indexed.", {
105
105
  query: z.string().describe("Search query. Examples: 'Opta goal qualifier', 'StatsBomb shot event type', 'coordinate system differences', 'xG qualifier ID', 'SportMonks fixture endpoint', 'FMDB Pro players endpoint'"),
106
106
  provider: z
107
107
  .string()
package/dist/ingest.js CHANGED
@@ -22,8 +22,8 @@ import { execFileSync } from "node:child_process";
22
22
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
23
23
  import { basename, dirname, resolve } from "node:path";
24
24
  import { fileURLToPath } from "node:url";
25
- import Database from "better-sqlite3";
26
25
  import { SCHEMA_SQL, writeMeta } from "./data-format.js";
26
+ import { openDatabase, transaction } from "./sqlite.js";
27
27
  const __dirname = dirname(fileURLToPath(import.meta.url));
28
28
  const DOCS_DIR = resolve(__dirname, "..", "docs");
29
29
  const DB_DIR = resolve(__dirname, "..", "data");
@@ -158,14 +158,14 @@ function main() {
158
158
  const providerArg = process.argv.indexOf("--provider");
159
159
  const singleProvider = providerArg >= 0 ? process.argv[providerArg + 1] : undefined;
160
160
  mkdirSync(DB_DIR, { recursive: true });
161
- const db = new Database(DB_PATH);
162
- db.pragma("journal_mode = WAL");
161
+ const db = openDatabase(DB_PATH);
162
+ db.exec("PRAGMA journal_mode = WAL");
163
163
  if (singleProvider) {
164
164
  // Single-provider mode: only rebuild that provider's data
165
165
  // Ensure tables exist (in case DB is fresh)
166
166
  ensureSchema(db);
167
167
  // Atomically delete existing data and re-ingest for this provider
168
- const deleteAndReinsert = db.transaction(() => {
168
+ transaction(db, () => {
169
169
  const rows = db.prepare("SELECT id, provider, category, title, content FROM docs WHERE provider = ?").all(singleProvider);
170
170
  const ftsDelete = db.prepare("INSERT INTO docs_fts(docs_fts, rowid, provider, category, title, content) VALUES('delete', ?, ?, ?, ?, ?)");
171
171
  for (const row of rows) {
@@ -173,7 +173,6 @@ function main() {
173
173
  }
174
174
  db.prepare("DELETE FROM docs WHERE provider = ?").run(singleProvider);
175
175
  });
176
- deleteAndReinsert();
177
176
  console.log(`Ingesting ${singleProvider}...\n`);
178
177
  const count = ingestProvider(db, singleProvider);
179
178
  console.log(`\nDone: ${count} chunks from ${singleProvider}`);
@@ -186,7 +185,7 @@ function main() {
186
185
  console.log(`No docs directory at ${DOCS_DIR}`);
187
186
  console.log("Create docs/{provider}/*.md files first.");
188
187
  recordMeta(db);
189
- db.pragma("journal_mode = DELETE");
188
+ db.exec("PRAGMA journal_mode = DELETE");
190
189
  db.close();
191
190
  return;
192
191
  }
@@ -207,7 +206,7 @@ function main() {
207
206
  // A shipped or downloaded file must not be in WAL mode: opening it read-only
208
207
  // would try to create -wal/-shm files next to it, which fails in a read-only
209
208
  // install and leaves side files behind in the cache.
210
- db.pragma("journal_mode = DELETE");
209
+ db.exec("PRAGMA journal_mode = DELETE");
211
210
  db.close();
212
211
  }
213
212
  // Only run when executed directly, not when imported for tests
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Validation for the Opta ID tables.
3
+ *
4
+ * Opta's reference, the Stats Perform F24 appendices, has no machine-readable
5
+ * form, so data/opta-truth.json is kept by hand: each ID the docs use,
6
+ * with the label the docs give it, checked against F24. The tests then hold the
7
+ * docs to that file, and reject meanings that were wrong in earlier versions of
8
+ * the docs (Q76 as big chance, Q213 as xG and so on) wherever they reappear.
9
+ */
10
+ export declare const OPTA_TRUTH_PATH: string;
11
+ export interface OptaTruth {
12
+ source: {
13
+ reference: string;
14
+ url: string;
15
+ checked: string;
16
+ note: string;
17
+ };
18
+ /** typeId -> event type name. */
19
+ eventTypes: Record<string, string>;
20
+ /** qualifierId -> the label docs/opta/qualifiers.md gives it. */
21
+ qualifiers: Record<string, string>;
22
+ }
23
+ export interface OptaDoc {
24
+ path: string;
25
+ text: string;
26
+ }
27
+ export interface OptaViolation {
28
+ path: string;
29
+ line: number;
30
+ message: string;
31
+ }
32
+ export declare function loadOptaTruth(): OptaTruth;
33
+ /**
34
+ * Meanings earlier docs gave these IDs, all wrong. The pattern matches the ID
35
+ * and the wrong meaning in one clause, in either order, and in a row of an Opta
36
+ * qualifier table. A clause that negates the claim ("Q213 is the pass angle, not
37
+ * xG", "Do not read qualifier 213 as xG") is allowed.
38
+ */
39
+ export declare const WRONG_MEANINGS: Array<{
40
+ id: number;
41
+ meaning: string;
42
+ pattern: RegExp;
43
+ }>;
44
+ export declare function validateOptaDocs(docs: OptaDoc[], truth: OptaTruth): OptaViolation[];
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Validation for the Opta ID tables.
3
+ *
4
+ * Opta's reference, the Stats Perform F24 appendices, has no machine-readable
5
+ * form, so data/opta-truth.json is kept by hand: each ID the docs use,
6
+ * with the label the docs give it, checked against F24. The tests then hold the
7
+ * docs to that file, and reject meanings that were wrong in earlier versions of
8
+ * the docs (Q76 as big chance, Q213 as xG and so on) wherever they reappear.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ const __dirname = dirname(fileURLToPath(import.meta.url));
14
+ export const OPTA_TRUTH_PATH = resolve(__dirname, "..", "data", "opta-truth.json");
15
+ export function loadOptaTruth() {
16
+ return JSON.parse(readFileSync(OPTA_TRUTH_PATH, "utf-8"));
17
+ }
18
+ /**
19
+ * Meanings earlier docs gave these IDs, all wrong. The pattern matches the ID
20
+ * and the wrong meaning in one clause, in either order, and in a row of an Opta
21
+ * qualifier table. A clause that negates the claim ("Q213 is the pass angle, not
22
+ * xG", "Do not read qualifier 213 as xG") is allowed.
23
+ */
24
+ export const WRONG_MEANINGS = [
25
+ { id: 7, meaning: "goal kick (goal kick is Q124)", pattern: /goal[- ]?kick/ },
26
+ { id: 17, meaning: "blocked x (blocked x is Q146)", pattern: /block(ed)?[ _-]?x/ },
27
+ { id: 18, meaning: "blocked y (blocked y is Q147)", pattern: /block(ed)?[ _-]?y/ },
28
+ { id: 20, meaning: "an involved-player field (Q20 is right foot)", pattern: /involved/ },
29
+ { id: 22, meaning: "other body part (other body part is Q21)", pattern: /other[ _-]?body/ },
30
+ { id: 24, meaning: "assisted shot (Q24 is set piece; assisted is Q29)", pattern: /assisted[ _-]?shot/ },
31
+ { id: 26, meaning: "low drive (Q26 is a direct free-kick shot)", pattern: /low[ _-]?drive/ },
32
+ { id: 31, meaning: "second yellow (Q31 is yellow card; second yellow is Q32)", pattern: /second[ _-]?yellow/ },
33
+ { id: 56, meaning: "right foot (Q56 is zone; right foot is Q20)", pattern: /right[ _-]?foot/ },
34
+ { id: 72, meaning: "angle (Q72 is left foot; angle is Q213)", pattern: /\bangle\b/ },
35
+ { id: 76, meaning: "big chance (Q76 is low left; big chance is Q214)", pattern: /big[ _-]?chance/ },
36
+ { id: 108, meaning: "penalty (Q108 is volley; penalty is Q9)", pattern: /penalt/ },
37
+ { id: 136, meaning: "direct free kick (Q136 is keeper touched)", pattern: /direct[ _-]?(free|fk)/ },
38
+ { id: 154, meaning: "volley (Q154 is intentional assist; volley is Q108)", pattern: /volley/ },
39
+ { id: 213, meaning: "xG (Q213 is angle; xG is Q321)", pattern: /\bxg\b|\bexpected[ _-]?goals\b/ },
40
+ { id: 214, meaning: "length or xA (Q214 is big chance)", pattern: /\blength\b|\bxa\b|\bexpected[ _-]?assist/ },
41
+ { id: 328, meaning: "strong or big chance (Q328 is first touch)", pattern: /strong|powerful|big[ _-]?chance/ },
42
+ { id: 468, meaning: "xG (Q468 is related error 1 ID)", pattern: /\bxg\b|\bexpected[ _-]?goals/ },
43
+ ];
44
+ const NEGATION = /\bnot\b|\bnever\b|n't\b|\binstead\b/;
45
+ /** A clause ends at a full stop, semicolon or table cell. */
46
+ const CLAUSE = "[^.;|\\n]{0,60}?";
47
+ function idPattern(id) {
48
+ return `(?:\\bq|\\bqualifier\\s*(?:id\\s*)?\`?)${id}\\b\`?`;
49
+ }
50
+ function lineOf(text, index) {
51
+ return text.slice(0, index).split("\n").length;
52
+ }
53
+ /** The start of the clause that ends at `index`, for a negation before the match. */
54
+ function clauseBefore(text, index) {
55
+ const before = text.slice(Math.max(0, index - 40), index);
56
+ return before.split(/[.;|\n]/).pop() ?? "";
57
+ }
58
+ function findWrongMeanings(doc) {
59
+ const text = doc.text.toLowerCase();
60
+ const violations = [];
61
+ const report = (id, meaning, index, length) => violations.push({
62
+ path: doc.path,
63
+ line: lineOf(doc.text, index),
64
+ message: `states qualifier ${id} as ${meaning}: "${doc.text.slice(index, index + length)}"`,
65
+ });
66
+ for (const { id, meaning, pattern } of WRONG_MEANINGS) {
67
+ const forward = new RegExp(`${idPattern(id)}(${CLAUSE})(?:${pattern.source})`, "g");
68
+ const backward = new RegExp(`(?:${pattern.source})(${CLAUSE})${idPattern(id)}`, "g");
69
+ for (const regex of [forward, backward]) {
70
+ for (const match of text.matchAll(regex)) {
71
+ const index = match.index ?? 0;
72
+ if (NEGATION.test(match[1] ?? "") || NEGATION.test(clauseBefore(text, index)))
73
+ continue;
74
+ report(id, meaning, index, match[0].length);
75
+ }
76
+ }
77
+ }
78
+ // Opta tables give the ID a cell of its own ("| 76 | bigChance |"). The typeId
79
+ // table is skipped: its IDs are event types, not qualifiers.
80
+ if (doc.path.includes("opta/") && !doc.path.endsWith("event-types.md")) {
81
+ let offset = 0;
82
+ for (const line of text.split("\n")) {
83
+ const row = line.match(/^\|\s*`?(\d+)`?\s*\|(.*)$/);
84
+ const entry = row && WRONG_MEANINGS.find((candidate) => String(candidate.id) === row[1]);
85
+ if (row && entry) {
86
+ const hit = row[2].match(entry.pattern);
87
+ if (hit && !NEGATION.test(row[2].slice(0, hit.index)))
88
+ report(entry.id, entry.meaning, offset, line.length);
89
+ }
90
+ offset += line.length + 1;
91
+ }
92
+ }
93
+ return violations;
94
+ }
95
+ /** Rows of every table whose header starts with the given first column name. */
96
+ function idTableRows(text, firstColumn) {
97
+ const rows = [];
98
+ let inTable = false;
99
+ text.split("\n").forEach((line, index) => {
100
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
101
+ if (line.startsWith("|") && cells[0] === firstColumn) {
102
+ inTable = true;
103
+ return;
104
+ }
105
+ if (!line.startsWith("|")) {
106
+ inTable = false;
107
+ return;
108
+ }
109
+ if (inTable && /^\d+$/.test(cells[0]))
110
+ rows.push({ id: cells[0], name: cells[1], line: index + 1 });
111
+ });
112
+ return rows;
113
+ }
114
+ export function validateOptaDocs(docs, truth) {
115
+ const violations = [];
116
+ for (const doc of docs) {
117
+ if (doc.path.endsWith("opta/qualifiers.md")) {
118
+ for (const row of idTableRows(doc.text, "ID")) {
119
+ const expected = truth.qualifiers[row.id];
120
+ if (expected === undefined) {
121
+ violations.push({
122
+ path: doc.path,
123
+ line: row.line,
124
+ message: `qualifier ${row.id} is not in data/opta-truth.json; check it against F24 and add it`,
125
+ });
126
+ }
127
+ else if (row.name !== expected) {
128
+ violations.push({
129
+ path: doc.path,
130
+ line: row.line,
131
+ message: `qualifier ${row.id} is labelled "${row.name}"; the checked label is "${expected}"`,
132
+ });
133
+ }
134
+ }
135
+ }
136
+ if (doc.path.endsWith("opta/event-types.md")) {
137
+ for (const row of idTableRows(doc.text, "typeId")) {
138
+ const expected = truth.eventTypes[row.id];
139
+ if (expected === undefined) {
140
+ violations.push({
141
+ path: doc.path,
142
+ line: row.line,
143
+ message: `typeId ${row.id} is not in data/opta-truth.json; check it against F24 and add it`,
144
+ });
145
+ }
146
+ else if (row.name.toLowerCase() !== expected.toLowerCase()) {
147
+ violations.push({
148
+ path: doc.path,
149
+ line: row.line,
150
+ message: `typeId ${row.id} is named "${row.name}"; F24 names it "${expected}"`,
151
+ });
152
+ }
153
+ }
154
+ }
155
+ violations.push(...findWrongMeanings(doc));
156
+ }
157
+ return violations;
158
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Validation for the SportMonks ID tables.
3
+ *
4
+ * SportMonks publishes its type and state IDs on its definitions pages and in a
5
+ * types spreadsheet linked from the Types page. data/sportmonks-types-truth.json
6
+ * holds those ID, name, developer name and code values as published. The tests
7
+ * hold every ID table in docs/sportmonks to it: an ID must be published, and the
8
+ * name the doc gives it must be SportMonks' own (or an alias listed below).
9
+ */
10
+ export declare const SPORTMONKS_TRUTH_PATH: string;
11
+ type Published = {
12
+ name?: string;
13
+ developer_name?: string;
14
+ code?: string;
15
+ state?: string;
16
+ };
17
+ export interface SportMonksTruth {
18
+ source: {
19
+ pages: string;
20
+ fetched: string;
21
+ note: string;
22
+ };
23
+ types: Record<string, Published>;
24
+ states: Record<string, Published>;
25
+ }
26
+ export interface SportMonksDoc {
27
+ path: string;
28
+ text: string;
29
+ }
30
+ export interface SportMonksViolation {
31
+ path: string;
32
+ line: number;
33
+ message: string;
34
+ }
35
+ export declare function loadSportMonksTruth(): SportMonksTruth;
36
+ export declare function validateSportMonksDocs(docs: SportMonksDoc[], truth: SportMonksTruth): SportMonksViolation[];
37
+ export {};
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Validation for the SportMonks ID tables.
3
+ *
4
+ * SportMonks publishes its type and state IDs on its definitions pages and in a
5
+ * types spreadsheet linked from the Types page. data/sportmonks-types-truth.json
6
+ * holds those ID, name, developer name and code values as published. The tests
7
+ * hold every ID table in docs/sportmonks to it: an ID must be published, and the
8
+ * name the doc gives it must be SportMonks' own (or an alias listed below).
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { dirname, resolve } from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ const __dirname = dirname(fileURLToPath(import.meta.url));
14
+ export const SPORTMONKS_TRUTH_PATH = resolve(__dirname, "..", "data", "sportmonks-types-truth.json");
15
+ /** Which truth section each table's first column names. */
16
+ const TABLE_SECTIONS = {
17
+ "Type ID": "types",
18
+ "Stat Type ID": "types",
19
+ "Position ID": "types",
20
+ "State ID": "states",
21
+ };
22
+ /**
23
+ * Names docs use that differ from SportMonks' wording but mean the same type.
24
+ * Keep this short: a loose match would let a swap through, since "Yellow/Red
25
+ * card" contains "Red card".
26
+ */
27
+ const ALIASES = {
28
+ "16": ["Penalty goal"],
29
+ };
30
+ function normalise(value) {
31
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
32
+ }
33
+ export function loadSportMonksTruth() {
34
+ return JSON.parse(readFileSync(SPORTMONKS_TRUTH_PATH, "utf-8"));
35
+ }
36
+ export function validateSportMonksDocs(docs, truth) {
37
+ const violations = [];
38
+ for (const doc of docs) {
39
+ let section;
40
+ let header = false;
41
+ doc.text.split("\n").forEach((line, index) => {
42
+ if (!line.startsWith("|")) {
43
+ section = undefined;
44
+ header = false;
45
+ return;
46
+ }
47
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
48
+ if (!header) {
49
+ header = true;
50
+ section = TABLE_SECTIONS[cells[0]];
51
+ return;
52
+ }
53
+ const id = cells[0].replace(/`/g, "");
54
+ if (!section || !/^\d+$/.test(id))
55
+ return;
56
+ const at = { path: doc.path, line: index + 1 };
57
+ const published = truth[section][id];
58
+ // "Full-Time (`FT`)" names the state and gives its code; both must match.
59
+ const codeMatch = cells[1].match(/\(`([^`]+)`\)/);
60
+ const name = cells[1].replace(/\(`[^`]*`\)/, "").replace(/`/g, "").trim();
61
+ if (!published) {
62
+ violations.push({
63
+ ...at,
64
+ message: `${section === "states" ? "state" : "type"} ${id} is not in SportMonks' published definitions`,
65
+ });
66
+ return;
67
+ }
68
+ const accepted = [published.name, published.developer_name, published.code, published.state, ...(ALIASES[id] ?? [])]
69
+ .filter((value) => Boolean(value))
70
+ .map(normalise);
71
+ if (!accepted.includes(normalise(name))) {
72
+ violations.push({
73
+ ...at,
74
+ message: `${section === "states" ? "state" : "type"} ${id} is "${name}" in the doc; SportMonks publishes "${published.name ?? published.developer_name}"`,
75
+ });
76
+ }
77
+ const publishedCode = published.state ?? published.developer_name;
78
+ if (codeMatch && publishedCode && normalise(codeMatch[1]) !== normalise(publishedCode)) {
79
+ violations.push({
80
+ ...at,
81
+ message: `${section === "states" ? "state" : "type"} ${id} has code ${codeMatch[1]} in the doc; SportMonks publishes ${publishedCode}`,
82
+ });
83
+ }
84
+ });
85
+ }
86
+ return violations;
87
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * SQLite access for the docs index and the request queue.
3
+ *
4
+ * This uses Node's built-in `node:sqlite`, not a native addon. An addon is built
5
+ * for one Node ABI, and `npx` shares its cache between Node versions: a copy
6
+ * installed under Node 22 failed to load under Node 24. The built-in module
7
+ * always matches the Node running it.
8
+ */
9
+ import { DatabaseSync } from "node:sqlite";
10
+ export type Database = DatabaseSync;
11
+ /** Open a database file, or ":memory:". A read-only open fails when the file does not exist. */
12
+ export declare function openDatabase(path: string, options?: {
13
+ readonly?: boolean;
14
+ }): Database;
15
+ /** Run `work` inside one transaction, rolling back if it throws. */
16
+ export declare function transaction<T>(db: Database, work: () => T): T;
17
+ /** The first column of a pragma's first row, such as "ok" from quick_check. */
18
+ export declare function pragmaValue(db: Database, pragma: string): unknown;