@anybio/govern 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,1541 +1,170 @@
1
1
  'use strict';
2
2
 
3
- // src/errors.ts
4
- var MAX_SERVER_MESSAGE_CHARS = 300;
5
- var GovernError = class extends Error {
6
- name = "GovernError";
7
- constructor(message, options) {
8
- super(message, options);
9
- Object.setPrototypeOf(this, new.target.prototype);
10
- }
11
- };
12
- var GovernConfigError = class extends GovernError {
13
- name = "GovernConfigError";
14
- };
15
- var GovernApiError = class extends GovernError {
16
- name = "GovernApiError";
17
- status;
18
- /** The server's machine-readable error kind (for example `BAD_REQUEST_ERROR`), when it sent one. */
19
- kind;
20
- /** Whether the SDK considered the failure retryable (429 and 5xx). */
21
- retryable;
22
- /** Milliseconds the server asked us to wait, from `Retry-After`, when it sent one. */
23
- retryAfterMs;
24
- /**
25
- * The server's own error text, collapsed to one line and bounded, or `null`.
26
- *
27
- * Deliberately not part of `.message`: an error message is the string that
28
- * ends up in a log line, an alert and a bug report, and the SDK cannot
29
- * promise what a server put in this one. Read it when you are debugging a
30
- * call, and treat what comes back the way you treat the message it was
31
- * about.
32
- */
33
- serverMessage;
34
- constructor(input) {
35
- super(`AnyBio Govern API responded ${input.status}${input.kind ? ` (${input.kind})` : ""}`);
36
- this.status = input.status;
37
- this.kind = input.kind;
38
- this.retryable = input.retryable;
39
- this.retryAfterMs = input.retryAfterMs;
40
- this.serverMessage = input.serverMessage === null ? null : truncate(input.serverMessage);
41
- }
42
- };
43
- var GovernConflictError = class extends GovernApiError {
44
- name = "GovernConflictError";
45
- };
46
- var GovernNetworkError = class extends GovernError {
47
- name = "GovernNetworkError";
48
- constructor(message, options) {
49
- super(message, options);
50
- }
51
- };
52
- var GovernTimeoutError = class extends GovernError {
53
- name = "GovernTimeoutError";
54
- timeoutMs;
55
- constructor(timeoutMs) {
56
- super(`AnyBio Govern request timed out after ${timeoutMs} ms`);
57
- this.timeoutMs = timeoutMs;
58
- }
59
- };
60
- var GovernAbortError = class extends GovernError {
61
- name = "GovernAbortError";
62
- constructor(reason) {
63
- super("AnyBio Govern request aborted", reason === void 0 ? void 0 : { cause: reason });
64
- }
65
- };
66
- var GovernWebhookError = class extends GovernError {
67
- name = "GovernWebhookError";
68
- };
69
- var GovernNotAvailableError = class extends GovernError {
70
- name = "GovernNotAvailableError";
71
- };
72
- function truncate(text) {
73
- const oneLine = text.replace(/\s+/g, " ").trim();
74
- return oneLine.length > MAX_SERVER_MESSAGE_CHARS ? `${oneLine.slice(0, MAX_SERVER_MESSAGE_CHARS)}...` : oneLine;
75
- }
76
- function isGovernError(error) {
77
- return error instanceof GovernError;
78
- }
3
+ var chunkI5XIXB5M_cjs = require('./chunk-I5XIXB5M.cjs');
79
4
 
80
- // src/crypto.ts
81
- var cached = null;
82
- function webCrypto() {
83
- if (cached) return cached;
84
- cached = (async () => {
85
- const global = globalThis.crypto;
86
- if (global?.subtle) return global;
87
- try {
88
- const specifier = "node:crypto";
89
- const mod = await import(
90
- /* @vite-ignore */
91
- specifier
92
- );
93
- if (mod.webcrypto?.subtle) return mod.webcrypto;
94
- } catch {
95
- }
96
- throw new GovernConfigError(
97
- "Web Crypto (crypto.subtle) is not available in this runtime. Node 20+ and edge runtimes provide it."
98
- );
99
- })();
100
- return cached;
101
- }
102
- var HEX = "0123456789abcdef";
103
- function toHex(bytes) {
104
- let out = "";
105
- for (const byte of bytes) out += HEX[byte >> 4] + HEX[byte & 15];
106
- return out;
107
- }
108
- async function sha256Hex(text) {
109
- const { subtle } = await webCrypto();
110
- const digest = await subtle.digest("SHA-256", new TextEncoder().encode(text));
111
- return toHex(new Uint8Array(digest));
112
- }
113
- async function hmacSha256Hex(secret, message) {
114
- const { subtle } = await webCrypto();
115
- const key = await subtle.importKey(
116
- "raw",
117
- new TextEncoder().encode(secret),
118
- { name: "HMAC", hash: "SHA-256" },
119
- false,
120
- ["sign"]
121
- );
122
- const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
123
- const signature = await subtle.sign("HMAC", key, bytes);
124
- return toHex(new Uint8Array(signature));
125
- }
126
- function timingSafeEqual(a, b) {
127
- if (a.length !== b.length) return false;
128
- let diff = 0;
129
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
130
- return diff === 0;
131
- }
132
- function randomId() {
133
- const global = globalThis.crypto;
134
- if (global?.randomUUID) return global.randomUUID();
135
- const bytes = new Uint8Array(16);
136
- if (global?.getRandomValues) {
137
- global.getRandomValues(bytes);
138
- } else {
139
- for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
140
- }
141
- bytes[6] = bytes[6] & 15 | 64;
142
- bytes[8] = bytes[8] & 63 | 128;
143
- const hex = toHex(bytes);
144
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
145
- }
146
5
 
147
- // src/version.ts
148
- var SDK_VERSION = "0.2.1";
149
- var SDK_NAME = "@anybio/govern";
150
6
 
