nuxt-ai-ready 3.6.0 → 3.6.2

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 (161) hide show
  1. package/dist/agent-skills-config-CmZq9uWW.mjs +18 -0
  2. package/dist/agent-skills-zGLgFB6H.mjs +468 -0
  3. package/dist/cli.d.mts +1 -0
  4. package/dist/cli.mjs +656 -570
  5. package/dist/devtools/pages/ai-ready/debug.vue +9 -3
  6. package/dist/devtools/pages/ai-ready/index.vue +3 -1
  7. package/dist/devtools/pages/ai-ready/llms-txt.vue +15 -4
  8. package/dist/devtools/pages/ai-ready.vue +28 -4
  9. package/dist/module.d.mts +106 -112
  10. package/dist/module.json +3 -3
  11. package/dist/module.mjs +2732 -26
  12. package/dist/package-metadata-B1darl8W.mjs +28 -0
  13. package/dist/prerender-QMv07W4h.mjs +650 -0
  14. package/dist/runtime/app/composables/webmcp.js +90 -97
  15. package/dist/runtime/app/plugins/md-alternate.server.js +29 -26
  16. package/dist/runtime/app/plugins/md-hints.prerender.js +13 -15
  17. package/dist/runtime/app/plugins/webmcp.client.js +49 -53
  18. package/dist/runtime/app/webmcp-config.js +2 -2
  19. package/dist/runtime/cache-control.js +16 -10
  20. package/dist/runtime/i18n-url.js +6 -6
  21. package/dist/runtime/index.js +4 -12
  22. package/dist/runtime/llms-txt-directive.js +20 -13
  23. package/dist/runtime/llms-txt-files.js +188 -187
  24. package/dist/runtime/llms-txt-format.js +54 -55
  25. package/dist/runtime/llms-txt-i18n.js +22 -19
  26. package/dist/runtime/llms-txt-utils.js +140 -95
  27. package/dist/runtime/markdown-links.js +45 -39
  28. package/dist/runtime/markdown-path.js +29 -9
  29. package/dist/runtime/markdown-text.js +2 -1
  30. package/dist/runtime/mcp.js +5 -1
  31. package/dist/runtime/route-path.js +14 -8
  32. package/dist/runtime/server/db/drizzle/client.js +71 -75
  33. package/dist/runtime/server/db/drizzle/index.js +16 -28
  34. package/dist/runtime/server/db/drizzle/providers/bun.d.ts +2 -1
  35. package/dist/runtime/server/db/drizzle/providers/bun.js +10 -7
  36. package/dist/runtime/server/db/drizzle/providers/d1.js +16 -13
  37. package/dist/runtime/server/db/drizzle/providers/dbPath.js +60 -37
  38. package/dist/runtime/server/db/drizzle/providers/libsql.js +23 -11
  39. package/dist/runtime/server/db/drizzle/providers/neon.js +13 -10
  40. package/dist/runtime/server/db/drizzle/providers/node-sqlite.js +10 -7
  41. package/dist/runtime/server/db/drizzle/providers/postgres.js +13 -10
  42. package/dist/runtime/server/db/drizzle/queries.js +633 -532
  43. package/dist/runtime/server/db/drizzle/raw.js +200 -176
  44. package/dist/runtime/server/db/index.js +3 -0
  45. package/dist/runtime/server/db/queries.js +816 -607
  46. package/dist/runtime/server/db/schema/postgres.js +56 -50
  47. package/dist/runtime/server/db/schema/sqlite.js +56 -50
  48. package/dist/runtime/server/db/schema-sql.js +35 -38
  49. package/dist/runtime/server/db/seed.js +60 -45
  50. package/dist/runtime/server/db/shared.js +300 -213
  51. package/dist/runtime/server/index.js +1 -17
  52. package/dist/runtime/server/mcp/cache-key.js +5 -1
  53. package/dist/runtime/server/mcp/resources/pages.js +32 -33
  54. package/dist/runtime/server/mcp/tools/get-page-markdown.js +41 -27
  55. package/dist/runtime/server/mcp/tools/list-pages.js +40 -34
  56. package/dist/runtime/server/mcp/tools/search-pages.js +24 -16
  57. package/dist/runtime/server/middleware/markdown.d.ts +1 -1
  58. package/dist/runtime/server/middleware/markdown.js +15 -13
  59. package/dist/runtime/server/middleware/markdown.prerender.d.ts +1 -1
  60. package/dist/runtime/server/middleware/markdown.prerender.js +135 -119
  61. package/dist/runtime/server/middleware/render-markdown.d.ts +1 -1
  62. package/dist/runtime/server/middleware/render-markdown.js +164 -144
  63. package/dist/runtime/server/plugins/ai-terms.d.ts +1 -1
  64. package/dist/runtime/server/plugins/ai-terms.js +4 -8
  65. package/dist/runtime/server/plugins/content-signal-capture-nitro3.prerender.d.ts +1 -1
  66. package/dist/runtime/server/plugins/content-signal-capture-nitro3.prerender.js +7 -8
  67. package/dist/runtime/server/plugins/content-signal-capture.prerender.d.ts +1 -1
  68. package/dist/runtime/server/plugins/content-signal-capture.prerender.js +7 -7
  69. package/dist/runtime/server/plugins/db-lifecycle-nitro3.d.ts +1 -1
  70. package/dist/runtime/server/plugins/db-lifecycle-nitro3.js +13 -14
  71. package/dist/runtime/server/plugins/db-lifecycle.js +13 -11
  72. package/dist/runtime/server/plugins/html-capture.prerender.js +6 -6
  73. package/dist/runtime/server/plugins/link-header-nitro3.d.ts +1 -1
  74. package/dist/runtime/server/plugins/link-header-nitro3.js +23 -13
  75. package/dist/runtime/server/plugins/link-header.d.ts +1 -1
  76. package/dist/runtime/server/plugins/link-header.js +30 -30
  77. package/dist/runtime/server/plugins/llms-txt-directive-html.d.ts +1 -1
  78. package/dist/runtime/server/plugins/llms-txt-directive-html.js +4 -3
  79. package/dist/runtime/server/plugins/markdown-negotiation.d.ts +1 -1
  80. package/dist/runtime/server/plugins/markdown-negotiation.js +64 -45
  81. package/dist/runtime/server/plugins/sitemap-seeder.js +144 -112
  82. package/dist/runtime/server/routes/__ai-ready/cron.get.d.ts +1 -1
  83. package/dist/runtime/server/routes/__ai-ready/cron.get.js +17 -11
  84. package/dist/runtime/server/routes/__ai-ready/devtools.get.d.ts +1 -1
  85. package/dist/runtime/server/routes/__ai-ready/devtools.get.js +60 -45
  86. package/dist/runtime/server/routes/__ai-ready/pages.get.d.ts +36 -1
  87. package/dist/runtime/server/routes/__ai-ready/pages.get.js +44 -40
  88. package/dist/runtime/server/routes/__ai-ready/poll.post.d.ts +15 -1
  89. package/dist/runtime/server/routes/__ai-ready/poll.post.js +30 -30
  90. package/dist/runtime/server/routes/__ai-ready/prune.post.d.ts +13 -1
  91. package/dist/runtime/server/routes/__ai-ready/prune.post.js +29 -15
  92. package/dist/runtime/server/routes/__ai-ready/reindex.post.d.ts +22 -1
  93. package/dist/runtime/server/routes/__ai-ready/reindex.post.js +31 -21
  94. package/dist/runtime/server/routes/__ai-ready/restore.post.d.ts +4 -1
  95. package/dist/runtime/server/routes/__ai-ready/restore.post.js +28 -22
  96. package/dist/runtime/server/routes/__ai-ready/status.get.d.ts +1 -1
  97. package/dist/runtime/server/routes/__ai-ready/status.get.js +52 -53
  98. package/dist/runtime/server/routes/__ai-ready-debug.get.d.ts +83 -1
  99. package/dist/runtime/server/routes/__ai-ready-debug.get.js +209 -189
  100. package/dist/runtime/server/routes/agent-skills-artifact.d.ts +1 -1
  101. package/dist/runtime/server/routes/agent-skills-artifact.js +16 -14
  102. package/dist/runtime/server/routes/agent-skills-index.d.ts +1 -1
  103. package/dist/runtime/server/routes/agent-skills-index.js +8 -6
  104. package/dist/runtime/server/routes/ai-catalog.js +19 -19
  105. package/dist/runtime/server/routes/ai-terms.js +23 -19
  106. package/dist/runtime/server/routes/api-catalog.js +23 -23
  107. package/dist/runtime/server/routes/llms-full.txt.get.d.ts +1 -1
  108. package/dist/runtime/server/routes/llms-full.txt.get.js +42 -41
  109. package/dist/runtime/server/routes/llms.txt.get.d.ts +1 -1
  110. package/dist/runtime/server/routes/llms.txt.get.js +38 -33
  111. package/dist/runtime/server/routes/mcp-server-card.js +19 -19
  112. package/dist/runtime/server/routes/sitemap.md.get.d.ts +1 -1
  113. package/dist/runtime/server/routes/sitemap.md.get.js +38 -39
  114. package/dist/runtime/server/tasks/ai-ready-cron.d.ts +1 -1
  115. package/dist/runtime/server/tasks/ai-ready-cron.js +17 -14
  116. package/dist/runtime/server/utils/auth.js +76 -53
  117. package/dist/runtime/server/utils/batchIndex.js +72 -60
  118. package/dist/runtime/server/utils/checkStale.js +181 -134
  119. package/dist/runtime/server/utils/cloudflare-prerendered.js +23 -20
  120. package/dist/runtime/server/utils/cloudflare.js +69 -51
  121. package/dist/runtime/server/utils/content-negotiation.js +30 -18
  122. package/dist/runtime/server/utils/content.js +4 -1
  123. package/dist/runtime/server/utils/context.js +30 -19
  124. package/dist/runtime/server/utils/cron-plan.js +6 -6
  125. package/dist/runtime/server/utils/discovery-response.js +5 -6
  126. package/dist/runtime/server/utils/fetch.js +2 -1
  127. package/dist/runtime/server/utils/frontmatter.js +44 -57
  128. package/dist/runtime/server/utils/i18n.js +3 -8
  129. package/dist/runtime/server/utils/indexPage.js +152 -113
  130. package/dist/runtime/server/utils/keywords.js +278 -277
  131. package/dist/runtime/server/utils/link-header.js +67 -56
  132. package/dist/runtime/server/utils/llms-full.js +39 -49
  133. package/dist/runtime/server/utils/markdown-redirect.js +26 -14
  134. package/dist/runtime/server/utils/markdown-request.js +62 -47
  135. package/dist/runtime/server/utils/negotiation-decision.d.ts +8 -0
  136. package/dist/runtime/server/utils/negotiation-decision.js +106 -34
  137. package/dist/runtime/server/utils/negotiation-response.d.ts +1 -1
  138. package/dist/runtime/server/utils/negotiation-response.js +195 -144
  139. package/dist/runtime/server/utils/page-updated-at.js +23 -15
  140. package/dist/runtime/server/utils/prerender-html.js +31 -17
  141. package/dist/runtime/server/utils/runCron.js +263 -192
  142. package/dist/runtime/server/utils/sitemap-crawl-state.js +57 -39
  143. package/dist/runtime/server/utils/sitemap-lastmod.js +16 -14
  144. package/dist/runtime/server/utils/sitemap-md.js +39 -50
  145. package/dist/runtime/server/utils/sitemap-routes.js +7 -7
  146. package/dist/runtime/server/utils/sitemap.js +459 -414
  147. package/dist/runtime/server/utils.js +141 -122
  148. package/dist/runtime/site-tool-catalog.js +39 -43
  149. package/dist/runtime/site-tool-config.js +1 -0
  150. package/dist/runtime/sync-secret.js +11 -11
  151. package/dist/runtime/types.js +1 -0
  152. package/dist/runtime/webmcp-site-tools.js +278 -250
  153. package/dist/runtime/webmcp.js +53 -42
  154. package/dist/static-headers-G7hFL3wE.mjs +328 -0
  155. package/dist/types.d.mts +1 -9
  156. package/package.json +20 -24
  157. package/skills/nuxt-ai-ready/SKILL.md +8 -2
  158. package/dist/chunks/agent-skills.mjs +0 -383
  159. package/dist/chunks/prerender.mjs +0 -683
  160. package/dist/shared/nuxt-ai-ready.Bzx0dNWj.mjs +0 -3034
  161. package/dist/shared/nuxt-ai-ready.DCd-1s1G.mjs +0 -29
