qarpeo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/chunks/tools.mjs +993 -31
  2. package/dist/cli/index.mjs +1102 -31
  3. package/dist/fate/index.d.ts +9 -1
  4. package/dist/fate/index.mjs +20 -3
  5. package/dist/module.mjs +296 -753
  6. package/dist/runtime/browser.mjs +2 -2
  7. package/dist/runtime/comments-server.d.ts +3 -0
  8. package/dist/runtime/comments-server.mjs +2 -0
  9. package/dist/runtime/comments.d.ts +0 -2
  10. package/dist/runtime/comments.mjs +0 -2
  11. package/dist/runtime/db.d.ts +10 -9
  12. package/dist/runtime/db.mjs +79 -8
  13. package/dist/runtime/drizzle.mjs +21 -6
  14. package/dist/runtime/index.d.ts +4 -0
  15. package/dist/runtime/realtime-server.d.ts +4 -0
  16. package/dist/runtime/realtime-server.mjs +13 -0
  17. package/dist/runtime/realtime.d.ts +1 -4
  18. package/dist/runtime/realtime.mjs +0 -13
  19. package/dist/runtime/replica.d.ts +27 -0
  20. package/dist/runtime/replica.mjs +229 -0
  21. package/dist/runtime/server/durable-objects/agent.mjs +14 -2
  22. package/dist/runtime/server/durable-objects/room.d.ts +10 -0
  23. package/dist/runtime/server/durable-objects/room.mjs +119 -28
  24. package/dist/runtime/server/middleware/devtools.mjs +1 -1
  25. package/dist/runtime/server/middleware/tenancy.mjs +7 -4
  26. package/dist/runtime/server/plugins/store.mjs +1 -1
  27. package/dist/runtime/server/routes/__qarpeo/mail/track/click/[id].get.mjs +57 -17
  28. package/dist/runtime/server/routes/agents/[agent]/chat.post.mjs +19 -12
  29. package/dist/runtime/server/routes/agents/[agent]/clear.post.mjs +8 -9
  30. package/dist/runtime/server/routes/agents/[agent]/history.get.mjs +8 -9
  31. package/dist/runtime/server/routes/analytics/events.get.mjs +12 -2
  32. package/dist/runtime/server/routes/analytics/pageviews.get.mjs +10 -1
  33. package/dist/runtime/server/routes/analytics/summary.get.mjs +10 -1
  34. package/dist/runtime/server/routes/auth/2fa/disable.post.mjs +11 -2
  35. package/dist/runtime/server/routes/auth/2fa/setup.post.mjs +7 -0
  36. package/dist/runtime/server/routes/auth/2fa/verify.post.mjs +11 -2
  37. package/dist/runtime/server/routes/auth/account.delete.mjs +7 -0
  38. package/dist/runtime/server/routes/auth/magic-link/verify.get.mjs +5 -3
  39. package/dist/runtime/server/routes/auth/organization/sso/index.post.mjs +10 -0
  40. package/dist/runtime/server/routes/auth/otp/verify.post.mjs +5 -3
  41. package/dist/runtime/server/routes/auth/sso/saml/acs.post.mjs +18 -0
  42. package/dist/runtime/server/routes/auth/webauthn/login/options.post.d.ts +1 -1
  43. package/dist/runtime/server/routes/auth/webauthn/login/options.post.mjs +11 -2
  44. package/dist/runtime/server/routes/auth/webauthn/login/verify.post.mjs +10 -1
  45. package/dist/runtime/server/routes/auth/webauthn/register/options.post.d.ts +1 -1
  46. package/dist/runtime/server/routes/auth/webauthn/register/options.post.mjs +10 -1
  47. package/dist/runtime/server/routes/auth/webauthn/register/verify.post.mjs +10 -1
  48. package/dist/runtime/server/routes/browser/crawl.post.mjs +13 -0
  49. package/dist/runtime/server/routes/browser/invoice.post.mjs +15 -1
  50. package/dist/runtime/server/routes/browser/og-image.post.mjs +13 -0
  51. package/dist/runtime/server/routes/browser/pdf.post.mjs +15 -1
  52. package/dist/runtime/server/routes/browser/screenshot.post.mjs +13 -0
  53. package/dist/runtime/server/routes/cms/[collection]/[id]/preview-token.post.mjs +23 -8
  54. package/dist/runtime/server/routes/cms/[collection]/[id]/publish.post.mjs +2 -1
  55. package/dist/runtime/server/routes/cms/[collection]/[id]/review.post.mjs +2 -1
  56. package/dist/runtime/server/routes/cms/[collection]/[id]/revisions/[revId]/restore.post.mjs +2 -1
  57. package/dist/runtime/server/routes/cms/[collection]/[id].delete.mjs +2 -1
  58. package/dist/runtime/server/routes/cms/[collection]/[id].put.mjs +2 -1
  59. package/dist/runtime/server/routes/cms/[collection]/index.post.mjs +2 -1
  60. package/dist/runtime/server/routes/cms/categories/[id].delete.mjs +2 -1
  61. package/dist/runtime/server/routes/cms/categories/[id].put.mjs +2 -1
  62. package/dist/runtime/server/routes/cms/categories.post.mjs +2 -1
  63. package/dist/runtime/server/routes/cms/collections/[id].delete.mjs +2 -1
  64. package/dist/runtime/server/routes/cms/collections/[id].put.mjs +2 -1
  65. package/dist/runtime/server/routes/cms/collections/index.post.mjs +2 -1
  66. package/dist/runtime/server/routes/cms/export.post.mjs +1 -1
  67. package/dist/runtime/server/routes/cms/subscribers/[id].delete.mjs +2 -1
  68. package/dist/runtime/server/routes/cms/subscribers/[id].patch.mjs +2 -1
  69. package/dist/runtime/server/routes/cms/tags/[id].delete.mjs +2 -1
  70. package/dist/runtime/server/routes/cms/tags.post.mjs +2 -1
  71. package/dist/runtime/server/routes/comments/[id]/react.post.mjs +7 -3
  72. package/dist/runtime/server/routes/comments/[id]/report.post.mjs +3 -0
  73. package/dist/runtime/server/routes/comments/[id].delete.mjs +1 -1
  74. package/dist/runtime/server/routes/comments/[id].get.mjs +13 -0
  75. package/dist/runtime/server/routes/comments/[id].patch.mjs +1 -1
  76. package/dist/runtime/server/routes/fate.d.ts +6 -0
  77. package/dist/runtime/server/routes/fate.mjs +32 -3
  78. package/dist/runtime/server/routes/mail/bounce.post.mjs +14 -2
  79. package/dist/runtime/server/routes/mail/unsubscribe.mjs +2 -1
  80. package/dist/runtime/server/routes/mail/webhooks.post.mjs +18 -4
  81. package/dist/runtime/server/routes/notifications/[id].get.mjs +3 -4
  82. package/dist/runtime/server/routes/notifications/index.get.mjs +4 -2
  83. package/dist/runtime/server/routes/notifications/push/subscribe.post.mjs +3 -1
  84. package/dist/runtime/server/routes/notifications/push/unsubscribe.post.mjs +5 -3
  85. package/dist/runtime/server/routes/notifications/read-all.post.mjs +6 -2
  86. package/dist/runtime/server/routes/notifications/send.post.mjs +13 -2
  87. package/dist/runtime/server/routes/payments/cancel.post.mjs +1 -1
  88. package/dist/runtime/server/routes/payments/change-plan.post.mjs +1 -1
  89. package/dist/runtime/server/routes/payments/checkout.post.mjs +1 -1
  90. package/dist/runtime/server/routes/payments/pause.post.mjs +1 -1
  91. package/dist/runtime/server/routes/payments/portal.post.mjs +1 -1
  92. package/dist/runtime/server/routes/payments/subscription.get.mjs +1 -1
  93. package/dist/runtime/server/routes/payments/usage.get.mjs +1 -1
  94. package/dist/runtime/server/routes/payments/usage.post.mjs +1 -1
  95. package/dist/runtime/server/routes/payments/webhook.post.mjs +8 -1
  96. package/dist/runtime/server/routes/realtime/broadcast.post.mjs +3 -2
  97. package/dist/runtime/server/routes/realtime/history.delete.mjs +2 -2
  98. package/dist/runtime/server/routes/realtime/history.get.mjs +2 -2
  99. package/dist/runtime/server/routes/realtime/presence.get.mjs +3 -3
  100. package/dist/runtime/server/routes/realtime/state.get.mjs +3 -3
  101. package/dist/runtime/server/routes/realtime/state.post.mjs +13 -4
  102. package/dist/runtime/server/routes/realtime/ws.get.mjs +2 -2
  103. package/dist/runtime/server/routes/storage/file/[...key].delete.mjs +1 -1
  104. package/dist/runtime/server/routes/storage/file/[...key].get.mjs +7 -0
  105. package/dist/runtime/server/routes/storage/files.get.d.ts +1 -1
  106. package/dist/runtime/server/routes/storage/files.get.mjs +24 -4
  107. package/dist/runtime/server/routes/storage/multipart/abort.post.mjs +16 -1
  108. package/dist/runtime/server/routes/storage/multipart/complete.post.d.ts +1 -1
  109. package/dist/runtime/server/routes/storage/multipart/complete.post.mjs +15 -1
  110. package/dist/runtime/server/routes/storage/multipart/create.post.mjs +7 -0
  111. package/dist/runtime/server/routes/storage/multipart/part.put.mjs +15 -1
  112. package/dist/runtime/server/routes/storage/presigned-r2.post.mjs +8 -1
  113. package/dist/runtime/server/routes/storage/presigned.post.d.ts +1 -1
  114. package/dist/runtime/server/routes/storage/presigned.post.mjs +8 -1
  115. package/dist/runtime/server/routes/storage/sign.post.mjs +7 -0
  116. package/dist/runtime/server/routes/storage/upload.post.d.ts +2 -2
  117. package/dist/runtime/server/routes/store/cart/index.delete.mjs +3 -4
  118. package/dist/runtime/server/routes/store/cart/index.get.mjs +3 -10
  119. package/dist/runtime/server/routes/store/cart/items/[id].delete.mjs +6 -4
  120. package/dist/runtime/server/routes/store/cart/items/[id].patch.mjs +12 -4
  121. package/dist/runtime/server/routes/store/cart/items.post.mjs +9 -10
  122. package/dist/runtime/server/routes/store/categories/index.get.mjs +4 -2
  123. package/dist/runtime/server/routes/store/checkout.post.mjs +13 -3
  124. package/dist/runtime/server/routes/store/coupons/apply.post.mjs +6 -5
  125. package/dist/runtime/server/routes/store/orders/[id].get.mjs +2 -2
  126. package/dist/runtime/server/routes/store/orders/download/[token].get.mjs +6 -3
  127. package/dist/runtime/server/routes/store/orders/index.get.mjs +1 -1
  128. package/dist/runtime/server/routes/store/products/[slug].get.mjs +2 -2
  129. package/dist/runtime/server/routes/store/products/index.get.mjs +1 -1
  130. package/dist/runtime/server/routes/store/tax/calculate.post.mjs +10 -0
  131. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/index.delete.mjs +26 -25
  132. package/dist/runtime/server/routes/tenants/[tenant]/domains/[domain]/verify.post.mjs +26 -25
  133. package/dist/runtime/server/utils/ai.d.ts +6 -0
  134. package/dist/runtime/server/utils/ai.mjs +12 -2
  135. package/dist/runtime/server/utils/analytics-query.mjs +8 -4
  136. package/dist/runtime/server/utils/browser-utils.d.ts +9 -0
  137. package/dist/runtime/server/utils/browser-utils.mjs +135 -0
  138. package/dist/runtime/server/utils/cms/cache.d.ts +13 -0
  139. package/dist/runtime/server/utils/cms/cache.mjs +95 -0
  140. package/dist/runtime/server/utils/cms/common.mjs +1 -1
  141. package/dist/runtime/server/utils/cms/markdown.mjs +38 -8
  142. package/dist/runtime/server/utils/cms/mutations.d.ts +26 -0
  143. package/dist/runtime/server/utils/cms/mutations.mjs +569 -0
  144. package/dist/runtime/server/utils/cms/path.d.ts +8 -0
  145. package/dist/runtime/server/utils/cms/path.mjs +23 -0
  146. package/dist/runtime/server/utils/cms/queries.d.ts +27 -0
  147. package/dist/runtime/server/utils/cms/queries.mjs +366 -0
  148. package/dist/runtime/server/utils/cms/references.d.ts +48 -0
  149. package/dist/runtime/server/utils/cms/references.mjs +309 -0
  150. package/dist/runtime/server/utils/cms/revisions.d.ts +7 -0
  151. package/dist/runtime/server/utils/cms/revisions.mjs +60 -0
  152. package/dist/runtime/server/utils/cms/sync.mjs +3 -3
  153. package/dist/runtime/server/utils/cms.d.ts +5 -82
  154. package/dist/runtime/server/utils/cms.mjs +28 -1367
  155. package/dist/runtime/server/utils/comments.d.ts +11 -0
  156. package/dist/runtime/server/utils/comments.mjs +65 -17
  157. package/dist/runtime/server/utils/crypto.mjs +1 -1
  158. package/dist/runtime/server/utils/domains.mjs +9 -0
  159. package/dist/runtime/server/utils/drizzle.d.ts +26 -1
  160. package/dist/runtime/server/utils/drizzle.mjs +78 -19
  161. package/dist/runtime/server/utils/email-inbound.mjs +9 -1
  162. package/dist/runtime/server/utils/impersonation.mjs +58 -1
  163. package/dist/runtime/server/utils/lock.d.ts +11 -0
  164. package/dist/runtime/server/utils/lock.mjs +4 -0
  165. package/dist/runtime/server/utils/mail-suppression.mjs +48 -13
  166. package/dist/runtime/server/utils/mail.d.ts +2 -1
  167. package/dist/runtime/server/utils/mail.mjs +17 -11
  168. package/dist/runtime/server/utils/notifications.d.ts +13 -4
  169. package/dist/runtime/server/utils/notifications.mjs +20 -4
  170. package/dist/runtime/server/utils/organization.mjs +36 -1
  171. package/dist/runtime/server/utils/passwordless.mjs +8 -0
  172. package/dist/runtime/server/utils/payments/checkout.d.ts +34 -0
  173. package/dist/runtime/server/utils/payments/checkout.mjs +158 -0
  174. package/dist/runtime/server/utils/payments/common.d.ts +45 -0
  175. package/dist/runtime/server/utils/payments/common.mjs +234 -0
  176. package/dist/runtime/server/utils/payments/index.d.ts +9 -0
  177. package/dist/runtime/server/utils/payments/index.mjs +21 -0
  178. package/dist/runtime/server/utils/payments/lemonsqueezy.d.ts +7 -0
  179. package/dist/runtime/server/utils/payments/lemonsqueezy.mjs +55 -0
  180. package/dist/runtime/server/utils/payments/paddle.d.ts +7 -0
  181. package/dist/runtime/server/utils/payments/paddle.mjs +92 -0
  182. package/dist/runtime/server/utils/payments/polar.d.ts +11 -0
  183. package/dist/runtime/server/utils/payments/polar.mjs +66 -0
  184. package/dist/runtime/server/utils/payments/stripe.d.ts +7 -0
  185. package/dist/runtime/server/utils/payments/stripe.mjs +159 -0
  186. package/dist/runtime/server/utils/payments/subscriptions.d.ts +89 -0
  187. package/dist/runtime/server/utils/payments/subscriptions.mjs +236 -0
  188. package/dist/runtime/server/utils/payments/usage.d.ts +12 -0
  189. package/dist/runtime/server/utils/payments/usage.mjs +143 -0
  190. package/dist/runtime/server/utils/payments/webhooks.d.ts +10 -0
  191. package/dist/runtime/server/utils/payments/webhooks.mjs +200 -0
  192. package/dist/runtime/server/utils/payments.d.ts +1 -158
  193. package/dist/runtime/server/utils/payments.mjs +1 -1289
  194. package/dist/runtime/server/utils/queue.d.ts +2 -0
  195. package/dist/runtime/server/utils/queue.mjs +34 -21
  196. package/dist/runtime/server/utils/rag.mjs +30 -17
  197. package/dist/runtime/server/utils/realtime.d.ts +5 -1
  198. package/dist/runtime/server/utils/realtime.mjs +43 -7
  199. package/dist/runtime/server/utils/session.mjs +16 -3
  200. package/dist/runtime/server/utils/sso.d.ts +3 -0
  201. package/dist/runtime/server/utils/sso.mjs +43 -0
  202. package/dist/runtime/server/utils/storage.mjs +12 -1
  203. package/dist/runtime/server/utils/store/cart.d.ts +63 -0
  204. package/dist/runtime/server/utils/store/cart.mjs +542 -0
  205. package/dist/runtime/server/utils/store/checkout.d.ts +14 -0
  206. package/dist/runtime/server/utils/store/checkout.mjs +118 -0
  207. package/dist/runtime/server/utils/store/common.d.ts +29 -0
  208. package/dist/runtime/server/utils/store/common.mjs +479 -0
  209. package/dist/runtime/server/utils/store/index.d.ts +7 -0
  210. package/dist/runtime/server/utils/store/index.mjs +30 -0
  211. package/dist/runtime/server/utils/store/inventory.d.ts +25 -0
  212. package/dist/runtime/server/utils/store/inventory.mjs +190 -0
  213. package/dist/runtime/server/utils/store/orders.d.ts +60 -0
  214. package/dist/runtime/server/utils/store/orders.mjs +590 -0
  215. package/dist/runtime/server/utils/store/products.d.ts +35 -0
  216. package/dist/runtime/server/utils/store/products.mjs +461 -0
  217. package/dist/runtime/server/utils/store/vendor.d.ts +18 -0
  218. package/dist/runtime/server/utils/store/vendor.mjs +68 -0
  219. package/dist/runtime/server/utils/store.d.ts +1 -207
  220. package/dist/runtime/server/utils/store.mjs +1 -2227
  221. package/dist/runtime/server/utils/string.d.ts +1 -1
  222. package/dist/runtime/server/utils/string.mjs +12 -4
  223. package/dist/runtime/server/utils/tenant.mjs +19 -5
  224. package/dist/runtime/server/utils/tracker.mjs +2 -0
  225. package/dist/runtime/server.d.ts +3 -3
  226. package/dist/runtime/server.mjs +4 -4
  227. package/dist/runtime/storage-server.d.ts +2 -0
  228. package/dist/runtime/storage-server.mjs +1 -0
  229. package/dist/runtime/storage.d.ts +1 -1
  230. package/dist/runtime/storage.mjs +0 -1
  231. package/dist/runtime/store.d.ts +0 -1
  232. package/dist/runtime/store.mjs +0 -1
  233. package/dist/runtime/test-utils.d.ts +4 -0
  234. package/dist/runtime/test-utils.mjs +54 -0
  235. package/dist/runtime/types/d1.d.ts +43 -0
  236. package/dist/runtime/types/drizzle.d.ts +6 -0
  237. package/dist/runtime/types/store.d.ts +1 -1
  238. package/dist/types/analytics.d.ts +80 -0
  239. package/dist/types/auth.d.ts +282 -0
  240. package/dist/types/cache.d.ts +55 -0
  241. package/dist/types/comments.d.ts +130 -0
  242. package/dist/types/db.d.ts +29 -0
  243. package/dist/types/email.d.ts +182 -0
  244. package/dist/types/index.d.ts +22 -0
  245. package/dist/types/jobs.d.ts +58 -0
  246. package/dist/types/notifications.d.ts +77 -0
  247. package/dist/types/options.d.ts +363 -0
  248. package/dist/types/payments.d.ts +145 -0
  249. package/dist/types/ratelimit.d.ts +71 -0
  250. package/dist/types/realtime.d.ts +136 -0
  251. package/dist/types/site.d.ts +121 -0
  252. package/dist/types/storage.d.ts +164 -0
  253. package/dist/types/store-options.d.ts +199 -0
  254. package/dist/types/tenant.d.ts +100 -0
  255. package/dist/types.d.ts +1 -2174
  256. package/dist/utils/migration-lock.d.ts +139 -0
  257. package/dist/utils/pkg.d.ts +14 -1
  258. package/dist/utils/schema-diff.d.ts +39 -0
  259. package/package.json +55 -17
  260. package/dist/chunks/auth-schema.mjs +0 -364
