@hipnation-truth/sdk 0.27.0 → 0.28.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.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
5
  var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
@@ -17,6 +19,7 @@ var __spreadValues = (a, b) => {
17
19
  }
18
20
  return a;
19
21
  };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
23
  var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
21
24
  var __async = (__this, __arguments, generator) => {
22
25
  return new Promise((resolve, reject) => {
@@ -352,6 +355,304 @@ var AttachmentsResource = class {
352
355
  }
353
356
  };
354
357
 
358
+ // src/resources/care-inbox.ts
359
+ var NO_PARTICIPANT = { address: "", name: null };
360
+ function participant(p) {
361
+ return p ? { address: p.address, name: p.name } : __spreadValues({}, NO_PARTICIPANT);
362
+ }
363
+ function toEmailMessage(m) {
364
+ var _a, _b;
365
+ return {
366
+ id: m.id,
367
+ threadId: (_a = m.threadId) != null ? _a : "",
368
+ mailboxId: m.mailboxId,
369
+ direction: m.direction,
370
+ from: participant(m.from),
371
+ to: m.to.map(participant),
372
+ subject: (_b = m.subject) != null ? _b : "",
373
+ sentAt: m.sentAt,
374
+ hasAttachments: m.hasAttachments,
375
+ linkedPatientId: m.linkedPatientId,
376
+ linkedPatientName: m.linkedPatientName,
377
+ bodyText: m.bodyText
378
+ };
379
+ }
380
+ function toEmailThreadSummary(t) {
381
+ var _a, _b;
382
+ return {
383
+ id: t.id,
384
+ mailboxId: t.mailboxId,
385
+ subject: (_a = t.subject) != null ? _a : "",
386
+ lastMessageAt: t.lastMessageAt,
387
+ lastDirection: (_b = t.lastDirection) != null ? _b : "inbound",
388
+ counterpart: participant(t.counterpart),
389
+ messageCount: t.messageCount,
390
+ unreadCount: t.unreadCount,
391
+ unlinkedCount: t.unlinkedCount,
392
+ linkedPatientName: t.linkedPatientName,
393
+ hasAttachments: t.hasAttachments
394
+ };
395
+ }
396
+ function toEmailMailbox(m) {
397
+ var _a;
398
+ return {
399
+ id: m.id,
400
+ address: (_a = m.address) != null ? _a : "",
401
+ displayName: m.displayName,
402
+ mode: m.mode,
403
+ canSend: m.canSend,
404
+ bodyVisible: m.bodyVisible
405
+ };
406
+ }
407
+ function toMailboxAccess(a) {
408
+ return { mailboxes: a.mailboxes.map(toEmailMailbox), canTriage: a.canTriage };
409
+ }
410
+ function toEmailThreadDetail(d) {
411
+ return {
412
+ summary: toEmailThreadSummary(d.summary),
413
+ mailbox: toEmailMailbox(d.mailbox),
414
+ messages: d.messages.map(toEmailMessage),
415
+ bodyVisible: d.bodyVisible,
416
+ patientContact: null
417
+ };
418
+ }
419
+ function toThreadPage(p) {
420
+ return {
421
+ threads: p.threads.map(toEmailThreadSummary),
422
+ nextCursor: p.nextCursor
423
+ };
424
+ }
425
+ function toUnlinkedMessagePage(p) {
426
+ return {
427
+ messages: p.messages.map(toEmailMessage),
428
+ nextCursor: p.nextCursor
429
+ };
430
+ }
431
+ function toMarkReadResult(r) {
432
+ return { thread: toEmailThreadSummary(r.thread) };
433
+ }
434
+ var REASONS = [
435
+ "send_disabled",
436
+ "not_triage",
437
+ "body_gated",
438
+ "unauthenticated"
439
+ ];
440
+ var CODES = [
441
+ "forbidden",
442
+ "not_found",
443
+ "offline",
444
+ "unavailable",
445
+ "validation",
446
+ "unknown"
447
+ ];
448
+ function asReason(value) {
449
+ return REASONS.includes(value) ? value : null;
450
+ }
451
+ function asCode(value) {
452
+ return CODES.includes(value) ? value : null;
453
+ }
454
+ var CareInboxError = class extends Error {
455
+ constructor(code, fields = {}) {
456
+ var _a, _b, _c, _d;
457
+ const reason = (_a = fields.reason) != null ? _a : null;
458
+ const status = (_b = fields.status) != null ? _b : 0;
459
+ super(
460
+ `Care inbox request failed: ${code}${reason ? ` (${reason})` : ""}${status ? ` HTTP ${status}` : ""}`
461
+ );
462
+ this.name = "CareInboxError";
463
+ this.code = code;
464
+ this.status = status;
465
+ this.rpcCode = (_c = fields.rpcCode) != null ? _c : null;
466
+ this.reason = reason;
467
+ this.detail = (_d = fields.detail) != null ? _d : null;
468
+ }
469
+ };
470
+ function codeForStatus(status, rpcCode) {
471
+ if (status === 0) {
472
+ if (rpcCode === "TRANSPORT" || rpcCode === "TIMEOUT") {
473
+ return "offline";
474
+ }
475
+ if (rpcCode === "NO_USER_TOKEN") {
476
+ return "forbidden";
477
+ }
478
+ return "unknown";
479
+ }
480
+ if (status === 400) {
481
+ return "validation";
482
+ }
483
+ if (status === 401 || status === 403) {
484
+ return "forbidden";
485
+ }
486
+ if (status === 404) {
487
+ return "not_found";
488
+ }
489
+ if (status === 503) {
490
+ return "unavailable";
491
+ }
492
+ return "unknown";
493
+ }
494
+ function httpError(fields) {
495
+ var _a;
496
+ const unauthenticated = fields.status === 401 || fields.rpcCode === "NO_USER_TOKEN";
497
+ return new CareInboxError(codeForStatus(fields.status, fields.rpcCode), __spreadProps(__spreadValues({}, fields), {
498
+ reason: (_a = fields.reason) != null ? _a : unauthenticated ? "unauthenticated" : null
499
+ }));
500
+ }
501
+ function isCareInboxError(value) {
502
+ return value instanceof Error && asCode(value.code) !== null;
503
+ }
504
+ function toCareInboxError(value) {
505
+ if (value instanceof CareInboxError) {
506
+ return value;
507
+ }
508
+ const data = value && typeof value === "object" ? value.data : void 0;
509
+ if (data && typeof data === "object") {
510
+ const { code, reason } = data;
511
+ const known = asCode(code);
512
+ if (known) {
513
+ return new CareInboxError(known, { reason: asReason(reason) });
514
+ }
515
+ }
516
+ if (isCareInboxError(value)) {
517
+ const v = value;
518
+ return new CareInboxError(value.code, {
519
+ status: typeof v.status === "number" && Number.isInteger(v.status) && v.status >= 0 ? v.status : 0,
520
+ rpcCode: typeof v.rpcCode === "string" ? v.rpcCode : null,
521
+ reason: asReason(v.reason),
522
+ detail: typeof v.detail === "string" ? v.detail : null
523
+ });
524
+ }
525
+ return new CareInboxError("unknown");
526
+ }
527
+ function careInboxErrorInfo(err) {
528
+ const e = toCareInboxError(err);
529
+ return { code: e.code, reason: e.reason };
530
+ }
531
+ function newRequestId() {
532
+ const c = globalThis.crypto;
533
+ if (c && typeof c.randomUUID === "function") {
534
+ return c.randomUUID();
535
+ }
536
+ const bytes = new Uint8Array(16);
537
+ if (c && typeof c.getRandomValues === "function") {
538
+ c.getRandomValues(bytes);
539
+ } else {
540
+ for (let i = 0; i < bytes.length; i++) {
541
+ bytes[i] = Math.floor(Math.random() * 256);
542
+ }
543
+ }
544
+ bytes[6] = bytes[6] & 15 | 64;
545
+ bytes[8] = bytes[8] & 63 | 128;
546
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
547
+ ""
548
+ );
549
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
550
+ }
551
+ var _CareInboxResource = class _CareInboxResource {
552
+ constructor(apiBaseUrl, apiKey, getAuthToken) {
553
+ this.baseUrl = apiBaseUrl;
554
+ this.auth = { apiKey, getAuthToken };
555
+ }
556
+ /** Link one message to a patient (triage only). */
557
+ linkMessage(input) {
558
+ return __async(this, null, function* () {
559
+ var _a;
560
+ return this.post("/care-inbox/link", {
561
+ messageId: input.messageId,
562
+ patientId: input.patientId,
563
+ requestId: (_a = input.requestId) != null ? _a : newRequestId()
564
+ });
565
+ });
566
+ }
567
+ /** Undo a manual link (triage only). */
568
+ unlinkMessage(input) {
569
+ return __async(this, null, function* () {
570
+ var _a;
571
+ return this.post("/care-inbox/unlink", {
572
+ messageId: input.messageId,
573
+ requestId: (_a = input.requestId) != null ? _a : newRequestId()
574
+ });
575
+ });
576
+ }
577
+ /** Reply into a thread. This build always rejects 403 `send_disabled`. */
578
+ replyToThread(input) {
579
+ return __async(this, null, function* () {
580
+ return this.post("/care-inbox/outbound/thread-reply", {
581
+ threadId: input.threadId,
582
+ body: input.body,
583
+ clientRequestId: input.clientRequestId
584
+ });
585
+ });
586
+ }
587
+ /** Start a new email. This build always rejects 403 `send_disabled`. */
588
+ composeEmail(input) {
589
+ return __async(this, null, function* () {
590
+ return this.post("/care-inbox/outbound/compose", __spreadProps(__spreadValues({
591
+ to: input.to,
592
+ subject: input.subject,
593
+ body: input.body
594
+ }, input.patientId !== void 0 ? { patientId: input.patientId } : {}), {
595
+ mailboxId: input.mailboxId,
596
+ clientRequestId: input.clientRequestId
597
+ }));
598
+ });
599
+ }
600
+ post(path, body) {
601
+ return __async(this, null, function* () {
602
+ const fail = (rpcCode) => httpError({ status: 0, rpcCode, reason: null, detail: null });
603
+ if (!this.auth.apiKey) {
604
+ throw fail("NO_API_KEY");
605
+ }
606
+ let headers;
607
+ try {
608
+ headers = yield buildAuthHeaders(this.auth, {
609
+ json: true,
610
+ requireUserToken: true
611
+ });
612
+ } catch (e) {
613
+ throw fail("NO_USER_TOKEN");
614
+ }
615
+ const controller = new AbortController();
616
+ const timeout = setTimeout(
617
+ () => controller.abort(),
618
+ _CareInboxResource.REQUEST_TIMEOUT_MS
619
+ );
620
+ let res;
621
+ try {
622
+ res = yield fetch(`${this.baseUrl}/api${path}`, {
623
+ method: "POST",
624
+ headers,
625
+ body: JSON.stringify(body),
626
+ signal: controller.signal
627
+ });
628
+ } catch (err) {
629
+ const isAbort = err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError");
630
+ throw fail(isAbort ? "TIMEOUT" : "TRANSPORT");
631
+ } finally {
632
+ clearTimeout(timeout);
633
+ }
634
+ if (!res.ok) {
635
+ let parsed = {};
636
+ try {
637
+ parsed = yield res.json();
638
+ } catch (e) {
639
+ }
640
+ const data = parsed.data && typeof parsed.data === "object" ? parsed.data : {};
641
+ throw httpError({
642
+ status: res.status,
643
+ rpcCode: typeof parsed.code === "string" ? parsed.code : null,
644
+ reason: asReason(data.reason),
645
+ detail: typeof parsed.message === "string" ? parsed.message.slice(0, 200) : null
646
+ });
647
+ }
648
+ return yield res.json();
649
+ });
650
+ }
651
+ };
652
+ /** 30s upstream timeout — matches ConversationsResource. */
653
+ _CareInboxResource.REQUEST_TIMEOUT_MS = 3e4;
654
+ var CareInboxResource = _CareInboxResource;
655
+
355
656
  // src/resources/conversations.ts
356
657
  var ConversationsError = class extends Error {
357
658
  constructor(operation, status, message) {
@@ -514,6 +815,25 @@ var _ConversationsResource = class _ConversationsResource {
514
815
  );
515
816
  });
516
817
  }
