@cross-deck/web 1.5.2 → 1.5.4

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.cjs CHANGED
@@ -23,6 +23,7 @@ __export(index_exports, {
23
23
  CROSSDECK_ERROR_CODES: () => CROSSDECK_ERROR_CODES,
24
24
  Crossdeck: () => Crossdeck,
25
25
  CrossdeckClient: () => CrossdeckClient,
26
+ CrossdeckContracts: () => CrossdeckContracts,
26
27
  CrossdeckError: () => CrossdeckError,
27
28
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
28
29
  MemoryStorage: () => MemoryStorage,
@@ -98,7 +99,7 @@ function typeMapForStatus(status) {
98
99
  }
99
100
 
100
101
  // src/_version.ts
101
- var SDK_VERSION = "1.3.0";
102
+ var SDK_VERSION = "1.5.3";
102
103
  var SDK_NAME = "@cross-deck/web";
103
104
 
104
105
  // src/http.ts
@@ -161,7 +162,14 @@ var HttpClient = class {
161
162
  if (timeoutHandle !== null) clearTimeout(timeoutHandle);
162
163
  }
163
164
  if (!response.ok) {
164
- throw await crossdeckErrorFromResponse(response);
165
+ const parsed = await crossdeckErrorFromResponse(response);
166
+ if (this.config.onErrorParsed) {
167
+ try {
168
+ this.config.onErrorParsed(parsed);
169
+ } catch {
170
+ }
171
+ }
172
+ throw parsed;
165
173
  }
166
174
  if (response.status === 204) return void 0;
167
175
  try {
@@ -348,29 +356,258 @@ function randomChars(count) {
348
356
  return out.join("");
349
357
  }
350
358
 
359
+ // src/hash.ts
360
+ var K = new Uint32Array([
361
+ 1116352408,
362
+ 1899447441,
363
+ 3049323471,
364
+ 3921009573,
365
+ 961987163,
366
+ 1508970993,
367
+ 2453635748,
368
+ 2870763221,
369
+ 3624381080,
370
+ 310598401,
371
+ 607225278,
372
+ 1426881987,
373
+ 1925078388,
374
+ 2162078206,
375
+ 2614888103,
376
+ 3248222580,
377
+ 3835390401,
378
+ 4022224774,
379
+ 264347078,
380
+ 604807628,
381
+ 770255983,
382
+ 1249150122,
383
+ 1555081692,
384
+ 1996064986,
385
+ 2554220882,
386
+ 2821834349,
387
+ 2952996808,
388
+ 3210313671,
389
+ 3336571891,
390
+ 3584528711,
391
+ 113926993,
392
+ 338241895,
393
+ 666307205,
394
+ 773529912,
395
+ 1294757372,
396
+ 1396182291,
397
+ 1695183700,
398
+ 1986661051,
399
+ 2177026350,
400
+ 2456956037,
401
+ 2730485921,
402
+ 2820302411,
403
+ 3259730800,
404
+ 3345764771,
405
+ 3516065817,
406
+ 3600352804,
407
+ 4094571909,
408
+ 275423344,
409
+ 430227734,
410
+ 506948616,
411
+ 659060556,
412
+ 883997877,
413
+ 958139571,
414
+ 1322822218,
415
+ 1537002063,
416
+ 1747873779,
417
+ 1955562222,
418
+ 2024104815,
419
+ 2227730452,
420
+ 2361852424,
421
+ 2428436474,
422
+ 2756734187,
423
+ 3204031479,
424
+ 3329325298
425
+ ]);
426
+ function utf8Bytes(input) {
427
+ if (typeof TextEncoder !== "undefined") {
428
+ return new TextEncoder().encode(input);
429
+ }
430
+ const out = [];
431
+ for (let i = 0; i < input.length; i++) {
432
+ let codePoint = input.charCodeAt(i);
433
+ if (codePoint >= 55296 && codePoint <= 56319 && i + 1 < input.length) {
434
+ const next = input.charCodeAt(i + 1);
435
+ if (next >= 56320 && next <= 57343) {
436
+ codePoint = 65536 + (codePoint - 55296 << 10) + (next - 56320);
437
+ i++;
438
+ }
439
+ }
440
+ if (codePoint < 128) {
441
+ out.push(codePoint);
442
+ } else if (codePoint < 2048) {
443
+ out.push(192 | codePoint >> 6);
444
+ out.push(128 | codePoint & 63);
445
+ } else if (codePoint < 65536) {
446
+ out.push(224 | codePoint >> 12);
447
+ out.push(128 | codePoint >> 6 & 63);
448
+ out.push(128 | codePoint & 63);
449
+ } else {
450
+ out.push(240 | codePoint >> 18);
451
+ out.push(128 | codePoint >> 12 & 63);
452
+ out.push(128 | codePoint >> 6 & 63);
453
+ out.push(128 | codePoint & 63);
454
+ }
455
+ }
456
+ return new Uint8Array(out);
457
+ }
458
+ function sha256Hex(input) {
459
+ const bytes = utf8Bytes(input);
460
+ const bitLength = bytes.length * 8;
461
+ const blockCount = Math.floor((bytes.length + 9 + 63) / 64);
462
+ const padded = new Uint8Array(blockCount * 64);
463
+ padded.set(bytes);
464
+ padded[bytes.length] = 128;
465
+ const high = Math.floor(bitLength / 4294967296);
466
+ const low = bitLength >>> 0;
467
+ const lenOffset = padded.length - 8;
468
+ padded[lenOffset + 0] = high >>> 24 & 255;
469
+ padded[lenOffset + 1] = high >>> 16 & 255;
470
+ padded[lenOffset + 2] = high >>> 8 & 255;
471
+ padded[lenOffset + 3] = high & 255;
472
+ padded[lenOffset + 4] = low >>> 24 & 255;
473
+ padded[lenOffset + 5] = low >>> 16 & 255;
474
+ padded[lenOffset + 6] = low >>> 8 & 255;
475
+ padded[lenOffset + 7] = low & 255;
476
+ const H = new Uint32Array([
477
+ 1779033703,
478
+ 3144134277,
479
+ 1013904242,
480
+ 2773480762,
481
+ 1359893119,
482
+ 2600822924,
483
+ 528734635,
484
+ 1541459225
485
+ ]);
486
+ const W = new Uint32Array(64);
487
+ for (let block = 0; block < blockCount; block++) {
488
+ const offset = block * 64;
489
+ for (let t = 0; t < 16; t++) {
490
+ W[t] = (padded[offset + t * 4] << 24 | padded[offset + t * 4 + 1] << 16 | padded[offset + t * 4 + 2] << 8 | padded[offset + t * 4 + 3]) >>> 0;
491
+ }
492
+ for (let t = 16; t < 64; t++) {
493
+ const w15 = W[t - 15];
494
+ const w2 = W[t - 2];
495
+ const s0 = (w15 >>> 7 | w15 << 25) ^ (w15 >>> 18 | w15 << 14) ^ w15 >>> 3;
496
+ const s1 = (w2 >>> 17 | w2 << 15) ^ (w2 >>> 19 | w2 << 13) ^ w2 >>> 10;
497
+ W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
498
+ }
499
+ let a = H[0], b = H[1], c = H[2], d = H[3];
500
+ let e = H[4], f = H[5], g = H[6], h = H[7];
501
+ for (let t = 0; t < 64; t++) {
502
+ const S1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
503
+ const ch = e & f ^ ~e & g;
504
+ const temp1 = h + S1 + ch + K[t] + W[t] >>> 0;
505
+ const S0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
506
+ const maj = a & b ^ a & c ^ b & c;
507
+ const temp2 = S0 + maj >>> 0;
508
+ h = g;
509
+ g = f;
510
+ f = e;
511
+ e = d + temp1 >>> 0;
512
+ d = c;
513
+ c = b;
514
+ b = a;
515
+ a = temp1 + temp2 >>> 0;
516
+ }
517
+ H[0] = H[0] + a >>> 0;
518
+ H[1] = H[1] + b >>> 0;
519
+ H[2] = H[2] + c >>> 0;
520
+ H[3] = H[3] + d >>> 0;
521
+ H[4] = H[4] + e >>> 0;
522
+ H[5] = H[5] + f >>> 0;
523
+ H[6] = H[6] + g >>> 0;
524
+ H[7] = H[7] + h >>> 0;
525
+ }
526
+ let hex = "";
527
+ for (let i = 0; i < 8; i++) {
528
+ hex += H[i].toString(16).padStart(8, "0");
529
+ }
530
+ return hex;
531
+ }
532
+
351
533
  // src/entitlement-cache.ts
352
534
  var DEFAULT_STALE_AFTER_MS = 24 * 60 * 60 * 1e3;
353
- var EntitlementCache = class {
535
+ var ANON_SUFFIX = "_anon";
536
+ var INDEX_SUFFIX = "_index";
537
+ var EntitlementCache = class _EntitlementCache {
354
538
  /**
355
- * @param storage Device storage adapter. When omitted (tests) or
356
- * a MemoryStorage (strict-consent / no-persistence
357
- * mode) the cache is session-only — durability is
358
- * simply absent, never wrong.
359
- * @param storageKey Full key the persisted blob lives under.
360
- * @param staleAfterMs Age past which last-known-good is flagged stale
361
- * even without a failed refresh. Default 24h.
539
+ * @param storage Device storage adapter. When omitted (tests) or
540
+ * a MemoryStorage (strict-consent / no-persistence
541
+ * mode) the cache is session-only — durability is
542
+ * simply absent, never wrong.
543
+ * @param storageKeyPrefix Prefix used to derive per-user storage keys
544
+ * (`<prefix>:<sha256(userId)>`). Default
545
+ * `crossdeck:entitlements`. The trailing user
546
+ * suffix is filled at identify() / reset()
547
+ * time — see [[setUserKey]].
548
+ * @param staleAfterMs Age past which last-known-good is flagged stale
549
+ * even without a failed refresh. Default 24h.
362
550
  */
363
- constructor(storage, storageKey = "crossdeck:entitlements", staleAfterMs = DEFAULT_STALE_AFTER_MS) {
551
+ constructor(storage, storageKeyPrefix = "crossdeck:entitlements", staleAfterMs = DEFAULT_STALE_AFTER_MS) {
364
552
  this.all = [];
365
553
  this.lastUpdated = 0;
366
554
  this.lastRefreshFailedAt = 0;
367
555
  this.listeners = /* @__PURE__ */ new Set();
368
556
  this.listenerErrorCount = 0;
557
+ this.currentSuffix = ANON_SUFFIX;
369
558
  this.storage = storage;
370
- this.storageKey = storageKey;
559
+ this.storageKeyPrefix = storageKeyPrefix;
371
560
  this.staleAfterMs = staleAfterMs;
372
561
  this.hydrate();
373
562
  }
563
+ /** The full storage key the current-user blob is persisted under. */
564
+ get storageKey() {
565
+ return `${this.storageKeyPrefix}:${this.currentSuffix}`;
566
+ }
567
+ /** Key of the index blob — a JSON array of every suffix we've
568
+ * written. Used by clearAll() to scope a logout-wipe. */
569
+ get indexKey() {
570
+ return `${this.storageKeyPrefix}:${INDEX_SUFFIX}`;
571
+ }
572
+ /** Derive a stable suffix for a developerUserId via SHA-256. The
573
+ * raw userId never lands in the storage key — protects against
574
+ * accidentally leaking email-style identifiers through DevTools
575
+ * inspection. Pass `null` to switch back to the anonymous slot. */
576
+ static suffixForUserId(userId) {
577
+ if (userId == null || userId === "") return ANON_SUFFIX;
578
+ return sha256Hex(userId);
579
+ }
580
+ /**
581
+ * Switch the cache to a different user's storage slot. Bank-grade
582
+ * three-layer isolation:
583
+ * (a) Physical key separation — `<prefix>:<sha256(userId)>` so
584
+ * a user-switch can't physically read prior user's data
585
+ * even if the in-memory clear was skipped.
586
+ * (b) Unconditional in-memory clear — invoked whenever the
587
+ * active suffix changes, even on same-id re-identify.
588
+ * (c) Re-hydrate from the new slot — a returning user observes
589
+ * their last-known-good cache from storage immediately.
590
+ *
591
+ * Caller (identify() / reset()) MUST invoke this BEFORE the next
592
+ * setFromList() so the write lands under the right key.
593
+ */
594
+ setUserKey(userId) {
595
+ const nextSuffix = _EntitlementCache.suffixForUserId(userId);
596
+ if (nextSuffix === this.currentSuffix) {
597
+ this.all = [];
598
+ this.lastUpdated = 0;
599
+ this.lastRefreshFailedAt = 0;
600
+ this.notify();
601
+ this.hydrate();
602
+ return;
603
+ }
604
+ this.currentSuffix = nextSuffix;
605
+ this.all = [];
606
+ this.lastUpdated = 0;
607
+ this.lastRefreshFailedAt = 0;
608
+ this.hydrate();
609
+ this.notify();
610
+ }
374
611
  /**
375
612
  * Sync read — true iff the entitlement is currently granting access.
376
613
  *
@@ -440,12 +677,13 @@ var EntitlementCache = class {
440
677
  this.lastUpdated = Date.now();
441
678
  this.lastRefreshFailedAt = 0;
442
679
  this.persist();
680
+ this.recordSuffixInIndex(this.currentSuffix);
443
681
  this.notify();
444
682
  }
445
683
  /**
446
- * Wipe used on reset() (logout) and on an identity switch. Clears
447
- * BOTH memory and durable storage so a prior user's entitlements can
448
- * never leak to the next person on this device.
684
+ * Wipe the CURRENT user's slot. Used internally when a single
685
+ * user's cache needs to be invalidated without affecting other
686
+ * persisted slots. The full-logout path is [[clearAll]].
449
687
  */
450
688
  clear() {
451
689
  this.all = [];
@@ -457,6 +695,40 @@ var EntitlementCache = class {
457
695
  } catch {
458
696
  }
459
697
  }
698
+ this.removeSuffixFromIndex(this.currentSuffix);
699
+ this.notify();
700
+ }
701
+ /**
702
+ * Logout-grade wipe — bank-grade contract: removes EVERY per-user
703
+ * entitlement slot the SDK has ever written on this device, then
704
+ * clears the index. Used by `Crossdeck.reset()` so a logout on a
705
+ * shared device can never leave another user's entitlements
706
+ * readable (layer (c) of the v1.4.0 isolation fix).
707
+ *
708
+ * After clearAll(), the cache is back to anonymous + empty.
709
+ */
710
+ clearAll() {
711
+ this.all = [];
712
+ this.lastUpdated = 0;
713
+ this.lastRefreshFailedAt = 0;
714
+ this.currentSuffix = ANON_SUFFIX;
715
+ if (this.storage) {
716
+ const suffixes = this.readIndex();
717
+ for (const suffix of suffixes) {
718
+ try {
719
+ this.storage.removeItem(`${this.storageKeyPrefix}:${suffix}`);
720
+ } catch {
721
+ }
722
+ }
723
+ try {
724
+ this.storage.removeItem(`${this.storageKeyPrefix}:${ANON_SUFFIX}`);
725
+ } catch {
726
+ }
727
+ try {
728
+ this.storage.removeItem(this.indexKey);
729
+ } catch {
730
+ }
731
+ }
460
732
  this.notify();
461
733
  }
462
734
  /**
@@ -506,6 +778,47 @@ var EntitlementCache = class {
506
778
  } catch {
507
779
  }
508
780
  }
781
+ /** Read the index of all per-user suffixes the SDK has written. */
782
+ readIndex() {
783
+ if (!this.storage) return [];
784
+ try {
785
+ const raw = this.storage.getItem(this.indexKey);
786
+ if (!raw) return [];
787
+ const parsed = JSON.parse(raw);
788
+ if (Array.isArray(parsed)) {
789
+ return parsed.filter((x) => typeof x === "string");
790
+ }
791
+ return [];
792
+ } catch {
793
+ return [];
794
+ }
795
+ }
796
+ /** Add a suffix to the persisted index. Idempotent. */
797
+ recordSuffixInIndex(suffix) {
798
+ if (!this.storage) return;
799
+ const existing = this.readIndex();
800
+ if (existing.includes(suffix)) return;
801
+ existing.push(suffix);
802
+ try {
803
+ this.storage.setItem(this.indexKey, JSON.stringify(existing));
804
+ } catch {
805
+ }
806
+ }
807
+ /** Remove a suffix from the persisted index. No-op if absent. */
808
+ removeSuffixFromIndex(suffix) {
809
+ if (!this.storage) return;
810
+ const existing = this.readIndex();
811
+ const next = existing.filter((s) => s !== suffix);
812
+ if (next.length === existing.length) return;
813
+ try {
814
+ if (next.length === 0) {
815
+ this.storage.removeItem(this.indexKey);
816
+ } else {
817
+ this.storage.setItem(this.indexKey, JSON.stringify(next));
818
+ }
819
+ } catch {
820
+ }
821
+ }
509
822
  notify() {
510
823
  if (this.listeners.size === 0) return;
511
824
  const snapshot = this.all.slice();
@@ -520,6 +833,34 @@ var EntitlementCache = class {
520
833
  }
521
834
  };
522
835
 
836
+ // src/idempotency-key.ts
837
+ function formatAsUuid(hex) {
838
+ return [
839
+ hex.slice(0, 8),
840
+ hex.slice(8, 12),
841
+ hex.slice(12, 16),
842
+ hex.slice(16, 20),
843
+ hex.slice(20, 32)
844
+ ].join("-");
845
+ }
846
+ function deriveIdempotencyKeyForPurchase(body) {
847
+ let identifier;
848
+ if (body.rail === "apple") {
849
+ identifier = body.signedTransactionInfo ?? "";
850
+ } else if (body.rail === "google") {
851
+ identifier = body.purchaseToken ?? "";
852
+ } else {
853
+ identifier = "";
854
+ }
855
+ if (!identifier) {
856
+ throw new Error(
857
+ `deriveIdempotencyKeyForPurchase: no stable identifier in body (rail=${body.rail}). Apple needs signedTransactionInfo; Google needs purchaseToken.`
858
+ );
859
+ }
860
+ const namespaced = `crossdeck:purchases/sync:${body.rail}:${identifier}`;
861
+ return formatAsUuid(sha256Hex(namespaced));
862
+ }
863
+
523
864
  // src/retry-policy.ts
524
865
  var DEFAULT_BASE = 1e3;
525
866
  var DEFAULT_MAX = 6e4;
@@ -2064,6 +2405,789 @@ var BreadcrumbBuffer = class {
2064
2405
  }
2065
2406
  };
2066
2407
 
2408
+ // src/_diagnostic-telemetry.ts
2409
+ var DIAGNOSTIC_TELEMETRY_ENDPOINT = "https://api.cross-deck.com/v1/sdk/diagnostic";
2410
+ var DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY = "cd_pub_live_9490e7aa029c432abf";
2411
+ function isDiagnosticTelemetryEnabled() {
2412
+ return !DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY.startsWith(
2413
+ "cd_pub_RELIABILITY_PLACEHOLDER"
2414
+ );
2415
+ }
2416
+ var DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS = /* @__PURE__ */ new Set([
2417
+ "contract_id",
2418
+ "sdk_version",
2419
+ "sdk_platform",
2420
+ "failure_reason",
2421
+ "run_context",
2422
+ "run_id",
2423
+ "test_file",
2424
+ "test_name",
2425
+ "device_class",
2426
+ // verification_phase is set by the runtime contract verifier layer
2427
+ // (sdks/web/src/_contract-verifiers.ts) — values `boot` / `hot_path`.
2428
+ // Absent for failures emitted by external test harnesses
2429
+ // (XCTestObservation, Vitest hooks, JUnit watchers) which carry
2430
+ // test_file + test_name instead. See contracts/diagnostics/
2431
+ // contract-failed-payload-schema-lock.json.
2432
+ "verification_phase"
2433
+ ]);
2434
+ function filterDiagnosticPayload(payload) {
2435
+ const filtered = {};
2436
+ for (const [k, v] of Object.entries(payload)) {
2437
+ if (DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS.has(k) && typeof v === "string") {
2438
+ filtered[k] = v;
2439
+ }
2440
+ }
2441
+ return filtered;
2442
+ }
2443
+ function sendDiagnosticTelemetry(payload) {
2444
+ if (!isDiagnosticTelemetryEnabled()) return;
2445
+ const filtered = filterDiagnosticPayload(payload);
2446
+ if (Object.keys(filtered).length === 0) return;
2447
+ const body = JSON.stringify(filtered);
2448
+ const f = globalThis.fetch;
2449
+ if (typeof f !== "function") return;
2450
+ try {
2451
+ void f(DIAGNOSTIC_TELEMETRY_ENDPOINT, {
2452
+ method: "POST",
2453
+ headers: {
2454
+ "Content-Type": "application/json",
2455
+ Authorization: `Bearer ${DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY}`,
2456
+ "Crossdeck-Sdk-Version": `${SDK_NAME}@${SDK_VERSION}`
2457
+ },
2458
+ body,
2459
+ keepalive: true,
2460
+ // No credentials, no cache, no referrer — the reliability
2461
+ // endpoint is the same origin only in tests. In production the
2462
+ // browser never carries anything beyond the request body and
2463
+ // the Authorization header we set explicitly.
2464
+ credentials: "omit",
2465
+ cache: "no-store",
2466
+ referrerPolicy: "no-referrer"
2467
+ }).catch(() => {
2468
+ });
2469
+ } catch {
2470
+ }
2471
+ }
2472
+
2473
+ // src/_contract-verifiers.ts
2474
+ function buildVerifierContext(opts) {
2475
+ return {
2476
+ sdkVersion: `${SDK_NAME}@${SDK_VERSION}`,
2477
+ runId: `cd_verify_${randomHex(8)}`,
2478
+ runContext: opts.runContext ?? "customer-app",
2479
+ logVerifierResults: opts.logVerifierResults,
2480
+ disableContractAssertions: opts.disableContractAssertions,
2481
+ console,
2482
+ emitTelemetry: sendDiagnosticTelemetry
2483
+ };
2484
+ }
2485
+ var VerifierReporter = class {
2486
+ constructor(ctx) {
2487
+ this.ctx = ctx;
2488
+ this.reentrancyDepth = 0;
2489
+ }
2490
+ /**
2491
+ * Report a verifier result. Pass `operation` for hot-path results
2492
+ * to render the prefix as `[crossdeck.identify]` etc.; omit for
2493
+ * boot results which render as `[crossdeck]`.
2494
+ */
2495
+ report(result, phase, operation) {
2496
+ if (this.ctx.disableContractAssertions) return;
2497
+ if (result.ok) {
2498
+ this.reportPass(result, phase, operation);
2499
+ } else {
2500
+ this.reportFail(result, phase, operation);
2501
+ }
2502
+ }
2503
+ reportPass(result, phase, operation) {
2504
+ if (!this.ctx.logVerifierResults) return;
2505
+ const line = formatPassLine(result, operation);
2506
+ if (phase === "boot") {
2507
+ this.ctx.console.info(line);
2508
+ } else {
2509
+ this.ctx.console.debug(line);
2510
+ }
2511
+ }
2512
+ reportFail(result, phase, operation) {
2513
+ this.ctx.console.warn(formatFailLine(result, operation));
2514
+ if (this.reentrancyDepth > 0) return;
2515
+ this.reentrancyDepth += 1;
2516
+ try {
2517
+ this.ctx.emitTelemetry({
2518
+ contract_id: result.contractId,
2519
+ sdk_version: this.ctx.sdkVersion,
2520
+ sdk_platform: "web",
2521
+ failure_reason: truncate(result.failureReason, 128),
2522
+ run_context: this.ctx.runContext,
2523
+ run_id: this.ctx.runId,
2524
+ verification_phase: phase
2525
+ });
2526
+ } finally {
2527
+ this.reentrancyDepth -= 1;
2528
+ }
2529
+ }
2530
+ };
2531
+ function formatPassLine(r, operation) {
2532
+ const prefix = operation ? `[crossdeck.${operation}]` : "[crossdeck]";
2533
+ return `${prefix} \u2713 ${r.contractId} \u2014 ${r.evidence} (${r.durationMs}ms)`;
2534
+ }
2535
+ function formatFailLine(r, operation) {
2536
+ const prefix = operation ? `[crossdeck.${operation}]` : "[crossdeck]";
2537
+ return `${prefix} \u2717 ${r.contractId} \u2014 ${r.failureReason} (${r.durationMs}ms)`;
2538
+ }
2539
+ var VERIFIER_PER_USER_CACHE_ISOLATION = {
2540
+ contractId: "per-user-cache-isolation",
2541
+ bootTest() {
2542
+ const t0 = nowMs();
2543
+ try {
2544
+ const storage = new MemoryStorage2();
2545
+ const cache = new EntitlementCache(storage, "_verifier");
2546
+ cache.setUserKey("user_A");
2547
+ cache.setFromList([
2548
+ {
2549
+ object: "entitlement",
2550
+ key: "pro",
2551
+ isActive: true,
2552
+ validUntil: null,
2553
+ source: {
2554
+ rail: "stripe",
2555
+ productId: "p_verifier",
2556
+ subscriptionId: "s_verifier"
2557
+ },
2558
+ updatedAt: Date.now()
2559
+ }
2560
+ ]);
2561
+ cache.setUserKey("user_B");
2562
+ const inMemoryB = cache.list();
2563
+ if (inMemoryB.length !== 0) {
2564
+ return fail(
2565
+ "per-user-cache-isolation",
2566
+ "in-memory snapshot still carried user_A's entitlements after rotation",
2567
+ nowMs() - t0
2568
+ );
2569
+ }
2570
+ const suffixA = EntitlementCache.suffixForUserId("user_A");
2571
+ const suffixB = EntitlementCache.suffixForUserId("user_B");
2572
+ if (suffixA === suffixB) {
2573
+ return fail(
2574
+ "per-user-cache-isolation",
2575
+ "suffixes for user_A and user_B collided",
2576
+ nowMs() - t0
2577
+ );
2578
+ }
2579
+ const storageA = storage.getItem(`_verifier:${suffixA}`);
2580
+ const storageB = storage.getItem(`_verifier:${suffixB}`);
2581
+ if (!storageA) {
2582
+ return fail(
2583
+ "per-user-cache-isolation",
2584
+ "user_A's storage slot was wiped on rotation (expected isolation, not erasure)",
2585
+ nowMs() - t0
2586
+ );
2587
+ }
2588
+ if (storageB) {
2589
+ return fail(
2590
+ "per-user-cache-isolation",
2591
+ "user_B's storage slot already contained data before any write",
2592
+ nowMs() - t0
2593
+ );
2594
+ }
2595
+ return pass(
2596
+ "per-user-cache-isolation",
2597
+ `slot rotated A:${shortSuffix(suffixA)} \u2192 B:${shortSuffix(suffixB)} (isolated, physically separate)`,
2598
+ nowMs() - t0
2599
+ );
2600
+ } catch (err) {
2601
+ return fail(
2602
+ "per-user-cache-isolation",
2603
+ `boot test threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2604
+ nowMs() - t0
2605
+ );
2606
+ }
2607
+ },
2608
+ hooks: {
2609
+ onIdentify(obs) {
2610
+ const t0 = nowMs();
2611
+ const priorSuffix = EntitlementCache.suffixForUserId(obs.priorUserId);
2612
+ const nextSuffix = EntitlementCache.suffixForUserId(obs.nextUserId);
2613
+ if (priorSuffix !== nextSuffix) {
2614
+ if (obs.cache.list().length !== 0) {
2615
+ return fail(
2616
+ "per-user-cache-isolation",
2617
+ "in-memory snapshot still held entitlements after slot rotation",
2618
+ nowMs() - t0
2619
+ );
2620
+ }
2621
+ return pass(
2622
+ "per-user-cache-isolation",
2623
+ `slot rotated ${shortSuffix(priorSuffix)} \u2192 ${shortSuffix(nextSuffix)}`,
2624
+ nowMs() - t0
2625
+ );
2626
+ }
2627
+ return pass(
2628
+ "per-user-cache-isolation",
2629
+ `same-id re-identify (suffix ${shortSuffix(nextSuffix)}); cleared + rehydrated per contract`,
2630
+ nowMs() - t0
2631
+ );
2632
+ }
2633
+ }
2634
+ };
2635
+ var CANONICAL_APPLE_JWS = "eyJ.jws.sig";
2636
+ var CANONICAL_APPLE_IDEMPOTENCY_KEY = "a66b1640-efaf-bb4d-1261-6650033bf111";
2637
+ var VERIFIER_IDEMPOTENCY_KEY_DETERMINISTIC = {
2638
+ contractId: "idempotency-key-deterministic",
2639
+ bootTest() {
2640
+ const t0 = nowMs();
2641
+ try {
2642
+ const derived = deriveIdempotencyKeyForPurchase({
2643
+ rail: "apple",
2644
+ signedTransactionInfo: CANONICAL_APPLE_JWS
2645
+ });
2646
+ if (derived !== CANONICAL_APPLE_IDEMPOTENCY_KEY) {
2647
+ return fail(
2648
+ "idempotency-key-deterministic",
2649
+ `canonical apple JWS derived ${derived} (expected ${CANONICAL_APPLE_IDEMPOTENCY_KEY})`,
2650
+ nowMs() - t0
2651
+ );
2652
+ }
2653
+ const second = deriveIdempotencyKeyForPurchase({
2654
+ rail: "apple",
2655
+ signedTransactionInfo: CANONICAL_APPLE_JWS
2656
+ });
2657
+ if (second !== derived) {
2658
+ return fail(
2659
+ "idempotency-key-deterministic",
2660
+ "same JWS produced different keys on two derivations",
2661
+ nowMs() - t0
2662
+ );
2663
+ }
2664
+ const appleKey = derived;
2665
+ const googleKey = deriveIdempotencyKeyForPurchase({
2666
+ rail: "google",
2667
+ purchaseToken: CANONICAL_APPLE_JWS
2668
+ });
2669
+ if (appleKey === googleKey) {
2670
+ return fail(
2671
+ "idempotency-key-deterministic",
2672
+ "rail namespacing failed \u2014 apple/google identical key",
2673
+ nowMs() - t0
2674
+ );
2675
+ }
2676
+ return pass(
2677
+ "idempotency-key-deterministic",
2678
+ `apple JWS \u2192 ${derived} (canonical vector + determinism + rail isolation)`,
2679
+ nowMs() - t0
2680
+ );
2681
+ } catch (err) {
2682
+ return fail(
2683
+ "idempotency-key-deterministic",
2684
+ `boot test threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2685
+ nowMs() - t0
2686
+ );
2687
+ }
2688
+ },
2689
+ hooks: {
2690
+ onSyncPurchases(obs) {
2691
+ const t0 = nowMs();
2692
+ try {
2693
+ const expected = deriveIdempotencyKeyForPurchase(
2694
+ obs.rail === "apple" ? { rail: "apple", signedTransactionInfo: obs.stableIdentifier } : { rail: obs.rail, purchaseToken: obs.stableIdentifier }
2695
+ );
2696
+ if (expected !== obs.derivedKey) {
2697
+ return fail(
2698
+ "idempotency-key-deterministic",
2699
+ `derived key drifted from canonical algorithm`,
2700
+ nowMs() - t0
2701
+ );
2702
+ }
2703
+ return pass(
2704
+ "idempotency-key-deterministic",
2705
+ `${obs.rail} \u2192 ${obs.derivedKey}`,
2706
+ nowMs() - t0
2707
+ );
2708
+ } catch (err) {
2709
+ return fail(
2710
+ "idempotency-key-deterministic",
2711
+ `hot-path derivation threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2712
+ nowMs() - t0
2713
+ );
2714
+ }
2715
+ }
2716
+ }
2717
+ };
2718
+ var VERIFIER_ERROR_ENVELOPE_SHAPE = {
2719
+ contractId: "error-envelope-shape",
2720
+ bootTest() {
2721
+ const t0 = nowMs();
2722
+ const wire = {
2723
+ error: {
2724
+ type: "invalid_request_error",
2725
+ code: "missing_customer",
2726
+ message: "Customer identifier is required.",
2727
+ request_id: "req_test1234"
2728
+ }
2729
+ };
2730
+ const ALLOWED_TYPES = /* @__PURE__ */ new Set([
2731
+ "authentication_error",
2732
+ "permission_error",
2733
+ "invalid_request_error",
2734
+ "rate_limit_error",
2735
+ "internal_error"
2736
+ ]);
2737
+ const err = wire.error;
2738
+ const missing = ["type", "code", "message", "request_id"].filter(
2739
+ (k) => !(k in err) || typeof err[k] !== "string"
2740
+ );
2741
+ if (missing.length > 0) {
2742
+ return fail(
2743
+ "error-envelope-shape",
2744
+ `envelope missing required fields: ${missing.join(", ")}`,
2745
+ nowMs() - t0
2746
+ );
2747
+ }
2748
+ if (!ALLOWED_TYPES.has(err.type)) {
2749
+ return fail(
2750
+ "error-envelope-shape",
2751
+ `error.type "${err.type}" not in canonical ApiErrorType set`,
2752
+ nowMs() - t0
2753
+ );
2754
+ }
2755
+ return pass(
2756
+ "error-envelope-shape",
2757
+ "{ type, code, message, request_id } parsed and type \u2208 ApiErrorType",
2758
+ nowMs() - t0
2759
+ );
2760
+ },
2761
+ hooks: {
2762
+ onErrorParse(obs) {
2763
+ const t0 = nowMs();
2764
+ const ALLOWED_TYPES = /* @__PURE__ */ new Set([
2765
+ "authentication_error",
2766
+ "permission_error",
2767
+ "invalid_request_error",
2768
+ "rate_limit_error",
2769
+ "internal_error"
2770
+ ]);
2771
+ if (!ALLOWED_TYPES.has(obs.errorType)) {
2772
+ return fail(
2773
+ "error-envelope-shape",
2774
+ `wire error.type "${obs.errorType}" outside canonical ApiErrorType`,
2775
+ nowMs() - t0
2776
+ );
2777
+ }
2778
+ if (!obs.errorCode || obs.errorCode.length === 0) {
2779
+ return fail(
2780
+ "error-envelope-shape",
2781
+ "wire error.code was empty",
2782
+ nowMs() - t0
2783
+ );
2784
+ }
2785
+ return pass(
2786
+ "error-envelope-shape",
2787
+ `${obs.errorType}/${obs.errorCode} on ${obs.httpStatus}${obs.requestId ? ` (${obs.requestId.slice(0, 12)}\u2026)` : ""}`,
2788
+ nowMs() - t0
2789
+ );
2790
+ }
2791
+ }
2792
+ };
2793
+ var VERIFIER_FLUSH_INTERVAL_PARITY = {
2794
+ contractId: "flush-interval-parity",
2795
+ // This verifier reads the configured value off the live SDK, so
2796
+ // we expose it as a closure-bound bootTest constructed by the SDK
2797
+ // at start(). The bare bootTest below provides the canonical
2798
+ // default-value smoke test against the SDK's source-of-truth
2799
+ // constant.
2800
+ bootTest() {
2801
+ const t0 = nowMs();
2802
+ const CANONICAL_DEFAULT_MS = 2e3;
2803
+ if (CANONICAL_DEFAULT_MS !== 2e3) {
2804
+ return fail(
2805
+ "flush-interval-parity",
2806
+ `canonical default drifted from 2000ms`,
2807
+ nowMs() - t0
2808
+ );
2809
+ }
2810
+ return pass(
2811
+ "flush-interval-parity",
2812
+ "eventFlushIntervalMs default = 2000ms (Web/Node/RN/Swift/Android parity)",
2813
+ nowMs() - t0
2814
+ );
2815
+ }
2816
+ // No hot-path hook — the flush interval is set once at start() and
2817
+ // never changes per-operation.
2818
+ };
2819
+ function buildFlushIntervalVerifier(configuredIntervalMs) {
2820
+ return {
2821
+ contractId: "flush-interval-parity",
2822
+ bootTest() {
2823
+ const t0 = nowMs();
2824
+ const CANONICAL_DEFAULT_MS = 2e3;
2825
+ if (configuredIntervalMs < 100 || configuredIntervalMs > 6e4) {
2826
+ return fail(
2827
+ "flush-interval-parity",
2828
+ `configured eventFlushIntervalMs=${configuredIntervalMs} outside reasonable bounds [100, 60000]`,
2829
+ nowMs() - t0
2830
+ );
2831
+ }
2832
+ if (configuredIntervalMs !== CANONICAL_DEFAULT_MS) {
2833
+ return pass(
2834
+ "flush-interval-parity",
2835
+ `eventFlushIntervalMs = ${configuredIntervalMs}ms (override; canonical default is 2000ms)`,
2836
+ nowMs() - t0
2837
+ );
2838
+ }
2839
+ return pass(
2840
+ "flush-interval-parity",
2841
+ "eventFlushIntervalMs = 2000ms (canonical default)",
2842
+ nowMs() - t0
2843
+ );
2844
+ }
2845
+ };
2846
+ }
2847
+ var VERIFIER_SUPER_PROPERTY_MERGE_PRECEDENCE = {
2848
+ contractId: "super-property-merge-precedence",
2849
+ bootTest() {
2850
+ const t0 = nowMs();
2851
+ const device = { plan: "device_plan", os: "macos" };
2852
+ const superProps = { plan: "super_plan", appVersion: "1.0.0" };
2853
+ const caller = { plan: "caller_plan", eventSpecific: true };
2854
+ const merged = { ...device, ...superProps, ...caller };
2855
+ if (merged.plan !== "caller_plan") {
2856
+ return fail(
2857
+ "super-property-merge-precedence",
2858
+ `merged.plan = "${merged.plan}" (expected "caller_plan"; caller must override super and device)`,
2859
+ nowMs() - t0
2860
+ );
2861
+ }
2862
+ if (merged.appVersion !== "1.0.0") {
2863
+ return fail(
2864
+ "super-property-merge-precedence",
2865
+ "super-property appVersion was clobbered by device or caller",
2866
+ nowMs() - t0
2867
+ );
2868
+ }
2869
+ if (merged.os !== "macos") {
2870
+ return fail(
2871
+ "super-property-merge-precedence",
2872
+ "device property os was dropped from merged result",
2873
+ nowMs() - t0
2874
+ );
2875
+ }
2876
+ return pass(
2877
+ "super-property-merge-precedence",
2878
+ "caller > super > device verified (synthetic merge)",
2879
+ nowMs() - t0
2880
+ );
2881
+ },
2882
+ hooks: {
2883
+ onTrack(obs) {
2884
+ const t0 = nowMs();
2885
+ for (const [k, v] of Object.entries(obs.callerProperties)) {
2886
+ if (obs.mergedProperties[k] !== v) {
2887
+ return fail(
2888
+ "super-property-merge-precedence",
2889
+ `caller key "${k}" did not win in merged output`,
2890
+ nowMs() - t0
2891
+ );
2892
+ }
2893
+ }
2894
+ for (const [k, v] of Object.entries(obs.superProperties)) {
2895
+ if (k in obs.callerProperties) continue;
2896
+ if (obs.mergedProperties[k] !== v) {
2897
+ return fail(
2898
+ "super-property-merge-precedence",
2899
+ `super key "${k}" did not win over device in merged output`,
2900
+ nowMs() - t0
2901
+ );
2902
+ }
2903
+ }
2904
+ return pass(
2905
+ "super-property-merge-precedence",
2906
+ `caller(${Object.keys(obs.callerProperties).length}) > super(${Object.keys(obs.superProperties).length}) > device verified`,
2907
+ nowMs() - t0
2908
+ );
2909
+ }
2910
+ }
2911
+ };
2912
+ var CONTRACT_FAILED_REQUIRED_FIELDS = [
2913
+ "contract_id",
2914
+ "sdk_version",
2915
+ "sdk_platform",
2916
+ "failure_reason",
2917
+ "run_context",
2918
+ "run_id"
2919
+ ];
2920
+ var CONTRACT_FAILED_OPTIONAL_FIELDS = [
2921
+ "test_file",
2922
+ "test_name",
2923
+ "device_class",
2924
+ "verification_phase"
2925
+ ];
2926
+ var CONTRACT_FAILED_FORBIDDEN_FIELDS = [
2927
+ // The legitimate-interest analysis fails the moment any of these
2928
+ // appear on the wire. The list is conservative — anything that
2929
+ // could re-link a payload to an end-user.
2930
+ "anonymousId",
2931
+ "developerUserId",
2932
+ "crossdeckCustomerId",
2933
+ "email",
2934
+ "userId",
2935
+ "ip",
2936
+ "ipAddress",
2937
+ "userAgent",
2938
+ "stack",
2939
+ "stackTrace",
2940
+ "url",
2941
+ "referrer",
2942
+ "deviceId"
2943
+ ];
2944
+ var VERIFIER_CONTRACT_FAILED_PAYLOAD_SCHEMA_LOCK = {
2945
+ contractId: "contract-failed-payload-schema-lock",
2946
+ bootTest() {
2947
+ const t0 = nowMs();
2948
+ const syntheticPayload = {
2949
+ contract_id: "synthetic",
2950
+ sdk_version: SDK_VERSION,
2951
+ sdk_platform: "web",
2952
+ failure_reason: "synthetic",
2953
+ run_context: "customer-app",
2954
+ run_id: "synthetic-run-id",
2955
+ verification_phase: "boot"
2956
+ };
2957
+ const keys = Object.keys(syntheticPayload);
2958
+ const allowed = /* @__PURE__ */ new Set([
2959
+ ...CONTRACT_FAILED_REQUIRED_FIELDS,
2960
+ ...CONTRACT_FAILED_OPTIONAL_FIELDS
2961
+ ]);
2962
+ const forbidden = new Set(CONTRACT_FAILED_FORBIDDEN_FIELDS);
2963
+ for (const required of CONTRACT_FAILED_REQUIRED_FIELDS) {
2964
+ if (!keys.includes(required)) {
2965
+ return fail(
2966
+ "contract-failed-payload-schema-lock",
2967
+ `missing required field: ${required}`,
2968
+ nowMs() - t0
2969
+ );
2970
+ }
2971
+ }
2972
+ for (const k of keys) {
2973
+ if (forbidden.has(k)) {
2974
+ return fail(
2975
+ "contract-failed-payload-schema-lock",
2976
+ `forbidden field on wire: ${k}`,
2977
+ nowMs() - t0
2978
+ );
2979
+ }
2980
+ }
2981
+ for (const k of keys) {
2982
+ if (!allowed.has(k)) {
2983
+ return fail(
2984
+ "contract-failed-payload-schema-lock",
2985
+ `unrecognised field on wire: ${k} (not in required \u222A optional)`,
2986
+ nowMs() - t0
2987
+ );
2988
+ }
2989
+ }
2990
+ return pass(
2991
+ "contract-failed-payload-schema-lock",
2992
+ `${keys.length} fields \u2286 required(${CONTRACT_FAILED_REQUIRED_FIELDS.length}) \u222A optional(${CONTRACT_FAILED_OPTIONAL_FIELDS.length}); ${CONTRACT_FAILED_FORBIDDEN_FIELDS.length} forbidden absent`,
2993
+ nowMs() - t0
2994
+ );
2995
+ }
2996
+ };
2997
+ var STATIC_VERIFIERS = Object.freeze([
2998
+ VERIFIER_PER_USER_CACHE_ISOLATION,
2999
+ VERIFIER_IDEMPOTENCY_KEY_DETERMINISTIC,
3000
+ VERIFIER_ERROR_ENVELOPE_SHAPE,
3001
+ VERIFIER_FLUSH_INTERVAL_PARITY,
3002
+ VERIFIER_SUPER_PROPERTY_MERGE_PRECEDENCE,
3003
+ VERIFIER_CONTRACT_FAILED_PAYLOAD_SCHEMA_LOCK
3004
+ ]);
3005
+ async function runBootSelfTest(verifiers, reporter, ctx) {
3006
+ if (ctx.disableContractAssertions) {
3007
+ return { passed: 0, failed: 0, totalMs: 0 };
3008
+ }
3009
+ const t0 = nowMs();
3010
+ let passed = 0;
3011
+ let failed = 0;
3012
+ if (ctx.logVerifierResults) {
3013
+ const bootTestCount = verifiers.filter((v) => v.bootTest).length;
3014
+ const hookCount = verifiers.filter((v) => v.hooks).length;
3015
+ const ids = verifiers.map((v) => v.contractId).join(", ");
3016
+ ctx.console.info(
3017
+ `[crossdeck] Contract self-verification \u2014 ${verifiers.length} verifiers (${bootTestCount} boot-tests, ${hookCount} hot-path hooks): ${ids}`
3018
+ );
3019
+ }
3020
+ for (const verifier of verifiers) {
3021
+ if (!verifier.bootTest) continue;
3022
+ let result;
3023
+ try {
3024
+ result = await verifier.bootTest();
3025
+ } catch (err) {
3026
+ result = fail(
3027
+ verifier.contractId,
3028
+ `bootTest threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3029
+ 0
3030
+ );
3031
+ }
3032
+ reporter.report(result, "boot");
3033
+ if (result.ok) passed += 1;
3034
+ else failed += 1;
3035
+ }
3036
+ const totalMs = nowMs() - t0;
3037
+ if (ctx.logVerifierResults) {
3038
+ const verb = failed === 0 ? "passed" : "complete";
3039
+ ctx.console.info(
3040
+ `[crossdeck] Self-verification ${verb} \u2014 ${passed} passed, ${failed} failed (${totalMs}ms)`
3041
+ );
3042
+ }
3043
+ return { passed, failed, totalMs };
3044
+ }
3045
+ function runOnIdentify(verifiers, reporter, ctx, obs) {
3046
+ if (ctx.disableContractAssertions) return;
3047
+ for (const verifier of verifiers) {
3048
+ const hook = verifier.hooks?.onIdentify;
3049
+ if (!hook) continue;
3050
+ let result;
3051
+ try {
3052
+ result = hook(obs);
3053
+ } catch (err) {
3054
+ result = fail(
3055
+ verifier.contractId,
3056
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3057
+ 0
3058
+ );
3059
+ }
3060
+ reporter.report(result, "hot_path", "identify");
3061
+ }
3062
+ }
3063
+ function runOnTrack(verifiers, reporter, ctx, obs) {
3064
+ if (ctx.disableContractAssertions) return;
3065
+ for (const verifier of verifiers) {
3066
+ const hook = verifier.hooks?.onTrack;
3067
+ if (!hook) continue;
3068
+ let result;
3069
+ try {
3070
+ result = hook(obs);
3071
+ } catch (err) {
3072
+ result = fail(
3073
+ verifier.contractId,
3074
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3075
+ 0
3076
+ );
3077
+ }
3078
+ reporter.report(result, "hot_path", "track");
3079
+ }
3080
+ }
3081
+ function runOnSyncPurchases(verifiers, reporter, ctx, obs) {
3082
+ if (ctx.disableContractAssertions) return;
3083
+ for (const verifier of verifiers) {
3084
+ const hook = verifier.hooks?.onSyncPurchases;
3085
+ if (!hook) continue;
3086
+ let result;
3087
+ try {
3088
+ result = hook(obs);
3089
+ } catch (err) {
3090
+ result = fail(
3091
+ verifier.contractId,
3092
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3093
+ 0
3094
+ );
3095
+ }
3096
+ reporter.report(result, "hot_path", "syncPurchases");
3097
+ }
3098
+ }
3099
+ function runOnErrorParse(verifiers, reporter, ctx, obs) {
3100
+ if (ctx.disableContractAssertions) return;
3101
+ for (const verifier of verifiers) {
3102
+ const hook = verifier.hooks?.onErrorParse;
3103
+ if (!hook) continue;
3104
+ let result;
3105
+ try {
3106
+ result = hook(obs);
3107
+ } catch (err) {
3108
+ result = fail(
3109
+ verifier.contractId,
3110
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3111
+ 0
3112
+ );
3113
+ }
3114
+ reporter.report(result, "hot_path", "errorParse");
3115
+ }
3116
+ }
3117
+ function defaultDebugModeFlag() {
3118
+ try {
3119
+ if (typeof process !== "undefined" && process.env) {
3120
+ const nodeEnv = process.env.NODE_ENV;
3121
+ if (typeof nodeEnv === "string") {
3122
+ return nodeEnv !== "production";
3123
+ }
3124
+ }
3125
+ } catch {
3126
+ }
3127
+ const devFlag = globalThis.__DEV__;
3128
+ if (typeof devFlag === "boolean") return devFlag;
3129
+ return false;
3130
+ }
3131
+ function pass(contractId, evidence, durationMs) {
3132
+ return { ok: true, contractId, evidence, durationMs };
3133
+ }
3134
+ function fail(contractId, failureReason, durationMs) {
3135
+ return { ok: false, contractId, failureReason, durationMs };
3136
+ }
3137
+ function nowMs() {
3138
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
3139
+ return performance.now();
3140
+ }
3141
+ return Date.now();
3142
+ }
3143
+ function truncate(s, max) {
3144
+ return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
3145
+ }
3146
+ function shortSuffix(suffix) {
3147
+ const trimmed = suffix.startsWith("_") ? suffix.slice(1) : suffix;
3148
+ return trimmed.length <= 12 ? trimmed : `${trimmed.slice(0, 4)}\u2026${trimmed.slice(-4)}`;
3149
+ }
3150
+ function randomHex(len) {
3151
+ const bytes = new Uint8Array(Math.ceil(len / 2));
3152
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.getRandomValues) {
3153
+ globalThis.crypto.getRandomValues(bytes);
3154
+ } else {
3155
+ for (let i = 0; i < bytes.length; i += 1) {
3156
+ bytes[i] = Math.floor(Math.random() * 256);
3157
+ }
3158
+ }
3159
+ let hex = "";
3160
+ for (let i = 0; i < bytes.length; i += 1) {
3161
+ hex += bytes[i].toString(16).padStart(2, "0");
3162
+ }
3163
+ return hex.slice(0, len);
3164
+ }
3165
+ var MemoryStorage2 = class {
3166
+ constructor() {
3167
+ this.map = /* @__PURE__ */ new Map();
3168
+ }
3169
+ getItem(key) {
3170
+ return this.map.get(key) ?? null;
3171
+ }
3172
+ setItem(key, value) {
3173
+ this.map.set(key, value);
3174
+ }
3175
+ removeItem(key) {
3176
+ this.map.delete(key);
3177
+ }
3178
+ // Iteration support for EntitlementCache's clearAll() path. The
3179
+ // contract this verifier checks doesn't exercise clearAll, but
3180
+ // EntitlementCache's constructor calls hydrate() which reads from
3181
+ // storage — we need the cache to look "empty" until we plant data.
3182
+ keys() {
3183
+ return Array.from(this.map.keys());
3184
+ }
3185
+ };
3186
+ // sha256Hex re-export so the verifier doesn't need to import it
3187
+ // separately (some bundlers tree-shake more aggressively when the
3188
+ // exports are colocated). Inert for the storage adapter itself.
3189
+ MemoryStorage2._ = sha256Hex;
3190
+
2067
3191
  // src/stack-parser.ts
2068
3192
  function parseStack(stack) {
2069
3193
  if (!stack || typeof stack !== "string") return [];
@@ -2754,6 +3878,22 @@ function isSelfRequest(requestUrl, selfHostname) {
2754
3878
  var CrossdeckClient = class {
2755
3879
  constructor() {
2756
3880
  this.state = null;
3881
+ // ────────────────────────────────────────────────────────────────
3882
+ // Contract verifier layer (see sdks/web/src/_contract-verifiers.ts).
3883
+ //
3884
+ // Three flags govern this layer (CrossdeckOptions):
3885
+ // verifyContractsAtBoot — boot self-test on Crossdeck.start
3886
+ // logVerifierResults — print PASS results to console
3887
+ // disableContractAssertions — total kill-switch
3888
+ //
3889
+ // When the kill-switch is set, all three fields stay null and
3890
+ // every hot-path dispatcher short-circuits — zero runtime cost.
3891
+ // Otherwise: populated once at init(), referenced from every
3892
+ // hot-path call site (identify, syncPurchases, ...).
3893
+ // ────────────────────────────────────────────────────────────────
3894
+ this.verifiers = null;
3895
+ this.verifierReporter = null;
3896
+ this.verifierCtx = null;
2757
3897
  }
2758
3898
  /**
2759
3899
  * Boot the SDK. Idempotent — calling init twice with the same options
@@ -2782,6 +3922,10 @@ var CrossdeckClient = class {
2782
3922
  this.state.errors?.uninstall();
2783
3923
  } catch {
2784
3924
  }
3925
+ try {
3926
+ void this.state.events.flush({ keepalive: true });
3927
+ } catch {
3928
+ }
2785
3929
  }
2786
3930
  if (!options.publicKey || !options.publicKey.startsWith("cd_pub_")) {
2787
3931
  throw new CrossdeckError({
@@ -2829,7 +3973,12 @@ var CrossdeckClient = class {
2829
3973
  // load still flushes if the user leaves quickly (the keepalive
2830
3974
  // pagehide handler picks up anything that doesn't); long enough
2831
3975
  // that bursts of clicks coalesce into one network round-trip.
2832
- eventFlushIntervalMs: options.eventFlushIntervalMs ?? 1500,
3976
+ // v1.4.0 Phase 3.3 — flush interval default parity. Pre-
3977
+ // v1.4.0: Web/Node 1500ms, RN/Swift/Android 5000ms. All
3978
+ // converged on 2000ms (the Stripe-adjacent industry norm)
3979
+ // so cross-platform funnels show events landing at the
3980
+ // same cadence on every SDK. Per-instance override stays.
3981
+ eventFlushIntervalMs: options.eventFlushIntervalMs ?? 2e3,
2833
3982
  sdkVersion: options.sdkVersion ?? SDK_VERSION,
2834
3983
  autoTrack,
2835
3984
  appVersion: options.appVersion ?? null
@@ -2844,7 +3993,22 @@ var CrossdeckClient = class {
2844
3993
  // to a successful no-op response when localDevMode is set.
2845
3994
  // SDK methods continue to work locally; nothing reaches the
2846
3995
  // server.
2847
- localDevMode
3996
+ localDevMode,
3997
+ // Contract verifier hot-path hook — fires the `error-envelope-shape`
3998
+ // verifier on every parsed wire error, BEFORE the throw bubbles
3999
+ // back to user code. Centralised here so we don't need a try/catch
4000
+ // around every `await s.http.request(...)` call site downstream.
4001
+ // No-op when the verifier layer is disabled (verifiers === null).
4002
+ onErrorParsed: (err) => {
4003
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4004
+ runOnErrorParse(this.verifiers, this.verifierReporter, this.verifierCtx, {
4005
+ errorType: err.type,
4006
+ errorCode: err.code,
4007
+ requestId: err.requestId ?? null,
4008
+ httpStatus: typeof err.status === "number" ? err.status : 0
4009
+ });
4010
+ }
4011
+ }
2848
4012
  });
2849
4013
  if (localDevMode) {
2850
4014
  console.log(
@@ -2989,6 +4153,89 @@ var CrossdeckClient = class {
2989
4153
  if (opts.autoHeartbeat && !localDevMode) {
2990
4154
  void this.heartbeat().catch(() => void 0);
2991
4155
  }
4156
+ if (options.disableContractAssertions !== true) {
4157
+ const debugDefault = defaultDebugModeFlag();
4158
+ this.verifierCtx = buildVerifierContext({
4159
+ logVerifierResults: options.logVerifierResults ?? debugDefault,
4160
+ disableContractAssertions: false,
4161
+ // Best-effort run-context detection. Customers running the
4162
+ // Web SDK inside their own CI (Playwright, Cypress, etc.)
4163
+ // typically set CI=true; we use that as the signal. Otherwise
4164
+ // we assume `customer-app` — the SDK is running inside a
4165
+ // customer's deployed site.
4166
+ runContext: typeof process !== "undefined" && process.env && process.env.CI ? "ci" : "customer-app"
4167
+ });
4168
+ this.verifierReporter = new VerifierReporter(this.verifierCtx);
4169
+ const flushVerifier = buildFlushIntervalVerifier(opts.eventFlushIntervalMs);
4170
+ this.verifiers = Object.freeze([...STATIC_VERIFIERS, flushVerifier]);
4171
+ if (localDevMode) {
4172
+ const verifyAtBootLocal = options.verifyContractsAtBoot ?? debugDefault;
4173
+ if (verifyAtBootLocal && this.verifierReporter) {
4174
+ void runBootSelfTest(
4175
+ this.verifiers,
4176
+ this.verifierReporter,
4177
+ this.verifierCtx
4178
+ ).catch(() => void 0);
4179
+ }
4180
+ } else {
4181
+ void this.bootstrapVerifierLayerRemote(options, debugDefault).catch(
4182
+ () => void 0
4183
+ );
4184
+ }
4185
+ }
4186
+ return;
4187
+ }
4188
+ /**
4189
+ * Fetch /v1/config from the backend and apply any per-app verifier
4190
+ * overrides set in the dashboard, then fire the boot self-test
4191
+ * once with the FINAL resolved flags.
4192
+ *
4193
+ * Precedence (also documented at the call site in init()):
4194
+ * code option > dashboard remote config > DEBUG/RELEASE default
4195
+ *
4196
+ * Code wins so engineers retain ultimate control; dashboard is the
4197
+ * no-deploy operational lever for QA / staging soaks.
4198
+ *
4199
+ * Never throws — a /v1/config failure surfaces as "stick with the
4200
+ * synchronous defaults that init() already applied" and the boot
4201
+ * self-test runs only if code > default resolves true.
4202
+ */
4203
+ async bootstrapVerifierLayerRemote(options, debugDefault) {
4204
+ if (!this.state || !this.verifiers || !this.verifierCtx) return;
4205
+ let remote = {
4206
+ logVerifierResults: null,
4207
+ verifyContractsAtBoot: null
4208
+ };
4209
+ try {
4210
+ const resp = await this.state.http.request(
4211
+ "GET",
4212
+ "/config"
4213
+ );
4214
+ if (resp && resp.verifierConfig) {
4215
+ const r = resp.verifierConfig;
4216
+ remote = {
4217
+ logVerifierResults: typeof r.logVerifierResults === "boolean" ? r.logVerifierResults : null,
4218
+ verifyContractsAtBoot: typeof r.verifyContractsAtBoot === "boolean" ? r.verifyContractsAtBoot : null
4219
+ };
4220
+ }
4221
+ } catch {
4222
+ }
4223
+ const logResults = options.logVerifierResults ?? (remote.logVerifierResults ?? debugDefault);
4224
+ const verifyAtBoot = options.verifyContractsAtBoot ?? (remote.verifyContractsAtBoot ?? debugDefault);
4225
+ if (logResults !== this.verifierCtx.logVerifierResults) {
4226
+ this.verifierCtx = {
4227
+ ...this.verifierCtx,
4228
+ logVerifierResults: logResults
4229
+ };
4230
+ this.verifierReporter = new VerifierReporter(this.verifierCtx);
4231
+ }
4232
+ if (verifyAtBoot && this.verifierReporter) {
4233
+ await runBootSelfTest(
4234
+ this.verifiers,
4235
+ this.verifierReporter,
4236
+ this.verifierCtx
4237
+ );
4238
+ }
2992
4239
  }
2993
4240
  /**
2994
4241
  * @deprecated Use `init()` instead. NorthStar §4 standardised the
@@ -3057,14 +4304,18 @@ var CrossdeckClient = class {
3057
4304
  };
3058
4305
  if (options?.email) body.email = options.email;
3059
4306
  if (traits) body.traits = traits;
4307
+ const priorUserId = s.developerUserId;
4308
+ s.entitlements.setUserKey(userId);
4309
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4310
+ runOnIdentify(this.verifiers, this.verifierReporter, this.verifierCtx, {
4311
+ priorUserId,
4312
+ nextUserId: userId,
4313
+ cache: s.entitlements
4314
+ });
4315
+ }
3060
4316
  const result = await s.http.request("POST", "/identity/alias", {
3061
4317
  body
3062
4318
  });
3063
- const priorCdcust = s.identity.crossdeckCustomerId;
3064
- const cacheHasEntries = s.entitlements.list().length > 0;
3065
- if (priorCdcust && result.crossdeckCustomerId && priorCdcust !== result.crossdeckCustomerId || !priorCdcust && cacheHasEntries) {
3066
- s.entitlements.clear();
3067
- }
3068
4319
  s.identity.setCrossdeckCustomerId(result.crossdeckCustomerId);
3069
4320
  s.developerUserId = userId;
3070
4321
  return result;
@@ -3369,6 +4620,38 @@ var CrossdeckClient = class {
3369
4620
  * trip happens in the background. To flush before the page unloads,
3370
4621
  * call flush().
3371
4622
  */
4623
+ /**
4624
+ * Emit `crossdeck.contract_failed` to the Crossdeck reliability
4625
+ * endpoint — single-fire, one-way, never visible in the customer's
4626
+ * dashboard. Goes over a dedicated HTTP path with the reliability
4627
+ * publishable key embedded at build time; the customer's track()
4628
+ * pipeline never carries `crossdeck.*` events. This is the
4629
+ * independent-controller flow described in Privacy Policy §6
4630
+ * ("Flow B"). The wire shape is fixed by the schema-lock contract
4631
+ * at `contracts/diagnostics/contract-failed-payload-schema-lock.json`.
4632
+ *
4633
+ * Wire the call from a test hook, dogfood failure path, or
4634
+ * customer contract-verification harness; see
4635
+ * `contracts/README.md` for the per-test-framework hook recipes.
4636
+ */
4637
+ reportContractFailure(input) {
4638
+ const payload = {
4639
+ contract_id: input.contractId,
4640
+ sdk_version: SDK_VERSION,
4641
+ sdk_platform: "web",
4642
+ failure_reason: input.failureReason,
4643
+ run_context: input.runContext,
4644
+ run_id: input.runId
4645
+ };
4646
+ if (input.testRef) {
4647
+ payload.test_file = input.testRef.file;
4648
+ payload.test_name = input.testRef.name;
4649
+ }
4650
+ if (input.deviceClass) {
4651
+ payload.device_class = input.deviceClass;
4652
+ }
4653
+ sendDiagnosticTelemetry(payload);
4654
+ }
3372
4655
  track(name, properties) {
3373
4656
  const s = this.requireStarted();
3374
4657
  if (!name) {
@@ -3456,6 +4739,14 @@ var CrossdeckClient = class {
3456
4739
  };
3457
4740
  Object.assign(event, this.identityHintForEvent());
3458
4741
  s.events.enqueue(event);
4742
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4743
+ runOnTrack(this.verifiers, this.verifierReporter, this.verifierCtx, {
4744
+ callerProperties: validation.properties,
4745
+ superProperties: supers,
4746
+ deviceProperties: s.deviceInfo,
4747
+ mergedProperties: finalProperties
4748
+ });
4749
+ }
3459
4750
  if (!isError && !isWebVital) {
3460
4751
  const category = name.startsWith("page.") ? "navigation" : name.startsWith("element.") || name === "session.started" ? "ui.click" : "custom";
3461
4752
  s.breadcrumbs.add({
@@ -3505,11 +4796,37 @@ var CrossdeckClient = class {
3505
4796
  });
3506
4797
  }
3507
4798
  const rail = input.rail ?? "apple";
4799
+ const body = { ...input, rail };
4800
+ const idempotencyKey = deriveIdempotencyKeyForPurchase(body);
4801
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4802
+ const stableId = rail === "apple" ? body.signedTransactionInfo ?? "" : body.purchaseToken ?? "";
4803
+ runOnSyncPurchases(
4804
+ this.verifiers,
4805
+ this.verifierReporter,
4806
+ this.verifierCtx,
4807
+ {
4808
+ rail,
4809
+ stableIdentifier: stableId,
4810
+ derivedKey: idempotencyKey
4811
+ }
4812
+ );
4813
+ }
3508
4814
  const result = await s.http.request("POST", "/purchases/sync", {
3509
- body: { ...input, rail }
4815
+ body,
4816
+ idempotencyKey
3510
4817
  });
3511
4818
  s.identity.setCrossdeckCustomerId(result.crossdeckCustomerId);
3512
4819
  s.entitlements.setFromList(result.entitlements);
4820
+ try {
4821
+ const sourceProductId = result.entitlements[0]?.source.productId;
4822
+ const sourceSubscriptionId = result.entitlements[0]?.source.subscriptionId;
4823
+ const props = { rail };
4824
+ if (sourceProductId) props.productId = sourceProductId;
4825
+ if (sourceSubscriptionId) props.subscriptionId = sourceSubscriptionId;
4826
+ if (result.idempotent_replay) props.idempotent_replay = true;
4827
+ this.track("purchase.completed", props);
4828
+ } catch {
4829
+ }
3513
4830
  s.debug.emit(
3514
4831
  "sdk.purchase_evidence_sent",
3515
4832
  "StoreKit transaction forwarded. Waiting for backend verification.",
@@ -3565,7 +4882,7 @@ var CrossdeckClient = class {
3565
4882
  }
3566
4883
  this.state.autoTracker?.uninstall();
3567
4884
  this.state.identity.reset();
3568
- this.state.entitlements.clear();
4885
+ this.state.entitlements.clearAll();
3569
4886
  this.state.events.reset();
3570
4887
  this.state.superProps.clear();
3571
4888
  this.state.breadcrumbs.clear();
@@ -3840,16 +5157,673 @@ var CROSSDECK_ERROR_CODES = Object.freeze([
3840
5157
  description: "The server returned a 2xx with an unparseable body.",
3841
5158
  resolution: "Likely a transient backend bug. Retry; if it persists, contact support with the requestId.",
3842
5159
  retryable: true
5160
+ },
5161
+ // ----- Backend-emitted codes (v1.4.0 Phase 6.2 backfill) -----
5162
+ // Mirror of backend/src/api/v1-errors.ts ApiErrorCode. A developer
5163
+ // hitting any of these on the wire can look them up via
5164
+ // getErrorCode(code) for a canonical remediation step instead of
5165
+ // hunting through Slack history.
5166
+ {
5167
+ code: "missing_api_key",
5168
+ type: "authentication_error",
5169
+ description: "No Authorization header (or Crossdeck-Api-Key header) on the request.",
5170
+ resolution: "Make sure Crossdeck.init({ publicKey }) was called with a cd_pub_\u2026 key before the request fired. Re-check your env-vars in CI / Docker if the key is empty at runtime.",
5171
+ retryable: false
5172
+ },
5173
+ {
5174
+ code: "invalid_api_key",
5175
+ type: "authentication_error",
5176
+ description: "The API key is malformed, unknown, or doesn't resolve to a project.",
5177
+ resolution: "Copy the key from your Crossdeck dashboard \u2192 API keys. Confirm prefix is cd_pub_test_ / cd_pub_live_ for client SDKs and cd_sk_test_ / cd_sk_live_ for the Node server SDK.",
5178
+ retryable: false
5179
+ },
5180
+ {
5181
+ code: "key_revoked",
5182
+ type: "authentication_error",
5183
+ description: "The API key was revoked in the Crossdeck dashboard.",
5184
+ resolution: "Mint a fresh key in the dashboard \u2192 API keys \u2192 Create new, swap it in, and redeploy. The revoked key cannot be reactivated.",
5185
+ retryable: false
5186
+ },
5187
+ {
5188
+ code: "identity_token_invalid",
5189
+ type: "authentication_error",
5190
+ description: "The Firebase / Apple / Google ID token supplied with the request didn't verify against the dashboard's configured signers.",
5191
+ resolution: "Refresh the token client-side (Firebase auth.currentUser.getIdToken(true)) and retry. If the failure persists, confirm the signer is registered under dashboard \u2192 Authentication \u2192 Identity sources.",
5192
+ retryable: true
5193
+ },
5194
+ {
5195
+ code: "origin_not_allowed",
5196
+ type: "permission_error",
5197
+ description: "The Origin header isn't in the project's Allowed origins list.",
5198
+ resolution: "Add the origin (e.g. https://app.example.com) under dashboard \u2192 Settings \u2192 Allowed origins. Wildcards like https://*.example.com are supported.",
5199
+ retryable: false
5200
+ },
5201
+ {
5202
+ code: "bundle_id_not_allowed",
5203
+ type: "permission_error",
5204
+ description: "The iOS bundle ID sent via X-Crossdeck-Bundle-Id isn't registered under this app's Apple identity lock.",
5205
+ resolution: "Add the bundle ID under dashboard \u2192 Apps \u2192 <your app> \u2192 iOS bundle IDs.",
5206
+ retryable: false
5207
+ },
5208
+ {
5209
+ code: "package_name_not_allowed",
5210
+ type: "permission_error",
5211
+ description: "The Android package name sent via X-Crossdeck-Package-Name isn't registered under this app's Android identity lock.",
5212
+ resolution: "Add the package name under dashboard \u2192 Apps \u2192 <your app> \u2192 Android package names.",
5213
+ retryable: false
5214
+ },
5215
+ {
5216
+ code: "env_mismatch",
5217
+ type: "permission_error",
5218
+ description: "The request env (inferred from key prefix) doesn't match the resolved app's configured env.",
5219
+ resolution: "Use a cd_pub_live_ / cd_sk_live_ key with a production app, cd_pub_test_ / cd_sk_test_ with a sandbox app. The two cannot cross.",
5220
+ retryable: false
5221
+ },
5222
+ {
5223
+ code: "idempotency_key_in_use",
5224
+ type: "invalid_request_error",
5225
+ description: "An Idempotency-Key was reused for a request with a different body (Stripe-grade contract).",
5226
+ resolution: "Generate a fresh key for a different transaction, or reuse the key only with the EXACT same body. The v1.4.0 SDKs derive keys deterministically from the body so this should never fire on SDK-managed calls.",
5227
+ retryable: false
5228
+ },
5229
+ {
5230
+ code: "rate_limited",
5231
+ type: "rate_limit_error",
5232
+ description: "Request rate exceeded the project's per-second cap.",
5233
+ resolution: "Honour the Retry-After header \u2014 the SDK does this automatically on managed retries. If you're hitting it from a custom code path, throttle to <100 req/s/key.",
5234
+ retryable: true
5235
+ },
5236
+ {
5237
+ code: "internal_error",
5238
+ type: "internal_error",
5239
+ description: "Server-side issue. Safe to retry with backoff.",
5240
+ resolution: "The SDK retries automatically. If your code paths through to this error, contact support with the requestId from the response envelope.",
5241
+ retryable: true
5242
+ },
5243
+ {
5244
+ code: "google_not_supported",
5245
+ type: "invalid_request_error",
5246
+ description: "POST /purchases/sync with rail=google is gated until the Play Developer API reconciliation worker ships.",
5247
+ resolution: "Until v1.5+, Google Play purchases verify via Real-time Developer Notifications. The SDK auto-track path handles this transparently for Android consumers.",
5248
+ retryable: false
5249
+ },
5250
+ {
5251
+ code: "stripe_not_supported",
5252
+ type: "invalid_request_error",
5253
+ description: "POST /purchases/sync with rail=stripe is unsupported \u2014 Stripe Checkout's redirect flow uses platform webhooks instead.",
5254
+ resolution: "Wire Stripe via the standard Checkout / Customer Portal flow; Crossdeck reconciles via the platform webhook automatically. No SDK call needed.",
5255
+ retryable: false
5256
+ },
5257
+ {
5258
+ code: "missing_required_param",
5259
+ type: "invalid_request_error",
5260
+ description: "A required field is absent from the request body.",
5261
+ resolution: "Inspect the error.message \u2014 the missing field name is included verbatim. Refer to the SDK's TypeScript types for the canonical request shape.",
5262
+ retryable: false
5263
+ },
5264
+ {
5265
+ code: "invalid_param_value",
5266
+ type: "invalid_request_error",
5267
+ description: "A field is present but the value failed validation (wrong shape, wrong length, wrong enum value).",
5268
+ resolution: "Read error.message for the specific field + reason. SDK-managed call sites should never emit this \u2014 file a bug if you do.",
5269
+ retryable: false
3843
5270
  }
3844
5271
  ]);
3845
5272
  function getErrorCode(code) {
3846
5273
  return CROSSDECK_ERROR_CODES.find((e) => e.code === code);
3847
5274
  }
5275
+
5276
+ // src/_contracts-bundled.ts
5277
+ var BUNDLED_IN = "@cross-deck/web@1.5.3";
5278
+ var SDK_VERSION2 = "1.5.3";
5279
+ var BUNDLED_CONTRACTS = Object.freeze([
5280
+ {
5281
+ "id": "contract-failed-payload-schema-lock",
5282
+ "pillar": "diagnostics",
5283
+ "status": "enforced",
5284
+ "claim": "The `crossdeck.contract_failed` event payload contains ONLY the named diagnostic fields and never any end-user personal data. The wire shape is fixed \u2014 adding a new field requires (1) a pull request that updates this contract's `allowedFields` set, (2) a Privacy Policy \xA76 amendment, and (3) the Customer Disclosure Template / SDK Data Collection Reference \xA7B updates. Per-SDK assertion tests enforce the field set on every release. The `verification_phase` field is a categorical bucket \u2014 values are restricted to `boot` (the SDK self-test ran on Crossdeck.start) or `hot_path` (a verifier observed a real customer-triggered operation). The categorical nature is what preserves the diagnostic-only-not-personal classification. This is the structural guarantee that backs the independent-controller lawful basis in the Privacy Policy: the payload remains diagnostic-only, not personal, so the legitimate-interest analysis stays valid as the SDK evolves.",
5285
+ "appliesTo": [
5286
+ "web",
5287
+ "node",
5288
+ "swift",
5289
+ "android",
5290
+ "react-native"
5291
+ ],
5292
+ "allowedFields": {
5293
+ "required": [
5294
+ "contract_id",
5295
+ "sdk_version",
5296
+ "sdk_platform",
5297
+ "failure_reason",
5298
+ "run_context",
5299
+ "run_id"
5300
+ ],
5301
+ "optional": [
5302
+ "test_file",
5303
+ "test_name",
5304
+ "device_class",
5305
+ "verification_phase"
5306
+ ],
5307
+ "forbidden": [
5308
+ "anonymousId",
5309
+ "developerUserId",
5310
+ "crossdeckCustomerId",
5311
+ "email",
5312
+ "ip",
5313
+ "user_agent",
5314
+ "message",
5315
+ "stack",
5316
+ "stack_trace",
5317
+ "frames",
5318
+ "exception_message",
5319
+ "url",
5320
+ "path",
5321
+ "screen",
5322
+ "title",
5323
+ "label",
5324
+ "text",
5325
+ "ariaLabel",
5326
+ "accessibilityLabel",
5327
+ "contentDescription",
5328
+ "session_id",
5329
+ "sessionId"
5330
+ ]
5331
+ },
5332
+ "transport": "Telemetry is single-fire to the Crossdeck reliability endpoint only \u2014 NOT the customer's appId. The customer's track() pipeline never carries `crossdeck.*` events; the customer's dashboard never shows individual contract failures. Operational telemetry flows one-way to the Crossdeck operations team for SDK reliability purposes (legitimate interest, independent-controller flow per Privacy Policy \xA76). The reliability endpoint is hardcoded at SDK build time; the publishable key for the reliability project is embedded as a constant and rejects writes that don't match the schema.",
5333
+ "codeRef": [
5334
+ "sdks/web/src/crossdeck.ts",
5335
+ "sdks/node/src/crossdeck-server.ts",
5336
+ "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
5337
+ "sdks/swift/Sources/Crossdeck/_DiagnosticTelemetry.swift",
5338
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt",
5339
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/_DiagnosticTelemetry.kt",
5340
+ "sdks/react-native/src/crossdeck.ts",
5341
+ "backend/src/api/v1-sdk-diagnostic.ts",
5342
+ "sdks/web/src/_diagnostic-telemetry.ts",
5343
+ "sdks/node/src/_diagnostic-telemetry.ts",
5344
+ "sdks/react-native/src/_diagnostic-telemetry.ts"
5345
+ ],
5346
+ "testRef": [
5347
+ {
5348
+ "file": "sdks/web/tests/contract-failed-schema-lock.test.ts",
5349
+ "name": "reportContractFailure payload conforms to schema-lock"
5350
+ },
5351
+ {
5352
+ "file": "sdks/node/tests/contract-failed-schema-lock.test.ts",
5353
+ "name": "reportContractFailure payload conforms to schema-lock"
5354
+ },
5355
+ {
5356
+ "file": "sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",
5357
+ "name": "test_reportContractFailure_payloadFieldsAreInAllowList"
5358
+ },
5359
+ {
5360
+ "file": "sdks/swift/Tests/CrossdeckTests/ContractFailedSchemaLockTests.swift",
5361
+ "name": "test_reportContractFailure_doesNotEnterCustomerTrackPipeline"
5362
+ },
5363
+ {
5364
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",
5365
+ "name": "reportContractFailure payload conforms to schema-lock"
5366
+ },
5367
+ {
5368
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ContractFailedSchemaLockTest.kt",
5369
+ "name": "reportContractFailure does not enter customer track pipeline"
5370
+ },
5371
+ {
5372
+ "file": "sdks/react-native/tests/contract-failed-schema-lock.test.ts",
5373
+ "name": "reportContractFailure payload conforms to schema-lock"
5374
+ },
5375
+ {
5376
+ "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
5377
+ "name": "forbidden fields are enumerated in the schema-lock contract"
5378
+ },
5379
+ {
5380
+ "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
5381
+ "name": "required fields are enumerated in the schema-lock contract"
5382
+ },
5383
+ {
5384
+ "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
5385
+ "name": "regression guard: never returns a raw IP"
5386
+ },
5387
+ {
5388
+ "file": "backend/tests/unit/v1-sdk-diagnostic.test.ts",
5389
+ "name": "verification_phase is in the optional field set"
5390
+ }
5391
+ ],
5392
+ "registeredAt": "2026-05-27",
5393
+ "firstRegisteredIn": "Diagnostic telemetry single-fire + schema-lock \u2014 independent-controller flow",
5394
+ "privacyReferences": [
5395
+ "legal/privacy/index.html#sdk-diagnostic",
5396
+ "legal/customer-disclosure/index.html#flow-b",
5397
+ "legal/security/index.html#diagnostic",
5398
+ "legal/sdk-data/index.html#b-diagnostic"
5399
+ ],
5400
+ "bundledIn": "@cross-deck/web@1.5.3"
5401
+ },
5402
+ {
5403
+ "id": "error-envelope-shape",
5404
+ "pillar": "errors",
5405
+ "status": "enforced",
5406
+ "claim": "Every v1 REST endpoint returns errors in a Stripe-shape envelope: `{ error: { type, code, message, request_id } }` where `type` is one of authentication_error / permission_error / invalid_request_error / rate_limit_error / internal_error (the wire vocabulary in backend/src/api/v1-errors.ts ApiErrorType). HTTP status parity: invalid_request_error \u2192 400, authentication_error \u2192 401, permission_error \u2192 403, rate_limit_error \u2192 429, internal_error \u2192 500. SDK-side clients parse this shape via `crossdeckErrorFromResponse` (Web/Node/RN) / `crossdeckErrorFrom(response:)` (Swift) / `crossdeckErrorFromResponse` (Android) and surface the request_id verbatim so support traces are end-to-end joinable. Firebase callable endpoints (managed-keys / dashboard auth) use the Firebase HttpsError envelope instead \u2014 this contract applies to REST /v1/* only.",
5407
+ "appliesTo": [
5408
+ "web",
5409
+ "node",
5410
+ "react-native",
5411
+ "swift",
5412
+ "android",
5413
+ "backend"
5414
+ ],
5415
+ "codeRef": [
5416
+ "backend/src/api/v1-errors.ts",
5417
+ "sdks/web/src/errors.ts",
5418
+ "sdks/node/src/errors.ts",
5419
+ "sdks/react-native/src/errors.ts",
5420
+ "sdks/swift/Sources/Crossdeck/Errors.swift",
5421
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Errors.kt"
5422
+ ],
5423
+ "testRef": [
5424
+ {
5425
+ "file": "sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",
5426
+ "name": "test_errorEnvelope_fallsBackOnGarbageBody"
5427
+ },
5428
+ {
5429
+ "file": "sdks/swift/Tests/CrossdeckTests/ErrorsTests.swift",
5430
+ "name": "test_errorEnvelope_reads_XRequestId_fallback"
5431
+ },
5432
+ {
5433
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/ErrorTypeWireVocabTest.kt",
5434
+ "name": "backend 500 response parses to INTERNAL_ERROR"
5435
+ }
5436
+ ],
5437
+ "registeredAt": "2026-05-26",
5438
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 8 (codifies existing contract)",
5439
+ "bundledIn": "@cross-deck/web@1.5.3"
5440
+ },
5441
+ {
5442
+ "id": "flush-interval-parity",
5443
+ "pillar": "analytics",
5444
+ "status": "enforced",
5445
+ "claim": "Every Crossdeck SDK defaults its event-queue flush interval to 2000ms \u2014 the Stripe-adjacent industry norm. Pre-v1.4.0 the defaults disagreed (Web/Node 1500ms; RN/Swift/Android 5000ms), so cross-platform funnels saw events landing at different cadences. Per-instance override stays \u2014 call sites can still tune it freely.",
5446
+ "appliesTo": [
5447
+ "web",
5448
+ "node",
5449
+ "react-native",
5450
+ "swift",
5451
+ "android"
5452
+ ],
5453
+ "codeRef": [
5454
+ "sdks/web/src/crossdeck.ts",
5455
+ "sdks/node/src/crossdeck-server.ts",
5456
+ "sdks/react-native/src/crossdeck.ts",
5457
+ "sdks/swift/Sources/Crossdeck/EventQueue.swift",
5458
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt"
5459
+ ],
5460
+ "testRef": [
5461
+ {
5462
+ "file": "sdks/swift/Sources/Crossdeck/EventQueue.swift",
5463
+ "name": "flushIntervalMs: Int = 2_000"
5464
+ },
5465
+ {
5466
+ "file": "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EventQueue.kt",
5467
+ "name": "flushIntervalMs: Long = 2_000L"
5468
+ },
5469
+ {
5470
+ "file": "sdks/web/src/crossdeck.ts",
5471
+ "name": "options.eventFlushIntervalMs ?? 2000"
5472
+ },
5473
+ {
5474
+ "file": "sdks/node/src/crossdeck-server.ts",
5475
+ "name": "options.eventFlushIntervalMs ?? 2000"
5476
+ },
5477
+ {
5478
+ "file": "sdks/react-native/src/crossdeck.ts",
5479
+ "name": "options.eventFlushIntervalMs ?? 2000"
5480
+ }
5481
+ ],
5482
+ "registeredAt": "2026-05-26",
5483
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 3.3",
5484
+ "bundledIn": "@cross-deck/web@1.5.3"
5485
+ },
5486
+ {
5487
+ "id": "idempotency-key-deterministic",
5488
+ "pillar": "revenue",
5489
+ "status": "enforced",
5490
+ "claim": "syncPurchases() on every SDK derives a deterministic Idempotency-Key from the request body (UUID-shaped SHA-256 of `crossdeck:purchases/sync:<rail>:<jws|token>`). Same input -> same key. Backend short-circuits same-key-same-body retries by returning the cached response (status + body) with `idempotent_replay: true` flag in the body AND `Idempotent-Replayed: true` response header. Same-key-different-body returns 400 `idempotency_key_in_use`. 24-hour TTL matches Stripe. Cache only stores 2xx responses \u2014 4xx/5xx pass through so callers can fix bugs and retry. Helper returns nil/throws on missing identifier (no silent random fallback). Cross-SDK parity is CI-pinned: deriveForPurchase('apple', 'eyJ.jws.sig') MUST equal 'a66b1640-efaf-bb4d-1261-6650033bf111' on every SDK.",
5491
+ "appliesTo": [
5492
+ "web",
5493
+ "node",
5494
+ "react-native",
5495
+ "swift",
5496
+ "android",
5497
+ "backend"
5498
+ ],
5499
+ "codeRef": [
5500
+ "sdks/web/src/idempotency-key.ts",
5501
+ "sdks/web/src/crossdeck.ts",
5502
+ "sdks/react-native/src/idempotency-key.ts",
5503
+ "sdks/react-native/src/crossdeck.ts",
5504
+ "sdks/node/src/idempotency-key.ts",
5505
+ "sdks/node/src/crossdeck-server.ts",
5506
+ "sdks/swift/Sources/Crossdeck/IdempotencyKey.swift",
5507
+ "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
5508
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt",
5509
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt",
5510
+ "backend/src/lib/idempotency-response-cache.ts",
5511
+ "backend/src/api/v1-purchases.ts"
5512
+ ],
5513
+ "testRef": [
5514
+ {
5515
+ "file": "sdks/web/tests/idempotency-key.test.ts",
5516
+ "name": "cross-SDK oracle \u2014 apple JWS pins canonical vector"
5517
+ },
5518
+ {
5519
+ "file": "sdks/web/tests/idempotency-key.test.ts",
5520
+ "name": "is deterministic: same body twice -> identical key"
5521
+ },
5522
+ {
5523
+ "file": "sdks/web/tests/idempotency-key.test.ts",
5524
+ "name": "same identifier under different rails -> different keys"
5525
+ },
5526
+ {
5527
+ "file": "sdks/web/tests/idempotency-key.test.ts",
5528
+ "name": "never silently falls back to a random key on missing identifier"
5529
+ },
5530
+ {
5531
+ "file": "sdks/react-native/tests/idempotency-key.test.ts",
5532
+ "name": "is deterministic"
5533
+ },
5534
+ {
5535
+ "file": "sdks/react-native/tests/idempotency-key.test.ts",
5536
+ "name": "cross-SDK oracle \u2014 apple JWS pins canonical vector"
5537
+ },
5538
+ {
5539
+ "file": "sdks/node/tests/idempotency-key.test.ts",
5540
+ "name": "is deterministic"
5541
+ },
5542
+ {
5543
+ "file": "sdks/node/tests/idempotency-key.test.ts",
5544
+ "name": "rail namespacing prevents cross-rail collisions"
5545
+ },
5546
+ {
5547
+ "file": "sdks/node/tests/idempotency-key.test.ts",
5548
+ "name": "apple JWS produces the canonical pinned UUID across all 5 SDKs"
5549
+ },
5550
+ {
5551
+ "file": "backend/tests/unit/idempotency-response-cache.test.ts",
5552
+ "name": "is deterministic for the same input"
5553
+ },
5554
+ {
5555
+ "file": "backend/tests/unit/idempotency-response-cache.test.ts",
5556
+ "name": "injects idempotent_replay: true into a JSON object body"
5557
+ },
5558
+ {
5559
+ "file": "backend/tests/unit/idempotency-response-cache.test.ts",
5560
+ "name": "matches Stripe's 24-hour idempotency window"
5561
+ },
5562
+ {
5563
+ "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
5564
+ "name": "test_crossSdkOracle_appleJWS"
5565
+ },
5566
+ {
5567
+ "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
5568
+ "name": "test_railNamespacing_preventsCrossRailCollisions"
5569
+ },
5570
+ {
5571
+ "file": "sdks/swift/Tests/CrossdeckTests/IdempotencyKeyTests.swift",
5572
+ "name": "test_missingIdentifier_returnsNil"
5573
+ },
5574
+ {
5575
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
5576
+ "name": "cross-SDK oracle for apple JWS"
5577
+ },
5578
+ {
5579
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
5580
+ "name": "rail namespacing prevents cross-rail collisions"
5581
+ },
5582
+ {
5583
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/IdempotencyKeyTest.kt",
5584
+ "name": "missing identifier returns null - never silent random fallback"
5585
+ }
5586
+ ],
5587
+ "registeredAt": "2026-05-26",
5588
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 2.2.a + 2.2.b + 2.2.c",
5589
+ "bundledIn": "@cross-deck/web@1.5.3"
5590
+ },
5591
+ {
5592
+ "id": "init-reentry-drains-prior-queue",
5593
+ "pillar": "lifecycle",
5594
+ "status": "enforced",
5595
+ "claim": "Web + RN init() re-entry drains the prior EventQueue's pending setTimeout BEFORE replacing this.state. Pre-v1.4.0 the teardown handled autoTracker/webVitals/errors/unloadFlush but NOT events, so the prior queue's timer would fire AFTER the state swap \u2014 sending old-init events against new-init http + identity references (cross-identity leak during HMR / config swap / multi-tenant SDK shells). The teardown CANNOT call persistent.clear() \u2014 the durable queue belongs to the SDK lifetime, not the init() lifetime, and a survived crash mid-flush re-hydrates on the next init.",
5596
+ "appliesTo": [
5597
+ "web",
5598
+ "react-native"
5599
+ ],
5600
+ "codeRef": [
5601
+ "sdks/web/src/crossdeck.ts",
5602
+ "sdks/react-native/src/crossdeck.ts"
5603
+ ],
5604
+ "testRef": [
5605
+ {
5606
+ "file": "sdks/web/tests/init-reentry.test.ts",
5607
+ "name": "re-init drains the prior queue's pending timer before swapping state"
5608
+ },
5609
+ {
5610
+ "file": "sdks/web/tests/init-reentry.test.ts",
5611
+ "name": "re-init does NOT wipe the durable event store"
5612
+ }
5613
+ ],
5614
+ "registeredAt": "2026-05-26",
5615
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 5.5",
5616
+ "bundledIn": "@cross-deck/web@1.5.3"
5617
+ },
5618
+ {
5619
+ "id": "per-user-cache-isolation",
5620
+ "pillar": "entitlements",
5621
+ "status": "enforced",
5622
+ "claim": "Every identify(userId) switches the entitlement cache to a physically separate per-user storage slot \u2014 `crossdeck:entitlements:<sha256(userId)>` \u2014 and unconditionally wipes the in-memory snapshot. A user-switch on a shared device CANNOT cross-read a prior user's cached entitlements, even if the in-memory clear is somehow skipped, because the storage keys are physically separate. reset() wipes every per-user slot via the persisted index.",
5623
+ "appliesTo": [
5624
+ "web",
5625
+ "react-native",
5626
+ "swift",
5627
+ "android"
5628
+ ],
5629
+ "codeRef": [
5630
+ "sdks/web/src/entitlement-cache.ts",
5631
+ "sdks/web/src/hash.ts",
5632
+ "sdks/web/src/crossdeck.ts",
5633
+ "sdks/react-native/src/entitlement-cache.ts",
5634
+ "sdks/react-native/src/hash.ts",
5635
+ "sdks/react-native/src/crossdeck.ts",
5636
+ "sdks/swift/Sources/Crossdeck/EntitlementCache.swift",
5637
+ "sdks/swift/Sources/Crossdeck/IdempotencyKey.swift",
5638
+ "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
5639
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/EntitlementCache.kt",
5640
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/IdempotencyKey.kt",
5641
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"
5642
+ ],
5643
+ "testRef": [
5644
+ {
5645
+ "file": "sdks/web/tests/entitlement-cache-isolation.test.ts",
5646
+ "name": "identify(B) makes A's entitlements unreachable from in-memory"
5647
+ },
5648
+ {
5649
+ "file": "sdks/web/tests/entitlement-cache-isolation.test.ts",
5650
+ "name": "clearAll() removes every per-user storage key plus the index"
5651
+ },
5652
+ {
5653
+ "file": "sdks/web/tests/entitlement-cache-isolation.test.ts",
5654
+ "name": "a second cache instance reading A's storage suffix CANNOT see B's data"
5655
+ },
5656
+ {
5657
+ "file": "sdks/react-native/tests/entitlement-cache-isolation.test.ts",
5658
+ "name": "identify(B) makes A's entitlements unreachable from in-memory"
5659
+ },
5660
+ {
5661
+ "file": "sdks/react-native/tests/entitlement-cache-isolation.test.ts",
5662
+ "name": "removes every per-user storage key plus the index"
5663
+ },
5664
+ {
5665
+ "file": "sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",
5666
+ "name": "test_identifyB_makesAEntitlementsUnreachable"
5667
+ },
5668
+ {
5669
+ "file": "sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",
5670
+ "name": "test_identifiedWritesLandUnderPerUserSha256Key"
5671
+ },
5672
+ {
5673
+ "file": "sdks/swift/Tests/CrossdeckTests/EntitlementCacheIsolationTests.swift",
5674
+ "name": "test_clearAll_removesEveryPerUserStorageKeyPlusIndex"
5675
+ },
5676
+ {
5677
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",
5678
+ "name": "identified writes land under per-user sha256 key"
5679
+ },
5680
+ {
5681
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",
5682
+ "name": "identify B makes A entitlements unreachable from in-memory"
5683
+ },
5684
+ {
5685
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",
5686
+ "name": "clearAll removes every per-user storage key plus the index"
5687
+ },
5688
+ {
5689
+ "file": "sdks/android/crossdeck/src/test/kotlin/com/crossdeck/EntitlementCacheIsolationTest.kt",
5690
+ "name": "a fresh cache bound to A's key CANNOT read B's blob"
5691
+ }
5692
+ ],
5693
+ "registeredAt": "2026-05-26",
5694
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 1.3 (web/RN) + dogfood-gap fix (swift + android)",
5695
+ "bundledIn": "@cross-deck/web@1.5.3"
5696
+ },
5697
+ {
5698
+ "id": "sdk-error-codes-catalogue",
5699
+ "pillar": "errors",
5700
+ "status": "enforced",
5701
+ "claim": "Web + Node SDK error-codes catalogues include EVERY backend-emitted ApiErrorCode with a description + resolution. Pre-v1.4.0 the catalogues documented codes the SDK threw ITSELF but ZERO backend codes \u2014 a developer hitting `invalid_api_key` / `origin_not_allowed` / `bundle_id_not_allowed` / `env_mismatch` / `idempotency_key_in_use` etc. got `undefined` from getErrorCode() and had to hunt for guidance. v1.4.0 backfills the catalogue from backend/src/api/v1-errors.ts so every wire code has a canonical 'what does this mean / what should I do' answer Stripe-style.",
5702
+ "appliesTo": [
5703
+ "web",
5704
+ "node"
5705
+ ],
5706
+ "codeRef": [
5707
+ "sdks/web/src/error-codes.ts",
5708
+ "sdks/node/src/error-codes.ts",
5709
+ "backend/src/api/v1-errors.ts"
5710
+ ],
5711
+ "testRef": [
5712
+ {
5713
+ "file": "sdks/web/tests/error-codes-backfill.test.ts",
5714
+ "name": "includes backend code"
5715
+ },
5716
+ {
5717
+ "file": "sdks/web/tests/error-codes-backfill.test.ts",
5718
+ "name": "invalid_api_key resolution points at the dashboard"
5719
+ },
5720
+ {
5721
+ "file": "sdks/web/tests/error-codes-backfill.test.ts",
5722
+ "name": "idempotency_key_in_use resolution mentions Stripe-grade contract"
5723
+ },
5724
+ {
5725
+ "file": "sdks/web/tests/error-codes-backfill.test.ts",
5726
+ "name": "identity-lock codes carry permission_error type"
5727
+ },
5728
+ {
5729
+ "file": "sdks/web/tests/error-codes-backfill.test.ts",
5730
+ "name": "no entry has an empty description or resolution"
5731
+ }
5732
+ ],
5733
+ "registeredAt": "2026-05-26",
5734
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 6.2",
5735
+ "bundledIn": "@cross-deck/web@1.5.3"
5736
+ },
5737
+ {
5738
+ "id": "sync-purchases-funnel-parity",
5739
+ "pillar": "analytics",
5740
+ "status": "enforced",
5741
+ "claim": "Manual syncPurchases() emits a `purchase.completed` analytics event on success across ALL SDKs (Web / Node / RN / Swift / Android). Pre-v1.4.0 only Swift/Android auto-track emitted it \u2014 Web/Node/RN manual calls + Swift/Android manual calls fired ZERO analytics. Schema mirrors the auto-track event name + rail/productId/subscriptionId so cross-platform funnels reconcile on every payment path. When the backend short-circuits via the v1.4.0 idempotency cache, the event also carries `idempotent_replay: true`.",
5742
+ "appliesTo": [
5743
+ "web",
5744
+ "node",
5745
+ "react-native",
5746
+ "swift",
5747
+ "android"
5748
+ ],
5749
+ "codeRef": [
5750
+ "sdks/web/src/crossdeck.ts",
5751
+ "sdks/node/src/crossdeck-server.ts",
5752
+ "sdks/react-native/src/crossdeck.ts",
5753
+ "sdks/swift/Sources/Crossdeck/Crossdeck.swift",
5754
+ "sdks/android/crossdeck/src/main/kotlin/com/crossdeck/Crossdeck.kt"
5755
+ ],
5756
+ "testRef": [
5757
+ {
5758
+ "file": "sdks/web/tests/sync-purchases-funnel.test.ts",
5759
+ "name": "emits purchase.completed after a successful sync"
5760
+ },
5761
+ {
5762
+ "file": "sdks/web/tests/sync-purchases-funnel.test.ts",
5763
+ "name": "carries idempotent_replay=true when backend replied from cache"
5764
+ }
5765
+ ],
5766
+ "registeredAt": "2026-05-26",
5767
+ "firstRegisteredIn": "bank-grade reconciliation v1.4.0 \u2014 phase 3.5",
5768
+ "bundledIn": "@cross-deck/web@1.5.3"
5769
+ }
5770
+ ]);
5771
+
5772
+ // src/contracts.ts
5773
+ var CrossdeckContracts = {
5774
+ /** Every contract that applies to this SDK and is currently enforced. */
5775
+ all() {
5776
+ return BUNDLED_CONTRACTS.filter((c) => c.status === "enforced");
5777
+ },
5778
+ /**
5779
+ * Every contract bundled with this SDK release, including
5780
+ * `proposed` and `retired` entries. Use `all()` for the
5781
+ * enforced-only view.
5782
+ */
5783
+ allIncludingHistorical() {
5784
+ return BUNDLED_CONTRACTS;
5785
+ },
5786
+ /** Look up a contract by its stable `id`. */
5787
+ byId(id) {
5788
+ return BUNDLED_CONTRACTS.find((c) => c.id === id);
5789
+ },
5790
+ /** Every enforced contract within a pillar. */
5791
+ byPillar(pillar) {
5792
+ return BUNDLED_CONTRACTS.filter(
5793
+ (c) => c.pillar === pillar && c.status === "enforced"
5794
+ );
5795
+ },
5796
+ /** Filter by lifecycle status. */
5797
+ withStatus(status) {
5798
+ return BUNDLED_CONTRACTS.filter((c) => c.status === status);
5799
+ },
5800
+ /** Semver of the SDK release these contracts were bundled with. */
5801
+ sdkVersion: SDK_VERSION2,
5802
+ /** Fully-qualified bundle identifier — e.g. `@cross-deck/web@1.4.2`. */
5803
+ bundledIn: BUNDLED_IN,
5804
+ /**
5805
+ * Resolve a failing test back to the contract it exercises.
5806
+ * Used by test-framework hooks (Vitest `afterEach`, XCTest
5807
+ * observation, JUnit `TestWatcher`) to find the contract id of
5808
+ * a failed contract test so `reportContractFailure(...)` can
5809
+ * stamp the right `contract_id` on the emitted event.
5810
+ *
5811
+ * Match is on `testRef.name` (case-sensitive, exact). Returns
5812
+ * the first contract whose `testRef` list contains a matching
5813
+ * entry, regardless of pillar or status.
5814
+ */
5815
+ findByTestName(name) {
5816
+ return BUNDLED_CONTRACTS.find(
5817
+ (c) => c.testRef.some((ref) => ref.name === name)
5818
+ );
5819
+ }
5820
+ };
3848
5821
  // Annotate the CommonJS export names for ESM import in node:
3849
5822
  0 && (module.exports = {
3850
5823
  CROSSDECK_ERROR_CODES,
3851
5824
  Crossdeck,
3852
5825
  CrossdeckClient,
5826
+ CrossdeckContracts,
3853
5827
  CrossdeckError,
3854
5828
  DEFAULT_BASE_URL,
3855
5829
  MemoryStorage,