@fire-spark/core 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +46 -10
  2. package/dist/index.js +547 -180
  3. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Money, PaymentAdapter, PaymentCollectAt, PaymentContext, PaymentResult, PaymentReversal, PaymentStorage, PaymentUI, RedeemLike, RedeemSource, isDeliveryFee, isRealPaymentMethod, orderRedeems } from "@fire-spark/payments";
2
- import { AndConditions, ApplyFeesInput, ApplyFeesOrderScope, CheckoutMode, CheckoutResolved, CmsBlock, Condition, Customer, CustomerIdentifyInput, CustomerRegisterInput, CustomerUpdateInput, DeviceSecretStorage, DeviceSecretsConfigureOptions, DeviceSecretsConfigureOptions as DeviceSecretsConfigureOptions$1, DeviceSecretsPayload, DeviceSecretsPayload as DeviceSecretsPayload$1, Fee, Fulfillment, FulfillmentEligibilityInput, FulfillmentEligibilityInput as FulfillmentEligibilityInput$1, FulfillmentListInput, GroupDisplayType, KioskDeviceConfig, KioskDeviceConfigInput, KioskDeviceOverrides, KioskHealthBatchInput, KioskHealthBatchResult, KioskHeartbeatInput, KioskHeartbeatResult, KioskPickupNameRules, KioskRealtimeToken, LocalServerConfig, LocalServerConfig as LocalServerConfig$1, LocalServerHealthResult, LocalServerHealthResult as LocalServerHealthResult$1, MasivoTotpCode, MasivoTotpCreateInput, MasivoTotpVerification, MasivoTotpVerifyInput, MatchResult, MatchableRule, Menu, Menu as Menu$1, MenuLookup, MenuLookup as MenuLookup$1, MerchantPayment, ModifierControlType, ModifierGroup, OrConditions, Order as Order$1, Order as Order$2, OrderAdvanceFulfillmentInput, OrderCancelInput, OrderCancelInput as OrderCancelInput$1, OrderCancelType, OrderCancelType as OrderCancelType$1, OrderDeviceListInput, OrderDeviceListResult, OrderFulfillment, OrderFulfillmentWorkflow, OrderFulfillmentWorkflowEdge, OrderFulfillmentWorkflowNode, OrderInsertInput, OrderLine, OrderListInput, OrderRateInput, OrderRating, OrderRecord, OrderRecordPaymentInput, OrderRedeem, OrderRedemptionStep, OrderReorderInput, OrderRouteKind, OrderRouteKind as OrderRouteKind$1, OrderRouteStatus, OrderRoutes, OrderRoutes as OrderRoutes$1, OrderSetCustomerInput, OrderTotals, OrderUpdateInput, OrderValidateInput, OrderValidateOutput, PaymentCollectAt as PaymentCollectAt$1, PaymentEligibilityInput, PaymentEligibilityInput as PaymentEligibilityInput$1, PaymentIntentPutInput, PaymentMethod, PaymentProvider, PaymentTender, PaymentTenderInput, PlaceOrderResult, PosCatalog, PosFloorInput, PosFloorOccupancy, PosFloorPlan, PosFloorRealtimeToken, PosHealthBatchInput, PosHealthBatchResult, PosHeartbeatInput, PosHeartbeatResult, PosKioskOrder, PosKioskSettleInput, PosKioskSettleResult, PosOrderInput, PosOrderResult, PosTableAttachOrderInput, PosTableCloseInput, PosTableJoinInput, PosTableSeatInput, PosTableSeatReservationInput, PosTableSplitInput, PricingModifier, Product, Product as Product$1, ProductRewardSavings, Recommendation, RecurringDateCronFormatter, RecurringDateCronResult, RecurringDateCronSummary, RecurringDateCronValues, RouteEligibility, RouteEligibility as RouteEligibility$1, RouteEligibilityDetail, RouteEligibilityFlags, RouteEligibilityReason, RouteFailureKind, RouteFailureKind as RouteFailureKind$1, RouteHealthEvent, RouteHealthEvent as RouteHealthEvent$1, RouteHealthListener, RouteHealthListener as RouteHealthListener$1, RulesEngineOrder, RulesEngineOrderLine, RulesEngineParams, RulesEngineRuntime, Schedule, SdkLogContext, SdkLogErrorInfo, SdkLogLevel, SdkLogOptions, Store, StoreGetInput, StoreListInput, StoreNearbyInput, StorefrontAvailability, StorefrontMenu, StorefrontMenuScope, StorefrontMenuStreamOptions, StorefrontPaymentsListInput, StorefrontPreferences, SwitchCustomerArg, SwitchCustomerArg as SwitchCustomerArg$1, SwitchCustomerIdToken, SwitchCustomerOptions, SwitchCustomerOptions as SwitchCustomerOptions$1, SwitchCustomerResult, SwitchCustomerResult as SwitchCustomerResult$1, TenderRefundInput, TenderReplaceInput, TenderVoidInput, Variant, VariantGroup, WordFilterCheckInput, WordFilterCheckResult } from "@fire-spark/types";
2
+ import { AndConditions, ApplyFeesInput, ApplyFeesOrderScope, CheckoutMode, CheckoutResolved, CmsBlock, Condition, Customer, CustomerIdentifyInput, CustomerRegisterInput, CustomerUpdateInput, DeviceSecretStorage, DeviceSecretsConfigureOptions, DeviceSecretsConfigureOptions as DeviceSecretsConfigureOptions$1, DeviceSecretsPayload, DeviceSecretsPayload as DeviceSecretsPayload$1, Fee, Fulfillment, FulfillmentEligibilityInput, FulfillmentEligibilityInput as FulfillmentEligibilityInput$1, FulfillmentListInput, GroupDisplayType, InvoiceCountryCode, InvoiceCountryDescriptor, KioskDeviceConfig, KioskDeviceConfigInput, KioskDeviceOverrides, KioskHealthBatchInput, KioskHealthBatchResult, KioskHeartbeatInput, KioskHeartbeatResult, KioskPickupNameRules, KioskRealtimeToken, LocalServerConfig, LocalServerConfig as LocalServerConfig$1, LocalServerHealthResult, LocalServerHealthResult as LocalServerHealthResult$1, MasivoTotpCode, MasivoTotpCreateInput, MasivoTotpVerification, MasivoTotpVerifyInput, MatchResult, MatchableRule, Menu, Menu as Menu$1, MenuLookup, MenuLookup as MenuLookup$1, MerchantPayment, ModifierControlType, ModifierGroup, OrConditions, Order as Order$1, Order as Order$2, OrderAdvanceFulfillmentInput, OrderCancelInput, OrderCancelInput as OrderCancelInput$1, OrderCancelType, OrderCancelType as OrderCancelType$1, OrderDeviceListInput, OrderDeviceListResult, OrderFulfillment, OrderFulfillmentWorkflow, OrderFulfillmentWorkflowEdge, OrderFulfillmentWorkflowNode, OrderInsertInput, OrderLine, OrderListInput, OrderRateInput, OrderRating, OrderRecord, OrderRecordPaymentInput, OrderRedeem, OrderRedemptionStep, OrderReorderInput, OrderRouteKind, OrderRouteKind as OrderRouteKind$1, OrderRouteStatus, OrderRoutes, OrderRoutes as OrderRoutes$1, OrderSetCustomerInput, OrderTotals, OrderUpdateInput, OrderValidateInput, OrderValidateOutput, PaymentCollectAt as PaymentCollectAt$1, PaymentEligibilityInput, PaymentEligibilityInput as PaymentEligibilityInput$1, PaymentIntentPutInput, PaymentMethod, PaymentProvider, PaymentTender, PaymentTenderInput, PlaceOrderResult, PosCatalog, PosFloorInput, PosFloorOccupancy, PosFloorPlan, PosFloorRealtimeToken, PosHealthBatchInput, PosHealthBatchResult, PosHeartbeatInput, PosHeartbeatResult, PosKioskOrder, PosKioskSettleInput, PosKioskSettleResult, PosOrderInput, PosOrderResult, PosTableAttachOrderInput, PosTableCloseInput, PosTableJoinInput, PosTableSeatInput, PosTableSeatReservationInput, PosTableSplitInput, PricingModifier, Product, Product as Product$1, ProductRewardSavings, Recommendation, RecurringDateCronFormatter, RecurringDateCronResult, RecurringDateCronSummary, RecurringDateCronValues, RouteEligibility, RouteEligibility as RouteEligibility$1, RouteEligibilityDetail, RouteEligibilityFlags, RouteEligibilityReason, RouteFailureKind, RouteFailureKind as RouteFailureKind$1, RouteHealthEvent, RouteHealthEvent as RouteHealthEvent$1, RouteHealthListener, RouteHealthListener as RouteHealthListener$1, RulesEngineOrder, RulesEngineOrderLine, RulesEngineParams, RulesEngineRuntime, Schedule, SdkLogContext, SdkLogErrorInfo, SdkLogLevel, SdkLogOptions, Store, StoreGetInput, StoreListInput, StoreNearbyInput, StorefrontAvailability, StorefrontMenu, StorefrontMenuScope, StorefrontMenuStreamOptions, StorefrontPaymentsListInput, StorefrontPreferences, SwitchCustomerArg, SwitchCustomerArg as SwitchCustomerArg$1, SwitchCustomerIdToken, SwitchCustomerOptions, SwitchCustomerOptions as SwitchCustomerOptions$1, SwitchCustomerResult, SwitchCustomerResult as SwitchCustomerResult$1, TaxBreakdownItem, TaxCategory, TaxIdValidationResult, TenderRefundInput, TenderReplaceInput, TenderVoidInput, Variant, VariantGroup, WordFilterCheckInput, WordFilterCheckResult } from "@fire-spark/types";
3
3
  import { Big } from "big.js";