818
+ /**
819
+ * Mark / unmark a conversation Urgent (conversation-level, shared by
820
+ * participants). Refused if `userId` is not a participant.
821
+ */
822
+ setUrgent(input) {
823
+ return __async(this, null, function* () {
824
+ if (!this.convex) {
825
+ throw new ConversationsError(
826
+ "/setUrgent",
827
+ 0,
828
+ "ConversationsResource missing Convex client"
829
+ );
830
+ }
831
+ return yield this.convex.mutation(
832
+ "conversations:setUrgent",
833
+ input
834
+ );
835
+ });
836
+ }
517
837
  /**
518
838
  * Zero unread on every conversation the user has reads for, except
519
839
  * those whose `providerPhone` is in `excludedProviderPhones`.
@@ -1075,6 +1395,11 @@ var _NotesResource = class _NotesResource {
1075
1395
  * physician/practice in Elation, posts the note, and writes an audit
1076
1396
  * row to `elationSyncEvents`. Replaces CommHub's `pushNotesToElation`
1077
1397
  * Hasura action.
1398
+ *
1399
+ * Auth: requires a user token. The server runs this route under
1400
+ * `verifiedUserProcedure`, so the API key alone is rejected with 401 —
1401
+ * configure `getAuthToken` on the client. `input.initiatedBy` is ignored;
1402
+ * the audit row's actor is the verified JWT `sub`.
1078
1403
  */
