@fire-spark/core 0.24.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1276 -4
- package/dist/index.js +1802 -12
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DIGITAL_COLLECT_AT, PARTIAL_APPROVAL_ERROR, REDEMPTION_METHOD, activeIntent, createAttemptReference, createPaymentError, currentIntent, defaultReversalFor, groupRedeems, hasRedeemPayment, isDeliveryFee, isManualPayment, isPaymentError, isProductReward, isRealPaymentMethod, isRealPaymentMethod as isRealPaymentMethod$1, isTenderSettled, isTipFee, liveTenders, memoryPaymentStorage, missingDeviceFields, money, moneyMin, moneyNumber, moneyZero, orderRedeems, orderRedeems as orderRedeems$1, redeemsCoverTotal, resolvePaymentPolicy, resolveProviderEnvironment, scopedPaymentStorage, taxBreakdown, toChargeAmount, withTerminalLock } from "@fire-spark/payments";
|
|
1
|
+
import { DIGITAL_COLLECT_AT, PARTIAL_APPROVAL_ERROR, REDEMPTION_METHOD, activeIntent, createAttemptReference, createPaymentError, currentIntent, defaultReversalFor, derivePaymentStatus, groupRedeems, hasRedeemPayment, isDeliveryFee, isManualPayment, isMixedTenders, isPaymentError, isProductReward, isRealPaymentMethod, isRealPaymentMethod as isRealPaymentMethod$1, isTenderSettled, isTipFee, liveRealTenders, liveTenders, memoryPaymentStorage, missingDeviceFields, money, moneyMin, moneyNumber, moneyZero, orderRedeems, orderRedeems as orderRedeems$1, paymentResultAmount, paymentResultDecimal, primaryTender, redeemsCoverTotal, resolvePaymentPolicy, resolveProviderEnvironment, scopedPaymentStorage, taxBreakdown, toChargeAmount, withTerminalLock } from "@fire-spark/payments";
|
|
2
2
|
import advancedFormat from "dayjs/plugin/advancedFormat.js";
|
|
3
3
|
import isBetween from "dayjs/plugin/isBetween.js";
|
|
4
4
|
import isSameOrAfter from "dayjs/plugin/isSameOrAfter.js";
|
|
@@ -4589,7 +4589,7 @@ const failed = (ctx, error, extra = {}) => {
|
|
|
4589
4589
|
};
|
|
4590
4590
|
return {
|
|
4591
4591
|
status: "FAILED",
|
|
4592
|
-
|
|
4592
|
+
...paymentResultAmount(ctx.amount.value),
|
|
4593
4593
|
metadata,
|
|
4594
4594
|
error
|
|
4595
4595
|
};
|
|
@@ -4855,7 +4855,7 @@ const partialOf = (result) => {
|
|
|
4855
4855
|
const isPartialApproval = (result, tender, ctx) => {
|
|
4856
4856
|
if (result.status !== "PAID") return false;
|
|
4857
4857
|
if (ctx.amount.currency !== tender.amount.currency) return false;
|
|
4858
|
-
return money(result
|
|
4858
|
+
return money(paymentResultDecimal(result)).lt(tender.amount.total);
|
|
4859
4859
|
};
|
|
4860
4860
|
const toFailure = (error) => {
|
|
4861
4861
|
const message = error instanceof Error ? error.message : "Terminal failed";
|
|
@@ -5121,7 +5121,7 @@ var PaymentSession = class {
|
|
|
5121
5121
|
/** D31: the provider approved less than the tender; void it, FAILED. */
|
|
5122
5122
|
async rejectPartial(adapter, ctx, result, tender) {
|
|
5123
5123
|
const voided = adapter.cancel ? await adapter.cancel(ctx, result).catch(() => null) : null;
|
|
5124
|
-
const error = createPaymentError("INSUFFICIENT_FUNDS", { provider_message: `Approved ${result
|
|
5124
|
+
const error = createPaymentError("INSUFFICIENT_FUNDS", { provider_message: `Approved ${paymentResultDecimal(result)}` });
|
|
5125
5125
|
const needs_review = voided?.status !== "CANCELLED";
|
|
5126
5126
|
const partial_approval = { approved_amount: result.amount };
|
|
5127
5127
|
const metadata = {
|
|
@@ -5132,7 +5132,7 @@ var PaymentSession = class {
|
|
|
5132
5132
|
};
|
|
5133
5133
|
return {
|
|
5134
5134
|
status: "FAILED",
|
|
5135
|
-
|
|
5135
|
+
...paymentResultAmount(tender.amount.total),
|
|
5136
5136
|
metadata,
|
|
5137
5137
|
error
|
|
5138
5138
|
};
|
|
@@ -5151,7 +5151,7 @@ var PaymentSession = class {
|
|
|
5151
5151
|
if (!isManual(payment) && tender.status !== "PENDING") {
|
|
5152
5152
|
const pending = {
|
|
5153
5153
|
status: "PENDING",
|
|
5154
|
-
amount,
|
|
5154
|
+
...paymentResultAmount(amount),
|
|
5155
5155
|
metadata
|
|
5156
5156
|
};
|
|
5157
5157
|
await this.recordResult(tender, pending);
|
|
@@ -5296,9 +5296,10 @@ var PaymentSession = class {
|
|
|
5296
5296
|
...metadata,
|
|
5297
5297
|
attempt_reference
|
|
5298
5298
|
};
|
|
5299
|
+
const a1 = paymentResultAmount(tender.amount.total);
|
|
5299
5300
|
return {
|
|
5300
5301
|
status: tender.status,
|
|
5301
|
-
|
|
5302
|
+
...a1,
|
|
5302
5303
|
metadata: m1,
|
|
5303
5304
|
...error ? { error } : {}
|
|
5304
5305
|
};
|
|
@@ -7226,7 +7227,7 @@ var Order = class Order {
|
|
|
7226
7227
|
};
|
|
7227
7228
|
//#endregion
|
|
7228
7229
|
//#region src/order/fulfillmentTrack.ts
|
|
7229
|
-
const isPrimaryPathKind = (pathKind) => {
|
|
7230
|
+
const isPrimaryPathKind$1 = (pathKind) => {
|
|
7230
7231
|
return pathKind === "default" || pathKind === "success" || pathKind == null;
|
|
7231
7232
|
};
|
|
7232
7233
|
const pathKindForTarget = (target) => {
|
|
@@ -7300,7 +7301,7 @@ const walkPrimaryMilestones = (workflow) => {
|
|
|
7300
7301
|
if (!nodesById.has(edge.source) || !nodesById.has(edge.target)) continue;
|
|
7301
7302
|
const target = nodesById.get(edge.target);
|
|
7302
7303
|
const pathKind = edge.data?.pathKind ?? pathKindForTarget(target);
|
|
7303
|
-
if (!isPrimaryPathKind(pathKind)) continue;
|
|
7304
|
+
if (!isPrimaryPathKind$1(pathKind)) continue;
|
|
7304
7305
|
primaryOut.get(edge.source)?.push(edge.target);
|
|
7305
7306
|
primaryIn.get(edge.target)?.push(edge.source);
|
|
7306
7307
|
}
|
|
@@ -8619,7 +8620,7 @@ const stepIssues = (submitted, expected) => {
|
|
|
8619
8620
|
};
|
|
8620
8621
|
const validateRedemptions = (input, issues, lineIssues) => {
|
|
8621
8622
|
const redeem = input.redeem ?? [];
|
|
8622
|
-
const now = input.now ?? Date.now();
|
|
8623
|
+
const now = input.now ?? input.asOf?.getTime() ?? Date.now();
|
|
8623
8624
|
const p1 = {
|
|
8624
8625
|
lines: input.lines,
|
|
8625
8626
|
totals: input.totals,
|
|
@@ -8679,7 +8680,7 @@ const compareRootGroups = (submitted, expected, out) => {
|
|
|
8679
8680
|
/** Compare cart lines/totals against a fresh menu (exact Big.js equality). */
|
|
8680
8681
|
const validateOrderAgainstMenu = (input) => {
|
|
8681
8682
|
const locale = input.locale ?? "en_us";
|
|
8682
|
-
const at = input.scheduleAt ?? /* @__PURE__ */ new Date();
|
|
8683
|
+
const at = input.scheduleAt ?? input.asOf ?? /* @__PURE__ */ new Date();
|
|
8683
8684
|
const zone = input.timeZone;
|
|
8684
8685
|
const issues = [];
|
|
8685
8686
|
const lineIssues = {};
|
|
@@ -11473,4 +11474,1793 @@ const validatePickupName = (raw, rules) => {
|
|
|
11473
11474
|
return null;
|
|
11474
11475
|
};
|
|
11475
11476
|
//#endregion
|
|
11476
|
-
|
|
11477
|
+
//#region src/state/canonical.ts
|
|
11478
|
+
/** Nesting limit for parsing and serializing, so input can't blow the stack. */
|
|
11479
|
+
const CANONICAL_MAX_DEPTH = 256;
|
|
11480
|
+
/** Largest decimal exponent accepted, so `1e999999999` can't allocate GBs. */
|
|
11481
|
+
const CANONICAL_MAX_EXPONENT = 1e3;
|
|
11482
|
+
const NUMBER_PATTERN = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?$/;
|
|
11483
|
+
const createCanonicalizationError = (code, message) => {
|
|
11484
|
+
const error = new Error(message);
|
|
11485
|
+
error.name = "CanonicalizationError";
|
|
11486
|
+
error.code = code;
|
|
11487
|
+
return error;
|
|
11488
|
+
};
|
|
11489
|
+
const isCanonicalizationError = (error) => {
|
|
11490
|
+
if (!(error instanceof Error)) return false;
|
|
11491
|
+
return error.name === "CanonicalizationError" && "code" in error;
|
|
11492
|
+
};
|
|
11493
|
+
function LosslessNumberImpl(raw) {
|
|
11494
|
+
this.raw = raw;
|
|
11495
|
+
}
|
|
11496
|
+
/** A JSON number kept as its exact text. Check with `instanceof`. */
|
|
11497
|
+
const LosslessNumber = LosslessNumberImpl;
|
|
11498
|
+
const fail = (code, message) => {
|
|
11499
|
+
throw createCanonicalizationError(code, message);
|
|
11500
|
+
};
|
|
11501
|
+
const exponentOf = (raw) => {
|
|
11502
|
+
const index = raw.search(/[eE]/);
|
|
11503
|
+
if (index < 0) return 0;
|
|
11504
|
+
return Number(raw.slice(index + 1));
|
|
11505
|
+
};
|
|
11506
|
+
/**
|
|
11507
|
+
* Exact decimal text in plain notation: no exponent, no trailing zeros and
|
|
11508
|
+
* `-0` as `0`. Never rounds.
|
|
11509
|
+
*/
|
|
11510
|
+
const canonicalNumber = (raw) => {
|
|
11511
|
+
if (!NUMBER_PATTERN.test(raw)) fail("INVALID_NUMBER", `Invalid number`);
|
|
11512
|
+
const exponent = exponentOf(raw);
|
|
11513
|
+
if (Math.abs(exponent) > 1e3) fail("NUMBER_OUT_OF_RANGE", `Exponent out of range: ${exponent}`);
|
|
11514
|
+
const fixed = new Big(raw).toFixed();
|
|
11515
|
+
if (fixed === "-0") return "0";
|
|
11516
|
+
return fixed;
|
|
11517
|
+
};
|
|
11518
|
+
const hex4 = (code) => {
|
|
11519
|
+
return ("000" + code.toString(16)).slice(-4);
|
|
11520
|
+
};
|
|
11521
|
+
const SHORT_ESCAPES = {
|
|
11522
|
+
8: "\\b",
|
|
11523
|
+
9: "\\t",
|
|
11524
|
+
10: "\\n",
|
|
11525
|
+
12: "\\f",
|
|
11526
|
+
13: "\\r",
|
|
11527
|
+
34: "\\\"",
|
|
11528
|
+
92: "\\\\"
|
|
11529
|
+
};
|
|
11530
|
+
/** RFC 8785 string serialization. Lone surrogates are rejected (I-JSON). */
|
|
11531
|
+
const canonicalString = (value) => {
|
|
11532
|
+
let out = "\"";
|
|
11533
|
+
for (let i = 0; i < value.length; i++) {
|
|
11534
|
+
const code = value.charCodeAt(i);
|
|
11535
|
+
const short = SHORT_ESCAPES[code];
|
|
11536
|
+
if (short !== void 0) {
|
|
11537
|
+
out += short;
|
|
11538
|
+
continue;
|
|
11539
|
+
}
|
|
11540
|
+
if (code < 32) {
|
|
11541
|
+
out += "\\u" + hex4(code);
|
|
11542
|
+
continue;
|
|
11543
|
+
}
|
|
11544
|
+
if (code >= 55296 && code <= 56319) {
|
|
11545
|
+
const next = value.charCodeAt(i + 1);
|
|
11546
|
+
if (!(next >= 56320 && next <= 57343)) fail("LONE_SURROGATE", "Lone surrogate in string");
|
|
11547
|
+
out += value.charAt(i) + value.charAt(i + 1);
|
|
11548
|
+
i++;
|
|
11549
|
+
continue;
|
|
11550
|
+
}
|
|
11551
|
+
if (code >= 56320 && code <= 57343) fail("LONE_SURROGATE", "Lone surrogate in string");
|
|
11552
|
+
out += value.charAt(i);
|
|
11553
|
+
}
|
|
11554
|
+
return out + "\"";
|
|
11555
|
+
};
|
|
11556
|
+
const isLosslessNumber = (value) => {
|
|
11557
|
+
return value instanceof LosslessNumber;
|
|
11558
|
+
};
|
|
11559
|
+
const jsNumberText = (value) => {
|
|
11560
|
+
if (!isFinite(value)) fail("UNSUPPORTED_VALUE", "Non-finite number");
|
|
11561
|
+
return canonicalNumber(String(value));
|
|
11562
|
+
};
|
|
11563
|
+
const serializeObject = (value, depth) => {
|
|
11564
|
+
const record = value;
|
|
11565
|
+
const keys = Object.keys(record).sort();
|
|
11566
|
+
const parts = [];
|
|
11567
|
+
for (const key of keys) {
|
|
11568
|
+
const item = record[key];
|
|
11569
|
+
if (item === void 0) continue;
|
|
11570
|
+
const text = serialize(item, depth + 1);
|
|
11571
|
+
parts.push(canonicalString(key) + ":" + text);
|
|
11572
|
+
}
|
|
11573
|
+
return "{" + parts.join(",") + "}";
|
|
11574
|
+
};
|
|
11575
|
+
const serializeArray = (value, depth) => {
|
|
11576
|
+
const parts = [];
|
|
11577
|
+
for (const item of value) {
|
|
11578
|
+
if (item === void 0) fail("UNSUPPORTED_VALUE", "undefined in array");
|
|
11579
|
+
parts.push(serialize(item, depth + 1));
|
|
11580
|
+
}
|
|
11581
|
+
return "[" + parts.join(",") + "]";
|
|
11582
|
+
};
|
|
11583
|
+
const serialize = (value, depth) => {
|
|
11584
|
+
if (depth > 256) fail("MAX_DEPTH", "Value nested too deep");
|
|
11585
|
+
if (value === null) return "null";
|
|
11586
|
+
if (value === true) return "true";
|
|
11587
|
+
if (value === false) return "false";
|
|
11588
|
+
if (typeof value === "string") return canonicalString(value);
|
|
11589
|
+
if (typeof value === "number") return jsNumberText(value);
|
|
11590
|
+
if (typeof value === "bigint") return canonicalNumber(value.toString());
|
|
11591
|
+
if (Array.isArray(value)) return serializeArray(value, depth);
|
|
11592
|
+
if (typeof value !== "object") return fail("UNSUPPORTED_VALUE", `Unsupported ${typeof value}`);
|
|
11593
|
+
if (isLosslessNumber(value)) return canonicalNumber(value.raw);
|
|
11594
|
+
const proto = Object.getPrototypeOf(value);
|
|
11595
|
+
if (proto !== Object.prototype && proto !== null) return fail("UNSUPPORTED_VALUE", "Only plain objects are supported");
|
|
11596
|
+
return serializeObject(value, depth);
|
|
11597
|
+
};
|
|
11598
|
+
/** `fs-c14n-v1` text of a value: sorted keys, no whitespace, exact numbers. */
|
|
11599
|
+
const canonicalize = (value) => {
|
|
11600
|
+
return serialize(value, 0);
|
|
11601
|
+
};
|
|
11602
|
+
const WHITESPACE = {
|
|
11603
|
+
" ": true,
|
|
11604
|
+
" ": true,
|
|
11605
|
+
"\n": true,
|
|
11606
|
+
"\r": true
|
|
11607
|
+
};
|
|
11608
|
+
const skipWhitespace = (c) => {
|
|
11609
|
+
while (c.pos < c.text.length && WHITESPACE[c.text.charAt(c.pos)]) c.pos++;
|
|
11610
|
+
};
|
|
11611
|
+
const invalid = (c) => {
|
|
11612
|
+
return fail("INVALID_JSON", `Invalid JSON at ${c.pos}`);
|
|
11613
|
+
};
|
|
11614
|
+
const expectLiteral = (c, literal) => {
|
|
11615
|
+
if (c.text.slice(c.pos, c.pos + literal.length) !== literal) invalid(c);
|
|
11616
|
+
c.pos += literal.length;
|
|
11617
|
+
};
|
|
11618
|
+
const ESCAPES = {
|
|
11619
|
+
"\"": "\"",
|
|
11620
|
+
"\\": "\\",
|
|
11621
|
+
"/": "/",
|
|
11622
|
+
b: "\b",
|
|
11623
|
+
f: "\f",
|
|
11624
|
+
n: "\n",
|
|
11625
|
+
r: "\r",
|
|
11626
|
+
t: " "
|
|
11627
|
+
};
|
|
11628
|
+
const parseHex4 = (c) => {
|
|
11629
|
+
const hex = c.text.slice(c.pos, c.pos + 4);
|
|
11630
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) invalid(c);
|
|
11631
|
+
c.pos += 4;
|
|
11632
|
+
return parseInt(hex, 16);
|
|
11633
|
+
};
|
|
11634
|
+
const parseString = (c) => {
|
|
11635
|
+
c.pos++;
|
|
11636
|
+
let out = "";
|
|
11637
|
+
while (true) {
|
|
11638
|
+
if (c.pos >= c.text.length) invalid(c);
|
|
11639
|
+
const char = c.text.charAt(c.pos);
|
|
11640
|
+
const code = c.text.charCodeAt(c.pos);
|
|
11641
|
+
if (char === "\"") {
|
|
11642
|
+
c.pos++;
|
|
11643
|
+
return out;
|
|
11644
|
+
}
|
|
11645
|
+
if (code < 32) invalid(c);
|
|
11646
|
+
if (char !== "\\") {
|
|
11647
|
+
out += char;
|
|
11648
|
+
c.pos++;
|
|
11649
|
+
continue;
|
|
11650
|
+
}
|
|
11651
|
+
const escape = c.text.charAt(c.pos + 1);
|
|
11652
|
+
c.pos += 2;
|
|
11653
|
+
if (escape === "u") {
|
|
11654
|
+
out += String.fromCharCode(parseHex4(c));
|
|
11655
|
+
continue;
|
|
11656
|
+
}
|
|
11657
|
+
const mapped = ESCAPES[escape];
|
|
11658
|
+
if (mapped === void 0) invalid(c);
|
|
11659
|
+
out += mapped;
|
|
11660
|
+
}
|
|
11661
|
+
};
|
|
11662
|
+
const parseNumber = (c) => {
|
|
11663
|
+
const start = c.pos;
|
|
11664
|
+
const rest = c.text.slice(start);
|
|
11665
|
+
const match = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(rest);
|
|
11666
|
+
if (!match || match[0].length === 0) return invalid(c);
|
|
11667
|
+
c.pos += match[0].length;
|
|
11668
|
+
return new LosslessNumber(match[0]);
|
|
11669
|
+
};
|
|
11670
|
+
const parseArray = (c, depth) => {
|
|
11671
|
+
c.pos++;
|
|
11672
|
+
const out = [];
|
|
11673
|
+
skipWhitespace(c);
|
|
11674
|
+
if (c.text.charAt(c.pos) === "]") {
|
|
11675
|
+
c.pos++;
|
|
11676
|
+
return out;
|
|
11677
|
+
}
|
|
11678
|
+
while (true) {
|
|
11679
|
+
out.push(parseValue(c, depth + 1));
|
|
11680
|
+
skipWhitespace(c);
|
|
11681
|
+
const char = c.text.charAt(c.pos);
|
|
11682
|
+
c.pos++;
|
|
11683
|
+
if (char === "]") return out;
|
|
11684
|
+
if (char !== ",") invalid(c);
|
|
11685
|
+
}
|
|
11686
|
+
};
|
|
11687
|
+
const parseObject = (c, depth) => {
|
|
11688
|
+
c.pos++;
|
|
11689
|
+
const out = Object.create(null);
|
|
11690
|
+
skipWhitespace(c);
|
|
11691
|
+
if (c.text.charAt(c.pos) === "}") {
|
|
11692
|
+
c.pos++;
|
|
11693
|
+
return out;
|
|
11694
|
+
}
|
|
11695
|
+
while (true) {
|
|
11696
|
+
skipWhitespace(c);
|
|
11697
|
+
if (c.text.charAt(c.pos) !== "\"") invalid(c);
|
|
11698
|
+
const key = parseString(c);
|
|
11699
|
+
if (Object.prototype.hasOwnProperty.call(out, key)) fail("DUPLICATE_KEY", `Duplicate key ${JSON.stringify(key)}`);
|
|
11700
|
+
skipWhitespace(c);
|
|
11701
|
+
if (c.text.charAt(c.pos) !== ":") invalid(c);
|
|
11702
|
+
c.pos++;
|
|
11703
|
+
out[key] = parseValue(c, depth + 1);
|
|
11704
|
+
skipWhitespace(c);
|
|
11705
|
+
const char = c.text.charAt(c.pos);
|
|
11706
|
+
c.pos++;
|
|
11707
|
+
if (char === "}") return out;
|
|
11708
|
+
if (char !== ",") invalid(c);
|
|
11709
|
+
}
|
|
11710
|
+
};
|
|
11711
|
+
const LITERALS = {
|
|
11712
|
+
t: {
|
|
11713
|
+
text: "true",
|
|
11714
|
+
value: true
|
|
11715
|
+
},
|
|
11716
|
+
f: {
|
|
11717
|
+
text: "false",
|
|
11718
|
+
value: false
|
|
11719
|
+
},
|
|
11720
|
+
n: {
|
|
11721
|
+
text: "null",
|
|
11722
|
+
value: null
|
|
11723
|
+
}
|
|
11724
|
+
};
|
|
11725
|
+
const parseValue = (c, depth) => {
|
|
11726
|
+
if (depth > 256) fail("MAX_DEPTH", "JSON nested too deep");
|
|
11727
|
+
skipWhitespace(c);
|
|
11728
|
+
const char = c.text.charAt(c.pos);
|
|
11729
|
+
if (char === "{") return parseObject(c, depth);
|
|
11730
|
+
if (char === "[") return parseArray(c, depth);
|
|
11731
|
+
if (char === "\"") return parseString(c);
|
|
11732
|
+
const literal = LITERALS[char];
|
|
11733
|
+
if (literal === void 0) return parseNumber(c);
|
|
11734
|
+
expectLiteral(c, literal.text);
|
|
11735
|
+
return literal.value;
|
|
11736
|
+
};
|
|
11737
|
+
/**
|
|
11738
|
+
* Parses JSON text keeping every number as its exact decimal text
|
|
11739
|
+
* (`LosslessNumber`). Objects have no prototype, so `__proto__` is a key.
|
|
11740
|
+
*/
|
|
11741
|
+
const parseLosslessJson = (text) => {
|
|
11742
|
+
const cursor = {
|
|
11743
|
+
text,
|
|
11744
|
+
pos: 0
|
|
11745
|
+
};
|
|
11746
|
+
const value = parseValue(cursor, 0);
|
|
11747
|
+
skipWhitespace(cursor);
|
|
11748
|
+
if (cursor.pos !== text.length) invalid(cursor);
|
|
11749
|
+
return value;
|
|
11750
|
+
};
|
|
11751
|
+
/** Canonical text of JSON text, without ever going through JS numbers. */
|
|
11752
|
+
const canonicalizeJson = (text) => {
|
|
11753
|
+
return canonicalize(parseLosslessJson(text));
|
|
11754
|
+
};
|
|
11755
|
+
//#endregion
|
|
11756
|
+
//#region src/state/sha256.ts
|
|
11757
|
+
const K = [
|
|
11758
|
+
1116352408,
|
|
11759
|
+
1899447441,
|
|
11760
|
+
3049323471,
|
|
11761
|
+
3921009573,
|
|
11762
|
+
961987163,
|
|
11763
|
+
1508970993,
|
|
11764
|
+
2453635748,
|
|
11765
|
+
2870763221,
|
|
11766
|
+
3624381080,
|
|
11767
|
+
310598401,
|
|
11768
|
+
607225278,
|
|
11769
|
+
1426881987,
|
|
11770
|
+
1925078388,
|
|
11771
|
+
2162078206,
|
|
11772
|
+
2614888103,
|
|
11773
|
+
3248222580,
|
|
11774
|
+
3835390401,
|
|
11775
|
+
4022224774,
|
|
11776
|
+
264347078,
|
|
11777
|
+
604807628,
|
|
11778
|
+
770255983,
|
|
11779
|
+
1249150122,
|
|
11780
|
+
1555081692,
|
|
11781
|
+
1996064986,
|
|
11782
|
+
2554220882,
|
|
11783
|
+
2821834349,
|
|
11784
|
+
2952996808,
|
|
11785
|
+
3210313671,
|
|
11786
|
+
3336571891,
|
|
11787
|
+
3584528711,
|
|
11788
|
+
113926993,
|
|
11789
|
+
338241895,
|
|
11790
|
+
666307205,
|
|
11791
|
+
773529912,
|
|
11792
|
+
1294757372,
|
|
11793
|
+
1396182291,
|
|
11794
|
+
1695183700,
|
|
11795
|
+
1986661051,
|
|
11796
|
+
2177026350,
|
|
11797
|
+
2456956037,
|
|
11798
|
+
2730485921,
|
|
11799
|
+
2820302411,
|
|
11800
|
+
3259730800,
|
|
11801
|
+
3345764771,
|
|
11802
|
+
3516065817,
|
|
11803
|
+
3600352804,
|
|
11804
|
+
4094571909,
|
|
11805
|
+
275423344,
|
|
11806
|
+
430227734,
|
|
11807
|
+
506948616,
|
|
11808
|
+
659060556,
|
|
11809
|
+
883997877,
|
|
11810
|
+
958139571,
|
|
11811
|
+
1322822218,
|
|
11812
|
+
1537002063,
|
|
11813
|
+
1747873779,
|
|
11814
|
+
1955562222,
|
|
11815
|
+
2024104815,
|
|
11816
|
+
2227730452,
|
|
11817
|
+
2361852424,
|
|
11818
|
+
2428436474,
|
|
11819
|
+
2756734187,
|
|
11820
|
+
3204031479,
|
|
11821
|
+
3329325298
|
|
11822
|
+
];
|
|
11823
|
+
const INITIAL = [
|
|
11824
|
+
1779033703,
|
|
11825
|
+
3144134277,
|
|
11826
|
+
1013904242,
|
|
11827
|
+
2773480762,
|
|
11828
|
+
1359893119,
|
|
11829
|
+
2600822924,
|
|
11830
|
+
528734635,
|
|
11831
|
+
1541459225
|
|
11832
|
+
];
|
|
11833
|
+
/** UTF-8 bytes of a well-formed string. No `TextEncoder`, so Hermes-safe. */
|
|
11834
|
+
const utf8Encode = (value) => {
|
|
11835
|
+
const bytes = [];
|
|
11836
|
+
for (let i = 0; i < value.length; i++) {
|
|
11837
|
+
let code = value.charCodeAt(i);
|
|
11838
|
+
if (code >= 55296 && code <= 56319) {
|
|
11839
|
+
const next = value.charCodeAt(i + 1);
|
|
11840
|
+
if (!(next >= 56320 && next <= 57343)) throw createCanonicalizationError("LONE_SURROGATE", "Lone surrogate");
|
|
11841
|
+
code = 65536 + (code - 55296 << 10) + (next - 56320);
|
|
11842
|
+
i++;
|
|
11843
|
+
} else if (code >= 56320 && code <= 57343) throw createCanonicalizationError("LONE_SURROGATE", "Lone surrogate");
|
|
11844
|
+
if (code < 128) bytes.push(code);
|
|
11845
|
+
else if (code < 2048) bytes.push(192 | code >> 6, 128 | code & 63);
|
|
11846
|
+
else if (code < 65536) {
|
|
11847
|
+
const b1 = 224 | code >> 12;
|
|
11848
|
+
bytes.push(b1, 128 | code >> 6 & 63, 128 | code & 63);
|
|
11849
|
+
} else {
|
|
11850
|
+
const b1 = 240 | code >> 18;
|
|
11851
|
+
const b2 = 128 | code >> 12 & 63;
|
|
11852
|
+
bytes.push(b1, b2, 128 | code >> 6 & 63, 128 | code & 63);
|
|
11853
|
+
}
|
|
11854
|
+
}
|
|
11855
|
+
return bytes;
|
|
11856
|
+
};
|
|
11857
|
+
const rotr = (x, n) => x >>> n | x << 32 - n;
|
|
11858
|
+
/** Reads a word that is always in range; keeps `noUncheckedIndexedAccess` quiet. */
|
|
11859
|
+
const at = (words, i) => words[i];
|
|
11860
|
+
const compress = (h, w) => {
|
|
11861
|
+
for (let t = 16; t < 64; t++) {
|
|
11862
|
+
const x = at(w, t - 15);
|
|
11863
|
+
const y = at(w, t - 2);
|
|
11864
|
+
const s0 = rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
|
|
11865
|
+
const s1 = rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10;
|
|
11866
|
+
w[t] = at(w, t - 16) + s0 + at(w, t - 7) + s1 | 0;
|
|
11867
|
+
}
|
|
11868
|
+
let a = at(h, 0);
|
|
11869
|
+
let b = at(h, 1);
|
|
11870
|
+
let c = at(h, 2);
|
|
11871
|
+
let d = at(h, 3);
|
|
11872
|
+
let e = at(h, 4);
|
|
11873
|
+
let f = at(h, 5);
|
|
11874
|
+
let g = at(h, 6);
|
|
11875
|
+
let hh = at(h, 7);
|
|
11876
|
+
for (let t = 0; t < 64; t++) {
|
|
11877
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
11878
|
+
const ch = e & f ^ ~e & g;
|
|
11879
|
+
const t1 = hh + s1 + ch + at(K, t) + at(w, t) | 0;
|
|
11880
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) | 0;
|
|
11881
|
+
hh = g;
|
|
11882
|
+
g = f;
|
|
11883
|
+
f = e;
|
|
11884
|
+
e = d + t1 | 0;
|
|
11885
|
+
d = c;
|
|
11886
|
+
c = b;
|
|
11887
|
+
b = a;
|
|
11888
|
+
a = t1 + t2 | 0;
|
|
11889
|
+
}
|
|
11890
|
+
const next = [
|
|
11891
|
+
a,
|
|
11892
|
+
b,
|
|
11893
|
+
c,
|
|
11894
|
+
d,
|
|
11895
|
+
e,
|
|
11896
|
+
f,
|
|
11897
|
+
g,
|
|
11898
|
+
hh
|
|
11899
|
+
];
|
|
11900
|
+
for (let i = 0; i < 8; i++) h[i] = at(h, i) + at(next, i) | 0;
|
|
11901
|
+
};
|
|
11902
|
+
const toHex = (h) => {
|
|
11903
|
+
let out = "";
|
|
11904
|
+
for (const word of h) out += ("0000000" + (word >>> 0).toString(16)).slice(-8);
|
|
11905
|
+
return out;
|
|
11906
|
+
};
|
|
11907
|
+
/** Lowercase hex SHA-256 of bytes (FIPS 180-4), in plain JS. */
|
|
11908
|
+
const sha256Hex = (bytes) => {
|
|
11909
|
+
const h = INITIAL.slice();
|
|
11910
|
+
const length = bytes.length;
|
|
11911
|
+
const padded = length + 9 + 63 >> 6 << 6;
|
|
11912
|
+
const w = new Array(64);
|
|
11913
|
+
for (let block = 0; block < padded; block += 64) {
|
|
11914
|
+
for (let t = 0; t < 16; t++) {
|
|
11915
|
+
let word = 0;
|
|
11916
|
+
for (let k = 0; k < 4; k++) {
|
|
11917
|
+
const i = block + t * 4 + k;
|
|
11918
|
+
let byte = 0;
|
|
11919
|
+
if (i < length) byte = at(bytes, i) & 255;
|
|
11920
|
+
else if (i === length) byte = 128;
|
|
11921
|
+
else if (i >= padded - 8) byte = lengthByte(length, padded - 1 - i);
|
|
11922
|
+
word = word << 8 | byte;
|
|
11923
|
+
}
|
|
11924
|
+
w[t] = word;
|
|
11925
|
+
}
|
|
11926
|
+
compress(h, w);
|
|
11927
|
+
}
|
|
11928
|
+
return toHex(h);
|
|
11929
|
+
};
|
|
11930
|
+
/** Byte `index` (0 = least significant) of the message length in bits. */
|
|
11931
|
+
const lengthByte = (length, index) => {
|
|
11932
|
+
const bits = length * 8;
|
|
11933
|
+
return Math.floor(bits / Math.pow(2, index * 8)) & 255;
|
|
11934
|
+
};
|
|
11935
|
+
/** Lowercase hex SHA-256 of the UTF-8 bytes of a string. */
|
|
11936
|
+
const sha256HexOfString = (value) => {
|
|
11937
|
+
return sha256Hex(utf8Encode(value));
|
|
11938
|
+
};
|
|
11939
|
+
//#endregion
|
|
11940
|
+
//#region src/state/hash.ts
|
|
11941
|
+
const STATE_ALGO = "fs-c14n-v1";
|
|
11942
|
+
const STATE_HASH_PREFIX = "sha256:";
|
|
11943
|
+
const HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
11944
|
+
const isStateHash = (value) => HASH_PATTERN.test(value);
|
|
11945
|
+
/** Sorted, deduplicated copy of a scope, the only form ever hashed. */
|
|
11946
|
+
const normalizeStateScope = (scope) => {
|
|
11947
|
+
const unique = Object.create(null);
|
|
11948
|
+
for (const id of scope.channel_ids) unique[id] = true;
|
|
11949
|
+
const channelIds = Object.keys(unique).sort();
|
|
11950
|
+
const { merchant_id, env, store_id } = scope;
|
|
11951
|
+
return {
|
|
11952
|
+
merchant_id,
|
|
11953
|
+
env,
|
|
11954
|
+
store_id,
|
|
11955
|
+
channel_ids: channelIds
|
|
11956
|
+
};
|
|
11957
|
+
};
|
|
11958
|
+
/** `sha256(canonical(scope))`, written `sha256:<hex>`. */
|
|
11959
|
+
const stateScopeKey = (scope) => {
|
|
11960
|
+
const text = canonicalize({ ...normalizeStateScope(scope) });
|
|
11961
|
+
return STATE_HASH_PREFIX + sha256HexOfString(text);
|
|
11962
|
+
};
|
|
11963
|
+
/** `sha256("fs-c14n-v1\n" + name + "\n" + canonical)`, written `sha256:<hex>`. */
|
|
11964
|
+
const stateSectionHash = (name, canonical) => {
|
|
11965
|
+
const text = "fs-c14n-v1\n" + name + "\n" + canonical;
|
|
11966
|
+
return STATE_HASH_PREFIX + sha256HexOfString(text);
|
|
11967
|
+
};
|
|
11968
|
+
/** Hash of a section from raw JSON text, keeping every number exact. */
|
|
11969
|
+
const stateSectionHashOfJson = (name, json) => {
|
|
11970
|
+
return stateSectionHash(name, canonicalizeJson(json));
|
|
11971
|
+
};
|
|
11972
|
+
/** `sha256(canonical({algo, scope_key, sections}))`, written `sha256:<hex>`. */
|
|
11973
|
+
const stateRootHash = (input) => {
|
|
11974
|
+
const { algo, scopeKey, sections } = input;
|
|
11975
|
+
const text = canonicalize({
|
|
11976
|
+
algo,
|
|
11977
|
+
scope_key: scopeKey,
|
|
11978
|
+
sections
|
|
11979
|
+
});
|
|
11980
|
+
return STATE_HASH_PREFIX + sha256HexOfString(text);
|
|
11981
|
+
};
|
|
11982
|
+
//#endregion
|
|
11983
|
+
//#region src/state/goldenVectors.ts
|
|
11984
|
+
const errorCodeOf = (error) => {
|
|
11985
|
+
if (isCanonicalizationError(error)) return error.code;
|
|
11986
|
+
return String(error);
|
|
11987
|
+
};
|
|
11988
|
+
const runVector = (vector, fails) => {
|
|
11989
|
+
const { name } = vector;
|
|
11990
|
+
let canonical;
|
|
11991
|
+
try {
|
|
11992
|
+
canonical = canonicalizeJson(vector.input);
|
|
11993
|
+
} catch (error) {
|
|
11994
|
+
const actual = `error:${errorCodeOf(error)}`;
|
|
11995
|
+
const expected = vector.error ? `error:${vector.error}` : "no error";
|
|
11996
|
+
if (actual !== expected) fails.push({
|
|
11997
|
+
name,
|
|
11998
|
+
expected,
|
|
11999
|
+
actual
|
|
12000
|
+
});
|
|
12001
|
+
return;
|
|
12002
|
+
}
|
|
12003
|
+
if (vector.error) {
|
|
12004
|
+
const expected = `error:${vector.error}`;
|
|
12005
|
+
fails.push({
|
|
12006
|
+
name,
|
|
12007
|
+
expected,
|
|
12008
|
+
actual: canonical
|
|
12009
|
+
});
|
|
12010
|
+
return;
|
|
12011
|
+
}
|
|
12012
|
+
if (canonical !== vector.canonical) {
|
|
12013
|
+
const expected = vector.canonical ?? "";
|
|
12014
|
+
fails.push({
|
|
12015
|
+
name,
|
|
12016
|
+
expected,
|
|
12017
|
+
actual: canonical
|
|
12018
|
+
});
|
|
12019
|
+
return;
|
|
12020
|
+
}
|
|
12021
|
+
const hash = stateSectionHash(vector.section ?? "vector", canonical);
|
|
12022
|
+
if (hash !== vector.hash) {
|
|
12023
|
+
const expected = vector.hash ?? "";
|
|
12024
|
+
fails.push({
|
|
12025
|
+
name: `${name}#hash`,
|
|
12026
|
+
expected,
|
|
12027
|
+
actual: hash
|
|
12028
|
+
});
|
|
12029
|
+
}
|
|
12030
|
+
};
|
|
12031
|
+
/**
|
|
12032
|
+
* Checks every `fs-c14n-v1` golden vector and returns the failures. Shared by
|
|
12033
|
+
* the Node tests and the Hermes runner, so all runtimes check the same file.
|
|
12034
|
+
*/
|
|
12035
|
+
const runStateGoldenVectors = (file) => {
|
|
12036
|
+
const fails = [];
|
|
12037
|
+
for (const vector of file.vectors) runVector(vector, fails);
|
|
12038
|
+
for (const root of file.roots) {
|
|
12039
|
+
const scopeKey = stateScopeKey(root.scope);
|
|
12040
|
+
if (scopeKey !== root.scope_key) {
|
|
12041
|
+
const p1 = {
|
|
12042
|
+
expected: root.scope_key,
|
|
12043
|
+
actual: scopeKey
|
|
12044
|
+
};
|
|
12045
|
+
fails.push({
|
|
12046
|
+
name: `${root.name}#scope_key`,
|
|
12047
|
+
...p1
|
|
12048
|
+
});
|
|
12049
|
+
}
|
|
12050
|
+
const rootHash = stateRootHash({
|
|
12051
|
+
algo: file.algo,
|
|
12052
|
+
scopeKey,
|
|
12053
|
+
sections: root.sections
|
|
12054
|
+
});
|
|
12055
|
+
if (rootHash !== root.root_hash) {
|
|
12056
|
+
const p3 = {
|
|
12057
|
+
expected: root.root_hash,
|
|
12058
|
+
actual: rootHash
|
|
12059
|
+
};
|
|
12060
|
+
fails.push({
|
|
12061
|
+
name: `${root.name}#root`,
|
|
12062
|
+
...p3
|
|
12063
|
+
});
|
|
12064
|
+
}
|
|
12065
|
+
}
|
|
12066
|
+
return fails;
|
|
12067
|
+
};
|
|
12068
|
+
//#endregion
|
|
12069
|
+
//#region src/rules/orderFacts.ts
|
|
12070
|
+
const unique = (values) => [...new Set(values)];
|
|
12071
|
+
/**
|
|
12072
|
+
* Payment facts from the live tenders of the current intent (§7.4).
|
|
12073
|
+
* `collect_ats` / `is_mixed` read real tenders only; `methods` / `ids` also
|
|
12074
|
+
* read `REDEMPTION` tenders so conditions can target them. The singular
|
|
12075
|
+
* fields are the primary tender, for conditions written before mixed payments.
|
|
12076
|
+
*/
|
|
12077
|
+
const paymentFacts = (order) => {
|
|
12078
|
+
const intents = order.payment_intents ?? [];
|
|
12079
|
+
const intent = currentIntent(intents);
|
|
12080
|
+
const tenders = liveRealTenders(intents);
|
|
12081
|
+
const live = liveTenders(intent);
|
|
12082
|
+
const primary = primaryTender(intent) ?? tenders[0];
|
|
12083
|
+
const status = intent ? derivePaymentStatus(intent) : order.payment_status;
|
|
12084
|
+
const collect_ats = unique(tenders.map((tender) => tender.collect_at));
|
|
12085
|
+
const methods = unique(live.map((tender) => tender.method));
|
|
12086
|
+
const paymentIds = live.map((tender) => tender.payment_id ?? "");
|
|
12087
|
+
const ids = unique(paymentIds.filter(Boolean));
|
|
12088
|
+
const is_mixed = isMixedTenders(tenders);
|
|
12089
|
+
const captured = live.some((tender) => tender.status === "PAID");
|
|
12090
|
+
const p1 = {
|
|
12091
|
+
id: primary?.payment_id,
|
|
12092
|
+
method: primary?.method
|
|
12093
|
+
};
|
|
12094
|
+
const p2 = {
|
|
12095
|
+
collect_at: primary?.collect_at,
|
|
12096
|
+
status,
|
|
12097
|
+
ids
|
|
12098
|
+
};
|
|
12099
|
+
return {
|
|
12100
|
+
...p1,
|
|
12101
|
+
...p2,
|
|
12102
|
+
collect_ats,
|
|
12103
|
+
methods,
|
|
12104
|
+
is_mixed,
|
|
12105
|
+
captured
|
|
12106
|
+
};
|
|
12107
|
+
};
|
|
12108
|
+
const orderFactsFromOrder = (order) => {
|
|
12109
|
+
const lines = (order.lines ?? []).map((line) => {
|
|
12110
|
+
return {
|
|
12111
|
+
id: line.id,
|
|
12112
|
+
quantity: line.quantity
|
|
12113
|
+
};
|
|
12114
|
+
});
|
|
12115
|
+
const brand_id = order.brand_id ?? void 0;
|
|
12116
|
+
const b1 = {
|
|
12117
|
+
total: order.totals.total,
|
|
12118
|
+
is_anonymous: order.is_anonymous
|
|
12119
|
+
};
|
|
12120
|
+
const b2 = {
|
|
12121
|
+
store_id: order.store_id,
|
|
12122
|
+
channel_id: order.channel_id
|
|
12123
|
+
};
|
|
12124
|
+
const b3 = {
|
|
12125
|
+
fulfillment_id: order.fulfillment_id,
|
|
12126
|
+
brand_id,
|
|
12127
|
+
lines
|
|
12128
|
+
};
|
|
12129
|
+
const scheduled_at = order.scheduled_at ?? null;
|
|
12130
|
+
const orderScope = {
|
|
12131
|
+
...b1,
|
|
12132
|
+
...b2,
|
|
12133
|
+
...b3,
|
|
12134
|
+
scheduled_at
|
|
12135
|
+
};
|
|
12136
|
+
const dob = (order.customer?.customer_info)?.dob ?? void 0;
|
|
12137
|
+
return {
|
|
12138
|
+
order: orderScope,
|
|
12139
|
+
customer: {
|
|
12140
|
+
is_anonymous: order.is_anonymous,
|
|
12141
|
+
dob
|
|
12142
|
+
},
|
|
12143
|
+
payment: paymentFacts(order)
|
|
12144
|
+
};
|
|
12145
|
+
};
|
|
12146
|
+
const buildRulesEngineFromOrder = (order) => {
|
|
12147
|
+
return new RulesEngine(orderFactsFromOrder(order));
|
|
12148
|
+
};
|
|
12149
|
+
//#endregion
|
|
12150
|
+
//#region src/fulfillment/status.ts
|
|
12151
|
+
/** `injecting` / ` Injecting ` → `INJECTING`. Casing never matters. */
|
|
12152
|
+
const normalizeFulfillmentStatus = (status) => {
|
|
12153
|
+
return status.trim().toUpperCase();
|
|
12154
|
+
};
|
|
12155
|
+
const fulfillmentStatusesEqual = (left, right) => {
|
|
12156
|
+
return normalizeFulfillmentStatus(left) === normalizeFulfillmentStatus(right);
|
|
12157
|
+
};
|
|
12158
|
+
/** Edge path kind is derived from the target: default, or terminal outcome. */
|
|
12159
|
+
const pathKindForTargetNode = (target) => {
|
|
12160
|
+
if (!target || target.kind !== "terminal") return "default";
|
|
12161
|
+
const status = normalizeFulfillmentStatus(target.mappedStatus ?? "");
|
|
12162
|
+
if (status === "VOIDED") return "cancel";
|
|
12163
|
+
if (status === "REFUNDED" || status === "RETURNED") return "refund";
|
|
12164
|
+
if (status === "REVERSED") return "refund";
|
|
12165
|
+
return "success";
|
|
12166
|
+
};
|
|
12167
|
+
//#endregion
|
|
12168
|
+
//#region src/fulfillment/graph.ts
|
|
12169
|
+
const isPrimaryPathKind = (pathKind) => {
|
|
12170
|
+
return pathKind === "default" || pathKind === "success" || pathKind == null;
|
|
12171
|
+
};
|
|
12172
|
+
const edgePathKind = (edge, target) => {
|
|
12173
|
+
return edge.data?.pathKind ?? pathKindForTargetNode(target?.data);
|
|
12174
|
+
};
|
|
12175
|
+
const findNodeById = (workflow, nodeId) => {
|
|
12176
|
+
return workflow.nodes.find((node) => node.id === nodeId) ?? null;
|
|
12177
|
+
};
|
|
12178
|
+
const findStartNode = (workflow) => {
|
|
12179
|
+
return workflow.nodes.find((node) => node.data.kind === "start") ?? null;
|
|
12180
|
+
};
|
|
12181
|
+
const outgoingEdges = (workflow, nodeId) => {
|
|
12182
|
+
return workflow.edges.filter((edge) => edge.source === nodeId);
|
|
12183
|
+
};
|
|
12184
|
+
const incomingEdges = (workflow, nodeId) => {
|
|
12185
|
+
return workflow.edges.filter((edge) => edge.target === nodeId);
|
|
12186
|
+
};
|
|
12187
|
+
const defaultOutgoingEdge = (workflow, nodeId) => {
|
|
12188
|
+
const outgoing = outgoingEdges(workflow, nodeId);
|
|
12189
|
+
return outgoing.find((edge) => {
|
|
12190
|
+
const target = findNodeById(workflow, edge.target);
|
|
12191
|
+
return isPrimaryPathKind(edgePathKind(edge, target));
|
|
12192
|
+
}) ?? outgoing[0] ?? null;
|
|
12193
|
+
};
|
|
12194
|
+
const findFirstState = (workflow) => {
|
|
12195
|
+
const start = findStartNode(workflow);
|
|
12196
|
+
if (!start) return null;
|
|
12197
|
+
const visited = /* @__PURE__ */ new Set();
|
|
12198
|
+
let current = start;
|
|
12199
|
+
while (current && !visited.has(current.id)) {
|
|
12200
|
+
visited.add(current.id);
|
|
12201
|
+
if (current.data.kind === "state") return current;
|
|
12202
|
+
if (current.data.kind === "terminal") return current;
|
|
12203
|
+
if (current.data.kind === "join") return current;
|
|
12204
|
+
const edge = defaultOutgoingEdge(workflow, current.id);
|
|
12205
|
+
if (!edge) return current;
|
|
12206
|
+
current = findNodeById(workflow, edge.target);
|
|
12207
|
+
}
|
|
12208
|
+
return current;
|
|
12209
|
+
};
|
|
12210
|
+
const canEnterJoin = (workflow, node) => {
|
|
12211
|
+
if (node.data.kind !== "join") return true;
|
|
12212
|
+
const incoming = incomingEdges(workflow, node.id);
|
|
12213
|
+
if (incoming.length === 0) return true;
|
|
12214
|
+
const taken = incoming.filter((edge) => edge.data?.taken_at);
|
|
12215
|
+
if ((node.data.joinPolicy ?? "all") === "any") return taken.length > 0;
|
|
12216
|
+
return taken.length === incoming.length;
|
|
12217
|
+
};
|
|
12218
|
+
const edgeMatchesConditions = (edge, order, engine) => {
|
|
12219
|
+
const conditions = edge.data?.conditions ?? [];
|
|
12220
|
+
if (conditions.length === 0) return true;
|
|
12221
|
+
try {
|
|
12222
|
+
const rules = engine ?? buildRulesEngineFromOrder(order);
|
|
12223
|
+
return Boolean(rules.matchOrConditions(conditions).match);
|
|
12224
|
+
} catch {
|
|
12225
|
+
return false;
|
|
12226
|
+
}
|
|
12227
|
+
};
|
|
12228
|
+
/** Unused primary outs whose conditions match the order (Door fork, etc.). */
|
|
12229
|
+
const matchingPrimaryOutgoing = (input) => {
|
|
12230
|
+
const { workflow, nodeId, order, outgoingBySource } = input;
|
|
12231
|
+
const unused = unusedOutgoing(workflow, nodeId, outgoingBySource);
|
|
12232
|
+
let engine;
|
|
12233
|
+
const matches = [];
|
|
12234
|
+
for (const edge of unused) {
|
|
12235
|
+
const node = input.nodesById?.get(edge.target) ?? findNodeById(workflow, edge.target);
|
|
12236
|
+
if (!isPrimaryPathKind(edgePathKind(edge, node))) continue;
|
|
12237
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12238
|
+
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
12239
|
+
matches.push(edge);
|
|
12240
|
+
}
|
|
12241
|
+
return matches;
|
|
12242
|
+
};
|
|
12243
|
+
/** Unused primary outs only (cancel/refund siblings do not keep a head alive). */
|
|
12244
|
+
const unusedPrimaryOutgoing = (workflow, nodeId, outgoingBySource, nodesById) => {
|
|
12245
|
+
return unusedOutgoing(workflow, nodeId, outgoingBySource).filter((edge) => {
|
|
12246
|
+
const node = nodesById?.get(edge.target) ?? findNodeById(workflow, edge.target);
|
|
12247
|
+
return isPrimaryPathKind(edgePathKind(edge, node));
|
|
12248
|
+
});
|
|
12249
|
+
};
|
|
12250
|
+
const leftoverPrimaryOutgoing = (input) => {
|
|
12251
|
+
const { workflow, nodeId, order, outgoingBySource, nodesById } = input;
|
|
12252
|
+
if (order) return matchingPrimaryOutgoing({
|
|
12253
|
+
workflow,
|
|
12254
|
+
nodeId,
|
|
12255
|
+
order,
|
|
12256
|
+
outgoingBySource,
|
|
12257
|
+
nodesById
|
|
12258
|
+
});
|
|
12259
|
+
return unusedPrimaryOutgoing(workflow, nodeId, outgoingBySource, nodesById);
|
|
12260
|
+
};
|
|
12261
|
+
const indexOutgoingBySource = (workflow) => {
|
|
12262
|
+
const bySource = /* @__PURE__ */ new Map();
|
|
12263
|
+
for (const edge of workflow.edges) {
|
|
12264
|
+
const list = bySource.get(edge.source);
|
|
12265
|
+
if (list) list.push(edge);
|
|
12266
|
+
else bySource.set(edge.source, [edge]);
|
|
12267
|
+
}
|
|
12268
|
+
return bySource;
|
|
12269
|
+
};
|
|
12270
|
+
const unusedOutgoing = (workflow, nodeId, outgoingBySource) => {
|
|
12271
|
+
return (outgoingBySource?.get(nodeId) ?? outgoingEdges(workflow, nodeId)).filter((edge) => !edge.data?.taken_at);
|
|
12272
|
+
};
|
|
12273
|
+
/** First edge wins; every edge into that same target travels with it. */
|
|
12274
|
+
const pickAdvanceTarget = (edges) => {
|
|
12275
|
+
const first = edges[0];
|
|
12276
|
+
if (!first) return null;
|
|
12277
|
+
const matching = edges.filter((edge) => edge.target === first.target);
|
|
12278
|
+
return {
|
|
12279
|
+
targetId: first.target,
|
|
12280
|
+
edgeIds: matching.map((edge) => edge.id)
|
|
12281
|
+
};
|
|
12282
|
+
};
|
|
12283
|
+
const resolveAdvanceEdges = (input) => {
|
|
12284
|
+
const { workflow, currentNodeIds, fulfillmentStatus, order } = input;
|
|
12285
|
+
if (currentNodeIds.length === 0) return [];
|
|
12286
|
+
const current = new Set(currentNodeIds);
|
|
12287
|
+
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12288
|
+
const outgoingBySource = /* @__PURE__ */ new Map();
|
|
12289
|
+
for (const edge of workflow.edges) {
|
|
12290
|
+
if (!current.has(edge.source)) continue;
|
|
12291
|
+
const list = outgoingBySource.get(edge.source);
|
|
12292
|
+
if (list) list.push(edge);
|
|
12293
|
+
else outgoingBySource.set(edge.source, [edge]);
|
|
12294
|
+
}
|
|
12295
|
+
let engine;
|
|
12296
|
+
const matches = [];
|
|
12297
|
+
for (const id of currentNodeIds) {
|
|
12298
|
+
const outgoing = outgoingBySource.get(id);
|
|
12299
|
+
if (!outgoing) continue;
|
|
12300
|
+
for (const edge of outgoing) {
|
|
12301
|
+
if (edge.data?.taken_at) continue;
|
|
12302
|
+
const target = nodesById.get(edge.target);
|
|
12303
|
+
if (!target) continue;
|
|
12304
|
+
const mapped = target.data.mappedStatus;
|
|
12305
|
+
if (!fulfillmentStatusesEqual(mapped, fulfillmentStatus)) continue;
|
|
12306
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12307
|
+
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
12308
|
+
matches.push(edge);
|
|
12309
|
+
}
|
|
12310
|
+
}
|
|
12311
|
+
return matches;
|
|
12312
|
+
};
|
|
12313
|
+
const findMappedStatusNode = (workflow, status) => {
|
|
12314
|
+
const terminal = workflow.nodes.find((node) => {
|
|
12315
|
+
if (node.data.kind !== "terminal") return false;
|
|
12316
|
+
return fulfillmentStatusesEqual(node.data.mappedStatus, status);
|
|
12317
|
+
});
|
|
12318
|
+
if (terminal) return terminal;
|
|
12319
|
+
return workflow.nodes.find((node) => {
|
|
12320
|
+
return fulfillmentStatusesEqual(node.data.mappedStatus, status);
|
|
12321
|
+
}) ?? null;
|
|
12322
|
+
};
|
|
12323
|
+
const isTerminalMappedStatus = (workflow, status) => {
|
|
12324
|
+
return workflow.nodes.some((node) => {
|
|
12325
|
+
if (node.data.kind !== "terminal") return false;
|
|
12326
|
+
return fulfillmentStatusesEqual(node.data.mappedStatus, status);
|
|
12327
|
+
});
|
|
12328
|
+
};
|
|
12329
|
+
/** Unused primary outs are only success terminals — ready to auto-enter. */
|
|
12330
|
+
const resolveSuccessTerminalEdges = (input) => {
|
|
12331
|
+
const { workflow, currentNodeIds, order } = input;
|
|
12332
|
+
if (currentNodeIds.length === 0) return [];
|
|
12333
|
+
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12334
|
+
const outgoingBySource = indexOutgoingBySource(workflow);
|
|
12335
|
+
const edges = [];
|
|
12336
|
+
for (const id of currentNodeIds) {
|
|
12337
|
+
const sitting = nodesById.get(id);
|
|
12338
|
+
if (!sitting || sitting.data.exited_at) continue;
|
|
12339
|
+
if (sitting.data.kind === "terminal") continue;
|
|
12340
|
+
const matches = matchingPrimaryOutgoing({
|
|
12341
|
+
workflow,
|
|
12342
|
+
nodeId: id,
|
|
12343
|
+
order,
|
|
12344
|
+
outgoingBySource,
|
|
12345
|
+
nodesById
|
|
12346
|
+
});
|
|
12347
|
+
if (matches.length === 0) return [];
|
|
12348
|
+
for (const edge of matches) {
|
|
12349
|
+
const target = nodesById.get(edge.target);
|
|
12350
|
+
if (target?.data.kind !== "terminal") return [];
|
|
12351
|
+
const inferred = pathKindForTargetNode(target.data);
|
|
12352
|
+
const pathKind = edge.data?.pathKind ?? inferred;
|
|
12353
|
+
if (!isPrimaryPathKind(pathKind) || inferred !== "success") return [];
|
|
12354
|
+
edges.push(edge);
|
|
12355
|
+
}
|
|
12356
|
+
}
|
|
12357
|
+
const first = edges[0];
|
|
12358
|
+
if (!first) return [];
|
|
12359
|
+
if (edges.some((edge) => edge.target !== first.target)) return [];
|
|
12360
|
+
return edges;
|
|
12361
|
+
};
|
|
12362
|
+
const FAILURE_PATH_KINDS = ["cancel", "refund"];
|
|
12363
|
+
/**
|
|
12364
|
+
* The `cancel` / `refund` edge out of the current nodes whose conditions
|
|
12365
|
+
* match the order (e.g. `Payment captured`), used when callbacks fail
|
|
12366
|
+
* (§7.1). `null` when none applies: no terminal is invented.
|
|
12367
|
+
*/
|
|
12368
|
+
const resolveFailureTerminalEdge = (input) => {
|
|
12369
|
+
const { workflow, currentNodeIds, order } = input;
|
|
12370
|
+
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12371
|
+
let engine;
|
|
12372
|
+
for (const id of currentNodeIds) for (const edge of outgoingEdges(workflow, id)) {
|
|
12373
|
+
if (edge.data?.taken_at) continue;
|
|
12374
|
+
const target = nodesById.get(edge.target);
|
|
12375
|
+
if (target?.data.kind !== "terminal") continue;
|
|
12376
|
+
if (!FAILURE_PATH_KINDS.includes(edgePathKind(edge, target))) continue;
|
|
12377
|
+
if ((edge.data?.conditions ?? []).length > 0 && !engine) engine = buildRulesEngineFromOrder(order);
|
|
12378
|
+
if (!edgeMatchesConditions(edge, order, engine)) continue;
|
|
12379
|
+
return {
|
|
12380
|
+
edge,
|
|
12381
|
+
target
|
|
12382
|
+
};
|
|
12383
|
+
}
|
|
12384
|
+
return null;
|
|
12385
|
+
};
|
|
12386
|
+
const resolveAdvanceEdge = (input) => {
|
|
12387
|
+
return resolveAdvanceEdges(input)[0] ?? null;
|
|
12388
|
+
};
|
|
12389
|
+
const nextCurrentNodeIds = (input) => {
|
|
12390
|
+
const current = [...new Set(input.currentNodeIds)];
|
|
12391
|
+
if (!input.entered) return current;
|
|
12392
|
+
const target = findNodeById(input.workflow, input.targetId);
|
|
12393
|
+
if (target?.data.kind === "terminal") return [input.targetId];
|
|
12394
|
+
const outgoingBySource = indexOutgoingBySource(input.workflow);
|
|
12395
|
+
const nodesById = new Map(input.workflow.nodes.map((node) => [node.id, node]));
|
|
12396
|
+
const next = new Set(current);
|
|
12397
|
+
for (const sourceId of input.takenSourceIds) {
|
|
12398
|
+
const l1 = {
|
|
12399
|
+
workflow: input.workflow,
|
|
12400
|
+
nodeId: sourceId
|
|
12401
|
+
};
|
|
12402
|
+
const l2 = {
|
|
12403
|
+
order: input.order,
|
|
12404
|
+
outgoingBySource,
|
|
12405
|
+
nodesById
|
|
12406
|
+
};
|
|
12407
|
+
if (leftoverPrimaryOutgoing({
|
|
12408
|
+
...l1,
|
|
12409
|
+
...l2
|
|
12410
|
+
}).length === 0) next.delete(sourceId);
|
|
12411
|
+
}
|
|
12412
|
+
if (target?.data.kind === "join") {
|
|
12413
|
+
const incoming = incomingEdges(input.workflow, target.id);
|
|
12414
|
+
for (const edge of incoming) if (edge.data?.taken_at) next.delete(edge.source);
|
|
12415
|
+
}
|
|
12416
|
+
next.add(input.targetId);
|
|
12417
|
+
return [...next];
|
|
12418
|
+
};
|
|
12419
|
+
/** Prefer the entered target, then any sitting terminal, then the first head. */
|
|
12420
|
+
const sittingWorkflowNode = (workflow, currentNodeIds, fallbackId) => {
|
|
12421
|
+
if (fallbackId && currentNodeIds.includes(fallbackId)) {
|
|
12422
|
+
const preferred = findNodeById(workflow, fallbackId);
|
|
12423
|
+
if (preferred) return preferred;
|
|
12424
|
+
}
|
|
12425
|
+
for (const id of currentNodeIds) {
|
|
12426
|
+
const node = findNodeById(workflow, id);
|
|
12427
|
+
if (node?.data.kind === "terminal") return node;
|
|
12428
|
+
}
|
|
12429
|
+
for (const id of currentNodeIds) {
|
|
12430
|
+
const node = findNodeById(workflow, id);
|
|
12431
|
+
if (node) return node;
|
|
12432
|
+
}
|
|
12433
|
+
if (!fallbackId) return null;
|
|
12434
|
+
return findNodeById(workflow, fallbackId);
|
|
12435
|
+
};
|
|
12436
|
+
const appendNodeLog = (node, type, message, extra) => {
|
|
12437
|
+
const logs = node.data.logs ?? [];
|
|
12438
|
+
const b1 = {
|
|
12439
|
+
type,
|
|
12440
|
+
message,
|
|
12441
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
12442
|
+
};
|
|
12443
|
+
logs.push({
|
|
12444
|
+
...b1,
|
|
12445
|
+
...extra
|
|
12446
|
+
});
|
|
12447
|
+
node.data.logs = logs;
|
|
12448
|
+
};
|
|
12449
|
+
const applyManualAdvanceNote = (input) => {
|
|
12450
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
12451
|
+
const who = input.actor_name?.trim();
|
|
12452
|
+
const avatar = input.actor_avatar_url?.trim();
|
|
12453
|
+
const by = who ? ` by ${who}` : "";
|
|
12454
|
+
const message = `Manual advance to ${input.to_status}${by}: ${input.reason}`;
|
|
12455
|
+
const nodesById = new Map(input.workflow.nodes.map((node) => [node.id, node]));
|
|
12456
|
+
const seen = /* @__PURE__ */ new Set();
|
|
12457
|
+
for (const id of input.targetIds) {
|
|
12458
|
+
if (seen.has(id)) continue;
|
|
12459
|
+
seen.add(id);
|
|
12460
|
+
const node = nodesById.get(id);
|
|
12461
|
+
if (!node) continue;
|
|
12462
|
+
const b1 = {
|
|
12463
|
+
reason: input.reason,
|
|
12464
|
+
at,
|
|
12465
|
+
to_status: input.to_status
|
|
12466
|
+
};
|
|
12467
|
+
const b2 = who ? { actor_name: who } : {};
|
|
12468
|
+
const b3 = avatar ? { actor_avatar_url: avatar } : {};
|
|
12469
|
+
node.data.manual_advance = {
|
|
12470
|
+
...b1,
|
|
12471
|
+
...b2,
|
|
12472
|
+
...b3
|
|
12473
|
+
};
|
|
12474
|
+
appendNodeLog(node, "info", message, {
|
|
12475
|
+
...b2,
|
|
12476
|
+
...b3
|
|
12477
|
+
});
|
|
12478
|
+
}
|
|
12479
|
+
};
|
|
12480
|
+
const markNodeEntered = (node, at = (/* @__PURE__ */ new Date()).toISOString()) => {
|
|
12481
|
+
node.data.entered_at = at;
|
|
12482
|
+
delete node.data.ready_at;
|
|
12483
|
+
delete node.data.advance_requested_at;
|
|
12484
|
+
delete node.data.resumed_at;
|
|
12485
|
+
};
|
|
12486
|
+
/**
|
|
12487
|
+
* In-memory only: the caller persists `workflow` in a write it already
|
|
12488
|
+
* makes. The node did its own work and now waits for the next advance.
|
|
12489
|
+
*/
|
|
12490
|
+
const markNodesReady = (input) => {
|
|
12491
|
+
const at = input.at ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
12492
|
+
const ids = new Set(input.nodeIds);
|
|
12493
|
+
for (const node of input.workflow.nodes) {
|
|
12494
|
+
if (!ids.has(node.id)) continue;
|
|
12495
|
+
if (!node.data.entered_at || node.data.exited_at) continue;
|
|
12496
|
+
if (!node.data.ready_at) node.data.ready_at = at;
|
|
12497
|
+
}
|
|
12498
|
+
};
|
|
12499
|
+
/**
|
|
12500
|
+
* In-memory only. `requestedAt` is when the advance reached the API (it
|
|
12501
|
+
* travels in the hook payload); `resumedAt` is when the walker woke up.
|
|
12502
|
+
*/
|
|
12503
|
+
const markNodesAdvance = (input) => {
|
|
12504
|
+
const ids = new Set(input.nodeIds);
|
|
12505
|
+
for (const node of input.workflow.nodes) {
|
|
12506
|
+
if (!ids.has(node.id)) continue;
|
|
12507
|
+
if (!node.data.entered_at || node.data.exited_at) continue;
|
|
12508
|
+
node.data.resumed_at = input.resumedAt;
|
|
12509
|
+
if (input.requestedAt) node.data.advance_requested_at = input.requestedAt;
|
|
12510
|
+
}
|
|
12511
|
+
};
|
|
12512
|
+
const markNodeExited = (node, at = (/* @__PURE__ */ new Date()).toISOString()) => {
|
|
12513
|
+
node.data.exited_at = at;
|
|
12514
|
+
};
|
|
12515
|
+
/** In-memory only. The caller already writes `workflow`. */
|
|
12516
|
+
const markNodeSkipped = (node, at = (/* @__PURE__ */ new Date()).toISOString()) => {
|
|
12517
|
+
node.data.skipped_at = at;
|
|
12518
|
+
appendNodeLog(node, "info", "Skipped scheduled wait");
|
|
12519
|
+
};
|
|
12520
|
+
const markEdgeTaken = (edge, at = (/* @__PURE__ */ new Date()).toISOString()) => {
|
|
12521
|
+
edge.data = {
|
|
12522
|
+
...edge.data ?? {},
|
|
12523
|
+
taken_at: at
|
|
12524
|
+
};
|
|
12525
|
+
};
|
|
12526
|
+
const enterWorkflowNode = (input) => {
|
|
12527
|
+
const { workflow, nodeId, order } = input;
|
|
12528
|
+
const node = findNodeById(workflow, nodeId);
|
|
12529
|
+
if (!node) throw new Error(`Node ${nodeId} not found`);
|
|
12530
|
+
const fromEdgeIds = [...input.fromEdgeIds ?? []];
|
|
12531
|
+
if (input.fromEdgeId && !fromEdgeIds.includes(input.fromEdgeId)) fromEdgeIds.push(input.fromEdgeId);
|
|
12532
|
+
const taken = [];
|
|
12533
|
+
if (fromEdgeIds.length > 0) {
|
|
12534
|
+
const edgesById = new Map(workflow.edges.map((row) => [row.id, row]));
|
|
12535
|
+
for (const edgeId of fromEdgeIds) {
|
|
12536
|
+
const edge = edgesById.get(edgeId);
|
|
12537
|
+
if (!edge) continue;
|
|
12538
|
+
markEdgeTaken(edge);
|
|
12539
|
+
taken.push(edge);
|
|
12540
|
+
}
|
|
12541
|
+
}
|
|
12542
|
+
if (node.data.kind === "join" && !canEnterJoin(workflow, node)) {
|
|
12543
|
+
appendNodeLog(node, "warning", "Join policy is not satisfied");
|
|
12544
|
+
return null;
|
|
12545
|
+
}
|
|
12546
|
+
const outgoingBySource = indexOutgoingBySource(workflow);
|
|
12547
|
+
const nodesById = new Map(workflow.nodes.map((node) => [node.id, node]));
|
|
12548
|
+
if (node.data.kind === "join") {
|
|
12549
|
+
const incoming = incomingEdges(workflow, node.id);
|
|
12550
|
+
for (const edge of incoming) {
|
|
12551
|
+
if (!edge.data?.taken_at) continue;
|
|
12552
|
+
const previous = nodesById.get(edge.source);
|
|
12553
|
+
if (previous) markNodeExited(previous);
|
|
12554
|
+
}
|
|
12555
|
+
} else for (const edge of taken) {
|
|
12556
|
+
const p1 = {
|
|
12557
|
+
workflow,
|
|
12558
|
+
nodeId: edge.source,
|
|
12559
|
+
order,
|
|
12560
|
+
outgoingBySource,
|
|
12561
|
+
nodesById
|
|
12562
|
+
};
|
|
12563
|
+
if (leftoverPrimaryOutgoing(p1).length > 0 && node.data.kind !== "terminal") continue;
|
|
12564
|
+
const previous = nodesById.get(edge.source);
|
|
12565
|
+
if (previous) markNodeExited(previous);
|
|
12566
|
+
}
|
|
12567
|
+
markNodeEntered(node);
|
|
12568
|
+
return node;
|
|
12569
|
+
};
|
|
12570
|
+
const clearNodeVisit = (node) => {
|
|
12571
|
+
delete node.data.entered_at;
|
|
12572
|
+
delete node.data.ready_at;
|
|
12573
|
+
delete node.data.advance_requested_at;
|
|
12574
|
+
delete node.data.resumed_at;
|
|
12575
|
+
delete node.data.exited_at;
|
|
12576
|
+
delete node.data.skipped_at;
|
|
12577
|
+
};
|
|
12578
|
+
const clearEdgeTaken = (edge) => {
|
|
12579
|
+
if (!edge.data) return;
|
|
12580
|
+
const { taken_at: _taken, ...rest } = edge.data;
|
|
12581
|
+
edge.data = rest;
|
|
12582
|
+
};
|
|
12583
|
+
/** Statuses that close an order on their own, with or without a capture. */
|
|
12584
|
+
const ORDER_FROM_KEY = {
|
|
12585
|
+
COMPLETED: "COMPLETED",
|
|
12586
|
+
FULFILLED: "COMPLETED",
|
|
12587
|
+
VOIDED: "VOIDED",
|
|
12588
|
+
CANCELLED: "VOIDED",
|
|
12589
|
+
REFUNDED: "REFUNDED",
|
|
12590
|
+
RETURNED: "REFUNDED",
|
|
12591
|
+
REVERSED: "REVERSED"
|
|
12592
|
+
};
|
|
12593
|
+
/** Not preset terminals. A capture reverses; otherwise the order is voided. */
|
|
12594
|
+
const AMBIGUOUS_FAILURE = /* @__PURE__ */ new Set([
|
|
12595
|
+
"REJECTED",
|
|
12596
|
+
"FAILED",
|
|
12597
|
+
"EXPIRED"
|
|
12598
|
+
]);
|
|
12599
|
+
/**
|
|
12600
|
+
* An order with a charge never ends `VOIDED` (0.11.0): a `VOIDED` terminal,
|
|
12601
|
+
* node or payload becomes `REVERSED` when a tender was captured.
|
|
12602
|
+
*/
|
|
12603
|
+
const reversedWhenCaptured = (status, paymentCaptured) => {
|
|
12604
|
+
if (status === "VOIDED" && paymentCaptured) return "REVERSED";
|
|
12605
|
+
return status;
|
|
12606
|
+
};
|
|
12607
|
+
/**
|
|
12608
|
+
* Order status for a fulfillment status that ends the order. Lane statuses
|
|
12609
|
+
* (`PREPARING`, `DELIVERED`, `PAID`) return nothing: `DELIVERED` closes
|
|
12610
|
+
* only when the node itself is a terminal.
|
|
12611
|
+
*/
|
|
12612
|
+
const orderStatusForFulfillmentStatus = (fulfillmentStatus, paymentCaptured = false) => {
|
|
12613
|
+
const key = normalizeFulfillmentStatus(fulfillmentStatus ?? "");
|
|
12614
|
+
const known = ORDER_FROM_KEY[key];
|
|
12615
|
+
if (known) return reversedWhenCaptured(known, paymentCaptured);
|
|
12616
|
+
if (!AMBIGUOUS_FAILURE.has(key)) return void 0;
|
|
12617
|
+
if (paymentCaptured) return "REVERSED";
|
|
12618
|
+
return "VOIDED";
|
|
12619
|
+
};
|
|
12620
|
+
/**
|
|
12621
|
+
* Order status implied by the node we just entered. Entering a node never
|
|
12622
|
+
* writes `payment_status`: it is derived from the tenders (D32). Every
|
|
12623
|
+
* terminal closes the order. A captured payment turns any `VOIDED` result
|
|
12624
|
+
* (payload, milestone, mapped or unknown terminal) into `REVERSED`.
|
|
12625
|
+
*/
|
|
12626
|
+
const orderFieldsFromNode = (node, terminalStatus, paymentCaptured = false) => {
|
|
12627
|
+
if (node.data.kind !== "terminal") return {};
|
|
12628
|
+
const status = (value) => {
|
|
12629
|
+
return { status: reversedWhenCaptured(value, paymentCaptured) };
|
|
12630
|
+
};
|
|
12631
|
+
if (terminalStatus) return status(terminalStatus);
|
|
12632
|
+
const mapped = normalizeFulfillmentStatus(node.data.mappedStatus);
|
|
12633
|
+
const rawMilestone = node.data.milestone;
|
|
12634
|
+
let milestone = "";
|
|
12635
|
+
if (rawMilestone) milestone = normalizeFulfillmentStatus(rawMilestone);
|
|
12636
|
+
const fromMilestone = milestone ? ORDER_FROM_KEY[milestone] : void 0;
|
|
12637
|
+
if (fromMilestone) return status(fromMilestone);
|
|
12638
|
+
const known = orderStatusForFulfillmentStatus(mapped, paymentCaptured);
|
|
12639
|
+
if (known) return { status: known };
|
|
12640
|
+
if (mapped === "DELIVERED") return { status: "COMPLETED" };
|
|
12641
|
+
return status("VOIDED");
|
|
12642
|
+
};
|
|
12643
|
+
//#endregion
|
|
12644
|
+
//#region src/shared/locale.ts
|
|
12645
|
+
const DEFAULT_LOCALE = "en";
|
|
12646
|
+
const normalizeLocaleKey = (raw) => {
|
|
12647
|
+
return raw.trim().toLowerCase().replace(/-/g, "_");
|
|
12648
|
+
};
|
|
12649
|
+
const findLocaleKey = (value, locale) => {
|
|
12650
|
+
const normalized = normalizeLocaleKey(locale);
|
|
12651
|
+
if (!normalized) return void 0;
|
|
12652
|
+
return Object.keys(value).find((key) => {
|
|
12653
|
+
return normalizeLocaleKey(key) === normalized;
|
|
12654
|
+
});
|
|
12655
|
+
};
|
|
12656
|
+
const languageOf = (locale) => {
|
|
12657
|
+
return normalizeLocaleKey(locale).split("_")[0] ?? "";
|
|
12658
|
+
};
|
|
12659
|
+
const firstNonEmpty = (value) => {
|
|
12660
|
+
return Object.values(value).find((text) => text.trim());
|
|
12661
|
+
};
|
|
12662
|
+
const pickMultiLanguageText = (value, locale, fallback = "") => {
|
|
12663
|
+
if (value == null) return fallback;
|
|
12664
|
+
if (typeof value === "string") return value || fallback;
|
|
12665
|
+
if (locale) {
|
|
12666
|
+
const exactKey = findLocaleKey(value, locale);
|
|
12667
|
+
const exact = exactKey ? value[exactKey] : void 0;
|
|
12668
|
+
if (exact?.trim()) return exact;
|
|
12669
|
+
const lang = languageOf(locale);
|
|
12670
|
+
if (lang) {
|
|
12671
|
+
const langKey = Object.keys(value).find((key) => {
|
|
12672
|
+
return languageOf(key) === lang;
|
|
12673
|
+
});
|
|
12674
|
+
const langText = langKey ? value[langKey] : void 0;
|
|
12675
|
+
if (langText?.trim()) return langText;
|
|
12676
|
+
}
|
|
12677
|
+
}
|
|
12678
|
+
return firstNonEmpty(value) ?? fallback;
|
|
12679
|
+
};
|
|
12680
|
+
//#endregion
|
|
12681
|
+
//#region src/order/fees.ts
|
|
12682
|
+
const FEE_ROUNDING_MODE = {
|
|
12683
|
+
NONE: null,
|
|
12684
|
+
NEAREST: Big.roundHalfUp,
|
|
12685
|
+
UP: Big.roundUp,
|
|
12686
|
+
DOWN: Big.roundDown,
|
|
12687
|
+
QUARTER_NEAREST: Big.roundHalfUp,
|
|
12688
|
+
QUARTER_UP: Big.roundUp,
|
|
12689
|
+
QUARTER_DOWN: Big.roundDown,
|
|
12690
|
+
HALF_NEAREST: Big.roundHalfUp,
|
|
12691
|
+
HALF_UP: Big.roundUp,
|
|
12692
|
+
HALF_DOWN: Big.roundDown,
|
|
12693
|
+
WHOLE_NEAREST: Big.roundHalfUp,
|
|
12694
|
+
WHOLE_UP: Big.roundUp,
|
|
12695
|
+
WHOLE_DOWN: Big.roundDown
|
|
12696
|
+
};
|
|
12697
|
+
const FEE_ROUNDING_STEP = {
|
|
12698
|
+
NONE: null,
|
|
12699
|
+
NEAREST: null,
|
|
12700
|
+
UP: null,
|
|
12701
|
+
DOWN: null,
|
|
12702
|
+
QUARTER_NEAREST: "0.25",
|
|
12703
|
+
QUARTER_UP: "0.25",
|
|
12704
|
+
QUARTER_DOWN: "0.25",
|
|
12705
|
+
HALF_NEAREST: "0.5",
|
|
12706
|
+
HALF_UP: "0.5",
|
|
12707
|
+
HALF_DOWN: "0.5",
|
|
12708
|
+
WHOLE_NEAREST: "1",
|
|
12709
|
+
WHOLE_UP: "1",
|
|
12710
|
+
WHOLE_DOWN: "1"
|
|
12711
|
+
};
|
|
12712
|
+
const roundFeeAmount = (value, rounding, digits) => {
|
|
12713
|
+
const amount = new Big(value);
|
|
12714
|
+
const mode = FEE_ROUNDING_MODE[rounding];
|
|
12715
|
+
if (mode == null) return amount.toNumber();
|
|
12716
|
+
const step = FEE_ROUNDING_STEP[rounding];
|
|
12717
|
+
if (step == null) return amount.round(digits, mode).toNumber();
|
|
12718
|
+
return amount.div(step).round(0, mode).times(step).toNumber();
|
|
12719
|
+
};
|
|
12720
|
+
const TAG_STUB_BASE = 4.55;
|
|
12721
|
+
const DISTANCE_STUB_UNITS = 5;
|
|
12722
|
+
const NAME_MAX = 100;
|
|
12723
|
+
const isProductRoot = (line) => {
|
|
12724
|
+
return line.parent_uid == null && line.type === "PRODUCT";
|
|
12725
|
+
};
|
|
12726
|
+
const stripFeeLines = (lines) => {
|
|
12727
|
+
return lines.filter((line) => line.type !== "FEE");
|
|
12728
|
+
};
|
|
12729
|
+
const stubUnsupportedFeeAmount = (effect) => {
|
|
12730
|
+
if (effect.based_on === "TIPS") return new Big(effect.min).plus(effect.max).div(2).toNumber();
|
|
12731
|
+
if (effect.based_on === "DISTANCE_STRAIGHT") return new Big(DISTANCE_STUB_UNITS).times(effect.amount).toNumber();
|
|
12732
|
+
if (effect.based_on === "DISTANCE_STREET") return new Big(DISTANCE_STUB_UNITS).times(effect.amount).toNumber();
|
|
12733
|
+
if ("value" in effect) return new Big(TAG_STUB_BASE).times(effect.value).toNumber();
|
|
12734
|
+
return 0;
|
|
12735
|
+
};
|
|
12736
|
+
const parseTagNumber = (raw) => {
|
|
12737
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
12738
|
+
if (typeof raw !== "string") return null;
|
|
12739
|
+
const parsed = Number.parseFloat(raw);
|
|
12740
|
+
if (!Number.isFinite(parsed)) return null;
|
|
12741
|
+
return parsed;
|
|
12742
|
+
};
|
|
12743
|
+
const productRootsOf = (lines) => {
|
|
12744
|
+
return lines.filter(isProductRoot);
|
|
12745
|
+
};
|
|
12746
|
+
const sumGroup = (lines, field) => {
|
|
12747
|
+
return lines.reduce((sum, line) => sum.plus(line[field]), new Big(0));
|
|
12748
|
+
};
|
|
12749
|
+
const feeName = (name, locale) => {
|
|
12750
|
+
const trimmed = pickMultiLanguageText(name, locale, "Fee").trim();
|
|
12751
|
+
if (!trimmed) return "Fee";
|
|
12752
|
+
return trimmed.slice(0, NAME_MAX);
|
|
12753
|
+
};
|
|
12754
|
+
const engineLines = (roots) => {
|
|
12755
|
+
return roots.map((line) => ({
|
|
12756
|
+
id: line.id,
|
|
12757
|
+
quantity: line.quantity
|
|
12758
|
+
}));
|
|
12759
|
+
};
|
|
12760
|
+
const selectMatchingFees = (fees, order, roots) => {
|
|
12761
|
+
const total = sumGroup(roots, "group_total").toNumber();
|
|
12762
|
+
const store_id = order.store_id ?? void 0;
|
|
12763
|
+
const channel_id = order.channel_id ?? void 0;
|
|
12764
|
+
const fulfillment_id = order.fulfillment_id ?? void 0;
|
|
12765
|
+
const brand_id = order.brand_id ?? void 0;
|
|
12766
|
+
const o1 = {
|
|
12767
|
+
total,
|
|
12768
|
+
is_anonymous: order.is_anonymous
|
|
12769
|
+
};
|
|
12770
|
+
const o2 = {
|
|
12771
|
+
store_id,
|
|
12772
|
+
channel_id,
|
|
12773
|
+
fulfillment_id,
|
|
12774
|
+
brand_id
|
|
12775
|
+
};
|
|
12776
|
+
const o3 = { lines: engineLines(roots) };
|
|
12777
|
+
const engine = new RulesEngine({
|
|
12778
|
+
order: {
|
|
12779
|
+
...o1,
|
|
12780
|
+
...o2,
|
|
12781
|
+
...o3
|
|
12782
|
+
},
|
|
12783
|
+
customer: { is_anonymous: order.is_anonymous }
|
|
12784
|
+
});
|
|
12785
|
+
return fees.filter((fee) => {
|
|
12786
|
+
const conditions = fee.conditions ?? [];
|
|
12787
|
+
if (conditions.length === 0) return true;
|
|
12788
|
+
return Boolean(engine.matchOrConditions(conditions).match);
|
|
12789
|
+
});
|
|
12790
|
+
};
|
|
12791
|
+
const effectAmount = (effect, productSubtotal, productTotal, storeTags) => {
|
|
12792
|
+
if (effect.based_on === "FIXED") return effect.amount;
|
|
12793
|
+
if (effect.based_on === "ORDER_SUBTOTAL") {
|
|
12794
|
+
const pct = new Big(effect.percentage).div(100);
|
|
12795
|
+
return productSubtotal.times(pct).toNumber();
|
|
12796
|
+
}
|
|
12797
|
+
if (effect.based_on === "ORDER_TOTAL") {
|
|
12798
|
+
const pct = new Big(effect.percentage).div(100);
|
|
12799
|
+
return productTotal.times(pct).toNumber();
|
|
12800
|
+
}
|
|
12801
|
+
if (effect.based_on === "STORE_TAG") {
|
|
12802
|
+
const tagValue = parseTagNumber(storeTags?.[effect.tag_key]);
|
|
12803
|
+
if (tagValue == null) return stubUnsupportedFeeAmount(effect);
|
|
12804
|
+
return new Big(tagValue).times(effect.value).toNumber();
|
|
12805
|
+
}
|
|
12806
|
+
return stubUnsupportedFeeAmount(effect);
|
|
12807
|
+
};
|
|
12808
|
+
const applyFeeMoney = (amount, taxable, taxInclusive, taxRatePct) => {
|
|
12809
|
+
const rate = taxable ? new Big(taxRatePct).div(100) : new Big(0);
|
|
12810
|
+
const base = new Big(amount);
|
|
12811
|
+
if (!taxable || rate.eq(0)) {
|
|
12812
|
+
const n = base.toNumber();
|
|
12813
|
+
const b1 = {
|
|
12814
|
+
amount: n,
|
|
12815
|
+
tax_rate: taxable ? 0 : null
|
|
12816
|
+
};
|
|
12817
|
+
const b2 = {
|
|
12818
|
+
unit_subtotal: n,
|
|
12819
|
+
unit_tax_total: 0,
|
|
12820
|
+
unit_total: n
|
|
12821
|
+
};
|
|
12822
|
+
return {
|
|
12823
|
+
...b1,
|
|
12824
|
+
...b2
|
|
12825
|
+
};
|
|
12826
|
+
}
|
|
12827
|
+
if (taxInclusive) {
|
|
12828
|
+
const divisor = new Big(1).plus(rate);
|
|
12829
|
+
const tax = base.times(rate).div(divisor);
|
|
12830
|
+
const n = base.toNumber();
|
|
12831
|
+
const b1 = {
|
|
12832
|
+
amount: n,
|
|
12833
|
+
tax_rate: rate.toNumber(),
|
|
12834
|
+
unit_subtotal: n
|
|
12835
|
+
};
|
|
12836
|
+
const b2 = {
|
|
12837
|
+
unit_tax_total: tax.toNumber(),
|
|
12838
|
+
unit_total: n
|
|
12839
|
+
};
|
|
12840
|
+
return {
|
|
12841
|
+
...b1,
|
|
12842
|
+
...b2
|
|
12843
|
+
};
|
|
12844
|
+
}
|
|
12845
|
+
const tax = base.times(rate);
|
|
12846
|
+
const n = base.toNumber();
|
|
12847
|
+
const unit_total = base.plus(tax).toNumber();
|
|
12848
|
+
const b1 = {
|
|
12849
|
+
amount: n,
|
|
12850
|
+
tax_rate: rate.toNumber(),
|
|
12851
|
+
unit_subtotal: n
|
|
12852
|
+
};
|
|
12853
|
+
const b2 = {
|
|
12854
|
+
unit_tax_total: tax.toNumber(),
|
|
12855
|
+
unit_total
|
|
12856
|
+
};
|
|
12857
|
+
return {
|
|
12858
|
+
...b1,
|
|
12859
|
+
...b2
|
|
12860
|
+
};
|
|
12861
|
+
};
|
|
12862
|
+
const requiredEffects = (fee) => {
|
|
12863
|
+
return fee.effects.filter((effect) => effect.requirement === "REQUIRED");
|
|
12864
|
+
};
|
|
12865
|
+
const effectMoney = (effect, productSubtotal, productTotal, storeTags, digits) => {
|
|
12866
|
+
const raw = effectAmount(effect, productSubtotal, productTotal, storeTags);
|
|
12867
|
+
const rounded = roundFeeAmount(raw, effect.rounding, digits);
|
|
12868
|
+
const taxable = effect.taxable;
|
|
12869
|
+
const inclusive = effect.tax_inclusive;
|
|
12870
|
+
const taxRate = effect.tax_rate ?? 0;
|
|
12871
|
+
return applyFeeMoney(rounded, taxable, inclusive, taxRate);
|
|
12872
|
+
};
|
|
12873
|
+
const sumMoney = (parts) => {
|
|
12874
|
+
const z1 = {
|
|
12875
|
+
amount: 0,
|
|
12876
|
+
tax_rate: parts[0]?.tax_rate ?? null
|
|
12877
|
+
};
|
|
12878
|
+
const z2 = {
|
|
12879
|
+
unit_subtotal: 0,
|
|
12880
|
+
unit_tax_total: 0,
|
|
12881
|
+
unit_total: 0
|
|
12882
|
+
};
|
|
12883
|
+
const zero = {
|
|
12884
|
+
...z1,
|
|
12885
|
+
...z2
|
|
12886
|
+
};
|
|
12887
|
+
return parts.reduce((acc, part) => {
|
|
12888
|
+
const amount = new Big(acc.amount).plus(part.amount).toNumber();
|
|
12889
|
+
const unit_subtotal = new Big(acc.unit_subtotal).plus(part.unit_subtotal);
|
|
12890
|
+
const tax = new Big(acc.unit_tax_total).plus(part.unit_tax_total);
|
|
12891
|
+
const unit_total = new Big(acc.unit_total).plus(part.unit_total);
|
|
12892
|
+
const r1 = {
|
|
12893
|
+
amount,
|
|
12894
|
+
tax_rate: acc.tax_rate
|
|
12895
|
+
};
|
|
12896
|
+
const r2 = { unit_subtotal: unit_subtotal.toNumber() };
|
|
12897
|
+
const r3 = { unit_tax_total: tax.toNumber() };
|
|
12898
|
+
const r4 = { unit_total: unit_total.toNumber() };
|
|
12899
|
+
return {
|
|
12900
|
+
...r1,
|
|
12901
|
+
...r2,
|
|
12902
|
+
...r3,
|
|
12903
|
+
...r4
|
|
12904
|
+
};
|
|
12905
|
+
}, zero);
|
|
12906
|
+
};
|
|
12907
|
+
const toFeeLine = (fee, money, locale) => {
|
|
12908
|
+
const name = feeName(fee.name, locale);
|
|
12909
|
+
const metadata = { fee_based_on: requiredEffects(fee)[0]?.based_on ?? null };
|
|
12910
|
+
const u = money.unit_subtotal;
|
|
12911
|
+
const d = 0;
|
|
12912
|
+
const tax = money.unit_tax_total;
|
|
12913
|
+
const t = money.unit_total;
|
|
12914
|
+
const id = fee.id;
|
|
12915
|
+
const b1 = {
|
|
12916
|
+
type: "FEE",
|
|
12917
|
+
uid: id,
|
|
12918
|
+
id,
|
|
12919
|
+
parent_uid: null
|
|
12920
|
+
};
|
|
12921
|
+
const b2 = {
|
|
12922
|
+
parent_id: null,
|
|
12923
|
+
name,
|
|
12924
|
+
metadata,
|
|
12925
|
+
bundled_items: []
|
|
12926
|
+
};
|
|
12927
|
+
const b3 = {
|
|
12928
|
+
quantity: 1,
|
|
12929
|
+
tax_rate: money.tax_rate,
|
|
12930
|
+
discount_rate: 0
|
|
12931
|
+
};
|
|
12932
|
+
const b4 = {
|
|
12933
|
+
unit_subtotal: u,
|
|
12934
|
+
unit_discount: d,
|
|
12935
|
+
unit_tax_total: tax
|
|
12936
|
+
};
|
|
12937
|
+
const b5 = {
|
|
12938
|
+
unit_total: t,
|
|
12939
|
+
subtotal: u,
|
|
12940
|
+
discount_total: d,
|
|
12941
|
+
tax_total: tax
|
|
12942
|
+
};
|
|
12943
|
+
const b6 = {
|
|
12944
|
+
total: t,
|
|
12945
|
+
unit_group_subtotal: u,
|
|
12946
|
+
unit_group_discount: d
|
|
12947
|
+
};
|
|
12948
|
+
const b7 = {
|
|
12949
|
+
unit_group_tax_total: tax,
|
|
12950
|
+
unit_group_total: t
|
|
12951
|
+
};
|
|
12952
|
+
const b8 = {
|
|
12953
|
+
group_subtotal: u,
|
|
12954
|
+
group_discount: d,
|
|
12955
|
+
group_tax_total: tax
|
|
12956
|
+
};
|
|
12957
|
+
const b9 = {
|
|
12958
|
+
group_total: t,
|
|
12959
|
+
redeem: []
|
|
12960
|
+
};
|
|
12961
|
+
return {
|
|
12962
|
+
...b1,
|
|
12963
|
+
...b2,
|
|
12964
|
+
...b3,
|
|
12965
|
+
...b4,
|
|
12966
|
+
...b5,
|
|
12967
|
+
...b6,
|
|
12968
|
+
...b7,
|
|
12969
|
+
...b8,
|
|
12970
|
+
...b9
|
|
12971
|
+
};
|
|
12972
|
+
};
|
|
12973
|
+
const applyFees = (input) => {
|
|
12974
|
+
const locale = input.locale ?? "en";
|
|
12975
|
+
const digits = input.currencyDigits ?? 2;
|
|
12976
|
+
const roots = productRootsOf(input.lines);
|
|
12977
|
+
if (roots.length === 0) return [];
|
|
12978
|
+
const productSubtotal = sumGroup(roots, "group_subtotal");
|
|
12979
|
+
const productTotal = sumGroup(roots, "group_total");
|
|
12980
|
+
const matched = selectMatchingFees(input.fees, input.order, roots);
|
|
12981
|
+
const lines = [];
|
|
12982
|
+
for (const fee of matched) {
|
|
12983
|
+
const effects = requiredEffects(fee);
|
|
12984
|
+
if (effects.length === 0) continue;
|
|
12985
|
+
const parts = effects.map((effect) => {
|
|
12986
|
+
return effectMoney(...[
|
|
12987
|
+
effect,
|
|
12988
|
+
productSubtotal,
|
|
12989
|
+
productTotal
|
|
12990
|
+
], input.storeTags, digits);
|
|
12991
|
+
});
|
|
12992
|
+
lines.push(toFeeLine(fee, sumMoney(parts), locale));
|
|
12993
|
+
}
|
|
12994
|
+
return lines;
|
|
12995
|
+
};
|
|
12996
|
+
const rebuildOrderLinesWithFees = (input) => {
|
|
12997
|
+
const products = stripFeeLines(input.lines);
|
|
12998
|
+
const fees = applyFees({
|
|
12999
|
+
...input,
|
|
13000
|
+
lines: products
|
|
13001
|
+
});
|
|
13002
|
+
return [...products, ...fees];
|
|
13003
|
+
};
|
|
13004
|
+
//#endregion
|
|
13005
|
+
//#region src/order/checkout.ts
|
|
13006
|
+
const asRecord = (value) => {
|
|
13007
|
+
if (!value || typeof value !== "object") return null;
|
|
13008
|
+
if (Array.isArray(value)) return null;
|
|
13009
|
+
return value;
|
|
13010
|
+
};
|
|
13011
|
+
/** `now` (ISO) evaluates time conditions at another moment, e.g. a sale. */
|
|
13012
|
+
const collectCheckoutIssues = (checkout, order, fulfillmentType, now) => {
|
|
13013
|
+
const customer = asRecord(order.customer) ?? {};
|
|
13014
|
+
const address = asRecord(customer.address_info);
|
|
13015
|
+
const billing = asRecord(customer.billing_info);
|
|
13016
|
+
const resolved = resolveCheckout(order, {
|
|
13017
|
+
runtime: "server",
|
|
13018
|
+
checkout,
|
|
13019
|
+
fulfillmentType,
|
|
13020
|
+
now
|
|
13021
|
+
});
|
|
13022
|
+
const issues = [];
|
|
13023
|
+
const pushFields = (info, fields, code) => {
|
|
13024
|
+
for (const [key, mode] of Object.entries(fields)) {
|
|
13025
|
+
if (mode !== "required") continue;
|
|
13026
|
+
if (isCheckoutFieldFilled(info, key)) continue;
|
|
13027
|
+
issues.push({
|
|
13028
|
+
code,
|
|
13029
|
+
field: key
|
|
13030
|
+
});
|
|
13031
|
+
}
|
|
13032
|
+
};
|
|
13033
|
+
if (resolved.shipping !== "hidden") if (!address) {
|
|
13034
|
+
if (resolved.shipping === "required") issues.push({ code: "SHIPPING_REQUIRED" });
|
|
13035
|
+
} else {
|
|
13036
|
+
const fields = resolved.shippingFields;
|
|
13037
|
+
pushFields(address, fields, "SHIPPING_FIELD_REQUIRED");
|
|
13038
|
+
}
|
|
13039
|
+
if (resolved.billing !== "hidden") if (!billing) {
|
|
13040
|
+
if (resolved.billing === "required") issues.push({ code: "BILLING_REQUIRED" });
|
|
13041
|
+
} else {
|
|
13042
|
+
const fields = resolved.billingFields;
|
|
13043
|
+
pushFields(billing, fields, "BILLING_FIELD_REQUIRED");
|
|
13044
|
+
}
|
|
13045
|
+
if (order.is_anonymous) {
|
|
13046
|
+
const info = asRecord(customer.customer_info);
|
|
13047
|
+
const fields = resolved.customerFields;
|
|
13048
|
+
for (const [key, mode] of Object.entries(fields)) {
|
|
13049
|
+
if (mode !== "required") continue;
|
|
13050
|
+
if (isCustomerInfoFieldFilled(info, key, order.customer_id)) continue;
|
|
13051
|
+
issues.push({
|
|
13052
|
+
code: "CUSTOMER_FIELD_REQUIRED",
|
|
13053
|
+
field: key
|
|
13054
|
+
});
|
|
13055
|
+
}
|
|
13056
|
+
}
|
|
13057
|
+
return issues;
|
|
13058
|
+
};
|
|
13059
|
+
//#endregion
|
|
13060
|
+
//#region src/hpke/hpke.ts
|
|
13061
|
+
const HPKE_ALG = "HPKE-Base-P256-SHA256-AES256GCM";
|
|
13062
|
+
const KEM_ID = 16;
|
|
13063
|
+
const KDF_ID = 1;
|
|
13064
|
+
const AEAD_IDS = {
|
|
13065
|
+
"AES-128-GCM": 1,
|
|
13066
|
+
"AES-256-GCM": 2
|
|
13067
|
+
};
|
|
13068
|
+
const AEAD_KEY_BYTES = {
|
|
13069
|
+
"AES-128-GCM": 16,
|
|
13070
|
+
"AES-256-GCM": 32
|
|
13071
|
+
};
|
|
13072
|
+
const HASH_BYTES = 32;
|
|
13073
|
+
const NONCE_BYTES = 12;
|
|
13074
|
+
const POINT_BYTES = 65;
|
|
13075
|
+
const ECDH = {
|
|
13076
|
+
name: "ECDH",
|
|
13077
|
+
namedCurve: "P-256"
|
|
13078
|
+
};
|
|
13079
|
+
const subtle = () => {
|
|
13080
|
+
const value = globalThis.crypto?.subtle;
|
|
13081
|
+
if (!value) throw new Error("WebCrypto (crypto.subtle) is required");
|
|
13082
|
+
return value;
|
|
13083
|
+
};
|
|
13084
|
+
const text = (value) => new TextEncoder().encode(value);
|
|
13085
|
+
const concat = (...parts) => {
|
|
13086
|
+
const size = parts.reduce((sum, part) => sum + part.length, 0);
|
|
13087
|
+
const out = new Uint8Array(size);
|
|
13088
|
+
let at = 0;
|
|
13089
|
+
for (const part of parts) {
|
|
13090
|
+
out.set(part, at);
|
|
13091
|
+
at += part.length;
|
|
13092
|
+
}
|
|
13093
|
+
return out;
|
|
13094
|
+
};
|
|
13095
|
+
const i2osp = (value, length) => {
|
|
13096
|
+
const out = new Uint8Array(length);
|
|
13097
|
+
for (let i = length - 1, rest = value; i >= 0; i -= 1, rest >>= 8) out[i] = rest & 255;
|
|
13098
|
+
return out;
|
|
13099
|
+
};
|
|
13100
|
+
const buffer = (value) => value;
|
|
13101
|
+
const base64UrlEncode = (bytes) => {
|
|
13102
|
+
let binary = "";
|
|
13103
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
13104
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
13105
|
+
};
|
|
13106
|
+
const base64UrlDecode = (value) => {
|
|
13107
|
+
if (!/^[A-Za-z0-9_-]*$/.test(value)) throw new Error("Invalid base64url");
|
|
13108
|
+
const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
13109
|
+
const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
|
|
13110
|
+
const binary = atob(padded);
|
|
13111
|
+
const out = new Uint8Array(binary.length);
|
|
13112
|
+
for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
|
|
13113
|
+
return out;
|
|
13114
|
+
};
|
|
13115
|
+
const hmac = async (key, data) => {
|
|
13116
|
+
const k = await subtle().importKey("raw", buffer(key), {
|
|
13117
|
+
name: "HMAC",
|
|
13118
|
+
hash: "SHA-256"
|
|
13119
|
+
}, false, ["sign"]);
|
|
13120
|
+
const mac = await subtle().sign("HMAC", k, buffer(data));
|
|
13121
|
+
return new Uint8Array(mac);
|
|
13122
|
+
};
|
|
13123
|
+
/** An empty salt is HashLen zeros (RFC 5869); same HMAC result. */
|
|
13124
|
+
const extract = (salt, ikm) => {
|
|
13125
|
+
const key = salt.length > 0 ? salt : new Uint8Array(HASH_BYTES);
|
|
13126
|
+
return hmac(key, ikm);
|
|
13127
|
+
};
|
|
13128
|
+
const expand = async (prk, info, length) => {
|
|
13129
|
+
const blocks = [];
|
|
13130
|
+
let previous = /* @__PURE__ */ new Uint8Array(0);
|
|
13131
|
+
let size = 0;
|
|
13132
|
+
for (let counter = 1; size < length; counter += 1) {
|
|
13133
|
+
const input = concat(previous, info, Uint8Array.of(counter));
|
|
13134
|
+
previous = await hmac(prk, input);
|
|
13135
|
+
blocks.push(previous);
|
|
13136
|
+
size += previous.length;
|
|
13137
|
+
}
|
|
13138
|
+
return concat(...blocks).slice(0, length);
|
|
13139
|
+
};
|
|
13140
|
+
const VERSION = text("HPKE-v1");
|
|
13141
|
+
const labeledExtract = (suite, salt, label, ikm) => {
|
|
13142
|
+
return extract(salt, concat(VERSION, suite, text(label), ikm));
|
|
13143
|
+
};
|
|
13144
|
+
const labeledExpand = (suite, prk, label, info, length) => {
|
|
13145
|
+
const labeled = concat(i2osp(length, 2), VERSION, suite, text(label), info);
|
|
13146
|
+
return expand(prk, labeled, length);
|
|
13147
|
+
};
|
|
13148
|
+
const kemSuite = () => concat(text("KEM"), i2osp(KEM_ID, 2));
|
|
13149
|
+
const hpkeSuite = (aead) => {
|
|
13150
|
+
const ids = concat(i2osp(KEM_ID, 2), i2osp(KDF_ID, 2));
|
|
13151
|
+
return concat(text("HPKE"), ids, i2osp(AEAD_IDS[aead], 2));
|
|
13152
|
+
};
|
|
13153
|
+
const rawPoint = (jwk) => {
|
|
13154
|
+
const x = base64UrlDecode(jwk.x);
|
|
13155
|
+
const y = base64UrlDecode(jwk.y);
|
|
13156
|
+
if (x.length !== 32 || y.length !== 32) throw new Error("Invalid P-256 key");
|
|
13157
|
+
return concat(Uint8Array.of(4), x, y);
|
|
13158
|
+
};
|
|
13159
|
+
const importPublic = (raw) => {
|
|
13160
|
+
if (raw.length !== POINT_BYTES || raw[0] !== 4) throw new Error("Invalid HPKE enc");
|
|
13161
|
+
return subtle().importKey("raw", buffer(raw), ECDH, true, []);
|
|
13162
|
+
};
|
|
13163
|
+
const importPrivate = (jwk) => {
|
|
13164
|
+
const key = {
|
|
13165
|
+
kty: "EC",
|
|
13166
|
+
crv: "P-256",
|
|
13167
|
+
x: jwk.x,
|
|
13168
|
+
y: jwk.y,
|
|
13169
|
+
d: jwk.d
|
|
13170
|
+
};
|
|
13171
|
+
return subtle().importKey("jwk", key, ECDH, false, ["deriveBits"]);
|
|
13172
|
+
};
|
|
13173
|
+
const dh = async (privateKey, publicKey) => {
|
|
13174
|
+
const alg = {
|
|
13175
|
+
name: "ECDH",
|
|
13176
|
+
public: publicKey
|
|
13177
|
+
};
|
|
13178
|
+
const bits = await subtle().deriveBits(alg, privateKey, 256);
|
|
13179
|
+
return new Uint8Array(bits);
|
|
13180
|
+
};
|
|
13181
|
+
const sharedSecret = async (secret, context) => {
|
|
13182
|
+
const suite = kemSuite();
|
|
13183
|
+
const prk = await labeledExtract(suite, /* @__PURE__ */ new Uint8Array(0), "eae_prk", secret);
|
|
13184
|
+
return labeledExpand(suite, prk, "shared_secret", context, HASH_BYTES);
|
|
13185
|
+
};
|
|
13186
|
+
const keySchedule = async (aead, shared, info) => {
|
|
13187
|
+
const suite = hpkeSuite(aead);
|
|
13188
|
+
const empty = /* @__PURE__ */ new Uint8Array(0);
|
|
13189
|
+
const pskId = await labeledExtract(suite, empty, "psk_id_hash", empty);
|
|
13190
|
+
const infoHash = await labeledExtract(suite, empty, "info_hash", info);
|
|
13191
|
+
const context = concat(Uint8Array.of(0), pskId, infoHash);
|
|
13192
|
+
const secret = await labeledExtract(suite, shared, "secret", empty);
|
|
13193
|
+
const p1 = [
|
|
13194
|
+
suite,
|
|
13195
|
+
secret,
|
|
13196
|
+
"key",
|
|
13197
|
+
context,
|
|
13198
|
+
AEAD_KEY_BYTES[aead]
|
|
13199
|
+
];
|
|
13200
|
+
return {
|
|
13201
|
+
key: await labeledExpand(...p1),
|
|
13202
|
+
nonce: await labeledExpand(...[
|
|
13203
|
+
suite,
|
|
13204
|
+
secret,
|
|
13205
|
+
"base_nonce",
|
|
13206
|
+
context,
|
|
13207
|
+
NONCE_BYTES
|
|
13208
|
+
])
|
|
13209
|
+
};
|
|
13210
|
+
};
|
|
13211
|
+
const aesKey = (key, usage) => {
|
|
13212
|
+
return subtle().importKey("raw", buffer(key), { name: "AES-GCM" }, false, [usage]);
|
|
13213
|
+
};
|
|
13214
|
+
const ephemeralKey = async (fixed) => {
|
|
13215
|
+
if (fixed) return {
|
|
13216
|
+
privateKey: await importPrivate(fixed),
|
|
13217
|
+
enc: rawPoint(fixed)
|
|
13218
|
+
};
|
|
13219
|
+
const pair = await subtle().generateKey(ECDH, true, ["deriveBits"]);
|
|
13220
|
+
const raw = await subtle().exportKey("raw", pair.publicKey);
|
|
13221
|
+
return {
|
|
13222
|
+
privateKey: pair.privateKey,
|
|
13223
|
+
enc: new Uint8Array(raw)
|
|
13224
|
+
};
|
|
13225
|
+
};
|
|
13226
|
+
/** Seals `plaintext` to the recipient's P-256 key. */
|
|
13227
|
+
const hpkeSeal = async (input) => {
|
|
13228
|
+
const aead = input.aead ?? "AES-256-GCM";
|
|
13229
|
+
const recipientRaw = rawPoint(input.recipient);
|
|
13230
|
+
const recipient = await importPublic(recipientRaw);
|
|
13231
|
+
const { privateKey, enc } = await ephemeralKey(input.ephemeral);
|
|
13232
|
+
const secret = await dh(privateKey, recipient);
|
|
13233
|
+
const shared = await sharedSecret(secret, concat(enc, recipientRaw));
|
|
13234
|
+
const { key, nonce } = await keySchedule(aead, shared, input.info);
|
|
13235
|
+
const k = await aesKey(key, "encrypt");
|
|
13236
|
+
const params = {
|
|
13237
|
+
name: "AES-GCM",
|
|
13238
|
+
iv: buffer(nonce),
|
|
13239
|
+
additionalData: buffer(input.aad)
|
|
13240
|
+
};
|
|
13241
|
+
const sealed = await subtle().encrypt(params, k, buffer(input.plaintext));
|
|
13242
|
+
return {
|
|
13243
|
+
enc,
|
|
13244
|
+
ciphertext: new Uint8Array(sealed)
|
|
13245
|
+
};
|
|
13246
|
+
};
|
|
13247
|
+
/** Opens a sealed message; throws when anything was altered. */
|
|
13248
|
+
const hpkeOpen = async (input) => {
|
|
13249
|
+
const aead = input.aead ?? "AES-256-GCM";
|
|
13250
|
+
const recipientRaw = rawPoint(input.recipient);
|
|
13251
|
+
const privateKey = await importPrivate(input.recipient);
|
|
13252
|
+
const ephemeral = await importPublic(input.enc);
|
|
13253
|
+
const secret = await dh(privateKey, ephemeral);
|
|
13254
|
+
const shared = await sharedSecret(secret, concat(input.enc, recipientRaw));
|
|
13255
|
+
const { key, nonce } = await keySchedule(aead, shared, input.info);
|
|
13256
|
+
const k = await aesKey(key, "decrypt");
|
|
13257
|
+
const params = {
|
|
13258
|
+
name: "AES-GCM",
|
|
13259
|
+
iv: buffer(nonce),
|
|
13260
|
+
additionalData: buffer(input.aad)
|
|
13261
|
+
};
|
|
13262
|
+
const opened = await subtle().decrypt(params, k, buffer(input.ciphertext));
|
|
13263
|
+
return new Uint8Array(opened);
|
|
13264
|
+
};
|
|
13265
|
+
//#endregion
|
|
13266
|
+
export { CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_RECOMMENDATION_TYPES, DelegatedSessionExpiredError, HPKE_ALG, ID_HASH_FORMATS, LosslessNumber, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, addLines, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, auth, base64UrlDecode, base64UrlEncode, buildCustomerSnapshot, buildRulesEngineFromOrder, buildScheduleSlots, canEnterJoin, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, computeStartingPrice, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultOutgoingEdge, detectCardBrand, enterWorkflowNode, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getLogContext, getScheduleWindow, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeviceCharged, isDeviceNotLinked, isExpiryComplete, isGenId, isKioskUnauthorized, isMilestoneStepDone, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isScheduleSlot, isScheduledAtError, isStateHash, isStorefrontNotFound, isTerminalMappedStatus, isVariantBase, linePayableTotal, listMenusStream, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizePickupName, normalizeStateScope, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, paymentMatchesClientConditions, pickAdvanceTarget, pickMultiLanguageText, placeCartLines, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, resolveAdvanceEdge, resolveAdvanceEdges, resolveCheckout, resolveFailureTerminalEdge, resolveModifierImageUrl, resolveSchedulePrepMinutes, resolveSuccessTerminalEdges, reversePayment, reversedWhenCaptured, roundFeeAmount, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateExpiry, validateOrderAgainstMenu, validatePickupName, verifyWebhookSignature, visitedStates };
|