@final-commerce/common 2.11.1-online.5 → 2.11.1-online.7

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/README.md CHANGED
@@ -219,6 +219,26 @@ node -p "const c = require('@final-commerce/common'); c.formatCurrency(2500, 'EU
219
219
  # → €25.00
220
220
  ```
221
221
 
222
+ ## Quality gates
223
+
224
+ ### `gate-done` time budgets
225
+
226
+ `gate-done` (the pre-push hook) runs three sweeps: gitleaks, Vitest with coverage, and a bundle-size or build check. It gives them two separate time budgets, both set in milliseconds through environment variables:
227
+
228
+ | Variable | Default | Covers |
229
+ | -------------------------- | -------- | ----------------------------- |
230
+ | `GATE_DONE_BUDGET_MS` | `90000` | gitleaks and the bundle sweep |
231
+ | `GATE_DONE_TEST_BUDGET_MS` | `300000` | the Vitest sweep on its own |
232
+
233
+ A budget only counts time spent in its own sweeps, so a slow test suite never takes time from the other sweeps, and the other sweeps never take time from the tests. Husky's pre-push hook inherits your shell environment, so you can raise a budget for one push or for good:
234
+
235
+ ```bash
236
+ GATE_DONE_TEST_BUDGET_MS=600000 git push # one push
237
+ export GATE_DONE_TEST_BUDGET_MS=600000 # in ~/.zshrc, for every push
238
+ ```
239
+
240
+ If a sweep runs past its budget, `gate-done` kills it and blocks the push with a timeout message (`Vitest killed after 300.0s by the test budget … not a test failure`), not as a test failure. Values that are not positive integers are ignored with a warning, and the default applies.
241
+
222
242
  ## License
223
243
 
224
244
  Private — Final Commerce internal use only.
package/bin/gate-done.mjs CHANGED
@@ -2,58 +2,79 @@
2
2
  /**
3
3
  * gate-done — pre-push hook.
4
4
  *
5
- * Runs three sweeps inside a 90-second wall-clock budget:
5
+ * Runs three sweeps under two time budgets:
6
6
  *
7
7
  * 1. gitleaks — credential / secret scanning (git log + staged)
8
8
  * 2. vitest — full test suite with coverage threshold enforcement
9
9
  * 3. bundle — size-limit or custom bundle-size script (if configured)
10
10
  *
11
+ * Budgets (milliseconds, read from the environment — Husky's pre-push inherits the shell):
12
+ *
13
+ * GATE_DONE_BUDGET_MS default 90000 shared by sweeps 1 and 3
14
+ * GATE_DONE_TEST_BUDGET_MS default 300000 sweep 2 (Vitest) on its own
15
+ *
16
+ * A budget only drains while its own sweeps run, so a slow test suite cannot
17
+ * starve the bundle sweep and vice versa.
18
+ *
11
19
  * Any sweep failure exits 1, blocking the push.
12
- * Budget overrun also exits 1.
20
+ * A sweep killed by its budget also exits 1, but is reported as a timeout,
21
+ * not as a failure of the thing it was checking.
13
22
  *
14
23
  * Install as Husky pre-push hook:
15
24
  * echo "npx gate-done" > .husky/pre-push
16
25
  */
17
26
 
18
- import { spawnSync } from 'node:child_process';
19
27
  import { readFileSync } from 'node:fs';
20
28
  import { resolve } from 'node:path';
21
29
 
22
- const BUDGET_MS = 90_000;
30
+ import {
31
+ DEFAULT_BUDGET_MS,
32
+ DEFAULT_TEST_BUDGET_MS,
33
+ budgetKillMessage,
34
+ createBudget,
35
+ readBudgetMs,
36
+ runInBudget,
37
+ } from './lib/budget.mjs';
38
+
23
39
  const t0 = Date.now();
24
40
 
25
41
  // ── helpers ──────────────────────────────────────────────────────────────────
26
42
 
27
- function remaining() {
28
- return Math.max(0, BUDGET_MS - (Date.now() - t0));
29
- }
30
-
31
43
  function elapsed() {
32
44
  return ((Date.now() - t0) / 1000).toFixed(1);
33
45
  }
34
46
 
35
- function checkBudget(label) {
36
- if (remaining() <= 0) {
37
- fail(`90s budget exhausted before "${label}" could complete. Push blocked.`);
47
+ function makeBudget(name, envVar, fallback) {
48
+ const { ms, invalid } = readBudgetMs(process.env, envVar, fallback);
49
+ if (invalid !== undefined) {
50
+ warn(`${envVar}="${invalid}" is not a positive integer of milliseconds — using ${fallback}.`);
51
+ }
52
+ return createBudget(name, envVar, ms);
53
+ }
54
+
55
+ function checkBudget(budget, label) {
56
+ if (budget.exhausted()) {
57
+ fail(
58
+ `${budget.name} budget (${budget.envVar}=${budget.ms}) exhausted before "${label}" could start. ` +
59
+ `Push blocked — not a ${label} failure.`,
60
+ );
38
61
  }
39
62
  }
40
63
 
41
64
  /**
42
- * Run a command, streaming output. Returns the spawnSync result.
43
- * Passes remaining budget as the process timeout so a runaway child
44
- * cannot exceed the wall-clock limit on its own.
65
+ * Run a command, streaming output, charged to `budget`. The budget's remaining
66
+ * time is the child's timeout, so a runaway child cannot overrun it. A child
67
+ * killed by that timeout blocks the push with a timeout message instead of
68
+ * being reported as a failure of the sweep.
45
69
  */
46
- function run(cmd) {
47
- return spawnSync(cmd, {
48
- shell: true,
49
- encoding: 'utf8',
50
- stdio: 'inherit',
51
- timeout: remaining(),
52
- });
70
+ function run(budget, label, cmd) {
71
+ const result = runInBudget(budget, cmd, { stdio: 'inherit' });
72
+ if (result.timedOut) fail(budgetKillMessage(label, budget, result.durationMs) + ' Push blocked.');
73
+ return result;
53
74
  }
54
75
 
55
- function capture(cmd) {
56
- return spawnSync(cmd, { shell: true, encoding: 'utf8', timeout: remaining() });
76
+ function capture(budget, cmd) {
77
+ return runInBudget(budget, cmd);
57
78
  }
58
79
 
59
80
  function fail(msg) {
@@ -73,12 +94,22 @@ function ok(msg) {
73
94
  process.stdout.write(`\x1b[32m✔ [${elapsed()}s] ${msg}\x1b[0m\n`);
74
95
  }
75
96
 
97
+ // ── budgets ──────────────────────────────────────────────────────────────────
98
+
99
+ const sweepBudget = makeBudget('sweep', 'GATE_DONE_BUDGET_MS', DEFAULT_BUDGET_MS);
100
+ const testBudget = makeBudget('test', 'GATE_DONE_TEST_BUDGET_MS', DEFAULT_TEST_BUDGET_MS);
101
+
102
+ info(
103
+ `Budgets: sweeps ${sweepBudget.ms / 1000}s (GATE_DONE_BUDGET_MS), ` +
104
+ `tests ${testBudget.ms / 1000}s (GATE_DONE_TEST_BUDGET_MS).`,
105
+ );
106
+
76
107
  // ── 1. gitleaks ───────────────────────────────────────────────────────────────
77
108
 
78
109
  info('Sweep 1/3 — gitleaks secrets scan…');
79
- checkBudget('gitleaks');
110
+ checkBudget(sweepBudget, 'gitleaks');
80
111
 
81
- const hasGitleaks = capture('command -v gitleaks 2>/dev/null').status === 0;
112
+ const hasGitleaks = capture(sweepBudget, 'command -v gitleaks 2>/dev/null').status === 0;
82
113
 
83
114
  if (!hasGitleaks) {
84
115
  warn(
@@ -88,7 +119,7 @@ if (!hasGitleaks) {
88
119
  } else {
89
120
  // Scan the full git history visible from HEAD — correct mode for a pre-push hook.
90
121
  // --no-git-serial scans refs in parallel for speed within the budget.
91
- const glResult = run('gitleaks git --exit-code 1 .');
122
+ const glResult = run(sweepBudget, 'gitleaks', 'gitleaks git --exit-code 1 .');
92
123
  if (glResult.status !== 0) {
93
124
  fail('gitleaks detected a potential secret. Remove it and retry the push.');
94
125
  }
@@ -98,9 +129,9 @@ if (!hasGitleaks) {
98
129
  // ── 2. vitest coverage ────────────────────────────────────────────────────────
99
130
 
100
131
  info('Sweep 2/3 — Vitest test suite + coverage thresholds…');
101
- checkBudget('vitest');
132
+ checkBudget(testBudget, 'Vitest');
102
133
 
103
- const vitestResult = run('npx vitest run --coverage');
134
+ const vitestResult = run(testBudget, 'Vitest', 'npx vitest run --coverage');
104
135
 
105
136
  if (vitestResult.status !== 0) {
106
137
  fail('Vitest coverage gate failed — fix failing tests or low-coverage areas before pushing.');
@@ -111,7 +142,7 @@ ok('Vitest: all tests passed, coverage thresholds met.');
111
142
  // ── 3. bundle size ────────────────────────────────────────────────────────────
112
143
 
113
144
  info('Sweep 3/3 — bundle size audit…');
114
- checkBudget('bundle audit');
145
+ checkBudget(sweepBudget, 'bundle audit');
115
146
 
116
147
  const pkgPath = resolve(process.cwd(), 'package.json');
117
148
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
@@ -122,21 +153,21 @@ const hasBundlesize = Boolean(pkg.devDependencies?.['bundlesize']) || Boolean(pk
122
153
  const hasBuildScript = Boolean(pkg.scripts?.build);
123
154
 
124
155
  if (hasBundleSizeScript) {
125
- const result = run('npm run bundle-size');
156
+ const result = run(sweepBudget, 'bundle-size', 'npm run bundle-size');
126
157
  if (result.status !== 0) fail('bundle-size script reported a violation. Push blocked.');
127
158
  ok('Bundle size: within limits.');
128
159
  } else if (hasSizeLimit) {
129
- const result = run('npx size-limit');
160
+ const result = run(sweepBudget, 'size-limit', 'npx size-limit');
130
161
  if (result.status !== 0) fail('size-limit reported a violation. Push blocked.');
131
162
  ok('Bundle size: size-limit passed.');
132
163
  } else if (hasBundlesize) {
133
- const result = run('npx bundlesize');
164
+ const result = run(sweepBudget, 'bundlesize', 'npx bundlesize');
134
165
  if (result.status !== 0) fail('bundlesize reported a violation. Push blocked.');
135
166
  ok('Bundle size: bundlesize passed.');
136
167
  } else if (hasBuildScript) {
137
168
  // No size tool configured — at minimum verify the build succeeds cleanly.
138
169
  info('No size-limit/bundlesize configured — running build as a smoke-check.');
139
- const result = run('npm run build');
170
+ const result = run(sweepBudget, 'build', 'npm run build');
140
171
  if (result.status !== 0) fail('Build failed during gate-done. Push blocked.');
141
172
  ok('Build: succeeded (no size budget configured).');
142
173
  } else {
@@ -145,5 +176,9 @@ if (hasBundleSizeScript) {
145
176
 
146
177
  // ── done ─────────────────────────────────────────────────────────────────────
147
178
 
148
- ok(`gate-done completed in ${elapsed()}s (budget: 90s). Push proceeding.`);
179
+ ok(
180
+ `gate-done completed in ${elapsed()}s ` +
181
+ `(sweeps ${(sweepBudget.spent() / 1000).toFixed(1)}/${sweepBudget.ms / 1000}s, ` +
182
+ `tests ${(testBudget.spent() / 1000).toFixed(1)}/${testBudget.ms / 1000}s). Push proceeding.`,
183
+ );
149
184
  process.exit(0);
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Time budgets for the gate-* hooks.
3
+ *
4
+ * A budget is a pool of milliseconds that only drains while one of its own
5
+ * sweeps is running, so gate-done can give the Vitest sweep its own allowance
6
+ * without the fast sweeps (gitleaks, bundle) eating into it.
7
+ */
8
+
9
+ import { spawnSync } from 'node:child_process';
10
+
11
+ export const DEFAULT_BUDGET_MS = 90_000;
12
+ export const DEFAULT_TEST_BUDGET_MS = 300_000;
13
+
14
+ /**
15
+ * Read a budget in milliseconds from `env[name]`.
16
+ * Unset or empty falls back to the default; anything that is not a positive
17
+ * integer also falls back, and `invalid` carries the rejected raw value so the
18
+ * caller can warn about it.
19
+ */
20
+ export function readBudgetMs(env, name, fallback) {
21
+ const raw = env[name];
22
+ if (raw === undefined || raw.trim() === '') return { ms: fallback, source: 'default' };
23
+ const ms = Number(raw.trim());
24
+ if (!Number.isInteger(ms) || ms <= 0) return { ms: fallback, source: 'default', invalid: raw };
25
+ return { ms, source: 'env' };
26
+ }
27
+
28
+ export function createBudget(name, envVar, ms, now = Date.now) {
29
+ let spentMs = 0;
30
+ return {
31
+ name,
32
+ envVar,
33
+ ms,
34
+ spent: () => spentMs,
35
+ remaining: () => Math.max(0, ms - spentMs),
36
+ exhausted: () => spentMs >= ms,
37
+ /** Charge the time `fn` takes to this budget and return its result. */
38
+ track(fn) {
39
+ const start = now();
40
+ try {
41
+ return fn();
42
+ } finally {
43
+ spentMs += now() - start;
44
+ }
45
+ },
46
+ };
47
+ }
48
+
49
+ /**
50
+ * Run a shell command with the budget's remaining time as the child timeout.
51
+ * `timedOut` is true when the child was killed because the budget ran out,
52
+ * as opposed to exiting non-zero on its own.
53
+ */
54
+ export function runInBudget(budget, cmd, options = {}) {
55
+ const before = budget.spent();
56
+ const result = budget.track(() =>
57
+ spawnSync(cmd, { shell: true, encoding: 'utf8', ...options, timeout: budget.remaining() }),
58
+ );
59
+ const durationMs = budget.spent() - before;
60
+ return { ...result, durationMs, timedOut: result.error?.code === 'ETIMEDOUT' };
61
+ }
62
+
63
+ /** Human-readable reason a sweep was killed by its budget; not a test failure. */
64
+ export function budgetKillMessage(label, budget, durationMs) {
65
+ const secs = (durationMs / 1000).toFixed(1);
66
+ return (
67
+ `${label} killed after ${secs}s by the ${budget.name} budget ` +
68
+ `(${budget.envVar}=${budget.ms}) — not a test failure. ` +
69
+ `Raise ${budget.envVar} (milliseconds) if the run is legitimately slow.`
70
+ );
71
+ }
package/dist/index.d.mts CHANGED
@@ -1849,6 +1849,8 @@ interface ShippingOptionRule {
1849
1849
  freeOver?: number | null;
1850
1850
  minDays?: number | null;
1851
1851
  maxDays?: number | null;
1852
+ minMinutes?: number | null;
1853
+ maxMinutes?: number | null;
1852
1854
  channels: (ShippingChannel | `${ShippingChannel}`)[];
1853
1855
  outletId?: string | null;
1854
1856
  }
@@ -1884,6 +1886,8 @@ interface ShippingQuoteOption {
1884
1886
  amountToFree: number | null;
1885
1887
  minDays: number | null;
1886
1888
  maxDays: number | null;
1889
+ minMinutes: number | null;
1890
+ maxMinutes: number | null;
1887
1891
  outletId: string | null;
1888
1892
  }
1889
1893
  interface ShippingResolution {
@@ -1933,6 +1937,14 @@ declare function addressPlaceKeys(address: NormalizedAddress): string[];
1933
1937
  declare function resolveShipping({ zones, address, itemsTotal, channel }: ResolveShippingInput): ShippingResolution;
1934
1938
  declare function priceForTotal(option: ShippingOptionRule, itemsTotal: number): number;
1935
1939
 
1940
+ interface ShippingDuration {
1941
+ unit: 'minute' | 'hour';
1942
+ min: number;
1943
+ max: number;
1944
+ }
1945
+ declare function shippingDuration(minMinutes: number | null | undefined, maxMinutes: number | null | undefined): ShippingDuration | null;
1946
+ declare function formatShippingDuration(minMinutes: number | null | undefined, maxMinutes: number | null | undefined, locale?: string, display?: 'long' | 'short'): string | null;
1947
+
1936
1948
  interface ShippingZoneProblem {
1937
1949
  code: ShippingZoneError;
1938
1950
  optionId?: string;
@@ -2216,4 +2228,4 @@ declare const EXPENSE_DEFAULT_CATEGORIES: readonly [{
2216
2228
  }];
2217
2229
  type ExpenseDefaultCategoryKey = (typeof EXPENSE_DEFAULT_CATEGORIES)[number]['key'];
2218
2230
 
2219
- export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AutomaticTaxPart, type AutomaticTaxRateRow, type AutomaticTaxRowStatus, type AutomaticTaxRuleRow, type AutomaticTaxTable, type AutomaticTaxTypeRow, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, BookingRulesError, type BookingRulesInput, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderTaxSkip, type OrderWriteStrategy, OtherFixedRates, OutOfProvinceTaxes, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, SHOPPER_CONSENT_SOURCES, SHOPPER_ERROR_CODES, SHOPPER_RETURN_DECLINE_REASON_MAX, SHOPPER_RETURN_METHODS, SHOPPER_RETURN_STATUSES, STANDARD_TAX_TYPE, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type ShopperAddressInput, type ShopperCard, type ShopperConsentSource, type ShopperErrorCode, type ShopperIdentity, type ShopperNotificationChoices, type ShopperOrderDetail, type ShopperOrderItem, type ShopperOrderRow, type ShopperOrderStatus, type ShopperOrderTotals, type ShopperPaymentMethod, type ShopperProfile, type ShopperReturnMethod, type ShopperReturnRequestInput, type ShopperReturnRequestState, type ShopperReturnStatus, type ShopperSavedAddress, type ShopperScope, type ShopperStore, type ShopperStoreRef, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, TAX_EXCEPTION_REASON_MAX, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxException, TaxExceptionSource, type TaxRegistration, TaxRegistrationKind, TaxSource, TaxWarningCode, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UserTypes, type WeeklyHours, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, amountToString, ancestorChain, applyAssignment, assertUnitSane, automaticTaxTableVersion, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, buildAutomaticTaxTable, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, canTransition, cardFromProcessorData, cheapestCompositeItem, cheapestCompositePrice, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, mapToLegacyStatus, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, normalizeShopperEmail, occupancyIn, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, placeKey, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, registrationPlacesByKind, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, sameFamily, setOrderState, sha1Hex, shipsToCountry, shopDayKey, shopDayRange, signReportForDisplay, slotsForWindow, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, withinPresence };
2231
+ export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AutomaticTaxPart, type AutomaticTaxRateRow, type AutomaticTaxRowStatus, type AutomaticTaxRuleRow, type AutomaticTaxTable, type AutomaticTaxTypeRow, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, BookingRulesError, type BookingRulesInput, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderTaxSkip, type OrderWriteStrategy, OtherFixedRates, OutOfProvinceTaxes, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, SHOPPER_CONSENT_SOURCES, SHOPPER_ERROR_CODES, SHOPPER_RETURN_DECLINE_REASON_MAX, SHOPPER_RETURN_METHODS, SHOPPER_RETURN_STATUSES, STANDARD_TAX_TYPE, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, type ShippingDuration, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type ShopperAddressInput, type ShopperCard, type ShopperConsentSource, type ShopperErrorCode, type ShopperIdentity, type ShopperNotificationChoices, type ShopperOrderDetail, type ShopperOrderItem, type ShopperOrderRow, type ShopperOrderStatus, type ShopperOrderTotals, type ShopperPaymentMethod, type ShopperProfile, type ShopperReturnMethod, type ShopperReturnRequestInput, type ShopperReturnRequestState, type ShopperReturnStatus, type ShopperSavedAddress, type ShopperScope, type ShopperStore, type ShopperStoreRef, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, TAX_EXCEPTION_REASON_MAX, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxException, TaxExceptionSource, type TaxRegistration, TaxRegistrationKind, TaxSource, TaxWarningCode, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UserTypes, type WeeklyHours, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, amountToString, ancestorChain, applyAssignment, assertUnitSane, automaticTaxTableVersion, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, buildAutomaticTaxTable, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, canTransition, cardFromProcessorData, cheapestCompositeItem, cheapestCompositePrice, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, formatShippingDuration, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, mapToLegacyStatus, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, normalizeShopperEmail, occupancyIn, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, placeKey, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, registrationPlacesByKind, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, sameFamily, setOrderState, sha1Hex, shippingDuration, shipsToCountry, shopDayKey, shopDayRange, signReportForDisplay, slotsForWindow, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, withinPresence };
package/dist/index.d.ts CHANGED
@@ -1849,6 +1849,8 @@ interface ShippingOptionRule {
1849
1849
  freeOver?: number | null;
1850
1850
  minDays?: number | null;
1851
1851
  maxDays?: number | null;
1852
+ minMinutes?: number | null;
1853
+ maxMinutes?: number | null;
1852
1854
  channels: (ShippingChannel | `${ShippingChannel}`)[];
1853
1855
  outletId?: string | null;
1854
1856
  }
@@ -1884,6 +1886,8 @@ interface ShippingQuoteOption {
1884
1886
  amountToFree: number | null;
1885
1887
  minDays: number | null;
1886
1888
  maxDays: number | null;
1889
+ minMinutes: number | null;
1890
+ maxMinutes: number | null;
1887
1891
  outletId: string | null;
1888
1892
  }
1889
1893
  interface ShippingResolution {
@@ -1933,6 +1937,14 @@ declare function addressPlaceKeys(address: NormalizedAddress): string[];
1933
1937
  declare function resolveShipping({ zones, address, itemsTotal, channel }: ResolveShippingInput): ShippingResolution;
1934
1938
  declare function priceForTotal(option: ShippingOptionRule, itemsTotal: number): number;
1935
1939
 
1940
+ interface ShippingDuration {
1941
+ unit: 'minute' | 'hour';
1942
+ min: number;
1943
+ max: number;
1944
+ }
1945
+ declare function shippingDuration(minMinutes: number | null | undefined, maxMinutes: number | null | undefined): ShippingDuration | null;
1946
+ declare function formatShippingDuration(minMinutes: number | null | undefined, maxMinutes: number | null | undefined, locale?: string, display?: 'long' | 'short'): string | null;
1947
+
1936
1948
  interface ShippingZoneProblem {
1937
1949
  code: ShippingZoneError;
1938
1950
  optionId?: string;
@@ -2216,4 +2228,4 @@ declare const EXPENSE_DEFAULT_CATEGORIES: readonly [{
2216
2228
  }];
2217
2229
  type ExpenseDefaultCategoryKey = (typeof EXPENSE_DEFAULT_CATEGORIES)[number]['key'];
2218
2230
 
2219
- export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AutomaticTaxPart, type AutomaticTaxRateRow, type AutomaticTaxRowStatus, type AutomaticTaxRuleRow, type AutomaticTaxTable, type AutomaticTaxTypeRow, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, BookingRulesError, type BookingRulesInput, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderTaxSkip, type OrderWriteStrategy, OtherFixedRates, OutOfProvinceTaxes, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, SHOPPER_CONSENT_SOURCES, SHOPPER_ERROR_CODES, SHOPPER_RETURN_DECLINE_REASON_MAX, SHOPPER_RETURN_METHODS, SHOPPER_RETURN_STATUSES, STANDARD_TAX_TYPE, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type ShopperAddressInput, type ShopperCard, type ShopperConsentSource, type ShopperErrorCode, type ShopperIdentity, type ShopperNotificationChoices, type ShopperOrderDetail, type ShopperOrderItem, type ShopperOrderRow, type ShopperOrderStatus, type ShopperOrderTotals, type ShopperPaymentMethod, type ShopperProfile, type ShopperReturnMethod, type ShopperReturnRequestInput, type ShopperReturnRequestState, type ShopperReturnStatus, type ShopperSavedAddress, type ShopperScope, type ShopperStore, type ShopperStoreRef, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, TAX_EXCEPTION_REASON_MAX, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxException, TaxExceptionSource, type TaxRegistration, TaxRegistrationKind, TaxSource, TaxWarningCode, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UserTypes, type WeeklyHours, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, amountToString, ancestorChain, applyAssignment, assertUnitSane, automaticTaxTableVersion, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, buildAutomaticTaxTable, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, canTransition, cardFromProcessorData, cheapestCompositeItem, cheapestCompositePrice, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, mapToLegacyStatus, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, normalizeShopperEmail, occupancyIn, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, placeKey, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, registrationPlacesByKind, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, sameFamily, setOrderState, sha1Hex, shipsToCountry, shopDayKey, shopDayRange, signReportForDisplay, slotsForWindow, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, withinPresence };
2231
+ export { ADYEN_JOB_TITLE_ASSOCIATION_TYPES, ADYEN_LEGAL_ENTITY_STATE_PROVINCE_COUNTRIES, ADYEN_NO_TAX_NUMBER_ABSENT_COUNTRIES, ADYEN_ROLLOUT_COUNTRY_CODES, ADYEN_STORE_STATE_PROVINCE_COUNTRIES, ADYEN_TAX_NUMBER_FORMATS, ADYEN_TAX_NUMBER_MIN_LENGTH, AFFIRM_COUNTRY_CODES, AFFIRM_PRICE_PLANS, type AddressLike, type AdyenBnplSettings, type AdyenBnplSkippedStore, type AdyenBnplUpdateResult, type AffirmPricePlan, type Amount, type AssignUserChange, AttributeType, type AutomaticTaxPart, type AutomaticTaxRateRow, type AutomaticTaxRowStatus, type AutomaticTaxRuleRow, type AutomaticTaxTable, type AutomaticTaxTypeRow, type AvailabilityInput, type AvailabilitySlot, type AvailableTransition, BNPL_METHOD_STATUS, BNPL_SKIP_REASON, type BnplMethodStatus, type BnplSkipReason, type BookingOccupancy, BookingRatePeriod, type BookingResourceInput, BookingResourceKind, BookingResourceStatus, BookingRulesError, type BookingRulesInput, BookingType, type BusyWindow, CANADA_PROVINCES, CONDITION_OPERATORS, COUNTRY_CURRENCIES, CURRENCY_CONFIG, type CartDiscountBucket, type CartFeeBucket, type CashDrawer, type CashRoundingTuple, type CategoryModifierRow, type CategoryRow, CompanyType, type CompositeAvailabilityRows, type CompositeMakeable, type CompositeMakeableRow, type CompositePriceItem, type CompositePricePart, type CompositeReservationOrder, type CompositeShelf, type CompositeStockPart, type Condition, type ConditionGroup, type ConditionOperator, type ConfigUpdatedPayload, type ConfigValidationError, type ConfigValidationResult, type ConfigValidationWarning, type CountryOption, type CrossAxisRequires, type CrossAxisRule, type CrossAxisTrigger, CurrencyCode, type CurrencyConfig, type CurrencyRate, CustomTableAvailability, CustomerPlatform, DEFAULT_CONFIG, DEFAULT_CROSS_AXIS_RULES, DEFAULT_DISPLAY_STATE_MAP, DEFAULT_HOLD_MINUTES, DEFAULT_RESOLVED_CONFIG, DEFAULT_UNIT_ID, type DeleteStateConfigFragmentParams, type DeleteStateConfigFragmentResponse, type DiscountsBreakdown, type DiscountsTuple, type DisplayStateResult, type DisplayStateRule, DualWriteStrategy, EUFixedRates, EUROPE, EVERYWHERE_KEY, EXPENSE_DEFAULT_CATEGORIES, EXPENSE_NAME_MAX_LENGTH, EXPENSE_PAYMENT_METHOD_PRESETS, type EndOfSessionReport, type ExpenseDefaultCategoryKey, ExtensionCategory, FINANCIAL_INVARIANTS, FULFILLMENT_STATES, type FailedCondition, type FeesBreakdown, FeesCustomBillingStatus, type FeesTuple, type FinancialInvariant, type FragmentParam, type FragmentValidationResult, type FulfillmentState, type FulfillmentStateDefinition, type FulfillmentTransitionPath, type GetAvailableTransitionsParams, type GetAvailableTransitionsResponse, type GetOrderDisplayStateParams, type GetOrderDisplayStateResponse, type GetOrderStateConfigParams, type GetOrderStateConfigResponse, type GetStateConfigFragmentParams, type GetStateConfigFragmentResponse, type GridSlot, HttpMethod, InventoryBaseActionEnum, type InventoryBaseActionType, InventorySpecificActionType, InvoiceStatus, LegacyWriteStrategy, LibraryItemType, type LineStockMove, MAX_PRECISION, type Measurable, type MeasurementBase, type MeasurementUnit, type MeasurementUnitFamily, MenuProject, type ModifierChoiceRow, type ModifierRow, type ModifiersBreakdown, type ModifiersTuple, NAFixedRates, NORTH_AMERICA, NonRevenueItemType, type NormalizedAddress, ORDER_STATE_ACTIONS, ORDER_STATE_EVENTS, ORDER_STATE_TOPIC, type OrderContext, type OrderLikeForAssignedUsers, type OrderLikeForContext, type OrderLikeForInCart, type OrderLikeForLegacyInference, type OrderLineItem, type OrderMutationData, type OrderPaymentMethod, OrderPlatform, type OrderRefund, type OrderReservationForContext, type OrderStateEventPayload, type OrderStateWritable, type OrderStatusDefinition, type OrderStatusValidationError, type OrderTaxSkip, type OrderWriteStrategy, OtherFixedRates, OutOfProvinceTaxes, OwnerType, PATH_MODES, PAYMENT_CHANNELS, PAYMENT_STATES, POS_VALID_INITIAL_STATES, type PathMode, type PaymentChannel, PaymentMethod, PaymentProcessor, type PaymentState, type PaymentStateDefinition, type PaymentTransitionPath, type PlanWindowInput, Platform, type PoolDrawing, PreviewImageMode, PricingLevel, PricingPlanEnum, PricingRegionEnum, ProcessorType, type ProductDiscountBucket, type ProductFeeBucket, ProductSalesChartStep, ProductSalesReportCompare, ProductStatus, ProductType, type Province, PublicationAvailability, type PublicationConfig, PublicationStatus, REGION_MAPPING, REPORT_NEGATE_PATHS, ReceiptSendChannel, ReceiptType, type RefundsBreakdown, ReservationStatus, ResidualPaymentMethod, ResidualStatus, type ResolveInputs, type ResolveShippingInput, type ResolveTemplateResult, type ResourceAvailability, ResourceAvailabilityState, type ResourceInWindow, type ResourcePresenceRow, SHIPPING_COUNTRIES, SHOPPER_CONSENT_SOURCES, SHOPPER_ERROR_CODES, SHOPPER_RETURN_DECLINE_REASON_MAX, SHOPPER_RETURN_METHODS, SHOPPER_RETURN_STATUSES, STANDARD_TAX_TYPE, STATE_SCHEMA, STRIPE_SUPPORTED_COUNTRIES, SYSTEM_FAMILIES, SYSTEM_FAMILY_IDS, SYSTEM_UNITS, SYSTEM_UNIT_IDS, SalesLineAction, SalesLineSourceArray, type SalesSummary, type SaveStateConfigFragmentParams, type SaveStateConfigFragmentResponse, type SettlementBreakdown, type SettlementBuckets, type SettlementCardSection, type SettlementCashSection, type SettlementCustomEntry, ShippingChannel, type ShippingDuration, ShippingNoOptionReason, type ShippingOptionRule, ShippingOptionType, type ShippingPlace, type ShippingPriceTier, type ShippingQuoteOption, ShippingRateType, type ShippingResolution, type ShippingTuple, ShippingZoneError, ShippingZoneKind, type ShippingZoneProblem, type ShippingZoneRule, type ShopperAddressInput, type ShopperCard, type ShopperConsentSource, type ShopperErrorCode, type ShopperIdentity, type ShopperNotificationChoices, type ShopperOrderDetail, type ShopperOrderItem, type ShopperOrderRow, type ShopperOrderStatus, type ShopperOrderTotals, type ShopperPaymentMethod, type ShopperProfile, type ShopperReturnMethod, type ShopperReturnRequestInput, type ShopperReturnRequestState, type ShopperReturnStatus, type ShopperSavedAddress, type ShopperScope, type ShopperStore, type ShopperStoreRef, type SplitPayment, type SplitPaymentPayment, type StaffSales, type StaffSalesEntry, type StateConfig, type StateConfigFragment, type StateDefinition, type StatePair, type StateSchema, type StateTransitionBlockedPayload, type StateTransitionCompletedPayload, StationStatus, type StockLine, type StockLineComponent, type StockReservationLink, type StoredStateConfig, StripeCurrencyCode, StripeStatus, TAX_EXCEPTION_REASON_MAX, type TaxBreakdown, type TaxBreakdownRateEntry, type TaxBreakdownSection, type TaxBreakdownSubtotal, type TaxException, TaxExceptionSource, type TaxRegistration, TaxRegistrationKind, TaxSource, TaxWarningCode, type TaxesTuple, TimePeriod, type TipEntry, type TipsBreakdown, type TipsTuple, TopMetericsSort, type TransitionBlockedBy, type TransitionConditionSet, type TransitionOrderStateParams, type TransitionOrderStateResponse, type TransitionPath, type TransitionRequest, type TransitionResult, UserTypes, type WeeklyHours, addAmounts, addressPlaceKeys, adyenLegalEntityRequiresStateOrProvince, adyenRequiresJobTitle, adyenStoreRequiresStateOrProvince, adyenSupportsTaxNumberAbsent, adyenTaxNumberFormat, amountToString, ancestorChain, applyAssignment, assertUnitSane, automaticTaxTableVersion, availableIn, baseFor, baseFulfillmentDefinitions, baseOf, basePaymentDefinitions, buildAutomaticTaxTable, buildAvailability, buildGrid, buildOrderContext, buildPosPresetConfig, buildResolvedConfig, calculatePercentage, canTransition, cardFromProcessorData, cheapestCompositeItem, cheapestCompositePrice, compositeItemCost, compositeItemUnavailable, compositeMakeable, compositeModifierMismatches, compositeReservationMismatches, compositeVariantInStock, conditionSummary, convertFixedFeeToLocalCurrency, createAmount, crossAxisRuleApplies, currentAssignees, deriveDisplayState, deriveFamilyCode, deriveUnitId, displayRuleMatchesPair, divideAmount, evaluateCondition, evaluateConditionSet, extendPrice, extendPriceFor, formatCurrency, formatInUnit, formatMinorUnitsToString, formatQuantity, formatShippingDuration, fromBase, fromMinorUnits, generateMongoID, getAvailableTransitions, getCashAmountDue, getCountriesByRegion, getCurrencyConfig, getCurrentISODate, getFinancialInvariantViolations, getGoodsPortion, getLineSubtotal, getMinorUnitMultiplier, getMinorUnits, getPaymentLegTotal, getPricingRegionFromCountry, getSettlementTotal, getTotalCollected, hasInCartFlag, hasSellableChoice, holdExpiresAt, inferStatesFromLegacyStatus, isAdyenRolloutCountry, isAffirmCountry, isAffirmPricePlan, isChoiceAvailableAtOutlet, isConditionOperator, isFulfillmentState, isInCart, isPaymentState, isSupportedCurrency, isSystemFamilyCode, isValidQuantity, isWhole, lineStockMoves, listCountries, listProvinces, listShippingCountries, mapToLegacyStatus, maxPrecisionFor, mergeFragment, modifiersSellable, multiplyAmount, normalizeAddress, normalizeCityKey, normalizeCountry, normalizeMongoIdString, normalizePostCode, normalizeProvince, normalizeShopperEmail, occupancyIn, orderAssignments, parseAmountToMinorUnits, parseCurrencyCode, parseStripeCurrencyCode, placeKey, planWindow, poolDemand, poolOf, poolShortfall, poolStockAt, postCodeMatchesProvince, presentAt, priceForTotal, provincesForPostCode, registrationPlacesByKind, removeFragment, resolveFamily, resolveModifiersForProduct, resolveShipping, resolveTemplate, resolveUnit, roundToPrecision, sameFamily, setOrderState, sha1Hex, shippingDuration, shipsToCountry, shopDayKey, shopDayRange, signReportForDisplay, slotsForWindow, stringifyMinorUnits, subtractAmounts, toBase, toMinorUnits, validateConfig, validateFragmentCompatibility, validateOrderStatuses, validateShippingZone, violatesFinancialInvariant, windowEndsAt, withinPresence };
package/dist/index.js CHANGED
@@ -189,6 +189,7 @@ __export(index_exports, {
189
189
  formatInUnit: () => formatInUnit,
190
190
  formatMinorUnitsToString: () => formatMinorUnitsToString,
191
191
  formatQuantity: () => formatQuantity,
192
+ formatShippingDuration: () => formatShippingDuration,
192
193
  fromBase: () => fromBase,
193
194
  fromMinorUnits: () => fromMinorUnits,
194
195
  generateMongoID: () => generateMongoID,
@@ -264,6 +265,7 @@ __export(index_exports, {
264
265
  sameFamily: () => sameFamily,
265
266
  setOrderState: () => setOrderState,
266
267
  sha1Hex: () => sha1Hex,
268
+ shippingDuration: () => shippingDuration,
267
269
  shipsToCountry: () => shipsToCountry,
268
270
  shopDayKey: () => shopDayKey,
269
271
  shopDayRange: () => shopDayRange,
@@ -4290,6 +4292,8 @@ function quote(option, zoneId, itemsTotal) {
4290
4292
  amountToFree: freeOver != null && amount > 0 ? freeOver - itemsTotal : null,
4291
4293
  minDays: option.minDays ?? null,
4292
4294
  maxDays: option.maxDays ?? null,
4295
+ minMinutes: option.minMinutes ?? null,
4296
+ maxMinutes: option.maxMinutes ?? null,
4293
4297
  outletId: option.outletId ?? null
4294
4298
  };
4295
4299
  }
@@ -4304,6 +4308,21 @@ function countriesShippedTo(zones) {
4304
4308
  return [...countries].sort();
4305
4309
  }
4306
4310
 
4311
+ // shipping/time.ts
4312
+ function shippingDuration(minMinutes, maxMinutes) {
4313
+ const min = minMinutes ?? maxMinutes;
4314
+ const max = maxMinutes ?? minMinutes;
4315
+ if (min == null || max == null) return null;
4316
+ const wholeHours = max > 0 && min % 60 === 0 && max % 60 === 0;
4317
+ return wholeHours ? { unit: "hour", min: min / 60, max: max / 60 } : { unit: "minute", min, max };
4318
+ }
4319
+ function formatShippingDuration(minMinutes, maxMinutes, locale, display = "long") {
4320
+ const duration = shippingDuration(minMinutes, maxMinutes);
4321
+ if (!duration) return null;
4322
+ const unit2 = new Intl.NumberFormat(locale ?? "en", { style: "unit", unit: duration.unit, unitDisplay: display });
4323
+ return duration.min === duration.max ? unit2.format(duration.max) : `${duration.min}\u2013${unit2.format(duration.max)}`;
4324
+ }
4325
+
4307
4326
  // shipping/validate.ts
4308
4327
  function validateShippingZone(zone) {
4309
4328
  const problems = [...placeProblems(zone)];
@@ -4332,7 +4351,15 @@ function fitsKind(place, kind) {
4332
4351
  return false;
4333
4352
  }
4334
4353
  var isAmount = (value) => Number.isInteger(value) && value >= 0;
4335
- var isDays = (value) => value == null || isAmount(value);
4354
+ var isTime = (value) => value == null || isAmount(value);
4355
+ var inOrder = (min, max) => (min ?? 0) <= (max ?? Infinity);
4356
+ function timeIsValid(option) {
4357
+ const { minDays, maxDays, minMinutes, maxMinutes } = option;
4358
+ if (![minDays, maxDays, minMinutes, maxMinutes].every(isTime)) return false;
4359
+ const hasDays = minDays != null || maxDays != null;
4360
+ const hasMinutes = minMinutes != null || maxMinutes != null;
4361
+ return !(hasDays && hasMinutes) && inOrder(minDays, maxDays) && inOrder(minMinutes, maxMinutes);
4362
+ }
4336
4363
  function optionProblems(option) {
4337
4364
  const problems = [];
4338
4365
  const isPickup = option.type === "pickup" /* PICKUP */;
@@ -4340,9 +4367,7 @@ function optionProblems(option) {
4340
4367
  problems.push("INVALID_PRICE" /* INVALID_PRICE */);
4341
4368
  }
4342
4369
  if (!isPickup && !option.name?.trim()) problems.push("MISSING_NAME" /* MISSING_NAME */);
4343
- if (!isDays(option.minDays) || !isDays(option.maxDays) || (option.minDays ?? 0) > (option.maxDays ?? Infinity)) {
4344
- problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4345
- }
4370
+ if (!timeIsValid(option)) problems.push("INVALID_DAYS" /* INVALID_DAYS */);
4346
4371
  if (!tiersAreValid(option)) problems.push("INVALID_TIERS" /* INVALID_TIERS */);
4347
4372
  if (option.channels.length === 0) problems.push("NO_CHANNEL" /* NO_CHANNEL */);
4348
4373
  if (isPickup && !option.outletId) problems.push("PICKUP_WITHOUT_STORE" /* PICKUP_WITHOUT_STORE */);
@@ -4811,6 +4836,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4811
4836
  formatInUnit,
4812
4837
  formatMinorUnitsToString,
4813
4838
  formatQuantity,
4839
+ formatShippingDuration,
4814
4840
  fromBase,
4815
4841
  fromMinorUnits,
4816
4842
  generateMongoID,
@@ -4886,6 +4912,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4886
4912
  sameFamily,
4887
4913
  setOrderState,
4888
4914
  sha1Hex,
4915
+ shippingDuration,
4889
4916
  shipsToCountry,
4890
4917
  shopDayKey,
4891
4918
  shopDayRange,