@fire-spark/core 0.53.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.
package/dist/index.d.ts CHANGED
@@ -3824,7 +3824,7 @@ declare const DEFAULT_MAX_INCOMPLETE_MINUTES = 240;
3824
3824
  declare const MIN_MAX_INCOMPLETE_MINUTES = 1;
3825
3825
  declare const MAX_MAX_INCOMPLETE_MINUTES = 43200;
3826
3826
  type FulfillmentStepName = "ACCEPTING" | "PROCESS_STATE_NODE" | "PAUSE_FOR_ADVANCE" | "WARN_NO_EDGE" | "FINALIZE" | "ROLLBACK_PROCESS_STATE_NODE" | "ROLLBACK_ACCEPT";
3827
- type FulfillmentRunStatus = "PROCESSING" | "WAITING" | "SUCCESS" | "FAILED";
3827
+ type FulfillmentRunStatus = "PROCESSING" | "WAITING" | "SUCCESS" | "FAILED" | "CANCELLED";
3828
3828
  type FulfillmentTerminalOrderStatus = "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED" | "FAILED";
3829
3829
  type EngineOrderStatus = "OPEN" | "CLOSED" | "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED" | "CANCELLED" | "FAILED";
3830
3830
  interface EngineExecutionContext {
@@ -4068,6 +4068,7 @@ interface AdvanceAndEnterConfig extends EngineScope {
4068
4068
  }
4069
4069
  type AdvanceAndEnterResult = {
4070
4070
  noEdge: true;
4071
+ alreadyTerminal?: boolean;
4071
4072
  } | {
4072
4073
  noEdge: false;
4073
4074
  ran: ProcessStateNodeResult;
@@ -4093,7 +4094,7 @@ interface DispatchWebhooksConfig extends EngineScope {
4093
4094
  }
4094
4095
  interface FinalizePlaceOrderConfig {
4095
4096
  orderFulfillmentId: string;
4096
- status: "SUCCESS" | "FAILED";
4097
+ status: "SUCCESS" | "FAILED" | "CANCELLED";
4097
4098
  failureMessage?: string;
4098
4099
  errorCode?: string;
4099
4100
  errorDetails?: Record<string, unknown>;
@@ -4170,17 +4171,25 @@ declare const processStateNode: (ports: FulfillmentPorts, config: ProcessStateNo
4170
4171
  interface PauseForAdvanceConfig {
4171
4172
  orderFulfillmentId: string;
4172
4173
  }
4174
+ type PauseForAdvanceResult = {
4175
+ closed: true;
4176
+ status: "SUCCESS" | "FAILED" | "CANCELLED";
4177
+ } | {
4178
+ closed: false;
4179
+ };
4173
4180
  interface ResumeFromAdvanceConfig extends PauseForAdvanceConfig {
4174
4181
  orderId: string;
4175
4182
  fulfillmentStatus?: string;
4176
4183
  requestedAt?: string;
4177
4184
  emit?: boolean;
4178
4185
  }
4179
- declare const pauseForAdvance: (ports: FulfillmentPorts, config: PauseForAdvanceConfig) => Promise<void>;
4186
+ declare const pauseForAdvance: (ports: FulfillmentPorts, config: PauseForAdvanceConfig) => Promise<PauseForAdvanceResult>;
4180
4187
  declare const resumeFromAdvance: (ports: FulfillmentPorts, config: ResumeFromAdvanceConfig) => Promise<{
4181
4188
  edges: null;
4189
+ alreadyTerminal: boolean;
4182
4190
  } | {
4183
4191
  edges: import("@fire-spark/types").OrderFulfillmentWorkflowEdge[];
4192
+ alreadyTerminal: boolean;
4184
4193
  }>;
4185
4194
  //#endregion
4186
4195
  //#region src/fulfillment/engine/enterAndPause.d.ts
@@ -4263,6 +4272,8 @@ declare const resolveWebhookTargetUrl: (webhook: Pick<EngineWebhookTarget, "url"
4263
4272
  declare const dispatchOrderWebhooks: (ports: FulfillmentPorts, config: DispatchWebhooksConfig) => Promise<EngineWebhookNodeRun[]>;
4264
4273
  //#endregion
4265
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";
4266
4277
  declare const engineOrderStatusForFailedRun: (order: EngineOrder | null, isPaymentCaptured?: typeof defaultIsPaymentCaptured) => "REVERSED" | "VOIDED" | null;
4267
4278
  declare const finalizePlaceOrder: (ports: FulfillmentPorts, config: FinalizePlaceOrderConfig) => Promise<{
4268
4279
  failed: boolean;
@@ -4280,7 +4291,7 @@ declare const settleEnter: (ports: FulfillmentPorts, scope: EngineScope, next: P
4280
4291
  declare const autoEnterSuccessTerminal: (ports: FulfillmentPorts, scope: EngineScope, ran: EnterRunResult, terminalStatus?: "COMPLETED" | "VOIDED" | "REVERSED" | "REFUNDED") => Promise<EnterRunResult>;
4281
4292
  declare const runIsTerminal: (ran: EnterRunResult) => boolean;
4282
4293
  interface StepOutcome {
4283
- status: "WAITING" | "SCHEDULED_WAIT" | "SUCCESS" | "FAILED";
4294
+ status: "WAITING" | "SCHEDULED_WAIT" | "SUCCESS" | "FAILED" | "CANCELLED";
4284
4295
  scheduledWakeAt?: string;
4285
4296
  errorCode?: string;
4286
4297
  errorMessage?: string;
@@ -4391,4 +4402,4 @@ declare const validateEcuadorCedula: (raw: string) => TaxIdValidationResult;
4391
4402
  declare const validateEcuadorRuc: (raw: string) => TaxIdValidationResult;
4392
4403
  declare const validateTaxId: (country: string, type: string, raw: string) => TaxIdValidationResult;
4393
4404
  //#endregion
4394
- 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 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, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
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
@@ -16301,6 +16301,194 @@ const processStateNode = async (ports, config) => {
16301
16301
  }
16302
16302
  };
16303
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
16304
16492
  //#region src/fulfillment/engine/pauseForAdvance.ts
16305
16493
  const WAITING_STEP = "PAUSE_FOR_ADVANCE";
16306
16494
  const isWaitingPaymentNode = (row) => {
@@ -16311,18 +16499,56 @@ const isWaitingPaymentNode = (row) => {
16311
16499
  }
16312
16500
  return false;
16313
16501
  };
16502
+ const isTerminalRunStatus = (status) => {
16503
+ return status === "SUCCESS" || status === "FAILED" || status === "CANCELLED";
16504
+ };
16314
16505
  const pauseForAdvance = async (ports, config) => {
16315
16506
  const { storage, execution: execPort } = ports;
16316
16507
  const { orderFulfillmentId } = config;
16317
16508
  const now = execPort.now;
16318
16509
  const row = await storage.getOrderFulfillment(orderFulfillmentId);
16319
16510
  if (!row) throw new Error("Order fulfillment not found");
16320
- 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 };
16321
16547
  const already = row.status === "WAITING" && row.step === WAITING_STEP;
16322
16548
  const steps_logs = row.steps_logs;
16323
16549
  let order = null;
16324
16550
  if (!already) {
16325
- if (row.status !== "PROCESSING") return;
16551
+ if (row.status !== "PROCESSING") return { closed: false };
16326
16552
  beginEngineStepLog(steps_logs, WAITING_STEP, void 0, now);
16327
16553
  const at = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
16328
16554
  markNodesReady({
@@ -16335,7 +16561,7 @@ const pauseForAdvance = async (ports, config) => {
16335
16561
  workflow: row.workflow
16336
16562
  };
16337
16563
  const [paused, loaded] = await Promise.all([storage.casPauseOrderFulfillment(orderFulfillmentId, patch), storage.getOrder(row.order_id)]);
16338
- if (!paused) return;
16564
+ if (!paused) return { closed: false };
16339
16565
  order = loaded;
16340
16566
  }
16341
16567
  const u2 = {
@@ -16353,6 +16579,7 @@ const pauseForAdvance = async (ports, config) => {
16353
16579
  order
16354
16580
  });
16355
16581
  if (isWaitingPaymentNode(patched)) await execPort.onWaitingPayment?.(row.order_id);
16582
+ return { closed: false };
16356
16583
  };
16357
16584
  const resumeFromAdvance = async (ports, config) => {
16358
16585
  const { storage, execution: execPort } = ports;
@@ -16388,14 +16615,21 @@ const resumeFromAdvance = async (ports, config) => {
16388
16615
  requestedAt
16389
16616
  });
16390
16617
  }
16618
+ const alreadyTerminal = sittingWorkflowNode(row.workflow, row.current_node_ids)?.data.kind === "terminal";
16391
16619
  const patch = {
16392
16620
  steps_logs,
16393
16621
  status: "PROCESSING",
16394
16622
  workflow: row.workflow
16395
16623
  };
16396
16624
  await storage.updateOrderFulfillment(orderFulfillmentId, patch);
16397
- if (!order) return { edges: null };
16398
- 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
+ };
16399
16633
  const patched = {
16400
16634
  ...row,
16401
16635
  ...patch
@@ -16405,7 +16639,10 @@ const resumeFromAdvance = async (ports, config) => {
16405
16639
  row: patched,
16406
16640
  order
16407
16641
  });
16408
- return { edges };
16642
+ return {
16643
+ edges,
16644
+ alreadyTerminal
16645
+ };
16409
16646
  };
16410
16647
  //#endregion
16411
16648
  //#region src/fulfillment/engine/enterAndPause.ts
@@ -16431,7 +16668,7 @@ const enterAndPause = async (ports, config) => {
16431
16668
  };
16432
16669
  const advanceAndEnter = async (ports, config) => {
16433
16670
  const { fulfillmentStatus, requestedAt, terminalStatus, ...scope } = config;
16434
- const { edges } = await resumeFromAdvance(ports, {
16671
+ const { edges, alreadyTerminal } = await resumeFromAdvance(ports, {
16435
16672
  ...scope,
16436
16673
  fulfillmentStatus,
16437
16674
  requestedAt,
@@ -16439,7 +16676,10 @@ const advanceAndEnter = async (ports, config) => {
16439
16676
  });
16440
16677
  if (!edges) throw new Error("Fulfillment or order missing during advance");
16441
16678
  const target = pickAdvanceTarget(edges);
16442
- if (!target) return { noEdge: true };
16679
+ if (!target) return {
16680
+ noEdge: true,
16681
+ alreadyTerminal
16682
+ };
16443
16683
  const e1 = {
16444
16684
  ...scope,
16445
16685
  nodeId: target.targetId,
@@ -16620,6 +16860,16 @@ const defaultPublicOrder = (order) => {
16620
16860
  for (const key of INTERNAL_ORDER_KEYS$1) delete copy[key];
16621
16861
  return copy;
16622
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
+ };
16623
16873
  const webhookScope = (order) => {
16624
16874
  const b0 = order.merchant_id ? { merchant_id: order.merchant_id } : {};
16625
16875
  const b1 = {
@@ -16632,12 +16882,15 @@ const webhookScope = (order) => {
16632
16882
  };
16633
16883
  const b3 = { brand_id: order.brand_id ?? null };
16634
16884
  const b4 = { customer_id: order.customer_id };
16885
+ const replacedBy = replacedByOrderIdOf(order);
16886
+ const b5 = replacedBy ? { replaced_by_order_id: replacedBy } : {};
16635
16887
  return {
16636
16888
  ...b0,
16637
16889
  ...b1,
16638
16890
  ...b2,
16639
16891
  ...b3,
16640
- ...b4
16892
+ ...b4,
16893
+ ...b5
16641
16894
  };
16642
16895
  };
16643
16896
  /** Target URL for a webhook given cloud / local-online / offline mode. */
@@ -17501,171 +17754,6 @@ const resolveCallbackFailTerminal = async (ports, config) => {
17501
17754
  return null;
17502
17755
  };
17503
17756
  //#endregion
17504
- //#region src/fulfillment/engine/finalize.ts
17505
- const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
17506
- const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
17507
- if (!order) return null;
17508
- if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
17509
- return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
17510
- };
17511
- const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
17512
- const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
17513
- if (!row) return;
17514
- const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
17515
- if (!sitting || sitting.data.kind !== "terminal") return;
17516
- const order = await ports.storage.getOrder(row.order_id);
17517
- const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
17518
- const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
17519
- const patch = {
17520
- fulfillment_status: sitting.data.mappedStatus,
17521
- ...fields
17522
- };
17523
- await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
17524
- };
17525
- const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
17526
- const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
17527
- const orderId = row?.order_id;
17528
- const order = orderId ? await ports.storage.getOrder(orderId) : null;
17529
- if (row && order) {
17530
- await ports.execution.onOrderChanged?.({
17531
- orderFulfillmentId,
17532
- row,
17533
- order,
17534
- error
17535
- });
17536
- return;
17537
- }
17538
- await ports.execution.onOrderChanged?.({
17539
- orderFulfillmentId,
17540
- error
17541
- });
17542
- };
17543
- const finalizePlaceOrder = async (ports, config) => {
17544
- const { storage, execution: execPort } = ports;
17545
- const { orderFulfillmentId, status, failureMessage } = config;
17546
- const { errorCode, errorDetails } = config;
17547
- const now = execPort.now;
17548
- const row = await storage.getOrderFulfillment(orderFulfillmentId);
17549
- const steps_logs = row?.steps_logs ?? [];
17550
- const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
17551
- if (status === "FAILED" && failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
17552
- code: errorCode,
17553
- details: errorDetails,
17554
- now
17555
- });
17556
- beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
17557
- if (status === "FAILED" && isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
17558
- type: "error",
17559
- message: failureMessage,
17560
- code: errorCode,
17561
- details: errorDetails
17562
- });
17563
- completeEngineStepLog(steps_logs, "FINALIZE", status === "SUCCESS" ? "Fulfillment completed" : "Fulfillment failed", now);
17564
- if (status === "FAILED") {
17565
- const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
17566
- const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
17567
- if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
17568
- const ok = {
17569
- steps_logs,
17570
- step: "FINALIZE",
17571
- status: "SUCCESS"
17572
- };
17573
- await storage.updateOrderFulfillment(orderFulfillmentId, ok);
17574
- await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
17575
- await emitFinalizeChanged(ports, orderFulfillmentId);
17576
- return { failed: false };
17577
- }
17578
- if (isHardFailed && peekOrder) {
17579
- const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
17580
- await storage.updateOrderStatusAndSettle(peekOrder.id, {
17581
- fulfillment_status: "FAILED",
17582
- status: "FAILED",
17583
- resolved_at: resolvedAt
17584
- });
17585
- const key = `${orderFulfillmentId}:${errorCode}`;
17586
- const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
17587
- await storage.flagOrderForReview?.({
17588
- order: peekOrder,
17589
- key,
17590
- message: reviewMsg
17591
- });
17592
- } else if (peekOrder) {
17593
- const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
17594
- const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
17595
- if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
17596
- fulfillment_status: closed,
17597
- status: closed
17598
- });
17599
- }
17600
- }
17601
- const errorFields = status === "FAILED" ? {
17602
- error_code: errorCode ?? null,
17603
- error_message: failureMessage ?? "Fulfillment failed"
17604
- } : {};
17605
- await storage.updateOrderFulfillment(orderFulfillmentId, {
17606
- steps_logs,
17607
- step: "FINALIZE",
17608
- status,
17609
- ...errorFields
17610
- });
17611
- if (status !== "FAILED") {
17612
- await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
17613
- await emitFinalizeChanged(ports, orderFulfillmentId);
17614
- return { failed: false };
17615
- }
17616
- const raw = failureMessage ?? "Fulfillment failed";
17617
- await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
17618
- message: raw,
17619
- code: errorCode
17620
- } : { message: raw });
17621
- if (row?.order_id) await execPort.onInjectionFailed?.({
17622
- orderId: row.order_id,
17623
- message: raw,
17624
- code: errorCode
17625
- });
17626
- return { failed: true };
17627
- };
17628
- const warnNoEdge = async (ports, config) => {
17629
- const { storage, execution: execPort } = ports;
17630
- const { orderFulfillmentId, fulfillmentStatus } = config;
17631
- const now = execPort.now;
17632
- const row = await storage.getOrderFulfillment(orderFulfillmentId);
17633
- if (!row || row.current_node_ids.length === 0) return;
17634
- const orderPromise = storage.getOrder(row.order_id);
17635
- const message = `No outgoing edge matches ${fulfillmentStatus}`;
17636
- const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
17637
- for (const id of row.current_node_ids) {
17638
- const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
17639
- if (node) appendNodeLog(node, "warning", message);
17640
- }
17641
- const steps_logs = row.steps_logs;
17642
- beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
17643
- appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
17644
- type: "warning",
17645
- message
17646
- });
17647
- completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
17648
- const warning_count = (row.warning_count ?? 0) + 1;
17649
- const patch = {
17650
- workflow: row.workflow,
17651
- steps_logs,
17652
- warning_count,
17653
- status: "WAITING"
17654
- };
17655
- await storage.updateOrderFulfillment(orderFulfillmentId, patch);
17656
- const order = await orderPromise;
17657
- if (!order) return;
17658
- const patched = {
17659
- ...row,
17660
- ...patch
17661
- };
17662
- await execPort.onOrderChanged?.({
17663
- orderFulfillmentId,
17664
- row: patched,
17665
- order
17666
- });
17667
- };
17668
- //#endregion
17669
17757
  //#region src/fulfillment/engine/runner.ts