4
4
  //#region src/productCustomization/catalog.utils.d.ts
5
5
  /** Image for a product inside one modifier group, else the product image. */
@@ -1285,6 +1285,7 @@ declare const capRedeems: <T extends CapOrder>(order: T) => T & {
1285
1285
  }[];
1286
1286
  quantity: number;
1287
1287
  tax_rate: number | null;
1288
+ tax_category?: "EXEMPT" | "NOT_SUBJECT" | "STANDARD" | "ZERO" | undefined;
1288
1289
  discount_rate: number;
1289
1290
  unit_subtotal: number;
1290
1291
  unit_discount: number;
@@ -2890,7 +2891,7 @@ declare const outgoingEdges: (workflow: OrderFulfillmentWorkflow, nodeId: string
2890
2891
  channel_id: string;
2891
2892
  brand_id: string;
2892
2893
  primitive: "boolean";
2893
- type: "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
2894
+ type: "Buyer identified" | "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
2894
2895
  operator: "is" | "is not";
2895
2896
  value: boolean;
2896
2897
  invalidMessage?: string | undefined;
@@ -2999,7 +3000,7 @@ declare const incomingEdges: (workflow: OrderFulfillmentWorkflow, nodeId: string
2999
3000
  channel_id: string;
3000
3001
  brand_id: string;
3001
3002
  primitive: "boolean";
3002
- type: "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3003
+ type: "Buyer identified" | "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3003
3004
  operator: "is" | "is not";
3004
3005
  value: boolean;
3005
3006
  invalidMessage?: string | undefined;
@@ -3108,7 +3109,7 @@ declare const defaultOutgoingEdge: (workflow: OrderFulfillmentWorkflow, nodeId:
3108
3109
  channel_id: string;
3109
3110
  brand_id: string;
3110
3111
  primitive: "boolean";
3111
- type: "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3112
+ type: "Buyer identified" | "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3112
3113
  operator: "is" | "is not";
3113
3114
  value: boolean;
3114
3115
  invalidMessage?: string | undefined;
@@ -3363,7 +3364,7 @@ declare const resolveFailureTerminalEdge: (input: {
3363
3364
  channel_id: string;
3364
3365
  brand_id: string;
3365
3366
  primitive: "boolean";
3366
- type: "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3367
+ type: "Buyer identified" | "Customer is anonymous" | "Is anonymous order" | "Is running local" | "Is running offline" | "Order includes product with tag" | "Order is scheduled" | "Payment captured" | "Payment is mixed";
3367
3368
  operator: "is" | "is not";
3368
3369
  value: boolean;
3369
3370
  invalidMessage?: string | undefined;
@@ -3823,7 +3824,7 @@ declare const DEFAULT_MAX_INCOMPLETE_MINUTES = 240;
3823
3824
  declare const MIN_MAX_INCOMPLETE_MINUTES = 1;
3824
3825
  declare const MAX_MAX_INCOMPLETE_MINUTES = 43200;
3825
3826
  type FulfillmentStepName = "ACCEPTING" | "PROCESS_STATE_NODE" | "PAUSE_FOR_ADVANCE" | "WARN_NO_EDGE" | "FINALIZE" | "ROLLBACK_PROCESS_STATE_NODE" | "ROLLBACK_ACCEPT";
3826
- type FulfillmentRunStatus = "PROCESSING" | "WAITING" | "SUCCESS" | "FAILED";
3827
+ type FulfillmentRunStatus = "PROCESSING" | "WAITING" | "SUCCESS" | "FAILED" | "CANCELLED";
3827
3828
  type FulfillmentTerminalOrderStatus = "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED" | "FAILED";
3828
3829
  type EngineOrderStatus = "OPEN" | "CLOSED" | "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED" | "CANCELLED" | "FAILED";
3829
3830
  interface EngineExecutionContext {
@@ -4067,6 +4068,7 @@ interface AdvanceAndEnterConfig extends EngineScope {
4067
4068
  }
4068
4069
  type AdvanceAndEnterResult = {
4069
4070
  noEdge: true;
4071
+ alreadyTerminal?: boolean;
4070
4072
  } | {
4071
4073
  noEdge: false;
4072
4074
  ran: ProcessStateNodeResult;
@@ -4092,7 +4094,7 @@ interface DispatchWebhooksConfig extends EngineScope {
4092
4094
  }
4093
4095
  interface FinalizePlaceOrderConfig {
4094
4096
  orderFulfillmentId: string;
4095
- status: "SUCCESS" | "FAILED";
4097
+ status: "SUCCESS" | "FAILED" | "CANCELLED";
4096
4098
  failureMessage?: string;
4097
4099
  errorCode?: string;
4098
4100
  errorDetails?: Record<string, unknown>;
@@ -4169,17 +4171,25 @@ declare const processStateNode: (ports: FulfillmentPorts, config: ProcessStateNo
4169
4171
  interface PauseForAdvanceConfig {
4170
4172
  orderFulfillmentId: string;
4171
4173
  }
4174
+ type PauseForAdvanceResult = {
4175
+ closed: true;
4176
+ status: "SUCCESS" | "FAILED" | "CANCELLED";
4177
+ } | {
4178
+ closed: false;
4179
+ };
4172
4180
  interface ResumeFromAdvanceConfig extends PauseForAdvanceConfig {
4173
4181
  orderId: string;
4174
4182
  fulfillmentStatus?: string;
4175
4183
  requestedAt?: string;
4176
4184
  emit?: boolean;
4177
4185
  }
4178
- declare const pauseForAdvance: (ports: FulfillmentPorts, config: PauseForAdvanceConfig) => Promise<void>;
4186
+ declare const pauseForAdvance: (ports: FulfillmentPorts, config: PauseForAdvanceConfig) => Promise<PauseForAdvanceResult>;
4179
4187
  declare const resumeFromAdvance: (ports: FulfillmentPorts, config: ResumeFromAdvanceConfig) => Promise<{
4180
4188
  edges: null;
4189
+ alreadyTerminal: boolean;
4181
4190
  } | {
4182
4191
  edges: import("@fire-spark/types").OrderFulfillmentWorkflowEdge[];
4192
+ alreadyTerminal: boolean;
4183
4193
  }>;
4184
4194
  //#endregion
4185
4195
  //#region src/fulfillment/engine/enterAndPause.d.ts
@@ -4262,6 +4272,8 @@ declare const resolveWebhookTargetUrl: (webhook: Pick<EngineWebhookTarget, "url"
4262
4272
  declare const dispatchOrderWebhooks: (ports: FulfillmentPorts, config: DispatchWebhooksConfig) => Promise<EngineWebhookNodeRun[]>;
4263
4273
  //#endregion
4264
4274
  //#region src/fulfillment/engine/finalize.d.ts
4275
+ declare const terminalRunStatusForNode: (node?: Pick<OrderFulfillmentWorkflowNode, "data"> | null, order?: Pick<EngineOrder, "status"> | null) => "SUCCESS" | "CANCELLED";
4276
+ declare const terminalRunStatusForEnter: (ran: EnterRunResult) => "SUCCESS" | "CANCELLED";
4265
4277
  declare const engineOrderStatusForFailedRun: (order: EngineOrder | null, isPaymentCaptured?: typeof defaultIsPaymentCaptured) => "REVERSED" | "VOIDED" | null;
4266
4278
  declare const finalizePlaceOrder: (ports: FulfillmentPorts, config: FinalizePlaceOrderConfig) => Promise<{
4267
4279
  failed: boolean;
@@ -4279,7 +4291,7 @@ declare const settleEnter: (ports: FulfillmentPorts, scope: EngineScope, next: P
4279
4291
  declare const autoEnterSuccessTerminal: (ports: FulfillmentPorts, scope: EngineScope, ran: EnterRunResult, terminalStatus?: "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED") => Promise<EnterRunResult>;
4280
4292
  declare const runIsTerminal: (ran: EnterRunResult) => boolean;
4281
4293
  interface StepOutcome {
4282
- status: "WAITING" | "SCHEDULED_WAIT" | "SUCCESS" | "FAILED";
4294
+ status: "WAITING" | "SCHEDULED_WAIT" | "SUCCESS" | "FAILED" | "CANCELLED";
4283
4295
  scheduledWakeAt?: string;
4284
4296
  errorCode?: string;
4285
4297
  errorMessage?: string;
@@ -4366,4 +4378,28 @@ declare const hpkeSeal: (input: HpkeSealInput) => Promise<{
4366
4378
  /** Opens a sealed message; throws when anything was altered. */
4367
4379
  declare const hpkeOpen: (input: HpkeOpenInput) => Promise<Uint8Array<ArrayBuffer>>;
4368
4380
  //#endregion
4369
- export { type AdvanceAndEnterConfig, type AdvanceAndEnterResult, type ApplyRedeemInput, type AuthConfigureOptions, type BuildRouteHttpInput, type BuildScheduleSlotsConfig, CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CallbackMissingLocalUrlDetails, 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 ComputeProductRewardSavingsInput, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type DeviceSecretStorage, type DeviceSecretsConfigureOptions, type DeviceSecretsPayload, type DeviceSecretsStore, type DispatchWebhooksConfig, type EngineCallbackRun, type EngineCallbackRunError, type EngineExecutionContext, type EngineFlagReviewInput, type EngineFulfillmentPatch, type EngineOrder, type EngineOrderChangedEvent, type EngineOrderFulfillment, type EngineOrderStatus, type EngineOrderStatusPatch, type EngineScope, type EngineStepLog, type EngineStepLogEntry, type EngineStepsLogs, type EngineWebhookEnvelope, type EngineWebhookFailureEvent, type EngineWebhookNodeRun, type EngineWebhookTarget, type EnterAndPauseResult, type EnterRunResult, type ExchangeOptions, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, type FailedCharge, type FinalizePlaceOrderConfig, type FiresparkOrigin, type FlatMenuCategory, type FulfillmentEligibilityInput, type FulfillmentExecutionPort, type FulfillmentPorts, type FulfillmentRunStatus, type FulfillmentStepName, type FulfillmentStoragePort, type FulfillmentTerminalOrderStatus, 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 InvokeCallbackAttemptConfig, type InvokeCallbackAttemptResult, type ListMenusStreamOptions, type ListPaymentsOptions, type LocalDeviceCredentials, type LocalRouteProbeResult, type LocalServerConfig, type LocalServerHealthResult, LosslessNumber, type LosslessNumberLike, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, type MarkRouteDownInput, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, 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 OrderRouteKind, type OrderRouteStatus, OrderRouteUnavailableError, type OrderRoutes, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type OriginListener, type OriginState, type PauseForAdvanceConfig, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentEligibilityInput, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, type PendingWebhooks, PickupNameIssue, type PinnedFetchFactory, type PinnedFetchOptions, type PosOrderHttpOptions, type PricingModifier, type ProbeLocalRouteHealthOptions, type ProcessStateNodeCallbackJob, type ProcessStateNodeConfig, type ProcessStateNodeResult, type Product, type ProductCtx, type QuantitiesByPath, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ResolveRouteEligibilityInput, type ResolvedPaymentEligibility, type ResumeFromAdvanceConfig, type ReversalOutcome, type ReverseAllOptions, type RouteEligibility, type RouteEligibilityDetail, type RouteEligibilityFlags, type RouteEligibilityReason, type RouteFailureClassification, type RouteFailureKind, type RouteHealthEvent, type RouteHealthListener, type RouteHealthSnapshot, type RouteTenderCandidate, RulesEngine, type RunNodeCallbacksResult, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type ScheduledSuccessorConfig, type SdkPaymentEligibility, 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 StepOutcome, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerOptions, type SwitchCustomerResult, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, type TestLocalServerHealthOptions, TlsFingerprintMismatchError, TokenExchangeError, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, type WorkflowTimeoutDetails, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
4381
+ //#region src/invoicing/countries.d.ts
4382
+ declare const INVOICE_COUNTRIES: Record<InvoiceCountryCode, InvoiceCountryDescriptor>;
4383
+ declare const getInvoiceCountry: (code: string) => InvoiceCountryDescriptor | undefined;
4384
+ //#endregion
4385
+ //#region src/invoicing/taxBreakdown.d.ts
4386
+ interface TaxBreakdownLineInput {
4387
+ parent_uid?: string | null;
4388
+ tax_category?: TaxCategory | null;
4389
+ tax_rate?: number | string | null;
4390
+ group_subtotal: number | string;
4391
+ group_discount?: number | string | null;
4392
+ group_tax_total: number | string;
4393
+ }
4394
+ /**
4395
+ * Compute per-(tax_category, tax_rate) breakdown using Big.js with no rounding.
4396
+ * Only root lines (parent_uid == null) are aggregated to avoid double-counting.
4397
+ */
4398
+ declare const computeTaxBreakdown: (lines: TaxBreakdownLineInput[]) => TaxBreakdownItem[];
4399
+ //#endregion
4400
+ //#region src/invoicing/validateTaxId.d.ts
4401
+ declare const validateEcuadorCedula: (raw: string) => TaxIdValidationResult;
4402
+ declare const validateEcuadorRuc: (raw: string) => TaxIdValidationResult;
4403
+ declare const validateTaxId: (country: string, type: string, raw: string) => TaxIdValidationResult;
4404
+ //#endregion
4405
+ export { type AdvanceAndEnterConfig, type AdvanceAndEnterResult, type ApplyRedeemInput, type AuthConfigureOptions, type BuildRouteHttpInput, type BuildScheduleSlotsConfig, CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CallbackMissingLocalUrlDetails, 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 ComputeProductRewardSavingsInput, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type DeviceSecretStorage, type DeviceSecretsConfigureOptions, type DeviceSecretsPayload, type DeviceSecretsStore, type DispatchWebhooksConfig, type EngineCallbackRun, type EngineCallbackRunError, type EngineExecutionContext, type EngineFlagReviewInput, type EngineFulfillmentPatch, type EngineOrder, type EngineOrderChangedEvent, type EngineOrderFulfillment, type EngineOrderStatus, type EngineOrderStatusPatch, type EngineScope, type EngineStepLog, type EngineStepLogEntry, type EngineStepsLogs, type EngineWebhookEnvelope, type EngineWebhookFailureEvent, type EngineWebhookNodeRun, type EngineWebhookTarget, type EnterAndPauseResult, type EnterRunResult, type ExchangeOptions, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, type FailedCharge, type FinalizePlaceOrderConfig, type FiresparkOrigin, type FlatMenuCategory, type FulfillmentEligibilityInput, type FulfillmentExecutionPort, type FulfillmentPorts, type FulfillmentRunStatus, type FulfillmentStepName, type FulfillmentStoragePort, type FulfillmentTerminalOrderStatus, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, INVOICE_COUNTRIES, type IdBuilder, type IdHashFormat, type InvokeCallbackAttemptConfig, type InvokeCallbackAttemptResult, type ListMenusStreamOptions, type ListPaymentsOptions, type LocalDeviceCredentials, type LocalRouteProbeResult, type LocalServerConfig, type LocalServerHealthResult, LosslessNumber, type LosslessNumberLike, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, type MarkRouteDownInput, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, 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 OrderRouteKind, type OrderRouteStatus, OrderRouteUnavailableError, type OrderRoutes, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type OriginListener, type OriginState, type PauseForAdvanceConfig, type PauseForAdvanceResult, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentEligibilityInput, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, type PendingWebhooks, PickupNameIssue, type PinnedFetchFactory, type PinnedFetchOptions, type PosOrderHttpOptions, type PricingModifier, type ProbeLocalRouteHealthOptions, type ProcessStateNodeCallbackJob, type ProcessStateNodeConfig, type ProcessStateNodeResult, type Product, type ProductCtx, type QuantitiesByPath, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ResolveRouteEligibilityInput, type ResolvedPaymentEligibility, type ResumeFromAdvanceConfig, type ReversalOutcome, type ReverseAllOptions, type RouteEligibility, type RouteEligibilityDetail, type RouteEligibilityFlags, type RouteEligibilityReason, type RouteFailureClassification, type RouteFailureKind, type RouteHealthEvent, type RouteHealthListener, type RouteHealthSnapshot, type RouteTenderCandidate, RulesEngine, type RunNodeCallbacksResult, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type ScheduledSuccessorConfig, type SdkPaymentEligibility, 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 StepOutcome, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerOptions, type SwitchCustomerResult, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, type TaxBreakdownLineInput, type TestLocalServerHealthOptions, TlsFingerprintMismatchError, TokenExchangeError, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, type WorkflowTimeoutDetails, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, computeTaxBreakdown, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getInvoiceCountry, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, terminalRunStatusForEnter, terminalRunStatusForNode, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
package/dist/index.js CHANGED
@@ -6392,6 +6392,14 @@ const isRunningOffline = (condition, isOffline) => {
6392
6392
  assert(value != null, "Invalid value");
6393
6393
  return matchBooleanOperator(condition, isOffline ?? false);
6394
6394
  };
6395
+ const buyerIdentified = (condition, identified) => {
6396
+ const { type, primitive, value } = condition;
6397
+ const matcherType = "Buyer identified";
6398
+ assert(primitive === "boolean", primitiveError("boolean"));
6399
+ assert(type === matcherType, typeError(matcherType));
6400
+ assert(value != null, "Invalid value");
6401
+ return matchBooleanOperator(condition, identified ?? false);
6402
+ };
6395
6403
  //#endregion
6396
6404
  //#region src/rules/currencyMatcher.ts
6397
6405
  const matchCurrencyOperator = (condition, matcher) => {
@@ -7210,6 +7218,10 @@ var RulesEngine = class {
7210
7218
  const offline = this.execution?.is_offline;
7211
7219
  return isRunningOffline(condition, offline);
7212
7220
  }
7221
+ if (type === "Buyer identified") {
7222
+ const order = this.getDependency("order", type);
7223
+ return buyerIdentified(condition, order.buyer_identified);
7224
+ }
7213
7225
  throw new Error(`Condition ${type} not supported in boolean matcher`);
7214
7226
  };
7215
7227
  assertCurrency = (condition) => {
@@ -16289,6 +16301,194 @@ const processStateNode = async (ports, config) => {
16289
16301
  }
16290
16302
  };
16291
16303
  //#endregion
16304
+ //#region src/fulfillment/engine/finalize.ts
16305
+ const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
16306
+ const terminalRunStatusForNode = (node, order) => {
16307
+ if (isInterruptTerminalStatus(order?.status)) return "CANCELLED";
16308
+ const mapped = node?.data.mappedStatus?.trim().toUpperCase();
16309
+ if (isInterruptTerminalStatus(mapped)) return "CANCELLED";
16310
+ return "SUCCESS";
16311
+ };
16312
+ const terminalRunStatusForEnter = (ran) => {
16313
+ if (ran.failed) return "CANCELLED";
16314
+ const mapped = ran.next.mappedStatus?.trim().toUpperCase();
16315
+ if (isInterruptTerminalStatus(mapped)) return "CANCELLED";
16316
+ return "SUCCESS";
16317
+ };
16318
+ const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
16319
+ if (!order) return null;
16320
+ if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
16321
+ return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
16322
+ };
16323
+ const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
16324
+ const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
16325
+ if (!row) return;
16326
+ const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
16327
+ if (!sitting || sitting.data.kind !== "terminal") return;
16328
+ const order = await ports.storage.getOrder(row.order_id);
16329
+ const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
16330
+ const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
16331
+ const patch = {
16332
+ fulfillment_status: sitting.data.mappedStatus,
16333
+ ...fields
16334
+ };
16335
+ await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
16336
+ };
16337
+ const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
16338
+ const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
16339
+ const orderId = row?.order_id;
16340
+ const order = orderId ? await ports.storage.getOrder(orderId) : null;
16341
+ if (row && order) {
16342
+ await ports.execution.onOrderChanged?.({
16343
+ orderFulfillmentId,
16344
+ row,
16345
+ order,
16346
+ error
16347
+ });
16348
+ return;
16349
+ }
16350
+ await ports.execution.onOrderChanged?.({
16351
+ orderFulfillmentId,
16352
+ error
16353
+ });
16354
+ };
16355
+ const finalizePlaceOrder = async (ports, config) => {
16356
+ const { storage, execution: execPort } = ports;
16357
+ const { orderFulfillmentId, status, failureMessage } = config;
16358
+ const { errorCode, errorDetails } = config;
16359
+ const now = execPort.now;
16360
+ const row = await storage.getOrderFulfillment(orderFulfillmentId);
16361
+ const steps_logs = row?.steps_logs ?? [];
16362
+ const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
16363
+ let msg = "Fulfillment failed";
16364
+ if (status === "SUCCESS") msg = "Fulfillment completed";
16365
+ else if (status === "CANCELLED") msg = "Fulfillment cancelled";
16366
+ if (status === "FAILED") {
16367
+ const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
16368
+ const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
16369
+ if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
16370
+ beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
16371
+ completeEngineStepLog(steps_logs, "FINALIZE", "Fulfillment cancelled", now);
16372
+ const cancelled = {
16373
+ steps_logs,
16374
+ step: "FINALIZE",
16375
+ status: "CANCELLED"
16376
+ };
16377
+ await storage.updateOrderFulfillment(orderFulfillmentId, cancelled);
16378
+ await emitFinalizeChanged(ports, orderFulfillmentId);
16379
+ return { failed: false };
16380
+ }
16381
+ if (failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
16382
+ code: errorCode,
16383
+ details: errorDetails,
16384
+ now
16385
+ });
16386
+ beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
16387
+ if (isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
16388
+ type: "error",
16389
+ message: failureMessage,
16390
+ code: errorCode,
16391
+ details: errorDetails
16392
+ });
16393
+ completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
16394
+ if (isHardFailed && peekOrder) {
16395
+ const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
16396
+ await storage.updateOrderStatusAndSettle(peekOrder.id, {
16397
+ fulfillment_status: "FAILED",
16398
+ status: "FAILED",
16399
+ resolved_at: resolvedAt
16400
+ });
16401
+ const key = `${orderFulfillmentId}:${errorCode}`;
16402
+ const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
16403
+ await storage.flagOrderForReview?.({
16404
+ order: peekOrder,
16405
+ key,
16406
+ message: reviewMsg
16407
+ });
16408
+ } else if (peekOrder) {
16409
+ const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
16410
+ const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
16411
+ if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
16412
+ fulfillment_status: closed,
16413
+ status: closed
16414
+ });
16415
+ }
16416
+ } else {
16417
+ beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
16418
+ completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
16419
+ }
16420
+ const errorFields = status === "FAILED" ? {
16421
+ error_code: errorCode ?? null,
16422
+ error_message: failureMessage ?? "Fulfillment failed"
16423
+ } : {};
16424
+ await storage.updateOrderFulfillment(orderFulfillmentId, {
16425
+ steps_logs,
16426
+ step: "FINALIZE",
16427
+ status,
16428
+ ...errorFields
16429
+ });
16430
+ if (status === "CANCELLED") {
16431
+ await emitFinalizeChanged(ports, orderFulfillmentId);
16432
+ return { failed: false };
16433
+ }
16434
+ if (status === "SUCCESS") {
16435
+ await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
16436
+ await emitFinalizeChanged(ports, orderFulfillmentId);
16437
+ return { failed: false };
16438
+ }
16439
+ const raw = failureMessage ?? "Fulfillment failed";
16440
+ await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
16441
+ message: raw,
16442
+ code: errorCode
16443
+ } : { message: raw });
16444
+ if (row?.order_id) await execPort.onInjectionFailed?.({
16445
+ orderId: row.order_id,
16446
+ message: raw,
16447
+ code: errorCode
16448
+ });
16449
+ return { failed: true };
16450
+ };
16451
+ const warnNoEdge = async (ports, config) => {
16452
+ const { storage, execution: execPort } = ports;
16453
+ const { orderFulfillmentId, fulfillmentStatus } = config;
16454
+ const now = execPort.now;
16455
+ const row = await storage.getOrderFulfillment(orderFulfillmentId);
16456
+ if (!row || row.current_node_ids.length === 0) return;
16457
+ const orderPromise = storage.getOrder(row.order_id);
16458
+ const message = `No outgoing edge matches ${fulfillmentStatus}`;
16459
+ const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
16460
+ for (const id of row.current_node_ids) {
16461
+ const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
16462
+ if (node) appendNodeLog(node, "warning", message);
16463
+ }
16464
+ const steps_logs = row.steps_logs;
16465
+ beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
16466
+ appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
16467
+ type: "warning",
16468
+ message
16469
+ });
16470
+ completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
16471
+ const warning_count = (row.warning_count ?? 0) + 1;
16472
+ const patch = {
16473
+ workflow: row.workflow,
16474
+ steps_logs,
16475
+ warning_count,
16476
+ status: "WAITING"
16477
+ };
16478
+ await storage.updateOrderFulfillment(orderFulfillmentId, patch);
16479
+ const order = await orderPromise;
16480
+ if (!order) return;
16481
+ const patched = {
16482
+ ...row,
16483
+ ...patch
16484
+ };
16485
+ await execPort.onOrderChanged?.({
16486
+ orderFulfillmentId,
16487
+ row: patched,
16488
+ order
16489
+ });
16490
+ };
16491
+ //#endregion
16292
16492
  //#region src/fulfillment/engine/pauseForAdvance.ts
16293
16493
  const WAITING_STEP = "PAUSE_FOR_ADVANCE";
16294
16494
  const isWaitingPaymentNode = (row) => {
@@ -16299,18 +16499,56 @@ const isWaitingPaymentNode = (row) => {
16299
16499
  }
16300
16500
  return false;
16301
16501
  };
16502
+ const isTerminalRunStatus = (status) => {
16503
+ return status === "SUCCESS" || status === "FAILED" || status === "CANCELLED";
16504
+ };
16302
16505
  const pauseForAdvance = async (ports, config) => {
16303
16506
  const { storage, execution: execPort } = ports;
16304
16507
  const { orderFulfillmentId } = config;
16305
16508
  const now = execPort.now;
16306
16509
  const row = await storage.getOrderFulfillment(orderFulfillmentId);
16307
16510
  if (!row) throw new Error("Order fulfillment not found");
16308
- if (row.status === "PROCESSING" && row.step === WAITING_STEP) return;
16511
+ if (isTerminalRunStatus(row.status)) return {
16512
+ closed: true,
16513
+ status: row.status
16514
+ };
16515
+ const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
16516
+ if (sitting?.data.kind === "terminal") {
16517
+ const order = await storage.getOrder(row.order_id);
16518
+ const closedStatus = terminalRunStatusForNode(sitting, order);
16519
+ const msg = closedStatus === "CANCELLED" ? "Fulfillment cancelled" : "Fulfillment completed";
16520
+ const steps_logs = row.steps_logs;
16521
+ if (steps_logs.some((entry) => entry.step === WAITING_STEP && !entry.ended_at)) completeEngineStepLog(steps_logs, WAITING_STEP, msg, now);
16522
+ beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
16523
+ completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
16524
+ const patch = {
16525
+ steps_logs,
16526
+ step: "FINALIZE",
16527
+ status: closedStatus
16528
+ };
16529
+ await storage.updateOrderFulfillment(orderFulfillmentId, patch);
16530
+ if (order) {
16531
+ const patched = {
16532
+ ...row,
16533
+ ...patch
16534
+ };
16535
+ await execPort.onOrderChanged?.({
16536
+ orderFulfillmentId,
16537
+ row: patched,
16538
+ order
16539
+ });
16540
+ }
16541
+ return {
16542
+ closed: true,
16543
+ status: closedStatus
16544
+ };
16545
+ }
16546
+ if (row.status === "PROCESSING" && row.step === WAITING_STEP) return { closed: false };
16309
16547
  const already = row.status === "WAITING" && row.step === WAITING_STEP;
16310
16548
  const steps_logs = row.steps_logs;
16311
16549
  let order = null;
16312
16550
  if (!already) {
16313
- if (row.status !== "PROCESSING") return;
16551
+ if (row.status !== "PROCESSING") return { closed: false };
16314
16552
  beginEngineStepLog(steps_logs, WAITING_STEP, void 0, now);
16315
16553
  const at = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
16316
16554
  markNodesReady({
@@ -16323,7 +16561,7 @@ const pauseForAdvance = async (ports, config) => {
16323
16561
  workflow: row.workflow
16324
16562
  };
16325
16563
  const [paused, loaded] = await Promise.all([storage.casPauseOrderFulfillment(orderFulfillmentId, patch), storage.getOrder(row.order_id)]);
16326
- if (!paused) return;
16564
+ if (!paused) return { closed: false };
16327
16565
  order = loaded;
16328
16566
  }
16329
16567
  const u2 = {
@@ -16341,6 +16579,7 @@ const pauseForAdvance = async (ports, config) => {
16341
16579
  order
16342
16580
  });
16343
16581
  if (isWaitingPaymentNode(patched)) await execPort.onWaitingPayment?.(row.order_id);
16582
+ return { closed: false };
16344
16583
  };
16345
16584
  const resumeFromAdvance = async (ports, config) => {
16346
16585
  const { storage, execution: execPort } = ports;
@@ -16376,14 +16615,21 @@ const resumeFromAdvance = async (ports, config) => {
16376
16615
  requestedAt
16377
16616
  });
16378
16617
  }
16618
+ const alreadyTerminal = sittingWorkflowNode(row.workflow, row.current_node_ids)?.data.kind === "terminal";
16379
16619
  const patch = {
16380
16620
  steps_logs,
16381
16621
  status: "PROCESSING",
16382
16622
  workflow: row.workflow
16383
16623
  };
16384
16624
  await storage.updateOrderFulfillment(orderFulfillmentId, patch);
16385
- if (!order) return { edges: null };
16386
- if (config.emit === false) return { edges };
16625
+ if (!order) return {
16626
+ edges: null,
16627
+ alreadyTerminal
16628
+ };
16629
+ if (config.emit === false) return {
16630
+ edges,
16631
+ alreadyTerminal
16632
+ };
16387
16633
  const patched = {
16388
16634
  ...row,
16389
16635
  ...patch
@@ -16393,7 +16639,10 @@ const resumeFromAdvance = async (ports, config) => {
16393
16639
  row: patched,
16394
16640
  order
16395
16641
  });
16396
- return { edges };
16642
+ return {
16643
+ edges,
16644
+ alreadyTerminal
16645
+ };
16397
16646
  };
16398
16647
  //#endregion
16399
16648
  //#region src/fulfillment/engine/enterAndPause.ts
@@ -16419,7 +16668,7 @@ const enterAndPause = async (ports, config) => {
16419
16668
  };
16420
16669
  const advanceAndEnter = async (ports, config) => {
16421
16670
  const { fulfillmentStatus, requestedAt, terminalStatus, ...scope } = config;
16422
- const { edges } = await resumeFromAdvance(ports, {
16671
+ const { edges, alreadyTerminal } = await resumeFromAdvance(ports, {
16423
16672
  ...scope,
16424
16673
  fulfillmentStatus,
16425
16674
  requestedAt,
@@ -16427,7 +16676,10 @@ const advanceAndEnter = async (ports, config) => {
16427
16676
  });
16428
16677
  if (!edges) throw new Error("Fulfillment or order missing during advance");
16429
16678
  const target = pickAdvanceTarget(edges);
16430
- if (!target) return { noEdge: true };
16679
+ if (!target) return {
16680
+ noEdge: true,
16681
+ alreadyTerminal
16682
+ };
16431
16683
  const e1 = {
16432
16684
  ...scope,
16433
16685
  nodeId: target.targetId,
@@ -16608,6 +16860,16 @@ const defaultPublicOrder = (order) => {
16608
16860
  for (const key of INTERNAL_ORDER_KEYS$1) delete copy[key];
16609
16861
  return copy;
16610
16862
  };
16863
+ const replacedByOrderIdOf = (order) => {
16864
+ const meta = order.metadata;
16865
+ if (!meta || typeof meta !== "object") return null;
16866
+ const reopen = meta.reopen;
16867
+ if (!reopen || typeof reopen !== "object") return null;
16868
+ const raw = reopen.as_order_id;
16869
+ if (typeof raw !== "string") return null;
16870
+ const trimmed = raw.trim();
16871
+ return trimmed.length > 0 ? trimmed : null;
16872
+ };
16611
16873
  const webhookScope = (order) => {
16612
16874
  const b0 = order.merchant_id ? { merchant_id: order.merchant_id } : {};
16613
16875
  const b1 = {
@@ -16620,12 +16882,15 @@ const webhookScope = (order) => {
16620
16882
  };
16621
16883
  const b3 = { brand_id: order.brand_id ?? null };
16622
16884
  const b4 = { customer_id: order.customer_id };
16885
+ const replacedBy = replacedByOrderIdOf(order);
16886
+ const b5 = replacedBy ? { replaced_by_order_id: replacedBy } : {};
16623
16887
  return {
16624
16888
  ...b0,
16625
16889
  ...b1,
16626
16890
  ...b2,
16627
16891
  ...b3,
16628
- ...b4
16892
+ ...b4,
16893
+ ...b5
16629
16894
  };
16630
16895
  };
16631
16896
  /** Target URL for a webhook given cloud / local-online / offline mode. */
@@ -17489,171 +17754,6 @@ const resolveCallbackFailTerminal = async (ports, config) => {
17489
17754
  return null;
17490
17755
  };
17491
17756
  //#endregion
17492
- //#region src/fulfillment/engine/finalize.ts
17493
- const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
17494
- const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
17495
- if (!order) return null;
17496
- if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
17497
- return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
17498
- };
17499
- const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
17500
- const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
17501
- if (!row) return;
17502
- const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
17503
- if (!sitting || sitting.data.kind !== "terminal") return;
17504
- const order = await ports.storage.getOrder(row.order_id);
17505
- const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
17506
- const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
17507
- const patch = {
17508
- fulfillment_status: sitting.data.mappedStatus,
17509
- ...fields
17510
- };
17511
- await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
17512
- };
17513
- const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
17514
- const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
17515
- const orderId = row?.order_id;
17516
- const order = orderId ? await ports.storage.getOrder(orderId) : null;
17517
- if (row && order) {
17518
- await ports.execution.onOrderChanged?.({
17519
- orderFulfillmentId,
17520
- row,
17521
- order,
17522
- error
17523
- });
17524
- return;
17525
- }
17526
- await ports.execution.onOrderChanged?.({
17527
- orderFulfillmentId,
17528
- error
17529
- });
17530
- };
17531
- const finalizePlaceOrder = async (ports, config) => {
17532
- const { storage, execution: execPort } = ports;
17533
- const { orderFulfillmentId, status, failureMessage } = config;
17534
- const { errorCode, errorDetails } = config;
17535
- const now = execPort.now;
17536
- const row = await storage.getOrderFulfillment(orderFulfillmentId);
17537
- const steps_logs = row?.steps_logs ?? [];
17538
- const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
17539
- if (status === "FAILED" && failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
17540
- code: errorCode,
17541
- details: errorDetails,
17542
- now
17543
- });
17544
- beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
17545
- if (status === "FAILED" && isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
17546
- type: "error",
17547
- message: failureMessage,
17548
- code: errorCode,
17549
- details: errorDetails
17550
- });
17551
- completeEngineStepLog(steps_logs, "FINALIZE", status === "SUCCESS" ? "Fulfillment completed" : "Fulfillment failed", now);
17552
- if (status === "FAILED") {
17553
- const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
17554
- const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
17555
- if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
17556
- const ok = {
17557
- steps_logs,
17558
- step: "FINALIZE",
17559
- status: "SUCCESS"
17560
- };
17561
- await storage.updateOrderFulfillment(orderFulfillmentId, ok);
17562
- await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
17563
- await emitFinalizeChanged(ports, orderFulfillmentId);
17564
- return { failed: false };
17565
- }
17566
- if (isHardFailed && peekOrder) {
17567
- const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
17568
- await storage.updateOrderStatusAndSettle(peekOrder.id, {
17569
- fulfillment_status: "FAILED",
17570
- status: "FAILED",
17571
- resolved_at: resolvedAt
17572
- });
17573
- const key = `${orderFulfillmentId}:${errorCode}`;
17574
- const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
17575
- await storage.flagOrderForReview?.({
17576
- order: peekOrder,
17577
- key,
17578
- message: reviewMsg
17579
- });
17580
- } else if (peekOrder) {
17581
- const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
17582
- const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
17583
- if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
17584
- fulfillment_status: closed,
17585
- status: closed
17586
- });
17587
- }
17588
- }
17589
- const errorFields = status === "FAILED" ? {
17590
- error_code: errorCode ?? null,
17591
- error_message: failureMessage ?? "Fulfillment failed"
17592
- } : {};
17593
- await storage.updateOrderFulfillment(orderFulfillmentId, {
17594
- steps_logs,
17595
- step: "FINALIZE",
17596
- status,
17597
- ...errorFields
17598
- });
17599
- if (status !== "FAILED") {
17600
- await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
17601
- await emitFinalizeChanged(ports, orderFulfillmentId);
17602
- return { failed: false };
17603
- }
17604
- const raw = failureMessage ?? "Fulfillment failed";
17605
- await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
17606
- message: raw,
17607
- code: errorCode
17608
- } : { message: raw });
17609
- if (row?.order_id) await execPort.onInjectionFailed?.({
17610
- orderId: row.order_id,
17611
- message: raw,
17612
- code: errorCode
17613
- });
17614
- return { failed: true };
17615
- };
17616
- const warnNoEdge = async (ports, config) => {
17617
- const { storage, execution: execPort } = ports;
17618
- const { orderFulfillmentId, fulfillmentStatus } = config;
17619
- const now = execPort.now;
17620
- const row = await storage.getOrderFulfillment(orderFulfillmentId);
17621
- if (!row || row.current_node_ids.length === 0) return;
17622
- const orderPromise = storage.getOrder(row.order_id);
17623
- const message = `No outgoing edge matches ${fulfillmentStatus}`;
17624
- const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
17625
- for (const id of row.current_node_ids) {
17626
- const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
17627
- if (node) appendNodeLog(node, "warning", message);
17628
- }
17629
- const steps_logs = row.steps_logs;
17630
- beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
17631
- appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
17632
- type: "warning",
17633
- message
17634
- });
17635
- completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
17636
- const warning_count = (row.warning_count ?? 0) + 1;
17637
- const patch = {
17638
- workflow: row.workflow,
17639
- steps_logs,
17640
- warning_count,
17641
- status: "WAITING"
17642
- };
17643
- await storage.updateOrderFulfillment(orderFulfillmentId, patch);
17644
- const order = await orderPromise;
17645
- if (!order) return;
17646
- const patched = {
17647
- ...row,
17648
- ...patch
17649
- };
17650
- await execPort.onOrderChanged?.({
17651
- orderFulfillmentId,
17652
- row: patched,
17653
- order
17654
- });
17655
- };
17656
- //#endregion
17657
17757
  //#region src/fulfillment/engine/runner.ts
