@esushealth/sdk 0.1.0 → 1.0.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/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # Esus SDK for TypeScript
2
2
 
3
- Server integrations and app user sessions for Esus Health. This is a public beta.
3
+ Server integrations and app user sessions for Esus Health.
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```sh
8
- npm install @esushealth/sdk@beta
8
+ npm install @esushealth/sdk
9
9
  ```
10
10
 
11
11
  Requires Node.js 22 or later and ES modules. Keep API keys and session tokens on the server. Start with synthetic data.
@@ -31,7 +31,7 @@ FHIR can read and update the current `Organization`. Create and delete organizat
31
31
 
32
32
  Use `validateConnection({ resources: ["Patient", "Observation"] })` to confirm permissions by resource. The API can still restrict individual records by consent or patient launch context.
33
33
 
34
- Use `fhir.operation` for registered operations such as `fhir.operation("GET /fhir/Patient/:id/$everything", { params: { id } })`. The response includes the status, headers, and body. Bulk export downloads return a readable NDJSON stream. SMART can call `Patient/$everything` with a wildcard read grant. A patient-scoped grant still limits the request to the launch patient.
34
+ Use `fhir.operation` for registered operations such as `fhir.operation("GET /fhir/Patient/:id/$everything", { params: { id } })`. The response includes the status, headers, and body. Bulk export downloads return a readable NDJSON stream. Pass an abort signal to cancel the download while reading it. SMART can call `Patient/$everything` with a wildcard read grant. A patient-scoped grant still limits the request to the launch patient.
35
35
 
36
36
  Esus bulk exports contain FHIR resources in NDJSON and require dedicated export permissions. The kickoff returns a `Content-Location` header. Extract the job ID and pass it to the SDK's status and download operations. Both kickoff routes export within the organization. The `patient` filter is currently unsupported.
37
37
 
@@ -69,7 +69,7 @@ The same client handles account email. Use `signUp` to create an app user and ch
69
69
 
70
70
  Use `verifyInvitation(inviteToken)` to validate an invitation for this app before rendering the signup form. Pass the same token to `signUp` with the invited email and password.
71
71
 
72
- For Google sign-in, enable Google for the tenant app and add your app's callback to its redirect allowlist. Redirect the browser to `app.googleSignInUrl(callbackUrl)`. In the callback, pass the returned code to `app.exchangeGoogleCode(code)` on your server. Handle the resulting session or MFA challenge the same way as password sign-in.
72
+ For Google sign-in, enable Google for the tenant app and add your app's callback to its redirect allowlist. Redirect the browser to `app.googleSignInUrl(callbackUrl)`. In the callback, pass the returned code to `app.exchangeGoogleCode(code)` on your server. Esus binds the code to the app that issued it and accepts it once. Handle the resulting session or MFA challenge the same way as password sign-in.
73
73
 
74
74
  Use the app user's access token with `listSessions`, `revokeSession`, and `revokeAllSessions` to manage active devices. The account methods also support profile updates, password changes, and deletion with the proof required by Esus.
75
75
 
@@ -97,10 +97,13 @@ Authorize the action in your application, then use a server API key with `File.c
97
97
  ```ts
98
98
  const uploaded = await esus.files.upload(file);
99
99
  const { body, headers } = await esus.files.download(uploaded.id);
