qarpeo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/chunks/tools.mjs +993 -31
  2. package/dist/cli/index.mjs +1102 -31
  3. package/dist/fate/index.d.ts +9 -1
  4. package/dist/fate/index.mjs +20 -3
  5. package/dist/module.mjs +296 -753
  6. package/dist/runtime/browser.mjs +2 -2
  7. package/dist/runtime/comments-server.d.ts +3 -0
  8. package/dist/runtime/comments-server.mjs +2 -0
  9. package/dist/runtime/comments.d.ts +0 -2
  10. package/dist/runtime/comments.mjs +0 -2
  11. package/dist/runtime/db.d.ts +10 -9
  12. package/dist/runtime/db.mjs +79 -8
  13. package/dist/runtime/drizzle.mjs +21 -6
  14. package/dist/runtime/index.d.ts +4 -0
  15. package/dist/runtime/realtime-server.d.ts +4 -0
  16. package/dist/runtime/realtime-server.mjs +13 -0
  17. package/dist/runtime/realtime.d.ts +1 -4
  18. package/dist/runtime/realtime.mjs +0 -13
  19. package/dist/runtime/replica.d.ts +27 -0
  20. package/dist/runtime/replica.mjs +229 -0
  21. package/dist/runtime/server/durable-objects/agent.mjs +14 -2
  22. package/dist/runtime/server/durable-objects/room.d.ts +10 -0
  23. package/dist/runtime/server/durable-objects/room.mjs +119 -28
  24. package/dist/runtime/server/middleware/devtools.mjs +1 -1
  25. package/dist/runtime/server/middleware/tenancy.mjs +7 -4
  26. package/dist/runtime/server/plugins/store.mjs +1 -1
  27. package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
  28. package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
  29. package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
  30. package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
  31. package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
  32. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
  33. package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
  34. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
  35. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
  36. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
  37. package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
  38. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
  39. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
  40. package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
  41. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
  42. package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
  43. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
  44. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
  45. package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
  46. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
  47. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
  48. package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
  49. package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
  50. package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
  51. package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
  52. package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
  53. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
  54. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
  55. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
  56. package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
  57. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
  58. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
  59. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
  60. package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
  61. package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
  62. package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
  63. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
  64. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
  65. package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
  66. package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
  67. package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
  68. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
  69. package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
  70. package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
  71. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
  72. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
  73. package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
  74. package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
  75. package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
  76. package/dist/runtime/server/routes/fate.d.ts +6 -0
  77. package/dist/runtime/server/routes/fate.mjs +32 -3
  78. package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
  79. package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
  80. package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
  81. package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
  82. package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
  83. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
  84. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
  85. package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
  86. package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
  87. package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
  88. package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
  89. package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
  90. package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
  91. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  92. package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
  93. package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
  94. package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
  95. package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
  96. package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
  97. package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
  98. package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
  99. package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
  100. package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
  101. package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
  102. package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
  103. package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
  104. package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
  105. package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
  106. package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
  107. package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
  108. package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
  109. package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
  110. package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
  111. package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
  112. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
  113. package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
  114. package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
  115. package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
  116. package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
  117. package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
  118. package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
  119. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
  120. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
  121. package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
  122. package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
  123. package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
  124. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
  125. package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
  126. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
  127. package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
  128. package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
  129. package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
  130. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
  131. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
  132. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
  133. package/dist/runtime/server/utils/ai.d.ts +6 -0
  134. package/dist/runtime/server/utils/ai.mjs +12 -2
  135. package/dist/runtime/server/utils/analytics-query.mjs +8 -4
  136. package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
  137. package/dist/runtime/server/utils/browser-utils.mjs +135 -0
  138. package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
  139. package/dist/runtime/server/utils/cms/cache.mjs +95 -0
  140. package/dist/runtime/server/utils/cms/common.mjs +1 -1
  141. package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
  142. package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
  143. package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
  144. package/dist/runtime/server/utils/cms/path.d.ts +8 -0
  145. package/dist/runtime/server/utils/cms/path.mjs +23 -0
  146. package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
  147. package/dist/runtime/server/utils/cms/queries.mjs +366 -0
  148. package/dist/runtime/server/utils/cms/references.d.ts +48 -0
  149. package/dist/runtime/server/utils/cms/references.mjs +309 -0
  150. package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
  151. package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
  152. package/dist/runtime/server/utils/cms/sync.mjs +3 -3
  153. package/dist/runtime/server/utils/cms.d.ts +5 -82
  154. package/dist/runtime/server/utils/cms.mjs +28 -1367
  155. package/dist/runtime/server/utils/comments.d.ts +11 -0
  156. package/dist/runtime/server/utils/comments.mjs +65 -17
  157. package/dist/runtime/server/utils/crypto.mjs +1 -1
  158. package/dist/runtime/server/utils/domains.mjs +9 -0
  159. package/dist/runtime/server/utils/drizzle.d.ts +26 -1
  160. package/dist/runtime/server/utils/drizzle.mjs +78 -19
  161. package/dist/runtime/server/utils/email-inbound.mjs +9 -1
  162. package/dist/runtime/server/utils/impersonation.mjs +58 -1
  163. package/dist/runtime/server/utils/lock.d.ts +11 -0
  164. package/dist/runtime/server/utils/lock.mjs +4 -0
  165. package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
  166. package/dist/runtime/server/utils/mail.d.ts +2 -1
  167. package/dist/runtime/server/utils/mail.mjs +17 -11
  168. package/dist/runtime/server/utils/notifications.d.ts +13 -4
  169. package/dist/runtime/server/utils/notifications.mjs +20 -4
  170. package/dist/runtime/server/utils/organization.mjs +36 -1
  171. package/dist/runtime/server/utils/passwordless.mjs +8 -0
  172. package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
  173. package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
  174. package/dist/runtime/server/utils/payments/common.d.ts +45 -0
  175. package/dist/runtime/server/utils/payments/common.mjs +234 -0
  176. package/dist/runtime/server/utils/payments/index.d.ts +9 -0
  177. package/dist/runtime/server/utils/payments/index.mjs +21 -0
  178. package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
  179. package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
  180. package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
  181. package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
  182. package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
  183. package/dist/runtime/server/utils/payments/polar.mjs +66 -0
  184. package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
  185. package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
  186. package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
  187. package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
  188. package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
  189. package/dist/runtime/server/utils/payments/usage.mjs +143 -0
  190. package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
  191. package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
  192. package/dist/runtime/server/utils/payments.d.ts +1 -158
  193. package/dist/runtime/server/utils/payments.mjs +1 -1289
  194. package/dist/runtime/server/utils/queue.d.ts +2 -0
  195. package/dist/runtime/server/utils/queue.mjs +34 -21
  196. package/dist/runtime/server/utils/rag.mjs +30 -17
  197. package/dist/runtime/server/utils/realtime.d.ts +5 -1
  198. package/dist/runtime/server/utils/realtime.mjs +43 -7
  199. package/dist/runtime/server/utils/session.mjs +16 -3
  200. package/dist/runtime/server/utils/sso.d.ts +3 -0
  201. package/dist/runtime/server/utils/sso.mjs +43 -0
  202. package/dist/runtime/server/utils/storage.mjs +12 -1
  203. package/dist/runtime/server/utils/store/cart.d.ts +63 -0
  204. package/dist/runtime/server/utils/store/cart.mjs +542 -0
  205. package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
  206. package/dist/runtime/server/utils/store/checkout.mjs +118 -0
  207. package/dist/runtime/server/utils/store/common.d.ts +29 -0
  208. package/dist/runtime/server/utils/store/common.mjs +479 -0
  209. package/dist/runtime/server/utils/store/index.d.ts +7 -0
  210. package/dist/runtime/server/utils/store/index.mjs +30 -0
  211. package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
  212. package/dist/runtime/server/utils/store/inventory.mjs +190 -0
  213. package/dist/runtime/server/utils/store/orders.d.ts +60 -0
  214. package/dist/runtime/server/utils/store/orders.mjs +590 -0
  215. package/dist/runtime/server/utils/store/products.d.ts +35 -0
  216. package/dist/runtime/server/utils/store/products.mjs +461 -0
  217. package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
  218. package/dist/runtime/server/utils/store/vendor.mjs +68 -0
  219. package/dist/runtime/server/utils/store.d.ts +1 -207
  220. package/dist/runtime/server/utils/store.mjs +1 -2227
  221. package/dist/runtime/server/utils/string.d.ts +1 -1
  222. package/dist/runtime/server/utils/string.mjs +12 -4
  223. package/dist/runtime/server/utils/tenant.mjs +19 -5
  224. package/dist/runtime/server/utils/tracker.mjs +2 -0
  225. package/dist/runtime/server.d.ts +3 -3
  226. package/dist/runtime/server.mjs +4 -4
  227. package/dist/runtime/storage-server.d.ts +2 -0
  228. package/dist/runtime/storage-server.mjs +1 -0
  229. package/dist/runtime/storage.d.ts +1 -1
  230. package/dist/runtime/storage.mjs +0 -1
  231. package/dist/runtime/store.d.ts +0 -1
  232. package/dist/runtime/store.mjs +0 -1
  233. package/dist/runtime/test-utils.d.ts +4 -0
  234. package/dist/runtime/test-utils.mjs +54 -0
  235. package/dist/runtime/types/d1.d.ts +43 -0
  236. package/dist/runtime/types/drizzle.d.ts +6 -0
  237. package/dist/runtime/types/store.d.ts +1 -1
  238. package/dist/types/analytics.d.ts +80 -0
  239. package/dist/types/auth.d.ts +282 -0
  240. package/dist/types/cache.d.ts +55 -0
  241. package/dist/types/comments.d.ts +130 -0
  242. package/dist/types/db.d.ts +29 -0
  243. package/dist/types/email.d.ts +182 -0
  244. package/dist/types/index.d.ts +22 -0
  245. package/dist/types/jobs.d.ts +58 -0
  246. package/dist/types/notifications.d.ts +77 -0
  247. package/dist/types/options.d.ts +363 -0
  248. package/dist/types/payments.d.ts +145 -0
  249. package/dist/types/ratelimit.d.ts +71 -0
  250. package/dist/types/realtime.d.ts +136 -0
  251. package/dist/types/site.d.ts +121 -0
  252. package/dist/types/storage.d.ts +164 -0
  253. package/dist/types/store-options.d.ts +199 -0
  254. package/dist/types/tenant.d.ts +100 -0
  255. package/dist/types.d.ts +1 -2174
  256. package/dist/utils/migration-lock.d.ts +139 -0
  257. package/dist/utils/pkg.d.ts +14 -1
  258. package/dist/utils/schema-diff.d.ts +39 -0
  259. package/package.json +55 -17
  260. package/dist/chunks/auth-schema.mjs +0 -364