@@ -1,262 +1,350 @@
1
+ // Shared database utilities for build-time and runtime
1
2
  import { isMap, isScalar, parseDocument } from "yaml";
2
3
  import { buildSchemaSql, DROP_TABLES_SQL, resolveFtsTokenizer, SCHEMA_VERSION } from "./schema-sql.js";
3
4
  const LEADING_BLOCK_RE = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
4
- const PAGE_FRONTMATTER_KEYS = /* @__PURE__ */ new Set(["title", "description", "meta", "canonical_url", "last_updated", "locale", "alternates"]);
5
+ // Keys that mdream and the markdown middleware write into page frontmatter.
6
+ const PAGE_FRONTMATTER_KEYS = new Set([
7
+ "title",
8
+ "description",
9
+ "meta",
10
+ "canonical_url",
11
+ "last_updated",
12
+ "locale",
13
+ "alternates"
14
+ ]);
15
+ /**
16
+ * Strip conversion fields while retaining image metadata for content hashing.
17
+ * A leading `---` block is only frontmatter when it holds a recognized key.
18
+ * Other leading blocks remain body content, such as text between horizontal rules.
19
+ */
5
20
  function stripPageFrontmatter(markdown) {
6
- const match = markdown.match(LEADING_BLOCK_RE);
7
- if (!match)
8
- return markdown;
9
- const document = parseDocument(match[1]);
10
- if (document.errors.length || !isMap(document.contents))
11
- return markdown;
12
- const isPageFrontmatter = document.contents.items.some((item) => isScalar(item.key) && PAGE_FRONTMATTER_KEYS.has(String(item.key.value)));
13
- if (!isPageFrontmatter)
14
- return markdown;
15
- const body = markdown.slice(match[0].length);
16
- const meta = document.get("meta", true);
17
- const images = [];
18
- if (isMap(meta)) {
19
- for (const { key, value } of meta.items) {
20
- if (!isScalar(key) || typeof key.value !== "string" || !isScalar(value))
21
- continue;
22
- if (key.value !== "og:image" && !key.value.startsWith("og:image:") && key.value !== "twitter:image" && !key.value.startsWith("twitter:image:"))
23
- continue;
24
- if (typeof value.value === "string" || typeof value.value === "number" && Number.isFinite(value.value))
25
- images.push([key.value, value.value]);
26
- }
27
- }
28
- if (!images.length)
29
- return body;
30
- images.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
31
- return JSON.stringify([images, body.trim()]);
21
+ const match = markdown.match(LEADING_BLOCK_RE);
22
+ if (!match) return markdown;
23
+ const document = parseDocument(match[1]);
24
+ if (document.errors.length || !isMap(document.contents)) return markdown;
25
+ const isPageFrontmatter = document.contents.items.some((item) => isScalar(item.key) && PAGE_FRONTMATTER_KEYS.has(String(item.key.value)));
26
+ if (!isPageFrontmatter) return markdown;
27
+ const body = markdown.slice(match[0].length);
28
+ const meta = document.get("meta", true);
29
+ const images = [];
30
+ if (isMap(meta)) {
31
+ for (const { key, value } of meta.items) {
32
+ if (!isScalar(key) || typeof key.value !== "string" || !isScalar(value)) continue;
33
+ if (key.value !== "og:image" && !key.value.startsWith("og:image:") && key.value !== "twitter:image" && !key.value.startsWith("twitter:image:")) continue;
34
+ if (typeof value.value === "string" || typeof value.value === "number" && Number.isFinite(value.value)) images.push([key.value, value.value]);
35
+ }
36
+ }
37
+ if (!images.length) return body;
38
+ images.sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
39
+ return JSON.stringify([images, body.trim()]);
32
40
  }