17670
17758
  const pendingWebhooksOf = (next) => {
17671
17759
  if (!next.entered || next.alreadyTerminal) return null;
@@ -17794,15 +17882,17 @@ const finalizeOrPause = async (ports, scope, settled) => {
17794
17882
  };
17795
17883
  }
17796
17884
  if (runIsTerminal(settled)) {
17885
+ const terminalStatus = terminalRunStatusForEnter(settled);
17797
17886
  await finalizePlaceOrder(ports, {
17798
17887
  orderFulfillmentId: scope.orderFulfillmentId,
17799
- status: "SUCCESS"
17888
+ status: terminalStatus
17800
17889
  });
17801
17890
  await dispatchPendingWebhooks(ports, scope, settled.pending);
17802
- return { status: "SUCCESS" };
17891
+ return { status: terminalStatus };
17803
17892
  }
17804
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17893
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17805
17894
  await dispatchPendingWebhooks(ports, scope, settled.pending);
17895
+ if (paused.closed) return { status: paused.status };
17806
17896
  return { status: "WAITING" };
17807
17897
  };
17808
17898
  const handlePausedNode = async (ports, scope, ran, terminalStatus) => {
@@ -17840,11 +17930,17 @@ const executeAdvance = async (ports, scope, event) => {
17840
17930
  terminalStatus: event.status
17841
17931
  });
