@eigenpal/sdk 0.25.14 → 1.0.0-rc.2

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 (73) hide show
  1. package/README.md +27 -105
  2. package/dist/client.d.ts +164 -0
  3. package/dist/client.js +234 -0
  4. package/dist/core.d.ts +82 -0
  5. package/dist/core.js +311 -0
  6. package/dist/errors.d.ts +64 -0
  7. package/dist/errors.js +132 -0
  8. package/dist/generated/operations.gen.d.ts +336 -0
  9. package/dist/generated/operations.gen.js +135 -0
  10. package/dist/generated/public.gen.d.ts +2 -0
  11. package/dist/generated/public.gen.js +2 -0
  12. package/dist/generated/resources.gen.d.ts +490 -0
  13. package/dist/generated/resources.gen.js +659 -0
  14. package/dist/generated/types.gen.d.ts +2457 -0
  15. package/dist/generated/types.gen.js +2 -0
  16. package/dist/index.d.ts +20 -0
  17. package/dist/index.js +15 -0
  18. package/dist/lib/fetch-body.d.ts +23 -0
  19. package/dist/lib/fetch-body.js +66 -0
  20. package/dist/lib/files.d.ts +134 -0
  21. package/dist/lib/files.js +296 -0
  22. package/dist/lib/upload-app-chunked.d.ts +36 -0
  23. package/dist/lib/upload-app-chunked.js +94 -0
  24. package/dist/lib/upload-limits.d.ts +32 -0
  25. package/dist/lib/upload-limits.js +60 -0
  26. package/dist/lib/upload-presigned-multipart.d.ts +74 -0
  27. package/dist/lib/upload-presigned-multipart.js +212 -0
  28. package/dist/page.d.ts +30 -0
  29. package/dist/page.js +38 -0
  30. package/dist/resources.d.ts +85 -0
  31. package/dist/resources.js +247 -0
  32. package/dist/telemetry.d.ts +20 -0
  33. package/{src/telemetry.ts → dist/telemetry.js} +26 -31
  34. package/dist/upload-file.d.ts +31 -0
  35. package/dist/upload-file.js +286 -0
  36. package/{src/upload.ts → dist/upload.d.ts} +4 -4
  37. package/dist/upload.js +12 -0
  38. package/package.json +19 -15
  39. package/src/client.ts +0 -656
  40. package/src/errors.ts +0 -130
  41. package/src/generated/client/client.gen.ts +0 -277
  42. package/src/generated/client/index.ts +0 -27
  43. package/src/generated/client/types.gen.ts +0 -218
  44. package/src/generated/client/utils.gen.ts +0 -316
  45. package/src/generated/client.gen.ts +0 -18
  46. package/src/generated/core/auth.gen.ts +0 -48
  47. package/src/generated/core/bodySerializer.gen.ts +0 -82
  48. package/src/generated/core/params.gen.ts +0 -178
  49. package/src/generated/core/pathSerializer.gen.ts +0 -171
  50. package/src/generated/core/queryKeySerializer.gen.ts +0 -117
  51. package/src/generated/core/serverSentEvents.gen.ts +0 -242
  52. package/src/generated/core/types.gen.ts +0 -110
  53. package/src/generated/core/utils.gen.ts +0 -140
  54. package/src/generated/index.ts +0 -4
  55. package/src/generated/sdk.gen.ts +0 -1361
  56. package/src/generated/types.gen.ts +0 -9282
  57. package/src/index.ts +0 -120
  58. package/src/lib/fetch-body.ts +0 -92
  59. package/src/lib/files.ts +0 -390
  60. package/src/lib/upload-app-chunked.ts +0 -121
  61. package/src/lib/upload-limits.ts +0 -72
  62. package/src/lib/upload-presigned-multipart.ts +0 -285
  63. package/src/resources/auth.ts +0 -18
  64. package/src/resources/automations.ts +0 -830
  65. package/src/resources/dataset-review-requests.ts +0 -38
  66. package/src/resources/email-servers.ts +0 -95
  67. package/src/resources/files.ts +0 -592
  68. package/src/resources/folders.ts +0 -77
  69. package/src/resources/human-reviews.ts +0 -106
  70. package/src/resources/models.ts +0 -37
  71. package/src/resources/runs.ts +0 -350
  72. package/src/resources/templates.ts +0 -153
  73. package/src/runtime-config.ts +0 -14