41
+ /**
42
+ * Compute content hash for change detection (first 16 chars of SHA-256).
43
+ * Hash the page body and image metadata. Other frontmatter holds fields
44
+ * (`canonical_url`, `last_updated`) that can differ between conversion paths.
45
+ * Those fields stay excluded so unchanged pages keep the same hash.
46
+ */
33
47
  export async function computeContentHash(markdown) {
34
- const encoder = new TextEncoder();
35
- const data = encoder.encode(stripPageFrontmatter(markdown).trim());
36
- const hashBuffer = await crypto.subtle.digest("SHA-256", data);
37
- const hashArray = [...new Uint8Array(hashBuffer)];
38
- return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
48
+ const encoder = new TextEncoder();
49
+ const data = encoder.encode(stripPageFrontmatter(markdown).trim());
50
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
51
+ const hashArray = [...new Uint8Array(hashBuffer)];
52
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
39
53
  }
54
+ /**
55
+ * Initialize database schema with version checking.
56
+ * Rebuilds when SCHEMA_VERSION changes or when the configured FTS5 tokenizer
57
+ * differs from the one baked into the existing virtual table (e.g. user added
58
+ * a CJK locale on a later deploy).
59
+ */
40
60
  export async function initSchema(db, options = {}) {
41
- const tokenizer = resolveFtsTokenizer(options.ftsTokenizer);
42
- const currentVersion = await getSchemaVersion(db);
43
- const currentTokenizer = await getStoredTokenizer(db);
44
- const versionMatches = currentVersion === SCHEMA_VERSION;
45
- const tokenizerMatches = !currentTokenizer || currentTokenizer === tokenizer;
46
- if (versionMatches && tokenizerMatches)
47
- return;
48
- if (currentVersion) {
49
- for (const sql of DROP_TABLES_SQL) {
50
- await db.exec(sql);
51
- }
52
- }
53
- for (const sql of buildSchemaSql({ ftsTokenizer: tokenizer })) {
54
- await db.exec(sql);
55
- }
56
- await db.exec(
57
- "INSERT OR REPLACE INTO _ai_ready_info (id, version) VALUES (?, ?)",
58
- ["schema", SCHEMA_VERSION]
59
- );
60
- await db.exec(
61
- "INSERT OR REPLACE INTO _ai_ready_info (id, value) VALUES (?, ?)",
62
- ["fts_tokenizer", tokenizer]
63
- );
61
+ const tokenizer = resolveFtsTokenizer(options.ftsTokenizer);
62
+ const currentVersion = await getSchemaVersion(db);
63
+ const currentTokenizer = await getStoredTokenizer(db);
64
+ const versionMatches = currentVersion === SCHEMA_VERSION;
65
+ const tokenizerMatches = !currentTokenizer || currentTokenizer === tokenizer;
66
+ if (versionMatches && tokenizerMatches) return;
67
+ // Drop and rebuild on any mismatch (version bump or tokenizer change).
68
+ if (currentVersion) {
69
+ for (const sql of DROP_TABLES_SQL) {
70
+ await db.exec(sql);
71
+ }
72
+ }
73
+ // Create all tables/indexes
74
+ for (const sql of buildSchemaSql({ ftsTokenizer: tokenizer })) {
75
+ await db.exec(sql);
76
+ }
77
+ await db.exec("INSERT OR REPLACE INTO _ai_ready_info (id, version) VALUES (?, ?)", ["schema", SCHEMA_VERSION]);
78
+ await db.exec("INSERT OR REPLACE INTO _ai_ready_info (id, value) VALUES (?, ?)", ["fts_tokenizer", tokenizer]);
64
79
  }
