qarpeo 0.1.35 → 0.2.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 (363) hide show
  1. package/README.md +114 -26
  2. package/dist/apps/cms.d.ts +4 -0
  3. package/dist/apps/comments.d.ts +4 -0
  4. package/dist/apps/payments.d.ts +4 -0
  5. package/dist/apps/store.d.ts +4 -0
  6. package/dist/chunks/auth-schema.mjs +169 -30
  7. package/dist/chunks/tools.mjs +1680 -0
  8. package/dist/cli/index.mjs +1256 -221
  9. package/dist/core/aliases.d.ts +5 -0
  10. package/dist/core/context.d.ts +10 -0
  11. package/dist/core/cross-drive.d.ts +2 -0
  12. package/dist/core/d1-migrate.d.ts +4 -0
  13. package/dist/core/devtools.d.ts +4 -0
  14. package/dist/core/nitro.d.ts +4 -0
  15. package/dist/core/schema.d.ts +4 -0
  16. package/dist/core/server-utils.d.ts +4 -0
  17. package/dist/core/wrangler.d.ts +4 -0
  18. package/dist/dev/wrangler.d.ts +1 -0
  19. package/dist/fate/index.d.ts +8 -8
  20. package/dist/features/agents.d.ts +4 -0
  21. package/dist/features/auth.d.ts +4 -0
  22. package/dist/features/bots.d.ts +4 -0
  23. package/dist/features/fate.d.ts +4 -0
  24. package/dist/features/mail.d.ts +4 -0
  25. package/dist/features/mcp.d.ts +4 -0
  26. package/dist/features/multitenant.d.ts +4 -0
  27. package/dist/features/notifications.d.ts +4 -0
  28. package/dist/features/realtime.d.ts +4 -0
  29. package/dist/module.d.ts +10 -2
  30. package/dist/module.mjs +6313 -5118
  31. package/dist/primitives/ai.d.ts +4 -0
  32. package/dist/primitives/analytics.d.ts +4 -0
  33. package/dist/primitives/blob.d.ts +4 -0
  34. package/dist/primitives/browser.d.ts +4 -0
  35. package/dist/primitives/cache.d.ts +4 -0
  36. package/dist/primitives/d1.d.ts +4 -0
  37. package/dist/primitives/do.d.ts +4 -0
  38. package/dist/primitives/email.d.ts +4 -0
  39. package/dist/primitives/hyperdrive.d.ts +4 -0
  40. package/dist/primitives/kv.d.ts +4 -0
  41. package/dist/primitives/queue.d.ts +4 -0
  42. package/dist/primitives/ratelimit.d.ts +4 -0
  43. package/dist/primitives/vectorize.d.ts +4 -0
  44. package/dist/primitives/workflows.d.ts +4 -0
  45. package/dist/runtime/ai.d.ts +3 -3
  46. package/dist/runtime/ai.mjs +8 -1
  47. package/dist/runtime/app/components/RealtimeCursors.vue +2 -2
  48. package/dist/runtime/app/composables/ai.d.ts +56 -29
  49. package/dist/runtime/app/composables/analytics.d.ts +26 -106
  50. package/dist/runtime/app/composables/api-tokens.d.ts +31 -34
  51. package/dist/runtime/app/composables/auth.d.ts +147 -51
  52. package/dist/runtime/app/composables/auth.mjs +0 -7
  53. package/dist/runtime/app/composables/chat.d.ts +38 -35
  54. package/dist/runtime/app/composables/cms-preview.d.ts +30 -25
  55. package/dist/runtime/app/composables/cms.d.ts +57 -282
  56. package/dist/runtime/app/composables/cms.mjs +0 -35
  57. package/dist/runtime/app/composables/comments.d.ts +32 -5
  58. package/dist/runtime/app/composables/comments.mjs +29 -1
  59. package/dist/runtime/app/composables/docs-version.d.ts +25 -28
  60. package/dist/runtime/app/composables/impersonation.d.ts +22 -5
  61. package/dist/runtime/app/composables/organization.d.ts +38 -91
  62. package/dist/runtime/app/composables/passkey.d.ts +22 -6
  63. package/dist/runtime/app/composables/passwordless.d.ts +24 -7
  64. package/dist/runtime/app/composables/payments.d.ts +50 -34
  65. package/dist/runtime/app/composables/payments.mjs +1 -0
  66. package/dist/runtime/app/composables/sse.d.ts +76 -0
  67. package/dist/runtime/app/composables/sse.mjs +152 -0
  68. package/dist/runtime/app/composables/storage.d.ts +53 -65
  69. package/dist/runtime/app/composables/storage.mjs +17 -0
  70. package/dist/runtime/app/composables/store.d.ts +198 -0
  71. package/dist/runtime/app/composables/store.mjs +414 -0
  72. package/dist/runtime/app/composables/tenant.d.ts +31 -72
  73. package/dist/runtime/app/composables/turnstile.d.ts +16 -3
  74. package/dist/runtime/app/composables/two-factor.d.ts +23 -6
  75. package/dist/runtime/app/pages/devtools/notifications.vue +30 -27
  76. package/dist/runtime/app/pages/devtools/realtime.vue +19 -31
  77. package/dist/runtime/app/pages/devtools.vue +0 -7
  78. package/dist/runtime/auth.d.ts +9 -9
  79. package/dist/runtime/blob.d.ts +10 -1
  80. package/dist/runtime/blob.mjs +83 -0
  81. package/dist/runtime/cache.d.ts +48 -0
  82. package/dist/runtime/cache.mjs +92 -0
  83. package/dist/runtime/comments.d.ts +4 -0
  84. package/dist/runtime/comments.mjs +2 -0
  85. package/dist/runtime/db.d.ts +21 -1
  86. package/dist/runtime/db.mjs +54 -0
  87. package/dist/runtime/drizzle.d.ts +4 -2
  88. package/dist/runtime/drizzle.mjs +68 -1
  89. package/dist/runtime/durable-object.d.ts +2 -0
  90. package/dist/runtime/durable-object.mjs +2 -0
  91. package/dist/runtime/email.d.ts +1 -1
  92. package/dist/runtime/email.mjs +1 -1
  93. package/dist/runtime/kv.mjs +50 -1
  94. package/dist/runtime/mcp.d.ts +2 -0
  95. package/dist/runtime/mcp.mjs +2 -0
  96. package/dist/runtime/queue.d.ts +12 -2
  97. package/dist/runtime/queue.mjs +19 -1
  98. package/dist/runtime/ratelimit.d.ts +1 -0
  99. package/dist/runtime/ratelimit.mjs +7 -0
  100. package/dist/runtime/schema.d.ts +313 -0
  101. package/dist/runtime/schema.mjs +259 -0
  102. package/dist/runtime/server/db/cms-schema.d.ts +1225 -171
  103. package/dist/runtime/server/db/cms-schema.mjs +69 -70
  104. package/dist/runtime/server/db/store-schema.d.ts +4344 -0
  105. package/dist/runtime/server/db/store-schema.mjs +266 -0
  106. package/dist/runtime/server/durable-objects/agent.mjs +35 -0
  107. package/dist/runtime/server/durable-objects/room.mjs +0 -1
  108. package/dist/runtime/server/middleware/ratelimit.mjs +10 -8
  109. package/dist/runtime/server/plugins/comments.d.ts +7 -0
  110. package/dist/runtime/server/plugins/comments.mjs +7 -0
  111. package/dist/runtime/server/plugins/email-inbound.d.ts +5 -0
  112. package/dist/runtime/server/plugins/email-inbound.mjs +17 -0
  113. package/dist/runtime/server/plugins/store.d.ts +7 -0
  114. package/dist/runtime/server/plugins/store.mjs +7 -0
  115. package/dist/runtime/server/routes/__qarpeo/db/tables.get.mjs +2 -2
  116. package/dist/runtime/server/routes/atom.xml.get.mjs +3 -1
  117. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +13 -2
  118. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +9 -3
  119. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -3
  120. package/dist/runtime/server/routes/auth/account.delete.mjs +2 -1
  121. package/dist/runtime/server/routes/auth/audit-logs.get.mjs +1 -1
  122. package/dist/runtime/server/routes/auth/magic-link/send.post.d.ts +1 -9
  123. package/dist/runtime/server/routes/auth/magic-link/send.post.mjs +8 -0
  124. package/dist/runtime/server/routes/auth/organization/sso/[id].delete.mjs +1 -1
  125. package/dist/runtime/server/routes/auth/organization/sso/index.get.mjs +1 -1
  126. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +1 -1
  127. package/dist/runtime/server/routes/auth/otp/send.post.d.ts +1 -9
  128. package/dist/runtime/server/routes/auth/otp/send.post.mjs +8 -0
  129. package/dist/runtime/server/routes/auth/sso/login.get.mjs +3 -3
  130. package/dist/runtime/server/routes/auth/sso/oidc/callback.get.mjs +1 -1
  131. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +2 -2
  132. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +1 -1
  133. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +1 -1
  134. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +2 -2
  135. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +1 -1
  136. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +1 -1
  137. package/dist/runtime/server/routes/cms/[collection]/atom.xml.get.mjs +3 -1
  138. package/dist/runtime/server/routes/cms/[collection]/feed.xml.get.mjs +3 -1
  139. package/dist/runtime/server/routes/cms/bookmarks/[id].delete.mjs +1 -1
  140. package/dist/runtime/server/routes/cms/bookmarks/check.post.mjs +1 -1
  141. package/dist/runtime/server/routes/cms/bookmarks/index.get.mjs +1 -1
  142. package/dist/runtime/server/routes/cms/bookmarks/index.post.mjs +1 -1
  143. package/dist/runtime/server/routes/cms/deploy.post.mjs +1 -1
  144. package/dist/runtime/server/routes/cms/export.post.mjs +4 -3
  145. package/dist/runtime/server/routes/cms/search.get.mjs +7 -5
  146. package/dist/runtime/server/routes/cms/sync.post.mjs +2 -1
  147. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +1 -2
  148. package/dist/runtime/server/routes/comments/[id]/report.post.d.ts +1 -1
  149. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +0 -2
  150. package/dist/runtime/server/routes/comments/[id].delete.mjs +8 -4
  151. package/dist/runtime/server/routes/comments/[id].get.d.ts +1 -1
  152. package/dist/runtime/server/routes/comments/[id].get.mjs +1 -2
  153. package/dist/runtime/server/routes/comments/[id].patch.d.ts +1 -1
  154. package/dist/runtime/server/routes/comments/[id].patch.mjs +6 -3
  155. package/dist/runtime/server/routes/comments/batch.post.d.ts +2 -0
  156. package/dist/runtime/server/routes/comments/batch.post.mjs +33 -0
  157. package/dist/runtime/server/routes/comments/index.get.d.ts +1 -1
  158. package/dist/runtime/server/routes/comments/index.get.mjs +6 -4
  159. package/dist/runtime/server/routes/comments/index.post.d.ts +1 -1
  160. package/dist/runtime/server/routes/comments/index.post.mjs +6 -2
  161. package/dist/runtime/server/routes/feed.xml.get.mjs +3 -1
  162. package/dist/runtime/server/routes/sitemap.xml.get.mjs +3 -1
  163. package/dist/runtime/server/routes/storage/presigned-r2.post.d.ts +17 -0
  164. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +29 -0
  165. package/dist/runtime/server/routes/store/cart/index.delete.d.ts +6 -0
  166. package/dist/runtime/server/routes/store/cart/index.delete.mjs +11 -0
  167. package/dist/runtime/server/routes/store/cart/index.get.d.ts +5 -0
  168. package/dist/runtime/server/routes/store/cart/index.get.mjs +14 -0
  169. package/dist/runtime/server/routes/store/cart/items/[id].delete.d.ts +6 -0
  170. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +25 -0
  171. package/dist/runtime/server/routes/store/cart/items/[id].patch.d.ts +6 -0
  172. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +29 -0
  173. package/dist/runtime/server/routes/store/cart/items.post.d.ts +6 -0
  174. package/dist/runtime/server/routes/store/cart/items.post.mjs +36 -0
  175. package/dist/runtime/server/routes/store/categories/index.get.d.ts +2 -0
  176. package/dist/runtime/server/routes/store/categories/index.get.mjs +8 -0
  177. package/dist/runtime/server/routes/store/checkout.post.d.ts +6 -0
  178. package/dist/runtime/server/routes/store/checkout.post.mjs +21 -0
  179. package/dist/runtime/server/routes/store/coupons/apply.post.d.ts +7 -0
  180. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +18 -0
  181. package/dist/runtime/server/routes/store/currencies.get.d.ts +15 -0
  182. package/dist/runtime/server/routes/store/currencies.get.mjs +13 -0
  183. package/dist/runtime/server/routes/store/orders/[id].get.d.ts +2 -0
  184. package/dist/runtime/server/routes/store/orders/[id].get.mjs +26 -0
  185. package/dist/runtime/server/routes/store/orders/download/[token].get.d.ts +7 -0
  186. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +57 -0
  187. package/dist/runtime/server/routes/store/orders/index.get.d.ts +5 -0
  188. package/dist/runtime/server/routes/store/orders/index.get.mjs +30 -0
  189. package/dist/runtime/server/routes/store/products/[slug].get.d.ts +2 -0
  190. package/dist/runtime/server/routes/store/products/[slug].get.mjs +18 -0
  191. package/dist/runtime/server/routes/store/products/index.get.d.ts +5 -0
  192. package/dist/runtime/server/routes/store/products/index.get.mjs +33 -0
  193. package/dist/runtime/server/routes/store/tax/calculate.post.d.ts +9 -0
  194. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +18 -0
  195. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +14 -1
  196. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +14 -1
  197. package/dist/runtime/server/routes/tenants/[tenant]/domains/index.get.mjs +24 -1
  198. package/dist/runtime/server/routes/tenants/[tenant]/domains/index.post.mjs +6 -0
  199. package/dist/runtime/server/utils/ai.d.ts +146 -21
  200. package/dist/runtime/server/utils/ai.mjs +406 -11
  201. package/dist/runtime/server/utils/analytics-query.d.ts +13 -58
  202. package/dist/runtime/server/utils/audit.d.ts +5 -4
  203. package/dist/runtime/server/utils/audit.mjs +25 -14
  204. package/dist/runtime/server/utils/auth.d.ts +29 -12
  205. package/dist/runtime/server/utils/auth.mjs +88 -70
  206. package/dist/runtime/server/utils/bots.d.ts +20 -4
  207. package/dist/runtime/server/utils/bots.mjs +7 -3
  208. package/dist/runtime/server/utils/browser-utils.d.ts +23 -23
  209. package/dist/runtime/server/utils/cache.d.ts +3 -3
  210. package/dist/runtime/server/utils/cms/collections.d.ts +23 -0
  211. package/dist/runtime/server/utils/cms/collections.mjs +143 -0
  212. package/dist/runtime/server/utils/cms/common.d.ts +9 -0
  213. package/dist/runtime/server/utils/cms/common.mjs +28 -0
  214. package/dist/runtime/server/utils/cms/git.mjs +2 -2
  215. package/dist/runtime/server/utils/cms/navigation.d.ts +46 -0
  216. package/dist/runtime/server/utils/cms/navigation.mjs +683 -0
  217. package/dist/runtime/server/utils/cms/preview.d.ts +11 -0
  218. package/dist/runtime/server/utils/cms/preview.mjs +50 -0
  219. package/dist/runtime/server/utils/cms/search.d.ts +1 -1
  220. package/dist/runtime/server/utils/cms/search.mjs +11 -7
  221. package/dist/runtime/server/utils/cms/sync.d.ts +34 -0
  222. package/dist/runtime/server/utils/cms/sync.mjs +1082 -0
  223. package/dist/runtime/server/utils/cms/taxonomy.d.ts +103 -0
  224. package/dist/runtime/server/utils/cms/taxonomy.mjs +348 -0
  225. package/dist/runtime/server/utils/cms.d.ts +13 -249
  226. package/dist/runtime/server/utils/cms.mjs +108 -2350
  227. package/dist/runtime/server/utils/comments-filter.d.ts +45 -0
  228. package/dist/runtime/server/utils/comments-filter.mjs +541 -0
  229. package/dist/runtime/server/utils/comments.d.ts +71 -0
  230. package/dist/runtime/server/utils/comments.mjs +137 -61
  231. package/dist/runtime/server/utils/config.d.ts +4 -3
  232. package/dist/runtime/server/utils/config.mjs +7 -6
  233. package/dist/runtime/server/utils/context.d.ts +14 -0
  234. package/dist/runtime/server/utils/context.mjs +2 -2
  235. package/dist/runtime/server/utils/crypto.d.ts +44 -5
  236. package/dist/runtime/server/utils/crypto.mjs +18 -0
  237. package/dist/runtime/server/utils/domains.mjs +9 -5
  238. package/dist/runtime/server/utils/drizzle.d.ts +35 -3
  239. package/dist/runtime/server/utils/drizzle.mjs +115 -6
  240. package/dist/runtime/server/utils/durable-object.d.ts +106 -0
  241. package/dist/runtime/server/utils/durable-object.mjs +628 -0
  242. package/dist/runtime/server/utils/email-inbound.d.ts +29 -0
  243. package/dist/runtime/server/utils/email-inbound.mjs +76 -0
  244. package/dist/runtime/server/utils/impersonation.d.ts +32 -2
  245. package/dist/runtime/server/utils/impersonation.mjs +16 -13
  246. package/dist/runtime/server/utils/lock.d.ts +71 -0
  247. package/dist/runtime/server/utils/lock.mjs +139 -0
  248. package/dist/runtime/server/utils/mail-suppression.mjs +7 -7
  249. package/dist/runtime/server/utils/mail.d.ts +30 -19
  250. package/dist/runtime/server/utils/mcp.d.ts +44 -0
  251. package/dist/runtime/server/utils/mcp.mjs +308 -0
  252. package/dist/runtime/server/utils/notifications.d.ts +72 -7
  253. package/dist/runtime/server/utils/notifications.mjs +67 -55
  254. package/dist/runtime/server/utils/oauth.d.ts +27 -4
  255. package/dist/runtime/server/utils/organization.d.ts +63 -7
  256. package/dist/runtime/server/utils/organization.mjs +26 -21
  257. package/dist/runtime/server/utils/passwordless.d.ts +62 -33
  258. package/dist/runtime/server/utils/payments.d.ts +51 -12
  259. package/dist/runtime/server/utils/payments.mjs +472 -282
  260. package/dist/runtime/server/utils/queue.d.ts +106 -13
  261. package/dist/runtime/server/utils/queue.mjs +313 -28
  262. package/dist/runtime/server/utils/rag.d.ts +42 -14
  263. package/dist/runtime/server/utils/rag.mjs +169 -4
  264. package/dist/runtime/server/utils/ratelimit.d.ts +34 -5
  265. package/dist/runtime/server/utils/ratelimit.mjs +95 -14
  266. package/dist/runtime/server/utils/realtime.d.ts +68 -52
  267. package/dist/runtime/server/utils/scheduled-task.d.ts +42 -1
  268. package/dist/runtime/server/utils/scheduled-task.mjs +29 -0
  269. package/dist/runtime/server/utils/schema-fallback.d.ts +1 -1
  270. package/dist/runtime/server/utils/schema-fallback.mjs +1 -1
  271. package/dist/runtime/server/utils/session.d.ts +84 -10
  272. package/dist/runtime/server/utils/session.mjs +12 -10
  273. package/dist/runtime/server/utils/sse.d.ts +75 -0
  274. package/dist/runtime/server/utils/sse.mjs +147 -0
  275. package/dist/runtime/server/utils/sso.d.ts +1 -1
  276. package/dist/runtime/server/utils/storage.d.ts +53 -4
  277. package/dist/runtime/server/utils/storage.mjs +15 -11
  278. package/dist/runtime/server/utils/store-localization.d.ts +51 -0
  279. package/dist/runtime/server/utils/store-localization.mjs +417 -0
  280. package/dist/runtime/server/utils/store.d.ts +207 -0
  281. package/dist/runtime/server/utils/store.mjs +2227 -0
  282. package/dist/runtime/server/utils/table-names.d.ts +51 -0
  283. package/dist/runtime/server/utils/table-names.mjs +69 -0
  284. package/dist/runtime/server/utils/tenant.d.ts +26 -2
  285. package/dist/runtime/server/utils/tenant.mjs +16 -12
  286. package/dist/runtime/server/utils/tools-registry-fallback.d.ts +1 -0
  287. package/dist/runtime/server/utils/tools-registry-fallback.mjs +1 -0
  288. package/dist/runtime/server/utils/totp.d.ts +45 -2
  289. package/dist/runtime/server/utils/tracker.d.ts +10 -11
  290. package/dist/runtime/server/utils/turnstile.d.ts +16 -1
  291. package/dist/runtime/server/utils/workflows.d.ts +92 -0
  292. package/dist/runtime/server/utils/workflows.mjs +299 -0
  293. package/dist/runtime/server.d.ts +8 -1
  294. package/dist/runtime/server.mjs +8 -5
  295. package/dist/runtime/service.d.ts +10 -10
  296. package/dist/runtime/storage.d.ts +1 -0
  297. package/dist/runtime/storage.mjs +1 -0
  298. package/dist/runtime/store.d.ts +4 -0
  299. package/dist/runtime/store.mjs +2 -0
  300. package/dist/runtime/test-utils.d.ts +11 -10
  301. package/dist/runtime/test-utils.mjs +64 -4
  302. package/dist/runtime/types/ai.d.ts +21 -2
  303. package/dist/runtime/types/d1.d.ts +17 -0
  304. package/dist/runtime/types/drizzle.d.ts +2 -2
  305. package/dist/runtime/types/durable-object.d.ts +62 -2
  306. package/dist/runtime/types/email.d.ts +46 -0
  307. package/dist/runtime/types/imports.d.ts +6 -1
  308. package/dist/runtime/types/index.d.ts +58 -0
  309. package/dist/runtime/types/index.mjs +3 -0
  310. package/dist/runtime/types/mcp.d.ts +83 -0
  311. package/dist/runtime/types/mcp.mjs +0 -0
  312. package/dist/runtime/types/queue.d.ts +36 -0
  313. package/dist/runtime/types/r2.d.ts +41 -0
  314. package/dist/runtime/types/store.d.ts +313 -0
  315. package/dist/runtime/types/store.mjs +0 -0
  316. package/dist/runtime/types/workflows.d.ts +98 -0
  317. package/dist/runtime/types/workflows.mjs +0 -0
  318. package/dist/runtime/workflows.d.ts +5 -0
  319. package/dist/runtime/workflows.mjs +2 -0
  320. package/dist/types/ai.d.ts +721 -0
  321. package/dist/types/cms.d.ts +710 -0
  322. package/dist/types.d.ts +406 -1288
  323. package/dist/utils/auth-schema.d.ts +3 -2
  324. package/dist/utils/bots.d.ts +20 -0
  325. package/dist/utils/comments-schema.d.ts +5 -4
  326. package/dist/utils/drizzle.d.ts +83 -3
  327. package/dist/utils/durable-objects.d.ts +10 -0
  328. package/dist/utils/email-inbound.d.ts +10 -0
  329. package/dist/utils/local-db.d.ts +1 -3
  330. package/dist/utils/mcp.d.ts +24 -0
  331. package/dist/utils/notifications-schema.d.ts +5 -4
  332. package/dist/utils/payments-schema.d.ts +4 -3
  333. package/dist/utils/store-schema.d.ts +14 -0
  334. package/dist/utils/table-names.d.ts +1 -0
  335. package/dist/utils/tenants-schema.d.ts +4 -3
  336. package/dist/utils/tools.d.ts +20 -0
  337. package/dist/utils/workflows.d.ts +8 -0
  338. package/package.json +34 -4
  339. package/dist/chunks/wrangler.mjs +0 -897
  340. package/dist/runtime/app/components/AuthRegister.vue +0 -306
  341. package/dist/runtime/app/components/AuthSessionsList.vue +0 -137
  342. package/dist/runtime/app/components/AuthSignIn.vue +0 -298
  343. package/dist/runtime/app/components/CMSBookmarkButton.vue +0 -59
  344. package/dist/runtime/app/components/CMSImage.vue +0 -47
  345. package/dist/runtime/app/components/CMSLocaleSwitcher.vue +0 -110
  346. package/dist/runtime/app/components/CMSNewsletter.vue +0 -81
  347. package/dist/runtime/app/components/CMSPreviewBanner.vue +0 -83
  348. package/dist/runtime/app/components/CMSTableOfContents.vue +0 -84
  349. package/dist/runtime/app/components/CMSVersionBanner.vue +0 -53
  350. package/dist/runtime/app/components/CMSVersionSwitcher.vue +0 -140
  351. package/dist/runtime/app/components/Comments.vue +0 -411
  352. package/dist/runtime/app/components/FileUpload.vue +0 -200
  353. package/dist/runtime/app/components/ImpersonationBanner.vue +0 -61
  354. package/dist/runtime/app/components/NotificationBell.vue +0 -263
  355. package/dist/runtime/app/components/NotificationList.vue +0 -205
  356. package/dist/runtime/app/components/NotificationPrompt.vue +0 -133
  357. package/dist/runtime/app/components/PricingGated.vue +0 -81
  358. package/dist/runtime/app/components/PricingTable.vue +0 -274
  359. package/dist/runtime/app/components/RealtimeChat.vue +0 -164
  360. package/dist/runtime/app/components/RealtimePresence.vue +0 -129
  361. package/dist/runtime/app/components/RealtimeStatus.vue +0 -79
  362. package/dist/runtime/app/components/SubscriptionCard.vue +0 -207
  363. package/dist/runtime/app/components/UserProfile.vue +0 -558
