@haakco/custd-sdk 0.0.0-stage → 3.71.1

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 (196) hide show
  1. package/README.md +958 -2
  2. package/dist/admin-accounting-evidence.d.ts +48 -0
  3. package/dist/admin-accounting-evidence.js +24 -0
  4. package/dist/admin-app-releases.d.ts +116 -0
  5. package/dist/admin-app-releases.js +8 -0
  6. package/dist/admin-apps.d.ts +120 -0
  7. package/dist/admin-apps.js +47 -0
  8. package/dist/admin-auth-project-domain.d.ts +125 -0
  9. package/dist/admin-auth-project-domain.js +37 -0
  10. package/dist/admin-auth-projects.d.ts +989 -0
  11. package/dist/admin-auth-projects.js +527 -0
  12. package/dist/admin-campaign-email.d.ts +120 -0
  13. package/dist/admin-campaign-email.js +64 -0
  14. package/dist/admin-client-setup.d.ts +122 -0
  15. package/dist/admin-client-setup.js +408 -0
  16. package/dist/admin-data-labels.d.ts +124 -0
  17. package/dist/admin-data-labels.js +51 -0
  18. package/dist/admin-data-scopes.d.ts +93 -0
  19. package/dist/admin-data-scopes.js +154 -0
  20. package/dist/admin-email-relay.d.ts +66 -0
  21. package/dist/admin-email-relay.js +25 -0
  22. package/dist/admin-environment-policy.d.ts +32 -0
  23. package/dist/admin-environment-policy.js +26 -0
  24. package/dist/admin-error-issues.d.ts +91 -0
  25. package/dist/admin-error-issues.js +52 -0
  26. package/dist/admin-event-types.d.ts +57 -0
  27. package/dist/admin-event-types.js +28 -0
  28. package/dist/admin-impersonation.d.ts +48 -0
  29. package/dist/admin-impersonation.js +27 -0
  30. package/dist/admin-ingest-claims.d.ts +35 -0
  31. package/dist/admin-ingest-claims.js +26 -0
  32. package/dist/admin-managed-audit.d.ts +13 -0
  33. package/dist/admin-managed-audit.js +13 -0
  34. package/dist/admin-measurement-projects.d.ts +166 -0
  35. package/dist/admin-measurement-projects.js +120 -0
  36. package/dist/admin-notification-destinations.d.ts +31 -0
  37. package/dist/admin-notification-destinations.js +19 -0
  38. package/dist/admin-notification-webhooks.d.ts +64 -0
  39. package/dist/admin-notification-webhooks.js +42 -0
  40. package/dist/admin-oauth-client-admissions.d.ts +65 -0
  41. package/dist/admin-oauth-client-admissions.js +46 -0
  42. package/dist/admin-offboarding.d.ts +123 -0
  43. package/dist/admin-offboarding.js +129 -0
  44. package/dist/admin-predictions.d.ts +266 -0
  45. package/dist/admin-predictions.js +93 -0
  46. package/dist/admin-privacy-erasures.d.ts +74 -0
  47. package/dist/admin-privacy-erasures.js +73 -0
  48. package/dist/admin-retention.d.ts +99 -0
  49. package/dist/admin-retention.js +60 -0
  50. package/dist/admin-rls.d.ts +94 -0
  51. package/dist/admin-rls.js +33 -0
  52. package/dist/admin-sdk-usage.d.ts +41 -0
  53. package/dist/admin-sdk-usage.js +23 -0
  54. package/dist/admin-site-ai.d.ts +72 -0
  55. package/dist/admin-site-ai.js +1 -0
  56. package/dist/admin-site-analytics.d.ts +52 -0
  57. package/dist/admin-site-analytics.js +14 -0
  58. package/dist/admin-site-audit-pages.d.ts +76 -0
  59. package/dist/admin-site-audit-pages.js +27 -0
  60. package/dist/admin-site-campaign-links.d.ts +40 -0
  61. package/dist/admin-site-campaign-links.js +9 -0
  62. package/dist/admin-site-domains.d.ts +733 -0
  63. package/dist/admin-site-domains.js +768 -0
  64. package/dist/admin-site-export.d.ts +76 -0
  65. package/dist/admin-site-export.js +15 -0
  66. package/dist/admin-site-insights-tasks.d.ts +44 -0
  67. package/dist/admin-site-insights-tasks.js +28 -0
  68. package/dist/admin-site-insights.d.ts +527 -0
  69. package/dist/admin-site-insights.js +61 -0
  70. package/dist/admin-site-links.d.ts +87 -0
  71. package/dist/admin-site-links.js +16 -0
  72. package/dist/admin-site-monitors.d.ts +110 -0
  73. package/dist/admin-site-monitors.js +25 -0
  74. package/dist/admin-site-next-actions.d.ts +93 -0
  75. package/dist/admin-site-next-actions.js +36 -0
  76. package/dist/admin-site-page-queries.d.ts +63 -0
  77. package/dist/admin-site-page-queries.js +20 -0
  78. package/dist/admin-site-rankings.d.ts +98 -0
  79. package/dist/admin-site-rankings.js +46 -0
  80. package/dist/admin-site-regional-trends.d.ts +30 -0
  81. package/dist/admin-site-regional-trends.js +1 -0
  82. package/dist/admin-site-saved-reports.d.ts +45 -0
  83. package/dist/admin-site-saved-reports.js +13 -0
  84. package/dist/admin-site-search-pool.d.ts +77 -0
  85. package/dist/admin-site-search-pool.js +41 -0
  86. package/dist/admin-site-search-value.d.ts +97 -0
  87. package/dist/admin-site-search-value.js +29 -0
  88. package/dist/admin-site-status-page.d.ts +57 -0
  89. package/dist/admin-site-status-page.js +10 -0
  90. package/dist/admin-site-traffic.d.ts +145 -0
  91. package/dist/admin-site-traffic.js +32 -0
  92. package/dist/admin-site-web-data.d.ts +258 -0
  93. package/dist/admin-site-web-data.js +60 -0
  94. package/dist/admin-subject-exports.d.ts +79 -0
  95. package/dist/admin-subject-exports.js +44 -0
  96. package/dist/admin-support-access.d.ts +32 -0
  97. package/dist/admin-support-access.js +21 -0
  98. package/dist/admin-system.d.ts +283 -0
  99. package/dist/admin-system.js +65 -0
  100. package/dist/admin-tenant-storage.d.ts +35 -0
  101. package/dist/admin-tenant-storage.js +24 -0
  102. package/dist/admin-timeplans.d.ts +512 -0
  103. package/dist/admin-timeplans.js +200 -0
  104. package/dist/admin-uncertainty-models.d.ts +42 -0
  105. package/dist/admin-uncertainty-models.js +53 -0
  106. package/dist/admin-usage.d.ts +124 -0
  107. package/dist/admin-usage.js +169 -0
  108. package/dist/admin-users.d.ts +124 -0
  109. package/dist/admin-users.js +82 -0
  110. package/dist/admin-workflow-timings.d.ts +367 -0
  111. package/dist/admin-workflow-timings.js +117 -0
  112. package/dist/analytics-events.d.ts +167 -0
  113. package/dist/analytics-events.js +197 -0
  114. package/dist/analytics-reads.d.ts +81 -0
  115. package/dist/analytics-reads.js +5 -0
  116. package/dist/app-account.d.ts +84 -0
  117. package/dist/app-account.js +177 -0
  118. package/dist/app-alerts.d.ts +120 -0
  119. package/dist/app-alerts.js +44 -0
  120. package/dist/app-items.d.ts +786 -0
  121. package/dist/app-items.js +524 -0
  122. package/dist/app-live.d.ts +84 -0
  123. package/dist/app-live.js +228 -0
  124. package/dist/app-meetings.d.ts +95 -0
  125. package/dist/app-meetings.js +26 -0
  126. package/dist/app-models.d.ts +271 -0
  127. package/dist/app-models.js +83 -0
  128. package/dist/app-push.d.ts +64 -0
  129. package/dist/app-push.js +178 -0
  130. package/dist/backend-lifecycle.d.ts +85 -0
  131. package/dist/backend-lifecycle.js +212 -0
  132. package/dist/browser-manifest.json +7 -0
  133. package/dist/browser-script-BWnwDjAC.js +711 -0
  134. package/dist/browser-script.d.ts +1 -0
  135. package/dist/browser-script.js +5 -0
  136. package/dist/browser-sign-in.d.ts +153 -0
  137. package/dist/browser-sign-in.js +410 -0
  138. package/dist/browser-tracker.d.ts +142 -0
  139. package/dist/browser-tracker.js +775 -0
  140. package/dist/browser-web-vitals.d.ts +22 -0
  141. package/dist/browser-web-vitals.js +116 -0
  142. package/dist/browser.d.ts +10 -0
  143. package/dist/browser.js +10 -0
  144. package/dist/download-stream.d.ts +16 -0
  145. package/dist/download-stream.js +55 -0
  146. package/dist/error-capture.d.ts +62 -0
  147. package/dist/error-capture.js +168 -0
  148. package/dist/hosted-app.d.ts +115 -0
  149. package/dist/hosted-app.js +275 -0
  150. package/dist/index.d.ts +2324 -0
  151. package/dist/index.js +2226 -0
  152. package/dist/ingest-operations.d.ts +483 -0
  153. package/dist/ingest-operations.js +154 -0
  154. package/dist/measurement.d.ts +164 -0
  155. package/dist/measurement.js +104 -0
  156. package/dist/mobile-adapter.d.ts +25 -0
  157. package/dist/mobile-adapter.js +57 -0
  158. package/dist/mobile-context.d.ts +32 -0
  159. package/dist/mobile-context.js +156 -0
  160. package/dist/mobile-queue.d.ts +22 -0
  161. package/dist/mobile-queue.js +73 -0
  162. package/dist/oauth.d.ts +1 -0
  163. package/dist/oauth.js +8 -0
  164. package/dist/parsers.d.ts +149 -0
  165. package/dist/parsers.js +115 -0
  166. package/dist/public-reads.d.ts +79 -0
  167. package/dist/public-reads.js +57 -0
  168. package/dist/reporting-catalogue.d.ts +264 -0
  169. package/dist/reporting-catalogue.js +5 -0
  170. package/dist/reporting-state.d.ts +46 -0
  171. package/dist/reporting-state.js +76 -0
  172. package/dist/response-lists.d.ts +16 -0
  173. package/dist/response-lists.generated.d.ts +7 -0
  174. package/dist/response-lists.generated.js +1927 -0
  175. package/dist/response-lists.js +70 -0
  176. package/dist/response-validation.d.ts +30 -0
  177. package/dist/response-validation.js +94 -0
  178. package/dist/runtime-readiness.d.ts +30 -0
  179. package/dist/runtime-readiness.js +150 -0
  180. package/dist/schema-registry.d.ts +45 -0
  181. package/dist/schema-registry.js +9 -0
  182. package/dist/secure-url.d.ts +4 -0
  183. package/dist/secure-url.js +23 -0
  184. package/dist/site-ai-owner.d.ts +34 -0
  185. package/dist/site-ai-owner.js +99 -0
  186. package/dist/site-monitor-reports.d.ts +15 -0
  187. package/dist/site-monitor-reports.js +87 -0
  188. package/dist/testing/fake-custd.d.ts +150 -0
  189. package/dist/testing/fake-custd.js +842 -0
  190. package/dist/testing/fake-results.d.ts +30 -0
  191. package/dist/testing/fake-results.js +293 -0
  192. package/dist/testing.d.ts +2 -0
  193. package/dist/testing.js +3 -0
  194. package/dist/version.d.ts +10 -0
  195. package/dist/version.js +10 -0
  196. package/package.json +57 -4