65
80
  async function getSchemaVersion(db) {
66
- const info = await db.first(
67
- "SELECT version FROM _ai_ready_info WHERE id = ?",
68
- ["schema"]
69
- ).catch(() => {
70
- return null;
71
- });
72
- return info?.version || null;
81
+ const info = await db.first("SELECT version FROM _ai_ready_info WHERE id = ?", ["schema"]).catch(() => {
82
+ // The metadata table is absent before the first schema initialization.
83
+ return null;
84
+ });
85
+ return info?.version || null;
73
86
  }
74
87
  async function getStoredTokenizer(db) {
75
- const info = await db.first(
76
- "SELECT value FROM _ai_ready_info WHERE id = ?",
77
- ["fts_tokenizer"]
78
- ).catch(() => {
79
- return null;
80
- });
81
- return info?.value || null;
88
+ const info = await db.first("SELECT value FROM _ai_ready_info WHERE id = ?", ["fts_tokenizer"]).catch(() => {
89
+ // The metadata table is absent before the first schema initialization.
90
+ return null;
91
+ });
92
+ return info?.value || null;
82
93
  }
83
94
  const RE_LEADING_SLASH = /^\//;
84
95
  const RE_SLASH = /\//g;
96
+ /**
97
+ * Canonical storage form of a route.
98
+ *
99
+ * `ai_ready_pages` puts a UNIQUE index on `route` and another on `route_key`,
100
+ * while every upsert targets `ON CONFLICT(route)`. Two spellings of one page
101
+ * therefore have to agree on `route`, or the conflict target misses, the insert
102
+ * reaches the `route_key` index instead, and the whole statement fails with
103
+ * `UNIQUE constraint failed: ai_ready_pages.route_key`.
104
+ *
105
+ * `''` and `'/'` are the pair that occurs in practice, since both key to
106
+ * `index`: one spelling takes the row, the other retries and fails on every
107
+ * subsequent write. A bare `'about'` against `'/about'` is the same defect.
108
+ *
109
+ * Normalising here rather than widening the conflict target keeps one page to
110
+ * one row. Widening it would let both spellings persist and race for the key.
111
+ */
85
112
  export function normalizeRoute(route) {
86
- if (!route || route === "/")
87
- return "/";
88
- return route.startsWith("/") ? route : `/${route}`;
113
+ if (!route || route === "/") return "/";
114
+ return route.startsWith("/") ? route : `/${route}`;
89
115
  }