151
- // src/http.ts
152
- var BACKOFF_BASE_MS = 250;
153
- var BACKOFF_MAX_MS = 5e3;
154
- var RETRY_AFTER_MAX_MS = 3e4;
155
- var HEADER_IDEMPOTENCY_KEY = "Idempotency-Key";
156
- async function send(config, request) {
157
- const url = buildUrl(config.baseUrl, request.path, request.query);
158
- const headers = {
159
- Authorization: `Bearer ${config.apiKey}`,
160
- Accept: "application/json",
161
- "X-AnyBio-Govern-SDK": `${SDK_NAME}/${SDK_VERSION}`
162
- };
163
- if (request.body !== void 0) headers["Content-Type"] = "application/json";
164
- if (request.idempotencyKey) headers[HEADER_IDEMPOTENCY_KEY] = request.idempotencyKey;
165
- const payload = request.body === void 0 ? void 0 : JSON.stringify(request.body);
166
- const retry = request.retry ?? true;
167
- const attempts = retry ? config.maxRetries + 1 : 1;
168
- let lastError = null;
169
- for (let attempt = 1; attempt <= attempts; attempt++) {
170
- if (request.signal?.aborted) throw new GovernAbortError(request.signal.reason);
171
- config.onEvent?.({ type: "request", method: request.method, path: request.path, attempt });
172
- const started = now();
173
- let response;
174
- try {
175
- response = await withTimeout(
176
- config.fetch,
177
- url,
178
- { method: request.method, headers, body: payload },
179
- config.timeoutMs,
180
- request.signal
181
- );
182
- } catch (error) {
183
- if (error instanceof GovernAbortError) throw error;
184
- const failure2 = error instanceof GovernTimeoutError ? error : new GovernNetworkError("AnyBio Govern request failed before a response arrived", {
185
- cause: error
186
- });
187
- lastError = failure2;
188
- if (attempt < attempts) {
189
- const delayMs = backoff(attempt);
190
- config.onEvent?.({
191
- type: "retry",
192
- method: request.method,
193
- path: request.path,
194
- attempt,
195
- status: null,
196
- delayMs,
197
- reason: failure2 instanceof GovernTimeoutError ? "timeout" : "network"
198
- });
199
- await sleep(delayMs, request.signal);
200
- continue;
201
- }
202
- throw failure2;
203
- }
204
- config.onEvent?.({
205
- type: "response",
206
- method: request.method,
207
- path: request.path,
208
- status: response.status,
209
- attempt,
210
- durationMs: Math.round(now() - started)
211
- });
212
- if (response.ok) {
213
- return { status: response.status, body: await readJson(response), headers: response.headers };
214
- }
215
- const retryable = response.status === 429 || response.status >= 500;
216
- const retryAfterMs = response.status === 429 ? parseRetryAfter(response.headers.get("retry-after")) : null;
217
- const { kind, message } = await readError(response);
218
- const detail = { status: response.status, kind, serverMessage: message, retryable, retryAfterMs };
219
- const failure = response.status === 409 ? new GovernConflictError(detail) : new GovernApiError(detail);
220
- lastError = failure;
221
- if (retryable && attempt < attempts) {
222
- const delayMs = retryAfterMs ?? backoff(attempt);
223
- config.onEvent?.({
224
- type: "retry",
225
- method: request.method,
226
- path: request.path,
227
- attempt,
228
- status: response.status,
229
- delayMs,
230
- reason: response.status === 429 ? "rate_limited" : "server_error"
231
- });
232
- await sleep(delayMs, request.signal);
233
- continue;
234
- }
235
- throw failure;
236
- }
237
- throw lastError ?? new GovernNetworkError("AnyBio Govern request failed");
238
- }
239
- function buildUrl(baseUrl, path, query) {
240
- const base = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
241
- const url = new URL(`${base}${path}`);
242
- if (query) {
243
- for (const [key, value] of Object.entries(query)) {
244
- if (value !== void 0) url.searchParams.set(key, value);
245
- }
246
- }
247
- return url.toString();
248
- }
249
- async function withTimeout(fetchImpl, url, init, timeoutMs, signal) {
250
- const controller = new AbortController();
251
- let timedOut = false;
252
- let rejectTimeout = () => {
253
- };
254
- const timeout = new Promise((_, reject) => {
255
- rejectTimeout = reject;
256
- });
257
- const timer = setTimeout(() => {
258
- timedOut = true;
259
- controller.abort();
260
- rejectTimeout(new GovernTimeoutError(timeoutMs));
261
- }, timeoutMs);
262
- const onAbort = () => {
263
- controller.abort();
264
- rejectTimeout(new GovernAbortError(signal?.reason));
265
- };
266
- signal?.addEventListener("abort", onAbort, { once: true });
267
- try {
268
- return await Promise.race([fetchImpl(url, { ...init, signal: controller.signal }), timeout]);
269
- } catch (error) {
270
- if (signal?.aborted) throw new GovernAbortError(signal.reason);
271
- if (timedOut) throw new GovernTimeoutError(timeoutMs);
272
- throw error;
273
- } finally {
274
- clearTimeout(timer);
275
- signal?.removeEventListener("abort", onAbort);
276
- }
277
- }
278
- async function readJson(response) {
279
- const text = await response.text();
280
- if (!text) return void 0;
281
- try {
282
- return JSON.parse(text);
283
- } catch {
284
- throw new GovernNetworkError(`AnyBio Govern API returned a non-JSON body with status ${response.status}`);
285
- }
286
- }
287
- async function readError(response) {
288
- let text = "";
289
- try {
290
- text = await response.text();
291
- } catch {
292
- return { kind: null, message: null };
293
- }
294
- if (!text) return { kind: null, message: null };
295
- try {
296
- const parsed = JSON.parse(text);
297
- const kind = typeof parsed.kind === "string" ? parsed.kind : null;
298
- const message = typeof parsed.error_message === "string" ? parsed.error_message : typeof parsed.error === "string" ? parsed.error : typeof parsed.message === "string" ? parsed.message : null;
299
- return { kind, message };
300
- } catch {
301
- return { kind: null, message: null };
302
- }
303
- }
304
- function parseRetryAfter(header2, nowMs = Date.now()) {
305
- if (!header2) return null;
306
- const trimmed = header2.trim();
307
- if (/^\d+$/.test(trimmed)) {
308
- return Math.min(Number(trimmed) * 1e3, RETRY_AFTER_MAX_MS);
309
- }
310
- const at = Date.parse(trimmed);
311
- if (Number.isNaN(at)) return null;
312
- return Math.max(0, Math.min(at - nowMs, RETRY_AFTER_MAX_MS));
313
- }
314
- function backoff(attempt, random = Math.random) {
315
- const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, attempt - 1));
316
- return Math.round(random() * ceiling);
317
- }
318
- function sleep(ms, signal) {
319
- return new Promise((resolve, reject) => {
320
- if (signal?.aborted) {
321
- reject(new GovernAbortError(signal.reason));
322
- return;
323
- }
324
- const timer = setTimeout(() => {
325
- signal?.removeEventListener("abort", onAbort);
326
- resolve();
327
- }, ms);
328
- const onAbort = () => {
329
- clearTimeout(timer);
330
- reject(new GovernAbortError(signal?.reason));
331
- };
332
- signal?.addEventListener("abort", onAbort, { once: true });
333
- });
334
- }
335
- function now() {
336
- return typeof performance !== "undefined" ? performance.now() : Date.now();
337
- }
338
-
339
- // src/types.ts
340
- var CHANNELS = ["sms", "app_message", "web_chat", "voice", "email"];
341
- var IN_SESSION_CHANNELS = ["web_chat", "app_message"];
342
- function isInSessionChannel(channel) {
343
- return typeof channel === "string" && IN_SESSION_CHANNELS.includes(channel);
344
- }
345
- var AUDIENCES = ["patient", "clinician"];
346
- var REASONS = {
347
- policyMissing: "policy_missing",
348
- gateUnavailable: "gate_unavailable",
349
- prohibitedClaim: "prohibited_claim",
350
- /**
351
- * The draft told a patient to start, stop or change a medication or a dose.
352
- * A deterministic floor: the stop is `never_sendable`.
353
- */
354
- medicationInstruction: "medication_instruction",
355
- missingDisclaimer: "missing_disclaimer",
356
- clinicalClaim: "clinical_claim",
357
- reviewRequired: "review_required",
358
- patientRewriteWithheld: "patient_rewrite_withheld",
359
- disclosureMissing: "disclosure_missing",
360
- heldForReview: "held_for_review",
361
- rewritten: "rewritten",
362
- notEvaluated: "not_evaluated",
363
- /** The patient opted out: `block`, on every channel. */
364
- optedOut: "opted_out",
365
- /**
366
- * No `granted` consent on record, on a channel that requires one, for a turn
367
- * that answers nothing the patient sent: `block`. A turn that carries the
368
- * patient's `inbound` proceeds.
369
- */
370
- consentMissing: "consent_missing",
371
- /** The consent on record was revoked: `block`, on every outbound channel. */
372
- consentRevoked: "consent_revoked",
373
- /** The patient is over the application's cap in the current window: `hold`. */
374
- frequencyCap: "frequency_cap",
375
- /**
376
- * The patient-state store (opt-out, consent, the cap) could not be read, so
377
- * nothing is known about whether this patient may be messaged. Always beside
378
- * `gate_unavailable`. `sendHoldingLine` is false on it: another message could
379
- * be the wrong thing, not merely an unnecessary one.
380
- */
381
- patientStateUnavailable: "patient_state_unavailable",
382
- /**
383
- * SDK-only: the API answered and refused the call, and would refuse it again.
384
- * A revoked or wrong application key, a key not bound to the application, a
385
- * request the server will not accept. `guard` still holds in enforce, so
386
- * nothing reaches a patient, but the thing to check is the integration's own
387
- * configuration, not the API's availability: this does not heal on its own.
388
- */
389
- clientMisconfigured: "client_misconfigured",
390
- /** SDK-only: the server sent a decision value this version does not know. */
391
- unknownDecision: "unknown_decision"
392
- };
393
- function isAutomationPaused(handoff) {
394
- if (!handoff) return false;
395
- if ("pausesAutomation" in handoff) {
396
- return handoff.pausesAutomation && handoff.automationResumedAt == null;
397
- }
398
- const wire = handoff;
399
- return wire.pauses_automation !== false && wire.automation_resumed_at == null;
400
- }
401
-
402
- // src/webhook.ts
403
- var WEBHOOK_HEADERS = {
404
- timestamp: "x-govern-timestamp",
405
- signature: "x-govern-signature",
406
- event: "x-govern-event",
407
- delivery: "x-govern-delivery"
408
- };
409
- var WEBHOOK_EVENTS = {
410
- decisionReleased: "decision.released",
411
- decisionRejected: "decision.rejected",
412
- handoffOpened: "handoff.opened",
413
- handoffClaimed: "handoff.claimed",
414
- handoffResolved: "handoff.resolved",
415
- handoffResumed: "handoff.resumed"
416
- };
417
- async function signWebhookPayload(secret, timestamp, body) {
418
- requireSecret(secret, "signWebhookPayload");
419
- return `v1=${await hmacSha256Hex(secret, signedMessage(timestamp, body))}`;
420
- }
421
- async function verifyWebhookSignature(rawBody, headers, secret, options = {}) {
422
- requireSecret(secret, "verifyWebhookSignature");
423
- const tolerance = options.toleranceSeconds ?? 300;
424
- if (!Number.isFinite(tolerance) || tolerance < 0) {
425
- throw new GovernConfigError(
426
- "verifyWebhookSignature: toleranceSeconds must be a finite number of seconds, zero or more. Pass 0 to accept a delivery of any age on purpose; a negative or non-finite value did that silently, which is a replay window left open by accident."
427
- );
428
- }
429
- const bodyBytes = toBytes(rawBody);
430
- const timestampHeader = header(headers, WEBHOOK_HEADERS.timestamp);
431
- const signatureHeader = header(headers, WEBHOOK_HEADERS.signature);
432
- if (!timestampHeader || !signatureHeader) {
433
- throw new GovernWebhookError("missing X-Govern-Timestamp or X-Govern-Signature header");
434
- }
435
- const timestamp = Number(timestampHeader.trim());
436
- if (!Number.isInteger(timestamp)) {
437
- throw new GovernWebhookError("X-Govern-Timestamp is not an integer");
438
- }
439
- if (tolerance > 0) {
440
- const now2 = options.now ? options.now() : Math.floor(Date.now() / 1e3);
441
- if (!Number.isFinite(now2)) {
442
- throw new GovernConfigError(
443
- "verifyWebhookSignature: the `now` option must return the current unix time in seconds as a finite number. A value that is not one cannot be compared with the delivery's timestamp, which leaves the replay window open."
444
- );
445
- }
446
- if (Math.abs(now2 - timestamp) > tolerance) {
447
- throw new GovernWebhookError("X-Govern-Timestamp is outside the accepted window");
448
- }
449
- }
450
- const expected = await signWebhookPayload(secret, timestamp, bodyBytes);
451
- const candidates = signatureHeader.split(/[\s,]+/).map((s) => s.trim()).filter((s) => s.startsWith("v1="));
452
- const matched = candidates.some((candidate) => timingSafeEqual(candidate, expected));
453
- if (!matched) throw new GovernWebhookError("webhook signature does not match");
454
- return {
455
- timestamp,
456
- event: header(headers, WEBHOOK_HEADERS.event),
457
- deliveryId: header(headers, WEBHOOK_HEADERS.delivery),
458
- body: new TextDecoder().decode(bodyBytes)
459
- };
460
- }
461
- async function handleWebhook(rawBody, headers, secret, options = {}) {
462
- const verified = await verifyWebhookSignature(rawBody, headers, secret, options);
463
- let parsed;
464
- try {
465
- parsed = JSON.parse(verified.body);
466
- } catch {
467
- throw new GovernWebhookError("webhook body is not JSON");
468
- }
469
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
470
- throw new GovernWebhookError("webhook body is not a JSON object");
471
- }
472
- return parseEvent(parsed, verified.event);
473
- }
474
- function parseEvent(raw, headerEvent) {
475
- const event = str(raw.event) ?? headerEvent ?? "unknown";
476
- const envelope = {
477
- id: str(raw.id) ?? "",
478
- attempt: num(raw.attempt) ?? 1,
479
- createdAt: str(raw.created_at) ?? "",
480
- applicationId: str(raw.application_id) ?? "",
481
- at: str(raw.at) ?? "",
482
- raw
483
- };
484
- switch (event) {
485
- case WEBHOOK_EVENTS.decisionReleased:
486
- case WEBHOOK_EVENTS.decisionRejected: {
487
- const reviewer = raw.reviewer && typeof raw.reviewer === "object" ? raw.reviewer : {};
488
- return {
489
- ...envelope,
490
- type: event,
491
- decisionId: str(raw.decision_id) ?? "",
492
- conversationId: str(raw.conversation_id) ?? "",
493
- turnId: str(raw.turn_id) ?? "",
494
- channel: str(raw.channel) ?? "",
495
- reviewState: event === WEBHOOK_EVENTS.decisionReleased ? "released" : "rejected",
496
- reviewer: { role: str(reviewer.role) },
497
- releasedContent: event === WEBHOOK_EVENTS.decisionReleased ? str(raw.released_content) : null,
498
- releasedWith: str(raw.released_with),
499
- model: str(raw.model),
500
- modelVersion: str(raw.model_version),
501
- stopClass: raw.stop_class === void 0 || raw.stop_class === null ? null : raw.stop_class === "never_sendable" ? "never_sendable" : "uncertain"
502
- };
503
- }
504
- case WEBHOOK_EVENTS.handoffOpened:
505
- case WEBHOOK_EVENTS.handoffClaimed:
506
- case WEBHOOK_EVENTS.handoffResolved:
507
- case WEBHOOK_EVENTS.handoffResumed:
508
- return {
509
- ...envelope,
510
- type: event,
511
- handoffId: str(raw.handoff_id) ?? "",
512
- decisionId: str(raw.decision_id),
513
- patientRefHash: str(raw.patient_ref_hash),
514
- state: str(raw.state) ?? "",
515
- version: num(raw.version) ?? 0,
516
- queueLabel: str(raw.queue_label),
517
- assigned: raw.assigned === true,
518
- dueAt: str(raw.due_at),
519
- resolvedAt: str(raw.resolved_at),
520
- pausesAutomation: raw.pauses_automation !== false
521
- };
522
- default:
523
- return { ...envelope, type: "unknown", event };
524
- }
525
- }
526
- function requireSecret(secret, fn) {
527
- if (typeof secret !== "string" || secret.trim() === "") {
528
- throw new GovernConfigError(
529
- `${fn}: a webhook secret is required. Pass the application's signing secret (\`whsec_...\`); an empty or blank one cannot verify anything.`
530
- );
531
- }
532
- }
533
- function signedMessage(timestamp, body) {
534
- const prefix = new TextEncoder().encode(`${timestamp}.`);
535
- const bodyBytes = typeof body === "string" ? new TextEncoder().encode(body) : body;
536
- const out = new Uint8Array(prefix.length + bodyBytes.length);
537
- out.set(prefix, 0);
538
- out.set(bodyBytes, prefix.length);
539
- return out;
540
- }
541
- function toBytes(body) {
542
- if (typeof body === "string") return new TextEncoder().encode(body);
543
- if (body instanceof Uint8Array) return body;
544
- if (body instanceof ArrayBuffer) return new Uint8Array(body);
545
- throw new GovernConfigError(
546
- "verifyWebhookSignature: the body must be the raw request body, as a string, a Uint8Array (a Node Buffer is one) or an ArrayBuffer. A body that has been through JSON.parse, or no body at all, is not the bytes that were signed, so there is nothing a signature can be checked against."
547
- );
548
- }
549
- function header(headers, name) {
550
- if (typeof headers.get === "function") {
551
- const value2 = headers.get(name);
552
- return value2 ?? null;
553
- }
554
- const record = headers;
555
- const key = Object.keys(record).find((k) => k.toLowerCase() === name);
556
- if (!key) return null;
557
- const value = record[key];
558
- if (Array.isArray(value)) return value[0] ?? null;
559
- return value ?? null;
560
- }
561
- function str(value) {
562
- return typeof value === "string" ? value : null;
563
- }
564
- function num(value) {
565
- return typeof value === "number" && Number.isFinite(value) ? value : null;
566
- }
567
-
568
- // src/client.ts
569
- var DEFAULT_BASE_URL = "https://api.anybio.io";
570
- var DEFAULT_TIMEOUT_MS = 5e3;
571
- var DEFAULT_MAX_RETRIES = 2;
572
- var DEFAULT_HOLD_MESSAGE = "Thanks for your message. A person from our team will review it and follow up with you shortly.";
573
- var RESERVED_TURN_ID_PREFIX = "govern:";
574
- var MAX_CONVERSATION_ID_CHARS = 187;
575
- var MAX_TURN_ID_CHARS = 206;
576
- var TRANSIENT_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429]);
577
- function isClientMisconfiguration(error) {
578
- if (!(error instanceof GovernApiError)) return false;
579
- if (error.status < 400 || error.status >= 500) return false;
580
- return !TRANSIENT_HTTP_STATUSES.has(error.status);
581
- }
582
- var GOVERN_PATHS = {
583
- evaluate: "/api/v1/govern/evaluate",
584
- decision: (id) => `/api/v1/govern/decisions/${encodeURIComponent(id)}`,
585
- outcome: (id) => `/api/v1/govern/decisions/${encodeURIComponent(id)}/outcome`,
586
- disclosures: "/api/v1/govern/disclosures",
587
- transcripts: "/api/v1/govern/transcripts",
588
- transcriptJob: (id) => `/api/v1/govern/transcripts/${encodeURIComponent(id)}`,
589
- transcriptTurns: (id) => `/api/v1/govern/transcripts/${encodeURIComponent(id)}/turns`,
590
- patientConsent: "/api/v1/govern/patients/consent",
591
- patientOptOut: "/api/v1/govern/patients/opt-out",
592
- patientState: "/api/v1/govern/patients/state",
593
- webhookDeliveries: "/api/v1/govern/webhook-deliveries",
594
- handoffs: "/api/v1/govern/handoffs",
595
- handoff: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}`,
596
- handoffClaim: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/claim`,
597
- handoffContact: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/contact-attempt`,
598
- handoffResolve: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/resolve`,
599
- handoffResume: (id) => `/api/v1/govern/handoffs/${encodeURIComponent(id)}/resume`
600
- };
601
- var KNOWN_VERDICTS = /* @__PURE__ */ new Set(["allow", "hold", "block", "route_to_human"]);
602
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
603
- function createGovern(options) {
604
- return new Govern(options);
605
- }
606
- var Govern = class {
607
- application;
608
- applicationId;
609
- baseUrl;
610
- holdMessage;
611
- assumeMode;
612
- /** Hand-offs on your team. */
613
- handoffs;
614
- transport;
615
- onEvent;
616
- modes = /* @__PURE__ */ new Map();
617
- disclosureRefs = new BoundedMap(1e4);
618
- pendingAcks = new BoundedMap(1e4);
619
- reportedDecisions = new BoundedMap(1e4);
620
- /** Decision ids whose holding line this instance has already armed. */
621
- holdingLines = new BoundedMap(1e4);
622
- releaseWaiters = /* @__PURE__ */ new Map();
623
- constructor(options) {
624
- if (!options.dangerouslyAllowBrowser && runningInBrowser()) {
625
- throw new GovernConfigError(
626
- "Govern must not run in a browser: the application key is a server-side secret. Call the API from your server, or from an edge or serverless function."
627
- );
628
- }
629
- if (typeof options.apiKey !== "string" || options.apiKey.trim() === "") {
630
- throw new GovernConfigError("Govern requires apiKey (the application key from the console).");
631
- }
632
- if (typeof options.application !== "string" || options.application.trim() === "") {
633
- throw new GovernConfigError("Govern requires application (the application id or a label).");
634
- }
635
- const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch : void 0);
636
- if (!fetchImpl) {
637
- throw new GovernConfigError("No fetch implementation found. Pass one as `fetch` or run on Node 18+.");
638
- }
639
- this.application = options.application.trim();
640
- this.applicationId = UUID.test(this.application) ? this.application.toLowerCase() : null;
641
- this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
642
- this.holdMessage = options.holdMessage ?? DEFAULT_HOLD_MESSAGE;
643
- this.assumeMode = options.assumeMode ?? "enforce";
644
- this.onEvent = isolateEvents(options.onEvent);
645
- this.transport = {
646
- baseUrl: this.baseUrl,
647
- apiKey: options.apiKey.trim(),
648
- fetch: fetchImpl,
649
- timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
650
- maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
651
- onEvent: this.onEvent
652
- };
653
- this.handoffs = new GovernHandoffs(this.transport);
654
- }
655
- // -------------------------------------------------------------------------
656
- // The contract
657
- // -------------------------------------------------------------------------
658
- /**
659
- * Evaluate one turn. Enforce answers inline (200). Observe answers 202 at
660
- * once with `decision: "allow"` and a decision id; the gate runs after the
661
- * response and its verdict lands on the record as `wouldHave`. A replay of
662
- * the same `turnId` returns the stored decision.
663
- */
664
- async evaluate(input) {
665
- requireConversationId(input.conversationId);
666
- requireTurnId(input.turnId);
667
- requireText(input.content, "content");
668
- const disclosure = input.disclosure ?? this.disclosureAttachment(input.conversationId);
669
- const body = {
670
- conversation_id: input.conversationId,
671
- turn_id: input.turnId,
672
- channel: input.channel,
673
- audience: input.audience,
674
- content: input.content
675
- };
676
- if (this.applicationId) body.application_id = this.applicationId;
677
- if (input.patientRef !== void 0) body.patient_ref = input.patientRef;
678
- if (disclosure) {
679
- body.disclosure = {};
680
- if (disclosure.established !== void 0) body.disclosure.established = disclosure.established;
681
- if (disclosure.ref !== void 0) body.disclosure.ref = disclosure.ref;
682
- }
683
- if (input.metadata !== void 0) body.metadata = input.metadata;
684
- if (input.modeHint !== void 0) body.mode_hint = input.modeHint;
685
- if (input.inbound) {
686
- body.inbound = {
687
- content: input.inbound.content,
688
- received_at: isoString(input.inbound.receivedAt)
689
- };
690
- }
691
- const model = input.model?.trim();
692
- if (model) body.model = model;
693
- const modelVersion = input.modelVersion?.trim();
694
- if (modelVersion) body.model_version = modelVersion;
695
- const response = await send(this.transport, {
696
- method: "POST",
697
- path: GOVERN_PATHS.evaluate,
698
- body,
699
- idempotencyKey: input.turnId,
700
- signal: input.signal
701
- });
702
- const decision = this.read(toDecision(response.body, response.status === 202));
703
- this.onEvent?.({
704
- type: "decision",
705
- decisionId: decision.id,
706
- conversationId: decision.conversationId,
707
- turnId: decision.turnId,
708
- channel: decision.channel,
709
- audience: decision.audience,
710
- decision: decision.decision,
711
- mode: decision.mode,
712
- status: decision.status,
713
- accepted: decision.accepted,
714
- reasons: decision.reasons
715
- });
716
- return decision;
717
- }
718
- /** The decision with its current review state; the first hold-resolution path. */
719
- async getDecision(decisionId, options = {}) {
720
- requireText(decisionId, "decisionId");
721
- const response = await send(this.transport, {
722
- method: "GET",
723
- path: GOVERN_PATHS.decision(decisionId),
724
- signal: options.signal
725
- });
726
- return this.read(toDecision(response.body, false));
727
- }
728
- /**
729
- * Report what went out. The text is hashed here with SHA-256 and only the
730
- * hash is sent. One outcome per decision: the same report again is
731
- * accepted; a different one is refused with 409.
732
- */
733
- async reportOutcome(decisionId, input) {
734
- requireText(decisionId, "decisionId");
735
- const given = input.contentHash?.trim().toLowerCase();
736
- let hash = given === "" ? void 0 : given;
737
- if (hash === void 0 && input.content !== void 0) hash = await sha256Hex(input.content);
738
- if (input.delivered && hash === void 0) {
739
- throw new GovernConfigError(
740
- "reportOutcome: pass `content` (hashed locally) or `contentHash` when delivered is true."
741
- );
742
- }
743
- const decision = await this.postOutcome(decisionId, {
744
- delivered: input.delivered,
745
- deliveredAt: isoString(input.deliveredAt ?? /* @__PURE__ */ new Date()),
746
- contentHash: hash,
747
- deliveryRef: input.deliveryRef,
748
- signal: input.signal
749
- });
750
- this.reportedDecisions.set(decisionId, true);
751
- this.onEvent?.({ type: "outcome", decisionId, delivered: input.delivered, auto: false });
752
- return decision;
753
- }
754
- /**
755
- * Record the AI-identity disclosure shown at the start of a conversation.
756
- * Once per conversation; the returned `ref` is attached to every later
757
- * `evaluate` for the conversation automatically.
758
- */
759
- async recordDisclosure(input) {
760
- requireConversationId(input.conversationId);
761
- requireText(input.textShown, "textShown");
762
- const body = {
763
- conversation_id: input.conversationId,
764
- channel: input.channel,
765
- text_shown: input.textShown,
766
- at: isoString(input.at ?? /* @__PURE__ */ new Date())
767
- };
768
- if (this.applicationId) body.application_id = this.applicationId;
769
- const response = await send(this.transport, {
770
- method: "POST",
771
- path: GOVERN_PATHS.disclosures,
772
- body,
773
- signal: input.signal
774
- });
775
- const view = response.body;
776
- this.disclosureRefs.set(input.conversationId, view.ref);
777
- return {
778
- ref: view.ref,
779
- applicationId: view.application_id,
780
- conversationId: view.conversation_id,
781
- channel: view.channel,
782
- evidenceId: view.evidence_id,
783
- recordedAt: view.recorded_at,
784
- created: response.status === 201,
785
- raw: view
786
- };
787
- }
788
- /**
789
- * Poll a held decision with backoff until a reviewer releases or rejects
790
- * it. Resolves `null` on timeout; throws `GovernAbortError` if `signal`
791
- * fires. A webhook handled through `handleWebhook` wakes the poll early.
792
- */
793
- async waitForRelease(decisionId, options = {}) {
794
- requireText(decisionId, "decisionId");
795
- const timeoutMs = options.timeoutMs ?? 15 * 6e4;
796
- const maxIntervalMs = options.maxIntervalMs ?? 15e3;
797
- let intervalMs = options.intervalMs ?? 1e3;
798
- const deadline = Date.now() + timeoutMs;
799
- for (; ; ) {
800
- const decision = await this.getDecision(decisionId, { signal: options.signal });
801
- const settled = settle(decision);
802
- if (settled) return settled;
803
- const remaining = deadline - Date.now();
804
- if (remaining <= 0) return null;
805
- await this.sleepOrWake(decisionId, Math.min(intervalMs, remaining), options.signal);
806
- intervalMs = Math.min(intervalMs * 2, maxIntervalMs);
807
- }
808
- }
809
- /**
810
- * Verify a webhook delivery and return the typed event. When the event
811
- * resolves a held decision, any `waitForRelease` on it is woken at once.
812
- */
813
- async handleWebhook(rawBody, headers, secret, options) {
814
- const event = await handleWebhook(rawBody, headers, secret, options);
815
- if (event.type === "decision.released" || event.type === "decision.rejected") {
816
- this.wake(event.decisionId);
817
- }
818
- return event;
819
- }
820
- // -------------------------------------------------------------------------
821
- // guard
822
- // -------------------------------------------------------------------------
823
- /**
824
- * Run `fn` to get the draft, evaluate it, and return what to deliver.
825
- *
826
- * - allow: the draft (or, for a clinician audience, the gate's substitution when it returns one)
827
- * - hold or block: the hold message when `showHoldText`, else the empty string
828
- * - API unreachable: a hold, as above, when the channel's last known mode is
829
- * enforce (or unknown), the draft flagged `degraded` when it is observe or off
830
- *
831
- * On a hold, `sendHoldingLine` says whether a holding line is owed to the
832
- * patient now: at most once per decision in this instance, and never where
833
- * the contract says another message is the wrong thing. `showHoldText`
834
- * applies the channel: true on every hold in an in-session channel
835
- * (`web_chat`, `app_message`), where the patient is waiting for the reply,
836
- * and exactly `sendHoldingLine` on an outbound or unknown channel.
837
- *
838
- * Never returns rewritten text for a patient audience.
839
- */
840
- async guard(fn, ctx) {
841
- requireConversationId(ctx.conversationId);
842
- if (ctx.turnId !== void 0) requireTurnId(ctx.turnId);
843
- void this.flushPendingAck(ctx.conversationId);
844
- const produced = await fn();
845
- const draft = typeof produced === "string" ? produced : produced?.text;
846
- if (typeof draft !== "string") {
847
- throw new GovernConfigError("guard: the draft function must return a string or { text: string }.");
848
- }
849
- const turnId = ctx.turnId ?? randomId();
850
- const holdMessage = ctx.holdMessage ?? this.holdMessage;
851
- let record = null;
852
- let mode;
853
- let degraded = false;
854
- let degradeCause = "gate_unavailable";
855
- let routeToHuman = false;
856
- let handoff = null;
857
- let inboundFlags = [];
858
- try {
859
- const input = {
860
- conversationId: ctx.conversationId,
861
- turnId,
862
- channel: ctx.channel,
863
- audience: ctx.audience,
864
- content: draft
865
- };
866
- if (ctx.patientRef !== void 0) input.patientRef = ctx.patientRef;
867
- if (ctx.disclosure !== void 0) input.disclosure = ctx.disclosure;
868
- if (ctx.metadata !== void 0) input.metadata = ctx.metadata;
869
- if (ctx.inbound !== void 0) input.inbound = ctx.inbound;
870
- if (ctx.model !== void 0) input.model = ctx.model;
871
- if (ctx.modelVersion !== void 0) input.modelVersion = ctx.modelVersion;
872
- if (ctx.signal !== void 0) input.signal = ctx.signal;
873
- record = await this.evaluate(input);
874
- mode = record.mode;
875
- degraded = record.degraded;
876
- routeToHuman = record.routeToHuman || record.decision === "route_to_human";
877
- handoff = record.handoff;
878
- inboundFlags = record.inboundFlags;
879
- } catch (error) {
880
- if (error instanceof GovernAbortError || error instanceof GovernConfigError) throw error;
881
- degraded = true;
882
- degradeCause = isClientMisconfiguration(error) ? REASONS.clientMisconfigured : REASONS.gateUnavailable;
883
- const learned = this.modes.get(ctx.channel);
884
- mode = learned ?? this.assumeMode;
885
- this.onEvent?.({
886
- type: "degraded",
887
- conversationId: ctx.conversationId,
888
- turnId,
889
- channel: ctx.channel,
890
- mode,
891
- modeSource: learned ? "learned" : "assumed",
892
- cause: degradeCause,
893
- status: error instanceof GovernApiError ? error.status : null,
894
- error: describe(error)
895
- });
896
- }
897
- let decision;
898
- let text;
899
- let reasons;
900
- if (record) {
901
- decision = record.decision;
902
- reasons = record.unknownDecision ? [...record.reasons, REASONS.unknownDecision] : record.reasons;
903
- if (decision === "allow") {
904
- text = record.audience === "clinician" && record.deliverableContent ? record.deliverableContent : draft;
905
- } else {
906
- text = holdMessage;
907
- }
908
- } else if (mode === "enforce") {
909
- decision = "hold";
910
- text = holdMessage;
911
- reasons = [degradeCause];
912
- } else {
913
- decision = "allow";
914
- text = draft;
915
- reasons = [degradeCause];
916
- }
917
- const held = decision !== "allow";
918
- const sendHoldingLine = held && record !== null && record.sendHoldingLine;
919
- const showHoldText = held && (ctx.audience !== "patient" || isInSessionChannel(ctx.channel) || sendHoldingLine);
920
- if (held && !showHoldText) text = "";
921
- const stopClass = record?.stopClass ?? null;
922
- const owed = !held || showHoldText;
923
- const decisionId = record?.id ?? null;
924
- if (decisionId) {
925
- const delivered = owed;
926
- this.pendingAcks.set(ctx.conversationId, {
927
- decisionId,
928
- delivered,
929
- contentHash: delivered ? await sha256Hex(text) : void 0,
930
- at: (/* @__PURE__ */ new Date()).toISOString()
931
- });
932
- }
933
- let acked = false;
934
- const ack = async (options = {}) => {
935
- if (acked) return;
936
- acked = true;
937
- if (!decisionId) return;
938
- const pending = this.pendingAcks.get(ctx.conversationId);
939
- if (pending?.decisionId === decisionId) this.pendingAcks.delete(ctx.conversationId);
940
- if (this.reportedDecisions.has(decisionId)) return;
941
- const delivered = options.delivered ?? owed;
942
- const outcome = { delivered };
943
- if (options.content !== void 0) outcome.content = options.content;
944
- else if (delivered) outcome.content = text;
945
- if (options.deliveredAt !== void 0) outcome.deliveredAt = options.deliveredAt;
946
- if (options.deliveryRef !== void 0) outcome.deliveryRef = options.deliveryRef;
947
- await this.reportOutcome(decisionId, outcome);
948
- };
949
- return {
950
- text,
951
- decisionId,
952
- decision,
953
- mode,
954
- degraded,
955
- reasons,
956
- held,
957
- sendHoldingLine,
958
- showHoldText,
959
- stopClass,
960
- routeToHuman,
961
- handoff,
962
- inboundFlags,
963
- record,
964
- ack
965
- };
966
- }
967
- /** Report every outcome `guard` is still holding as delivered. Call on shutdown. */
968
- async flushPendingAcks() {
969
- const conversations = [...this.pendingAcks.keys()];
970
- await Promise.all(conversations.map((c) => this.flushPendingAck(c)));
971
- }
972
- // -------------------------------------------------------------------------
973
- // Memory the caller may read or seed
974
- // -------------------------------------------------------------------------
975
- /** The mode last seen for a channel, learned from responses. */
976
- lastKnownMode(channel) {
977
- return this.modes.get(channel);
978
- }
979
- /** Seed the mode memory, for example from a value persisted across processes. */
980
- rememberMode(channel, mode) {
981
- this.modes.set(channel, mode);
982
- }
983
- /** The disclosure `ref` recorded for a conversation in this process, if any. */
984
- disclosureRef(conversationId) {
985
- return this.disclosureRefs.get(conversationId);
986
- }
987
- /** Seed a disclosure `ref` recorded elsewhere so it is attached to later evaluates. */
988
- rememberDisclosure(conversationId, ref) {
989
- this.disclosureRefs.set(conversationId, ref);
990
- }
991
- // -------------------------------------------------------------------------
992
- // Transcripts, patient state and webhook deliveries
993
- // -------------------------------------------------------------------------
994
- /** Observe only: a batch of past turns, each evaluated and recorded as would-have. */
995
- async submitTranscripts(input) {
996
- if (!Array.isArray(input.turns) || input.turns.length === 0) {
997
- throw new GovernConfigError("submitTranscripts: turns must be a non-empty array.");
998
- }
999
- input.turns.forEach((turn, index) => {
1000
- requireConversationId(turn.conversationId, `turns[${index}].conversationId`);
1001
- requireTurnId(turn.turnId, `turns[${index}].turnId`);
1002
- });
1003
- const body = {
1004
- turns: input.turns.map((turn) => ({
1005
- conversation_id: turn.conversationId,
1006
- turn_id: turn.turnId,
1007
- channel: turn.channel,
1008
- audience: turn.audience,
1009
- content: turn.content,
1010
- sent_at: isoString(turn.sentAt)
1011
- }))
1012
- };
1013
- if (this.applicationId) body.application_id = this.applicationId;
1014
- const response = await send(this.transport, {
1015
- method: "POST",
1016
- path: GOVERN_PATHS.transcripts,
1017
- body,
1018
- signal: input.signal,
1019
- // The transport retries a 500, and the API replays a batch by this key.
1020
- // Without one, a 500-then-success opens a second job. Defaulted per call, so every attempt of this call is the one
1021
- // write and a genuinely new batch is still a new job.
1022
- idempotencyKey: idempotencyKey(input.idempotencyKey)
1023
- });
1024
- return toTranscriptJob(response.body, response.status === 202);
1025
- }
1026
- async getTranscriptJob(jobId, options = {}) {
1027
- requireText(jobId, "jobId");
1028
- const response = await send(this.transport, {
1029
- method: "GET",
1030
- path: GOVERN_PATHS.transcriptJob(jobId),
1031
- signal: options.signal
1032
- });
1033
- return toTranscriptJob(response.body, false);
1034
- }
1035
- async getTranscriptJobTurns(jobId, options = {}) {
1036
- requireText(jobId, "jobId");
1037
- const response = await send(this.transport, {
1038
- method: "GET",
1039
- path: GOVERN_PATHS.transcriptTurns(jobId),
1040
- signal: options.signal
1041
- });
1042
- return response.body;
1043
- }
1044
- /** Record that the patient granted or revoked consent to be contacted. The reference travels in the body, never a URL. */
1045
- async recordPatientConsent(input) {
1046
- requireText(input.patientRef, "patientRef");
1047
- const body = { patient_ref: input.patientRef, state: input.state };
1048
- if (input.channel !== void 0) body.channel = input.channel;
1049
- if (input.at !== void 0) body.at = isoString(input.at);
1050
- const response = await send(this.transport, {
1051
- method: "POST",
1052
- path: GOVERN_PATHS.patientConsent,
1053
- body,
1054
- signal: input.signal,
1055
- idempotencyKey: idempotencyKey(input.idempotencyKey)
1056
- });
1057
- return response.body;
1058
- }
1059
- /** Record an opt-out (or, for an opt-out you recorded yourself, an opt back in). */
1060
- async recordPatientOptOut(input) {
1061
- requireText(input.patientRef, "patientRef");
1062
- const body = { patient_ref: input.patientRef, opted_out: input.optedOut };
1063
- if (input.channel !== void 0) body.channel = input.channel;
1064
- if (input.at !== void 0) body.at = isoString(input.at);
1065
- const response = await send(this.transport, {
1066
- method: "POST",
1067
- path: GOVERN_PATHS.patientOptOut,
1068
- body,
1069
- signal: input.signal,
1070
- idempotencyKey: idempotencyKey(input.idempotencyKey)
1071
- });
1072
- return response.body;
1073
- }
1074
- /** The patient's consent, opt-out and frequency state. A POST so the reference stays out of the URL. */
1075
- async getPatientState(patientRef, options = {}) {
1076
- requireText(patientRef, "patientRef");
1077
- const response = await send(this.transport, {
1078
- method: "POST",
1079
- path: GOVERN_PATHS.patientState,
1080
- body: { patient_ref: patientRef },
1081
- signal: options.signal
1082
- });
1083
- return response.body;
1084
- }
1085
- /** The webhook delivery log for the application: counts and codes, never a body. */
1086
- async listWebhookDeliveries(query = {}) {
1087
- const response = await send(this.transport, {
1088
- method: "GET",
1089
- path: GOVERN_PATHS.webhookDeliveries,
1090
- query: {
1091
- decision_id: query.decisionId,
1092
- handoff_id: query.handoffId,
1093
- status: query.status
1094
- },
1095
- signal: query.signal
1096
- });
1097
- return response.body;
1098
- }
1099
- // -------------------------------------------------------------------------
1100
- // Internals
1101
- // -------------------------------------------------------------------------
1102
- async postOutcome(decisionId, input) {
1103
- const body = {
1104
- delivered: input.delivered,
1105
- delivered_at: input.deliveredAt
1106
- };
1107
- if (input.contentHash !== void 0) body.delivered_content_hash = input.contentHash;
1108
- if (input.deliveryRef !== void 0) body.delivery_ref = input.deliveryRef;
1109
- const response = await send(this.transport, {
1110
- method: "POST",
1111
- path: GOVERN_PATHS.outcome(decisionId),
1112
- body,
1113
- signal: input.signal
1114
- });
1115
- return this.read(toDecision(response.body, false), { arm: false });
1116
- }
1117
- async flushPendingAck(conversationId) {
1118
- const pending = this.pendingAcks.get(conversationId);
1119
- if (!pending) return;
1120
- this.pendingAcks.delete(conversationId);
1121
- if (this.reportedDecisions.has(pending.decisionId)) return;
1122
- try {
1123
- await this.postOutcome(pending.decisionId, {
1124
- delivered: pending.delivered,
1125
- deliveredAt: pending.at,
1126
- contentHash: pending.contentHash,
1127
- deliveryRef: void 0,
1128
- signal: void 0
1129
- });
1130
- this.reportedDecisions.set(pending.decisionId, true);
1131
- this.onEvent?.({ type: "outcome", decisionId: pending.decisionId, delivered: pending.delivered, auto: true });
1132
- } catch (error) {
1133
- if (!this.pendingAcks.has(conversationId)) this.pendingAcks.set(conversationId, pending);
1134
- this.onEvent?.({ type: "error", operation: "auto_ack", error: describe(error) });
1135
- }
1136
- }
1137
- disclosureAttachment(conversationId) {
1138
- const ref = this.disclosureRefs.get(conversationId);
1139
- return ref ? { established: true, ref } : void 0;
1140
- }
1141
- /**
1142
- * Every decision the API returns passes through here: the channel's mode is
1143
- * learned, and the holding line is armed at most once per decision id.
1144
- *
1145
- * The API's `send_holding_line` is a property of the decision, returned on
1146
- * every read of it, and the contract asks the caller to send at most one
1147
- * holding line per decision. Handing that flag through unfiltered would put
1148
- * the dedup on every integration, and the obvious integration (send the
1149
- * holding line whenever the flag is set) would send it again on a retried
1150
- * turn. So the first read that carries it arms it and every later read in
1151
- * this instance answers false. The API's own value stays on `raw`.
1152
- *
1153
- * The conditions the API already applies are applied again here, so a
1154
- * server that disagrees with its own contract cannot make this SDK tell a
1155
- * caller to message a patient who opted out.
1156
- */
1157
- read(decision, options = { arm: true }) {
1158
- this.modes.set(decision.channel, decision.mode);
1159
- const id = decision.id;
1160
- if (!decision.sendHoldingLine || !id) return decision;
1161
- const eligible = options.arm && holdingLineApplies(decision) && !this.holdingLines.has(id);
1162
- this.holdingLines.set(id, true);
1163
- return eligible ? decision : { ...decision, sendHoldingLine: false };
1164
- }
1165
- sleepOrWake(decisionId, ms, signal) {
1166
- return new Promise((resolve, reject) => {
1167
- if (signal?.aborted) {
1168
- reject(new GovernAbortError(signal.reason));
1169
- return;
1170
- }
1171
- const waiters = this.releaseWaiters.get(decisionId) ?? /* @__PURE__ */ new Set();
1172
- this.releaseWaiters.set(decisionId, waiters);
1173
- const done = () => {
1174
- clearTimeout(timer);
1175
- waiters.delete(wake);
1176
- if (waiters.size === 0) this.releaseWaiters.delete(decisionId);
1177
- signal?.removeEventListener("abort", onAbort);
1178
- };
1179
- const wake = () => {
1180
- done();
1181
- resolve();
1182
- };
1183
- const onAbort = () => {
1184
- done();
1185
- reject(new GovernAbortError(signal?.reason));
1186
- };
1187
- const timer = setTimeout(wake, ms);
1188
- waiters.add(wake);
1189
- signal?.addEventListener("abort", onAbort, { once: true });
1190
- });
1191
- }
1192
- wake(decisionId) {
1193
- const waiters = this.releaseWaiters.get(decisionId);
1194
- if (!waiters) return;
1195
- for (const wake of [...waiters]) wake();
1196
- }
1197
- };
1198
- function toDecision(wire, accepted) {
1199
- const rawVerdict = String(wire.decision);
1200
- const known = KNOWN_VERDICTS.has(rawVerdict);
1201
- const failOpen = wire.mode === "observe" || wire.mode === "off";
1202
- const decision = known ? rawVerdict : failOpen ? "allow" : "hold";
1203
- return {
1204
- id: wire.decision_id ?? null,
1205
- status: wire.status,
1206
- decision,
1207
- mode: wire.mode,
1208
- channel: wire.channel,
1209
- audience: wire.audience,
1210
- conversationId: wire.conversation_id,
1211
- turnId: wire.turn_id,
1212
- wouldHave: wire.would_have ?? null,
1213
- policy: wire.policy ? { id: wire.policy.id, name: wire.policy.name, version: wire.policy.version } : null,
1214
- reasons: Array.isArray(wire.reasons) ? [...wire.reasons] : [],
1215
- rationale: wire.rationale ?? null,
1216
- detectedClaims: Array.isArray(wire.detected_claims) ? [...wire.detected_claims] : [],
1217
- disclosureRequired: wire.disclosure_required === true,
1218
- reviewUrl: wire.review_url ?? null,
1219
- reviewState: wire.review_state ?? null,
1220
- // A patient audience never receives text from this field, whatever the server sends.
1221
- deliverableContent: wire.audience === "clinician" ? wire.deliverable_content ?? null : null,
1222
- releasedContent: wire.released_content ?? null,
1223
- stopClass: toStopClass(wire.stop_class),
1224
- // The API's value. `Govern` narrows it to at most once per decision id on
1225
- // the way out (see `Govern.read`); `raw.send_holding_line` keeps the original.
1226
- sendHoldingLine: wire.send_holding_line === true,
1227
- model: typeof wire.model === "string" ? wire.model : null,
1228
- modelVersion: typeof wire.model_version === "string" ? wire.model_version : null,
1229
- createdAt: wire.created_at ?? null,
1230
- decidedAt: wire.decided_at ?? null,
1231
- reviewedAt: wire.reviewed_at ?? null,
1232
- outcome: wire.outcome ? toOutcome(wire.outcome) : null,
1233
- // Read from the typed wire. Absent means false.
1234
- routeToHuman: wire.route_to_human === true,
1235
- wouldHaveRouted: wire.would_have_routed === true,
1236
- inboundFlags: toInboundFlags(wire.inbound_flags),
1237
- handoff: toHandoffRef(wire.handoff),
1238
- webhookDeliveries: Array.isArray(wire.webhook_deliveries) ? [...wire.webhook_deliveries] : [],
1239
- unknownDecision: known ? null : rawVerdict,
1240
- accepted,
1241
- degraded: !known,
1242
- raw: wire
1243
- };
1244
- }
1245
- function toStopClass(value) {
1246
- if (value === null || value === void 0) return null;
1247
- return value === "never_sendable" ? "never_sendable" : "uncertain";
1248
- }
1249
- var NO_HOLDING_LINE = /* @__PURE__ */ new Set([
1250
- REASONS.optedOut,
1251
- REASONS.consentMissing,
1252
- REASONS.consentRevoked,
1253
- REASONS.frequencyCap,
1254
- REASONS.patientStateUnavailable
1255
- ]);
1256
- function holdingLineApplies(decision) {
1257
- if (decision.decision === "allow") return false;
1258
- if (decision.audience !== "patient") return false;
1259
- if (decision.reviewState === "released" || decision.reviewState === "rejected") return false;
1260
- return !decision.reasons.some((reason) => NO_HOLDING_LINE.has(reason));
1261
- }
1262
- function toInboundFlags(value) {
1263
- if (!Array.isArray(value)) return [];
1264
- const out = [];
1265
- for (const item of value) {
1266
- if (item && typeof item === "object") {
1267
- const flag = item;
1268
- out.push({
1269
- ruleId: typeof flag.rule_id === "string" ? flag.rule_id : "",
1270
- category: typeof flag.category === "string" ? flag.category : ""
1271
- });
1272
- }
1273
- }
1274
- return out;
1275
- }
1276
- function toHandoffRef(value) {
1277
- if (!value || typeof value !== "object") return null;
1278
- const h = value;
1279
- if (typeof h.id !== "string") return null;
1280
- const str2 = (v) => typeof v === "string" ? v : null;
1281
- return {
1282
- id: h.id,
1283
- state: str2(h.state) ?? "",
1284
- version: typeof h.version === "number" ? h.version : 0,
1285
- queueLabel: str2(h.queue_label) ?? "",
1286
- assignedTo: str2(h.assigned_to),
1287
- dueAt: str2(h.due_at),
1288
- escalationDueAt: str2(h.escalation_due_at),
1289
- resolvedAt: str2(h.resolved_at),
1290
- automationResumedAt: str2(h.automation_resumed_at),
1291
- // Absent only from a server that predates the field, where every open
1292
- // hand-off paused automation; read it that way rather than as "not paused".
1293
- pausesAutomation: h.pauses_automation !== false
1294
- };
1295
- }
1296
- var GovernHandoffs = class {
1297
- constructor(transport) {
1298
- this.transport = transport;
1299
- }
1300
- transport;
1301
- async list(query = {}) {
1302
- const response = await send(this.transport, {
1303
- method: "GET",
1304
- path: GOVERN_PATHS.handoffs,
1305
- query: {
1306
- application_id: query.applicationId,
1307
- status: query.status,
1308
- assigned_to: query.assignedTo,
1309
- overdue: query.overdue === void 0 ? void 0 : String(query.overdue),
1310
- sort: query.sort,
1311
- limit: query.limit === void 0 ? void 0 : String(query.limit),
1312
- offset: query.offset === void 0 ? void 0 : String(query.offset)
1313
- },
1314
- signal: query.signal
1315
- });
1316
- return {
1317
- items: response.body.items,
1318
- total: response.body.total,
1319
- patientNames: { ...response.body.patient_names },
1320
- awaitingReply: Array.isArray(response.body.awaiting_reply) ? [...response.body.awaiting_reply] : [],
1321
- raw: response.body
1322
- };
1323
- }
1324
- async get(handoffId, options = {}) {
1325
- requireText(handoffId, "handoffId");
1326
- const response = await send(this.transport, {
1327
- method: "GET",
1328
- path: GOVERN_PATHS.handoff(handoffId),
1329
- signal: options.signal
1330
- });
1331
- return response.body;
1332
- }
1333
- /** Take the hand-off. */
1334
- claim(handoffId, input) {
1335
- return this.act(GOVERN_PATHS.handoffClaim, handoffId, input, { expected_version: input.expectedVersion });
1336
- }
1337
- /** Record an attempt to reach the patient on a claimed hand-off. */
1338
- contactAttempt(handoffId, input) {
1339
- const body = {
1340
- expected_version: input.expectedVersion,
1341
- outcome: input.outcome,
1342
- note: input.note
1343
- };
1344
- if (input.nextDueAt !== void 0) body.next_due_at = isoString(input.nextDueAt);
1345
- return this.act(GOVERN_PATHS.handoffContact, handoffId, input, body);
1346
- }
1347
- /** Resolve a claimed hand-off. */
1348
- resolve(handoffId, input) {
1349
- return this.act(GOVERN_PATHS.handoffResolve, handoffId, input, {
1350
- expected_version: input.expectedVersion,
1351
- disposition: input.disposition,
1352
- note: input.note,
1353
- resume_automation: input.resumeAutomation
1354
- });
1355
- }
1356
- /** Release the hold on automation for the patient of a resolved hand-off. */
1357
- resume(handoffId, input) {
1358
- return this.act(GOVERN_PATHS.handoffResume, handoffId, input, {
1359
- expected_version: input.expectedVersion,
1360
- note: input.note
1361
- });
1362
- }
1363
- async act(path, handoffId, input, body) {
1364
- requireText(handoffId, "handoffId");
1365
- if (!Number.isInteger(input.expectedVersion)) {
1366
- throw new GovernConfigError("expectedVersion is required and must be the integer version you last read.");
1367
- }
1368
- const response = await send(this.transport, {
1369
- method: "POST",
1370
- path: path(handoffId),
1371
- body,
1372
- signal: input.signal,
1373
- retry: false
1374
- });
1375
- return response.body;
1376
- }
1377
- };
1378
- function toOutcome(wire) {
1379
- return {
1380
- delivered: wire.delivered,
1381
- deliveredAt: wire.delivered_at,
1382
- deliveredContentHash: wire.delivered_content_hash ?? null,
1383
- deliveryRef: wire.delivery_ref ?? null,
1384
- recordedAt: wire.recorded_at,
1385
- hashMatchesRelease: wire.hash_matches_release ?? null,
1386
- raw: wire
1387
- };
1388
- }
1389
- function toTranscriptJob(wire, created) {
1390
- return {
1391
- jobId: wire.job_id,
1392
- applicationId: wire.application_id,
1393
- status: wire.status,
1394
- total: wire.total,
1395
- processed: wire.processed,
1396
- evaluated: wire.evaluated,
1397
- duplicate: wire.duplicate,
1398
- unavailable: wire.unavailable,
1399
- abandoned: wire.abandoned,
1400
- wouldHave: { ...wire.would_have },
1401
- created,
1402
- raw: wire
1403
- };
1404
- }
1405
- function settle(decision) {
1406
- if (decision.reviewState === "released") {
1407
- return { state: "released", content: decision.releasedContent, decision };
1408
- }
1409
- if (decision.reviewState === "rejected") return { state: "rejected", decision };
1410
- if (decision.decision === "allow") return { state: "not_held", decision };
1411
- if (decision.decision === "block" && decision.reviewState === null) return { state: "blocked", decision };
1412
- return null;
1413
- }
1414
- function runningInBrowser() {
1415
- const w = globalThis.window;
1416
- return typeof w !== "undefined" && typeof w.document !== "undefined";
1417
- }
1418
- function requireText(value, name) {
1419
- if (typeof value !== "string" || value.trim() === "") {
1420
- throw new GovernConfigError(`${name} is required and must be a non-empty string.`);
1421
- }
1422
- }
1423
- function codePoints(value) {
1424
- return [...value].length;
1425
- }
1426
- function requireConversationId(value, name = "conversationId") {
1427
- requireText(value, name);
1428
- if (codePoints(value.trim()) > MAX_CONVERSATION_ID_CHARS) {
1429
- throw new GovernConfigError(
1430
- `${name} must be at most ${MAX_CONVERSATION_ID_CHARS} characters. The API composes the conversation's disclosure reference from it, and that reference is bounded.`
1431
- );
1432
- }
1433
- }
1434
- function requireTurnId(value, name = "turnId") {
1435
- requireText(value, name);
1436
- const trimmed = value.trim();
1437
- if (trimmed.startsWith(RESERVED_TURN_ID_PREFIX)) {
1438
- throw new GovernConfigError(
1439
- `${name} must not start with "${RESERVED_TURN_ID_PREFIX}", which is reserved for the rows the API writes itself.`
1440
- );
1441
- }
1442
- if (codePoints(trimmed) > MAX_TURN_ID_CHARS) {
1443
- throw new GovernConfigError(
1444
- `${name} must be at most ${MAX_TURN_ID_CHARS} characters. The API composes the turn's reference from it, and that reference is bounded.`
1445
- );
1446
- }
1447
- }
1448
- function idempotencyKey(given) {
1449
- return given?.trim() || randomId();
1450
- }
1451
- function isoString(value) {
1452
- return value instanceof Date ? value.toISOString() : value;
1453
- }
1454
- function describe(error) {
1455
- if (error instanceof Error) return `${error.name}: ${error.message}`;
1456
- return String(error);
1457
- }
1458
- function isolateEvents(onEvent) {
1459
- if (!onEvent) return void 0;
1460
- let reporting = false;
1461
- return (event) => {
1462
- try {
1463
- onEvent(event);
1464
- } catch (error) {
1465
- if (reporting) return;
1466
- reporting = true;
1467
- try {
1468
- onEvent({ type: "error", operation: "on_event", error: describe(error) });
1469
- } catch {
1470
- } finally {
1471
- reporting = false;
1472
- }
1473
- }
1474
- };
1475
- }
1476
- var BoundedMap = class {
1477
- constructor(max) {
1478
- this.max = max;
1479
- }
1480
- max;
1481
- map = /* @__PURE__ */ new Map();
1482
- get(key) {
1483
- return this.map.get(key);
1484
- }
1485
- has(key) {
1486
- return this.map.has(key);
1487
- }
1488
- set(key, value) {
1489
- if (this.map.has(key)) this.map.delete(key);
1490
- this.map.set(key, value);
1491
- while (this.map.size > this.max) {
1492
- const oldest = this.map.keys().next();
1493
- if (oldest.done) break;
1494
- this.map.delete(oldest.value);
1495
- }
1496
- }
1497
- delete(key) {
1498
- this.map.delete(key);
1499
- }
1500
- keys() {
1501
- return this.map.keys();
1502
- }
1503
- };
1504
-
1505
- exports.AUDIENCES = AUDIENCES;
1506
- exports.CHANNELS = CHANNELS;
1507
- exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1508
- exports.DEFAULT_HOLD_MESSAGE = DEFAULT_HOLD_MESSAGE;
1509
- exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
1510
- exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1511
- exports.Govern = Govern;
1512
- exports.GovernAbortError = GovernAbortError;
1513
- exports.GovernApiError = GovernApiError;
1514
- exports.GovernConfigError = GovernConfigError;
1515
- exports.GovernConflictError = GovernConflictError;
1516
- exports.GovernError = GovernError;
1517
- exports.GovernHandoffs = GovernHandoffs;
1518
- exports.GovernNetworkError = GovernNetworkError;
1519
- exports.GovernNotAvailableError = GovernNotAvailableError;
1520
- exports.GovernTimeoutError = GovernTimeoutError;
1521
- exports.GovernWebhookError = GovernWebhookError;
1522
- exports.IN_SESSION_CHANNELS = IN_SESSION_CHANNELS;
1523
- exports.MAX_CONVERSATION_ID_CHARS = MAX_CONVERSATION_ID_CHARS;
1524
- exports.MAX_TURN_ID_CHARS = MAX_TURN_ID_CHARS;
1525
- exports.REASONS = REASONS;
1526
- exports.RESERVED_TURN_ID_PREFIX = RESERVED_TURN_ID_PREFIX;
1527
- exports.SDK_NAME = SDK_NAME;
1528
- exports.SDK_VERSION = SDK_VERSION;
1529
- exports.TRANSIENT_HTTP_STATUSES = TRANSIENT_HTTP_STATUSES;
1530
- exports.WEBHOOK_EVENTS = WEBHOOK_EVENTS;
1531
- exports.WEBHOOK_HEADERS = WEBHOOK_HEADERS;
1532
- exports.createGovern = createGovern;
1533
- exports.handleWebhook = handleWebhook;
1534
- exports.isAutomationPaused = isAutomationPaused;
1535
- exports.isClientMisconfiguration = isClientMisconfiguration;
1536
- exports.isGovernError = isGovernError;
1537
- exports.isInSessionChannel = isInSessionChannel;
1538
- exports.parseEvent = parseEvent;
1539
- exports.sha256Hex = sha256Hex;
1540
- exports.signWebhookPayload = signWebhookPayload;
1541
- exports.verifyWebhookSignature = verifyWebhookSignature;
7
+ Object.defineProperty(exports, "AUDIENCES", {
8
+ enumerable: true,
9
+ get: function () { return chunkI5XIXB5M_cjs.AUDIENCES; }
10
+ });
11
+ Object.defineProperty(exports, "CHANNELS", {
12
+ enumerable: true,
13
+ get: function () { return chunkI5XIXB5M_cjs.CHANNELS; }
14
+ });
15
+ Object.defineProperty(exports, "DEFAULT_BASE_URL", {
16
+ enumerable: true,
17
+ get: function () { return chunkI5XIXB5M_cjs.DEFAULT_BASE_URL; }
18
+ });
19
+ Object.defineProperty(exports, "DEFAULT_HOLD_MESSAGE", {
20
+ enumerable: true,
21
+ get: function () { return chunkI5XIXB5M_cjs.DEFAULT_HOLD_MESSAGE; }
22
+ });
23
+ Object.defineProperty(exports, "DEFAULT_MAX_RETRIES", {
24
+ enumerable: true,
25
+ get: function () { return chunkI5XIXB5M_cjs.DEFAULT_MAX_RETRIES; }
26
+ });
27
+ Object.defineProperty(exports, "DEFAULT_TIMEOUT_MS", {
28
+ enumerable: true,
29
+ get: function () { return chunkI5XIXB5M_cjs.DEFAULT_TIMEOUT_MS; }
30
+ });
31
+ Object.defineProperty(exports, "Govern", {
32
+ enumerable: true,
33
+ get: function () { return chunkI5XIXB5M_cjs.Govern; }
34
+ });
35
+ Object.defineProperty(exports, "GovernAbortError", {
36
+ enumerable: true,
37
+ get: function () { return chunkI5XIXB5M_cjs.GovernAbortError; }
38
+ });
39
+ Object.defineProperty(exports, "GovernApiError", {
40
+ enumerable: true,
41
+ get: function () { return chunkI5XIXB5M_cjs.GovernApiError; }
42
+ });
43
+ Object.defineProperty(exports, "GovernConfigError", {
44
+ enumerable: true,
45
+ get: function () { return chunkI5XIXB5M_cjs.GovernConfigError; }
46
+ });
47
+ Object.defineProperty(exports, "GovernConflictError", {
48
+ enumerable: true,
49
+ get: function () { return chunkI5XIXB5M_cjs.GovernConflictError; }
50
+ });
51
+ Object.defineProperty(exports, "GovernError", {
52
+ enumerable: true,
53
+ get: function () { return chunkI5XIXB5M_cjs.GovernError; }
54
+ });
55
+ Object.defineProperty(exports, "GovernHandoffs", {
56
+ enumerable: true,
57
+ get: function () { return chunkI5XIXB5M_cjs.GovernHandoffs; }
58
+ });
59
+ Object.defineProperty(exports, "GovernNetworkError", {
60
+ enumerable: true,
61
+ get: function () { return chunkI5XIXB5M_cjs.GovernNetworkError; }
62
+ });
63
+ Object.defineProperty(exports, "GovernNotAvailableError", {
64
+ enumerable: true,
65
+ get: function () { return chunkI5XIXB5M_cjs.GovernNotAvailableError; }
66
+ });
67
+ Object.defineProperty(exports, "GovernReportError", {
68
+ enumerable: true,
69
+ get: function () { return chunkI5XIXB5M_cjs.GovernReportError; }
70
+ });
71
+ Object.defineProperty(exports, "GovernTimeoutError", {
72
+ enumerable: true,
73
+ get: function () { return chunkI5XIXB5M_cjs.GovernTimeoutError; }
74
+ });
75
+ Object.defineProperty(exports, "GovernWebhookError", {
76
+ enumerable: true,
77
+ get: function () { return chunkI5XIXB5M_cjs.GovernWebhookError; }
78
+ });
79
+ Object.defineProperty(exports, "IN_SESSION_CHANNELS", {
80
+ enumerable: true,
81
+ get: function () { return chunkI5XIXB5M_cjs.IN_SESSION_CHANNELS; }
82
+ });
83
+ Object.defineProperty(exports, "MAX_CONVERSATION_ID_CHARS", {
84
+ enumerable: true,
85
+ get: function () { return chunkI5XIXB5M_cjs.MAX_CONVERSATION_ID_CHARS; }
86
+ });
87
+ Object.defineProperty(exports, "MAX_SUPERSEDES", {
88
+ enumerable: true,
89
+ get: function () { return chunkI5XIXB5M_cjs.MAX_SUPERSEDES; }
90
+ });
91
+ Object.defineProperty(exports, "MAX_TURN_ID_CHARS", {
92
+ enumerable: true,
93
+ get: function () { return chunkI5XIXB5M_cjs.MAX_TURN_ID_CHARS; }
94
+ });
95
+ Object.defineProperty(exports, "MAX_TURN_REF_CHARS", {
96
+ enumerable: true,
97
+ get: function () { return chunkI5XIXB5M_cjs.MAX_TURN_REF_CHARS; }
98
+ });
99
+ Object.defineProperty(exports, "OUTCOME_REASONS", {
100
+ enumerable: true,
101
+ get: function () { return chunkI5XIXB5M_cjs.OUTCOME_REASONS; }
102
+ });
103
+ Object.defineProperty(exports, "REASONS", {
104
+ enumerable: true,
105
+ get: function () { return chunkI5XIXB5M_cjs.REASONS; }
106
+ });
107
+ Object.defineProperty(exports, "RESERVED_TURN_ID_PREFIX", {
108
+ enumerable: true,
109
+ get: function () { return chunkI5XIXB5M_cjs.RESERVED_TURN_ID_PREFIX; }
110
+ });
111
+ Object.defineProperty(exports, "SDK_NAME", {
112
+ enumerable: true,
113
+ get: function () { return chunkI5XIXB5M_cjs.SDK_NAME; }
114
+ });
115
+ Object.defineProperty(exports, "SDK_VERSION", {
116
+ enumerable: true,
117
+ get: function () { return chunkI5XIXB5M_cjs.SDK_VERSION; }
118
+ });
119
+ Object.defineProperty(exports, "TRANSIENT_HTTP_STATUSES", {
120
+ enumerable: true,
121
+ get: function () { return chunkI5XIXB5M_cjs.TRANSIENT_HTTP_STATUSES; }
122
+ });
123
+ Object.defineProperty(exports, "WEBHOOK_EVENTS", {
124
+ enumerable: true,
125
+ get: function () { return chunkI5XIXB5M_cjs.WEBHOOK_EVENTS; }
126
+ });
127
+ Object.defineProperty(exports, "WEBHOOK_HEADERS", {
128
+ enumerable: true,
129
+ get: function () { return chunkI5XIXB5M_cjs.WEBHOOK_HEADERS; }
130
+ });
131
+ Object.defineProperty(exports, "createGovern", {
132
+ enumerable: true,
133
+ get: function () { return chunkI5XIXB5M_cjs.createGovern; }
134
+ });
135
+ Object.defineProperty(exports, "handleWebhook", {
136
+ enumerable: true,
137
+ get: function () { return chunkI5XIXB5M_cjs.handleWebhook; }
138
+ });
139
+ Object.defineProperty(exports, "isAutomationPaused", {
140
+ enumerable: true,
141
+ get: function () { return chunkI5XIXB5M_cjs.isAutomationPaused; }
142
+ });
143
+ Object.defineProperty(exports, "isClientMisconfiguration", {
144
+ enumerable: true,
145
+ get: function () { return chunkI5XIXB5M_cjs.isClientMisconfiguration; }
146
+ });
147
+ Object.defineProperty(exports, "isGovernError", {
148
+ enumerable: true,
149
+ get: function () { return chunkI5XIXB5M_cjs.isGovernError; }
150
+ });
151
+ Object.defineProperty(exports, "isInSessionChannel", {
152
+ enumerable: true,
153
+ get: function () { return chunkI5XIXB5M_cjs.isInSessionChannel; }
154
+ });
155
+ Object.defineProperty(exports, "parseEvent", {
156
+ enumerable: true,
157
+ get: function () { return chunkI5XIXB5M_cjs.parseEvent; }
158
+ });
159
+ Object.defineProperty(exports, "sha256Hex", {
160
+ enumerable: true,
161
+ get: function () { return chunkI5XIXB5M_cjs.sha256Hex; }
162
+ });
163
+ Object.defineProperty(exports, "signWebhookPayload", {
164
+ enumerable: true,
165
+ get: function () { return chunkI5XIXB5M_cjs.signWebhookPayload; }
166
+ });
167
+ Object.defineProperty(exports, "verifyWebhookSignature", {
168
+ enumerable: true,
169
+ get: function () { return chunkI5XIXB5M_cjs.verifyWebhookSignature; }
170
+ });