@gravity-rail/sdk 8.2.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +2 -3
  2. package/dist/{agent_standing_job-CQqd8LDQ.d.ts → agent_team-C4ZYR_m1.d.ts} +731 -354
  3. package/dist/{agent_standing_job-DfjwGfg_.d.cts → agent_team-C6FdNgYH.d.cts} +731 -354
  4. package/dist/{chunk-U2U5X3LY.js → chunk-7LQYEV5Y.js} +245 -226
  5. package/dist/chunk-7LQYEV5Y.js.map +1 -0
  6. package/dist/{chunk-IIIRXFKG.js → chunk-MWTQXZGB.js} +1 -1
  7. package/dist/chunk-MWTQXZGB.js.map +1 -0
  8. package/dist/{chunk-6KPGCPGW.js → chunk-ZJJDZUAK.js} +40 -1
  9. package/dist/chunk-ZJJDZUAK.js.map +1 -0
  10. package/dist/{client-Bd-zXY42.d.ts → client-DVF3qwNq.d.ts} +2380 -1113
  11. package/dist/{client-BGGgZhKg.d.cts → client-DwslF70Y.d.cts} +2380 -1113
  12. package/dist/helpers.cjs +41 -0
  13. package/dist/helpers.cjs.map +1 -1
  14. package/dist/helpers.d.cts +2 -2
  15. package/dist/helpers.d.ts +2 -2
  16. package/dist/helpers.js +5 -1
  17. package/dist/helpers.js.map +1 -1
  18. package/dist/index.cjs +290 -305
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +7 -23
  21. package/dist/index.d.ts +7 -23
  22. package/dist/index.js +14 -84
  23. package/dist/index.js.map +1 -1
  24. package/dist/internal.cjs +252 -230
  25. package/dist/internal.cjs.map +1 -1
  26. package/dist/internal.d.cts +775 -999
  27. package/dist/internal.d.ts +775 -999
  28. package/dist/internal.js +12 -9
  29. package/dist/internal.js.map +1 -1
  30. package/dist/member-import-BpcX-swC.d.ts +92 -0
  31. package/dist/member-import-CA9YWv3Y.d.cts +92 -0
  32. package/dist/realtime.cjs +109 -54
  33. package/dist/realtime.cjs.map +1 -1
  34. package/dist/realtime.d.cts +7 -2
  35. package/dist/realtime.d.ts +7 -2
  36. package/dist/realtime.js +109 -54
  37. package/dist/realtime.js.map +1 -1
  38. package/dist/schemas.cjs +24 -6
  39. package/dist/schemas.cjs.map +1 -1
  40. package/dist/schemas.d.cts +53 -39
  41. package/dist/schemas.d.ts +53 -39
  42. package/dist/schemas.js +24 -7
  43. package/dist/schemas.js.map +1 -1
  44. package/dist/{tasks-2LhXIwL8.d.ts → tasks-BGLfmf5y.d.ts} +69 -904
  45. package/dist/{tasks-BTURuIlD.d.cts → tasks-BZb3rt5m.d.cts} +69 -904
  46. package/package.json +10 -9
  47. package/dist/chunk-6KPGCPGW.js.map +0 -1
  48. package/dist/chunk-IIIRXFKG.js.map +0 -1
  49. package/dist/chunk-U2U5X3LY.js.map +0 -1
  50. package/dist/member-import-4VSE3yYo.d.cts +0 -46
  51. package/dist/member-import-BQDFoSyf.d.ts +0 -46