90
116
  const RE_LIKE_META = /[\\%_]/g;
117
+ /**
118
+ * Escape LIKE/ILIKE wildcard characters in a search term so the term matches
119
+ * literal text. Pair with an `ESCAPE` clause (see `LIKE_ESCAPE`): SQLite has no
120
+ * default escape character, so without the clause the escaping is inert.
121
+ */
91
122
  export function escapeLikeTerm(term) {
92
- return term.replace(RE_LIKE_META, (ch) => `\\${ch}`);
123
+ return term.replace(RE_LIKE_META, (ch) => `\\${ch}`);
93
124
  }
125
+ /** Substring LIKE/ILIKE pattern for a term, with wildcards escaped. */
94
126
  export function likeSubstring(term) {
95
- return `%${escapeLikeTerm(term)}%`;
127
+ return `%${escapeLikeTerm(term)}%`;
96
128
  }
129
+ /** Escape character to bind next to `likeSubstring` patterns. */
97
130
  export const LIKE_ESCAPE = "\\";
98
131
  const RE_FTS_TERM_SPLIT = /\s+/;
99
132
  const RE_FTS_TOKEN_CHAR = /[\p{L}\p{N}]/u;
100
133
  const RE_DOUBLE_QUOTE = /"/g;
134
+ /**
135
+ * Turn free text into an FTS5 MATCH expression that cannot throw. Each term
136
+ * becomes a quoted FTS5 string, so `-`, `.`, `'`, `AND`, `NOT` and `col:`
137
+ * filters stay literal text. The trailing `*` keeps prefix matching for
138
+ * partial words. A term with no letter or digit holds no token, so it is
139
+ * dropped. Returns null when no term remains.
140
+ */
101
141
  export function toFtsMatchQuery(query) {
102
- const terms = query.split(RE_FTS_TERM_SPLIT).filter((term) => RE_FTS_TOKEN_CHAR.test(term)).map((term) => `"${term.replace(RE_DOUBLE_QUOTE, '""')}"*`);
103
- return terms.length ? terms.join(" ") : null;
142
+ const terms = query.split(RE_FTS_TERM_SPLIT).filter((term) => RE_FTS_TOKEN_CHAR.test(term)).map((term) => `"${term.replace(RE_DOUBLE_QUOTE, "\"\"")}"*`);
143
+ return terms.length ? terms.join(" ") : null;
104
144
  }
105
145
  const MAX_BIND_PARAMS_PER_STATEMENT = 100;
146
+ /**
147
+ * Multi-row INSERT chunk size that keeps one statement within the 100-bind
148
+ * cap shared by SQLite and D1, derived from the row's bind count so an added
149
+ * column resizes the chunk instead of breaking the insert.
150
+ */
106
151
  export function maxRowsPerInsert(paramsPerRow) {
107
- return Math.max(1, Math.floor(MAX_BIND_PARAMS_PER_STATEMENT / paramsPerRow));
152
+ return Math.max(1, Math.floor(MAX_BIND_PARAMS_PER_STATEMENT / paramsPerRow));
108
153
  }
