@fire-spark/core 0.25.0 → 0.26.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.d.ts CHANGED
@@ -3212,7 +3212,8 @@ declare const applyFees: (input: ApplyFeesInput) => OrderLine[];
3212
3212
  declare const rebuildOrderLinesWithFees: (input: ApplyFeesInput) => OrderLine[];
3213
3213
  //#endregion
3214
3214
  //#region src/order/checkout.d.ts
3215
- declare const collectCheckoutIssues: (checkout: CheckoutPreferences, order: OrderRecord, fulfillmentType?: string | null) => OrderIssue[];
3215
+ /** `now` (ISO) evaluates time conditions at another moment, e.g. a sale. */
3216
+ declare const collectCheckoutIssues: (checkout: CheckoutPreferences, order: OrderRecord, fulfillmentType?: string | null, now?: string) => OrderIssue[];
3216
3217
  //#endregion
3217
3218
  //#region src/rules/orderFacts.d.ts
3218
3219
  declare const orderFactsFromOrder: (order: OrderRecord) => RulesEngineParams;
@@ -3224,4 +3225,55 @@ declare const normalizeLocaleKey: (raw: string) => string;
3224
3225
  declare const findLocaleKey: (value: Record<string, string>, locale: string) => string | undefined;
3225
3226
  declare const pickMultiLanguageText: (value: Record<string, string> | string | null | undefined, locale?: string, fallback?: string) => string;
3226
3227
  //#endregion
