@capxul/observability 4.20.0-beta.1 → 4.20.0-beta.10

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.
@@ -0,0 +1,3295 @@
1
+ import { Effect, Schema, SchemaGetter } from "effect";
2
+ //#region ../errors/src/secret-material.ts
3
+ const CREDENTIAL_FIELDS = /* @__PURE__ */ new Set([
4
+ "password",
5
+ "passwd",
6
+ "pwd",
7
+ "pass",
8
+ "passphrase",
9
+ "currentpassword",
10
+ "newpassword",
11
+ "confirmpassword",
12
+ "passwordconfirmation",
13
+ "passwordhash",
14
+ "hashedpassword",
15
+ "pin",
16
+ "privatekey",
17
+ "walletprivatekey",
18
+ "secretkey",
19
+ "signingkey",
20
+ "signingsecret",
21
+ "seed",
22
+ "seedphrase",
23
+ "mnemonic",
24
+ "recoveryphrase",
25
+ "recovery",
26
+ "recoverycode",
27
+ "recoverycodes",
28
+ "keyshare",
29
+ "signingmaterial",
30
+ "recoverymaterial",
31
+ "privatekeybytes",
32
+ "signingprivatekey",
33
+ "encryptionkey",
34
+ "decryptionkey",
35
+ "authtoken",
36
+ "apitoken",
37
+ "bearertoken",
38
+ "oauthtoken",
39
+ "csrftoken",
40
+ "clientassertion",
41
+ "token",
42
+ "accesstoken",
43
+ "refreshtoken",
44
+ "idtoken",
45
+ "sessiontoken",
46
+ "session",
47
+ "sessionkey",
48
+ "sessionsecret",
49
+ "authsessionid",
50
+ "sessioncredential",
51
+ "sessioncredentials",
52
+ "sessioncookie",
53
+ "auth",
54
+ "authentication",
55
+ "authorization",
56
+ "proxyauthorization",
57
+ "cookie",
58
+ "cookies",
59
+ "setcookie",
60
+ "apikey",
61
+ "xapikey",
62
+ "xauthtoken",
63
+ "clientsecret",
64
+ "secret",
65
+ "secrets",
66
+ "credential",
67
+ "credentials",
68
+ "signature",
69
+ "otp",
70
+ "otpcode",
71
+ "totpsecret",
72
+ "onetimecode",
73
+ "onetimepassword",
74
+ "verificationcode",
75
+ "authcode",
76
+ "authorizationcode",
77
+ "oauthcode",
78
+ "codeverifier",
79
+ "devicecode",
80
+ "usercode",
81
+ "continuitytoken",
82
+ "refreshattemptid",
83
+ "revocationtoken"
84
+ ]);
85
+ /** Match credential fields by meaning, without hiding token addresses or replay IDs. */
86
+ function isCredentialField(name, context) {
87
+ const normalized = name.toLowerCase().replace(/[^a-z0-9]/gu, "");
88
+ return CREDENTIAL_FIELDS.has(normalized) || /(?:password(?:hash)?|passwd|passphrase|privatekey|signingkey|apikey|clientsecret|accesstoken|refreshtoken|sessiontoken)$/u.test(normalized) || context === "authentication" && (normalized === "code" || normalized === "sessionid") || context === "header" && /(?:token|secret|apikey|privatekey|signingkey|password|authorization|cookie|session)$/u.test(normalized);
89
+ }
90
+ function decodeUrlComponent(text) {
91
+ try {
92
+ return decodeURIComponent(text);
93
+ } catch {
94
+ return text;
95
+ }
96
+ }
97
+ /** Preserve URL diagnostics while removing credentials from their declared components. */
98
+ function redactUrlSecrets(value, source) {
99
+ try {
100
+ const absolute = /^[a-z][a-z0-9+.-]*:/iu.test(value);
101
+ const protocolRelative = value.startsWith("//");
102
+ const url = new URL(value, "https://redaction.invalid");
103
+ if (url.protocol !== "https:" && url.protocol !== "http:") return maskText(value);
104
+ let changed = url.username.length > 0 || url.password.length > 0;
105
+ const maskParams = (params) => new URLSearchParams(Array.from(params, ([name, entry]) => {
106
+ const safeName = maskText(name);
107
+ const safeEntry = isCredentialField(name) || /^(?:code|draft|__posthog)$/iu.test(name) ? "[REDACTED]" : maskText(entry);
108
+ changed ||= safeName !== name || safeEntry !== entry;
109
+ return [safeName, safeEntry];
110
+ })).toString();
111
+ const provider = source === "alchemy" || source === "infura" || /(?:^|\.)(?:alchemy\.com|alchemyapi\.io|infura\.io)$/iu.test(url.hostname);
112
+ const rawPath = absolute || protocolRelative ? url.pathname : value.split(/[?#]/u)[0] ?? "";
113
+ const segments = rawPath.split("/");
114
+ let path = segments.map((segment, index) => {
115
+ const decoded = decodeUrlComponent(segment);
116
+ const masked = provider && /^v[23]$/u.test(decodeUrlComponent(segments[index - 1] ?? "")) && decoded.length > 0 ? "[REDACTED]" : maskText(decoded);
117
+ changed ||= masked !== decoded;
118
+ return masked === decoded ? segment : encodeURIComponent(masked);
119
+ }).join("/");
120
+ if (source === "gateway" && rawPath.length > 0) {
121
+ path = `${rawPath.startsWith("/") ? "/" : ""}${encodeURIComponent("[REDACTED]")}`;
122
+ changed = true;
123
+ }
124
+ const query = maskParams(url.searchParams);
125
+ const fragment = url.hash.slice(1);
126
+ const decodedFragment = decodeUrlComponent(fragment);
127
+ const maskedFragment = maskText(decodedFragment);
128
+ changed ||= maskedFragment !== decodedFragment;
129
+ const fragmentQuery = fragment.indexOf("?");
130
+ const fragmentPath = fragment.slice(0, fragmentQuery);
131
+ const maskedFragmentPath = maskText(decodeUrlComponent(fragmentPath));
132
+ changed ||= maskedFragmentPath !== decodeUrlComponent(fragmentPath);
133
+ const hash = fragmentQuery >= 0 ? `${maskedFragmentPath === decodeUrlComponent(fragmentPath) ? fragmentPath : encodeURIComponent(maskedFragmentPath)}?${maskParams(new URLSearchParams(fragment.slice(fragmentQuery + 1)))}` : fragment.includes("=") ? maskParams(new URLSearchParams(fragment)) : maskedFragment === decodedFragment ? fragment : encodeURIComponent(maskedFragment);
134
+ const origin = absolute ? url.origin : protocolRelative ? `//${url.host}` : "";
135
+ if (!changed) return value;
136
+ return `${origin}${path}${query ? `?${query}` : ""}${hash ? `#${hash}` : ""}`;
137
+ } catch {
138
+ if (source === "gateway") return "[REDACTED]";
139
+ return maskText(value.replace(/(https?:\/\/)[^/\s@]+@/giu, "$1[REDACTED]@").replace(/([?&#])([^=&#]+)=([^&#]*)/gu, (whole, separator, name) => isCredentialField(decodeUrlComponent(name)) || /^(?:code|draft|__posthog)$/iu.test(decodeUrlComponent(name)) ? `${separator}${name}=[REDACTED]` : whole));
140
+ }
141
+ }
142
+ const JSON_FIELD = /("(?:[^"\\]|\\.)*")(\s*:\s*)("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/gu;
143
+ const PROSE_FIELD = /(?=(\b([A-Za-z][A-Za-z0-9_-]*(?:[ \t]+[A-Za-z][A-Za-z0-9_-]*){0,3})\s*[:=]\s*((?:Bearer|Basic)[ \t]+[^\s,;"']+|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s,;&"']+)))/gu;
144
+ const EMBEDDED_URL = /(https?:\/\/[^\s"<>]*)/giu;
145
+ function isSecretLabel(name) {
146
+ return isCredentialField(name) || /^request[ _-]?body$/iu.test(name);
147
+ }
148
+ const JSON_ENCODING_MAX = 8;
149
+ const JSON_NESTING_MAX = 64;
150
+ const JSON_KEY = /("(?:[^"\\]|\\.)*")\s*:/gu;
151
+ const JSON_CONTAINER_START = /(?:\{\s*["}]|\[\s*[[\]{}"0-9tfn-])/uy;
152
+ function hasSecretJsonKey(value) {
153
+ for (const match of value.matchAll(JSON_KEY)) try {
154
+ if (match[1] !== void 0 && isSecretLabel(JSON.parse(match[1]))) return true;
155
+ } catch {}
156
+ return false;
157
+ }
158
+ /** Project a complete fragment once. Never retry all of its nested substrings. */
159
+ function projectJsonFragment(value, encodingDepth, overDepth) {
160
+ if (overDepth || encodingDepth >= JSON_ENCODING_MAX) return "[REDACTED]";
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(value);
164
+ } catch {
165
+ return hasSecretJsonKey(value) ? "[REDACTED]" : value;
166
+ }
167
+ try {
168
+ let changed = false;
169
+ const masked = JSON.stringify(parsed, (name, nested) => {
170
+ if (isSecretLabel(name)) {
171
+ changed ||= nested !== "[REDACTED]";
172
+ return "[REDACTED]";
173
+ }
174
+ if (typeof nested === "string") {
175
+ const projected = maskJsonFragments(nested, encodingDepth + 1);
176
+ changed ||= projected !== nested;
177
+ return projected;
178
+ }
179
+ return nested;
180
+ });
181
+ return changed ? masked : value;
182
+ } catch {
183
+ return "[REDACTED]";
184
+ }
185
+ }
186
+ /** Scan balanced object/array fragments once, respecting JSON quotes and escapes. */
187
+ function maskJsonFragments(value, encodingDepth = 0) {
188
+ if (value.trimStart().startsWith("\"")) try {
189
+ const decoded = JSON.parse(value);
190
+ if (typeof decoded === "string") {
191
+ if (encodingDepth >= JSON_ENCODING_MAX) return "\"[REDACTED]\"";
192
+ const masked = maskJsonFragments(decoded, encodingDepth + 1);
193
+ return masked === decoded ? value : JSON.stringify(masked);
194
+ }
195
+ } catch {}
196
+ let output = "";
197
+ let cursor = 0;
198
+ let start = -1;
199
+ let depth = 0;
200
+ let overDepth = false;
201
+ let quoted = false;
202
+ let escaped = false;
203
+ for (let index = 0; index < value.length; index++) {
204
+ const character = value[index];
205
+ if (start < 0) {
206
+ JSON_CONTAINER_START.lastIndex = index;
207
+ if (!JSON_CONTAINER_START.test(value)) continue;
208
+ start = index;
209
+ depth = 1;
210
+ overDepth = false;
211
+ continue;
212
+ }
213
+ if (quoted) {
214
+ if (escaped) escaped = false;
215
+ else if (character === "\\") escaped = true;
216
+ else if (character === "\"") quoted = false;
217
+ continue;
218
+ }
219
+ if (character === "\"") quoted = true;
220
+ else if (character === "{" || character === "[") {
221
+ depth++;
222
+ overDepth ||= depth > JSON_NESTING_MAX;
223
+ } else if (character === "}" || character === "]") {
224
+ depth--;
225
+ if (depth !== 0) continue;
226
+ output += value.slice(cursor, start) + projectJsonFragment(value.slice(start, index + 1), encodingDepth, overDepth);
227
+ cursor = index + 1;
228
+ start = -1;
229
+ }
230
+ }
231
+ if (start >= 0) {
232
+ const fragment = value.slice(start);
233
+ output += value.slice(cursor, start) + (overDepth || hasSecretJsonKey(fragment) ? "[REDACTED]" : fragment);
234
+ cursor = value.length;
235
+ }
236
+ return output + value.slice(cursor);
237
+ }
238
+ function maskLabelledText(value) {
239
+ const jsonMasked = maskJsonFragments(value).replace(JSON_FIELD, (whole, quotedName, separator) => {
240
+ try {
241
+ return isSecretLabel(JSON.parse(quotedName)) ? `${quotedName}${separator}"[REDACTED]"` : whole;
242
+ } catch {
243
+ return whole;
244
+ }
245
+ });
246
+ let output = "";
247
+ let cursor = 0;
248
+ for (const match of jsonMasked.matchAll(PROSE_FIELD)) {
249
+ const [, whole, label, entry] = match;
250
+ if (whole === void 0 || label === void 0 || entry === void 0 || match.index < cursor || /^Bearer[ \t]+/iu.test(entry)) continue;
251
+ const words = label.split(/[ \t]+/u);
252
+ for (let index = 0; index < words.length; index++) {
253
+ const name = words.slice(index).join(" ");
254
+ if (isSecretLabel(name)) {
255
+ const prefix = words.slice(0, index).join(" ");
256
+ output += jsonMasked.slice(cursor, match.index) + `${prefix ? `${prefix} ` : ""}${name}=[REDACTED]`;
257
+ cursor = match.index + whole.length;
258
+ break;
259
+ }
260
+ }
261
+ }
262
+ return output + jsonMasked.slice(cursor);
263
+ }
264
+ const TOKEN_MASKS = [
265
+ [/\bBearer\s+(?!(?:realm|error|error_description|scope|authorization_uri|resource|claims)\s*=)[^\s,;"']+/giu, "Bearer [REDACTED]"],
266
+ [/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, "[REDACTED]"],
267
+ [/(^|[^a-fA-F0-9])(?<!0[xX])[a-fA-F0-9]{64}(?=$|[^a-fA-F0-9])/gu, "$1[REDACTED]"],
268
+ [/(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/giu, "[REDACTED]"]
269
+ ];
270
+ /** URL components and malformed URLs use this non-recursive masking layer. */
271
+ function maskText(value) {
272
+ let text = maskLabelledText(value);
273
+ for (const [pattern, replacement] of TOKEN_MASKS) text = text.replace(pattern, replacement);
274
+ return text;
275
+ }
276
+ /** Mask credential fields and embedded URLs while preserving surrounding evidence. */
277
+ function redactSecrets(value, source) {
278
+ return maskLabelledText(value).split(EMBEDDED_URL).map((part, index) => index % 2 === 1 ? redactUrlSecrets(part, source).replaceAll("%5BREDACTED%5D", "[REDACTED]") : maskText(part)).join("");
279
+ }
280
+ //#endregion
281
+ //#region ../errors/src/chain-cause.ts
282
+ /**
283
+ * Why an operation failed — the one flat vocabulary. The first four are the
284
+ * auth/provider diagnoses that predate this file. The rest name the chain
285
+ * path. `FailureMode` is derived from this list so a runtime membership check
286
+ * (the SDK's `$exception` projection, the observability schema) and the type
287
+ * can never drift apart.
288
+ */
289
+ const FAILURE_MODES = [
290
+ "auth-origin-mismatch",
291
+ "stale-openfort-cache",
292
+ "app-env-allowlist",
293
+ "no-secure-context",
294
+ "signer-not-ready",
295
+ "rate-limited",
296
+ "timeout",
297
+ "upstream-down",
298
+ "revert",
299
+ "insufficient-balance",
300
+ "insufficient-allowance",
301
+ "rejected",
302
+ "unauthorized",
303
+ "forbidden",
304
+ "bad-request",
305
+ "method-unsupported",
306
+ "unknown"
307
+ ];
308
+ /** Who answered. `alto` is the bundler; `gateway` is the AA gateway's own logic. */
309
+ const CHAIN_UPSTREAMS = [
310
+ "alchemy",
311
+ "infura",
312
+ "public",
313
+ "alto",
314
+ "gateway"
315
+ ];
316
+ //#endregion
317
+ //#region ../errors/src/errors.ts
318
+ const CAPXUL_ERROR_CODES = [
319
+ "NOT_AUTHENTICATED",
320
+ "EMAIL_DELIVERY_FAILED",
321
+ "PROFILE_NOT_FOUND",
322
+ "SMART_ACCOUNT_MISSING",
323
+ "PLAYER_NOT_FOUND",
324
+ "ACCOUNT_NOT_FOUND",
325
+ "ACCOUNT_CLAIMED_BY_OTHER_SIGNER",
326
+ "PROVIDER_ERROR",
327
+ "CAPABILITY_UNAVAILABLE",
328
+ "INVALID_INPUT",
329
+ "ENV_MISSING",
330
+ "NOT_IMPLEMENTED",
331
+ "VERIFICATION_REQUIRED",
332
+ "INSUFFICIENT_BALANCE",
333
+ "INVALID_RECIPIENT",
334
+ "ROLE_PERMISSION_DENIED",
335
+ "TRANSACTION_FAILED",
336
+ "RATE_LIMITED",
337
+ "NETWORK_ERROR",
338
+ "UNKNOWN",
339
+ "OTP_EXPIRED",
340
+ "SIGNER_REJECTED",
341
+ "CANCELLED",
342
+ "WRONG_STATE",
343
+ "STALE_EPOCH",
344
+ "SUPERSEDED",
345
+ "WORK_DIED",
346
+ "ACTOR_STOPPED"
347
+ ];
348
+ new Set(CAPXUL_ERROR_CODES);
349
+ //#endregion
350
+ //#region ../types/src/index.ts
351
+ const EVM_ADDRESS_RE = /^0x[0-9a-f]{40}$/i;
352
+ const BYTES32_RE = /^0x[0-9a-f]{64}$/i;
353
+ `${"0".repeat(64)}`;
354
+ const SUPPORTED_CURRENCIES = [
355
+ {
356
+ code: "USD",
357
+ symbol: "$",
358
+ name: "US Dollar"
359
+ },
360
+ {
361
+ code: "NGN",
362
+ symbol: "NGN",
363
+ name: "Nigerian Naira"
364
+ },
365
+ {
366
+ code: "GHS",
367
+ symbol: "GHS",
368
+ name: "Ghanaian Cedi"
369
+ },
370
+ {
371
+ code: "KES",
372
+ symbol: "KSh",
373
+ name: "Kenyan Shilling"
374
+ },
375
+ {
376
+ code: "UGX",
377
+ symbol: "USh",
378
+ name: "Ugandan Shilling"
379
+ }
380
+ ];
381
+ SUPPORTED_CURRENCIES.map((currency) => currency.code);
382
+ Object.fromEntries(SUPPORTED_CURRENCIES.map((currency) => [currency.code, currency.symbol]));
383
+ const APP_ID_RE = /^app_[0-7][0-9A-HJKMNP-TV-Z]{25}$/;
384
+ Math.floor(Number.MAX_SAFE_INTEGER / 1e3);
385
+ //#endregion
386
+ //#region src/operations.ts
387
+ const CAPXUL_OPERATIONS = {
388
+ account: {
389
+ addressBook: {
390
+ add: "account.addressBook.add",
391
+ get: "account.addressBook.get",
392
+ hide: "account.addressBook.hide",
393
+ label: "account.addressBook.label",
394
+ list: "account.addressBook.list",
395
+ unhide: "account.addressBook.unhide"
396
+ },
397
+ balance: "account.balance",
398
+ faucetMint: "account.faucetMint",
399
+ getLifecycle: "account.getLifecycle",
400
+ readBalance: "account.readBalance",
401
+ retrySetup: "account.retrySetup",
402
+ status: "account.status",
403
+ profile: {
404
+ depositInstructions: "account.profile.depositInstructions",
405
+ get: "account.profile.get"
406
+ },
407
+ inbox: {
408
+ approve: "account.inbox.approve",
409
+ decline: "account.inbox.decline",
410
+ list: "account.inbox.list"
411
+ },
412
+ requests: {
413
+ cancel: "account.requests.cancel",
414
+ get: "account.requests.get",
415
+ issue: "account.requests.issue",
416
+ list: "account.requests.list"
417
+ }
418
+ },
419
+ accounts: {
420
+ fund: "accounts.fund",
421
+ read: "accounts.read"
422
+ },
423
+ activity: {
424
+ annotate: "activity.annotate",
425
+ emitAnnotationSaved: "activity.emitAnnotationSaved",
426
+ get: "activity.get",
427
+ list: "activity.list",
428
+ /** The SDK's live Activity read over the indexer's SSE stream. */
429
+ subscribe: "activity.subscribe",
430
+ summary: "activity.summary"
431
+ },
432
+ addressBook: {
433
+ add: "addressBook.add",
434
+ emitRelationshipChanged: "addressBook.emitRelationshipChanged",
435
+ get: "addressBook.get",
436
+ hide: "addressBook.hide",
437
+ label: "addressBook.label",
438
+ list: "addressBook.list",
439
+ unhide: "addressBook.unhide"
440
+ },
441
+ applications: { create: "applications.create" },
442
+ auth: {
443
+ canSendOtp: "auth.canSendOtp",
444
+ getSession: "auth.getSession",
445
+ signIn: "auth.signIn",
446
+ signOut: "auth.signOut",
447
+ sendVerificationOtp: "auth.sendVerificationOTP",
448
+ verifyOtp: "auth.verifyOtp"
449
+ },
450
+ client: {
451
+ createOrg: "createOrg",
452
+ orgs: "orgs"
453
+ },
454
+ /** AUTH A3 (#2073): the SDK facade over the native continuation endpoints. */
455
+ clientRequests: {
456
+ decide: "clientRequests.decide",
457
+ read: "clientRequests.read"
458
+ },
459
+ /** AUTH A2 (#2072): the native client authorization issuer and its browser
460
+ * continuation. One name per durable transition the endpoints can fail on. */
461
+ clientAuthorization: {
462
+ acceptRequest: "clientAuthorization.acceptRequest",
463
+ cancelRequest: "clientAuthorization.cancelRequest",
464
+ consumeRequest: "clientAuthorization.consumeRequest",
465
+ denyRequest: "clientAuthorization.denyRequest",
466
+ invalidateContext: "clientAuthorization.invalidateContext",
467
+ markConsented: "clientAuthorization.markConsented",
468
+ readMetadata: "clientAuthorization.readMetadata",
469
+ revokeGrant: "clientAuthorization.revokeGrant",
470
+ rotateGrant: "clientAuthorization.rotateGrant",
471
+ startRequest: "clientAuthorization.startRequest",
472
+ sweepExpired: "clientAuthorization.sweepExpired"
473
+ },
474
+ credentials: {
475
+ bootstrapClient: "credentials.bootstrapClient",
476
+ mintQuickstartKey: "credentials.mintQuickstartKey"
477
+ },
478
+ currentUser: { get: "currentUser.get" },
479
+ devIdentity: { seedFinancialOpsOrg: "devIdentity.seedFinancialOpsOrg" },
480
+ dev: { browserSeed: "dev.browserSeed" },
481
+ destinations: {
482
+ add: "destinations.add",
483
+ list: "destinations.list",
484
+ remove: "destinations.remove"
485
+ },
486
+ faucetSafe: { deploy: "FaucetSafe.deploy" },
487
+ financialOps: {
488
+ addDestination: "financialOps.addDestination",
489
+ approveRequest: "financialOps.approveRequest",
490
+ cancelRequest: "financialOps.cancelRequest",
491
+ createPayee: "financialOps.createPayee",
492
+ declineRequest: "financialOps.declineRequest",
493
+ emitInvoiceIssued: "financialOps.emitInvoiceIssued",
494
+ emitInvoiceRequestTransitioned: "financialOps.emitInvoiceRequestTransitioned",
495
+ emitPaymentWriterTelemetry: "financialOps.emitPaymentWriterTelemetry",
496
+ issueRequest: "financialOps.issueRequest",
497
+ migrateEvidenceIdentity: "financialOps.migrateEvidenceIdentity",
498
+ planEvidenceIdentity: "financialOps.planEvidenceIdentity",
499
+ recoverSettlementVerification: "financialOps.recoverSettlementVerification",
500
+ removeDestination: "financialOps.removeDestination",
501
+ verifySettlement: "financialOps.verifySettlement"
502
+ },
503
+ holdings: { current: "holdings.current" },
504
+ indexer: { reconcile: "indexer.reconcile" },
505
+ identity: {
506
+ accountAt: "identity.AccountAt",
507
+ accountClaimed: "identity.AccountClaimed",
508
+ accountClaiming: "identity.AccountClaiming",
509
+ accountDerived: "identity.AccountDerived",
510
+ accountFailed: "identity.AccountFailed",
511
+ attachOrganization: "identity.AttachOrganization",
512
+ claimAccount: "identity.ClaimAccount",
513
+ completeOnboarding: "identity.completeOnboarding",
514
+ completeProfile: "identity.completeProfile",
515
+ create: "identity.create",
516
+ createOrganization: "identity.CreateOrganization",
517
+ ensureAccount: "identity.EnsureAccount",
518
+ leaveOrganization: "identity.LeaveOrganization",
519
+ loadByAuthUserId: "identity.loadByAuthUserId",
520
+ loadCurrent: "identity.loadCurrent",
521
+ orgAt: "identity.OrgAt",
522
+ orgFailed: "identity.OrgFailed",
523
+ orgReady: "identity.OrgReady",
524
+ otpFailed: "identity.OtpFailed",
525
+ otpSent: "identity.OtpSent",
526
+ readSession: "identity.ReadSession",
527
+ requestOtp: "identity.RequestOtp",
528
+ reset: "identity.Reset",
529
+ restoreSession: "identity.RestoreSession",
530
+ resumeOtpEntry: "identity.ResumeOtpEntry",
531
+ retryAccount: "identity.RetryAccount",
532
+ retryOrganization: "identity.RetryOrganization",
533
+ sessionAbsent: "identity.SessionAbsent",
534
+ sessionRead: "identity.SessionRead",
535
+ sessionReadFailed: "identity.SessionReadFailed",
536
+ sessionRestored: "identity.SessionRestored",
537
+ signedOut: "identity.SignedOut",
538
+ signOut: "identity.SignOut",
539
+ signOutFailed: "identity.SignOutFailed",
540
+ update: "identity.update",
541
+ handleAvailable: "identity.handleAvailable",
542
+ verified: "identity.Verified",
543
+ verifyFailed: "identity.VerifyFailed",
544
+ verifyOtp: "identity.VerifyOtp"
545
+ },
546
+ media: {
547
+ generateUploadUrl: "media.generateUploadUrl",
548
+ setOrgLogo: "media.setOrgLogo",
549
+ setProfileImage: "media.setProfileImage",
550
+ uploadImage: "media.uploadImage"
551
+ },
552
+ me: {
553
+ depositInstructions: "me.depositInstructions",
554
+ get: "me.get"
555
+ },
556
+ moneyExecution: {
557
+ abandonPaymentExecution: "moneyExecution.abandonPaymentExecution",
558
+ prepareOrganizationPaymentExecution: "moneyExecution.prepareOrganizationPaymentExecution",
559
+ preparePaymentExecution: "moneyExecution.preparePaymentExecution",
560
+ preparePaymentLifecycleExecution: "moneyExecution.preparePaymentLifecycleExecution",
561
+ prepareInvitationConfiguration: "moneyExecution.prepareInvitationConfiguration",
562
+ preparePermissionExecution: "moneyExecution.preparePermissionExecution",
563
+ recoverSubmissionClaims: "moneyExecution.recoverSubmissionClaims",
564
+ submit: "moneyExecution.submit",
565
+ submitPaymentCommandExecution: "moneyExecution.submitPaymentCommandExecution",
566
+ submitInvitationConfigurationExecution: "moneyExecution.submitInvitationConfigurationExecution",
567
+ submitPaymentExecution: "moneyExecution.submitPaymentExecution",
568
+ submitPermissionExecution: "moneyExecution.submitPermissionExecution"
569
+ },
570
+ movement: {
571
+ emitDepositSettled: "movement.emitDepositSettled",
572
+ scan: "movement.scan"
573
+ },
574
+ inbox: {
575
+ approve: "inbox.approve",
576
+ decline: "inbox.decline",
577
+ list: "inbox.list"
578
+ },
579
+ offramp: {
580
+ quote: "offramp.quote",
581
+ status: "offramp.status"
582
+ },
583
+ onboarding: {
584
+ completeOrganization: "onboarding.completeOrganization",
585
+ completePerson: "onboarding.completePerson"
586
+ },
587
+ org: {
588
+ account: { get: "org.account.get" },
589
+ auditLog: "org.auditLog",
590
+ confirmBootstrap: "org.confirmBootstrap",
591
+ createOrg: "org.createOrg",
592
+ create: "org.create",
593
+ /**
594
+ * §11: the consent mutation reports `org_invite_accepted` through its own
595
+ * scheduled emitter. It is named for the emit, not the acceptance, because
596
+ * the interactive acceptance itself owns `org.invitations.accept`.
597
+ */
598
+ emitInviteAccepted: "org.emitInviteAccepted",
599
+ emitInviteProgressed: "org.emitInviteProgressed",
600
+ expireInvitations: "org.expireInvitations",
601
+ getLifecycle: "org.getLifecycle",
602
+ getProofReceipt: "org.getProofReceipt",
603
+ invite: "org.invite",
604
+ /** D8 invitation lifecycle: preview, own list, read, and the four transitions. */
605
+ invitations: {
606
+ /** The exact grantee's consent commit (§8): one accepted digest, once. */
607
+ accept: "org.invitations.accept",
608
+ /**
609
+ * The authoring write. It is named `authorize`, not `invite`, because the
610
+ * backend already uses `org.invitations.invite` as a refusal label and
611
+ * `lint:telemetry-spine` refuses a label that collides with an operation.
612
+ */
613
+ authorize: "org.invitations.authorize",
614
+ cancel: "org.invitations.cancel",
615
+ decline: "org.invitations.decline",
616
+ get: "org.invitations.get",
617
+ list: "org.invitations.list",
618
+ /**
619
+ * The Admin-scoped Organization list. It is named `listScoped`, not
620
+ * `list`, because the own-offer list already owns `org.invitations.list`.
621
+ */
622
+ listScoped: "org.invitations.listScoped",
623
+ /**
624
+ * The authoring write's inner hops: the SDK drives the backend's existing
625
+ * prepare/submit pair, and these names label the two Convex calls. The
626
+ * owning `capxul_sdk_operation` record stays `org.invitations.authorize`.
627
+ */
628
+ prepareConfiguration: "org.invitations.prepareConfiguration",
629
+ preview: "org.invitations.preview",
630
+ resend: "org.invitations.resend",
631
+ retry: "org.invitations.retry",
632
+ submitConfiguration: "org.invitations.submitConfiguration"
633
+ },
634
+ list: "org.list",
635
+ load: "org.load",
636
+ me: "org.me",
637
+ members: "org.members",
638
+ orgs: "org.orgs",
639
+ payment: "org.payment",
640
+ permissions: {
641
+ assign: "org.permissions.assign",
642
+ change: "org.permissions.change",
643
+ create: "org.permissions.create",
644
+ get: "org.permissions.get",
645
+ list: "org.permissions.list",
646
+ replace: "org.permissions.replace",
647
+ revoke: "org.permissions.revoke"
648
+ },
649
+ payments: {
650
+ pay: "org.payments.pay",
651
+ payBatch: "org.payments.payBatch"
652
+ },
653
+ payroll: {
654
+ authorizeRun: "org.payroll.authorizeRun",
655
+ groups: {
656
+ list: "org.payroll.groups.list",
657
+ remove: "org.payroll.groups.remove",
658
+ save: "org.payroll.groups.save"
659
+ },
660
+ runs: "org.payroll.runs",
661
+ terms: "org.payroll.terms"
662
+ },
663
+ addressBook: {
664
+ add: "org.addressBook.add",
665
+ get: "org.addressBook.get",
666
+ hide: "org.addressBook.hide",
667
+ label: "org.addressBook.label",
668
+ list: "org.addressBook.list",
669
+ unhide: "org.addressBook.unhide"
670
+ },
671
+ inbox: {
672
+ approve: "org.inbox.approve",
673
+ decline: "org.inbox.decline",
674
+ list: "org.inbox.list"
675
+ },
676
+ lifecycle: { startOrResume: "org.lifecycle.startOrResume" },
677
+ prepareBootstrap: "org.prepareBootstrap",
678
+ prepareFounderAccount: "org.prepareFounderAccount",
679
+ profile: {
680
+ depositInstructions: "org.profile.depositInstructions",
681
+ get: "org.profile.get"
682
+ },
683
+ readTreasury: "org.readTreasury",
684
+ requests: {
685
+ cancel: "org.requests.cancel",
686
+ get: "org.requests.get",
687
+ issue: "org.requests.issue",
688
+ list: "org.requests.list"
689
+ },
690
+ recordFailure: "org.recordFailure",
691
+ recordProgress: "org.recordProgress",
692
+ resumeBootstrapSubmission: "org.resumeBootstrapSubmission",
693
+ retry: "org.retry",
694
+ retrySetup: "org.retrySetup",
695
+ roles: "org.roles",
696
+ startOrResume: "org.startOrResume",
697
+ submitBootstrap: "org.submitBootstrap",
698
+ treasury: "org.treasury"
699
+ },
700
+ organization: { setup: "organization.setup" },
701
+ organizationPayments: {
702
+ pay: "organizationPayments.pay",
703
+ payBatch: "organizationPayments.payBatch",
704
+ prepareExecution: "organizationPayments.prepareExecution",
705
+ retry: "organizationPayments.retry"
706
+ },
707
+ organizationSetup: { getProofReceipt: "organizationSetup.getProofReceipt" },
708
+ payments: {
709
+ cancel: "payments.cancel",
710
+ claim: "payments.claim",
711
+ createCommitment: "payments.createCommitment",
712
+ get: "payments.get",
713
+ ledger: "payments",
714
+ list: "payments.list",
715
+ pay: "payments.pay",
716
+ prepareExecution: "payments.prepareExecution",
717
+ prepareLifecycleExecution: "payments.prepareLifecycleExecution",
718
+ redirect: "payments.redirect",
719
+ retry: "payments.retry",
720
+ submitCommandExecution: "payments.submitCommandExecution",
721
+ submitExecution: "payments.submitExecution"
722
+ },
723
+ paymentDocuments: {
724
+ get: "paymentDocuments.get",
725
+ render: "paymentDocuments.render",
726
+ verify: "paymentDocuments.verify"
727
+ },
728
+ recipient: { resolve: "recipient.resolve" },
729
+ payroll: {
730
+ authorizeRun: "payroll.authorizeRun",
731
+ emitGroupChanged: "payroll.emitGroupChanged",
732
+ emitRunTransitioned: "payroll.emitRunTransitioned",
733
+ groups: {
734
+ access: "payroll.groups",
735
+ list: "payroll.groups.list",
736
+ remove: "payroll.groups.remove",
737
+ save: "payroll.groups.save"
738
+ },
739
+ removeGroup: "payroll.removeGroup",
740
+ runs: "payroll.runs",
741
+ saveGroup: "payroll.saveGroup",
742
+ terms: "payroll.terms"
743
+ },
744
+ permission: {
745
+ verifyInvitationConfiguration: "permission.verifyInvitationConfiguration",
746
+ command: "permission.command",
747
+ retryVerification: "permission.retryVerification",
748
+ verify: "permission.verify",
749
+ verifySubmitted: "permission.verifySubmitted"
750
+ },
751
+ permissions: {
752
+ assign: "permissions.assign",
753
+ change: "permissions.change",
754
+ create: "permissions.create",
755
+ get: "permissions.get",
756
+ list: "permissions.list",
757
+ prepareExecution: "permissions.prepareExecution",
758
+ replace: "permissions.replace",
759
+ revoke: "permissions.revoke",
760
+ submitExecution: "permissions.submitExecution"
761
+ },
762
+ publishableKeys: {
763
+ mint: "publishableKeys.mint",
764
+ revoke: "publishableKeys.revoke",
765
+ rotate: "publishableKeys.rotate"
766
+ },
767
+ requests: {
768
+ cancel: "requests.cancel",
769
+ get: "requests.get",
770
+ issue: "requests.issue",
771
+ list: "requests.list"
772
+ },
773
+ runtime: {
774
+ assign: "assign",
775
+ canSendOtp: "canSendOtp",
776
+ cancelCommitment: "cancel_commitment",
777
+ change: "change",
778
+ claimCommitment: "claim_commitment",
779
+ create: "create",
780
+ createCapxulClient: "createCapxulClient",
781
+ createCapxulClientWithOrgDeploymentSeams: "createCapxulClientWithOrgDeploymentSeams",
782
+ createCommitment: "create_commitment",
783
+ getConvexJwt: "getConvexJwt",
784
+ getSession: "getSession",
785
+ initialize: "initialize",
786
+ mutation: "mutation",
787
+ now: "now",
788
+ port: "port",
789
+ query: "query",
790
+ redirectCommitment: "redirect_commitment",
791
+ replace: "replace",
792
+ resolve: "resolve",
793
+ revoke: "revoke",
794
+ send: "send",
795
+ sendOtp: "sendOtp",
796
+ signIn: "signIn",
797
+ signOut: "signOut",
798
+ sleep: "sleep",
799
+ verifyOtp: "verifyOtp",
800
+ wallet: "wallet"
801
+ },
802
+ smartAccount: {
803
+ claim: "smartAccount.claim",
804
+ confirmDeployment: "smartAccount.confirmDeployment",
805
+ loadByAuthUserId: "smartAccount.loadByAuthUserId",
806
+ loadCurrent: "smartAccount.loadCurrent",
807
+ provision: "smartAccount.provision"
808
+ },
809
+ system: {
810
+ health: "system.health",
811
+ ping: "system.ping",
812
+ runtimeChain: "system.runtimeChain"
813
+ },
814
+ testUsdc: { mint: "TestUSDC.mint" },
815
+ _internal: {
816
+ accounts: { fund: "_internal.accounts.fund" },
817
+ close: "_internal.close",
818
+ identity: {
819
+ completeProfile: "_internal.identity.completeProfile",
820
+ runFacade: "_internal.identity.runFacade",
821
+ send: "_internal.identity.send"
822
+ },
823
+ organizationSetup: { getProofReceipt: "_internal.organizationSetup.getProofReceipt" }
824
+ },
825
+ tenancy: {
826
+ revokeBackendTenancyConsent: "tenancy.revokeBackendTenancyConsent",
827
+ seedBackendTenancy: "tenancy.seedBackendTenancy"
828
+ }
829
+ };
830
+ function collectOperations(tree) {
831
+ return Object.values(tree).flatMap((value) => typeof value === "string" ? [value] : collectOperations(value));
832
+ }
833
+ const operations = new Set(collectOperations(CAPXUL_OPERATIONS));
834
+ function isCapxulOperation(value) {
835
+ return typeof value === "string" && operations.has(value);
836
+ }
837
+ function normalizeCapxulOperation(value) {
838
+ return isCapxulOperation(value) ? value : "unknown";
839
+ }
840
+ //#endregion
841
+ //#region src/index.ts
842
+ const TELEMETRY_EVENT_NAMES = [
843
+ "auth_otp_requested",
844
+ "auth_otp_delivered",
845
+ "auth_otp_expired",
846
+ "auth_verified",
847
+ "auth_failed",
848
+ "identity_refused",
849
+ "auth_signed_out",
850
+ "native_authorization_started",
851
+ "native_authorization_reviewed",
852
+ "native_authorization_accepted",
853
+ "native_authorization_denied",
854
+ "native_authorization_connected",
855
+ "native_authorization_failed",
856
+ "onboarding_intent_selected",
857
+ "onboarding_profile_submitted",
858
+ "onboarding_organization_submitted",
859
+ "onboarding_dashboard_reached",
860
+ "provisioning_safe_created",
861
+ "provisioning_safe_confirmed",
862
+ "bootstrap_resolved",
863
+ "bootstrap_failed",
864
+ "member_activation_started",
865
+ "member_activation_ready",
866
+ "member_activation_failed",
867
+ "organization_creation_started",
868
+ "organization_creation_ready",
869
+ "organization_creation_failed",
870
+ "chain_upstream_fallback",
871
+ "bundler_error",
872
+ "receipt_pending",
873
+ "operation_retried",
874
+ "account_balance_read",
875
+ "account_balance_failed",
876
+ "faucet_requested",
877
+ "faucet_confirmed",
878
+ "faucet_failed",
879
+ "org_create_started",
880
+ "org_safe_created",
881
+ "org_safe_confirmed",
882
+ "org_roles_seeded",
883
+ "org_created",
884
+ "org_create_failed",
885
+ "org_invite_sent",
886
+ "org_invite_accepted",
887
+ "org_invite_expired",
888
+ "payment_initiated",
889
+ "payment_settled",
890
+ "payment_failed",
891
+ "payment_verification_retry",
892
+ "payment_lifecycle_transition",
893
+ "quick_pay_external_address_acknowledged",
894
+ "deposit_initiated",
895
+ "deposit_settled",
896
+ "permission_mirror_verification",
897
+ "movement_scan_window",
898
+ "movement_scan_checkpoint",
899
+ "movement_scan_incident",
900
+ "indexer_drift_corrected",
901
+ "activity_annotation_saved",
902
+ "ui_activity_action_completed",
903
+ "contact_relationship_changed",
904
+ "ui_contact_action_completed",
905
+ "access_recovery_completed",
906
+ "ui_access_step_completed",
907
+ "org_invite_progressed",
908
+ "invoice_issued",
909
+ "invoice_request_transitioned",
910
+ "ui_invoice_step_completed",
911
+ "ui_treasury_step_completed",
912
+ "ui_receive_step_completed",
913
+ "payroll_group_changed",
914
+ "payroll_run_transitioned",
915
+ "ui_payroll_action_completed",
916
+ "cli_diagnostic_completed",
917
+ "cli_first_used",
918
+ "cli_command_started",
919
+ "cli_command_completed"
920
+ ];
921
+ const TELEMETRY_JOURNEYS = {
922
+ returning_user_login: {
923
+ type: "funnel",
924
+ steps: [
925
+ "auth_otp_requested",
926
+ "auth_otp_delivered",
927
+ "auth_verified"
928
+ ],
929
+ drops_on: ["auth_otp_expired", "auth_failed"]
930
+ },
931
+ new_user_first_signin: {
932
+ type: "funnel",
933
+ steps: [
934
+ "auth_otp_requested",
935
+ "auth_otp_delivered",
936
+ "auth_verified",
937
+ "provisioning_safe_created",
938
+ "provisioning_safe_confirmed"
939
+ ],
940
+ drops_on: ["auth_otp_expired", "auth_failed"]
941
+ },
942
+ sign_out_session_close: {
943
+ type: "point_event",
944
+ point_event: "auth_signed_out"
945
+ },
946
+ member_activation: {
947
+ type: "funnel",
948
+ steps: ["member_activation_started", "member_activation_ready"],
949
+ drops_on: ["member_activation_failed"]
950
+ },
951
+ organization_creation_lifecycle: {
952
+ type: "funnel",
953
+ steps: ["organization_creation_started", "organization_creation_ready"],
954
+ drops_on: ["organization_creation_failed"]
955
+ },
956
+ new_member_personal_dashboard: {
957
+ type: "funnel",
958
+ steps: [
959
+ "auth_verified",
960
+ "onboarding_intent_selected",
961
+ "onboarding_profile_submitted",
962
+ "member_activation_ready",
963
+ "onboarding_dashboard_reached"
964
+ ],
965
+ step_filters: {
966
+ onboarding_intent_selected: [{
967
+ key: "intent",
968
+ value: ["personal"],
969
+ operator: "exact",
970
+ type: "event"
971
+ }, {
972
+ key: "entry_point",
973
+ value: ["signup"],
974
+ operator: "exact",
975
+ type: "event"
976
+ }],
977
+ onboarding_profile_submitted: [{
978
+ key: "intent",
979
+ value: ["personal"],
980
+ operator: "exact",
981
+ type: "event"
982
+ }],
983
+ onboarding_dashboard_reached: [{
984
+ key: "intent",
985
+ value: ["personal"],
986
+ operator: "exact",
987
+ type: "event"
988
+ }]
989
+ }
990
+ },
991
+ new_member_organization_dashboard: {
992
+ type: "funnel",
993
+ steps: [
994
+ "auth_verified",
995
+ "onboarding_intent_selected",
996
+ "onboarding_profile_submitted",
997
+ "onboarding_organization_submitted",
998
+ "member_activation_started",
999
+ "member_activation_ready",
1000
+ "organization_creation_started",
1001
+ "organization_creation_ready",
1002
+ "onboarding_dashboard_reached"
1003
+ ],
1004
+ step_filters: {
1005
+ onboarding_intent_selected: [{
1006
+ key: "intent",
1007
+ value: ["organization"],
1008
+ operator: "exact",
1009
+ type: "event"
1010
+ }, {
1011
+ key: "entry_point",
1012
+ value: ["signup"],
1013
+ operator: "exact",
1014
+ type: "event"
1015
+ }],
1016
+ onboarding_profile_submitted: [{
1017
+ key: "intent",
1018
+ value: ["organization"],
1019
+ operator: "exact",
1020
+ type: "event"
1021
+ }],
1022
+ onboarding_dashboard_reached: [{
1023
+ key: "intent",
1024
+ value: ["organization"],
1025
+ operator: "exact",
1026
+ type: "event"
1027
+ }]
1028
+ }
1029
+ },
1030
+ existing_member_organization_dashboard: {
1031
+ type: "funnel",
1032
+ steps: [
1033
+ "onboarding_intent_selected",
1034
+ "onboarding_organization_submitted",
1035
+ "organization_creation_started",
1036
+ "organization_creation_ready",
1037
+ "onboarding_dashboard_reached"
1038
+ ],
1039
+ step_filters: {
1040
+ onboarding_intent_selected: [{
1041
+ key: "intent",
1042
+ value: ["organization"],
1043
+ operator: "exact",
1044
+ type: "event"
1045
+ }, {
1046
+ key: "entry_point",
1047
+ value: ["dashboard"],
1048
+ operator: "exact",
1049
+ type: "event"
1050
+ }],
1051
+ onboarding_dashboard_reached: [{
1052
+ key: "intent",
1053
+ value: ["organization"],
1054
+ operator: "exact",
1055
+ type: "event"
1056
+ }]
1057
+ }
1058
+ },
1059
+ money_on_screen: {
1060
+ type: "point_event",
1061
+ point_event: "account_balance_read"
1062
+ },
1063
+ fund_account: {
1064
+ type: "funnel",
1065
+ steps: ["faucet_requested", "faucet_confirmed"],
1066
+ drops_on: ["faucet_failed"]
1067
+ },
1068
+ org_creation: {
1069
+ type: "funnel",
1070
+ steps: [
1071
+ "org_create_started",
1072
+ "org_safe_created",
1073
+ "org_safe_confirmed",
1074
+ "org_roles_seeded",
1075
+ "org_created"
1076
+ ],
1077
+ drops_on: ["org_create_failed"]
1078
+ },
1079
+ org_member_onboarding: {
1080
+ type: "funnel",
1081
+ steps: ["org_invite_sent", "org_invite_accepted"],
1082
+ drops_on: ["org_invite_expired"]
1083
+ },
1084
+ direct_payment: {
1085
+ type: "funnel",
1086
+ steps: ["payment_initiated", "payment_settled"],
1087
+ drops_on: ["payment_failed"]
1088
+ },
1089
+ deposit: {
1090
+ type: "funnel",
1091
+ steps: ["deposit_initiated", "deposit_settled"]
1092
+ }
1093
+ };
1094
+ const PII = Schema.String.pipe(Schema.brand("PII"));
1095
+ const OptionalString = Schema.optional(Schema.String);
1096
+ const AddressSchema = Schema.String.pipe(Schema.decodeTo(Schema.String, {
1097
+ decode: SchemaGetter.transform((value) => value.toLowerCase()),
1098
+ encode: SchemaGetter.transform((value) => value)
1099
+ }), Schema.refine((value) => EVM_ADDRESS_RE.test(value), { message: "must be 0x + 40 hex chars" }));
1100
+ const AppIdSchema = Schema.String.pipe(Schema.refine((value) => APP_ID_RE.test(value), { message: "must be app_ plus a ULID" }));
1101
+ const BlockNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1102
+ const ChainIdSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1103
+ const DurationMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1104
+ const EpochMsSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value >= 0, { message: "must be a non-negative safe integer" }));
1105
+ const PublishableKeyIdSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty string" }));
1106
+ const TxHashSchema = Schema.String.pipe(Schema.refine((value) => BYTES32_RE.test(value), { message: "must be 0x + 64 hex chars" }));
1107
+ const ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;
1108
+ const WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;
1109
+ const AccountIdSchema = Schema.String.pipe(Schema.refine((value) => ACCOUNT_ID_TELEMETRY_RE.test(value), { message: "must be account_ plus an alphanumeric id" }));
1110
+ const WeiAmountSchema = Schema.String.pipe(Schema.refine((value) => WEI_AMOUNT_TELEMETRY_RE.test(value), { message: "must be a non-negative integer string" }));
1111
+ const CurrencyCodeSchema = Schema.String.pipe(Schema.refine((value) => value.length > 0, { message: "must be a non-empty currency code" }));
1112
+ const BalanceBucketSchema = Schema.Literals(["zero", "nonzero"]);
1113
+ const OptionalAccountId = Schema.optional(AccountIdSchema);
1114
+ const OptionalWeiAmount = Schema.optional(WeiAmountSchema);
1115
+ const OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);
1116
+ const OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);
1117
+ /** Which Safe a money record is about. Declared here so the money-domain
1118
+ * props below can name it as well as the UI-step props further down. */
1119
+ const AccountKindSchema = Schema.Literals(["personalSafe", "orgTreasury"]);
1120
+ const OptionalAccountKind = Schema.optional(AccountKindSchema);
1121
+ const OptionalAddress = Schema.optional(AddressSchema);
1122
+ const OptionalAppId = Schema.optional(AppIdSchema);
1123
+ const OptionalBlockNumber = Schema.optional(BlockNumberSchema);
1124
+ const OptionalChainId = Schema.optional(ChainIdSchema);
1125
+ const OptionalDurationMs = Schema.optional(DurationMsSchema);
1126
+ const OptionalEpochMs = Schema.optional(EpochMsSchema);
1127
+ const OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);
1128
+ const OptionalTxHash = Schema.optional(TxHashSchema);
1129
+ /**
1130
+ * Environment discriminator (ADR-0020 A1 amendment, 2026-08-07). PostHog
1131
+ * project 368736 is the SINGLE sink for every environment, so `capxul_env` —
1132
+ * not project isolation — is what keeps a production surface from reading dev
1133
+ * traffic. It is REQUIRED on every catalog event and every synced artifact
1134
+ * filters on it.
1135
+ *
1136
+ * `unknown` is a defect marker, not an environment: it means a producer
1137
+ * reached the transport without declaring where it runs. It is in the union so
1138
+ * the property is never ABSENT (an absent property is invisible to a filter,
1139
+ * a present `unknown` is loud), and sync v2 never synthesizes an artifact for
1140
+ * it.
1141
+ */
1142
+ const CAPXUL_ENVS = [
1143
+ "development",
1144
+ "staging",
1145
+ "production",
1146
+ "unknown",
1147
+ "local"
1148
+ ];
1149
+ /**
1150
+ * Environments a synced product surface may be built for. `unknown` and
1151
+ * `local` cannot. This list is deliberately narrower than `CAPXUL_ENVS`.
1152
+ */
1153
+ const SYNCABLE_CAPXUL_ENVS = [
1154
+ "development",
1155
+ "staging",
1156
+ "production"
1157
+ ];
1158
+ /**
1159
+ * Which half of the system emitted the event. REQUIRED alongside `capxul_env`
1160
+ * so a name that two halves can produce (settlement, auth) stays attributable.
1161
+ */
1162
+ const TELEMETRY_PRODUCERS = [
1163
+ "server",
1164
+ "browser",
1165
+ "sdk",
1166
+ "mcp",
1167
+ "e2e"
1168
+ ];
1169
+ /**
1170
+ * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and
1171
+ * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema
1172
+ * decode instead of silently shipping an unattributable event. Call sites do
1173
+ * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,
1174
+ * which is the only place that knows where the process runs.
1175
+ */
1176
+ const TelemetryEnvelopeProps = {
1177
+ capxul_env: Schema.Literals(CAPXUL_ENVS),
1178
+ producer: Schema.Literals(TELEMETRY_PRODUCERS),
1179
+ journey_id: OptionalString,
1180
+ correlation_id: OptionalString,
1181
+ sdk_version: OptionalString
1182
+ };
1183
+ /**
1184
+ * The cause of a failure, flat (ADR-0023 R7–R8). `failure_mode` is the one
1185
+ * word from `@capxul/errors`; the `chain_*` keys are the `ChainCause` when the
1186
+ * failure came from the chain path. Spread into every failure event and posted
1187
+ * on `$exception`, so one PostHog filter finds a cause wherever it was seen.
1188
+ */
1189
+ const FailureModeSchema = Schema.Literals(FAILURE_MODES);
1190
+ const ChainUpstreamSchema = Schema.Literals(CHAIN_UPSTREAMS);
1191
+ /**
1192
+ * The refusing upstream's response headers (#1818): exactly the names in
1193
+ * `RESPONSE_HEADER_ALLOWLIST`, each optional, so the catalog itself refuses a
1194
+ * `set-cookie` or `authorization` that a producer let through.
1195
+ */
1196
+ const ResponseHeadersSchema = Schema.Struct({
1197
+ "retry-after": OptionalString,
1198
+ "www-authenticate": OptionalString,
1199
+ "content-type": OptionalString,
1200
+ "x-request-id": OptionalString,
1201
+ "cf-ray": OptionalString,
1202
+ "x-ratelimit-remaining": OptionalString,
1203
+ "x-ratelimit-reset": OptionalString,
1204
+ server: OptionalString
1205
+ });
1206
+ /** One upstream tried, flat (#1818): the `chain_attempts` entry on every producer's row. */
1207
+ const ChainAttemptSchema = Schema.Struct({
1208
+ upstream: ChainUpstreamSchema,
1209
+ failure_mode: FailureModeSchema,
1210
+ http_status: Schema.optional(Schema.Number),
1211
+ rpc_code: Schema.optional(Schema.Number),
1212
+ duration_ms: Schema.Number
1213
+ });
1214
+ const ChainCauseTelemetryProps = {
1215
+ failure_mode: Schema.optional(FailureModeSchema),
1216
+ chain_upstream: Schema.optional(ChainUpstreamSchema),
1217
+ chain_method: OptionalString,
1218
+ chain_retryable: Schema.optional(Schema.Boolean),
1219
+ chain_http_status: Schema.optional(Schema.Number),
1220
+ chain_rpc_code: Schema.optional(Schema.Number),
1221
+ chain_revert_name: OptionalString,
1222
+ chain_revert_selector: OptionalString,
1223
+ chain_revert_args: Schema.optional(Schema.Record(Schema.String, Schema.String)),
1224
+ chain_provider_message: OptionalString,
1225
+ chain_attempts: Schema.optional(Schema.Array(ChainAttemptSchema)),
1226
+ chain_response_headers: Schema.optional(ResponseHeadersSchema)
1227
+ };
1228
+ /**
1229
+ * Stamp the required envelope onto an event at its emit boundary. Call-site
1230
+ * props win on conflict: a relay that already knows the true producer (the
1231
+ * browser-failure relay stamps `browser` while running on the server) must not
1232
+ * be overwritten by the transport's own default.
1233
+ */
1234
+ function stampTelemetryEnvelope(event, defaults) {
1235
+ return {
1236
+ name: event.name,
1237
+ props: {
1238
+ ...defaults,
1239
+ ...event.props
1240
+ }
1241
+ };
1242
+ }
1243
+ const AuthOtpRequestedProps = Schema.Struct({
1244
+ ...TelemetryEnvelopeProps,
1245
+ email: Schema.optional(PII),
1246
+ email_domain: OptionalString
1247
+ });
1248
+ const AuthOtpDeliveredProps = Schema.Struct({
1249
+ ...TelemetryEnvelopeProps,
1250
+ durationMs: OptionalDurationMs,
1251
+ email: Schema.optional(PII),
1252
+ email_domain: OptionalString,
1253
+ resendMessageId: OptionalString
1254
+ });
1255
+ const AuthOtpExpiredProps = Schema.Struct({
1256
+ ...TelemetryEnvelopeProps,
1257
+ email: Schema.optional(PII),
1258
+ email_domain: OptionalString
1259
+ });
1260
+ const AuthVerifiedProps = Schema.Struct({
1261
+ ...TelemetryEnvelopeProps,
1262
+ auth_type: OptionalString
1263
+ });
1264
+ const AuthFailedProps = Schema.Struct({
1265
+ ...TelemetryEnvelopeProps,
1266
+ ...ChainCauseTelemetryProps,
1267
+ email: Schema.optional(PII),
1268
+ auth_type: OptionalString,
1269
+ reason: OptionalString
1270
+ });
1271
+ const IdentityRefusedProps = Schema.Struct({
1272
+ ...TelemetryEnvelopeProps,
1273
+ /** The refused identity event tag, for example CreateOrganization. */
1274
+ event: OptionalString,
1275
+ /** The machine's refusal code: WRONG_STATE, SUPERSEDED or STALE_EPOCH. */
1276
+ refusal_code: OptionalString,
1277
+ /** The machine slot the request targeted, for example identity:org. */
1278
+ slot: OptionalString,
1279
+ /** The machine state at refusal, for example authenticated:claiming. */
1280
+ state: OptionalString
1281
+ });
1282
+ const AuthSignedOutProps = Schema.Struct(TelemetryEnvelopeProps);
1283
+ const NativeAuthorizationMode = Schema.Literals(["login", "signup"]);
1284
+ const NativeAuthorizationStartedProps = Schema.Struct({
1285
+ ...TelemetryEnvelopeProps,
1286
+ mode: NativeAuthorizationMode
1287
+ });
1288
+ const NativeAuthorizationReviewedProps = Schema.Struct({
1289
+ ...TelemetryEnvelopeProps,
1290
+ mode: NativeAuthorizationMode
1291
+ });
1292
+ const NativeAuthorizationAcceptedProps = Schema.Struct({
1293
+ ...TelemetryEnvelopeProps,
1294
+ mode: NativeAuthorizationMode,
1295
+ /** Whether consent also had to finish account setup first. */
1296
+ setup_state: Schema.optional(Schema.Literals([
1297
+ "not_required",
1298
+ "new",
1299
+ "resumable"
1300
+ ]))
1301
+ });
1302
+ const NativeAuthorizationDeniedProps = Schema.Struct({
1303
+ ...TelemetryEnvelopeProps,
1304
+ mode: NativeAuthorizationMode
1305
+ });
1306
+ const NativeAuthorizationConnectedProps = Schema.Struct({
1307
+ ...TelemetryEnvelopeProps,
1308
+ mode: NativeAuthorizationMode
1309
+ });
1310
+ const NativeAuthorizationFailedProps = Schema.Struct({
1311
+ ...TelemetryEnvelopeProps,
1312
+ mode: Schema.optional(NativeAuthorizationMode),
1313
+ /** The refusal word the store returned, for example `identity_mismatch` or
1314
+ * `request_expired`. These are the closed `CLIENT_AUTHORIZATION_REFUSALS` from
1315
+ * `@capxul/wire` plus the store-internal `fresh_session_required` (ruling R3),
1316
+ * which the continuation maps to `identity_mismatch` on the wire but reports
1317
+ * truthfully here. Kept as `OptionalString` rather than an imported literal
1318
+ * set: this package must not depend on the transport contract. */
1319
+ reason: OptionalString
1320
+ });
1321
+ const ProvisioningSafeCreatedProps = Schema.Struct({
1322
+ ...TelemetryEnvelopeProps,
1323
+ safe_address: OptionalAddress
1324
+ });
1325
+ const ProvisioningSafeConfirmedProps = Schema.Struct({
1326
+ ...TelemetryEnvelopeProps,
1327
+ chainId: OptionalChainId,
1328
+ deployedAt: OptionalEpochMs,
1329
+ deployedAtBlock: OptionalBlockNumber,
1330
+ deployTxHash: OptionalTxHash,
1331
+ durationMs: OptionalDurationMs,
1332
+ safe_address: OptionalAddress,
1333
+ userOpHash: OptionalTxHash
1334
+ });
1335
+ const BootstrapResolvedProps = Schema.Struct({
1336
+ ...TelemetryEnvelopeProps,
1337
+ applicationId: OptionalAppId,
1338
+ durationMs: OptionalDurationMs,
1339
+ env: OptionalString,
1340
+ keyId: OptionalPublishableKeyId,
1341
+ origin: OptionalString
1342
+ });
1343
+ const BootstrapFailedProps = Schema.Struct({
1344
+ ...TelemetryEnvelopeProps,
1345
+ ...ChainCauseTelemetryProps,
1346
+ applicationId: OptionalAppId,
1347
+ durationMs: OptionalDurationMs,
1348
+ origin: OptionalString,
1349
+ provider: OptionalString,
1350
+ provider_operation: OptionalString,
1351
+ reason: OptionalString,
1352
+ target_host: OptionalString
1353
+ });
1354
+ /**
1355
+ * R08 (#1966): which Safe was read, on which chain, of which token. `currency`
1356
+ * is the DISPLAY code the surface shows ("USD"); it never says which ERC-20 the
1357
+ * `balanceOf` actually hit, so a reader could not tell a treasury read from a
1358
+ * personal one, nor one token from another with the same fiat peg. The producer
1359
+ * takes each of these from the authority that already decided it — the verified
1360
+ * Organization row's chain, the configured token address — never from a label.
1361
+ * The verified `organization_id` and its group arrive from the backend
1362
+ * attribution, so they are not repeated here.
1363
+ *
1364
+ * D1 (2026-09-10): `asset_id` carries the canonical branded identity the read
1365
+ * resolved, `eip155:<chainId>/erc20:<lowercase-address>`, from the registry
1366
+ * row. `token_address`/`chain_id` are its parts; `currency` is the peg and a
1367
+ * display code. The producer emits the branded id so the live read can be
1368
+ * grouped by ASSET, never by symbol or peg.
1369
+ */
1370
+ const AccountBalanceReadProps = Schema.Struct({
1371
+ ...TelemetryEnvelopeProps,
1372
+ account_id: OptionalAccountId,
1373
+ account_kind: OptionalAccountKind,
1374
+ chain_id: OptionalChainId,
1375
+ token_address: OptionalAddress,
1376
+ asset_id: OptionalString,
1377
+ currency: OptionalCurrencyCode,
1378
+ balance_bucket: OptionalBalanceBucket,
1379
+ durationMs: OptionalDurationMs
1380
+ });
1381
+ const AccountBalanceFailedProps = Schema.Struct({
1382
+ ...TelemetryEnvelopeProps,
1383
+ ...ChainCauseTelemetryProps,
1384
+ reason: OptionalString
1385
+ });
1386
+ const FaucetRequestedProps = Schema.Struct({
1387
+ ...TelemetryEnvelopeProps,
1388
+ amount: OptionalWeiAmount,
1389
+ chainId: OptionalChainId,
1390
+ asset_id: OptionalString
1391
+ });
1392
+ const FaucetConfirmedProps = Schema.Struct({
1393
+ ...TelemetryEnvelopeProps,
1394
+ amount: OptionalWeiAmount,
1395
+ chainId: OptionalChainId,
1396
+ txHash: OptionalTxHash,
1397
+ asset_id: OptionalString,
1398
+ token_address: OptionalAddress,
1399
+ durationMs: OptionalDurationMs
1400
+ });
1401
+ const FaucetFailedProps = Schema.Struct({
1402
+ ...TelemetryEnvelopeProps,
1403
+ ...ChainCauseTelemetryProps,
1404
+ reason: OptionalString,
1405
+ amount: OptionalWeiAmount,
1406
+ chainId: OptionalChainId,
1407
+ asset_id: OptionalString,
1408
+ token_address: OptionalAddress
1409
+ });
1410
+ const ChainServiceSchema = Schema.Literals(["aa-gateway", "backend"]);
1411
+ const ChainUpstreamFallbackProps = Schema.Struct({
1412
+ ...TelemetryEnvelopeProps,
1413
+ service: ChainServiceSchema,
1414
+ method: Schema.String,
1415
+ from_upstream: ChainUpstreamSchema,
1416
+ to_upstream: Schema.optional(ChainUpstreamSchema),
1417
+ failure_mode: FailureModeSchema,
1418
+ exhausted: Schema.Boolean,
1419
+ http_status: Schema.optional(Schema.Number),
1420
+ rpc_code: Schema.optional(Schema.Number),
1421
+ response_headers: Schema.optional(ResponseHeadersSchema)
1422
+ });
1423
+ const BundlerErrorProps = Schema.Struct({
1424
+ ...TelemetryEnvelopeProps,
1425
+ method: Schema.String,
1426
+ failure_mode: FailureModeSchema,
1427
+ chain_upstream: ChainUpstreamSchema,
1428
+ chain_retryable: Schema.Boolean,
1429
+ http_status: Schema.optional(Schema.Number),
1430
+ rpc_code: Schema.optional(Schema.Number),
1431
+ chain_revert_name: OptionalString,
1432
+ chain_provider_message: OptionalString
1433
+ });
1434
+ const ReceiptPendingProps = Schema.Struct({
1435
+ ...TelemetryEnvelopeProps,
1436
+ service: ChainServiceSchema,
1437
+ method: Schema.String,
1438
+ chain_upstream: ChainUpstreamSchema,
1439
+ reason: Schema.Literals(["zero_block_hash", "no_receipt"])
1440
+ });
1441
+ const OperationRetriedProps = Schema.Struct({
1442
+ ...TelemetryEnvelopeProps,
1443
+ operation: Schema.String,
1444
+ failure_mode: FailureModeSchema,
1445
+ reason: Schema.optional(Schema.Literal("connection-lost-in-flight")),
1446
+ connection_id: OptionalString,
1447
+ connection_count: Schema.optional(Schema.Number),
1448
+ attempt: Schema.Number,
1449
+ delay_ms: DurationMsSchema
1450
+ });
1451
+ const ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;
1452
+ const OrgIdTelemetrySchema = Schema.String.pipe(Schema.refine((value) => ORG_ID_TELEMETRY_RE.test(value), { message: "must be org_ plus an alphanumeric id" }));
1453
+ const OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);
1454
+ const AttemptNumberSchema = Schema.Number.pipe(Schema.refine((value) => Number.isSafeInteger(value) && value > 0, { message: "must be a positive safe integer" }));
1455
+ const OnboardingStageSchema = Schema.Literals([
1456
+ "profile",
1457
+ "accountProvisioning",
1458
+ "accountClaim",
1459
+ "preparingFounderAccount",
1460
+ "awaitingFounderAuthorization",
1461
+ "submittingBootstrap",
1462
+ "confirmingBootstrap"
1463
+ ]);
1464
+ const MemberActivationStartedProps = Schema.Struct({
1465
+ ...TelemetryEnvelopeProps,
1466
+ $insert_id: Schema.String
1467
+ });
1468
+ const MemberActivationReadyProps = Schema.Struct({
1469
+ ...TelemetryEnvelopeProps,
1470
+ $insert_id: Schema.String,
1471
+ duration_ms: DurationMsSchema
1472
+ });
1473
+ const MemberActivationFailedProps = Schema.Struct({
1474
+ ...TelemetryEnvelopeProps,
1475
+ ...ChainCauseTelemetryProps,
1476
+ $insert_id: Schema.String,
1477
+ stage: OnboardingStageSchema,
1478
+ error_code: Schema.String,
1479
+ retryable: Schema.Boolean
1480
+ });
1481
+ const OrganizationCreationStartedProps = Schema.Struct({
1482
+ ...TelemetryEnvelopeProps,
1483
+ $insert_id: Schema.String,
1484
+ organization_id: OrgIdTelemetrySchema,
1485
+ attempt_number: AttemptNumberSchema
1486
+ });
1487
+ const OrganizationCreationReadyProps = Schema.Struct({
1488
+ ...TelemetryEnvelopeProps,
1489
+ $insert_id: Schema.String,
1490
+ organization_id: OrgIdTelemetrySchema,
1491
+ attempt_number: AttemptNumberSchema,
1492
+ duration_ms: DurationMsSchema
1493
+ });
1494
+ const OrganizationCreationFailedProps = Schema.Struct({
1495
+ ...TelemetryEnvelopeProps,
1496
+ ...ChainCauseTelemetryProps,
1497
+ $insert_id: Schema.String,
1498
+ organization_id: OrgIdTelemetrySchema,
1499
+ attempt_number: AttemptNumberSchema,
1500
+ stage: OnboardingStageSchema,
1501
+ error_code: Schema.String,
1502
+ retryable: Schema.Boolean,
1503
+ /** #1655: the SDK's backoff before this attempt. Absent on the first attempt. */
1504
+ backoff_ms: Schema.optional(DurationMsSchema),
1505
+ failure_reason: Schema.optional(Schema.Literals([
1506
+ "deterministic_address_mismatch",
1507
+ "receipt_provider_unavailable",
1508
+ "receipt_mismatch",
1509
+ "block_provider_unavailable",
1510
+ "authority_event_mismatch",
1511
+ "allowance_timestamp_mismatch",
1512
+ "receipt_identity_unavailable",
1513
+ "receipt_identity_mismatch",
1514
+ "contract_code_unavailable",
1515
+ "contract_state_mismatch",
1516
+ "permission_projection_mismatch"
1517
+ ]))
1518
+ });
1519
+ const OnboardingIntentSchema = Schema.Literals(["personal", "organization"]);
1520
+ const OnboardingIntentSelectedProps = Schema.Struct({
1521
+ ...TelemetryEnvelopeProps,
1522
+ journey_id: Schema.String,
1523
+ intent: OnboardingIntentSchema,
1524
+ entry_point: Schema.String
1525
+ });
1526
+ const OnboardingProfileSubmittedProps = Schema.Struct({
1527
+ ...TelemetryEnvelopeProps,
1528
+ journey_id: Schema.String,
1529
+ intent: OnboardingIntentSchema
1530
+ });
1531
+ const OnboardingOrganizationSubmittedProps = Schema.Struct({
1532
+ ...TelemetryEnvelopeProps,
1533
+ journey_id: Schema.String
1534
+ });
1535
+ const OnboardingDashboardReachedProps = Schema.Struct({
1536
+ ...TelemetryEnvelopeProps,
1537
+ journey_id: Schema.String,
1538
+ intent: OnboardingIntentSchema,
1539
+ organization_id: Schema.optional(OrgIdTelemetrySchema)
1540
+ });
1541
+ const OrgCreateStartedProps = Schema.Struct({
1542
+ ...TelemetryEnvelopeProps,
1543
+ org_id: OptionalOrgId,
1544
+ email_domain: OptionalString,
1545
+ template: OptionalString
1546
+ });
1547
+ const OrgSafeCreatedProps = Schema.Struct({
1548
+ ...TelemetryEnvelopeProps,
1549
+ org_id: OptionalOrgId,
1550
+ chainId: OptionalChainId,
1551
+ safe_address: OptionalAddress
1552
+ });
1553
+ const OrgSafeConfirmedProps = Schema.Struct({
1554
+ ...TelemetryEnvelopeProps,
1555
+ org_id: OptionalOrgId,
1556
+ chainId: OptionalChainId,
1557
+ safe_address: OptionalAddress,
1558
+ durationMs: OptionalDurationMs
1559
+ });
1560
+ const OrgRolesSeededProps = Schema.Struct({
1561
+ ...TelemetryEnvelopeProps,
1562
+ org_id: OptionalOrgId,
1563
+ chainId: OptionalChainId,
1564
+ role: OptionalString,
1565
+ txHash: OptionalTxHash
1566
+ });
1567
+ const OrgCreatedProps = Schema.Struct({
1568
+ ...TelemetryEnvelopeProps,
1569
+ org_id: OptionalOrgId,
1570
+ chainId: OptionalChainId,
1571
+ safe_address: OptionalAddress,
1572
+ durationMs: OptionalDurationMs
1573
+ });
1574
+ const OrgCreateFailedProps = Schema.Struct({
1575
+ ...TelemetryEnvelopeProps,
1576
+ ...ChainCauseTelemetryProps,
1577
+ org_id: OptionalOrgId,
1578
+ reason: OptionalString
1579
+ });
1580
+ const OrgInviteSentProps = Schema.Struct({
1581
+ ...TelemetryEnvelopeProps,
1582
+ org_id: OptionalOrgId,
1583
+ invitation_id: OptionalString,
1584
+ generation: OptionalString,
1585
+ command_id: OptionalString,
1586
+ subject_party_id: OptionalString,
1587
+ persisted_at: OptionalEpochMs,
1588
+ email_domain: OptionalString,
1589
+ role: OptionalString,
1590
+ status: OptionalString
1591
+ });
1592
+ const OrgInviteAcceptedProps = Schema.Struct({
1593
+ ...TelemetryEnvelopeProps,
1594
+ org_id: OptionalOrgId,
1595
+ invitation_id: OptionalString,
1596
+ accepted_at: OptionalEpochMs,
1597
+ generation: OptionalString,
1598
+ command_id: OptionalString,
1599
+ subject_party_id: OptionalString,
1600
+ role: OptionalString,
1601
+ status: OptionalString
1602
+ });
1603
+ const OrgInviteExpiredProps = Schema.Struct({
1604
+ ...TelemetryEnvelopeProps,
1605
+ org_id: OptionalOrgId,
1606
+ email_domain: OptionalString,
1607
+ invitation_id: OptionalString,
1608
+ reason: OptionalString,
1609
+ role: OptionalString,
1610
+ status: OptionalString
1611
+ });
1612
+ const RecipientLocatorKindSchema = Schema.Literals([
1613
+ "handle",
1614
+ "email",
1615
+ "address",
1616
+ "party"
1617
+ ]);
1618
+ const RecipientResolutionStatusSchema = Schema.Literals([
1619
+ "known_party",
1620
+ "new_email",
1621
+ "external_address"
1622
+ ]);
1623
+ const RecipientPartyKindSchema = Schema.Literals([
1624
+ "person",
1625
+ "organization",
1626
+ "unresolved"
1627
+ ]);
1628
+ const RecipientTelemetryProps = {
1629
+ recipient_locator_kind: Schema.optional(RecipientLocatorKindSchema),
1630
+ recipient_resolution_status: Schema.optional(RecipientResolutionStatusSchema),
1631
+ recipient_party_id: OptionalString,
1632
+ recipient_party_kind: Schema.optional(RecipientPartyKindSchema),
1633
+ recipient_is_capxul_account: Schema.optional(Schema.Boolean),
1634
+ recipient_handle: OptionalString,
1635
+ recipient_address: OptionalAddress,
1636
+ external_address_acknowledged: Schema.optional(Schema.Boolean)
1637
+ };
1638
+ const PaymentInitiatedProps = Schema.Struct({
1639
+ command_id: OptionalString,
1640
+ execution_id: OptionalString,
1641
+ payment_lifecycle_id: OptionalString,
1642
+ ...TelemetryEnvelopeProps,
1643
+ ...RecipientTelemetryProps,
1644
+ kind: Schema.String,
1645
+ payment_id: Schema.String
1646
+ });
1647
+ const PaymentLifecycleProps = {
1648
+ payment_state: OptionalString,
1649
+ execution_state: OptionalString,
1650
+ occurred_at: Schema.optional(Schema.Number),
1651
+ causal_sequence: Schema.optional(Schema.Number),
1652
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1653
+ terminal_event_id: OptionalString
1654
+ };
1655
+ const PaymentSettledL2Props = Schema.Struct({
1656
+ ...PaymentLifecycleProps,
1657
+ ...TelemetryEnvelopeProps,
1658
+ ...RecipientTelemetryProps,
1659
+ kind: Schema.String,
1660
+ chain_id: Schema.Number,
1661
+ settlement_id: Schema.String,
1662
+ payment_id: OptionalString,
1663
+ payment_ids: OptionalString,
1664
+ command_id: OptionalString,
1665
+ payment_lifecycle_id: OptionalString,
1666
+ execution_id: OptionalString,
1667
+ user_op_hash: OptionalString,
1668
+ transaction_hash: OptionalString
1669
+ });
1670
+ const PaymentFailedL2Props = Schema.Struct({
1671
+ ...PaymentLifecycleProps,
1672
+ ...TelemetryEnvelopeProps,
1673
+ ...ChainCauseTelemetryProps,
1674
+ ...RecipientTelemetryProps,
1675
+ kind: Schema.String,
1676
+ payment_id: Schema.String,
1677
+ payment_ids: OptionalString,
1678
+ reason_code: Schema.String,
1679
+ command_id: OptionalString,
1680
+ payment_lifecycle_id: OptionalString,
1681
+ execution_id: OptionalString,
1682
+ user_op_hash: OptionalString
1683
+ });
1684
+ const PaymentVerificationRetryProps = Schema.Struct({
1685
+ ...PaymentLifecycleProps,
1686
+ ...TelemetryEnvelopeProps,
1687
+ ...RecipientTelemetryProps,
1688
+ command_id: Schema.String,
1689
+ payment_lifecycle_id: Schema.String,
1690
+ attempt: Schema.Number,
1691
+ reason_code: Schema.String,
1692
+ chain_id: Schema.Number,
1693
+ delay_ms: DurationMsSchema,
1694
+ outcome: Schema.Literals(["scheduled", "unresolved"]),
1695
+ payment_id: OptionalString,
1696
+ payment_ids: OptionalString,
1697
+ execution_id: OptionalString,
1698
+ user_op_hash: OptionalString
1699
+ });
1700
+ const PaymentLifecycleTransitionProps = Schema.Struct({
1701
+ ...TelemetryEnvelopeProps,
1702
+ ...RecipientTelemetryProps,
1703
+ payment_id: Schema.String,
1704
+ payment_lifecycle_id: Schema.String,
1705
+ command_id: Schema.String,
1706
+ payment_state: Schema.String,
1707
+ occurred_at: Schema.Number,
1708
+ causal_sequence: Schema.Number,
1709
+ execution_id: OptionalString,
1710
+ execution_state: OptionalString,
1711
+ user_op_hash: OptionalString,
1712
+ sponsorship_valid_until: Schema.optional(Schema.Number),
1713
+ reason_code: OptionalString
1714
+ });
1715
+ const QuickPayExternalAddressAcknowledgedProps = Schema.Struct({
1716
+ ...TelemetryEnvelopeProps,
1717
+ recipient_locator_kind: Schema.Literal("address"),
1718
+ recipient_resolution_status: Schema.Literal("external_address"),
1719
+ recipient_address: AddressSchema,
1720
+ external_address_acknowledged: Schema.Literal(true),
1721
+ organization_id: OptionalOrgId
1722
+ });
1723
+ const DepositInitiatedProps = Schema.Struct({
1724
+ ...TelemetryEnvelopeProps,
1725
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1726
+ account_kind: Schema.optional(Schema.Literals(["personalSafe", "orgTreasury"])),
1727
+ chain_id: Schema.optional(Schema.Number),
1728
+ network: Schema.optional(Schema.Literal("base-sepolia")),
1729
+ organization_id: OptionalOrgId,
1730
+ $groups: Schema.optional(Schema.Struct({ organization: OptionalOrgId })),
1731
+ actor_id: OptionalString,
1732
+ actor_kind: Schema.optional(Schema.Literal("authenticated")),
1733
+ distinct_id: OptionalString,
1734
+ trace_id: OptionalString,
1735
+ span_id: OptionalString
1736
+ });
1737
+ const DepositSettledProps = Schema.Struct({
1738
+ ...TelemetryEnvelopeProps,
1739
+ chain_id: Schema.Number,
1740
+ tx_hash: Schema.String,
1741
+ log_index: Schema.Number
1742
+ });
1743
+ const PermissionMirrorVerificationProps = Schema.Struct({
1744
+ ...TelemetryEnvelopeProps,
1745
+ /** The RECEIPT verification outcome. What the mirror then did is separate. */
1746
+ outcome: Schema.String,
1747
+ reason: Schema.String,
1748
+ chain_id: Schema.Number,
1749
+ retry_count: Schema.Number,
1750
+ /**
1751
+ * #1960 R02, consumed by R03. A verified receipt is not an applied Permission:
1752
+ * these two optional fields let the producer say what the applying mutation
1753
+ * actually returned, and which command it was, without either fact rewriting
1754
+ * the receipt outcome above. Absent when application has not happened yet.
1755
+ */
1756
+ application_result: Schema.optional(Schema.Literals([
1757
+ "applied",
1758
+ "replayed",
1759
+ "conflicting_replay",
1760
+ "revision_mismatch",
1761
+ "cleanup_required",
1762
+ "not_applied",
1763
+ "application_failure",
1764
+ "mismatch",
1765
+ "refused"
1766
+ ])),
1767
+ command_kind: Schema.optional(Schema.Literals(["invitation_configuration", "invitation_eoa"])),
1768
+ command_id: OptionalString,
1769
+ invitation_id: OptionalString,
1770
+ generation: OptionalString,
1771
+ purpose: Schema.optional(Schema.Literals([
1772
+ "configure",
1773
+ "grant",
1774
+ "disable",
1775
+ "compensate"
1776
+ ])),
1777
+ $insert_id: OptionalString,
1778
+ /**
1779
+ * #1961 R03. The authorized stored row names the Permission it changed; the
1780
+ * verified receipt names the chain facts that prove it. Every field is
1781
+ * optional because a pending or provider-failed verification has neither an
1782
+ * application result nor a receipt to report.
1783
+ */
1784
+ permission_id: OptionalString,
1785
+ permission_assignment_id: OptionalString,
1786
+ permission_operation: Schema.optional(Schema.Literals([
1787
+ "create",
1788
+ "change",
1789
+ "assign",
1790
+ "revoke",
1791
+ "replace"
1792
+ ])),
1793
+ revision: Schema.optional(Schema.Number),
1794
+ user_op_hash: OptionalString,
1795
+ transaction_hash: OptionalString,
1796
+ block_number: Schema.optional(Schema.Number),
1797
+ log_index: Schema.optional(Schema.Number)
1798
+ });
1799
+ const MovementScanWindowProps = Schema.Struct({
1800
+ ...TelemetryEnvelopeProps,
1801
+ chain_id: Schema.Number,
1802
+ token_address: Schema.String,
1803
+ from_block: Schema.Number,
1804
+ to_block: Schema.Number,
1805
+ log_count: Schema.Number,
1806
+ request_count: Schema.Number,
1807
+ outcome: Schema.String
1808
+ });
1809
+ const MovementScanCheckpointProps = Schema.Struct({
1810
+ ...TelemetryEnvelopeProps,
1811
+ chain_id: Schema.Number,
1812
+ token_address: Schema.String,
1813
+ next_block: Schema.Number,
1814
+ anchor_block_number: Schema.Number
1815
+ });
1816
+ const MovementScanIncidentProps = Schema.Struct({
1817
+ ...TelemetryEnvelopeProps,
1818
+ chain_id: Schema.Number,
1819
+ token_address: Schema.String,
1820
+ incident_kind: Schema.String,
1821
+ anchor_block_number: Schema.Number
1822
+ });
1823
+ /**
1824
+ * One durable row the reconciliation job corrected against Ponder (SPEC D9).
1825
+ *
1826
+ * Both block fields are optional and for the same reason: a correction INTO
1827
+ * drift (a Payment settled in Convex whose Ponder fact a reorg removed) has no
1828
+ * current block, and a correction that confirms a later fact has one.
1829
+ *
1830
+ * `projection_kind` is closed. A later ticket that reconciles a deploy, a
1831
+ * bootstrap or a grant outcome adds its kind here in the same change; an
1832
+ * unknown kind must not decode.
1833
+ */
1834
+ const IndexerDriftCorrectedProps = Schema.Struct({
1835
+ ...TelemetryEnvelopeProps,
1836
+ projection_kind: Schema.Literals([
1837
+ "member_authority",
1838
+ "payment_settlement",
1839
+ "permission_assignment"
1840
+ ]),
1841
+ previous_state: Schema.String,
1842
+ current_state: Schema.String,
1843
+ previous_block: Schema.optional(Schema.Number),
1844
+ current_block: Schema.optional(Schema.Number),
1845
+ logical_event_id: Schema.optional(Schema.String),
1846
+ scope_kind: Schema.optional(Schema.Literals(["account", "organization"])),
1847
+ account_id: OptionalAccountId,
1848
+ reference_id: OptionalString
1849
+ });
1850
+ const AuthOtpRequestedTelemetryEventSchema = Schema.Struct({
1851
+ name: Schema.Literal("auth_otp_requested"),
1852
+ props: AuthOtpRequestedProps
1853
+ });
1854
+ const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({
1855
+ name: Schema.Literal("auth_otp_delivered"),
1856
+ props: AuthOtpDeliveredProps
1857
+ });
1858
+ const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({
1859
+ name: Schema.Literal("auth_otp_expired"),
1860
+ props: AuthOtpExpiredProps
1861
+ });
1862
+ const AuthVerifiedTelemetryEventSchema = Schema.Struct({
1863
+ name: Schema.Literal("auth_verified"),
1864
+ props: AuthVerifiedProps
1865
+ });
1866
+ const AuthFailedTelemetryEventSchema = Schema.Struct({
1867
+ name: Schema.Literal("auth_failed"),
1868
+ props: AuthFailedProps
1869
+ });
1870
+ const IdentityRefusedTelemetryEventSchema = Schema.Struct({
1871
+ name: Schema.Literal("identity_refused"),
1872
+ props: IdentityRefusedProps
1873
+ });
1874
+ const AuthSignedOutTelemetryEventSchema = Schema.Struct({
1875
+ name: Schema.Literal("auth_signed_out"),
1876
+ props: AuthSignedOutProps
1877
+ });
1878
+ const NativeAuthorizationStartedTelemetryEventSchema = Schema.Struct({
1879
+ name: Schema.Literal("native_authorization_started"),
1880
+ props: NativeAuthorizationStartedProps
1881
+ });
1882
+ const NativeAuthorizationReviewedTelemetryEventSchema = Schema.Struct({
1883
+ name: Schema.Literal("native_authorization_reviewed"),
1884
+ props: NativeAuthorizationReviewedProps
1885
+ });
1886
+ const NativeAuthorizationAcceptedTelemetryEventSchema = Schema.Struct({
1887
+ name: Schema.Literal("native_authorization_accepted"),
1888
+ props: NativeAuthorizationAcceptedProps
1889
+ });
1890
+ const NativeAuthorizationDeniedTelemetryEventSchema = Schema.Struct({
1891
+ name: Schema.Literal("native_authorization_denied"),
1892
+ props: NativeAuthorizationDeniedProps
1893
+ });
1894
+ const NativeAuthorizationConnectedTelemetryEventSchema = Schema.Struct({
1895
+ name: Schema.Literal("native_authorization_connected"),
1896
+ props: NativeAuthorizationConnectedProps
1897
+ });
1898
+ const NativeAuthorizationFailedTelemetryEventSchema = Schema.Struct({
1899
+ name: Schema.Literal("native_authorization_failed"),
1900
+ props: NativeAuthorizationFailedProps
1901
+ });
1902
+ const OnboardingIntentSelectedTelemetryEventSchema = Schema.Struct({
1903
+ name: Schema.Literal("onboarding_intent_selected"),
1904
+ props: OnboardingIntentSelectedProps
1905
+ });
1906
+ const OnboardingProfileSubmittedTelemetryEventSchema = Schema.Struct({
1907
+ name: Schema.Literal("onboarding_profile_submitted"),
1908
+ props: OnboardingProfileSubmittedProps
1909
+ });
1910
+ const OnboardingOrganizationSubmittedTelemetryEventSchema = Schema.Struct({
1911
+ name: Schema.Literal("onboarding_organization_submitted"),
1912
+ props: OnboardingOrganizationSubmittedProps
1913
+ });
1914
+ const OnboardingDashboardReachedTelemetryEventSchema = Schema.Struct({
1915
+ name: Schema.Literal("onboarding_dashboard_reached"),
1916
+ props: OnboardingDashboardReachedProps
1917
+ });
1918
+ const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({
1919
+ name: Schema.Literal("provisioning_safe_created"),
1920
+ props: ProvisioningSafeCreatedProps
1921
+ });
1922
+ const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({
1923
+ name: Schema.Literal("provisioning_safe_confirmed"),
1924
+ props: ProvisioningSafeConfirmedProps
1925
+ });
1926
+ const BootstrapResolvedTelemetryEventSchema = Schema.Struct({
1927
+ name: Schema.Literal("bootstrap_resolved"),
1928
+ props: BootstrapResolvedProps
1929
+ });
1930
+ const BootstrapFailedTelemetryEventSchema = Schema.Struct({
1931
+ name: Schema.Literal("bootstrap_failed"),
1932
+ props: BootstrapFailedProps
1933
+ });
1934
+ const MemberActivationStartedTelemetryEventSchema = Schema.Struct({
1935
+ name: Schema.Literal("member_activation_started"),
1936
+ props: MemberActivationStartedProps
1937
+ });
1938
+ const MemberActivationReadyTelemetryEventSchema = Schema.Struct({
1939
+ name: Schema.Literal("member_activation_ready"),
1940
+ props: MemberActivationReadyProps
1941
+ });
1942
+ const MemberActivationFailedTelemetryEventSchema = Schema.Struct({
1943
+ name: Schema.Literal("member_activation_failed"),
1944
+ props: MemberActivationFailedProps
1945
+ });
1946
+ const OrganizationCreationStartedTelemetryEventSchema = Schema.Struct({
1947
+ name: Schema.Literal("organization_creation_started"),
1948
+ props: OrganizationCreationStartedProps
1949
+ });
1950
+ const OrganizationCreationReadyTelemetryEventSchema = Schema.Struct({
1951
+ name: Schema.Literal("organization_creation_ready"),
1952
+ props: OrganizationCreationReadyProps
1953
+ });
1954
+ const OrganizationCreationFailedTelemetryEventSchema = Schema.Struct({
1955
+ name: Schema.Literal("organization_creation_failed"),
1956
+ props: OrganizationCreationFailedProps
1957
+ });
1958
+ const AccountBalanceReadTelemetryEventSchema = Schema.Struct({
1959
+ name: Schema.Literal("account_balance_read"),
1960
+ props: AccountBalanceReadProps
1961
+ });
1962
+ const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({
1963
+ name: Schema.Literal("account_balance_failed"),
1964
+ props: AccountBalanceFailedProps
1965
+ });
1966
+ const FaucetRequestedTelemetryEventSchema = Schema.Struct({
1967
+ name: Schema.Literal("faucet_requested"),
1968
+ props: FaucetRequestedProps
1969
+ });
1970
+ const FaucetConfirmedTelemetryEventSchema = Schema.Struct({
1971
+ name: Schema.Literal("faucet_confirmed"),
1972
+ props: FaucetConfirmedProps
1973
+ });
1974
+ const FaucetFailedTelemetryEventSchema = Schema.Struct({
1975
+ name: Schema.Literal("faucet_failed"),
1976
+ props: FaucetFailedProps
1977
+ });
1978
+ const ChainUpstreamFallbackTelemetryEventSchema = Schema.Struct({
1979
+ name: Schema.Literal("chain_upstream_fallback"),
1980
+ props: ChainUpstreamFallbackProps
1981
+ });
1982
+ const BundlerErrorTelemetryEventSchema = Schema.Struct({
1983
+ name: Schema.Literal("bundler_error"),
1984
+ props: BundlerErrorProps
1985
+ });
1986
+ const ReceiptPendingTelemetryEventSchema = Schema.Struct({
1987
+ name: Schema.Literal("receipt_pending"),
1988
+ props: ReceiptPendingProps
1989
+ });
1990
+ const OperationRetriedTelemetryEventSchema = Schema.Struct({
1991
+ name: Schema.Literal("operation_retried"),
1992
+ props: OperationRetriedProps
1993
+ });
1994
+ const OrgCreateStartedTelemetryEventSchema = Schema.Struct({
1995
+ name: Schema.Literal("org_create_started"),
1996
+ props: OrgCreateStartedProps
1997
+ });
1998
+ const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({
1999
+ name: Schema.Literal("org_safe_created"),
2000
+ props: OrgSafeCreatedProps
2001
+ });
2002
+ const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({
2003
+ name: Schema.Literal("org_safe_confirmed"),
2004
+ props: OrgSafeConfirmedProps
2005
+ });
2006
+ const OrgRolesSeededTelemetryEventSchema = Schema.Struct({
2007
+ name: Schema.Literal("org_roles_seeded"),
2008
+ props: OrgRolesSeededProps
2009
+ });
2010
+ const OrgCreatedTelemetryEventSchema = Schema.Struct({
2011
+ name: Schema.Literal("org_created"),
2012
+ props: OrgCreatedProps
2013
+ });
2014
+ const OrgCreateFailedTelemetryEventSchema = Schema.Struct({
2015
+ name: Schema.Literal("org_create_failed"),
2016
+ props: OrgCreateFailedProps
2017
+ });
2018
+ const OrgInviteSentTelemetryEventSchema = Schema.Struct({
2019
+ name: Schema.Literal("org_invite_sent"),
2020
+ props: OrgInviteSentProps
2021
+ });
2022
+ const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({
2023
+ name: Schema.Literal("org_invite_accepted"),
2024
+ props: OrgInviteAcceptedProps
2025
+ });
2026
+ const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({
2027
+ name: Schema.Literal("org_invite_expired"),
2028
+ props: OrgInviteExpiredProps
2029
+ });
2030
+ const PaymentInitiatedTelemetryEventSchema = Schema.Struct({
2031
+ name: Schema.Literal("payment_initiated"),
2032
+ props: PaymentInitiatedProps
2033
+ });
2034
+ const PaymentSettledTelemetryEventSchema = Schema.Struct({
2035
+ name: Schema.Literal("payment_settled"),
2036
+ props: PaymentSettledL2Props
2037
+ });
2038
+ const PaymentFailedTelemetryEventSchema = Schema.Struct({
2039
+ name: Schema.Literal("payment_failed"),
2040
+ props: PaymentFailedL2Props
2041
+ });
2042
+ const PaymentVerificationRetryTelemetryEventSchema = Schema.Struct({
2043
+ name: Schema.Literal("payment_verification_retry"),
2044
+ props: PaymentVerificationRetryProps
2045
+ });
2046
+ const PaymentLifecycleTransitionTelemetryEventSchema = Schema.Struct({
2047
+ name: Schema.Literal("payment_lifecycle_transition"),
2048
+ props: PaymentLifecycleTransitionProps
2049
+ });
2050
+ const QuickPayExternalAddressAcknowledgedTelemetryEventSchema = Schema.Struct({
2051
+ name: Schema.Literal("quick_pay_external_address_acknowledged"),
2052
+ props: QuickPayExternalAddressAcknowledgedProps
2053
+ });
2054
+ const DepositInitiatedTelemetryEventSchema = Schema.Struct({
2055
+ name: Schema.Literal("deposit_initiated"),
2056
+ props: DepositInitiatedProps
2057
+ });
2058
+ const DepositSettledTelemetryEventSchema = Schema.Struct({
2059
+ name: Schema.Literal("deposit_settled"),
2060
+ props: DepositSettledProps
2061
+ });
2062
+ const PermissionMirrorVerificationTelemetryEventSchema = Schema.Struct({
2063
+ name: Schema.Literal("permission_mirror_verification"),
2064
+ props: PermissionMirrorVerificationProps
2065
+ });
2066
+ const MovementScanWindowTelemetryEventSchema = Schema.Struct({
2067
+ name: Schema.Literal("movement_scan_window"),
2068
+ props: MovementScanWindowProps
2069
+ });
2070
+ const MovementScanCheckpointTelemetryEventSchema = Schema.Struct({
2071
+ name: Schema.Literal("movement_scan_checkpoint"),
2072
+ props: MovementScanCheckpointProps
2073
+ });
2074
+ const MovementScanIncidentTelemetryEventSchema = Schema.Struct({
2075
+ name: Schema.Literal("movement_scan_incident"),
2076
+ props: MovementScanIncidentProps
2077
+ });
2078
+ const IndexerDriftCorrectedTelemetryEventSchema = Schema.Struct({
2079
+ name: Schema.Literal("indexer_drift_corrected"),
2080
+ props: IndexerDriftCorrectedProps
2081
+ });
2082
+ /** The one spelling of "whose scope did this happen in" across every surface. */
2083
+ const ScopeKindSchema = Schema.Literals(["account", "organization"]);
2084
+ const OptionalReasonCode = Schema.optional(Schema.Literals(CAPXUL_ERROR_CODES));
2085
+ const ActivityReferenceProps = {
2086
+ reference_kind: Schema.Literals(["payment", "movement"]),
2087
+ reference_id: Schema.String
2088
+ };
2089
+ const ActivityFilterProps = {
2090
+ filter_kind: Schema.optional(Schema.Literals([
2091
+ "all",
2092
+ "payment",
2093
+ "movement"
2094
+ ])),
2095
+ filter_direction: Schema.optional(Schema.Literals([
2096
+ "all",
2097
+ "in",
2098
+ "out",
2099
+ "self"
2100
+ ])),
2101
+ filter_status: Schema.optional(Schema.Array(Schema.Literals([
2102
+ "pending",
2103
+ "settling",
2104
+ "unresolved",
2105
+ "pending_claim",
2106
+ "scheduled",
2107
+ "streaming",
2108
+ "settled",
2109
+ "cancelled",
2110
+ "failed"
2111
+ ])))
2112
+ };
2113
+ const ActivityActionProps = {
2114
+ ...TelemetryEnvelopeProps,
2115
+ scope_kind: ScopeKindSchema,
2116
+ reason_code: OptionalReasonCode
2117
+ };
2118
+ const ContactRelationshipChangedTelemetryEventSchema = Schema.Struct({
2119
+ name: Schema.Literal("contact_relationship_changed"),
2120
+ props: Schema.Struct({
2121
+ ...TelemetryEnvelopeProps,
2122
+ change: Schema.Literals([
2123
+ "added",
2124
+ "renamed",
2125
+ "hidden",
2126
+ "restored"
2127
+ ]),
2128
+ scope_kind: ScopeKindSchema,
2129
+ scope_id: Schema.String,
2130
+ owner_party_id: Schema.String,
2131
+ party_id: Schema.String,
2132
+ hidden: Schema.Boolean,
2133
+ occurred_at: Schema.Number,
2134
+ operation: Schema.Literals([
2135
+ CAPXUL_OPERATIONS.addressBook.add,
2136
+ CAPXUL_OPERATIONS.addressBook.label,
2137
+ CAPXUL_OPERATIONS.addressBook.hide,
2138
+ CAPXUL_OPERATIONS.addressBook.unhide
2139
+ ])
2140
+ })
2141
+ });
2142
+ const ContactActionProps = {
2143
+ ...TelemetryEnvelopeProps,
2144
+ scope_kind: ScopeKindSchema,
2145
+ party_id: OptionalString,
2146
+ reason_code: OptionalReasonCode
2147
+ };
2148
+ /** One completed online CLI diagnostic. No command input or provider text. */
2149
+ const CLI_COMMAND_NAMES = [
2150
+ "capxul",
2151
+ "doctor",
2152
+ "telemetry",
2153
+ "telemetry.status",
2154
+ "telemetry.enable",
2155
+ "telemetry.disable",
2156
+ "auth",
2157
+ "auth.login",
2158
+ "auth.signup",
2159
+ "auth.send",
2160
+ "auth.verify",
2161
+ "auth.profile",
2162
+ "auth.status",
2163
+ "auth.logout",
2164
+ "contact",
2165
+ "contact.list",
2166
+ "contact.get",
2167
+ "contact.add",
2168
+ "contact.label",
2169
+ "contact.hide",
2170
+ "contact.unhide",
2171
+ "org",
2172
+ CAPXUL_OPERATIONS.org.list,
2173
+ "org.use",
2174
+ "org.status",
2175
+ CAPXUL_OPERATIONS.org.me,
2176
+ CAPXUL_OPERATIONS.org.members,
2177
+ "org.member",
2178
+ "org.member.get",
2179
+ "org.member.invite",
2180
+ "org.contact",
2181
+ "org.contact.list",
2182
+ "org.contact.get",
2183
+ "org.contact.add",
2184
+ "org.contact.label",
2185
+ "org.contact.hide",
2186
+ "org.contact.unhide",
2187
+ CAPXUL_OPERATIONS.org.invite,
2188
+ "org.invite.list",
2189
+ "org.invite.get",
2190
+ "org.invite.wait",
2191
+ "org.invite.review",
2192
+ "org.invite.accept",
2193
+ "org.invite.decline",
2194
+ "org.invite.cancel",
2195
+ "org.invite.resend",
2196
+ "org.invite.retry",
2197
+ "org.wait",
2198
+ CAPXUL_OPERATIONS.org.create,
2199
+ CAPXUL_OPERATIONS.org.retry,
2200
+ "unknown"
2201
+ ];
2202
+ const CLI_CAPABILITIES = [
2203
+ "cli",
2204
+ "diagnostics",
2205
+ "collection",
2206
+ "authentication",
2207
+ "organization",
2208
+ "contacts"
2209
+ ];
2210
+ const CLI_INVOCATION_KINDS = [
2211
+ "command",
2212
+ "help",
2213
+ "version",
2214
+ "completion",
2215
+ "parse_refusal",
2216
+ "collection_control"
2217
+ ];
2218
+ const CliRelease = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u));
2219
+ const CliInvocationProps = {
2220
+ ...TelemetryEnvelopeProps,
2221
+ schema_version: Schema.Literal(1),
2222
+ command: Schema.Literals(CLI_COMMAND_NAMES),
2223
+ capability: Schema.Literals(CLI_CAPABILITIES),
2224
+ invocation_kind: Schema.Literals(CLI_INVOCATION_KINDS),
2225
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2226
+ cli_identity_kind: Schema.optional(Schema.Literals(["anonymous", "identified"])),
2227
+ anonymous_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u))),
2228
+ auth_user_id: Schema.optional(Schema.String.check(Schema.isPattern(/^[^\s]{1,256}$/u))),
2229
+ occurred_at: Schema.Number,
2230
+ cli_version: CliRelease,
2231
+ sdk_version: CliRelease,
2232
+ release: CliRelease,
2233
+ platform: Schema.Literals([
2234
+ "darwin",
2235
+ "linux",
2236
+ "unknown"
2237
+ ]),
2238
+ architecture: Schema.Literals([
2239
+ "arm64",
2240
+ "x64",
2241
+ "unknown"
2242
+ ]),
2243
+ ci: Schema.Boolean,
2244
+ tty: Schema.Boolean,
2245
+ output_mode: Schema.Literals(["human", "json"])
2246
+ };
2247
+ const CliFirstUsedTelemetryEventSchema = Schema.Struct({
2248
+ name: Schema.Literal("cli_first_used"),
2249
+ props: Schema.Struct(CliInvocationProps)
2250
+ });
2251
+ const CliCommandStartedTelemetryEventSchema = Schema.Struct({
2252
+ name: Schema.Literal("cli_command_started"),
2253
+ props: Schema.Struct({
2254
+ ...CliInvocationProps,
2255
+ invocation_kind: Schema.Literals([
2256
+ "command",
2257
+ "help",
2258
+ "version"
2259
+ ])
2260
+ })
2261
+ });
2262
+ const CliCommandCompletedTelemetryEventSchema = Schema.Struct({
2263
+ name: Schema.Literal("cli_command_completed"),
2264
+ props: Schema.Struct({
2265
+ ...CliInvocationProps,
2266
+ outcome: Schema.Literals([
2267
+ "succeeded",
2268
+ "refused",
2269
+ "failed",
2270
+ "cancelled"
2271
+ ]),
2272
+ duration_ms: Schema.Number,
2273
+ error_code: Schema.optional(Schema.Literals([
2274
+ ...CAPXUL_ERROR_CODES,
2275
+ "CLI_USAGE",
2276
+ "CLI_CONFIG",
2277
+ "CLI_STORAGE",
2278
+ "CLI_DEFECT"
2279
+ ]))
2280
+ })
2281
+ });
2282
+ const CliDiagnosticCompletedTelemetryEventSchema = Schema.Struct({
2283
+ name: Schema.Literal("cli_diagnostic_completed"),
2284
+ props: Schema.Struct({
2285
+ ...TelemetryEnvelopeProps,
2286
+ outcome: Schema.Literals([
2287
+ "succeeded",
2288
+ "refused",
2289
+ "failed",
2290
+ "cancelled"
2291
+ ]),
2292
+ invocation_id: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u)),
2293
+ cli_version: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u))
2294
+ })
2295
+ });
2296
+ const UiContactActionCompletedTelemetryEventSchema = Schema.Struct({
2297
+ name: Schema.Literal("ui_contact_action_completed"),
2298
+ props: Schema.Union([
2299
+ Schema.Struct({
2300
+ ...ContactActionProps,
2301
+ action: Schema.Literal("add"),
2302
+ outcome: Schema.Literals(["opened", "cancelled"])
2303
+ }),
2304
+ Schema.Struct({
2305
+ ...ContactActionProps,
2306
+ action: Schema.Literal("refusal"),
2307
+ outcome: Schema.Literal("displayed")
2308
+ }),
2309
+ Schema.Struct({
2310
+ ...ContactActionProps,
2311
+ action: Schema.Literal("retry"),
2312
+ outcome: Schema.Literal("requested")
2313
+ })
2314
+ ])
2315
+ });
2316
+ const ActivityAnnotationSavedTelemetryEventSchema = Schema.Struct({
2317
+ name: Schema.Literal("activity_annotation_saved"),
2318
+ props: Schema.Struct({
2319
+ ...TelemetryEnvelopeProps,
2320
+ ...ActivityReferenceProps,
2321
+ scope_kind: ScopeKindSchema,
2322
+ scope_id: Schema.String,
2323
+ occurred_at: Schema.Number
2324
+ })
2325
+ });
2326
+ const UiActivityActionCompletedTelemetryEventSchema = Schema.Struct({
2327
+ name: Schema.Literal("ui_activity_action_completed"),
2328
+ props: Schema.Union([
2329
+ Schema.Struct({
2330
+ ...ActivityActionProps,
2331
+ action: Schema.Literal("read"),
2332
+ outcome: Schema.Literals(["partial_displayed", "recovered"]),
2333
+ surface: Schema.Literals([
2334
+ "transactions",
2335
+ "recent",
2336
+ "summary"
2337
+ ])
2338
+ }),
2339
+ Schema.Struct({
2340
+ ...ActivityActionProps,
2341
+ ...ActivityFilterProps,
2342
+ action: Schema.Literal("filter"),
2343
+ outcome: Schema.Literal("committed")
2344
+ }),
2345
+ Schema.Struct({
2346
+ ...ActivityActionProps,
2347
+ action: Schema.Literal("refusal"),
2348
+ outcome: Schema.Literal("displayed")
2349
+ }),
2350
+ Schema.Struct({
2351
+ ...ActivityActionProps,
2352
+ action: Schema.Literal("retry"),
2353
+ outcome: Schema.Literal("requested")
2354
+ }),
2355
+ Schema.Struct({
2356
+ ...ActivityActionProps,
2357
+ ...ActivityReferenceProps,
2358
+ action: Schema.Literal("detail"),
2359
+ outcome: Schema.Literals(["opened", "failed"])
2360
+ }),
2361
+ Schema.Struct({
2362
+ ...ActivityActionProps,
2363
+ ...ActivityReferenceProps,
2364
+ action: Schema.Literal("receipt"),
2365
+ outcome: Schema.Literals([
2366
+ "document_rendered",
2367
+ "explorer_opened",
2368
+ "popup_blocked",
2369
+ "failed"
2370
+ ])
2371
+ }),
2372
+ Schema.Struct({
2373
+ ...ActivityActionProps,
2374
+ ...ActivityFilterProps,
2375
+ action: Schema.Literal("export"),
2376
+ outcome: Schema.Literals([
2377
+ "completed",
2378
+ "partial",
2379
+ "failed"
2380
+ ]),
2381
+ row_count: Schema.optional(Schema.Number),
2382
+ truncated: Schema.optional(Schema.Boolean)
2383
+ })
2384
+ ])
2385
+ });
2386
+ /**
2387
+ * Reliability closeout (#1960 R02) — the shape every explicit UI observation
2388
+ * below shares. `scope_kind` says whose surface the person was looking at,
2389
+ * `organization_id` is the verified Organization the producer resolved (absent
2390
+ * on a personal action), and `reason_code` is a catalog error code, never copy.
2391
+ */
2392
+ const UiStepProps = {
2393
+ ...TelemetryEnvelopeProps,
2394
+ scope_kind: ScopeKindSchema,
2395
+ organization_id: OptionalOrgId,
2396
+ reason_code: OptionalReasonCode
2397
+ };
2398
+ const AccessRecoveryCompletedProps = Schema.Union([Schema.Struct({
2399
+ ...TelemetryEnvelopeProps,
2400
+ recovery: Schema.Literal("session_restoration"),
2401
+ outcome: Schema.Literals([
2402
+ "restored",
2403
+ "absent",
2404
+ "failed"
2405
+ ]),
2406
+ reason_code: OptionalReasonCode,
2407
+ organization_id: OptionalOrgId
2408
+ }), Schema.Struct({
2409
+ ...TelemetryEnvelopeProps,
2410
+ recovery: Schema.Literal("signer_readiness"),
2411
+ outcome: Schema.Literals(["ready", "unavailable"]),
2412
+ reason_code: OptionalReasonCode,
2413
+ organization_id: OptionalOrgId
2414
+ })]);
2415
+ const AccessRecoveryCompletedTelemetryEventSchema = Schema.Struct({
2416
+ name: Schema.Literal("access_recovery_completed"),
2417
+ props: AccessRecoveryCompletedProps
2418
+ });
2419
+ /**
2420
+ * R05 (#1963) wired three of these steps at the app's dashboard Access
2421
+ * boundary: `dashboard_granted` on the commit of the granted content,
2422
+ * `gate_error_displayed` on the mounted error surface, and `retry_selected` on
2423
+ * the actual selection. `redirect_completed` stays RESERVED and unproduced —
2424
+ * asking for a navigation is not arriving, and the destination page's own
2425
+ * normalized pageview already carries the arrival on the same journey, so a
2426
+ * second event would add no fact. `capability_refusal_displayed` and
2427
+ * `signer_refusal_displayed` belong to the screens that draw those refusals
2428
+ * (Recipients, Invoice, Payroll, Quick Pay); Access publishes the contract and
2429
+ * the `CanReason` those owners report, and produces neither itself.
2430
+ */
2431
+ const UiAccessStepCompletedTelemetryEventSchema = Schema.Struct({
2432
+ name: Schema.Literal("ui_access_step_completed"),
2433
+ props: Schema.Struct({
2434
+ ...UiStepProps,
2435
+ step: Schema.Literals([
2436
+ "dashboard_granted",
2437
+ "redirect_completed",
2438
+ "gate_error_displayed",
2439
+ "retry_selected",
2440
+ "capability_refusal_displayed",
2441
+ "signer_refusal_displayed"
2442
+ ]),
2443
+ capability: Schema.optional(Schema.Literals(["spend", "managePeople"])),
2444
+ probe: Schema.optional(Schema.Literals([
2445
+ "session",
2446
+ "membership",
2447
+ "lifecycle"
2448
+ ])),
2449
+ reason: Schema.optional(Schema.Literals([
2450
+ "loading",
2451
+ "no-permission",
2452
+ "org-unavailable"
2453
+ ]))
2454
+ })
2455
+ });
2456
+ /**
2457
+ * R06 (#1964) wired three of the four progress words to the durable writer that
2458
+ * commits each one. `account_ready` comes from `org/memberLifecycle.ts`, for
2459
+ * every membership row a claimed personal Account actually advanced.
2460
+ * `permission_applied` and `membership_activated` come from
2461
+ * `permission/mirror.ts`: the first only when the mirror wrote a NEW Permission
2462
+ * state, the second only when that call flipped a `pending_grant` row to
2463
+ * `active`. A replay of an applied command writes neither, so it reports
2464
+ * neither. `revoked` stays RESERVED and unproduced — no writer revokes a
2465
+ * membership yet, and #1459 owns that ceremony.
2466
+ */
2467
+ const OrgInviteProgressedTelemetryEventSchema = Schema.Struct({
2468
+ name: Schema.Literal("org_invite_progressed"),
2469
+ props: Schema.Struct({
2470
+ ...TelemetryEnvelopeProps,
2471
+ organization_id: OrgIdTelemetrySchema,
2472
+ progress: Schema.Literals([
2473
+ "configuration_authorized",
2474
+ "account_ready",
2475
+ "permission_applied",
2476
+ "membership_activated",
2477
+ "revoked"
2478
+ ]),
2479
+ /** The invited Party. The initiating actor stays on the envelope's identity. */
2480
+ member_party_id: Schema.String,
2481
+ invitation_id: Schema.optional(Schema.String),
2482
+ generation: Schema.optional(Schema.String),
2483
+ command_id: Schema.optional(Schema.String),
2484
+ occurred_at: Schema.Number
2485
+ })
2486
+ });
2487
+ const InvoiceIssuedTelemetryEventSchema = Schema.Struct({
2488
+ name: Schema.Literal("invoice_issued"),
2489
+ props: Schema.Struct({
2490
+ ...TelemetryEnvelopeProps,
2491
+ request_id: Schema.String,
2492
+ issuer_scope_kind: ScopeKindSchema,
2493
+ issuer_scope_id: Schema.String,
2494
+ payer_party_id: OptionalString,
2495
+ occurred_at: Schema.Number
2496
+ })
2497
+ });
2498
+ const InvoiceRequestTransitionedTelemetryEventSchema = Schema.Struct({
2499
+ name: Schema.Literal("invoice_request_transitioned"),
2500
+ props: Schema.Struct({
2501
+ ...TelemetryEnvelopeProps,
2502
+ request_id: Schema.String,
2503
+ transition: Schema.Literals([
2504
+ "approval_prepared",
2505
+ "declined",
2506
+ "cancelled"
2507
+ ]),
2508
+ actor_scope_kind: ScopeKindSchema,
2509
+ actor_scope_id: Schema.String,
2510
+ occurred_at: Schema.Number
2511
+ })
2512
+ });
2513
+ const UiInvoiceStepCompletedTelemetryEventSchema = Schema.Struct({
2514
+ name: Schema.Literal("ui_invoice_step_completed"),
2515
+ props: Schema.Struct({
2516
+ ...UiStepProps,
2517
+ step: Schema.Literals([
2518
+ "opened",
2519
+ "previewed",
2520
+ "dismissed",
2521
+ "submitted",
2522
+ "result_displayed",
2523
+ "refusal_displayed",
2524
+ "retry_selected"
2525
+ ]),
2526
+ request_id: OptionalString
2527
+ })
2528
+ });
2529
+ const UiTreasuryStepCompletedTelemetryEventSchema = Schema.Struct({
2530
+ name: Schema.Literal("ui_treasury_step_completed"),
2531
+ props: Schema.Struct({
2532
+ ...UiStepProps,
2533
+ step: Schema.Literals([
2534
+ "balance_displayed",
2535
+ "read_refusal_displayed",
2536
+ "retry_selected",
2537
+ "recovery_completed"
2538
+ ]),
2539
+ account_kind: Schema.optional(AccountKindSchema)
2540
+ })
2541
+ });
2542
+ const UiReceiveStepCompletedTelemetryEventSchema = Schema.Struct({
2543
+ name: Schema.Literal("ui_receive_step_completed"),
2544
+ props: Schema.Struct({
2545
+ ...UiStepProps,
2546
+ step: Schema.Literals([
2547
+ "instructions_displayed",
2548
+ "address_copied",
2549
+ "copy_failed",
2550
+ "refusal_displayed",
2551
+ "retry_selected"
2552
+ ]),
2553
+ account_kind: Schema.optional(AccountKindSchema)
2554
+ })
2555
+ });
2556
+ const PayrollGroupChangedTelemetryEventSchema = Schema.Struct({
2557
+ name: Schema.Literal("payroll_group_changed"),
2558
+ props: Schema.Struct({
2559
+ ...TelemetryEnvelopeProps,
2560
+ organization_id: OrgIdTelemetrySchema,
2561
+ change: Schema.Literals([
2562
+ "created",
2563
+ "updated",
2564
+ "deleted"
2565
+ ]),
2566
+ group_id: Schema.String,
2567
+ member_count: Schema.Number,
2568
+ occurred_at: Schema.Number
2569
+ })
2570
+ });
2571
+ const PayrollRunTransitionedTelemetryEventSchema = Schema.Struct({
2572
+ name: Schema.Literal("payroll_run_transitioned"),
2573
+ props: Schema.Struct({
2574
+ ...TelemetryEnvelopeProps,
2575
+ organization_id: OrgIdTelemetrySchema,
2576
+ transition: Schema.Literals([
2577
+ "prepared",
2578
+ "authorized",
2579
+ "settled"
2580
+ ]),
2581
+ run_id: Schema.String,
2582
+ /**
2583
+ * The `paymentCommands` row at `payrollRuns.batchRef` — the durable owner of
2584
+ * this run's Payment membership. `payment_count` counts THAT command's
2585
+ * `paymentIds`, so an unrelated Payment quoting the run id changes neither.
2586
+ */
2587
+ command_id: OptionalString,
2588
+ payment_count: Schema.optional(Schema.Number),
2589
+ occurred_at: Schema.Number
2590
+ })
2591
+ });
2592
+ const UiPayrollActionCompletedTelemetryEventSchema = Schema.Struct({
2593
+ name: Schema.Literal("ui_payroll_action_completed"),
2594
+ props: Schema.Struct({
2595
+ ...UiStepProps,
2596
+ action: Schema.Literals([
2597
+ "opened",
2598
+ "refusal_displayed",
2599
+ "recovery_completed",
2600
+ "cancelled",
2601
+ "submitted_displayed"
2602
+ ]),
2603
+ run_id: OptionalString
2604
+ })
2605
+ });
2606
+ const TELEMETRY_EVENT_SCHEMAS = {
2607
+ contact_relationship_changed: ContactRelationshipChangedTelemetryEventSchema,
2608
+ access_recovery_completed: AccessRecoveryCompletedTelemetryEventSchema,
2609
+ ui_access_step_completed: UiAccessStepCompletedTelemetryEventSchema,
2610
+ org_invite_progressed: OrgInviteProgressedTelemetryEventSchema,
2611
+ invoice_issued: InvoiceIssuedTelemetryEventSchema,
2612
+ invoice_request_transitioned: InvoiceRequestTransitionedTelemetryEventSchema,
2613
+ ui_invoice_step_completed: UiInvoiceStepCompletedTelemetryEventSchema,
2614
+ ui_treasury_step_completed: UiTreasuryStepCompletedTelemetryEventSchema,
2615
+ ui_receive_step_completed: UiReceiveStepCompletedTelemetryEventSchema,
2616
+ payroll_group_changed: PayrollGroupChangedTelemetryEventSchema,
2617
+ payroll_run_transitioned: PayrollRunTransitionedTelemetryEventSchema,
2618
+ ui_payroll_action_completed: UiPayrollActionCompletedTelemetryEventSchema,
2619
+ ui_contact_action_completed: UiContactActionCompletedTelemetryEventSchema,
2620
+ cli_diagnostic_completed: CliDiagnosticCompletedTelemetryEventSchema,
2621
+ cli_first_used: CliFirstUsedTelemetryEventSchema,
2622
+ cli_command_started: CliCommandStartedTelemetryEventSchema,
2623
+ cli_command_completed: CliCommandCompletedTelemetryEventSchema,
2624
+ activity_annotation_saved: ActivityAnnotationSavedTelemetryEventSchema,
2625
+ ui_activity_action_completed: UiActivityActionCompletedTelemetryEventSchema,
2626
+ auth_otp_requested: AuthOtpRequestedTelemetryEventSchema,
2627
+ auth_otp_delivered: AuthOtpDeliveredTelemetryEventSchema,
2628
+ auth_otp_expired: AuthOtpExpiredTelemetryEventSchema,
2629
+ auth_verified: AuthVerifiedTelemetryEventSchema,
2630
+ auth_failed: AuthFailedTelemetryEventSchema,
2631
+ identity_refused: IdentityRefusedTelemetryEventSchema,
2632
+ auth_signed_out: AuthSignedOutTelemetryEventSchema,
2633
+ native_authorization_started: NativeAuthorizationStartedTelemetryEventSchema,
2634
+ native_authorization_reviewed: NativeAuthorizationReviewedTelemetryEventSchema,
2635
+ native_authorization_accepted: NativeAuthorizationAcceptedTelemetryEventSchema,
2636
+ native_authorization_denied: NativeAuthorizationDeniedTelemetryEventSchema,
2637
+ native_authorization_connected: NativeAuthorizationConnectedTelemetryEventSchema,
2638
+ native_authorization_failed: NativeAuthorizationFailedTelemetryEventSchema,
2639
+ onboarding_intent_selected: OnboardingIntentSelectedTelemetryEventSchema,
2640
+ onboarding_profile_submitted: OnboardingProfileSubmittedTelemetryEventSchema,
2641
+ onboarding_organization_submitted: OnboardingOrganizationSubmittedTelemetryEventSchema,
2642
+ onboarding_dashboard_reached: OnboardingDashboardReachedTelemetryEventSchema,
2643
+ provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,
2644
+ provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,
2645
+ bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,
2646
+ bootstrap_failed: BootstrapFailedTelemetryEventSchema,
2647
+ member_activation_started: MemberActivationStartedTelemetryEventSchema,
2648
+ member_activation_ready: MemberActivationReadyTelemetryEventSchema,
2649
+ member_activation_failed: MemberActivationFailedTelemetryEventSchema,
2650
+ organization_creation_started: OrganizationCreationStartedTelemetryEventSchema,
2651
+ organization_creation_ready: OrganizationCreationReadyTelemetryEventSchema,
2652
+ organization_creation_failed: OrganizationCreationFailedTelemetryEventSchema,
2653
+ account_balance_read: AccountBalanceReadTelemetryEventSchema,
2654
+ account_balance_failed: AccountBalanceFailedTelemetryEventSchema,
2655
+ faucet_requested: FaucetRequestedTelemetryEventSchema,
2656
+ faucet_confirmed: FaucetConfirmedTelemetryEventSchema,
2657
+ faucet_failed: FaucetFailedTelemetryEventSchema,
2658
+ chain_upstream_fallback: ChainUpstreamFallbackTelemetryEventSchema,
2659
+ bundler_error: BundlerErrorTelemetryEventSchema,
2660
+ receipt_pending: ReceiptPendingTelemetryEventSchema,
2661
+ operation_retried: OperationRetriedTelemetryEventSchema,
2662
+ org_create_started: OrgCreateStartedTelemetryEventSchema,
2663
+ org_safe_created: OrgSafeCreatedTelemetryEventSchema,
2664
+ org_safe_confirmed: OrgSafeConfirmedTelemetryEventSchema,
2665
+ org_roles_seeded: OrgRolesSeededTelemetryEventSchema,
2666
+ org_created: OrgCreatedTelemetryEventSchema,
2667
+ org_create_failed: OrgCreateFailedTelemetryEventSchema,
2668
+ org_invite_sent: OrgInviteSentTelemetryEventSchema,
2669
+ org_invite_accepted: OrgInviteAcceptedTelemetryEventSchema,
2670
+ org_invite_expired: OrgInviteExpiredTelemetryEventSchema,
2671
+ payment_initiated: PaymentInitiatedTelemetryEventSchema,
2672
+ payment_settled: PaymentSettledTelemetryEventSchema,
2673
+ payment_failed: PaymentFailedTelemetryEventSchema,
2674
+ payment_verification_retry: PaymentVerificationRetryTelemetryEventSchema,
2675
+ payment_lifecycle_transition: PaymentLifecycleTransitionTelemetryEventSchema,
2676
+ quick_pay_external_address_acknowledged: QuickPayExternalAddressAcknowledgedTelemetryEventSchema,
2677
+ deposit_initiated: DepositInitiatedTelemetryEventSchema,
2678
+ deposit_settled: DepositSettledTelemetryEventSchema,
2679
+ permission_mirror_verification: PermissionMirrorVerificationTelemetryEventSchema,
2680
+ movement_scan_window: MovementScanWindowTelemetryEventSchema,
2681
+ movement_scan_checkpoint: MovementScanCheckpointTelemetryEventSchema,
2682
+ movement_scan_incident: MovementScanIncidentTelemetryEventSchema,
2683
+ indexer_drift_corrected: IndexerDriftCorrectedTelemetryEventSchema
2684
+ };
2685
+ const FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS = [];
2686
+ /**
2687
+ * Contract-first events whose producer is owned by a later domain node.
2688
+ *
2689
+ * A domain node removes its entry when it adds the producer. The telemetry
2690
+ * gate rejects an entry that has a producer.
2691
+ */
2692
+ const CONTRACT_FIRST_TELEMETRY_EVENTS = [];
2693
+ /**
2694
+ * Catalog events whose product mapper remains gated on the #1150 frontend
2695
+ * adoption. L1 S1 removes their retired SDK-flow producers without inventing
2696
+ * replacements inside the identity actor. The telemetry-spine gate enforces
2697
+ * planned-XOR-wired: a name must leave this list in the same change that adds
2698
+ * its real product-boundary producer.
2699
+ */
2700
+ const PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS = ["auth_otp_expired"];
2701
+ /** Catalogued browser observations whose producers remain owned by app adoption. */
2702
+ const BROWSER_GATED_TELEMETRY_EVENTS = [
2703
+ "onboarding_intent_selected",
2704
+ "onboarding_profile_submitted",
2705
+ "onboarding_organization_submitted",
2706
+ "onboarding_dashboard_reached",
2707
+ "ui_activity_action_completed",
2708
+ "ui_contact_action_completed",
2709
+ "ui_access_step_completed",
2710
+ "ui_invoice_step_completed",
2711
+ "ui_treasury_step_completed",
2712
+ "ui_receive_step_completed",
2713
+ "ui_payroll_action_completed"
2714
+ ];
2715
+ let trackHandler = () => {};
2716
+ function setTrackHandler(handler) {
2717
+ const previous = trackHandler;
2718
+ trackHandler = handler;
2719
+ return previous;
2720
+ }
2721
+ function getTrackHandler() {
2722
+ return trackHandler;
2723
+ }
2724
+ function track(name, props) {
2725
+ trackHandler(name, props);
2726
+ }
2727
+ function redactTelemetryEvent(event, options = {}) {
2728
+ const props = redactTelemetryProps(event.name, event.props, options);
2729
+ return props === void 0 ? { name: event.name } : {
2730
+ name: event.name,
2731
+ props
2732
+ };
2733
+ }
2734
+ function redactTelemetryProps(name, props, options = {}) {
2735
+ if (props === void 0) return void 0;
2736
+ const clone = cloneProps(props);
2737
+ if (options.rawMode === true) return clone;
2738
+ for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) redactProperty(clone, key);
2739
+ return clone;
2740
+ }
2741
+ /**
2742
+ * Remove query strings and fragments from every PostHog URL/referrer/path
2743
+ * property before transport. Browser applications may carry emails, draft ids,
2744
+ * or other capabilities in the URL; those values must never leave the origin.
2745
+ *
2746
+ * The callback replaces the event's data with a sanitized copy. Nested values
2747
+ * can refer to live clients or configuration; observation must never mutate them.
2748
+ */
2749
+ function sanitizePostHogBrowserEvent(event, urlPolicy = "path-only") {
2750
+ if (event === null) return event;
2751
+ const transportToken = event.properties.token;
2752
+ const seen = /* @__PURE__ */ new WeakMap();
2753
+ event.properties = sanitizePostHogBrowserValue(event.properties, seen, urlPolicy);
2754
+ if (transportToken !== void 0) event.properties.token = transportToken;
2755
+ if (event.$set !== void 0) event.$set = sanitizePostHogBrowserValue(event.$set, seen, urlPolicy);
2756
+ if (event.$set_once !== void 0) event.$set_once = sanitizePostHogBrowserValue(event.$set_once, seen, urlPolicy);
2757
+ return event;
2758
+ }
2759
+ /**
2760
+ * Drop local events before transport. Sanitize and stamp every other browser
2761
+ * event with `capxul_env` and `producer: "browser"`.
2762
+ */
2763
+ function createCapxulBeforeSend(capxulEnv, urlPolicy = "path-only") {
2764
+ return (event) => {
2765
+ if (capxulEnv === "local") return null;
2766
+ const sanitized = sanitizePostHogBrowserEvent(event, urlPolicy);
2767
+ if (sanitized === null) return sanitized;
2768
+ sanitized.properties.capxul_env = capxulEnv;
2769
+ sanitized.properties.producer ??= "browser";
2770
+ return sanitized;
2771
+ };
2772
+ }
2773
+ function utilityAppAnalytics(input) {
2774
+ return {
2775
+ api_host: input.host,
2776
+ defaults: "2026-01-30",
2777
+ autocapture: false,
2778
+ capture_pageview: false,
2779
+ capture_pageleave: true,
2780
+ disable_session_recording: true,
2781
+ disable_persistence: true,
2782
+ capture_heatmaps: false,
2783
+ capture_exceptions: false,
2784
+ capture_performance: false,
2785
+ disable_surveys: true,
2786
+ disable_web_experiments: true,
2787
+ disable_product_tours: true,
2788
+ disable_conversations: true,
2789
+ disable_external_dependency_loading: true,
2790
+ person_profiles: "identified_only",
2791
+ advanced_disable_flags: true,
2792
+ save_campaign_params: false,
2793
+ save_referrer: false,
2794
+ before_send: createCapxulBeforeSend(input.capxulEnv)
2795
+ };
2796
+ }
2797
+ /** In unstructured bodies, preserve text around explicitly named credentials. */
2798
+ const NETWORK_FIELD = /((?:"?)([A-Za-z_][A-Za-z0-9_.-]*)(?:"?)\s*[:=]\s*)("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s,;&}]+)/gu;
2799
+ function maskNetworkText(text, context) {
2800
+ return redactSecrets(text).replace(NETWORK_FIELD, (whole, prefix, name, value) => {
2801
+ if (!isCredentialField(name, context)) return whole;
2802
+ const quote = value.startsWith("\"") ? "\"" : value.startsWith("'") ? "'" : "";
2803
+ return `${prefix}${quote}[REDACTED]${quote}`;
2804
+ });
2805
+ }
2806
+ function maskNetworkHeaders(headers) {
2807
+ if (headers === void 0) return void 0;
2808
+ const masked = {};
2809
+ for (const [name, value] of Object.entries(headers)) masked[name] = isCredentialField(name, "header") ? "[REDACTED]" : /^(?:location|content-location|referer)$/iu.test(name) ? redactUrlSecrets(value) : maskNetworkText(value);
2810
+ return masked;
2811
+ }
2812
+ function maskJsonValue(value, depth = 0, context) {
2813
+ if (typeof value === "function" || typeof value === "symbol") return "[UNREADABLE]";
2814
+ if (typeof value === "string") return maskNetworkText(value, context);
2815
+ if (typeof value !== "object" || value === null) return value;
2816
+ if (depth >= 16) return "[REDACTED]";
2817
+ if (Array.isArray(value)) return value.map((item) => maskJsonValue(item, depth + 1, context));
2818
+ const masked = Object.create(null);
2819
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
2820
+ if (!descriptor.enumerable) continue;
2821
+ masked[key] = isCredentialField(key, context) ? "[REDACTED]" : !("value" in descriptor) ? "[UNREADABLE]" : typeof descriptor.value === "string" && isPostHogUrlProperty(key) ? redactUrlSecrets(descriptor.value) : maskJsonValue(descriptor.value, depth + 1, context);
2822
+ }
2823
+ return masked;
2824
+ }
2825
+ function maskNetworkBody(body, context) {
2826
+ try {
2827
+ if (typeof body !== "string") return maskJsonValue(body, 0, context);
2828
+ let parsed;
2829
+ try {
2830
+ parsed = JSON.parse(body);
2831
+ } catch {
2832
+ if (/^[^=&\s]+=[\s\S]*$/u.test(body)) return new URLSearchParams(Array.from(new URLSearchParams(body), ([name, value]) => [name, isCredentialField(name, context) ? "[REDACTED]" : maskNetworkText(value)])).toString();
2833
+ return maskNetworkText(body, context);
2834
+ }
2835
+ return JSON.stringify(maskJsonValue(parsed, 0, context));
2836
+ } catch {
2837
+ return "[UNREADABLE]";
2838
+ }
2839
+ }
2840
+ /** Keep request evidence while masking credential values at the browser boundary. */
2841
+ function maskCapturedNetworkRequest(request) {
2842
+ const requestUrl = request.name ?? request.url ?? "";
2843
+ let context;
2844
+ try {
2845
+ const path = new URL(requestUrl, "https://capxul.invalid").pathname;
2846
+ if (/\/(?:auth|oauth|sign-in|signin|login|verify-otp|verify-email)(?:\/|$)/iu.test(path)) context = "authentication";
2847
+ } catch {}
2848
+ return {
2849
+ ...request,
2850
+ ...request.name === void 0 ? {} : { name: redactUrlSecrets(request.name) },
2851
+ ...request.url === void 0 ? {} : { url: redactUrlSecrets(request.url) },
2852
+ requestHeaders: maskNetworkHeaders(request.requestHeaders),
2853
+ responseHeaders: maskNetworkHeaders(request.responseHeaders),
2854
+ requestBody: maskNetworkBody(request.requestBody, context),
2855
+ responseBody: maskNetworkBody(request.responseBody)
2856
+ };
2857
+ }
2858
+ function productAppAnalytics(input) {
2859
+ return {
2860
+ api_host: input.host,
2861
+ defaults: "2026-01-30",
2862
+ autocapture: false,
2863
+ capture_pageview: false,
2864
+ capture_pageleave: true,
2865
+ disable_session_recording: false,
2866
+ disable_persistence: false,
2867
+ capture_heatmaps: false,
2868
+ capture_exceptions: true,
2869
+ capture_performance: {
2870
+ network_timing: true,
2871
+ web_vitals: false
2872
+ },
2873
+ disable_surveys: true,
2874
+ disable_web_experiments: true,
2875
+ disable_product_tours: true,
2876
+ disable_conversations: true,
2877
+ disable_external_dependency_loading: false,
2878
+ person_profiles: "identified_only",
2879
+ advanced_disable_flags: false,
2880
+ save_campaign_params: false,
2881
+ save_referrer: false,
2882
+ session_recording: {
2883
+ maskAllInputs: true,
2884
+ maskInputFn: (text, element) => {
2885
+ const autocomplete = element?.getAttribute("autocomplete")?.toLowerCase().split(/\s+/u) ?? [];
2886
+ return element?.getAttribute("type")?.toLowerCase() === "password" || autocomplete.some((value) => [
2887
+ "one-time-code",
2888
+ "current-password",
2889
+ "new-password"
2890
+ ].includes(value)) || isCredentialField(element?.getAttribute("name") ?? "") || isCredentialField(element?.getAttribute("id") ?? "") ? "*".repeat(text.length) : maskNetworkText(text);
2891
+ },
2892
+ captureCanvas: { recordCanvas: false },
2893
+ recordHeaders: true,
2894
+ recordBody: true,
2895
+ maskCapturedNetworkRequestFn: maskCapturedNetworkRequest
2896
+ },
2897
+ before_send: createCapxulBeforeSend(input.capxulEnv, "diagnostic")
2898
+ };
2899
+ }
2900
+ /**
2901
+ * Apply a named privacy profile before an application-owned PostHog client
2902
+ * initializes. Hosts still own the vendor client and lifecycle; this helper
2903
+ * centralizes the security-relevant options and the missing-key opt-out (no
2904
+ * key ⇒ no client ⇒ no network call).
2905
+ */
2906
+ function initializeCapxulBrowserAnalytics(profile, input, initialize) {
2907
+ const key = input.key?.trim();
2908
+ if (key === void 0 || key.length === 0) return void 0;
2909
+ try {
2910
+ const options = profile(input);
2911
+ const client = initialize(key, options);
2912
+ warnWhenReplayHasNoRecorder(options, client);
2913
+ return client;
2914
+ } catch {
2915
+ return;
2916
+ }
2917
+ }
2918
+ let replayRecorderWarned = false;
2919
+ /**
2920
+ * #1709: `posthog-js/dist/module.slim` never registers the session recording
2921
+ * manager, so a profile that enables replay records nothing with it. The
2922
+ * client exposes the manager as `sessionRecording` once `init` ran on the
2923
+ * standard build. Warn once per page so the missing build is visible.
2924
+ */
2925
+ function warnWhenReplayHasNoRecorder(options, client) {
2926
+ if (replayRecorderWarned) return;
2927
+ const replayEnabled = typeof options === "object" && options !== null && options.disable_session_recording === false;
2928
+ const recorderMissing = typeof client === "object" && client !== null && client.sessionRecording === void 0;
2929
+ if (!replayEnabled || !recorderMissing) return;
2930
+ replayRecorderWarned = true;
2931
+ console.warn("@capxul/observability: session replay is enabled but the PostHog client has no session recording manager. Import the standard `posthog-js` build; `posthog-js/dist/module.slim` records nothing.");
2932
+ }
2933
+ /** The utility profile, pre-bound — the shape ADR-0016's consumers already use. */
2934
+ function initializePostHogBrowserAnalytics(input, initialize) {
2935
+ return initializeCapxulBrowserAnalytics(utilityAppAnalytics, input, initialize);
2936
+ }
2937
+ /**
2938
+ * Build an explicit SPA pageview sink for toolbar-free PostHog clients. The
2939
+ * pathname-only input avoids query capabilities, repeated pathnames are
2940
+ * deduplicated, and vendor failures remain best-effort.
2941
+ */
2942
+ function createPostHogBrowserPageviewTracker(client) {
2943
+ let previousPathname;
2944
+ return (pathname) => {
2945
+ if (client === null || client === void 0) return;
2946
+ const safePathname = stripUrlQueryAndFragment(pathname);
2947
+ if (safePathname === previousPathname) return;
2948
+ try {
2949
+ Promise.resolve(client.capture("$pageview", { $pathname: safePathname })).catch(() => {});
2950
+ previousPathname = safePathname;
2951
+ } catch {}
2952
+ };
2953
+ }
2954
+ function sanitizePostHogBrowserValue(value, seen, urlPolicy) {
2955
+ if (typeof value !== "object" || value === null || value instanceof Date) return value;
2956
+ if (seen.has(value)) return seen.get(value);
2957
+ if (Array.isArray(value)) {
2958
+ const copy = [];
2959
+ seen.set(value, copy);
2960
+ for (let index = 0; index < value.length; index++) {
2961
+ const item = value[index];
2962
+ copy[index] = typeof item === "string" ? maskNetworkText(item) : sanitizePostHogBrowserValue(item, seen, urlPolicy);
2963
+ }
2964
+ return copy;
2965
+ }
2966
+ const properties = Object.create(null);
2967
+ seen.set(value, properties);
2968
+ for (const [key, nestedValue] of Object.entries(value)) {
2969
+ if (isPostHogQueryDerivedProperty(key)) continue;
2970
+ if (isCredentialField(key)) {
2971
+ properties[key] = "[REDACTED]";
2972
+ continue;
2973
+ }
2974
+ if (typeof nestedValue === "string") {
2975
+ properties[key] = isPostHogUrlProperty(key) ? urlPolicy === "path-only" ? stripUrlQueryAndFragment(nestedValue) : redactUrlSecrets(nestedValue) : maskNetworkText(nestedValue);
2976
+ continue;
2977
+ }
2978
+ properties[key] = sanitizePostHogBrowserValue(nestedValue, seen, urlPolicy);
2979
+ }
2980
+ return properties;
2981
+ }
2982
+ const POSTHOG_QUERY_DERIVED_PROPERTY_NAMES = [
2983
+ "utm_source",
2984
+ "utm_medium",
2985
+ "utm_campaign",
2986
+ "utm_content",
2987
+ "utm_term",
2988
+ "gad_source",
2989
+ "mc_cid",
2990
+ "gclid",
2991
+ "gclsrc",
2992
+ "dclid",
2993
+ "gbraid",
2994
+ "wbraid",
2995
+ "fbclid",
2996
+ "msclkid",
2997
+ "twclid",
2998
+ "li_fat_id",
2999
+ "igshid",
3000
+ "ttclid",
3001
+ "rdt_cid",
3002
+ "epik",
3003
+ "qclid",
3004
+ "sccid",
3005
+ "irclid",
3006
+ "_kx",
3007
+ "ph_keyword"
3008
+ ];
3009
+ function isPostHogQueryDerivedProperty(key) {
3010
+ const normalized = key.toLowerCase();
3011
+ return POSTHOG_QUERY_DERIVED_PROPERTY_NAMES.some((propertyName) => normalized === propertyName || normalized.endsWith(`_${propertyName}`) || normalized.endsWith(`$${propertyName}`));
3012
+ }
3013
+ function isPostHogUrlProperty(key) {
3014
+ const normalized = key.toLowerCase();
3015
+ return normalized.includes("url") || normalized.includes("referrer") || normalized.includes("path") || normalized.includes("filename");
3016
+ }
3017
+ function stripUrlQueryAndFragment(value) {
3018
+ const queryIndex = value.indexOf("?");
3019
+ const fragmentIndex = value.indexOf("#");
3020
+ if (queryIndex === -1 && fragmentIndex === -1) return value;
3021
+ if (queryIndex === -1) return value.slice(0, fragmentIndex);
3022
+ if (fragmentIndex === -1) return value.slice(0, queryIndex);
3023
+ return value.slice(0, Math.min(queryIndex, fragmentIndex));
3024
+ }
3025
+ var RecordingTelemetryAdapter = class {
3026
+ #events = [];
3027
+ #rawMode;
3028
+ constructor(options = {}) {
3029
+ this.#rawMode = options.rawMode === true;
3030
+ }
3031
+ get events() {
3032
+ return this.#events.map((event) => cloneEvent(event));
3033
+ }
3034
+ emit(event) {
3035
+ return Effect.sync(() => {
3036
+ this.#events.push(redactTelemetryEvent(event, { rawMode: this.#rawMode }));
3037
+ });
3038
+ }
3039
+ identify(_input) {
3040
+ return Effect.void;
3041
+ }
3042
+ group(_input) {
3043
+ return Effect.void;
3044
+ }
3045
+ reset() {
3046
+ return Effect.void;
3047
+ }
3048
+ reportHandledError(_error, _context) {
3049
+ return Effect.void;
3050
+ }
3051
+ clear() {
3052
+ this.#events.length = 0;
3053
+ }
3054
+ };
3055
+ var PostHogTelemetryAdapter = class {
3056
+ #capture;
3057
+ constructor(deps) {
3058
+ this.#capture = deps.capture;
3059
+ }
3060
+ emit(event) {
3061
+ return Effect.sync(() => {
3062
+ try {
3063
+ Promise.resolve(this.#capture(event.name, redactTelemetryProps(event.name, event.props))).catch(() => {});
3064
+ } catch {}
3065
+ });
3066
+ }
3067
+ identify(_input) {
3068
+ return Effect.void;
3069
+ }
3070
+ group(_input) {
3071
+ return Effect.void;
3072
+ }
3073
+ reset() {
3074
+ return Effect.void;
3075
+ }
3076
+ reportHandledError(_error, _context) {
3077
+ return Effect.void;
3078
+ }
3079
+ };
3080
+ var InMemoryTelemetryBusAdapter = class {
3081
+ #subscribers = /* @__PURE__ */ new Set();
3082
+ #rawMode;
3083
+ constructor(options = {}) {
3084
+ this.#rawMode = options.rawMode === true;
3085
+ }
3086
+ subscribe(handler) {
3087
+ this.#subscribers.add(handler);
3088
+ return () => {
3089
+ this.#subscribers.delete(handler);
3090
+ };
3091
+ }
3092
+ emit(event) {
3093
+ return Effect.sync(() => {
3094
+ const delivered = redactTelemetryEvent(event, { rawMode: this.#rawMode });
3095
+ for (const handler of this.#subscribers) try {
3096
+ handler(cloneEvent(delivered));
3097
+ } catch {}
3098
+ });
3099
+ }
3100
+ identify(_input) {
3101
+ return Effect.void;
3102
+ }
3103
+ group(_input) {
3104
+ return Effect.void;
3105
+ }
3106
+ reset() {
3107
+ return Effect.void;
3108
+ }
3109
+ reportHandledError(_error, _context) {
3110
+ return Effect.void;
3111
+ }
3112
+ };
3113
+ const PII_PROP_KEYS_BY_EVENT = {
3114
+ auth_otp_requested: ["email"],
3115
+ auth_otp_delivered: ["email"],
3116
+ auth_otp_expired: ["email"],
3117
+ auth_failed: ["email"]
3118
+ };
3119
+ function redactProperty(props, key) {
3120
+ const value = props[key];
3121
+ if (typeof value === "string") props[key] = sha256Hex(value).slice(0, 12);
3122
+ }
3123
+ function cloneEvent(event) {
3124
+ if (event.props === void 0) return { name: event.name };
3125
+ return {
3126
+ name: event.name,
3127
+ props: cloneProps(event.props)
3128
+ };
3129
+ }
3130
+ function cloneProps(props) {
3131
+ const cloned = {};
3132
+ for (const [key, value] of Object.entries(props)) cloned[key] = cloneTelemetryValue(value);
3133
+ return cloned;
3134
+ }
3135
+ function cloneTelemetryValue(value) {
3136
+ if (Array.isArray(value)) return value.map(cloneTelemetryValue);
3137
+ if (value === null || typeof value !== "object") return value;
3138
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
3139
+ const cloned = {};
3140
+ for (const [key, nested] of Object.entries(value)) cloned[key] = cloneTelemetryValue(nested);
3141
+ return cloned;
3142
+ }
3143
+ const SHA256_INITIAL_HASH = [
3144
+ 1779033703,
3145
+ 3144134277,
3146
+ 1013904242,
3147
+ 2773480762,
3148
+ 1359893119,
3149
+ 2600822924,
3150
+ 528734635,
3151
+ 1541459225
3152
+ ];
3153
+ const SHA256_K = [
3154
+ 1116352408,
3155
+ 1899447441,
3156
+ 3049323471,
3157
+ 3921009573,
3158
+ 961987163,
3159
+ 1508970993,
3160
+ 2453635748,
3161
+ 2870763221,
3162
+ 3624381080,
3163
+ 310598401,
3164
+ 607225278,
3165
+ 1426881987,
3166
+ 1925078388,
3167
+ 2162078206,
3168
+ 2614888103,
3169
+ 3248222580,
3170
+ 3835390401,
3171
+ 4022224774,
3172
+ 264347078,
3173
+ 604807628,
3174
+ 770255983,
3175
+ 1249150122,
3176
+ 1555081692,
3177
+ 1996064986,
3178
+ 2554220882,
3179
+ 2821834349,
3180
+ 2952996808,
3181
+ 3210313671,
3182
+ 3336571891,
3183
+ 3584528711,
3184
+ 113926993,
3185
+ 338241895,
3186
+ 666307205,
3187
+ 773529912,
3188
+ 1294757372,
3189
+ 1396182291,
3190
+ 1695183700,
3191
+ 1986661051,
3192
+ 2177026350,
3193
+ 2456956037,
3194
+ 2730485921,
3195
+ 2820302411,
3196
+ 3259730800,
3197
+ 3345764771,
3198
+ 3516065817,
3199
+ 3600352804,
3200
+ 4094571909,
3201
+ 275423344,
3202
+ 430227734,
3203
+ 506948616,
3204
+ 659060556,
3205
+ 883997877,
3206
+ 958139571,
3207
+ 1322822218,
3208
+ 1537002063,
3209
+ 1747873779,
3210
+ 1955562222,
3211
+ 2024104815,
3212
+ 2227730452,
3213
+ 2361852424,
3214
+ 2428436474,
3215
+ 2756734187,
3216
+ 3204031479,
3217
+ 3329325298
3218
+ ];
3219
+ function sha256Hex(input) {
3220
+ const padded = padSha256Message(new TextEncoder().encode(input));
3221
+ const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);
3222
+ const words = /* @__PURE__ */ new Uint32Array(64);
3223
+ let h0 = SHA256_INITIAL_HASH[0];
3224
+ let h1 = SHA256_INITIAL_HASH[1];
3225
+ let h2 = SHA256_INITIAL_HASH[2];
3226
+ let h3 = SHA256_INITIAL_HASH[3];
3227
+ let h4 = SHA256_INITIAL_HASH[4];
3228
+ let h5 = SHA256_INITIAL_HASH[5];
3229
+ let h6 = SHA256_INITIAL_HASH[6];
3230
+ let h7 = SHA256_INITIAL_HASH[7];
3231
+ for (let offset = 0; offset < padded.byteLength; offset += 64) {
3232
+ for (let i = 0; i < 16; i++) words[i] = view.getUint32(offset + i * 4);
3233
+ for (let i = 16; i < 64; i++) {
3234
+ const s0 = rotr(words[i - 15], 7) ^ rotr(words[i - 15], 18) ^ words[i - 15] >>> 3;
3235
+ const s1 = rotr(words[i - 2], 17) ^ rotr(words[i - 2], 19) ^ words[i - 2] >>> 10;
3236
+ words[i] = words[i - 16] + s0 + words[i - 7] + s1 >>> 0;
3237
+ }
3238
+ let a = h0;
3239
+ let b = h1;
3240
+ let c = h2;
3241
+ let d = h3;
3242
+ let e = h4;
3243
+ let f = h5;
3244
+ let g = h6;
3245
+ let h = h7;
3246
+ for (let i = 0; i < 64; i++) {
3247
+ const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
3248
+ const ch = e & f ^ ~e & g;
3249
+ const temp1 = h + s1 + ch + SHA256_K[i] + words[i] >>> 0;
3250
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
3251
+ h = g;
3252
+ g = f;
3253
+ f = e;
3254
+ e = d + temp1 >>> 0;
3255
+ d = c;
3256
+ c = b;
3257
+ b = a;
3258
+ a = temp1 + temp2 >>> 0;
3259
+ }
3260
+ h0 = h0 + a >>> 0;
3261
+ h1 = h1 + b >>> 0;
3262
+ h2 = h2 + c >>> 0;
3263
+ h3 = h3 + d >>> 0;
3264
+ h4 = h4 + e >>> 0;
3265
+ h5 = h5 + f >>> 0;
3266
+ h6 = h6 + g >>> 0;
3267
+ h7 = h7 + h >>> 0;
3268
+ }
3269
+ return [
3270
+ h0,
3271
+ h1,
3272
+ h2,
3273
+ h3,
3274
+ h4,
3275
+ h5,
3276
+ h6,
3277
+ h7
3278
+ ].map((word) => word.toString(16).padStart(8, "0")).join("");
3279
+ }
3280
+ function padSha256Message(bytes) {
3281
+ const bitLength = bytes.byteLength * 8;
3282
+ const zeroPadLength = (64 - (bytes.byteLength + 1 + 8) % 64) % 64;
3283
+ const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);
3284
+ output.set(bytes);
3285
+ output[bytes.byteLength] = 128;
3286
+ const view = new DataView(output.buffer);
3287
+ view.setUint32(output.byteLength - 8, Math.floor(bitLength / 4294967296));
3288
+ view.setUint32(output.byteLength - 4, bitLength >>> 0);
3289
+ return output;
3290
+ }
3291
+ function rotr(value, bits) {
3292
+ return value >>> bits | value << 32 - bits;
3293
+ }
3294
+ //#endregion
3295
+ export { OnboardingIntentSelectedTelemetryEventSchema as $, redactTelemetryProps as $t, FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS as A, ReceiptPendingTelemetryEventSchema as At, MemberActivationFailedTelemetryEventSchema as B, UiContactActionCompletedTelemetryEventSchema as Bt, CliCommandCompletedTelemetryEventSchema as C, PayrollGroupChangedTelemetryEventSchema as Ct, ContactRelationshipChangedTelemetryEventSchema as D, ProvisioningSafeConfirmedTelemetryEventSchema as Dt, CliFirstUsedTelemetryEventSchema as E, PostHogTelemetryAdapter as Et, IdentityRefusedTelemetryEventSchema as F, TELEMETRY_EVENT_SCHEMAS as Ft, MovementScanWindowTelemetryEventSchema as G, createCapxulBeforeSend as Gt, MemberActivationStartedTelemetryEventSchema as H, UiPayrollActionCompletedTelemetryEventSchema as Ht, InMemoryTelemetryBusAdapter as I, TELEMETRY_JOURNEYS as It, NativeAuthorizationDeniedTelemetryEventSchema as J, initializeCapxulBrowserAnalytics as Jt, NativeAuthorizationAcceptedTelemetryEventSchema as K, createPostHogBrowserPageviewTracker as Kt, IndexerDriftCorrectedTelemetryEventSchema as L, TELEMETRY_PRODUCERS as Lt, FaucetConfirmedTelemetryEventSchema as M, ResponseHeadersSchema as Mt, FaucetFailedTelemetryEventSchema as N, SYNCABLE_CAPXUL_ENVS as Nt, DepositInitiatedTelemetryEventSchema as O, ProvisioningSafeCreatedTelemetryEventSchema as Ot, FaucetRequestedTelemetryEventSchema as P, TELEMETRY_EVENT_NAMES as Pt, OnboardingDashboardReachedTelemetryEventSchema as Q, redactTelemetryEvent as Qt, InvoiceIssuedTelemetryEventSchema as R, UiAccessStepCompletedTelemetryEventSchema as Rt, ChainUpstreamSchema as S, PaymentVerificationRetryTelemetryEventSchema as St, CliDiagnosticCompletedTelemetryEventSchema as T, PermissionMirrorVerificationTelemetryEventSchema as Tt, MovementScanCheckpointTelemetryEventSchema as U, UiReceiveStepCompletedTelemetryEventSchema as Ut, MemberActivationReadyTelemetryEventSchema as V, UiInvoiceStepCompletedTelemetryEventSchema as Vt, MovementScanIncidentTelemetryEventSchema as W, UiTreasuryStepCompletedTelemetryEventSchema as Wt, NativeAuthorizationReviewedTelemetryEventSchema as X, maskCapturedNetworkRequest as Xt, NativeAuthorizationFailedTelemetryEventSchema as Y, initializePostHogBrowserAnalytics as Yt, NativeAuthorizationStartedTelemetryEventSchema as Z, productAppAnalytics as Zt, CLI_COMMAND_NAMES as _, PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS as _t, AuthFailedTelemetryEventSchema as a, CAPXUL_OPERATIONS as an, OrgCreatedTelemetryEventSchema as at, ChainAttemptSchema as b, PaymentLifecycleTransitionTelemetryEventSchema as bt, AuthOtpRequestedTelemetryEventSchema as c, CAPXUL_ERROR_CODES as cn, OrgInviteProgressedTelemetryEventSchema as ct, BROWSER_GATED_TELEMETRY_EVENTS as d, redactSecrets as dn, OrgSafeConfirmedTelemetryEventSchema as dt, sanitizePostHogBrowserEvent as en, OnboardingOrganizationSubmittedTelemetryEventSchema as et, BootstrapFailedTelemetryEventSchema as f, redactUrlSecrets as fn, OrgSafeCreatedTelemetryEventSchema as ft, CLI_CAPABILITIES as g, PII as gt, CAPXUL_ENVS as h, OrganizationCreationStartedTelemetryEventSchema as ht, ActivityAnnotationSavedTelemetryEventSchema as i, utilityAppAnalytics as in, OrgCreateStartedTelemetryEventSchema as it, FailureModeSchema as j, RecordingTelemetryAdapter as jt, DepositSettledTelemetryEventSchema as k, QuickPayExternalAddressAcknowledgedTelemetryEventSchema as kt, AuthSignedOutTelemetryEventSchema as l, FAILURE_MODES as ln, OrgInviteSentTelemetryEventSchema as lt, BundlerErrorTelemetryEventSchema as m, OrganizationCreationReadyTelemetryEventSchema as mt, AccountBalanceFailedTelemetryEventSchema as n, stampTelemetryEnvelope as nn, OperationRetriedTelemetryEventSchema as nt, AuthOtpDeliveredTelemetryEventSchema as o, isCapxulOperation as on, OrgInviteAcceptedTelemetryEventSchema as ot, BootstrapResolvedTelemetryEventSchema as p, OrganizationCreationFailedTelemetryEventSchema as pt, NativeAuthorizationConnectedTelemetryEventSchema as q, getTrackHandler as qt, AccountBalanceReadTelemetryEventSchema as r, track as rn, OrgCreateFailedTelemetryEventSchema as rt, AuthOtpExpiredTelemetryEventSchema as s, normalizeCapxulOperation as sn, OrgInviteExpiredTelemetryEventSchema as st, AccessRecoveryCompletedTelemetryEventSchema as t, setTrackHandler as tn, OnboardingProfileSubmittedTelemetryEventSchema as tt, AuthVerifiedTelemetryEventSchema as u, isCredentialField as un, OrgRolesSeededTelemetryEventSchema as ut, CLI_INVOCATION_KINDS as v, PaymentFailedTelemetryEventSchema as vt, CliCommandStartedTelemetryEventSchema as w, PayrollRunTransitionedTelemetryEventSchema as wt, ChainUpstreamFallbackTelemetryEventSchema as x, PaymentSettledTelemetryEventSchema as xt, CONTRACT_FIRST_TELEMETRY_EVENTS as y, PaymentInitiatedTelemetryEventSchema as yt, InvoiceRequestTransitionedTelemetryEventSchema as z, UiActivityActionCompletedTelemetryEventSchema as zt };