@classytic/cart 0.3.1 → 1.1.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 (49) hide show
  1. package/CHANGELOG.md +188 -147
  2. package/LICENSE +75 -21
  3. package/dist/{cart-event-catalog-BxDJhtTM.d.mts → cart-event-catalog-Cokx0iOw.d.mts} +1 -2
  4. package/dist/cart.error-xi5OT4Sz.mjs +52 -0
  5. package/dist/{clock.port-CNu2wgdA.d.mts → clock.port-DrSBrsit.d.mts} +9 -5
  6. package/dist/{create-cart-zgAh3UVt.mjs → define-cart-Cr9VMeVc.mjs} +362 -236
  7. package/dist/domain/errors/index.d.mts +2 -2
  8. package/dist/domain/errors/index.mjs +6 -6
  9. package/dist/domain/events/index.d.mts +2 -2
  10. package/dist/domain/events/index.mjs +2 -2
  11. package/dist/domain/index.d.mts +14 -11
  12. package/dist/domain/index.mjs +12 -12
  13. package/dist/domain/ports/index.d.mts +3 -3
  14. package/dist/domain/ports/index.mjs +1 -1
  15. package/dist/domain/saga/index.d.mts +1 -1
  16. package/dist/domain/saga/index.mjs +1 -1
  17. package/dist/engine/cart-config.schema.d.mts +3 -4
  18. package/dist/engine/cart-config.schema.mjs +7 -7
  19. package/dist/engine/index.d.mts +3 -3
  20. package/dist/engine/index.mjs +3 -3
  21. package/dist/{errors-BNPgUilS.mjs → errors-Dj8itvAh.mjs} +1 -1
  22. package/dist/{id.port-BhbFZJPm.mjs → id.port-DYAnXbfV.mjs} +1 -1
  23. package/dist/{index-wh5Q7UY1.d.mts → index-BTSo-RLv.d.mts} +41 -3
  24. package/dist/index.d.mts +88 -24
  25. package/dist/index.mjs +195 -14
  26. package/dist/{internal-event-bus-DFcwV79F.d.mts → internal-event-bus-BA-WrtE0.d.mts} +200 -179
  27. package/dist/{kind-registry-DG2iCCH1.d.mts → kind-registry-DFvNDb81.d.mts} +3 -5
  28. package/dist/{kind-registry-Bvrj3P1Q.mjs → kind-registry-DQYqRQZU.mjs} +1 -1
  29. package/dist/{kind.error-DIaJpdUb.mjs → kind.error-BoyoVjKx.mjs} +1 -1
  30. package/dist/kinds/index.d.mts +1 -1
  31. package/dist/kinds/index.mjs +1 -1
  32. package/dist/{line-kind-B1mU1iJp.d.mts → line-kind-BW2zLNSr.d.mts} +3 -4
  33. package/dist/line-total-6VJQMjGV.mjs +24 -0
  34. package/dist/{outbox-store-CBt9fSYh.d.mts → outbox-store-Br7MHuOz.d.mts} +3 -18
  35. package/dist/{outbox-store-CWW8ppxS.mjs → outbox-store-DLxCPOUN.mjs} +2 -30
  36. package/dist/{reservation.entity-DLMxgpLE.d.mts → reservation.entity-BEeYbRUY.d.mts} +4 -5
  37. package/dist/{state-transition.error-2fRLh3p0.mjs → state-transition.error-BssJiRoW.mjs} +1 -1
  38. package/dist/{state-transitions-D19wZe-w.d.mts → state-transitions-BQ2Nhxnb.d.mts} +14 -11
  39. package/dist/{state-transitions-Defw8gAt.mjs → state-transitions-wunwhjap.mjs} +1 -1
  40. package/dist/{unmanaged-session.error-C9Z1Yh9j.mjs → unmanaged-session.error-DIRT2PR3.mjs} +31 -2
  41. package/dist/{variant.kind-q-yv-vnQ.d.mts → variant.kind-CClf8MTF.d.mts} +3 -3
  42. package/dist/{variant.kind-BHiivO9B.mjs → variant.kind-NmWSslu-.mjs} +23 -32
  43. package/package.json +10 -9
  44. package/dist/cart.error-BwWy4RlY.mjs +0 -27
  45. package/dist/index-2Ag-54t8.d.mts +0 -1
  46. /package/dist/{cart-status.vo-CNJw4aaB.d.mts → cart-status.vo-BoVPaSXX.d.mts} +0 -0
  47. /package/dist/{domain-event-CIEORKF6.mjs → domain-event-DBFsiHNJ.mjs} +0 -0
  48. /package/dist/{id.port-DitjeoHg.d.mts → id.port-DzgWy8sy.d.mts} +0 -0
  49. /package/dist/{idempotency-key.vo-D0lJsvGn.mjs → idempotency-key.vo-BoRvSIxx.mjs} +0 -0
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
- import { t as CART_REF_NEW } from "./idempotency-key.vo-D0lJsvGn.mjs";
2
- import { t as CartError } from "./cart.error-BwWy4RlY.mjs";
3
- import { a as ConcurrencyError, i as NotFoundError, n as StaleQuoteError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-C9Z1Yh9j.mjs";
4
- import { n as UnknownKindError, t as KindError } from "./kind.error-DIaJpdUb.mjs";
5
- import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-BNPgUilS.mjs";
6
- import { t as StateTransitionError } from "./state-transition.error-2fRLh3p0.mjs";
7
- import { n as CartEvents, t as createCartEvent } from "./domain-event-CIEORKF6.mjs";
8
- import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-CWW8ppxS.mjs";
9
- import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-BhbFZJPm.mjs";
10
- import { a as IdempotencyRepository, c as CheckoutRepository, d as createReservationModel, f as createIdempotencyModel, g as PENDING_EVENTS, h as flushPending, i as ReservationRepository, l as DEFAULT_STALE_OPEN_CHECKOUT_MS, m as createCheckoutModel, n as InProcessCartEventBus, o as DraftRepository, p as createDraftModel, r as createCartRepositories, s as runPricing, t as createCart, u as createCartModels } from "./create-cart-zgAh3UVt.mjs";
11
- import { t as createKindRegistry } from "./kind-registry-Bvrj3P1Q.mjs";
12
- import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-Defw8gAt.mjs";
13
- import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-BHiivO9B.mjs";
1
+ import { t as CART_REF_NEW } from "./idempotency-key.vo-BoRvSIxx.mjs";
2
+ import { t as CartError } from "./cart.error-xi5OT4Sz.mjs";
3
+ import { a as CurrencyMismatchError, i as NotFoundError, n as StaleQuoteError, o as ConcurrencyError, r as PriceChangedError, t as UnmanagedSessionError } from "./unmanaged-session.error-DIRT2PR3.mjs";
4
+ import { n as UnknownKindError, t as KindError } from "./kind.error-BoyoVjKx.mjs";
5
+ import { i as ReservationError, n as IdempotencyStorageError, r as SagaError, t as IdempotencyBusyError } from "./errors-Dj8itvAh.mjs";
6
+ import { t as StateTransitionError } from "./state-transition.error-BssJiRoW.mjs";
7
+ import { n as CartEvents, t as createCartEvent } from "./domain-event-DBFsiHNJ.mjs";
8
+ import { a as cartEventsByName, i as cartEventDefinitions, n as MemoryOutboxStore, o as createCartEventRegistry, r as OutboxOwnershipError, s as defineCartEvent, t as InvalidOutboxEventError } from "./outbox-store-DLxCPOUN.mjs";
9
+ import { n as cryptoIdPort, r as systemClock, t as createCounterIdPort } from "./id.port-DYAnXbfV.mjs";
10
+ import { _ as PENDING_EVENTS, a as ReservationRepository, c as runPricing, d as defineCartModels, f as buildReservationSchema, g as flushPending, h as buildCheckoutSchema, i as createCartRepositories, l as CheckoutRepository, m as buildDraftSchema, n as defineCart, o as IdempotencyRepository, p as buildIdempotencySchema, r as InProcessCartEventBus, s as DraftRepository, t as createCartDomain, u as DEFAULT_STALE_OPEN_CHECKOUT_MS } from "./define-cart-Cr9VMeVc.mjs";
11
+ import { t as createKindRegistry } from "./kind-registry-DQYqRQZU.mjs";
12
+ import { i as CheckoutStep, n as CHECKOUT_STATE_TRANSITIONS, r as isLegalCheckoutTransition } from "./state-transitions-wunwhjap.mjs";
13
+ import { a as skuKind, c as serviceFeePayloadSchema, i as timeslotPayloadSchema, l as bundleKind, n as variantPayloadSchema, o as skuPayloadSchema, r as timeslotKind, s as serviceFeeKind, t as variantKind, u as bundlePayloadSchema } from "./variant.kind-NmWSslu-.mjs";
14
14
  import { cartConfigSchema, checkoutConfigSchema, idempotencyConfigSchema, reservationConfigSchema, scopeConfigSchema } from "./engine/cart-config.schema.mjs";
15
15
  import { addMoney, fromMajor, money, multiplyMoney, subtractMoney, sumMoney, toMajor } from "@classytic/primitives/money";
16
16
  //#region src/services/abandonment.service.ts
@@ -147,4 +147,185 @@ async function mergeDrafts(opts) {
147
147
  throw lastError;
148
148
  }
149
149
  //#endregion
150
- export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, ConcurrencyError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PENDING_EVENTS, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError, addMoney, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCart, createCartEvent, createCartEventRegistry, createCartModels, createCartRepositories, createCheckoutModel, createCounterIdPort, createDraftModel, createIdempotencyModel, createKindRegistry, createReservationModel, cryptoIdPort, defineCartEvent, findAbandonedDrafts, flushPending, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };
150
+ //#region src/cleanup/cleanup.error.ts
151
+ /**
152
+ * Error raised by the cart data-cleanup provider steps
153
+ * (`src/cleanup/steps.ts`).
154
+ *
155
+ * Two failure classes flow through this one type — the concrete `code` +
156
+ * `category` tell them apart:
157
+ *
158
+ * - `cart/cleanup_invalid_param` (category `validation`) — an operator
159
+ * parameter (`before`, `organizationId`, `batchSize`) is malformed.
160
+ * Thrown at the edge, before any read or write. Never retryable — the
161
+ * caller must fix the parameter.
162
+ * - `cart/cleanup_purge_failed` (category `system`) — the underlying
163
+ * chunked purge reported `ok: false` (a chunk aborted). Surfaced LOUD
164
+ * instead of silently reporting a partial delete as success (retention
165
+ * design §8). Retryable: re-running the step resumes from the surviving
166
+ * rows.
167
+ *
168
+ * A `CartError` subclass so hosts catch cleanup failures with the same
169
+ * `instanceof CartError` net as every other cart error.
170
+ */
171
+ var CleanupError = class extends CartError {
172
+ code;
173
+ category;
174
+ retryable;
175
+ constructor(code, message, opts = {}) {
176
+ super(message, opts.context);
177
+ this.code = code;
178
+ this.category = opts.category ?? "validation";
179
+ this.retryable = opts.retryable ?? false;
180
+ }
181
+ };
182
+ //#endregion
183
+ //#region src/cleanup/steps.ts
184
+ /**
185
+ * The ONLY draft statuses this domain declares disposable — terminal,
186
+ * never-converted baskets. See the disposable-state decision in this
187
+ * module's docblock. `active` (live) and `converted` (became an order —
188
+ * business history) are never included.
189
+ */
190
+ const DISPOSABLE_DRAFT_STATUSES = ["abandoned", "expired"];
191
+ const STEP_ID = "cart.remove-abandoned";
192
+ const RESOURCE = "abandoned carts";
193
+ const RETAINED = "converted/checked-out carts untouched";
194
+ function invalidParam(op, name, value, expected) {
195
+ return new CleanupError("cart/cleanup_invalid_param", `${op}: parameter '${name}' must be ${expected} (got '${String(value)}')`, {
196
+ category: "validation",
197
+ context: {
198
+ param: name,
199
+ value
200
+ }
201
+ });
202
+ }
203
+ /** Validate + coerce operator parameters at the edge. */
204
+ function parseParams(ctx, op) {
205
+ const p = ctx.parameters ?? {};
206
+ const out = {};
207
+ const before = p.before;
208
+ if (before !== void 0) {
209
+ if (typeof before !== "string" || Number.isNaN(Date.parse(before))) throw invalidParam(op, "before", before, "a full ISO instant (e.g. 2026-08-01T00:00:00.000Z)");
210
+ /**
211
+ * A DATE-ONLY string is refused, not silently read as UTC midnight.
212
+ *
213
+ * This was `new Date(before)` for both forms. `new Date('2026-08-01')` is
214
+ * UTC midnight — 06:00 that day in Asia/Dhaka — so "remove abandoned carts
215
+ * before 1 August" swept the first six hours of a day the operator had
216
+ * excluded. Nothing errored and a plausible count came back.
217
+ *
218
+ * A kernel cannot fix that by picking a calendar: it does not know the
219
+ * deployment's timezone, and guessing UTC is exactly the bug. So the
220
+ * ambiguity is REFUSED here and resolved by the host, which does know —
221
+ * be-prod converts a civil date through `businessDayStartUtc` before the
222
+ * parameter ever reaches a step. Refusing is what makes that conversion
223
+ * mandatory rather than merely available.
224
+ */
225
+ if (/^\d{4}-\d{2}-\d{2}$/.test(before)) throw invalidParam(op, "before", before, "a full ISO instant — a bare calendar date is ambiguous without a timezone, so the host must resolve it against its business calendar first");
226
+ out.before = new Date(before);
227
+ }
228
+ const org = p.organizationId;
229
+ if (org !== void 0) {
230
+ if (typeof org !== "string" || org.length === 0) throw invalidParam(op, "organizationId", org, "a non-empty string");
231
+ out.organizationId = org;
232
+ }
233
+ const batchSize = p.batchSize;
234
+ if (batchSize !== void 0) {
235
+ if (typeof batchSize !== "number" || !Number.isInteger(batchSize) || batchSize < 1) throw invalidParam(op, "batchSize", batchSize, "a positive integer");
236
+ out.batchSize = batchSize;
237
+ }
238
+ return out;
239
+ }
240
+ /** Disposable-status (+ optional `before`) predicate — the org-agnostic scope. */
241
+ function statusFilter(params) {
242
+ const filter = { status: { $in: [...DISPOSABLE_DRAFT_STATUSES] } };
243
+ if (params.before) filter.updatedAt = { $lt: params.before };
244
+ return filter;
245
+ }
246
+ /** Full read/purge predicate — disposable status + `before` + optional org scope. */
247
+ function readFilter(params) {
248
+ const filter = statusFilter(params);
249
+ if (params.organizationId) filter.organizationId = params.organizationId;
250
+ return filter;
251
+ }
252
+ /**
253
+ * Count disposable carts matching the parameters. `skipTenant: true` opts
254
+ * out of the tenant plugin (the filter carries any scope); this is the
255
+ * cross-branch admin read.
256
+ */
257
+ async function countAbandoned(src, filter) {
258
+ return src.repositories.draft.count(filter, { skipTenant: true });
259
+ }
260
+ /**
261
+ * A native purge NEVER throws for in-strategy errors — it wraps them into
262
+ * `result.error` and returns `ok: false`. Fail LOUD instead of silently
263
+ * reporting a partial count as success (retention §8, invoice `assertPurgeOk`).
264
+ */
265
+ function assertPurgeOk(result, op) {
266
+ if (!result.ok) throw new CleanupError("cart/cleanup_purge_failed", `${op}: purge did not complete — ${result.error?.message ?? "unknown error"} (chunkOffset ${result.error?.chunkOffset ?? "?"}, processed ${result.processed})`, {
267
+ category: "system",
268
+ retryable: true,
269
+ context: {
270
+ op,
271
+ processed: result.processed,
272
+ error: result.error
273
+ }
274
+ });
275
+ return result;
276
+ }
277
+ function createCartCleanupSteps(source) {
278
+ const draftRepo = source.repositories.draft;
279
+ return { removeAbandonedCarts: {
280
+ id: STEP_ID,
281
+ resource: RESOURCE,
282
+ destructive: true,
283
+ async estimate(ctx) {
284
+ const estimated = await countAbandoned(source, readFilter(parseParams(ctx, `${STEP_ID} estimate`)));
285
+ return {
286
+ resource: RESOURCE,
287
+ estimated,
288
+ retained: RETAINED
289
+ };
290
+ },
291
+ async execute(ctx) {
292
+ const params = parseParams(ctx, `${STEP_ID} execute`);
293
+ await ctx.throwIfCancelled?.();
294
+ let cancelledErr;
295
+ const options = {
296
+ ...params.batchSize !== void 0 ? { batchSize: params.batchSize } : {},
297
+ ...ctx.signal ? { signal: ctx.signal } : {},
298
+ onProgress: async (e) => {
299
+ await ctx.onProgress?.({
300
+ resource: RESOURCE,
301
+ processed: e.processed
302
+ });
303
+ if (ctx.throwIfCancelled) try {
304
+ await ctx.throwIfCancelled();
305
+ } catch (err) {
306
+ cancelledErr = err;
307
+ throw err;
308
+ }
309
+ }
310
+ };
311
+ const result = await draftRepo.purgeByFilter(readFilter(params), { type: "hard" }, options);
312
+ if (cancelledErr) throw cancelledErr;
313
+ assertPurgeOk(result, STEP_ID);
314
+ return {
315
+ resource: RESOURCE,
316
+ processed: result.processed,
317
+ ok: true
318
+ };
319
+ },
320
+ async verify(ctx) {
321
+ const remaining = await countAbandoned(source, readFilter(parseParams(ctx, `${STEP_ID} verify`)));
322
+ return [{
323
+ name: "cart.no-abandoned-carts-remain",
324
+ ok: remaining === 0,
325
+ detail: remaining === 0 ? "no disposable carts match the parameters" : `${remaining} disposable cart(s) still match the parameters`
326
+ }];
327
+ }
328
+ } };
329
+ }
330
+ //#endregion
331
+ export { CART_REF_NEW, CHECKOUT_STATE_TRANSITIONS, CartError, CartEvents, CheckoutRepository, CheckoutStep, CleanupError, ConcurrencyError, CurrencyMismatchError, DEFAULT_STALE_OPEN_CHECKOUT_MS, DISPOSABLE_DRAFT_STATUSES, DraftRepository, IdempotencyBusyError, IdempotencyRepository, IdempotencyStorageError, InProcessCartEventBus, InvalidOutboxEventError, KindError, MemoryOutboxStore, NotFoundError, OutboxOwnershipError, PENDING_EVENTS, PriceChangedError, ReservationError, ReservationRepository, SagaError, StaleQuoteError, StateTransitionError, UnknownKindError, UnmanagedSessionError, addMoney, buildCheckoutSchema, buildDraftSchema, buildIdempotencySchema, buildReservationSchema, bundleKind, bundlePayloadSchema, cartConfigSchema, cartEventDefinitions, cartEventsByName, checkoutConfigSchema, createCartCleanupSteps, createCartDomain, createCartEvent, createCartEventRegistry, createCartRepositories, createCounterIdPort, createKindRegistry, cryptoIdPort, defineCart, defineCartEvent, defineCartModels, findAbandonedDrafts, flushPending, fromMajor, idempotencyConfigSchema, isLegalCheckoutTransition, markAbandoned, mergeDrafts, money, multiplyMoney, reservationConfigSchema, runPricing, scopeConfigSchema, serviceFeeKind, serviceFeePayloadSchema, skuKind, skuPayloadSchema, subtractMoney, sumMoney, systemClock, timeslotKind, timeslotPayloadSchema, toMajor, variantKind, variantPayloadSchema };