pcific 0.0.0-stage → 0.2.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,516 @@
1
+ import { PcificConfigError } from "./errors.js";
2
+
3
+ export const DEFAULT_PCIFIC_KIT_BASE_URL = "https://business.pcific.ai";
4
+
5
+ const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
6
+
7
+ const KIT_SCRIPT_PATH = "/static/templates/kit.js";
8
+
9
+ export const PCIFIC_KIT_TOOLS = [
10
+ "orbit",
11
+ "safeguard",
12
+ "ask",
13
+ "pixel-trace",
14
+ "trust",
15
+ "chat",
16
+ ] as const;
17
+
18
+ export type PcificKitTool = (typeof PCIFIC_KIT_TOOLS)[number];
19
+
20
+ export type PcificKitTagName = `pcific-${PcificKitTool}`;
21
+
22
+ export type PcificKitLauncherCorner = "bottom-right" | "bottom-left" | "top-right" | "top-left";
23
+
24
+ export type PcificKitLauncher = PcificKitLauncherCorner | "inline";
25
+
26
+ export type PcificKitThemeMode = "auto" | "light" | "dark";
27
+
28
+ export type PcificKitOnOff = "on" | "off";
29
+
30
+ export const PCIFIC_KIT_FONTS = [
31
+ "business",
32
+ "inherit",
33
+ "Inter",
34
+ "Work Sans",
35
+ "Georgia",
36
+ "Arial",
37
+ "Verdana",
38
+ "Times New Roman",
39
+ "Courier New",
40
+ "system-ui",
41
+ "sans-serif",
42
+ "serif",
43
+ "monospace",
44
+ ] as const;
45
+
46
+ export type PcificKitFont = (typeof PCIFIC_KIT_FONTS)[number];
47
+
48
+ export interface PcificKitTheme {
49
+ accent?: string;
50
+ background?: string;
51
+ surface?: string;
52
+ text?: string;
53
+ mutedText?: string;
54
+ border?: string;
55
+ mode?: PcificKitThemeMode;
56
+ radius?: number;
57
+ font?: PcificKitFont;
58
+ density?: "comfortable" | "compact";
59
+ launcher?: {
60
+ corner?: PcificKitLauncherCorner;
61
+ offset?: number;
62
+ label?: string;
63
+ };
64
+ }
65
+
66
+ export interface PcificChatMessage {
67
+ id: string;
68
+ text: string;
69
+ senderId: string;
70
+ senderName?: string;
71
+ createdAt?: string;
72
+ warn?: boolean;
73
+ label?: string | null;
74
+ }
75
+
76
+ export interface PcificChatSendPayload {
77
+ text: string;
78
+ maskedText: string;
79
+ verdict: string;
80
+ enforce: boolean;
81
+ checkId: string;
82
+ receipt: string | null;
83
+ }
84
+
85
+ export type PcificResultEventDetail = Record<string, string | string[]>;
86
+
87
+ export interface PcificStateEventDetail {
88
+ type: "pcific:state";
89
+ state: string;
90
+ label: string;
91
+ link?: string;
92
+ }
93
+
94
+ export interface PcificProblemEventDetail {
95
+ message: string;
96
+ }
97
+
98
+ export interface PcificCapabilitiesEventDetail {
99
+ type: "pcific:capabilities";
100
+ states: Array<{ id: string; label: string }>;
101
+ acts: Array<{ id: string; label: string }>;
102
+ }
103
+
104
+ export interface PcificMessageSentEventDetail extends PcificChatSendPayload {
105
+ message: PcificChatMessage | null;
106
+ }
107
+
108
+ export interface PcificMessageBlockedEventDetail {
109
+ verdict: string;
110
+ }
111
+
112
+ export interface PcificKitEventDetailMap {
113
+ "pcific:result": PcificResultEventDetail;
114
+ "pcific:state": PcificStateEventDetail;
115
+ "pcific:problem": PcificProblemEventDetail;
116
+ "pcific:capabilities": PcificCapabilitiesEventDetail;
117
+ "pcific:message-sent": PcificMessageSentEventDetail;
118
+ "pcific:message-blocked": PcificMessageBlockedEventDetail;
119
+ }
120
+
121
+ export type PcificKitEventMap = {
122
+ [K in keyof PcificKitEventDetailMap]: CustomEvent<PcificKitEventDetailMap[K]>;
123
+ };
124
+
125
+ export type PcificKitEventName = keyof PcificKitEventMap;
126
+
127
+ export interface PcificTagCommonAttributes {
128
+ session?: string;
129
+ read?: string;
130
+ fill?: string;
131
+ form?: string;
132
+ accent?: string;
133
+ mode?: PcificKitThemeMode;
134
+ radius?: number | string;
135
+ font?: PcificKitFont;
136
+ theme?: string;
137
+ logo?: string;
138
+ launcher?: PcificKitLauncher;
139
+ simulate?: boolean | "";
140
+ title?: string;
141
+ }
142
+
143
+ export interface PcificOrbitAttributes extends PcificTagCommonAttributes {
144
+ "pixel-trace"?: PcificKitOnOff;
145
+ safeguard?: PcificKitOnOff;
146
+ faq?: PcificKitOnOff;
147
+ price?: PcificKitOnOff;
148
+ "edit-chat"?: PcificKitOnOff;
149
+ }
150
+
151
+ export interface PcificSafeguardAttributes extends PcificTagCommonAttributes {}
152
+
153
+ export interface PcificAskAttributes extends PcificTagCommonAttributes {
154
+ "item-id"?: string;
155
+ }
156
+
157
+ export interface PcificPixelTraceAttributes extends PcificTagCommonAttributes {}
158
+
159
+ export interface PcificTrustAttributes extends PcificTagCommonAttributes {}
160
+
161
+ export interface PcificChatAttributes extends PcificTagCommonAttributes {
162
+ "messages-url"?: string;
163
+ "send-url"?: string;
164
+ "session-url"?: string;
165
+ "poll-seconds"?: number | string;
166
+ }
167
+
168
+ export interface PcificTagAttributes
169
+ extends PcificOrbitAttributes,
170
+ PcificAskAttributes,
171
+ PcificChatAttributes {}
172
+
173
+ export interface PcificKitElement extends HTMLElement {
174
+ simulate(action: string): void;
175
+ }
176
+
177
+ export interface PcificChatElement extends PcificKitElement {
178
+ pushMessage(message: PcificChatMessage): void;
179
+ refresh(): void;
180
+ }
181
+
182
+ export interface PcificKitElementMap {
183
+ "pcific-orbit": PcificKitElement;
184
+ "pcific-safeguard": PcificKitElement;
185
+ "pcific-ask": PcificKitElement;
186
+ "pcific-pixel-trace": PcificKitElement;
187
+ "pcific-trust": PcificKitElement;
188
+ "pcific-chat": PcificChatElement;
189
+ }
190
+
191
+ export interface LoadPcificKitOptions {
192
+ /** Base origin serving `/static/templates/kit.js`. Defaults to `https://business.pcific.ai`. */
193
+ baseUrl?: string;
194
+ /** Maximum milliseconds to wait for the Kit script to load. Defaults to 15000. */
195
+ timeoutMs?: number;
196
+ /** When true, resolves as a no-op during SSR instead of throwing `PcificConfigError`. */
197
+ ignoreSsr?: boolean;
198
+ }
199
+
200
+ export interface PcificKitHandle {
201
+ readonly baseUrl: string;
202
+ readonly scriptUrl: string;
203
+ load(): Promise<void>;
204
+ onEvent: typeof onPcificEvent;
205
+ }
206
+
207
+ export interface KitScriptNode extends EventTarget {
208
+ type: string;
209
+ src: string;
210
+ getAttribute(name: string): string | null;
211
+ setAttribute(name: string, value: string): void;
212
+ }
213
+
214
+ export interface KitDocumentLike {
215
+ readonly head: { appendChild(node: KitScriptNode): KitScriptNode } | null;
216
+ readonly documentElement: { appendChild(node: KitScriptNode): KitScriptNode } | null;
217
+ createElement(tagName: "script"): KitScriptNode;
218
+ querySelectorAll(selector: string): ArrayLike<KitScriptNode>;
219
+ }
220
+
221
+ export interface KitCustomElementsLike {
222
+ get(name: string): CustomElementConstructor | undefined;
223
+ whenDefined?(name: string): Promise<CustomElementConstructor>;
224
+ }
225
+
226
+ interface BrowserGlobals {
227
+ document?: KitDocumentLike;
228
+ customElements?: KitCustomElementsLike;
229
+ }
230
+
231
+ const inflightLoads = new Map<string, Promise<void>>();
232
+
233
+ function readBrowserGlobals(): BrowserGlobals {
234
+ // SAFETY: globalThis may provide document and customElements in browser runtimes and omit them in SSR/Node.
235
+ return globalThis as BrowserGlobals;
236
+ }
237
+
238
+ function normalizeBaseUrl(rawBaseUrl: string | undefined): string {
239
+ const candidate = (rawBaseUrl ?? DEFAULT_PCIFIC_KIT_BASE_URL).trim();
240
+
241
+ if (!candidate) {
242
+ throw new PcificConfigError("PCIFIC Kit baseUrl cannot be empty.", {
243
+ code: "INVALID_KIT_BASE_URL",
244
+ tryThis: `Pass a valid http(s) baseUrl or omit it to use ${DEFAULT_PCIFIC_KIT_BASE_URL}.`,
245
+ });
246
+ }
247
+
248
+ let parsed: URL;
249
+
250
+ try {
251
+ parsed = new URL(candidate);
252
+ } catch {
253
+ throw new PcificConfigError(`Invalid PCIFIC Kit baseUrl "${candidate}".`, {
254
+ code: "INVALID_KIT_BASE_URL",
255
+ tryThis: `Pass a valid http(s) origin such as "${DEFAULT_PCIFIC_KIT_BASE_URL}".`,
256
+ });
257
+ }
258
+
259
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
260
+ throw new PcificConfigError(
261
+ `Unsupported PCIFIC Kit baseUrl protocol "${parsed.protocol}".`,
262
+ {
263
+ code: "INVALID_KIT_BASE_URL",
264
+ tryThis: `Use an https:// or http:// origin such as "${DEFAULT_PCIFIC_KIT_BASE_URL}".`,
265
+ },
266
+ );
267
+ }
268
+
269
+ return `${parsed.origin}${parsed.pathname}`.replace(/\/+$/, "");
270
+ }
271
+
272
+ export function getPcificKitScriptUrl(baseUrl?: string): string {
273
+ return `${normalizeBaseUrl(baseUrl)}${KIT_SCRIPT_PATH}`;
274
+ }
275
+
276
+ function findExistingKitScript(doc: KitDocumentLike, scriptUrl: string): KitScriptNode | null {
277
+ const scripts = doc.querySelectorAll("script[src]");
278
+
279
+ for (const node of Array.from(scripts)) {
280
+ const attrSrc = node.getAttribute("src");
281
+
282
+ if (attrSrc === scriptUrl || node.src === scriptUrl) {
283
+ return node;
284
+ }
285
+ }
286
+
287
+ return null;
288
+ }
289
+
290
+ /**
291
+ * Idempotently loads the PCIFIC Kit web components script in browser environments.
292
+ * Safe against concurrent calls and duplicate script tags.
293
+ */
294
+ export function loadPcificKit(options: LoadPcificKitOptions = {}): Promise<void> {
295
+ const scriptUrl = getPcificKitScriptUrl(options.baseUrl);
296
+ const timeoutMs = options.timeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS;
297
+
298
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
299
+ return Promise.reject(
300
+ new PcificConfigError("PCIFIC Kit timeoutMs must be a positive number.", {
301
+ code: "INVALID_KIT_TIMEOUT",
302
+ tryThis: "Pass a positive number of milliseconds for timeoutMs, or omit it to use 15000.",
303
+ }),
304
+ );
305
+ }
306
+
307
+ const globals = readBrowserGlobals();
308
+ const doc = globals.document;
309
+ const registry = globals.customElements;
310
+
311
+ if (!doc || !registry) {
312
+ if (options.ignoreSsr) {
313
+ return Promise.resolve();
314
+ }
315
+
316
+ return Promise.reject(
317
+ new PcificConfigError(
318
+ "loadPcificKit() can only run in a browser environment with document and customElements.",
319
+ {
320
+ code: "PCIFIC_KIT_BROWSER_ONLY",
321
+ tryThis:
322
+ "Call loadPcificKit() inside a client-side effect (such as useEffect or onMount), or pass { ignoreSsr: true } if calling during SSR.",
323
+ },
324
+ ),
325
+ );
326
+ }
327
+
328
+ if (registry.get("pcific-orbit")) {
329
+ return Promise.resolve();
330
+ }
331
+
332
+ const inflight = inflightLoads.get(scriptUrl);
333
+
334
+ if (inflight) {
335
+ return inflight;
336
+ }
337
+
338
+ const existing = findExistingKitScript(doc, scriptUrl);
339
+
340
+ if (existing?.getAttribute("data-pcific-kit-loaded") === "true") {
341
+ return Promise.resolve();
342
+ }
343
+
344
+ const loadPromise = new Promise<void>((resolve, reject) => {
345
+ const script = existing ?? doc.createElement("script");
346
+ let settled = false;
347
+
348
+ const cleanup = () => {
349
+ clearTimeout(timer);
350
+ script.removeEventListener("load", onLoad);
351
+ script.removeEventListener("error", onError);
352
+ };
353
+
354
+ const fail = (error: PcificConfigError) => {
355
+ if (settled) return;
356
+ settled = true;
357
+ cleanup();
358
+ inflightLoads.delete(scriptUrl);
359
+ reject(error);
360
+ };
361
+
362
+ const succeed = () => {
363
+ if (settled) return;
364
+ settled = true;
365
+ cleanup();
366
+ script.setAttribute("data-pcific-kit-loaded", "true");
367
+ inflightLoads.delete(scriptUrl);
368
+ resolve();
369
+ };
370
+
371
+ const onLoad = () => {
372
+ if (registry.get("pcific-orbit")) {
373
+ succeed();
374
+
375
+ return;
376
+ }
377
+
378
+ if (registry.whenDefined) {
379
+ registry.whenDefined("pcific-orbit").then(
380
+ () => succeed(),
381
+ () => succeed(),
382
+ );
383
+
384
+ return;
385
+ }
386
+
387
+ succeed();
388
+ };
389
+
390
+ const onError = () => {
391
+ fail(
392
+ new PcificConfigError(`Failed to load PCIFIC Kit script from ${scriptUrl}.`, {
393
+ code: "PCIFIC_KIT_LOAD_FAILED",
394
+ tryThis: `Check that ${scriptUrl} is reachable and allowed by your Content-Security-Policy.`,
395
+ }),
396
+ );
397
+ };
398
+
399
+ const timer = setTimeout(() => {
400
+ fail(
401
+ new PcificConfigError(
402
+ `Timed out after ${timeoutMs}ms waiting for PCIFIC Kit script (${scriptUrl}).`,
403
+ {
404
+ code: "PCIFIC_KIT_LOAD_TIMEOUT",
405
+ tryThis: "Check network connectivity or raise timeoutMs, then retry loadPcificKit().",
406
+ },
407
+ ),
408
+ );
409
+ }, timeoutMs);
410
+
411
+ script.addEventListener("load", onLoad, { once: true });
412
+ script.addEventListener("error", onError, { once: true });
413
+
414
+ if (!existing) {
415
+ script.type = "module";
416
+ script.src = scriptUrl;
417
+ script.setAttribute("data-pcific-kit", "true");
418
+ const target = doc.head ?? doc.documentElement;
419
+
420
+ if (!target) {
421
+ fail(
422
+ new PcificConfigError("Cannot mount PCIFIC Kit script: document has no head or root element.", {
423
+ code: "PCIFIC_KIT_NO_DOCUMENT_TARGET",
424
+ tryThis: "Call loadPcificKit() after the page document has been initialized.",
425
+ }),
426
+ );
427
+
428
+ return;
429
+ }
430
+
431
+ target.appendChild(script);
432
+ }
433
+ });
434
+
435
+ inflightLoads.set(scriptUrl, loadPromise);
436
+
437
+ return loadPromise;
438
+ }
439
+
440
+ /**
441
+ * Attaches a typed listener for any PCIFIC custom event (`pcific:result`, `pcific:state`,
442
+ * `pcific:problem`, etc.) and returns a cleanup function that removes it.
443
+ */
444
+ export function onPcificEvent<K extends PcificKitEventName>(
445
+ element: EventTarget,
446
+ eventName: K,
447
+ handler: (detail: PcificKitEventDetailMap[K], event: CustomEvent<PcificKitEventDetailMap[K]>) => void,
448
+ options?: AddEventListenerOptions | boolean,
449
+ ): () => void {
450
+ const listener = (rawEvent: Event) => {
451
+ // SAFETY: The listener is registered specifically for eventName, which PCIFIC Kit dispatches as CustomEvent<PcificKitEventDetailMap[K]>.
452
+ const customEvent = rawEvent as CustomEvent<PcificKitEventDetailMap[K]>;
453
+ handler(customEvent.detail, customEvent);
454
+ };
455
+
456
+ element.addEventListener(eventName, listener, options);
457
+
458
+ return () => {
459
+ element.removeEventListener(eventName, listener, options);
460
+ };
461
+ }
462
+
463
+ /**
464
+ * Creates a reusable handle configured with a baseUrl for loading PCIFIC Kit
465
+ * and subscribing to typed web component events.
466
+ */
467
+ export function createPcificKit(options: LoadPcificKitOptions = {}): PcificKitHandle {
468
+ const baseUrl = normalizeBaseUrl(options.baseUrl);
469
+ const scriptUrl = `${baseUrl}${KIT_SCRIPT_PATH}`;
470
+
471
+ return {
472
+ baseUrl,
473
+ scriptUrl,
474
+ load: () => loadPcificKit({ ...options, baseUrl }),
475
+ onEvent: onPcificEvent,
476
+ };
477
+ }
478
+
479
+ /** Clears internal in-flight script cache. Intended for test isolation. */
480
+ export function resetPcificKitLoader(): void {
481
+ inflightLoads.clear();
482
+ }
483
+
484
+ export interface PcificIntrinsicElementBase {
485
+ id?: string;
486
+ class?: string;
487
+ className?: string;
488
+ style?: string | Record<string, string | number | undefined>;
489
+ slot?: string;
490
+ hidden?: boolean;
491
+ "aria-label"?: string;
492
+ children?: unknown;
493
+ ref?: unknown;
494
+ }
495
+
496
+ declare global {
497
+ interface HTMLElementTagNameMap {
498
+ "pcific-orbit": PcificKitElement;
499
+ "pcific-safeguard": PcificKitElement;
500
+ "pcific-ask": PcificKitElement;
501
+ "pcific-pixel-trace": PcificKitElement;
502
+ "pcific-trust": PcificKitElement;
503
+ "pcific-chat": PcificChatElement;
504
+ }
505
+
506
+ namespace JSX {
507
+ interface IntrinsicElements {
508
+ "pcific-orbit": PcificIntrinsicElementBase & PcificOrbitAttributes;
509
+ "pcific-safeguard": PcificIntrinsicElementBase & PcificSafeguardAttributes;
510
+ "pcific-ask": PcificIntrinsicElementBase & PcificAskAttributes;
511
+ "pcific-pixel-trace": PcificIntrinsicElementBase & PcificPixelTraceAttributes;
512
+ "pcific-trust": PcificIntrinsicElementBase & PcificTrustAttributes;
513
+ "pcific-chat": PcificIntrinsicElementBase & PcificChatAttributes;
514
+ }
515
+ }
516
+ }
@@ -0,0 +1,99 @@
1
+ export interface UploadFileDescriptor {
2
+ data: Blob | Uint8Array | ArrayBuffer;
3
+ filename?: string;
4
+ contentType?: string;
5
+ }
6
+
7
+ export type UploadInput = Blob | Uint8Array | ArrayBuffer | UploadFileDescriptor;
8
+
9
+ export interface NormalizedUpload {
10
+ blob: Blob;
11
+ filename: string;
12
+ contentType: string;
13
+ }
14
+
15
+ function isFileLike(value: Blob | Uint8Array | ArrayBuffer): value is File {
16
+ return typeof File !== "undefined" && value instanceof File;
17
+ }
18
+
19
+ function isDescriptor(value: UploadInput): value is UploadFileDescriptor {
20
+ return (
21
+ typeof value === "object" &&
22
+ value !== null &&
23
+ !(value instanceof Blob) &&
24
+ !(value instanceof Uint8Array) &&
25
+ !(value instanceof ArrayBuffer) &&
26
+ "data" in value
27
+ );
28
+ }
29
+
30
+ function toArrayBufferSlice(bytes: Uint8Array): ArrayBuffer {
31
+ const copy = new Uint8Array(bytes.byteLength);
32
+ copy.set(bytes);
33
+
34
+ return copy.buffer;
35
+ }
36
+
37
+ /**
38
+ * Normalizes Blob, File, Uint8Array, ArrayBuffer, or descriptor objects into a Blob with filename and contentType.
39
+ */
40
+ export function normalizeUpload(
41
+ input: UploadInput,
42
+ defaultFilename = "upload.jpg",
43
+ defaultContentType = "application/octet-stream",
44
+ ): NormalizedUpload {
45
+ if (isDescriptor(input)) {
46
+ const contentType =
47
+ input.contentType ??
48
+ (input.data instanceof Blob && input.data.type ? input.data.type : defaultContentType);
49
+
50
+ const filename =
51
+ input.filename ?? (isFileLike(input.data) && input.data.name ? input.data.name : defaultFilename);
52
+
53
+ const blob =
54
+ input.data instanceof Blob
55
+ ? input.data.type === contentType
56
+ ? input.data
57
+ : new Blob([input.data], { type: contentType })
58
+ : input.data instanceof Uint8Array
59
+ ? new Blob([toArrayBufferSlice(input.data)], { type: contentType })
60
+ : new Blob([input.data], { type: contentType });
61
+
62
+ return { blob, filename, contentType };
63
+ }
64
+
65
+ if (input instanceof Blob) {
66
+ const contentType = input.type || defaultContentType;
67
+ const filename = isFileLike(input) && input.name ? input.name : defaultFilename;
68
+
69
+ return { blob: input, filename, contentType };
70
+ }
71
+
72
+ if (input instanceof Uint8Array) {
73
+ return {
74
+ blob: new Blob([toArrayBufferSlice(input)], { type: defaultContentType }),
75
+ filename: defaultFilename,
76
+ contentType: defaultContentType,
77
+ };
78
+ }
79
+
80
+ return {
81
+ blob: new Blob([input], { type: defaultContentType }),
82
+ filename: defaultFilename,
83
+ contentType: defaultContentType,
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Serializes a FormData instance to exact bytes and its boundary Content-Type header
89
+ * so request signing covers the exact transmitted payload.
90
+ */
91
+ export async function serializeFormData(
92
+ formData: FormData,
93
+ ): Promise<{ body: Uint8Array; contentType: string }> {
94
+ const response = new Response(formData);
95
+ const contentType = response.headers.get("content-type") ?? "multipart/form-data";
96
+ const body = new Uint8Array(await response.arrayBuffer());
97
+
98
+ return { body, contentType };
99
+ }