@@ -1,17 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { defineCommand, runMain } from 'citty';
3
- import { r as resolveDatabaseTarget, a as resolveBinaryPath, e as ensurePackage, g as getLocalDatabaseContext, d as discoverDatabases, b as getJiti, s as spawnBinSync, c as resolveProjectName, f as checkDrizzleVersion, h as findSchemaFiles, i as findLocalD1Database, j as findAgentFiles, k as findToolFiles, l as findBotFiles, m as findMcpFiles, n as findJobFiles, o as findWorkflowFiles, p as findEmailHandlerFiles, v as version } from '../chunks/tools.mjs';
3
+ import { r as resolveDatabaseTarget, a as resolveBinaryPath, e as ensurePackage, g as getLocalDatabaseContext, b as getActiveAuthTableNames, A as ALL_CMS_TABLE_NAMES, c as ALL_STORE_TABLE_NAMES, d as ALL_COMMENTS_TABLE_NAMES, s as scanSchemaExports, f as discoverDatabases, h as findLocalD1Database, i as spawnBinSync, j as getJiti, k as resolveProjectName, l as checkDrizzleVersion, m as findSchemaFiles, n as findAgentFiles, o as findToolFiles, p as findBotFiles, q as findMcpFiles, t as findJobFiles, u as findWorkflowFiles, v as findEmailHandlerFiles, w as version } from '../chunks/tools.mjs';
4
4
  import { spawnSync, spawn } from 'node:child_process';
5
- import { existsSync, mkdirSync, writeFileSync, readFileSync, statSync, readdirSync } from 'node:fs';
5
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync, readdirSync, statSync } from 'node:fs';
6
6
  import { loadNuxtConfig } from '@nuxt/kit';
7
- import { resolve, join, relative, basename, extname } from 'pathe';
7
+ import { resolve, join, dirname, relative, basename, extname } from 'pathe';
8
8
  import { reset, seed } from 'drizzle-seed';
9
9
  import { stdin, stdout } from 'node:process';
10
10
  import readline from 'node:readline/promises';
11
- import { homedir } from 'node:os';
11
+ import { hostname, homedir } from 'node:os';
12
12
  import 'node:module';
13
13
  import 'drizzle-orm/node-sqlite';
14
14
  import 'node:url';
15
+ import 'drizzle-orm/sqlite-core';
16
+ import 'nuxt/server';
15
17
  import 'node:fs/promises';
16
18
  import 'defu';
17
19
 
@@ -391,6 +393,244 @@ const deleteDb = defineCommand({
391
393
  }
392
394
  });
393
395
 
