@cross-deck/web 1.5.1 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/contracts.json +133 -11
  2. package/dist/crossdeck.umd.min.js +2 -2
  3. package/dist/crossdeck.umd.min.js.map +1 -1
  4. package/dist/error-codes.json +1 -1
  5. package/dist/index.cjs +1081 -25
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.mts +51 -16
  8. package/dist/index.d.ts +51 -16
  9. package/dist/index.mjs +1081 -25
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/react.cjs +950 -16
  12. package/dist/react.cjs.map +1 -1
  13. package/dist/react.d.mts +1 -1
  14. package/dist/react.d.ts +1 -1
  15. package/dist/react.mjs +950 -16
  16. package/dist/react.mjs.map +1 -1
  17. package/dist/{types-Bu3jbmdq.d.ts → types-B9sxUuKh.d.mts} +71 -0
  18. package/dist/{types-Bu3jbmdq.d 2.mts → types-B9sxUuKh.d.ts} +71 -0
  19. package/dist/vue.cjs +950 -16
  20. package/dist/vue.cjs.map +1 -1
  21. package/dist/vue.mjs +950 -16
  22. package/dist/vue.mjs.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/contracts 2.json +0 -378
  25. package/dist/crossdeck.umd.min 2.js +0 -3
  26. package/dist/crossdeck.umd.min.js 2.map +0 -1
  27. package/dist/error-codes 2.json +0 -196
  28. package/dist/index 2.cjs +0 -4778
  29. package/dist/index 2.mjs +0 -4742
  30. package/dist/index.cjs 2.map +0 -1
  31. package/dist/index.d 2.mts +0 -938
  32. package/dist/index.d 2.ts +0 -938
  33. package/dist/index.mjs 2.map +0 -1
  34. package/dist/react 2.cjs +0 -4220
  35. package/dist/react 2.mjs +0 -4193
  36. package/dist/react.cjs 2.map +0 -1
  37. package/dist/react.d 2.mts +0 -91
  38. package/dist/react.d 2.ts +0 -91
  39. package/dist/react.mjs 2.map +0 -1
  40. package/dist/types-Bu3jbmdq.d 2.ts +0 -314
  41. package/dist/types-Bu3jbmdq.d.mts +0 -314
  42. package/dist/vue 2.cjs +0 -4185
  43. package/dist/vue 2.mjs +0 -4159
  44. package/dist/vue.cjs 2.map +0 -1
  45. package/dist/vue.d 2.mts +0 -37
  46. package/dist/vue.d 2.ts +0 -37
  47. package/dist/vue.mjs 2.map +0 -1
package/dist/vue.mjs CHANGED
@@ -67,7 +67,7 @@ function typeMapForStatus(status) {
67
67
  }
68
68
 
69
69
  // src/_version.ts
70
- var SDK_VERSION = "1.4.2";
70
+ var SDK_VERSION = "1.5.3";
71
71
  var SDK_NAME = "@cross-deck/web";
72
72
 
73
73
  // src/http.ts
@@ -130,7 +130,14 @@ var HttpClient = class {
130
130
  if (timeoutHandle !== null) clearTimeout(timeoutHandle);
131
131
  }
132
132
  if (!response.ok) {
133
- throw await crossdeckErrorFromResponse(response);
133
+ const parsed = await crossdeckErrorFromResponse(response);
134
+ if (this.config.onErrorParsed) {
135
+ try {
136
+ this.config.onErrorParsed(parsed);
137
+ } catch {
138
+ }
139
+ }
140
+ throw parsed;
134
141
  }
135
142
  if (response.status === 204) return void 0;
136
143
  try {
@@ -2366,6 +2373,789 @@ var BreadcrumbBuffer = class {
2366
2373
  }
2367
2374
  };
2368
2375
 
