nuxt-ai-ready 3.6.1 → 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 +18 -22
  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
@@ -8,359 +8,417 @@ import { LIKE_ESCAPE, likeSubstring, maxRowsPerInsert, toFtsMatchQuery } from ".
8
8
  import { useDrizzle } from "./client.js";
9
9
  import { getRawExecutor, useRawDb } from "./raw.js";
10
10
  function resolveFtsTokenizer(_event) {
11
- const cfg = useRuntimeConfig();
12
- return validateFtsTokenizer(cfg["nuxt-ai-ready"]?.ftsTokenizer);
11
+ const cfg = useRuntimeConfig();
12
+ return validateFtsTokenizer(cfg["nuxt-ai-ready"]?.ftsTokenizer);
13
13
  }
14
+ // ============================================================================
15
+ // Helpers
16
+ // ============================================================================
14
17
  const RE_LEADING_SLASH = /^\//;
15
18
  const RE_SLASH = /\//g;
19
+ /** See `normalizeRoute` in `../shared`: one page must resolve to one `route`. */
16
20
  function normalizeRoute(route) {
17
- if (!route || route === "/")
18
- return "/";
19
- return route.startsWith("/") ? route : `/${route}`;
21
+ if (!route || route === "/") return "/";
22
+ return route.startsWith("/") ? route : `/${route}`;
20
23
  }
21
24
  function normalizeRouteKey(route) {
22
- return normalizeRoute(route).replace(RE_LEADING_SLASH, "").replace(RE_SLASH, ":") || "index";
25
+ return normalizeRoute(route).replace(RE_LEADING_SLASH, "").replace(RE_SLASH, ":") || "index";
23
26
  }
24
27
  function rowToPage(row) {
25
- return {
26
- route: row.route,
27
- title: row.title,
28
- description: row.description,
29
- markdown: row.markdown,
30
- headings: row.headings,
31
- keywords: JSON.parse(row.keywords || "[]"),
32
- contentHash: row.contentHash || void 0,
33
- updatedAt: row.updatedAt,
34
- isError: row.isError === 1
35
- };
28
+ return {
29
+ route: row.route,
30
+ title: row.title,
31
+ description: row.description,
32
+ markdown: row.markdown,
33
+ headings: row.headings,
34
+ keywords: JSON.parse(row.keywords || "[]"),
35
+ contentHash: row.contentHash || undefined,
36
+ updatedAt: row.updatedAt,
37
+ isError: row.isError === 1
38
+ };
36
39
  }
