@asteby/storefront 0.5.0 → 0.6.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.
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { availabilityLocale, formatAvailabilityMessage } from './chunk-HBSB7XS2.js';
2
+ export { availabilityLocale, availabilityMessages, availabilityView, cartLineProblemView, formatAvailabilityMessage, productAvailability, resolveAvailability, schemaAvailability } from './chunk-HBSB7XS2.js';
1
3
  import { isValidPoint } from './chunk-45R47HYO.js';
2
4
 
3
5
  // src/errors.ts
@@ -6,14 +8,26 @@ var StorefrontError = class extends Error {
6
8
  status;
7
9
  code;
8
10
  field;
11
+ details;
9
12
  url;
10
13
  constructor(init) {
11
14
  super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
12
15
  this.status = init.status;
13
16
  this.code = init.code;
14
17
  this.field = init.field;
18
+ this.details = init.details;
15
19
  this.url = init.url;
16
20
  }
21
+ /**
22
+ * Affected lines of a `409 insufficient_stock` (empty for any other error or a
23
+ * server older than contract 1.1). The cart is untouched: show the lines and
24
+ * let the buyer adjust or remove them.
25
+ */
26
+ get stockLines() {
27
+ const lines = this.details?.lines;
28
+ if (this.code !== "insufficient_stock" || !Array.isArray(lines)) return [];
29
+ return lines.filter((l) => typeof l === "object" && l !== null && typeof l.sku === "string");
30
+ }
17
31
  toJSON() {
18
32
  return { name: this.name, status: this.status, code: this.code, message: this.message, field: this.field };
19
33
  }
@@ -46,7 +60,7 @@ function formatMoney(money, locale, options = {}) {
46
60
  const whole = Number.isInteger(value);
47
61
  const digits = options.withoutTrailingZeros && whole ? 0 : void 0;
48
62
  try {
49
- const fmt = new Intl.NumberFormat(locale, {
63
+ const fmt2 = new Intl.NumberFormat(locale, {
50
64
  ...options.withoutCurrency ? { style: "decimal", minimumFractionDigits: digits ?? 2, maximumFractionDigits: digits ?? 2 } : {
51
65
  style: "currency",
52
66
  currency: money.currency_code,
@@ -54,7 +68,7 @@ function formatMoney(money, locale, options = {}) {
54
68
  ...digits === 0 ? { minimumFractionDigits: 0, maximumFractionDigits: 0 } : {}
55
69
  }
56
70
  });
57
- return fmt.format(value);
71
+ return fmt2.format(value);
58
72
  } catch {
59
73
  const amount = digits === 0 ? String(value) : value.toFixed(2);
60
74
  return options.withoutCurrency ? amount : `${amount} ${money.currency_code}`;
@@ -167,6 +181,7 @@ async function readError(res, url) {
167
181
  code: e?.code ?? defaultCodeForStatus(res.status),
168
182
  message: e?.message ?? `Storefront API responded ${res.status}${res.statusText ? " " + res.statusText : ""}`,
169
183
  ...e?.field ? { field: e.field } : {},
184
+ ...e?.details !== void 0 ? { details: e.details } : {},
170
185
  url
171
186
  });
172
187
  }
@@ -298,6 +313,13 @@ function createStorefrontClient(config) {
298
313
  /** Stock for up to 250 SKUs. */
299
314
  get: (skus, options) => get("/storefront/stock", { sku: skus }, options)
300
315
  },
316
+ restock: {
317
+ /**
318
+ * "Notify me when it is back". Idempotent per contact + SKU; always answers `202 pending`.
319
+ * Only offered when `availability.notify_available` is true. Needs `customer:write`.
320
+ */
321
+ subscribe: (input, options) => write("POST", "/storefront/restock-subscriptions", input, options)
322
+ },
301
323
  carts: {
302
324
  create: (input = {}, options) => write("POST", "/storefront/carts", input, options),
303
325
  /** `null` when the cart does not exist (e.g. expired cookie). */
@@ -313,13 +335,37 @@ function createStorefrontClient(config) {
313
335
  /** Payment providers active for the cart's market; send the chosen `key` as `payment_method`. */
314
336
  paymentMethods: (id, options) => get(cartPath(id, "/payment-methods"), void 0, options),
315
337
  setDelivery: (id, delivery, options) => write("PUT", cartPath(id, "/delivery"), delivery, options),
338
+ /** Order note (up to 1000 characters). `null` or empty clears it. */
339
+ setNote: (id, note, options) => write("PUT", cartPath(id, "/note"), { note }, options),
340
+ /**
341
+ * Cross-sell suggestions: only sellable variants, with `unlocks` when adding one reaches the next
342
+ * discount tier. `first` 1-8 (default 4). `private, no-store`; ask on demand, not on every render.
343
+ */
344
+ recommendations: (id, params = {}, options) => get(cartPath(id, "/recommendations"), params, options),
316
345
  /** Reserves stock and creates the order. Sends `Idempotency-Key` (auto-generated if omitted). */
317
346
  checkout: (id, input, options = {}) => write("POST", cartPath(id, "/checkout"), input, {
318
347
  ...options,
319
348
  idempotencyKey: options.idempotencyKey ?? generateIdempotencyKey()
320
349
  })
321
350
  },
351
+ promotions: {
352
+ /** Public promotions and the entry pop-up announcement for the request's market (cacheable). */
353
+ list: (options) => get("/storefront/promotions", void 0, options)
354
+ },
322
355
  checkouts: {
356
+ /** What to mount for an embedded checkout (public key, options, amount) and whether it can still be paid. Never cache. */
357
+ paymentConfig: (id, options) => getOrNull(`/storefront/checkouts/${enc(id)}/payment-config`, void 0, options),
358
+ /**
359
+ * Pays a checkout in the page. The browser brings only what the provider SDK returned (`provider_data`);
360
+ * the amount is the server's. `idempotencyKey` is REQUIRED (use `paymentIdempotencyKey(checkoutId, attempt)`):
361
+ * repeating a call with the same key never charges twice. Needs a server token (`checkout:write`).
362
+ */
363
+ pay: (id, input, options) => {
364
+ if (!options || typeof options.idempotencyKey !== "string" || !options.idempotencyKey.trim()) {
365
+ throw new TypeError("checkouts.pay: idempotencyKey is required");
366
+ }
367
+ return write("POST", `/storefront/checkouts/${enc(id)}/payment`, input, options);
368
+ },
323
369
  /**
324
370
  * Reads a placed checkout (same shape as the `carts.checkout` result). `order.number` is `null` until OPS
325
371
  * has created the order (a few hundred ms after checkout); poll once or twice and, if it is still `null`,
@@ -360,6 +406,426 @@ function createStorefrontClient(config) {
360
406
  return client;
361
407
  }
362
408
 
363
- export { CLIENT_IP_HEADER, StorefrontError, appendParams, createStorefrontClient, formatMoney, generateIdempotencyKey, isStorefrontError, isTokenPublishable, normalizeClientIp, parseMoney, parseProductFilters, productListQuery, toMoney };
409
+ // src/payments.ts
410
+ var ES = {
411
+ "decline.insufficient_funds": "Tu tarjeta no tiene saldo suficiente. Prueba con otra tarjeta o paga en efectivo.",
412
+ "decline.invalid_cvc": "El c\xF3digo de seguridad no es correcto. Rev\xEDsalo e intenta de nuevo.",
413
+ "decline.invalid_expiry": "La fecha de vencimiento no es correcta.",
414
+ "decline.invalid_card_data": "Revisa los datos de tu tarjeta.",
415
+ "decline.call_issuer": "Tu banco necesita que autorices este pago. Llama al n\xFAmero al reverso de tu tarjeta y vuelve a intentarlo.",
416
+ "decline.card_disabled": "Tu tarjeta no est\xE1 activa. Act\xEDvala con tu banco o usa otra.",
417
+ "decline.duplicate": "Ya hiciste un pago igual hace un momento. Revisa tu correo antes de volver a pagar.",
418
+ "decline.max_attempts": "Llegaste al l\xEDmite de intentos con esta tarjeta. Usa otra o paga en efectivo.",
419
+ "decline.authentication_failed": "Tu banco no pudo verificar el pago. Intenta de nuevo o usa otra tarjeta.",
420
+ "decline.declined": "Tu banco rechaz\xF3 el pago. Usa otra tarjeta o paga en efectivo.",
421
+ "state.loading": "Cargando pago seguro\u2026",
422
+ "state.processing": "Procesando pago\u2026",
423
+ "state.approved": "\xA1Pago aprobado!",
424
+ "state.in_review": "Tu pago est\xE1 en revisi\xF3n. Te avisamos por correo en m\xE1ximo 2 d\xEDas h\xE1biles. No vuelvas a pagar.",
425
+ "state.voucher": "Tu ficha de pago est\xE1 lista. El pedido se confirma cuando pagues.",
426
+ "state.challenge": "Tu banco necesita verificar el pago. Termina la verificaci\xF3n para continuar.",
427
+ "state.expired": "La ficha venci\xF3. Vuelve a armar tu carrito para pagar.",
428
+ "state.cancelled": "El pago se cancel\xF3. Puedes intentarlo de nuevo.",
429
+ "state.redirect": "Te llevamos a la p\xE1gina de pago\u2026",
430
+ "state.fallback": "No pudimos cargar el formulario seguro de tarjeta. Puedes pagar con tarjeta en el sitio del proveedor y regresar aqu\xED.",
431
+ "error.network": "No pudimos conectar. Revisa tu conexi\xF3n e intenta de nuevo; no se te cobrar\xE1 dos veces.",
432
+ "error.card_data": "Revisa los datos de tu tarjeta.",
433
+ "error.price_mismatch": "El total cambi\xF3. Revisa el nuevo total y vuelve a pagar.",
434
+ "error.payment_in_progress": "Ya hay un pago en proceso para este pedido. No vuelvas a pagar; revisa tu correo.",
435
+ "error.expired": "Tu apartado venci\xF3. Vuelve a armar tu carrito.",
436
+ "error.too_many_attempts": "Por seguridad no podemos intentar con m\xE1s tarjetas. Paga en efectivo o escr\xEDbenos.",
437
+ "error.generic": "No pudimos procesar tu pago. Intenta de nuevo.",
438
+ "action.retry": "Reintentar",
439
+ "action.try_again": "Intentar de nuevo",
440
+ "action.pay": "Pagar",
441
+ "action.cancel": "Cancelar",
442
+ "voucher.title": "Ficha de pago",
443
+ "voucher.point": "Punto de pago",
444
+ "voucher.reference": "Referencia",
445
+ "voucher.amount": "Monto exacto",
446
+ "voucher.expires": "Vence el {date}",
447
+ "voucher.clabe": "CLABE",
448
+ "voucher.barcode": "C\xF3digo de barras",
449
+ "voucher.open": "Ver o imprimir ficha",
450
+ "voucher.email": "Tambi\xE9n te la enviamos a tu correo.",
451
+ "form.label": "Datos de tu tarjeta",
452
+ "challenge.title": "Verificaci\xF3n de tu banco"
453
+ };
454
+ var EN = {
455
+ "decline.insufficient_funds": "Your card has insufficient funds. Try another card or pay in cash.",
456
+ "decline.invalid_cvc": "The security code is not correct. Check it and try again.",
457
+ "decline.invalid_expiry": "The expiry date is not correct.",
458
+ "decline.invalid_card_data": "Check your card details.",
459
+ "decline.call_issuer": "Your bank needs you to authorize this payment. Call the number on the back of your card and try again.",
460
+ "decline.card_disabled": "Your card is not active. Activate it with your bank or use another one.",
461
+ "decline.duplicate": "You already made the same payment a moment ago. Check your email before paying again.",
462
+ "decline.max_attempts": "You reached the attempt limit for this card. Use another card or pay in cash.",
463
+ "decline.authentication_failed": "Your bank could not verify the payment. Try again or use another card.",
464
+ "decline.declined": "Your bank declined the payment. Use another card or pay in cash.",
465
+ "state.loading": "Loading secure payment\u2026",
466
+ "state.processing": "Processing payment\u2026",
467
+ "state.approved": "Payment approved!",
468
+ "state.in_review": "Your payment is under review. We will email you within 2 business days. Do not pay again.",
469
+ "state.voucher": "Your payment voucher is ready. The order is confirmed once you pay.",
470
+ "state.challenge": "Your bank needs to verify the payment. Finish the verification to continue.",
471
+ "state.expired": "The voucher expired. Rebuild your cart to pay.",
472
+ "state.cancelled": "The payment was cancelled. You can try again.",
473
+ "state.redirect": "Taking you to the payment page\u2026",
474
+ "state.fallback": "We could not load the secure card form. You can pay by card on the provider site and come back here.",
475
+ "error.network": "We could not connect. Check your connection and try again; you will not be charged twice.",
476
+ "error.card_data": "Check your card details.",
477
+ "error.price_mismatch": "The total changed. Review the new total and pay again.",
478
+ "error.payment_in_progress": "A payment is already in progress for this order. Do not pay again; check your email.",
479
+ "error.expired": "Your reservation expired. Rebuild your cart.",
480
+ "error.too_many_attempts": "For security we cannot try more cards. Pay in cash or contact us.",
481
+ "error.generic": "We could not process your payment. Please try again.",
482
+ "action.retry": "Retry",
483
+ "action.try_again": "Try again",
484
+ "action.pay": "Pay",
485
+ "action.cancel": "Cancel",
486
+ "voucher.title": "Payment voucher",
487
+ "voucher.point": "Payment point",
488
+ "voucher.reference": "Reference",
489
+ "voucher.amount": "Exact amount",
490
+ "voucher.expires": "Expires on {date}",
491
+ "voucher.clabe": "CLABE",
492
+ "voucher.barcode": "Barcode",
493
+ "voucher.open": "View or print voucher",
494
+ "voucher.email": "We also emailed it to you.",
495
+ "form.label": "Your card details",
496
+ "challenge.title": "Your bank verification"
497
+ };
498
+ var CATALOG = { es: ES, en: EN };
499
+ function paymentMessages(locale, overrides) {
500
+ const base = CATALOG[availabilityLocale(locale)];
501
+ if (!overrides) return base;
502
+ const out = { ...base };
503
+ for (const [k, v] of Object.entries(overrides)) if (typeof v === "string" && k in base) out[k] = v;
504
+ return out;
505
+ }
506
+ var DECLINE_CODES = /* @__PURE__ */ new Set([
507
+ "insufficient_funds",
508
+ "invalid_cvc",
509
+ "invalid_expiry",
510
+ "invalid_card_data",
511
+ "call_issuer",
512
+ "card_disabled",
513
+ "duplicate",
514
+ "max_attempts",
515
+ "authentication_failed",
516
+ "declined"
517
+ ]);
518
+ function declineMessageKey(code) {
519
+ return `decline.${code && DECLINE_CODES.has(code) ? code : "declined"}`;
520
+ }
521
+ function declineMessage(code, locale, overrides) {
522
+ return paymentMessages(locale, overrides)[declineMessageKey(code)];
523
+ }
524
+ function safeHttpsUrl(value) {
525
+ if (typeof value !== "string" || value.length > 2048) return null;
526
+ try {
527
+ const u = new URL(value);
528
+ if (u.protocol !== "https:" || u.username || u.password) return null;
529
+ return u.toString();
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+ var NEXT_STEP = {
535
+ insufficient_funds: "use_other_card",
536
+ invalid_cvc: "fix_card_data",
537
+ invalid_expiry: "fix_card_data",
538
+ invalid_card_data: "fix_card_data",
539
+ call_issuer: "contact_issuer",
540
+ card_disabled: "use_other_card",
541
+ duplicate: "check_email",
542
+ max_attempts: "use_other_card",
543
+ authentication_failed: "retry",
544
+ declined: "use_other_card"
545
+ };
546
+ function voucherMoney(v) {
547
+ const a = v.amount;
548
+ if (a && typeof a === "object" && typeof a.amount === "string") return a;
549
+ const text = typeof a === "number" ? String(a) : typeof a === "string" ? a : "";
550
+ if (!text || !/^\d+(\.\d+)?$/.test(text) || !v.currency) return null;
551
+ return { amount: text.includes(".") ? text : `${text}.00`, currency_code: v.currency };
552
+ }
553
+ function paymentOutcome(result, locale, overrides) {
554
+ const m = paymentMessages(locale, overrides);
555
+ const p = result.payment;
556
+ const action = p.action ?? null;
557
+ const base = {
558
+ decline_code: null,
559
+ retryable: false,
560
+ redirect_url: null,
561
+ challenge: null,
562
+ voucher: null,
563
+ attempts_left: typeof result.attempts_left === "number" ? result.attempts_left : null,
564
+ next_step: p.next_step ?? null
565
+ };
566
+ const out = (kind, message, extra = {}) => ({ ...base, kind, message, ...extra });
567
+ if (p.status === "paid") return out("approved", m["state.approved"]);
568
+ if (p.status === "failed") {
569
+ const code = p.decline_code ?? "declined";
570
+ const known = DECLINE_CODES.has(code) ? code : "declined";
571
+ return out("rejected", m[declineMessageKey(code)], {
572
+ decline_code: known,
573
+ next_step: p.next_step ?? NEXT_STEP[known],
574
+ retryable: p.retryable !== false && base.attempts_left !== 0
575
+ });
576
+ }
577
+ if (p.status === "expired") return out("expired", m["state.expired"], { next_step: "rebuild_cart" });
578
+ if (p.status === "cancelled") return out("cancelled", m["state.cancelled"], { retryable: true, next_step: "rebuild_cart" });
579
+ if (action?.type === "redirect") {
580
+ const url = safeHttpsUrl(action.redirect_url);
581
+ if (url) return out("redirect", m["state.redirect"], { redirect_url: url });
582
+ }
583
+ if (p.status === "requires_action" || p.status === "pending") {
584
+ if (action?.type === "voucher" && action.voucher) {
585
+ const { amount: _a, currency: _c, voucher_url, ...rest } = action.voucher;
586
+ return out("voucher", m["state.voucher"], {
587
+ next_step: "pay_cash",
588
+ voucher: { ...rest, voucher_url: safeHttpsUrl(voucher_url), amount: voucherMoney(action.voucher) }
589
+ });
590
+ }
591
+ if (action?.type === "challenge" && action.challenge) {
592
+ return out("challenge", m["state.challenge"], {
593
+ challenge: { url: safeHttpsUrl(action.challenge.url), creq: typeof action.challenge.creq === "string" ? action.challenge.creq : null }
594
+ });
595
+ }
596
+ }
597
+ return out("in_review", m["state.in_review"]);
598
+ }
599
+ function paymentErrorView(err, locale, overrides) {
600
+ const m = paymentMessages(locale, overrides);
601
+ const e = err ?? {};
602
+ const status = typeof e.status === "number" ? e.status : 0;
603
+ const code = typeof e.code === "string" ? e.code : "";
604
+ if (code === "price_mismatch") {
605
+ return { kind: "price_mismatch", message: m["error.price_mismatch"], retrySameAttempt: false, canRetry: true };
606
+ }
607
+ if (status === 409 && code === "expired") return { kind: "expired", message: m["error.expired"], retrySameAttempt: false, canRetry: false };
608
+ if (status === 409 && code === "payment_in_progress") {
609
+ return { kind: "payment_in_progress", message: m["error.payment_in_progress"], retrySameAttempt: false, canRetry: false };
610
+ }
611
+ if (status === 409) return { kind: "generic", message: m["error.generic"], retrySameAttempt: false, canRetry: true };
612
+ if (status === 429 || code === "too_many_attempts") {
613
+ return { kind: "too_many_attempts", message: m["error.too_many_attempts"], retrySameAttempt: false, canRetry: false };
614
+ }
615
+ if (status === 0 || status === 502 || status === 503 || status === 504 || code === "network" || code === "timeout") {
616
+ return { kind: "network", message: m["error.network"], retrySameAttempt: true, canRetry: true };
617
+ }
618
+ return { kind: "generic", message: m["error.generic"], retrySameAttempt: false, canRetry: true };
619
+ }
620
+ function formatVoucherExpiry(expiresAt, locale, overrides) {
621
+ if (!expiresAt) return null;
622
+ const d = new Date(expiresAt);
623
+ if (Number.isNaN(d.getTime())) return null;
624
+ let date;
625
+ try {
626
+ date = new Intl.DateTimeFormat(locale ?? void 0, { dateStyle: "long", timeStyle: "short" }).format(d);
627
+ } catch {
628
+ date = d.toISOString();
629
+ }
630
+ return formatAvailabilityMessage(paymentMessages(locale, overrides)["voucher.expires"], { date });
631
+ }
632
+ function paymentIdempotencyKey(checkoutId, attempt) {
633
+ return `pay-${checkoutId}-${attempt}`;
634
+ }
635
+
636
+ // src/promotions.ts
637
+ var ES2 = {
638
+ "discount.next": "A\xF1ade {remaining} para activar tu descuento autom\xE1tico",
639
+ "discount.next_upgrade": "A\xF1ade {remaining} para subir a {reward}",
640
+ "discount.applied": "\xA1Tienes {reward} de descuento!",
641
+ "discount.max": "\xA1Tienes {reward} de descuento, el m\xE1ximo!",
642
+ "discount.suppressed": "Tu c\xF3digo de descuento ya te da un mejor precio.",
643
+ "discount.unlocks": "Desbloqueas {reward} de descuento",
644
+ "discount.remaining": "Te faltan {remaining}",
645
+ "shipping.progress": "A\xF1ade {remaining} para env\xEDo gratis",
646
+ "shipping.reached": "\xA1Felicidades! Tienes env\xEDo gratis",
647
+ "shipping.always": "Env\xEDo gratis en todo tu pedido",
648
+ "reward.free_shipping": "Env\xEDo gratis",
649
+ "bar.discount": "Progreso del descuento autom\xE1tico",
650
+ "bar.shipping": "Progreso del env\xEDo gratis",
651
+ "popup.close": "Cerrar",
652
+ "popup.valid_until": "V\xE1lido hasta el {date}",
653
+ "popup.limited_time": "Por tiempo limitado",
654
+ "popup.discount_tier": "{reward} comprando {threshold}",
655
+ "popup.free_shipping_min": "Env\xEDo gratis desde {threshold}",
656
+ "popup.free_shipping_always": "Env\xEDos gratis sin m\xEDnimo de compra",
657
+ "upsell.title": "Completa tu compra y desbloquea m\xE1s",
658
+ "upsell.subtitle": "Descuento autom\xE1tico",
659
+ "upsell.next_level": "Siguiente nivel",
660
+ "upsell.you_miss": "Te faltan {remaining}",
661
+ "upsell.unlocks_reward": "Desbloqueas {reward} de descuento",
662
+ "upsell.total_saved": "Total ahorrado",
663
+ "upsell.current_benefit": "Beneficio actual",
664
+ "upsell.status": "Estado",
665
+ "upsell.status_pending": "Pendiente",
666
+ "upsell.status_active": "Activo",
667
+ "upsell.next_reward": "Siguiente recompensa {reward} \xB7 {threshold}",
668
+ "upsell.suggestions": "Suma y desbloquea \xB7 Productos que pueden interesarte",
669
+ "upsell.add": "Agregar y avanzar +",
670
+ "upsell.adding": "Agregando\u2026",
671
+ "upsell.flavor": "Sabor",
672
+ "upsell.unlocks_badge": "Desbloquea tu {reward}",
673
+ "upsell.unlocked": "\xA1Desbloqueaste {reward}!",
674
+ "upsell.best": "Tienes el mejor descuento: {reward}",
675
+ "upsell.skip": "Continuar sin agregar",
676
+ "upsell.continue": "Continuar al pago",
677
+ "upsell.footer": "Tu mejor descuento se aplica autom\xE1ticamente",
678
+ "upsell.sold_out": "Se agot\xF3 este sabor, elige otro.",
679
+ "upsell.error": "No pudimos agregarlo. Intenta de nuevo.",
680
+ "note.label": "A\xF1adir nota",
681
+ "note.placeholder": "Instrucciones para tu pedido",
682
+ "note.save": "Guardar nota",
683
+ "note.saving": "Guardando\u2026",
684
+ "note.saved": "Guardada",
685
+ "note.error": "No se pudo guardar la nota. Intenta de nuevo.",
686
+ "note.counter": "{n} de {max} caracteres"
687
+ };
688
+ var EN2 = {
689
+ "discount.next": "Add {remaining} to unlock your automatic discount",
690
+ "discount.next_upgrade": "Add {remaining} to move up to {reward}",
691
+ "discount.applied": "You have {reward} off!",
692
+ "discount.max": "You have {reward} off, the maximum!",
693
+ "discount.suppressed": "Your discount code already gives you a better price.",
694
+ "discount.unlocks": "Unlock {reward} off",
695
+ "discount.remaining": "{remaining} to go",
696
+ "shipping.progress": "Add {remaining} for free shipping",
697
+ "shipping.reached": "Congratulations! You get free shipping",
698
+ "shipping.always": "Free shipping on your whole order",
699
+ "reward.free_shipping": "Free shipping",
700
+ "bar.discount": "Automatic discount progress",
701
+ "bar.shipping": "Free shipping progress",
702
+ "popup.close": "Close",
703
+ "popup.valid_until": "Valid until {date}",
704
+ "popup.limited_time": "Limited time",
705
+ "popup.discount_tier": "{reward} when you spend {threshold}",
706
+ "popup.free_shipping_min": "Free shipping from {threshold}",
707
+ "popup.free_shipping_always": "Free shipping, no minimum purchase",
708
+ "upsell.title": "Complete your purchase and unlock more",
709
+ "upsell.subtitle": "Automatic discount",
710
+ "upsell.next_level": "Next level",
711
+ "upsell.you_miss": "{remaining} to go",
712
+ "upsell.unlocks_reward": "Unlock {reward} off",
713
+ "upsell.total_saved": "Total saved",
714
+ "upsell.current_benefit": "Current benefit",
715
+ "upsell.status": "Status",
716
+ "upsell.status_pending": "Pending",
717
+ "upsell.status_active": "Active",
718
+ "upsell.next_reward": "Next reward {reward} \xB7 {threshold}",
719
+ "upsell.suggestions": "Add and unlock \xB7 Products you may like",
720
+ "upsell.add": "Add and move up +",
721
+ "upsell.adding": "Adding\u2026",
722
+ "upsell.flavor": "Flavor",
723
+ "upsell.unlocks_badge": "Unlocks your {reward}",
724
+ "upsell.unlocked": "You unlocked {reward}!",
725
+ "upsell.best": "You have the best discount: {reward}",
726
+ "upsell.skip": "Continue without adding",
727
+ "upsell.continue": "Continue to payment",
728
+ "upsell.footer": "Your best discount is applied automatically",
729
+ "upsell.sold_out": "This flavor sold out, pick another one.",
730
+ "upsell.error": "We could not add it. Please try again.",
731
+ "note.label": "Add a note",
732
+ "note.placeholder": "Instructions for your order",
733
+ "note.save": "Save note",
734
+ "note.saving": "Saving\u2026",
735
+ "note.saved": "Saved",
736
+ "note.error": "The note could not be saved. Please try again.",
737
+ "note.counter": "{n} of {max} characters"
738
+ };
739
+ var CATALOG2 = { es: ES2, en: EN2 };
740
+ function promotionMessages(locale, overrides) {
741
+ const base = CATALOG2[availabilityLocale(locale)];
742
+ if (!overrides) return base;
743
+ const out = { ...base };
744
+ for (const [k, v] of Object.entries(overrides)) if (typeof v === "string" && k in base) out[k] = v;
745
+ return out;
746
+ }
747
+ var NOTE_MAX_LENGTH = 1e3;
748
+ function normalizeNote(note) {
749
+ const t = (note ?? "").trim();
750
+ return t ? t.slice(0, NOTE_MAX_LENGTH) : null;
751
+ }
752
+ function rewardLabel(reward, locale, overrides) {
753
+ const m = promotionMessages(locale, overrides);
754
+ if (reward.kind === "free_shipping") return m["reward.free_shipping"];
755
+ if (reward.kind === "fixed") return formatMoney(reward.amount, locale ?? void 0, { withoutTrailingZeros: true });
756
+ const n = Number.parseFloat(reward.percent);
757
+ let num = reward.percent;
758
+ try {
759
+ if (Number.isFinite(n)) num = new Intl.NumberFormat(locale ?? void 0, { maximumFractionDigits: 4 }).format(n);
760
+ } catch {
761
+ }
762
+ return availabilityLocale(locale) === "en" ? `${num}%` : `${num} %`;
763
+ }
764
+ function clampPercent(value) {
765
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value));
766
+ if (!Number.isFinite(n)) return 0;
767
+ return Math.min(100, Math.max(0, Math.round(n)));
768
+ }
769
+ var fmt = (money, locale) => formatMoney(money, locale ?? void 0, { withoutTrailingZeros: true });
770
+ function promoProgressView(promotions, locale, overrides) {
771
+ if (!promotions) return { discount: null, shipping: null };
772
+ const m = promotionMessages(locale, overrides);
773
+ const f = (tpl, vars) => formatAvailabilityMessage(tpl, vars);
774
+ let discount = null;
775
+ const hasTiers = promotions.tiers.length > 0 || promotions.next_tier !== null || promotions.applied !== null;
776
+ if (hasTiers) {
777
+ const next = promotions.next_tier;
778
+ const applied = promotions.applied;
779
+ const appliedReward = applied ? rewardLabel(applied.reward, locale, overrides) : null;
780
+ let state;
781
+ let text;
782
+ if (promotions.suppressed?.reason === "code_better" && !applied) {
783
+ state = "suppressed";
784
+ text = m["discount.suppressed"];
785
+ } else if (!next) {
786
+ state = "max";
787
+ text = appliedReward ? f(m["discount.max"], { reward: appliedReward }) : m["discount.suppressed"];
788
+ } else if (applied) {
789
+ state = "upgrade";
790
+ text = f(m["discount.next_upgrade"], { remaining: fmt(next.remaining, locale), reward: rewardLabel(next.reward, locale, overrides) });
791
+ } else {
792
+ state = "next";
793
+ text = f(m["discount.next"], { remaining: fmt(next.remaining, locale) });
794
+ }
795
+ discount = {
796
+ state,
797
+ percent: clampPercent(promotions.percent_of_max),
798
+ text,
799
+ valueText: text,
800
+ remaining: next?.remaining ?? null,
801
+ rewardText: next ? rewardLabel(next.reward, locale, overrides) : appliedReward,
802
+ appliedText: appliedReward ? f(m["discount.applied"], { reward: appliedReward }) : null,
803
+ nextText: next ? f(m["discount.unlocks"], { reward: rewardLabel(next.reward, locale, overrides) }) : null,
804
+ tiers: promotions.tiers.map((t) => ({
805
+ id: t.id,
806
+ label: rewardLabel(t.reward, locale, overrides),
807
+ threshold: fmt(t.threshold, locale),
808
+ reached: t.reached,
809
+ position: clampPercent(t.percent_of_max)
810
+ }))
811
+ };
812
+ }
813
+ let shipping = null;
814
+ const fs = promotions.free_shipping;
815
+ if (fs) {
816
+ const noMinimum = Number.parseFloat(fs.threshold.amount) === 0;
817
+ if (noMinimum) {
818
+ shipping = { state: "always", percent: 100, text: m["shipping.always"], valueText: m["shipping.always"], remaining: null, showBar: false };
819
+ } else if (fs.reached) {
820
+ shipping = { state: "reached", percent: 100, text: m["shipping.reached"], valueText: m["shipping.reached"], remaining: null, showBar: true };
821
+ } else {
822
+ const text = f(m["shipping.progress"], { remaining: fmt(fs.remaining, locale) });
823
+ shipping = { state: "progress", percent: clampPercent(fs.percent), text, valueText: text, remaining: fs.remaining, showBar: true };
824
+ }
825
+ }
826
+ return { discount, shipping };
827
+ }
828
+
829
+ export { CLIENT_IP_HEADER, NOTE_MAX_LENGTH, StorefrontError, appendParams, clampPercent, createStorefrontClient, declineMessage, declineMessageKey, formatMoney, formatVoucherExpiry, generateIdempotencyKey, isStorefrontError, isTokenPublishable, normalizeClientIp, normalizeNote, parseMoney, parseProductFilters, paymentErrorView, paymentIdempotencyKey, paymentMessages, paymentOutcome, productListQuery, promoProgressView, promotionMessages, rewardLabel, safeHttpsUrl, toMoney };
364
830
  //# sourceMappingURL=index.js.map
365
831
  //# sourceMappingURL=index.js.map