package/README.md CHANGED
@@ -1,3 +1,959 @@
1
- # Temporary Holding Version
1
+ # custd SDK (TypeScript)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ingestion client with retry, batching, and optional offline queueing.
4
+
5
+ ## Compatibility
6
+
7
+ The supported 3.x SDK sends events to `POST /api/v1/events` and batches to
8
+ `POST /api/v1/events/batch`. Installation examples below were verified against
9
+ release **3.52.0** on 2026-11-17, including Node 26, pnpm 12 and Expo 58 consumers.
10
+
11
+ ## Install
12
+
13
+ Both packages are public on npmjs and released at every SDK tag:
14
+
15
+ ```bash
16
+ pnpm add @haakco/custd-sdk@^3.71.1
17
+ ```
18
+
19
+ A pnpm project with `minimumReleaseAge` set should list `@haakco/*` in
20
+ `minimumReleaseAgeExclude`, so a new SDK release installs on the day it ships.
21
+
22
+ ## Server-side producer usage
23
+
24
+ Producer OAuth credentials belong only in trusted backend processes. Browser
25
+ applications use the [Browser Tracker](#browser-tracker) or native error client;
26
+ Expo/React Native applications use their own authenticated application relay.
27
+ Keep the existing company and provision project-owned resources; an application
28
+ is not a new tenant. See the root [onboarding/setup guidance](../README.md#producer-setup-helper).
29
+
30
+ ```ts
31
+ import { createDogfoodEvent, CustdClient, LocalStorageQueueStorage } from "@haakco/custd-sdk";
32
+
33
+ const client = new CustdClient({
34
+ baseUrl: "http://localhost:8087",
35
+ oauth: {
36
+ clientId: "producer-client",
37
+ clientSecret: process.env.CUSTD_CLIENT_SECRET ?? "",
38
+ tokenUrl: "http://localhost:4444/oauth2/token",
39
+ audience: "custd",
40
+ scopes: ["events.write"],
41
+ },
42
+ retry: { maxAttempts: 3 },
43
+ batch: { maxBatchSize: 25, flushIntervalMs: 5000 },
44
+ queue: {
45
+ enabled: true,
46
+ storage: new LocalStorageQueueStorage("custd_queue"),
47
+ maxQueueSize: 1000,
48
+ },
49
+ // Batch request bodies are gzip-compressed by default once they reach
50
+ // `thresholdBytes`. Disable with `{ enabled: false }`. Compression is skipped
51
+ // automatically in runtimes without `CompressionStream`. (zstd is a planned
52
+ // follow-up.)
53
+ compression: { enabled: true, thresholdBytes: 1024 },
54
+ });
55
+
56
+ await client.track({
57
+ eventUuid: "...",
58
+ eventTypeSlug: "page-view",
59
+ schemaVersion: "1.0.0",
60
+ timestamp: new Date().toISOString(),
61
+ sessionId: "...",
62
+ anonymousId: "...",
63
+ companySlug: "acme",
64
+ context: {
65
+ page: { path: "/start" },
66
+ device: { type: "desktop" },
67
+ locale: "en-US",
68
+ timezone: "UTC",
69
+ ip: "127.0.0.1",
70
+ },
71
+ payload: { example: true },
72
+ });
73
+ ```
74
+
75
+ When Custd provisions a producer it returns a flat credential bundle. Pass it
76
+ straight to `fromProvisionedProducer` — no OAuth wiring required:
77
+
78
+ ```ts
79
+ const client = CustdClient.fromProvisionedProducer(credentials);
80
+ await client.track({
81
+ eventTypeSlug: "order.completed",
82
+ schemaVersion: "1.0.0",
83
+ companySlug: credentials.companySlug,
84
+ context: { device: { type: "server" } },
85
+ payload: { orderTotal: 42 }
86
+ });
87
+ ```
88
+
89
+ Use `redactedProvisionedProducer(credentials)` to show the bundle on a dashboard
90
+ without exposing the client secret.
91
+
92
+ The client also accepts `getToken: () => "<token>"` for existing static-token
93
+ or callback integrations. Producer clients should prefer the OAuth2
94
+ `client_credentials` config above so token refresh stays inside the SDK.
95
+
96
+ Trusted broker services can build an admin/provisioning client directly from
97
+ Custd provisioning environment variables:
98
+
99
+ ```ts
100
+ const broker = CustdClient.fromBrokerEnv(env);
101
+
102
+ await broker.admin.tenants.create({
103
+ slug: "agency-store-001",
104
+ companyName: "Agency Store 001",
105
+ });
106
+
107
+ const credentials = await broker.provisioning.producers.provision({
108
+ companySlug: "agency-store-001",
109
+ producerSlug: "woocommerce",
110
+ scopeTemplate: "managed-audit-reporting-read",
111
+ });
112
+ ```
113
+
114
+ `fromBrokerEnv` reads `CUSTD_PROVISIONING_CLIENT_ID`,
115
+ `CUSTD_PROVISIONING_CLIENT_SECRET`, `CUSTD_PROVISIONING_TOKEN_URL`,
116
+ `CUSTD_PROVISIONING_AUDIENCE`, and either `CUSTD_BASE_URL` or an existing
117
+ Custd endpoint such as `CUSTD_PROVISIONING_ENDPOINT`. It defaults the OAuth
118
+ request scopes to `admin producers.provision`; pass `{ scopes: [...] }` when a
119
+ broker should request a narrower token.
120
+
121
+ Dogfood producers can use `createDogfoodEvent`:
122
+
123
+ ```ts
124
+ const event = createDogfoodEvent({
125
+ eventTypeSlug: "dogfood.producer.metric",
126
+ schemaVersion: "1.0.0",
127
+ companySlug: "haakco",
128
+ sourceSystem: "vorrent",
129
+ sourceCompany: "haakco",
130
+ environment: "production",
131
+ correlationId: "run-123",
132
+ payload: { metric: "media_cache.queue_depth", value: 7 },
133
+ strictPayloadKeys: true,
134
+ });
135
+ ```
136
+
137
+ `strictPayloadKeys: true` throws if the dogfood sanitizer would drop payload
138
+ keys such as `token`, `password`, `signedUrl`, `environment`, or
139
+ `sourceSystem`. Leave it off only when backward compatibility with existing
140
+ payloads is more important than surfacing dropped data.
141
+
142
+ The SDK requires `companySlug` and rejects plaintext non-local Custd/token URLs.
143
+ Localhost HTTP is allowed for development.
144
+
145
+ ## Browser Tracker
146
+
147
+ Use the browser entrypoint for public website analytics. It sends to the
148
+ collector endpoints, not the producer OAuth endpoint:
149
+
150
+ ```ts
151
+ import { createBrowserTracker } from "@haakco/custd-sdk/browser";
152
+
153
+ const tracker = createBrowserTracker({
154
+ baseUrl: "https://custd.example.com",
155
+ siteUuid: "site-uuid",
156
+ writeKey: "site_pk_public_write_key",
157
+ allowedOrigins: ["https://www.example.com"],
158
+ batchSize: 25,
159
+ });
160
+
161
+ tracker.installSpaTracking();
162
+ ```
163
+
164
+ `installSpaTracking()` sends an initial page view by default, tracks
165
+ `pushState`, `replaceState`, and `popstate`, and is idempotent. It sends a page
166
+ view only when the route path changes, so a history update that rewrites the
167
+ query string alone does not count as a new page. Pass
168
+ `trackInitialPageView: false` when the application already sends the first page
169
+ view during hydration.
170
+
171
+ By default a page view carries the sanitized `location.pathname` and
172
+ `document.title`. Pass `pageContext` to send a route template instead of the
173
+ address bar path and to omit the title, for example when a path segment or the
174
+ title names a private tenant page:
175
+
176
+ ```ts
177
+ const tracker = createBrowserTracker({
178
+ baseUrl: "https://custd.example.com",
179
+ siteUuid: "site-uuid",
180
+ writeKey: "site_pk_public_write_key",
181
+ allowedOrigins: ["https://www.example.com"],
182
+ pageContext: () => ({ path: "/companies/:companySlug/board" }),
183
+ });
184
+ ```
185
+
186
+ The provider receives the default `{ path, title }` and a field it leaves out is
187
+ not sent. A `path` that is not a safe route path, such as a full URL or one
188
+ carrying a query or fragment, is replaced with the default sanitized path, and a
189
+ provider that throws sends no page context rather than falling back to page
190
+ content.
191
+
192
+ Every tracked event declares a schema version, `1.0.0` by default. Pass
193
+ `schemaVersion` when this Site's collector has a different version enabled: the
194
+ collector accepts an event only under a version it has enabled for that event
195
+ type, so the configured value and the collector's enabled schema version must
196
+ match. A value that is not a dotted numeric version such as `1.0.1` is refused
197
+ at construction instead of being sent.
198
+
199
+ Pass `labels` to stamp every tracked event, including the automatic page views,
200
+ with controlled deployment metadata such as the cluster and region this build
201
+ runs in:
202
+
203
+ ```ts
204
+ const tracker = createBrowserTracker({
205
+ baseUrl: "https://custd.example.com",
206
+ siteUuid: "site-uuid",
207
+ writeKey: "site_pk_public_write_key",
208
+ allowedOrigins: ["https://www.example.com"],
209
+ environment: "production",
210
+ labels: { cluster: "eu-central", region: "eu" },
211
+ });
212
+ ```
213
+
214
+ These are deployment labels, not visitor data: use build-time configuration
215
+ rather than anything derived from the person browsing. Every key and value must
216
+ already exist in the tenant's label catalogue, and the reserved `custd.`
217
+ namespace stays with the SDK, so `custd.environment` still comes only from
218
+ `environment` and a configured label that tries to set it is rejected. The
219
+ tracker copies the object at construction, so mutating it afterwards changes
220
+ nothing. Without `labels` the envelope carries no labels of its own.
221
+
222
+ Automatic tracking calls, namely the initial page view, the history hooks,
223
+ `popstate`, and background flushes, absorb their own failures so they never
224
+ surface as unhandled rejections in the host page. Pass `onFailure` to observe
225
+ them as sanitized descriptions:
226
+
227
+ ```ts
228
+ onFailure: (failure) => {
229
+ // { source: "page-view" | "flush", status?, rejectedEvents? }
230
+ report(failure);
231
+ },
232
+ ```
233
+
234
+ The collector answers a batch with one result per event. Events it rejects
235
+ permanently are dropped instead of retried and are reported through `onFailure`
236
+ as `rejectedEvents`; events that failed with a retryable status stay queued for
237
+ the next flush. A batch answer that does not match the collector contract is not
238
+ treated as delivered, so the queue keeps its events.
239
+
240
+ Script-tag installs read `data-site-uuid` and `data-write-key`, then load site
241
+ identity/origin config from `/api/v1/sites/{siteUuid}/config`. That platform
242
+ endpoint must exist before script-tag installs are usable in production. Until
243
+ then, use `createBrowserTracker()` with explicit `allowedOrigins`. When the
244
+ endpoint is available, the site config response must include the current origin
245
+ in `allowedOrigins`; the browser tracker refuses to run without an
246
+ allowed-origin match. Script attributes cannot expand the server-provided origin
247
+ list.
248
+
249
+ ```html
250
+ <script
251
+ type="module"
252
+ src="https://custd.com/custd-sdk/browser-script.js"
253
+ data-site-uuid="site-uuid"
254
+ data-write-key="site_pk_public_write_key"
255
+ ></script>
256
+ ```
257
+
258
+ Load the stable entry, not a content-hashed artifact name.
259
+ `browser-script.js` aliases whatever build the deployed manifest
260
+ (`/custd-sdk/browser-manifest.json`) names and is served with a one-hour bounded
261
+ cache, so a host picks up new SDK builds without editing its markup, and it can
262
+ never be left pointing at a retired artifact. A pinned
263
+ `browser-script-<content-hash>.js` URL changes on every release: the markup has
264
+ to be edited by hand to upgrade, and the old name stops resolving once the
265
+ artifact is gone.
266
+
267
+ ```ts
268
+ await window.custd.track("purchase", { amount: 12.99 });
269
+ await window.custd.trackPageView();
270
+ ```
271
+
272
+ The default mode is cookieless: `anonymousId` and `sessionId` are sent as empty
273
+ strings. For consented identity, opt in explicitly:
274
+
275
+ ```ts
276
+ const tracker = createBrowserTracker({
277
+ baseUrl: "https://custd.example.com",
278
+ siteUuid: "site-uuid",
279
+ writeKey: "site_pk_public_write_key",
280
+ allowedOrigins: ["https://www.example.com"],
281
+ identityMode: "extended",
282
+ consent: "required",
283
+ });
284
+
285
+ tracker.setConsent("granted");
286
+ ```
287
+
288
+ Extended mode starts with consent required for script-tag installs unless
289
+ `data-consent="granted"` is present. It stores an anonymous ID in
290
+ `localStorage`, a session ID in `sessionStorage`, and all modes honor browser Do
291
+ Not Track. Page-exit flushes use `fetch` with `keepalive: true` so the tracker
292
+ can keep `credentials: "omit"` on collector requests; normal flushes also use
293
+ `fetch` with bearer write-key auth and omitted credentials. Queued events are
294
+ kept in memory by default so page URLs and payloads are not persisted; pass
295
+ `persistentQueue: true` to opt into `localStorage` queueing, and `maxQueueSize`
296
+ to lower the default limit of 1000 queued events. Script-tag installs can opt
297
+ into persistent queueing with `data-persistent-queue="true"`. Calling
298
+ `setConsent("denied")` clears extended-mode identifiers and queued events.
299
+
300
+ A page view also carries its sanitized path in the payload, so reporting can
301
+ group page views by page. When the first page view of a document arrives from
302
+ an AI assistant (the hostnames in `aiAssistantReferrers`, such as `chatgpt.com`,
303
+ `perplexity.ai`, `claude.ai`, `gemini.google.com` and `copilot.microsoft.com`),
304
+ it carries `referrerClass: "ai-assistant"` and the assistant name as
305
+ `aiAssistant`. The referrer URL itself is never sent.
306
+
307
+ Pass `webVitals: true` (script tag: `data-web-vitals="true"`) to capture
308
+ real-user Core Web Vitals with the browser's `PerformanceObserver`. When the page
309
+ is first hidden, the tracker sends one `web-vitals` event for the landing path
310
+ with `lcp`, `inp`, `fcp` and `ttfb` in milliseconds and `cls` as a score. A
311
+ metric the browser does not report, such as INP on a visit with no interaction,
312
+ is omitted rather than sent as zero. Single-page route changes do not send
313
+ further vitals events, because LCP, FCP and TTFB describe the document load.
314
+
315
+ The browser-side origin check is a guardrail, not the security boundary.
316
+ Collectors must enforce `allowedOrigins`, write-key validity, and rate limits
317
+ server-side.
318
+
319
+ ## Hosted apps
320
+
321
+ An app Custd hosts starts tracking, error capture and sign-in with one call and
322
+ no copied configuration. `startHostedApp` reads `/.well-known/custd.json` from
323
+ the page's own origin and starts each capability the file enables:
324
+
325
+ ```ts
326
+ import { startHostedApp } from "@haakco/custd-sdk/browser";
327
+
328
+ type AppEvents = {
329
+ "item-created": { kind: string };
330
+ "measurement-added": { value: number };
331
+ };
332
+
333
+ const started = await startHostedApp<AppEvents>({ release: import.meta.env.VITE_COMMIT });
334
+ if (started.status === "ready") {
335
+ const { app } = started;
336
+ await app.signIn?.restore(); // only when sign_in is enabled
337
+ await app.trackAppEvent("item-created", { kind: "counter" }); // "tracked" | "tracking_off" | "failed"
338
+ // app.tracker, app.errorCapture, app.problems, app.stop()
339
+ } else {
340
+ console.warn(started.error.code); // HOSTED_APP_ERROR_CODES; the app keeps working without Custd
341
+ }
342
+ ```
343
+
344
+ - `tracking` starts the browser tracker with SPA page views for the app's Site.
345
+ Consent follows the Site's identity mode: a cookieless Site tracks at once, an
346
+ extended Site waits for `app.tracker.setConsent("granted")`. Pass `consent` to
347
+ override that default.
348
+ - `error_capture` installs browser error capture with the app's key.
349
+ - `sign_in` creates a `BrowserSignIn` for the environment's directory using the
350
+ discovery `redirectUri`.
351
+
352
+ `startHostedApp` never rejects. A missing or malformed discovery file returns
353
+ `{ status: "error", error }`; an enabled capability that cannot start is listed
354
+ in `app.problems` while the others keep running. App events must be registered
355
+ event types with flat scalar properties; `trackAppEvent` never rejects either.
356
+
357
+ ### App items
358
+
359
+ With `app_data` enabled, `app.appItems` is an `AppItemsClient` for the app's
360
+ items. Creating one needs only the Site key; every other call takes the item's
361
+ owner link token (reads and changes) or share link token (reads only). Tokens
362
+ travel only in the `Authorization` header and are never logged.
363
+
364
+ ```ts
365
+ import { appItemOwnerUrl, appItemShareUrl, parseAppItemLink } from "@haakco/custd-sdk/browser";
366
+
367
+ const items = app.appItems!; // or AppItemsClient.fromDiscovery(discovery)
368
+ const created = await items.createItem({
369
+ kind: "measurement_project",
370
+ measurementProject: { kind: "deadline_forecast", name: "Launch", series: [series], target },
371
+ });
372
+ const ownerUrl = appItemOwnerUrl({ host: app.discovery.host, kindPath: "c", token: created.ownerToken });
373
+ const shareUrl = appItemShareUrl({ host: app.discovery.host, kindPath: "c", token: created.shareToken });
374
+
375
+ await items.addMeasurements(created.ownerToken, { rows: [{ observedAt: new Date().toISOString(), value: 12 }] });
376
+ await items.runForecast(created.ownerToken);
377
+
378
+ const pasted = parseAppItemLink(input); // owner URL, share URL or bare token; null otherwise
379
+ const watch = items.watchItem(created.shareToken); // { getState, subscribe, refresh }
380
+ const stop = watch.subscribe(() => render(watch.getState()));
381
+ ```
382
+
383
+ Reads (`readItem`, `latestForecast`, `forecastRun`, `forecastStory`) take
384
+ `{ item, etag }` and return `{ status: "modified", data, etag }` or
385
+ `{ status: "not_modified", etag }`. `item` reads an entry of a dashboard through
386
+ the dashboard's own link. Failures throw `AppItemError` with the server's
387
+ `code` (`APP_ITEM_ERROR_CODES`); `terminal` is true when retrying cannot help.
388
+
389
+ `watchItem`, `watchLatestForecast` and `watchForecastStory` poll with
390
+ `If-None-Match` every 5 s (`intervalMs`), pause while the tab is hidden, poll at
391
+ once when it is shown or the browser comes back online, and back off up to 60 s
392
+ while requests fail. Watchers of the same read and link share one poller. State
393
+ is `loading`, `fresh`, `stale` (earlier data, the last poll failed), `offline`
394
+ or `error` (`retrying: false` once the link or key is refused, until
395
+ `refresh()`); `lastUpdatedAt` is when the server last confirmed the data,
396
+ including an unchanged answer. A write through the client polls that link's
397
+ watchers at once. The latest forecast is `empty` until a first run exists.
398
+ Watchers share a poller on the same client. A Site key refused for the page's
399
+ origin gets no CORS header, so the browser reports it as `network`/`offline`.
400
+
401
+ Watched reads also listen on one realtime WebSocket per client
402
+ (`/api/v1/realtime`): a pushed `item.changed` polls that read at once, and while
403
+ push carries a read its timer stays quiet. The socket reconnects with backoff
404
+ and resubscribes; while it is down or refused, reads poll as above. It uses the
405
+ global `WebSocket` unless you pass your own `fetch`; then pass `webSocket` too,
406
+ or `null` for polling only.
407
+
408
+ A signed-in user's access token travels in `X-Custd-User-Token` beside the
409
+ link: `startHostedApp` wires it from `app.signIn`, or pass `userToken` to the
410
+ client. `listMyItems()` reads "my items", `claim(ownerToken)` takes ownership of
411
+ an unowned item, and `{ item: itemUuid }` in place of a token reaches an item
412
+ the user owns without a link. Reads carry `item.ownership` (`unowned`, `yours`,
413
+ `other`). `error.signInNeeded` means sign in again; `app_user_check_unavailable`
414
+ is retried and keeps the session.
415
+
416
+ Model items add `addModelVersion`, `copyModel`, `runModel`, `latestModelRun`,
417
+ `watchLatestModelRun` and `calculateModel(token, { versionNumber, inputs,
418
+ outputs })`, which any link may call and which stores nothing.
419
+
420
+ Meeting items are created with `{ kind: "meeting", meeting: { name, blocks:
421
+ [{ title, predictedMs }] } }`. The owner calls `startMeeting`,
422
+ `advanceMeeting(token, { blockUuid })` and `endMeeting`; each returns the item
423
+ read, whose `meeting` holds `status`, `currentBlockUuid`, every block's
424
+ `predictedMs`, `allocatedMs` (rebalanced after an overrun) and `actualMs`, and
425
+ the `summary`. `blockUuid` names the block being finished, so a retried
426
+ advance is a no-op; a stale one fails with 409
427
+ `APP_MEETING_ERROR_CODES.stepRefused` and the client's watchers poll at once.
428
+
429
+ Alerts manage the item with the owner link or the owning user:
430
+ `alertSettings`, `addAlertRule(token, { type, threshold?, staleDays? })`,
431
+ `removeAlertRule`, `addAlertWebhook(token, { endpoint })` (its
432
+ `signingSecret` is shown once), `addAlertSlack(token, { webhookUrl })` (a Slack
433
+ incoming webhook; the URL is sealed and only a hint comes back, `kind:
434
+ "slack"`), `removeAlertWebhook` (either kind), `alertDeliveries`, and
435
+ for a signed-in user `subscribeAlertEmail` and `unsubscribeAlertEmail`.
436
+ `error.verifiedEmailNeeded` means the user has no verified address
437
+ (`app_alert_no_verified_email`); `app_alert_email_check_unavailable` is
438
+ retryable. The codes are in `APP_ALERT_ERROR_CODES`.
439
+
440
+ ### Testing apps without Custd
441
+
442
+ `@haakco/custd-sdk/testing` is an in-memory Custd for an app's tests. It serves
443
+ the discovery file, the app item, link, measurement, estimate, forecast,
444
+ model, alert and meeting routes, and a PKCE sign-in, with deterministic,
445
+ deliberately simple results (a straight-line forecast, model midpoints). Its
446
+ answers are built from this SDK's DTOs, so a contract change fails your
447
+ typecheck. `fake.requests` records every request for assertions. Every
448
+ capability starts: tracking and error capture are recorders that touch no page
449
+ globals and send nothing, so `fake.trackedEvents` and `fake.capturedErrors` hold
450
+ what the app tracked and captured.
451
+
452
+ ```ts
453
+ import { startHostedApp } from "@haakco/custd-sdk/browser";
454
+ import { FakeCustd, signInWithFake } from "@haakco/custd-sdk/testing";
455
+
456
+ const fake = new FakeCustd({ now: () => Date.parse("2026-01-01T00:00:00Z") });
457
+ const start = await startHostedApp(fake.hostedAppOptions());
458
+ if (start.status === "ready" && start.app.signIn) await signInWithFake(fake, start.app.signIn, "alice");
459
+ const items = fake.appItemsClient({ userToken: "alice" });
460
+ ```
461
+
462
+ In a browser test, route the page's requests to `fake.handle({ method, url,
463
+ headers, body })` and serve its `{ status, headers, body }`; the API lives under
464
+ `/__custd` and sign-in under `/__auth` on the fake's `origin`.
465
+
466
+ ## Browser app user sign-in
467
+
468
+ `BrowserSignIn` signs a hosted app's users in through the environment's Custd
469
+ directory with OAuth 2.0 authorization code and PKCE (S256). The app is a
470
+ public client: no client secret is involved. Pending sign-in state and the
471
+ token set live in `sessionStorage`; tokens never appear in errors.
472
+
473
+ ```ts
474
+ import { BrowserSignIn, signInConfigFromDiscovery } from "@haakco/custd-sdk";
475
+
476
+ const discovery = await (await fetch("/.well-known/custd.json")).json();
477
+ const signIn = new BrowserSignIn(
478
+ signInConfigFromDiscovery(discovery, { redirectUri: `${location.origin}/callback` }),
479
+ );
480
+
481
+ await signIn.restore(); // completes a /callback redirect or refreshes an expired session
482
+ await signIn.signIn({ returnTo: "/items" }); // sends the browser to the authorize URL
483
+ const session = signIn.currentSession(); // { accessToken, tokenType, expiresAtMs, refreshToken?, idToken?, scopes }
484
+ signIn.signOut({ postLogoutRedirectUri: location.origin }); // clears state, then visits end-session
485
+ ```
486
+
487
+ The discovery `signIn` block holds `issuer`, `authorizationEndpoint`,
488
+ `tokenEndpoint`, `endSessionEndpoint` (optional) and `clientId`. Scopes
489
+ default to `openid profile offline_access`. `startSignIn`, `completeSignIn`
490
+ and `refreshSession` are the lower-level steps when the app owns navigation.
491
+ A redirect whose `state` does not match is refused, and each pending sign-in
492
+ is single-use. Failures throw `SignInError` with a `code` from
493
+ `SIGN_IN_ERROR_CODES`.
494
+
495
+ ## Browser Site Admin Helpers
496
+
497
+ Server-side admin code can use `client.admin.sites` to create, list, get,
498
+ delete, and rotate browser tracker Sites. `create` returns the public write key
499
+ once. `list` and `get` return Site metadata without the write key.
500
+ `rotateWriteKey` returns the replacement write key once; update tracker config
501
+ and stop using the old key after rotation.
502
+
503
+ ## Site Insights (site domains)
504
+
505
+ Server-side code can use `client.admin.siteDomains` to claim a host for a Site,
506
+ prove control (`verify`, or `attest` from a site-bound broker credential), queue
507
+ an audit, read findings and outages, choose the check mode, set the alert
508
+ address and connect Google or Bing search numbers. The routes are under
509
+ `/api/v1/site-domains`; a system administrator names the tenant with
510
+ `{ companySlug }` in the last argument.
511
+
512
+ ```ts
513
+ import { SITE_DOMAIN_NOT_VERIFIED_CODE, SiteRule } from "@haakco/custd-sdk";
514
+
515
+ const domain = await client.admin.siteDomains.create({ siteUuid, host: "example.com" });
516
+ // Or omit siteUuid: Custd places the host (SITE_CHOICE_REQUIRED_CODE when it cannot tell).
517
+ // Publish domain.ownership.instructions (DNS TXT or well-known file), then:
518
+ await client.admin.siteDomains.verify(domain.domainUuid);
519
+ await client.admin.siteDomains.requestAudit(domain.domainUuid);
520
+
521
+ const { findings } = await client.admin.siteDomains.listFindings(domain.domainUuid, "open");
522
+ const missingTitles = findings.filter((finding) => finding.rule === SiteRule.TitleMissing);
523
+ ```
524
+
525
+ `SiteRule` holds the stable rule IDs a finding carries in `rule`; key any
526
+ client-side fix on them. A refused audit of an unverified domain is a
527
+ `CustdRequestError` whose `code` is `SITE_DOMAIN_NOT_VERIFIED_CODE`.
528
+
529
+ Each finding carries a `remedy` (`kind`, `element`, and ready-to-copy
530
+ `generated` code for some rules) and `recheckable` when a one-page recheck can
531
+ confirm the fix. The page tools are `getPageFacts`,
532
+ `requestPageRecheck` / `getPageRecheck` / `listPageRechecks` (up to
533
+ `SITE_PAGE_RECHECK_READ_LIMIT` at once; refusals: `SITE_PAGE_NOT_ON_DOMAIN_CODE`,
534
+ `SITE_PAGE_RECHECK_LIMIT_CODE`), `checkPage` for draft HTML and `testRobots`.
535
+ Search adds `listSearchRows` (its `unavailable` list names providers that cannot
536
+ report a dimension) and Search Console URL inspection
537
+ (`requestSearchInspection`, `listSearchInspections`). `getProjectContext` /
538
+ `setProjectContext` keep a Site's brands, competitors and markets. The client
539
+ report reads are `getReport`, `getUptimeHistory`, `getLighthouseHistory` and
540
+ `listReportShares` / `createReportShare` / `revokeReportShare`. IndexNow is
541
+ `getIndexNow`, `enableIndexNow`, `verifyIndexNowKey`, `submitIndexNow` and
542
+ `disableIndexNow`, with `SITE_INDEXNOW_*_CODE` refusals. A measurement
543
+ Custd did not take is absent, never `0`.
544
+
545
+ More reads and controls on the same client:
546
+
547
+ - Audit pages: `listAuditPages(domainUuid, offset?, limit?)` and `getAuditDelta`
548
+ (new, reopened and fixed findings).
549
+ - Lighthouse pages: `getLighthousePages` / `setLighthousePages(domainUuid, urls)`
550
+ (at most five extra pages; `[]` clears them). `getLighthouseHistory(domainUuid, days, { url })`
551
+ reads one extra page.
552
+ - Reports: `getReport(domainUuid, { template, days })` (`SiteReportTemplate.Executive`
553
+ or `Full`), and saved reports with `listSavedReports`, `saveReport`, `getSavedReport`,
554
+ `replaceSavedReport`, `deleteSavedReport`. `createReportShare(domainUuid, { reportUuid })`
555
+ shares a saved report.
556
+ - Public web data per Site (`siteUuid` optional for a site-bound credential):
557
+ `getWebDomains`, `listWebPages(domain, { after })`, `getTopicTrends`, `getContentGap`,
558
+ and keyword lists with `listKeywordLists`, `saveKeywordList`, `deleteKeywordList`,
559
+ `getKeywordClusters`.
560
+ - Referring domains: `getReferringDomains(domain, siteUuid?)` lists the domains linking to one
561
+ of the Site's web domains per source (`SiteLinkSource` bing, commoncrawl, crawl), its Common
562
+ Crawl authority and lost links. A count a source did not report is absent, never `0`.
563
+ - Shared search pool (tenant-wide; a site-bound credential is refused with
564
+ `SITE_SEARCH_POOL_SITE_BOUND_CODE`): `getSearchPool`, `setSearchPool(joined, termsVersion?)` and
565
+ `listSearchPoolQueries(search?, limit?)` (refused with `SITE_SEARCH_POOL_NOT_JOINED_CODE`
566
+ before joining). `getRankings` then carries `pool` and each keyword's pooled `pool` band.
567
+ Joining is audited consent: pass the `termsVersion` the caller accepted (the setting's
568
+ `termsVersion`; `SEARCH_POOL_TERMS_VERSION` names the one current at this release). Joining
569
+ without it is refused locally before any request; leaving sends only `{ joined: false }`.
570
+ - Page search queries: `getPageSearchQueries(domainUuid, url)` returns one page's queries, title
571
+ options and pages to link from. `checkPage` takes `scope` (`SitePageCheckScope`); a content
572
+ check returns `checkedRules`. `getPageFacts` answers 404 `SITE_PAGE_NOT_READ_CODE` for a page
573
+ nothing has read yet. Keyword clusters carry Bing `demand`, and keyword lists `related` keywords.
574
+ - GA4: `getAnalytics`, `connectAnalytics(domainUuid, { propertyId })` and `disconnectAnalytics`.
575
+ `retrySearchImport(domainUuid, provider)` retries a failing search import.
576
+ - Export: `getExport(domainUuid)` and `listExportSearchMetrics(domainUuid, { offset, limit })`.
577
+ - Operators: `client.admin.siteInsights.listTasks()` reads the Site Insights tasks' state.
578
+ - Draft tools: `checkPage` takes optional `previousUrl` and `phrase` and returns `slug`,
579
+ `redirect` (format `redirect`) and `phrase`; page facts carry `shareImage` and `faqSchema`.
580
+ `compareWording(domainUuid, { first, second })` measures shared wording as the
581
+ `content.near-duplicate` rule does; `sharedPercent` is absent when the texts were not compared.
582
+ `comparePageWording(domainUuid, { firstUrl, secondUrl })` compares two stored checks from
583
+ one verified domain and returns each page's evidence state. Neither URL is fetched.
584
+ - Campaign links: `listCampaignLinks(domainUuid, includeArchived?)`, `createCampaignLink` and
585
+ `archiveCampaignLink` keep a domain's saved UTM links (409 `SITE_CAMPAIGN_LINK_TAKEN_CODE` or
586
+ `SITE_CAMPAIGN_LINK_LIMIT_CODE`).
587
+ - Next actions: `getNextActions(domainUuid)` returns the status, one plain `headline`, what is not
588
+ checked yet and the three most important actions in Custd's fixed order (`SiteNextActionKind`;
589
+ show an unknown kind by its `title` and `why`). `getPortfolioSummary()` gives every domain's
590
+ status, open findings and `firstAction`, worst first; a report's `nextActions` are the same three.
591
+ The `site-insights-read` scope template provisions a credential that reads only these two calls.
592
+ - Access logs: `getTraffic(domainUuid, from?, to?)`, `getAIVisibility`, and
593
+ `replayAccessLogHour(hourStart)` for system administrators.
594
+ - Rank tracking: `getRankings(domainUuid, days?)`, `trackKeyword`,
595
+ `updateTrackedKeyword` (always sends `paused`; an omitted `notifyPosition` keeps the
596
+ stored one), `untrackKeyword`. A day that did not rank has no `position`.
597
+ - Search value: `getFindingSearchImpact(domainUuid, findingUuid, days?)` compares a fixed
598
+ finding's page in search before and after the fix, and `getSearchValue(domainUuid, goals, days?)`
599
+ credits up to five goal event types to search landing pages. Unmeasured numbers are absent.
600
+ - Approval (system administrators): `approve(domainUuid)` verifies a domain (`verifiedBy: "operator"`),
601
+ `withdrawApproval(domainUuid)` removes it.
602
+ - Uptime: `requestUptimeCheck(domainUuid)` queues a public check; `acknowledgeIncident(domainUuid, incidentUuid)`
603
+ marks an open incident as seen (`acknowledgedAt`).
604
+ - Finding dismissals: `listFindingDismissals`, `dismissFinding(domainUuid, { findingUuid, scope: "rule" | "url", reason })`,
605
+ `restoreFinding(domainUuid, dismissalUuid)`.
606
+ - Heartbeats for scheduled jobs: `listHeartbeats`, `createHeartbeat(domainUuid, { name, schedule: { cron, timezone, graceMinutes } })`,
607
+ `rotateHeartbeat`, `deleteHeartbeat`. Create and rotate return the write token once.
608
+ - Maintenance windows: `listMaintenance`, `scheduleMaintenance(domainUuid, { windowUuid, startsAt, endsAt })` (reuse
609
+ `windowUuid` on retry), `cancelMaintenance(domainUuid, windowUuid)`.
610
+ - Private uptime: `getPrivateUptime`, `createPrivateUptime(domainUuid, networkLabel)`, `requestPrivateUptime`,
611
+ `rotatePrivateUptime`, `deletePrivateUptime`. Create and rotate return the probe's write token once.
612
+ - Browser collector: `setBrowserCollector(domainUuid, { mode: "enabled", environment })` returns the browser key
613
+ (repeating an identical enable returns the same key); `{ mode: "disabled" }` turns it off.
614
+ - Empty lists decode as `[]`.
615
+ - Older servers (3.46.0) send no report `template` or Lighthouse `url` / `pages`; those fields
616
+ are then absent (no pages).
617
+
618
+ Each refusal code is a named constant, such as `SAVED_SITE_REPORT_NAME_TAKEN_CODE`,
619
+ `SITE_KEYWORD_LIST_LIMIT_CODE`, `ACCESS_LOG_HOUR_INVALID_CODE` or
620
+ `SITE_TRACKED_KEYWORD_DUPLICATE_CODE`.
621
+
622
+ ## Schema Admin Helpers
623
+
624
+ Server-side setup code can use `client.admin.schemas`:
625
+
626
+ Supported feature parity and intentionally missing helpers are documented in the SDK
627
+ root README.
628
+
629
+ ```ts
630
+ const schemaJson = JSON.stringify({ type: "object" });
631
+ const candidate = { tenantSlug: "acme", eventTypeSlug: "courib.delivery.created", dialect: "jsonschema" as const, schemaJson };
632
+
633
+ await client.admin.schemas.validate(candidate);
634
+ await client.admin.schemas.dryRun("acme", "courib.delivery.created", { ...candidate, samples: [{}] });
635
+ await client.admin.schemas.enableVersion("acme", "courib.delivery.created", {
636
+ tenantSlug: "acme",
637
+ eventTypeSlug: "courib.delivery.created",
638
+ version: "1.1.0",
639
+ });
640
+ ```
641
+
642
+ ## React Native
643
+
644
+ Mobile applications must not contain Custd producer credentials, provisioned
645
+ producer bundles, or tenant-wide `reporting:read` tokens. Send events to an
646
+ application-authenticated relay instead. The relay owns its Custd client and
647
+ producer credentials; the app sends only allowlisted, pseudonymous event data.
648
+ Likewise, have the relay render or authorize reporting results rather than
649
+ shipping a tenant-wide reporting token to the app.
650
+
651
+ The SDK provides dependency-free async queue and lifecycle primitives for Expo
652
+ or React Native. Pass your installed AsyncStorage-, AppState-, and
653
+ NetInfo-shaped implementations in; the SDK does not import or require those
654
+ packages. The queue keeps event IDs and ordering across storage restarts,
655
+ evicts oldest events at its configured bound, and retains unacknowledged events
656
+ after a partial batch response.
657
+
658
+ Use `createMobileEvent()` for app-originated events. It accepts only iOS or
659
+ Android platform context, a semantic app version, BCP 47 locale, IANA timezone,
660
+ network state, and exactly one explicit anonymous or authenticated subject.
661
+ The helper rejects unknown context fields and credential-shaped payload fields
662
+ such as producer secrets, client secrets, or reporting tokens. Mobile apps send
663
+ these allowlisted event envelopes to an application-authenticated relay; they
664
+ must not contain Custd producer credentials or reporting-read credentials.
665
+
666
+ ```ts
667
+ import { AppState } from "react-native";
668
+ import NetInfo from "@react-native-community/netinfo";
669
+ import AsyncStorage from "@react-native-async-storage/async-storage";
670
+ import {
671
+ AsyncEventQueue,
672
+ createMobileAsyncQueueStorage,
673
+ createMobileFlushTriggers,
674
+ } from "@haakco/custd-sdk";
675
+
676
+ const queue = new AsyncEventQueue(
677
+ createMobileAsyncQueueStorage(AsyncStorage, "custd.mobile.events"),
678
+ 1_000,
679
+ );
680
+ await queue.load();
681
+
682
+ const removeLifecycleTriggers = createMobileFlushTriggers({
683
+ appState: AppState,
684
+ network: NetInfo,
685
+ })(async () => {
686
+ // Send a bounded `await queue.peek(limit)` batch to the authenticated
687
+ // application relay. Acknowledge only event UUIDs accepted by that relay.
688
+ const events = await queue.peek(50);
689
+ const acceptedIDs = await sendEventsToApplicationRelay(events);
690
+ await queue.acknowledge(acceptedIDs);
691
+ });
692
+ ```
693
+
694
+ Call `removeLifecycleTriggers()` during application shutdown. A manual flush
695
+ uses the same bounded relay path; do not call a Custd producer endpoint from
696
+ the app or persist credentials alongside queued events.
697
+
698
+ ```ts
699
+ const events = await queue.peek(50);
700
+ await queue.acknowledge(await sendEventsToApplicationRelay(events));
701
+ ```
702
+
703
+ ## Dev smoke test (Hydra)
704
+
705
+ Requires dev stack running with Hydra using JWT access tokens and ingest-api configured with `AUTH_JWKS_URL`.
706
+
707
+ ```bash
708
+ export AUTH_JWKS_URL="http://localhost:4444/.well-known/jwks.json"
709
+ cd sdk-js
710
+ pnpm run smoke:dev
711
+ ```
712
+
713
+ The smoke test uses `scripts/dev-hydra-token.sh` and `scripts/dev-seed-core.sh` to create a dev OAuth client and seed core tables (company, device type, event type, schema).
714
+
715
+ To run all SDK checks, use `mise exec -- just check` from the repository root.
716
+
717
+ ## Lifecycle administration
718
+
719
+ The TypeScript SDK exposes typed admin clients for the five lifecycle
720
+ namespaces. Forward-only: no deprecated aliases.
721
+
722
+ ```ts
723
+ const admin = client.admin();
724
+
725
+ // Tenant storage: list/get/create/revoke. The server assigns the bucket and root prefix.
726
+ const loc = await admin.tenantStorage.create();
727
+
728
+ // Subject exports: full request lifecycle.
729
+ const exp = await admin.subjectExports.create({
730
+ opaqueSubjectId: "subject-01J5...",
731
+ scope: "both",
732
+ idempotencyKey: "acme-2026-07-31",
733
+ });
734
+ // Each artifact downloads by its own scope: access or portability.
735
+ const artifact = await admin.subjectExports.download(exp.id, "portability");
736
+
737
+ // Physical erasures: NO cancel/retry.
738
+ const force = await admin.privacyErasures.force("acme", "pe_01J5...");
739
+
740
+ // Retention policies: list/get/upsert/delete + preview/apply/listRuns (follow nextOffset while hasMore).
741
+ const runs = await admin.retention.listRuns("acme", { limit: 25 });
742
+
743
+ // Offboarding: full request lifecycle + schedules.
744
+ const sched = await admin.offboarding.schedule({
745
+ tenantSlug: "acme",
746
+ effectiveAt: "2026-12-31T00:00:00Z",
747
+ gracePeriodDays: 30,
748
+ reason: "contract_end",
749
+ status: "scheduled",
750
+ });
751
+
752
+ const request = await admin.offboarding.requestOffboarding(
753
+ { confirmation: "acme" },
754
+ { idempotencyKey: "acme-offboarding-2026-12-31" },
755
+ );
756
+
757
+ // Large downloads stream: the body arrives as a ReadableStream with the server's request id.
758
+ // download() buffers and verifies a bundle up to 64 MiB; downloadStream() leaves the checksum
759
+ // (stream.checksumSha256) for the caller to check against what it stored.
760
+ const bundle = await admin.offboarding.downloadStream(request.requestUuid, { signal });
761
+ await bundle.body.pipeTo(fileWritable);
762
+ const auditExport = await admin.audit.exportEvents({ environmentId: "env-1" }, "csv");
763
+ console.log(auditExport.requestId, auditExport.contentType);
764
+ ```
765
+
766
+ ## Time-plan administration
767
+
768
+ `client.admin.timePlans` exposes typed `TimePlan*` types for plan
769
+ drafts/revisions, previews, publication and retirement, runs, commands,
770
+ history, and annotation correction/redaction. Every call takes a company slug;
771
+ the server remains authoritative for allocations and command results.
772
+
773
+ ```ts
774
+ import { type TimePlanDefinition } from "@haakco/custd-sdk";
775
+
776
+ const definition: TimePlanDefinition = {
777
+ horizonMs: 60_000,
778
+ blocks: [{ uuid: "block-1", semanticKey: "focus", title: "Focus", basis: "absolute" }],
779
+ };
780
+
781
+ const preview = await client.admin.timePlans.preview("acme", definition);
782
+ const plan = await client.admin.timePlans.create("acme", {
783
+ planKey: "focus",
784
+ name: "Focus",
785
+ definition,
786
+ });
787
+ ```
788
+
789
+ The typed clients are available in `v1.8.25` and later.
790
+
791
+ ## Usage reporting
792
+
793
+ `client.admin.usage` reads the attributed usage for the authenticated tenant
794
+ through `GET /api/v1/admin/usage/me`. The tenant comes from the credential, so
795
+ the call never names a company slug. The system-admin `/usage` and `/usage/export`
796
+ surfaces are deliberately not exposed.
797
+
798
+ ```ts
799
+ const report = await client.admin.usage.get({
800
+ meterSlug: "events.ingested",
801
+ start: "2026-09-01T00:00:00Z",
802
+ end: "2026-10-01T00:00:00Z",
803
+ limit: 200,
804
+ });
805
+ ```
806
+
807
+ `report.totals` carries the per-meter totals and `report.rows` the per-window
808
+ detail. `report.containsProvisional` and `report.containsIncomplete` are the
809
+ server's own assessment, so a caller deciding whether a number is settled reads
810
+ them rather than assuming every row is final. An omitted `start`/`end` uses the
811
+ service default (the trailing 30 days) and an omitted `limit` uses
812
+ `USAGE_DEFAULT_LIMIT`; a limit outside `1..USAGE_MAX_LIMIT` rejects before a
813
+ request is sent.
814
+
815
+ ## Auth-project admin helpers
816
+
817
+ `client.admin.authProjects` manages Custd projects, their environments, and the
818
+ application principals a directory holds, through `/api/v1/admin/auth-projects`:
819
+
820
+ - `createProject` / `listProjects` (pass the previous `nextAfter` as the `after` cursor)
821
+ - `createEnvironment`
822
+ - `listPrincipalSessions`, `revokePrincipalSession`, `revokePrincipalSessions`
823
+ - `revokePrincipalMembership`
824
+ - Apps (`/api/v1/admin/apps`): `createApp({ name, signIn? })` creates the
825
+ project, its hosted environment and ingest destination in one call and
826
+ requires `idempotencyKey` (repeat it to finish `app_setup_incomplete`);
827
+ `listApps(after?)` and `getApp(slug)` report one `status` per app (codes in
828
+ `APP_STATUSES`, `APP_REASON_CODES`, `APP_ERROR_CODES`);
829
+ `createAppDeployCredential(slug)` returns a CI client that can deploy only that
830
+ app (its secret is shown once), `listAppDeployCredentials(slug)` and
831
+ `deleteAppDeployCredential(slug, clientId)`; `pauseApp`, `resumeApp`, `repairApp` and
832
+ `setAppSignIn(slug, { mode, expectedRevision })` (modes in `APP_SIGN_IN_MODES`) require
833
+ `idempotencyKey` (repeat it to finish `app_hosting_incomplete` or `app_repair_incomplete`)
834
+ - Authentication domain: `getEnvironmentAuthDomain`, `bindEnvironmentAuthDomain`,
835
+ `mintEnvironmentAuthDomain`, `admitEnvironmentAuthDomain`, `retryEnvironmentAuthDomain`,
836
+ `disableEnvironmentAuthDomain`, `releaseEnvironmentAuthDomain`, and the incident pin
837
+ `setEnvironmentAuthDomainImageOverride` / `clearEnvironmentAuthDomainImageOverride`
838
+ - Realm branding: `setAuthProjectBrandLogo(projectId, environmentId, logo, filename?)` uploads a
839
+ `Blob` as multipart `logo`; `clearAuthProjectBrandLogo` removes it
840
+ - `listEnvironmentAppLinks` lists the environment's app item owner and share links
841
+ - Hosted app releases: `createAppRelease` (manifest files and routing),
842
+ `uploadAppReleaseFile` (one file's raw bytes, sent as `application/octet-stream`),
843
+ `verifyAppRelease`, `promoteAppRelease` and `listAppReleases`
844
+
845
+ An environment is served as a hosted app by the optional `hosting` section of
846
+ its desired state (`mode`, `capabilities`, `ingestTarget`); leaving it out keeps
847
+ the stored section. `getEnvironmentStatus` reports the derived `hosting.host`,
848
+ `hosting.origin` and, with `sign_in`, the `hosting.signIn` client.
849
+
850
+ Every call takes `RequestOptions`. A machine credential must name the platform
851
+ user it acts for in `owningUserUuid`, sent as `X-Custd-Owning-User-UUID`; Custd
852
+ validates the named user as a live member of the machine's own company. A human
853
+ administrator's own token subject is the actor and leaves it unset. The
854
+ operations Custd makes retry-safe (`createProject`, `revokePrincipalSession`,
855
+ `revokePrincipalSessions`) require `idempotencyKey` and reject an empty value
856
+ before a request is sent.
857
+
858
+ ```ts
859
+ const creation = await client.admin.authProjects.createProject(
860
+ { slug: "hosting-eu", name: "Hosting EU", environmentSlug: "production", identityMode: "isolated" },
861
+ { owningUserUuid, idempotencyKey: "create-hosting-eu" },
862
+ );
863
+ ```
864
+
865
+ Responses are typed: `AuthProjectCreation`, `AuthProjectListResponse`,
866
+ `ApplicationSessionInventory`, `ApplicationSessionRevocation` and
867
+ `ApplicationMembershipRevocation`.
868
+
869
+ ## Admin Users
870
+
871
+ `client.admin.users` manages tenant administrator users. A user's global identity state and its
872
+ membership in one company are reported separately.
873
+
874
+ - `list({ companySlug?, role?, globalState?, membershipState?, welcomeStatus?, includeEnded?, includeDeleted? })`
875
+ - `get(userUuid, { companySlug?, includeEnded? })`, `create({ companySlug, email, roles })`,
876
+ `update(userUuid, { roles }, companySlug?)`, `addMembership(userUuid, { companySlug, roles })`
877
+ - `disable(userUuid, { reason?, companySlug?, globalUser? })`, `enable(userUuid, { roles, companySlug?, globalUser? })`
878
+ - `softDelete(userUuid, companySlug, { reason })`, `restore(userUuid, companySlug, { reason })`
879
+ - `resetPassword(userUuid)` returns the queued notification (`messageUuid`, `deliveryUuids`), never a password;
880
+ `retryWelcome(userUuid, { companySlug? })` re-sends the welcome message.
881
+
882
+ Roles are `ADMIN_USER_ROLES` (`tenant_admin`, `tenant_ingest_manager`, `tenant_analyst`).
883
+
884
+ ## Workflow Timings
885
+
886
+ `client.admin.workflowTimings` records facts another system observed about its own work. Custd never runs,
887
+ schedules or retries that work; every append is idempotent through the caller's key.
888
+
889
+ ```ts
890
+ await client.admin.workflowTimings.reconcileDefinition("acme", {
891
+ workflowKey: "nightly-import",
892
+ name: "Nightly import",
893
+ steps: [{ stepKey: "fetch", name: "Fetch", nominalMs: 60_000 }],
894
+ });
895
+ const result = await client.admin.workflowTimings.appendObservation("acme", {
896
+ workflowKey: "nightly-import",
897
+ externalRunId: "run-42",
898
+ idempotencyKey: "workflow-timing:nightly-import:run-42:run_started",
899
+ fact: { kind: WORKFLOW_TIMING_FACT_KINDS.runStarted, occurredAt: new Date().toISOString(), run: { state: "running" } },
900
+ });
901
+ if (result.rejected > 0) throw new Error(result.results.find((item) => !item.accepted)?.errorCode);
902
+ ```
903
+
904
+ A 200 answer is not a durable append: read `accepted` per result. `appendObservations` sends one bounded batch
905
+ (10,000 facts, 1 MiB); `correctObservation` supersedes an accepted fact via `supersedesFactUuid`. Reads:
906
+ `listDefinitions`, `getDefinition`, `listRuns({ workflowKey?, limit? })`, `getRun`, `getPrediction` (only a
907
+ `ready` expectation is a forecast; see `WORKFLOW_TIMING_STATES`), `getDurationHistory`, `getEvaluation`.
908
+ `rebuildRun` is the repair path when a run's `projectionStatus.pendingFacts` is above zero.
909
+
910
+ ## Tenant administration
911
+
912
+ `client.admin.tenants` (system administrators) also reads and sets a tenant's data-space limits
913
+ (`getDataSpaceEntitlement`, `updateDataSpaceEntitlement`) and storage allowance
914
+ (`updateStorageLimit`). Removing a deleted tenant is two steps that each take its positive
915
+ `companyId`: `historicalCleanup(slug, companyId, { idempotencyKey })` returns a content-free
916
+ `TenantHistoricalCleanupReceipt`, then `finalize(slug, companyId)`.
917
+ `client.provisioning.dataSpaces.usage(parentCompanySlug?)` reports retained storage per data space,
918
+ and `client.provisioning.producers.get(clientId)` reads one producer.
919
+
920
+ ## Analytics range query
921
+
922
+ `client.analytics.queryRange` reads a tenant's own events across an inclusive
923
+ date range of at most `ANALYTICS_MAX_RANGE_DAYS` days, with
924
+ `groupBy: "day"`. `buckets` carries each day's `count`/`source`/`complete` and
925
+ `rows` the capped detail. The per-day completeness is the server's assessment
926
+ and is surfaced unchanged.
927
+
928
+ ```ts
929
+ const range = await client.analytics.queryRange({
930
+ from: "2026-02-23",
931
+ to: "2026-05-23",
932
+ eventType: "page-view",
933
+ limit: 10000,
934
+ source: "auto",
935
+ groupBy: "day",
936
+ });
937
+ ```
938
+
939
+ SDKs never log signed URLs, raw personal data, export bytes, or
940
+ subject identifiers outside opaque IDs.
941
+
942
+ ## Error capture in Expo and React Native
943
+
944
+ Use `createErrorCaptureEvent({ error, mode }, { environment, release })` to
945
+ format a sanitized `ErrorCaptureEvent` for an application-authenticated relay.
946
+ It keeps only the exception type and bounded code basenames/line/column locations,
947
+ including Hermes and Metro bundle locations. Messages, full paths, request data,
948
+ and user context are excluded. Without `eventId`, it needs no `crypto`, DOM,
949
+ `TextEncoder`, or fetch globals; the relay's Go `CaptureEvent` generates the ID
950
+ and supplies its own server-only Site credential. Never put that credential in
951
+ the app or construct a collector envelope in application code.
952
+
953
+ `installNativeErrorCapture(errorUtils, capture)` accepts an injected React Native
954
+ `ErrorUtils`-shaped object and a capture callback. It chains the original handler
955
+ even if capture fails and returns cleanup that restores only its own handler.
956
+ The callback owns authenticated relay delivery and its session/concurrency bounds;
957
+ the installer does not create a queue, retry, persist, or modify native globals.
958
+ Caught React errors still belong in the application's error boundary. Native OS
959
+ crash capture is not provided by this JavaScript handler.