154
+ /**
155
+ * Normalize route to storage key format
156
+ * e.g., '/about/team' -> 'about:team', '/' -> 'index'
157
+ *
158
+ * Derived from the canonical route so the two can never disagree: equal keys
159
+ * imply equal routes, which is what the pair of unique indexes requires.
160
+ */
109
161
  export function normalizeRouteKey(route) {
110
- return normalizeRoute(route).replace(RE_LEADING_SLASH, "").replace(RE_SLASH, ":") || "index";
162
+ return normalizeRoute(route).replace(RE_LEADING_SLASH, "").replace(RE_SLASH, ":") || "index";
111
163
  }
164
+ /**
165
+ * Compress data to base64 gzip
166
+ */
112
167
  export async function compressToBase64(data) {
113
- const json = JSON.stringify(data);
114
- const encoder = new TextEncoder();
115
- const stream = new Blob([encoder.encode(json)]).stream();
116
- const compressed = stream.pipeThrough(new CompressionStream("gzip"));
117
- const buffer = await new Response(compressed).arrayBuffer();
118
- return Buffer.from(buffer).toString("base64");
168
+ const json = JSON.stringify(data);
169
+ const encoder = new TextEncoder();
170
+ const stream = new Blob([encoder.encode(json)]).stream();
171
+ const compressed = stream.pipeThrough(new CompressionStream("gzip"));
172
+ const buffer = await new Response(compressed).arrayBuffer();
173
+ return Buffer.from(buffer).toString("base64");
119
174
  }
175
+ /**
176
+ * Decompress from base64 gzip
177
+ */
120
178
  export async function decompressFromBase64(base64) {
121
- const buffer = Buffer.from(base64, "base64");
122
- const stream = new Blob([buffer]).stream();
123
- const decompressed = stream.pipeThrough(new DecompressionStream("gzip"));
124
- const text = await new Response(decompressed).text();
125
- return JSON.parse(text);
179
+ const buffer = Buffer.from(base64, "base64");
180
+ const stream = new Blob([buffer]).stream();
181
+ const decompressed = stream.pipeThrough(new DecompressionStream("gzip"));
182
+ const text = await new Response(decompressed).text();
183
+ return JSON.parse(text);
126
184
  }
