@cross-deck/web 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,342 +1,54 @@
1
- /**
2
- * Public types for @cross-deck/web. These mirror the wire format
3
- * exposed by the v1 backend API. Keep them in lockstep with
4
- * backend/src/api/v1-types.ts — same field names, same nullability.
5
- */
6
- type Environment = "production" | "sandbox";
7
- type Platform = "ios" | "android" | "web";
8
- type AuditRail = "apple" | "stripe" | "google" | "manual";
9
- interface PublicEntitlement {
10
- object: "entitlement";
11
- key: string;
12
- isActive: boolean;
13
- validUntil?: number | null;
14
- source: {
15
- rail: AuditRail;
16
- productId: string;
17
- subscriptionId: string;
18
- };
19
- updatedAt: number;
20
- }
21
- interface EntitlementsListResponse {
22
- object: "list";
23
- data: PublicEntitlement[];
24
- crossdeckCustomerId: string;
25
- env: Environment;
26
- }
27
- interface AliasResult {
28
- object: "alias_result";
29
- crossdeckCustomerId: string;
30
- linked: Array<{
31
- type: "developer";
32
- id: string;
33
- } | {
34
- type: "anonymous";
35
- id: string;
36
- }>;
37
- mergePending: boolean;
38
- env: Environment;
39
- }
40
- interface PurchaseResult {
41
- object: "purchase_result";
42
- crossdeckCustomerId: string;
43
- env: Environment;
44
- entitlements: PublicEntitlement[];
45
- }
46
- interface HeartbeatResponse {
47
- object: "heartbeat";
48
- ok: true;
49
- projectId: string;
50
- appId: string;
51
- platform: Platform;
52
- env: Environment;
53
- serverTime: number;
54
- }
55
- /**
56
- * Configuration for Crossdeck.init. Three fields are mandatory —
57
- * `appId`, `publicKey`, and `environment` — per NorthStar §11.1.
58
- *
59
- * The pair of (appId, environment) is what we put on the wire envelope
60
- * (NorthStar §13.1) so the backend can correlate events against the
61
- * specific app surface and refuse mismatched env declarations loudly.
62
- */
63
- interface CrossdeckOptions {
64
- /**
65
- * Your Crossdeck App ID (e.g. "app_web_xxx"). Required.
66
- *
67
- * Issued in the dashboard when you create an app. Goes on the wire
68
- * envelope so the backend correlates events with the specific app
69
- * surface — useful when one project has multiple apps (web + iOS +
70
- * Android) sharing the same publishable key family.
71
- */
72
- appId: string;
73
- /** Your Crossdeck publishable key (cd_pub_…). Required. */
74
- publicKey: string;
75
- /**
76
- * Explicit environment declaration. Required.
77
- *
78
- * Must match the publishable key's prefix:
79
- * cd_pub_test_… → "sandbox"
80
- * cd_pub_live_… → "production"
81
- *
82
- * Mismatch is rejected at init time so a typo'd key can't silently
83
- * route prod telemetry into sandbox dashboards.
84
- */
85
- environment: Environment;
86
- /**
87
- * Override the API base URL. Default is https://api.cross-deck.com/v1.
88
- * Useful for self-hosted setups or pointing at the local emulator
89
- * (e.g. http://localhost:5001/crossdeck-47d8f/us-east4/v1).
90
- */
91
- baseUrl?: string;
92
- /**
93
- * Persist anonymousId + crossdeckCustomerId across sessions.
94
- * Default: true in the browser (localStorage), false in Node (in-memory only).
95
- */
96
- persistIdentity?: boolean;
97
- /**
98
- * Storage adapter. The SDK calls .getItem / .setItem / .removeItem.
99
- * Defaults to globalThis.localStorage when present. Pass an in-memory
100
- * adapter for Node runtimes where you want session-only persistence.
101
- */
102
- storage?: KeyValueStorage;
103
- /** Storage key prefix for the SDK's persisted state. Default "crossdeck:". */
104
- storagePrefix?: string;
105
- /**
106
- * Send a heartbeat to /v1/sdk/heartbeat on start(). Default true.
107
- * Disable for high-frequency boot scenarios where the heartbeat is
108
- * pure overhead.
109
- */
110
- autoHeartbeat?: boolean;
111
- /** Maximum events buffered before forced flush. Default 20. */
112
- eventFlushBatchSize?: number;
113
- /** Idle ms after the last track() before flushing. Default 5000. */
114
- eventFlushIntervalMs?: number;
115
- /** Override the SDK version reported on heartbeats. Default: package version. */
116
- sdkVersion?: string;
117
- /**
118
- * Auto-tracking. Default: every flag is `true` in browsers, all
119
- * silently no-op in Node.
120
- *
121
- * Pass `false` to disable everything, or a partial object to override
122
- * individual flags:
123
- *
124
- * Crossdeck.start({
125
- * publicKey: "...",
126
- * autoTrack: { pageViews: false }, // sessions + deviceInfo still on
127
- * });
128
- */
129
- autoTrack?: boolean | Partial<AutoTrackOptions>;
130
- /**
131
- * Your app's version (e.g. "1.2.3"). Auto-attached to every event as
132
- * `properties.appVersion` when `autoTrack.deviceInfo` is enabled.
133
- * Useful for slicing dashboards by build.
134
- */
135
- appVersion?: string;
136
- /**
137
- * Enable verbose diagnostic logging via the NorthStar §16 debug-signal
138
- * vocabulary. Default: false. Equivalent to calling
139
- * `Crossdeck.setDebugMode(true)` after init.
140
- */
141
- debug?: boolean;
142
- /**
143
- * Respect the browser's Do Not Track signal at init (v0.10.0+).
144
- * Default `false`. When `true` AND the user has `navigator.doNotTrack === "1"`,
145
- * the SDK boots with analytics / marketing / errors all denied —
146
- * locked off even if the developer later calls `Crossdeck.consent({...})`.
147
- * Industry has effectively deprecated DNT, but opt-in support is the
148
- * polite default for privacy-first apps.
149
- */
150
- respectDnt?: boolean;
151
- /**
152
- * Scrub PII-shaped strings (email addresses, card numbers) from
153
- * URL paths, event properties, and acquisition referrer before they
154
- * leave the SDK. Default `true` — Stripe-grade. Disable only if your
155
- * pipeline does its own PII redaction downstream and you need the
156
- * raw strings.
157
- */
158
- scrubPii?: boolean;
159
- }
160
- /** Auto-tracking flags. See CrossdeckOptions.autoTrack. */
161
- interface AutoTrackOptions {
162
- /** Emit `session.started` / `session.ended` automatically. Default true (browser only). */
163
- sessions: boolean;
164
- /** Emit `page.viewed` on initial load + SPA navigation. Default true (browser only). */
165
- pageViews: boolean;
166
- /** Auto-attach os/browser/locale/screen/etc to every event's `properties`. Default true (browser only). */
167
- deviceInfo: boolean;
168
- /**
169
- * Click autocapture — fire `element.clicked` for every interactive
170
- * click on the page. Default true. Mixpanel/Amplitude pattern. Powers
171
- * Crossdeck's funnel-attribution USP ("clicked X then converted").
172
- * Privacy: skips form inputs / password fields / [class~="cd-noTrack"]
173
- * subtrees. Override on individual elements with data-cd-event="custom"
174
- * or data-cd-prop-* for custom property tagging.
175
- */
176
- clicks: boolean;
177
- /**
178
- * Web Vitals capture (v0.9.0+) — emits `webvitals.lcp`, `webvitals.inp`,
179
- * `webvitals.cls`, `webvitals.fcp`, `webvitals.ttfb` events using the
180
- * browser's `PerformanceObserver`. Defaults to true in browsers,
181
- * no-op everywhere else. Disable if you have a separate RUM provider
182
- * (DataDog, Sentry Performance) and don't want duplicates.
183
- */
184
- webVitals: boolean;
185
- /**
186
- * Error capture (v1.0.0+) — installs window.onerror +
187
- * window.onunhandledrejection listeners, wraps fetch + XHR to catch
188
- * 5xx + network failures, ships each captured error as a Crossdeck
189
- * event (kind: error.unhandled / error.unhandledrejection /
190
- * error.handled / error.http / error.message). Errors gate on
191
- * `consent.errors`. Rate-limited per-fingerprint so a runaway loop
192
- * can't flood the queue; browser-extension noise filtered by
193
- * default. Default true in browsers, no-op everywhere else.
194
- */
195
- errors: boolean;
196
- }
197
- /** Minimal interface for any pluggable key-value persistence. */
198
- interface KeyValueStorage {
199
- getItem(key: string): string | null;
200
- setItem(key: string, value: string): void;
201
- removeItem(key: string): void;
202
- }
203
- /**
204
- * Identity hint + profile traits passed to identify().
205
- *
206
- * `traits` is a free-form bag of profile data (name, plan, signupDate,
207
- * teamRole, etc.) that gets persisted on the Crossdeck customer record
208
- * and attached to every subsequent event of the identified user as
209
- * `$user.<key>` properties for dashboard filtering.
210
- *
211
- * Like event properties, traits are validated at the SDK boundary —
212
- * functions/symbols/undefined dropped, Date / BigInt / Error coerced,
213
- * strings > 1024 chars truncated. Caller's object is never mutated.
214
- */
215
- interface IdentifyOptions {
216
- /** Optional email to attach to the customer record. */
217
- email?: string;
218
- /**
219
- * Optional profile traits. Examples:
220
- * `{ name: "Wes", plan: "pro", signedUpAt: "2026-05-11" }`
221
- *
222
- * Treated like event properties — values are sanitised at the SDK
223
- * boundary so a `{ avatar: <File>, callback: () => {} }` payload
224
- * doesn't crash the alias request. Server-side, traits land on
225
- * `customers/{cdcust}.traits` (additively — existing fields are
226
- * preserved unless the new identify call overrides them).
227
- */
228
- traits?: Record<string, unknown>;
229
- }
230
- /**
231
- * Group context — Mixpanel-style. Identifies a customer's membership
232
- * in an organisational entity (org, account, team, workspace) so B2B
233
- * dashboards can answer "how is account X using my product".
234
- *
235
- * Attached to every event as `$groups.<type>` until cleared via
236
- * `Crossdeck.group(type, null)`. Multiple types can coexist (e.g.
237
- * `org` + `team`) — the SDK keeps a map keyed by type.
238
- */
239
- interface GroupTraits {
240
- [key: string]: unknown;
241
- }
242
- /** Properties payload for track(). Arbitrary key/value, JSON-serialisable, ≤ 8 KB. */
243
- type EventProperties = Record<string, unknown>;
244
- /**
245
- * Diagnostic snapshot returned by Crossdeck.diagnostics(). Stable shape
246
- * whether or not start() has been called — callers don't need to narrow
247
- * on `started` to read `events` or `entitlements`. Pre-start values are
248
- * sensible empties (zeros, nulls).
249
- */
250
- interface Diagnostics {
251
- started: boolean;
252
- anonymousId: string | null;
253
- crossdeckCustomerId: string | null;
254
- developerUserId: string | null;
255
- sdkVersion: string | null;
256
- baseUrl: string | null;
257
- /**
258
- * Last `serverTime` value the SDK saw on a /sdk/heartbeat response,
259
- * along with the local clock value AT that moment. Lets dashboards
260
- * (and the developer, in debug mode) detect a wrong-system-clock
261
- * problem before it corrupts a day of analytics. Null until the
262
- * first heartbeat completes.
263
- */
264
- clock: {
265
- /** Server's view of "now" from the last heartbeat (epoch ms). */
266
- lastServerTime: number | null;
267
- /** Client's `Date.now()` taken at the same moment as `lastServerTime`. */
268
- lastClientTime: number | null;
269
- /**
270
- * `lastClientTime - lastServerTime` — positive means the client
271
- * clock is AHEAD of the server. Outside ±5 minutes is suspicious
272
- * and worth surfacing to the developer.
273
- */
274
- skewMs: number | null;
275
- };
276
- entitlements: {
277
- count: number;
278
- lastUpdated: number;
279
- /**
280
- * Cumulative count of listener invocations that threw. Swallowed
281
- * inside the cache (a buggy consumer must not crash the SDK) but
282
- * surfaced here so developers can spot broken subscribers.
283
- */
284
- listenerErrors: number;
285
- };
286
- events: {
287
- buffered: number;
288
- dropped: number;
289
- inFlight: number;
290
- lastFlushAt: number;
291
- lastError: string | null;
292
- /** Consecutive flush failures since the last success. */
293
- consecutiveFailures: number;
294
- /**
295
- * When the next retry is scheduled (epoch ms), or null if the queue
296
- * is idle / healthy.
297
- */
298
- nextRetryAt: number | null;
299
- };
300
- }
1
+ import { P as PublicEntitlement, C as CrossdeckOptions, I as IdentifyOptions, A as AliasResult, G as GroupTraits, E as EventProperties, a as PurchaseResult, H as HeartbeatResponse, D as Diagnostics, K as KeyValueStorage } from './types-BzoKor4z.js';
2
+ export { b as AuditRail, c as AutoTrackOptions, d as EntitlementsListResponse, e as Environment, f as Platform } from './types-BzoKor4z.js';
301
3
 