1079
1404
  pushConversationToElation(input) {
1080
1405
  return __async(this, null, function* () {
@@ -1559,6 +1884,11 @@ import { z } from "zod";
1559
1884
  var memberSchema = z.object({
1560
1885
  elationId: z.string(),
1561
1886
  name: z.string(),
1887
+ // T6: mirrors truth's member-activation-report.ts memberSchema (T5).
1888
+ // Optional/nullable so a comhub build against an older/newer server
1889
+ // payload still parses either way.
1890
+ lastName: z.string().nullable().optional(),
1891
+ firstName: z.string().nullable().optional(),
1562
1892
  doctor: z.string().nullable(),
1563
1893
  status: z.enum(["activated", "outreach", "scheduled", "review", "data"]),
1564
1894
  membershipStart: z.string(),
@@ -2176,6 +2506,11 @@ var TruthClient = class {
2176
2506
  this.convex,
2177
2507
  config.getAuthToken
2178
2508
  );
2509
+ this.careInbox = new CareInboxResource(
2510
+ apiUrl,
2511
+ config.apiKey,
2512
+ config.getAuthToken
2513
+ );
2179
2514
  this.userSettings = new UserSettingsResource(this.convex);
2180
2515
  this._getAuthToken = config.getAuthToken;
2181
2516
  this._serviceWorkerPath = (_h = config.serviceWorkerPath) != null ? _h : "/truth-sw.js";
@@ -2317,6 +2652,103 @@ var TruthClient = class {
2317
2652
  }
2318
2653
  };
2319
2654
 
2655
+ // src/resources/care-inbox-source.ts
2656
+ import { makeFunctionReference as makeFunctionReference2 } from "convex/server";
2657
+ var careInboxRefs = {
2658
+ listThreadsForUser: makeFunctionReference2("careInboxQueries:listThreadsForUser"),
2659
+ getThread: makeFunctionReference2("careInboxQueries:getThread"),
2660
+ listUnlinked: makeFunctionReference2("careInboxQueries:listUnlinked"),
2661
+ unreadEmailCount: makeFunctionReference2("careInboxQueries:unreadEmailCount"),
2662
+ listMailboxesForUser: makeFunctionReference2("careInboxQueries:listMailboxesForUser"),
2663
+ searchPatientsForLink: makeFunctionReference2("careInboxQueries:searchPatientsForLink"),
2664
+ markRead: makeFunctionReference2("careInboxReads:markRead"),
2665
+ openThreadBodies: makeFunctionReference2("careInboxReads:openThreadBodies")
2666
+ };
2667
+ function compactArgs(args) {
2668
+ const out = {};
2669
+ for (const [k, v] of Object.entries(args)) {
2670
+ if (v !== void 0) {
2671
+ out[k] = v;
2672
+ }
2673
+ }
2674
+ return out;
2675
+ }
2676
+ function guarded(run) {
2677
+ return __async(this, null, function* () {
2678
+ try {
2679
+ return yield run();
2680
+ } catch (err) {
2681
+ throw toCareInboxError(err);
2682
+ }
2683
+ });
2684
+ }
2685
+ function createCareInboxSource({
2686
+ convex,
2687
+ careInbox
2688
+ }) {
2689
+ const q = (ref, args) => convex.query(
2690
+ ref,
2691
+ compactArgs(args)
2692
+ );
2693
+ return {
2694
+ listThreads: (args = {}) => guarded(
2695
+ () => __async(null, null, function* () {
2696
+ return toThreadPage(
2697
+ yield q(careInboxRefs.listThreadsForUser, {
2698
+ mailboxId: args.mailboxId,
2699
+ filter: args.filter,
2700
+ cursor: args.cursor,
2701
+ limit: args.limit
2702
+ })
2703
+ );
2704
+ })
2705
+ ),
2706
+ getUnreadCount: (args = {}) => guarded(
2707
+ () => q(careInboxRefs.unreadEmailCount, {
2708
+ mailboxId: args.mailboxId
2709
+ })
2710
+ ),
2711
+ getThread: (threadId) => guarded(() => __async(null, null, function* () {
2712
+ const detail = yield q(
2713
+ careInboxRefs.getThread,
2714
+ { threadId }
2715
+ );
2716
+ if (!detail) {
2717
+ throw new CareInboxError("unavailable");
2718
+ }
2719
+ return toEmailThreadDetail(detail);
2720
+ })),
2721
+ listMailboxesForUser: () => guarded(
2722
+ () => __async(null, null, function* () {
2723
+ return toMailboxAccess(
2724
+ yield q(
2725
+ careInboxRefs.listMailboxesForUser,
2726
+ {}
2727
+ )
2728
+ );
2729
+ })
2730
+ ),
2731
+ searchPatientsForLink: (query) => guarded(
2732
+ () => q(careInboxRefs.searchPatientsForLink, {
2733
+ q: query
2734
+ })
2735
+ ),
2736
+ linkMessage: (args) => guarded(() => careInbox.linkMessage(args)),
2737
+ unlinkMessage: (args) => guarded(() => careInbox.unlinkMessage(args)),
2738
+ sendReply: (args) => guarded(() => careInbox.replyToThread(args)),
2739
+ sendEmail: (args) => guarded(() => careInbox.composeEmail(args)),
2740
+ markRead: ({ threadId }) => guarded(
2741
+ () => __async(null, null, function* () {
2742
+ return toMarkReadResult(
2743
+ yield convex.mutation(careInboxRefs.markRead, {
2744
+ threadId
2745
+ })
2746
+ );
2747
+ })
2748
+ )
2749
+ };
2750
+ }
2751
+
2320
2752
  // src/tracking/events.ts
2321
2753
  var CONVERSATION_EVENTS = {
2322
2754
  created: "conversation.created.v1",
@@ -2390,6 +2822,8 @@ export {
2390
2822
  AttachmentsResource,
2391
2823
  CALL_EVENTS,
2392
2824
  CONVERSATION_EVENTS,
2825
+ CareInboxError,
2826
+ CareInboxResource,
2393
2827
  ConversationsError,
2394
2828
  ConversationsResource,
2395
2829
  DialpadProxyError,
@@ -2423,11 +2857,24 @@ export {
2423
2857
  TranslationResource,
2424
2858
  TruthClient,
2425
2859
  UserSettingsResource,
2860
+ careInboxErrorInfo,
2861
+ careInboxRefs,
2862
+ createCareInboxSource,
2426
2863
  generateUuidV7,
2864
+ isCareInboxError,
2427
2865
  isWebPushSupported,
2428
2866
  onServiceWorkerMessage,
2429
2867
  registerServiceWorker,
2430
2868
  subscribeToPush,
2431
- subscriptionToJSON
2869
+ subscriptionToJSON,
2870
+ toCareInboxError,
2871
+ toEmailMailbox,
2872
+ toEmailMessage,
2873
+ toEmailThreadDetail,
2874
+ toEmailThreadSummary,
2875
+ toMailboxAccess,
2876
+ toMarkReadResult,
2877
+ toThreadPage,
2878
+ toUnlinkedMessagePage
2432
2879
  };
2433
2880
  //# sourceMappingURL=index.mjs.map