2376
+ // src/_diagnostic-telemetry.ts
2377
+ var DIAGNOSTIC_TELEMETRY_ENDPOINT = "https://api.cross-deck.com/v1/sdk/diagnostic";
2378
+ var DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY = "cd_pub_live_9490e7aa029c432abf";
2379
+ function isDiagnosticTelemetryEnabled() {
2380
+ return !DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY.startsWith(
2381
+ "cd_pub_RELIABILITY_PLACEHOLDER"
2382
+ );
2383
+ }
2384
+ var DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS = /* @__PURE__ */ new Set([
2385
+ "contract_id",
2386
+ "sdk_version",
2387
+ "sdk_platform",
2388
+ "failure_reason",
2389
+ "run_context",
2390
+ "run_id",
2391
+ "test_file",
2392
+ "test_name",
2393
+ "device_class",
2394
+ // verification_phase is set by the runtime contract verifier layer
2395
+ // (sdks/web/src/_contract-verifiers.ts) — values `boot` / `hot_path`.
2396
+ // Absent for failures emitted by external test harnesses
2397
+ // (XCTestObservation, Vitest hooks, JUnit watchers) which carry
2398
+ // test_file + test_name instead. See contracts/diagnostics/
2399
+ // contract-failed-payload-schema-lock.json.
2400
+ "verification_phase"
2401
+ ]);
2402
+ function filterDiagnosticPayload(payload) {
2403
+ const filtered = {};
2404
+ for (const [k, v] of Object.entries(payload)) {
2405
+ if (DIAGNOSTIC_TELEMETRY_ALLOWED_KEYS.has(k) && typeof v === "string") {
2406
+ filtered[k] = v;
2407
+ }
2408
+ }
2409
+ return filtered;
2410
+ }
2411
+ function sendDiagnosticTelemetry(payload) {
2412
+ if (!isDiagnosticTelemetryEnabled()) return;
2413
+ const filtered = filterDiagnosticPayload(payload);
2414
+ if (Object.keys(filtered).length === 0) return;
2415
+ const body = JSON.stringify(filtered);
2416
+ const f = globalThis.fetch;
2417
+ if (typeof f !== "function") return;
2418
+ try {
2419
+ void f(DIAGNOSTIC_TELEMETRY_ENDPOINT, {
2420
+ method: "POST",
2421
+ headers: {
2422
+ "Content-Type": "application/json",
2423
+ Authorization: `Bearer ${DIAGNOSTIC_TELEMETRY_PUBLISHABLE_KEY}`,
2424
+ "Crossdeck-Sdk-Version": `${SDK_NAME}@${SDK_VERSION}`
2425
+ },
2426
+ body,
2427
+ keepalive: true,
2428
+ // No credentials, no cache, no referrer — the reliability
2429
+ // endpoint is the same origin only in tests. In production the
2430
+ // browser never carries anything beyond the request body and
2431
+ // the Authorization header we set explicitly.
2432
+ credentials: "omit",
2433
+ cache: "no-store",
2434
+ referrerPolicy: "no-referrer"
2435
+ }).catch(() => {
2436
+ });
2437
+ } catch {
2438
+ }
2439
+ }
2440
+
2441
+ // src/_contract-verifiers.ts
2442
+ function buildVerifierContext(opts) {
2443
+ return {
2444
+ sdkVersion: `${SDK_NAME}@${SDK_VERSION}`,
2445
+ runId: `cd_verify_${randomHex(8)}`,
2446
+ runContext: opts.runContext ?? "customer-app",
2447
+ logVerifierResults: opts.logVerifierResults,
2448
+ disableContractAssertions: opts.disableContractAssertions,
2449
+ console,
2450
+ emitTelemetry: sendDiagnosticTelemetry
2451
+ };
2452
+ }
2453
+ var VerifierReporter = class {
2454
+ constructor(ctx) {
2455
+ this.ctx = ctx;
2456
+ this.reentrancyDepth = 0;
2457
+ }
2458
+ /**
2459
+ * Report a verifier result. Pass `operation` for hot-path results
2460
+ * to render the prefix as `[crossdeck.identify]` etc.; omit for
2461
+ * boot results which render as `[crossdeck]`.
2462
+ */
2463
+ report(result, phase, operation) {
2464
+ if (this.ctx.disableContractAssertions) return;
2465
+ if (result.ok) {
2466
+ this.reportPass(result, phase, operation);
2467
+ } else {
2468
+ this.reportFail(result, phase, operation);
2469
+ }
2470
+ }
2471
+ reportPass(result, phase, operation) {
2472
+ if (!this.ctx.logVerifierResults) return;
2473
+ const line = formatPassLine(result, operation);
2474
+ if (phase === "boot") {
2475
+ this.ctx.console.info(line);
2476
+ } else {
2477
+ this.ctx.console.debug(line);
2478
+ }
2479
+ }
2480
+ reportFail(result, phase, operation) {
2481
+ this.ctx.console.warn(formatFailLine(result, operation));
2482
+ if (this.reentrancyDepth > 0) return;
2483
+ this.reentrancyDepth += 1;
2484
+ try {
2485
+ this.ctx.emitTelemetry({
2486
+ contract_id: result.contractId,
2487
+ sdk_version: this.ctx.sdkVersion,
2488
+ sdk_platform: "web",
2489
+ failure_reason: truncate(result.failureReason, 128),
2490
+ run_context: this.ctx.runContext,
2491
+ run_id: this.ctx.runId,
2492
+ verification_phase: phase
2493
+ });
2494
+ } finally {
2495
+ this.reentrancyDepth -= 1;
2496
+ }
2497
+ }
2498
+ };
2499
+ function formatPassLine(r, operation) {
2500
+ const prefix = operation ? `[crossdeck.${operation}]` : "[crossdeck]";
2501
+ return `${prefix} \u2713 ${r.contractId} \u2014 ${r.evidence} (${r.durationMs}ms)`;
2502
+ }
2503
+ function formatFailLine(r, operation) {
2504
+ const prefix = operation ? `[crossdeck.${operation}]` : "[crossdeck]";
2505
+ return `${prefix} \u2717 ${r.contractId} \u2014 ${r.failureReason} (${r.durationMs}ms)`;
2506
+ }
2507
+ var VERIFIER_PER_USER_CACHE_ISOLATION = {
2508
+ contractId: "per-user-cache-isolation",
2509
+ bootTest() {
2510
+ const t0 = nowMs();
2511
+ try {
2512
+ const storage = new MemoryStorage2();
2513
+ const cache = new EntitlementCache(storage, "_verifier");
2514
+ cache.setUserKey("user_A");
2515
+ cache.setFromList([
2516
+ {
2517
+ object: "entitlement",
2518
+ key: "pro",
2519
+ isActive: true,
2520
+ validUntil: null,
2521
+ source: {
2522
+ rail: "stripe",
2523
+ productId: "p_verifier",
2524
+ subscriptionId: "s_verifier"
2525
+ },
2526
+ updatedAt: Date.now()
2527
+ }
2528
+ ]);
2529
+ cache.setUserKey("user_B");
2530
+ const inMemoryB = cache.list();
2531
+ if (inMemoryB.length !== 0) {
2532
+ return fail(
2533
+ "per-user-cache-isolation",
2534
+ "in-memory snapshot still carried user_A's entitlements after rotation",
2535
+ nowMs() - t0
2536
+ );
2537
+ }
2538
+ const suffixA = EntitlementCache.suffixForUserId("user_A");
2539
+ const suffixB = EntitlementCache.suffixForUserId("user_B");
2540
+ if (suffixA === suffixB) {
2541
+ return fail(
2542
+ "per-user-cache-isolation",
2543
+ "suffixes for user_A and user_B collided",
2544
+ nowMs() - t0
2545
+ );
2546
+ }
2547
+ const storageA = storage.getItem(`_verifier:${suffixA}`);
2548
+ const storageB = storage.getItem(`_verifier:${suffixB}`);
2549
+ if (!storageA) {
2550
+ return fail(
2551
+ "per-user-cache-isolation",
2552
+ "user_A's storage slot was wiped on rotation (expected isolation, not erasure)",
2553
+ nowMs() - t0
2554
+ );
2555
+ }
2556
+ if (storageB) {
2557
+ return fail(
2558
+ "per-user-cache-isolation",
2559
+ "user_B's storage slot already contained data before any write",
2560
+ nowMs() - t0
2561
+ );
2562
+ }
2563
+ return pass(
2564
+ "per-user-cache-isolation",
2565
+ `slot rotated A:${shortSuffix(suffixA)} \u2192 B:${shortSuffix(suffixB)} (isolated, physically separate)`,
2566
+ nowMs() - t0
2567
+ );
2568
+ } catch (err) {
2569
+ return fail(
2570
+ "per-user-cache-isolation",
2571
+ `boot test threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2572
+ nowMs() - t0
2573
+ );
2574
+ }
2575
+ },
2576
+ hooks: {
2577
+ onIdentify(obs) {
2578
+ const t0 = nowMs();
2579
+ const priorSuffix = EntitlementCache.suffixForUserId(obs.priorUserId);
2580
+ const nextSuffix = EntitlementCache.suffixForUserId(obs.nextUserId);
2581
+ if (priorSuffix !== nextSuffix) {
2582
+ if (obs.cache.list().length !== 0) {
2583
+ return fail(
2584
+ "per-user-cache-isolation",
2585
+ "in-memory snapshot still held entitlements after slot rotation",
2586
+ nowMs() - t0
2587
+ );
2588
+ }
2589
+ return pass(
2590
+ "per-user-cache-isolation",
2591
+ `slot rotated ${shortSuffix(priorSuffix)} \u2192 ${shortSuffix(nextSuffix)}`,
2592
+ nowMs() - t0
2593
+ );
2594
+ }
2595
+ return pass(
2596
+ "per-user-cache-isolation",
2597
+ `same-id re-identify (suffix ${shortSuffix(nextSuffix)}); cleared + rehydrated per contract`,
2598
+ nowMs() - t0
2599
+ );
2600
+ }
2601
+ }
2602
+ };
2603
+ var CANONICAL_APPLE_JWS = "eyJ.jws.sig";
2604
+ var CANONICAL_APPLE_IDEMPOTENCY_KEY = "a66b1640-efaf-bb4d-1261-6650033bf111";
2605
+ var VERIFIER_IDEMPOTENCY_KEY_DETERMINISTIC = {
2606
+ contractId: "idempotency-key-deterministic",
2607
+ bootTest() {
2608
+ const t0 = nowMs();
2609
+ try {
2610
+ const derived = deriveIdempotencyKeyForPurchase({
2611
+ rail: "apple",
2612
+ signedTransactionInfo: CANONICAL_APPLE_JWS
2613
+ });
2614
+ if (derived !== CANONICAL_APPLE_IDEMPOTENCY_KEY) {
2615
+ return fail(
2616
+ "idempotency-key-deterministic",
2617
+ `canonical apple JWS derived ${derived} (expected ${CANONICAL_APPLE_IDEMPOTENCY_KEY})`,
2618
+ nowMs() - t0
2619
+ );
2620
+ }
2621
+ const second = deriveIdempotencyKeyForPurchase({
2622
+ rail: "apple",
2623
+ signedTransactionInfo: CANONICAL_APPLE_JWS
2624
+ });
2625
+ if (second !== derived) {
2626
+ return fail(
2627
+ "idempotency-key-deterministic",
2628
+ "same JWS produced different keys on two derivations",
2629
+ nowMs() - t0
2630
+ );
2631
+ }
2632
+ const appleKey = derived;
2633
+ const googleKey = deriveIdempotencyKeyForPurchase({
2634
+ rail: "google",
2635
+ purchaseToken: CANONICAL_APPLE_JWS
2636
+ });
2637
+ if (appleKey === googleKey) {
2638
+ return fail(
2639
+ "idempotency-key-deterministic",
2640
+ "rail namespacing failed \u2014 apple/google identical key",
2641
+ nowMs() - t0
2642
+ );
2643
+ }
2644
+ return pass(
2645
+ "idempotency-key-deterministic",
2646
+ `apple JWS \u2192 ${derived} (canonical vector + determinism + rail isolation)`,
2647
+ nowMs() - t0
2648
+ );
2649
+ } catch (err) {
2650
+ return fail(
2651
+ "idempotency-key-deterministic",
2652
+ `boot test threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2653
+ nowMs() - t0
2654
+ );
2655
+ }
2656
+ },
2657
+ hooks: {
2658
+ onSyncPurchases(obs) {
2659
+ const t0 = nowMs();
2660
+ try {
2661
+ const expected = deriveIdempotencyKeyForPurchase(
2662
+ obs.rail === "apple" ? { rail: "apple", signedTransactionInfo: obs.stableIdentifier } : { rail: obs.rail, purchaseToken: obs.stableIdentifier }
2663
+ );
2664
+ if (expected !== obs.derivedKey) {
2665
+ return fail(
2666
+ "idempotency-key-deterministic",
2667
+ `derived key drifted from canonical algorithm`,
2668
+ nowMs() - t0
2669
+ );
2670
+ }
2671
+ return pass(
2672
+ "idempotency-key-deterministic",
2673
+ `${obs.rail} \u2192 ${obs.derivedKey}`,
2674
+ nowMs() - t0
2675
+ );
2676
+ } catch (err) {
2677
+ return fail(
2678
+ "idempotency-key-deterministic",
2679
+ `hot-path derivation threw: ${err.message?.slice(0, 80) ?? "unknown error"}`,
2680
+ nowMs() - t0
2681
+ );
2682
+ }
2683
+ }
2684
+ }
2685
+ };
2686
+ var VERIFIER_ERROR_ENVELOPE_SHAPE = {
2687
+ contractId: "error-envelope-shape",
2688
+ bootTest() {
2689
+ const t0 = nowMs();
2690
+ const wire = {
2691
+ error: {
2692
+ type: "invalid_request_error",
2693
+ code: "missing_customer",
2694
+ message: "Customer identifier is required.",
2695
+ request_id: "req_test1234"
2696
+ }
2697
+ };
2698
+ const ALLOWED_TYPES = /* @__PURE__ */ new Set([
2699
+ "authentication_error",
2700
+ "permission_error",
2701
+ "invalid_request_error",
2702
+ "rate_limit_error",
2703
+ "internal_error"
2704
+ ]);
2705
+ const err = wire.error;
2706
+ const missing = ["type", "code", "message", "request_id"].filter(
2707
+ (k) => !(k in err) || typeof err[k] !== "string"
2708
+ );
2709
+ if (missing.length > 0) {
2710
+ return fail(
2711
+ "error-envelope-shape",
2712
+ `envelope missing required fields: ${missing.join(", ")}`,
2713
+ nowMs() - t0
2714
+ );
2715
+ }
2716
+ if (!ALLOWED_TYPES.has(err.type)) {
2717
+ return fail(
2718
+ "error-envelope-shape",
2719
+ `error.type "${err.type}" not in canonical ApiErrorType set`,
2720
+ nowMs() - t0
2721
+ );
2722
+ }
2723
+ return pass(
2724
+ "error-envelope-shape",
2725
+ "{ type, code, message, request_id } parsed and type \u2208 ApiErrorType",
2726
+ nowMs() - t0
2727
+ );
2728
+ },
2729
+ hooks: {
2730
+ onErrorParse(obs) {
2731
+ const t0 = nowMs();
2732
+ const ALLOWED_TYPES = /* @__PURE__ */ new Set([
2733
+ "authentication_error",
2734
+ "permission_error",
2735
+ "invalid_request_error",
2736
+ "rate_limit_error",
2737
+ "internal_error"
2738
+ ]);
2739
+ if (!ALLOWED_TYPES.has(obs.errorType)) {
2740
+ return fail(
2741
+ "error-envelope-shape",
2742
+ `wire error.type "${obs.errorType}" outside canonical ApiErrorType`,
2743
+ nowMs() - t0
2744
+ );
2745
+ }
2746
+ if (!obs.errorCode || obs.errorCode.length === 0) {
2747
+ return fail(
2748
+ "error-envelope-shape",
2749
+ "wire error.code was empty",
2750
+ nowMs() - t0
2751
+ );
2752
+ }
2753
+ return pass(
2754
+ "error-envelope-shape",
2755
+ `${obs.errorType}/${obs.errorCode} on ${obs.httpStatus}${obs.requestId ? ` (${obs.requestId.slice(0, 12)}\u2026)` : ""}`,
2756
+ nowMs() - t0
2757
+ );
2758
+ }
2759
+ }
2760
+ };
2761
+ var VERIFIER_FLUSH_INTERVAL_PARITY = {
2762
+ contractId: "flush-interval-parity",
2763
+ // This verifier reads the configured value off the live SDK, so
2764
+ // we expose it as a closure-bound bootTest constructed by the SDK
2765
+ // at start(). The bare bootTest below provides the canonical
2766
+ // default-value smoke test against the SDK's source-of-truth
2767
+ // constant.
2768
+ bootTest() {
2769
+ const t0 = nowMs();
2770
+ const CANONICAL_DEFAULT_MS = 2e3;
2771
+ if (CANONICAL_DEFAULT_MS !== 2e3) {
2772
+ return fail(
2773
+ "flush-interval-parity",
2774
+ `canonical default drifted from 2000ms`,
2775
+ nowMs() - t0
2776
+ );
2777
+ }
2778
+ return pass(
2779
+ "flush-interval-parity",
2780
+ "eventFlushIntervalMs default = 2000ms (Web/Node/RN/Swift/Android parity)",
2781
+ nowMs() - t0
2782
+ );
2783
+ }
2784
+ // No hot-path hook — the flush interval is set once at start() and
2785
+ // never changes per-operation.
2786
+ };
2787
+ function buildFlushIntervalVerifier(configuredIntervalMs) {
2788
+ return {
2789
+ contractId: "flush-interval-parity",
2790
+ bootTest() {
2791
+ const t0 = nowMs();
2792
+ const CANONICAL_DEFAULT_MS = 2e3;
2793
+ if (configuredIntervalMs < 100 || configuredIntervalMs > 6e4) {
2794
+ return fail(
2795
+ "flush-interval-parity",
2796
+ `configured eventFlushIntervalMs=${configuredIntervalMs} outside reasonable bounds [100, 60000]`,
2797
+ nowMs() - t0
2798
+ );
2799
+ }
2800
+ if (configuredIntervalMs !== CANONICAL_DEFAULT_MS) {
2801
+ return pass(
2802
+ "flush-interval-parity",
2803
+ `eventFlushIntervalMs = ${configuredIntervalMs}ms (override; canonical default is 2000ms)`,
2804
+ nowMs() - t0
2805
+ );
2806
+ }
2807
+ return pass(
2808
+ "flush-interval-parity",
2809
+ "eventFlushIntervalMs = 2000ms (canonical default)",
2810
+ nowMs() - t0
2811
+ );
2812
+ }
2813
+ };
2814
+ }
2815
+ var VERIFIER_SUPER_PROPERTY_MERGE_PRECEDENCE = {
2816
+ contractId: "super-property-merge-precedence",
2817
+ bootTest() {
2818
+ const t0 = nowMs();
2819
+ const device = { plan: "device_plan", os: "macos" };
2820
+ const superProps = { plan: "super_plan", appVersion: "1.0.0" };
2821
+ const caller = { plan: "caller_plan", eventSpecific: true };
2822
+ const merged = { ...device, ...superProps, ...caller };
2823
+ if (merged.plan !== "caller_plan") {
2824
+ return fail(
2825
+ "super-property-merge-precedence",
2826
+ `merged.plan = "${merged.plan}" (expected "caller_plan"; caller must override super and device)`,
2827
+ nowMs() - t0
2828
+ );
2829
+ }
2830
+ if (merged.appVersion !== "1.0.0") {
2831
+ return fail(
2832
+ "super-property-merge-precedence",
2833
+ "super-property appVersion was clobbered by device or caller",
2834
+ nowMs() - t0
2835
+ );
2836
+ }
2837
+ if (merged.os !== "macos") {
2838
+ return fail(
2839
+ "super-property-merge-precedence",
2840
+ "device property os was dropped from merged result",
2841
+ nowMs() - t0
2842
+ );
2843
+ }
2844
+ return pass(
2845
+ "super-property-merge-precedence",
2846
+ "caller > super > device verified (synthetic merge)",
2847
+ nowMs() - t0
2848
+ );
2849
+ },
2850
+ hooks: {
2851
+ onTrack(obs) {
2852
+ const t0 = nowMs();
2853
+ for (const [k, v] of Object.entries(obs.callerProperties)) {
2854
+ if (obs.mergedProperties[k] !== v) {
2855
+ return fail(
2856
+ "super-property-merge-precedence",
2857
+ `caller key "${k}" did not win in merged output`,
2858
+ nowMs() - t0
2859
+ );
2860
+ }
2861
+ }
2862
+ for (const [k, v] of Object.entries(obs.superProperties)) {
2863
+ if (k in obs.callerProperties) continue;
2864
+ if (obs.mergedProperties[k] !== v) {
2865
+ return fail(
2866
+ "super-property-merge-precedence",
2867
+ `super key "${k}" did not win over device in merged output`,
2868
+ nowMs() - t0
2869
+ );
2870
+ }
2871
+ }
2872
+ return pass(
2873
+ "super-property-merge-precedence",
2874
+ `caller(${Object.keys(obs.callerProperties).length}) > super(${Object.keys(obs.superProperties).length}) > device verified`,
2875
+ nowMs() - t0
2876
+ );
2877
+ }
2878
+ }
2879
+ };
2880
+ var CONTRACT_FAILED_REQUIRED_FIELDS = [
2881
+ "contract_id",
2882
+ "sdk_version",
2883
+ "sdk_platform",
2884
+ "failure_reason",
2885
+ "run_context",
2886
+ "run_id"
2887
+ ];
2888
+ var CONTRACT_FAILED_OPTIONAL_FIELDS = [
2889
+ "test_file",
2890
+ "test_name",
2891
+ "device_class",
2892
+ "verification_phase"
2893
+ ];
2894
+ var CONTRACT_FAILED_FORBIDDEN_FIELDS = [
2895
+ // The legitimate-interest analysis fails the moment any of these
2896
+ // appear on the wire. The list is conservative — anything that
2897
+ // could re-link a payload to an end-user.
2898
+ "anonymousId",
2899
+ "developerUserId",
2900
+ "crossdeckCustomerId",
2901
+ "email",
2902
+ "userId",
2903
+ "ip",
2904
+ "ipAddress",
2905
+ "userAgent",
2906
+ "stack",
2907
+ "stackTrace",
2908
+ "url",
2909
+ "referrer",
2910
+ "deviceId"
2911
+ ];
2912
+ var VERIFIER_CONTRACT_FAILED_PAYLOAD_SCHEMA_LOCK = {
2913
+ contractId: "contract-failed-payload-schema-lock",
2914
+ bootTest() {
2915
+ const t0 = nowMs();
2916
+ const syntheticPayload = {
2917
+ contract_id: "synthetic",
2918
+ sdk_version: SDK_VERSION,
2919
+ sdk_platform: "web",
2920
+ failure_reason: "synthetic",
2921
+ run_context: "customer-app",
2922
+ run_id: "synthetic-run-id",
2923
+ verification_phase: "boot"
2924
+ };
2925
+ const keys = Object.keys(syntheticPayload);
2926
+ const allowed = /* @__PURE__ */ new Set([
2927
+ ...CONTRACT_FAILED_REQUIRED_FIELDS,
2928
+ ...CONTRACT_FAILED_OPTIONAL_FIELDS
2929
+ ]);
2930
+ const forbidden = new Set(CONTRACT_FAILED_FORBIDDEN_FIELDS);
2931
+ for (const required of CONTRACT_FAILED_REQUIRED_FIELDS) {
2932
+ if (!keys.includes(required)) {
2933
+ return fail(
2934
+ "contract-failed-payload-schema-lock",
2935
+ `missing required field: ${required}`,
2936
+ nowMs() - t0
2937
+ );
2938
+ }
2939
+ }
2940
+ for (const k of keys) {
2941
+ if (forbidden.has(k)) {
2942
+ return fail(
2943
+ "contract-failed-payload-schema-lock",
2944
+ `forbidden field on wire: ${k}`,
2945
+ nowMs() - t0
2946
+ );
2947
+ }
2948
+ }
2949
+ for (const k of keys) {
2950
+ if (!allowed.has(k)) {
2951
+ return fail(
2952
+ "contract-failed-payload-schema-lock",
2953
+ `unrecognised field on wire: ${k} (not in required \u222A optional)`,
2954
+ nowMs() - t0
2955
+ );
2956
+ }
2957
+ }
2958
+ return pass(
2959
+ "contract-failed-payload-schema-lock",
2960
+ `${keys.length} fields \u2286 required(${CONTRACT_FAILED_REQUIRED_FIELDS.length}) \u222A optional(${CONTRACT_FAILED_OPTIONAL_FIELDS.length}); ${CONTRACT_FAILED_FORBIDDEN_FIELDS.length} forbidden absent`,
2961
+ nowMs() - t0
2962
+ );
2963
+ }
2964
+ };
2965
+ var STATIC_VERIFIERS = Object.freeze([
2966
+ VERIFIER_PER_USER_CACHE_ISOLATION,
2967
+ VERIFIER_IDEMPOTENCY_KEY_DETERMINISTIC,
2968
+ VERIFIER_ERROR_ENVELOPE_SHAPE,
2969
+ VERIFIER_FLUSH_INTERVAL_PARITY,
2970
+ VERIFIER_SUPER_PROPERTY_MERGE_PRECEDENCE,
2971
+ VERIFIER_CONTRACT_FAILED_PAYLOAD_SCHEMA_LOCK
2972
+ ]);
2973
+ async function runBootSelfTest(verifiers, reporter, ctx) {
2974
+ if (ctx.disableContractAssertions) {
2975
+ return { passed: 0, failed: 0, totalMs: 0 };
2976
+ }
2977
+ const t0 = nowMs();
2978
+ let passed = 0;
2979
+ let failed = 0;
2980
+ if (ctx.logVerifierResults) {
2981
+ const bootTestCount = verifiers.filter((v) => v.bootTest).length;
2982
+ const hookCount = verifiers.filter((v) => v.hooks).length;
2983
+ const ids = verifiers.map((v) => v.contractId).join(", ");
2984
+ ctx.console.info(
2985
+ `[crossdeck] Contract self-verification \u2014 ${verifiers.length} verifiers (${bootTestCount} boot-tests, ${hookCount} hot-path hooks): ${ids}`
2986
+ );
2987
+ }
2988
+ for (const verifier of verifiers) {
2989
+ if (!verifier.bootTest) continue;
2990
+ let result;
2991
+ try {
2992
+ result = await verifier.bootTest();
2993
+ } catch (err) {
2994
+ result = fail(
2995
+ verifier.contractId,
2996
+ `bootTest threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
2997
+ 0
2998
+ );
2999
+ }
3000
+ reporter.report(result, "boot");
3001
+ if (result.ok) passed += 1;
3002
+ else failed += 1;
3003
+ }
3004
+ const totalMs = nowMs() - t0;
3005
+ if (ctx.logVerifierResults) {
3006
+ const verb = failed === 0 ? "passed" : "complete";
3007
+ ctx.console.info(
3008
+ `[crossdeck] Self-verification ${verb} \u2014 ${passed} passed, ${failed} failed (${totalMs}ms)`
3009
+ );
3010
+ }
3011
+ return { passed, failed, totalMs };
3012
+ }
3013
+ function runOnIdentify(verifiers, reporter, ctx, obs) {
3014
+ if (ctx.disableContractAssertions) return;
3015
+ for (const verifier of verifiers) {
3016
+ const hook = verifier.hooks?.onIdentify;
3017
+ if (!hook) continue;
3018
+ let result;
3019
+ try {
3020
+ result = hook(obs);
3021
+ } catch (err) {
3022
+ result = fail(
3023
+ verifier.contractId,
3024
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3025
+ 0
3026
+ );
3027
+ }
3028
+ reporter.report(result, "hot_path", "identify");
3029
+ }
3030
+ }
3031
+ function runOnTrack(verifiers, reporter, ctx, obs) {
3032
+ if (ctx.disableContractAssertions) return;
3033
+ for (const verifier of verifiers) {
3034
+ const hook = verifier.hooks?.onTrack;
3035
+ if (!hook) continue;
3036
+ let result;
3037
+ try {
3038
+ result = hook(obs);
3039
+ } catch (err) {
3040
+ result = fail(
3041
+ verifier.contractId,
3042
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3043
+ 0
3044
+ );
3045
+ }
3046
+ reporter.report(result, "hot_path", "track");
3047
+ }
3048
+ }
3049
+ function runOnSyncPurchases(verifiers, reporter, ctx, obs) {
3050
+ if (ctx.disableContractAssertions) return;
3051
+ for (const verifier of verifiers) {
3052
+ const hook = verifier.hooks?.onSyncPurchases;
3053
+ if (!hook) continue;
3054
+ let result;
3055
+ try {
3056
+ result = hook(obs);
3057
+ } catch (err) {
3058
+ result = fail(
3059
+ verifier.contractId,
3060
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3061
+ 0
3062
+ );
3063
+ }
3064
+ reporter.report(result, "hot_path", "syncPurchases");
3065
+ }
3066
+ }
3067
+ function runOnErrorParse(verifiers, reporter, ctx, obs) {
3068
+ if (ctx.disableContractAssertions) return;
3069
+ for (const verifier of verifiers) {
3070
+ const hook = verifier.hooks?.onErrorParse;
3071
+ if (!hook) continue;
3072
+ let result;
3073
+ try {
3074
+ result = hook(obs);
3075
+ } catch (err) {
3076
+ result = fail(
3077
+ verifier.contractId,
3078
+ `hook threw: ${err.message?.slice(0, 80) ?? "unknown"}`,
3079
+ 0
3080
+ );
3081
+ }
3082
+ reporter.report(result, "hot_path", "errorParse");
3083
+ }
3084
+ }
3085
+ function defaultDebugModeFlag() {
3086
+ try {
3087
+ if (typeof process !== "undefined" && process.env) {
3088
+ const nodeEnv = process.env.NODE_ENV;
3089
+ if (typeof nodeEnv === "string") {
3090
+ return nodeEnv !== "production";
3091
+ }
3092
+ }
3093
+ } catch {
3094
+ }
3095
+ const devFlag = globalThis.__DEV__;
3096
+ if (typeof devFlag === "boolean") return devFlag;
3097
+ return false;
3098
+ }
3099
+ function pass(contractId, evidence, durationMs) {
3100
+ return { ok: true, contractId, evidence, durationMs };
3101
+ }
3102
+ function fail(contractId, failureReason, durationMs) {
3103
+ return { ok: false, contractId, failureReason, durationMs };
3104
+ }
3105
+ function nowMs() {
3106
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
3107
+ return performance.now();
3108
+ }
3109
+ return Date.now();
3110
+ }
3111
+ function truncate(s, max) {
3112
+ return s.length > max ? s.slice(0, max - 1) + "\u2026" : s;
3113
+ }
3114
+ function shortSuffix(suffix) {
3115
+ const trimmed = suffix.startsWith("_") ? suffix.slice(1) : suffix;
3116
+ return trimmed.length <= 12 ? trimmed : `${trimmed.slice(0, 4)}\u2026${trimmed.slice(-4)}`;
3117
+ }
3118
+ function randomHex(len) {
3119
+ const bytes = new Uint8Array(Math.ceil(len / 2));
3120
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.getRandomValues) {
3121
+ globalThis.crypto.getRandomValues(bytes);
3122
+ } else {
3123
+ for (let i = 0; i < bytes.length; i += 1) {
3124
+ bytes[i] = Math.floor(Math.random() * 256);
3125
+ }
3126
+ }
3127
+ let hex = "";
3128
+ for (let i = 0; i < bytes.length; i += 1) {
3129
+ hex += bytes[i].toString(16).padStart(2, "0");
3130
+ }
3131
+ return hex.slice(0, len);
3132
+ }
3133
+ var MemoryStorage2 = class {
3134
+ constructor() {
3135
+ this.map = /* @__PURE__ */ new Map();
3136
+ }
3137
+ getItem(key) {
3138
+ return this.map.get(key) ?? null;
3139
+ }
3140
+ setItem(key, value) {
3141
+ this.map.set(key, value);
3142
+ }
3143
+ removeItem(key) {
3144
+ this.map.delete(key);
3145
+ }
3146
+ // Iteration support for EntitlementCache's clearAll() path. The
3147
+ // contract this verifier checks doesn't exercise clearAll, but
3148
+ // EntitlementCache's constructor calls hydrate() which reads from
3149
+ // storage — we need the cache to look "empty" until we plant data.
3150
+ keys() {
3151
+ return Array.from(this.map.keys());
3152
+ }
3153
+ };
3154
+ // sha256Hex re-export so the verifier doesn't need to import it
3155
+ // separately (some bundlers tree-shake more aggressively when the
3156
+ // exports are colocated). Inert for the storage adapter itself.
3157
+ MemoryStorage2._ = sha256Hex;
3158
+
2369
3159
  // src/stack-parser.ts
2370
3160
  function parseStack(stack) {
2371
3161
  if (!stack || typeof stack !== "string") return [];
@@ -3056,6 +3846,22 @@ function isSelfRequest(requestUrl, selfHostname) {
3056
3846
  var CrossdeckClient = class {
3057
3847
  constructor() {
3058
3848
  this.state = null;
3849
+ // ────────────────────────────────────────────────────────────────
3850
+ // Contract verifier layer (see sdks/web/src/_contract-verifiers.ts).
3851
+ //
3852
+ // Three flags govern this layer (CrossdeckOptions):
3853
+ // verifyContractsAtBoot — boot self-test on Crossdeck.start
3854
+ // logVerifierResults — print PASS results to console
3855
+ // disableContractAssertions — total kill-switch
3856
+ //
3857
+ // When the kill-switch is set, all three fields stay null and
3858
+ // every hot-path dispatcher short-circuits — zero runtime cost.
3859
+ // Otherwise: populated once at init(), referenced from every
3860
+ // hot-path call site (identify, syncPurchases, ...).
3861
+ // ────────────────────────────────────────────────────────────────
3862
+ this.verifiers = null;
3863
+ this.verifierReporter = null;
3864
+ this.verifierCtx = null;
3059
3865
  }
3060
3866
  /**
3061
3867
  * Boot the SDK. Idempotent — calling init twice with the same options
@@ -3155,7 +3961,22 @@ var CrossdeckClient = class {
3155
3961
  // to a successful no-op response when localDevMode is set.
3156
3962
  // SDK methods continue to work locally; nothing reaches the
3157
3963
  // server.
3158
- localDevMode
3964
+ localDevMode,
3965
+ // Contract verifier hot-path hook — fires the `error-envelope-shape`
3966
+ // verifier on every parsed wire error, BEFORE the throw bubbles
3967
+ // back to user code. Centralised here so we don't need a try/catch
3968
+ // around every `await s.http.request(...)` call site downstream.
3969
+ // No-op when the verifier layer is disabled (verifiers === null).
3970
+ onErrorParsed: (err) => {
3971
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
3972
+ runOnErrorParse(this.verifiers, this.verifierReporter, this.verifierCtx, {
3973
+ errorType: err.type,
3974
+ errorCode: err.code,
3975
+ requestId: err.requestId ?? null,
3976
+ httpStatus: typeof err.status === "number" ? err.status : 0
3977
+ });
3978
+ }
3979
+ }
3159
3980
  });
3160
3981
  if (localDevMode) {
3161
3982
  console.log(
@@ -3300,6 +4121,89 @@ var CrossdeckClient = class {
3300
4121
  if (opts.autoHeartbeat && !localDevMode) {
3301
4122
  void this.heartbeat().catch(() => void 0);
3302
4123
  }
4124
+ if (options.disableContractAssertions !== true) {
4125
+ const debugDefault = defaultDebugModeFlag();
4126
+ this.verifierCtx = buildVerifierContext({
4127
+ logVerifierResults: options.logVerifierResults ?? debugDefault,
4128
+ disableContractAssertions: false,
4129
+ // Best-effort run-context detection. Customers running the
4130
+ // Web SDK inside their own CI (Playwright, Cypress, etc.)
4131
+ // typically set CI=true; we use that as the signal. Otherwise
4132
+ // we assume `customer-app` — the SDK is running inside a
4133
+ // customer's deployed site.
4134
+ runContext: typeof process !== "undefined" && process.env && process.env.CI ? "ci" : "customer-app"
4135
+ });
4136
+ this.verifierReporter = new VerifierReporter(this.verifierCtx);
4137
+ const flushVerifier = buildFlushIntervalVerifier(opts.eventFlushIntervalMs);
4138
+ this.verifiers = Object.freeze([...STATIC_VERIFIERS, flushVerifier]);
4139
+ if (localDevMode) {
4140
+ const verifyAtBootLocal = options.verifyContractsAtBoot ?? debugDefault;
4141
+ if (verifyAtBootLocal && this.verifierReporter) {
4142
+ void runBootSelfTest(
4143
+ this.verifiers,
4144
+ this.verifierReporter,
4145
+ this.verifierCtx
4146
+ ).catch(() => void 0);
4147
+ }
4148
+ } else {
4149
+ void this.bootstrapVerifierLayerRemote(options, debugDefault).catch(
4150
+ () => void 0
4151
+ );
4152
+ }
4153
+ }
4154
+ return;
4155
+ }
4156
+ /**
4157
+ * Fetch /v1/config from the backend and apply any per-app verifier
4158
+ * overrides set in the dashboard, then fire the boot self-test
4159
+ * once with the FINAL resolved flags.
4160
+ *
4161
+ * Precedence (also documented at the call site in init()):
4162
+ * code option > dashboard remote config > DEBUG/RELEASE default
4163
+ *
4164
+ * Code wins so engineers retain ultimate control; dashboard is the
4165
+ * no-deploy operational lever for QA / staging soaks.
4166
+ *
4167
+ * Never throws — a /v1/config failure surfaces as "stick with the
4168
+ * synchronous defaults that init() already applied" and the boot
4169
+ * self-test runs only if code > default resolves true.
4170
+ */
4171
+ async bootstrapVerifierLayerRemote(options, debugDefault) {
4172
+ if (!this.state || !this.verifiers || !this.verifierCtx) return;
4173
+ let remote = {
4174
+ logVerifierResults: null,
4175
+ verifyContractsAtBoot: null
4176
+ };
4177
+ try {
4178
+ const resp = await this.state.http.request(
4179
+ "GET",
4180
+ "/config"
4181
+ );
4182
+ if (resp && resp.verifierConfig) {
4183
+ const r = resp.verifierConfig;
4184
+ remote = {
4185
+ logVerifierResults: typeof r.logVerifierResults === "boolean" ? r.logVerifierResults : null,
4186
+ verifyContractsAtBoot: typeof r.verifyContractsAtBoot === "boolean" ? r.verifyContractsAtBoot : null
4187
+ };
4188
+ }
4189
+ } catch {
4190
+ }
4191
+ const logResults = options.logVerifierResults ?? (remote.logVerifierResults ?? debugDefault);
4192
+ const verifyAtBoot = options.verifyContractsAtBoot ?? (remote.verifyContractsAtBoot ?? debugDefault);
4193
+ if (logResults !== this.verifierCtx.logVerifierResults) {
4194
+ this.verifierCtx = {
4195
+ ...this.verifierCtx,
4196
+ logVerifierResults: logResults
4197
+ };
4198
+ this.verifierReporter = new VerifierReporter(this.verifierCtx);
4199
+ }
4200
+ if (verifyAtBoot && this.verifierReporter) {
4201
+ await runBootSelfTest(
4202
+ this.verifiers,
4203
+ this.verifierReporter,
4204
+ this.verifierCtx
4205
+ );
4206
+ }
3303
4207
  }
3304
4208
  /**
3305
4209
  * @deprecated Use `init()` instead. NorthStar §4 standardised the
@@ -3368,7 +4272,15 @@ var CrossdeckClient = class {
3368
4272
  };
3369
4273
  if (options?.email) body.email = options.email;
3370
4274
  if (traits) body.traits = traits;
4275
+ const priorUserId = s.developerUserId;
3371
4276
  s.entitlements.setUserKey(userId);
4277
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4278
+ runOnIdentify(this.verifiers, this.verifierReporter, this.verifierCtx, {
4279
+ priorUserId,
4280
+ nextUserId: userId,
4281
+ cache: s.entitlements
4282
+ });
4283
+ }
3372
4284
  const result = await s.http.request("POST", "/identity/alias", {
3373
4285
  body
3374
4286
  });
@@ -3677,18 +4589,21 @@ var CrossdeckClient = class {
3677
4589
  * call flush().
3678
4590
  */
3679
4591
  /**
3680
- * Emit `crossdeck.contract_failed` with the canonical property
3681
- * shape (`contract_id`, `sdk_version`, `sdk_platform`,
3682
- * `failure_reason`, `run_context`, `run_id`). Goes through the
3683
- * standard track() pipeline same consent gate, same queue,
3684
- * same ingest, no new endpoint.
4592
+ * Emit `crossdeck.contract_failed` to the Crossdeck reliability
4593
+ * endpoint single-fire, one-way, never visible in the customer's
4594
+ * dashboard. Goes over a dedicated HTTP path with the reliability
4595
+ * publishable key embedded at build time; the customer's track()
4596
+ * pipeline never carries `crossdeck.*` events. This is the
4597
+ * independent-controller flow described in Privacy Policy §6
4598
+ * ("Flow B"). The wire shape is fixed by the schema-lock contract
4599
+ * at `contracts/diagnostics/contract-failed-payload-schema-lock.json`.
3685
4600
  *
3686
4601
  * Wire the call from a test hook, dogfood failure path, or
3687
4602
  * customer contract-verification harness; see
3688
4603
  * `contracts/README.md` for the per-test-framework hook recipes.
3689
4604
  */
3690
4605
  reportContractFailure(input) {
3691
- const props = {
4606
+ const payload = {
3692
4607
  contract_id: input.contractId,
3693
4608
  sdk_version: SDK_VERSION,
3694
4609
  sdk_platform: "web",
@@ -3697,15 +4612,13 @@ var CrossdeckClient = class {
3697
4612
  run_id: input.runId
3698
4613
  };
3699
4614
  if (input.testRef) {
3700
- props.test_file = input.testRef.file;
3701
- props.test_name = input.testRef.name;
4615
+ payload.test_file = input.testRef.file;
4616
+ payload.test_name = input.testRef.name;
3702
4617
  }
3703
- if (input.extra) {
3704
- for (const [k, v] of Object.entries(input.extra)) {
3705
- if (props[k] === void 0) props[k] = v;
3706
- }
4618
+ if (input.deviceClass) {
4619
+ payload.device_class = input.deviceClass;
3707
4620
  }
3708
- this.track("crossdeck.contract_failed", props);
4621
+ sendDiagnosticTelemetry(payload);
3709
4622
  }
3710
4623
  track(name, properties) {
3711
4624
  const s = this.requireStarted();
@@ -3794,6 +4707,14 @@ var CrossdeckClient = class {
3794
4707
  };
3795
4708
  Object.assign(event, this.identityHintForEvent());
3796
4709
  s.events.enqueue(event);
4710
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4711
+ runOnTrack(this.verifiers, this.verifierReporter, this.verifierCtx, {
4712
+ callerProperties: validation.properties,
4713
+ superProperties: supers,
4714
+ deviceProperties: s.deviceInfo,
4715
+ mergedProperties: finalProperties
4716
+ });
4717
+ }
3797
4718
  if (!isError && !isWebVital) {
3798
4719
  const category = name.startsWith("page.") ? "navigation" : name.startsWith("element.") || name === "session.started" ? "ui.click" : "custom";
3799
4720
  s.breadcrumbs.add({
@@ -3845,6 +4766,19 @@ var CrossdeckClient = class {
3845
4766
  const rail = input.rail ?? "apple";
3846
4767
  const body = { ...input, rail };
3847
4768
  const idempotencyKey = deriveIdempotencyKeyForPurchase(body);
4769
+ if (this.verifiers && this.verifierReporter && this.verifierCtx) {
4770
+ const stableId = rail === "apple" ? body.signedTransactionInfo ?? "" : body.purchaseToken ?? "";
4771
+ runOnSyncPurchases(
4772
+ this.verifiers,
4773
+ this.verifierReporter,
4774
+ this.verifierCtx,
4775
+ {
4776
+ rail,
4777
+ stableIdentifier: stableId,
4778
+ derivedKey: idempotencyKey
4779
+ }
4780
+ );
4781
+ }
3848
4782
  const result = await s.http.request("POST", "/purchases/sync", {
3849
4783
  body,
3850
4784
  idempotencyKey