185
+ /**
186
+ * Insert or update a page
187
+ */
127
188
  export async function insertPage(db, page) {
128
- const now = Date.now();
129
- const source = page.source || "prerender";
130
- await db.exec(`
189
+ const now = Date.now();
190
+ const source = page.source || "prerender";
191
+ await db.exec(`
131
192
  INSERT OR REPLACE INTO ai_ready_pages (route, route_key, title, description, markdown, headings, keywords, content_hash, updated_at, indexed_at, is_error, indexed, source, last_seen_at, locale)
132
193
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
133
194
  `, [
134
- page.route,
135
- normalizeRouteKey(page.route),
136
- page.title,
137
- page.description,
138
- page.markdown,
139
- page.headings,
140
- JSON.stringify(page.keywords),
141
- page.contentHash || null,
142
- page.updatedAt,
143
- now,
144
- page.isError ? 1 : 0,
145
- page.isError ? 0 : 1,
146
- source,
147
- now,
148
- page.locale || ""
149
- ]);
195
+ page.route,
196
+ normalizeRouteKey(page.route),
197
+ page.title,
198
+ page.description,
199
+ page.markdown,
200
+ page.headings,
201
+ JSON.stringify(page.keywords),
202
+ page.contentHash || null,
203
+ page.updatedAt,
204
+ now,
205
+ page.isError ? 1 : 0,
206
+ page.isError ? 0 : 1,
207
+ source,
208
+ now,
209
+ page.locale || ""
210
+ ]);
150
211
  }
151
212
  export async function queryAllPages(db, options) {
152
- const where = options?.includeErrors ? "" : "WHERE is_error = 0";
153
- const fields = options?.excludeMarkdown ? "route, title, description, headings, keywords, content_hash, updated_at, is_error, locale" : "route, title, description, markdown, headings, keywords, content_hash, updated_at, is_error, locale";
154
- const rows = await db.all(`SELECT ${fields} FROM ai_ready_pages ${where}`);
155
- return rows.map((row) => ({
156
- route: row.route,
157
- title: row.title,
158
- description: row.description,
159
- ...options?.excludeMarkdown ? {} : { markdown: row.markdown },
160
- headings: row.headings,
161
- keywords: JSON.parse(row.keywords || "[]"),
162
- contentHash: row.content_hash || void 0,
163
- updatedAt: row.updated_at,
164
- isError: row.is_error === 1,
165
- locale: row.locale || ""
166
- }));
213
+ const where = options?.includeErrors ? "" : "WHERE is_error = 0";
214
+ const fields = options?.excludeMarkdown ? "route, title, description, headings, keywords, content_hash, updated_at, is_error, locale" : "route, title, description, markdown, headings, keywords, content_hash, updated_at, is_error, locale";
215
+ const rows = await db.all(`SELECT ${fields} FROM ai_ready_pages ${where}`);
216
+ return rows.map((row) => ({
217
+ route: row.route,
218
+ title: row.title,
219
+ description: row.description,
220
+ ...options?.excludeMarkdown ? {} : { markdown: row.markdown },
221
+ headings: row.headings,
222
+ keywords: JSON.parse(row.keywords || "[]"),
223
+ contentHash: row.content_hash || undefined,
224
+ updatedAt: row.updated_at,
225
+ isError: row.is_error === 1,
226
+ locale: row.locale || ""
227
+ }));
167
228
  }
168
229
  const DUMP_BATCH_SIZE = 500;
230
+ /**
231
+ * Export database as compressed dump (base64 gzip) using batched streaming
232
+ * Processes rows in batches to avoid loading entire database into memory
233
+ */
169
234
  export async function exportDbDump(db) {
170
- const encoder = new TextEncoder();
171
- const chunks = [];
172
- const compressionStream = new CompressionStream("gzip");
173
- const writer = compressionStream.writable.getWriter();
174
- const reader = compressionStream.readable.getReader();
175
- const readPromise = (async () => {
176
- while (true) {
177
- const { done, value } = await reader.read();
178
- if (done)
179
- break;
180
- chunks.push(value);
181
- }
182
- })();
183
- try {
184
- await writer.write(encoder.encode("["));
185
- let lastRoute;
186
- let first = true;
187
- while (true) {
188
- const rows = await db.all(`
235
+ const encoder = new TextEncoder();
236
+ const chunks = [];
237
+ // Create compression stream
238
+ const compressionStream = new CompressionStream("gzip");
239
+ const writer = compressionStream.writable.getWriter();
240
+ // Collect compressed output
241
+ const reader = compressionStream.readable.getReader();
242
+ const readPromise = (async () => {
243
+ while (true) {
244
+ const { done, value } = await reader.read();
245
+ if (done) break;
246
+ chunks.push(value);
247
+ }
248
+ })();
249
+ // Stream rows in batches. If anything throws mid-stream the writer must be
250
+ // aborted so the reader loop exits; otherwise `await readPromise` hangs forever.
251
+ try {
252
+ await writer.write(encoder.encode("["));
253
+ let lastRoute;
254
+ let first = true;
255
+ // Keyset (cursor) pagination on the route index; `OFFSET` would re-scan
256
+ // from the start on every page, degrading to O(N) on large tables.
257
+ while (true) {
258
+ const rows = await db.all(`
189
259
  SELECT route, route_key, title, description, markdown, headings, keywords, content_hash, updated_at, indexed_at, is_error, indexed, source, last_seen_at, locale
190
260
  FROM ai_ready_pages
191
261
  ${lastRoute ? "WHERE route > ?" : ""}
192
262
  ORDER BY route
193
263
  LIMIT ${DUMP_BATCH_SIZE}
194
264
  `, lastRoute ? [lastRoute] : []);
195
- if (rows.length === 0)
196
- break;
197
- for (const row of rows) {
198
- const prefix = first ? "" : ",";
199
- first = false;
200
- await writer.write(encoder.encode(prefix + JSON.stringify(row)));
201
- }
202
- if (rows.length < DUMP_BATCH_SIZE)
203
- break;
204
- lastRoute = rows[rows.length - 1].route;
205
- }
206
- await writer.write(encoder.encode("]"));
207
- await writer.close();
208
- } catch (err) {
209
- await writer.abort(err).catch(() => {
210
- });
211
- await reader.cancel().catch(() => {
212
- });
213
- throw err;
214
- }
215
- await readPromise;
216
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
217
- const result = new Uint8Array(totalLength);
218
- let pos = 0;
219
- for (const chunk of chunks) {
220
- result.set(chunk, pos);
221
- pos += chunk.length;
222
- }
223
- return Buffer.from(result).toString("base64");
265
+ if (rows.length === 0) break;
266
+ for (const row of rows) {
267
+ const prefix = first ? "" : ",";
268
+ first = false;
269
+ await writer.write(encoder.encode(prefix + JSON.stringify(row)));
270
+ }
271
+ if (rows.length < DUMP_BATCH_SIZE) break;
272
+ lastRoute = rows[rows.length - 1].route;
273
+ }
274
+ await writer.write(encoder.encode("]"));
275
+ await writer.close();
276
+ } catch (err) {
277
+ // Best-effort teardown; original error is rethrown below regardless.
278
+ await writer.abort(err).catch(() => {
279
+ // Preserve the original stream failure thrown below.
280
+ });
281
+ await reader.cancel().catch(() => {
282
+ // Preserve the original stream failure thrown below.
283
+ });
284
+ throw err;
285
+ }
286
+ await readPromise;
287
+ // Combine chunks and convert to base64
288
+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
289
+ const result = new Uint8Array(totalLength);
290
+ let pos = 0;
291
+ for (const chunk of chunks) {
292
+ result.set(chunk, pos);
293
+ pos += chunk.length;
294
+ }
295
+ return Buffer.from(result).toString("base64");
224
296
  }
297
+ /**
298
+ * Import dump into database
299
+ * Sets indexed=1 and last_seen_at=indexed_at.
300
+ *
301
+ * Rows are packed into multi-row INSERTs (14 bind params per row, 7 rows per
302
+ * statement stay under D1's 100-param cap) and fired through `db.batch` so a
303
+ * cold-start restore of thousands of pages is a handful of round-trips, not one
304
+ * per page.
305
+ */
225
306
  const IMPORT_ROWS_PER_STATEMENT = 7;
