@braille-ai/webhook-send 0.0.0-stage → 0.1.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/bin.cjs ADDED
@@ -0,0 +1,383 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // src/bin.ts
5
+ var import_node_fs3 = require("fs");
6
+ var import_node_path2 = require("path");
7
+
8
+ // src/errors.ts
9
+ var WebhookConfigError = class extends Error {
10
+ name = "WebhookConfigError";
11
+ };
12
+ function describe(cause) {
13
+ const error = cause;
14
+ if (error?.name === "TimeoutError") return "no answer within the timeout";
15
+ if (error?.name === "AbortError") return "aborted by the caller";
16
+ return error?.cause?.code ?? error?.cause?.errors?.[0]?.code ?? error?.cause?.message ?? error?.message ?? String(cause);
17
+ }
18
+ var WebhookUnreachableError = class extends Error {
19
+ name = "WebhookUnreachableError";
20
+ eventId;
21
+ url;
22
+ constructor(url, eventId, cause) {
23
+ super(`Could not reach ${url}: ${describe(cause)}`, { cause });
24
+ this.url = url;
25
+ this.eventId = eventId;
26
+ }
27
+ };
28
+
29
+ // src/env.ts
30
+ var import_node_fs = require("fs");
31
+ var ENV = {
32
+ url: "BRAILLE_WEBHOOK_URL",
33
+ secret: "BRAILLE_WEBHOOK_SECRET",
34
+ secretFile: "BRAILLE_WEBHOOK_SECRET_FILE"
35
+ };
36
+ function parseEnvFile(text) {
37
+ const values = {};
38
+ for (const rawLine of text.split(/\r?\n/)) {
39
+ const line = rawLine.trim();
40
+ if (!line || line.startsWith("#")) continue;
41
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
42
+ if (!match) continue;
43
+ const key = match[1];
44
+ let value = (match[2] ?? "").trim();
45
+ const quote = value[0];
46
+ if ((quote === '"' || quote === "'") && value.length >= 2 && value.endsWith(quote)) {
47
+ value = value.slice(1, -1);
48
+ if (quote === '"') value = value.replace(/\\n/g, "\n");
49
+ } else {
50
+ value = value.replace(/\s+#.*$/, "");
51
+ }
52
+ values[key] = value;
53
+ }
54
+ return values;
55
+ }
56
+ function readEnvFile(path) {
57
+ let text;
58
+ try {
59
+ text = (0, import_node_fs.readFileSync)(path, "utf8");
60
+ } catch (error) {
61
+ const code = error.code ?? error.message;
62
+ throw new WebhookConfigError(`Could not read the env file at ${path}: ${code}`);
63
+ }
64
+ return parseEnvFile(text);
65
+ }
66
+ function optionsFromEnv(env = process.env) {
67
+ const url = env[ENV.url]?.trim();
68
+ if (!url) throw new WebhookConfigError(`${ENV.url} is not set. It is the delivery URL Braille printed for the endpoint.`);
69
+ const secretFile = env[ENV.secretFile]?.trim();
70
+ let secret;
71
+ if (secretFile) {
72
+ try {
73
+ secret = (0, import_node_fs.readFileSync)(secretFile, "utf8").trim();
74
+ } catch (error) {
75
+ const code = error.code ?? error.message;
76
+ throw new WebhookConfigError(`Could not read the secret file at ${secretFile}: ${code}`);
77
+ }
78
+ if (!secret) throw new WebhookConfigError(`The secret file at ${secretFile} is empty.`);
79
+ } else {
80
+ secret = env[ENV.secret]?.trim();
81
+ if (!secret) {
82
+ throw new WebhookConfigError(
83
+ `Neither ${ENV.secret} nor ${ENV.secretFile} is set. One of them must hold the endpoint's signing secret.`
84
+ );
85
+ }
86
+ }
87
+ return { url, secret };
88
+ }
89
+
90
+ // src/send.ts
91
+ var import_node_fs2 = require("fs");
92
+ var import_node_path = require("path");
93
+
94
+ // src/sign.ts
95
+ var import_node_crypto = require("crypto");
96
+ var EVENT_ID_HEADER = "Braille-Event-Id";
97
+ var SIGNATURE_HEADER = "Braille-Signature";
98
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
99
+ var ULID = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
100
+ function isEventId(value) {
101
+ return UUID.test(value) || ULID.test(value);
102
+ }
103
+ function newEventId() {
104
+ return (0, import_node_crypto.randomUUID)();
105
+ }
106
+ function unixSeconds(now = /* @__PURE__ */ new Date()) {
107
+ return Math.floor(now.getTime() / 1e3);
108
+ }
109
+ function signedPayload(timestamp, eventId, body) {
110
+ return Buffer.concat([Buffer.from(`${timestamp}.${eventId}.`, "utf8"), Buffer.from(body)]);
111
+ }
112
+ function signatureHeader({ secret, timestamp, eventId, body }) {
113
+ const v1 = (0, import_node_crypto.createHmac)("sha256", secret).update(signedPayload(timestamp, eventId, body)).digest("hex");
114
+ return `t=${timestamp},v1=${v1}`;
115
+ }
116
+
117
+ // src/send.ts
118
+ var CONTENT_TYPES = {
119
+ ".pdf": "application/pdf",
120
+ ".png": "image/png",
121
+ ".jpg": "image/jpeg",
122
+ ".jpeg": "image/jpeg",
123
+ ".gif": "image/gif",
124
+ ".webp": "image/webp",
125
+ ".zip": "application/zip"
126
+ };
127
+ var RESERVED_FIELDS = /* @__PURE__ */ new Set(["surfaceId", "surfaceModality"]);
128
+ var DEFAULT_TIMEOUT_MS = 12e4;
129
+ function fileFromPath(path, options = {}) {
130
+ let data;
131
+ try {
132
+ data = (0, import_node_fs2.readFileSync)(path);
133
+ } catch (error) {
134
+ const code = error.code ?? error.message;
135
+ throw new WebhookConfigError(`Could not read the document at ${path}: ${code}`);
136
+ }
137
+ return { data, filename: (0, import_node_path.basename)(path), ...options };
138
+ }
139
+ function contentTypeFor(file) {
140
+ if (file.contentType) return file.contentType;
141
+ const type = CONTENT_TYPES[(0, import_node_path.extname)(file.filename).toLowerCase()];
142
+ if (!type) {
143
+ throw new WebhookConfigError(
144
+ `${file.filename}: Braille accepts PDF, PNG, JPEG, GIF, WebP and ZIP. Pass contentType to send it anyway.`
145
+ );
146
+ }
147
+ return type;
148
+ }
149
+ function toBlob(file, type) {
150
+ if (file.data instanceof Blob) return file.data.type === type ? file.data : new Blob([file.data], { type });
151
+ return new Blob([file.data], { type });
152
+ }
153
+ async function encode(files) {
154
+ const form = new FormData();
155
+ for (const file of files) {
156
+ const field = file.field ?? "file";
157
+ if (RESERVED_FIELDS.has(field)) {
158
+ throw new WebhookConfigError(`"${field}" is a reserved field name; the endpoint decides the destination.`);
159
+ }
160
+ if (!file.filename) throw new WebhookConfigError("Every file needs a filename.");
161
+ form.append(field, toBlob(file, contentTypeFor(file)), file.filename);
162
+ }
163
+ const encoded = new Response(form);
164
+ const contentType = encoded.headers.get("content-type");
165
+ if (!contentType) throw new WebhookConfigError("The multipart body could not be encoded.");
166
+ return { body: Buffer.from(await encoded.arrayBuffer()), contentType };
167
+ }
168
+ function parseRetryAfter(value) {
169
+ if (!value) return null;
170
+ const seconds = Number(value);
171
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
172
+ }
173
+ function interpret(status, text, eventId, retryAfter) {
174
+ let json = null;
175
+ try {
176
+ const parsed = JSON.parse(text);
177
+ if (parsed && typeof parsed === "object") json = parsed;
178
+ } catch {
179
+ json = null;
180
+ }
181
+ if (status >= 200 && status < 300) {
182
+ const files = Array.isArray(json?.files) ? json.files.flatMap(
183
+ (row) => row && typeof row === "object" ? [
184
+ {
185
+ fileName: String(row.fileName ?? ""),
186
+ disposition: String(row.disposition ?? "")
187
+ }
188
+ ] : []
189
+ ) : [];
190
+ return {
191
+ ok: true,
192
+ status,
193
+ eventId: typeof json?.eventId === "string" ? json.eventId : eventId,
194
+ partial: status === 207,
195
+ workspaceDocumentId: typeof json?.workspaceDocumentId === "string" ? json.workspaceDocumentId : null,
196
+ files
197
+ };
198
+ }
199
+ const code = typeof json?.code === "string" ? json.code : "UNEXPECTED_RESPONSE";
200
+ const message = typeof json?.message === "string" ? json.message : `The endpoint answered ${status} without Braille's JSON body. Check the URL.`;
201
+ return {
202
+ ok: false,
203
+ status,
204
+ eventId,
205
+ code,
206
+ message,
207
+ retryable: status === 429 || status >= 500,
208
+ retryAfterSeconds: parseRetryAfter(retryAfter)
209
+ };
210
+ }
211
+ function createWebhookSender(options) {
212
+ const url = options.url?.trim();
213
+ let parsed;
214
+ try {
215
+ parsed = new URL(url);
216
+ } catch {
217
+ throw new WebhookConfigError(`"${url}" is not a URL. Use the delivery URL Braille printed for the endpoint.`);
218
+ }
219
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
220
+ throw new WebhookConfigError(`The delivery URL must be http or https, not ${parsed.protocol}`);
221
+ }
222
+ const secret = options.secret?.trim();
223
+ if (!secret) throw new WebhookConfigError("The signing secret is empty.");
224
+ const doFetch = options.fetch ?? globalThis.fetch;
225
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
226
+ if (!(timeoutMs > 0)) throw new WebhookConfigError("timeoutMs must be a positive number of milliseconds.");
227
+ return {
228
+ url,
229
+ async send(input, sendOptions = {}) {
230
+ const files = Array.isArray(input) ? input : [input];
231
+ if (files.length === 0) throw new WebhookConfigError("Nothing to send: pass at least one file.");
232
+ const eventId = sendOptions.eventId ?? newEventId();
233
+ if (!isEventId(eventId)) throw new WebhookConfigError(`"${eventId}" is not a UUID or a ULID.`);
234
+ const { body, contentType } = await encode(files);
235
+ const t = unixSeconds();
236
+ const headers = {
237
+ "content-type": contentType,
238
+ [EVENT_ID_HEADER]: eventId,
239
+ [SIGNATURE_HEADER]: signatureHeader({ secret, timestamp: t, eventId, body })
240
+ };
241
+ const timeout = AbortSignal.timeout(timeoutMs);
242
+ const signal = sendOptions.signal ? AbortSignal.any([sendOptions.signal, timeout]) : timeout;
243
+ let response;
244
+ try {
245
+ response = await doFetch(url, { method: "POST", headers, body, signal, redirect: "error" });
246
+ } catch (error) {
247
+ throw new WebhookUnreachableError(url, eventId, error);
248
+ }
249
+ return interpret(response.status, await response.text(), eventId, response.headers.get("retry-after"));
250
+ }
251
+ };
252
+ }
253
+
254
+ // src/bin.ts
255
+ var USAGE = `Usage: braille-webhook-send <file> [<file> ...] [--event-id <uuid-or-ulid>] [--env <path>] [--json]
256
+
257
+ Posts the file(s) to a Braille webhook endpoint as one signed delivery.
258
+
259
+ Configuration, from the environment or from .env in the current directory (--env names another file;
260
+ values already in the environment win):
261
+ ${ENV.url} the delivery URL Braille printed for the endpoint
262
+ ${ENV.secret} the endpoint's signing secret, or
263
+ ${ENV.secretFile} the path of a file holding it (what \`braille webhooks create --secret-file\` wrote)
264
+
265
+ Options:
266
+ --event-id <id> retry the same document under the id printed by the first attempt; a new id is a new document
267
+ --env <path> read configuration from this file instead of ./.env
268
+ --json print the result as JSON on stdout; messages go to stderr
269
+ --version, --help
270
+
271
+ Exit codes: 0 accepted (200 or 207), 1 refused (4xx, fix the cause), 2 usage or configuration (nothing sent),
272
+ 4 retry with the same event id (unreachable, 5xx or 429).`;
273
+ var Exit = class {
274
+ constructor(code, message) {
275
+ this.code = code;
276
+ this.message = message;
277
+ }
278
+ code;
279
+ message;
280
+ };
281
+ function parseArgs(argv) {
282
+ const parsed = { files: [], json: false };
283
+ for (let i = 0; i < argv.length; i += 1) {
284
+ const arg = argv[i];
285
+ const takeValue = (name) => {
286
+ const value = argv[i + 1];
287
+ if (value === void 0 || value.startsWith("--")) throw new Exit(2, `${name} was given without a value.
288
+
289
+ ${USAGE}`);
290
+ i += 1;
291
+ return value;
292
+ };
293
+ if (arg === "--help" || arg === "-h") {
294
+ console.log(USAGE);
295
+ throw new Exit(0);
296
+ } else if (arg === "--version") {
297
+ console.log("0.1.0");
298
+ throw new Exit(0);
299
+ } else if (arg === "--json") {
300
+ parsed.json = true;
301
+ } else if (arg === "--event-id") {
302
+ parsed.eventId = takeValue(arg);
303
+ } else if (arg.startsWith("--event-id=")) {
304
+ parsed.eventId = arg.slice("--event-id=".length);
305
+ } else if (arg === "--env") {
306
+ parsed.envFile = takeValue(arg);
307
+ } else if (arg.startsWith("--env=")) {
308
+ parsed.envFile = arg.slice("--env=".length);
309
+ } else if (arg.startsWith("--")) {
310
+ throw new Exit(2, `Unknown flag ${arg}.
311
+
312
+ ${USAGE}`);
313
+ } else {
314
+ parsed.files.push(arg);
315
+ }
316
+ }
317
+ if (parsed.files.length === 0) throw new Exit(2, `At least one file is required.
318
+
319
+ ${USAGE}`);
320
+ return parsed;
321
+ }
322
+ function environment(envFile) {
323
+ const set = Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== void 0 && value !== ""));
324
+ const path = (0, import_node_path2.resolve)(envFile ?? ".env");
325
+ if (envFile === void 0) {
326
+ if (!(0, import_node_fs3.existsSync)(path)) return set;
327
+ try {
328
+ return { ...readEnvFile(path), ...set };
329
+ } catch {
330
+ return set;
331
+ }
332
+ }
333
+ return { ...readEnvFile(path), ...set };
334
+ }
335
+ function report(result, json) {
336
+ const say = json ? console.error : console.log;
337
+ if (json) console.log(JSON.stringify(result));
338
+ if (result.ok) {
339
+ say(`\u2192 ${result.status} ${result.partial ? "Partial" : "OK"} event ${result.eventId}`);
340
+ for (const file of result.files) say(` ${file.disposition.padEnd(8)} ${file.fileName}`);
341
+ if (result.partial) say("Some files did not store. Send those again as a new event; this event id is spent.");
342
+ return 0;
343
+ }
344
+ say(`\u2192 ${result.status} ${result.code}: ${result.message}`);
345
+ if (result.status === 429) {
346
+ say(`Rate limited. Wait ${result.retryAfterSeconds ?? "a few"} seconds, then retry with --event-id ${result.eventId}.`);
347
+ } else if (result.status >= 500) {
348
+ say(`Braille could not take it just now. Retry with --event-id ${result.eventId}.`);
349
+ }
350
+ return result.retryable ? 4 : 1;
351
+ }
352
+ async function run(argv) {
353
+ const args = parseArgs(argv);
354
+ const say = args.json ? console.error : console.log;
355
+ try {
356
+ const sender = createWebhookSender(optionsFromEnv(environment(args.envFile)));
357
+ const files = args.files.map((path) => fileFromPath(path));
358
+ say(`POST ${sender.url} (${files.length} file${files.length === 1 ? "" : "s"})`);
359
+ const result = await sender.send(files, { eventId: args.eventId });
360
+ return report(result, args.json);
361
+ } catch (error) {
362
+ if (error instanceof WebhookConfigError) throw new Exit(2, error.message);
363
+ if (error instanceof WebhookUnreachableError) {
364
+ throw new Exit(4, `${error.message}
365
+ Nothing was delivered. Retry with --event-id ${error.eventId}.`);
366
+ }
367
+ throw error;
368
+ }
369
+ }
370
+ run(process.argv.slice(2)).then(
371
+ (code) => {
372
+ process.exitCode = code;
373
+ },
374
+ (error) => {
375
+ if (error instanceof Exit) {
376
+ if (error.message) console.error(error.message);
377
+ process.exitCode = error.code;
378
+ return;
379
+ }
380
+ console.error(error instanceof Error ? error.message : String(error));
381
+ process.exitCode = 4;
382
+ }
383
+ );
package/dist/index.cjs ADDED
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ CONTENT_TYPES: () => CONTENT_TYPES,
24
+ DEFAULT_TIMEOUT_MS: () => DEFAULT_TIMEOUT_MS,
25
+ ENV: () => ENV,
26
+ EVENT_ID_HEADER: () => EVENT_ID_HEADER,
27
+ SIGNATURE_HEADER: () => SIGNATURE_HEADER,
28
+ TIMESTAMP_TOLERANCE_SECONDS: () => TIMESTAMP_TOLERANCE_SECONDS,
29
+ WebhookConfigError: () => WebhookConfigError,
30
+ WebhookUnreachableError: () => WebhookUnreachableError,
31
+ createWebhookSender: () => createWebhookSender,
32
+ fileFromPath: () => fileFromPath,
33
+ isEventId: () => isEventId,
34
+ newEventId: () => newEventId,
35
+ optionsFromEnv: () => optionsFromEnv,
36
+ parseEnvFile: () => parseEnvFile,
37
+ readEnvFile: () => readEnvFile,
38
+ signatureHeader: () => signatureHeader,
39
+ signedPayload: () => signedPayload,
40
+ unixSeconds: () => unixSeconds
41
+ });
42
+ module.exports = __toCommonJS(src_exports);
43
+
44
+ // src/send.ts
45
+ var import_node_fs = require("fs");
46
+ var import_node_path = require("path");
47
+
48
+ // src/errors.ts
49
+ var WebhookConfigError = class extends Error {
50
+ name = "WebhookConfigError";
51
+ };
52
+ function describe(cause) {
53
+ const error = cause;
54
+ if (error?.name === "TimeoutError") return "no answer within the timeout";
55
+ if (error?.name === "AbortError") return "aborted by the caller";
56
+ return error?.cause?.code ?? error?.cause?.errors?.[0]?.code ?? error?.cause?.message ?? error?.message ?? String(cause);
57
+ }
58
+ var WebhookUnreachableError = class extends Error {
59
+ name = "WebhookUnreachableError";
60
+ eventId;
61
+ url;
62
+ constructor(url, eventId, cause) {
63
+ super(`Could not reach ${url}: ${describe(cause)}`, { cause });
64
+ this.url = url;
65
+ this.eventId = eventId;
66
+ }
67
+ };
68
+
69
+ // src/sign.ts
70
+ var import_node_crypto = require("crypto");
71
+ var EVENT_ID_HEADER = "Braille-Event-Id";
72
+ var SIGNATURE_HEADER = "Braille-Signature";
73
+ var TIMESTAMP_TOLERANCE_SECONDS = 300;
74
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
75
+ var ULID = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
76
+ function isEventId(value) {
77
+ return UUID.test(value) || ULID.test(value);
78
+ }
79
+ function newEventId() {
80
+ return (0, import_node_crypto.randomUUID)();
81
+ }
82
+ function unixSeconds(now = /* @__PURE__ */ new Date()) {
83
+ return Math.floor(now.getTime() / 1e3);
84
+ }
85
+ function signedPayload(timestamp, eventId, body) {
86
+ return Buffer.concat([Buffer.from(`${timestamp}.${eventId}.`, "utf8"), Buffer.from(body)]);
87
+ }
88
+ function signatureHeader({ secret, timestamp, eventId, body }) {
89
+ const v1 = (0, import_node_crypto.createHmac)("sha256", secret).update(signedPayload(timestamp, eventId, body)).digest("hex");
90
+ return `t=${timestamp},v1=${v1}`;
91
+ }
92
+
93
+ // src/send.ts
94
+ var CONTENT_TYPES = {
95
+ ".pdf": "application/pdf",
96
+ ".png": "image/png",
97
+ ".jpg": "image/jpeg",
98
+ ".jpeg": "image/jpeg",
99
+ ".gif": "image/gif",
100
+ ".webp": "image/webp",
101
+ ".zip": "application/zip"
102
+ };
103
+ var RESERVED_FIELDS = /* @__PURE__ */ new Set(["surfaceId", "surfaceModality"]);
104
+ var DEFAULT_TIMEOUT_MS = 12e4;
105
+ function fileFromPath(path, options = {}) {
106
+ let data;
107
+ try {
108
+ data = (0, import_node_fs.readFileSync)(path);
109
+ } catch (error) {
110
+ const code = error.code ?? error.message;
111
+ throw new WebhookConfigError(`Could not read the document at ${path}: ${code}`);
112
+ }
113
+ return { data, filename: (0, import_node_path.basename)(path), ...options };
114
+ }
115
+ function contentTypeFor(file) {
116
+ if (file.contentType) return file.contentType;
117
+ const type = CONTENT_TYPES[(0, import_node_path.extname)(file.filename).toLowerCase()];
118
+ if (!type) {
119
+ throw new WebhookConfigError(
120
+ `${file.filename}: Braille accepts PDF, PNG, JPEG, GIF, WebP and ZIP. Pass contentType to send it anyway.`
121
+ );
122
+ }
123
+ return type;
124
+ }
125
+ function toBlob(file, type) {
126
+ if (file.data instanceof Blob) return file.data.type === type ? file.data : new Blob([file.data], { type });
127
+ return new Blob([file.data], { type });
128
+ }
129
+ async function encode(files) {
130
+ const form = new FormData();
131
+ for (const file of files) {
132
+ const field = file.field ?? "file";
133
+ if (RESERVED_FIELDS.has(field)) {
134
+ throw new WebhookConfigError(`"${field}" is a reserved field name; the endpoint decides the destination.`);
135
+ }
136
+ if (!file.filename) throw new WebhookConfigError("Every file needs a filename.");
137
+ form.append(field, toBlob(file, contentTypeFor(file)), file.filename);
138
+ }
139
+ const encoded = new Response(form);
140
+ const contentType = encoded.headers.get("content-type");
141
+ if (!contentType) throw new WebhookConfigError("The multipart body could not be encoded.");
142
+ return { body: Buffer.from(await encoded.arrayBuffer()), contentType };
143
+ }
144
+ function parseRetryAfter(value) {
145
+ if (!value) return null;
146
+ const seconds = Number(value);
147
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
148
+ }
149
+ function interpret(status, text, eventId, retryAfter) {
150
+ let json = null;
151
+ try {
152
+ const parsed = JSON.parse(text);
153
+ if (parsed && typeof parsed === "object") json = parsed;
154
+ } catch {
155
+ json = null;
156
+ }
157
+ if (status >= 200 && status < 300) {
158
+ const files = Array.isArray(json?.files) ? json.files.flatMap(
159
+ (row) => row && typeof row === "object" ? [
160
+ {
161
+ fileName: String(row.fileName ?? ""),
162
+ disposition: String(row.disposition ?? "")
163
+ }
164
+ ] : []
165
+ ) : [];
166
+ return {
167
+ ok: true,
168
+ status,
169
+ eventId: typeof json?.eventId === "string" ? json.eventId : eventId,
170
+ partial: status === 207,
171
+ workspaceDocumentId: typeof json?.workspaceDocumentId === "string" ? json.workspaceDocumentId : null,
172
+ files
173
+ };
174
+ }
175
+ const code = typeof json?.code === "string" ? json.code : "UNEXPECTED_RESPONSE";
176
+ const message = typeof json?.message === "string" ? json.message : `The endpoint answered ${status} without Braille's JSON body. Check the URL.`;
177
+ return {
178
+ ok: false,
179
+ status,
180
+ eventId,
181
+ code,
182
+ message,
183
+ retryable: status === 429 || status >= 500,
184
+ retryAfterSeconds: parseRetryAfter(retryAfter)
185
+ };
186
+ }
187
+ function createWebhookSender(options) {
188
+ const url = options.url?.trim();
189
+ let parsed;
190
+ try {
191
+ parsed = new URL(url);
192
+ } catch {
193
+ throw new WebhookConfigError(`"${url}" is not a URL. Use the delivery URL Braille printed for the endpoint.`);
194
+ }
195
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
196
+ throw new WebhookConfigError(`The delivery URL must be http or https, not ${parsed.protocol}`);
197
+ }
198
+ const secret = options.secret?.trim();
199
+ if (!secret) throw new WebhookConfigError("The signing secret is empty.");
200
+ const doFetch = options.fetch ?? globalThis.fetch;
201
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
202
+ if (!(timeoutMs > 0)) throw new WebhookConfigError("timeoutMs must be a positive number of milliseconds.");
203
+ return {
204
+ url,
205
+ async send(input, sendOptions = {}) {
206
+ const files = Array.isArray(input) ? input : [input];
207
+ if (files.length === 0) throw new WebhookConfigError("Nothing to send: pass at least one file.");
208
+ const eventId = sendOptions.eventId ?? newEventId();
209
+ if (!isEventId(eventId)) throw new WebhookConfigError(`"${eventId}" is not a UUID or a ULID.`);
210
+ const { body, contentType } = await encode(files);
211
+ const t = unixSeconds();
212
+ const headers = {
213
+ "content-type": contentType,
214
+ [EVENT_ID_HEADER]: eventId,
215
+ [SIGNATURE_HEADER]: signatureHeader({ secret, timestamp: t, eventId, body })
216
+ };
217
+ const timeout = AbortSignal.timeout(timeoutMs);
218
+ const signal = sendOptions.signal ? AbortSignal.any([sendOptions.signal, timeout]) : timeout;
219
+ let response;
220
+ try {
221
+ response = await doFetch(url, { method: "POST", headers, body, signal, redirect: "error" });
222
+ } catch (error) {
223
+ throw new WebhookUnreachableError(url, eventId, error);
224
+ }
225
+ return interpret(response.status, await response.text(), eventId, response.headers.get("retry-after"));
226
+ }
227
+ };
228
+ }
229
+
230
+ // src/env.ts
231
+ var import_node_fs2 = require("fs");
232
+ var ENV = {
233
+ url: "BRAILLE_WEBHOOK_URL",
234
+ secret: "BRAILLE_WEBHOOK_SECRET",
235
+ secretFile: "BRAILLE_WEBHOOK_SECRET_FILE"
236
+ };
237
+ function parseEnvFile(text) {
238
+ const values = {};
239
+ for (const rawLine of text.split(/\r?\n/)) {
240
+ const line = rawLine.trim();
241
+ if (!line || line.startsWith("#")) continue;
242
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
243
+ if (!match) continue;
244
+ const key = match[1];
245
+ let value = (match[2] ?? "").trim();
246
+ const quote = value[0];
247
+ if ((quote === '"' || quote === "'") && value.length >= 2 && value.endsWith(quote)) {
248
+ value = value.slice(1, -1);
249
+ if (quote === '"') value = value.replace(/\\n/g, "\n");
250
+ } else {
251
+ value = value.replace(/\s+#.*$/, "");
252
+ }
253
+ values[key] = value;
254
+ }
255
+ return values;
256
+ }
257
+ function readEnvFile(path) {
258
+ let text;
259
+ try {
260
+ text = (0, import_node_fs2.readFileSync)(path, "utf8");
261
+ } catch (error) {
262
+ const code = error.code ?? error.message;
263
+ throw new WebhookConfigError(`Could not read the env file at ${path}: ${code}`);
264
+ }
265
+ return parseEnvFile(text);
266
+ }
267
+ function optionsFromEnv(env = process.env) {
268
+ const url = env[ENV.url]?.trim();
269
+ if (!url) throw new WebhookConfigError(`${ENV.url} is not set. It is the delivery URL Braille printed for the endpoint.`);
270
+ const secretFile = env[ENV.secretFile]?.trim();
271
+ let secret;
272
+ if (secretFile) {
273
+ try {
274
+ secret = (0, import_node_fs2.readFileSync)(secretFile, "utf8").trim();
275
+ } catch (error) {
276
+ const code = error.code ?? error.message;
277
+ throw new WebhookConfigError(`Could not read the secret file at ${secretFile}: ${code}`);
278
+ }
279
+ if (!secret) throw new WebhookConfigError(`The secret file at ${secretFile} is empty.`);
280
+ } else {
281
+ secret = env[ENV.secret]?.trim();
282
+ if (!secret) {
283
+ throw new WebhookConfigError(
284
+ `Neither ${ENV.secret} nor ${ENV.secretFile} is set. One of them must hold the endpoint's signing secret.`
285
+ );
286
+ }
287
+ }
288
+ return { url, secret };
289
+ }
290
+ // Annotate the CommonJS export names for ESM import in node:
291
+ 0 && (module.exports = {
292
+ CONTENT_TYPES,
293
+ DEFAULT_TIMEOUT_MS,
294
+ ENV,
295
+ EVENT_ID_HEADER,
296
+ SIGNATURE_HEADER,
297
+ TIMESTAMP_TOLERANCE_SECONDS,
298
+ WebhookConfigError,
299
+ WebhookUnreachableError,
300
+ createWebhookSender,
301
+ fileFromPath,
302
+ isEventId,
303
+ newEventId,
304
+ optionsFromEnv,
305
+ parseEnvFile,
306
+ readEnvFile,
307
+ signatureHeader,
308
+ signedPayload,
309
+ unixSeconds
310
+ });