@@ -158,6 +158,8 @@ export interface ReplayDeadLetterOptions<T = any> {
158
158
  transform?: (payload: DeadLetterPayload<T> | T) => any;
159
159
  /** Delay in seconds for redelivery */
160
160
  delaySeconds?: number;
161
+ /** Acknowledge skipped messages so they are not endlessly redelivered from DLQ */
162
+ ackSkipped?: boolean;
161
163
  }
162
164
  /**
163
165
  * Replays dead-letter messages back to the primary or target queue.
@@ -176,16 +176,21 @@ export function defineQueueConsumer(optionsOrHandler, maybeOptions) {
176
176
  },
177
177
  reject: async (reason) => {
178
178
  rejected = true;
179
- acknowledged = true;
180
- await sendToDeadLetter(options.deadLetterQueue, reason);
181
- if (typeof options.onDeadLetter === "function") {
182
- await options.onDeadLetter(
183
- message,
184
- new FatalQueueError(reason || "Explicit message rejection"),
185
- messageContext
186
- );
179
+ try {
180
+ await sendToDeadLetter(options.deadLetterQueue, reason);
181
+ if (typeof options.onDeadLetter === "function") {
182
+ await options.onDeadLetter(
183
+ message,
184
+ new FatalQueueError(reason || "Explicit message rejection"),
185
+ messageContext
186
+ );
187
+ }
188
+ } catch (rejectErr) {
189
+ console.error(`[qarpeo:queue] Error during message reject:`, rejectErr);
190
+ } finally {
191
+ acknowledged = true;
192
+ message.ack();
187
193
  }
188
- message.ack();
189
194
  },
190
195
  sendToDeadLetter
191
196
  };
@@ -210,20 +215,25 @@ export function defineQueueConsumer(optionsOrHandler, maybeOptions) {
210
215
  retried = true;
211
216
  message.retry(delaySeconds !== void 0 ? { delaySeconds } : void 0);
212
217
  } else {
213
- await sendToDeadLetter(
214
- options.deadLetterQueue,
215
- err?.message || String(err),
216
- err
217
- );
218
- if (typeof options.onDeadLetter === "function") {
219
- try {
220
- await options.onDeadLetter(message, err, messageContext);
221
- } catch (dlqHookErr) {
222
- console.error(`[qarpeo:queue] Error in onDeadLetter hook:`, dlqHookErr);
218
+ try {
219
+ await sendToDeadLetter(
220
+ options.deadLetterQueue,
221
+ err?.message || String(err),
222
+ err
223
+ );
224
+ if (typeof options.onDeadLetter === "function") {
225
+ try {
226
+ await options.onDeadLetter(message, err, messageContext);
227
+ } catch (dlqHookErr) {
228
+ console.error(`[qarpeo:queue] Error in onDeadLetter hook:`, dlqHookErr);
229
+ }
223
230
  }
231
+ } catch (dlqRouteErr) {
232
+ console.error(`[qarpeo:queue] Error routing to dead-letter queue:`, dlqRouteErr);
233
+ } finally {
234
+ message.ack();
235
+ acknowledged = true;
224
236
  }
225
- message.ack();
226
- acknowledged = true;
227
237
  }
228
238
  }
229
239
  })
@@ -405,6 +415,9 @@ export async function replayDeadLetterQueue(options) {
405
415
  try {
406
416
  const payload = msg.body;
407
417
  if (options.filter && !options.filter(payload)) {
418
+ if (options.ackSkipped) {
419
+ msg.ack();
420
+ }
408
421
  skipped++;
409
422
  continue;
410
423
  }
@@ -25,8 +25,9 @@ function cosineSimilarity(a, b) {
25
25
  const DEFAULT_SEPARATORS = ["\n\n", "\n", ". ", "? ", "! ", "; ", ", ", " "];
26
26
  export function splitTextIntoChunks(text, options) {
27
27
  if (!text || typeof text !== "string") return [];
28
- const chunkSize = options?.chunkSize ?? 800;
29
- const chunkOverlap = options?.chunkOverlap ?? 100;
28
+ const chunkSize = Math.max(1, options?.chunkSize ?? 800);
29
+ const rawOverlap = options?.chunkOverlap ?? 100;
30
+ const chunkOverlap = Math.max(0, Math.min(rawOverlap, chunkSize - 1));
30
31
  const separators = options?.separators ?? DEFAULT_SEPARATORS;
31
32
  const cleanText = text.trim();
32
33
  if (cleanText.length <= chunkSize) {
@@ -38,11 +39,12 @@ export function splitTextIntoChunks(text, options) {
38
39
  }
39
40
  if (separatorIndex >= separators.length) {
40
41
  const hardChunks = [];
42
+ const step = Math.max(1, chunkSize - chunkOverlap);
41
43
  let start = 0;
42
44
  while (start < content.length) {
43
45
  const end = Math.min(start + chunkSize, content.length);
44
46
  hardChunks.push(content.slice(start, end));
45
- start += chunkSize - chunkOverlap;
47
+ start += step;
46
48
  }
47
49
  return hardChunks;
48
50
  }
@@ -52,27 +54,34 @@ export function splitTextIntoChunks(text, options) {
52
54
  let currentChunk = "";
53
55
  for (let i = 0; i < parts.length; i++) {
54
56
  const part = parts[i];
57
+ if (!part) continue;
58
+ if (part.length > chunkSize) {
59
+ if (currentChunk.trim().length > 0) {
60
+ chunks.push(currentChunk.trim());
61
+ currentChunk = "";
62
+ }
63
+ const subChunks = splitRecursive(part, separatorIndex + 1);
64
+ chunks.push(...subChunks);
65
+ continue;
66
+ }
55
67
  const candidate = currentChunk ? `${currentChunk}${separator}${part}` : part;
56
68
  if (candidate.length <= chunkSize) {
57
69
  currentChunk = candidate;
58
70
  } else {
59
- if (currentChunk) {
60
- chunks.push(currentChunk);
61
- if (chunkOverlap > 0 && currentChunk.length > chunkOverlap) {
62
- const overlapText = currentChunk.slice(currentChunk.length - chunkOverlap);
63
- currentChunk = `${overlapText}${separator}${part}`;
64
- } else {
65
- currentChunk = part;
66
- }
71
+ if (currentChunk.trim().length > 0) {
72
+ chunks.push(currentChunk.trim());
73
+ }
74
+ if (chunkOverlap > 0 && currentChunk.length > chunkOverlap) {
75
+ const overlapText = currentChunk.slice(currentChunk.length - chunkOverlap);
76
+ const overlapCandidate = `${overlapText}${separator}${part}`;
77
+ currentChunk = overlapCandidate.length <= chunkSize ? overlapCandidate : part;
67
78
  } else {
68
- const subChunks = splitRecursive(part, separatorIndex + 1);
69
- chunks.push(...subChunks);
70
- currentChunk = "";
79
+ currentChunk = part;
71
80
  }
72
81
  }
73
82
  }
74
83
  if (currentChunk.trim().length > 0) {
75
- chunks.push(currentChunk);
84
+ chunks.push(currentChunk.trim());
76
85
  }
77
86
  return chunks;
78
87
  }
@@ -168,7 +177,7 @@ export function createRAGPipeline(config) {
168
177
  const batch = docs.slice(i, i + batchSize);
169
178
  await Promise.all(
170
179
  batch.map(async (doc) => {
171
- const res = await this.indexDocument(doc, options);
180
+ const res = await pipeline.indexDocument(doc, options);
172
181
  totalChunks += res.chunksIndexed;
173
182
  })
174
183
  );
@@ -185,7 +194,11 @@ export function createRAGPipeline(config) {
185
194
  _docChunkCounts.delete(documentId);
186
195
  const vectorize = resolveVectorize(options?.event || config?.event);
187
196
  if (vectorize) {
188
- await vectorize.deleteByIds(idsToDelete);
197
+ const batchSize = 1e3;
198
+ for (let i = 0; i < idsToDelete.length; i += batchSize) {
199
+ const slice = idsToDelete.slice(i, i + batchSize);
200
+ await vectorize.deleteByIds(slice);
201
+ }
189
202
  } else {
190
203
  const store = getDevMockRAGStore();
191
204
  for (const [id, item] of store.entries()) {
@@ -1,4 +1,4 @@
1
- import type { RequestEvent } from "nuxt/server";
1
+ import { type RequestEvent } from "nuxt/server";
2
2
  import type { DurableObjectStub, RealtimeMessage, RealtimeUser, RealtimePeer, RealtimeHandlerOptions, RealtimeHandlerRegistration, RoomStateSchema } from "../../../types";
3
3
  export type { RealtimePeer, RealtimeHandlerOptions, RealtimeHandlerRegistration, RoomStateSchema };
4
4
  /**
@@ -47,6 +47,10 @@ export declare function defineRealtimeHandler(roomPattern: string, handlers: Rea
47
47
  */