226
307
  export async function importDbDump(db, rows) {
227
- if (rows.length === 0)
228
- return;
229
- const byRoute = /* @__PURE__ */ new Map();
230
- for (const row of rows) {
231
- const route = normalizeRoute(row.route);
232
- byRoute.set(route, { ...row, route, route_key: normalizeRouteKey(route) });
233
- }
234
- const canonical = [...byRoute.values()];
235
- const stmts = [];
236
- for (let i = 0; i < canonical.length; i += IMPORT_ROWS_PER_STATEMENT) {
237
- const batch = canonical.slice(i, i + IMPORT_ROWS_PER_STATEMENT);
238
- const valuesSql = batch.map(() => `(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`).join(", ");
239
- const params = batch.flatMap((row) => {
240
- const source = row.source || "prerender";
241
- return [
242
- row.route,
243
- row.route_key,
244
- row.title,
245
- row.description,
246
- row.markdown,
247
- row.headings,
248
- row.keywords,
249
- row.content_hash || null,
250
- row.updated_at,
251
- row.indexed_at,
252
- row.is_error,
253
- source,
254
- row.indexed_at,
255
- row.locale || ""
256
- ];
257
- });
258
- stmts.push({
259
- sql: `
308
+ if (rows.length === 0) return;
309
+ // A dump written before routes were canonicalised can hold both '' and '/',
310
+ // which key alike and would fail the route_key index on import. Canonicalise
311
+ // and dedupe first so a stale dump cannot reintroduce the collision. Last row
312
+ // wins, matching the upsert semantics of the statement below.
313
+ const byRoute = new Map();
314
+ for (const row of rows) {
315
+ const route = normalizeRoute(row.route);
316
+ byRoute.set(route, {
317
+ ...row,
318
+ route,
319
+ route_key: normalizeRouteKey(route)
320
+ });
321
+ }
322
+ const canonical = [...byRoute.values()];
323
+ const stmts = [];
324
+ for (let i = 0; i < canonical.length; i += IMPORT_ROWS_PER_STATEMENT) {
325
+ const batch = canonical.slice(i, i + IMPORT_ROWS_PER_STATEMENT);
326
+ const valuesSql = batch.map(() => `(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`).join(", ");
327
+ const params = batch.flatMap((row) => {
328
+ const source = row.source || "prerender";
329
+ return [
330
+ row.route,
331
+ row.route_key,
332
+ row.title,
333
+ row.description,
334
+ row.markdown,
335
+ row.headings,
336
+ row.keywords,
337
+ row.content_hash || null,
338
+ row.updated_at,
339
+ row.indexed_at,
340
+ row.is_error,
341
+ source,
342
+ row.indexed_at,
343
+ row.locale || ""
344
+ ];
345
+ });
346
+ stmts.push({
347
+ sql: `
260
348
  INSERT INTO ai_ready_pages (route, route_key, title, description, markdown, headings, keywords, content_hash, updated_at, indexed_at, is_error, indexed, source, last_seen_at, locale)
261
349
  VALUES ${valuesSql}
262
350
  ON CONFLICT(route) DO UPDATE SET
@@ -275,13 +363,12 @@ export async function importDbDump(db, rows) {
275
363
  last_seen_at = excluded.last_seen_at,
276
364
  locale = excluded.locale
277
365
  `,
278
- params
279
- });
280
- }
281
- if (db.batch) {
282
- await db.batch(stmts);
283
- } else {
284
- for (const stmt of stmts)
285
- await db.exec(stmt.sql, stmt.params);
286
- }
366
+ params
367
+ });
368
+ }
369
+ if (db.batch) {
370
+ await db.batch(stmts);
371
+ } else {
372
+ for (const stmt of stmts) await db.exec(stmt.sql, stmt.params);
373
+ }
287
374
  }
@@ -1,17 +1 @@
1
- export {
2
- closeDrizzle,
3
- countPages,
4
- getPageLastmods,
5
- getStaleRoutes,
6
- indexPage,
7
- indexPageByRoute,
8
- isPageFresh,
9
- pruneStaleRoutes,
10
- queryPages,
11
- searchPages,
12
- seedRoutes,
13
- streamPages,
14
- upsertPage,
15
- useDrizzle,
16
- useRawDb
17
- } from "../index.js";
1
+ export { closeDrizzle, countPages, getPageLastmods, getStaleRoutes, indexPage, indexPageByRoute, isPageFresh, pruneStaleRoutes, queryPages, searchPages, seedRoutes, streamPages, upsertPage, useDrizzle, useRawDb } from "../index.js";
@@ -1,4 +1,8 @@
1
1
  import { hash } from "ohash";
2
+ /**
3
+ * Cache key for a site tool call: a digest of its parsed arguments.
4
+ * Each argument set gets its own entry, and every key has one length.
5
+ */
2
6
  export function siteToolCacheKey(args) {
3
- return hash(args);
7
+ return hash(args);
4
8
  }