@haakco/custd-sdk 0.0.0-stage → 2.4.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.
Files changed (50) hide show
  1. package/README.md +412 -2
  2. package/dist/admin-client-setup.d.ts +100 -0
  3. package/dist/admin-client-setup.js +398 -0
  4. package/dist/admin-data-labels.d.ts +124 -0
  5. package/dist/admin-data-labels.js +51 -0
  6. package/dist/admin-offboarding.d.ts +109 -0
  7. package/dist/admin-offboarding.js +108 -0
  8. package/dist/admin-predictions.d.ts +147 -0
  9. package/dist/admin-predictions.js +83 -0
  10. package/dist/admin-privacy-erasures.d.ts +62 -0
  11. package/dist/admin-privacy-erasures.js +72 -0
  12. package/dist/admin-retention.d.ts +51 -0
  13. package/dist/admin-retention.js +35 -0
  14. package/dist/admin-subject-exports.d.ts +48 -0
  15. package/dist/admin-subject-exports.js +28 -0
  16. package/dist/admin-tenant-storage.d.ts +27 -0
  17. package/dist/admin-tenant-storage.js +25 -0
  18. package/dist/admin-timeplans.d.ts +238 -0
  19. package/dist/admin-timeplans.js +146 -0
  20. package/dist/analytics-events.d.ts +85 -0
  21. package/dist/analytics-events.js +40 -0
  22. package/dist/backend-lifecycle.d.ts +85 -0
  23. package/dist/backend-lifecycle.js +212 -0
  24. package/dist/browser-manifest.json +7 -0
  25. package/dist/browser-script-BvgjdZSO.js +429 -0
  26. package/dist/browser-script.d.ts +1 -0
  27. package/dist/browser-script.js +5 -0
  28. package/dist/browser-tracker.d.ts +47 -0
  29. package/dist/browser-tracker.js +453 -0
  30. package/dist/browser.d.ts +1 -0
  31. package/dist/browser.js +1 -0
  32. package/dist/fixtures.d.ts +10 -0
  33. package/dist/fixtures.js +57 -0
  34. package/dist/index.d.ts +1310 -0
  35. package/dist/index.js +1706 -0
  36. package/dist/mobile-adapter.d.ts +25 -0
  37. package/dist/mobile-adapter.js +57 -0
  38. package/dist/mobile-context.d.ts +32 -0
  39. package/dist/mobile-context.js +156 -0
  40. package/dist/mobile-queue.d.ts +22 -0
  41. package/dist/mobile-queue.js +73 -0
  42. package/dist/oauth.d.ts +1 -0
  43. package/dist/oauth.js +8 -0
  44. package/dist/reporting-state.d.ts +46 -0
  45. package/dist/reporting-state.js +76 -0
  46. package/dist/runtime-readiness.d.ts +30 -0
  47. package/dist/runtime-readiness.js +150 -0
  48. package/dist/version.d.ts +10 -0
  49. package/dist/version.js +10 -0
  50. package/package.json +46 -4