3227
- export { type ApplyRedeemInput, type AuthConfigureOptions, type BuildScheduleSlotsConfig, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type ExchangeOptions, type FailedCharge, type FlatMenuCategory, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type ListMenusStreamOptions, type ListPaymentsOptions, LosslessNumber, type LosslessNumberLike, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, Order, OrderAuthPinnedError, type OrderCancelInput, type OrderCancelOptions, type OrderCancelResult, type OrderCancelType, type OrderCustomerSource, type OrderDeviceCredential, type OrderDraft, type OrderIssue, type OrderIssueCode, type OrderLineDiff, type OrderLineIssue, type OrderLineIssueCode, OrderNotOpenError, OrderPaymentRequiredError, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, PickupNameIssue, type PricingModifier, type Product, type ProductCtx, type QuantitiesByPath, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ReversalOutcome, type ReverseAllOptions, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerResult, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
3228
+ //#region src/hpke/hpke.d.ts
3229
+ /**
3230
+ * HPKE base mode (RFC 9180): DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and
3231
+ * AES-GCM, single-shot (sequence 0). WebCrypto only, so the cloud and a
3232
+ * Local Node share it. Credentials sent to a node are sealed with it.
3233
+ */
3234
+ type HpkeAead = "AES-128-GCM" | "AES-256-GCM";
3235
+ interface HpkePublicJwk {
3236
+ kty: "EC";
3237
+ crv: "P-256";
3238
+ x: string;
3239
+ y: string;
3240
+ }
3241
+ interface HpkePrivateJwk extends HpkePublicJwk {
3242
+ d: string;
3243
+ }
3244
+ interface HpkeSealInput {
3245
+ recipient: HpkePublicJwk;
3246
+ plaintext: Uint8Array;
3247
+ info: Uint8Array;
3248
+ aad: Uint8Array;
3249
+ aead?: HpkeAead;
3250
+ /** Tests only: a fixed ephemeral key (RFC 9180 vectors). */
3251
+ ephemeral?: HpkePrivateJwk;
3252
+ }
3253
+ interface HpkeOpenInput {
3254
+ recipient: HpkePrivateJwk;
3255
+ enc: Uint8Array;
3256
+ ciphertext: Uint8Array;
3257
+ info: Uint8Array;
3258
+ aad: Uint8Array;
3259
+ aead?: HpkeAead;
3260
+ }
3261
+ /** Envelope on the wire: `enc` and `ct` are base64url. */
3262
+ interface HpkeEnvelope {
3263
+ alg: typeof HPKE_ALG;
3264
+ kid?: string;
3265
+ enc: string;
3266
+ ct: string;
3267
+ }
3268
+ declare const HPKE_ALG: "HPKE-Base-P256-SHA256-AES256GCM";
3269
+ declare const base64UrlEncode: (bytes: Uint8Array) => string;
3270
+ declare const base64UrlDecode: (value: string) => Uint8Array<ArrayBuffer>;
3271
+ /** Seals `plaintext` to the recipient's P-256 key. */
3272
+ declare const hpkeSeal: (input: HpkeSealInput) => Promise<{
3273
+ enc: Uint8Array<ArrayBuffer>;
3274
+ ciphertext: Uint8Array<ArrayBuffer>;
3275
+ }>;
3276
+ /** Opens a sealed message; throws when anything was altered. */
3277
+ declare const hpkeOpen: (input: HpkeOpenInput) => Promise<Uint8Array<ArrayBuffer>>;
3278
+ //#endregion
3279
+ export { type ApplyRedeemInput, type AuthConfigureOptions, type BuildScheduleSlotsConfig, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type ExchangeOptions, type FailedCharge, type FlatMenuCategory, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type ListMenusStreamOptions, type ListPaymentsOptions, LosslessNumber, type LosslessNumberLike, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, Order, OrderAuthPinnedError, type OrderCancelInput, type OrderCancelOptions, type OrderCancelResult, type OrderCancelType, type OrderCustomerSource, type OrderDeviceCredential, type OrderDraft, type OrderIssue, type OrderIssueCode, type OrderLineDiff, type OrderLineIssue, type OrderLineIssueCode, OrderNotOpenError, OrderPaymentRequiredError, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, PickupNameIssue, type PricingModifier, type Product, type ProductCtx, type QuantitiesByPath, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ReversalOutcome, type ReverseAllOptions, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerResult, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
package/dist/index.js CHANGED
@@ -13008,14 +13008,16 @@ const asRecord = (value) => {
13008
13008
  if (Array.isArray(value)) return null;
13009
13009
  return value;
13010
13010
  };
13011
- const collectCheckoutIssues = (checkout, order, fulfillmentType) => {
13011
+ /** `now` (ISO) evaluates time conditions at another moment, e.g. a sale. */
13012
+ const collectCheckoutIssues = (checkout, order, fulfillmentType, now) => {
13012
13013
  const customer = asRecord(order.customer) ?? {};
13013
13014
  const address = asRecord(customer.address_info);
13014
13015
  const billing = asRecord(customer.billing_info);
13015
13016
  const resolved = resolveCheckout(order, {
13016
13017
  runtime: "server",
13017
13018
  checkout,
13018
- fulfillmentType
13019
+ fulfillmentType,
13020
+ now
13019
13021
  });
13020
13022
  const issues = [];
13021
13023
  const pushFields = (info, fields, code) => {
@@ -13055,4 +13057,210 @@ const collectCheckoutIssues = (checkout, order, fulfillmentType) => {
13055
13057
  return issues;
13056
13058
  };
13057
13059
  //#endregion
13058
- export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, ID_HASH_FORMATS, LosslessNumber, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
13060
+ //#region src/hpke/hpke.ts
13061
+ const HPKE_ALG = "HPKE-Base-P256-SHA256-AES256GCM";
13062
+ const KEM_ID = 16;
13063
+ const KDF_ID = 1;
13064
+ const AEAD_IDS = {
13065
+ "AES-128-GCM": 1,
13066
+ "AES-256-GCM": 2
13067
+ };
13068
+ const AEAD_KEY_BYTES = {
13069
+ "AES-128-GCM": 16,
13070
+ "AES-256-GCM": 32
13071
+ };
13072
+ const HASH_BYTES = 32;
13073
+ const NONCE_BYTES = 12;
13074
+ const POINT_BYTES = 65;
13075
+ const ECDH = {
13076
+ name: "ECDH",
13077
+ namedCurve: "P-256"
13078
+ };
13079
+ const subtle = () => {
13080
+ const value = globalThis.crypto?.subtle;
13081
+ if (!value) throw new Error("WebCrypto (crypto.subtle) is required");
13082
+ return value;
13083
+ };
13084
+ const text = (value) => new TextEncoder().encode(value);
13085
+ const concat = (...parts) => {
13086
+ const size = parts.reduce((sum, part) => sum + part.length, 0);
13087
+ const out = new Uint8Array(size);
13088
+ let at = 0;
13089
+ for (const part of parts) {
13090
+ out.set(part, at);
13091
+ at += part.length;
13092
+ }
13093
+ return out;
13094
+ };
13095
+ const i2osp = (value, length) => {
13096
+ const out = new Uint8Array(length);
13097
+ for (let i = length - 1, rest = value; i >= 0; i -= 1, rest >>= 8) out[i] = rest & 255;
13098
+ return out;
13099
+ };
13100
+ const buffer = (value) => value;
13101
+ const base64UrlEncode = (bytes) => {
13102
+ let binary = "";
13103
+ for (const byte of bytes) binary += String.fromCharCode(byte);
13104
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13105
+ };
13106
+ const base64UrlDecode = (value) => {
13107
+ if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid base64url");
13108
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
13109
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
13110
+ const binary = atob(padded);
13111
+ const out = new Uint8Array(binary.length);
13112
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
13113
+ return out;
13114
+ };
13115
+ const hmac = async (key, data) => {
13116
+ const k = await subtle().importKey("raw", buffer(key), {
13117
+ name: "HMAC",
13118
+ hash: "SHA-256"
13119
+ }, false, ["sign"]);
13120
+ const mac = await subtle().sign("HMAC", k, buffer(data));
13121
+ return new Uint8Array(mac);
13122
+ };
13123
+ /** An empty salt is HashLen zeros (RFC 5869); same HMAC result. */
13124
+ const extract = (salt, ikm) => {
13125
+ const key = salt.length > 0 ? salt : new Uint8Array(HASH_BYTES);
13126
+ return hmac(key, ikm);
13127
+ };
13128
+ const expand = async (prk, info, length) => {
13129
+ const blocks = [];
13130
+ let previous = /* @__PURE__ */ new Uint8Array(0);
13131
+ let size = 0;
13132
+ for (let counter = 1; size < length; counter += 1) {
13133
+ const input = concat(previous, info, Uint8Array.of(counter));
13134
+ previous = await hmac(prk, input);
13135
+ blocks.push(previous);
13136
+ size += previous.length;
13137
+ }
13138
+ return concat(...blocks).slice(0, length);
13139
+ };
13140
+ const VERSION = text("HPKE-v1");
13141
+ const labeledExtract = (suite, salt, label, ikm) => {
13142
+ return extract(salt, concat(VERSION, suite, text(label), ikm));
13143
+ };
13144
+ const labeledExpand = (suite, prk, label, info, length) => {
13145
+ const labeled = concat(i2osp(length, 2), VERSION, suite, text(label), info);
13146
+ return expand(prk, labeled, length);
13147
+ };
13148
+ const kemSuite = () => concat(text("KEM"), i2osp(KEM_ID, 2));
13149
+ const hpkeSuite = (aead) => {
13150
+ const ids = concat(i2osp(KEM_ID, 2), i2osp(KDF_ID, 2));
13151
+ return concat(text("HPKE"), ids, i2osp(AEAD_IDS[aead], 2));
13152
+ };
13153
+ const rawPoint = (jwk) => {
13154
+ const x = base64UrlDecode(jwk.x);
13155
+ const y = base64UrlDecode(jwk.y);
13156
+ if (x.length !== 32 || y.length !== 32) throw new Error("Invalid P-256 key");
13157
+ return concat(Uint8Array.of(4), x, y);
13158
+ };
13159
+ const importPublic = (raw) => {
13160
+ if (raw.length !== POINT_BYTES || raw[0] !== 4) throw new Error("Invalid HPKE enc");
13161
+ return subtle().importKey("raw", buffer(raw), ECDH, true, []);
13162
+ };
13163
+ const importPrivate = (jwk) => {
13164
+ const key = {
13165
+ kty: "EC",
13166
+ crv: "P-256",
13167
+ x: jwk.x,
13168
+ y: jwk.y,
13169
+ d: jwk.d
13170
+ };
13171
+ return subtle().importKey("jwk", key, ECDH, false, ["deriveBits"]);
13172
+ };
13173
+ const dh = async (privateKey, publicKey) => {
13174
+ const alg = {
13175
+ name: "ECDH",
13176
+ public: publicKey
13177
+ };
13178
+ const bits = await subtle().deriveBits(alg, privateKey, 256);
13179
+ return new Uint8Array(bits);
13180
+ };
13181
+ const sharedSecret = async (secret, context) => {
13182
+ const suite = kemSuite();
13183
+ const prk = await labeledExtract(suite, /* @__PURE__ */ new Uint8Array(0), "eae_prk", secret);
13184
+ return labeledExpand(suite, prk, "shared_secret", context, HASH_BYTES);
13185
+ };
13186
+ const keySchedule = async (aead, shared, info) => {
13187
+ const suite = hpkeSuite(aead);
13188
+ const empty = /* @__PURE__ */ new Uint8Array(0);
13189
+ const pskId = await labeledExtract(suite, empty, "psk_id_hash", empty);
13190
+ const infoHash = await labeledExtract(suite, empty, "info_hash", info);
13191
+ const context = concat(Uint8Array.of(0), pskId, infoHash);
13192
+ const secret = await labeledExtract(suite, shared, "secret", empty);
13193
+ const p1 = [
13194
+ suite,
13195
+ secret,
13196
+ "key",
13197
+ context,
13198
+ AEAD_KEY_BYTES[aead]
13199
+ ];
13200
+ return {
13201
+ key: await labeledExpand(...p1),
13202
+ nonce: await labeledExpand(...[
13203
+ suite,
13204
+ secret,
13205
+ "base_nonce",
13206
+ context,
13207
+ NONCE_BYTES
13208
+ ])
13209
+ };
13210
+ };
13211
+ const aesKey = (key, usage) => {
13212
+ return subtle().importKey("raw", buffer(key), { name: "AES-GCM" }, false, [usage]);
13213
+ };
13214
+ const ephemeralKey = async (fixed) => {
13215
+ if (fixed) return {
13216
+ privateKey: await importPrivate(fixed),
13217
+ enc: rawPoint(fixed)
13218
+ };
13219
+ const pair = await subtle().generateKey(ECDH, true, ["deriveBits"]);
13220
+ const raw = await subtle().exportKey("raw", pair.publicKey);
13221
+ return {
13222
+ privateKey: pair.privateKey,
13223
+ enc: new Uint8Array(raw)
13224
+ };
13225
+ };
13226
+ /** Seals `plaintext` to the recipient's P-256 key. */
13227
+ const hpkeSeal = async (input) => {
13228
+ const aead = input.aead ?? "AES-256-GCM";
13229
+ const recipientRaw = rawPoint(input.recipient);
13230
+ const recipient = await importPublic(recipientRaw);
13231
+ const { privateKey, enc } = await ephemeralKey(input.ephemeral);
13232
+ const secret = await dh(privateKey, recipient);
13233
+ const shared = await sharedSecret(secret, concat(enc, recipientRaw));
13234
+ const { key, nonce } = await keySchedule(aead, shared, input.info);
13235
+ const k = await aesKey(key, "encrypt");
13236
+ const params = {
13237
+ name: "AES-GCM",
13238
+ iv: buffer(nonce),
13239
+ additionalData: buffer(input.aad)
13240
+ };
13241
+ const sealed = await subtle().encrypt(params, k, buffer(input.plaintext));
13242
+ return {
13243
+ enc,
13244
+ ciphertext: new Uint8Array(sealed)
13245
+ };
13246
+ };
13247
+ /** Opens a sealed message; throws when anything was altered. */
13248
+ const hpkeOpen = async (input) => {
13249
+ const aead = input.aead ?? "AES-256-GCM";
13250
+ const recipientRaw = rawPoint(input.recipient);
13251
+ const privateKey = await importPrivate(input.recipient);
13252
+ const ephemeral = await importPublic(input.enc);
13253
+ const secret = await dh(privateKey, ephemeral);
13254
+ const shared = await sharedSecret(secret, concat(input.enc, recipientRaw));
13255
+ const { key, nonce } = await keySchedule(aead, shared, input.info);
13256
+ const k = await aesKey(key, "decrypt");
13257
+ const params = {
13258
+ name: "AES-GCM",
13259
+ iv: buffer(nonce),
13260
+ additionalData: buffer(input.aad)
13261
+ };
13262
+ const opened = await subtle().decrypt(params, k, buffer(input.ciphertext));
13263
+ return new Uint8Array(opened);
13264
+ };
13265
+ //#endregion
13266
+ export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fire-spark/core",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Fire Spark headless SDK",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -20,8 +20,8 @@
20
20
  "big.js": "6.2.1",
21
21
  "dayjs": "1.11.9",
22
22
  "@types/big.js": "6.2.2",
23
- "@fire-spark/payments": "^0.25.0",
24
- "@fire-spark/types": "^0.25.0"
23
+ "@fire-spark/payments": "^0.26.0",
24
+ "@fire-spark/types": "^0.26.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "tsdown": "^0.22.14",