302
4
  /**
303
- * Local cache of active entitlements so isEntitled() can answer
304
- * synchronously after the first read. Cache is updated:
305
- * - On successful getEntitlements()
306
- * - On successful purchase()
307
- * - Manually via setFromList() (used by callers that batch updates)
308
- *
309
- * The cache holds only ACTIVE entitlements — inactive ones are excluded
310
- * by the backend before they hit us. isEntitled returns false for
311
- * anything not in the set.
5
+ * Durable last-known-good cache of the customer's entitlements.
6
+ *
7
+ * This cache is NOT a second source of truth. Crossdeck remains the
8
+ * only source; this is the SDK's local copy of what the server last
9
+ * told us a cache that doesn't forget during a network partition.
10
+ *
11
+ * Durability contract (the RevenueCat model):
12
+ * - Every successful server read is persisted to device storage
13
+ * (localStorage, via the SDK's storage adapter).
14
+ * - On SDK boot the cache hydrates from storage synchronously, so
15
+ * isEntitled() answers correctly from the very first call — there
16
+ * is no cold-start window where a returning Pro customer reads as
17
+ * free.
18
+ * - When the server is unreachable, the SDK keeps serving the last
19
+ * entitlements it successfully fetched. A failed refresh never
20
+ * reaches setFromList(), so it cannot clear the cache; only a
21
+ * SUCCESSFUL fetch replaces it. An outage can never fail a paying
22
+ * customer down to free.
23
+ * - Staleness alone never returns false. Each entitlement is honoured
24
+ * against its OWN validUntil instead — a time-based trial expiry
25
+ * still applies even mid-partition, a still-valid Pro entitlement
26
+ * rides the outage out.
27
+ * - Staleness is VISIBLE, not silent. validUntil covers time-based
28
+ * expiry; it does NOT cover an event-based revoke (chargeback,
29
+ * refund, fraud) — that has no validUntil, so the cache would keep
30
+ * serving a revoked customer through an outage. Serving them is the
31
+ * right trade (don't lock real payers out), but unbounded-and-
32
+ * invisible is the bug. So: once a refresh ATTEMPT fails (or the
33
+ * data ages past staleAfterMs) the cache is marked stale —
34
+ * isStale / freshness are surfaced in diagnostics(). It keeps
35
+ * serving last-known-good; the staleness is just no longer hidden.
36
+ *
37
+ * The cache is wiped only on reset() (logout) and on an identity switch
38
+ * — never by a TTL.
312
39
  *
313
40
  * Reactive listener API
314
41
  * ---------------------
315
- * `subscribe(listener)` registers a callback that fires every time the
316
- * cache mutates (setFromList or clear). This is the foundation for the
317
- * `useEntitlement` React hook in `@cross-deck/web/react` and any other
318
- * framework binding consumers need: SwiftUI's `@Observable`, Vue's
319
- * `ref()`, Solid's signals, etc.
320
- *
321
- * Why we need it: isEntitled() is a sync cache read — but if a React
322
- * component calls it in a render path, React has no way to know when
323
- * the cache populates asynchronously after `getEntitlements()` lands.
324
- * Without a subscribe API the component shows the empty-cache result
325
- * forever (until something else triggers a re-render). With it, the
326
- * binding can re-render when the data actually arrives.
327
- *
328
- * Listener semantics:
329
- * - Fired AFTER the cache has been mutated (listener sees fresh state)
330
- * - Fire-and-forget: thrown errors in a listener don't crash the SDK
331
- * (they're swallowed; the next listener still runs)
332
- * - The unsubscribe function returned from subscribe() is idempotent
333
- * - Listeners are NOT fired on subscribe — caller is expected to
334
- * read current state synchronously from isEntitled()/list() if it
335
- * wants the initial render to reflect cached data
336
- *
337
- * Thread / re-entrancy safety: this is a synchronous in-memory Set with
338
- * no I/O. The async paths that update it are serialised through the
339
- * SDK's request queue — callers won't see torn reads.
42
+ * `subscribe(listener)` registers a callback fired every time the cache
43
+ * mutates (setFromList or clear) the foundation for the
44
+ * `useEntitlement` React hook and other framework bindings. Semantics:
45
+ * - Fired AFTER the mutation, so the listener sees fresh state.
46
+ * - Fire-and-forget: a throwing listener is swallowed (and counted)
47
+ * so a buggy consumer can't crash the SDK or other listeners.
48
+ * - Unsubscribe is idempotent.
49
+ * - Listeners are NOT fired on subscribe a caller that wants the
50
+ * initial state reads isEntitled() / list() synchronously, which
51
+ * work from boot thanks to hydration above.
340
52
  */
