@fire-spark/core 0.28.0 → 0.30.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 +67 -1
- package/dist/index.js +309 -50
- package/package.json +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -179,8 +179,23 @@ type StorefrontAccessToken = {
|
|
|
179
179
|
token_type: "Bearer";
|
|
180
180
|
expires_in: number;
|
|
181
181
|
};
|
|
182
|
+
/** A kiosk or POS device's own credentials (managed config). */
|
|
183
|
+
type LocalDeviceCredentials = {
|
|
184
|
+
uid: string;
|
|
185
|
+
secret: string;
|
|
186
|
+
};
|
|
182
187
|
type AuthConfigureBase = {
|
|
183
188
|
baseUrl?: string;
|
|
189
|
+
/**
|
|
190
|
+
* Used when `baseUrl` (a local node) drops the connection, usually
|
|
191
|
+
* `https://firespark.cloud`. See `onOriginChange`.
|
|
192
|
+
*/
|
|
193
|
+
fallbackBaseUrl?: string;
|
|
194
|
+
/**
|
|
195
|
+
* In-store devices: when a local node in LOCAL mode cannot exchange the
|
|
196
|
+
* subject token, a node-signed device token is issued with these.
|
|
197
|
+
*/
|
|
198
|
+
localDevice?: LocalDeviceCredentials;
|
|
184
199
|
fetchImpl?: typeof fetch;
|
|
185
200
|
tokenSkewMs?: number;
|
|
186
201
|
};
|
|
@@ -206,6 +221,7 @@ type AuthConfigureAccessTokenOptions = AuthConfigureBase & {
|
|
|
206
221
|
type AuthConfigureOptions = AuthConfigureSubjectOptions | AuthConfigureAccessTokenOptions;
|
|
207
222
|
type ExchangeOptions = {
|
|
208
223
|
baseUrl?: string;
|
|
224
|
+
fallbackBaseUrl?: string;
|
|
209
225
|
fetchImpl?: typeof fetch;
|
|
210
226
|
/** OAuth app alias (RFC 8693 `audience`) when the provider is shared. */
|
|
211
227
|
audience?: string;
|
|
@@ -213,6 +229,8 @@ type ExchangeOptions = {
|
|
|
213
229
|
//#endregion
|
|
214
230
|
//#region src/auth/auth.d.ts
|
|
215
231
|
declare const configure: (options: AuthConfigureOptions) => void;
|
|
232
|
+
/** `fallbackBaseUrl` from `configure()`, if any. */
|
|
233
|
+
declare const getFallbackBaseUrl: () => string | undefined;
|
|
216
234
|
declare const getBaseUrl: () => string;
|
|
217
235
|
declare const clear: () => void;
|
|
218
236
|
declare const isDelegatedSession: () => boolean;
|
|
@@ -223,15 +241,29 @@ declare const getAccessToken: () => Promise<string>;
|
|
|
223
241
|
declare const switchCustomer: (input: SwitchCustomerArg$1) => Promise<SwitchCustomerResult$1>;
|
|
224
242
|
//#endregion
|
|
225
243
|
//#region src/auth/exchange.d.ts
|
|
244
|
+
/** A refused token request; `code` is the API `details.code` or `code`. */
|
|
245
|
+
declare class TokenExchangeError extends Error {
|
|
246
|
+
status: number;
|
|
247
|
+
code?: string;
|
|
248
|
+
constructor(message: string, status: number, code?: string);
|
|
249
|
+
}
|
|
226
250
|
declare const exchangeSubjectToken: (subjectToken: string, options?: ExchangeOptions) => Promise<StorefrontAccessToken>;
|
|
251
|
+
/**
|
|
252
|
+
* `POST local/device-token` on a local node: device uid + secret for a
|
|
253
|
+
* node-signed token only that node accepts (when the cloud is out of
|
|
254
|
+
* reach and the exchange cannot run there).
|
|
255
|
+
*/
|
|
256
|
+
declare const issueLocalDeviceToken: (device: LocalDeviceCredentials, options?: ExchangeOptions) => Promise<StorefrontAccessToken>;
|
|
227
257
|
//#endregion
|
|
228
258
|
//#region src/auth/index.d.ts
|
|
229
259
|
declare const auth: {
|
|
230
260
|
configure: typeof configure;
|
|
231
261
|
getAccessToken: typeof getAccessToken;
|
|
232
262
|
getBaseUrl: typeof getBaseUrl;
|
|
263
|
+
getFallbackBaseUrl: typeof getFallbackBaseUrl;
|
|
233
264
|
clear: typeof clear;
|
|
234
265
|
exchangeSubjectToken: typeof exchangeSubjectToken;
|
|
266
|
+
issueLocalDeviceToken: typeof issueLocalDeviceToken;
|
|
235
267
|
resolveBaseUrl: typeof resolveBaseUrl;
|
|
236
268
|
switchCustomer: typeof switchCustomer;
|
|
237
269
|
isDelegatedSession: typeof isDelegatedSession;
|
|
@@ -275,6 +307,11 @@ declare const isCustomerInfoValueValid: (key: string, value: string) => boolean;
|
|
|
275
307
|
//#region src/services/http.d.ts
|
|
276
308
|
type ServiceHttpOptions = {
|
|
277
309
|
baseUrl?: string;
|
|
310
|
+
/**
|
|
311
|
+
* Used when `baseUrl` (e.g. a local node) drops the connection, usually
|
|
312
|
+
* the cloud. Without `baseUrl`, the one from `auth.configure()` applies.
|
|
313
|
+
*/
|
|
314
|
+
fallbackBaseUrl?: string;
|
|
278
315
|
accessToken?: string;
|
|
279
316
|
fetchImpl?: typeof fetch;
|
|
280
317
|
signal?: AbortSignal;
|
|
@@ -290,6 +327,11 @@ declare class StorefrontHttpError extends Error {
|
|
|
290
327
|
details: StorefrontErrorDetails | null;
|
|
291
328
|
constructor(message: string, status: number, code?: string, details?: StorefrontErrorDetails | null);
|
|
292
329
|
}
|
|
330
|
+
/**
|
|
331
|
+
* A local node does not know this order (e.g. the cart was opened on the
|
|
332
|
+
* cloud before the switch): the SDK creates it again with the same id.
|
|
333
|
+
*/
|
|
334
|
+
declare const isLocalOrderUnknown: (error: unknown) => boolean;
|
|
293
335
|
declare const isStorefrontNotFound: (error: unknown) => boolean;
|
|
294
336
|
declare const storefrontJson: <T>(path: string, init?: RequestInit, options?: ServiceHttpOptions) => Promise<T>;
|
|
295
337
|
//#endregion
|
|
@@ -765,6 +807,11 @@ declare class Order {
|
|
|
765
807
|
setTenders(tenders: PaymentTenderInput[]): Promise<Order$1>;
|
|
766
808
|
/** Drops the chosen tenders and discards the DRAFT intent. */
|
|
767
809
|
clearTenders(): Promise<Order$1>;
|
|
810
|
+
/**
|
|
811
|
+
* Runs a cart call; when a local node answers `LOCAL_ORDER_UNKNOWN`, the
|
|
812
|
+
* cart is created there again with the same id and the call repeated.
|
|
813
|
+
*/
|
|
814
|
+
private onKnownCart;
|
|
768
815
|
private assertPayable;
|
|
769
816
|
private syncPaymentIntent;
|
|
770
817
|
private applyServerOrder;
|
|
@@ -780,6 +827,7 @@ declare class Order {
|
|
|
780
827
|
* `OrderPaymentRequiredError` instead of placing.
|
|
781
828
|
*/
|
|
782
829
|
placeOrder(input?: PlaceOrderInput): Promise<void>;
|
|
830
|
+
private placeOnce;
|
|
783
831
|
/** Installed `@fire-spark/payments-*` adapters (provider + method). */
|
|
784
832
|
setPaymentAdapters(adapters: PaymentAdapter[]): void;
|
|
785
833
|
/** Template modal/sheet the adapters use to talk to the customer. */
|
|
@@ -1575,6 +1623,24 @@ declare const services: {
|
|
|
1575
1623
|
};
|
|
1576
1624
|
};
|
|
1577
1625
|
//#endregion
|
|
1626
|
+
//#region src/shared/origin.d.ts
|
|
1627
|
+
/** Response header a local node sets: `local` when it served the request. */
|
|
1628
|
+
declare const ORIGIN_HEADER = "x-firespark-origin";
|
|
1629
|
+
type FiresparkOrigin = "cloud" | "local";
|
|
1630
|
+
type OriginState = {
|
|
1631
|
+
/** `local`: a local node answered from its own data (LOCAL mode). */
|
|
1632
|
+
origin: FiresparkOrigin;
|
|
1633
|
+
/** Base URL that answered. */
|
|
1634
|
+
baseUrl: string;
|
|
1635
|
+
/** The primary was unreachable and `fallbackBaseUrl` answered. */
|
|
1636
|
+
fallback: boolean;
|
|
1637
|
+
};
|
|
1638
|
+
type OriginListener = (state: OriginState) => void;
|
|
1639
|
+
/** Last origin that answered; null before the first response. */
|
|
1640
|
+
declare const getOrigin: () => OriginState | null;
|
|
1641
|
+
/** Called when the answering origin (cloud, local, fallback) changes. */
|
|
1642
|
+
declare const onOriginChange: (listener: OriginListener) => () => void;
|
|
1643
|
+
//#endregion
|
|
1578
1644
|
//#region src/schedule/schedule.d.ts
|
|
1579
1645
|
type ScheduleWindow = {
|
|
1580
1646
|
active: true;
|
|
@@ -3276,4 +3342,4 @@ declare const hpkeSeal: (input: HpkeSealInput) => Promise<{
|
|
|
3276
3342
|
/** Opens a sealed message; throws when anything was altered. */
|
|
3277
3343
|
declare const hpkeOpen: (input: HpkeOpenInput) => Promise<Uint8Array<ArrayBuffer>>;
|
|
3278
3344
|
//#endregion
|
|
3279
|
-
export { type ApplyRedeemInput, type AuthConfigureOptions, type BuildScheduleSlotsConfig, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type ExchangeOptions, type FailedCharge, type FlatMenuCategory, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type ListMenusStreamOptions, type ListPaymentsOptions, LosslessNumber, type LosslessNumberLike, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, Order, OrderAuthPinnedError, type OrderCancelInput, type OrderCancelOptions, type OrderCancelResult, type OrderCancelType, type OrderCustomerSource, type OrderDeviceCredential, type OrderDraft, type OrderIssue, type OrderIssueCode, type OrderLineDiff, type OrderLineIssue, type OrderLineIssueCode, OrderNotOpenError, OrderPaymentRequiredError, type OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, PickupNameIssue, type PricingModifier, type Product, type ProductCtx, type QuantitiesByPath, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ReversalOutcome, type ReverseAllOptions, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerResult, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|
|
3345
|
+
export { type ApplyRedeemInput, type AuthConfigureOptions, type BuildScheduleSlotsConfig, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, type CanonicalInput, type CanonicalizationError, type CanonicalizationErrorCode, type CardBrand, type CardBrandSpec, type CardCvcError, type CardExpiry, type CardExpiryError, type CardNumberError, type CardPreviewSlot, type CardholderNameError, type CmsBlockScope, type CmsVisibilityBlock, type CmsVisibilityContext, type CmsVisibilityRules, type CreateOrderOptions, type CreateSessionOptions, type CustomizationPath, type CustomizationSession, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, type DeunaCallbackUrls, type DeunaOrderStatus, type ExchangeOptions, type FailedCharge, type FiresparkOrigin, type FlatMenuCategory, type GenOrderIdOptions, type GetCmsBlockOptions, type GroupDisplayType, HPKE_ALG, type HpkeAead, type HpkeEnvelope, type HpkeOpenInput, type HpkePrivateJwk, type HpkePublicJwk, type HpkeSealInput, ID_HASH_FORMATS, type IdBuilder, type IdHashFormat, type ListMenusStreamOptions, type ListPaymentsOptions, type LocalDeviceCredentials, LosslessNumber, type LosslessNumberLike, type Menu, type MenuCategoryNode, type MenuLookup, type MilestoneSteps, type MilestoneTrackItem, type ModifierControlType, type ModifierCtx, type ModifierGroupCtx, type NestedMenuCategory, 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 OrderScope, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, type OrderValidationResult, type OriginListener, type OriginState, type PayIntentOptions, type PayIntentResult, type PayOptions, type PaymentCardBrand, type PaymentProgressEvent, type PaymentProgressListener, type PaymentRunOptions, type PaymentSessionOptions, PickupNameIssue, type PricingModifier, type Product, type ProductCtx, type QuantitiesByPath, type RecommendationType, RecurringDateCron, type RedeemPaymentRow, type RemoveRedeemInput, type ReorderOrderOptions, type ResetOptions, type ReversalOutcome, type ReverseAllOptions, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, type ScheduleSlot, type ScheduleSlotCart, type ScheduleSlotCartLine, type ScheduleWindow, type SelectionStatus, type SelectionsByPath, type SerializedError, type ServiceHttpOptions, type SimpleTenderPayment, type Snapshot, type StateGoldenRootVector, type StateGoldenVector, type StateGoldenVectors, type StateManifest, type StateManifestSection, type StateRootInput, type StateScope, type StateVectorFailure, type StorefrontAccessToken, type StorefrontErrorDetails, StorefrontHttpError, type SwitchCustomerArg, type SwitchCustomerIdToken, type SwitchCustomerResult, TokenExchangeError, type TrackWorkflow, type ValidateOptions, type ValidateOrderAgainstMenuInput, type Variant, type VariantGroup, type VariantGroupCtx, type VariantOptionCtx, type VariantSelection, type VerifyWebhookSignatureInput, type VisitedState, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getOrigin, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, onOriginChange, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|
package/dist/index.js
CHANGED
|
@@ -1917,45 +1917,181 @@ var OrderAuthPinnedError = class extends Error {
|
|
|
1917
1917
|
}
|
|
1918
1918
|
};
|
|
1919
1919
|
//#endregion
|
|
1920
|
-
//#region src/
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1920
|
+
//#region src/shared/origin.ts
|
|
1921
|
+
/** Response header a local node sets: `local` when it served the request. */
|
|
1922
|
+
const ORIGIN_HEADER = "x-firespark-origin";
|
|
1923
|
+
/** How long a primary that dropped the connection is skipped. */
|
|
1924
|
+
const PRIMARY_RETRY_AFTER_MS = 3e4;
|
|
1925
|
+
/** Retries of a refusal the node asks to repeat (same body, same key). */
|
|
1926
|
+
const MAX_RETRIES = 3;
|
|
1927
|
+
const MAX_RETRY_DELAY_MS = 1e4;
|
|
1928
|
+
const DEFAULT_RETRY_DELAY_MS = 2e3;
|
|
1929
|
+
/** Node refusals retried as is after `retry-after` (status → code). */
|
|
1930
|
+
const RETRIED = /* @__PURE__ */ new Map([[503, "LOCAL_NODE_DRAINING"], [502, "LOCAL_CLOUD_UNREACHABLE"]]);
|
|
1931
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1932
|
+
const downUntil = /* @__PURE__ */ new Map();
|
|
1933
|
+
let current = null;
|
|
1934
|
+
const defaultSleep$2 = (ms) => {
|
|
1935
|
+
return new Promise((resolve) => {
|
|
1936
|
+
setTimeout(resolve, ms);
|
|
1932
1937
|
});
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1938
|
+
};
|
|
1939
|
+
let sleepImpl = defaultSleep$2;
|
|
1940
|
+
/** Last origin that answered; null before the first response. */
|
|
1941
|
+
const getOrigin = () => current;
|
|
1942
|
+
/** Called when the answering origin (cloud, local, fallback) changes. */
|
|
1943
|
+
const onOriginChange = (listener) => {
|
|
1944
|
+
listeners.add(listener);
|
|
1945
|
+
return () => {
|
|
1946
|
+
listeners.delete(listener);
|
|
1947
|
+
};
|
|
1948
|
+
};
|
|
1949
|
+
const report = (next) => {
|
|
1950
|
+
if (current?.origin === next.origin && current?.fallback === next.fallback) {
|
|
1951
|
+
current = next;
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
current = next;
|
|
1955
|
+
for (const listener of listeners) listener(next);
|
|
1956
|
+
};
|
|
1957
|
+
const originOf = (response) => {
|
|
1958
|
+
return (response.headers?.get?.("x-firespark-origin"))?.toLowerCase() === "local" ? "local" : "cloud";
|
|
1959
|
+
};
|
|
1960
|
+
const isPrimaryDown = (baseUrl) => {
|
|
1961
|
+
const until = downUntil.get(baseUrl);
|
|
1962
|
+
if (until === void 0) return false;
|
|
1963
|
+
if (until > Date.now()) return true;
|
|
1964
|
+
downUntil.delete(baseUrl);
|
|
1965
|
+
return false;
|
|
1966
|
+
};
|
|
1967
|
+
const readCode$1 = async (response) => {
|
|
1968
|
+
try {
|
|
1969
|
+
const body = await response.clone().json();
|
|
1970
|
+
const code = body?.details?.code ?? body?.code;
|
|
1971
|
+
return typeof code === "string" ? code : null;
|
|
1972
|
+
} catch {
|
|
1973
|
+
return null;
|
|
1974
|
+
}
|
|
1975
|
+
};
|
|
1976
|
+
/** `retry-after` in seconds (or an HTTP date), bounded to 10 s. */
|
|
1977
|
+
const retryDelayMs = (response) => {
|
|
1978
|
+
const raw = response.headers?.get?.("retry-after");
|
|
1979
|
+
if (!raw) return DEFAULT_RETRY_DELAY_MS;
|
|
1980
|
+
const seconds = Number(raw);
|
|
1981
|
+
let ms = seconds * 1e3;
|
|
1982
|
+
if (!Number.isFinite(seconds)) ms = Date.parse(raw) - Date.now();
|
|
1983
|
+
if (!Number.isFinite(ms)) return DEFAULT_RETRY_DELAY_MS;
|
|
1984
|
+
return Math.min(Math.max(ms, 0), MAX_RETRY_DELAY_MS);
|
|
1985
|
+
};
|
|
1986
|
+
const shouldRetry = async (response) => {
|
|
1987
|
+
const code = RETRIED.get(response.status);
|
|
1988
|
+
if (!code) return false;
|
|
1989
|
+
return await readCode$1(response) === code;
|
|
1990
|
+
};
|
|
1991
|
+
const isAbort = (error, init) => {
|
|
1992
|
+
if (init.signal?.aborted) return true;
|
|
1993
|
+
return error?.name === "AbortError";
|
|
1994
|
+
};
|
|
1995
|
+
const joinUrl = (baseUrl, path) => {
|
|
1996
|
+
return `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
|
|
1997
|
+
};
|
|
1998
|
+
/**
|
|
1999
|
+
* Fetch against a primary base URL (a local node or the cloud) that:
|
|
2000
|
+
* - falls back to `fallbackBaseUrl` when the primary drops the connection,
|
|
2001
|
+
* and skips the primary for 30 s afterwards;
|
|
2002
|
+
* - repeats 503 `LOCAL_NODE_DRAINING` and 502 `LOCAL_CLOUD_UNREACHABLE`
|
|
2003
|
+
* after `retry-after`, with the same body, so the same idempotency key;
|
|
2004
|
+
* - reports the answering origin to `onOriginChange` listeners.
|
|
2005
|
+
*/
|
|
2006
|
+
const originFetch = async (input) => {
|
|
2007
|
+
const { baseUrl, fallbackBaseUrl, path, init, fetchImpl } = input;
|
|
2008
|
+
const fallback = fallbackBaseUrl && fallbackBaseUrl !== baseUrl;
|
|
2009
|
+
for (let attempt = 0;; attempt += 1) {
|
|
2010
|
+
const useFallback = Boolean(fallback && isPrimaryDown(baseUrl));
|
|
2011
|
+
const target = useFallback && fallbackBaseUrl ? fallbackBaseUrl : baseUrl;
|
|
2012
|
+
let response;
|
|
2013
|
+
try {
|
|
2014
|
+
response = await fetchImpl(joinUrl(target, path), init);
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
if (useFallback || !fallback || isAbort(error, init)) throw error;
|
|
2017
|
+
downUntil.set(baseUrl, Date.now() + PRIMARY_RETRY_AFTER_MS);
|
|
2018
|
+
continue;
|
|
2019
|
+
}
|
|
2020
|
+
const origin = originOf(response);
|
|
2021
|
+
report({
|
|
2022
|
+
origin,
|
|
2023
|
+
baseUrl: target,
|
|
2024
|
+
fallback: useFallback
|
|
2025
|
+
});
|
|
2026
|
+
if (attempt >= MAX_RETRIES || !await shouldRetry(response)) return response;
|
|
2027
|
+
await sleepImpl(retryDelayMs(response));
|
|
1936
2028
|
}
|
|
2029
|
+
};
|
|
2030
|
+
//#endregion
|
|
2031
|
+
//#region src/auth/exchange.ts
|
|
2032
|
+
const EXCHANGE_PATH = "/api/storefront/v1/oauth/exchange";
|
|
2033
|
+
const LOCAL_TOKEN_PATH = "/api/storefront/v1/local/device-token";
|
|
2034
|
+
/** A refused token request; `code` is the API `details.code` or `code`. */
|
|
2035
|
+
var TokenExchangeError = class extends Error {
|
|
2036
|
+
status;
|
|
2037
|
+
code;
|
|
2038
|
+
constructor(message, status, code) {
|
|
2039
|
+
super(message);
|
|
2040
|
+
this.name = "TokenExchangeError";
|
|
2041
|
+
this.status = status;
|
|
2042
|
+
this.code = code;
|
|
2043
|
+
}
|
|
2044
|
+
};
|
|
2045
|
+
const readCode = (text) => {
|
|
2046
|
+
try {
|
|
2047
|
+
const body = JSON.parse(text);
|
|
2048
|
+
const code = body?.details?.code ?? body?.code;
|
|
2049
|
+
return typeof code === "string" ? code : void 0;
|
|
2050
|
+
} catch {
|
|
2051
|
+
return;
|
|
2052
|
+
}
|
|
2053
|
+
};
|
|
2054
|
+
const refused = async (response) => {
|
|
2055
|
+
const text = await response.text();
|
|
2056
|
+
return new TokenExchangeError(text || `Token exchange failed (${response.status})`, response.status, readCode(text));
|
|
2057
|
+
};
|
|
2058
|
+
const postToken = (path, body, options) => {
|
|
2059
|
+
const baseUrl = resolveBaseUrl(options.baseUrl);
|
|
2060
|
+
const fallback = options.fallbackBaseUrl;
|
|
2061
|
+
const fallbackBaseUrl = fallback ? resolveBaseUrl(fallback) : void 0;
|
|
2062
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
2063
|
+
return originFetch({
|
|
2064
|
+
baseUrl,
|
|
2065
|
+
fallbackBaseUrl,
|
|
2066
|
+
path,
|
|
2067
|
+
init: {
|
|
2068
|
+
method: "POST",
|
|
2069
|
+
headers: { "Content-Type": "application/json" },
|
|
2070
|
+
body: JSON.stringify(body)
|
|
2071
|
+
},
|
|
2072
|
+
fetchImpl
|
|
2073
|
+
});
|
|
2074
|
+
};
|
|
2075
|
+
const exchangeSubjectToken = async (subjectToken, options = {}) => {
|
|
2076
|
+
const response = await postToken(EXCHANGE_PATH, {
|
|
2077
|
+
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
2078
|
+
subject_token: subjectToken,
|
|
2079
|
+
subject_token_type: "urn:ietf:params:oauth:token-type:id_token",
|
|
2080
|
+
...options.audience ? { audience: options.audience } : {}
|
|
2081
|
+
}, options);
|
|
2082
|
+
if (!response.ok) throw await refused(response);
|
|
1937
2083
|
const json = await response.json();
|
|
1938
2084
|
if (!json.data?.access_token) throw new Error("Token exchange response missing access_token");
|
|
1939
2085
|
return json.data;
|
|
1940
2086
|
};
|
|
1941
2087
|
const GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
1942
2088
|
const switchCustomerToken = async (body, options = {}) => {
|
|
1943
|
-
const base = resolveBaseUrl(options.baseUrl);
|
|
1944
|
-
const fetchImpl = options.fetchImpl ?? fetch;
|
|
1945
|
-
const url = `${base}/api/storefront/v1/oauth/exchange`;
|
|
1946
2089
|
const payload = {
|
|
1947
2090
|
grant_type: GRANT,
|
|
1948
2091
|
...body
|
|
1949
2092
|
};
|
|
1950
|
-
const response = await
|
|
1951
|
-
|
|
1952
|
-
headers: { "Content-Type": "application/json" },
|
|
1953
|
-
body: JSON.stringify(payload)
|
|
1954
|
-
});
|
|
1955
|
-
if (!response.ok) {
|
|
1956
|
-
const message = await response.text();
|
|
1957
|
-
throw new Error(message || `Token exchange failed (${response.status})`);
|
|
1958
|
-
}
|
|
2093
|
+
const response = await postToken(EXCHANGE_PATH, payload, options);
|
|
2094
|
+
if (!response.ok) throw await refused(response);
|
|
1959
2095
|
const data = (await response.json()).data;
|
|
1960
2096
|
if (!data?.access_token || !data.customer_id || !data.order) throw new Error("Token exchange response missing access_token");
|
|
1961
2097
|
const order = data.order;
|
|
@@ -1965,6 +2101,31 @@ const switchCustomerToken = async (body, options = {}) => {
|
|
|
1965
2101
|
order
|
|
1966
2102
|
};
|
|
1967
2103
|
};
|
|
2104
|
+
/**
|
|
2105
|
+
* `POST local/device-token` on a local node: device uid + secret for a
|
|
2106
|
+
* node-signed token only that node accepts (when the cloud is out of
|
|
2107
|
+
* reach and the exchange cannot run there).
|
|
2108
|
+
*/
|
|
2109
|
+
const issueLocalDeviceToken = async (device, options = {}) => {
|
|
2110
|
+
const body = {
|
|
2111
|
+
device_uid: device.uid,
|
|
2112
|
+
device_secret: device.secret
|
|
2113
|
+
};
|
|
2114
|
+
const local = {
|
|
2115
|
+
...options,
|
|
2116
|
+
fallbackBaseUrl: void 0
|
|
2117
|
+
};
|
|
2118
|
+
const response = await postToken(LOCAL_TOKEN_PATH, body, local);
|
|
2119
|
+
if (!response.ok) throw await refused(response);
|
|
2120
|
+
const json = await response.json();
|
|
2121
|
+
if (!json.data?.access_token) throw new Error("Local device token response missing access_token");
|
|
2122
|
+
const { access_token, expires_in } = json.data;
|
|
2123
|
+
return {
|
|
2124
|
+
access_token,
|
|
2125
|
+
token_type: "Bearer",
|
|
2126
|
+
expires_in
|
|
2127
|
+
};
|
|
2128
|
+
};
|
|
1968
2129
|
//#endregion
|
|
1969
2130
|
//#region src/auth/auth.ts
|
|
1970
2131
|
const DEFAULT_TOKEN_SKEW_MS = 3e4;
|
|
@@ -2033,12 +2194,20 @@ const configure = (options) => {
|
|
|
2033
2194
|
delegated,
|
|
2034
2195
|
listeners
|
|
2035
2196
|
};
|
|
2197
|
+
const fallback = options.fallbackBaseUrl;
|
|
2198
|
+
const b4 = {
|
|
2199
|
+
fallbackBaseUrl: fallback ? resolveBaseUrl(fallback) : void 0,
|
|
2200
|
+
localDevice: options.localDevice
|
|
2201
|
+
};
|
|
2036
2202
|
state = {
|
|
2037
2203
|
...b1,
|
|
2038
2204
|
...b2,
|
|
2039
|
-
...b3
|
|
2205
|
+
...b3,
|
|
2206
|
+
...b4
|
|
2040
2207
|
};
|
|
2041
2208
|
};
|
|
2209
|
+
/** `fallbackBaseUrl` from `configure()`, if any. */
|
|
2210
|
+
const getFallbackBaseUrl = () => state?.fallbackBaseUrl;
|
|
2042
2211
|
const getBaseUrl = () => {
|
|
2043
2212
|
if (!state) throw new Error("auth.configure() must be called before getBaseUrl()");
|
|
2044
2213
|
return state.baseUrl;
|
|
@@ -2096,11 +2265,27 @@ const releaseDelegatedOrder = (orderId) => {
|
|
|
2096
2265
|
const issueToken = async (current) => {
|
|
2097
2266
|
if (current.getDirectToken) return current.getDirectToken();
|
|
2098
2267
|
if (!current.getSubjectToken) throw new Error("auth.configure() needs getSubjectToken or getAccessToken");
|
|
2099
|
-
|
|
2268
|
+
const subjectToken = await current.getSubjectToken();
|
|
2269
|
+
const http = {
|
|
2100
2270
|
baseUrl: current.baseUrl,
|
|
2101
2271
|
fetchImpl: current.fetchImpl,
|
|
2272
|
+
fallbackBaseUrl: current.fallbackBaseUrl
|
|
2273
|
+
};
|
|
2274
|
+
const opts = {
|
|
2275
|
+
...http,
|
|
2102
2276
|
audience: current.audience
|
|
2103
|
-
}
|
|
2277
|
+
};
|
|
2278
|
+
try {
|
|
2279
|
+
return await exchangeSubjectToken(subjectToken, opts);
|
|
2280
|
+
} catch (error) {
|
|
2281
|
+
if (!current.localDevice || !isLocalRefusal(error)) throw error;
|
|
2282
|
+
return issueLocalDeviceToken(current.localDevice, http);
|
|
2283
|
+
}
|
|
2284
|
+
};
|
|
2285
|
+
/** A local node that cannot reach the cloud refuses with `LOCAL_*`. */
|
|
2286
|
+
const isLocalRefusal = (error) => {
|
|
2287
|
+
if (!(error instanceof TokenExchangeError)) return false;
|
|
2288
|
+
return error.code?.startsWith("LOCAL_") ?? false;
|
|
2104
2289
|
};
|
|
2105
2290
|
const subjectRotated = async (current) => {
|
|
2106
2291
|
const actorSub = current.delegated?.actorSub;
|
|
@@ -2176,7 +2361,8 @@ const switchCustomer = async (input) => {
|
|
|
2176
2361
|
...b2
|
|
2177
2362
|
}, {
|
|
2178
2363
|
baseUrl: state.baseUrl,
|
|
2179
|
-
fetchImpl: state.fetchImpl
|
|
2364
|
+
fetchImpl: state.fetchImpl,
|
|
2365
|
+
fallbackBaseUrl: state.fallbackBaseUrl
|
|
2180
2366
|
});
|
|
2181
2367
|
const expiresAt = Date.now() + result.expires_in * 1e3;
|
|
2182
2368
|
const d1 = {
|
|
@@ -2202,8 +2388,10 @@ const auth = {
|
|
|
2202
2388
|
configure,
|
|
2203
2389
|
getAccessToken,
|
|
2204
2390
|
getBaseUrl,
|
|
2391
|
+
getFallbackBaseUrl,
|
|
2205
2392
|
clear,
|
|
2206
2393
|
exchangeSubjectToken,
|
|
2394
|
+
issueLocalDeviceToken,
|
|
2207
2395
|
resolveBaseUrl,
|
|
2208
2396
|
switchCustomer,
|
|
2209
2397
|
isDelegatedSession,
|
|
@@ -2468,6 +2656,14 @@ const toStorefrontHttpError = (text, status) => {
|
|
|
2468
2656
|
const bodyCode = typeof body?.code === "string" ? body.code : void 0;
|
|
2469
2657
|
return new StorefrontHttpError(text, status, detailsCode ?? bodyCode, details);
|
|
2470
2658
|
};
|
|
2659
|
+
/**
|
|
2660
|
+
* A local node does not know this order (e.g. the cart was opened on the
|
|
2661
|
+
* cloud before the switch): the SDK creates it again with the same id.
|
|
2662
|
+
*/
|
|
2663
|
+
const isLocalOrderUnknown = (error) => {
|
|
2664
|
+
if (!(error instanceof StorefrontHttpError)) return false;
|
|
2665
|
+
return error.code === "LOCAL_ORDER_UNKNOWN";
|
|
2666
|
+
};
|
|
2471
2667
|
const isStorefrontNotFound = (error) => {
|
|
2472
2668
|
return error instanceof StorefrontHttpError && error.status === 404;
|
|
2473
2669
|
};
|
|
@@ -2479,6 +2675,11 @@ const httpBaseUrl = (options) => {
|
|
|
2479
2675
|
return resolveBaseUrl();
|
|
2480
2676
|
}
|
|
2481
2677
|
};
|
|
2678
|
+
const httpFallbackUrl = (options) => {
|
|
2679
|
+
if (options.fallbackBaseUrl) return resolveBaseUrl(options.fallbackBaseUrl);
|
|
2680
|
+
if (options.baseUrl) return void 0;
|
|
2681
|
+
return auth.getFallbackBaseUrl();
|
|
2682
|
+
};
|
|
2482
2683
|
const resolveAccessToken = async (options) => {
|
|
2483
2684
|
if (options.accessToken) return options.accessToken;
|
|
2484
2685
|
return auth.getAccessToken();
|
|
@@ -2493,7 +2694,8 @@ const withAuthRetry = async (options, run) => {
|
|
|
2493
2694
|
/** Low-level storefront fetch. Prefer typed services over calling this directly. */
|
|
2494
2695
|
const storefrontRequest = async (path, init = {}, options = {}) => {
|
|
2495
2696
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
2496
|
-
const
|
|
2697
|
+
const baseUrl = httpBaseUrl(options);
|
|
2698
|
+
const fallbackBaseUrl = httpFallbackUrl(options);
|
|
2497
2699
|
return withAuthRetry(options, (accessToken) => {
|
|
2498
2700
|
const headers = new Headers(init.headers);
|
|
2499
2701
|
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
@@ -2504,7 +2706,13 @@ const storefrontRequest = async (path, init = {}, options = {}) => {
|
|
|
2504
2706
|
headers,
|
|
2505
2707
|
signal
|
|
2506
2708
|
};
|
|
2507
|
-
return
|
|
2709
|
+
return originFetch({
|
|
2710
|
+
baseUrl,
|
|
2711
|
+
fallbackBaseUrl,
|
|
2712
|
+
path,
|
|
2713
|
+
init: req,
|
|
2714
|
+
fetchImpl
|
|
2715
|
+
});
|
|
2508
2716
|
});
|
|
2509
2717
|
};
|
|
2510
2718
|
const storefrontJson = async (path, init = {}, options = {}) => {
|
|
@@ -2675,11 +2883,12 @@ const getFulfillment = (id, input = {}, options) => {
|
|
|
2675
2883
|
};
|
|
2676
2884
|
//#endregion
|
|
2677
2885
|
//#region src/services/kiosk.ts
|
|
2678
|
-
const
|
|
2679
|
-
const
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2886
|
+
const kioskBases = (options) => {
|
|
2887
|
+
const fallback = options?.fallbackBaseUrl;
|
|
2888
|
+
return {
|
|
2889
|
+
baseUrl: resolveBaseUrl(options?.baseUrl || void 0),
|
|
2890
|
+
fallbackBaseUrl: fallback ? resolveBaseUrl(fallback) : void 0
|
|
2891
|
+
};
|
|
2683
2892
|
};
|
|
2684
2893
|
const kioskFetch = async (path, init, options) => {
|
|
2685
2894
|
const fetchImpl = options?.fetchImpl ?? fetch;
|
|
@@ -2691,7 +2900,12 @@ const kioskFetch = async (path, init, options) => {
|
|
|
2691
2900
|
headers,
|
|
2692
2901
|
signal
|
|
2693
2902
|
};
|
|
2694
|
-
return
|
|
2903
|
+
return originFetch({
|
|
2904
|
+
...kioskBases(options),
|
|
2905
|
+
path,
|
|
2906
|
+
init: req,
|
|
2907
|
+
fetchImpl
|
|
2908
|
+
});
|
|
2695
2909
|
};
|
|
2696
2910
|
const readError$1 = async (response) => {
|
|
2697
2911
|
const text = await response.text();
|
|
@@ -3310,11 +3524,12 @@ const posErrorMessage = (code, locale = "en-US") => {
|
|
|
3310
3524
|
};
|
|
3311
3525
|
//#endregion
|
|
3312
3526
|
//#region src/services/pos.ts
|
|
3313
|
-
const
|
|
3314
|
-
const
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3527
|
+
const posBases = (options) => {
|
|
3528
|
+
const fallback = options?.fallbackBaseUrl;
|
|
3529
|
+
return {
|
|
3530
|
+
baseUrl: resolveBaseUrl(options?.baseUrl || void 0),
|
|
3531
|
+
fallbackBaseUrl: fallback ? resolveBaseUrl(fallback) : void 0
|
|
3532
|
+
};
|
|
3318
3533
|
};
|
|
3319
3534
|
const posFetch = async (path, init, options) => {
|
|
3320
3535
|
const fetchImpl = options?.fetchImpl ?? fetch;
|
|
@@ -3326,7 +3541,12 @@ const posFetch = async (path, init, options) => {
|
|
|
3326
3541
|
headers,
|
|
3327
3542
|
signal
|
|
3328
3543
|
};
|
|
3329
|
-
return
|
|
3544
|
+
return originFetch({
|
|
3545
|
+
...posBases(options),
|
|
3546
|
+
path,
|
|
3547
|
+
init: req,
|
|
3548
|
+
fetchImpl
|
|
3549
|
+
});
|
|
3330
3550
|
};
|
|
3331
3551
|
const readError = async (response) => {
|
|
3332
3552
|
const text = await response.text();
|
|
@@ -4065,6 +4285,15 @@ const createFlushController = (runtime) => {
|
|
|
4065
4285
|
if (!pending) return;
|
|
4066
4286
|
await flushNow();
|
|
4067
4287
|
};
|
|
4288
|
+
const recreate = async () => {
|
|
4289
|
+
const payload = structuredClone(runtime.getDraft());
|
|
4290
|
+
const body = insertBody(payload);
|
|
4291
|
+
const created = await services.orders.post(body, runtime.http);
|
|
4292
|
+
runtime.setPersisted(true);
|
|
4293
|
+
runtime.setSynced(created);
|
|
4294
|
+
runtime.setDraft(created);
|
|
4295
|
+
runtime.notify();
|
|
4296
|
+
};
|
|
4068
4297
|
const run = async () => {
|
|
4069
4298
|
const batchBase = structuredClone(runtime.getSynced());
|
|
4070
4299
|
const payload = structuredClone(runtime.getDraft());
|
|
@@ -4080,7 +4309,10 @@ const createFlushController = (runtime) => {
|
|
|
4080
4309
|
body,
|
|
4081
4310
|
runtime.http
|
|
4082
4311
|
];
|
|
4083
|
-
return services.orders.patch(...p1)
|
|
4312
|
+
return services.orders.patch(...p1).catch((error) => {
|
|
4313
|
+
if (!isLocalOrderUnknown(error)) throw error;
|
|
4314
|
+
return services.orders.post(insertBody(payload), runtime.http);
|
|
4315
|
+
});
|
|
4084
4316
|
}, { sleep: runtime.sleep });
|
|
4085
4317
|
pending = false;
|
|
4086
4318
|
rejected = null;
|
|
@@ -4151,6 +4383,7 @@ const createFlushController = (runtime) => {
|
|
|
4151
4383
|
flushNow,
|
|
4152
4384
|
settle,
|
|
4153
4385
|
resume,
|
|
4386
|
+
recreate,
|
|
4154
4387
|
getInFlight: () => inFlight,
|
|
4155
4388
|
getPending: () => pending,
|
|
4156
4389
|
getRejected: () => rejected
|
|
@@ -6932,10 +7165,24 @@ var Order = class Order {
|
|
|
6932
7165
|
this.realTenders = null;
|
|
6933
7166
|
if (activeIntent(this.draft.payment_intents)?.status !== "DRAFT") return this.getOrder();
|
|
6934
7167
|
const id = this.draft.id;
|
|
6935
|
-
const
|
|
7168
|
+
const drop = () => services.orders.deletePaymentIntent(id, this.http);
|
|
7169
|
+
const next = await this.onKnownCart(drop);
|
|
6936
7170
|
this.applyServerOrder(next);
|
|
6937
7171
|
return this.getOrder();
|
|
6938
7172
|
}
|
|
7173
|
+
/**
|
|
7174
|
+
* Runs a cart call; when a local node answers `LOCAL_ORDER_UNKNOWN`, the
|
|
7175
|
+
* cart is created there again with the same id and the call repeated.
|
|
7176
|
+
*/
|
|
7177
|
+
async onKnownCart(run) {
|
|
7178
|
+
try {
|
|
7179
|
+
return await run();
|
|
7180
|
+
} catch (error) {
|
|
7181
|
+
if (!isLocalOrderUnknown(error)) throw error;
|
|
7182
|
+
await this.flush.recreate();
|
|
7183
|
+
return run();
|
|
7184
|
+
}
|
|
7185
|
+
}
|
|
6939
7186
|
assertPayable(payment) {
|
|
6940
7187
|
if (redeemsCoverTotal(cappedRedeems(this.draft), this.draft.totals)) return;
|
|
6941
7188
|
const method = payment?.type;
|
|
@@ -6948,7 +7195,8 @@ var Order = class Order {
|
|
|
6948
7195
|
await this.flush.settle();
|
|
6949
7196
|
const id = this.draft.id;
|
|
6950
7197
|
const put = services.orders.putPaymentIntent;
|
|
6951
|
-
const
|
|
7198
|
+
const save = () => put(id, { tenders }, this.http);
|
|
7199
|
+
const next = await this.onKnownCart(save);
|
|
6952
7200
|
this.applyServerOrder(next);
|
|
6953
7201
|
return this.getOrder();
|
|
6954
7202
|
}
|
|
@@ -6975,6 +7223,16 @@ var Order = class Order {
|
|
|
6975
7223
|
* `OrderPaymentRequiredError` instead of placing.
|
|
6976
7224
|
*/
|
|
6977
7225
|
async placeOrder(input = {}) {
|
|
7226
|
+
try {
|
|
7227
|
+
await this.placeOnce(input);
|
|
7228
|
+
} catch (error) {
|
|
7229
|
+
if (!isLocalOrderUnknown(error)) throw error;
|
|
7230
|
+
await this.flush.recreate();
|
|
7231
|
+
const { intent_id: _stale, ...fresh } = input;
|
|
7232
|
+
await this.placeOnce(fresh);
|
|
7233
|
+
}
|
|
7234
|
+
}
|
|
7235
|
+
async placeOnce(input) {
|
|
6978
7236
|
await this.persist();
|
|
6979
7237
|
await this.flush.settle();
|
|
6980
7238
|
if (!input.intent_id) this.assertPayable(input.payment);
|
|
@@ -6998,7 +7256,8 @@ var Order = class Order {
|
|
|
6998
7256
|
try {
|
|
6999
7257
|
await services.orders.place(this.draft.id, body, this.http);
|
|
7000
7258
|
} catch (error) {
|
|
7001
|
-
|
|
7259
|
+
const known = !isLocalOrderUnknown(error);
|
|
7260
|
+
if (!(error instanceof StorefrontHttpError && known) || error.status !== 409) throw error;
|
|
7002
7261
|
}
|
|
7003
7262
|
const next = await services.orders.get(this.draft.id, this.http);
|
|
7004
7263
|
this.applyServerOrder(next);
|
|
@@ -13263,4 +13522,4 @@ const hpkeOpen = async (input) => {
|
|
|
13263
13522
|
return new Uint8Array(opened);
|
|
13264
13523
|
};
|
|
13265
13524
|
//#endregion
|
|
13266
|
-
export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|
|
13525
|
+
export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TokenExchangeError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getOrigin, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, onOriginChange, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fire-spark/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.30.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.
|
|
24
|
-
"@fire-spark/types": "^0.
|
|
23
|
+
"@fire-spark/payments": "^0.30.0",
|
|
24
|
+
"@fire-spark/types": "^0.30.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"tsdown": "^0.22.14",
|