48
48
  export declare function getRealtimeHandlersForRoom(roomId: string): RealtimeHandlerOptions[];
49
49
  export type EventOrRoom = RequestEvent | string;
50
+ /**
51
+ * Validates and sanitizes a room identifier to prevent DO ID injection, path traversal, and control character attacks.
52
+ */
53
+ export declare function assertSafeRoomName(room: unknown): string;
50
54
  /**
51
55
  * Retrieves the Durable Object stub for a specific room name.
52
56
  *
@@ -1,3 +1,4 @@
1
+ import { createError } from "nuxt/server";
1
2
  import { getCloudflareEnv } from "../../bindings.mjs";
2
3
  import { trackRoomActivity } from "./realtime-store.mjs";
3
4
  export function defineRoomState(schema) {
@@ -22,11 +23,36 @@ export function getRealtimeHandlersForRoom(roomId) {
22
23
  return false;
23
24
  }).map((reg) => reg.handlers);
24
25
  }
26
+ export function assertSafeRoomName(room) {
27
+ if (!room || typeof room !== "string") {
28
+ throw createError({
29
+ statusCode: 400,
30
+ statusMessage: "Bad Request",
31
+ message: "Room identifier is required and must be a non-empty string."
32
+ });
33
+ }
34
+ const trimmed = room.trim();
35
+ if (!trimmed || trimmed.length > 128) {
36
+ throw createError({
37
+ statusCode: 400,
38
+ statusMessage: "Bad Request",
39
+ message: "Room identifier must be between 1 and 128 characters."
40
+ });
41
+ }
42
+ if (trimmed.includes("..") || /[\0\r\n\x00-\x1f\x7f]/.test(trimmed)) {
43
+ throw createError({
44
+ statusCode: 400,
45
+ statusMessage: "Bad Request",
46
+ message: "Room identifier contains invalid characters or path traversal sequences."
47
+ });
48
+ }
49
+ return trimmed;
50
+ }
25
51
  function resolveRoomAndEvent(arg1, arg2) {
26
52
  if (typeof arg1 === "string") {
27
- return { event: void 0, roomId: arg1 };
53
+ return { event: void 0, roomId: assertSafeRoomName(arg1) };
28
54
  }
29
- return { event: arg1, roomId: arg2 || "general" };
55
+ return { event: arg1, roomId: assertSafeRoomName(arg2 || "general") };
30
56
  }
31
57
  export function getRoomDurableObject(eventOrRoom, maybeRoom, bindingName = "QARPEO_ROOM_DO") {
32
58
  const { event, roomId } = resolveRoomAndEvent(eventOrRoom, maybeRoom);
@@ -40,6 +66,15 @@ export function getRoomDurableObject(eventOrRoom, maybeRoom, bindingName = "QARP
40
66
  const id = binding.idFromName(roomId);
41
67
  return binding.get(id);
42
68
  }
69
+ function getInternalRoomHeaders(event) {
70
+ const env = getCloudflareEnv(event);
71
+ const secret = env?.REALTIME_ROOM_SECRET || env?.roomSecret;
72
+ const headers = { "Content-Type": "application/json" };
73
+ if (secret) {
74
+ headers["x-qarpeo-room-secret"] = String(secret);
75
+ }
76
+ return headers;
77
+ }
43
78
  export async function broadcastToRoom(eventOrRoom, roomOrEventName, eventNameOrPayload, payloadOrOptions, options) {
44
79
  let event;
45
80
  let roomId;
@@ -62,7 +97,7 @@ export async function broadcastToRoom(eventOrRoom, roomOrEventName, eventNameOrP
62
97
  const stub = getRoomDurableObject(event, roomId);
63
98
  const res = await stub.fetch("http://internal/broadcast", {
64
99
  method: "POST",
65
- headers: { "Content-Type": "application/json" },
100
+ headers: getInternalRoomHeaders(event),
66
101
  body: JSON.stringify({
67
102
  event: eventName,
68
103
  payload,
@@ -130,7 +165,8 @@ export async function clearRoomHistory(eventOrRoom, maybeRoom) {
130
165
  const { event, roomId } = resolveRoomAndEvent(eventOrRoom, maybeRoom);
131
166
  const stub = getRoomDurableObject(event, roomId);
132
167
  const res = await stub.fetch("http://internal/history", {
133
- method: "DELETE"
168
+ method: "DELETE",
169
+ headers: getInternalRoomHeaders(event)
134
170
  });
135
171
  return res.ok;
136
172
  }
@@ -150,7 +186,7 @@ export async function disconnectRoomUser(eventOrRoom, roomOrUserId, maybeUserId)
150
186
  const stub = getRoomDurableObject(event, roomId);
151
187
  const res = await stub.fetch("http://internal/disconnect", {
152
188
  method: "POST",
153
- headers: { "Content-Type": "application/json" },
189
+ headers: getInternalRoomHeaders(event),
154
190
  body: JSON.stringify({ userId })
155
191
  });
156
192
  if (!res.ok) {
@@ -183,7 +219,7 @@ export async function setRoomState(eventOrRoom, roomOrState, maybeState) {
183
219
  const stub = getRoomDurableObject(event, roomId);
184
220
  const res = await stub.fetch("http://internal/state", {
185
221
  method: "POST",
186
- headers: { "Content-Type": "application/json" },
222
+ headers: getInternalRoomHeaders(event),
187
223
  body: JSON.stringify({ state })
188
224
  });
189
225
  if (!res.ok) throw new Error("[qarpeo.realtime] setRoomState failed");
@@ -206,7 +242,7 @@ export async function patchRoomState(eventOrRoom, roomOrPatch, maybePatch) {
206
242
  const stub = getRoomDurableObject(event, roomId);
207
243
  const res = await stub.fetch("http://internal/state", {
208
244
  method: "POST",
209
- headers: { "Content-Type": "application/json" },
245
+ headers: getInternalRoomHeaders(event),
210
246
  body: JSON.stringify({ patch })
211
247
  });
212
248
  if (!res.ok) throw new Error("[qarpeo.realtime] patchRoomState failed");
@@ -222,13 +222,19 @@ export async function revokeDeviceSession(event, userId, sessionIdToRevoke) {
222
222
  try {
223
223
  const bindingName = globalThis.process?.env?.QARPEO_DEFAULT_DB_BINDING || "DB";
224
224
  const d1 = getD1Binding(bindingName, event);
225
- await d1.prepare(`DELETE FROM ${sessionTbl(event)} WHERE id = ? AND user_id = ?`).bind(sessionIdToRevoke, userId).run();
225
+ const res = await d1.prepare(`DELETE FROM ${sessionTbl(event)} WHERE id = ? AND user_id = ?`).bind(sessionIdToRevoke, userId).run();
226
+ const changes = res?.meta?.changes ?? res?.changes ?? 0;
227
+ let kvFound = false;
226
228
  try {
227
229
  const kv = getKVBinding("KV", event);
228
- await kv.delete(`session:${sessionIdToRevoke}`);
230
+ const kvData = await kv.get(`session:${sessionIdToRevoke}`, { type: "json" });
231
+ if (kvData && kvData.userId === userId) {
232
+ kvFound = true;
233
+ await kv.delete(`session:${sessionIdToRevoke}`);
234
+ }
229
235
  } catch {
230
236
  }
231
- return true;
237
+ return changes > 0 || kvFound;
232
238
  } catch {
233
239
  return false;
234
240
  }
@@ -282,6 +288,13 @@ export async function verifyKVSession(event, sessionId) {
282
288
  if (sessionTenantId && requestTenantId && sessionTenantId !== requestTenantId) {
283
289
  return false;
284
290
  }
291
+ if (data.expiresAt && Date.now() > data.expiresAt) {
292
+ try {
293
+ await kv.delete(`session:${sessionId}`);
294
+ } catch {
295
+ }
296
+ return false;
297
+ }
285
298
  return true;
286
299
  } catch {
287
300
  return true;
@@ -10,6 +10,9 @@ export interface SAMLAssertionResult {
10
10
  name?: string;
11
11
  issuer?: string;
12
12
  sessionIndex?: string;
13
+ assertionId?: string;
14
+ notBefore?: number;
15
+ notOnOrAfter?: number;
13
16
  attributes: Record<string, string>;
14
17
  }
15
18
  /**
@@ -179,10 +179,53 @@ export function parseSAMLResponse(base64Response) {
179
179
  ].join(" ").trim() || void 0;
180
180
  const issuerMatch = xml.match(/<(?:\w+:)?Issuer[^>]*>([^<]+)<\/(?:\w+:)?Issuer>/i);
181
181
  const issuer = issuerMatch ? issuerMatch[1].trim() : void 0;
182
+ const assertionIdMatch = xml.match(/<(?:\w+:)?Assertion[^>]*\sID=["']([^"']+)["']/i);
183
+ const assertionId = assertionIdMatch ? assertionIdMatch[1] : void 0;
184
+ let notBefore;
185
+ let notOnOrAfter;
186
+ const conditionsMatch = xml.match(/<(?:\w+:)?Conditions[^>]*>/i);
187
+ if (conditionsMatch) {
188
+ const nbMatch = conditionsMatch[0].match(/NotBefore=["']([^"']+)["']/i);
189
+ if (nbMatch) {
190
+ const parsed = Date.parse(nbMatch[1]);
191
+ if (!isNaN(parsed)) notBefore = parsed;
192
+ }
193
+ const noaMatch = conditionsMatch[0].match(/NotOnOrAfter=["']([^"']+)["']/i);
194
+ if (noaMatch) {
195
+ const parsed = Date.parse(noaMatch[1]);
196
+ if (!isNaN(parsed)) notOnOrAfter = parsed;
197
+ }
198
+ }
199
+ if (!notOnOrAfter) {
200
+ const scdMatch = xml.match(/<(?:\w+:)?SubjectConfirmationData[^>]*\sNotOnOrAfter=["']([^"']+)["']/i);
201
+ if (scdMatch) {
202
+ const parsed = Date.parse(scdMatch[1]);
203
+ if (!isNaN(parsed)) notOnOrAfter = parsed;
204
+ }
205
+ }
206
+ const now = Date.now();
207
+ const clockSkewMs = 3e5;
208
+ if (notOnOrAfter !== void 0 && now - clockSkewMs > notOnOrAfter) {
209
+ throw createError({
210
+ statusCode: 401,
211
+ statusMessage: "Unauthorized",
212
+ message: "SAML assertion has expired (NotOnOrAfter)"
213
+ });
214
+ }
215
+ if (notBefore !== void 0 && now + clockSkewMs < notBefore) {
216
+ throw createError({
217
+ statusCode: 401,
218
+ statusMessage: "Unauthorized",
219
+ message: "SAML assertion is not yet valid (NotBefore)"
220
+ });
221
+ }
182
222
  return {
183
223
  email: email.toLowerCase(),
184
224
  name,
185
225
  issuer,
226
+ assertionId,
227
+ notBefore,
228
+ notOnOrAfter,
186
229
  attributes
187
230
  };
188
231
  }
@@ -64,7 +64,11 @@ export async function resolveStorageScopePrefix(event, config) {
64
64
  return "public";
65
65
  }
66
66
  export function sanitizeFilename(filename) {
67
- return filename.toLowerCase().replace(/[^\w.-]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
67
+ const clean = filename.toLowerCase().replace(/[^\w.-]/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
68
+ if (!clean || /^[\.-]+$/.test(clean)) {
69
+ return "unnamed-file";
70
+ }
71
+ return clean;
68
72
  }
69
73
  export function validateStorageFile(file, config) {
70
74
  const maxBytes = parseByteSize(config.maxSize || "20MB");
@@ -468,6 +472,13 @@ export async function listStorageFiles(event, options) {
468
472
  }
469
473
  export async function serveStorageFile(event, key) {
470
474
  const cleanKey = key.replace(/^\/+/, "");
475
+ if (cleanKey.includes("..") || cleanKey.includes("\\") || cleanKey.includes("\0")) {
476
+ throw createError({
477
+ statusCode: 400,
478
+ statusMessage: "Bad Request",
479
+ message: "Invalid storage key"
480
+ });
481
+ }
471
482
  const query = getQuery(event);
472
483
  const hasTransform = ["w", "h", "f", "fit", "q"].some(
473
484
  (p) => query[p] !== void 0 && query[p] !== ""
@@ -0,0 +1,63 @@
1
+ import type { RequestEvent } from "nuxt/server";
2
+ import type { StoreCart, StoreCartItem, StoreCartTotals, StoreDiscount, StoreDiscountType, StoreQueryDiscountsOptions } from "../../../types/store";
3
+ export declare function getOrCreateStoreCart(sessionToken?: string, event?: RequestEvent): Promise<StoreCart>;
4
+ export declare function getStoreCart(cartIdOrToken: string, event?: RequestEvent): Promise<StoreCart | null>;
5
+ /**
6
+ * Resolves the active cart for the current request event and verifies ownership.
7
+ *
8
+ * Enforces ownership:
9
+ * 1. Resolves caller's token from:
10
+ * - `options.sessionToken` (if explicitly passed in body)
11
+ * - `x-cart-session` request header
12
+ * - `qarpeo_cart_session` cookie
13
+ * - Authenticated user ID via `getAuthContext(event)`
14
+ * 2. If caller already has an established cart or session, and an `explicitCartId`
15
+ * is provided, verifies that `explicitCartId === cart.id` or that the cart belongs
16
+ * to the same authenticated user or session token.
17
+ * 3. Throws 403 Forbidden if a caller attempts to access, mutate, or checkout a foreign cart.
18
+ * 4. Persists the cookie on `event` so the browser maintains the verified session.
19
+ */
20
+ export declare function resolveStoreCart(event?: RequestEvent, options?: {
21
+ cartId?: string;
22
+ sessionToken?: string;
23
+ }): Promise<StoreCart>;
24
+ export declare function addToStoreCart(cartId: string, item: {
25
+ productId: string;
26
+ variantId: string;
27
+ quantity: number;
28
+ customAttributes?: Record<string, any>;
29
+ }, event?: RequestEvent): Promise<StoreCartItem>;
30
+ export declare function updateStoreCartItem(itemId: string, quantity: number, event?: RequestEvent): Promise<StoreCartItem | null>;
31
+ export declare function removeStoreCartItem(itemId: string, event?: RequestEvent): Promise<boolean>;
32
+ export declare function clearStoreCart(cartId: string, event?: RequestEvent): Promise<boolean>;
33
+ export declare function calculateStoreCartTotals(cartId: string, event?: RequestEvent): Promise<StoreCartTotals>;
34
+ export declare function mergeGuestCartOnLogin(guestSessionToken: string, userId: string, event?: RequestEvent): Promise<StoreCart>;
35
+ export declare function validateStoreDiscount(code: string, subtotal: number, event?: RequestEvent, opts?: {
36
+ tenantId?: string;
37
+ }): Promise<{
38
+ valid: boolean;
39
+ discount?: StoreDiscount;
40
+ discountAmount: number;
41
+ message?: string;
42
+ }>;
43
+ export declare function applyStoreDiscount(cartId: string, code: string, event?: RequestEvent): Promise<{
44
+ success: boolean;
45
+ totals: StoreCartTotals;
46
+ message?: string;
47
+ }>;
48
+ export declare function createStoreDiscount(data: Partial<StoreDiscount> & {
49
+ code: string;
50
+ type: StoreDiscountType;
51
+ value: number;
52
+ }, event?: RequestEvent): Promise<StoreDiscount>;
53
+ export declare function getStoreDiscount(idOrCode: string, event?: RequestEvent): Promise<StoreDiscount | null>;
54
+ export declare function updateStoreDiscount(id: string, updates: Partial<StoreDiscount>, event?: RequestEvent): Promise<StoreDiscount | null>;
55
+ export declare function deleteStoreDiscount(id: string, event?: RequestEvent): Promise<boolean>;
56
+ export declare function queryStoreDiscounts(opts?: StoreQueryDiscountsOptions, event?: RequestEvent): Promise<{
57
+ discounts: StoreDiscount[];
58
+ total: number;
59
+ }>;
60
+ export declare function removeStoreDiscount(cartId: string, event?: RequestEvent): Promise<{
61
+ success: boolean;
62
+ totals: StoreCartTotals;
63
+ }>;