esigncomply 0.0.0-stage → 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/dist/index.js ADDED
@@ -0,0 +1,825 @@
1
+ // packages/esigncomply/src/errors.ts
2
+ function ok(data) {
3
+ return { data, error: null };
4
+ }
5
+ function fail(error) {
6
+ return { data: null, error };
7
+ }
8
+ var STATUS_DEFAULTS = {
9
+ 400: ["invalid_request_error", "invalid_request"],
10
+ 401: ["authentication_error", "invalid_api_key"],
11
+ 402: ["quota_error", "quota_exceeded"],
12
+ 403: ["permission_error", "insufficient_permission"],
13
+ 404: ["invalid_request_error", "not_found"],
14
+ 409: ["conflict_error", "idempotency_conflict"],
15
+ 421: ["invalid_request_error", "region_mismatch"],
16
+ 422: ["invalid_request_error", "invalid_request"],
17
+ 429: ["rate_limit_error", "rate_limit_exceeded"],
18
+ 500: ["api_error", "internal_error"],
19
+ 503: ["api_error", "service_unavailable"]
20
+ };
21
+ function isObject(v) {
22
+ return typeof v === "object" && v !== null && !Array.isArray(v);
23
+ }
24
+ function errorFromResponse(status, body, headers) {
25
+ const fallback = STATUS_DEFAULTS[status] ?? (status >= 500 ? STATUS_DEFAULTS[500] : STATUS_DEFAULTS[400]);
26
+ const envelope = isObject(body) && isObject(body.error) ? body.error : null;
27
+ const error = envelope ? {
28
+ ...envelope,
29
+ type: typeof envelope.type === "string" ? envelope.type : fallback[0],
30
+ code: typeof envelope.code === "string" ? envelope.code : fallback[1],
31
+ message: typeof envelope.message === "string" ? envelope.message : `The API answered ${status}.`,
32
+ status
33
+ } : {
34
+ type: fallback[0],
35
+ code: fallback[1],
36
+ message: `The API answered ${status} without an error body. ${status === 404 ? "This endpoint may not exist on the server you are calling." : "This usually comes from a proxy in front of the API."}`,
37
+ status
38
+ };
39
+ if (error.request_id === void 0 && headers.requestId) error.request_id = headers.requestId;
40
+ if (headers.retryAfter !== null) error.retry_after = headers.retryAfter;
41
+ return error;
42
+ }
43
+ function networkError(err, context) {
44
+ const cause = err instanceof Error ? err.message : String(err);
45
+ const nested = err instanceof Error && err.cause instanceof Error ? ` (${err.cause.message})` : "";
46
+ return { type: "api_error", code: "network_error", message: `${context}: ${cause}${nested}`, status: 0 };
47
+ }
48
+
49
+ // packages/esigncomply/src/version.ts
50
+ var VERSION = "1.0.0";
51
+
52
+ // packages/esigncomply/src/client.ts
53
+ var US_BASE = "https://esigncomply.com/v1";
54
+ var MAX_RETRY_WAIT_MS = 6e4;
55
+ function baseUrlForKey(apiKey) {
56
+ const region = /^esc_(?:test|live)_([a-z]{2})_/.exec(apiKey)?.[1];
57
+ return region && region !== "us" ? `https://api.${region}.esigncomply.com/v1` : US_BASE;
58
+ }
59
+ function normalizeBaseUrl(url) {
60
+ const trimmed = url.trim().replace(/\/+$/, "");
61
+ try {
62
+ if (new URL(trimmed).pathname === "/") return `${trimmed}/v1`;
63
+ } catch {
64
+ }
65
+ return trimmed;
66
+ }
67
+ function retryAfterSeconds(res) {
68
+ const header2 = res.headers.get("retry-after");
69
+ if (!header2) return null;
70
+ const seconds = Number(header2);
71
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds;
72
+ const date = Date.parse(header2);
73
+ return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - Date.now()) / 1e3));
74
+ }
75
+ function backoffMs(attempt) {
76
+ const base = Math.min(8e3, 500 * 2 ** attempt);
77
+ return Math.round(base * (0.75 + Math.random() * 0.5));
78
+ }
79
+ function filename(res) {
80
+ const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(res.headers.get("content-disposition") ?? "");
81
+ return m ? decodeURIComponent(m[1]) : void 0;
82
+ }
83
+ var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
84
+ var HttpClient = class {
85
+ baseUrl;
86
+ apiKey;
87
+ apiVersion;
88
+ fetchImpl;
89
+ maxRetries;
90
+ timeoutMs;
91
+ sleep;
92
+ constructor(apiKey, options = {}) {
93
+ this.apiKey = (apiKey ?? process.env.ESIGNCOMPLY_API_KEY ?? "").trim();
94
+ this.baseUrl = normalizeBaseUrl(options.baseUrl || process.env.ESIGNCOMPLY_API_URL || baseUrlForKey(this.apiKey));
95
+ this.apiVersion = options.apiVersion;
96
+ this.fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
97
+ this.maxRetries = Number.isInteger(options.maxRetries) && options.maxRetries >= 0 ? options.maxRetries : 2;
98
+ this.timeoutMs = options.timeoutMs ?? 6e4;
99
+ this.sleep = options.sleep ?? defaultSleep;
100
+ }
101
+ /** A JSON request. */
102
+ request(req) {
103
+ return this.send(req, "json");
104
+ }
105
+ /** A request whose successful response is a file. */
106
+ requestBinary(req) {
107
+ return this.send(req, "binary");
108
+ }
109
+ /** A request that may answer with JSON or with a file, depending on the content type. */
110
+ requestEither(req) {
111
+ return this.send(req, "either");
112
+ }
113
+ /** Fetch a URL outside the API (a signed download or upload URL). The API key is never sent. */
114
+ async external(url, init, context) {
115
+ if (!this.fetchImpl) return fail(networkError(new Error("no fetch implementation is available"), context));
116
+ try {
117
+ const res = await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
118
+ if (res.ok) return ok(res);
119
+ const text = await res.text().catch(() => "");
120
+ return fail({ type: "api_error", code: "service_unavailable", message: `${context}: the storage service answered ${res.status}. ${text.slice(0, 200)}`.trim(), status: res.status });
121
+ } catch (err) {
122
+ return fail(networkError(err, context));
123
+ }
124
+ }
125
+ async send(req, expect) {
126
+ try {
127
+ return await this.attempt(req, expect);
128
+ } catch (err) {
129
+ return fail(networkError(err, `${req.method} ${req.path}`));
130
+ }
131
+ }
132
+ async attempt(req, expect) {
133
+ const token = req.token ?? this.apiKey;
134
+ if (!token) {
135
+ return fail({
136
+ type: "authentication_error",
137
+ code: "missing_api_key",
138
+ message: "No API key. Pass it to new EsignComply(key) or set ESIGNCOMPLY_API_KEY. Keys are secret and belong on your server.",
139
+ status: 0
140
+ });
141
+ }
142
+ if (!this.fetchImpl) return fail(networkError(new Error("no fetch implementation is available; use Node 20 or later, or pass { fetch }"), `${req.method} ${req.path}`));
143
+ let url;
144
+ try {
145
+ const u = new URL(this.baseUrl + (req.path.startsWith("/") ? req.path : `/${req.path}`));
146
+ for (const [key, value] of Object.entries(req.query ?? {})) {
147
+ if (value === void 0 || value === null) continue;
148
+ if (Array.isArray(value)) for (const v of value) u.searchParams.append(key, String(v));
149
+ else u.searchParams.set(key, String(value));
150
+ }
151
+ url = u.toString();
152
+ } catch {
153
+ return fail({ type: "invalid_request_error", code: "invalid_request", message: `The API base URL "${this.baseUrl}" is not a valid URL.`, param: "baseUrl", status: 0 });
154
+ }
155
+ const headers = {
156
+ Authorization: `Bearer ${token}`,
157
+ Accept: expect === "json" ? "application/json" : "*/*",
158
+ "X-Esc-Sdk": `node/${VERSION}`,
159
+ "User-Agent": `esigncomply-node/${VERSION}`
160
+ };
161
+ const version = req.options?.apiVersion ?? this.apiVersion;
162
+ if (version) headers["Esign-Comply-Version"] = version;
163
+ const idempotencyKey = req.options?.idempotencyKey;
164
+ if (idempotencyKey && req.method === "POST") headers["Idempotency-Key"] = idempotencyKey;
165
+ let body;
166
+ if (req.body !== void 0 && req.method !== "GET") {
167
+ body = JSON.stringify(req.body);
168
+ headers["Content-Type"] = "application/json";
169
+ }
170
+ const repeatable = req.method === "GET" || req.method === "POST" && !!idempotencyKey;
171
+ const context = `${req.method} ${req.path}`;
172
+ for (let attempt = 0; ; attempt++) {
173
+ const canRetry = attempt < this.maxRetries;
174
+ let res;
175
+ try {
176
+ const timeout = AbortSignal.timeout(this.timeoutMs);
177
+ const signal = req.options?.signal ? AbortSignal.any([req.options.signal, timeout]) : timeout;
178
+ res = await this.fetchImpl(url, { method: req.method, headers, body, signal });
179
+ } catch (err) {
180
+ if (repeatable && canRetry && !req.options?.signal?.aborted) {
181
+ await this.sleep(backoffMs(attempt));
182
+ continue;
183
+ }
184
+ return fail(networkError(err, context));
185
+ }
186
+ const retryAfter = retryAfterSeconds(res);
187
+ if (canRetry && (res.status === 429 || res.status >= 500 && repeatable)) {
188
+ const wait = retryAfter !== null ? retryAfter * 1e3 : backoffMs(attempt);
189
+ if (wait <= MAX_RETRY_WAIT_MS) {
190
+ await res.arrayBuffer().catch(() => void 0);
191
+ await this.sleep(wait);
192
+ continue;
193
+ }
194
+ }
195
+ return this.read(res, expect, retryAfter, context);
196
+ }
197
+ }
198
+ async read(res, expect, retryAfter, context) {
199
+ const requestId = res.headers.get("x-request-id");
200
+ const contentType = res.headers.get("content-type") ?? "";
201
+ const isJson = /\bjson\b/i.test(contentType);
202
+ try {
203
+ if (res.status >= 200 && res.status < 300) {
204
+ if (expect === "binary" || expect === "either" && !isJson) {
205
+ const bytes = new Uint8Array(await res.arrayBuffer());
206
+ const name = filename(res);
207
+ return ok({ bytes, contentType: contentType || "application/octet-stream", ...name ? { filename: name } : {} });
208
+ }
209
+ const text2 = await res.text();
210
+ if (text2.trim() === "") return ok({});
211
+ try {
212
+ return ok(JSON.parse(text2));
213
+ } catch {
214
+ return fail({ type: "api_error", code: "invalid_response", message: `${context}: the API answered ${res.status} with a body that is not JSON.`, status: res.status, ...requestId ? { request_id: requestId } : {} });
215
+ }
216
+ }
217
+ const text = await res.text();
218
+ let parsed;
219
+ try {
220
+ parsed = JSON.parse(text);
221
+ } catch {
222
+ parsed = void 0;
223
+ }
224
+ return fail(errorFromResponse(res.status, parsed, { requestId, retryAfter }));
225
+ } catch (err) {
226
+ const error = networkError(err, `${context}: the response could not be read`);
227
+ return fail({ ...error, status: res.status, ...requestId ? { request_id: requestId } : {} });
228
+ }
229
+ }
230
+ };
231
+
232
+ // packages/esigncomply/src/resources/base.ts
233
+ var Resource = class {
234
+ /** @internal */
235
+ constructor(client) {
236
+ this.client = client;
237
+ }
238
+ client;
239
+ /** @internal */
240
+ _get(path2, query, options) {
241
+ return this.client.request({ method: "GET", path: path2, query, options });
242
+ }
243
+ /** @internal */
244
+ _post(path2, body, options) {
245
+ return this.client.request({ method: "POST", path: path2, body: body ?? {}, options });
246
+ }
247
+ /** @internal */
248
+ _send(method, path2, body, options) {
249
+ return this.client.request({ method, path: path2, body, options });
250
+ }
251
+ };
252
+ function path(strings, ...ids) {
253
+ return strings.reduce((out, s, i) => out + s + (i < ids.length ? encodeURIComponent(String(ids[i])) : ""), "");
254
+ }
255
+
256
+ // packages/esigncomply/src/resources/account.ts
257
+ var UsageResource = class extends Resource {
258
+ /** Events used in the subscription year, quota, period end; certificate allowance and spend; supplement storage. */
259
+ get() {
260
+ return this._get("/usage");
261
+ }
262
+ };
263
+ var Conformance = class extends Resource {
264
+ /** Run the conformance checker over recent test records (12.6). Findings are advisory statements about measurable design facts. */
265
+ run(body = {}, options) {
266
+ return this._post("/conformance/runs", body, options);
267
+ }
268
+ get(id) {
269
+ return this._get(path`/conformance/runs/${id}`);
270
+ }
271
+ };
272
+ var Prompts = class extends Resource {
273
+ /**
274
+ * Generate the integration prompt for an AI coding tool from wizard selections (section 12).
275
+ * Creates or reuses the ceremony profiles the prompt names and stores the prompt. Needs a `full_access` key.
276
+ */
277
+ generate(body = {}, options) {
278
+ return this._post("/prompts/generate", body, options);
279
+ }
280
+ /** Prompts generated for this domain and environment, newest first. List items leave out the Markdown: read one prompt for its text. */
281
+ list(params = {}) {
282
+ return this._get("/prompts", params);
283
+ }
284
+ /** One stored prompt with its Markdown. Prompt IDs resolve permanently (BC-15). */
285
+ get(id) {
286
+ return this._get(path`/prompts/${id}`);
287
+ }
288
+ };
289
+ var Domains = class extends Resource {
290
+ create(body, options) {
291
+ return this._post("/domains", body, options);
292
+ }
293
+ get(id) {
294
+ return this._get(path`/domains/${id}`);
295
+ }
296
+ /** Trigger verification of the domain. */
297
+ verify(id) {
298
+ return this._post(path`/domains/${id}/verify`);
299
+ }
300
+ /** Change domain settings, for example `certificate_spend_limit` (OC-16). */
301
+ update(id, body) {
302
+ return this._send("PATCH", path`/domains/${id}`, body);
303
+ }
304
+ /** Watch jurisdiction codes without enabling their packs, to receive their notices (GD-14). Replaces the whole list and resolves to it. */
305
+ watchJurisdictions(id, jurisdictions) {
306
+ return this._send("PUT", path`/domains/${id}/watched-jurisdictions`, { jurisdictions });
307
+ }
308
+ };
309
+ var ApiKeys = class extends Resource {
310
+ /** Create a key. The full key is in the response once; only a prefix and a hash are stored. */
311
+ create(body, options) {
312
+ return this._post("/api-keys", body, options);
313
+ }
314
+ list() {
315
+ return this._get("/api-keys");
316
+ }
317
+ delete(id) {
318
+ return this._send("DELETE", path`/api-keys/${id}`);
319
+ }
320
+ };
321
+
322
+ // packages/esigncomply/src/resources/certificates.ts
323
+ var Certificates = class extends Resource {
324
+ /** Issue one certificate over a set of records selected by filter. Asynchronous: answers `processing`, then `certificate.issued` fires. */
325
+ create(body, options) {
326
+ return this._post("/certificates", body, options);
327
+ }
328
+ /** What a certificate request would cost. Issues nothing and charges nothing (OC-13). */
329
+ quote(body) {
330
+ return this._post("/certificates/quote", body);
331
+ }
332
+ list(filters = {}) {
333
+ return this._get("/certificates", filters);
334
+ }
335
+ get(id) {
336
+ return this._get(path`/certificates/${id}`);
337
+ }
338
+ /** The certificate as a PDF. */
339
+ pdf(id) {
340
+ return this.client.requestBinary({ method: "GET", path: path`/certificates/${id}/pdf` });
341
+ }
342
+ /** Create a time-limited share link that opens the certificate and runs verification without an account (OC-8). */
343
+ share(id, body, options) {
344
+ return this._post(path`/certificates/${id}/share`, body, options);
345
+ }
346
+ revokeShare(id) {
347
+ return this._send("DELETE", path`/certificates/${id}/share`);
348
+ }
349
+ };
350
+
351
+ // packages/esigncomply/src/resources/documents.ts
352
+ var DocumentVersions = class extends Resource {
353
+ /** Publish an immutable version: text or file, language, version label, effective date. Returns the content hash. */
354
+ create(documentId, body, options) {
355
+ return this._post(path`/documents/${documentId}/versions`, body, options);
356
+ }
357
+ list(documentId) {
358
+ return this._get(path`/documents/${documentId}/versions`);
359
+ }
360
+ get(documentId, versionId) {
361
+ return this._get(path`/documents/${documentId}/versions/${versionId}`);
362
+ }
363
+ /** The canonical content to render. `"current"` picks the version in force, by `locale` when translations exist. */
364
+ getContent(documentId, versionId, params = {}) {
365
+ return this._get(path`/documents/${documentId}/versions/${versionId}/content`, params);
366
+ }
367
+ };
368
+ var Documents = class extends Resource {
369
+ versions = new DocumentVersions(this.client);
370
+ create(body, options) {
371
+ return this._post("/documents", body, options);
372
+ }
373
+ list(params = {}) {
374
+ return this._get("/documents", params);
375
+ }
376
+ get(id) {
377
+ return this._get(path`/documents/${id}`);
378
+ }
379
+ };
380
+
381
+ // packages/esigncomply/src/resources/guidance.ts
382
+ var GuidanceNotices = class extends Resource {
383
+ /** Notices that reach this domain. Filters: jurisdiction, class, severity, kind, topic, since, affecting_profile. */
384
+ list(filters = {}) {
385
+ return this._get("/guidance/notices", filters);
386
+ }
387
+ get(id) {
388
+ return this._get(path`/guidance/notices/${id}`);
389
+ }
390
+ /** Mark a notice `read`, `applied` or `not_applicable`. Acknowledgment never gates recording (GD-10). */
391
+ acknowledge(id, body, options) {
392
+ return this._post(path`/guidance/notices/${id}/acknowledge`, body, options);
393
+ }
394
+ };
395
+ var GuidanceReleases = class extends Resource {
396
+ list(params = {}) {
397
+ return this._get("/guidance/releases", params);
398
+ }
399
+ /** One release with its changelog: items added, changed, retired. */
400
+ get(id) {
401
+ return this._get(path`/guidance/releases/${id}`);
402
+ }
403
+ };
404
+ var GuidanceUpdates = class extends Resource {
405
+ /** An update prompt: a short reviewed block that describes one change, to hand to a coding tool (GD-9). */
406
+ async get(id) {
407
+ const res = await this.client.requestEither({ method: "GET", path: path`/guidance/updates/${id}` });
408
+ if (res.error) return res;
409
+ if ("bytes" in res.data && res.data.bytes instanceof Uint8Array) {
410
+ return ok({ id, markdown: new TextDecoder().decode(res.data.bytes) });
411
+ }
412
+ return ok(res.data);
413
+ }
414
+ };
415
+ var Guidance = class extends Resource {
416
+ notices = new GuidanceNotices(this.client);
417
+ releases = new GuidanceReleases(this.client);
418
+ updates = new GuidanceUpdates(this.client);
419
+ };
420
+
421
+ // packages/esigncomply/src/resources/jurisdictions.ts
422
+ var Jurisdictions = class extends Resource {
423
+ /** The public catalogue of packs. Read it instead of hard-coding codes, so new packs need no SDK release (JR-1). */
424
+ list(params = {}) {
425
+ return this._get("/jurisdictions", params);
426
+ }
427
+ get(code) {
428
+ return this._get(path`/jurisdictions/${code}`);
429
+ }
430
+ /** Version history and changelog of one pack. */
431
+ versions(code) {
432
+ return this._get(path`/jurisdictions/${code}/versions`);
433
+ }
434
+ /** Dry run: the packs, rules, steps, strings and retention floor a session would get. Creates nothing and is not metered (JR-12). */
435
+ resolve(body) {
436
+ return this._post("/jurisdictions/resolve", body);
437
+ }
438
+ };
439
+
440
+ // packages/esigncomply/src/resources/profiles.ts
441
+ var Profiles = class extends Resource {
442
+ /** Create a ceremony profile: which packs, which method, which assurance level (13.12). */
443
+ create(body, options) {
444
+ return this._post("/profiles", body, options);
445
+ }
446
+ list() {
447
+ return this._get("/profiles");
448
+ }
449
+ get(id) {
450
+ return this._get(path`/profiles/${id}`);
451
+ }
452
+ /** Everything that applies to a profile now: record conditions, obligations, recommendations and reports (13.15). */
453
+ guidance(id) {
454
+ return this._get(path`/profiles/${id}/guidance`);
455
+ }
456
+ /** Move every pending record condition from advise to enforce (BC-6). Creates a new profile version. Body: `note`, optional. */
457
+ adopt(id, body = {}, options) {
458
+ return this._post(path`/profiles/${id}/adopt`, body, options);
459
+ }
460
+ /** Return to the previous baseline, within 90 days of adoption (BC-6). */
461
+ rollback(id, options) {
462
+ return this._post(path`/profiles/${id}/rollback`, {}, options);
463
+ }
464
+ };
465
+
466
+ // packages/esigncomply/src/resources/records.ts
467
+ var Records = class extends Resource {
468
+ /** Search records. Filters: signer, e-mail, document, version, creation time, status. */
469
+ list(filters = {}) {
470
+ return this._get("/records", filters);
471
+ }
472
+ /**
473
+ * Retrieve a record. This is the server-side confirmation of CP-3: before
474
+ * granting access, check that `status` is `recorded`, `timestamped` or
475
+ * `anchored`, that `livemode` is what you expect, and that the signer and
476
+ * the document versions match what your server asked for.
477
+ */
478
+ get(id) {
479
+ return this._get(path`/records/${id}`);
480
+ }
481
+ /** The evidence report as a PDF. */
482
+ report(id) {
483
+ return this.client.requestBinary({ method: "GET", path: path`/records/${id}/report` });
484
+ }
485
+ async evidence(id, options = {}) {
486
+ const query = { ...options.inline ? { inline: "true" } : {}, ...options.supplements === false ? { supplements: "false" } : {} };
487
+ const res = await this.client.requestEither({ method: "GET", path: path`/records/${id}/evidence`, query });
488
+ if (res.error || !options.inline || "bytes" in res.data) return res;
489
+ const link = res.data;
490
+ const download = await this.client.external(link.url, { method: "GET" }, "Evidence package download");
491
+ if (download.error) return fail(download.error);
492
+ try {
493
+ const bytes = new Uint8Array(await download.data.arrayBuffer());
494
+ return ok({ bytes, contentType: download.data.headers.get("content-type") ?? "application/zip", filename: `${link.record_id}.zip` });
495
+ } catch (err) {
496
+ return fail({ type: "api_error", code: "network_error", message: `Evidence package download: ${err instanceof Error ? err.message : String(err)}`, status: 0 });
497
+ }
498
+ }
499
+ /** The signed receipt (JWS): the compact proof you can keep in your own database. */
500
+ receipt(id) {
501
+ return this._get(path`/records/${id}/receipt`);
502
+ }
503
+ /**
504
+ * Add a later fact: `superseded`, `legal_hold`, `legal_hold_released`,
505
+ * `note`, `paper_copy_requested`. Body: `type`, and optionally `data` and a
506
+ * free-text `note`. The earlier report types `notice.sent` and
507
+ * `cancellation.requested` are still accepted here and are stored as
508
+ * supplements (SM-12); new code sends those to `supplements.create`.
509
+ */
510
+ annotate(id, body, options) {
511
+ return this._post(path`/records/${id}/annotations`, body, options);
512
+ }
513
+ /** Issue an on-request certificate for one record (13.13). Needs `confirm_charge: true` when a charge would result. */
514
+ certify(id, body = {}, options) {
515
+ return this._post(path`/records/${id}/certificates`, body, options);
516
+ }
517
+ /** Submit a deferred acceptance under `fail_open_deferred`. The record says it was reported, not observed. */
518
+ submitDeferred(body, options) {
519
+ return this._post("/records/deferred", body, options);
520
+ }
521
+ };
522
+
523
+ // packages/esigncomply/src/resources/sessions.ts
524
+ var Sessions = class extends Resource {
525
+ /**
526
+ * Start a ceremony for one signer and a bundle of document versions (13.4).
527
+ * Hand `client_token` to the browser SDK and read the steps from
528
+ * `required_steps`. Pass an `idempotencyKey` so a retry cannot start two.
529
+ */
530
+ create(body, options) {
531
+ return this._post("/sessions", body, options);
532
+ }
533
+ /** State and remaining steps. `record_id` is set once the ceremony completed. */
534
+ get(id) {
535
+ return this._get(path`/sessions/${id}`);
536
+ }
537
+ cancel(id, options) {
538
+ return this._post(path`/sessions/${id}/cancel`, {}, options);
539
+ }
540
+ };
541
+
542
+ // packages/esigncomply/src/resources/signers.ts
543
+ var Signers = class extends Resource {
544
+ /** All records for one signer. */
545
+ records(externalId, params = {}) {
546
+ return this._get(path`/signers/${externalId}/records`, params);
547
+ }
548
+ /** For each document: the latest version accepted, and whether the current version is outstanding (DV-4). */
549
+ status(externalId) {
550
+ return this._get(path`/signers/${externalId}/status`);
551
+ }
552
+ /** Record that the signer withdrew consent to electronic records. Body: `record_id`, `scope`, `note`, all optional. */
553
+ withdrawConsent(externalId, body = {}, options) {
554
+ return this._post(path`/signers/${externalId}/consents/withdraw`, body, options);
555
+ }
556
+ /** Start a data-subject erasure or restriction workflow (17.3). Body: `scope` (`erasure` by default, or `restriction`) and `basis`. */
557
+ requestErasure(externalId, body = {}, options) {
558
+ return this._post(path`/signers/${externalId}/erasure-requests`, body, options);
559
+ }
560
+ };
561
+
562
+ // packages/esigncomply/src/resources/supplements.ts
563
+ import { createHash } from "node:crypto";
564
+ import { readFile } from "node:fs/promises";
565
+ import { basename } from "node:path";
566
+ function subjectFilter(subject) {
567
+ if (subject === void 0 || typeof subject === "string") return subject;
568
+ const [kind, id] = Object.entries(subject)[0] ?? [];
569
+ if (kind === "domain") return "domain";
570
+ return typeof id === "string" && id ? id : void 0;
571
+ }
572
+ var Supplements = class extends Resource {
573
+ /**
574
+ * Send what you have, in the shape you have it. At least one of `text`,
575
+ * `data` or `files`; nothing else is required. The seal shows that you sent
576
+ * it no later than `received_at`. Esign Comply does not verify its content.
577
+ */
578
+ create(body, options) {
579
+ return this._post("/supplements", body, options);
580
+ }
581
+ list(filters = {}) {
582
+ return this._get("/supplements", { ...filters, subject: subjectFilter(filters.subject) });
583
+ }
584
+ get(id) {
585
+ return this._get(path`/supplements/${id}`);
586
+ }
587
+ /** Text, data and files as stored. */
588
+ content(id) {
589
+ return this._get(path`/supplements/${id}/content`);
590
+ }
591
+ /** Withdraw a supplement (CS-14). It stays listed, marked withdrawn. */
592
+ withdraw(id) {
593
+ return this._send("DELETE", path`/supplements/${id}`);
594
+ }
595
+ /** The public catalogue of recognised types with suggested fields. Any other type is accepted too (SM-3). */
596
+ types() {
597
+ return this._get("/supplement-types");
598
+ }
599
+ };
600
+ var Files = class extends Resource {
601
+ /**
602
+ * Upload a file to attach to a supplement. Performs the three steps of the
603
+ * upload flow (13.14): registers the file with its name, size, type and
604
+ * SHA-256; sends the bytes straight to storage; then reads the file back so
605
+ * `status` reflects what the API saw. A file not referenced by a supplement
606
+ * within 7 days is deleted.
607
+ */
608
+ async upload(pathOrBytes, options = {}) {
609
+ let bytes;
610
+ let name = options.name;
611
+ if (typeof pathOrBytes === "string") {
612
+ try {
613
+ bytes = await readFile(pathOrBytes);
614
+ } catch (err) {
615
+ return fail({ type: "invalid_request_error", code: "invalid_request", message: `Cannot read ${pathOrBytes}: ${err instanceof Error ? err.message : String(err)}`, param: "file", status: 0 });
616
+ }
617
+ name ??= basename(pathOrBytes);
618
+ } else if (pathOrBytes instanceof Uint8Array) {
619
+ bytes = pathOrBytes;
620
+ } else {
621
+ return fail({ type: "invalid_request_error", code: "invalid_request", message: "files.upload takes a file path or the bytes (Uint8Array or Buffer).", param: "file", status: 0 });
622
+ }
623
+ if (!name) return fail({ type: "invalid_request_error", code: "invalid_request", message: "Give the file a name: files.upload(bytes, { name }).", param: "name", status: 0 });
624
+ const contentType = options.contentType ?? "application/octet-stream";
625
+ const created = await this._post("/files", { name, size: bytes.length, content_type: contentType, sha256: "sha256:" + createHash("sha256").update(bytes).digest("hex") });
626
+ if (created.error) return created;
627
+ const file = created.data;
628
+ if (!file.upload_url) {
629
+ return fail({ type: "api_error", code: "invalid_response", message: "The API registered the file but returned no upload_url.", status: 0 });
630
+ }
631
+ const put = await this.client.external(file.upload_url, { method: "PUT", headers: { "Content-Type": contentType }, body: bytes }, `Upload of ${name}`);
632
+ if (put.error) return fail(put.error);
633
+ await put.data.arrayBuffer().catch(() => void 0);
634
+ const stored = await this.get(file.id);
635
+ if (stored.error) return ok({ ...file, upload_url: void 0, resumable_url: void 0 });
636
+ return stored;
637
+ }
638
+ /** Upload status: `stored` once Esign Comply has recomputed the hash, `rejected` on a mismatch. */
639
+ get(id) {
640
+ return this._get(path`/files/${id}`);
641
+ }
642
+ };
643
+
644
+ // packages/esigncomply/src/resources/webhooks.ts
645
+ import { createHmac, timingSafeEqual } from "node:crypto";
646
+ function header(headers, name) {
647
+ if (typeof headers.get === "function") return headers.get(name);
648
+ const record = headers;
649
+ for (const key of Object.keys(record)) {
650
+ if (key.toLowerCase() !== name) continue;
651
+ const value = record[key];
652
+ return Array.isArray(value) ? value[0] ?? null : value ?? null;
653
+ }
654
+ return null;
655
+ }
656
+ var refuse = (code, message) => fail({ type: "invalid_request_error", code, message, status: 0 });
657
+ function secretKey(secret) {
658
+ return Buffer.from(secret.startsWith("whsec_") ? secret.slice(6) : secret, "base64");
659
+ }
660
+ function verifyWebhookSignature(rawBody, headers, secret, options = {}) {
661
+ try {
662
+ if (typeof secret !== "string" || secret.length === 0) return refuse("webhook_signature_invalid", "No webhook secret. Pass the endpoint's whsec_\u2026 secret.");
663
+ if (typeof rawBody !== "string" && !(rawBody instanceof Uint8Array)) {
664
+ return refuse("webhook_payload_invalid", "Pass the raw request body exactly as received (a string or bytes), not a parsed object: the signature covers the bytes.");
665
+ }
666
+ const body = typeof rawBody === "string" ? rawBody : Buffer.from(rawBody).toString("utf8");
667
+ const id = header(headers, "webhook-id");
668
+ const timestamp = header(headers, "webhook-timestamp");
669
+ const signature = header(headers, "webhook-signature");
670
+ if (!id || !timestamp || !signature) {
671
+ return refuse("webhook_signature_missing", "The request lacks webhook-id, webhook-timestamp or webhook-signature. It did not come from Esign Comply, or a proxy removed the headers.");
672
+ }
673
+ const seconds = Number(timestamp);
674
+ const now = (options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3;
675
+ const tolerance = options.toleranceSeconds ?? 300;
676
+ if (!/^\d+$/.test(timestamp) || !Number.isFinite(seconds) || Math.abs(now - seconds) > tolerance) {
677
+ return refuse("webhook_timestamp_out_of_tolerance", `The delivery's timestamp is more than ${tolerance} seconds from now. Old deliveries are refused so a captured request cannot be replayed.`);
678
+ }
679
+ const expected = createHmac("sha256", secretKey(secret)).update(`${id}.${timestamp}.${body}`).digest();
680
+ let matched = false;
681
+ for (const part of signature.split(" ")) {
682
+ const comma = part.indexOf(",");
683
+ if (comma < 0 || part.slice(0, comma) !== "v1") continue;
684
+ const got = Buffer.from(part.slice(comma + 1), "base64");
685
+ if (got.length === expected.length && timingSafeEqual(got, expected)) matched = true;
686
+ }
687
+ if (!matched) return refuse("webhook_signature_invalid", "The signature does not match. Check that the secret belongs to this endpoint and that the body is the raw, unparsed request body.");
688
+ let event;
689
+ try {
690
+ event = JSON.parse(body);
691
+ } catch {
692
+ return refuse("webhook_payload_invalid", "The signature is valid but the body is not JSON.");
693
+ }
694
+ if (typeof event !== "object" || event === null || Array.isArray(event)) return refuse("webhook_payload_invalid", "The signature is valid but the body is not an event object.");
695
+ return ok(event);
696
+ } catch (err) {
697
+ return refuse("webhook_signature_invalid", `The delivery could not be verified: ${err instanceof Error ? err.message : String(err)}`);
698
+ }
699
+ }
700
+ var Webhooks = class extends Resource {
701
+ /**
702
+ * Verify a delivery and return its event. Pass the raw body exactly as
703
+ * received. Deliveries older than 5 minutes are refused (WH-2). Deliveries
704
+ * are at-least-once: make your handler idempotent on `event.id` (WH-4), and
705
+ * ignore event types you do not know (WH-6).
706
+ */
707
+ async verify(rawBody, headers, secret, options) {
708
+ return verifyWebhookSignature(rawBody, headers, secret, options);
709
+ }
710
+ /** Register an endpoint. The response carries the signing `secret` once. */
711
+ create(body, options) {
712
+ return this._post("/webhooks", body, options);
713
+ }
714
+ list() {
715
+ return this._get("/webhooks");
716
+ }
717
+ update(id, body) {
718
+ return this._send("PATCH", path`/webhooks/${id}`, body);
719
+ }
720
+ delete(id) {
721
+ return this._send("DELETE", path`/webhooks/${id}`);
722
+ }
723
+ /**
724
+ * Delivery history with response codes. `since` returns deliveries created
725
+ * after that time, oldest first; `include: "payload"` adds each event.
726
+ * Used by `esigncomply webhooks listen`.
727
+ */
728
+ listDeliveries(params = {}) {
729
+ return this._get("/webhooks/deliveries", params);
730
+ }
731
+ };
732
+
733
+ // packages/esigncomply/src/index.ts
734
+ var EsignComply = class {
735
+ documents;
736
+ profiles;
737
+ jurisdictions;
738
+ sessions;
739
+ records;
740
+ certificates;
741
+ supplements;
742
+ files;
743
+ guidance;
744
+ signers;
745
+ webhooks;
746
+ usage;
747
+ conformance;
748
+ prompts;
749
+ domains;
750
+ apiKeys;
751
+ client;
752
+ /**
753
+ * @param apiKey A secret key (`esc_test_us_…`, `esc_live_eu_…`). Default: the `ESIGNCOMPLY_API_KEY` environment variable.
754
+ * The region code in the key selects the API host.
755
+ */
756
+ constructor(apiKey, options = {}) {
757
+ if (typeof window !== "undefined") {
758
+ throw new Error(
759
+ "The esigncomply server SDK was loaded in a browser. Your secret API key must never reach client code: anyone who opens the page could read it. Create the session on your server with esc.sessions.create() and pass only its client_token to @esigncomply/browser."
760
+ );
761
+ }
762
+ const client = new HttpClient(apiKey, options);
763
+ this.client = client;
764
+ this.documents = new Documents(client);
765
+ this.profiles = new Profiles(client);
766
+ this.jurisdictions = new Jurisdictions(client);
767
+ this.sessions = new Sessions(client);
768
+ this.records = new Records(client);
769
+ this.certificates = new Certificates(client);
770
+ this.supplements = new Supplements(client);
771
+ this.files = new Files(client);
772
+ this.guidance = new Guidance(client);
773
+ this.signers = new Signers(client);
774
+ this.webhooks = new Webhooks(client);
775
+ this.usage = new UsageResource(client);
776
+ this.conformance = new Conformance(client);
777
+ this.prompts = new Prompts(client);
778
+ this.domains = new Domains(client);
779
+ this.apiKeys = new ApiKeys(client);
780
+ }
781
+ /** The API base URL in use, e.g. `https://api.eu.esigncomply.com/v1`. */
782
+ get baseUrl() {
783
+ return this.client.baseUrl;
784
+ }
785
+ /**
786
+ * Ask the API whether a record matches its seal. Pass one of:
787
+ *
788
+ * - the full signed receipt (a compact JWS, three dot-separated parts), sent
789
+ * as `receipt`: anyone holding it may ask;
790
+ * - a record hash (`sha256:…`, or the 64 hexadecimal digits alone), sent as `record_hash`;
791
+ * - a record ID (`rec_…`), sent as `record_id`.
792
+ *
793
+ * A hash or an ID is answered only for a record of the domain and
794
+ * environment of the secret key this client was created with. The answer is
795
+ * proof status only: an ID or hash alone never reveals that a record exists
796
+ * (10.7).
797
+ *
798
+ * To verify without the API at all, use `esigncomply-verify`.
799
+ */
800
+ verify(receiptOrHash) {
801
+ const value = String(receiptOrHash ?? "").trim();
802
+ const isHash = value.startsWith("sha256:") || /^[0-9a-f]{64}$/i.test(value);
803
+ const body = value.split(".").length === 3 ? { receipt: value } : isHash ? { record_hash: value } : { record_id: value };
804
+ return this.client.request({ method: "POST", path: "/verify", body });
805
+ }
806
+ /**
807
+ * Call an endpoint this SDK version has no method for. Same contract as
808
+ * every other method: resolves to `{ data, error }`, never throws.
809
+ *
810
+ * `token` authenticates with a session client token instead of the API key,
811
+ * which is how a server reports the steps of a `server_only` session.
812
+ */
813
+ request(method, path2, params = {}) {
814
+ const { query, body, token, ...options } = params;
815
+ return this.client.request({ method, path: path2, query, body: body ?? (method === "POST" ? {} : void 0), token, options });
816
+ }
817
+ };
818
+ var index_default = EsignComply;
819
+ export {
820
+ EsignComply,
821
+ VERSION,
822
+ baseUrlForKey,
823
+ index_default as default,
824
+ verifyWebhookSignature
825
+ };