@@ -0,0 +1,247 @@
1
+ /**
2
+ * The custom methods (SDK_GEN_DECISION section 5): the generated classes
3
+ * declare them, these subclasses fill them. Every request is an operation of
4
+ * the table (`core.request(opId, ...)`), never a path string.
5
+ */
6
+ import { DEFAULT_WAIT_TIMEOUT_MS } from './core.js';
7
+ import { EigenPalError, EigenPalNotFoundError, EigenPalTimeoutError } from './errors.js';
8
+ import { DatasetsReviewsResource as DatasetsReviewsBase, EmailServersResource as EmailServersBase, ExperimentsResource as ExperimentsBase, FilesResource as FilesBase, RunsResource as RunsBase, TemplatesResource as TemplatesBase, } from './generated/resources.gen.js';
9
+ import { uploadFile } from './upload-file.js';
10
+ /** Poll `read` until `done`, backing off from 2 s to 5 s; out of time raises with the last record. */
11
+ export async function waitUntil(core, read, done, options = {}) {
12
+ const deadline = core.now() + (options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS);
13
+ let record = options.first ?? (await read());
14
+ let delay = 2_000;
15
+ while (!done(record)) {
16
+ if (core.now() >= deadline) {
17
+ throw new EigenPalTimeoutError('The wait ran out; the record is in `.record`.', record);
18
+ }
19
+ await core.sleep(delay, options.signal);
20
+ delay = Math.min(5_000, Math.round(delay * 1.5));
21
+ record = await read();
22
+ }
23
+ return record;
24
+ }
25
+ const RUN_FINAL = new Set(['succeeded', 'failed', 'cancelled', 'waiting']);
26
+ const EXPERIMENT_FINAL = new Set(['succeeded', 'failed', 'cancelled']);
27
+ const REVIEW_FINAL = new Set(['closed', 'cancelled']);
28
+ export const runSettled = (run) => RUN_FINAL.has(String(run.state));
29
+ export class Runs extends RunsBase {
30
+ /**
31
+ * The run's events, oldest first, every page. With `follow`, keeps reading
32
+ * until the run is final (the CLI's `runs logs --follow`).
33
+ */
34
+ async *logs(run, options = {}) {
35
+ let cursor = options.cursor;
36
+ for (;;) {
37
+ const page = await this.core.request('runs.events.list', {
38
+ path: { id: run },
39
+ query: { cursor },
40
+ signal: options.signal,
41
+ });
42
+ yield* page.data;
43
+ cursor = page.nextCursor ?? cursor;
44
+ if (page.nextCursor && page.data.length > 0)
45
+ continue;
46
+ if (!options.follow)
47
+ return;
48
+ const current = await this.core.request('runs.get', {
49
+ path: { id: run },
50
+ signal: options.signal,
51
+ });
52
+ if (runSettled(current)) {
53
+ const rest = await this.core.request('runs.events.list', {
54
+ path: { id: run },
55
+ query: { cursor },
56
+ signal: options.signal,
57
+ });
58
+ yield* rest.data;
59
+ return;
60
+ }
61
+ await this.core.sleep(options.pollMs ?? 2_000, options.signal);
62
+ }
63
+ }
64
+ /** The files of a run (all, or the given artifact paths), with their bytes. */
65
+ async download(run, options = {}) {
66
+ const listed = await this.core.request('runs.artifacts.list', {
67
+ path: { id: run },
68
+ signal: options.signal,
69
+ });
70
+ const wanted = options.paths?.length
71
+ ? listed.data.filter((a) => options.paths.some((p) => a.path === p || a.path.startsWith(`${p}/`)))
72
+ : listed.data;
73
+ const out = [];
74
+ for (const artifact of wanted) {
75
+ const content = await this.core.request('runs.artifacts.get', { path: { id: run, path: artifact.path }, signal: options.signal }, { binary: true });
76
+ out.push({ path: artifact.path, content });
77
+ }
78
+ return out;
79
+ }
80
+ }
81
+ export class Experiments extends ExperimentsBase {
82
+ async #ref(experiment, signal) {
83
+ return this.core.request('experiments.resolve', {
84
+ path: { experimentId: experiment },
85
+ signal,
86
+ });
87
+ }
88
+ /** An experiment with its runs and scores. With `wait`, polls until it is final. */
89
+ async get(experiment, options = {}) {
90
+ const { automationId } = await this.#ref(experiment, options.signal);
91
+ const read = () => this.core.request('automations.experiments.get', {
92
+ path: { id: automationId, experimentId: experiment },
93
+ signal: options.signal,
94
+ });
95
+ if (!options.wait)
96
+ return read();
97
+ return waitUntil(this.core, read, (e) => EXPERIMENT_FINAL.has(String(e.state)), options);
98
+ }
99
+ /** Stop an experiment's runs that have not finished. */
100
+ async cancel(experiment, options = {}) {
101
+ const { automationId } = await this.#ref(experiment, options.signal);
102
+ return this.core.request('automations.experiments.cancel', {
103
+ path: { id: automationId, experimentId: experiment },
104
+ signal: options.signal,
105
+ });
106
+ }
107
+ }
108
+ export class DatasetsReviews extends DatasetsReviewsBase {
109
+ /** The automation of a review, from the organization inbox. */
110
+ async #automationOf(review, signal) {
111
+ let cursor;
112
+ do {
113
+ const page = await this.core.request('datasetReviewRequests.list', {
114
+ query: { limit: 100, cursor, project: this.core.project },
115
+ signal,
116
+ });
117
+ const found = page.data.find((r) => r.id === review);
118
+ if (found)
119
+ return found.automationId;
120
+ cursor = page.nextCursor ?? undefined;
121
+ } while (cursor);
122
+ throw new EigenPalNotFoundError({
123
+ code: 'not_found',
124
+ message: `No dataset review ${review}.`,
125
+ hint: 'List the dataset reviews with datasets.reviews.list().',
126
+ issues: [],
127
+ requestId: '',
128
+ });
129
+ }
130
+ #read(automation, review, signal) {
131
+ return this.core.request('automations.datasetReviewRequests.get', {
132
+ path: { id: automation, reviewId: review },
133
+ signal,
134
+ });
135
+ }
136
+ /** A dataset review: progress, decisions, notes. With `wait`, polls until it is closed. */
137
+ async get(review, options = {}) {
138
+ const automation = await this.#automationOf(review, options.signal);
139
+ const read = () => this.#read(automation, review, options.signal);
140
+ if (!options.wait)
141
+ return read();
142
+ return waitUntil(this.core, read, (r) => REVIEW_FINAL.has(String(r.status)), options);
143
+ }
144
+ /** Comment on one example of a review (optionally on one field). */
145
+ async comment(review, example, options) {
146
+ const automation = await this.#automationOf(review, options.signal);
147
+ const detail = await this.#read(automation, review, options.signal);
148
+ const item = detail.items.find((i) => i.exampleName === example || i.id === example);
149
+ if (!item) {
150
+ throw new EigenPalError(`Example ${example} is not in review ${review}.`, { status: 0 });
151
+ }
152
+ return this.core.request('automations.datasetReviewRequests.updateItem', {
153
+ path: { id: automation, reviewId: review, itemId: item.id },
154
+ body: {
155
+ action: 'comment',
156
+ comment: options.text,
157
+ ...(options.field ? { fieldPath: options.field } : {}),
158
+ },
159
+ signal: options.signal,
160
+ });
161
+ }
162
+ /** Close a review; open decisions stay as they are. */
163
+ async close(review, options = {}) {
164
+ const automation = await this.#automationOf(review, options.signal);
165
+ return this.core.request('automations.datasetReviewRequests.update', {
166
+ path: { id: automation, reviewId: review },
167
+ body: { status: 'closed' },
168
+ signal: options.signal,
169
+ });
170
+ }
171
+ }
172
+ export class Templates extends TemplatesBase {
173
+ /**
174
+ * Upload a DOCX or XLSX template: a new one, or a new revision of `replace`
175
+ * (a template id).
176
+ */
177
+ async upload(file, options = {}) {
178
+ const uploaded = await uploadFile(this.core, file, {
179
+ filename: options.filename,
180
+ signal: options.signal,
181
+ });
182
+ try {
183
+ if (options.replace) {
184
+ return await this.core.request('templates.replace', {
185
+ path: { id: options.replace },
186
+ body: { fileId: uploaded.id },
187
+ signal: options.signal,
188
+ });
189
+ }
190
+ return await this.core.request('templates.create', {
191
+ body: {
192
+ fileId: uploaded.id,
193
+ name: options.name ?? templateName(uploaded),
194
+ description: options.description,
195
+ },
196
+ signal: options.signal,
197
+ });
198
+ }
199
+ finally {
200
+ await this.core.request('files.delete', { path: { id: uploaded.id } }).catch(() => undefined);
201
+ }
202
+ }
203
+ }
204
+ function templateName(file) {
205
+ const name = file.filename ?? 'template';
206
+ return name.replace(/\.[^.]+$/, '');
207
+ }
208
+ export class EmailServers extends EmailServersBase {
209
+ /** Create the server of this name, or update it (secrets are write-only). */
210
+ async set(name, config) {
211
+ const { signal, ...fields } = config;
212
+ let cursor;
213
+ do {
214
+ const page = await this.core.request('emailServers.list', {
215
+ query: { limit: 100, cursor },
216
+ signal,
217
+ });
218
+ const found = page.data.find((s) => s.name === name);
219
+ if (found) {
220
+ return this.core.request('emailServers.update', {
221
+ path: { id: found.id },
222
+ body: fields,
223
+ signal,
224
+ });
225
+ }
226
+ cursor = page.nextCursor ?? undefined;
227
+ } while (cursor);
228
+ return this.core.request('emailServers.create', {
229
+ body: { ...fields, name },
230
+ signal,
231
+ });
232
+ }
233
+ }
234
+ export class Files extends FilesBase {
235
+ /** Upload a file once; pass `{ $fileId: file.id }` as a run input, to as many runs as you like. */
236
+ upload(file, options = {}) {
237
+ return uploadFile(this.core, file, options);
238
+ }
239
+ }
240
+ export const RESOURCE_IMPLS = {
241
+ RunsResource: Runs,
242
+ ExperimentsResource: Experiments,
243
+ DatasetsReviewsResource: DatasetsReviews,
244
+ TemplatesResource: Templates,
245
+ EmailServersResource: EmailServers,
246
+ FilesResource: Files,
247
+ };
@@ -0,0 +1,20 @@
1
+ /**
2
+ * SDK telemetry headers attached to every outbound request.
3
+ *
4
+ * The server reads these to track adoption — which language, which
5
+ * version, which runtime are calling? Lets us answer "should we still
6
+ * support Node 20?" or "is the 0.4 series still in use?" from log
7
+ * aggregation alone, without having to ship a separate phone-home.
8
+ *
9
+ * Header convention follows the Stainless / Anthropic SDK pattern:
10
+ * X-Eigenpal-Sdk — language tag ("typescript")
11
+ * X-Eigenpal-Sdk-Version — package version (rewritten at publish)
12
+ * X-Eigenpal-Sdk-Runtime — "bun-1.3.11" / "node-22.0.0" / "deno-X" / "browser"
13
+ * X-Eigenpal-Sdk-Os — "darwin-arm64" / "linux-x64" / "browser"
14
+ *
15
+ * `User-Agent` carries the same info in a single human-readable string
16
+ * for log lines and proxies that don't surface custom headers.
17
+ */
18
+ export declare const SDK_LANGUAGE = "typescript";
19
+ export declare const SDK_VERSION = "1.0.0-rc.2";
20
+ export declare function buildTelemetryHeaders(): Record<string, string>;
@@ -15,40 +15,35 @@
15
15
  * `User-Agent` carries the same info in a single human-readable string