@@ -1,5 +1,4 @@
1
1
  import { createError, getCookie } from "nuxt/server";
2
- import { parse as parseYaml } from "yaml";
3
2
  import { getKVBinding } from "../../kv.mjs";
4
3
  import { fireCMSWebhooks, fireCMSDeployTrigger } from "./cms-events.mjs";
5
4
  import {
@@ -7,41 +6,34 @@ import {
7
6
  nanoid,
8
7
  getCMSConfig,
9
8
  resolveCollectionApproval,
10
- computeContentHash,
11
9
  getCMSTenantId,
12
- getCMSTenantPrefix
10
+ getCMSTenantPrefix,
11
+ cmsCollectionTbl,
12
+ cmsEntryTbl,
13
+ cmsRevisionTbl,
14
+ cmsCategoryTbl
13
15
  } from "./cms/common.mjs";
16
+ import { resolveTableName } from "./table-names.mjs";
17
+ const userTbl = (e) => resolveTableName("user", e);
14
18
  import { syncEntryToGit, registerEntryFormatter } from "./cms/git.mjs";
15
19
  import {
16
20
  parseMarkdownAST,
17
21
  processMarkdown,
18
- parseFrontmatter,
19
22
  formatFrontmatter
20
23
  } from "./cms/markdown.mjs";
21
- import {
22
- stripOrderPrefix,
23
- isGroupSegment,
24
- extractGroupTitle,
25
- extractOrderPrefix,
26
- computeEntryPath,
27
- resolveCollectionForPath,
28
- extractTOC
29
- } from "./cms/path.mjs";
30
- import { registerEnsureCMSSynced } from "./cms/search.mjs";
31
- import {
32
- createComment,
33
- deleteComment,
34
- getComment,
35
- queryComments,
36
- updateCommentStatus
37
- } from "./comments.mjs";
38
- import { getSessionSecret } from "./config.mjs";
24
+ import { verifyPreviewToken } from "./cms/preview.mjs";
25
+ import { syncCMSEntryTags } from "./cms/taxonomy.mjs";
39
26
  import { getAuthContext } from "./context.mjs";
40
27
  export * from "./cms/common.mjs";
41
28
  export * from "./cms/path.mjs";
42
29
  export * from "./cms/markdown.mjs";
43
30
  export * from "./cms/git.mjs";
44
31
  export * from "./cms/search.mjs";
32
+ export * from "./cms/preview.mjs";
33
+ export * from "./cms/taxonomy.mjs";
34
+ export * from "./cms/navigation.mjs";
35
+ export * from "./cms/sync.mjs";
36
+ export * from "./cms/collections.mjs";
45
37
  export function formatEntryAsMarkdown(entry) {
46
38
  const e = entry;
47
39
  let metadata = {};
@@ -76,140 +68,6 @@ export function formatEntryAsMarkdown(entry) {
76
68
  return formatFrontmatter(fmData, body);
77
69
  }
78
70
  registerEntryFormatter(formatEntryAsMarkdown);
79
- export async function getCMSCollection(event, collectionId) {
80
- const config = getCMSConfig(event);
81
- const tenantPrefix = getCMSTenantPrefix(event);
82
- if (config.cache) {
83
- try {
84
- const kv = getKVBinding("KV", event);
85
- const cached = await kv.get(`${tenantPrefix}cms:schema:${collectionId}`, {
86
- type: "json"
87
- });
88
- if (cached) return cached;
89
- } catch {
90
- }
91
- }
92
- const db = getCMSDb(event);
93
- const row = await db.prepare("SELECT * FROM _qarpeo_cms_collections WHERE id = ?").bind(collectionId).first();
94
- if (!row) return null;
95
- const collection = rowToCollection(row);
96
- if (config.cache) {
97
- try {
98
- const kv = getKVBinding("KV", event);
99
- await kv.put(`${tenantPrefix}cms:schema:${collectionId}`, JSON.stringify(collection), {
100
- expirationTtl: 300
101
- });
102
- } catch {
103
- }
104
- }
105
- return collection;
106
- }
107
- function rowToCollection(row, config) {
108
- let fields;
109
- try {
110
- fields = JSON.parse(row.schema_json || "{}");
111
- } catch {
112
- fields = {};
113
- }
114
- const id = row.id;
115
- const resolvedConfig = config || getCMSConfig();
116
- const colCfg = resolvedConfig.collections?.[id];
117
- return {
118
- id,
119
- name: row.name,
120
- description: row.description,
121
- schemaJson: row.schema_json,
122
- fields,
123
- source: row.source,
124
- order: row.order ?? 0,
125
- singleton: colCfg?.singleton,
126
- tenantId: row.tenant_id || void 0,
127
- createdAt: row.created_at,
128
- updatedAt: row.updated_at
129
- };
130
- }
131
- export async function listCMSCollections(event) {
132
- await ensureCMSSynced(event).catch(() => {
133
- });
134
- const db = getCMSDb(event);
135
- if (db) {
136
- try {
137
- const results = await db.prepare('SELECT * FROM _qarpeo_cms_collections ORDER BY "order" ASC, name ASC').all();
138
- return (results.results || []).map(
139
- (r) => rowToCollection(r)
140
- );
141
- } catch {
142
- }
143
- }
144
- try {
145
- const { manifestCollections } = await import("#qarpeo/cms/manifest");
146
- if (manifestCollections) {
147
- return Object.entries(manifestCollections).map(([id, cfg]) => ({
148
- id,
149
- name: cfg.name || id.charAt(0).toUpperCase() + id.slice(1).replace(/-/g, " "),
150
- description: cfg.description,
151
- schemaJson: JSON.stringify(cfg.fields || {}),
152
- fields: cfg.fields || {},
153
- source: "config",
154
- order: cfg.order ?? 0,
155
- createdAt: 0,
156
- updatedAt: 0
157
- }));
158
- }
159
- } catch {
160
- }
161
- return [];
162
- }
163
- export async function createCMSCollection(event, data) {
164
- const db = getCMSDb(event);
165
- const now = Date.now();
166
- const schemaJson = JSON.stringify(data.fields || {});
167
- await db.prepare(
168
- "INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, created_at, updated_at) VALUES (?, ?, ?, ?, 'db', ?, ?)"
169
- ).bind(data.id, data.name, data.description ?? null, schemaJson, now, now).run();
170
- return {
171
- id: data.id,
172
- name: data.name,
173
- description: data.description ?? null,
174
- schemaJson,
175
- fields: data.fields,
176
- source: "db",
177
- createdAt: now,
178
- updatedAt: now
179
- };
180
- }
181
- export async function updateCMSCollection(event, id, data) {
182
- const db = getCMSDb(event);
183
- const now = Date.now();
184
- const schemaJson = JSON.stringify(data.fields || {});
185
- await db.prepare(
186
- "UPDATE _qarpeo_cms_collections SET name = COALESCE(?, name), description = COALESCE(?, description), schema_json = ?, updated_at = ? WHERE id = ?"
187
- ).bind(data.name ?? null, data.description ?? null, schemaJson, now, id).run();
188
- try {
189
- const kv = getKVBinding("KV", event);
190
- const tenantPrefix = getCMSTenantPrefix(event);
191
- await kv.delete(`${tenantPrefix}cms:schema:${id}`);
192
- } catch {
193
- }
194
- }
195
- export async function deleteCMSCollection(event, id) {
196
- const db = getCMSDb(event);
197
- const row = await db.prepare("SELECT source FROM _qarpeo_cms_collections WHERE id = ?").bind(id).first();
198
- if (!row) throw createError({ statusCode: 404, message: `Collection '${id}' not found` });
199
- if (row.source === "config") {
200
- throw createError({
201
- statusCode: 403,
202
- message: "Cannot delete a config-seeded collection from the API. Remove it from nuxt.config.ts instead."
203
- });
204
- }
205
- await db.prepare("DELETE FROM _qarpeo_cms_collections WHERE id = ?").bind(id).run();
206
- try {
207
- const kv = getKVBinding("KV", event);
208
- const tenantPrefix = getCMSTenantPrefix(event);
209
- await kv.delete(`${tenantPrefix}cms:schema:${id}`);
210
- } catch {
211
- }
212
- }
213
71
  export function projectCMSEntry(entry, fields) {
214
72
  if (!entry) return null;
215
73
  if (!fields) return entry;
@@ -223,7 +81,7 @@ export function projectCMSEntry(entry, fields) {
223
81
  }
224
82
  return projected;
225
83
  }
226
- function rowToEntry(row) {
84
+ export function rowToEntry(row) {
227
85
  let metadata;
228
86
  try {
229
87
  metadata = JSON.parse(row.metadata_json || "{}");
@@ -296,7 +154,7 @@ export async function getCollectionFields(event, collectionId) {
296
154
  let dbFields;
297
155
  try {
298
156
  const db = getCMSDb(event);
299
- const row = await db.prepare("SELECT schema_json FROM _qarpeo_cms_collections WHERE id = ?").bind(collectionId).first();
157
+ const row = await db.prepare(`SELECT schema_json FROM ${cmsCollectionTbl(event)} WHERE id = ?`).bind(collectionId).first();
300
158
  if (row?.schema_json) {
301
159
  dbFields = JSON.parse(row.schema_json);
302
160
  }
@@ -308,7 +166,7 @@ async function fetchEntryRef(event, collectionId, slugOrId) {
308
166
  const db = getCMSDb(event);
309
167
  const tenantId = getCMSTenantId(event);
310
168
  const row = await db.prepare(
311
- `SELECT id, collection_id, slug, title FROM _qarpeo_cms_entries
169
+ `SELECT id, collection_id, slug, title FROM ${cmsEntryTbl(event)}
312
170
  WHERE collection_id = ? AND (slug = ? OR id = ?)
313
171
  ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""}
314
172
  LIMIT 1`
@@ -497,7 +355,7 @@ async function populateReferenceFields(event, entry, populate) {
497
355
  const db = getCMSDb(event);
498
356
  if (db) {
499
357
  const userRow = await db.prepare(
500
- "SELECT id, name, email, image, username, avatar, role, bio FROM user WHERE id = ? LIMIT 1"
358
+ `SELECT id, name, email, image, username, avatar, role, bio FROM ${userTbl(event)} WHERE id = ? LIMIT 1`
501
359
  ).bind(resEntry.authorId).first();
502
360
  if (userRow) {
503
361
  resEntry.author = {
@@ -551,7 +409,7 @@ function serializeReferencesForFrontmatter(metadata) {
551
409
  }
552
410
  return out;
553
411
  }
554
- async function resolveReferenceFieldsFromFrontmatter(event, collectionId, fm) {
412
+ export async function resolveReferenceFieldsFromFrontmatter(event, collectionId, fm) {
555
413
  const fields = await getCollectionFields(event, collectionId);
556
414
  for (const [fieldName, fieldDef] of Object.entries(fields)) {
557
415
  if (fieldDef.type !== "reference" || !fieldDef.reference) continue;
@@ -626,6 +484,7 @@ async function setCachedEntry(event, collectionId, slugOrId, entry) {
626
484
  }
627
485
  })();
628
486
  runCMSBackgroundTask(event, task);
487
+ return task;
629
488
  }
630
489
  async function getCachedList(event, key) {
631
490
  const config = getCMSConfig(event);
@@ -651,6 +510,7 @@ async function setCachedList(event, key, data) {
651
510
  }
652
511
  })();
653
512
  runCMSBackgroundTask(event, task);
513
+ return task;
654
514
  }
655
515
  export async function invalidateCMSEntryCache(event, collectionId, slug) {
656
516
  const config = getCMSConfig(event);
@@ -659,8 +519,11 @@ export async function invalidateCMSEntryCache(event, collectionId, slug) {
659
519
  const task = (async () => {
660
520
  try {
661
521
  const kv = getKVBinding("KV", event);
662
- if (slug) {
663
- await kv.delete(`${tenantPrefix}cms:entry:${collectionId}:${slug}`);
522
+ const slugs = Array.isArray(slug) ? slug : slug ? [slug] : [];
523
+ for (const s of slugs) {
524
+ if (s) {
525
+ await kv.delete(`${tenantPrefix}cms:entry:${collectionId}:${s}`);
526
+ }
664
527
  }
665
528
  const listRes = await kv.list({ prefix: `${tenantPrefix}cms:list:${collectionId}:` });
666
529
  if (listRes?.keys?.length) {
@@ -670,6 +533,7 @@ export async function invalidateCMSEntryCache(event, collectionId, slug) {
670
533
  }
671
534
  })();
672
535
  runCMSBackgroundTask(event, task);
536
+ return task;
673
537
  }
674
538
  export async function queryCMSEntries(event, collectionId, opts = {}) {
675
539
  const status = opts.status || "published";
@@ -701,7 +565,7 @@ export async function queryCMSEntries(event, collectionId, opts = {}) {
701
565
  }
702
566
  if (opts.category) {
703
567
  conditions.push(
704
- "(category_id IN (SELECT id FROM _qarpeo_cms_categories WHERE slug = ?) OR category_id = ?)"
568
+ `(category_id IN (SELECT id FROM ${cmsCategoryTbl(event)} WHERE slug = ?) OR category_id = ?)`
705
569
  );
706
570
  binds.push(opts.category, opts.category);
707
571
  }
@@ -761,9 +625,9 @@ export async function queryCMSEntries(event, collectionId, opts = {}) {
761
625
  try {
762
626
  ;
763
627
  [countResult, dataResult] = await Promise.all([
764
- db.prepare(`SELECT COUNT(*) as total FROM _qarpeo_cms_entries ${where}`).bind(...binds).first(),
628
+ db.prepare(`SELECT COUNT(*) as total FROM ${cmsEntryTbl(event)} ${where}`).bind(...binds).first(),
765
629
  db.prepare(
766
- `SELECT * FROM _qarpeo_cms_entries ${where} ORDER BY ${safeSortField} ${safeDir} LIMIT ? OFFSET ?`
630
+ `SELECT * FROM ${cmsEntryTbl(event)} ${where} ORDER BY ${safeSortField} ${safeDir} LIMIT ? OFFSET ?`
767
631
  ).bind(...binds, limit, offset).all()
768
632
  ]);
769
633
  } catch {
@@ -825,7 +689,10 @@ export async function getCMSEntry(event, collectionId, slugOrId, opts = {}) {
825
689
  } catch {
826
690
  }
827
691
  }
828
- const isPreviewRequested = opts.preview || Boolean(cookieObj);
692
+ const isMatchingCookie = Boolean(
693
+ cookieObj && (!cookieObj.collection || cookieObj.collection === collectionId) && (!cookieObj.slug || cookieObj.slug === slugOrId)
694
+ );
695
+ const isPreviewRequested = opts.preview || isMatchingCookie;
829
696
  if (isPreviewRequested) {
830
697
  const auth = await getAuthContext(event).catch(() => null);
831
698
  const config = getCMSConfig(event);
@@ -833,8 +700,8 @@ export async function getCMSEntry(event, collectionId, slugOrId, opts = {}) {
833
700
  allowDraft = true;
834
701
  }
835
702
  if (!allowDraft) {
836
- const token = opts.previewToken || cookieObj?.token;
837
- const expires = opts.previewExpires || cookieObj?.expires;
703
+ const token = opts.previewToken || (isMatchingCookie ? cookieObj?.token : void 0);
704
+ const expires = opts.previewExpires || (isMatchingCookie ? cookieObj?.expires : void 0);
838
705
  if (token && expires) {
839
706
  allowDraft = await verifyPreviewToken(event, collectionId, slugOrId, token, expires);
840
707
  }
@@ -853,7 +720,7 @@ export async function getCMSEntry(event, collectionId, slugOrId, opts = {}) {
853
720
  if (db) {
854
721
  try {
855
722
  row = await db.prepare(
856
- `SELECT * FROM _qarpeo_cms_entries WHERE collection_id = ? AND (slug = ? OR id = ?) ${statusClause} ${tenantClause} ${statusOrder} LIMIT 1`
723
+ `SELECT * FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND (slug = ? OR id = ?) ${statusClause} ${tenantClause} ${statusOrder} LIMIT 1`
857
724
  ).bind(...binds).first();
858
725
  } catch {
859
726
  }
@@ -920,7 +787,7 @@ export async function createCMSEntry(event, collectionId, data) {
920
787
  const cmsConfig = getCMSConfig(event);
921
788
  const isSingleton = cmsConfig.collections?.[collectionId]?.singleton;
922
789
  if (isSingleton) {
923
- const existing = await db.prepare("SELECT COUNT(*) as total FROM _qarpeo_cms_entries WHERE collection_id = ?").bind(collectionId).first();
790
+ const existing = await db.prepare(`SELECT COUNT(*) as total FROM ${cmsEntryTbl(event)} WHERE collection_id = ?`).bind(collectionId).first();
924
791
  if (existing && existing.total > 0) {
925
792
  throw createError({
926
793
  statusCode: 409,
@@ -939,7 +806,7 @@ export async function createCMSEntry(event, collectionId, data) {
939
806
  const publishedAt = data.status === "published" ? data.publishedAt ?? now : data.status === "scheduled" && data.publishedAt ? data.publishedAt : data.publishedAt ?? null;
940
807
  const tenantId = getCMSTenantId(event);
941
808
  const existingSlug = await db.prepare(
942
- `SELECT id FROM _qarpeo_cms_entries WHERE collection_id = ? AND slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
809
+ `SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
943
810
  ).bind(...tenantId ? [collectionId, data.slug, tenantId] : [collectionId, data.slug]).first();
944
811
  if (existingSlug?.id) {
945
812
  throw createError({
@@ -952,7 +819,7 @@ export async function createCMSEntry(event, collectionId, data) {
952
819
  const readingTime = data.readingTime ?? metadata.readingTime ?? calculatedReadingTime;
953
820
  try {
954
821
  await db.prepare(
955
- `INSERT INTO _qarpeo_cms_entries
822
+ `INSERT INTO ${cmsEntryTbl(event)}
956
823
  (id, collection_id, slug, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, author_id, category_id, sub_category_id, featured, view_count, reading_time, published_at, created_at, updated_at, tenant_id)
957
824
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
958
825
  ).bind(
@@ -1024,7 +891,11 @@ export async function createCMSEntry(event, collectionId, data) {
1024
891
  entry.contentHash = gitResult.contentHash || null;
1025
892
  entry.source = "file";
1026
893
  }
1027
- await invalidateCMSEntryCache(event, collectionId, data.slug);
894
+ await invalidateCMSEntryCache(
895
+ event,
896
+ collectionId,
897
+ [data.slug, entry.id].filter(Boolean)
898
+ );
1028
899
  await syncCMSEntryTags(event, null, data.tags ?? null).catch(() => {
1029
900
  });
1030
901
  fireCMSWebhooks(getCMSConfig(event), collectionId, "create", entry).catch(console.warn);
@@ -1033,7 +904,7 @@ export async function createCMSEntry(event, collectionId, data) {
1033
904
  export async function updateCMSEntry(event, entryId, data) {
1034
905
  const db = getCMSDb(event);
1035
906
  const now = Date.now();
1036
- const existing = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
907
+ const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1037
908
  if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1038
909
  const tenantId = getCMSTenantId(event);
1039
910
  if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
@@ -1044,7 +915,7 @@ export async function updateCMSEntry(event, entryId, data) {
1044
915
  }
1045
916
  if (data.slug && data.slug !== existing.slug) {
1046
917
  const slugCollision = await db.prepare(
1047
- `SELECT id FROM _qarpeo_cms_entries WHERE collection_id = ? AND slug = ? AND id != ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
918
+ `SELECT id FROM ${cmsEntryTbl(event)} WHERE collection_id = ? AND slug = ? AND id != ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
1048
919
  ).bind(
1049
920
  ...tenantId ? [existing.collection_id, data.slug, entryId, tenantId] : [existing.collection_id, data.slug, entryId]
1050
921
  ).first();
@@ -1088,7 +959,7 @@ export async function updateCMSEntry(event, entryId, data) {
1088
959
  const calculatedReadingTime = Math.max(1, Math.ceil(words / 200));
1089
960
  const readingTime = data.readingTime !== void 0 ? data.readingTime : data.contentMd !== void 0 || data.content !== void 0 ? calculatedReadingTime : existing.reading_time || calculatedReadingTime;
1090
961
  await db.prepare(
1091
- "INSERT INTO _qarpeo_cms_revisions (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
962
+ `INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
1092
963
  ).bind(
1093
964
  nanoid(),
1094
965
  entryId,
@@ -1099,7 +970,7 @@ export async function updateCMSEntry(event, entryId, data) {
1099
970
  now
1100
971
  ).run();
1101
972
  await db.prepare(
1102
- `UPDATE _qarpeo_cms_entries SET
973
+ `UPDATE ${cmsEntryTbl(event)} SET
1103
974
  slug = COALESCE(?, slug), title = COALESCE(?, title),
1104
975
  description = COALESCE(?, description), cover_image = COALESCE(?, cover_image),
1105
976
  tags = COALESCE(?, tags), "order" = COALESCE(?, "order"),
@@ -1136,7 +1007,7 @@ export async function updateCMSEntry(event, entryId, data) {
1136
1007
  const config = getCMSConfig(event);
1137
1008
  const maxRevisions = typeof config.revisions === "object" ? config.revisions.max ?? 10 : 10;
1138
1009
  await pruneRevisions(event, entryId, maxRevisions);
1139
- const updated = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1010
+ const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1140
1011
  const updatedEntry = rowToEntry(updated);
1141
1012
  const gitResult = await syncEntryToGit(event, updatedEntry.collectionId, updatedEntry, "update");
1142
1013
  if (gitResult?.filePath) {
@@ -1144,7 +1015,16 @@ export async function updateCMSEntry(event, entryId, data) {
1144
1015
  updatedEntry.contentHash = gitResult.contentHash || null;
1145
1016
  updatedEntry.source = "file";
1146
1017
  }
1147
- await invalidateCMSEntryCache(event, updatedEntry.collectionId, updatedEntry.slug);
1018
+ await invalidateCMSEntryCache(
1019
+ event,
1020
+ updatedEntry.collectionId,
1021
+ [
1022
+ updatedEntry.slug,
1023
+ updatedEntry.id,
1024
+ existing.slug,
1025
+ existing.id
1026
+ ].filter(Boolean)
1027
+ );
1148
1028
  await syncCMSEntryTags(
1149
1029
  event,
1150
1030
  existing.tags,
@@ -1164,7 +1044,7 @@ async function nullifyOrphanedReferences(event, deletedEntryId) {
1164
1044
  const searchPattern = `%"${deletedEntryId}"%`;
1165
1045
  const binds = tenantId ? [searchPattern, tenantId] : [searchPattern];
1166
1046
  const rows = (await db.prepare(
1167
- `SELECT id, collection_id, slug, metadata_json FROM _qarpeo_cms_entries
1047
+ `SELECT id, collection_id, slug, metadata_json FROM ${cmsEntryTbl(event)}
1168
1048
  WHERE json_extract(metadata_json, '$') IS NOT NULL
1169
1049
  AND metadata_json LIKE ?${tenantClause}`
1170
1050
  ).bind(...binds).all()).results;
@@ -1191,7 +1071,7 @@ async function nullifyOrphanedReferences(event, deletedEntryId) {
1191
1071
  }
1192
1072
  }
1193
1073
  if (changed) {
1194
- await db.prepare("UPDATE _qarpeo_cms_entries SET metadata_json = ? WHERE id = ?").bind(JSON.stringify(meta), row.id).run();
1074
+ await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET metadata_json = ? WHERE id = ?`).bind(JSON.stringify(meta), row.id).run();
1195
1075
  await invalidateCMSEntryCache(event, row.collection_id, row.slug);
1196
1076
  }
1197
1077
  }
@@ -1201,7 +1081,7 @@ async function nullifyOrphanedReferences(event, deletedEntryId) {
1201
1081
  }
1202
1082
  export async function deleteCMSEntry(event, entryId) {
1203
1083
  const db = getCMSDb(event);
1204
- const existing = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1084
+ const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1205
1085
  if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1206
1086
  const tenantId = getCMSTenantId(event);
1207
1087
  if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
@@ -1211,14 +1091,18 @@ export async function deleteCMSEntry(event, entryId) {
1211
1091
  });
1212
1092
  }
1213
1093
  await db.batch([
1214
- db.prepare("DELETE FROM _qarpeo_cms_revisions WHERE entry_id = ?").bind(entryId),
1215
- db.prepare("DELETE FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId)
1094
+ db.prepare(`DELETE FROM ${cmsRevisionTbl(event)} WHERE entry_id = ?`).bind(entryId),
1095
+ db.prepare(`DELETE FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId)
1216
1096
  ]);
1217
1097
  if (existing) {
1218
1098
  await nullifyOrphanedReferences(event, entryId);
1219
1099
  await syncCMSEntryTags(event, existing.tags, null).catch(() => {
1220
1100
  });
1221
- await invalidateCMSEntryCache(event, existing.collection_id, existing.slug);
1101
+ await invalidateCMSEntryCache(
1102
+ event,
1103
+ existing.collection_id,
1104
+ [existing.slug, existing.id].filter(Boolean)
1105
+ );
1222
1106
  await syncEntryToGit(
1223
1107
  event,
1224
1108
  existing.collection_id,
@@ -1236,7 +1120,7 @@ export async function deleteCMSEntry(event, entryId) {
1236
1120
  export async function publishCMSEntry(event, entryId, targetStatus, targetPublishedAt) {
1237
1121
  const db = getCMSDb(event);
1238
1122
  const now = Date.now();
1239
- const existing = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1123
+ const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1240
1124
  if (!existing) {
1241
1125
  throw createError({ statusCode: 404, message: "Entry not found" });
1242
1126
  }
@@ -1283,11 +1167,21 @@ export async function publishCMSEntry(event, entryId, targetStatus, targetPublis
1283
1167
  metadataJson = JSON.stringify(metaObj);
1284
1168
  }
1285
1169
  await db.prepare(
1286
- "UPDATE _qarpeo_cms_entries SET status = ?, published_at = ?, metadata_json = ?, updated_at = ? WHERE id = ?"
1170
+ `UPDATE ${cmsEntryTbl(event)} SET status = ?, published_at = ?, metadata_json = ?, updated_at = ? WHERE id = ?`
1287
1171
  ).bind(targetStatus, publishedAt, metadataJson, now, entryId).run();
1288
- const updatedRow = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1172
+ const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1289
1173
  if (updatedRow) {
1290
1174
  const updated = rowToEntry(updatedRow);
1175
+ await invalidateCMSEntryCache(
1176
+ event,
1177
+ collectionId,
1178
+ [
1179
+ updated.slug,
1180
+ updated.id,
1181
+ existing.slug,
1182
+ existing.id
1183
+ ].filter(Boolean)
1184
+ );
1291
1185
  await syncEntryToGit(
1292
1186
  event,
1293
1187
  updated.collectionId,
@@ -1313,18 +1207,28 @@ export async function publishDueScheduledEntries(event) {
1313
1207
  const now = Date.now();
1314
1208
  const config = getCMSConfig(event);
1315
1209
  const rows = await db.prepare(
1316
- "SELECT * FROM _qarpeo_cms_entries WHERE status = 'scheduled' AND published_at IS NOT NULL AND published_at <= ?"
1210
+ `SELECT * FROM ${cmsEntryTbl(event)} WHERE status = 'scheduled' AND published_at IS NOT NULL AND published_at <= ?`
1317
1211
  ).bind(now).all();
1318
1212
  const entriesToPublish = rows.results || [];
1319
1213
  const publishedEntries = [];
1320
1214
  for (const row of entriesToPublish) {
1321
1215
  const entryId = row.id;
1322
1216
  const collectionId = row.collection_id;
1323
- await db.prepare("UPDATE _qarpeo_cms_entries SET status = 'published', updated_at = ? WHERE id = ?").bind(now, entryId).run();
1324
- const updatedRow = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1217
+ await db.prepare(`UPDATE ${cmsEntryTbl(event)} SET status = 'published', updated_at = ? WHERE id = ?`).bind(now, entryId).run();
1218
+ const updatedRow = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1325
1219
  if (updatedRow) {
1326
1220
  const entry = rowToEntry(updatedRow);
1327
1221
  publishedEntries.push(entry);
1222
+ await invalidateCMSEntryCache(
1223
+ event,
1224
+ collectionId,
1225
+ [
1226
+ entry.slug,
1227
+ entry.id,
1228
+ row.slug,
1229
+ row.id
1230
+ ].filter(Boolean)
1231
+ );
1328
1232
  await syncEntryToGit(event, collectionId, entry, "publish").catch(console.warn);
1329
1233
  fireCMSWebhooks(config, collectionId, "publish", entry).catch(console.warn);
1330
1234
  fireCMSDeployTrigger(config, collectionId, "publish").catch(console.warn);
@@ -1335,7 +1239,7 @@ export async function publishDueScheduledEntries(event) {
1335
1239
  export async function submitCMSEntryForReview(event, entryId, note) {
1336
1240
  const db = getCMSDb(event);
1337
1241
  const now = Date.now();
1338
- const existing = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1242
+ const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1339
1243
  if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1340
1244
  const tenantId = getCMSTenantId(event);
1341
1245
  if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
@@ -1359,7 +1263,7 @@ export async function submitCMSEntryForReview(event, entryId, note) {
1359
1263
  };
1360
1264
  const metadataJson = JSON.stringify(metaObj);
1361
1265
  await db.prepare(
1362
- "INSERT INTO _qarpeo_cms_revisions (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
1266
+ `INSERT INTO ${cmsRevisionTbl(event)} (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`
1363
1267
  ).bind(
1364
1268
  nanoid(),
1365
1269
  entryId,
@@ -1370,15 +1274,15 @@ export async function submitCMSEntryForReview(event, entryId, note) {
1370
1274
  now
1371
1275
  ).run();
1372
1276
  await db.prepare(
1373
- "UPDATE _qarpeo_cms_entries SET status = 'pending_review', metadata_json = ?, updated_at = ? WHERE id = ?"
1277
+ `UPDATE ${cmsEntryTbl(event)} SET status = 'pending_review', metadata_json = ?, updated_at = ? WHERE id = ?`
1374
1278
  ).bind(metadataJson, now, entryId).run();
1375
- const updated = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1279
+ const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1376
1280
  return rowToEntry(updated);
1377
1281
  }
1378
1282
  export async function rejectCMSEntryReview(event, entryId, reason) {
1379
1283
  const db = getCMSDb(event);
1380
1284
  const now = Date.now();
1381
- const existing = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1285
+ const existing = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1382
1286
  if (!existing) throw createError({ statusCode: 404, message: "Entry not found" });
1383
1287
  const tenantId = getCMSTenantId(event);
1384
1288
  if (tenantId && existing.tenant_id && existing.tenant_id !== tenantId) {
@@ -1416,16 +1320,16 @@ export async function rejectCMSEntryReview(event, entryId, reason) {
1416
1320
  };
1417
1321
  const metadataJson = JSON.stringify(metaObj);
1418
1322
  await db.prepare(
1419
- "UPDATE _qarpeo_cms_entries SET status = 'draft', metadata_json = ?, updated_at = ? WHERE id = ?"
1323
+ `UPDATE ${cmsEntryTbl(event)} SET status = 'draft', metadata_json = ?, updated_at = ? WHERE id = ?`
1420
1324
  ).bind(metadataJson, now, entryId).run();
1421
- const updated = await db.prepare("SELECT * FROM _qarpeo_cms_entries WHERE id = ?").bind(entryId).first();
1325
+ const updated = await db.prepare(`SELECT * FROM ${cmsEntryTbl(event)} WHERE id = ?`).bind(entryId).first();
1422
1326
  return rowToEntry(updated);
1423
1327
  }
1424
1328
  export async function pruneRevisions(event, entryId, max) {
1425
1329
  const db = getCMSDb(event);
1426
1330
  await db.prepare(
1427
- `DELETE FROM _qarpeo_cms_revisions WHERE entry_id = ? AND id NOT IN (
1428
- SELECT id FROM _qarpeo_cms_revisions WHERE entry_id = ? ORDER BY created_at DESC LIMIT ?
1331
+ `DELETE FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? AND id NOT IN (
1332
+ SELECT id FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? ORDER BY created_at DESC LIMIT ?
1429
1333
  )`
1430
1334
  ).bind(entryId, entryId, max).run();
1431
1335
  }
@@ -1433,7 +1337,7 @@ export async function listCMSRevisions(event, entryId) {
1433
1337
  const db = getCMSDb(event);
1434
1338
  if (!db) return [];
1435
1339
  const res = await db.prepare(
1436
- "SELECT id, entry_id as entryId, title, content_md as contentMd, metadata_json as metadataJson, author_id as authorId, created_at as createdAt FROM _qarpeo_cms_revisions WHERE entry_id = ? ORDER BY created_at DESC"
1340
+ `SELECT id, entry_id as entryId, title, content_md as contentMd, metadata_json as metadataJson, author_id as authorId, created_at as createdAt FROM ${cmsRevisionTbl(event)} WHERE entry_id = ? ORDER BY created_at DESC`
1437
1341
  ).bind(entryId).all().catch(() => ({ results: [] }));
1438
1342
  return res?.results || [];
1439
1343
  }
@@ -1442,7 +1346,7 @@ export async function restoreCMSRevision(event, entryId, revisionId) {
1442
1346
  if (!db) throw createError({ statusCode: 500, message: "Database not available" });
1443
1347
  const tenantId = getCMSTenantId(event);
1444
1348
  const entryCheck = await db.prepare(
1445
- `SELECT id FROM _qarpeo_cms_entries WHERE id = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
1349
+ `SELECT id FROM ${cmsEntryTbl(event)} WHERE id = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
1446
1350
  ).bind(...tenantId ? [entryId, tenantId] : [entryId]).first();
1447
1351
  if (!entryCheck?.id) {
1448
1352
  throw createError({
@@ -1450,7 +1354,7 @@ export async function restoreCMSRevision(event, entryId, revisionId) {
1450
1354
  message: `Entry '${entryId}' not found`
1451
1355
  });
1452
1356
  }
1453
- const rev = await db.prepare("SELECT * FROM _qarpeo_cms_revisions WHERE id = ? AND entry_id = ?").bind(revisionId, entryId).first();
1357
+ const rev = await db.prepare(`SELECT * FROM ${cmsRevisionTbl(event)} WHERE id = ? AND entry_id = ?`).bind(revisionId, entryId).first();
1454
1358
  if (!rev) {
1455
1359
  throw createError({
1456
1360
  statusCode: 404,
@@ -1471,2149 +1375,3 @@ export async function restoreCMSRevision(event, entryId, revisionId) {
1471
1375
  metadata: meta
1472
1376
  });
1473
1377
  }
1474
- async function getCMSSecret(event) {
1475
- const secret = getSessionSecret(event);
1476
- const enc = new TextEncoder();
1477
- return crypto.subtle.importKey(
1478
- "raw",
1479
- enc.encode(secret),
1480
- { name: "HMAC", hash: "SHA-256" },
1481
- false,
1482
- ["sign", "verify"]
1483
- );
1484
- }
1485
- export async function generatePreviewToken(event, collection, slugOrId, ttlMs = 24 * 60 * 60 * 1e3) {
1486
- const expires = Date.now() + ttlMs;
1487
- const key = await getCMSSecret(event);
1488
- const msg = new TextEncoder().encode(`${collection}:${slugOrId}:${expires}`);
1489
- const sig = await crypto.subtle.sign("HMAC", key, msg);
1490
- const token = btoa(String.fromCharCode(...new Uint8Array(sig)));
1491
- return { token, expires };
1492
- }
1493
- export async function verifyPreviewToken(event, collection, slugOrId, token, expiresStr) {
1494
- try {
1495
- const expires = typeof expiresStr === "number" ? expiresStr : parseInt(String(expiresStr), 10);
1496
- if (Number.isNaN(expires) || Date.now() > expires) return false;
1497
- const key = await getCMSSecret(event);
1498
- const sigBytes = Uint8Array.from(atob(token), (c) => c.charCodeAt(0));
1499
- const msg = new TextEncoder().encode(`${collection}:${slugOrId}:${expires}`);
1500
- const isValid = await crypto.subtle.verify("HMAC", key, sigBytes, msg);
1501
- if (isValid) return true;
1502
- try {
1503
- const db = getCMSDb(event);
1504
- const row = await db.prepare(
1505
- "SELECT id, slug FROM _qarpeo_cms_entries WHERE collection_id = ? AND (id = ? OR slug = ?) LIMIT 1"
1506
- ).bind(collection, slugOrId, slugOrId).first();
1507
- if (row) {
1508
- const alt = row.id === slugOrId ? row.slug : row.id;
1509
- if (alt) {
1510
- const altMsg = new TextEncoder().encode(`${collection}:${alt}:${expires}`);
1511
- return await crypto.subtle.verify("HMAC", key, sigBytes, altMsg);
1512
- }
1513
- }
1514
- } catch {
1515
- }
1516
- return false;
1517
- } catch {
1518
- return false;
1519
- }
1520
- }
1521
- let ensureCMSTablesPromise = null;
1522
- export async function ensureCMSTables(event) {
1523
- const db = getCMSDb(event);
1524
- if (!db) return;
1525
- if (!ensureCMSTablesPromise) {
1526
- ensureCMSTablesPromise = (async () => {
1527
- const tableStatements = [
1528
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_collections (id TEXT PRIMARY KEY, tenant_id TEXT, name TEXT NOT NULL, description TEXT, schema_json TEXT NOT NULL DEFAULT '{}', source TEXT NOT NULL DEFAULT 'db', "order" INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`,
1529
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_entries (id TEXT PRIMARY KEY, tenant_id TEXT, collection_id TEXT NOT NULL, slug TEXT NOT NULL, title TEXT NOT NULL, description TEXT, cover_image TEXT, tags TEXT, "order" INTEGER NOT NULL DEFAULT 0, content_md TEXT NOT NULL DEFAULT '', content_html TEXT NOT NULL DEFAULT '', metadata_json TEXT DEFAULT '{}', status TEXT NOT NULL DEFAULT 'draft', source TEXT NOT NULL DEFAULT 'db', path TEXT, file_path TEXT, content_hash TEXT, author_id TEXT, category_id TEXT, sub_category_id TEXT, featured INTEGER NOT NULL DEFAULT 0, view_count INTEGER NOT NULL DEFAULT 0, reading_time INTEGER, locale TEXT NOT NULL DEFAULT 'en', version TEXT NOT NULL DEFAULT 'latest', published_at INTEGER, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`,
1530
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_revisions (id TEXT PRIMARY KEY, entry_id TEXT NOT NULL, title TEXT NOT NULL, content_md TEXT NOT NULL, metadata_json TEXT DEFAULT '{}', author_id TEXT, created_at INTEGER NOT NULL);`,
1531
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_categories (id TEXT PRIMARY KEY, tenant_id TEXT, name TEXT NOT NULL, slug TEXT NOT NULL, description TEXT, icon TEXT, parent_id TEXT, "order" INTEGER NOT NULL DEFAULT 0, metadata_json TEXT DEFAULT '{}', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`,
1532
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_tags (id TEXT PRIMARY KEY, tenant_id TEXT, name TEXT NOT NULL, slug TEXT NOT NULL, description TEXT, count INTEGER NOT NULL DEFAULT 0, metadata_json TEXT DEFAULT '{}', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`,
1533
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_comments (id TEXT PRIMARY KEY, tenant_id TEXT, entry_id TEXT NOT NULL, parent_id TEXT, author_name TEXT NOT NULL, author_email TEXT, author_avatar TEXT, content TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', metadata_json TEXT DEFAULT '{}', created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`,
1534
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_bookmarks (id TEXT PRIMARY KEY, tenant_id TEXT, user_id TEXT NOT NULL, entry_id TEXT NOT NULL, created_at INTEGER NOT NULL);`,
1535
- `CREATE TABLE IF NOT EXISTS _qarpeo_cms_subscribers (id TEXT PRIMARY KEY, tenant_id TEXT, email TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', source TEXT DEFAULT 'website', created_at INTEGER NOT NULL);`
1536
- ];
1537
- for (const sql of tableStatements) {
1538
- try {
1539
- await db.exec(sql);
1540
- } catch (err) {
1541
- console.warn("[qarpeo:cms] ensureCMSTables warning on table creation:", sql, err);
1542
- }
1543
- }
1544
- const columnMigrations = [
1545
- // _qarpeo_cms_entries
1546
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN tenant_id TEXT;",
1547
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN path TEXT;",
1548
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN file_path TEXT;",
1549
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN content_hash TEXT;",
1550
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN author_id TEXT;",
1551
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN category_id TEXT;",
1552
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN sub_category_id TEXT;",
1553
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN featured INTEGER NOT NULL DEFAULT 0;",
1554
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN view_count INTEGER NOT NULL DEFAULT 0;",
1555
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN reading_time INTEGER;",
1556
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN locale TEXT NOT NULL DEFAULT 'en';",
1557
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN version TEXT NOT NULL DEFAULT 'latest';",
1558
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN published_at INTEGER;",
1559
- 'ALTER TABLE _qarpeo_cms_entries ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0;',
1560
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN cover_image TEXT;",
1561
- "ALTER TABLE _qarpeo_cms_entries ADD COLUMN tags TEXT;",
1562
- // _qarpeo_cms_collections
1563
- "ALTER TABLE _qarpeo_cms_collections ADD COLUMN tenant_id TEXT;",
1564
- 'ALTER TABLE _qarpeo_cms_collections ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0;',
1565
- "ALTER TABLE _qarpeo_cms_collections ADD COLUMN source TEXT NOT NULL DEFAULT 'db';",
1566
- // _qarpeo_cms_categories
1567
- "ALTER TABLE _qarpeo_cms_categories ADD COLUMN tenant_id TEXT;",
1568
- 'ALTER TABLE _qarpeo_cms_categories ADD COLUMN "order" INTEGER NOT NULL DEFAULT 0;',
1569
- // _qarpeo_cms_tags
1570
- "ALTER TABLE _qarpeo_cms_tags ADD COLUMN tenant_id TEXT;",
1571
- // _qarpeo_cms_comments
1572
- "ALTER TABLE _qarpeo_cms_comments ADD COLUMN tenant_id TEXT;",
1573
- // _qarpeo_cms_bookmarks
1574
- "ALTER TABLE _qarpeo_cms_bookmarks ADD COLUMN tenant_id TEXT;",
1575
- // _qarpeo_cms_subscribers
1576
- "ALTER TABLE _qarpeo_cms_subscribers ADD COLUMN tenant_id TEXT;"
1577
- ];
1578
- for (const alterSql of columnMigrations) {
1579
- try {
1580
- await db.exec(alterSql);
1581
- } catch {
1582
- }
1583
- }
1584
- const indexStatements = [
1585
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_collection_idx ON _qarpeo_cms_entries(collection_id);`,
1586
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_tenant_idx ON _qarpeo_cms_entries(tenant_id, collection_id);`,
1587
- `CREATE UNIQUE INDEX IF NOT EXISTS _qarpeo_cms_entries_slug_idx ON _qarpeo_cms_entries(COALESCE(tenant_id,''), collection_id, slug);`,
1588
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_status_idx ON _qarpeo_cms_entries(status);`,
1589
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_order_idx ON _qarpeo_cms_entries(collection_id, "order");`,
1590
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_path_idx ON _qarpeo_cms_entries(collection_id, path);`,
1591
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_locale_idx ON _qarpeo_cms_entries(collection_id, locale);`,
1592
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_path_locale_idx ON _qarpeo_cms_entries(path, locale);`,
1593
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_version_idx ON _qarpeo_cms_entries(collection_id, version);`,
1594
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_path_version_idx ON _qarpeo_cms_entries(path, version);`,
1595
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_published_at_idx ON _qarpeo_cms_entries(published_at);`,
1596
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_list_idx ON _qarpeo_cms_entries(collection_id, status, published_at);`,
1597
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_category_idx ON _qarpeo_cms_entries(collection_id, category_id);`,
1598
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_entries_featured_idx ON _qarpeo_cms_entries(collection_id, featured);`,
1599
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_revisions_entry_idx ON _qarpeo_cms_revisions(entry_id, created_at);`,
1600
- `CREATE UNIQUE INDEX IF NOT EXISTS _qarpeo_cms_categories_slug_idx ON _qarpeo_cms_categories(COALESCE(tenant_id,''), slug);`,
1601
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_categories_parent_idx ON _qarpeo_cms_categories(parent_id);`,
1602
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_categories_tenant_idx ON _qarpeo_cms_categories(tenant_id);`,
1603
- `CREATE UNIQUE INDEX IF NOT EXISTS _qarpeo_cms_tags_slug_idx ON _qarpeo_cms_tags(COALESCE(tenant_id,''), slug);`,
1604
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_tags_tenant_idx ON _qarpeo_cms_tags(tenant_id);`,
1605
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_comments_entry_idx ON _qarpeo_cms_comments(entry_id, status);`,
1606
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_comments_parent_idx ON _qarpeo_cms_comments(parent_id);`,
1607
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_comments_status_idx ON _qarpeo_cms_comments(status);`,
1608
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_comments_tenant_idx ON _qarpeo_cms_comments(tenant_id);`,
1609
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_bookmarks_user_idx ON _qarpeo_cms_bookmarks(user_id);`,
1610
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_bookmarks_entry_idx ON _qarpeo_cms_bookmarks(entry_id);`,
1611
- `CREATE UNIQUE INDEX IF NOT EXISTS _qarpeo_cms_bookmarks_unique_idx ON _qarpeo_cms_bookmarks(COALESCE(tenant_id,''), user_id, entry_id);`,
1612
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_subscribers_email_idx ON _qarpeo_cms_subscribers(email);`,
1613
- `CREATE UNIQUE INDEX IF NOT EXISTS _qarpeo_cms_subscribers_unique_email_idx ON _qarpeo_cms_subscribers(COALESCE(tenant_id,''), email);`,
1614
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_subscribers_status_idx ON _qarpeo_cms_subscribers(status);`,
1615
- `CREATE INDEX IF NOT EXISTS _qarpeo_cms_subscribers_tenant_idx ON _qarpeo_cms_subscribers(tenant_id);`
1616
- ];
1617
- for (const sql of indexStatements) {
1618
- try {
1619
- await db.exec(sql);
1620
- } catch (err) {
1621
- console.warn("[qarpeo:cms] ensureCMSTables warning on index creation:", sql, err);
1622
- }
1623
- }
1624
- try {
1625
- await db.exec(
1626
- "CREATE VIRTUAL TABLE IF NOT EXISTS _qarpeo_cms_entries_fts USING fts5(id UNINDEXED, slug, title, description, content_md, tags, tokenize = 'unicode61');"
1627
- );
1628
- } catch (err) {
1629
- console.warn("[qarpeo:cms] ensureCMSTables FTS virtual table notice:", err);
1630
- }
1631
- try {
1632
- await db.exec(
1633
- "CREATE TRIGGER IF NOT EXISTS _qarpeo_cms_entries_fts_ai AFTER INSERT ON _qarpeo_cms_entries BEGIN INSERT INTO _qarpeo_cms_entries_fts(id, slug, title, description, content_md, tags) VALUES (new.id, new.slug, new.title, coalesce(new.description, ''), new.content_md, coalesce(new.tags, '')); END;"
1634
- );
1635
- } catch {
1636
- }
1637
- try {
1638
- await db.exec(
1639
- "CREATE TRIGGER IF NOT EXISTS _qarpeo_cms_entries_fts_ad AFTER DELETE ON _qarpeo_cms_entries BEGIN DELETE FROM _qarpeo_cms_entries_fts WHERE id = old.id; END;"
1640
- );
1641
- } catch {
1642
- }
1643
- try {
1644
- await db.exec(
1645
- "CREATE TRIGGER IF NOT EXISTS _qarpeo_cms_entries_fts_au AFTER UPDATE ON _qarpeo_cms_entries BEGIN DELETE FROM _qarpeo_cms_entries_fts WHERE id = old.id; INSERT INTO _qarpeo_cms_entries_fts(id, slug, title, description, content_md, tags) VALUES (new.id, new.slug, new.title, coalesce(new.description, ''), new.content_md, coalesce(new.tags, '')); END;"
1646
- );
1647
- } catch {
1648
- }
1649
- try {
1650
- await db.exec(
1651
- "INSERT INTO _qarpeo_cms_entries_fts(id, slug, title, description, content_md, tags) SELECT e.id, e.slug, e.title, coalesce(e.description, ''), e.content_md, coalesce(e.tags, '') FROM _qarpeo_cms_entries e WHERE NOT EXISTS (SELECT 1 FROM _qarpeo_cms_entries_fts fts WHERE fts.id = e.id);"
1652
- );
1653
- } catch {
1654
- }
1655
- return event;
1656
- })().catch((err) => {
1657
- ensureCMSTablesPromise = null;
1658
- throw err;
1659
- });
1660
- }
1661
- return ensureCMSTablesPromise;
1662
- }
1663
- let lastSyncTime = 0;
1664
- let syncPromise = null;
1665
- let hasInitialSynced = false;
1666
- async function _runCMSSync(event) {
1667
- try {
1668
- if (!globalThis.__QARPEO_DEV_ENV__) {
1669
- try {
1670
- const { getOrInitDevProxy } = await import("./dev-proxy.mjs");
1671
- const proxy = await getOrInitDevProxy();
1672
- if (proxy?.env) {
1673
- ;
1674
- globalThis.__QARPEO_DEV_ENV__ = proxy.env;
1675
- }
1676
- } catch (proxyErr) {
1677
- console.warn("[qarpeo:cms] Could not init dev proxy in ensureCMSSynced:", proxyErr);
1678
- }
1679
- }
1680
- await ensureCMSTables(event);
1681
- const config = getCMSConfig(event);
1682
- await seedCollectionsFromConfig(event, config.collections);
1683
- await syncLocalContentFiles(
1684
- event,
1685
- config.contentDir,
1686
- config.collections,
1687
- config.sources
1688
- );
1689
- } catch (err) {
1690
- console.error("[qarpeo:cms] Auto-sync failed:", err);
1691
- }
1692
- }
1693
- let prodTablesChecked = false;
1694
- export async function ensureCMSSynced(event) {
1695
- const db = getCMSDb(event);
1696
- if (!db) return;
1697
- if (process.env.NODE_ENV !== "production" || import.meta.dev) {
1698
- if (!hasInitialSynced) {
1699
- if (!syncPromise) {
1700
- syncPromise = _runCMSSync(event).finally(() => {
1701
- hasInitialSynced = true;
1702
- lastSyncTime = Date.now();
1703
- syncPromise = null;
1704
- });
1705
- }
1706
- await syncPromise;
1707
- return;
1708
- }
1709
- if (syncPromise) {
1710
- await syncPromise;
1711
- return;
1712
- }
1713
- const now = Date.now();
1714
- if (now - lastSyncTime > 3e4) {
1715
- lastSyncTime = now;
1716
- syncPromise = _runCMSSync(event).finally(() => {
1717
- syncPromise = null;
1718
- });
1719
- await syncPromise;
1720
- }
1721
- } else {
1722
- if (!prodTablesChecked) {
1723
- prodTablesChecked = true;
1724
- try {
1725
- await ensureCMSTables(event);
1726
- try {
1727
- const { manifestEntries, manifestCollections } = await import("#qarpeo/cms/manifest");
1728
- if (manifestCollections && Object.keys(manifestCollections).length > 0) {
1729
- await seedCollectionsFromConfig(event, manifestCollections);
1730
- }
1731
- if (manifestEntries && manifestEntries.length > 0) {
1732
- await seedEntriesIntoDb(event, manifestEntries, manifestCollections);
1733
- }
1734
- } catch {
1735
- }
1736
- } catch (err) {
1737
- console.warn("[qarpeo:cms] Production ensureCMSTables check failed:", err);
1738
- }
1739
- }
1740
- }
1741
- }
1742
- registerEnsureCMSSynced(ensureCMSSynced);
1743
- export async function seedCollectionsFromConfig(event, collectionsConfig) {
1744
- const db = getCMSDb(event);
1745
- const now = Date.now();
1746
- for (const [id, cfg] of Object.entries(collectionsConfig)) {
1747
- const schemaJson = JSON.stringify(cfg.fields || {});
1748
- const colName = cfg.name || id.charAt(0).toUpperCase() + id.slice(1).replace(/-/g, " ");
1749
- const existing = await db.prepare("SELECT id, source, schema_json FROM _qarpeo_cms_collections WHERE id = ?").bind(id).first();
1750
- if (!existing) {
1751
- await db.prepare(
1752
- `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, ?, 'config', ?, ?, ?)`
1753
- ).bind(id, colName, cfg.description ?? null, schemaJson, cfg.order ?? 0, now, now).run();
1754
- } else if (existing.source === "config" && existing.schema_json !== schemaJson) {
1755
- await db.prepare(
1756
- 'UPDATE _qarpeo_cms_collections SET name = ?, description = ?, schema_json = ?, "order" = ?, updated_at = ? WHERE id = ?'
1757
- ).bind(colName, cfg.description ?? null, schemaJson, cfg.order ?? 0, now, id).run();
1758
- try {
1759
- const kv = getKVBinding("KV", event);
1760
- const tenantPrefix = getCMSTenantPrefix(event);
1761
- await kv.delete(`${tenantPrefix}cms:schema:${id}`);
1762
- } catch {
1763
- }
1764
- }
1765
- }
1766
- }
1767
- export async function seedEntriesIntoDb(event, entries, collectionsConfig = {}) {
1768
- const db = getCMSDb(event);
1769
- let synced = 0;
1770
- let skipped = 0;
1771
- let inserted = 0;
1772
- const now = Date.now();
1773
- for (const entry of entries) {
1774
- const colId = entry.collection_id;
1775
- const colConfig = collectionsConfig[colId] || {};
1776
- const mode = colConfig.mode || "db";
1777
- try {
1778
- const existingCol = await db.prepare("SELECT id FROM _qarpeo_cms_collections WHERE id = ?").bind(colId).first();
1779
- if (!existingCol) {
1780
- const colName = colConfig.name || colId.charAt(0).toUpperCase() + colId.slice(1).replace(/-/g, " ");
1781
- await db.prepare(
1782
- `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, '{}', 'config', ?, ?, ?)`
1783
- ).bind(colId, colName, `Collection ${colName}`, colConfig.order ?? 0, now, now).run();
1784
- }
1785
- } catch {
1786
- }
1787
- const existing = await db.prepare(
1788
- "SELECT id, source, content_hash, metadata_json, file_path, status FROM _qarpeo_cms_entries WHERE collection_id = ? AND path = ?"
1789
- ).bind(colId, entry.path).first();
1790
- if (!existing) {
1791
- const id = entry.id || nanoid();
1792
- await db.prepare(
1793
- `INSERT INTO _qarpeo_cms_entries
1794
- (id, collection_id, slug, path, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
1795
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'file', ?, ?, ?, ?, ?)`
1796
- ).bind(
1797
- id,
1798
- colId,
1799
- entry.slug,
1800
- entry.path,
1801
- entry.title,
1802
- entry.description ?? null,
1803
- entry.cover_image ?? null,
1804
- entry.tags ?? null,
1805
- entry.order ?? 0,
1806
- entry.content_md ?? "",
1807
- entry.content_html ?? "",
1808
- entry.metadata_json ?? "{}",
1809
- entry.status ?? "published",
1810
- entry.file_path ?? "",
1811
- entry.content_hash ?? "",
1812
- entry.status === "draft" ? null : now,
1813
- now,
1814
- now
1815
- ).run();
1816
- inserted++;
1817
- } else {
1818
- if (mode === "file") {
1819
- if (existing.content_hash !== entry.content_hash || existing.metadata_json !== entry.metadata_json || existing.status !== entry.status) {
1820
- await db.prepare(
1821
- `UPDATE _qarpeo_cms_entries SET
1822
- status = ?, slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
1823
- content_md = ?, content_html = ?, metadata_json = ?,
1824
- file_path = ?, content_hash = ?, source = 'file', updated_at = ?
1825
- WHERE id = ?`
1826
- ).bind(
1827
- entry.status ?? "published",
1828
- entry.slug,
1829
- entry.path,
1830
- entry.title,
1831
- entry.description ?? null,
1832
- entry.cover_image ?? null,
1833
- entry.tags ?? null,
1834
- entry.order ?? 0,
1835
- entry.content_md ?? "",
1836
- entry.content_html ?? "",
1837
- entry.metadata_json ?? "{}",
1838
- entry.file_path ?? "",
1839
- entry.content_hash ?? "",
1840
- now,
1841
- existing.id
1842
- ).run();
1843
- synced++;
1844
- } else {
1845
- skipped++;
1846
- }
1847
- } else if (mode === "hybrid") {
1848
- if (existing.source === "file") {
1849
- if (existing.content_hash !== entry.content_hash) {
1850
- await db.prepare(
1851
- `UPDATE _qarpeo_cms_entries SET
1852
- status = ?, slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
1853
- content_md = ?, content_html = ?, metadata_json = ?,
1854
- file_path = ?, content_hash = ?, updated_at = ?
1855
- WHERE id = ?`
1856
- ).bind(
1857
- entry.status ?? "published",
1858
- entry.slug,
1859
- entry.path,
1860
- entry.title,
1861
- entry.description ?? null,
1862
- entry.cover_image ?? null,
1863
- entry.tags ?? null,
1864
- entry.order ?? 0,
1865
- entry.content_md ?? "",
1866
- entry.content_html ?? "",
1867
- entry.metadata_json ?? "{}",
1868
- entry.file_path ?? "",
1869
- entry.content_hash ?? "",
1870
- now,
1871
- existing.id
1872
- ).run();
1873
- synced++;
1874
- } else {
1875
- skipped++;
1876
- }
1877
- } else {
1878
- if (existing.content_hash !== entry.content_hash) {
1879
- const revId = nanoid();
1880
- await db.prepare(
1881
- "INSERT INTO _qarpeo_cms_revisions (id, entry_id, title, content_md, metadata_json, author_id, created_at) VALUES (?, ?, ?, ?, ?, 'git', ?)"
1882
- ).bind(revId, existing.id, entry.title, entry.content_md, entry.metadata_json, now).run();
1883
- synced++;
1884
- } else {
1885
- skipped++;
1886
- }
1887
- }
1888
- } else {
1889
- skipped++;
1890
- }
1891
- }
1892
- }
1893
- return { synced, skipped, inserted };
1894
- }
1895
- import { matchesSourceFilters, matchesGlobFilter } from "./cms-filter.mjs";
1896
- export { matchesSourceFilters, matchesGlobFilter };
1897
- export async function syncLocalContentFiles(event, contentDir, collectionsConfig = {}, sources = []) {
1898
- let readdir, readFile, existsSync;
1899
- try {
1900
- const fs = await import("node:fs/promises");
1901
- const fsSync = await import("node:fs");
1902
- readdir = (dir) => fs.readdir(dir, { withFileTypes: true });
1903
- readFile = (p) => fs.readFile(p, "utf8");
1904
- existsSync = fsSync.existsSync;
1905
- } catch {
1906
- return { synced: 0, skipped: 0, inserted: 0 };
1907
- }
1908
- async function readNavJson(dir) {
1909
- const navJsonPath = `${dir}/.navigation.json`;
1910
- if (existsSync(navJsonPath)) {
1911
- try {
1912
- const raw = await readFile(navJsonPath);
1913
- const clean = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
1914
- return JSON.parse(clean);
1915
- } catch {
1916
- }
1917
- }
1918
- const navYmlPath = `${dir}/.navigation.yml`;
1919
- if (existsSync(navYmlPath)) {
1920
- try {
1921
- const raw = await readFile(navYmlPath);
1922
- return parseYaml(raw) || {};
1923
- } catch {
1924
- }
1925
- }
1926
- return {};
1927
- }
1928
- async function readSchemaJson(dir) {
1929
- const schemaPath = `${dir}/.schema.json`;
1930
- if (existsSync(schemaPath)) {
1931
- try {
1932
- const raw = await readFile(schemaPath);
1933
- const clean = raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw;
1934
- const parsed = JSON.parse(clean);
1935
- return {
1936
- scope: parsed.scope || "cascade",
1937
- fields: parsed.fields || {}
1938
- };
1939
- } catch {
1940
- }
1941
- }
1942
- return null;
1943
- }
1944
- const db = getCMSDb(event);
1945
- const cmsConfig = getCMSConfig(event);
1946
- let synced = 0, skipped = 0, inserted = 0;
1947
- const now = Date.now();
1948
- try {
1949
- const existingFileRows = await db.prepare("SELECT id, file_path FROM _qarpeo_cms_entries WHERE source = 'file'").all();
1950
- for (const r of existingFileRows?.results || []) {
1951
- if (r.file_path && !existsSync(r.file_path)) {
1952
- await db.prepare("DELETE FROM _qarpeo_cms_entries WHERE id = ?").bind(r.id).run();
1953
- }
1954
- }
1955
- } catch {
1956
- }
1957
- async function syncSource(source) {
1958
- if (!source?.resolvedDir || !existsSync(source.resolvedDir)) return;
1959
- let orderCounter = 0;
1960
- const processDir = async (dir, relBase, sectionNavMeta) => {
1961
- let entries;
1962
- try {
1963
- entries = await readdir(dir);
1964
- } catch {
1965
- return;
1966
- }
1967
- entries.sort((a, b) => a.name.localeCompare(b.name, void 0, { numeric: true }));
1968
- let navMeta = await readNavJson(dir);
1969
- if (navMeta.private === true || navMeta.draft === true || navMeta.exclude === true) {
1970
- return;
1971
- }
1972
- if (navMeta.order == null && relBase) {
1973
- const lastSeg = relBase.split("/").filter(Boolean).pop();
1974
- if (lastSeg) {
1975
- const extracted = extractOrderPrefix(lastSeg);
1976
- if (extracted != null) navMeta.order = extracted;
1977
- }
1978
- }
1979
- const isTopLevelSection = Boolean(relBase && !relBase.includes("/"));
1980
- const currentSectionNavMeta = sectionNavMeta || (isTopLevelSection ? {
1981
- title: navMeta.title || stripOrderPrefix(relBase).charAt(0).toUpperCase() + stripOrderPrefix(relBase).slice(1).replace(/-/g, " "),
1982
- icon: navMeta.icon,
1983
- order: navMeta.order ?? extractOrderPrefix(relBase),
1984
- navigation: navMeta.navigation,
1985
- hidden: navMeta.hidden
1986
- } : void 0);
1987
- for (const entry of entries) {
1988
- if (entry.name.startsWith(".") || entry.name.startsWith("_")) continue;
1989
- const subRel = relBase ? `${relBase}/${entry.name}` : entry.name;
1990
- if (entry.isDirectory()) {
1991
- await processDir(`${dir}/${entry.name}`, subRel, currentSectionNavMeta);
1992
- } else if (entry.isFile() && entry.name.endsWith(".md")) {
1993
- const combinedExclude = [
1994
- ...Array.isArray(cmsConfig?.exclude) ? cmsConfig.exclude : cmsConfig?.exclude ? [cmsConfig.exclude] : [],
1995
- ...Array.isArray(source.exclude) ? source.exclude : source.exclude ? [source.exclude] : []
1996
- ];
1997
- if (!matchesSourceFilters(subRel, source.include, combinedExclude)) continue;
1998
- const filePath = `${dir}/${entry.name}`;
1999
- const rawContent = await readFile(filePath);
2000
- const fileHash = await computeContentHash(rawContent);
2001
- const { data: fm, content: body } = parseFrontmatter(rawContent);
2002
- const rawRelSegments = subRel.replace(/\.md$/, "").split("/").filter(Boolean);
2003
- const isReadme = entry.name.toLowerCase() === "readme.md";
2004
- const isIndex = entry.name.replace(/\.md$/, "") === "index" || entry.name.replace(/\.md$/, "") === "01.index" || isReadme;
2005
- const groupSegment = rawRelSegments.slice(0, -1).find(isGroupSegment);
2006
- let groupMeta;
2007
- if (groupSegment) {
2008
- const groupOrder = extractOrderPrefix(groupSegment);
2009
- const defaultGroupTitle = extractGroupTitle(groupSegment);
2010
- const groupKey = stripOrderPrefix(groupSegment).replace(/^\(|\)$/g, "");
2011
- const currentDirName = dir.replace(/\\/g, "/").split("/").filter(Boolean).pop();
2012
- const isGroupDir = currentDirName === groupSegment;
2013
- groupMeta = {
2014
- key: groupKey,
2015
- title: isGroupDir && navMeta.title ? navMeta.title : defaultGroupTitle,
2016
- icon: isGroupDir && navMeta.icon ? navMeta.icon : void 0,
2017
- order: groupOrder
2018
- };
2019
- }
2020
- const cleanedRelSegments = rawRelSegments.filter((seg) => !isGroupSegment(seg)).map(stripOrderPrefix).filter(Boolean);
2021
- if (isIndex && cleanedRelSegments.length > 0) {
2022
- cleanedRelSegments.pop();
2023
- }
2024
- const prefixSegments = (source.normalizedPrefix || "/").split("/").filter(Boolean);
2025
- const combinedSegments = [...prefixSegments, ...cleanedRelSegments];
2026
- const entryPath = "/" + combinedSegments.join("/");
2027
- const defaultCollectionId = prefixSegments[0] || "content";
2028
- const collectionId = resolveCollectionForPath(
2029
- entryPath,
2030
- collectionsConfig,
2031
- defaultCollectionId
2032
- );
2033
- const slug = fm.slug || cleanedRelSegments[cleanedRelSegments.length - 1] || prefixSegments[prefixSegments.length - 1] || "index";
2034
- const title = fm.title || slug;
2035
- const srcOrder = typeof source.order === "number" ? source.order : 0;
2036
- const existingCol = await db.prepare("SELECT id FROM _qarpeo_cms_collections WHERE id = ?").bind(collectionId).first();
2037
- if (!existingCol) {
2038
- const colName = collectionId.charAt(0).toUpperCase() + collectionId.slice(1).replace(/-/g, " ");
2039
- await db.prepare(
2040
- `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, '{}', 'file', ?, ?, ?)`
2041
- ).bind(
2042
- collectionId,
2043
- colName,
2044
- `Auto-discovered ${colName} collection`,
2045
- srcOrder,
2046
- now,
2047
- now
2048
- ).run();
2049
- }
2050
- const toc = extractTOC(body);
2051
- const { html: contentHtml } = await processMarkdown(body);
2052
- const description = fm.description || null;
2053
- const coverImage = fm.coverImage || fm.cover_image || null;
2054
- const tags = Array.isArray(fm.tags) ? fm.tags.join(",") : fm.tags || null;
2055
- const folderNum = rawRelSegments.length > 1 ? extractOrderPrefix(rawRelSegments[0]) : void 0;
2056
- const effectiveFolderNum = folderNum ?? (typeof currentSectionNavMeta?.order === "number" ? currentSectionNavMeta.order : void 0);
2057
- const folderOrder = effectiveFolderNum != null ? effectiveFolderNum * 1e3 : 5e4;
2058
- let subfolderOffset = 0;
2059
- if (rawRelSegments.length > 2) {
2060
- const subDir = rawRelSegments[1];
2061
- const subDirNum = extractOrderPrefix(subDir);
2062
- const subOrder = subDirNum ?? (typeof groupMeta?.order === "number" ? groupMeta.order : typeof navMeta?.order === "number" ? navMeta.order : void 0);
2063
- subfolderOffset = 500 + (subOrder != null ? subOrder * 50 : 100);
2064
- }
2065
- const fileNum = extractOrderPrefix(entry.name);
2066
- const itemOrder = typeof fm.order === "number" ? fm.order : isIndex ? 0 : fileNum ?? (subfolderOffset > 0 ? 10 + orderCounter++ : 100 + orderCounter++);
2067
- const order = srcOrder * 1e5 + folderOrder + subfolderOffset + itemOrder;
2068
- const itemTitle = fm.navigation?.title || fm.title || slug;
2069
- const {
2070
- slug: _s,
2071
- title: _t,
2072
- description: _d,
2073
- coverImage: _ci,
2074
- tags: _ta,
2075
- order: _o,
2076
- ...rest
2077
- } = fm;
2078
- void _s;
2079
- void _t;
2080
- void _d;
2081
- void _ci;
2082
- void _ta;
2083
- void _o;
2084
- const effectiveSection = currentSectionNavMeta?.title ? { title: currentSectionNavMeta.title, icon: currentSectionNavMeta.icon } : navMeta.title ? { title: navMeta.title, icon: navMeta.icon } : void 0;
2085
- const isDraft = Boolean(
2086
- fm.draft === true || fm.private === true || fm.status === "draft" || navMeta.draft === true || navMeta.private === true
2087
- );
2088
- const entryStatus = isDraft ? "draft" : "published";
2089
- const resolvedRest = { ...rest };
2090
- try {
2091
- await resolveReferenceFieldsFromFrontmatter(event, collectionId, resolvedRest);
2092
- } catch {
2093
- }
2094
- const metadataJson = JSON.stringify({
2095
- ...resolvedRest,
2096
- navigation: fm.navigation,
2097
- hidden: fm.hidden,
2098
- draft: isDraft,
2099
- _toc: { links: toc },
2100
- _nav: navMeta,
2101
- _section: effectiveSection,
2102
- _sectionOrder: effectiveFolderNum,
2103
- _group: groupMeta,
2104
- _itemTitle: itemTitle,
2105
- _itemOrder: itemOrder,
2106
- _fileOrder: fileNum,
2107
- _isIndex: isIndex,
2108
- _source: source.from || "unknown",
2109
- _sourceLabel: source.label || source.from || "source",
2110
- _sourcePriority: source.priority ?? 0,
2111
- _sourceOrder: source.order ?? srcOrder
2112
- });
2113
- const existing = await db.prepare(
2114
- "SELECT id, source, content_hash, metadata_json, file_path, status FROM _qarpeo_cms_entries WHERE collection_id = ? AND path = ?"
2115
- ).bind(collectionId, entryPath).first();
2116
- if (!existing) {
2117
- const id = nanoid();
2118
- await db.prepare(
2119
- `INSERT INTO _qarpeo_cms_entries
2120
- (id, collection_id, slug, path, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
2121
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'file', ?, ?, ?, ?, ?)`
2122
- ).bind(
2123
- id,
2124
- collectionId,
2125
- slug,
2126
- entryPath,
2127
- title,
2128
- description,
2129
- coverImage,
2130
- tags,
2131
- order,
2132
- body,
2133
- contentHtml,
2134
- metadataJson,
2135
- entryStatus,
2136
- filePath,
2137
- fileHash,
2138
- isDraft ? null : now,
2139
- now,
2140
- now
2141
- ).run();
2142
- inserted++;
2143
- } else if (existing.source === "file" && (existing.content_hash !== fileHash || existing.metadata_json !== metadataJson || existing.file_path !== filePath || existing.status !== entryStatus)) {
2144
- await db.prepare(
2145
- `UPDATE _qarpeo_cms_entries SET
2146
- status = ?, slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
2147
- content_md = ?, content_html = ?, metadata_json = ?,
2148
- file_path = ?, content_hash = ?, source = 'file', updated_at = ?
2149
- WHERE id = ?`
2150
- ).bind(
2151
- entryStatus,
2152
- slug,
2153
- entryPath,
2154
- title,
2155
- description,
2156
- coverImage,
2157
- tags,
2158
- order,
2159
- body,
2160
- contentHtml,
2161
- metadataJson,
2162
- filePath,
2163
- fileHash,
2164
- now,
2165
- existing.id
2166
- ).run();
2167
- synced++;
2168
- } else {
2169
- skipped++;
2170
- }
2171
- }
2172
- }
2173
- };
2174
- await processDir(source.resolvedDir, "");
2175
- }
2176
- const lowPrioritySources = (sources || []).filter((s) => (s.priority ?? 0) < 10);
2177
- const highPrioritySources = (sources || []).filter((s) => (s.priority ?? 0) >= 10);
2178
- for (const src of lowPrioritySources) {
2179
- await syncSource(src);
2180
- }
2181
- const targetCollections = {};
2182
- for (const [id, cfg] of Object.entries(collectionsConfig)) {
2183
- targetCollections[id] = {
2184
- directory: cfg.directory || `${contentDir}/${id}`,
2185
- name: cfg.name,
2186
- type: cfg.type || "content",
2187
- order: typeof cfg.order === "number" ? cfg.order : 0
2188
- };
2189
- }
2190
- const rootMdFiles = [];
2191
- try {
2192
- const rootItems = await readdir(contentDir);
2193
- for (const item of rootItems) {
2194
- if (item.isDirectory()) {
2195
- const colId = stripOrderPrefix(item.name).toLowerCase();
2196
- if (!targetCollections[colId]) {
2197
- targetCollections[colId] = {
2198
- directory: `${contentDir}/${item.name}`,
2199
- name: item.name.charAt(0).toUpperCase() + item.name.slice(1).replace(/-/g, " "),
2200
- type: "content",
2201
- order: extractOrderPrefix(item.name) ?? 0
2202
- };
2203
- }
2204
- } else if (item.isFile() && (item.name.endsWith(".md") || item.name.endsWith(".json") || item.name.endsWith(".yml") || item.name.endsWith(".yaml"))) {
2205
- if (item.name.endsWith(".md")) {
2206
- rootMdFiles.push(item);
2207
- } else {
2208
- const colId = item.name.replace(/\.(json|ya?ml)$/, "").toLowerCase();
2209
- if (!targetCollections[colId]) {
2210
- targetCollections[colId] = {
2211
- directory: `${contentDir}/${item.name}`,
2212
- name: colId.charAt(0).toUpperCase() + colId.slice(1).replace(/-/g, " "),
2213
- type: "content",
2214
- order: 0,
2215
- isSingleDataFile: true
2216
- };
2217
- }
2218
- }
2219
- }
2220
- }
2221
- } catch {
2222
- return { synced: 0, skipped: 0, inserted: 0 };
2223
- }
2224
- if (rootMdFiles.length > 0 && !targetCollections["content"]) {
2225
- targetCollections["content"] = {
2226
- directory: contentDir,
2227
- name: "Content",
2228
- type: "page",
2229
- order: 100
2230
- };
2231
- }
2232
- for (const [collectionId, meta] of Object.entries(targetCollections)) {
2233
- const isPageType = meta.type === "page";
2234
- const folderSchema = await readSchemaJson(meta.directory);
2235
- const initialFields = folderSchema?.fields ? JSON.stringify(folderSchema.fields) : "{}";
2236
- const existingCol = await db.prepare("SELECT id, source, schema_json FROM _qarpeo_cms_collections WHERE id = ?").bind(collectionId).first();
2237
- if (!existingCol) {
2238
- const colName = meta.name || collectionId.charAt(0).toUpperCase() + collectionId.slice(1).replace(/-/g, " ");
2239
- await db.prepare(
2240
- `INSERT INTO _qarpeo_cms_collections (id, name, description, schema_json, source, "order", created_at, updated_at) VALUES (?, ?, ?, ?, 'file', ?, ?, ?)`
2241
- ).bind(
2242
- collectionId,
2243
- colName,
2244
- `Auto-discovered ${colName} collection`,
2245
- initialFields,
2246
- meta.order,
2247
- now,
2248
- now
2249
- ).run();
2250
- } else if (folderSchema?.fields && existingCol.schema_json !== initialFields && existingCol.source === "file") {
2251
- await db.prepare("UPDATE _qarpeo_cms_collections SET schema_json = ?, updated_at = ? WHERE id = ?").bind(initialFields, now, collectionId).run();
2252
- }
2253
- if (meta.isSingleDataFile) {
2254
- const filePath = meta.directory;
2255
- let rawContent = "";
2256
- try {
2257
- rawContent = await readFile(filePath);
2258
- } catch {
2259
- continue;
2260
- }
2261
- const fileHash = await computeContentHash(rawContent);
2262
- let parsed = {};
2263
- if (filePath.endsWith(".json")) {
2264
- try {
2265
- parsed = JSON.parse(rawContent);
2266
- } catch {
2267
- }
2268
- } else {
2269
- try {
2270
- parsed = parseYaml(rawContent) || {};
2271
- } catch {
2272
- }
2273
- }
2274
- const slug = parsed.slug || collectionId;
2275
- const title = parsed.title || slug;
2276
- const description = parsed.description || null;
2277
- const entryPath = `/${collectionId}`;
2278
- const metadataJson = JSON.stringify(parsed);
2279
- const existing = await db.prepare(
2280
- "SELECT id, source, content_hash, metadata_json, file_path FROM _qarpeo_cms_entries WHERE collection_id = ? AND slug = ?"
2281
- ).bind(collectionId, slug).first();
2282
- if (!existing) {
2283
- const id = nanoid();
2284
- await db.prepare(
2285
- `INSERT INTO _qarpeo_cms_entries
2286
- (id, collection_id, slug, path, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
2287
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, '', '', ?, 'published', 'file', ?, ?, ?, ?, ?)`
2288
- ).bind(
2289
- id,
2290
- collectionId,
2291
- slug,
2292
- entryPath,
2293
- title,
2294
- description,
2295
- null,
2296
- null,
2297
- metadataJson,
2298
- filePath,
2299
- fileHash,
2300
- now,
2301
- now,
2302
- now
2303
- ).run();
2304
- inserted++;
2305
- } else if (existing.source === "file" && (existing.content_hash !== fileHash || existing.metadata_json !== metadataJson)) {
2306
- await db.prepare(
2307
- `UPDATE _qarpeo_cms_entries SET
2308
- slug = ?, path = ?, title = ?, description = ?,
2309
- metadata_json = ?, file_path = ?, content_hash = ?, source = 'file', updated_at = ?
2310
- WHERE id = ?`
2311
- ).bind(
2312
- slug,
2313
- entryPath,
2314
- title,
2315
- description,
2316
- metadataJson,
2317
- filePath,
2318
- fileHash,
2319
- now,
2320
- existing.id
2321
- ).run();
2322
- synced++;
2323
- } else {
2324
- skipped++;
2325
- }
2326
- continue;
2327
- }
2328
- if (isPageType) {
2329
- let orderCounter = 0;
2330
- const processDir = async (dir, relBase) => {
2331
- let entries;
2332
- try {
2333
- entries = await readdir(dir);
2334
- } catch {
2335
- return;
2336
- }
2337
- entries.sort((a, b) => a.name.localeCompare(b.name, void 0, { numeric: true }));
2338
- for (const entry of entries) {
2339
- if (entry.name.startsWith(".")) continue;
2340
- if (entry.isDirectory()) {
2341
- if (collectionId === "content") continue;
2342
- await processDir(`${dir}/${entry.name}`, `${relBase}/${entry.name}`);
2343
- } else if (entry.isFile() && entry.name.endsWith(".md")) {
2344
- const filePath = `${dir}/${entry.name}`;
2345
- const rawContent = await readFile(filePath);
2346
- const fileHash = await computeContentHash(rawContent);
2347
- const { data: fm, content: body } = parseFrontmatter(rawContent);
2348
- const relFilePath = `${relBase}/${entry.name}`.replace(/^\//, "");
2349
- const slug = fm.slug || stripOrderPrefix(entry.name.replace(/\.md$/, ""));
2350
- const title = fm.title || slug;
2351
- const navJson = await readNavJson(dir);
2352
- const navMeta = {
2353
- title: navJson.title,
2354
- icon: navJson.icon
2355
- };
2356
- const rawRelSegments = relFilePath.replace(/\.md$/, "").split("/").filter(Boolean);
2357
- const groupSegment = rawRelSegments.slice(0, -1).find(isGroupSegment);
2358
- let groupMeta;
2359
- if (groupSegment) {
2360
- const groupOrder = extractOrderPrefix(groupSegment);
2361
- const defaultGroupTitle = extractGroupTitle(groupSegment);
2362
- const groupKey = stripOrderPrefix(groupSegment).replace(/^\(|\)$/g, "");
2363
- const currentDirName = dir.replace(/\\/g, "/").split("/").filter(Boolean).pop();
2364
- const isGroupDir = currentDirName === groupSegment;
2365
- groupMeta = {
2366
- key: groupKey,
2367
- title: isGroupDir && navMeta.title ? navMeta.title : defaultGroupTitle,
2368
- icon: isGroupDir && navMeta.icon ? navMeta.icon : void 0,
2369
- order: groupOrder
2370
- };
2371
- }
2372
- const entryPath = computeEntryPath(relFilePath, collectionId);
2373
- const targetCollectionId = resolveCollectionForPath(
2374
- entryPath,
2375
- collectionsConfig,
2376
- collectionId
2377
- );
2378
- const toc = extractTOC(body);
2379
- const { html: contentHtml } = await processMarkdown(body);
2380
- const description = fm.description || null;
2381
- const coverImage = fm.coverImage || fm.cover_image || null;
2382
- const tags = Array.isArray(fm.tags) ? fm.tags.join(",") : fm.tags || null;
2383
- const order = fm.order ?? orderCounter++;
2384
- const isIndex = entry.name.replace(/\.md$/, "") === "01.index" || entry.name.replace(/\.md$/, "") === "index";
2385
- const itemTitle = fm.navigation?.title || fm.title || slug;
2386
- const {
2387
- slug: _s,
2388
- title: _t,
2389
- description: _d,
2390
- coverImage: _ci,
2391
- tags: _ta,
2392
- order: _o,
2393
- ...rest
2394
- } = fm;
2395
- void _s;
2396
- void _t;
2397
- void _d;
2398
- void _ci;
2399
- void _ta;
2400
- void _o;
2401
- const metadataJson = JSON.stringify({
2402
- ...rest,
2403
- _toc: { links: toc },
2404
- _nav: navMeta,
2405
- _section: navMeta.title ? { title: navMeta.title, icon: navMeta.icon } : void 0,
2406
- _group: groupMeta,
2407
- _itemTitle: itemTitle,
2408
- _isIndex: isIndex
2409
- });
2410
- const existing = await db.prepare(
2411
- "SELECT id, source, content_hash, metadata_json, file_path FROM _qarpeo_cms_entries WHERE collection_id = ? AND path = ?"
2412
- ).bind(targetCollectionId, entryPath).first();
2413
- if (!existing) {
2414
- const id = nanoid();
2415
- await db.prepare(
2416
- `INSERT INTO _qarpeo_cms_entries
2417
- (id, collection_id, slug, path, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
2418
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', 'file', ?, ?, ?, ?, ?)`
2419
- ).bind(
2420
- id,
2421
- targetCollectionId,
2422
- slug,
2423
- entryPath,
2424
- title,
2425
- description,
2426
- coverImage,
2427
- tags,
2428
- order,
2429
- body,
2430
- contentHtml,
2431
- metadataJson,
2432
- filePath,
2433
- fileHash,
2434
- now,
2435
- now,
2436
- now
2437
- ).run();
2438
- inserted++;
2439
- } else if (existing.source === "file" && (existing.content_hash !== fileHash || existing.metadata_json !== metadataJson || existing.file_path !== filePath)) {
2440
- await db.prepare(
2441
- `UPDATE _qarpeo_cms_entries SET
2442
- slug = ?, path = ?, title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
2443
- content_md = ?, content_html = ?, metadata_json = ?,
2444
- file_path = ?, content_hash = ?, source = 'file', updated_at = ?
2445
- WHERE id = ?`
2446
- ).bind(
2447
- slug,
2448
- entryPath,
2449
- title,
2450
- description,
2451
- coverImage,
2452
- tags,
2453
- order,
2454
- body,
2455
- contentHtml,
2456
- metadataJson,
2457
- filePath,
2458
- fileHash,
2459
- now,
2460
- existing.id
2461
- ).run();
2462
- synced++;
2463
- } else {
2464
- skipped++;
2465
- }
2466
- }
2467
- }
2468
- };
2469
- await processDir(meta.directory, "");
2470
- } else {
2471
- let entries;
2472
- try {
2473
- entries = await readdir(meta.directory);
2474
- } catch {
2475
- continue;
2476
- }
2477
- for (const entry of entries) {
2478
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
2479
- const filePath = `${meta.directory}/${entry.name}`;
2480
- const rawContent = await readFile(filePath);
2481
- const fileHash = await computeContentHash(rawContent);
2482
- const { data: fm, content: body } = parseFrontmatter(rawContent);
2483
- const slug = fm.slug || entry.name.replace(/\.md$/, "");
2484
- const title = fm.title || slug;
2485
- const { html: contentHtml } = await processMarkdown(body);
2486
- const description = fm.description || null;
2487
- const coverImage = fm.coverImage || fm.cover_image || null;
2488
- const tags = Array.isArray(fm.tags) ? fm.tags.join(",") : fm.tags || null;
2489
- const order = fm.order || 0;
2490
- const {
2491
- slug: _s,
2492
- title: _t,
2493
- description: _d,
2494
- coverImage: _ci,
2495
- tags: _ta,
2496
- order: _o,
2497
- ...rest
2498
- } = fm;
2499
- void _s;
2500
- void _t;
2501
- void _d;
2502
- void _ci;
2503
- void _ta;
2504
- void _o;
2505
- const metadataJson = JSON.stringify({
2506
- ...rest,
2507
- _source: "local",
2508
- _sourceLabel: "content",
2509
- _sourcePriority: 10
2510
- });
2511
- const existing = await db.prepare(
2512
- "SELECT id, source, content_hash FROM _qarpeo_cms_entries WHERE collection_id = ? AND slug = ?"
2513
- ).bind(collectionId, slug).first();
2514
- if (!existing) {
2515
- const id = nanoid();
2516
- await db.prepare(
2517
- `INSERT INTO _qarpeo_cms_entries
2518
- (id, collection_id, slug, title, description, cover_image, tags, "order", content_md, content_html, metadata_json, status, source, file_path, content_hash, published_at, created_at, updated_at)
2519
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'published', 'file', ?, ?, ?, ?, ?)`
2520
- ).bind(
2521
- id,
2522
- collectionId,
2523
- slug,
2524
- title,
2525
- description,
2526
- coverImage,
2527
- tags,
2528
- order,
2529
- body,
2530
- contentHtml,
2531
- metadataJson,
2532
- filePath,
2533
- fileHash,
2534
- now,
2535
- now,
2536
- now
2537
- ).run();
2538
- inserted++;
2539
- } else if (existing.source === "file" && existing.content_hash !== fileHash) {
2540
- await db.prepare(
2541
- `UPDATE _qarpeo_cms_entries SET
2542
- title = ?, description = ?, cover_image = ?, tags = ?, "order" = ?,
2543
- content_md = ?, content_html = ?, metadata_json = ?,
2544
- file_path = ?, content_hash = ?, source = 'file', updated_at = ?
2545
- WHERE id = ?`
2546
- ).bind(
2547
- title,
2548
- description,
2549
- coverImage,
2550
- tags,
2551
- order,
2552
- body,
2553
- contentHtml,
2554
- metadataJson,
2555
- filePath,
2556
- fileHash,
2557
- now,
2558
- existing.id
2559
- ).run();
2560
- synced++;
2561
- } else {
2562
- skipped++;
2563
- }
2564
- }
2565
- }
2566
- }
2567
- for (const src of highPrioritySources) {
2568
- await syncSource(src);
2569
- }
2570
- return { synced, skipped, inserted };
2571
- }
2572
- export async function getCMSEntryByPath(event, collectionId, path, locale, options = {}) {
2573
- await ensureCMSSynced(event);
2574
- const db = getCMSDb(event);
2575
- const cleanPath = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
2576
- const tenantId = getCMSTenantId(event);
2577
- const tenantClause = tenantId ? " AND (tenant_id = ? OR tenant_id IS NULL)" : "";
2578
- let allowDraft = false;
2579
- const previewCookie = event ? getCookie(event, "qarpeo_preview") : null;
2580
- let cookieObj = null;
2581
- if (previewCookie) {
2582
- try {
2583
- cookieObj = typeof previewCookie === "string" ? JSON.parse(previewCookie) : previewCookie;
2584
- } catch {
2585
- }
2586
- }
2587
- const isPreviewRequested = options.preview || Boolean(cookieObj);
2588
- if (isPreviewRequested) {
2589
- const auth = await getAuthContext(event).catch(() => null);
2590
- const config = getCMSConfig(event);
2591
- if (auth?.user && config.roles.some((r) => r === auth.role || auth.isAdmin)) {
2592
- allowDraft = true;
2593
- }
2594
- if (!allowDraft && db) {
2595
- const token = options.previewToken || cookieObj?.token;
2596
- const expires = options.previewExpires || cookieObj?.expires;
2597
- if (token && expires) {
2598
- try {
2599
- const candidate = await db.prepare(
2600
- `SELECT id, slug, collection_id FROM _qarpeo_cms_entries WHERE (collection_id = ? OR ? = 'content') AND (path = ? OR path = ?) ${tenantClause} LIMIT 1`
2601
- ).bind(collectionId, collectionId, cleanPath, `${cleanPath}/`).first();
2602
- if (candidate) {
2603
- allowDraft = await verifyPreviewToken(
2604
- event,
2605
- candidate.collection_id,
2606
- candidate.id,
2607
- token,
2608
- expires
2609
- ) || await verifyPreviewToken(
2610
- event,
2611
- candidate.collection_id,
2612
- candidate.slug,
2613
- token,
2614
- expires
2615
- );
2616
- }
2617
- } catch {
2618
- }
2619
- }
2620
- }
2621
- }
2622
- const statusFilter = allowDraft ? "status IN ('draft', 'published', 'scheduled')" : "status = 'published'";
2623
- const statusOrder = allowDraft ? "CASE WHEN status = 'draft' THEN 1 WHEN status = 'scheduled' THEN 2 ELSE 3 END," : "";
2624
- let row = null;
2625
- if (db) {
2626
- try {
2627
- if (locale) {
2628
- const bindsLocale = tenantId ? [collectionId, cleanPath, `${cleanPath}/`, locale, tenantId] : [collectionId, cleanPath, `${cleanPath}/`, locale];
2629
- row = await db.prepare(
2630
- `SELECT * FROM _qarpeo_cms_entries WHERE collection_id = ? AND (path = ? OR path = ?) AND locale = ? AND ${statusFilter}${tenantClause} ORDER BY ${statusOrder} created_at DESC LIMIT 1`
2631
- ).bind(...bindsLocale).first();
2632
- }
2633
- const binds1 = tenantId ? [collectionId, cleanPath, `${cleanPath}/`, tenantId] : [collectionId, cleanPath, `${cleanPath}/`];
2634
- if (!row) {
2635
- row = await db.prepare(
2636
- `SELECT * FROM _qarpeo_cms_entries WHERE collection_id = ? AND (path = ? OR path = ?) AND ${statusFilter}${tenantClause} ORDER BY ${statusOrder} CASE WHEN locale = 'en' THEN 1 ELSE 2 END LIMIT 1`
2637
- ).bind(...binds1).first();
2638
- }
2639
- if (!row && cleanPath.startsWith(`/${collectionId}`)) {
2640
- const unPrefixed = cleanPath.slice(`/${collectionId}`.length) || "/";
2641
- const binds2 = tenantId ? [collectionId, unPrefixed, `${unPrefixed}/`, tenantId] : [collectionId, unPrefixed, `${unPrefixed}/`];
2642
- row = await db.prepare(
2643
- `SELECT * FROM _qarpeo_cms_entries WHERE collection_id = ? AND (path = ? OR path = ?) AND ${statusFilter}${tenantClause} ORDER BY ${statusOrder} created_at DESC LIMIT 1`
2644
- ).bind(...binds2).first();
2645
- }
2646
- if (!row) {
2647
- const binds3 = tenantId ? [cleanPath, `${cleanPath}/`, tenantId] : [cleanPath, `${cleanPath}/`];
2648
- row = await db.prepare(
2649
- `SELECT * FROM _qarpeo_cms_entries WHERE (path = ? OR path = ?) AND ${statusFilter}${tenantClause} ORDER BY ${statusOrder} created_at DESC LIMIT 1`
2650
- ).bind(...binds3).first();
2651
- }
2652
- } catch {
2653
- }
2654
- }
2655
- if (!row) {
2656
- try {
2657
- const { manifestEntries } = await import("#qarpeo/cms/manifest");
2658
- const candidate = (manifestEntries || []).find(
2659
- (e) => (e.collection_id === collectionId || collectionId === "content") && (e.path === cleanPath || e.path === `${cleanPath}/`)
2660
- );
2661
- if (candidate) {
2662
- row = candidate;
2663
- }
2664
- } catch {
2665
- }
2666
- }
2667
- if (!row) return null;
2668
- const entry = rowToEntry(row);
2669
- const wantsBody = !options.fields || (Array.isArray(options.fields) ? options.fields.some((f) => f === "body" || f.includes("body")) : String(options.fields).includes("body"));
2670
- if (wantsBody && (!entry.body || !Array.isArray(entry.body.nodes)) && entry.contentMd) {
2671
- const ast = await parseMarkdownAST(entry.contentMd);
2672
- entry.body = {
2673
- ...ast,
2674
- toc: entry.toc || { links: [] }
2675
- };
2676
- } else if (entry.body && Array.isArray(entry.body.nodes)) {
2677
- if ("value" in entry.body) delete entry.body.value;
2678
- if ("content" in entry.body) delete entry.body.content;
2679
- }
2680
- if (options.fields) {
2681
- return projectCMSEntry(entry, options.fields);
2682
- }
2683
- return entry;
2684
- }
2685
- export async function getCMSEntrySurroundings(event, collectionId, path, fields = []) {
2686
- await ensureCMSSynced(event);
2687
- const db = getCMSDb(event);
2688
- const cleanPath = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
2689
- const pick = (entry) => {
2690
- if (!entry) return null;
2691
- if (!fields.length) return entry;
2692
- const partial = { id: entry.id, slug: entry.slug, path: entry.path, title: entry.title };
2693
- for (const f of fields) {
2694
- if (f in entry) partial[f] = entry[f];
2695
- }
2696
- return partial;
2697
- };
2698
- try {
2699
- const navTree = await getCMSNavigationTree(event, collectionId);
2700
- const orderedPaths = [];
2701
- const seenPaths = /* @__PURE__ */ new Set();
2702
- const collectPaths = (items) => {
2703
- for (const item of items) {
2704
- if (item.path && item.type !== "group") {
2705
- const norm = item.path.length > 1 && item.path.endsWith("/") ? item.path.slice(0, -1) : item.path;
2706
- if (!seenPaths.has(norm)) {
2707
- seenPaths.add(norm);
2708
- orderedPaths.push(norm);
2709
- }
2710
- }
2711
- if (item.children?.length) {
2712
- collectPaths(item.children);
2713
- }
2714
- }
2715
- };
2716
- collectPaths(navTree);
2717
- let idx2 = orderedPaths.indexOf(cleanPath);
2718
- if (idx2 === -1) {
2719
- idx2 = orderedPaths.indexOf(`${cleanPath}/`);
2720
- }
2721
- if (idx2 !== -1) {
2722
- const prevPath = idx2 > 0 ? orderedPaths[idx2 - 1] : null;
2723
- const nextPath = idx2 < orderedPaths.length - 1 ? orderedPaths[idx2 + 1] : null;
2724
- const [prevEntry, nextEntry] = await Promise.all([
2725
- prevPath ? getCMSEntryByPath(event, collectionId, prevPath) : Promise.resolve(null),
2726
- nextPath ? getCMSEntryByPath(event, collectionId, nextPath) : Promise.resolve(null)
2727
- ]);
2728
- return [pick(prevEntry), pick(nextEntry)];
2729
- }
2730
- } catch (err) {
2731
- console.warn("[qarpeo:cms] getCMSEntrySurroundings navTree lookup failed:", err);
2732
- }
2733
- if (!db) return [null, null];
2734
- const tenantId = getCMSTenantId(event);
2735
- const tenantClause = tenantId ? " AND (tenant_id = ? OR tenant_id IS NULL)" : "";
2736
- const binds = tenantId ? [collectionId, tenantId] : [collectionId];
2737
- const all = await db.prepare(
2738
- `SELECT * FROM _qarpeo_cms_entries WHERE collection_id = ? AND status = 'published'${tenantClause} ORDER BY "order" ASC`
2739
- ).bind(...binds).all();
2740
- const rows = (all.results || []).map(rowToEntry);
2741
- const idx = rows.findIndex((e) => e.path === cleanPath || e.path === `${cleanPath}/`);
2742
- if (idx === -1) return [null, null];
2743
- return [pick(rows[idx - 1]), pick(rows[idx + 1])];
2744
- }
2745
- function pruneTreeLevels(items, currentLevel, maxLevel) {
2746
- if (currentLevel >= maxLevel) {
2747
- for (const item of items) {
2748
- delete item.children;
2749
- }
2750
- return items;
2751
- }
2752
- for (const item of items) {
2753
- if (item.children) {
2754
- pruneTreeLevels(item.children, currentLevel + 1, maxLevel);
2755
- }
2756
- }
2757
- return items;
2758
- }
2759
- const CMS_FIRST_CLASS_COLUMNS = /* @__PURE__ */ new Set([
2760
- "id",
2761
- "slug",
2762
- "path",
2763
- "title",
2764
- "description",
2765
- "tags",
2766
- "status",
2767
- "source"
2768
- ]);
2769
- function matchesWhereFilter(row, meta, where) {
2770
- return Object.entries(where).every(([key, expected]) => {
2771
- if (CMS_FIRST_CLASS_COLUMNS.has(key)) {
2772
- const actual2 = row[key] ?? null;
2773
- return actual2 === expected;
2774
- }
2775
- const actual = meta[key] !== void 0 ? meta[key] : null;
2776
- return actual === expected;
2777
- });
2778
- }
2779
- export async function getCMSNavigationTree(event, collectionId, options) {
2780
- await ensureCMSSynced(event);
2781
- const db = getCMSDb(event);
2782
- if (collectionId === "content") {
2783
- const config = getCMSConfig(event);
2784
- const configuredKeys = Object.keys(config.collections || {});
2785
- const collections = await listCMSCollections(event);
2786
- const valid = collections.filter((c) => {
2787
- if (c.id.startsWith("_") || c.id === "content") return false;
2788
- const colConf = config.collections?.[c.id];
2789
- if (colConf && (colConf.navigation === false || colConf.hidden === true)) {
2790
- return false;
2791
- }
2792
- return true;
2793
- });
2794
- if (configuredKeys.length) {
2795
- valid.sort((a, b) => {
2796
- const ia = configuredKeys.indexOf(a.id);
2797
- const ib = configuredKeys.indexOf(b.id);
2798
- if (ia !== -1 && ib !== -1) return ia - ib;
2799
- if (ia !== -1) return -1;
2800
- if (ib !== -1) return 1;
2801
- return (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name);
2802
- });
2803
- } else {
2804
- valid.sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name));
2805
- }
2806
- let items = valid.map((c) => ({
2807
- title: c.name,
2808
- path: `/${c.id}`
2809
- }));
2810
- const targetStatus2 = options?.status || "published";
2811
- const navRootTenantId = getCMSTenantId(event);
2812
- let rootSql = `SELECT id, slug, path, title, "order", metadata_json, status FROM _qarpeo_cms_entries WHERE collection_id = 'content'`;
2813
- const rootBinds = [];
2814
- if (targetStatus2 !== "all") {
2815
- rootSql += " AND status = ?";
2816
- rootBinds.push(targetStatus2);
2817
- }
2818
- if (navRootTenantId) {
2819
- rootSql += " AND (tenant_id = ? OR tenant_id IS NULL)";
2820
- rootBinds.push(navRootTenantId);
2821
- }
2822
- rootSql += ' ORDER BY "order" ASC';
2823
- let rows2 = [];
2824
- if (db) {
2825
- try {
2826
- const rootEntries = await db.prepare(rootSql).bind(...rootBinds).all();
2827
- rows2 = rootEntries.results || [];
2828
- } catch {
2829
- }
2830
- }
2831
- if (!rows2.length) {
2832
- try {
2833
- const { manifestEntries } = await import("#qarpeo/cms/manifest");
2834
- rows2 = (manifestEntries || []).filter((e) => e.collection_id === "content").map((e) => ({
2835
- id: e.id,
2836
- slug: e.slug,
2837
- path: e.path,
2838
- title: e.title,
2839
- order: e.order ?? 0,
2840
- metadata_json: typeof e.metadata_json === "string" ? e.metadata_json : JSON.stringify(e.metadata || {}),
2841
- status: e.status || "published"
2842
- }));
2843
- } catch {
2844
- }
2845
- }
2846
- for (const r of rows2) {
2847
- let meta = {};
2848
- try {
2849
- meta = JSON.parse(r.metadata_json || "{}");
2850
- } catch {
2851
- }
2852
- if (meta.navigation === false || meta.hidden === true || meta.navigation?.hidden === true || meta._nav?.navigation === false || meta._nav?.hidden === true) {
2853
- continue;
2854
- }
2855
- if (options?.where && !matchesWhereFilter(r, meta, options.where)) {
2856
- continue;
2857
- }
2858
- const entryPath = r.path || (r.slug === "index" ? "/" : `/${r.slug}`);
2859
- const title = meta.navigation?.title || meta._itemTitle || r.title;
2860
- const icon = meta.navigation?.icon || meta._nav?.icon;
2861
- items.push({
2862
- title,
2863
- path: entryPath,
2864
- to: entryPath,
2865
- icon
2866
- });
2867
- }
2868
- if (options?.skip != null || options?.limit != null) {
2869
- const skip = options?.skip ?? 0;
2870
- const limit = options?.limit ?? items.length;
2871
- items = items.slice(skip, skip + limit);
2872
- }
2873
- return items;
2874
- }
2875
- const targetStatus = options?.status || "published";
2876
- const navTenantId = getCMSTenantId(event);
2877
- let sql = 'SELECT id, slug, path, title, "order", metadata_json, status FROM _qarpeo_cms_entries WHERE collection_id = ?';
2878
- const binds = [collectionId];
2879
- if (targetStatus !== "all") {
2880
- sql += " AND status = ?";
2881
- binds.push(targetStatus);
2882
- }
2883
- if (navTenantId) {
2884
- sql += " AND (tenant_id = ? OR tenant_id IS NULL)";
2885
- binds.push(navTenantId);
2886
- }
2887
- if (options?.locale) {
2888
- sql += " AND (locale = ? OR locale = 'en' OR locale IS NULL)";
2889
- binds.push(options.locale);
2890
- }
2891
- if (options?.path) {
2892
- const searchPath = ("/" + options.path.replace(/\\/g, "/").replace(/^\/+/, "")).replace(
2893
- /\/+$/,
2894
- ""
2895
- );
2896
- sql += " AND (path = ? OR path LIKE ?)";
2897
- binds.push(searchPath, `${searchPath}/%`);
2898
- }
2899
- sql += ' ORDER BY "order" ASC';
2900
- let rows = [];
2901
- if (db) {
2902
- try {
2903
- const all = await db.prepare(sql).bind(...binds).all();
2904
- rows = all.results || [];
2905
- } catch {
2906
- }
2907
- }
2908
- if (!rows.length) {
2909
- try {
2910
- const { manifestEntries } = await import("#qarpeo/cms/manifest");
2911
- rows = (manifestEntries || []).filter((e) => e.collection_id === collectionId).map((e) => ({
2912
- id: e.id,
2913
- slug: e.slug,
2914
- path: e.path,
2915
- title: e.title,
2916
- order: e.order ?? 0,
2917
- metadata_json: typeof e.metadata_json === "string" ? e.metadata_json : JSON.stringify(e.metadata || {})
2918
- }));
2919
- } catch {
2920
- }
2921
- }
2922
- const sectionsMap = /* @__PURE__ */ new Map();
2923
- for (const r of rows) {
2924
- let meta = {};
2925
- try {
2926
- meta = JSON.parse(r.metadata_json || "{}");
2927
- } catch {
2928
- }
2929
- const sectionMeta = meta._section || {};
2930
- const isHiddenFromNav = meta.navigation === false || meta.hidden === true || meta.navigation?.hidden === true || meta._nav?.navigation === false || meta._nav?.hidden === true || sectionMeta?.navigation === false || sectionMeta?.hidden === true;
2931
- if (isHiddenFromNav) {
2932
- continue;
2933
- }
2934
- if (options?.where && !matchesWhereFilter(r, meta, options.where)) {
2935
- continue;
2936
- }
2937
- const entryPath = r.path || `/${collectionId}/${r.slug}`;
2938
- const segments = entryPath.split("/").filter(Boolean);
2939
- const sectionPath = segments.length >= 2 ? `/${segments[0]}/${segments[1]}` : entryPath;
2940
- const defaultSectionTitle = segments.length >= 2 ? segments[1].charAt(0).toUpperCase() + segments[1].slice(1).replace(/-/g, " ") : r.title;
2941
- if (!sectionsMap.has(sectionPath)) {
2942
- const initialTitle = sectionMeta.title || defaultSectionTitle;
2943
- sectionsMap.set(sectionPath, {
2944
- title: initialTitle,
2945
- path: sectionPath,
2946
- icon: sectionMeta.icon,
2947
- children: [],
2948
- _order: meta._sectionOrder ?? (r.order ? Math.floor(r.order / 1e3) : 500)
2949
- });
2950
- }
2951
- const section = sectionsMap.get(sectionPath);
2952
- const itemTitle = meta.navigation?.title || meta._itemTitle || r.title;
2953
- const rawNavIcon = meta.navigation?.icon ?? meta.icon;
2954
- const itemIcon = rawNavIcon === false || rawNavIcon === null || rawNavIcon === "" ? void 0 : rawNavIcon;
2955
- const itemOrder = meta._isIndex ? 0 : typeof meta.navigation?.order === "number" ? meta.navigation.order : typeof meta.order === "number" ? meta.order : typeof meta._itemOrder === "number" ? meta._itemOrder : typeof meta._fileOrder === "number" ? meta._fileOrder : r.order ? r.order % 50 : 500;
2956
- if (entryPath === sectionPath) {
2957
- if (sectionMeta.title) section.title = sectionMeta.title;
2958
- if (sectionMeta.icon) section.icon = sectionMeta.icon;
2959
- if (sectionMeta.isolated !== void 0) section.isolated = sectionMeta.isolated;
2960
- if (meta._nav?.title) section.title = meta._nav.title;
2961
- if (meta._nav?.icon) section.icon = meta._nav.icon;
2962
- if (meta._nav?.isolated !== void 0) section.isolated = meta._nav.isolated;
2963
- section.children = section.children || [];
2964
- section.children.push({
2965
- title: itemTitle,
2966
- path: entryPath,
2967
- icon: itemIcon,
2968
- _groupOrder: itemOrder
2969
- });
2970
- continue;
2971
- }
2972
- if (meta._group) {
2973
- const groupKey = meta._group.key;
2974
- let groupItem = section.children?.find((c) => c._groupKey === groupKey);
2975
- if (!groupItem) {
2976
- groupItem = {
2977
- title: meta._group.title,
2978
- icon: meta._group.icon,
2979
- type: "group",
2980
- children: [],
2981
- _groupKey: groupKey,
2982
- _groupOrder: meta._group.order ?? 999
2983
- };
2984
- section.children = section.children || [];
2985
- section.children.push(groupItem);
2986
- }
2987
- const gi = groupItem;
2988
- gi.children = gi.children || [];
2989
- gi.children.push({
2990
- title: itemTitle,
2991
- path: entryPath,
2992
- icon: itemIcon,
2993
- _groupOrder: itemOrder
2994
- });
2995
- continue;
2996
- }
2997
- const folderSegments = meta._isIndex ? segments.slice(2) : segments.slice(2, -1);
2998
- let currentParent = section;
2999
- let currentPath = sectionPath;
3000
- for (let i = 0; i < folderSegments.length; i++) {
3001
- const folderSeg = folderSegments[i];
3002
- currentPath += `/${folderSeg}`;
3003
- const isLeafFolder = i === folderSegments.length - 1;
3004
- let subNode = currentParent.children?.find(
3005
- (c) => c._folderKey === folderSeg || c.path === currentPath
3006
- );
3007
- if (!subNode) {
3008
- const folderTitle = isLeafFolder && meta._nav?.title ? meta._nav.title : folderSeg.charAt(0).toUpperCase() + folderSeg.slice(1).replace(/-/g, " ");
3009
- const folderIcon = isLeafFolder ? meta._nav?.icon : void 0;
3010
- const folderOrder = isLeafFolder && typeof meta._nav?.order === "number" ? meta._nav.order : isLeafFolder && typeof meta._fileOrder === "number" ? meta._fileOrder : 500;
3011
- const newNode = {
3012
- title: folderTitle,
3013
- path: currentPath,
3014
- icon: folderIcon,
3015
- isolated: isLeafFolder ? meta._nav?.isolated : void 0,
3016
- children: [],
3017
- _folderKey: folderSeg,
3018
- _groupOrder: folderOrder
3019
- };
3020
- if (folderSegments.length > 1 && i > 0) {
3021
- newNode.type = "group";
3022
- }
3023
- currentParent.children = currentParent.children || [];
3024
- currentParent.children.push(newNode);
3025
- subNode = newNode;
3026
- } else if (isLeafFolder) {
3027
- if (meta._nav?.title) subNode.title = meta._nav.title;
3028
- if (meta._nav?.icon) subNode.icon = meta._nav.icon;
3029
- if (meta._nav?.isolated !== void 0) subNode.isolated = meta._nav.isolated;
3030
- if (typeof meta._nav?.order === "number") subNode._groupOrder = meta._nav.order;
3031
- }
3032
- currentParent = subNode;
3033
- }
3034
- if (meta._isIndex && folderSegments.length > 0) {
3035
- if (!currentParent.isolated) {
3036
- currentParent.children = currentParent.children || [];
3037
- currentParent.children.push({
3038
- title: itemTitle || "Overview",
3039
- path: entryPath,
3040
- icon: itemIcon,
3041
- _groupOrder: 0
3042
- });
3043
- }
3044
- continue;
3045
- }
3046
- currentParent.children = currentParent.children || [];
3047
- currentParent.children.push({
3048
- title: itemTitle,
3049
- path: entryPath,
3050
- icon: itemIcon,
3051
- _groupOrder: itemOrder
3052
- });
3053
- }
3054
- function cleanAndSortNode(item) {
3055
- if (item.path && !item.to) {
3056
- item.to = item.path;
3057
- }
3058
- if (item.children) {
3059
- item.children.sort((a, b) => {
3060
- if (a.path === item.path) return -1;
3061
- if (b.path === item.path) return 1;
3062
- const orderA = a._groupOrder ?? 500;
3063
- const orderB = b._groupOrder ?? 500;
3064
- if (orderA !== orderB) return orderA - orderB;
3065
- return (a.title || "").localeCompare(b.title || "");
3066
- });
3067
- for (const c of item.children) {
3068
- if (c.path && !c.to) {
3069
- c.to = c.path;
3070
- }
3071
- delete c._folderKey;
3072
- delete c._groupKey;
3073
- delete c._groupOrder;
3074
- delete c._subGroupKey;
3075
- delete c._subFeatureKey;
3076
- delete c._appKey;
3077
- cleanAndSortNode(c);
3078
- }
3079
- }
3080
- }
3081
- for (const s of sectionsMap.values()) {
3082
- cleanAndSortNode(s);
3083
- }
3084
- const sectionsList = Array.from(sectionsMap.values());
3085
- sectionsList.sort((a, b) => {
3086
- const orderA = a._order ?? 500;
3087
- const orderB = b._order ?? 500;
3088
- if (orderA !== orderB) return orderA - orderB;
3089
- return a.title.localeCompare(b.title);
3090
- });
3091
- for (const s of sectionsList) {
3092
- if (s.path && !s.to) {
3093
- s.to = s.path;
3094
- }
3095
- delete s._order;
3096
- }
3097
- let result = sectionsList;
3098
- if (options?.unwrap) {
3099
- if (result.length === 1 && result[0].children?.length) {
3100
- result = result[0].children;
3101
- } else {
3102
- const collectionRoot = result.find((item) => item.path === `/${collectionId}`);
3103
- if (collectionRoot?.children?.length) {
3104
- result = collectionRoot.children;
3105
- }
3106
- }
3107
- }
3108
- if (options?.path) {
3109
- const searchPath = ("/" + options.path.replace(/\\/g, "/").replace(/^\/+/, "")).replace(
3110
- /\/+$/,
3111
- ""
3112
- );
3113
- const matchedSection = sectionsList.find((s) => s.path === searchPath);
3114
- if (matchedSection && matchedSection.children?.length) {
3115
- result = matchedSection.children;
3116
- } else {
3117
- const findNode = (items) => {
3118
- for (const item of items) {
3119
- if (item.path === searchPath) return item;
3120
- if (item.children) {
3121
- const found = findNode(item.children);
3122
- if (found) return found;
3123
- }
3124
- }
3125
- };
3126
- const deepNode = findNode(sectionsList);
3127
- if (deepNode) {
3128
- result = deepNode.children?.length ? deepNode.children : [deepNode];
3129
- }
3130
- }
3131
- }
3132
- if (options?.levels != null && options.levels > 0) {
3133
- pruneTreeLevels(result, 1, options.levels);
3134
- }
3135
- if (options?.skip != null || options?.limit != null) {
3136
- const skip = options?.skip ?? 0;
3137
- const limit = options?.limit ?? result.length;
3138
- result = result.slice(skip, skip + limit);
3139
- }
3140
- return result;
3141
- }
3142
- export function queryCollection(event, collection) {
3143
- let _path = null;
3144
- let _locale = null;
3145
- let _limit = null;
3146
- let _page = 1;
3147
- let _sort = null;
3148
- let _tag = null;
3149
- let _status = "published";
3150
- let _preview = false;
3151
- let _fields = [];
3152
- const _wheres = {};
3153
- const builder = {
3154
- select(...fields) {
3155
- _fields = fields.flatMap((f) => typeof f === "string" ? f.split(",") : []).map((s) => s.trim()).filter(Boolean);
3156
- return builder;
3157
- },
3158
- locale(loc) {
3159
- _locale = loc;
3160
- return builder;
3161
- },
3162
- path(p) {
3163
- _path = p;
3164
- return builder;
3165
- },
3166
- limit(n) {
3167
- _limit = n;
3168
- return builder;
3169
- },
3170
- page(n) {
3171
- _page = n;
3172
- return builder;
3173
- },
3174
- order(field, direction = "ASC") {
3175
- const sanitizedField = String(field || "").replace(/[^a-zA-Z0-9_]/g, "");
3176
- const dir = String(direction).trim().toUpperCase() === "DESC" ? "desc" : "asc";
3177
- _sort = `${sanitizedField || "published_at"}:${dir}`;
3178
- return builder;
3179
- },
3180
- where(field, value) {
3181
- _wheres[field] = value;
3182
- return builder;
3183
- },
3184
- status(s) {
3185
- _status = s;
3186
- return builder;
3187
- },
3188
- tag(t) {
3189
- _tag = t;
3190
- return builder;
3191
- },
3192
- preview(enabled = true) {
3193
- _preview = enabled;
3194
- if (enabled) _status = "all";
3195
- return builder;
3196
- },
3197
- async first() {
3198
- if (_path) {
3199
- return await getCMSEntryByPath(event, collection, _path, _locale || void 0, {
3200
- preview: _preview,
3201
- fields: _fields.length ? _fields : void 0
3202
- });
3203
- }
3204
- const res = await queryCMSEntries(event, collection, {
3205
- limit: 1,
3206
- page: _page,
3207
- sort: _sort || void 0,
3208
- status: _status,
3209
- tag: _tag || void 0,
3210
- preview: _preview,
3211
- where: Object.keys(_wheres).length ? _wheres : void 0,
3212
- fields: _fields.length ? _fields : void 0
3213
- });
3214
- return res.entries[0] || null;
3215
- },
3216
- async all() {
3217
- const res = await queryCMSEntries(event, collection, {
3218
- limit: _limit || 100,
3219
- page: _page,
3220
- sort: _sort || void 0,
3221
- status: _status,
3222
- tag: _tag || void 0,
3223
- preview: _preview,
3224
- where: Object.keys(_wheres).length ? _wheres : void 0,
3225
- fields: _fields.length ? _fields : void 0
3226
- });
3227
- return res.entries;
3228
- },
3229
- async count() {
3230
- const res = await queryCMSEntries(event, collection, {
3231
- limit: 1,
3232
- page: 1,
3233
- status: _status,
3234
- tag: _tag || void 0,
3235
- preview: _preview,
3236
- where: Object.keys(_wheres).length ? _wheres : void 0
3237
- });
3238
- return res.total;
3239
- }
3240
- };
3241
- return builder;
3242
- }
3243
- export async function queryCMSCategories(event, opts) {
3244
- const db = getCMSDb(event);
3245
- if (!db) return [];
3246
- const tenantId = event ? getCMSTenantId(event) : null;
3247
- const conditions = [];
3248
- const binds = [];
3249
- if (tenantId) {
3250
- conditions.push("(tenant_id = ? OR tenant_id IS NULL)");
3251
- binds.push(tenantId);
3252
- }
3253
- if (opts?.parentId !== void 0) {
3254
- if (opts.parentId === null) {
3255
- conditions.push("parent_id IS NULL");
3256
- } else {
3257
- conditions.push("parent_id = ?");
3258
- binds.push(opts.parentId);
3259
- }
3260
- }
3261
- const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
3262
- const query = `SELECT * FROM _qarpeo_cms_categories ${where} ORDER BY "order" ASC, name ASC`;
3263
- const res = await db.prepare(query).bind(...binds).all().catch(() => ({ results: [] }));
3264
- return res?.results || [];
3265
- }
3266
- export async function createCMSCategory(event, data) {
3267
- const db = getCMSDb(event);
3268
- if (!db) throw new Error("Database not available");
3269
- const id = data.id || nanoid();
3270
- const slug = data.slug || data.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
3271
- const tenantId = getCMSTenantId(event);
3272
- const now = Date.now();
3273
- const metadataJson = data.metadataJson || (data.metadata ? JSON.stringify(data.metadata) : "{}");
3274
- await db.prepare(
3275
- 'INSERT INTO _qarpeo_cms_categories (id, tenant_id, name, slug, description, icon, parent_id, "order", metadata_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
3276
- ).bind(
3277
- id,
3278
- tenantId,
3279
- data.name,
3280
- slug,
3281
- data.description || null,
3282
- data.icon || null,
3283
- data.parentId || null,
3284
- data.order || 0,
3285
- metadataJson,
3286
- now,
3287
- now
3288
- ).run();
3289
- return {
3290
- id,
3291
- name: data.name,
3292
- slug,
3293
- description: data.description,
3294
- icon: data.icon,
3295
- parentId: data.parentId,
3296
- order: data.order || 0,
3297
- metadataJson,
3298
- createdAt: now,
3299
- updatedAt: now
3300
- };
3301
- }
3302
- export async function updateCMSCategory(event, id, data) {
3303
- const db = getCMSDb(event);
3304
- if (!db) throw new Error("Database not available");
3305
- const tenantId = getCMSTenantId(event);
3306
- const now = Date.now();
3307
- const updates = ["updated_at = ?"];
3308
- const binds = [now];
3309
- if (data.name !== void 0) {
3310
- updates.push("name = ?");
3311
- binds.push(data.name);
3312
- }
3313
- if (data.slug !== void 0) {
3314
- updates.push("slug = ?");
3315
- binds.push(data.slug);
3316
- }
3317
- if (data.description !== void 0) {
3318
- updates.push("description = ?");
3319
- binds.push(data.description);
3320
- }
3321
- if (data.icon !== void 0) {
3322
- updates.push("icon = ?");
3323
- binds.push(data.icon);
3324
- }
3325
- if (data.parentId !== void 0) {
3326
- updates.push("parent_id = ?");
3327
- binds.push(data.parentId);
3328
- }
3329
- if (data.order !== void 0) {
3330
- updates.push('"order" = ?');
3331
- binds.push(data.order);
3332
- }
3333
- if (data.metadata !== void 0 || data.metadataJson !== void 0) {
3334
- const metaStr = data.metadataJson || (data.metadata ? JSON.stringify(data.metadata) : "{}");
3335
- updates.push("metadata_json = ?");
3336
- binds.push(metaStr);
3337
- }
3338
- let query = `UPDATE _qarpeo_cms_categories SET ${updates.join(", ")} WHERE id = ?`;
3339
- binds.push(id);
3340
- if (tenantId) {
3341
- query += " AND (tenant_id = ? OR tenant_id IS NULL)";
3342
- binds.push(tenantId);
3343
- }
3344
- await db.prepare(query).bind(...binds).run();
3345
- return { success: true, id };
3346
- }
3347
- export async function deleteCMSCategory(event, id) {
3348
- const db = getCMSDb(event);
3349
- if (!db) throw new Error("Database not available");
3350
- const tenantId = getCMSTenantId(event);
3351
- const query = tenantId ? "DELETE FROM _qarpeo_cms_categories WHERE id = ? AND (tenant_id = ? OR tenant_id IS NULL)" : "DELETE FROM _qarpeo_cms_categories WHERE id = ?";
3352
- const binds = tenantId ? [id, tenantId] : [id];
3353
- await db.prepare(query).bind(...binds).run();
3354
- return { success: true, deletedId: id };
3355
- }
3356
- export async function syncCMSEntryTags(event, oldTagsString, newTagsString) {
3357
- const db = getCMSDb(event);
3358
- if (!db) return;
3359
- const parseTags = (str) => {
3360
- if (!str) return [];
3361
- return str.split(",").map((t) => t.trim().toLowerCase()).filter((t) => t.length > 0);
3362
- };
3363
- const oldTags = parseTags(oldTagsString);
3364
- const newTags = parseTags(newTagsString);
3365
- const added = newTags.filter((t) => !oldTags.includes(t));
3366
- const removed = oldTags.filter((t) => !newTags.includes(t));
3367
- const tenantId = getCMSTenantId(event);
3368
- const now = Date.now();
3369
- for (const tagName of added) {
3370
- const slug = tagName.replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
3371
- try {
3372
- const existing = await db.prepare(
3373
- `SELECT id, count FROM _qarpeo_cms_tags WHERE slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
3374
- ).bind(...tenantId ? [slug, tenantId] : [slug]).first();
3375
- if (existing) {
3376
- await db.prepare("UPDATE _qarpeo_cms_tags SET count = count + 1, updated_at = ? WHERE id = ?").bind(now, existing.id).run();
3377
- } else {
3378
- const id = nanoid();
3379
- await db.prepare(
3380
- "INSERT INTO _qarpeo_cms_tags (id, tenant_id, name, slug, count, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?)"
3381
- ).bind(id, tenantId, tagName, slug, now, now).run();
3382
- }
3383
- } catch (err) {
3384
- console.warn("[qarpeo:cms] syncCMSEntryTags add error:", err);
3385
- }
3386
- }
3387
- for (const tagName of removed) {
3388
- const slug = tagName.replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
3389
- try {
3390
- await db.prepare(
3391
- `UPDATE _qarpeo_cms_tags SET count = MAX(0, count - 1), updated_at = ? WHERE slug = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""}`
3392
- ).bind(...tenantId ? [now, slug, tenantId] : [now, slug]).run();
3393
- } catch (err) {
3394
- console.warn("[qarpeo:cms] syncCMSEntryTags remove error:", err);
3395
- }
3396
- }
3397
- }
3398
- export async function queryCMSTags(event) {
3399
- const db = getCMSDb(event);
3400
- if (!db) return [];
3401
- const tenantId = event ? getCMSTenantId(event) : null;
3402
- const query = tenantId ? "SELECT * FROM _qarpeo_cms_tags WHERE tenant_id = ? OR tenant_id IS NULL ORDER BY count DESC, name ASC" : "SELECT * FROM _qarpeo_cms_tags ORDER BY count DESC, name ASC";
3403
- const binds = tenantId ? [tenantId] : [];
3404
- const res = await db.prepare(query).bind(...binds).all().catch(() => ({ results: [] }));
3405
- return res?.results || [];
3406
- }
3407
- export async function createCMSTag(event, data) {
3408
- const db = getCMSDb(event);
3409
- if (!db) throw new Error("Database not available");
3410
- const id = nanoid();
3411
- const slug = data.slug || data.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
3412
- const tenantId = getCMSTenantId(event);
3413
- const now = Date.now();
3414
- await db.prepare(
3415
- "INSERT OR IGNORE INTO _qarpeo_cms_tags (id, tenant_id, name, slug, description, count, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?)"
3416
- ).bind(id, tenantId, data.name, slug, data.description || null, now, now).run();
3417
- return { id, name: data.name, slug, description: data.description };
3418
- }
3419
- export async function deleteCMSTag(event, id) {
3420
- const db = getCMSDb(event);
3421
- if (!db) throw new Error("Database not available");
3422
- const tenantId = getCMSTenantId(event);
3423
- const query = tenantId ? "DELETE FROM _qarpeo_cms_tags WHERE id = ? AND (tenant_id = ? OR tenant_id IS NULL)" : "DELETE FROM _qarpeo_cms_tags WHERE id = ?";
3424
- const binds = tenantId ? [id, tenantId] : [id];
3425
- await db.prepare(query).bind(...binds).run();
3426
- return { success: true, deletedId: id };
3427
- }
3428
- export async function getCMSComment(event, id) {
3429
- return await getComment(id, event);
3430
- }
3431
- export async function queryCMSComments(event, optsOrEntryId, statusArg) {
3432
- const opts = typeof optsOrEntryId === "string" ? { entryId: optsOrEntryId, status: statusArg || "approved", threaded: true } : optsOrEntryId || {};
3433
- const entryId = opts.entryId || "";
3434
- const targetUrn = entryId.startsWith("urn:") ? entryId : `urn:cms:entry:${entryId}`;
3435
- const res = await queryComments(
3436
- {
3437
- targetUrn,
3438
- status: (opts.status === "all" ? void 0 : opts.status) || "approved",
3439
- parentId: opts.parentId,
3440
- threaded: opts.threaded !== false,
3441
- limit: opts.limit,
3442
- offset: opts.offset
3443
- },
3444
- event
3445
- );
3446
- return res.comments;
3447
- }
3448
- export async function createCMSComment(event, data) {
3449
- const urn = data.entryId.startsWith("urn:") ? data.entryId : `urn:cms:entry:${data.entryId}`;
3450
- return await createComment(
3451
- {
3452
- targetUrn: urn,
3453
- parentId: data.parentId,
3454
- authorName: data.authorName,
3455
- authorEmail: data.authorEmail,
3456
- content: data.content
3457
- },
3458
- event
3459
- );
3460
- }
3461
- export async function updateCMSCommentStatus(event, id, status) {
3462
- return await updateCommentStatus(id, status, event);
3463
- }
3464
- export async function deleteCMSComment(event, id) {
3465
- await deleteComment(id, event);
3466
- return { success: true, deletedId: id };
3467
- }
3468
- export async function subscribeCMSNewsletter(event, email, source = "website") {
3469
- const db = getCMSDb(event);
3470
- if (!db) throw new Error("Database not available");
3471
- const id = nanoid();
3472
- const tenantId = getCMSTenantId(event);
3473
- const normalizedEmail = email.toLowerCase().trim();
3474
- const now = Date.now();
3475
- const existing = await db.prepare(
3476
- `SELECT id, status FROM _qarpeo_cms_subscribers WHERE email = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`
3477
- ).bind(...tenantId ? [normalizedEmail, tenantId] : [normalizedEmail]).first().catch(() => null);
3478
- if (existing?.id) {
3479
- if (existing.status !== "active") {
3480
- await db.prepare(
3481
- "UPDATE _qarpeo_cms_subscribers SET status = 'active', source = ? WHERE id = ?"
3482
- ).bind(source, existing.id).run();
3483
- }
3484
- return { success: true, email: normalizedEmail, existing: true };
3485
- }
3486
- await db.prepare(
3487
- "INSERT OR IGNORE INTO _qarpeo_cms_subscribers (id, tenant_id, email, status, source, created_at) VALUES (?, ?, ?, 'active', ?, ?)"
3488
- ).bind(id, tenantId, normalizedEmail, source, now).run();
3489
- return { success: true, email: normalizedEmail };
3490
- }
3491
- export async function queryCMSSubscribers(event, opts) {
3492
- const db = getCMSDb(event);
3493
- if (!db) return [];
3494
- const tenantId = event ? getCMSTenantId(event) : null;
3495
- let query = "SELECT id, email, status, source, created_at as createdAt FROM _qarpeo_cms_subscribers";
3496
- const conditions = [];
3497
- const binds = [];
3498
- if (opts?.status && opts.status !== "all") {
3499
- conditions.push("status = ?");
3500
- binds.push(opts.status);
3501
- }
3502
- if (tenantId) {
3503
- conditions.push("(tenant_id = ? OR tenant_id IS NULL)");
3504
- binds.push(tenantId);
3505
- }
3506
- if (conditions.length > 0) {
3507
- query += " WHERE " + conditions.join(" AND ");
3508
- }
3509
- query += " ORDER BY created_at DESC";
3510
- if (opts?.limit) {
3511
- query += ` LIMIT ${opts.limit}`;
3512
- if (opts.offset) {
3513
- query += ` OFFSET ${opts.offset}`;
3514
- }
3515
- }
3516
- const res = await db.prepare(query).bind(...binds).all().catch(() => ({ results: [] }));
3517
- return res?.results || [];
3518
- }
3519
- export async function deleteCMSSubscriber(event, id) {
3520
- const db = getCMSDb(event);
3521
- if (!db) throw new Error("Database not available");
3522
- const tenantId = getCMSTenantId(event);
3523
- const query = tenantId ? "DELETE FROM _qarpeo_cms_subscribers WHERE id = ? AND (tenant_id = ? OR tenant_id IS NULL)" : "DELETE FROM _qarpeo_cms_subscribers WHERE id = ?";
3524
- const binds = tenantId ? [id, tenantId] : [id];
3525
- await db.prepare(query).bind(...binds).run();
3526
- return { success: true, deletedId: id };
3527
- }
3528
- export async function updateCMSSubscriberStatus(event, id, status) {
3529
- const db = getCMSDb(event);
3530
- if (!db) throw new Error("Database not available");
3531
- const tenantId = getCMSTenantId(event);
3532
- const query = tenantId ? "UPDATE _qarpeo_cms_subscribers SET status = ? WHERE id = ? AND (tenant_id = ? OR tenant_id IS NULL)" : "UPDATE _qarpeo_cms_subscribers SET status = ? WHERE id = ?";
3533
- const binds = tenantId ? [status, id, tenantId] : [status, id];
3534
- await db.prepare(query).bind(...binds).run();
3535
- return { success: true, id, status };
3536
- }
3537
- export async function queryCMSBookmarks(event, userId) {
3538
- const db = getCMSDb(event);
3539
- if (!db) return [];
3540
- const tenantId = getCMSTenantId(event);
3541
- const query = `
3542
- SELECT
3543
- b.id,
3544
- b.user_id as userId,
3545
- b.entry_id as entryId,
3546
- b.created_at as createdAt,
3547
- e.title,
3548
- e.slug,
3549
- e.description,
3550
- e.cover_image as coverImage,
3551
- e.collection_id as collectionId,
3552
- e.published_at as publishedAt
3553
- FROM _qarpeo_cms_bookmarks b
3554
- LEFT JOIN _qarpeo_cms_entries e ON b.entry_id = e.id
3555
- WHERE b.user_id = ? ${tenantId ? "AND (b.tenant_id = ? OR b.tenant_id IS NULL)" : ""}
3556
- ORDER BY b.created_at DESC
3557
- `;
3558
- const binds = tenantId ? [userId, tenantId] : [userId];
3559
- const res = await db.prepare(query).bind(...binds).all().catch(() => ({ results: [] }));
3560
- return res?.results || [];
3561
- }
3562
- export async function isCMSBookmarked(event, userId, entryId) {
3563
- const db = getCMSDb(event);
3564
- if (!db) return false;
3565
- const tenantId = getCMSTenantId(event);
3566
- const query = `SELECT id FROM _qarpeo_cms_bookmarks WHERE user_id = ? AND entry_id = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`;
3567
- const binds = tenantId ? [userId, entryId, tenantId] : [userId, entryId];
3568
- const res = await db.prepare(query).bind(...binds).first().catch(() => null);
3569
- return !!res;
3570
- }
3571
- export async function toggleCMSBookmark(event, userId, entryId) {
3572
- const db = getCMSDb(event);
3573
- if (!db) throw new Error("Database not available");
3574
- const tenantId = getCMSTenantId(event);
3575
- const checkQuery = `SELECT id FROM _qarpeo_cms_bookmarks WHERE user_id = ? AND entry_id = ? ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`;
3576
- const checkBinds = tenantId ? [userId, entryId, tenantId] : [userId, entryId];
3577
- const existing = await db.prepare(checkQuery).bind(...checkBinds).first().catch(() => null);
3578
- if (existing?.id) {
3579
- const delQuery = "DELETE FROM _qarpeo_cms_bookmarks WHERE id = ?";
3580
- await db.prepare(delQuery).bind(existing.id).run();
3581
- return { bookmarked: false, id: existing.id };
3582
- } else {
3583
- const id = nanoid();
3584
- const now = Date.now();
3585
- const insertQuery = "INSERT OR IGNORE INTO _qarpeo_cms_bookmarks (id, tenant_id, user_id, entry_id, created_at) VALUES (?, ?, ?, ?, ?)";
3586
- await db.prepare(insertQuery).bind(id, tenantId, userId, entryId, now).run();
3587
- return { bookmarked: true, id };
3588
- }
3589
- }
3590
- export async function deleteCMSBookmark(event, id, userId) {
3591
- const db = getCMSDb(event);
3592
- if (!db) throw new Error("Database not available");
3593
- const tenantId = getCMSTenantId(event);
3594
- let query = "DELETE FROM _qarpeo_cms_bookmarks WHERE id = ?";
3595
- const binds = [id];
3596
- if (userId) {
3597
- query += " AND user_id = ?";
3598
- binds.push(userId);
3599
- }
3600
- if (tenantId) {
3601
- query += " AND (tenant_id = ? OR tenant_id IS NULL)";
3602
- binds.push(tenantId);
3603
- }
3604
- await db.prepare(query).bind(...binds).run();
3605
- return { success: true, deletedId: id };
3606
- }
3607
- export async function incrementCMSEntryViews(event, collectionId, slugOrId) {
3608
- const db = getCMSDb(event);
3609
- if (!db) return { views: 0 };
3610
- const tenantId = getCMSTenantId(event);
3611
- const query = `SELECT id, view_count FROM _qarpeo_cms_entries WHERE collection_id = ? AND (slug = ? OR id = ?) ${tenantId ? "AND (tenant_id = ? OR tenant_id IS NULL)" : ""} LIMIT 1`;
3612
- const binds = tenantId ? [collectionId, slugOrId, slugOrId, tenantId] : [collectionId, slugOrId, slugOrId];
3613
- const entry = await db.prepare(query).bind(...binds).first().catch(() => null);
3614
- if (!entry?.id) return { views: 0 };
3615
- const newViews = Number(entry.view_count || 0) + 1;
3616
- const updateQuery = "UPDATE _qarpeo_cms_entries SET view_count = view_count + 1 WHERE id = ?";
3617
- await db.prepare(updateQuery).bind(entry.id).run();
3618
- return { id: entry.id, views: newViews };
3619
- }