341
53
 
342
54
  type EntitlementsListener = (entitlements: PublicEntitlement[]) => void;
@@ -723,8 +435,12 @@ declare class CrossdeckClient {
723
435
  */
724
436
  getEntitlements(): Promise<PublicEntitlement[]>;
725
437
  /**
726
- * Synchronous read from the local cache. Returns false if the cache
727
- * has never been populated (call getEntitlements first to warm it).
438
+ * Synchronous read from the durable local cache answers from
439
+ * last-known-good. The cache hydrates from device storage on boot and
440
+ * survives a Crossdeck outage, so a returning paying customer reads
441
+ * true even before the session's first network round-trip. Returns
442
+ * false only for a genuinely new install that has never completed a
443
+ * getEntitlements(), or for an entitlement past its own validUntil.
728
444
  */
729
445
  isEntitled(key: string): boolean;
730
446
  /** Snapshot of the local entitlement cache. */
@@ -955,7 +671,7 @@ declare class MemoryStorage implements KeyValueStorage {
955
671
  * fetch shim, no transitive deps.
956
672
  */
957
673
  declare const SDK_NAME = "@cross-deck/web";
958
- declare const SDK_VERSION = "1.0.0";
674
+ declare const SDK_VERSION = "1.1.0";
959
675
  declare const DEFAULT_BASE_URL = "https://api.cross-deck.com/v1";
960
676
 
961
677
  /**
@@ -1028,4 +744,4 @@ interface DeviceInfo {
1028
744
  appVersion?: string;
1029
745
  }
1030
746
 
1031
- export { type AliasResult, type AuditRail, type AutoTrackOptions, type Breadcrumb, type BreadcrumbCategory, type BreadcrumbLevel, CROSSDECK_ERROR_CODES, type CapturedError, type ConsentState, Crossdeck, CrossdeckClient, CrossdeckError, type CrossdeckErrorPayload, type CrossdeckErrorType, type CrossdeckOptions, DEFAULT_BASE_URL, type DeviceInfo, type Diagnostics, type EntitlementsListResponse, type Environment, type ErrorCodeEntry, type ErrorLevel, type EventProperties, type GroupTraits, type HeartbeatResponse, type IdentifyOptions, type KeyValueStorage, MemoryStorage, type Platform, type PublicEntitlement, type PurchaseResult, SDK_NAME, SDK_VERSION, type StackFrame, getErrorCode };
747
+ export { AliasResult, type Breadcrumb, type BreadcrumbCategory, type BreadcrumbLevel, CROSSDECK_ERROR_CODES, type CapturedError, type ConsentState, Crossdeck, CrossdeckClient, CrossdeckError, type CrossdeckErrorPayload, type CrossdeckErrorType, CrossdeckOptions, DEFAULT_BASE_URL, type DeviceInfo, Diagnostics, type ErrorCodeEntry, type ErrorLevel, EventProperties, GroupTraits, HeartbeatResponse, IdentifyOptions, KeyValueStorage, MemoryStorage, PublicEntitlement, PurchaseResult, SDK_NAME, SDK_VERSION, type StackFrame, getErrorCode };