100
- return new Response(body, { headers });
100
+ return new Response(body, { headers: {
101
+ "content-type": headers.get("content-type")!,
102
+ "content-disposition": headers.get("content-disposition")!,
103
+ } });
101
104
  ```
102
105
 
103
- Store the returned file ID for downloads and deletion. The download uses a stream and carries the API's attachment headers.
106
+ Store the returned file ID for downloads and deletion. The download uses a stream and carries the API's attachment headers. The request timeout covers the wait for response headers. Pass an abort signal to cancel the download after it starts.
104
107
 
105
108
  ## Queue and pharmacy
106
109
 
package/dist/fhir.js CHANGED
@@ -13,23 +13,25 @@ function invalidResponse(response, message) {
13
13
  }
14
14
  export function readResource(expected, body, response) {
15
15
  const resource = record(body);
16
- if (resource?.resourceType !== expected || typeof resource.id !== "string") {
17
- return invalidResponse(response, `Esus did not return a ${expected} resource`);
16
+ if (resource?.resourceType !== expected || !validSegment(resource.id)) {
17
+ return invalidResponse(response, `Esus returned an invalid ${expected} resource`);
18
18
  }
19
19
  return resource;
20
20
  }
21
21
  export function validSegment(value) {
22
22
  return typeof value === "string" && /^[A-Za-z0-9.-]{1,64}$/.test(value) && value !== "." && value !== "..";
23
23
  }
24
- function resourcePath(resource, id) {
24
+ function collectionPath(resource) {
25
25
  if (!isFhirResource(resource))
26
26
  throw new TypeError("This SDK only supports resources in the Esus FHIR catalog");
27
- if (id === undefined)
28
- return `/fhir/${resource}`;
27
+ return `/fhir/${resource}`;
28
+ }
29
+ function resourcePath(resource, id) {
30
+ const path = collectionPath(resource);
29
31
  if (!validSegment(id)) {
30
32
  throw new TypeError(`Invalid ${resource} id`);
31
33
  }
32
- return `/fhir/${resource}/${id}`;
34
+ return `${path}/${id}`;
33
35
  }
34
36
  const operationNames = Object.keys(fhirOperations);
35
37
  export function fhirOperation(request, allowed) {
@@ -73,8 +75,11 @@ function readBundle(body, response, type) {
73
75
  if (bundle?.resourceType !== "Bundle" || bundle.type !== type) {
74
76
  return invalidResponse(response, `Esus did not return a ${type} bundle`);
75
77
  }
78
+ if (bundle.entry !== undefined && !Array.isArray(bundle.entry)) {
79
+ return invalidResponse(response, "Esus returned invalid bundle entries");
80
+ }
76
81
  return {
77
- entries: Array.isArray(bundle.entry) ? bundle.entry : [],
82
+ entries: (bundle.entry ?? []),
78
83
  total: typeof bundle.total === "number" ? bundle.total : undefined,
79
84
  };
80
85
  }
@@ -91,7 +96,7 @@ export function readSearchResult(resource, body, response) {
91
96
  }
92
97
  export function readFhir(request) {
93
98
  async function search(resource, filters, options = {}) {
94
- const { body, response } = await request(queryPath(resourcePath(resource), filters ?? {}), options);
99
+ const { body, response } = await request(queryPath(collectionPath(resource), filters ?? {}), options);
95
100
  return readSearchResult(resource, body, response);
96
101
  }
97
102
  async function read(resource, id, options = {}) {
@@ -137,7 +142,7 @@ export function writeFhir(request) {
137
142
  create(resource, input, options = {}) {
138
143
  if (!supportsFhirLifecycle(resource, "create"))
139
144
  throw new TypeError(`FHIR create is unavailable for ${resource}`);
140
- return write(resource, resourcePath(resource), {
145
+ return write(resource, collectionPath(resource), {
141
146
  ...options, method: "POST", headers: { "content-type": json }, body: JSON.stringify(input),
142
147
  });
143
148
  },
package/dist/transport.js CHANGED
@@ -52,6 +52,9 @@ export function createTransport(options, credential) {
52
52
  const origin = integrationOrigin(options.url);
53
53
  const fetch = options.fetch ?? globalThis.fetch;
54
54
  const timeoutMs = options.timeoutMs ?? 15_000;
55
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647) {
56
+ throw new RangeError("Esus request timeout must be between 1 and 2147483647 milliseconds");
57
+ }
55
58
  const organizationId = options.organizationId;
56
59
  return async (path, { responseMode = "json", acceptStatus, ...init } = {}) => {
57
60
  const url = new URL(path, origin);
@@ -65,44 +68,53 @@ export function createTransport(options, credential) {
65
68
  headers.set("accept", accept);
66
69
  if (organizationId !== undefined)
67
70
  headers.set("x-esus-expected-organization", organizationId);
68
- const timeout = AbortSignal.timeout(timeoutMs);
69
- let response;
71
+ const streaming = responseMode === "stream" || responseMode === "binary";
72
+ const deadline = streaming ? new AbortController() : undefined;
73
+ const timer = deadline && setTimeout(() => deadline.abort(new DOMException("Esus request timed out", "TimeoutError")), timeoutMs);
74
+ const timeout = deadline?.signal ?? AbortSignal.timeout(timeoutMs);
70
75
  try {
71
- response = await fetch(url, {
72
- ...init,
73
- headers,
74
- cache: "no-store",
75
- redirect: "error",
76
- signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
77
- });
78
- }
79
- catch (cause) {
80
- throw new EsusError("Esus request could not be completed", 0, null, null, null, { cause });
81
- }
82
- const requestId = response.headers.get("x-request-id");
83
- const retryAfter = response.headers.get("retry-after");
84
- if (!response.ok && response.status !== acceptStatus) {
85
- const body = await response.json().catch(() => null);
86
- const outcome = readOutcome(body);
87
- const error = record(body)?.error;
88
- throw new EsusError(`Esus returned HTTP ${response.status}`, response.status, requestId, outcome, retryAfter, undefined, typeof error === "string" ? error : null);
89
- }
90
- if (response.status === 204 || responseMode === "empty")
91
- return { body: undefined, response };
92
- if (responseMode === "binary")
93
- return { body: response.body, response };
94
- if (responseMode === "stream") {
95
- if (response.headers.get("content-type")?.split(";")[0]?.trim() !== "application/fhir+ndjson" || !response.body) {
96
- throw new EsusError("Esus did not return an NDJSON stream", response.status, requestId);
76
+ let response;
77
+ try {
78
+ response = await fetch(url, {
79
+ ...init,
80
+ headers,
81
+ cache: "no-store",
82
+ redirect: "error",
83
+ signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout,
84
+ });
85
+ }
86
+ catch (cause) {
87
+ throw new EsusError("Esus request could not be completed", 0, null, null, null, { cause });
88
+ }
89
+ const requestId = response.headers.get("x-request-id");
90
+ const retryAfter = response.headers.get("retry-after");
91
+ if (!response.ok && response.status !== acceptStatus) {
92
+ const body = await response.json().catch(() => null);
93
+ const outcome = readOutcome(body);
94
+ const error = record(body)?.error;
95
+ throw new EsusError(`Esus returned HTTP ${response.status}`, response.status, requestId, outcome, retryAfter, undefined, typeof error === "string" ? error : null);
96
+ }
97
+ if (response.status === 204 || responseMode === "empty")
98
+ return { body: undefined, response };
99
+ if (responseMode === "binary")
100
+ return { body: response.body, response };
101
+ if (responseMode === "stream") {
102
+ if (response.headers.get("content-type")?.split(";")[0]?.trim() !== "application/fhir+ndjson" || !response.body) {
103
+ void response.body?.cancel().catch(() => { });
104
+ throw new EsusError("Esus did not return an NDJSON stream", response.status, requestId);
105
+ }
106
+ return { body: response.body, response };
107
+ }
108
+ try {
109
+ const body = await response.json();
110
+ return { body, response };
111
+ }
112
+ catch (cause) {
113
+ throw new EsusError("Esus returned an invalid JSON response", response.status, requestId, null, null, { cause });
97
114
  }
98
- return { body: response.body, response };
99
- }
100
- try {
101
- const body = await response.json();
102
- return { body, response };
103
115
  }
104
- catch (cause) {
105
- throw new EsusError("Esus returned an invalid JSON response", response.status, requestId, null, null, { cause });
116
+ finally {
117
+ clearTimeout(timer);
106
118
  }
107
119
  };
108
120
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esushealth/sdk",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "TypeScript server SDK for Esus Health integrations and app sessions.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://esus.health",
@@ -8,7 +8,7 @@
8
8
  "engines": { "node": ">=22" },
9
9
  "scripts": { "prepack": "tsc -b --force" },
10
10
  "files": ["dist/*.js", "dist/*.d.ts"],
11
- "publishConfig": { "access": "public", "tag": "beta", "registry": "https://registry.npmjs.org/" },
11
+ "publishConfig": { "access": "public", "tag": "latest", "registry": "https://registry.npmjs.org/" },
12
12
  "typesVersions": { "*": { "server": ["dist/server.d.ts"] } },
13
13
  "exports": {
14
14
  "./server": {