17658
17758
  const pendingWebhooksOf = (next) => {
17659
17759
  if (!next.entered || next.alreadyTerminal) return null;
@@ -17782,15 +17882,17 @@ const finalizeOrPause = async (ports, scope, settled) => {
17782
17882
  };
17783
17883
  }
17784
17884
  if (runIsTerminal(settled)) {
17885
+ const terminalStatus = terminalRunStatusForEnter(settled);
17785
17886
  await finalizePlaceOrder(ports, {
17786
17887
  orderFulfillmentId: scope.orderFulfillmentId,
17787
- status: "SUCCESS"
17888
+ status: terminalStatus
17788
17889
  });
17789
17890
  await dispatchPendingWebhooks(ports, scope, settled.pending);
17790
- return { status: "SUCCESS" };
17891
+ return { status: terminalStatus };
17791
17892
  }
17792
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17893
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17793
17894
  await dispatchPendingWebhooks(ports, scope, settled.pending);
17895
+ if (paused.closed) return { status: paused.status };
17794
17896
  return { status: "WAITING" };
17795
17897
  };
17796
17898
  const handlePausedNode = async (ports, scope, ran, terminalStatus) => {
@@ -17828,11 +17930,17 @@ const executeAdvance = async (ports, scope, event) => {
17828
17930
  terminalStatus: event.status
17829
17931
  });