16
16
  * for log lines and proxies that don't surface custom headers.
17
17
  */
18
-
19
18
  export const SDK_LANGUAGE = 'typescript';
20
19
  // Rewritten at publish time by scripts/release/platform/render-sdk-versions.sh.
21
20
  // Keep this string literal exactly stable — sed matches on it.
22
- export const SDK_VERSION = '0.25.14';
23
-
24
- function detectRuntime(): string {
25
- const g = globalThis as unknown as {
26
- Bun?: { version: string };
27
- Deno?: { version?: { deno?: string } };
28
- };
29
- if (g.Bun?.version) return `bun-${g.Bun.version}`;
30
- if (g.Deno?.version?.deno) return `deno-${g.Deno.version.deno}`;
31
- if (typeof process !== 'undefined' && process.versions?.node) {
32
- return `node-${process.versions.node}`;
33
- }
34
- return 'browser';
21
+ export const SDK_VERSION = '1.0.0-rc.2';
22
+ function detectRuntime() {
23
+ const g = globalThis;
24
+ if (g.Bun?.version)
25
+ return `bun-${g.Bun.version}`;
26
+ if (g.Deno?.version?.deno)
27
+ return `deno-${g.Deno.version.deno}`;
28
+ if (typeof process !== 'undefined' && process.versions?.node) {
29
+ return `node-${process.versions.node}`;
30
+ }
31
+ return 'browser';
35
32
  }
36
-
37
- function detectOs(): string {
38
- if (typeof process !== 'undefined' && process.platform) {
39
- return `${process.platform}-${process.arch}`;
40
- }
41
- return 'browser';
33
+ function detectOs() {
34
+ if (typeof process !== 'undefined' && process.platform) {
35
+ return `${process.platform}-${process.arch}`;
36
+ }
37
+ return 'browser';
42
38
  }
43
-
44
- export function buildTelemetryHeaders(): Record<string, string> {
45
- const runtime = detectRuntime();
46
- const os = detectOs();
47
- return {
48
- 'X-Eigenpal-Sdk': SDK_LANGUAGE,
49
- 'X-Eigenpal-Sdk-Version': SDK_VERSION,
50
- 'X-Eigenpal-Sdk-Runtime': runtime,
51
- 'X-Eigenpal-Sdk-Os': os,
52
- 'User-Agent': `eigenpal-sdk-typescript/${SDK_VERSION} (${runtime}; ${os})`,
53
- };
39
+ export function buildTelemetryHeaders() {
40
+ const runtime = detectRuntime();
41
+ const os = detectOs();
42
+ return {
43
+ 'X-Eigenpal-Sdk': SDK_LANGUAGE,
44
+ 'X-Eigenpal-Sdk-Version': SDK_VERSION,
45
+ 'X-Eigenpal-Sdk-Runtime': runtime,
46
+ 'X-Eigenpal-Sdk-Os': os,
47
+ 'User-Agent': `eigenpal-sdk-typescript/${SDK_VERSION} (${runtime}; ${os})`,
48
+ };
54
49
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `files.upload`: the upload protocol (multipart form, presigned PUT,
3
+ * presigned multipart, app-chunked), every step an operation of the table.
4
+ * Hand-written; moved from 0.x `resources/files.ts`.
5
+ */
6
+ import type { Core } from './core.js';
7
+ import type { File as UploadedFile } from './generated/types.gen.js';
8
+ import { type FileInput } from './lib/files.js';
9
+ type SignalOptions = {
10
+ signal?: AbortSignal;
11
+ };
12
+ export type UploadOptions = SignalOptions & {
13
+ /** Required only when `file` is a nameless Blob. */
14
+ filename?: string;
15
+ /**
16
+ * Tenant-scoped idempotency key for upload-session creation. Generated when
17
+ * omitted so SDK retries of a lost create response reuse the same reservation.
18
+ */
19
+ idempotencyKey?: string;
20
+ /**
21
+ * Optional lifecycle marker. Pass `run_input` for automatic `client.run`
22
+ * pre-uploads so the server can retain them for retries and reap them after 24 hours.
23
+ * Explicit `files.upload` callers should omit this (durable reusable file).
24
+ */
25
+ purpose?: 'run_input';
26
+ onProgress?: (uploadedBytes: number, totalBytes: number) => void;
27
+ };
28
+ export type UploadableFile = FileInput | Uint8Array | ArrayBuffer;
29
+ /** Upload one file and answer its record; pass `{ $fileId: file.id }` as a run input. */
30
+ export declare function uploadFile(core: Core, file: UploadableFile, options?: UploadOptions): Promise<UploadedFile>;
31
+ export {};
@@ -0,0 +1,286 @@
1
+ import { EigenPalError } from './errors.js';
2
+ import { byteViewToArrayBuffer, destroyUnreadNodeReadable, ensureNodeReadableFullySent, isNodeReadableStream, toPutBody, } from './lib/fetch-body.js';
3
+ import { isFileDescriptor, isFileInput, isPathFileInput, isStreamFactoryFileInput, resolveFileBlob, statUploadSize, } from './lib/files.js';
4
+ import { annotateHttpChunkedCompleteFailure, ChunkUploadHttpError, shouldAbortHttpChunkedUploadSession, uploadHttpChunks, } from './lib/upload-app-chunked.js';
5
+ import { annotateMultipartCompleteFailure, annotatePresignedPutCompleteFailure, filterStorageHeaders, PartUploadHttpError, shouldAbortMultipartUploadSession, shouldAbortPresignedPutUploadSession, uploadPresignedMultipartParts, } from './lib/upload-presigned-multipart.js';
6
+ const UPLOAD_ABORT_CLEANUP_TIMEOUT_MS = 10_000;
7
+ function newIdempotencyKey() {
8
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
9
+ return crypto.randomUUID();
10
+ }
11
+ return `upload_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
12
+ }
13
+ /** Upload one file and answer its record; pass `{ $fileId: file.id }` as a run input. */
14
+ export async function uploadFile(core, file, options = {}) {
15
+ const signal = options.signal;
16
+ const source = await resolveUploadableSource(file, options.filename);
17
+ const negotiation = await core.request('files.uploads.create', {
18
+ body: {
19
+ filename: source.filename,
20
+ contentType: source.contentType,
21
+ size: source.size,
22
+ idempotencyKey: options.idempotencyKey ?? newIdempotencyKey(),
23
+ ...(options.purpose ? { purpose: options.purpose } : {}),
24
+ },
25
+ signal,
26
+ });
27
+ const complete = (uploadId) => core.request('files.uploads.complete', { path: { uploadId }, body: {}, signal });
28
+ const abort = (uploadId) => core
29
+ .request('files.uploads.abort', {
30
+ path: { uploadId },
31
+ signal: AbortSignal.timeout(UPLOAD_ABORT_CLEANUP_TIMEOUT_MS),
32
+ })
33
+ .catch(() => undefined);
34
+ if (negotiation.transport === 'presigned_multipart') {
35
+ if (!source.replayable)
36
+ throw new Error(ONE_SHOT('multipart'));
37
+ const uploadId = negotiation.uploadId;
38
+ let partsReady = false;
39
+ try {
40
+ await uploadPresignedMultipartParts({
41
+ partCount: negotiation.partCount,
42
+ partSizeBytes: negotiation.partSizeBytes,
43
+ totalSize: source.size,
44
+ signal,
45
+ onProgress: options.onProgress,
46
+ listParts: async () => (await core.request('files.uploads.parts.list', {
47
+ path: { uploadId },
48
+ signal,
49
+ })).parts ?? [],
50
+ presignPart: (partNumber) => core.request('files.uploads.parts.presign', { path: { uploadId }, body: { partNumber }, signal }),
51
+ putPart: async ({ url, headers, start, length }) => {
52
+ const body = await source.openPart(start, length);
53
+ const response = await putStorage(url, headers, body, signal, source.stripContentLength, length);
54
+ if (!response.ok)
55
+ throw new PartUploadHttpError(response.status);
56
+ },
57
+ });
58
+ partsReady = true;
59
+ return await complete(uploadId);
60
+ }
61
+ catch (error) {
62
+ if (shouldAbortMultipartUploadSession({ partsReady })) {
63
+ await abort(uploadId);
64
+ throw error;
65
+ }
66
+ throw annotateMultipartCompleteFailure(uploadId, error);
67
+ }
68
+ }
69
+ if (negotiation.transport === 'http_chunked') {
70
+ if (!source.replayable)
71
+ throw new Error(ONE_SHOT('chunked'));
72
+ const uploadId = negotiation.uploadId;
73
+ let chunksReady = false;
74
+ try {
75
+ await uploadHttpChunks({
76
+ chunkCount: negotiation.chunkCount,
77
+ chunkSizeBytes: negotiation.chunkSizeBytes,
78
+ totalSize: source.size,
79
+ signal,
80
+ onProgress: options.onProgress,
81
+ putChunk: async ({ chunkIndex, start, length }) => {
82
+ const body = await source.openPart(start, length);
83
+ try {
84
+ await core.request('files.uploads.chunks.put', {
85
+ path: { uploadId, chunkIndex: String(chunkIndex) },
86
+ body: await toBlob(body),
87
+ headers: { 'Content-Type': 'application/octet-stream' },
88
+ signal,
89
+ });
90
+ }
91
+ catch (error) {
92
+ if (error instanceof EigenPalError)
93
+ throw new ChunkUploadHttpError(error.status);
94
+ throw error;
95
+ }
96
+ },
97
+ });
98
+ chunksReady = true;
99
+ return await complete(uploadId);
100
+ }
101
+ catch (error) {
102
+ if (shouldAbortHttpChunkedUploadSession({ chunksReady })) {
103
+ await abort(uploadId);
104
+ throw error;
105
+ }
106
+ throw annotateHttpChunkedCompleteFailure(uploadId, error);
107
+ }
108
+ }
109
+ if (negotiation.transport === 'presigned_put') {
110
+ const uploadId = negotiation.uploadId;
111
+ let putReady = false;
112
+ try {
113
+ const body = await source.openPart(0, source.size);
114
+ const response = await putStorage(negotiation.url, (negotiation.headers ?? {}), body, signal, source.stripContentLength, source.size);
115
+ if (!response.ok)
116
+ throw new Error(`Storage upload failed (${response.status}); retry the upload`);
117
+ putReady = true;
118
+ options.onProgress?.(source.size, source.size);
119
+ }
120
+ catch (error) {
121
+ if (shouldAbortPresignedPutUploadSession({ putReady }))
122
+ await abort(uploadId);
123
+ throw error;
124
+ }
125
+ try {
126
+ return await complete(uploadId);
127
+ }
128
+ catch (error) {
129
+ throw annotatePresignedPutCompleteFailure(uploadId, error);
130
+ }
131
+ }
132
+ // `multipart`: small files go as one form to POST /v1/files.
133
+ const form = new FormData();
134
+ form.append('file', await source.asBlob(), source.filename);
135
+ if (options.purpose)
136
+ form.append('purpose', options.purpose);
137
+ const uploaded = await core.request('files.create', { body: form, signal });
138
+ options.onProgress?.(source.size, source.size);
139
+ return uploaded;
140
+ }
141
+ const ONE_SHOT = (kind) => `Cannot resume a ${kind} upload from a one-shot stream. Pass a file path, Blob, or a reusable stream factory.`;
142
+ async function toBlob(body) {
143
+ if (body instanceof Blob || body instanceof ArrayBuffer)
144
+ return body;
145
+ return new Response(body).blob();
146
+ }
147
+ async function resolveUploadableSource(file, filenameOption) {
148
+ if (file instanceof Uint8Array) {
149
+ const filename = filenameOption || 'file';
150
+ return {
151
+ filename,
152
+ contentType: 'application/octet-stream',
153
+ size: file.byteLength,
154
+ replayable: true,
155
+ stripContentLength: false,
156
+ openPart: async (start, length) => byteViewToArrayBuffer(file.subarray(start, start + length)),
157
+ asBlob: async () => new Blob([file]),
158
+ };
159
+ }
160
+ if (file instanceof ArrayBuffer) {
161
+ const filename = filenameOption || 'file';
162
+ const bytes = new Uint8Array(file);
163
+ return {
164
+ filename,
165
+ contentType: 'application/octet-stream',
166
+ size: bytes.byteLength,
167
+ replayable: true,
168
+ stripContentLength: false,
169
+ openPart: async (start, length) => byteViewToArrayBuffer(bytes.subarray(start, start + length)),
170
+ asBlob: async () => new Blob([bytes]),
171
+ };
172
+ }
173
+ if (!isFileInput(file)) {
174
+ throw new Error('filename is required when uploading a Blob');
175
+ }
176
+ if (typeof Blob !== 'undefined' && file instanceof Blob) {
177
+ const filename = filenameOption ??
178
+ (typeof File !== 'undefined' && file instanceof File ? file.name : undefined);
179
+ if (!filename)
180
+ throw new Error('filename is required when uploading a Blob');
181
+ return {
182
+ filename,
183
+ contentType: file.type || 'application/octet-stream',
184
+ size: file.size,
185
+ replayable: true,
186
+ stripContentLength: true,
187
+ openPart: async (start, length) => file.slice(start, start + length),
188
+ asBlob: async () => file,
189
+ };
190
+ }
191
+ if (isPathFileInput(file) || hasNodePath(file)) {
192
+ const filePath = isPathFileInput(file) ? file.path : file.path;
193
+ const meta = await statUploadSize(file);
194
+ const filename = filenameOption || meta.filename;
195
+ return {
196
+ filename,
197
+ contentType: meta.contentType,
198
+ size: meta.size,
199
+ replayable: true,
200
+ stripContentLength: false,
201
+ openPart: async (start, length) => {
202
+ if (length === 0)
203
+ return byteViewToArrayBuffer(new Uint8Array());
204
+ const { createReadStream } = await import('node:fs');
205
+ return toPutBody(createReadStream(filePath, {
206
+ start,
207
+ end: start + length - 1,
208
+ }));
209
+ },
210
+ asBlob: async () => (await resolveFileBlob(file)).blob,
211
+ };
212
+ }
213
+ if (isStreamFactoryFileInput(file)) {
214
+ return {
215
+ filename: filenameOption || file.filename,
216
+ contentType: file.mimeType || 'application/octet-stream',
217
+ size: file.size,
218
+ replayable: true,
219
+ stripContentLength: false,
220
+ openPart: async (start, length) => {
221
+ const part = file.open(start, length);
222
+ if (part instanceof Uint8Array)
223
+ return byteViewToArrayBuffer(part);
224
+ if (isNodeReadableStream(part))
225
+ return toPutBody(part);
226
+ return part;
227
+ },
228
+ asBlob: async () => (await resolveFileBlob(file)).blob,
229
+ };
230
+ }
231
+ if (isFileDescriptor(file)) {
232
+ const filename = filenameOption || file.filename;
233
+ const type = file.mimeType || 'application/octet-stream';
234
+ if (typeof Blob !== 'undefined' && file.content instanceof Blob) {
235
+ const blob = file.content;
236
+ return {
237
+ filename,
238
+ contentType: type,
239
+ size: blob.size,
240
+ replayable: true,
241
+ stripContentLength: true,
242
+ openPart: async (start, length) => blob.slice(start, start + length),
243
+ asBlob: async () => blob,
244
+ };
245
+ }
246
+ const bytes = file.content instanceof ArrayBuffer
247
+ ? new Uint8Array(file.content)
248
+ : new Uint8Array(file.content.buffer, file.content.byteOffset, file.content.byteLength);
249
+ return {
250
+ filename,
251
+ contentType: type,
252
+ size: bytes.byteLength,
253
+ replayable: true,
254
+ stripContentLength: false,
255
+ openPart: async (start, length) => byteViewToArrayBuffer(bytes.subarray(start, start + length)),
256
+ asBlob: async () => new Blob([bytes], { type }),
257
+ };
258
+ }
259
+ throw new Error('Cannot upload a one-shot stream. Pass a file path, Blob, or a reusable stream factory.');
260
+ }
261
+ function hasNodePath(file) {
262
+ return typeof file.path === 'string';
263
+ }
264
+ async function putStorage(url, headers, body, signal, stripContentLength, expectedByteLength) {
265
+ const stream = isNodeReadableStream(body);
266
+ const init = {
267
+ method: 'PUT',
268
+ headers: filterStorageHeaders(headers, stripContentLength && !stream),
269
+ body,
270
+ signal,
271
+ ...(stream ? { duplex: 'half' } : {}),
272
+ };
273
+ let response;
274
+ try {
275
+ response = await fetch(url, init);
276
+ }
277
+ catch (error) {
278
+ if (stream)
279
+ destroyUnreadNodeReadable(body);
280
+ throw error;
281
+ }
282
+ if (stream) {
283
+ await ensureNodeReadableFullySent(body, expectedByteLength);
284
+ }
285
+ return response;
286
+ }
@@ -6,7 +6,7 @@
6
6
  * so abort-safety rules (never abort once storage holds the bytes) live in
7
7
  * exactly one place.
8
8
  */
9
- export * from './lib/fetch-body';
10
- export * from './lib/upload-app-chunked';
11
- export * from './lib/upload-limits';
12
- export * from './lib/upload-presigned-multipart';
9
+ export * from './lib/fetch-body.js';
10
+ export * from './lib/upload-app-chunked.js';
11
+ export * from './lib/upload-limits.js';
12
+ export * from './lib/upload-presigned-multipart.js';
package/dist/upload.js ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@eigenpal/sdk/upload`: the canonical upload protocol helpers (presigned
3
+ * multipart, app-chunked, presigned PUT, multipart body budget).
4
+ *
5
+ * The EigenPal CLI and app import these instead of keeping their own copies,
6
+ * so abort-safety rules (never abort once storage holds the bytes) live in
7
+ * exactly one place.
8
+ */
9
+ export * from './lib/fetch-body.js';
10
+ export * from './lib/upload-app-chunked.js';
11
+ export * from './lib/upload-limits.js';
12
+ export * from './lib/upload-presigned-multipart.js';