@blogmcp/mdx-codemods 0.1.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.
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Types for the MDX codemod runner.
3
+ *
4
+ * The runner is storage-agnostic — the KB API graphile-worker task that
5
+ * consumes it (PR 4) implements `CodemodStore` against the actual
6
+ * `kb_articles_translations` table + `mdx_codemod_errors` log + tenant
7
+ * settings. Tests pass mock stores to exercise the runner without a DB.
8
+ */
9
+ /**
10
+ * One MDX content rewriter. Each migration ships as a TypeScript file
11
+ * under `packages/mdx-codemods/src/migrations/<from>-<slug>.ts` and is
12
+ * statically imported into the `ALL_MIGRATIONS` registry.
13
+ *
14
+ * The `from` / `to` versions form a directed graph the runner walks
15
+ * per-translation: applying the chain of migrations whose `from`
16
+ * matches the translation's current `schema_version`, until the
17
+ * translation reaches the target version.
18
+ *
19
+ * **Idempotency contract:** `transform(s)` MUST return the same result
20
+ * when called twice on the same input. The runner may retry on write
21
+ * conflict; non-idempotent transforms produce divergent stored content
22
+ * across retries.
23
+ */
24
+ export interface Migration {
25
+ /**
26
+ * `schema_version` the migration runs against. A translation stamped
27
+ * at this version is a candidate for this migration.
28
+ */
29
+ from: string;
30
+ /**
31
+ * `schema_version` to stamp on the translation after this migration
32
+ * succeeds. Must be strictly greater than `from` (semver `gt`).
33
+ */
34
+ to: string;
35
+ /**
36
+ * Kebab-case slug. Convention: file is named `<to>-<slug>.ts`, so
37
+ * `slug = 'remove-callout-type'` ⇒ file `0.3.0-remove-callout-type.ts`.
38
+ * Used in error logs and `mdx_codemod_errors.migration_slug`.
39
+ */
40
+ slug: string;
41
+ /**
42
+ * One-line description for the operations dashboard + commit log.
43
+ */
44
+ description: string;
45
+ /**
46
+ * The content transform. Receives the raw stored MDX (frontmatter
47
+ * intact); returns the rewritten content plus a flag indicating
48
+ * whether anything actually changed. The runner uses `changed` to
49
+ * skip the write path for no-op invocations (e.g. an article that
50
+ * didn't use the affected component).
51
+ *
52
+ * Throwing from `transform` causes the runner to record a
53
+ * `CodemodError` and skip this translation — the batch continues
54
+ * with the next row.
55
+ */
56
+ transform(content: string): {
57
+ content: string;
58
+ changed: boolean;
59
+ };
60
+ }
61
+ /**
62
+ * A single translation row as seen by the runner. The runner is
63
+ * agnostic to the table layout — the store adapter projects
64
+ * `kb_articles_translations` (or any future equivalent) onto this
65
+ * shape.
66
+ */
67
+ export interface StoredTranslation {
68
+ id: string;
69
+ articleId: string;
70
+ languageCode: string;
71
+ content: string;
72
+ schemaVersion: string;
73
+ }
74
+ /**
75
+ * Record of a per-translation migration failure. The runner accumulates
76
+ * these and hands them to the store via `recordError`. The store
77
+ * decides where to log them (PR 4: `mdx_codemod_errors` table).
78
+ */
79
+ export interface CodemodError {
80
+ translationId: string;
81
+ migrationSlug: string;
82
+ fromVersion: string;
83
+ toVersion: string;
84
+ errorMessage: string;
85
+ errorStack?: string;
86
+ }
87
+ /**
88
+ * Storage adapter implemented by consumers (KB API graphile-worker task).
89
+ *
90
+ * All methods are async — the runner awaits them sequentially per
91
+ * translation. The runner does NOT parallelize writes for a single
92
+ * translation (avoids racing optimistic-concurrency retries) but DOES
93
+ * iterate batches of translations in sequence; the calling task can
94
+ * fan out by sharding the batch range.
95
+ */
96
+ export interface CodemodStore {
97
+ /**
98
+ * Returns translations whose `schemaVersion` is strictly less than
99
+ * `targetVersion`. The store implements **cursor-based** pagination:
100
+ * results are ordered by `id` ascending; when `afterId` is set, only
101
+ * rows with `id > afterId` are returned. The runner stops calling
102
+ * when an empty batch comes back.
103
+ *
104
+ * Why cursor-based and not offset-based: offset breaks when rows
105
+ * fall out of the eligible set mid-iteration (which they do — once
106
+ * a translation is migrated, its `schemaVersion` is no longer
107
+ * `< targetVersion`). Also keeps failed rows past the cursor so a
108
+ * single bad row can't infinite-loop the batch.
109
+ */
110
+ listTranslationsBelow(targetVersion: string, opts: {
111
+ batchSize: number;
112
+ afterId?: string;
113
+ }): Promise<StoredTranslation[]>;
114
+ /**
115
+ * Persists `newContent` as a new version of the translation, going
116
+ * from `expectedSchemaVersion` → `newSchemaVersion`. Uses the
117
+ * existing optimistic-write path (see
118
+ * `competitor-monitor/docs/internal/optimistic-concurrency.md`).
119
+ *
120
+ * Returns `{ success: true }` on a clean write.
121
+ * Returns `{ success: false, conflict: true }` if another writer
122
+ * advanced the translation's `schemaVersion` mid-flight — the
123
+ * runner retries by re-fetching.
124
+ */
125
+ writeTranslation(translationId: string, newContent: string, newSchemaVersion: string, expectedSchemaVersion: string, migrationSlug: string): Promise<{
126
+ success: boolean;
127
+ conflict?: boolean;
128
+ pinViolation?: boolean;
129
+ }>;
130
+ /**
131
+ * Re-fetches a single translation by id. Used after a write conflict
132
+ * to pull the new `schemaVersion` for retry.
133
+ */
134
+ getTranslation(translationId: string): Promise<StoredTranslation | null>;
135
+ /** Records a per-translation migration failure for operator visibility. */
136
+ recordError(error: CodemodError): Promise<void>;
137
+ /**
138
+ * Marks the parent article for re-embedding (clears
139
+ * `kb_articles.embedded_at`). Called once per article after at least
140
+ * one of its translations was rewritten.
141
+ */
142
+ invalidateEmbedding(articleId: string): Promise<void>;
143
+ /**
144
+ * Emits a cache-bust event for the article so the blog's ISR cache
145
+ * + any other downstream caches drop their stale rendering. Called
146
+ * once per article after at least one translation was rewritten.
147
+ */
148
+ emitCacheBust(articleId: string): Promise<void>;
149
+ /**
150
+ * Returns the tenant's `mdx_schema_version_pin`, or `null` when no
151
+ * pin is set. The runner uses this to compute the effective target
152
+ * version (`min(targetVersion, pin)`).
153
+ */
154
+ getTenantPin(): Promise<string | null>;
155
+ }
156
+ /**
157
+ * Aggregate counts emitted at the end of a runner invocation. The
158
+ * graphile-worker task (PR 4) forwards these to the operations
159
+ * dashboard / Prometheus metrics.
160
+ */
161
+ export interface RunMigrationsResult {
162
+ /** Total translations the runner saw in batches. */
163
+ translationsProcessed: number;
164
+ /** Translations where at least one migration changed content. */
165
+ translationsMigrated: number;
166
+ /** Translations where every applicable migration was a no-op. */
167
+ translationsSkipped: number;
168
+ /** Translations that hit a transform throw / unrecoverable write conflict. */
169
+ translationsFailed: number;
170
+ /** Distinct article ids whose embeddings + caches were invalidated. */
171
+ articlesInvalidated: Set<string>;
172
+ /** Effective target version after pin clamping. */
173
+ effectiveTargetVersion: string;
174
+ }
package/dist/types.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Types for the MDX codemod runner.
3
+ *
4
+ * The runner is storage-agnostic — the KB API graphile-worker task that
5
+ * consumes it (PR 4) implements `CodemodStore` against the actual
6
+ * `kb_articles_translations` table + `mdx_codemod_errors` log + tenant
7
+ * settings. Tests pass mock stores to exercise the runner without a DB.
8
+ */
9
+ export {};
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@blogmcp/mdx-codemods",
3
+ "version": "0.1.0",
4
+ "description": "Codemod runner + migration interface for MDX article content. Storage-agnostic library; consumers (KB API graphile-worker task) wire the CodemodStore.",
5
+ "type": "module",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./src/index.ts",
15
+ "import": "./dist/index.js"
16
+ },
17
+ "./runner": {
18
+ "types": "./src/runner.ts",
19
+ "import": "./dist/runner.js"
20
+ },
21
+ "./types": {
22
+ "types": "./src/types.ts",
23
+ "import": "./dist/types.js"
24
+ },
25
+ "./migrations": {
26
+ "types": "./src/migrations.ts",
27
+ "import": "./dist/migrations.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src"
33
+ ],
34
+ "scripts": {
35
+ "build": "tsc -p tsconfig.build.json",
36
+ "dev": "tsc -p tsconfig.build.json --watch",
37
+ "test": "vitest run",
38
+ "test:watch": "vitest",
39
+ "typecheck": "tsc --noEmit"
40
+ },
41
+ "dependencies": {
42
+ "@blogmcp/mdx-schema": "^0.1.0",
43
+ "semver": "^7.6.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^20.10.0",
47
+ "@types/pg": "^8.10.0",
48
+ "@types/semver": "^7.5.6",
49
+ "@vitest/utils": "3.2.4",
50
+ "pg": "^8.16.3",
51
+ "typescript": "^5.3.3",
52
+ "vitest": "^3.0.0"
53
+ },
54
+ "keywords": [
55
+ "mdx",
56
+ "codemod",
57
+ "migration"
58
+ ],
59
+ "license": "MIT"
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @blogmcp/mdx-codemods
3
+ *
4
+ * Storage-agnostic codemod runner for MDX article content. Consumers
5
+ * (the KB API graphile-worker task in PR 4) implement `CodemodStore`
6
+ * against `kb_articles_translations` + `mdx_codemod_errors` + tenant
7
+ * settings, then call `runMigrations({ targetVersion, migrations,
8
+ * store })` at app boot whenever `SCHEMA_VERSION > MAX(schema_version)`.
9
+ *
10
+ * See `competitor-monitor/docs/internal/optimistic-concurrency.md`
11
+ * for the write-path contract the store must implement, and the plan
12
+ * file's "PR 3" / "Codemod runner" sections for the architectural
13
+ * design.
14
+ */
15
+
16
+ export * from './types.js'
17
+ export * from './runner.js'
18
+ export * from './migrations.js'
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Static migration registry.
3
+ *
4
+ * Each migration is a TypeScript file in `src/migrations/<to>-<slug>.ts`
5
+ * that exports a `migration: Migration` constant. This file collects them
6
+ * into a single `ALL_MIGRATIONS` array consumed by the runner.
7
+ *
8
+ * No filesystem globbing: keeping the registry static keeps tree-shaking
9
+ * correct in bundlers + makes the load order explicit (the runner sorts
10
+ * by `from` version internally, so order in this array doesn't affect
11
+ * correctness).
12
+ *
13
+ * The example / no-op fixture migrations live in `test/fixtures/`, not
14
+ * here — they must NOT ship to production. When the first real
15
+ * migration lands, add a literal import below and append it to the
16
+ * array.
17
+ */
18
+
19
+ import type { Migration } from './types.js'
20
+
21
+ const PRODUCTION_MIGRATIONS: Migration[] = [
22
+ // Example (do not uncomment in production):
23
+ //
24
+ // import { migration as removeCalloutType } from './migrations/0.3.0-remove-callout-type.js'
25
+ // PRODUCTION_MIGRATIONS.push(removeCalloutType)
26
+ //
27
+ // See `test/fixtures/*.ts` for the migration shape.
28
+ ]
29
+
30
+ /**
31
+ * Test-only override slot. Set via `__setMigrationsForTests([...])` from a
32
+ * test's `beforeAll`; reset with `__setMigrationsForTests(null)` in
33
+ * `afterAll` so subsequent test files see the production registry again.
34
+ *
35
+ * Production code that imports `ALL_MIGRATIONS` (the runtime task, the
36
+ * MCP introspection endpoint) always sees the live override when one is
37
+ * active. The override module-level — there is no per-call argument
38
+ * because the task code intentionally has no test seam, and threading a
39
+ * config option from `kb_run_mdx_codemods` payload up through the
40
+ * runner only to satisfy tests would leak test concerns into a production
41
+ * payload schema.
42
+ *
43
+ * Do NOT call this from anywhere except a test's `beforeAll` /
44
+ * `afterAll`. If `MDX_CODEMODS_TEST_OVERRIDE_DISABLED=true` is set at
45
+ * boot, the hook becomes a hard error (defense in depth for prod pods).
46
+ */
47
+ let TEST_OVERRIDE: Migration[] | null = null
48
+
49
+ export function __setMigrationsForTests(migrations: Migration[] | null): void {
50
+ if (process.env.MDX_CODEMODS_TEST_OVERRIDE_DISABLED === 'true') {
51
+ throw new Error(
52
+ '[mdx-codemods] __setMigrationsForTests called with MDX_CODEMODS_TEST_OVERRIDE_DISABLED=true ' +
53
+ '— this hook is for tests only and must not be reachable in production.',
54
+ )
55
+ }
56
+ TEST_OVERRIDE = migrations
57
+ }
58
+
59
+ /**
60
+ * The live registry the runner consumes. Reads the test override if set,
61
+ * otherwise the static production list. Exported as a getter via Proxy so
62
+ * existing `import { ALL_MIGRATIONS }` consumers (e.g. the KB API task)
63
+ * don't need to change call sites, but tests can still inject fixtures.
64
+ */
65
+ export const ALL_MIGRATIONS: Migration[] = new Proxy(PRODUCTION_MIGRATIONS, {
66
+ get(target, prop, receiver) {
67
+ const source = TEST_OVERRIDE ?? target
68
+ return Reflect.get(source, prop, receiver)
69
+ },
70
+ has(target, prop) {
71
+ const source = TEST_OVERRIDE ?? target
72
+ return Reflect.has(source, prop)
73
+ },
74
+ ownKeys(target) {
75
+ const source = TEST_OVERRIDE ?? target
76
+ return Reflect.ownKeys(source)
77
+ },
78
+ getOwnPropertyDescriptor(target, prop) {
79
+ const source = TEST_OVERRIDE ?? target
80
+ return Reflect.getOwnPropertyDescriptor(source, prop)
81
+ },
82
+ })