17830
17932
  if (advanced.noEdge) {
17933
+ if (advanced.alreadyTerminal) {
17934
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17935
+ if (paused.closed) return { status: paused.status };
17936
+ return { status: "WAITING" };
17937
+ }
17831
17938
  await warnNoEdge(ports, {
17832
17939
  orderFulfillmentId: scope.orderFulfillmentId,
17833
17940
  fulfillmentStatus: event.fulfillment_status
17834
17941
  });
17835
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17942
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17943
+ if (paused.closed) return { status: paused.status };
17836
17944
  return { status: "WAITING" };
17837
17945
  }
17838
17946
  if (advanced.paused) return handlePausedNode(ports, scope, advanced.ran, event.status);
@@ -17852,7 +17960,8 @@ const executeScheduledWake = async (ports, scope, nodeId, terminalStatus) => {
17852
17960
  orderFulfillmentId: scope.orderFulfillmentId,
17853
17961
  fulfillmentStatus: SCHEDULED_STATUS
17854
17962
  });
17855
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17963
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17964
+ if (paused.closed) return { status: paused.status };
17856
17965
  return { status: "WAITING" };
17857
17966
  }
17858
17967
  return executeAdvance(ports, scope, {
@@ -18122,4 +18231,262 @@ const hpkeOpen = async (input) => {
18122
18231
  return new Uint8Array(opened);
18123
18232
  };
18124
18233
  //#endregion
18125
- export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, 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, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
18234
+ //#region src/invoicing/countries.ts
18235
+ const INVOICE_COUNTRIES = { EC: {
18236
+ code: "EC",
18237
+ name: "Ecuador",
18238
+ authority: "SRI",
18239
+ currency: "USD",
18240
+ tax_id_types: [
18241
+ { code: "FINAL_CONSUMER" },
18242
+ {
18243
+ code: "CEDULA",
18244
+ min_length: 10,
18245
+ max_length: 10,
18246
+ numeric_only: true
18247
+ },
18248
+ {
18249
+ code: "RUC",
18250
+ min_length: 13,
18251
+ max_length: 13,
18252
+ numeric_only: true
18253
+ },
18254
+ {
18255
+ code: "PASSPORT",
18256
+ min_length: 3,
18257
+ max_length: 20,
18258
+ numeric_only: false
18259
+ }
18260
+ ],
18261
+ final_consumer_id: "9999999999999",
18262
+ final_consumer_name: "CONSUMIDOR FINAL",
18263
+ default_buyer_threshold: "50.00",
18264
+ supported_regimes: [
18265
+ "GENERAL",
18266
+ "RIMPE_EMPRENDEDOR",
18267
+ "RIMPE_NEGOCIO_POPULAR"
18268
+ ]
18269
+ } };
18270
+ const getInvoiceCountry = (code) => {
18271
+ const key = code.toUpperCase();
18272
+ return INVOICE_COUNTRIES[key];
18273
+ };
18274
+ //#endregion
18275
+ //#region src/invoicing/taxBreakdown.ts
18276
+ const inferTaxCategory = (line) => {
18277
+ if (line.tax_category) return line.tax_category;
18278
+ return new Big(line.tax_rate ?? 0).gt(0) ? "STANDARD" : "ZERO";
18279
+ };
18280
+ /**
18281
+ * Compute per-(tax_category, tax_rate) breakdown using Big.js with no rounding.
18282
+ * Only root lines (parent_uid == null) are aggregated to avoid double-counting.
18283
+ */
18284
+ const computeTaxBreakdown = (lines) => {
18285
+ const buckets = /* @__PURE__ */ new Map();
18286
+ for (const line of lines) {
18287
+ if (line.parent_uid != null) continue;
18288
+ const category = inferTaxCategory(line);
18289
+ const rate = new Big(line.tax_rate ?? 0);
18290
+ const key = `${category}:${rate.toFixed()}`;
18291
+ const subtotal = new Big(line.group_subtotal);
18292
+ const discount = new Big(line.group_discount ?? 0);
18293
+ const base = subtotal.minus(discount);
18294
+ const tax = new Big(line.group_tax_total);
18295
+ const existing = buckets.get(key);
18296
+ if (existing) {
18297
+ existing.taxable_base = existing.taxable_base.plus(base);
18298
+ existing.tax_amount = existing.tax_amount.plus(tax);
18299
+ } else buckets.set(key, {
18300
+ tax_category: category,
18301
+ tax_rate: rate,
18302
+ taxable_base: base,
18303
+ tax_amount: tax
18304
+ });
18305
+ }
18306
+ return Array.from(buckets.values()).map((bucket) => {
18307
+ return {
18308
+ tax_category: bucket.tax_category,
18309
+ tax_rate: bucket.tax_rate.toFixed(),
18310
+ taxable_base: bucket.taxable_base.toFixed(),
18311
+ tax_amount: bucket.tax_amount.toFixed()
18312
+ };
18313
+ });
18314
+ };
18315
+ //#endregion
18316
+ //#region src/invoicing/validateTaxId.ts
18317
+ const DIGITS_ONLY = /^\d+$/;
18318
+ const PASSPORT_REGEX = /^[A-Za-z0-9-]{3,20}$/;
18319
+ const FINAL_CONSUMER_EC = "9999999999999";
18320
+ const CEDULA_COEFFS = [
18321
+ 2,
18322
+ 1,
18323
+ 2,
18324
+ 1,
18325
+ 2,
18326
+ 1,
18327
+ 2,
18328
+ 1,
18329
+ 2
18330
+ ];
18331
+ const PUBLIC_RUC_COEFFS = [
18332
+ 3,
18333
+ 2,
18334
+ 7,
18335
+ 6,
18336
+ 5,
18337
+ 4,
18338
+ 3,
18339
+ 2
18340
+ ];
18341
+ const PRIVATE_RUC_COEFFS = [
18342
+ 4,
18343
+ 3,
18344
+ 2,
18345
+ 7,
18346
+ 6,
18347
+ 5,
18348
+ 4,
18349
+ 3,
18350
+ 2
18351
+ ];
18352
+ const isValidEcuadorProvince = (code) => {
18353
+ return code >= 1 && code <= 24 || code === 30;
18354
+ };
18355
+ const checkMod10 = (digits) => {
18356
+ let sum = 0;
18357
+ for (let i = 0; i < 9; i++) {
18358
+ let prod = Number(digits[i]) * (CEDULA_COEFFS[i] ?? 0);
18359
+ if (prod >= 10) prod -= 9;
18360
+ sum += prod;
18361
+ }
18362
+ const expected = (10 - sum % 10) % 10;
18363
+ return Number(digits[9]) === expected;
18364
+ };
18365
+ const checkMod11 = (digits, coeffs, checkIndex) => {
18366
+ let sum = 0;
18367
+ for (let i = 0; i < coeffs.length; i++) sum += Number(digits[i]) * (coeffs[i] ?? 0);
18368
+ const rem = sum % 11;
18369
+ const expected = rem === 0 ? 0 : 11 - rem;
18370
+ if (expected === 10) return false;
18371
+ return Number(digits[checkIndex]) === expected;
18372
+ };
18373
+ const validateEcuadorCedula = (raw) => {
18374
+ const value = raw.trim();
18375
+ if (!value) return {
18376
+ valid: false,
18377
+ reason: "EMPTY"
18378
+ };
18379
+ if (!DIGITS_ONLY.test(value)) return {
18380
+ valid: false,
18381
+ reason: "NON_NUMERIC"
18382
+ };
18383
+ if (value.length !== 10) return {
18384
+ valid: false,
18385
+ reason: "INVALID_LENGTH"
18386
+ };
18387
+ const province = Number(value.slice(0, 2));
18388
+ if (!isValidEcuadorProvince(province)) return {
18389
+ valid: false,
18390
+ reason: "INVALID_PROVINCE"
18391
+ };
18392
+ if (Number(value[2]) > 5) return {
18393
+ valid: false,
18394
+ reason: "INVALID_THIRD_DIGIT"
18395
+ };
18396
+ if (!checkMod10(value)) return {
18397
+ valid: false,
18398
+ reason: "INVALID_CHECK_DIGIT"
18399
+ };
18400
+ return { valid: true };
18401
+ };
18402
+ const validateEcuadorRuc = (raw) => {
18403
+ const value = raw.trim();
18404
+ if (!value) return {
18405
+ valid: false,
18406
+ reason: "EMPTY"
18407
+ };
18408
+ if (!DIGITS_ONLY.test(value)) return {
18409
+ valid: false,
18410
+ reason: "NON_NUMERIC"
18411
+ };
18412
+ if (value.length !== 13) return {
18413
+ valid: false,
18414
+ reason: "INVALID_LENGTH"
18415
+ };
18416
+ const province = Number(value.slice(0, 2));
18417
+ if (!isValidEcuadorProvince(province)) return {
18418
+ valid: false,
18419
+ reason: "INVALID_PROVINCE"
18420
+ };
18421
+ const third = Number(value[2]);
18422
+ if (third <= 5) {
18423
+ if (value.slice(10) === "000") return {
18424
+ valid: false,
18425
+ reason: "INVALID_ESTABLISHMENT"
18426
+ };
18427
+ if (!checkMod10(value.slice(0, 10))) return {
18428
+ valid: false,
18429
+ reason: "INVALID_CHECK_DIGIT"
18430
+ };
18431
+ return { valid: true };
18432
+ }
18433
+ if (third === 6) {
18434
+ if (value.slice(9) === "0000") return {
18435
+ valid: false,
18436
+ reason: "INVALID_ESTABLISHMENT"
18437
+ };
18438
+ if (!checkMod11(value, PUBLIC_RUC_COEFFS, 8)) return {
18439
+ valid: false,
18440
+ reason: "INVALID_CHECK_DIGIT"
18441
+ };
18442
+ return { valid: true };
18443
+ }
18444
+ if (third === 9) {
18445
+ if (value.slice(10) === "000") return {
18446
+ valid: false,
18447
+ reason: "INVALID_ESTABLISHMENT"
18448
+ };
18449
+ if (!checkMod11(value, PRIVATE_RUC_COEFFS, 9)) return {
18450
+ valid: false,
18451
+ reason: "INVALID_CHECK_DIGIT"
18452
+ };
18453
+ return { valid: true };
18454
+ }
18455
+ return {
18456
+ valid: false,
18457
+ reason: "INVALID_THIRD_DIGIT"
18458
+ };
18459
+ };
18460
+ const validateTaxId = (country, type, raw) => {
18461
+ const upperCountry = country.toUpperCase();
18462
+ const upperType = type.toUpperCase();
18463
+ const value = raw.trim();
18464
+ if (upperType === "FINAL_CONSUMER") {
18465
+ if (upperCountry === "EC") return value === FINAL_CONSUMER_EC ? { valid: true } : {
18466
+ valid: false,
18467
+ reason: "INVALID_FORMAT"
18468
+ };
18469
+ return value.length > 0 ? { valid: true } : {
18470
+ valid: false,
18471
+ reason: "EMPTY"
18472
+ };
18473
+ }
18474
+ if (!value) return {
18475
+ valid: false,
18476
+ reason: "EMPTY"
18477
+ };
18478
+ if (upperType === "PASSPORT") return PASSPORT_REGEX.test(value) ? { valid: true } : {
18479
+ valid: false,
18480
+ reason: "INVALID_FORMAT"
18481
+ };
18482
+ if (upperCountry === "EC") {
18483
+ if (upperType === "CEDULA") return validateEcuadorCedula(value);
18484
+ if (upperType === "RUC") return validateEcuadorRuc(value);
18485
+ }
18486
+ return {
18487
+ valid: false,
18488
+ reason: "INVALID_FORMAT"
18489
+ };
18490
+ };
18491
+ //#endregion
18492
+ export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, INVOICE_COUNTRIES, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, 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, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, computeTaxBreakdown, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getInvoiceCountry, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, terminalRunStatusForEnter, terminalRunStatusForNode, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fire-spark/core",
3
- "version": "0.52.0",
3
+ "version": "0.54.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.52.0",
24
- "@fire-spark/types": "^0.52.0"
23
+ "@fire-spark/payments": "^0.54.0",
24
+ "@fire-spark/types": "^0.54.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "tsdown": "^0.22.14",