17842
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
+ }
17843
17938
  await warnNoEdge(ports, {
17844
17939
  orderFulfillmentId: scope.orderFulfillmentId,
17845
17940
  fulfillmentStatus: event.fulfillment_status
17846
17941
  });
17847
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17942
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17943
+ if (paused.closed) return { status: paused.status };
17848
17944
  return { status: "WAITING" };
17849
17945
  }
17850
17946
  if (advanced.paused) return handlePausedNode(ports, scope, advanced.ran, event.status);
@@ -17864,7 +17960,8 @@ const executeScheduledWake = async (ports, scope, nodeId, terminalStatus) => {
17864
17960
  orderFulfillmentId: scope.orderFulfillmentId,
17865
17961
  fulfillmentStatus: SCHEDULED_STATUS
17866
17962
  });
17867
- await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17963
+ const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
17964
+ if (paused.closed) return { status: paused.status };
17868
17965
  return { status: "WAITING" };
17869
17966
  }
17870
17967
  return executeAdvance(ports, scope, {
@@ -18392,4 +18489,4 @@ const validateTaxId = (country, type, raw) => {
18392
18489
  };
18393
18490
  };
18394
18491
  //#endregion
18395
- 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, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
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.53.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.53.0",
24
- "@fire-spark/types": "^0.53.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",