@@ -0,0 +1,47 @@
1
+ import { type QueueStorage, type RetryOptions } from "./index.js";
2
+ export type BrowserIdentityMode = "cookieless" | "extended";
3
+ export type BrowserConsentState = "granted" | "denied";
4
+ export type BrowserTrackerConfig = {
5
+ baseUrl: string;
6
+ siteUuid: string;
7
+ writeKey: string;
8
+ /**
9
+ * The environment this build runs in, for a preview deployment, a staging
10
+ * host, or a local server that shares the same Site. It is sent as the
11
+ * reserved `custd.environment` label; a Site serves every environment unless
12
+ * an operator restricts it, so this is not a second credential.
13
+ */
14
+ environment?: string;
15
+ allowedOrigins?: string[];
16
+ identityMode?: BrowserIdentityMode;
17
+ consent?: "granted" | "required";
18
+ batchSize?: number;
19
+ maxQueueSize?: number;
20
+ persistentQueue?: boolean;
21
+ queueStorage?: QueueStorage;
22
+ retry?: RetryOptions;
23
+ trackInitialPageView?: boolean;
24
+ };
25
+ export type BrowserTracker = {
26
+ track: (eventTypeSlug: string, payload?: Record<string, unknown>) => Promise<void>;
27
+ trackPageView: () => Promise<void>;
28
+ installSpaTracking: () => void;
29
+ setConsent: (state: BrowserConsentState) => void;
30
+ flush: () => Promise<void>;
31
+ close: () => void;
32
+ };
33
+ export type BrowserSiteConfig = {
34
+ identityMode?: BrowserIdentityMode;
35
+ allowedOrigins?: string[];
36
+ };
37
+ export declare function createBrowserTracker(config: BrowserTrackerConfig): BrowserTracker;
38
+ export declare function installBrowserTrackerFromScript(scriptElement?: HTMLScriptElement): Promise<BrowserTracker>;
39
+ declare global {
40
+ interface Window {
41
+ custd: {
42
+ track: (eventTypeSlug: string, payload?: Record<string, unknown>) => Promise<void>;
43
+ trackPageView: () => Promise<void>;
44
+ setConsent: (state: BrowserConsentState) => void;
45
+ };
46
+ }
47
+ }
@@ -0,0 +1,453 @@
1
+ import { applyEnvironmentLabel, LocalStorageQueueStorage, MemoryQueueStorage, normalizeRetryOptions, prepareEvent, RetryableError, validateBrowserEvent, withRetry, } from "./index.js";
2
+ const defaultSchemaVersion = "1.0.0";
3
+ const maxQueuedGlobalCalls = 1000;
4
+ const redactedPathSegment = "[redacted]";
5
+ const safePathSegment = /^[A-Za-z][A-Za-z0-9._~-]{0,63}$/u;
6
+ const uuidPathSegment = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
7
+ const opaquePathSegment = /^[A-Za-z0-9_-]{24,}$/u;
8
+ const poweredByProjectSlug = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
9
+ export function createBrowserTracker(config) {
10
+ return new DefaultBrowserTracker(config);
11
+ }
12
+ class DefaultBrowserTracker {
13
+ constructor(config) {
14
+ this.queue = [];
15
+ this.installedSpaTracking = false;
16
+ this.originalPushState = null;
17
+ this.originalReplaceState = null;
18
+ this.onlineHandler = () => void this.flush();
19
+ this.pagehideHandler = () => this.flushWithKeepalive();
20
+ this.popstateHandler = () => void this.trackPageView();
21
+ this.config = config;
22
+ this.baseUrl = config.baseUrl.replace(/\/$/, "");
23
+ this.queueStorage = config.queueStorage ?? browserQueueStorage(config.siteUuid, config.persistentQueue === true);
24
+ this.retry = normalizeRetryOptions(config.retry);
25
+ this.maxQueueSize = config.maxQueueSize ?? 1000;
26
+ this.queue = this.queueStorage.load();
27
+ this.trimQueue();
28
+ this.consent = config.consent === "required" ? "denied" : "granted";
29
+ if (this.trackingDisabled()) {
30
+ this.clearStoredState();
31
+ }
32
+ assertSecureOrLocalHTTP(this.baseUrl, "baseUrl");
33
+ assertAllowedOrigin(config);
34
+ window.addEventListener("online", this.onlineHandler);
35
+ window.addEventListener("pagehide", this.pagehideHandler);
36
+ }
37
+ async track(eventTypeSlug, payload = {}) {
38
+ if (this.trackingDisabled()) {
39
+ return;
40
+ }
41
+ const event = this.buildEvent(eventTypeSlug, payload);
42
+ if ((this.config.batchSize ?? 0) > 1) {
43
+ this.enqueue(event);
44
+ if (this.queue.length >= (this.config.batchSize ?? 0)) {
45
+ await this.flush();
46
+ }
47
+ return;
48
+ }
49
+ await this.sendEvent(event);
50
+ }
51
+ trackPageView() {
52
+ return this.track("page-view", poweredByAttribution());
53
+ }
54
+ installSpaTracking() {
55
+ if (this.installedSpaTracking) {
56
+ return;
57
+ }
58
+ this.installedSpaTracking = true;
59
+ this.originalPushState = window.history.pushState;
60
+ this.originalReplaceState = window.history.replaceState;
61
+ window.history.pushState = this.wrapHistoryMethod(this.originalPushState);
62
+ window.history.replaceState = this.wrapHistoryMethod(this.originalReplaceState);
63
+ window.addEventListener("popstate", this.popstateHandler);
64
+ if (this.config.trackInitialPageView !== false) {
65
+ void this.trackPageView();
66
+ }
67
+ }
68
+ setConsent(state) {
69
+ this.consent = state;
70
+ if (state === "denied") {
71
+ this.clearStoredState();
72
+ }
73
+ }
74
+ async flush() {
75
+ if (this.trackingDisabled()) {
76
+ this.clearStoredState();
77
+ return;
78
+ }
79
+ if (this.queue.length === 0 || !isOnline()) {
80
+ return;
81
+ }
82
+ const events = this.queue.splice(0, this.queue.length);
83
+ try {
84
+ await this.sendBatch(events);
85
+ }
86
+ catch (error) {
87
+ this.queue.unshift(...events);
88
+ this.trimQueue();
89
+ this.queueStorage.save(this.queue);
90
+ throw error;
91
+ }
92
+ this.queueStorage.save(this.queue);
93
+ }
94
+ close() {
95
+ window.removeEventListener("online", this.onlineHandler);
96
+ window.removeEventListener("pagehide", this.pagehideHandler);
97
+ window.removeEventListener("popstate", this.popstateHandler);
98
+ if (this.originalPushState) {
99
+ window.history.pushState = this.originalPushState;
100
+ }
101
+ if (this.originalReplaceState) {
102
+ window.history.replaceState = this.originalReplaceState;
103
+ }
104
+ this.installedSpaTracking = false;
105
+ this.originalPushState = null;
106
+ this.originalReplaceState = null;
107
+ }
108
+ wrapHistoryMethod(original) {
109
+ return ((...args) => {
110
+ const result = original.apply(window.history, args);
111
+ void this.trackPageView();
112
+ return result;
113
+ });
114
+ }
115
+ trackingDisabled() {
116
+ if (this.consent !== "granted") {
117
+ return true;
118
+ }
119
+ if (doNotTrackEnabled()) {
120
+ return true;
121
+ }
122
+ return false;
123
+ }
124
+ enqueue(event) {
125
+ this.queue.push(event);
126
+ this.trimQueue();
127
+ this.queueStorage.save(this.queue);
128
+ }
129
+ trimQueue() {
130
+ if (this.queue.length > this.maxQueueSize) {
131
+ this.queue = this.queue.slice(this.queue.length - this.maxQueueSize);
132
+ }
133
+ }
134
+ clearStoredState() {
135
+ this.queue = [];
136
+ this.queueStorage.clear();
137
+ if (typeof localStorage !== "undefined") {
138
+ localStorage.removeItem(anonymousIDStorageKey(this.config.siteUuid));
139
+ localStorage.removeItem(queueStorageKey(this.config.siteUuid));
140
+ }
141
+ if (typeof sessionStorage !== "undefined") {
142
+ sessionStorage.removeItem(sessionIDStorageKey(this.config.siteUuid));
143
+ }
144
+ }
145
+ buildEvent(eventTypeSlug, payload) {
146
+ const identity = this.identityFields();
147
+ const event = {
148
+ eventTypeSlug,
149
+ schemaVersion: defaultSchemaVersion,
150
+ timestamp: new Date().toISOString(),
151
+ ...identity,
152
+ context: browserContext(),
153
+ payload: {
154
+ siteUuid: this.config.siteUuid,
155
+ ...payload,
156
+ },
157
+ };
158
+ const mode = this.config.identityMode === "extended" ? "producer" : "browser-cookieless";
159
+ const prepared = prepareEvent(event, { mode });
160
+ validateBrowserEvent(prepared);
161
+ applyEnvironmentLabel(prepared, this.config.environment);
162
+ return prepared;
163
+ }
164
+ identityFields() {
165
+ if (this.config.identityMode !== "extended") {
166
+ return { anonymousId: "", sessionId: "" };
167
+ }
168
+ return {
169
+ anonymousId: storedUUID(anonymousIDStorageKey(this.config.siteUuid), localStorage),
170
+ sessionId: storedUUID(sessionIDStorageKey(this.config.siteUuid), sessionStorage),
171
+ };
172
+ }
173
+ async sendEvent(event) {
174
+ await withRetry(this.retry, async () => {
175
+ const response = await fetch(`${this.baseUrl}/api/v1/collect/events`, {
176
+ method: "POST",
177
+ headers: collectorHeaders(this.config.writeKey),
178
+ body: JSON.stringify(event),
179
+ credentials: "omit",
180
+ });
181
+ assertAccepted(response);
182
+ });
183
+ }
184
+ async sendBatch(events, keepalive = false) {
185
+ await withRetry(this.retry, async () => {
186
+ const response = await fetch(`${this.baseUrl}/api/v1/collect/events/batch`, {
187
+ method: "POST",
188
+ headers: collectorHeaders(this.config.writeKey),
189
+ body: JSON.stringify({ events }),
190
+ credentials: "omit",
191
+ keepalive,
192
+ });
193
+ assertAccepted(response);
194
+ });
195
+ }
196
+ flushWithKeepalive() {
197
+ if (this.trackingDisabled()) {
198
+ this.clearStoredState();
199
+ return;
200
+ }
201
+ if (this.queue.length === 0) {
202
+ return;
203
+ }
204
+ const events = this.queue.splice(0, this.queue.length);
205
+ void this.sendBatch(events, true).then(() => {
206
+ this.queueStorage.save(this.queue);
207
+ }, () => {
208
+ this.queue.unshift(...events);
209
+ this.trimQueue();
210
+ this.queueStorage.save(this.queue);
211
+ });
212
+ }
213
+ }
214
+ function anonymousIDStorageKey(siteUuid) {
215
+ return `custd:${siteUuid}:anonymous_id`;
216
+ }
217
+ function sessionIDStorageKey(siteUuid) {
218
+ return `custd:${siteUuid}:session_id`;
219
+ }
220
+ function queueStorageKey(siteUuid) {
221
+ return `custd:${siteUuid}:event_queue`;
222
+ }
223
+ export async function installBrowserTrackerFromScript(scriptElement) {
224
+ const script = scriptElement ?? currentScript();
225
+ const queuedGlobal = installQueuedGlobal();
226
+ try {
227
+ const siteUuid = script.dataset.siteUuid;
228
+ const writeKey = script.dataset.writeKey;
229
+ if (!siteUuid || !writeKey) {
230
+ throw new Error("custd: browser script requires data-site-uuid and data-write-key");
231
+ }
232
+ const baseUrl = script.dataset.baseUrl ?? new URL(script.src).origin;
233
+ assertSecureOrLocalHTTP(baseUrl, "baseUrl");
234
+ const siteConfig = await fetchSiteConfig(baseUrl, siteUuid);
235
+ const tracker = createBrowserTracker({
236
+ baseUrl,
237
+ siteUuid,
238
+ writeKey,
239
+ identityMode: siteConfig.identityMode,
240
+ allowedOrigins: siteConfig.allowedOrigins,
241
+ batchSize: Number(script.dataset.batchSize || defaultScriptBatchSize(siteConfig)),
242
+ consent: scriptConsent(script, siteConfig),
243
+ persistentQueue: script.dataset.persistentQueue === "true",
244
+ });
245
+ window.custd = {
246
+ track: (eventTypeSlug, payload) => tracker.track(eventTypeSlug, payload),
247
+ trackPageView: () => tracker.trackPageView(),
248
+ setConsent: (state) => tracker.setConsent(state),
249
+ };
250
+ await drainQueuedGlobal(tracker, queuedGlobal);
251
+ return tracker;
252
+ }
253
+ catch (error) {
254
+ rejectQueuedGlobal(queuedGlobal, error);
255
+ installRejectingGlobal(error);
256
+ throw error;
257
+ }
258
+ }
259
+ async function fetchSiteConfig(baseUrl, siteUuid) {
260
+ const response = await fetch(`${baseUrl.replace(/\/$/, "")}/api/v1/sites/${encodeURIComponent(siteUuid)}/config`, {
261
+ credentials: "omit",
262
+ });
263
+ if (!response.ok) {
264
+ throw new Error(`custd: site config request failed with status ${response.status}`);
265
+ }
266
+ return (await response.json());
267
+ }
268
+ function browserContext() {
269
+ return {
270
+ page: {
271
+ path: sanitizeBrowserPath(window.location.pathname),
272
+ title: document.title,
273
+ },
274
+ device: { type: deviceType() },
275
+ locale: navigator.language,
276
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
277
+ };
278
+ }
279
+ function poweredByAttribution() {
280
+ const query = new URL(window.location.href).searchParams;
281
+ const project = query.get("ref") ?? "";
282
+ if (query.get("source") !== "powered-by" || !poweredByProjectSlug.test(project)) {
283
+ return {};
284
+ }
285
+ return { utmSource: project, utmMedium: "powered-by" };
286
+ }
287
+ function sanitizeBrowserPath(pathname) {
288
+ const path = pathname.startsWith("/") ? pathname : `/${pathname}`;
289
+ const segments = path.split("/").map(sanitizePathSegment);
290
+ return segments.join("/") || "/";
291
+ }
292
+ function sanitizePathSegment(segment) {
293
+ if (segment === "") {
294
+ return "";
295
+ }
296
+ let decoded;
297
+ try {
298
+ decoded = decodeURIComponent(segment);
299
+ }
300
+ catch {
301
+ return redactedPathSegment;
302
+ }
303
+ if (!safePathSegment.test(decoded) ||
304
+ uuidPathSegment.test(decoded) ||
305
+ /^\d+$/u.test(decoded) ||
306
+ opaquePathSegment.test(decoded)) {
307
+ return redactedPathSegment;
308
+ }
309
+ return decoded;
310
+ }
311
+ function collectorHeaders(writeKey) {
312
+ return {
313
+ "Content-Type": "application/json",
314
+ Authorization: `Bearer ${writeKey}`,
315
+ };
316
+ }
317
+ function assertAccepted(response) {
318
+ if (!response.ok) {
319
+ if ([408, 429, 500, 502, 503, 504].includes(response.status)) {
320
+ throw new RetryableError(`custd: retryable collector status ${response.status}`);
321
+ }
322
+ throw new Error(`custd: collector request failed with status ${response.status}`);
323
+ }
324
+ }
325
+ function assertAllowedOrigin(config) {
326
+ const allowedOrigins = config.allowedOrigins ?? [];
327
+ if (allowedOrigins.length === 0) {
328
+ throw new Error("custd: site config must include allowed origins for this site");
329
+ }
330
+ if (!allowedOrigins.includes(window.location.origin)) {
331
+ throw new Error("custd: origin is not allowed for this site");
332
+ }
333
+ }
334
+ function installQueuedGlobal() {
335
+ const queued = { calls: [], promises: [] };
336
+ window.custd = {
337
+ track: (eventTypeSlug, payload) => enqueueGlobalCall(queued, { type: "track", eventTypeSlug, payload }),
338
+ trackPageView: () => enqueueGlobalCall(queued, { type: "trackPageView" }),
339
+ setConsent: (state) => {
340
+ enqueueGlobalStateCall(queued, { type: "setConsent", state });
341
+ },
342
+ };
343
+ return queued;
344
+ }
345
+ function enqueueGlobalCall(queued, call) {
346
+ if (queued.calls.length >= maxQueuedGlobalCalls) {
347
+ return Promise.reject(new Error("custd: queued global call limit exceeded"));
348
+ }
349
+ return new Promise((resolve, reject) => {
350
+ queued.calls.push(call);
351
+ queued.promises.push({ resolve, reject });
352
+ });
353
+ }
354
+ function enqueueGlobalStateCall(queued, call) {
355
+ if (queued.calls.length >= maxQueuedGlobalCalls) {
356
+ return;
357
+ }
358
+ queued.calls.push(call);
359
+ }
360
+ async function drainQueuedGlobal(tracker, queued) {
361
+ for (const call of queued.calls) {
362
+ const deferred = call.type === "setConsent" ? undefined : queued.promises.shift();
363
+ try {
364
+ if (call.type === "track") {
365
+ await tracker.track(call.eventTypeSlug, call.payload);
366
+ }
367
+ else if (call.type === "trackPageView") {
368
+ await tracker.trackPageView();
369
+ }
370
+ else {
371
+ tracker.setConsent(call.state);
372
+ }
373
+ deferred?.resolve();
374
+ }
375
+ catch (error) {
376
+ deferred?.reject(error);
377
+ }
378
+ }
379
+ }
380
+ function rejectQueuedGlobal(queued, error) {
381
+ for (const deferred of queued.promises.splice(0, queued.promises.length)) {
382
+ deferred.reject(error);
383
+ }
384
+ }
385
+ function installRejectingGlobal(error) {
386
+ window.custd = {
387
+ track: () => Promise.reject(error),
388
+ trackPageView: () => Promise.reject(error),
389
+ setConsent: () => {
390
+ throw error;
391
+ },
392
+ };
393
+ }
394
+ function storedUUID(key, storage) {
395
+ const existing = storage.getItem(key);
396
+ if (existing) {
397
+ return existing;
398
+ }
399
+ const value = randomUUID();
400
+ storage.setItem(key, value);
401
+ return value;
402
+ }
403
+ function browserQueueStorage(siteUuid, persistent) {
404
+ if (!persistent || typeof localStorage === "undefined") {
405
+ return new MemoryQueueStorage();
406
+ }
407
+ return new LocalStorageQueueStorage(`custd:${siteUuid}:event_queue`);
408
+ }
409
+ function currentScript() {
410
+ const script = document.currentScript;
411
+ if (!script) {
412
+ throw new Error("custd: browser script could not find document.currentScript");
413
+ }
414
+ return script;
415
+ }
416
+ function scriptConsent(script, siteConfig) {
417
+ if (script.dataset.consent === "granted") {
418
+ return "granted";
419
+ }
420
+ return siteConfig.identityMode === "extended" ? "required" : undefined;
421
+ }
422
+ function defaultScriptBatchSize(siteConfig) {
423
+ return siteConfig.identityMode === "extended" ? 25 : 1;
424
+ }
425
+ function doNotTrackEnabled() {
426
+ const value = navigator.doNotTrack;
427
+ return value === "1" || value === "yes";
428
+ }
429
+ function isOnline() {
430
+ return typeof navigator.onLine !== "boolean" || navigator.onLine;
431
+ }
432
+ function deviceType() {
433
+ return /Mobi|Android/i.test(navigator.userAgent) ? "mobile" : "desktop";
434
+ }
435
+ function assertSecureOrLocalHTTP(rawUrl, field) {
436
+ const parsed = new URL(rawUrl);
437
+ if (parsed.protocol === "https:") {
438
+ return;
439
+ }
440
+ if (parsed.protocol === "http:" && isLocalHostname(parsed.hostname)) {
441
+ return;
442
+ }
443
+ throw new Error(`custd: ${field} must use https unless it targets localhost`);
444
+ }
445
+ function isLocalHostname(hostname) {
446
+ return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "host.docker.internal");
447
+ }
448
+ function randomUUID() {
449
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
450
+ return crypto.randomUUID();
451
+ }
452
+ return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (Number(c) ^ ((Math.random() * 16) >> (Number(c) / 4))).toString(16));
453
+ }
@@ -0,0 +1 @@
1
+ export * from "./browser-tracker.js";
@@ -0,0 +1 @@
1
+ export * from "./browser-tracker.js";
@@ -0,0 +1,10 @@
1
+ /**
2
+ * readLifecycleFixture loads a shared lifecycle contract fixture under
3
+ * contract-fixtures/lifecycle/{namespace}/{name}. Tests resolve the same
4
+ * fixtures used by the Go SDK's matrix; the fixture paths are the canonical
5
+ * wire-format contracts.
6
+ *
7
+ * Throws when the fixture is missing so a miss fails loudly rather than
8
+ * silently producing an empty body.
9
+ */
10
+ export declare function readLifecycleFixture(namespace: string, name: string): unknown;
@@ -0,0 +1,57 @@
1
+ // Shared contract fixture loader for tests.
2
+ //
3
+ // The TypeScript SDK ships inside the custd-sdk monorepo. The shared lifecycle
4
+ // fixtures live at <monorepo>/contract-fixtures/lifecycle/{namespace}/{name},
5
+ // and the monorepo also resolves to a standalone release where the fixtures
6
+ // are vendored at <module>/contract-fixtures/lifecycle/{namespace}/{name}.
7
+ //
8
+ // Tests resolve fixtures via either path so the same fixtures work under both
9
+ // layouts. The standalone-release layout is the typical npm install; the
10
+ // monorepo layout is the typical local-development layout.
11
+ import { readFileSync } from "node:fs";
12
+ import { dirname, resolve } from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ // findFixtureRoot walks upward from the current module to find the monorepo
15
+ // root that contains the contract-fixtures directory. When the SDK is running
16
+ // inside the standalone release split, fixtures live at <module>/contract-fixtures.
17
+ function findFixtureRoot() {
18
+ // node:url import.meta.url is available in both ESM and Node test contexts.
19
+ const modulePath = fileURLToPath(import.meta.url);
20
+ let cursor = dirname(modulePath);
21
+ for (let depth = 0; depth < 8; depth++) {
22
+ const candidate = resolve(cursor, "contract-fixtures");
23
+ try {
24
+ // Cheap probe: if the file exists, we landed at the correct root.
25
+ readFileSync(resolve(candidate, "lifecycle", "matrix.json"));
26
+ return candidate;
27
+ }
28
+ catch {
29
+ const parent = dirname(cursor);
30
+ if (parent === cursor) {
31
+ break;
32
+ }
33
+ cursor = parent;
34
+ }
35
+ }
36
+ throw new Error("custd-sdk: contract-fixtures root not found");
37
+ }
38
+ const fixtureRoot = findFixtureRoot();
39
+ /**
40
+ * readLifecycleFixture loads a shared lifecycle contract fixture under
41
+ * contract-fixtures/lifecycle/{namespace}/{name}. Tests resolve the same
42
+ * fixtures used by the Go SDK's matrix; the fixture paths are the canonical
43
+ * wire-format contracts.
44
+ *
45
+ * Throws when the fixture is missing so a miss fails loudly rather than
46
+ * silently producing an empty body.
47
+ */
48
+ export function readLifecycleFixture(namespace, name) {
49
+ const relPath = `lifecycle/${namespace}/${name}`;
50
+ try {
51
+ const text = readFileSync(resolve(fixtureRoot, relPath), "utf8");
52
+ return JSON.parse(text);
53
+ }
54
+ catch (err) {
55
+ throw new Error(`custd-sdk: lifecycle fixture ${namespace}/${name} not found: ${err.message}`);
56
+ }
57
+ }