package/dist/helpers.cjs CHANGED
@@ -46,6 +46,8 @@ __export(helpers_exports, {
46
46
  resolveOutboundPhoneNumberId: () => resolveOutboundPhoneNumberId,
47
47
  resolveOutboundWorkflowId: () => resolveOutboundWorkflowId,
48
48
  signWebhookPayload: () => signWebhookPayload,
49
+ toSafeBusinessImportPreview: () => toSafeBusinessImportPreview,
50
+ toSafeBusinessImportResult: () => toSafeBusinessImportResult,
49
51
  toSafeMemberImportPreview: () => toSafeMemberImportPreview,
50
52
  toSafeMemberImportSummary: () => toSafeMemberImportSummary,
51
53
  upsertDataRecordForMember: () => upsertDataRecordForMember,
@@ -467,6 +469,43 @@ var ChatInteractionController = class {
467
469
  }
468
470
  };
469
471
 
472
+ // src/helpers/business-import.ts
473
+ function toSafeRow(row, legalEntityUuid) {
474
+ return {
475
+ row: row.row,
476
+ action: row.action,
477
+ legalEntityUuid: legalEntityUuid ?? void 0,
478
+ proposedChanges: row.proposedChanges,
479
+ reason: row.reason ?? void 0,
480
+ error: row.error ?? void 0
481
+ };
482
+ }
483
+ function toSafeIssue({ row, column, columnPosition, code }) {
484
+ return { row, column, columnPosition, code };
485
+ }
486
+ function toSafeBusinessImportPreview(preview) {
487
+ return {
488
+ previewPlanToken: preview.previewPlanToken,
489
+ totalRows: preview.totalRows,
490
+ summary: preview.summary,
491
+ rows: preview.rows.map((row) => toSafeRow(row, row.match?.legalEntityUuid)),
492
+ ignoredColumnPositions: preview.ignoredColumnPositions,
493
+ issues: preview.issues?.map(toSafeIssue),
494
+ issueCount: preview.issueCount
495
+ };
496
+ }
497
+ function toSafeBusinessImportResult(result) {
498
+ return {
499
+ importId: result.importId,
500
+ totalRows: result.totalRows,
501
+ summary: result.summary,
502
+ rows: result.rows.map((row) => toSafeRow(row, row.legalEntityUuid)),
503
+ ignoredColumnPositions: result.ignoredColumnPositions,
504
+ issues: result.issues?.map(toSafeIssue),
505
+ issueCount: result.issueCount
506
+ };
507
+ }
508
+
470
509
  // src/helpers/member-import.ts
471
510
  function toSafeMemberImportPreview(preview) {
472
511
  return {
@@ -527,6 +566,8 @@ function toSafeMemberImportSummary(event) {
527
566
  resolveOutboundPhoneNumberId,
528
567
  resolveOutboundWorkflowId,
529
568
  signWebhookPayload,
569
+ toSafeBusinessImportPreview,
570
+ toSafeBusinessImportResult,
530
571
  toSafeMemberImportPreview,
531
572
  toSafeMemberImportSummary,
532
573
  upsertDataRecordForMember,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers/index.ts","../src/helpers/outbound.ts","../src/api/base.ts","../src/helpers/enrollment.ts","../src/helpers/webhooks.ts","../src/helpers/workspace-export-archive.ts","../src/helpers/chat-interaction.ts","../src/helpers/member-import.ts"],"sourcesContent":["export {\n findMemberByPhone,\n listOutboundPhoneNumbers,\n normalizePhoneLast10,\n resolveOutboundPhoneNumberId,\n resolveOutboundWorkflowId,\n type OutboundPhoneNumberConfigDefaults,\n type OutboundPhoneNumberOption,\n type WorkspacePhoneNumbersPayload,\n} from './outbound';\n\nexport {\n resolveMemberId,\n findOrCreateMemberLabels,\n upsertDataRecordForMember,\n enrollMemberInJourney,\n type MemberRef,\n type EnrollMemberInJourneyOptions,\n type EnrollMemberInJourneyResult,\n} from './enrollment';\n\nexport {\n WEBHOOK_SIGNATURE_HEADER,\n signWebhookPayload,\n verifyWebhookSignature,\n type VerifyWebhookOptions,\n type VerifyWebhookResult,\n} from './webhooks';\n\nexport {\n MAX_EXPORT_JSON_BYTES,\n WORKSPACE_EXPORT_JSON_MEMBER,\n extractWorkspaceExportJson,\n extractZipMember,\n isZipBuffer,\n} from './workspace-export-archive';\n\nexport { ChatInteractionController } from './chat-interaction';\n\nexport { toSafeMemberImportPreview, toSafeMemberImportSummary } from './member-import';\n","import type { GravityRailClient } from '../client/client';\nimport type { Member } from '../types/member-types';\n\nexport interface OutboundPhoneNumberOption {\n id: number;\n number: string;\n name: string | null;\n}\n\nexport interface WorkspacePhoneNumbersPayload {\n phones: OutboundPhoneNumberOption[];\n defaultPhoneNumberId: number | null;\n}\n\n/** App/env fallbacks when resolving outbound phone numbers. */\nexport interface OutboundPhoneNumberConfigDefaults {\n /** e.g. GRAVITY_RAIL_PHONE_NUMBER_ID */\n phoneNumberId?: number;\n /** Explicit selection overriding workspace default */\n requestedPhoneNumberId?: number;\n}\n\n/** Strip to digits and return the last 10 (US-friendly match). */\nexport function normalizePhoneLast10(phone: string): string {\n const digits = phone.replace(/\\D/g, '');\n return digits.length >= 10 ? digits.slice(-10) : digits;\n}\n\nfunction phonesMatchLast10(a: string, b: string): boolean {\n const da = normalizePhoneLast10(a);\n const db = normalizePhoneLast10(b);\n if (!da || !db) return false;\n if (da.length >= 10 && db.length >= 10) {\n return da === db;\n }\n return da === db;\n}\n\nexport async function listOutboundPhoneNumbers(\n client: GravityRailClient,\n workspaceUuid: string\n): Promise<WorkspacePhoneNumbersPayload> {\n const [phones, defaults] = await Promise.all([\n client.getPhoneNumbers(workspaceUuid, { isArchived: false }),\n client.getWorkspaceDefaults(workspaceUuid),\n ]);\n\n const voicePhones = phones\n .filter((phone) => phone.enableVoice && !phone.isArchived)\n .map((phone) => ({\n id: phone.id,\n number: phone.number,\n name: phone.name,\n }));\n\n let defaultPhoneNumberId = defaults.defaultPhoneNumberId ?? null;\n if (\n defaultPhoneNumberId !== null &&\n !voicePhones.some((phone) => phone.id === defaultPhoneNumberId)\n ) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n if (defaultPhoneNumberId === null) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n\n return { phones: voicePhones, defaultPhoneNumberId };\n}\n\nexport async function resolveOutboundPhoneNumberId(\n client: GravityRailClient,\n workspaceUuid: string,\n configDefaults: OutboundPhoneNumberConfigDefaults\n): Promise<number> {\n const { phones, defaultPhoneNumberId } = await listOutboundPhoneNumbers(client, workspaceUuid);\n\n if (phones.length === 0) {\n throw new Error(\n 'No voice-enabled phone numbers in this workspace. Add a line in Gravity Rail first.'\n );\n }\n\n const requestedId = configDefaults.requestedPhoneNumberId;\n const candidate =\n requestedId ?? defaultPhoneNumberId ?? configDefaults.phoneNumberId ?? phones[0]?.id;\n\n if (candidate === undefined || !phones.some((phone) => phone.id === candidate)) {\n throw new Error('Selected outbound phone number is not available.');\n }\n\n return candidate;\n}\n\nexport async function resolveOutboundWorkflowId(\n client: GravityRailClient,\n workspaceUuid: string,\n defaultWorkflowId: number,\n override?: number\n): Promise<number> {\n const workflowsPage = await client.getWorkflows(workspaceUuid, { archived: false });\n const options = workflowsPage.items\n .filter((item) => !item.workflow.archived)\n .map((item) => ({\n id: item.workflow.id,\n name: item.workflow.name,\n }))\n .sort((a, b) => a.name.localeCompare(b.name));\n\n if (options.length === 0) {\n throw new Error('No workflows in this workspace. Create a workflow in Gravity Rail first.');\n }\n\n let resolvedDefault = defaultWorkflowId;\n if (!options.some((workflow) => workflow.id === resolvedDefault)) {\n resolvedDefault = options[0]?.id ?? defaultWorkflowId;\n }\n\n const candidate = override ?? resolvedDefault;\n\n if (!options.some((workflow) => workflow.id === candidate)) {\n throw new Error('Selected workflow is not available.');\n }\n\n return candidate;\n}\n\nexport async function findMemberByPhone(\n client: GravityRailClient,\n workspaceUuid: string,\n phone: string\n): Promise<Member | null> {\n const searchDigits = phone.replace(/\\D/g, '');\n\n for (let page = 1; page <= 5; page += 1) {\n const response = await client.getWorkspaceMembers(workspaceUuid, page, 50, searchDigits);\n const match = response.items.find(\n (member) => member.phone && phonesMatchLast10(member.phone, phone)\n );\n if (match) return match;\n\n if (page >= response.totalPages) break;\n }\n\n return null;\n}\n","// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\n/** Browser-console sink for API failures. A fixed event name only — never the\n * error object, its ``name``, or response-derived ``message``/``errorData``. */\nfunction logApiClientError(_error: unknown): void {\n console.warn('API request failed');\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n authUrl: string;\n /** Requested authentication contexts. The server must verify the new evidence. */\n acrValues?: string[];\n /** The SDK sent an org credential on the request that produced this challenge. */\n sessionRejected?: boolean;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Bearer handlers return a candidate; cookie handlers may resolve without a value.\n * `sessionRejected` describes the credential sent on that request, without\n * exposing it. A rejected cached candidate requires fresh authentication.\n */\nexport interface OrgAuthSessionCandidate {\n session: string;\n orgUuid: string;\n /** Local provenance only; the server still validates the credential. */\n source: 'cache' | 'new';\n /** Cleanup for this exact candidate when its own org rejects it. */\n onRejected?: () => void;\n}\n\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<OrgAuthSessionCandidate | void>;\ntype OrgAuthCompletion = OrgAuthSessionCandidate['source'] | 'cookie';\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", auth_url=\"...\"\n * (the challenge names no cookie: a browser's org session is an httpOnly\n * cookie on its own host, and a bearer client sends `X-Org-Session`).\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n const acrValues = wwwAuthenticate\n .match(/acr_values=\"([^\"]*)\"/)?.[1]\n ?.trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (!orgUuidMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n authUrl: authUrlMatch[1],\n ...(acrValues?.length ? { acrValues } : {}),\n };\n}\n\n/**\n * The API versions a client can address. `/api/v2` is every existing method's\n * base; `/api/v3` serves the Chat resource\n * (`docs/decisions/api/2026-11-09-1-api-v3-begins-with-the-chat-resource.md`).\n */\ntype ApiVersion = 'v2' | 'v3';\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set('X-Org-Session', token);\n}\n\n/**\n * Transport and credential for every request the client makes.\n *\n * - **Bearer** (`apiKey` set): `Authorization: Bearer <apiKey>` on every\n * request, no cookies. This is how non-browser consumers (the CLI, servers,\n * API keys) and bearer-holding browser runtimes (widget iframes) call the API.\n * - **Same-origin session** (no `apiKey`): no `Authorization` header and\n * `credentials: 'same-origin'`. The browser presents the host's httpOnly\n * session cookie, and only to the origin the page is on; the client never\n * reads a cookie to build a credential. A browser app points `baseUrl` at its\n * own origin, which serves `/api/v2` and `/api/v3` (Gravity Rail's edge on\n * full-account hosts, the frontend's proxy on Site hosts).\n *\n * The org-auth challenge (`WWW-Authenticate: Bearer realm=\"org\"`) is answered by\n * `setOrgAuthHandler`. A bearer client's handler hands back the org session with\n * a candidate result, which is sent as `X-Org-Session`; in same-origin session\n * mode the org session is an httpOnly cookie on the page's origin, so the\n * request is retried once after the handler and the browser presents it.\n * A bearer request that starts without an org credential may first try a\n * cached candidate, then make one fresh-auth attempt if the server rejects\n * it. A request that starts with an org credential has only the fresh attempt.\n */\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: {\n orgUuid: string;\n requestRevision: number;\n promise: Promise<OrgAuthCompletion>;\n } | null = null;\n private orgSessionRevision = 0;\n private orgSessionRejectionHandler?: () => void;\n private orgSession?: string;\n /**\n * Optional issuer context supplied with an opaque credential. A handler\n * cannot complete a challenge with a session explicitly bound to another org.\n * The server remains responsible for validating the credential itself.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the opaque org session credential a bearer client sends as `X-Org-Session`.\n * Only opaque `gr_sess_` credentials are supported. A legacy org token\n * raises an error; sign in to the organization again to obtain a session.\n * Pass `undefined` to clear the session.\n *\n * `orgUuid` is the org that issued the credential. When supplied by an\n * org-auth handler, it must match the challenge the handler completes.\n * Callers without that context may omit it. Any rejected credential can\n * trigger one reauthentication attempt, including for the same org.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n if (session !== undefined && !/^gr_sess_[A-Za-z0-9_-]+$/.test(session)) {\n throw new Error(\n 'Unsupported organization session. Sign in again to obtain an opaque gr_sess_ credential.'\n );\n }\n this.orgSessionRejectionHandler = undefined;\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n this.orgSessionRevision += 1;\n }\n\n /**\n * The `credentials` a request carries: none for a bearer client (the fetch\n * default), the page's own-origin cookies for a same-origin session.\n */\n private credentialsInit(): Pick<RequestInit, 'credentials'> {\n return this.apiKey ? {} : { credentials: 'same-origin' };\n }\n\n /**\n * Run the org-auth handler once for concurrent challenges. A bearer client's\n * handler returns a candidate; a same-origin session's\n * handler leaves an httpOnly org-session cookie on the page's origin instead,\n * which the retry presents. A bearer client whose handler issued nothing has\n * nothing to retry with.\n */\n private async answerOrgAuthChallenge(\n info: OrgAuthInfo,\n presented: string | null,\n requestRevision: number\n ): Promise<OrgAuthCompletion> {\n const handler = this.orgAuthHandler;\n if (!handler) throw new ApiError('Organization authentication handler is unavailable', 401);\n if (this.orgAuthInProgress) {\n if (\n this.orgAuthInProgress.orgUuid !== info.orgUuid ||\n this.orgAuthInProgress.requestRevision !== requestRevision\n ) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n return this.orgAuthInProgress.promise;\n }\n if (this.orgSessionRevision !== requestRevision) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n this.clearOrgSessionIfCurrent(presented);\n const attemptRevision = this.orgSessionRevision;\n const promise: Promise<OrgAuthCompletion> = Promise.resolve()\n .then(() => handler(info))\n .then((candidate): OrgAuthCompletion => {\n if (this.orgSessionRevision !== attemptRevision) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n if (candidate === undefined) {\n if (this.apiKey) {\n throw new ApiError(\n 'Organization authentication must return a session candidate',\n 401\n );\n }\n return 'cookie';\n }\n if (\n !candidate ||\n typeof candidate.session !== 'string' ||\n (candidate.source !== 'cache' && candidate.source !== 'new')\n ) {\n throw new ApiError(\n 'Organization authentication returned an invalid session candidate',\n 401\n );\n }\n if (candidate.orgUuid !== info.orgUuid) {\n throw new ApiError(\n 'Organization authentication issued a session for another organization',\n 401\n );\n }\n if (candidate.source === 'cache' && info.sessionRejected) {\n throw new ApiError(\n 'Organization authentication requires a newly issued session after rejection',\n 401\n );\n }\n this.setOrgSession(candidate.session, candidate.orgUuid);\n let rejected = false;\n this.orgSessionRejectionHandler = () => {\n if (rejected) return;\n rejected = true;\n candidate.onRejected?.();\n };\n return candidate.source;\n })\n .finally(() => {\n if (this.orgAuthInProgress?.promise === promise) this.orgAuthInProgress = null;\n });\n this.orgAuthInProgress = { orgUuid: info.orgUuid, requestRevision, promise };\n return promise;\n }\n\n private assertOrgAuthContext(orgUuid: string): void {\n if (\n (this.orgSession && this.orgSessionOrgUuid !== orgUuid) ||\n (this.apiKey && !this.orgSession)\n ) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n }\n\n private notifyOrgSessionRejected(\n presented: string | null,\n callback: (() => void) | undefined\n ): void {\n try {\n callback?.();\n } catch {\n this.clearOrgSessionIfCurrent(presented);\n throw new ApiError('Could not discard rejected organization session', 401);\n }\n }\n\n private hasNewerOrgSession(presented: string | null, orgUuid: string): boolean {\n // A concurrent login may have replaced the rejected credential. Retry\n // that replacement only with an explicit matching org binding; the\n // server still validates it, and this consumes the existing retry budget.\n return Boolean(\n presented &&\n this.orgSession &&\n this.orgSession !== presented &&\n this.orgSessionOrgUuid === orgUuid\n );\n }\n\n private clearOrgSessionIfCurrent(expected: string | null | undefined): void {\n if (this.orgSession !== expected || this.orgSession === undefined) return;\n this.setOrgSession(undefined);\n }\n\n protected async fetch<T>(\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n return this.fetchApiVersion<T>(\n 'v2',\n endpoint,\n options,\n orgAuthRetriesRemaining,\n enhancedAuthRetry\n );\n }\n\n /**\n * `fetch` against a named API version: `/api/{version}/{endpoint}`, with the\n * same credentials, step-up retry, org-auth challenge handling and\n * org-session rejection bookkeeping. `fetch` is this method bound to `v2`.\n */\n protected async fetchApiVersion<T>(\n version: ApiVersion,\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (orgAuthInfo.acrValues?.includes('urn:gravity:mfa')) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && version === 'v2' && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property).\n //\n // TWO body shapes reach here and both carry structure:\n //\n // * `detail` IS the structured object — the member/account contact\n // conflicts build their whole payload as `HTTPException.detail`.\n // * `detail` is PROSE and the machine-readable fields sit beside it\n // at the top level. That is what the domain exception handlers\n // emit: `conflict_handler` writes `{detail, code, ...payload}`, so\n // a Journey v2 refusal arrives as\n // `{detail: \"...\", code: \"journey_v2_invalid_topology\", issues: [...]}`.\n //\n // `detail || errorData` picked the prose string for the second shape,\n // which is not an object, so the branch fell through and `code` and\n // `issues` were dropped on the floor — leaving a client unable to\n // tell a definition conflict from a structural refusal, or to point\n // at the resources a validator rejected. Prefer an OBJECT detail and\n // otherwise read the body itself; the message is unchanged in both\n // cases (prose still wins when there is prose).\n const detail = errorData.detail;\n const structuredError = detail && typeof detail === 'object' ? detail : errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message =\n (typeof detail === 'string' && detail) ||\n structuredError.message ||\n structuredError.code ||\n 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n const simpleError = new ApiError(errorMessage, response.status);\n // A prose `detail` STRING alongside a top-level `code` is the shape\n // the backend's domain-validation handler produces: it merges an\n // exception's `payload` into the body and keeps `detail`\n // authoritative. That misses the structured branch above, because\n // `errorData.detail || errorData` resolves to the string. Carry the\n // body through so a caller can still branch on the token — the\n // alternative is parsing `detail`, which is deliberately\n // human-facing prose and not a stable contract.\n if (typeof errorData.code === 'string') {\n simpleError.errorData = errorData;\n }\n throw simpleError;\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = [],\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n // Without this, fetch labels a string body text/plain and FastAPI\n // rejects a JSON body parameter with 422 \"Validation failed\" (every\n // live-view browser storage save, until 2026-10-27).\n if (typeof options?.body === 'string' && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (\n !allowedErrorStatuses.includes(401) &&\n orgAuthInfo.acrValues?.includes('urn:gravity:mfa')\n ) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n}\n","/**\n * Enrollment-flow helpers: the small compound operations every integration\n * re-implements when wiring \"register member → populate a form → enroll into a\n * journey\". They build on the plain client methods and are safe to call from a\n * server-side BFF.\n */\nimport { ApiError } from '../api/base';\nimport type { GravityRailClient } from '../client/client';\nimport type { DataRecord } from '../types/data-types';\nimport { findMemberByPhone } from './outbound';\n\n/** Identify a member by any one of these; `memberId` wins when present. */\nexport interface MemberRef {\n memberId?: number;\n phone?: string;\n externalId?: string;\n}\n\n/** Resolve a `MemberRef` to a concrete member id (throws if none matches). */\nexport async function resolveMemberId(\n client: GravityRailClient,\n workspaceUuid: string,\n ref: MemberRef\n): Promise<number> {\n if (typeof ref.memberId === 'number') {\n return ref.memberId;\n }\n if (ref.phone) {\n const member = await findMemberByPhone(client, workspaceUuid, ref.phone);\n if (member?.id) return member.id;\n // Do not put the phone (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided phone number');\n }\n if (ref.externalId) {\n const page = await client.getWorkspaceMembers(workspaceUuid, 1, 25, ref.externalId);\n const match = page.items.find((m) => m.externalId === ref.externalId);\n if (match?.id) return match.id;\n // Do not put the externalId (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided externalId');\n }\n throw new Error('Provide memberId, phone, or externalId');\n}\n\n/**\n * Find member labels by name, creating any that don't exist, and return their\n * ids. Case-insensitive match on name. (The API derives the slug from the name.)\n */\nexport async function findOrCreateMemberLabels(\n client: GravityRailClient,\n workspaceUuid: string,\n names: string[],\n options: { color?: string } = {}\n): Promise<number[]> {\n const clean = names.map((n) => n.trim()).filter(Boolean);\n if (clean.length === 0) return [];\n\n const existing = await client.getMemberLabels(workspaceUuid);\n const byName = new Map(existing.map((l) => [l.name.toLowerCase(), l]));\n const ids: number[] = [];\n for (const name of clean) {\n const found = byName.get(name.toLowerCase());\n if (found) {\n ids.push(found.id);\n continue;\n }\n const created = await client.createMemberLabel(workspaceUuid, {\n name,\n color: options.color ?? '#6366f1',\n });\n byName.set(name.toLowerCase(), created);\n ids.push(created.id);\n }\n return ids;\n}\n\n/**\n * Idempotently write a member-scoped data record: update the member's existing\n * record for the DataType if one exists, otherwise create it.\n */\nexport async function upsertDataRecordForMember(\n client: GravityRailClient,\n workspaceUuid: string,\n dataTypeId: number,\n memberId: number,\n fieldValues: Record<string, unknown>\n): Promise<DataRecord> {\n const existing = await client.getDataRecords(workspaceUuid, dataTypeId, {\n memberId,\n pageSize: 1,\n });\n const record = existing.items?.[0];\n const body = { dataTypeId, memberId, fieldValues };\n if (record?.id) {\n return client.updateDataRecord(workspaceUuid, dataTypeId, record.id, body);\n }\n return client.createDataRecord(workspaceUuid, dataTypeId, body);\n}\n\nexport interface EnrollMemberInJourneyOptions extends MemberRef {\n /** Journey to enroll into. Defaults to the workspace's first journey. */\n journeyId?: number;\n /** Labels to apply to the member before enrolling (journey/cohort tags). */\n labels?: string[];\n labelColor?: string;\n}\n\nexport interface EnrollMemberInJourneyResult {\n journeyId: number;\n journeyName?: string;\n memberId: number;\n appliedLabels: string[];\n}\n\n/**\n * Resolve a member, optionally tag them, and enroll them into a journey. The API\n * skips an already-enrolled member and answers 201 with only the enrollments it\n * created. A 409 means the member was not enrolled (for example, refused as a\n * test or archived member); this helper swallows it.\n */\nexport async function enrollMemberInJourney(\n client: GravityRailClient,\n workspaceUuid: string,\n options: EnrollMemberInJourneyOptions\n): Promise<EnrollMemberInJourneyResult> {\n const memberId = await resolveMemberId(client, workspaceUuid, options);\n\n const page = await client.getJourneys(workspaceUuid);\n const journeys = page.items ?? [];\n let journey: { id: number; name?: string } | undefined;\n if (options.journeyId != null) {\n journey = journeys.find((j) => j.id === options.journeyId) ?? { id: options.journeyId };\n } else {\n journey = journeys[0];\n }\n if (!journey) {\n throw new Error('No journey to enroll into: pass journeyId or create a journey');\n }\n\n const labelNames = (options.labels ?? []).map((l) => l.trim()).filter(Boolean);\n if (labelNames.length > 0) {\n const labelIds = await findOrCreateMemberLabels(client, workspaceUuid, labelNames, {\n color: options.labelColor,\n });\n // updateMember replaces the label set, so merge with the member's existing\n // labels rather than wiping them.\n const member = await client.getWorkspaceMember(workspaceUuid, memberId);\n const existingIds = (member.labels ?? [])\n .map((l) => l.id)\n .filter((id): id is number => typeof id === 'number');\n const mergedIds = Array.from(new Set([...existingIds, ...labelIds]));\n await client.updateMember(workspaceUuid, memberId, { labelIds: mergedIds });\n }\n\n try {\n await client.enrollMembers(workspaceUuid, journey.id, { memberId });\n } catch (error) {\n if (!(error instanceof ApiError && error.statusCode === 409)) {\n throw error;\n }\n }\n\n return { journeyId: journey.id, journeyName: journey.name, memberId, appliedLabels: labelNames };\n}\n","/**\n * Webhook signature helpers.\n *\n * Gravity Rail signs every outbound webhook with HMAC-SHA256 and sends the\n * result in the `X-Webhook-Signature` header as `t={unixSeconds},v1={hexDigest}`.\n * The signed message is the timestamp, a literal dot, then the raw request body:\n *\n * HMAC_SHA256(secret, `${t}.` + rawBody)\n *\n * The timestamp defeats replay — reject signatures older than the tolerance\n * window. Verify the signature against the RAW request body bytes, before any\n * JSON parsing/re-serialization.\n *\n * These use the Web Crypto API (`crypto.subtle`), so they run unchanged in Node\n * 18+ and the browser/edge runtimes.\n */\n\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Constant-time comparison of two equal-length hex strings. */\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i += 1) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Produce the `X-Webhook-Signature` header value for a payload. Primarily useful\n * for tests and for re-signing when relaying webhooks.\n */\nexport async function signWebhookPayload(\n rawBody: string,\n secret: string,\n timestampSeconds: number\n): Promise<string> {\n const digest = await hmacSha256Hex(secret, `${timestampSeconds}.${rawBody}`);\n return `t=${timestampSeconds},v1=${digest}`;\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature in seconds (default 300). */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — for deterministic tests. */\n nowSeconds?: number;\n}\n\nexport type VerifyWebhookResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Verify a webhook signature against the raw body. Returns a discriminated\n * result so callers can log the reason; it never throws on a bad signature.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {}\n): Promise<VerifyWebhookResult> {\n if (!signatureHeader) {\n return { ok: false, reason: 'missing signature header' };\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const idx = segment.indexOf('=');\n if (idx > 0) {\n parts[segment.slice(0, idx).trim()] = segment.slice(idx + 1).trim();\n }\n }\n\n const timestamp = Number(parts.t);\n const provided = parts.v1;\n if (!Number.isFinite(timestamp) || !provided) {\n return { ok: false, reason: 'malformed signature header' };\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n return { ok: false, reason: 'signature timestamp outside tolerance' };\n }\n\n const expected = await hmacSha256Hex(secret, `${timestamp}.${rawBody}`);\n if (!timingSafeEqualHex(expected, provided)) {\n return { ok: false, reason: 'signature mismatch' };\n }\n\n return { ok: true };\n}\n","/**\n * Helpers for the portable workspace export ZIP.\n *\n * Layout: ``export.json`` plus ``blobs/ab/cd/<sha256>``.\n */\n\nexport const WORKSPACE_EXPORT_JSON_MEMBER = 'export.json';\nexport const MAX_EXPORT_JSON_BYTES = 8 * 1024 * 1024;\n\nconst EOCD_SIGNATURE = 0x06054b50;\nconst CDFH_SIGNATURE = 0x02014b50;\nconst LFH_SIGNATURE = 0x04034b50;\nconst ZIP_STORED = 0;\nconst ZIP_DEFLATED = 8;\n\nfunction requireRange(bytes: Uint8Array, start: number, length: number): void {\n if (start < 0 || length < 0 || start + length > bytes.length) {\n throw new Error('ZIP offsets are out of range.');\n }\n}\n\nfunction u16(bytes: Uint8Array, offset: number): number {\n requireRange(bytes, offset, 2);\n return bytes[offset]! | (bytes[offset + 1]! << 8);\n}\n\nfunction u32(bytes: Uint8Array, offset: number): number {\n requireRange(bytes, offset, 4);\n return (\n (bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24)) >>>\n 0\n );\n}\n\nexport function isZipBuffer(bytes: Uint8Array): boolean {\n return bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4b;\n}\n\nasync function inflateRaw(data: Uint8Array, maxBytes: number): Promise<Uint8Array> {\n if (typeof DecompressionStream === 'function') {\n const stream = new Blob([data as BlobPart])\n .stream()\n .pipeThrough(new DecompressionStream('deflate-raw'));\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new Error('ZIP member exceeds the export.json size limit.');\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n }\n // Keep the Node-only fallback out of browser bundles. Native decompression\n // above handles browsers; unsupported browsers get a clear capability error.\n if (typeof window !== 'undefined') {\n throw new Error('This browser does not support ZIP decompression.');\n }\n const zlib = await import(/* webpackIgnore: true */ 'node:zlib');\n return Uint8Array.from(zlib.inflateRawSync(data, { maxOutputLength: maxBytes }));\n}\n\nfunction findEocdOffset(bytes: Uint8Array): number {\n const min = 22;\n const maxComment = 65535;\n const start = Math.max(0, bytes.length - (min + maxComment));\n for (let i = bytes.length - min; i >= start; i--) {\n if (u32(bytes, i) !== EOCD_SIGNATURE) continue;\n const commentLength = u16(bytes, i + 20);\n if (i + min + commentLength === bytes.length) {\n return i;\n }\n }\n throw new Error('Not a ZIP archive (missing end-of-central-directory).');\n}\n\n/**\n * Extract a single ZIP member. Supports STORE and DEFLATE (method 8).\n */\nexport async function extractZipMember(bytes: Uint8Array, memberName: string): Promise<Uint8Array> {\n const eocd = findEocdOffset(bytes);\n const entries = u16(bytes, eocd + 10);\n let offset = u32(bytes, eocd + 16);\n for (let i = 0; i < entries; i++) {\n if (u32(bytes, offset) !== CDFH_SIGNATURE) {\n throw new Error('ZIP central directory is corrupt.');\n }\n requireRange(bytes, offset, 46);\n const method = u16(bytes, offset + 10);\n const compressedSize = u32(bytes, offset + 20);\n const uncompressedSize = u32(bytes, offset + 24);\n const nameLen = u16(bytes, offset + 28);\n const extraLen = u16(bytes, offset + 30);\n const commentLen = u16(bytes, offset + 32);\n const localOffset = u32(bytes, offset + 42);\n requireRange(bytes, offset + 46, nameLen);\n const name = new TextDecoder().decode(bytes.subarray(offset + 46, offset + 46 + nameLen));\n offset += 46 + nameLen + extraLen + commentLen;\n requireRange(bytes, offset, 0);\n if (name !== memberName) continue;\n if (uncompressedSize === 0xffffffff || compressedSize === 0xffffffff) {\n throw new Error('ZIP64 members are not supported for export.json.');\n }\n if (uncompressedSize > MAX_EXPORT_JSON_BYTES || compressedSize > MAX_EXPORT_JSON_BYTES) {\n throw new Error('ZIP member exceeds the export.json size limit.');\n }\n\n if (u32(bytes, localOffset) !== LFH_SIGNATURE) {\n throw new Error(`ZIP local header for ${memberName} is corrupt.`);\n }\n const localNameLen = u16(bytes, localOffset + 26);\n const localExtraLen = u16(bytes, localOffset + 28);\n const dataStart = localOffset + 30 + localNameLen + localExtraLen;\n requireRange(bytes, dataStart, compressedSize);\n const compressed = bytes.subarray(dataStart, dataStart + compressedSize);\n if (method === ZIP_STORED) {\n if (compressed.length !== uncompressedSize) {\n throw new Error('ZIP stored member size does not match the directory.');\n }\n return compressed.slice();\n }\n if (method === ZIP_DEFLATED) {\n const inflated = await inflateRaw(compressed, MAX_EXPORT_JSON_BYTES);\n if (inflated.length !== uncompressedSize) {\n throw new Error('ZIP deflated member size does not match the directory.');\n }\n return inflated;\n }\n throw new Error(`Unsupported ZIP compression method ${method} for ${memberName}.`);\n }\n throw new Error(`ZIP is missing ${memberName}.`);\n}\n\nexport async function extractWorkspaceExportJson(bytes: Uint8Array): Promise<string> {\n const raw = await extractZipMember(bytes, WORKSPACE_EXPORT_JSON_MEMBER);\n return new TextDecoder().decode(raw);\n}\n","import type { ChatsApi } from '../api/chats';\nimport type { InteractionMode, InteractionSessionResponse } from '../types/chat-types';\n\ntype InteractionApi = Pick<\n ChatsApi,\n 'createChatInteractionSession' | 'transitionChatInteractionSession'\n>;\n\n/** One client's mode history in one Chat. Create a separate controller per device/session. */\nexport class ChatInteractionController {\n private current: InteractionSessionResponse | undefined;\n private pending: { mode: InteractionMode; requestId: string } | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n private readonly clientSessionId = crypto.randomUUID();\n\n constructor(\n private readonly api: InteractionApi,\n private readonly workspaceId: string,\n private readonly chatId: number\n ) {}\n\n /** Serialize switches and reuse request IDs when a response is lost. */\n ensure(mode: InteractionMode): Promise<InteractionSessionResponse> {\n const operation = this.tail.then(async () => {\n // Resolve an uncertain earlier write before selecting the next mode.\n if (this.pending) await this.applyPending();\n if (this.current?.mode !== mode) {\n this.pending = { mode, requestId: crypto.randomUUID() };\n await this.applyPending();\n }\n if (!this.current) throw new Error('Interaction session unavailable');\n return this.current;\n });\n this.tail = operation.catch(() => undefined);\n return operation;\n }\n\n private async applyPending(): Promise<void> {\n const pending = this.pending;\n if (!pending) return;\n this.current = this.current\n ? await this.api.transitionChatInteractionSession(\n this.workspaceId,\n this.chatId,\n this.current.id,\n pending\n )\n : await this.api.createChatInteractionSession(this.workspaceId, this.chatId, {\n ...pending,\n clientSessionId: this.clientSessionId,\n });\n this.pending = undefined;\n }\n}\n","import type { MemberImportPreviewResponse, MemberImportStreamEvent } from '../types/member-types';\n\n/** Counts and row references for logs/CLI/chat. Drops identity, contacts and free text. */\nexport function toSafeMemberImportPreview(preview: MemberImportPreviewResponse) {\n return {\n previewPlanToken: preview.previewPlanToken,\n totalRows: preview.totalRows,\n summary: preview.summary,\n rows: preview.rows.map((row) => ({\n row: row.row,\n action: row.action,\n memberId: row.match?.memberId,\n matchType: row.match?.matchType,\n conflict: row.conflict\n ? { code: row.conflict.code, fields: row.conflict.fields }\n : undefined,\n proposedChanges: row.proposedChanges,\n sharedContacts: row.sharedContacts,\n })),\n };\n}\n\n/** Deliberate allowlist: stream conflicts can contain global Account contact values. */\nexport function toSafeMemberImportSummary(event: MemberImportStreamEvent) {\n return {\n total: event.total,\n created: event.created,\n updated: event.updated,\n unchanged: event.unchanged,\n failed: event.failed,\n conflicted: event.conflicted,\n skipped: event.skipped,\n failedRows: event.failedRows,\n conflictRows: event.conflictRows,\n skippedRows: event.skippedRows,\n conflicts: event.conflicts?.map(({ row, code, fields, member_id }) => ({\n row,\n code,\n fields,\n memberId: member_id,\n })),\n updatedMembers: event.updatedMembers?.map(({ row, memberId, changes }) => ({\n row,\n memberId,\n changes,\n })),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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/base.ts","../src/helpers/enrollment.ts","../src/helpers/webhooks.ts","../src/helpers/workspace-export-archive.ts","../src/helpers/chat-interaction.ts","../src/helpers/business-import.ts","../src/helpers/member-import.ts"],"sourcesContent":["export {\n findMemberByPhone,\n listOutboundPhoneNumbers,\n normalizePhoneLast10,\n resolveOutboundPhoneNumberId,\n resolveOutboundWorkflowId,\n type OutboundPhoneNumberConfigDefaults,\n type OutboundPhoneNumberOption,\n type WorkspacePhoneNumbersPayload,\n} from './outbound';\n\nexport {\n resolveMemberId,\n findOrCreateMemberLabels,\n upsertDataRecordForMember,\n enrollMemberInJourney,\n type MemberRef,\n type EnrollMemberInJourneyOptions,\n type EnrollMemberInJourneyResult,\n} from './enrollment';\n\nexport {\n WEBHOOK_SIGNATURE_HEADER,\n signWebhookPayload,\n verifyWebhookSignature,\n type VerifyWebhookOptions,\n type VerifyWebhookResult,\n} from './webhooks';\n\nexport {\n MAX_EXPORT_JSON_BYTES,\n WORKSPACE_EXPORT_JSON_MEMBER,\n extractWorkspaceExportJson,\n extractZipMember,\n isZipBuffer,\n} from './workspace-export-archive';\n\nexport { ChatInteractionController } from './chat-interaction';\n\nexport { toSafeBusinessImportPreview, toSafeBusinessImportResult } from './business-import';\nexport { toSafeMemberImportPreview, toSafeMemberImportSummary } from './member-import';\n","import type { GravityRailClient } from '../client/client';\nimport type { Member } from '../types/member-types';\n\nexport interface OutboundPhoneNumberOption {\n id: number;\n number: string;\n name: string | null;\n}\n\nexport interface WorkspacePhoneNumbersPayload {\n phones: OutboundPhoneNumberOption[];\n defaultPhoneNumberId: number | null;\n}\n\n/** App/env fallbacks when resolving outbound phone numbers. */\nexport interface OutboundPhoneNumberConfigDefaults {\n /** e.g. GRAVITY_RAIL_PHONE_NUMBER_ID */\n phoneNumberId?: number;\n /** Explicit selection overriding workspace default */\n requestedPhoneNumberId?: number;\n}\n\n/** Strip to digits and return the last 10 (US-friendly match). */\nexport function normalizePhoneLast10(phone: string): string {\n const digits = phone.replace(/\\D/g, '');\n return digits.length >= 10 ? digits.slice(-10) : digits;\n}\n\nfunction phonesMatchLast10(a: string, b: string): boolean {\n const da = normalizePhoneLast10(a);\n const db = normalizePhoneLast10(b);\n if (!da || !db) return false;\n if (da.length >= 10 && db.length >= 10) {\n return da === db;\n }\n return da === db;\n}\n\nexport async function listOutboundPhoneNumbers(\n client: GravityRailClient,\n workspaceUuid: string\n): Promise<WorkspacePhoneNumbersPayload> {\n const [phones, defaults] = await Promise.all([\n client.getPhoneNumbers(workspaceUuid, { isArchived: false }),\n client.getWorkspaceDefaults(workspaceUuid),\n ]);\n\n const voicePhones = phones\n .filter((phone) => phone.enableVoice && !phone.isArchived)\n .map((phone) => ({\n id: phone.id,\n number: phone.number,\n name: phone.name,\n }));\n\n let defaultPhoneNumberId = defaults.defaultPhoneNumberId ?? null;\n if (\n defaultPhoneNumberId !== null &&\n !voicePhones.some((phone) => phone.id === defaultPhoneNumberId)\n ) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n if (defaultPhoneNumberId === null) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n\n return { phones: voicePhones, defaultPhoneNumberId };\n}\n\nexport async function resolveOutboundPhoneNumberId(\n client: GravityRailClient,\n workspaceUuid: string,\n configDefaults: OutboundPhoneNumberConfigDefaults\n): Promise<number> {\n const { phones, defaultPhoneNumberId } = await listOutboundPhoneNumbers(client, workspaceUuid);\n\n if (phones.length === 0) {\n throw new Error(\n 'No voice-enabled phone numbers in this workspace. Add a line in Gravity Rail first.'\n );\n }\n\n const requestedId = configDefaults.requestedPhoneNumberId;\n const candidate =\n requestedId ?? defaultPhoneNumberId ?? configDefaults.phoneNumberId ?? phones[0]?.id;\n\n if (candidate === undefined || !phones.some((phone) => phone.id === candidate)) {\n throw new Error('Selected outbound phone number is not available.');\n }\n\n return candidate;\n}\n\nexport async function resolveOutboundWorkflowId(\n client: GravityRailClient,\n workspaceUuid: string,\n defaultWorkflowId: number,\n override?: number\n): Promise<number> {\n const workflowsPage = await client.getWorkflows(workspaceUuid, { archived: false });\n const options = workflowsPage.items\n .filter((item) => !item.workflow.archived)\n .map((item) => ({\n id: item.workflow.id,\n name: item.workflow.name,\n }))\n .sort((a, b) => a.name.localeCompare(b.name));\n\n if (options.length === 0) {\n throw new Error('No workflows in this workspace. Create a workflow in Gravity Rail first.');\n }\n\n let resolvedDefault = defaultWorkflowId;\n if (!options.some((workflow) => workflow.id === resolvedDefault)) {\n resolvedDefault = options[0]?.id ?? defaultWorkflowId;\n }\n\n const candidate = override ?? resolvedDefault;\n\n if (!options.some((workflow) => workflow.id === candidate)) {\n throw new Error('Selected workflow is not available.');\n }\n\n return candidate;\n}\n\nexport async function findMemberByPhone(\n client: GravityRailClient,\n workspaceUuid: string,\n phone: string\n): Promise<Member | null> {\n const searchDigits = phone.replace(/\\D/g, '');\n\n for (let page = 1; page <= 5; page += 1) {\n const response = await client.getWorkspaceMembers(workspaceUuid, page, 50, searchDigits);\n const match = response.items.find(\n (member) => member.phone && phonesMatchLast10(member.phone, phone)\n );\n if (match) return match;\n\n if (page >= response.totalPages) break;\n }\n\n return null;\n}\n","// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\n/** Browser-console sink for API failures. A fixed event name only — never the\n * error object, its ``name``, or response-derived ``message``/``errorData``. */\nfunction logApiClientError(_error: unknown): void {\n console.warn('API request failed');\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n authUrl: string;\n /** Requested authentication contexts. The server must verify the new evidence. */\n acrValues?: string[];\n /** The SDK sent an org credential on the request that produced this challenge. */\n sessionRejected?: boolean;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Bearer handlers return a candidate; cookie handlers may resolve without a value.\n * `sessionRejected` describes the credential sent on that request, without\n * exposing it. A rejected cached candidate requires fresh authentication.\n */\nexport interface OrgAuthSessionCandidate {\n session: string;\n orgUuid: string;\n /** Local provenance only; the server still validates the credential. */\n source: 'cache' | 'new';\n /** Cleanup for this exact candidate when its own org rejects it. */\n onRejected?: () => void;\n}\n\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<OrgAuthSessionCandidate | void>;\ntype OrgAuthCompletion = OrgAuthSessionCandidate['source'] | 'cookie';\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", auth_url=\"...\"\n * (the challenge names no cookie: a browser's org session is an httpOnly\n * cookie on its own host, and a bearer client sends `X-Org-Session`).\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n const acrValues = wwwAuthenticate\n .match(/acr_values=\"([^\"]*)\"/)?.[1]\n ?.trim()\n .split(/\\s+/)\n .filter(Boolean);\n\n if (!orgUuidMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n authUrl: authUrlMatch[1],\n ...(acrValues?.length ? { acrValues } : {}),\n };\n}\n\n/**\n * The API versions a client can address. `/api/v2` is every existing method's\n * base; `/api/v3` serves the Chat resource\n * (`docs/decisions/api/2026-11-09-1-api-v3-begins-with-the-chat-resource.md`).\n */\ntype ApiVersion = 'v2' | 'v3';\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set('X-Org-Session', token);\n}\n\n/**\n * Transport and credential for every request the client makes.\n *\n * - **Bearer** (`apiKey` set): `Authorization: Bearer <apiKey>` on every\n * request, no cookies. This is how non-browser consumers (the CLI, servers,\n * API keys) and bearer-holding browser runtimes (widget iframes) call the API.\n * - **Same-origin session** (no `apiKey`): no `Authorization` header and\n * `credentials: 'same-origin'`. The browser presents the host's httpOnly\n * session cookie, and only to the origin the page is on; the client never\n * reads a cookie to build a credential. A browser app points `baseUrl` at its\n * own origin, which serves `/api/v2` and `/api/v3` (Gravity Rail's edge on\n * full-account hosts, the frontend's proxy on Site hosts).\n *\n * The org-auth challenge (`WWW-Authenticate: Bearer realm=\"org\"`) is answered by\n * `setOrgAuthHandler`. A bearer client's handler hands back the org session with\n * a candidate result, which is sent as `X-Org-Session`; in same-origin session\n * mode the org session is an httpOnly cookie on the page's origin, so the\n * request is retried once after the handler and the browser presents it.\n * A bearer request that starts without an org credential may first try a\n * cached candidate, then make one fresh-auth attempt if the server rejects\n * it. A request that starts with an org credential has only the fresh attempt.\n */\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: {\n orgUuid: string;\n requestRevision: number;\n promise: Promise<OrgAuthCompletion>;\n } | null = null;\n private orgSessionRevision = 0;\n private orgSessionRejectionHandler?: () => void;\n private orgSession?: string;\n /**\n * Optional issuer context supplied with an opaque credential. A handler\n * cannot complete a challenge with a session explicitly bound to another org.\n * The server remains responsible for validating the credential itself.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the opaque org session credential a bearer client sends as `X-Org-Session`.\n * Only opaque `gr_sess_` credentials are supported. A legacy org token\n * raises an error; sign in to the organization again to obtain a session.\n * Pass `undefined` to clear the session.\n *\n * `orgUuid` is the org that issued the credential. When supplied by an\n * org-auth handler, it must match the challenge the handler completes.\n * Callers without that context may omit it. Any rejected credential can\n * trigger one reauthentication attempt, including for the same org.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n if (session !== undefined && !/^gr_sess_[A-Za-z0-9_-]+$/.test(session)) {\n throw new Error(\n 'Unsupported organization session. Sign in again to obtain an opaque gr_sess_ credential.'\n );\n }\n this.orgSessionRejectionHandler = undefined;\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n this.orgSessionRevision += 1;\n }\n\n /**\n * The `credentials` a request carries: none for a bearer client (the fetch\n * default), the page's own-origin cookies for a same-origin session.\n */\n private credentialsInit(): Pick<RequestInit, 'credentials'> {\n return this.apiKey ? {} : { credentials: 'same-origin' };\n }\n\n /**\n * Run the org-auth handler once for concurrent challenges. A bearer client's\n * handler returns a candidate; a same-origin session's\n * handler leaves an httpOnly org-session cookie on the page's origin instead,\n * which the retry presents. A bearer client whose handler issued nothing has\n * nothing to retry with.\n */\n private async answerOrgAuthChallenge(\n info: OrgAuthInfo,\n presented: string | null,\n requestRevision: number\n ): Promise<OrgAuthCompletion> {\n const handler = this.orgAuthHandler;\n if (!handler) throw new ApiError('Organization authentication handler is unavailable', 401);\n if (this.orgAuthInProgress) {\n if (\n this.orgAuthInProgress.orgUuid !== info.orgUuid ||\n this.orgAuthInProgress.requestRevision !== requestRevision\n ) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n return this.orgAuthInProgress.promise;\n }\n if (this.orgSessionRevision !== requestRevision) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n this.clearOrgSessionIfCurrent(presented);\n const attemptRevision = this.orgSessionRevision;\n const promise: Promise<OrgAuthCompletion> = Promise.resolve()\n .then(() => handler(info))\n .then((candidate): OrgAuthCompletion => {\n if (this.orgSessionRevision !== attemptRevision) {\n throw new ApiError(\n 'Organization authentication context changed. Retry the request.',\n 401\n );\n }\n if (candidate === undefined) {\n if (this.apiKey) {\n throw new ApiError(\n 'Organization authentication must return a session candidate',\n 401\n );\n }\n return 'cookie';\n }\n if (\n !candidate ||\n typeof candidate.session !== 'string' ||\n (candidate.source !== 'cache' && candidate.source !== 'new')\n ) {\n throw new ApiError(\n 'Organization authentication returned an invalid session candidate',\n 401\n );\n }\n if (candidate.orgUuid !== info.orgUuid) {\n throw new ApiError(\n 'Organization authentication issued a session for another organization',\n 401\n );\n }\n if (candidate.source === 'cache' && info.sessionRejected) {\n throw new ApiError(\n 'Organization authentication requires a newly issued session after rejection',\n 401\n );\n }\n this.setOrgSession(candidate.session, candidate.orgUuid);\n let rejected = false;\n this.orgSessionRejectionHandler = () => {\n if (rejected) return;\n rejected = true;\n candidate.onRejected?.();\n };\n return candidate.source;\n })\n .finally(() => {\n if (this.orgAuthInProgress?.promise === promise) this.orgAuthInProgress = null;\n });\n this.orgAuthInProgress = { orgUuid: info.orgUuid, requestRevision, promise };\n return promise;\n }\n\n private assertOrgAuthContext(orgUuid: string): void {\n if (\n (this.orgSession && this.orgSessionOrgUuid !== orgUuid) ||\n (this.apiKey && !this.orgSession)\n ) {\n throw new ApiError('Organization authentication context changed. Retry the request.', 401);\n }\n }\n\n private notifyOrgSessionRejected(\n presented: string | null,\n callback: (() => void) | undefined\n ): void {\n try {\n callback?.();\n } catch {\n this.clearOrgSessionIfCurrent(presented);\n throw new ApiError('Could not discard rejected organization session', 401);\n }\n }\n\n private hasNewerOrgSession(presented: string | null, orgUuid: string): boolean {\n // A concurrent login may have replaced the rejected credential. Retry\n // that replacement only with an explicit matching org binding; the\n // server still validates it, and this consumes the existing retry budget.\n return Boolean(\n presented &&\n this.orgSession &&\n this.orgSession !== presented &&\n this.orgSessionOrgUuid === orgUuid\n );\n }\n\n private clearOrgSessionIfCurrent(expected: string | null | undefined): void {\n if (this.orgSession !== expected || this.orgSession === undefined) return;\n this.setOrgSession(undefined);\n }\n\n protected async fetch<T>(\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n return this.fetchApiVersion<T>(\n 'v2',\n endpoint,\n options,\n orgAuthRetriesRemaining,\n enhancedAuthRetry\n );\n }\n\n /**\n * `fetch` against a named API version: `/api/{version}/{endpoint}`, with the\n * same credentials, step-up retry, org-auth challenge handling and\n * org-session rejection bookkeeping. `fetch` is this method bound to `v2`.\n */\n protected async fetchApiVersion<T>(\n version: ApiVersion,\n endpoint: string,\n options?: RequestInit,\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/${version}/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchApiVersion<T>(\n version,\n endpoint,\n options,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (orgAuthInfo.acrValues?.includes('urn:gravity:mfa')) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && version === 'v2' && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property).\n //\n // TWO body shapes reach here and both carry structure:\n //\n // * `detail` IS the structured object — the member/account contact\n // conflicts build their whole payload as `HTTPException.detail`.\n // * `detail` is PROSE and the machine-readable fields sit beside it\n // at the top level. That is what the domain exception handlers\n // emit: `conflict_handler` writes `{detail, code, ...payload}`, so\n // a Journey v2 refusal arrives as\n // `{detail: \"...\", code: \"journey_v2_invalid_topology\", issues: [...]}`.\n //\n // `detail || errorData` picked the prose string for the second shape,\n // which is not an object, so the branch fell through and `code` and\n // `issues` were dropped on the floor — leaving a client unable to\n // tell a definition conflict from a structural refusal, or to point\n // at the resources a validator rejected. Prefer an OBJECT detail and\n // otherwise read the body itself; the message is unchanged in both\n // cases (prose still wins when there is prose).\n const detail = errorData.detail;\n const structuredError = detail && typeof detail === 'object' ? detail : errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message =\n (typeof detail === 'string' && detail) ||\n structuredError.message ||\n structuredError.code ||\n 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n const simpleError = new ApiError(errorMessage, response.status);\n // A prose `detail` STRING alongside a top-level `code` is the shape\n // the backend's domain-validation handler produces: it merges an\n // exception's `payload` into the body and keeps `detail`\n // authoritative. That misses the structured branch above, because\n // `errorData.detail || errorData` resolves to the string. Carry the\n // body through so a caller can still branch on the token — the\n // alternative is parsing `detail`, which is deliberately\n // human-facing prose and not a stable contract.\n if (typeof errorData.code === 'string') {\n simpleError.errorData = errorData;\n }\n throw simpleError;\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = [],\n orgAuthRetriesRemaining = this.apiKey && !this.orgSession ? 2 : 1,\n enhancedAuthRetry = false\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n // Without this, fetch labels a string body text/plain and FastAPI\n // rejects a JSON body parameter with 422 \"Validation failed\" (every\n // live-view browser storage save, until 2026-10-27).\n if (typeof options?.body === 'string' && !headers.has('Content-Type')) {\n headers.set('Content-Type', 'application/json');\n }\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n const presentedOrgSession = headers.get('X-Org-Session');\n const requestOrgRevision = this.orgSessionRevision;\n const presentedOrgUuid = this.orgSessionOrgUuid;\n const rejectionHandler = this.orgSessionRejectionHandler;\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n !enhancedAuthRetry &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n if (this.apiKey) this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n orgAuthRetriesRemaining,\n true\n );\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (orgAuthInfo && presentedOrgSession) {\n orgAuthInfo.sessionRejected = true;\n if (presentedOrgUuid === orgAuthInfo.orgUuid) {\n this.notifyOrgSessionRejected(presentedOrgSession, rejectionHandler);\n }\n }\n if (orgAuthInfo && orgAuthRetriesRemaining > 0 && this.orgAuthHandler) {\n let nextOrgRetries = orgAuthRetriesRemaining - 1;\n if (!this.hasNewerOrgSession(presentedOrgSession, orgAuthInfo.orgUuid)) {\n const completion = await this.answerOrgAuthChallenge(\n orgAuthInfo,\n presentedOrgSession,\n requestOrgRevision\n );\n if (completion !== 'cache') nextOrgRetries = 0;\n }\n this.assertOrgAuthContext(orgAuthInfo.orgUuid);\n return await this.fetchRaw(\n endpoint,\n options,\n allowedErrorStatuses,\n nextOrgRetries,\n enhancedAuthRetry\n );\n }\n if (orgAuthInfo) {\n this.clearOrgSessionIfCurrent(presentedOrgSession);\n if (\n !allowedErrorStatuses.includes(401) &&\n orgAuthInfo.acrValues?.includes('urn:gravity:mfa')\n ) {\n throw new ApiError(\n 'Organization sign-in still requires MFA. Complete MFA with your account or configured identity provider. For SSO, verify that the provider requires MFA and returns verified method evidence.',\n 401\n );\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...this.credentialsInit(),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n logApiClientError(error);\n throw error;\n }\n }\n}\n","/**\n * Enrollment-flow helpers: the small compound operations every integration\n * re-implements when wiring \"register member → populate a form → enroll into a\n * journey\". They build on the plain client methods and are safe to call from a\n * server-side BFF.\n */\nimport { ApiError } from '../api/base';\nimport type { GravityRailClient } from '../client/client';\nimport type { DataRecord } from '../types/data-types';\nimport { findMemberByPhone } from './outbound';\n\n/** Identify a member by any one of these; `memberId` wins when present. */\nexport interface MemberRef {\n memberId?: number;\n phone?: string;\n externalId?: string;\n}\n\n/** Resolve a `MemberRef` to a concrete member id (throws if none matches). */\nexport async function resolveMemberId(\n client: GravityRailClient,\n workspaceUuid: string,\n ref: MemberRef\n): Promise<number> {\n if (typeof ref.memberId === 'number') {\n return ref.memberId;\n }\n if (ref.phone) {\n const member = await findMemberByPhone(client, workspaceUuid, ref.phone);\n if (member?.id) return member.id;\n // Do not put the phone (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided phone number');\n }\n if (ref.externalId) {\n const page = await client.getWorkspaceMembers(workspaceUuid, 1, 25, ref.externalId);\n const match = page.items.find((m) => m.externalId === ref.externalId);\n if (match?.id) return match.id;\n // Do not put the externalId (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided externalId');\n }\n throw new Error('Provide memberId, phone, or externalId');\n}\n\n/**\n * Find member labels by name, creating any that don't exist, and return their\n * ids. Case-insensitive match on name. (The API derives the slug from the name.)\n */\nexport async function findOrCreateMemberLabels(\n client: GravityRailClient,\n workspaceUuid: string,\n names: string[],\n options: { color?: string } = {}\n): Promise<number[]> {\n const clean = names.map((n) => n.trim()).filter(Boolean);\n if (clean.length === 0) return [];\n\n const existing = await client.getMemberLabels(workspaceUuid);\n const byName = new Map(existing.map((l) => [l.name.toLowerCase(), l]));\n const ids: number[] = [];\n for (const name of clean) {\n const found = byName.get(name.toLowerCase());\n if (found) {\n ids.push(found.id);\n continue;\n }\n const created = await client.createMemberLabel(workspaceUuid, {\n name,\n color: options.color ?? '#6366f1',\n });\n byName.set(name.toLowerCase(), created);\n ids.push(created.id);\n }\n return ids;\n}\n\n/**\n * Idempotently write a member-scoped data record: update the member's existing\n * record for the DataType if one exists, otherwise create it.\n */\nexport async function upsertDataRecordForMember(\n client: GravityRailClient,\n workspaceUuid: string,\n dataTypeId: number,\n memberId: number,\n fieldValues: Record<string, unknown>\n): Promise<DataRecord> {\n const existing = await client.getDataRecords(workspaceUuid, dataTypeId, {\n memberId,\n pageSize: 1,\n });\n const record = existing.items?.[0];\n const body = { dataTypeId, memberId, fieldValues };\n if (record?.id) {\n return client.updateDataRecord(workspaceUuid, dataTypeId, record.id, body);\n }\n return client.createDataRecord(workspaceUuid, dataTypeId, body);\n}\n\nexport interface EnrollMemberInJourneyOptions extends MemberRef {\n /** Journey to enroll into. Defaults to the workspace's first journey. */\n journeyId?: number;\n /** Labels to apply to the member before enrolling (journey/cohort tags). */\n labels?: string[];\n labelColor?: string;\n}\n\nexport interface EnrollMemberInJourneyResult {\n journeyId: number;\n journeyName?: string;\n memberId: number;\n appliedLabels: string[];\n}\n\n/**\n * Resolve a member, optionally tag them, and enroll them into a journey. The API\n * skips an already-enrolled member and answers 201 with only the enrollments it\n * created. A 409 means the member was not enrolled (for example, refused as a\n * test or archived member); this helper swallows it.\n */\nexport async function enrollMemberInJourney(\n client: GravityRailClient,\n workspaceUuid: string,\n options: EnrollMemberInJourneyOptions\n): Promise<EnrollMemberInJourneyResult> {\n const memberId = await resolveMemberId(client, workspaceUuid, options);\n\n const page = await client.getJourneys(workspaceUuid);\n const journeys = page.items ?? [];\n let journey: { id: number; name?: string } | undefined;\n if (options.journeyId != null) {\n journey = journeys.find((j) => j.id === options.journeyId) ?? { id: options.journeyId };\n } else {\n journey = journeys[0];\n }\n if (!journey) {\n throw new Error('No journey to enroll into: pass journeyId or create a journey');\n }\n\n const labelNames = (options.labels ?? []).map((l) => l.trim()).filter(Boolean);\n if (labelNames.length > 0) {\n const labelIds = await findOrCreateMemberLabels(client, workspaceUuid, labelNames, {\n color: options.labelColor,\n });\n // updateMember replaces the label set, so merge with the member's existing\n // labels rather than wiping them.\n const member = await client.getWorkspaceMember(workspaceUuid, memberId);\n const existingIds = (member.labels ?? [])\n .map((l) => l.id)\n .filter((id): id is number => typeof id === 'number');\n const mergedIds = Array.from(new Set([...existingIds, ...labelIds]));\n await client.updateMember(workspaceUuid, memberId, { labelIds: mergedIds });\n }\n\n try {\n await client.enrollMembers(workspaceUuid, journey.id, { memberId });\n } catch (error) {\n if (!(error instanceof ApiError && error.statusCode === 409)) {\n throw error;\n }\n }\n\n return { journeyId: journey.id, journeyName: journey.name, memberId, appliedLabels: labelNames };\n}\n","/**\n * Webhook signature helpers.\n *\n * Gravity Rail signs every outbound webhook with HMAC-SHA256 and sends the\n * result in the `X-Webhook-Signature` header as `t={unixSeconds},v1={hexDigest}`.\n * The signed message is the timestamp, a literal dot, then the raw request body:\n *\n * HMAC_SHA256(secret, `${t}.` + rawBody)\n *\n * The timestamp defeats replay — reject signatures older than the tolerance\n * window. Verify the signature against the RAW request body bytes, before any\n * JSON parsing/re-serialization.\n *\n * These use the Web Crypto API (`crypto.subtle`), so they run unchanged in Node\n * 18+ and the browser/edge runtimes.\n */\n\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Constant-time comparison of two equal-length hex strings. */\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i += 1) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Produce the `X-Webhook-Signature` header value for a payload. Primarily useful\n * for tests and for re-signing when relaying webhooks.\n */\nexport async function signWebhookPayload(\n rawBody: string,\n secret: string,\n timestampSeconds: number\n): Promise<string> {\n const digest = await hmacSha256Hex(secret, `${timestampSeconds}.${rawBody}`);\n return `t=${timestampSeconds},v1=${digest}`;\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature in seconds (default 300). */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — for deterministic tests. */\n nowSeconds?: number;\n}\n\nexport type VerifyWebhookResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Verify a webhook signature against the raw body. Returns a discriminated\n * result so callers can log the reason; it never throws on a bad signature.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {}\n): Promise<VerifyWebhookResult> {\n if (!signatureHeader) {\n return { ok: false, reason: 'missing signature header' };\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const idx = segment.indexOf('=');\n if (idx > 0) {\n parts[segment.slice(0, idx).trim()] = segment.slice(idx + 1).trim();\n }\n }\n\n const timestamp = Number(parts.t);\n const provided = parts.v1;\n if (!Number.isFinite(timestamp) || !provided) {\n return { ok: false, reason: 'malformed signature header' };\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n return { ok: false, reason: 'signature timestamp outside tolerance' };\n }\n\n const expected = await hmacSha256Hex(secret, `${timestamp}.${rawBody}`);\n if (!timingSafeEqualHex(expected, provided)) {\n return { ok: false, reason: 'signature mismatch' };\n }\n\n return { ok: true };\n}\n","/**\n * Helpers for the portable workspace export ZIP.\n *\n * Layout: ``export.json`` plus ``blobs/ab/cd/<sha256>``.\n */\n\nexport const WORKSPACE_EXPORT_JSON_MEMBER = 'export.json';\nexport const MAX_EXPORT_JSON_BYTES = 8 * 1024 * 1024;\n\nconst EOCD_SIGNATURE = 0x06054b50;\nconst CDFH_SIGNATURE = 0x02014b50;\nconst LFH_SIGNATURE = 0x04034b50;\nconst ZIP_STORED = 0;\nconst ZIP_DEFLATED = 8;\n\nfunction requireRange(bytes: Uint8Array, start: number, length: number): void {\n if (start < 0 || length < 0 || start + length > bytes.length) {\n throw new Error('ZIP offsets are out of range.');\n }\n}\n\nfunction u16(bytes: Uint8Array, offset: number): number {\n requireRange(bytes, offset, 2);\n return bytes[offset]! | (bytes[offset + 1]! << 8);\n}\n\nfunction u32(bytes: Uint8Array, offset: number): number {\n requireRange(bytes, offset, 4);\n return (\n (bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24)) >>>\n 0\n );\n}\n\nexport function isZipBuffer(bytes: Uint8Array): boolean {\n return bytes.length >= 4 && bytes[0] === 0x50 && bytes[1] === 0x4b;\n}\n\nasync function inflateRaw(data: Uint8Array, maxBytes: number): Promise<Uint8Array> {\n if (typeof DecompressionStream === 'function') {\n const stream = new Blob([data as BlobPart])\n .stream()\n .pipeThrough(new DecompressionStream('deflate-raw'));\n const reader = stream.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw new Error('ZIP member exceeds the export.json size limit.');\n }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n }\n // Keep the Node-only fallback out of browser bundles. Native decompression\n // above handles browsers; unsupported browsers get a clear capability error.\n if (typeof window !== 'undefined') {\n throw new Error('This browser does not support ZIP decompression.');\n }\n const zlib = await import(/* webpackIgnore: true */ 'node:zlib');\n return Uint8Array.from(zlib.inflateRawSync(data, { maxOutputLength: maxBytes }));\n}\n\nfunction findEocdOffset(bytes: Uint8Array): number {\n const min = 22;\n const maxComment = 65535;\n const start = Math.max(0, bytes.length - (min + maxComment));\n for (let i = bytes.length - min; i >= start; i--) {\n if (u32(bytes, i) !== EOCD_SIGNATURE) continue;\n const commentLength = u16(bytes, i + 20);\n if (i + min + commentLength === bytes.length) {\n return i;\n }\n }\n throw new Error('Not a ZIP archive (missing end-of-central-directory).');\n}\n\n/**\n * Extract a single ZIP member. Supports STORE and DEFLATE (method 8).\n */\nexport async function extractZipMember(bytes: Uint8Array, memberName: string): Promise<Uint8Array> {\n const eocd = findEocdOffset(bytes);\n const entries = u16(bytes, eocd + 10);\n let offset = u32(bytes, eocd + 16);\n for (let i = 0; i < entries; i++) {\n if (u32(bytes, offset) !== CDFH_SIGNATURE) {\n throw new Error('ZIP central directory is corrupt.');\n }\n requireRange(bytes, offset, 46);\n const method = u16(bytes, offset + 10);\n const compressedSize = u32(bytes, offset + 20);\n const uncompressedSize = u32(bytes, offset + 24);\n const nameLen = u16(bytes, offset + 28);\n const extraLen = u16(bytes, offset + 30);\n const commentLen = u16(bytes, offset + 32);\n const localOffset = u32(bytes, offset + 42);\n requireRange(bytes, offset + 46, nameLen);\n const name = new TextDecoder().decode(bytes.subarray(offset + 46, offset + 46 + nameLen));\n offset += 46 + nameLen + extraLen + commentLen;\n requireRange(bytes, offset, 0);\n if (name !== memberName) continue;\n if (uncompressedSize === 0xffffffff || compressedSize === 0xffffffff) {\n throw new Error('ZIP64 members are not supported for export.json.');\n }\n if (uncompressedSize > MAX_EXPORT_JSON_BYTES || compressedSize > MAX_EXPORT_JSON_BYTES) {\n throw new Error('ZIP member exceeds the export.json size limit.');\n }\n\n if (u32(bytes, localOffset) !== LFH_SIGNATURE) {\n throw new Error(`ZIP local header for ${memberName} is corrupt.`);\n }\n const localNameLen = u16(bytes, localOffset + 26);\n const localExtraLen = u16(bytes, localOffset + 28);\n const dataStart = localOffset + 30 + localNameLen + localExtraLen;\n requireRange(bytes, dataStart, compressedSize);\n const compressed = bytes.subarray(dataStart, dataStart + compressedSize);\n if (method === ZIP_STORED) {\n if (compressed.length !== uncompressedSize) {\n throw new Error('ZIP stored member size does not match the directory.');\n }\n return compressed.slice();\n }\n if (method === ZIP_DEFLATED) {\n const inflated = await inflateRaw(compressed, MAX_EXPORT_JSON_BYTES);\n if (inflated.length !== uncompressedSize) {\n throw new Error('ZIP deflated member size does not match the directory.');\n }\n return inflated;\n }\n throw new Error(`Unsupported ZIP compression method ${method} for ${memberName}.`);\n }\n throw new Error(`ZIP is missing ${memberName}.`);\n}\n\nexport async function extractWorkspaceExportJson(bytes: Uint8Array): Promise<string> {\n const raw = await extractZipMember(bytes, WORKSPACE_EXPORT_JSON_MEMBER);\n return new TextDecoder().decode(raw);\n}\n","import type { ChatsApi } from '../api/chats';\nimport type { InteractionMode, InteractionSessionResponse } from '../types/chat-types';\n\ntype InteractionApi = Pick<\n ChatsApi,\n 'createChatInteractionSession' | 'transitionChatInteractionSession'\n>;\n\n/** One client's mode history in one Chat. Create a separate controller per device/session. */\nexport class ChatInteractionController {\n private current: InteractionSessionResponse | undefined;\n private pending: { mode: InteractionMode; requestId: string } | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n private readonly clientSessionId = crypto.randomUUID();\n\n constructor(\n private readonly api: InteractionApi,\n private readonly workspaceId: string,\n private readonly chatId: number\n ) {}\n\n /** Serialize switches and reuse request IDs when a response is lost. */\n ensure(mode: InteractionMode): Promise<InteractionSessionResponse> {\n const operation = this.tail.then(async () => {\n // Resolve an uncertain earlier write before selecting the next mode.\n if (this.pending) await this.applyPending();\n if (this.current?.mode !== mode) {\n this.pending = { mode, requestId: crypto.randomUUID() };\n await this.applyPending();\n }\n if (!this.current) throw new Error('Interaction session unavailable');\n return this.current;\n });\n this.tail = operation.catch(() => undefined);\n return operation;\n }\n\n private async applyPending(): Promise<void> {\n const pending = this.pending;\n if (!pending) return;\n this.current = this.current\n ? await this.api.transitionChatInteractionSession(\n this.workspaceId,\n this.chatId,\n this.current.id,\n pending\n )\n : await this.api.createChatInteractionSession(this.workspaceId, this.chatId, {\n ...pending,\n clientSessionId: this.clientSessionId,\n });\n this.pending = undefined;\n }\n}\n","import type {\n BusinessImportIssue,\n BusinessImportPreviewResponse,\n BusinessImportPreviewRow,\n BusinessImportResponse,\n BusinessImportResultRow,\n} from '../types/generated/business_import';\n\nfunction toSafeRow(\n row: BusinessImportPreviewRow | BusinessImportResultRow,\n legalEntityUuid: string | null | undefined\n) {\n return {\n row: row.row,\n action: row.action,\n legalEntityUuid: legalEntityUuid ?? undefined,\n proposedChanges: row.proposedChanges,\n reason: row.reason ?? undefined,\n error: row.error ?? undefined,\n };\n}\n\nfunction toSafeIssue({ row, column, columnPosition, code }: BusinessImportIssue) {\n return { row, column, columnPosition, code };\n}\n\n/** Counts, row numbers, codes, column keys, changed field names and business ids; no prose. */\nexport function toSafeBusinessImportPreview(preview: BusinessImportPreviewResponse) {\n return {\n previewPlanToken: preview.previewPlanToken,\n totalRows: preview.totalRows,\n summary: preview.summary,\n rows: preview.rows.map((row) => toSafeRow(row, row.match?.legalEntityUuid)),\n ignoredColumnPositions: preview.ignoredColumnPositions,\n issues: preview.issues?.map(toSafeIssue),\n issueCount: preview.issueCount,\n };\n}\n\n/** The same allowlist for a finished import; a row's business id is the one it wrote. */\nexport function toSafeBusinessImportResult(result: BusinessImportResponse) {\n return {\n importId: result.importId,\n totalRows: result.totalRows,\n summary: result.summary,\n rows: result.rows.map((row) => toSafeRow(row, row.legalEntityUuid)),\n ignoredColumnPositions: result.ignoredColumnPositions,\n issues: result.issues?.map(toSafeIssue),\n issueCount: result.issueCount,\n };\n}\n","import type { MemberImportPreviewResponse, MemberImportStreamEvent } from '../types/member-types';\n\n/** Counts and row references for logs/CLI/chat. Drops identity, contacts and free text. */\nexport function toSafeMemberImportPreview(preview: MemberImportPreviewResponse) {\n return {\n previewPlanToken: preview.previewPlanToken,\n totalRows: preview.totalRows,\n summary: preview.summary,\n rows: preview.rows.map((row) => ({\n row: row.row,\n action: row.action,\n memberId: row.match?.memberId,\n matchType: row.match?.matchType,\n conflict: row.conflict\n ? { code: row.conflict.code, fields: row.conflict.fields }\n : undefined,\n proposedChanges: row.proposedChanges,\n sharedContacts: row.sharedContacts,\n })),\n };\n}\n\n/** Deliberate allowlist: stream conflicts can contain global Account contact values. */\nexport function toSafeMemberImportSummary(event: MemberImportStreamEvent) {\n return {\n total: event.total,\n created: event.created,\n updated: event.updated,\n unchanged: event.unchanged,\n failed: event.failed,\n conflicted: event.conflicted,\n skipped: event.skipped,\n failedRows: event.failedRows,\n conflictRows: event.conflictRows,\n skippedRows: event.skippedRows,\n conflicts: event.conflicts?.map(({ row, code, fields, member_id }) => ({\n row,\n code,\n fields,\n memberId: member_id,\n })),\n updatedMembers: event.updatedMembers?.map(({ row, memberId, changes }) => ({\n row,\n memberId,\n changes,\n })),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;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,IACJ,kBAAkB,QAAQ;AAAA,IAC1B,WAAW,QAAQ;AAAA,IACnB,SAAS,QAAQ;AAAA,IACjB,MAAM,QAAQ,KAAK,IAAI,CAAC,SAAS;AAAA,MAC9B,KAAK,IAAI;AAAA,MACT,QAAQ,IAAI;AAAA,MACZ,UAAU,IAAI,OAAO;AAAA,MACrB,WAAW,IAAI,OAAO;AAAA,MACtB,UAAU,IAAI,WACT,EAAE,MAAM,IAAI,SAAS,MAAM,QAAQ,IAAI,SAAS,OAAO,IACvD;AAAA,MACL,iBAAiB,IAAI;AAAA,MACrB,gBAAgB,IAAI;AAAA,IACvB,EAAE;AAAA,EACL;AACH;AAGO,SAAS,0BAA0B,OAAgC;AACvE,SAAO;AAAA,IACJ,OAAO,MAAM;AAAA,IACb,SAAS,MAAM;AAAA,IACf,SAAS,MAAM;AAAA,IACf,WAAW,MAAM;AAAA,IACjB,QAAQ,MAAM;AAAA,IACd,YAAY,MAAM;AAAA,IAClB,SAAS,MAAM;AAAA,IACf,YAAY,MAAM;AAAA,IAClB,cAAc,MAAM;AAAA,IACpB,aAAa,MAAM;AAAA,IACnB,WAAW,MAAM,WAAW,IAAI,CAAC,EAAE,KAAK,MAAM,QAAQ,UAAU,OAAO;AAAA,MACpE;AAAA,MACA;AAAA,MACA;AAAA,MACA,UAAU;AAAA,IACb,EAAE;AAAA,IACF,gBAAgB,MAAM,gBAAgB,IAAI,CAAC,EAAE,KAAK,UAAU,QAAQ,OAAO;AAAA,MACxE;AAAA,MACA;AAAA,MACA;AAAA,IACH,EAAE;AAAA,EACL;AACH;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { GravityRailClient } from './index.cjs';
2
- export { C as ChatInteractionController } from './client-BGGgZhKg.cjs';
2
+ export { C as ChatInteractionController } from './client-DwslF70Y.cjs';
3
3
  import { WorkspaceMemberResponse, DataRecordResponse } from './index.cjs';
4
- export { t as toSafeMemberImportPreview, a as toSafeMemberImportSummary } from './member-import-4VSE3yYo.cjs';
4
+ export { t as toSafeBusinessImportPreview, a as toSafeBusinessImportResult, b as toSafeMemberImportPreview, c as toSafeMemberImportSummary } from './member-import-CA9YWv3Y.cjs';
5
5
  import './account-DLwJWX9b.cjs';
6
6
  import 'zod';
7
7
 
package/dist/helpers.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { GravityRailClient } from './index.js';
2
- export { C as ChatInteractionController } from './client-Bd-zXY42.js';
2
+ export { C as ChatInteractionController } from './client-DVF3qwNq.js';
3
3
  import { WorkspaceMemberResponse, DataRecordResponse } from './index.js';
4
- export { t as toSafeMemberImportPreview, a as toSafeMemberImportSummary } from './member-import-BQDFoSyf.js';
4
+ export { t as toSafeBusinessImportPreview, a as toSafeBusinessImportResult, b as toSafeMemberImportPreview, c as toSafeMemberImportSummary } from './member-import-BpcX-swC.js';
5
5
  import './account-DLwJWX9b.js';
6
6
  import 'zod';
7
7
 
package/dist/helpers.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
+ toSafeBusinessImportPreview,
3
+ toSafeBusinessImportResult,
2
4
  toSafeMemberImportPreview,
3
5
  toSafeMemberImportSummary
4
- } from "./chunk-6KPGCPGW.js";
6
+ } from "./chunk-ZJJDZUAK.js";
5
7
  import {
6
8
  ApiError,
7
9
  ChatInteractionController
@@ -367,6 +369,8 @@ export {
367
369
  resolveOutboundPhoneNumberId,
368
370
  resolveOutboundWorkflowId,
369
371
  signWebhookPayload,
372
+ toSafeBusinessImportPreview,
373
+ toSafeBusinessImportResult,
370
374
  toSafeMemberImportPreview,
371
375
  toSafeMemberImportSummary,
372
376
  upsertDataRecordForMember,