37
40
  function rowToMeta(row) {
38
- return {
39
- route: row.route,
40
- title: row.title,
41
- description: row.description,
42
- headings: row.headings,
43
- keywords: JSON.parse(row.keywords || "[]"),
44
- updatedAt: row.updatedAt,
45
- isError: row.isError === 1
46
- };
47
- }
41
+ return {
42
+ route: row.route,
43
+ title: row.title,
44
+ description: row.description,
45
+ headings: row.headings,
46
+ keywords: JSON.parse(row.keywords || "[]"),
47
+ updatedAt: row.updatedAt,
48
+ isError: row.isError === 1
49
+ };
50
+ }
51
+ // ============================================================================
52
+ // Page Queries
53
+ // ============================================================================
54
+ /**
55
+ * Insert or update a page
56
+ */
48
57
  export async function upsertPage(event, page) {
49
- const client = await useDrizzle(event);
50
- const now = Date.now();
51
- const values = {
52
- route: normalizeRoute(page.route),
53
- routeKey: normalizeRouteKey(page.route),
54
- title: page.title,
55
- description: page.description,
56
- markdown: page.markdown,
57
- headings: page.headings,
58
- keywords: JSON.stringify(page.keywords),
59
- contentHash: page.contentHash || null,
60
- updatedAt: page.updatedAt,
61
- indexedAt: now,
62
- isError: page.isError ? 1 : 0,
63
- indexed: page.isError ? 0 : 1,
64
- source: page.source || "prerender",
65
- lastSeenAt: now
66
- };
67
- await client.db.insert(pages).values(values).onConflictDoUpdate({
68
- target: pages.route,
69
- set: {
70
- routeKey: values.routeKey,
71
- title: values.title,
72
- description: values.description,
73
- markdown: values.markdown,
74
- headings: values.headings,
75
- keywords: values.keywords,
76
- contentHash: values.contentHash,
77
- updatedAt: values.updatedAt,
78
- indexedAt: values.indexedAt,
79
- isError: values.isError,
80
- indexed: values.indexed,
81
- source: values.source,
82
- lastSeenAt: values.lastSeenAt
83
- }
84
- });
85
- }
58
+ const client = await useDrizzle(event);
59
+ const now = Date.now();
60
+ const values = {
61
+ route: normalizeRoute(page.route),
62
+ routeKey: normalizeRouteKey(page.route),
63
+ title: page.title,
64
+ description: page.description,
65
+ markdown: page.markdown,
66
+ headings: page.headings,
67
+ keywords: JSON.stringify(page.keywords),
68
+ contentHash: page.contentHash || null,
69
+ updatedAt: page.updatedAt,
70
+ indexedAt: now,
71
+ isError: page.isError ? 1 : 0,
72
+ indexed: page.isError ? 0 : 1,
73
+ source: page.source || "prerender",
74
+ lastSeenAt: now
75
+ };
76
+ await client.db.insert(pages).values(values).onConflictDoUpdate({
77
+ target: pages.route,
78
+ set: {
79
+ routeKey: values.routeKey,
80
+ title: values.title,
81
+ description: values.description,
82
+ markdown: values.markdown,
83
+ headings: values.headings,
84
+ keywords: values.keywords,
85
+ contentHash: values.contentHash,
86
+ updatedAt: values.updatedAt,
87
+ indexedAt: values.indexedAt,
88
+ isError: values.isError,
89
+ indexed: values.indexed,
90
+ source: values.source,
91
+ lastSeenAt: values.lastSeenAt
92
+ }
93
+ });
94
+ }
95
+ /**
96
+ * Get all pages
97
+ */
86
98
  export async function getAllPages(event, options) {
87
- const client = await useDrizzle(event);
88
- const cols = options?.excludeMarkdown ? {
89
- route: pages.route,
90
- title: pages.title,
91
- description: pages.description,
92
- headings: pages.headings,
93
- keywords: pages.keywords,
94
- contentHash: pages.contentHash,
95
- updatedAt: pages.updatedAt,
96
- isError: pages.isError
97
- } : void 0;
98
- let query = cols ? client.db.select(cols).from(pages) : client.db.select().from(pages);
99
- if (!options?.includeErrors) {
100
- query = query.where(eq(pages.isError, 0));
101
- }
102
- const rows = await query;
103
- return rows.map((row) => cols ? rowToMeta(row) : rowToPage(row));
104
- }
99
+ const client = await useDrizzle(event);
100
+ // When markdown is excluded, project only the meta columns instead of
101
+ // selecting `*` and discarding markdown after transfer (markdown is by far
102
+ // the largest column).
103
+ const cols = options?.excludeMarkdown ? {
104
+ route: pages.route,
105
+ title: pages.title,
106
+ description: pages.description,
107
+ headings: pages.headings,
108
+ keywords: pages.keywords,
109
+ contentHash: pages.contentHash,
110
+ updatedAt: pages.updatedAt,
111
+ isError: pages.isError
112
+ } : undefined;
113
+ let query = cols ? client.db.select(cols).from(pages) : client.db.select().from(pages);
114
+ if (!options?.includeErrors) {
115
+ query = query.where(eq(pages.isError, 0));
116
+ }
117
+ const rows = await query;
118
+ return rows.map((row) => cols ? rowToMeta(row) : rowToPage(row));
119
+ }
120
+ /**
121
+ * Get a single page by route
122
+ */
105
123
  export async function getPageByRoute(event, route) {
106
- const client = await useDrizzle(event);
107
- const rows = await client.db.select().from(pages).where(eq(pages.route, route)).limit(1);
108
- if (!rows.length)
109
- return void 0;
110
- return rowToPage(rows[0]);
111
- }
124
+ const client = await useDrizzle(event);
125
+ const rows = await client.db.select().from(pages).where(eq(pages.route, route)).limit(1);
126
+ if (!rows.length) return undefined;
127
+ return rowToPage(rows[0]);
128
+ }
129
+ /**
130
+ * Get lastmod (updatedAt) for all indexed pages
131
+ * Returns a Map for O(1) lookup when enriching sitemaps
132
+ */
112
133
  export async function getPageLastmods(event) {
113
- const client = await useDrizzle(event);
114
- const rows = await client.db.select({
115
- route: pages.route,
116
- updatedAt: pages.updatedAt
117
- }).from(pages).where(and(
118
- eq(pages.isError, 0),
119
- eq(pages.indexed, 1)
120
- ));
121
- const map = /* @__PURE__ */ new Map();
122
- for (const row of rows) {
123
- if (row.route && row.updatedAt) {
124
- map.set(row.route, row.updatedAt);
125
- }
126
- }
127
- return map;
128
- }
134
+ const client = await useDrizzle(event);
135
+ const rows = await client.db.select({
136
+ route: pages.route,
137
+ updatedAt: pages.updatedAt
138
+ }).from(pages).where(and(eq(pages.isError, 0), eq(pages.indexed, 1)));
139
+ const map = new Map();
140
+ for (const row of rows) {
141
+ if (row.route && row.updatedAt) {
142
+ map.set(row.route, row.updatedAt);
143
+ }
144
+ }
145
+ return map;
146
+ }
147
+ /**
148
+ * Search pages (uses LIKE for both dialects, FTS5 fallback for SQLite)
149
+ */
129
150
  export async function searchPages(event, query, options) {
130
- const client = await useDrizzle(event);
131
- const limitNum = options?.limit || 20;
132
- const searchTerm = likeSubstring(query);
133
- const matches = (col) => sql`${col} LIKE ${searchTerm} ESCAPE ${LIKE_ESCAPE}`;
134
- const ftsQuery = toFtsMatchQuery(query);
135
- if (client.dialect === "sqlite" && ftsQuery) {
136
- try {
137
- const ftsResult = await client.db.all(sql`
151
+ const client = await useDrizzle(event);
152
+ const limitNum = options?.limit || 20;
153
+ const searchTerm = likeSubstring(query);
154
+ const matches = (col) => sql`${col} LIKE ${searchTerm} ESCAPE ${LIKE_ESCAPE}`;
155
+ // For SQLite, try FTS5 first via raw SQL. A query with no searchable term
156
+ // skips FTS and goes straight to LIKE, which still matches literal symbols.
157
+ const ftsQuery = toFtsMatchQuery(query);
158
+ if (client.dialect === "sqlite" && ftsQuery) {
159
+ try {
160
+ const ftsResult = await client.db.all(sql`
138
161
  SELECT p.route, p.title, p.description, p.headings, p.keywords, p.updated_at as "updatedAt", p.is_error as "isError"
139
162
  FROM ai_ready_pages p
140
163
  JOIN ai_ready_pages_fts fts ON p.id = fts.rowid
141
164
  WHERE ai_ready_pages_fts MATCH ${ftsQuery} AND p.is_error = 0
142
165
  LIMIT ${limitNum}
143
166
  `);
144
- if (ftsResult?.length) {
145
- return ftsResult.map(rowToMeta);
146
- }
147
- } catch {
148
- }
149
- }
150
- const rows = await client.db.select({
151
- route: pages.route,
152
- title: pages.title,
153
- description: pages.description,
154
- headings: pages.headings,
155
- keywords: pages.keywords,
156
- updatedAt: pages.updatedAt,
157
- isError: pages.isError
158
- }).from(pages).where(
159
- and(
160
- eq(pages.isError, 0),
161
- or(
162
- matches(pages.title),
163
- matches(pages.description),
164
- matches(pages.markdown),
165
- matches(pages.headings)
166
- )
167
- )
168
- ).limit(limitNum);
169
- return rows.map(rowToMeta);
170
- }
167
+ if (ftsResult?.length) {
168
+ return ftsResult.map(rowToMeta);
169
+ }
170
+ } catch {}
171
+ }
172
+ // LIKE-based search
173
+ const rows = await client.db.select({
174
+ route: pages.route,
175
+ title: pages.title,
176
+ description: pages.description,
177
+ headings: pages.headings,
178
+ keywords: pages.keywords,
179
+ updatedAt: pages.updatedAt,
180
+ isError: pages.isError
181
+ }).from(pages).where(and(eq(pages.isError, 0), or(matches(pages.title), matches(pages.description), matches(pages.markdown), matches(pages.headings)))).limit(limitNum);
182
+ return rows.map(rowToMeta);
183
+ }
184
+ /**
185
+ * Count pages
186
+ */
171
187
  export async function countPages(event, options) {
172
- const client = await useDrizzle(event);
173
- const conditions = [];
174
- if (options?.indexed !== void 0) {
175
- conditions.push(eq(pages.indexed, options.indexed ? 1 : 0));
176
- }
177
- if (options?.errors !== void 0) {
178
- conditions.push(eq(pages.isError, options.errors ? 1 : 0));
179
- } else {
180
- conditions.push(eq(pages.isError, 0));
181
- }
182
- let query = client.db.select({ count: count() }).from(pages);
183
- if (conditions.length > 0) {
184
- query = query.where(and(...conditions));
185
- }
186
- const result = await query;
187
- return Number(result[0]?.count || 0);
188
- }
188
+ const client = await useDrizzle(event);
189
+ const conditions = [];
190
+ if (options?.indexed !== undefined) {
191
+ conditions.push(eq(pages.indexed, options.indexed ? 1 : 0));
192
+ }
193
+ if (options?.errors !== undefined) {
194
+ conditions.push(eq(pages.isError, options.errors ? 1 : 0));
195
+ } else {
196
+ conditions.push(eq(pages.isError, 0));
197
+ }
198
+ let query = client.db.select({ count: count() }).from(pages);
199
+ if (conditions.length > 0) {
200
+ query = query.where(and(...conditions));
201
+ }
202
+ const result = await query;
203
+ return Number(result[0]?.count || 0);
204
+ }
205
+ /**
206
+ * Get pending pages (not yet indexed)
207
+ */
189
208
  export async function getPendingPages(event, limit = 10) {
190
- const client = await useDrizzle(event);
191
- return client.db.select({ route: pages.route }).from(pages).where(and(
192
- eq(pages.indexed, 0),
193
- eq(pages.isError, 0)
194
- )).orderBy(pages.route).limit(limit);
209
+ const client = await useDrizzle(event);
210
+ return client.db.select({ route: pages.route }).from(pages).where(and(eq(pages.indexed, 0), eq(pages.isError, 0))).orderBy(pages.route).limit(limit);
195
211
  }
212
+ /**
213
+ * Mark page as indexed
214
+ */
196
215
  export async function markPageIndexed(event, route) {
197
- const client = await useDrizzle(event);
198
- await client.db.update(pages).set({ indexed: 1, indexedAt: Date.now() }).where(eq(pages.route, route));
199
- }
216
+ const client = await useDrizzle(event);
217
+ await client.db.update(pages).set({
218
+ indexed: 1,
219
+ indexedAt: Date.now()
220
+ }).where(eq(pages.route, route));
221
+ }
222
+ /**
223
+ * Mark multiple routes as pending (needing re-index)
224
+ */
200
225
  export async function markRoutesPending(event, routes) {
201
- if (routes.length === 0)
202
- return;
203
- const db = await useRawDb(event);
204
- const stmts = [];
205
- const D1_MAX_IN_ROUTES = 99;
206
- for (let i = 0; i < routes.length; i += D1_MAX_IN_ROUTES) {
207
- const batch = routes.slice(i, i + D1_MAX_IN_ROUTES);
208
- const placeholders = batch.map(() => "?").join(",");
209
- stmts.push({
210
- sql: `UPDATE ai_ready_pages SET indexed = 0, is_error = 0 WHERE route IN (${placeholders})`,
211
- params: batch
212
- });
213
- }
214
- await db.batch(stmts);
215
- }
226
+ if (routes.length === 0) return;
227
+ // D1/SQLite caps prepared-statement params at 100; chunk the IN clause to
228
+ // 99 routes per statement, then run all chunks in one driver-level batch.
229
+ const db = await useRawDb(event);
230
+ const stmts = [];
231
+ const D1_MAX_IN_ROUTES = 99;
232
+ for (let i = 0; i < routes.length; i += D1_MAX_IN_ROUTES) {
233
+ const batch = routes.slice(i, i + D1_MAX_IN_ROUTES);
234
+ const placeholders = batch.map(() => "?").join(",");
235
+ stmts.push({
236
+ sql: `UPDATE ai_ready_pages SET indexed = 0, is_error = 0 WHERE route IN (${placeholders})`,
237
+ params: batch
238
+ });
239
+ }
240
+ await db.batch(stmts);
241
+ }
242
+ /**
243
+ * Get content hashes for all pages
244
+ */
216
245
  export async function getContentHashes(event) {
217
- const client = await useDrizzle(event);
218
- const rows = await client.db.select({ route: pages.route, contentHash: pages.contentHash }).from(pages);
219
- return new Map(rows.map((r) => [r.route, r.contentHash]));
220
- }
246
+ const client = await useDrizzle(event);
247
+ const rows = await client.db.select({
248
+ route: pages.route,
249
+ contentHash: pages.contentHash
250
+ }).from(pages);
251
+ return new Map(rows.map((r) => [r.route, r.contentHash]));
252
+ }
253
+ // ============================================================================
254
+ // Info Table Queries (key-value metadata store)
255
+ // ============================================================================
256
+ /**
257
+ * Get a value from the info table
258
+ */
221
259
  export async function getInfoValue(event, key) {
222
- const client = await useDrizzle(event);
223
- const row = await client.db.select({ value: info.value }).from(info).where(eq(info.id, key)).limit(1);
224
- return row[0]?.value || null;
260
+ const client = await useDrizzle(event);
261
+ const row = await client.db.select({ value: info.value }).from(info).where(eq(info.id, key)).limit(1);
262
+ return row[0]?.value || null;
225
263
  }
264
+ /**
265
+ * Set a value in the info table
266
+ */
226
267
  export async function setInfoValue(event, key, value) {
227
- const client = await useDrizzle(event);
228
- await client.db.insert(info).values({ id: key, value }).onConflictDoUpdate({
229
- target: info.id,
230
- set: { value }
231
- });
232
- }
268
+ const client = await useDrizzle(event);
269
+ await client.db.insert(info).values({
270
+ id: key,
271
+ value
272
+ }).onConflictDoUpdate({
273
+ target: info.id,
274
+ set: { value }
275
+ });
276
+ }
277
+ /**
278
+ * Delete a value from the info table
279
+ */
233
280
  export async function deleteInfoValue(event, key) {
234
- const client = await useDrizzle(event);
235
- await client.db.delete(info).where(eq(info.id, key));
281
+ const client = await useDrizzle(event);
282
+ await client.db.delete(info).where(eq(info.id, key));
236
283
  }
284
+ // ============================================================================
285
+ // Schema Management
286
+ // ============================================================================
237
287
  const LEGACY_SQLITE_SCHEMA_VERSION = "v2.3.0-drizzle";
238
288
  const SQLITE_SCHEMA_VERSION = "v2.4.0-drizzle-source-lastmod";
239
289
  const LEGACY_POSTGRES_INTEGER_SCHEMA_VERSION = "v2.3.0-drizzle";
240
290
  const LEGACY_POSTGRES_SCHEMA_VERSION = "v2.3.0-drizzle-postgres-bigint";
241
291
  const POSTGRES_SCHEMA_VERSION = "v2.4.0-drizzle-postgres-source-lastmod";
292
+ /**
293
+ * Initialize database schema. Rebuilds on a schema version change or when the
294
+ * SQLite FTS5 tokenizer differs from the one baked into the existing virtual
295
+ * table (Postgres has no FTS5; tokenizer comparison is SQLite-only).
296
+ */
242
297
  export async function initSchema(event) {
243
- const client = await useDrizzle(event);
244
- const tokenizer = resolveFtsTokenizer(event);
245
- const schemaVersion = client.dialect === "postgres" ? POSTGRES_SCHEMA_VERSION : SQLITE_SCHEMA_VERSION;
246
- const currentVersion = await getSchemaVersion(client);
247
- const currentTokenizer = client.dialect === "postgres" ? null : await getStoredTokenizer(client);
248
- const versionMatches = currentVersion === schemaVersion;
249
- const tokenizerMatches = client.dialect === "postgres" || !currentTokenizer || currentTokenizer === tokenizer;
250
- if (versionMatches && tokenizerMatches)
251
- return;
252
- if (client.dialect === "postgres" && currentVersion === LEGACY_POSTGRES_INTEGER_SCHEMA_VERSION) {
253
- await migratePostgresIntegerTimestamps(client);
254
- await migrateSourceLastmod(client, schemaVersion);
255
- return;
256
- }
257
- if (tokenizerMatches && (client.dialect === "postgres" ? currentVersion === LEGACY_POSTGRES_SCHEMA_VERSION : currentVersion === LEGACY_SQLITE_SCHEMA_VERSION)) {
258
- await migrateSourceLastmod(client, schemaVersion);
259
- return;
260
- }
261
- if (currentVersion) {
262
- if (client.dialect === "postgres") {
263
- await dropPostgresTables(client);
264
- } else {
265
- await dropSQLiteTables(client);
266
- }
267
- }
268
- if (client.dialect === "postgres") {
269
- await createPostgresTables(client);
270
- } else {
271
- await createSQLiteTables(client, tokenizer);
272
- }
273
- await client.db.insert(info).values({ id: "schema", version: schemaVersion }).onConflictDoUpdate({
274
- target: info.id,
275
- set: { version: schemaVersion }
276
- });
277
- if (client.dialect !== "postgres") {
278
- await client.db.insert(info).values({ id: "fts_tokenizer", value: tokenizer }).onConflictDoUpdate({
279
- target: info.id,
280
- set: { value: tokenizer }
281
- });
282
- }
298
+ const client = await useDrizzle(event);
299
+ const tokenizer = resolveFtsTokenizer(event);
300
+ const schemaVersion = client.dialect === "postgres" ? POSTGRES_SCHEMA_VERSION : SQLITE_SCHEMA_VERSION;
301
+ const currentVersion = await getSchemaVersion(client);
302
+ const currentTokenizer = client.dialect === "postgres" ? null : await getStoredTokenizer(client);
303
+ const versionMatches = currentVersion === schemaVersion;
304
+ const tokenizerMatches = client.dialect === "postgres" || !currentTokenizer || currentTokenizer === tokenizer;
305
+ if (versionMatches && tokenizerMatches) return;
306
+ if (client.dialect === "postgres" && currentVersion === LEGACY_POSTGRES_INTEGER_SCHEMA_VERSION) {
307
+ await migratePostgresIntegerTimestamps(client);
308
+ await migrateSourceLastmod(client, schemaVersion);
309
+ return;
310
+ }
311
+ if (tokenizerMatches && (client.dialect === "postgres" ? currentVersion === LEGACY_POSTGRES_SCHEMA_VERSION : currentVersion === LEGACY_SQLITE_SCHEMA_VERSION)) {
312
+ await migrateSourceLastmod(client, schemaVersion);
313
+ return;
314
+ }
315
+ // Drop tables on any mismatch (version bump or tokenizer change). Pages get re-indexed on next run.
316
+ if (currentVersion) {
317
+ if (client.dialect === "postgres") {
318
+ await dropPostgresTables(client);
319
+ } else {
320
+ await dropSQLiteTables(client);
321
+ }
322
+ }
323
+ // Create tables via raw SQL (Drizzle doesn't have push/migrate at runtime without CLI)
324
+ if (client.dialect === "postgres") {
325
+ await createPostgresTables(client);
326
+ } else {
327
+ await createSQLiteTables(client, tokenizer);
328
+ }
329
+ // Update version + tokenizer
330
+ await client.db.insert(info).values({
331
+ id: "schema",
332
+ version: schemaVersion
333
+ }).onConflictDoUpdate({
334
+ target: info.id,
335
+ set: { version: schemaVersion }
336
+ });
337
+ if (client.dialect !== "postgres") {
338
+ await client.db.insert(info).values({
339
+ id: "fts_tokenizer",
340
+ value: tokenizer
341
+ }).onConflictDoUpdate({
342
+ target: info.id,
343
+ set: { value: tokenizer }
344
+ });
345
+ }
283
346
  }
284
347
  async function getSchemaVersion(client) {
285
- try {
286
- const [row] = await client.db.select({ version: info.version }).from(info).where(eq(info.id, "schema")).limit(1);
287
- return row?.version || null;
288
- } catch (error) {
289
- if (isMissingInfoTableError(error))
290
- return null;
291
- throw error;
292
- }
348
+ try {
349
+ const [row] = await client.db.select({ version: info.version }).from(info).where(eq(info.id, "schema")).limit(1);
350
+ return row?.version || null;
351
+ } catch (error) {
352
+ if (isMissingInfoTableError(error)) return null;
353
+ throw error;
354
+ }
293
355
  }
294
356
  async function getStoredTokenizer(client) {
295
- try {
296
- const [row] = await client.db.select({ value: info.value }).from(info).where(eq(info.id, "fts_tokenizer")).limit(1);
297
- return row?.value || null;
298
- } catch (error) {
299
- if (isMissingInfoTableError(error))
300
- return null;
301
- throw error;
302
- }
357
+ try {
358
+ const [row] = await client.db.select({ value: info.value }).from(info).where(eq(info.id, "fts_tokenizer")).limit(1);
359
+ return row?.value || null;
360
+ } catch (error) {
361
+ if (isMissingInfoTableError(error)) return null;
362
+ throw error;
363
+ }
303
364
  }
304
365
  function isMissingInfoTableError(error) {
305
- let current = error;
306
- const seen = /* @__PURE__ */ new Set();
307
- while (current && typeof current === "object" && !seen.has(current)) {
308
- seen.add(current);
309
- const candidate = current;
310
- if (candidate.code === "42P01")
311
- return true;
312
- if (typeof candidate.message === "string" && candidate.message.includes("no such table") && candidate.message.includes("_ai_ready_info")) {
313
- return true;
314
- }
315
- current = candidate.cause;
316
- }
317
- return false;
366
+ let current = error;
367
+ const seen = new Set();
368
+ while (current && typeof current === "object" && !seen.has(current)) {
369
+ seen.add(current);
370
+ const candidate = current;
371
+ if (candidate.code === "42P01") return true;
372
+ if (typeof candidate.message === "string" && candidate.message.includes("no such table") && candidate.message.includes("_ai_ready_info")) {
373
+ return true;
374
+ }
375
+ current = candidate.cause;
376
+ }
377
+ return false;
318
378
  }
319
379
  const SQLITE_DROP_STATEMENTS = [
320
- sql`DROP TABLE IF EXISTS ai_ready_pages_fts`,
321
- sql`DROP TABLE IF EXISTS ai_ready_pages`,
322
- sql`DROP TABLE IF EXISTS _ai_ready_info`,
323
- sql`DROP TABLE IF EXISTS ai_ready_cron_runs`,
324
- sql`DROP TABLE IF EXISTS ai_ready_indexnow_log`,
325
- sql`DROP TABLE IF EXISTS ai_ready_sitemaps`
380
+ sql`DROP TABLE IF EXISTS ai_ready_pages_fts`,
381
+ sql`DROP TABLE IF EXISTS ai_ready_pages`,
382
+ sql`DROP TABLE IF EXISTS _ai_ready_info`,
383
+ sql`DROP TABLE IF EXISTS ai_ready_cron_runs`,
384
+ sql`DROP TABLE IF EXISTS ai_ready_indexnow_log`,
385
+ sql`DROP TABLE IF EXISTS ai_ready_sitemaps`
326
386
  ];
327
387
  const POSTGRES_DROP_STATEMENTS = [
328
- sql`DROP TABLE IF EXISTS ai_ready_pages CASCADE`,
329
- sql`DROP TABLE IF EXISTS _ai_ready_info CASCADE`,
330
- sql`DROP TABLE IF EXISTS ai_ready_cron_runs CASCADE`,
331
- sql`DROP TABLE IF EXISTS ai_ready_indexnow_log CASCADE`,
332
- sql`DROP TABLE IF EXISTS ai_ready_sitemaps CASCADE`
388
+ sql`DROP TABLE IF EXISTS ai_ready_pages CASCADE`,
389
+ sql`DROP TABLE IF EXISTS _ai_ready_info CASCADE`,
390
+ sql`DROP TABLE IF EXISTS ai_ready_cron_runs CASCADE`,
391
+ sql`DROP TABLE IF EXISTS ai_ready_indexnow_log CASCADE`,
392
+ sql`DROP TABLE IF EXISTS ai_ready_sitemaps CASCADE`
333
393
  ];
334
394
  async function dropSQLiteTables(client) {
335
- for (const stmt of SQLITE_DROP_STATEMENTS)
336
- await client.db.run(stmt);
395
+ for (const stmt of SQLITE_DROP_STATEMENTS) await client.db.run(stmt);
337
396
  }
338
397
  async function dropPostgresTables(client) {
339
- for (const stmt of POSTGRES_DROP_STATEMENTS)
340
- await client.db.execute(stmt);
398
+ for (const stmt of POSTGRES_DROP_STATEMENTS) await client.db.execute(stmt);
341
399
  }
342
400
  async function migratePostgresIntegerTimestamps(client) {
343
- await getRawExecutor(client).batch([
344
- { sql: "ALTER TABLE ai_ready_pages ALTER COLUMN indexed_at TYPE BIGINT USING indexed_at::BIGINT" },
345
- { sql: "ALTER TABLE ai_ready_pages ALTER COLUMN last_seen_at TYPE BIGINT USING last_seen_at::BIGINT" },
346
- { sql: "ALTER TABLE ai_ready_cron_runs ALTER COLUMN started_at TYPE BIGINT USING started_at::BIGINT" },
347
- { sql: "ALTER TABLE ai_ready_cron_runs ALTER COLUMN finished_at TYPE BIGINT USING finished_at::BIGINT" },
348
- { sql: "ALTER TABLE ai_ready_sitemaps ALTER COLUMN last_crawled_at TYPE BIGINT USING last_crawled_at::BIGINT" },
349
- {
350
- sql: "UPDATE _ai_ready_info SET version = ? WHERE id = 'schema'",
351
- params: [LEGACY_POSTGRES_SCHEMA_VERSION]
352
- }
353
- ]);
401
+ await getRawExecutor(client).batch([
402
+ { sql: "ALTER TABLE ai_ready_pages ALTER COLUMN indexed_at TYPE BIGINT USING indexed_at::BIGINT" },
403
+ { sql: "ALTER TABLE ai_ready_pages ALTER COLUMN last_seen_at TYPE BIGINT USING last_seen_at::BIGINT" },
404
+ { sql: "ALTER TABLE ai_ready_cron_runs ALTER COLUMN started_at TYPE BIGINT USING started_at::BIGINT" },
405
+ { sql: "ALTER TABLE ai_ready_cron_runs ALTER COLUMN finished_at TYPE BIGINT USING finished_at::BIGINT" },
406
+ { sql: "ALTER TABLE ai_ready_sitemaps ALTER COLUMN last_crawled_at TYPE BIGINT USING last_crawled_at::BIGINT" },
407
+ {
408
+ sql: "UPDATE _ai_ready_info SET version = ? WHERE id = 'schema'",
409
+ params: [LEGACY_POSTGRES_SCHEMA_VERSION]
410
+ }
411
+ ]);
354
412
  }
355
413
  async function migrateSourceLastmod(client, schemaVersion) {
356
- await getRawExecutor(client).batch([
357
- { sql: "ALTER TABLE ai_ready_pages ADD COLUMN source_lastmod TEXT" },
358
- { sql: "UPDATE _ai_ready_info SET version = ? WHERE id = 'schema'", params: [schemaVersion] }
359
- ]);
414
+ await getRawExecutor(client).batch([{ sql: "ALTER TABLE ai_ready_pages ADD COLUMN source_lastmod TEXT" }, {
415
+ sql: "UPDATE _ai_ready_info SET version = ? WHERE id = 'schema'",
416
+ params: [schemaVersion]
417
+ }]);
360
418
  }
361
419
  async function createSQLiteTables(client, ftsTokenizer) {
362
- const statements = [
363
- sql`CREATE TABLE IF NOT EXISTS ai_ready_pages (
420
+ const statements = [
421
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_pages (
364
422
  id INTEGER PRIMARY KEY AUTOINCREMENT,
365
423
  route TEXT UNIQUE NOT NULL,
366
424
  route_key TEXT UNIQUE NOT NULL,
@@ -379,14 +437,14 @@ async function createSQLiteTables(client, ftsTokenizer) {
379
437
  last_seen_at INTEGER,
380
438
  locale TEXT NOT NULL DEFAULT ''
381
439
  )`,
382
- sql`CREATE TABLE IF NOT EXISTS _ai_ready_info (
440
+ sql`CREATE TABLE IF NOT EXISTS _ai_ready_info (
383
441
  id TEXT PRIMARY KEY,
384
442
  value TEXT,
385
443
  version TEXT,
386
444
  checksum TEXT,
387
445
  ready INTEGER DEFAULT 0
388
446
  )`,
389
- sql`CREATE TABLE IF NOT EXISTS ai_ready_cron_runs (
447
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_cron_runs (
390
448
  id INTEGER PRIMARY KEY AUTOINCREMENT,
391
449
  started_at INTEGER NOT NULL,
392
450
  finished_at INTEGER,
@@ -396,7 +454,7 @@ async function createSQLiteTables(client, ftsTokenizer) {
396
454
  errors TEXT DEFAULT '[]',
397
455
  status TEXT DEFAULT 'running'
398
456
  )`,
399
- sql`CREATE TABLE IF NOT EXISTS ai_ready_sitemaps (
457
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_sitemaps (
400
458
  name TEXT PRIMARY KEY,
401
459
  route TEXT NOT NULL,
402
460
  last_crawled_at INTEGER,
@@ -405,29 +463,25 @@ async function createSQLiteTables(client, ftsTokenizer) {
405
463
  last_error TEXT,
406
464
  crawl_state TEXT
407
465
  )`,
408
- // Indexes
409
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_route ON ai_ready_pages(route)`,
410
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_is_error ON ai_ready_pages(is_error)`,
411
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_indexed ON ai_ready_pages(indexed)`,
412
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_source ON ai_ready_pages(source)`,
413
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_last_seen ON ai_ready_pages(last_seen_at)`,
414
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_locale ON ai_ready_pages(locale)`,
415
- // FTS5 virtual table — tokenizer chosen by runtime config (trigram for CJK locales)
416
- sql.raw(`CREATE VIRTUAL TABLE IF NOT EXISTS ai_ready_pages_fts USING fts5(
466
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_route ON ai_ready_pages(route)`,
467
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_is_error ON ai_ready_pages(is_error)`,
468
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_indexed ON ai_ready_pages(indexed)`,
469
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_source ON ai_ready_pages(source)`,
470
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_last_seen ON ai_ready_pages(last_seen_at)`,
471
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_locale ON ai_ready_pages(locale)`,
472
+ sql.raw(`CREATE VIRTUAL TABLE IF NOT EXISTS ai_ready_pages_fts USING fts5(
417
473
  route, title, description, markdown, headings, keywords,
418
474
  content=ai_ready_pages, content_rowid=id, tokenize='${ftsTokenizer}'
419
475
  )`),
420
- // FTS triggers. The UPDATE trigger only fires when a searchable column
421
- // actually changed; updates to bookkeeping columns skip FTS churn.
422
- sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_ai AFTER INSERT ON ai_ready_pages BEGIN
476
+ sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_ai AFTER INSERT ON ai_ready_pages BEGIN
423
477
  INSERT INTO ai_ready_pages_fts(rowid, route, title, description, markdown, headings, keywords)
424
478
  VALUES (new.id, new.route, new.title, new.description, new.markdown, new.headings, new.keywords);
425
479
  END`,
426
- sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_ad AFTER DELETE ON ai_ready_pages BEGIN
480
+ sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_ad AFTER DELETE ON ai_ready_pages BEGIN
427
481
  INSERT INTO ai_ready_pages_fts(ai_ready_pages_fts, rowid, route, title, description, markdown, headings, keywords)
428
482
  VALUES('delete', old.id, old.route, old.title, old.description, old.markdown, old.headings, old.keywords);
429
483
  END`,
430
- sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_au AFTER UPDATE ON ai_ready_pages
484
+ sql`CREATE TRIGGER IF NOT EXISTS ai_ready_pages_au AFTER UPDATE ON ai_ready_pages
431
485
  WHEN old.route IS NOT new.route
432
486
  OR old.title IS NOT new.title
433
487
  OR old.description IS NOT new.description
@@ -440,14 +494,14 @@ async function createSQLiteTables(client, ftsTokenizer) {
440
494
  INSERT INTO ai_ready_pages_fts(rowid, route, title, description, markdown, headings, keywords)
441
495
  VALUES (new.id, new.route, new.title, new.description, new.markdown, new.headings, new.keywords);
442
496
  END`
443
- ];
444
- for (const stmt of statements) {
445
- await client.db.run(stmt);
446
- }
497
+ ];
498
+ for (const stmt of statements) {
499
+ await client.db.run(stmt);
500
+ }
447
501
  }
448
502
  async function createPostgresTables(client) {
449
- const statements = [
450
- sql`CREATE TABLE IF NOT EXISTS ai_ready_pages (
503
+ const statements = [
504
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_pages (
451
505
  id SERIAL PRIMARY KEY,
452
506
  route TEXT UNIQUE NOT NULL,
453
507
  route_key TEXT UNIQUE NOT NULL,
@@ -466,14 +520,14 @@ async function createPostgresTables(client) {
466
520
  last_seen_at BIGINT,
467
521
  locale TEXT NOT NULL DEFAULT ''
468
522
  )`,
469
- sql`CREATE TABLE IF NOT EXISTS _ai_ready_info (
523
+ sql`CREATE TABLE IF NOT EXISTS _ai_ready_info (
470
524
  id TEXT PRIMARY KEY,
471
525
  value TEXT,
472
526
  version TEXT,
473
527
  checksum TEXT,
474
528
  ready INTEGER DEFAULT 0
475
529
  )`,
476
- sql`CREATE TABLE IF NOT EXISTS ai_ready_cron_runs (
530
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_cron_runs (
477
531
  id SERIAL PRIMARY KEY,
478
532
  started_at BIGINT NOT NULL,
479
533
  finished_at BIGINT,
@@ -483,7 +537,7 @@ async function createPostgresTables(client) {
483
537
  errors TEXT DEFAULT '[]',
484
538
  status TEXT DEFAULT 'running'
485
539
  )`,
486
- sql`CREATE TABLE IF NOT EXISTS ai_ready_sitemaps (
540
+ sql`CREATE TABLE IF NOT EXISTS ai_ready_sitemaps (
487
541
  name TEXT PRIMARY KEY,
488
542
  route TEXT NOT NULL,
489
543
  last_crawled_at BIGINT,
@@ -492,228 +546,275 @@ async function createPostgresTables(client) {
492
546
  last_error TEXT,
493
547
  crawl_state TEXT
494
548
  )`,
495
- // Indexes
496
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_route ON ai_ready_pages(route)`,
497
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_is_error ON ai_ready_pages(is_error)`,
498
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_indexed ON ai_ready_pages(indexed)`,
499
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_source ON ai_ready_pages(source)`,
500
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_last_seen ON ai_ready_pages(last_seen_at)`,
501
- sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_locale ON ai_ready_pages(locale)`
502
- ];
503
- for (const stmt of statements) {
504
- await client.db.execute(stmt);
505
- }
549
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_route ON ai_ready_pages(route)`,
550
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_is_error ON ai_ready_pages(is_error)`,
551
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_indexed ON ai_ready_pages(indexed)`,
552
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_source ON ai_ready_pages(source)`,
553
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_last_seen ON ai_ready_pages(last_seen_at)`,
554
+ sql`CREATE INDEX IF NOT EXISTS idx_ai_ready_pages_locale ON ai_ready_pages(locale)`
555
+ ];
556
+ for (const stmt of statements) {
557
+ await client.db.execute(stmt);
558
+ }
506
559
  }
507
560
  function rowToCronRun(row) {
508
- return {
509
- id: row.id,
510
- startedAt: row.startedAt,
511
- finishedAt: row.finishedAt,
512
- durationMs: row.durationMs,
513
- pagesIndexed: row.pagesIndexed || 0,
514
- pagesRemaining: row.pagesRemaining || 0,
515
- errors: JSON.parse(row.errors || "[]"),
516
- status: row.status
517
- };
518
- }
561
+ return {
562
+ id: row.id,
563
+ startedAt: row.startedAt,
564
+ finishedAt: row.finishedAt,
565
+ durationMs: row.durationMs,
566
+ pagesIndexed: row.pagesIndexed || 0,
567
+ pagesRemaining: row.pagesRemaining || 0,
568
+ errors: JSON.parse(row.errors || "[]"),
569
+ status: row.status
570
+ };
571
+ }
572
+ /**
573
+ * Start a cron run
574
+ */
519
575
  export async function startCronRun(event) {
520
- const client = await useDrizzle(event);
521
- const now = Date.now();
522
- const result = await client.db.insert(cronRuns).values({ startedAt: now, status: "running" }).returning({ id: cronRuns.id });
523
- return result[0]?.id || null;
524
- }
576
+ const client = await useDrizzle(event);
577
+ const now = Date.now();
578
+ const result = await client.db.insert(cronRuns).values({
579
+ startedAt: now,
580
+ status: "running"
581
+ }).returning({ id: cronRuns.id });
582
+ return result[0]?.id || null;
583
+ }
584
+ /**
585
+ * Complete a cron run
586
+ */
525
587
  export async function completeCronRun(event, runId, result) {
526
- const client = await useDrizzle(event);
527
- const now = Date.now();
528
- const existing = await client.db.select({ startedAt: cronRuns.startedAt }).from(cronRuns).where(eq(cronRuns.id, runId)).limit(1);
529
- const durationMs = existing[0] ? now - existing[0].startedAt : null;
530
- const status = result.errors.length > 0 ? result.pagesIndexed > 0 ? "partial" : "error" : "success";
531
- await client.db.update(cronRuns).set({
532
- finishedAt: now,
533
- durationMs,
534
- pagesIndexed: result.pagesIndexed,
535
- pagesRemaining: result.pagesRemaining,
536
- errors: JSON.stringify(result.errors),
537
- status
538
- }).where(eq(cronRuns.id, runId));
539
- }
588
+ const client = await useDrizzle(event);
589
+ const now = Date.now();
590
+ // Get start time for duration
591
+ const existing = await client.db.select({ startedAt: cronRuns.startedAt }).from(cronRuns).where(eq(cronRuns.id, runId)).limit(1);
592
+ const durationMs = existing[0] ? now - existing[0].startedAt : null;
593
+ const status = result.errors.length > 0 ? result.pagesIndexed > 0 ? "partial" : "error" : "success";
594
+ await client.db.update(cronRuns).set({
595
+ finishedAt: now,
596
+ durationMs,
597
+ pagesIndexed: result.pagesIndexed,
598
+ pagesRemaining: result.pagesRemaining,
599
+ errors: JSON.stringify(result.errors),
600
+ status
601
+ }).where(eq(cronRuns.id, runId));
602
+ }
603
+ /**
604
+ * Get recent cron runs
605
+ */
540
606
  export async function getRecentCronRuns(event, limit = 10) {
541
- const client = await useDrizzle(event);
542
- const rows = await client.db.select().from(cronRuns).orderBy(desc(cronRuns.startedAt)).limit(limit);
543
- return rows.map(rowToCronRun);
607
+ const client = await useDrizzle(event);
608
+ const rows = await client.db.select().from(cronRuns).orderBy(desc(cronRuns.startedAt)).limit(limit);
609
+ return rows.map(rowToCronRun);
544
610
  }
545
611
  function rowToSitemap(row) {
546
- const parsedState = parseSitemapCrawlState(row.crawlState ?? null);
547
- if (parsedState._tag === "error")
548
- throw new Error(`Invalid crawl state for sitemap ${row.name}: ${parsedState.error}`);
549
- return {
550
- name: row.name,
551
- route: row.route,
552
- lastCrawledAt: row.lastCrawledAt,
553
- urlCount: row.urlCount || 0,
554
- errorCount: row.errorCount || 0,
555
- lastError: row.lastError,
556
- crawlState: parsedState.state
557
- };
558
- }
612
+ const parsedState = parseSitemapCrawlState(row.crawlState ?? null);
613
+ if (parsedState._tag === "error") throw new Error(`Invalid crawl state for sitemap ${row.name}: ${parsedState.error}`);
614
+ return {
615
+ name: row.name,
616
+ route: row.route,
617
+ lastCrawledAt: row.lastCrawledAt,
618
+ urlCount: row.urlCount || 0,
619
+ errorCount: row.errorCount || 0,
620
+ lastError: row.lastError,
621
+ crawlState: parsedState.state
622
+ };
623
+ }
624
+ /**
625
+ * Sync sitemaps from config
626
+ */
559
627
  export async function syncSitemaps(event, sitemapList) {
560
- const client = await useDrizzle(event);
561
- const existing = await client.db.select({ name: sitemaps.name, route: sitemaps.route }).from(sitemaps);
562
- const existingNames = new Set(existing.map((r) => r.name));
563
- const existingRoutes = new Map(existing.map((row) => [row.name, row.route]));
564
- const configNames = new Set(sitemapList.map((s) => s.name));
565
- let added = 0;
566
- let removed = 0;
567
- for (const sitemap of sitemapList) {
568
- if (!existingNames.has(sitemap.name)) {
569
- await client.db.insert(sitemaps).values({ name: sitemap.name, route: sitemap.route });
570
- added++;
571
- } else if (existingRoutes.get(sitemap.name) !== sitemap.route) {
572
- await client.db.update(sitemaps).set({
573
- route: sitemap.route,
574
- lastCrawledAt: null,
575
- urlCount: 0,
576
- errorCount: 0,
577
- lastError: null,
578
- crawlState: null
579
- }).where(eq(sitemaps.name, sitemap.name));
580
- }
581
- }
582
- for (const name of existingNames) {
583
- if (!configNames.has(name)) {
584
- await client.db.delete(sitemaps).where(eq(sitemaps.name, name));
585
- removed++;
586
- }
587
- }
588
- return { added, removed };
589
- }
628
+ const client = await useDrizzle(event);
629
+ const existing = await client.db.select({
630
+ name: sitemaps.name,
631
+ route: sitemaps.route
632
+ }).from(sitemaps);
633
+ const existingNames = new Set(existing.map((r) => r.name));
634
+ const existingRoutes = new Map(existing.map((row) => [row.name, row.route]));
635
+ const configNames = new Set(sitemapList.map((s) => s.name));
636
+ let added = 0;
637
+ let removed = 0;
638
+ // Insert new
639
+ for (const sitemap of sitemapList) {
640
+ if (!existingNames.has(sitemap.name)) {
641
+ await client.db.insert(sitemaps).values({
642
+ name: sitemap.name,
643
+ route: sitemap.route
644
+ });
645
+ added++;
646
+ } else if (existingRoutes.get(sitemap.name) !== sitemap.route) {
647
+ await client.db.update(sitemaps).set({
648
+ route: sitemap.route,
649
+ lastCrawledAt: null,
650
+ urlCount: 0,
651
+ errorCount: 0,
652
+ lastError: null,
653
+ crawlState: null
654
+ }).where(eq(sitemaps.name, sitemap.name));
655
+ }
656
+ }
657
+ // Remove stale
658
+ for (const name of existingNames) {
659
+ if (!configNames.has(name)) {
660
+ await client.db.delete(sitemaps).where(eq(sitemaps.name, name));
661
+ removed++;
662
+ }
663
+ }
664
+ return {
665
+ added,
666
+ removed
667
+ };
668
+ }
669
+ /**
670
+ * Get next sitemap to crawl
671
+ */
590
672
  export async function getNextSitemapToCrawl(event, minIntervalMinutes = 5) {
591
- const client = await useDrizzle(event);
592
- const threshold = Date.now() - minIntervalMinutes * 60 * 1e3;
593
- const continuationRow = await client.db.select().from(sitemaps).where(and(
594
- isNotNull(sitemaps.crawlState),
595
- eq(sitemaps.errorCount, 0)
596
- )).orderBy(sitemaps.lastCrawledAt).limit(1);
597
- if (continuationRow.length)
598
- return rowToSitemap(continuationRow[0]);
599
- const errorRow = await client.db.select().from(sitemaps).where(
600
- and(
601
- gt(sitemaps.errorCount, 0),
602
- lt(sitemaps.errorCount, 10),
603
- or(
604
- isNull(sitemaps.lastCrawledAt),
605
- lt(sitemaps.lastCrawledAt, threshold)
606
- )
607
- )
608
- ).orderBy(sitemaps.lastCrawledAt).limit(1);
609
- if (errorRow.length)
610
- return rowToSitemap(errorRow[0]);
611
- const row = await client.db.select().from(sitemaps).where(
612
- and(
613
- eq(sitemaps.errorCount, 0),
614
- or(
615
- isNull(sitemaps.lastCrawledAt),
616
- lt(sitemaps.lastCrawledAt, threshold)
617
- )
618
- )
619
- ).orderBy(sitemaps.lastCrawledAt).limit(1);
620
- return row.length ? rowToSitemap(row[0]) : null;
621
- }
673
+ const client = await useDrizzle(event);
674
+ const threshold = Date.now() - minIntervalMinutes * 60 * 1e3;
675
+ // Continue bounded work before considering normal recrawl throttling.
676
+ const continuationRow = await client.db.select().from(sitemaps).where(and(isNotNull(sitemaps.crawlState), eq(sitemaps.errorCount, 0))).orderBy(sitemaps.lastCrawledAt).limit(1);
677
+ if (continuationRow.length) return rowToSitemap(continuationRow[0]);
678
+ // First try error sitemaps
679
+ const errorRow = await client.db.select().from(sitemaps).where(and(gt(sitemaps.errorCount, 0), lt(sitemaps.errorCount, 10), or(isNull(sitemaps.lastCrawledAt), lt(sitemaps.lastCrawledAt, threshold)))).orderBy(sitemaps.lastCrawledAt).limit(1);
680
+ if (errorRow.length) return rowToSitemap(errorRow[0]);
681
+ // Then oldest crawled
682
+ const row = await client.db.select().from(sitemaps).where(and(eq(sitemaps.errorCount, 0), or(isNull(sitemaps.lastCrawledAt), lt(sitemaps.lastCrawledAt, threshold)))).orderBy(sitemaps.lastCrawledAt).limit(1);
683
+ return row.length ? rowToSitemap(row[0]) : null;
684
+ }
685
+ /**
686
+ * Mark sitemap as crawled
687
+ */
622
688
  export async function markSitemapCrawled(event, name, urlCount) {
623
- const client = await useDrizzle(event);
624
- await client.db.update(sitemaps).set({
625
- lastCrawledAt: Date.now(),
626
- urlCount,
627
- errorCount: 0,
628
- lastError: null,
629
- crawlState: null
630
- }).where(eq(sitemaps.name, name));
631
- }
689
+ const client = await useDrizzle(event);
690
+ await client.db.update(sitemaps).set({
691
+ lastCrawledAt: Date.now(),
692
+ urlCount,
693
+ errorCount: 0,
694
+ lastError: null,
695
+ crawlState: null
696
+ }).where(eq(sitemaps.name, name));
697
+ }
698
+ /** Record a deferred sitemap hook seed only when no crawl is in progress. */
632
699
  export async function markSitemapSeeded(event, name, urlCount, expectedLastCrawledAt) {
633
- const client = await useDrizzle(event);
634
- await client.db.update(sitemaps).set({
635
- lastCrawledAt: Date.now(),
636
- urlCount,
637
- errorCount: 0,
638
- lastError: null
639
- }).where(and(
640
- eq(sitemaps.name, name),
641
- isNull(sitemaps.crawlState),
642
- eq(sitemaps.errorCount, 0),
643
- expectedLastCrawledAt === null ? isNull(sitemaps.lastCrawledAt) : eq(sitemaps.lastCrawledAt, expectedLastCrawledAt)
644
- ));
645
- }
700
+ const client = await useDrizzle(event);
701
+ await client.db.update(sitemaps).set({
702
+ lastCrawledAt: Date.now(),
703
+ urlCount,
704
+ errorCount: 0,
705
+ lastError: null
706
+ }).where(and(eq(sitemaps.name, name), isNull(sitemaps.crawlState), eq(sitemaps.errorCount, 0), expectedLastCrawledAt === null ? isNull(sitemaps.lastCrawledAt) : eq(sitemaps.lastCrawledAt, expectedLastCrawledAt)));
707
+ }
708
+ /** Persist a resumable sitemap crawl without incrementing its error budget. */
646
709
  export async function markSitemapCrawlPartial(event, name, state) {
647
- const client = await useDrizzle(event);
648
- await client.db.update(sitemaps).set({
649
- lastCrawledAt: Date.now(),
650
- urlCount: state.urlsObserved,
651
- errorCount: 0,
652
- lastError: null,
653
- crawlState: serializeSitemapCrawlState(state)
654
- }).where(eq(sitemaps.name, name));
655
- }
710
+ const client = await useDrizzle(event);
711
+ await client.db.update(sitemaps).set({
712
+ lastCrawledAt: Date.now(),
713
+ urlCount: state.urlsObserved,
714
+ errorCount: 0,
715
+ lastError: null,
716
+ crawlState: serializeSitemapCrawlState(state)
717
+ }).where(eq(sitemaps.name, name));
718
+ }
719
+ /**
720
+ * Mark sitemap error
721
+ */
656
722
  export async function markSitemapError(event, name, error) {
657
- const client = await useDrizzle(event);
658
- await client.db.update(sitemaps).set({
659
- lastCrawledAt: Date.now(),
660
- errorCount: sql`${sitemaps.errorCount} + 1`,
661
- lastError: error,
662
- crawlState: null
663
- }).where(eq(sitemaps.name, name));
664
- }
723
+ const client = await useDrizzle(event);
724
+ await client.db.update(sitemaps).set({
725
+ lastCrawledAt: Date.now(),
726
+ errorCount: sql`${sitemaps.errorCount} + 1`,
727
+ lastError: error,
728
+ crawlState: null
729
+ }).where(eq(sitemaps.name, name));
730
+ }
731
+ /**
732
+ * Get all sitemaps status
733
+ */
665
734
  export async function getSitemapStatus(event) {
666
- const client = await useDrizzle(event);
667
- const rows = await client.db.select().from(sitemaps).orderBy(sitemaps.name);
668
- return rows.map((row) => {
669
- const { crawlState, ...entry } = rowToSitemap(row);
670
- return { ...entry, continuing: crawlState !== null };
671
- });
672
- }
735
+ const client = await useDrizzle(event);
736
+ const rows = await client.db.select().from(sitemaps).orderBy(sitemaps.name);
737
+ return rows.map((row) => {
738
+ const { crawlState, ...entry } = rowToSitemap(row);
739
+ return {
740
+ ...entry,
741
+ continuing: crawlState !== null
742
+ };
743
+ });
744
+ }
745
+ /**
746
+ * Reset all sitemap errors (called on build_id change)
747
+ */
673
748
  export async function resetSitemapErrors(event) {
674
- const client = await useDrizzle(event);
675
- const countResult = await client.db.select({ count: count() }).from(sitemaps).where(or(
676
- gt(sitemaps.errorCount, 0),
677
- sql`${sitemaps.crawlState} IS NOT NULL`
678
- ));
679
- const errorCount = countResult[0]?.count || 0;
680
- if (errorCount > 0) {
681
- await client.db.update(sitemaps).set({
682
- errorCount: 0,
683
- lastError: null,
684
- lastCrawledAt: null,
685
- crawlState: null
686
- });
687
- }
688
- return errorCount;
689
- }
749
+ const client = await useDrizzle(event);
750
+ // Count sitemaps with errors or abandoned continuation state.
751
+ const countResult = await client.db.select({ count: count() }).from(sitemaps).where(or(gt(sitemaps.errorCount, 0), sql`${sitemaps.crawlState} IS NOT NULL`));
752
+ const errorCount = countResult[0]?.count || 0;
753
+ if (errorCount > 0) {
754
+ await client.db.update(sitemaps).set({
755
+ errorCount: 0,
756
+ lastError: null,
757
+ lastCrawledAt: null,
758
+ crawlState: null
759
+ });
760
+ }
761
+ return errorCount;
762
+ }
763
+ // ============================================================================
764
+ // Seed Routes (for sitemap seeding)
765
+ // ============================================================================
766
+ /**
767
+ * Seed routes from sitemap
768
+ *
769
+ * Mirrors `seedRoutes` in `../queries` (the raw layer), including the guarded
770
+ * DO UPDATE: an unchanged row is not rewritten on every crawl. Without the
771
+ * guard each run bumped `last_seen_at` on every row, which cost millions of
772
+ * D1 row writes a month. Keep the two layers in sync.
773
+ */
690
774
  export async function seedRoutes(event, routes, options = {}) {
691
- if (routes.length === 0)
692
- return 0;
693
- const refreshWindowMs = Math.max(0, Math.trunc(Number.isFinite(options.refreshWindowMs) ? options.refreshWindowMs : SEED_REFRESH_WINDOW_MS));
694
- const nowMs = Date.now();
695
- const byRoute = /* @__PURE__ */ new Map();
696
- for (const entry of routes) {
697
- const route = normalizeRoute(typeof entry === "string" ? entry : entry.route);
698
- const explicitLocale = typeof entry === "string" ? void 0 : entry.locale;
699
- const entryUrl = typeof entry === "string" ? void 0 : entry.url;
700
- byRoute.set(route, {
701
- route,
702
- routeKey: normalizeRouteKey(route),
703
- locale: deriveLocale(event, route, explicitLocale, entryUrl),
704
- sourceLastmod: parseSourceLastmod(typeof entry === "string" ? void 0 : entry.lastmod)
705
- });
706
- }
707
- const rowsPerInsert = maxRowsPerInsert(5);
708
- const db = await useRawDb(event);
709
- const entries = [...byRoute.values()];
710
- const stmts = [];
711
- for (let i = 0; i < entries.length; i += rowsPerInsert) {
712
- const batch = entries.slice(i, i + rowsPerInsert);
713
- const valuesSql = batch.map(() => `(?, ?, '', '', '', '[]', '[]', '', ?, 0, 0, 0, 'runtime', ?, ?)`).join(", ");
714
- const params = batch.flatMap((r) => [r.route, r.routeKey, r.sourceLastmod, nowMs, r.locale]);
715
- stmts.push({
716
- sql: `
775
+ if (routes.length === 0) return 0;
776
+ // Inlined as a literal: a bind param would push a full chunk past D1's
777
+ // 100-parameter cap. Truncating a finite number keeps it injection-safe.
778
+ const refreshWindowMs = Math.max(0, Math.trunc(Number.isFinite(options.refreshWindowMs) ? options.refreshWindowMs : SEED_REFRESH_WINDOW_MS));
779
+ const nowMs = Date.now();
780
+ // Resolve + dedupe rows up front (pure, no IO). Deduping by route avoids
781
+ // SQLite's "ON CONFLICT cannot affect row a second time" error when a
782
+ // multi-row INSERT contains the same route twice.
783
+ const byRoute = new Map();
784
+ for (const entry of routes) {
785
+ // Canonicalise before keying the map: '' and '/' are one page, so leaving
786
+ // them distinct here defeats the dedupe and collides on route_key instead.
787
+ const route = normalizeRoute(typeof entry === "string" ? entry : entry.route);
788
+ const explicitLocale = typeof entry === "string" ? undefined : entry.locale;
789
+ const entryUrl = typeof entry === "string" ? undefined : entry.url;
790
+ byRoute.set(route, {
791
+ route,
792
+ routeKey: normalizeRouteKey(route),
793
+ locale: deriveLocale(event, route, explicitLocale, entryUrl),
794
+ sourceLastmod: parseSourceLastmod(typeof entry === "string" ? undefined : entry.lastmod)
795
+ });
796
+ }
797
+ // Batch into multi-row INSERTs. Each statement is a DB round-trip (a network
798
+ // call on D1), so one INSERT per route times out large sitemaps. The chunk
799
+ // size is derived from the 5 bind params per row so each statement stays
800
+ // within D1's 100-parameter cap even if a column is added. All statements
801
+ // then go through `db.batch` so round-trips collapse into one.
802
+ const rowsPerInsert = maxRowsPerInsert(5);
803
+ const db = await useRawDb(event);
804
+ const entries = [...byRoute.values()];
805
+ const stmts = [];
806
+ for (let i = 0; i < entries.length; i += rowsPerInsert) {
807
+ const batch = entries.slice(i, i + rowsPerInsert);
808
+ const valuesSql = batch.map(() => `(?, ?, '', '', '', '[]', '[]', '', ?, 0, 0, 0, 'runtime', ?, ?)`).join(", ");
809
+ const params = batch.flatMap((r) => [
810
+ r.route,
811
+ r.routeKey,
812
+ r.sourceLastmod,
813
+ nowMs,
814
+ r.locale
815
+ ]);
816
+ stmts.push({
817
+ sql: `
717
818
  INSERT INTO ai_ready_pages (route, route_key, title, description, markdown, headings, keywords, updated_at, source_lastmod, indexed_at, is_error, indexed, source, last_seen_at, locale)
718
819
  VALUES ${valuesSql}
719
820
  ON CONFLICT(route) DO UPDATE SET
@@ -729,9 +830,9 @@ export async function seedRoutes(event, routes, options = {}) {
729
830
  OR ai_ready_pages.locale IS DISTINCT FROM excluded.locale
730
831
  OR (excluded.source_lastmod IS NOT NULL AND ai_ready_pages.source_lastmod IS DISTINCT FROM excluded.source_lastmod)
731
832
  `,
732
- params
733
- });
734
- }
735
- await db.batch(stmts);
736
- return byRoute.size;
833
+ params
834
+ });
835
+ }
836
+ await db.batch(stmts);
837
+ return byRoute.size;
737
838
  }