396
+ const DEFAULT_PAYMENTS_TABLES = [
397
+ "payment_customers",
398
+ "payment_subscriptions",
399
+ "payment_invoices",
400
+ "payment_methods"
401
+ ];
402
+ const DEFAULT_NOTIFICATIONS_TABLES = [
403
+ "notifications",
404
+ "push_subscriptions",
405
+ "notification_preferences"
406
+ ];
407
+ const DEFAULT_TENANTS_TABLES = [
408
+ "tenants",
409
+ "tenant_domains",
410
+ "tenant_members"
411
+ ];
412
+ function extractSchemaTableNames(schemaFiles) {
413
+ const tableNames = /* @__PURE__ */ new Set();
414
+ const explicitVars = /* @__PURE__ */ new Set();
415
+ for (const file of schemaFiles) {
416
+ let src;
417
+ try {
418
+ src = readFileSync(file, "utf-8");
419
+ } catch {
420
+ continue;
421
+ }
422
+ const exportedExplicitMatches = src.matchAll(
423
+ /export\s+const\s+([a-zA-Z0-9_]+)\s*=\s*(?:[a-zA-Z0-9_$.]+\.)?(?:snakeCase\.table|sqliteTable|pgTable|mysqlTable|msTable|sqlTable|table)\s*\(\s*["'`]([^"'`]+)["'`]/g
424
+ );
425
+ for (const m of exportedExplicitMatches) {
426
+ if (m[1]) explicitVars.add(m[1]);
427
+ if (m[2]) tableNames.add(m[2].trim());
428
+ }
429
+ const explicitMatches = src.matchAll(
430
+ /(?:sqliteTable|pgTable|mysqlTable|msTable|sqlTable|table)\s*\(\s*["'`]([^"'`]+)["'`]/g
431
+ );
432
+ for (const m of explicitMatches) {
433
+ if (m[1]) tableNames.add(m[1].trim());
434
+ }
435
+ const scan = scanSchemaExports([file]);
436
+ for (const t of scan.tables) {
437
+ if (!explicitVars.has(t.name)) {
438
+ tableNames.add(t.name);
439
+ }
440
+ }
441
+ explicitVars.clear();
442
+ }
443
+ return Array.from(tableNames).sort();
444
+ }
445
+ function getExpectedTableNames(db, qarpeoConfig = {}) {
446
+ const tables = /* @__PURE__ */ new Set();
447
+ const userTables = extractSchemaTableNames(db.schemaFiles || []);
448
+ for (const t of userTables) tables.add(t);
449
+ if (db.isPrimary) {
450
+ const prefix = (qarpeoConfig.tablePrefix ?? qarpeoConfig.prefix) || "";
451
+ if (qarpeoConfig.auth) {
452
+ const authTables = getActiveAuthTableNames(qarpeoConfig.auth);
453
+ for (const t of authTables) tables.add(prefix ? `${prefix}${t}` : t);
454
+ }
455
+ if (qarpeoConfig.cms) {
456
+ for (const t of ALL_CMS_TABLE_NAMES) tables.add(prefix ? `${prefix}${t}` : t);
457
+ }
458
+ if (qarpeoConfig.store) {
459
+ for (const t of ALL_STORE_TABLE_NAMES) tables.add(prefix ? `${prefix}${t}` : t);
460
+ }
461
+ if (qarpeoConfig.comments) {
462
+ for (const t of ALL_COMMENTS_TABLE_NAMES) tables.add(prefix ? `${prefix}${t}` : t);
463
+ }
464
+ if (qarpeoConfig.payments) {
465
+ for (const t of DEFAULT_PAYMENTS_TABLES) tables.add(prefix ? `${prefix}${t}` : t);
466
+ }
467
+ if (qarpeoConfig.notifications || qarpeoConfig.notify) {
468
+ for (const t of DEFAULT_NOTIFICATIONS_TABLES) tables.add(prefix ? `${prefix}${t}` : t);
469
+ }
470
+ if (qarpeoConfig.multitenant) {
471
+ for (const t of DEFAULT_TENANTS_TABLES) tables.add(prefix ? `${prefix}${t}` : t);
472
+ }
473
+ }
474
+ return Array.from(tables).sort();
475
+ }
476
+ async function getActualTableNames(sqlitePath) {
477
+ if (!sqlitePath || !existsSync(sqlitePath)) {
478
+ return [];
479
+ }
480
+ try {
481
+ const { DatabaseSync } = await import('node:sqlite');
482
+ const sqlite = new DatabaseSync(sqlitePath, { open: true, readOnly: true });
483
+ const rows = sqlite.prepare(
484
+ `SELECT name FROM sqlite_master
485
+ WHERE type='table'
486
+ AND name NOT LIKE 'sqlite_%'
487
+ AND name NOT LIKE '_cf_%'
488
+ AND name NOT LIKE '__drizzle_%'
489
+ AND name NOT LIKE 'd1_migrations'
490
+ ORDER BY name ASC`
491
+ ).all();
492
+ sqlite.close();
493
+ return rows.map((r) => r.name);
494
+ } catch {
495
+ return [];
496
+ }
497
+ }
498
+ async function computeSchemaDiff(options) {
499
+ const { database, sqlitePath, qarpeoConfig = {} } = options;
500
+ const expectedTables = getExpectedTableNames(database, qarpeoConfig);
501
+ let actualTables = options.actualTables || [];
502
+ if (!actualTables.length && sqlitePath) {
503
+ actualTables = await getActualTableNames(sqlitePath);
504
+ }
505
+ const actualSet = new Set(actualTables);
506
+ const expectedSet = new Set(expectedTables);
507
+ const missingTables = expectedTables.filter((t) => !actualSet.has(t));
508
+ const extraTables = actualTables.filter((t) => !expectedSet.has(t));
509
+ const matchingTables = expectedTables.filter((t) => actualSet.has(t));
510
+ const hasDrift = missingTables.length > 0;
511
+ const hasLocalDb = Boolean(sqlitePath && existsSync(sqlitePath)) || actualTables.length > 0;
512
+ let summary = "";
513
+ if (!hasLocalDb) {
514
+ summary = "No physical database to compare against";
515
+ } else if (!hasDrift && extraTables.length === 0) {
516
+ summary = `Table names in sync (${matchingTables.length} table(s) present; column-level diff not checked)`;
517
+ } else if (missingTables.length > 0 && extraTables.length > 0) {
518
+ summary = `${missingTables.length} table(s) missing, ${extraTables.length} unmanaged table(s)`;
519
+ } else if (missingTables.length > 0) {
520
+ summary = `${missingTables.length} table(s) missing from database`;
521
+ } else {
522
+ summary = `${matchingTables.length} verified, ${extraTables.length} unmanaged table(s)`;
523
+ }
524
+ return {
525
+ databaseName: database.name,
526
+ binding: database.binding,
527
+ dialect: database.dialect,
528
+ hasLocalDb,
529
+ sqlitePath: sqlitePath || void 0,
530
+ expectedTables,
531
+ actualTables,
532
+ missingTables,
533
+ extraTables,
534
+ matchingTables,
535
+ hasDrift,
536
+ summary
537
+ };
538
+ }
539
+
540
+ const diff = defineCommand({
541
+ meta: {
542
+ name: "diff",
543
+ description: "Detect schema drift between Drizzle definitions and the physical database"
544
+ },
545
+ args: {
546
+ db: {
547
+ type: "string",
548
+ description: "Target database name (e.g. --db analytics) or omit for primary DB"
549
+ },
550
+ all: {
551
+ type: "boolean",
552
+ description: "Compare schema diff across all discovered databases",
553
+ default: false
554
+ },
555
+ failOnDrift: {
556
+ type: "boolean",
557
+ description: "Exit with code 1 if schema drift (missing tables) is detected",
558
+ default: false
559
+ },
560
+ cwd: {
561
+ type: "string",
562
+ description: "Working directory",
563
+ default: "."
564
+ }
565
+ },
566
+ async run({ args }) {
567
+ const cwd = resolve(process.cwd(), args.cwd);
568
+ const nuxtConfig = await loadNuxtConfig({ cwd });
569
+ const qarpeoOpts = nuxtConfig.qarpeo || {};
570
+ const layers = nuxtConfig._layers || [{ cwd, config: nuxtConfig }];
571
+ const allDbs = discoverDatabases(layers, qarpeoOpts);
572
+ let targets = allDbs;
573
+ if (!args.all && args.db) {
574
+ try {
575
+ const target = resolveDatabaseTarget(layers, args.db, qarpeoOpts);
576
+ targets = [target];
577
+ } catch (err) {
578
+ console.error(`\u274C [qarpeo] ${err.message}`);
579
+ process.exit(1);
580
+ }
581
+ } else if (!args.all) {
582
+ const primary = allDbs.find((d) => d.isPrimary) || allDbs[0];
583
+ if (primary) {
584
+ targets = [primary];
585
+ }
586
+ }
587
+ const sqlitePath = findLocalD1Database(cwd);
588
+ console.log(`
589
+ \u{1F50D} [qarpeo] Running Schema Diff & Drift Detection`);
590
+ console.log(` Working directory: ${cwd}`);
591
+ console.log(` Local DB file: ${sqlitePath ? sqlitePath : "(none found)"}
592
+ `);
593
+ let totalMissing = 0;
594
+ let totalExtra = 0;
595
+ let totalMatching = 0;
596
+ for (const target of targets) {
597
+ const diffResult = await computeSchemaDiff({
598
+ database: target,
599
+ sqlitePath,
600
+ qarpeoConfig: qarpeoOpts
601
+ });
602
+ console.log(`\u{1F4E6} Database: ${target.name} [binding: ${target.binding}, dialect: ${target.dialect}]`);
603
+ if (!diffResult.hasLocalDb) {
604
+ console.log(` \u2139\uFE0F No physical local database found to compare against.`);
605
+ console.log(` \u2139\uFE0F Expected tables defined in schema (${diffResult.expectedTables.length}): ${diffResult.expectedTables.join(", ") || "(none)"}
606
+ `);
607
+ continue;
608
+ }
609
+ totalMissing += diffResult.missingTables.length;
610
+ totalExtra += diffResult.extraTables.length;
611
+ totalMatching += diffResult.matchingTables.length;
612
+ if (diffResult.matchingTables.length > 0) {
613
+ console.log(` \u2705 In Sync (${diffResult.matchingTables.length}): ${diffResult.matchingTables.join(", ")}`);
614
+ }
615
+ if (diffResult.missingTables.length > 0) {
616
+ console.log(` \u274C Missing in DB (${diffResult.missingTables.length}): ${diffResult.missingTables.join(", ")}`);
617
+ console.log(` \u21B3 Action: Run \`qp db migrate\` or \`qp db push\` to create missing tables.`);
618
+ }
619
+ if (diffResult.extraTables.length > 0) {
620
+ console.log(` \u26A0\uFE0F Unmanaged in schema (${diffResult.extraTables.length}): ${diffResult.extraTables.join(", ")}`);
621
+ }
622
+ if (!diffResult.hasDrift && diffResult.extraTables.length === 0) {
623
+ console.log(` \u2728 Fully synchronized! No schema drift detected.`);
624
+ }
625
+ console.log();
626
+ }
627
+ if (totalMissing > 0 && args.failOnDrift) {
628
+ console.error(`\u274C [qarpeo] Schema drift detected: ${totalMissing} table(s) missing from database.`);
629
+ process.exit(1);
630
+ }
631
+ }
632
+ });
633
+
394
634
  function getWranglerBin$6(cwd) {
395
635
  return resolveBinaryPath("wrangler", cwd) || resolveBinaryPath("wrangler") || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
396
636
  }
@@ -466,6 +706,523 @@ const list$2 = defineCommand({
466
706
  }
467
707
  });
468
708
 
709
+ const inMemoryLocks = /* @__PURE__ */ new Map();
710
+ const activeHeartbeats = /* @__PURE__ */ new Map();
711
+ function getActiveRemoteExecutor() {
712
+ return defaultRemoteD1Executor;
713
+ }
714
+ function parseLockDuration(duration) {
715
+ if (typeof duration === "number") return Math.max(1e3, duration);
716
+ if (!duration || typeof duration !== "string") return 6e5;
717
+ const str = duration.trim().toLowerCase();
718
+ const match = str.match(/^([\d.]+)\s*([a-z]+)$/);
719
+ if (!match) {
720
+ const num = Number(str);
721
+ return isNaN(num) ? 6e5 : Math.max(1e3, num);
722
+ }
723
+ const val = parseFloat(match[1]);
724
+ const unit = match[2];
725
+ switch (unit) {
726
+ case "ms":
727
+ case "millisecond":
728
+ case "milliseconds":
729
+ return Math.round(val);
730
+ case "s":
731
+ case "sec":
732
+ case "secs":
733
+ case "second":
734
+ case "seconds":
735
+ return Math.round(val * 1e3);
736
+ case "m":
737
+ case "min":
738
+ case "mins":
739
+ case "minute":
740
+ case "minutes":
741
+ return Math.round(val * 60 * 1e3);
742
+ case "h":
743
+ case "hr":
744
+ case "hrs":
745
+ case "hour":
746
+ case "hours":
747
+ return Math.round(val * 3600 * 1e3);
748
+ case "d":
749
+ case "day":
750
+ case "days":
751
+ return Math.round(val * 86400 * 1e3);
752
+ default:
753
+ return Math.max(1e3, Math.round(val));
754
+ }
755
+ }
756
+ function escapeSql(str) {
757
+ return str.replace(/'/g, "''");
758
+ }
759
+ function parseWranglerJson(stdout) {
760
+ if (!stdout) return null;
761
+ const trimmed = stdout.trim();
762
+ try {
763
+ return JSON.parse(trimmed);
764
+ } catch {
765
+ const startIdx = trimmed.search(/[\[\{]/);
766
+ const endIdx = Math.max(trimmed.lastIndexOf("]"), trimmed.lastIndexOf("}"));
767
+ if (startIdx !== -1 && endIdx > startIdx) {
768
+ try {
769
+ return JSON.parse(trimmed.slice(startIdx, endIdx + 1));
770
+ } catch {
771
+ }
772
+ }
773
+ return null;
774
+ }
775
+ }
776
+ async function defaultRemoteD1Executor(dbName, sql, options = {}) {
777
+ const cwd = resolve(process.cwd(), options.cwd || ".");
778
+ const execPath = options.execPath || resolveBinaryPath("wrangler", cwd) || (process.platform === "win32" ? "wrangler.cmd" : "wrangler");
779
+ const args = ["d1", "execute", dbName, "--remote", "--command", sql, "--json"];
780
+ if (options.wranglerConfigPath) {
781
+ args.push("-c", options.wranglerConfigPath);
782
+ }
783
+ try {
784
+ const res = spawnBinSync(execPath, args, { cwd, encoding: "utf8" });
785
+ if (res.status !== 0) {
786
+ return {
787
+ success: false,
788
+ error: res.stderr || res.stdout || `wrangler exited with code ${res.status}`
789
+ };
790
+ }
791
+ const parsed = parseWranglerJson(res.stdout || "");
792
+ if (!parsed) {
793
+ return {
794
+ success: false,
795
+ error: `Failed to parse wrangler JSON output: ${res.stdout || res.stderr}`
796
+ };
797
+ }
798
+ const resultArray = Array.isArray(parsed) ? parsed : [parsed];
799
+ const lastResult = resultArray[resultArray.length - 1];
800
+ const isSuccess = resultArray.every((r) => r.success !== false);
801
+ return {
802
+ success: isSuccess,
803
+ results: lastResult?.results || [],
804
+ error: isSuccess ? void 0 : lastResult?.error || "D1 command failed"
805
+ };
806
+ } catch (err) {
807
+ return {
808
+ success: false,
809
+ error: err?.message || String(err)
810
+ };
811
+ }
812
+ }
813
+ function getLockFilePath(dbName, cwd) {
814
+ const sanitized = dbName.replace(/[^a-zA-Z0-9_-]/g, "_");
815
+ const primaryPath = resolve(cwd, ".wrangler/state", `.migration_${sanitized}.lock`);
816
+ if (existsSync(dirname(primaryPath))) {
817
+ return primaryPath;
818
+ }
819
+ return resolve(cwd, ".nuxt", `.migration_${sanitized}.lock`);
820
+ }
821
+ function readFileLock(lockFile) {
822
+ if (!existsSync(lockFile)) return null;
823
+ try {
824
+ const content = readFileSync(lockFile, "utf8");
825
+ const lock = JSON.parse(content);
826
+ if (lock.expiresAt && Date.now() > lock.expiresAt) {
827
+ try {
828
+ rmSync(lockFile, { force: true });
829
+ } catch {
830
+ }
831
+ return null;
832
+ }
833
+ return lock;
834
+ } catch {
835
+ return null;
836
+ }
837
+ }
838
+ function writeFileLock(lockFile, lock) {
839
+ try {
840
+ const dir = dirname(lockFile);
841
+ if (!existsSync(dir)) {
842
+ mkdirSync(dir, { recursive: true });
843
+ }
844
+ writeFileSync(lockFile, JSON.stringify(lock, null, 2), "utf8");
845
+ } catch {
846
+ }
847
+ }
848
+ function removeFileLock(lockFile) {
849
+ try {
850
+ if (existsSync(lockFile)) {
851
+ rmSync(lockFile, { force: true });
852
+ }
853
+ } catch {
854
+ }
855
+ }
856
+ function getDefaultHolder() {
857
+ const host = hostname();
858
+ const pid = process.pid;
859
+ const ciRunId = process.env.GITHUB_RUN_ID || process.env.CI_JOB_ID || process.env.BUILD_ID;
860
+ if (ciRunId) {
861
+ return `${host} (CI #${ciRunId}, PID ${pid})`;
862
+ }
863
+ return `${host} (PID ${pid})`;
864
+ }
865
+ async function renewMigrationLock(dbName, token, options = {}) {
866
+ const now = Date.now();
867
+ const ttlMs = parseLockDuration(options.ttl);
868
+ const newExpiresAt = now + ttlMs;
869
+ const lockKey = `${dbName}:${options.remote ? "remote" : "local"}`;
870
+ const memLock = inMemoryLocks.get(lockKey);
871
+ if (memLock && memLock.token === token) {
872
+ memLock.expiresAt = newExpiresAt;
873
+ memLock.heartbeatAt = now;
874
+ }
875
+ if (options.remote) {
876
+ const executor = options.remoteExecutor || getActiveRemoteExecutor();
877
+ const sql = `UPDATE _qarpeo_migration_lock SET heartbeat_at = ${now}, expires_at = ${newExpiresAt} WHERE id = '${escapeSql(dbName)}' AND token = '${escapeSql(token)}';`;
878
+ const res = await executor(dbName, sql, {
879
+ cwd: options.cwd,
880
+ wranglerConfigPath: options.wranglerConfigPath,
881
+ execPath: options.execPath
882
+ });
883
+ return res.success;
884
+ } else {
885
+ const cwd = resolve(process.cwd(), options.cwd || ".");
886
+ const lockFile = getLockFilePath(dbName, cwd);
887
+ const fileLock = readFileLock(lockFile);
888
+ if (fileLock && fileLock.token === token) {
889
+ fileLock.expiresAt = newExpiresAt;
890
+ fileLock.heartbeatAt = now;
891
+ writeFileLock(lockFile, fileLock);
892
+ return true;
893
+ }
894
+ return false;
895
+ }
896
+ }
897
+ function startMigrationHeartbeat(dbName, token, options = {}) {
898
+ const ttlMs = parseLockDuration(options.ttl);
899
+ const intervalMs = options.intervalMs || Math.min(3e4, Math.max(5e3, Math.floor(ttlMs / 10)));
900
+ let alive = true;
901
+ const timer = setInterval(async () => {
902
+ if (!alive) return;
903
+ try {
904
+ await renewMigrationLock(dbName, token, {
905
+ cwd: options.cwd,
906
+ remote: options.remote,
907
+ ttl: options.ttl,
908
+ wranglerConfigPath: options.wranglerConfigPath,
909
+ execPath: options.execPath,
910
+ remoteExecutor: options.remoteExecutor
911
+ });
912
+ } catch (err) {
913
+ options.onHeartbeatError?.(err);
914
+ }
915
+ }, intervalMs);
916
+ if (timer.unref) {
917
+ timer.unref();
918
+ }
919
+ const handle = {
920
+ stop: () => {
921
+ alive = false;
922
+ clearInterval(timer);
923
+ activeHeartbeats.delete(token);
924
+ },
925
+ isAlive: () => alive
926
+ };
927
+ activeHeartbeats.set(token, handle);
928
+ return handle;
929
+ }
930
+ function stopActiveHeartbeat(token) {
931
+ const hb = activeHeartbeats.get(token);
932
+ if (hb) {
933
+ hb.stop();
934
+ }
935
+ }
936
+ async function acquireMigrationLock(dbName, options = {}) {
937
+ const cwd = resolve(process.cwd(), options.cwd || ".");
938
+ const ttlMs = parseLockDuration(options.ttl);
939
+ const token = options.token || crypto.randomUUID();
940
+ const holder = options.holder || getDefaultHolder();
941
+ const now = Date.now();
942
+ const expiresAt = now + ttlMs;
943
+ const lockKey = `${dbName}:${options.remote ? "remote" : "local"}`;
944
+ if (options.forceUnlock) {
945
+ const forceRes = await safeForceUnlockMigration(dbName, {
946
+ cwd,
947
+ remote: options.remote,
948
+ forceConfirmed: options.forceConfirmed,
949
+ wranglerConfigPath: options.wranglerConfigPath,
950
+ execPath: options.execPath,
951
+ remoteExecutor: options.remoteExecutor
952
+ });
953
+ if (!forceRes.unlocked) {
954
+ return {
955
+ acquired: false,
956
+ error: forceRes.error,
957
+ lock: forceRes.activeHolder
958
+ };
959
+ }
960
+ }
961
+ if (!options.remote) {
962
+ const memLock = inMemoryLocks.get(lockKey);
963
+ if (memLock && memLock.expiresAt > now) {
964
+ return {
965
+ acquired: false,
966
+ lock: memLock,
967
+ error: `Migration lock is currently held by "${memLock.holder}" until ${new Date(memLock.expiresAt).toLocaleTimeString()}`
968
+ };
969
+ } else if (memLock) {
970
+ inMemoryLocks.delete(lockKey);
971
+ }
972
+ const lockFile = getLockFilePath(dbName, cwd);
973
+ const fileLock = readFileLock(lockFile);
974
+ if (fileLock && fileLock.expiresAt > now) {
975
+ return {
976
+ acquired: false,
977
+ lock: fileLock,
978
+ error: `Migration lock is currently held by "${fileLock.holder}" until ${new Date(fileLock.expiresAt).toLocaleTimeString()}`
979
+ };
980
+ }
981
+ const newLock = {
982
+ token,
983
+ holder,
984
+ acquiredAt: now,
985
+ expiresAt,
986
+ heartbeatAt: now,
987
+ database: dbName,
988
+ remote: false
989
+ };
990
+ writeFileLock(lockFile, newLock);
991
+ inMemoryLocks.set(lockKey, newLock);
992
+ startMigrationHeartbeat(dbName, token, {
993
+ cwd,
994
+ remote: false,
995
+ ttl: options.ttl,
996
+ intervalMs: options.heartbeatIntervalMs
997
+ });
998
+ return {
999
+ acquired: true,
1000
+ lock: newLock
1001
+ };
1002
+ }
1003
+ const executor = options.remoteExecutor || getActiveRemoteExecutor();
1004
+ const atomicLockSql = [
1005
+ `CREATE TABLE IF NOT EXISTS _qarpeo_migration_lock (`,
1006
+ ` id TEXT PRIMARY KEY,`,
1007
+ ` token TEXT NOT NULL,`,
1008
+ ` holder TEXT NOT NULL,`,
1009
+ ` acquired_at INTEGER NOT NULL,`,
1010
+ ` expires_at INTEGER NOT NULL,`,
1011
+ ` heartbeat_at INTEGER NOT NULL`,
1012
+ `);`,
1013
+ `INSERT INTO _qarpeo_migration_lock (id, token, holder, acquired_at, expires_at, heartbeat_at)`,
1014
+ `VALUES ('${escapeSql(dbName)}', '${escapeSql(token)}', '${escapeSql(holder)}', ${now}, ${expiresAt}, ${now})`,
1015
+ `ON CONFLICT(id) DO UPDATE SET`,
1016
+ ` token = excluded.token,`,
1017
+ ` holder = excluded.holder,`,
1018
+ ` acquired_at = excluded.acquired_at,`,
1019
+ ` expires_at = excluded.expires_at,`,
1020
+ ` heartbeat_at = excluded.heartbeat_at`,
1021
+ `WHERE _qarpeo_migration_lock.expires_at <= ${now};`,
1022
+ `SELECT id, token, holder, acquired_at, expires_at, heartbeat_at`,
1023
+ `FROM _qarpeo_migration_lock`,
1024
+ `WHERE id = '${escapeSql(dbName)}';`
1025
+ ].join("\n");
1026
+ const res = await executor(dbName, atomicLockSql, {
1027
+ cwd,
1028
+ wranglerConfigPath: options.wranglerConfigPath,
1029
+ execPath: options.execPath
1030
+ });
1031
+ if (!res.success) {
1032
+ return {
1033
+ acquired: false,
1034
+ error: `Failed to acquire remote migration lock on D1 database "${dbName}": ${res.error}`
1035
+ };
1036
+ }
1037
+ const row = res.results?.[0];
1038
+ if (row && row.token === token) {
1039
+ const lock = {
1040
+ token,
1041
+ holder,
1042
+ acquiredAt: now,
1043
+ expiresAt,
1044
+ heartbeatAt: now,
1045
+ database: dbName,
1046
+ remote: true
1047
+ };
1048
+ inMemoryLocks.set(lockKey, lock);
1049
+ startMigrationHeartbeat(dbName, token, {
1050
+ cwd,
1051
+ remote: true,
1052
+ ttl: options.ttl,
1053
+ intervalMs: options.heartbeatIntervalMs,
1054
+ wranglerConfigPath: options.wranglerConfigPath,
1055
+ execPath: options.execPath,
1056
+ remoteExecutor: options.remoteExecutor
1057
+ });
1058
+ return {
1059
+ acquired: true,
1060
+ lock
1061
+ };
1062
+ }
1063
+ const activeHolder = row ? {
1064
+ token: row.token,
1065
+ holder: row.holder,
1066
+ acquiredAt: row.acquired_at,
1067
+ expiresAt: row.expires_at,
1068
+ heartbeatAt: row.heartbeat_at,
1069
+ database: dbName,
1070
+ remote: true
1071
+ } : void 0;
1072
+ const heartbeatAgeSec = row ? Math.max(0, Math.round((now - (row.heartbeat_at || row.acquired_at)) / 1e3)) : 0;
1073
+ const remainingSec = row ? Math.max(0, Math.round((row.expires_at - now) / 1e3)) : 0;
1074
+ return {
1075
+ acquired: false,
1076
+ lock: activeHolder,
1077
+ error: `Remote migration lock for "${dbName}" is held by "${row?.holder || "unknown"}". Last heartbeat was ${heartbeatAgeSec}s ago; lease expires in ${remainingSec}s.`
1078
+ };
1079
+ }
1080
+ async function releaseMigrationLock(dbName, token, options = {}) {
1081
+ const cwd = resolve(process.cwd(), options.cwd || ".");
1082
+ const lockKey = `${dbName}:${options.remote ? "remote" : "local"}`;
1083
+ stopActiveHeartbeat(token);
1084
+ inMemoryLocks.delete(lockKey);
1085
+ if (options.remote) {
1086
+ const executor = options.remoteExecutor || getActiveRemoteExecutor();
1087
+ const deleteSql = `DELETE FROM _qarpeo_migration_lock WHERE id = '${escapeSql(dbName)}' AND token = '${escapeSql(token)}';`;
1088
+ const res = await executor(dbName, deleteSql, {
1089
+ cwd,
1090
+ wranglerConfigPath: options.wranglerConfigPath,
1091
+ execPath: options.execPath
1092
+ });
1093
+ return res.success;
1094
+ }
1095
+ const lockFile = getLockFilePath(dbName, cwd);
1096
+ const fileLock = readFileLock(lockFile);
1097
+ if (fileLock && (fileLock.token === token || !token)) {
1098
+ removeFileLock(lockFile);
1099
+ return true;
1100
+ }
1101
+ return true;
1102
+ }
1103
+ async function safeForceUnlockMigration(dbName, options = {}) {
1104
+ const cwd = resolve(process.cwd(), options.cwd || ".");
1105
+ const lockKey = `${dbName}:${options.remote ? "remote" : "local"}`;
1106
+ const now = Date.now();
1107
+ const livenessThresholdMs = options.livenessThresholdMs || 6e4;
1108
+ if (options.remote) {
1109
+ const executor = options.remoteExecutor || getActiveRemoteExecutor();
1110
+ const selectSql = `SELECT id, token, holder, acquired_at, expires_at, heartbeat_at FROM _qarpeo_migration_lock WHERE id = '${escapeSql(dbName)}';`;
1111
+ const queryRes = await executor(dbName, selectSql, {
1112
+ cwd,
1113
+ wranglerConfigPath: options.wranglerConfigPath,
1114
+ execPath: options.execPath
1115
+ });
1116
+ const row = queryRes.results?.[0];
1117
+ if (row && row.expires_at > now) {
1118
+ const heartbeatAt = row.heartbeat_at || row.acquired_at;
1119
+ const heartbeatAgeMs = now - heartbeatAt;
1120
+ const isAlive = heartbeatAgeMs < livenessThresholdMs;
1121
+ if (isAlive && !options.forceConfirmed) {
1122
+ return {
1123
+ unlocked: false,
1124
+ activeHolder: {
1125
+ token: row.token,
1126
+ holder: row.holder,
1127
+ acquiredAt: row.acquired_at,
1128
+ expiresAt: row.expires_at,
1129
+ heartbeatAt: row.heartbeat_at,
1130
+ database: dbName,
1131
+ remote: true
1132
+ },
1133
+ error: `Active remote migration in flight: Holder "${row.holder}" sent a heartbeat ${Math.max(1, Math.round(heartbeatAgeMs / 1e3))}s ago (acquired ${Math.round((now - row.acquired_at) / 1e3)}s ago). Refusing to force-unlock active migration without --force.`
1134
+ };
1135
+ }
1136
+ }
1137
+ const deleteSql = `DELETE FROM _qarpeo_migration_lock WHERE id = '${escapeSql(dbName)}';`;
1138
+ await executor(dbName, deleteSql, {
1139
+ cwd,
1140
+ wranglerConfigPath: options.wranglerConfigPath,
1141
+ execPath: options.execPath
1142
+ });
1143
+ inMemoryLocks.delete(lockKey);
1144
+ if (row?.token) {
1145
+ stopActiveHeartbeat(row.token);
1146
+ }
1147
+ return {
1148
+ unlocked: true,
1149
+ stale: row ? now - (row.heartbeat_at || row.acquired_at) >= livenessThresholdMs : true
1150
+ };
1151
+ }
1152
+ const lockFile = getLockFilePath(dbName, cwd);
1153
+ const fileLock = readFileLock(lockFile);
1154
+ if (fileLock && fileLock.expiresAt > now) {
1155
+ const heartbeatAt = fileLock.heartbeatAt || fileLock.acquiredAt;
1156
+ const heartbeatAgeMs = now - heartbeatAt;
1157
+ const isAlive = heartbeatAgeMs < livenessThresholdMs;
1158
+ let pidAlive = false;
1159
+ const pidMatch = fileLock.holder?.match(/PID\s+(\d+)/);
1160
+ if (pidMatch && pidMatch[1]) {
1161
+ const pid = parseInt(pidMatch[1], 10);
1162
+ try {
1163
+ process.kill(pid, 0);
1164
+ pidAlive = true;
1165
+ } catch {
1166
+ pidAlive = false;
1167
+ }
1168
+ }
1169
+ if (isAlive && pidAlive && !options.forceConfirmed) {
1170
+ return {
1171
+ unlocked: false,
1172
+ activeHolder: fileLock,
1173
+ error: `Active local migration in flight: Holder "${fileLock.holder}" sent a heartbeat ${Math.max(1, Math.round(heartbeatAgeMs / 1e3))}s ago. Refusing to force-unlock active migration without --force.`
1174
+ };
1175
+ }
1176
+ }
1177
+ removeFileLock(lockFile);
1178
+ inMemoryLocks.delete(lockKey);
1179
+ if (fileLock?.token) {
1180
+ stopActiveHeartbeat(fileLock.token);
1181
+ }
1182
+ return { unlocked: true, stale: true };
1183
+ }
1184
+ async function getMigrationLockStatus(dbName, options = {}) {
1185
+ const cwd = resolve(process.cwd(), options.cwd || ".");
1186
+ const lockKey = `${dbName}:${options.remote ? "remote" : "local"}`;
1187
+ const now = Date.now();
1188
+ if (options.remote) {
1189
+ const executor = options.remoteExecutor || getActiveRemoteExecutor();
1190
+ try {
1191
+ const sql = `SELECT id, token, holder, acquired_at, expires_at, heartbeat_at FROM _qarpeo_migration_lock WHERE id = '${escapeSql(dbName)}';`;
1192
+ const res = await executor(dbName, sql, {
1193
+ cwd,
1194
+ wranglerConfigPath: options.wranglerConfigPath,
1195
+ execPath: options.execPath
1196
+ });
1197
+ const row = res.results?.[0];
1198
+ if (row && row.expires_at > now) {
1199
+ return {
1200
+ token: row.token,
1201
+ holder: row.holder,
1202
+ acquiredAt: row.acquired_at,
1203
+ expiresAt: row.expires_at,
1204
+ heartbeatAt: row.heartbeat_at,
1205
+ database: dbName,
1206
+ remote: true
1207
+ };
1208
+ }
1209
+ return null;
1210
+ } catch {
1211
+ return null;
1212
+ }
1213
+ }
1214
+ const memLock = inMemoryLocks.get(lockKey);
1215
+ if (memLock && memLock.expiresAt > now) {
1216
+ return memLock;
1217
+ }
1218
+ const lockFile = getLockFilePath(dbName, cwd);
1219
+ const fileLock = readFileLock(lockFile);
1220
+ if (fileLock && fileLock.expiresAt > now) {
1221
+ return fileLock;
1222
+ }
1223
+ return null;
1224
+ }
1225
+
469
1226
  const migrate = defineCommand({
470
1227
  meta: {
471
1228
  name: "migrate",
@@ -491,6 +1248,11 @@ const migrate = defineCommand({
491
1248
  description: "List pending migration statements without executing them",
492
1249
  default: false
493
1250
  },
1251
+ status: {
1252
+ type: "boolean",
1253
+ description: "Show migration status and pending migrations across all discovered databases",
1254
+ default: false
1255
+ },
494
1256
  backup: {
495
1257
  type: "boolean",
496
1258
  description: "Create an automatic Cloudflare D1 snapshot backup before running migrations",
@@ -501,6 +1263,36 @@ const migrate = defineCommand({
501
1263
  description: "Safely drop unused auth tables when corresponding features are disabled in nuxt.config.ts",
502
1264
  default: false
503
1265
  },
1266
+ lock: {
1267
+ type: "boolean",
1268
+ description: "Acquire a distributed migration lock to prevent concurrent migrations",
1269
+ default: true
1270
+ },
1271
+ lockTtl: {
1272
+ type: "string",
1273
+ description: "TTL duration for migration lock (e.g. '10m', '5m', '300s')",
1274
+ default: "10m"
1275
+ },
1276
+ forceUnlock: {
1277
+ type: "boolean",
1278
+ description: "Force release any active migration lock before migrating",
1279
+ default: false
1280
+ },
1281
+ force: {
1282
+ type: "boolean",
1283
+ description: "Force override active migration locks without prompt or confirmation",
1284
+ default: false
1285
+ },
1286
+ unlock: {
1287
+ type: "boolean",
1288
+ description: "Release migration lock for target database without running migrations",
1289
+ default: false
1290
+ },
1291
+ waitForLock: {
1292
+ type: "number",
1293
+ description: "Seconds to wait and retry acquiring lock if currently held (0 to fail immediately)",
1294
+ default: 0
1295
+ },
504
1296
  cwd: {
505
1297
  type: "string",
506
1298
  description: "Working directory",
@@ -532,7 +1324,7 @@ const migrate = defineCommand({
532
1324
  } else if (existsSync(resolve(cwd, ".nuxt/wrangler.json"))) {
533
1325
  wranglerConfigPath = resolve(cwd, ".nuxt/wrangler.json");
534
1326
  } else {
535
- const { generateDevWranglerConfig } = await import('../chunks/tools.mjs').then(function (n) { return n.E; });
1327
+ const { generateDevWranglerConfig } = await import('../chunks/tools.mjs').then(function (n) { return n.Z; });
536
1328
  const buildDir = resolve(cwd, ".nuxt");
537
1329
  wranglerConfigPath = await generateDevWranglerConfig(
538
1330
  {
@@ -548,12 +1340,51 @@ const migrate = defineCommand({
548
1340
  }
549
1341
  );
550
1342
  }
1343
+ if (args.status) {
1344
+ console.log(`
1345
+ \u{1F4CA} [qarpeo] Database Migration Status`);
1346
+ console.log(` Working directory: ${cwd}`);
1347
+ console.log(
1348
+ ` Environment: ${args.remote ? "\u2601\uFE0F Remote (Production)" : "\u{1F4BB} Local Development"}
1349
+ `
1350
+ );
1351
+ const allDbs = args.all ? discoverDatabases(layers, qarpeoOpts) : [resolveDatabaseTarget(layers, args.db, qarpeoOpts)];
1352
+ for (const d of allDbs) {
1353
+ const migDir = d.migrationsDir;
1354
+ let count = 0;
1355
+ if (existsSync(migDir)) {
1356
+ const files = readdirSync(migDir).filter((f) => f.endsWith(".sql"));
1357
+ count = files.length;
1358
+ }
1359
+ console.log(`\u{1F4E6} Database: ${d.name} [binding: ${d.binding}, dialect: ${d.dialect}]`);
1360
+ console.log(` Migrations folder: ${relative(cwd, migDir).replace(/\\/g, "/")}`);
1361
+ console.log(` Available SQL migrations: ${count}`);
1362
+ const lockInfo = await getMigrationLockStatus(d.binding, {
1363
+ cwd,
1364
+ remote: args.remote,
1365
+ wranglerConfigPath,
1366
+ execPath
1367
+ });
1368
+ if (lockInfo) {
1369
+ const remainingSec = Math.max(0, Math.round((lockInfo.expiresAt - Date.now()) / 1e3));
1370
+ const heartbeatSec = lockInfo.heartbeatAt ? Math.max(0, Math.round((Date.now() - lockInfo.heartbeatAt) / 1e3)) : null;
1371
+ const hbMsg = heartbeatSec !== null ? `, last heartbeat: ${heartbeatSec}s ago` : "";
1372
+ console.log(
1373
+ ` \u{1F512} Migration Lock: LOCKED by "${lockInfo.holder}" (expires in ${remainingSec}s${hbMsg})`
1374
+ );
1375
+ } else {
1376
+ console.log(` \u{1F513} Migration Lock: UNLOCKED`);
1377
+ }
1378
+ console.log();
1379
+ }
1380
+ return;
1381
+ }
551
1382
  let targets = [];
552
1383
  if (args.all) {
553
1384
  const allDbs = discoverDatabases(layers, qarpeoOpts);
554
- targets = allDbs.filter((d) => d.dialect === "sqlite");
1385
+ targets = allDbs;
555
1386
  if (targets.length === 0) {
556
- console.error("\u274C [qarpeo] No D1 databases found to migrate.");
1387
+ console.error("\u274C [qarpeo] No databases found to migrate.");
557
1388
  process.exit(1);
558
1389
  }
559
1390
  } else {
@@ -565,15 +1396,63 @@ const migrate = defineCommand({
565
1396
  process.exit(1);
566
1397
  }
567
1398
  }
1399
+ if (args.unlock) {
1400
+ console.log(`
1401
+ \u{1F513} [qarpeo] Releasing Migration Lock(s)`);
1402
+ console.log(` Environment: ${args.remote ? "\u2601\uFE0F Remote (Production)" : "\u{1F4BB} Local Development"}
1403
+ `);
1404
+ for (const target of targets) {
1405
+ const unlockRes = await safeForceUnlockMigration(target.binding, {
1406
+ cwd,
1407
+ remote: args.remote,
1408
+ forceConfirmed: args.force,
1409
+ wranglerConfigPath,
1410
+ execPath
1411
+ });
1412
+ if (unlockRes.unlocked) {
1413
+ console.log(`\u2705 [qarpeo] Migration lock released for "${target.binding}".`);
1414
+ } else {
1415
+ console.error(`\u274C [qarpeo] Cannot unlock "${target.binding}":`);
1416
+ console.error(` ${unlockRes.error}`);
1417
+ process.exit(1);
1418
+ }
1419
+ }
1420
+ return;
1421
+ }
1422
+ const migrationResults = [];
568
1423
  for (let i = 0; i < targets.length; i++) {
569
1424
  const target = targets[i];
570
1425
  const dbName = target.binding;
571
1426
  if (targets.length > 1) {
572
1427
  console.log(
573
1428
  `
574
- \u{1F4E6} [qarpeo] (${i + 1}/${targets.length}) Database "${target.name}" [${dbName}]...`
1429
+ \u{1F4E6} [qarpeo] (${i + 1}/${targets.length}) Database "${target.name}" [${dbName}] (${target.dialect})...`
575
1430
  );
576
1431
  }
1432
+ if (target.dialect !== "sqlite") {
1433
+ const migDir = target.migrationsDir;
1434
+ let count = 0;
1435
+ if (existsSync(migDir)) {
1436
+ count = readdirSync(migDir).filter((f) => f.endsWith(".sql")).length;
1437
+ }
1438
+ if (args.dryRun) {
1439
+ console.log(
1440
+ `\u{1F50D} [qarpeo] Dry-run preview for ${target.dialect.toUpperCase()} database "${dbName}": ${count} migration(s) found in ${migDir}.`
1441
+ );
1442
+ } else {
1443
+ console.log(
1444
+ `\u2139\uFE0F [qarpeo] Hyperdrive / ${target.dialect.toUpperCase()} database "${dbName}": ${count} migration(s) ready.`
1445
+ );
1446
+ }
1447
+ migrationResults.push({
1448
+ name: target.name,
1449
+ binding: dbName,
1450
+ dialect: target.dialect,
1451
+ status: "success",
1452
+ message: `${count} migration(s) ready`
1453
+ });
1454
+ continue;
1455
+ }
577
1456
  if (args.dryRun) {
578
1457
  console.log(
579
1458
  `\u{1F50D} [qarpeo] Dry-run preview for D1 database "${dbName}" (${args.remote ? "remote" : "local dev"})...`
@@ -583,6 +1462,52 @@ const migrate = defineCommand({
583
1462
  `\u26A1 [qarpeo] Applying migrations to D1 database "${dbName}" (${args.remote ? "remote" : "local dev"})...`
584
1463
  );
585
1464
  }
1465
+ let lockToken = null;
1466
+ if (args.lock && !args.dryRun) {
1467
+ let lockRes = await acquireMigrationLock(dbName, {
1468
+ cwd,
1469
+ ttl: args.lockTtl,
1470
+ remote: args.remote,
1471
+ forceUnlock: args.forceUnlock,
1472
+ forceConfirmed: args.force,
1473
+ wranglerConfigPath,
1474
+ execPath
1475
+ });
1476
+ if (!lockRes.acquired && args.waitForLock > 0) {
1477
+ console.log(
1478
+ `\u23F3 [qarpeo] Database "${dbName}" migration is locked. Waiting up to ${args.waitForLock}s for lock release...`
1479
+ );
1480
+ const deadline = Date.now() + args.waitForLock * 1e3;
1481
+ while (!lockRes.acquired && Date.now() < deadline) {
1482
+ await new Promise((r) => setTimeout(r, 1e3));
1483
+ lockRes = await acquireMigrationLock(dbName, {
1484
+ cwd,
1485
+ ttl: args.lockTtl,
1486
+ remote: args.remote,
1487
+ forceConfirmed: args.force,
1488
+ wranglerConfigPath,
1489
+ execPath
1490
+ });
1491
+ }
1492
+ }
1493
+ if (!lockRes.acquired) {
1494
+ console.error(`
1495
+ \u274C [qarpeo] Cannot run migrations on database "${dbName}":`);
1496
+ console.error(` ${lockRes.error}`);
1497
+ console.error(` Use --force-unlock (with --force if active) or --no-lock to bypass locking.
1498
+ `);
1499
+ migrationResults.push({
1500
+ name: target.name,
1501
+ binding: dbName,
1502
+ dialect: target.dialect,
1503
+ status: "failed",
1504
+ message: "Migration lock held by another process"
1505
+ });
1506
+ process.exit(1);
1507
+ }
1508
+ lockToken = lockRes.lock?.token || null;
1509
+ console.log(`\u{1F512} [qarpeo] Migration lock acquired for "${dbName}" (lease: ${args.lockTtl}, heartbeat active).`);
1510
+ }
586
1511
  if (args.backup && args.remote && !args.dryRun) {
587
1512
  console.log(
588
1513
  `\u{1F6E1}\uFE0F [qarpeo] Creating automatic snapshot backup of remote D1 database "${dbName}"...`
@@ -615,27 +1540,64 @@ const migrate = defineCommand({
615
1540
  wranglerArgs.push("--local", "--persist-to", resolve(cwd, ".wrangler/state"));
616
1541
  }
617
1542
  console.log(`\u{1F680} [qarpeo] Running: wrangler ${wranglerArgs.join(" ")}`);
618
- const result = spawnSync(execPath, wranglerArgs, {
619
- cwd,
620
- stdio: "inherit",
621
- shell: process.platform === "win32"
622
- // .cmd files require shell:true on Windows
623
- });
1543
+ let result;
1544
+ try {
1545
+ result = spawnSync(execPath, wranglerArgs, {
1546
+ cwd,
1547
+ stdio: "inherit",
1548
+ shell: process.platform === "win32"
1549
+ // .cmd files require shell:true on Windows
1550
+ });
1551
+ } finally {
1552
+ if (lockToken) {
1553
+ await releaseMigrationLock(dbName, lockToken, {
1554
+ cwd,
1555
+ remote: args.remote,
1556
+ wranglerConfigPath,
1557
+ execPath
1558
+ });
1559
+ console.log(`\u{1F513} [qarpeo] Migration lock released for "${dbName}".`);
1560
+ }
1561
+ }
624
1562
  if (result.status !== 0) {
625
1563
  console.error(`\u274C [qarpeo] Migration failed for database "${dbName}".`);
1564
+ migrationResults.push({
1565
+ name: target.name,
1566
+ binding: dbName,
1567
+ dialect: target.dialect,
1568
+ status: "failed",
1569
+ message: `wrangler exited with code ${result.status}`
1570
+ });
1571
+ if (targets.length > 1) {
1572
+ console.log(
1573
+ `
1574
+ \u26A0\uFE0F [qarpeo] Stopping multi-database migration sequence due to failure in "${dbName}".`
1575
+ );
1576
+ }
626
1577
  process.exit(result.status ?? 1);
627
1578
  }
1579
+ migrationResults.push({
1580
+ name: target.name,
1581
+ binding: dbName,
1582
+ dialect: target.dialect,
1583
+ status: "success"
1584
+ });
628
1585
  console.log(`\u2705 [qarpeo] Migrations for "${dbName}" applied successfully!`);
629
1586
  }
630
1587
  if (targets.length > 1) {
631
1588
  console.log(`
632
- \u{1F389} [qarpeo] All ${targets.length} database(s) migrated successfully!`);
1589
+ \u{1F389} [qarpeo] All ${targets.length} database(s) processed successfully!`);
1590
+ for (const r of migrationResults) {
1591
+ console.log(
1592
+ ` \u2713 ${r.name} [${r.binding}, ${r.dialect}]: ${r.status.toUpperCase()}${r.message ? ` (${r.message})` : ""}`
1593
+ );
1594
+ }
633
1595
  }
634
1596
  if (args.prune && targets.some((t) => t.isPrimary)) {
635
1597
  const primaryTarget = targets.find((t) => t.isPrimary);
636
1598
  const primaryBinding = primaryTarget.binding;
637
- const { getActiveAuthTableNames, ALL_AUTH_TABLE_NAMES } = await import('../chunks/auth-schema.mjs').then(function (n) { return n.c; });
638
- const { findLocalD1Database } = await import('../chunks/tools.mjs').then(function (n) { return n.D; });
1599
+ const { getActiveAuthTableNames, ALL_AUTH_TABLE_NAMES } = await import('../chunks/tools.mjs').then(function (n) { return n.Y; });
1600
+ const { findLocalD1Database } = await import('../chunks/tools.mjs').then(function (n) { return n.X; });
639
1601
  const authConfig = nuxtConfig.qarpeo?.auth || nuxtConfig.auth;
640
1602
  const activeTables = getActiveAuthTableNames(authConfig);
641
1603
  const unusedTables = ALL_AUTH_TABLE_NAMES.filter(
@@ -1000,6 +1962,7 @@ const db = defineCommand({
1000
1962
  create,
1001
1963
  delete: deleteDb,
1002
1964
  drop: deleteDb,
1965
+ diff,
1003
1966
  generate,
1004
1967
  migrate,
1005
1968
  push,
@@ -1505,7 +2468,7 @@ const deploy = defineCommand({
1505
2468
  if (!wranglerConfigPath) {
1506
2469
  try {
1507
2470
  const { loadNuxtConfig } = await import('@nuxt/kit');
1508
- const { generateDevWranglerConfig } = await import('../chunks/tools.mjs').then(function (n) { return n.E; });
2471
+ const { generateDevWranglerConfig } = await import('../chunks/tools.mjs').then(function (n) { return n.Z; });
1509
2472
  const nuxtConfig = await loadNuxtConfig({ cwd });
1510
2473
  const qarpeoOpts = nuxtConfig.qarpeo || {};
1511
2474
  const buildDir = resolve(cwd, ".nuxt");
@@ -1575,6 +2538,37 @@ const deploy = defineCommand({
1575
2538
  writeFileSync(wranglerConfigPath, JSON.stringify(config, null, 2), "utf8");
1576
2539
  }
1577
2540
  }
2541
+ let deduplicated = false;
2542
+ const dedupeBindingArray = (arr) => {
2543
+ if (!Array.isArray(arr)) return arr;
2544
+ const seen = /* @__PURE__ */ new Set();
2545
+ return arr.filter((item) => {
2546
+ const key = item?.binding || item?.name;
2547
+ if (!key || seen.has(key)) {
2548
+ deduplicated = true;
2549
+ return false;
2550
+ }
2551
+ seen.add(key);
2552
+ return true;
2553
+ });
2554
+ };
2555
+ if (Array.isArray(config.kv_namespaces)) config.kv_namespaces = dedupeBindingArray(config.kv_namespaces);
2556
+ if (Array.isArray(config.d1_databases)) config.d1_databases = dedupeBindingArray(config.d1_databases);
2557
+ if (Array.isArray(config.r2_buckets)) config.r2_buckets = dedupeBindingArray(config.r2_buckets);
2558
+ if (Array.isArray(config.vectorize)) config.vectorize = dedupeBindingArray(config.vectorize);
2559
+ if (Array.isArray(config.workflows)) config.workflows = dedupeBindingArray(config.workflows);
2560
+ if (Array.isArray(config.analytics_engine_datasets)) config.analytics_engine_datasets = dedupeBindingArray(config.analytics_engine_datasets);
2561
+ if (Array.isArray(config.ratelimits)) config.ratelimits = dedupeBindingArray(config.ratelimits);
2562
+ if (Array.isArray(config.compatibility_flags)) {
2563
+ const flags = Array.from(new Set(config.compatibility_flags));
2564
+ if (flags.length !== config.compatibility_flags.length) {
2565
+ config.compatibility_flags = flags;
2566
+ deduplicated = true;
2567
+ }
2568
+ }
2569
+ if (deduplicated && wranglerConfigPath) {
2570
+ writeFileSync(wranglerConfigPath, JSON.stringify(config, null, 2), "utf8");
2571
+ }
1578
2572
  let nuxtConfigWorkerName = null;
1579
2573
  for (const f of ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs"]) {
1580
2574
  const p = resolve(cwd, f);
@@ -1651,15 +2645,40 @@ const deploy = defineCommand({
1651
2645
  encoding: "utf8"
1652
2646
  });
1653
2647
  const stdoutText = String(createRes.stdout || "");
1654
- const matchUuid = stdoutText.match(/database_id\s*:\s*"([^"]+)"/) || stdoutText.match(/database_id\s*=\s*"([^"]+)"/) || stdoutText.match(/"database_id"\s*:\s*"([^"]+)"/) || stdoutText.match(
1655
- /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1656
- );
1657
- if (matchUuid?.[1]) {
1658
- d1.database_id = matchUuid[1];
2648
+ let createdUuid = null;
2649
+ const explicitMatch = stdoutText.match(/database_id\s*[:=]\s*["']?([0-9a-f-]{36})["']?/i) || stdoutText.match(/"database_id"\s*:\s*"([0-9a-f-]{36})"/i);
2650
+ if (explicitMatch?.[1]) {
2651
+ createdUuid = explicitMatch[1];
2652
+ } else {
2653
+ try {
2654
+ const refreshRes = spawnBinSync(wranglerBin, ["d1", "list", "--json"], {
2655
+ cwd,
2656
+ encoding: "utf8"
2657
+ });
2658
+ const refreshedDbs = JSON.parse(
2659
+ String(refreshRes.stdout || "[]")
2660
+ );
2661
+ const found = refreshedDbs.find((d) => d.name === targetDbName);
2662
+ if (found?.uuid) {
2663
+ createdUuid = found.uuid;
2664
+ }
2665
+ } catch {
2666
+ }
2667
+ if (!createdUuid) {
2668
+ const allUuids = stdoutText.match(
2669
+ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
2670
+ );
2671
+ if (allUuids && allUuids.length === 1) {
2672
+ createdUuid = allUuids[0];
2673
+ }
2674
+ }
2675
+ }
2676
+ if (createdUuid) {
2677
+ d1.database_id = createdUuid;
1659
2678
  d1.database_name = targetDbName;
1660
2679
  modified = true;
1661
2680
  console.log(
1662
- `\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} D1 database: ${matchUuid[1]}`
2681
+ `\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} D1 database: ${createdUuid}`
1663
2682
  );
1664
2683
  }
1665
2684
  }
@@ -1708,12 +2727,31 @@ const deploy = defineCommand({
1708
2727
  { cwd, encoding: "utf8" }
1709
2728
  );
1710
2729
  const stdoutKv = String(createRes.stdout || "");
1711
- const matchId = stdoutKv.match(/id\s*=\s*"([^"]+)"/);
2730
+ let createdKvId = null;
2731
+ const matchId = stdoutKv.match(/id\s*=\s*"([^"]+)"/) || stdoutKv.match(/"id"\s*:\s*"([^"]+)"/) || stdoutKv.match(/id\s*:\s*"([^"]+)"/);
1712
2732
  if (matchId?.[1]) {
1713
- kv.id = matchId[1];
2733
+ createdKvId = matchId[1];
2734
+ } else {
2735
+ try {
2736
+ const refreshKv = spawnBinSync(wranglerBin, ["kv", "namespace", "list"], {
2737
+ cwd,
2738
+ encoding: "utf8"
2739
+ });
2740
+ const refreshedKvs = JSON.parse(
2741
+ String(refreshKv.stdout || "[]")
2742
+ );
2743
+ const found = refreshedKvs.find((k) => k.title === expectedTitle);
2744
+ if (found?.id) {
2745
+ createdKvId = found.id;
2746
+ }
2747
+ } catch {
2748
+ }
2749
+ }
2750
+ if (createdKvId) {
2751
+ kv.id = createdKvId;
1714
2752
  modified = true;
1715
2753
  console.log(
1716
- `\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} KV namespace: ${matchId[1]}`
2754
+ `\u2705 [qarpeo] Created ${isPreview ? "preview" : "remote"} KV namespace: ${createdKvId}`
1717
2755
  );
1718
2756
  }
1719
2757
  }
@@ -1740,7 +2778,7 @@ const deploy = defineCommand({
1740
2778
  if (args.migrate && !args.dryRun) {
1741
2779
  try {
1742
2780
  if (Array.isArray(config.d1_databases) && config.d1_databases.length > 0) {
1743
- const migConfigPath = rootConfigPath || wranglerConfigPath;
2781
+ const migConfigPath = wranglerConfigPath || rootConfigPath;
1744
2782
  for (const d1 of config.d1_databases) {
1745
2783
  const hasId = d1.database_id && !d1.database_id.includes("LOCAL");
1746
2784
  const dbName = d1.database_name || d1.binding;
@@ -1753,20 +2791,28 @@ const deploy = defineCommand({
1753
2791
  isPrimary ? resolve(cwd, "db/d1/migrations") : null,
1754
2792
  isPrimary ? resolve(cwd, "db/migrations") : null,
1755
2793
  !isPrimary ? resolve(cwd, `db/d1-${secName}/migrations`) : null,
2794
+ !isPrimary ? resolve(cwd, `db/${secName}/migrations`) : null,
2795
+ !isPrimary ? resolve(cwd, `db/d1_${secName}/migrations`) : null,
1756
2796
  !isPrimary ? resolve(cwd, `db/migrations/${secName}`) : null,
1757
2797
  resolve(cwd, "migrations"),
1758
2798
  resolve(cwd, ".output/server/migrations")
1759
2799
  ].filter(Boolean);
1760
- const hasMigrations = candidateMigDirs.some(
2800
+ const foundMigDir = candidateMigDirs.find(
1761
2801
  (d) => existsSync(d) && statSync(d).isDirectory() && readdirSync(d).some(
1762
2802
  (f) => f.endsWith(".sql") || existsSync(join(d, f)) && statSync(join(d, f)).isDirectory()
1763
2803
  )
1764
2804
  );
1765
- if (hasMigrations || d1.migrations_dir) {
2805
+ if (foundMigDir) {
2806
+ const relMigDir = relative(cwd, foundMigDir).replace(/\\/g, "/");
2807
+ if (d1.migrations_dir !== relMigDir) {
2808
+ d1.migrations_dir = relMigDir;
2809
+ writeFileSync(wranglerConfigPath, JSON.stringify(config, null, 2), "utf8");
2810
+ }
1766
2811
  console.log(
1767
2812
  `
1768
2813
  \u26A1 [qarpeo] Applying D1 migrations for ${dbName} (${isPreview ? "preview" : "remote"})...`
1769
2814
  );
2815
+ console.log(`\u{1F4C1} [qarpeo] Migration source: ${relMigDir}`);
1770
2816
  const migArgs = [
1771
2817
  "d1",
1772
2818
  "migrations",
@@ -2228,7 +3274,7 @@ const doctor = defineCommand({
2228
3274
  status: "warn",
2229
3275
  title: "Schema Definitions",
2230
3276
  message: "No custom Drizzle schema files found in db/",
2231
- help: "Create table definitions in db/d1/schema.ts or db/d1/schema/."
3277
+ help: "Create table definitions in db/schema.ts or db/schema/."
2232
3278
  });
2233
3279
  }
2234
3280
  for (const db of discoveredDatabases) {
@@ -2297,6 +3343,31 @@ const doctor = defineCommand({
2297
3343
  title: "Local Database File",
2298
3344
  message: `Found: ${join(".", localDbPath.replace(cwd, "")).replace(/^[\\/]/, "")}`
2299
3345
  });
3346
+ const primaryDb = discoveredDatabases.find((d) => d.isPrimary) || discoveredDatabases[0];
3347
+ if (primaryDb) {
3348
+ try {
3349
+ const diffResult = await computeSchemaDiff({
3350
+ database: primaryDb,
3351
+ sqlitePath: localDbPath,
3352
+ qarpeoConfig
3353
+ });
3354
+ if (diffResult.missingTables.length > 0) {
3355
+ dbItems.push({
3356
+ status: "warn",
3357
+ title: "Schema Drift Detection",
3358
+ message: `${diffResult.missingTables.length} table(s) defined in schema missing from local database: ${diffResult.missingTables.join(", ")}`,
3359
+ help: "Run `qp db migrate` or `qp db push` to synchronize database tables."
3360
+ });
3361
+ } else if (diffResult.matchingTables.length > 0) {
3362
+ dbItems.push({
3363
+ status: "pass",
3364
+ title: "Schema Drift Detection",
3365
+ message: `All ${diffResult.matchingTables.length} schema table(s) verified in local database`
3366
+ });
3367
+ }
3368
+ } catch {
3369
+ }
3370
+ }
2300
3371
  } else {
2301
3372
  dbItems.push({
2302
3373
  status: "info",