@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,94 @@
1
+ /**
2
+ * Client protocol for `http_chunked` file uploads.
3
+ *
4
+ * Sequential PUTs of byte ranges, then POST complete. Resume listing is not
5
+ * implemented — a retry re-sends from chunk 0. The server accepts idempotent
6
+ * overwrite of an already-staged index.
7
+ */
8
+ import { isAbortError, isTransientHttpStatus, sleep } from './upload-presigned-multipart.js';
9
+ export const HTTP_CHUNKED_MAX_RETRIES = 4;
10
+ export const HTTP_CHUNKED_RETRY_BASE_MS = 250;
11
+ export function expectedHttpChunkByteLength(totalSize, chunkSizeBytes, chunkIndex, chunkCount) {
12
+ if (!Number.isInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= chunkCount) {
13
+ throw new Error(`chunkIndex must be an integer in [0, ${chunkCount})`);
14
+ }
15
+ if (totalSize === 0)
16
+ return 0;
17
+ if (chunkIndex < chunkCount - 1)
18
+ return chunkSizeBytes;
19
+ const remainder = totalSize % chunkSizeBytes;
20
+ return remainder === 0 ? chunkSizeBytes : remainder;
21
+ }
22
+ export function chunkByteOffset(chunkSizeBytes, chunkIndex) {
23
+ return chunkIndex * chunkSizeBytes;
24
+ }
25
+ export function shouldAbortHttpChunkedUploadSession(options) {
26
+ return !options.chunksReady;
27
+ }
28
+ export function httpChunkedCompleteRetryHint(uploadId) {
29
+ return `Uploaded chunks remain stored for ${uploadId}; retry complete and do not abort the session.`;
30
+ }
31
+ export function annotateHttpChunkedCompleteFailure(uploadId, error) {
32
+ const hint = httpChunkedCompleteRetryHint(uploadId);
33
+ if (error instanceof Error) {
34
+ if (!error.message.includes('retry complete')) {
35
+ error.message = `${error.message} ${hint}`;
36
+ }
37
+ return error;
38
+ }
39
+ return new Error(`${String(error)} ${hint}`);
40
+ }
41
+ export class ChunkUploadHttpError extends Error {
42
+ status;
43
+ constructor(status) {
44
+ super(`Chunk upload failed (${status})`);
45
+ this.status = status;
46
+ this.name = 'ChunkUploadHttpError';
47
+ }
48
+ }
49
+ function isRetryableChunkError(error, signal) {
50
+ if (signal?.aborted)
51
+ return false;
52
+ if (isAbortError(error))
53
+ return false;
54
+ if (error instanceof ChunkUploadHttpError)
55
+ return isTransientHttpStatus(error.status);
56
+ return true;
57
+ }
58
+ function abortError(signal) {
59
+ if (signal?.reason instanceof Error)
60
+ return signal.reason;
61
+ return typeof DOMException !== 'undefined'
62
+ ? new DOMException('Upload aborted', 'AbortError')
63
+ : Object.assign(new Error('Upload aborted'), { name: 'AbortError' });
64
+ }
65
+ export async function uploadHttpChunks(options) {
66
+ let uploadedBytes = 0;
67
+ for (let chunkIndex = 0; chunkIndex < options.chunkCount; chunkIndex++) {
68
+ if (options.signal?.aborted)
69
+ throw abortError(options.signal);
70
+ const length = expectedHttpChunkByteLength(options.totalSize, options.chunkSizeBytes, chunkIndex, options.chunkCount);
71
+ const start = chunkByteOffset(options.chunkSizeBytes, chunkIndex);
72
+ let lastError;
73
+ for (let attempt = 0; attempt <= HTTP_CHUNKED_MAX_RETRIES; attempt++) {
74
+ if (options.signal?.aborted)
75
+ throw abortError(options.signal);
76
+ try {
77
+ await options.putChunk({ chunkIndex, start, length });
78
+ uploadedBytes += length;
79
+ options.onProgress?.(uploadedBytes, options.totalSize);
80
+ lastError = undefined;
81
+ break;
82
+ }
83
+ catch (error) {
84
+ lastError = error;
85
+ if (!isRetryableChunkError(error, options.signal) || attempt === HTTP_CHUNKED_MAX_RETRIES) {
86
+ throw error;
87
+ }
88
+ await sleep(HTTP_CHUNKED_RETRY_BASE_MS * 2 ** attempt, options.signal);
89
+ }
90
+ }
91
+ if (lastError)
92
+ throw lastError;
93
+ }
94
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Default to Vercel's ~4.5 MiB function body limit. Operators with a different
3
+ * ingress limit can override it; `null` keeps every run file on multipart.
4
+ */
5
+ export declare const DEFAULT_MULTIPART_MAX_BYTES: number;
6
+ /**
7
+ * Conservative allowance for multipart boundaries, `target` / `input` /
8
+ * `overrides` / `metadata` parts, and Content-Disposition headers.
9
+ */
10
+ export declare const MULTIPART_ENVELOPE_HEADROOM_BYTES: number;
11
+ /** Max aggregate file-content bytes that may ride in one multipart run request. */
12
+ export declare function multipartFileByteBudget(multipartMaxBytes?: number | null): number | null;
13
+ /**
14
+ * Choose which file positions must be pre-uploaded so remaining multipart file
15
+ * bytes plus envelope headroom stay under the configured multipart maximum.
16
+ *
17
+ * Uses positional identity so repeated values for the same field (CLI
18
+ * `--input-file field=...`) are budgeted independently. Prefers shedding the
19
+ * largest files first so smaller ones can stay on the single multipart
20
+ * round-trip when the aggregate still fits; ties go to the earlier position.
21
+ */
22
+ export declare function indicesRequiringPreUpload(files: ReadonlyArray<{
23
+ size: number;
24
+ }>, multipartMaxBytes?: number | null): Set<number>;
25
+ /**
26
+ * Field-keyed variant of {@link indicesRequiringPreUpload} for inputs where
27
+ * each key appears once. Ties between equal sizes go to the lexically first key.
28
+ */
29
+ export declare function keysRequiringPreUpload(files: ReadonlyArray<{
30
+ key: string;
31
+ size: number;
32
+ }>, multipartMaxBytes?: number | null): Set<string>;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Default to Vercel's ~4.5 MiB function body limit. Operators with a different
3
+ * ingress limit can override it; `null` keeps every run file on multipart.
4
+ */
5
+ export const DEFAULT_MULTIPART_MAX_BYTES = Math.floor(4.5 * 1024 * 1024);
6
+ /**
7
+ * Conservative allowance for multipart boundaries, `target` / `input` /
8
+ * `overrides` / `metadata` parts, and Content-Disposition headers.
9
+ */
10
+ export const MULTIPART_ENVELOPE_HEADROOM_BYTES = 256 * 1024;
11
+ /** Max aggregate file-content bytes that may ride in one multipart run request. */
12
+ export function multipartFileByteBudget(multipartMaxBytes = DEFAULT_MULTIPART_MAX_BYTES) {
13
+ if (multipartMaxBytes === null)
14
+ return null;
15
+ return Math.max(0, multipartMaxBytes - MULTIPART_ENVELOPE_HEADROOM_BYTES);
16
+ }
17
+ /**
18
+ * Choose which file positions must be pre-uploaded so remaining multipart file
19
+ * bytes plus envelope headroom stay under the configured multipart maximum.
20
+ *
21
+ * Uses positional identity so repeated values for the same field (CLI
22
+ * `--input-file field=...`) are budgeted independently. Prefers shedding the
23
+ * largest files first so smaller ones can stay on the single multipart
24
+ * round-trip when the aggregate still fits; ties go to the earlier position.
25
+ */
26
+ export function indicesRequiringPreUpload(files, multipartMaxBytes = DEFAULT_MULTIPART_MAX_BYTES) {
27
+ const budget = multipartFileByteBudget(multipartMaxBytes);
28
+ const toPreUpload = new Set();
29
+ if (budget === null)
30
+ return toPreUpload;
31
+ files.forEach((file, index) => {
32
+ if (file.size > budget)
33
+ toPreUpload.add(index);
34
+ });
35
+ let multipartTotal = 0;
36
+ files.forEach((file, index) => {
37
+ if (!toPreUpload.has(index))
38
+ multipartTotal += file.size;
39
+ });
40
+ const candidates = files
41
+ .map((file, index) => ({ size: file.size, index }))
42
+ .filter(({ index }) => !toPreUpload.has(index))
43
+ .sort((a, b) => b.size - a.size || a.index - b.index);
44
+ for (const { size, index } of candidates) {
45
+ if (multipartTotal <= budget)
46
+ break;
47
+ toPreUpload.add(index);
48
+ multipartTotal -= size;
49
+ }
50
+ return toPreUpload;
51
+ }
52
+ /**
53
+ * Field-keyed variant of {@link indicesRequiringPreUpload} for inputs where
54
+ * each key appears once. Ties between equal sizes go to the lexically first key.
55
+ */
56
+ export function keysRequiringPreUpload(files, multipartMaxBytes = DEFAULT_MULTIPART_MAX_BYTES) {
57
+ const ordered = files.slice().sort((a, b) => a.key.localeCompare(b.key));
58
+ const indices = indicesRequiringPreUpload(ordered, multipartMaxBytes);
59
+ return new Set([...indices].map((index) => ordered[index].key));
60
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Client protocol for `presigned_multipart` file uploads.
3
+ * Part math matches the server session; ETags are never trusted locally.
4
+ */
5
+ export declare const MULTIPART_UPLOAD_CONCURRENCY = 4;
6
+ export declare const MULTIPART_PART_MAX_RETRIES = 4;
7
+ export declare const MULTIPART_PART_RETRY_BASE_MS = 250;
8
+ export type ListedUploadPart = {
9
+ partNumber: number;
10
+ size?: number;
11
+ etag: string;
12
+ };
13
+ export type PresignedUploadPart = {
14
+ url: string;
15
+ headers?: Record<string, string>;
16
+ partSizeBytes: number;
17
+ };
18
+ export declare function expectedPartByteLength(totalSize: number, partSizeBytes: number, partNumber: number, partCount: number): number;
19
+ export declare function partByteOffset(partSizeBytes: number, partNumber: number): number;
20
+ export declare function isTransientHttpStatus(status: number): boolean;
21
+ export declare function filterStorageHeaders(headers: Record<string, string> | undefined, stripContentLength: boolean): Record<string, string>;
22
+ export declare function partIsAuthoritativelyComplete(listed: ReadonlyArray<ListedUploadPart>, partNumber: number, expectedSize: number): boolean;
23
+ export declare class PartUploadHttpError extends Error {
24
+ readonly status: number;
25
+ constructor(status: number);
26
+ }
27
+ export declare function isAbortError(error: unknown): boolean;
28
+ /**
29
+ * Abort leftover MPU state only while parts are not yet authoritative.
30
+ *
31
+ * After ListParts shows every expected part, POST complete is idempotent.
32
+ * 409/429/timeout/lost responses must not abort — that would delete GiB of
33
+ * uploaded parts and can race a complete that already succeeded server-side.
34
+ * Caller cancellation and unrecoverable part PUT/API failures still abort
35
+ * because `partsReady` is false in those cases.
36
+ */
37
+ export declare function shouldAbortMultipartUploadSession(options: {
38
+ partsReady: boolean;
39
+ }): boolean;
40
+ /**
41
+ * Abort leftover presigned-PUT state only while storage PUT is not yet authoritative.
42
+ *
43
+ * After a successful storage PUT, POST complete is idempotent. 409/429/timeout/lost
44
+ * responses must not abort — that would delete a recoverable up-to-4-GiB object and
45
+ * can race a complete that already succeeded server-side. Caller cancellation and
46
+ * unrecoverable PUT failures still abort because `putReady` is false in those cases.
47
+ */
48
+ export declare function shouldAbortPresignedPutUploadSession(options: {
49
+ putReady: boolean;
50
+ }): boolean;
51
+ export declare function multipartCompleteRetryHint(uploadId: string): string;
52
+ export declare function presignedPutCompleteRetryHint(uploadId: string): string;
53
+ export declare function annotateMultipartCompleteFailure(uploadId: string, error: unknown): unknown;
54
+ export declare function annotatePresignedPutCompleteFailure(uploadId: string, error: unknown): unknown;
55
+ export declare function isRetryablePartError(error: unknown, signal?: AbortSignal): boolean;
56
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
57
+ export declare function mapPool<T>(items: readonly T[], concurrency: number, signal: AbortSignal | undefined, worker: (item: T) => Promise<void>): Promise<void>;
58
+ export declare function uploadPresignedMultipartParts(options: {
59
+ partCount: number;
60
+ partSizeBytes: number;
61
+ totalSize: number;
62
+ signal?: AbortSignal;
63
+ concurrency?: number;
64
+ onProgress?: (uploadedBytes: number, totalBytes: number) => void;
65
+ listParts: () => Promise<ReadonlyArray<ListedUploadPart>>;
66
+ presignPart: (partNumber: number) => Promise<PresignedUploadPart>;
67
+ putPart: (args: {
68
+ url: string;
69
+ headers: Record<string, string>;
70
+ partNumber: number;
71
+ start: number;
72
+ length: number;
73
+ }) => Promise<void>;
74
+ }): Promise<void>;
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Client protocol for `presigned_multipart` file uploads.
3
+ * Part math matches the server session; ETags are never trusted locally.
4
+ */
5
+ export const MULTIPART_UPLOAD_CONCURRENCY = 4;
6
+ export const MULTIPART_PART_MAX_RETRIES = 4;
7
+ export const MULTIPART_PART_RETRY_BASE_MS = 250;
8
+ export function expectedPartByteLength(totalSize, partSizeBytes, partNumber, partCount) {
9
+ if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > partCount) {
10
+ throw new Error(`partNumber must be an integer in [1, ${partCount}]`);
11
+ }
12
+ if (totalSize === 0)
13
+ return 0;
14
+ if (partNumber < partCount)
15
+ return partSizeBytes;
16
+ const remainder = totalSize % partSizeBytes;
17
+ return remainder === 0 ? partSizeBytes : remainder;
18
+ }
19
+ export function partByteOffset(partSizeBytes, partNumber) {
20
+ return (partNumber - 1) * partSizeBytes;
21
+ }
22
+ export function isTransientHttpStatus(status) {
23
+ return status === 408 || status === 429 || (status >= 500 && status <= 599);
24
+ }
25
+ export function filterStorageHeaders(headers, stripContentLength) {
26
+ return Object.fromEntries(Object.entries(headers ?? {}).filter(([name]) => stripContentLength ? name.toLowerCase() !== 'content-length' : true));
27
+ }
28
+ export function partIsAuthoritativelyComplete(listed, partNumber, expectedSize) {
29
+ const found = listed.find((part) => part.partNumber === partNumber);
30
+ if (!found)
31
+ return false;
32
+ // Server complete rejects missing sizes. Treat them as incomplete so resume
33
+ // re-uploads instead of skipping a part the API cannot finalize.
34
+ return found.size === expectedSize;
35
+ }
36
+ export class PartUploadHttpError extends Error {
37
+ status;
38
+ constructor(status) {
39
+ super(`Storage part upload failed (${status})`);
40
+ this.status = status;
41
+ this.name = 'PartUploadHttpError';
42
+ }
43
+ }
44
+ export function isAbortError(error) {
45
+ return ((error instanceof Error && error.name === 'AbortError') ||
46
+ (typeof DOMException !== 'undefined' &&
47
+ error instanceof DOMException &&
48
+ error.name === 'AbortError'));
49
+ }
50
+ /**
51
+ * Abort leftover MPU state only while parts are not yet authoritative.
52
+ *
53
+ * After ListParts shows every expected part, POST complete is idempotent.
54
+ * 409/429/timeout/lost responses must not abort — that would delete GiB of
55
+ * uploaded parts and can race a complete that already succeeded server-side.
56
+ * Caller cancellation and unrecoverable part PUT/API failures still abort
57
+ * because `partsReady` is false in those cases.
58
+ */
59
+ export function shouldAbortMultipartUploadSession(options) {
60
+ return !options.partsReady;
61
+ }
62
+ /**
63
+ * Abort leftover presigned-PUT state only while storage PUT is not yet authoritative.
64
+ *
65
+ * After a successful storage PUT, POST complete is idempotent. 409/429/timeout/lost
66
+ * responses must not abort — that would delete a recoverable up-to-4-GiB object and
67
+ * can race a complete that already succeeded server-side. Caller cancellation and
68
+ * unrecoverable PUT failures still abort because `putReady` is false in those cases.
69
+ */
70
+ export function shouldAbortPresignedPutUploadSession(options) {
71
+ return !options.putReady;
72
+ }
73
+ export function multipartCompleteRetryHint(uploadId) {
74
+ return `Uploaded parts remain stored for ${uploadId}; retry complete and do not abort the session.`;
75
+ }
76
+ export function presignedPutCompleteRetryHint(uploadId) {
77
+ return `Uploaded object remains stored for ${uploadId}; retry complete and do not abort the session.`;
78
+ }
79
+ export function annotateMultipartCompleteFailure(uploadId, error) {
80
+ return annotateUploadCompleteFailure(multipartCompleteRetryHint(uploadId), error);
81
+ }
82
+ export function annotatePresignedPutCompleteFailure(uploadId, error) {
83
+ return annotateUploadCompleteFailure(presignedPutCompleteRetryHint(uploadId), error);
84
+ }
85
+ function annotateUploadCompleteFailure(hint, error) {
86
+ if (error instanceof Error) {
87
+ if (!error.message.includes('retry complete')) {
88
+ error.message = `${error.message} ${hint}`;
89
+ }
90
+ return error;
91
+ }
92
+ return new Error(`${String(error)} ${hint}`);
93
+ }
94
+ export function isRetryablePartError(error, signal) {
95
+ if (signal?.aborted)
96
+ return false;
97
+ if (isAbortError(error))
98
+ return false;
99
+ if (error instanceof PartUploadHttpError)
100
+ return isTransientHttpStatus(error.status);
101
+ return true;
102
+ }
103
+ export async function sleep(ms, signal) {
104
+ if (signal?.aborted)
105
+ throw abortError(signal);
106
+ await new Promise((resolve, reject) => {
107
+ const timer = setTimeout(resolve, ms);
108
+ const onAbort = () => {
109
+ clearTimeout(timer);
110
+ reject(abortError(signal));
111
+ };
112
+ signal?.addEventListener('abort', onAbort, { once: true });
113
+ });
114
+ }
115
+ function abortError(signal) {
116
+ if (signal?.reason instanceof Error)
117
+ return signal.reason;
118
+ return typeof DOMException !== 'undefined'
119
+ ? new DOMException('Upload aborted', 'AbortError')
120
+ : Object.assign(new Error('Upload aborted'), { name: 'AbortError' });
121
+ }
122
+ export async function mapPool(items, concurrency, signal, worker) {
123
+ if (items.length === 0)
124
+ return;
125
+ let cursor = 0;
126
+ let firstError;
127
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, concurrency), items.length) }, async () => {
128
+ while (firstError == null) {
129
+ if (signal?.aborted)
130
+ throw abortError(signal);
131
+ const index = cursor++;
132
+ if (index >= items.length)
133
+ return;
134
+ try {
135
+ await worker(items[index]);
136
+ }
137
+ catch (error) {
138
+ firstError ??= error;
139
+ }
140
+ }
141
+ }));
142
+ if (firstError)
143
+ throw firstError;
144
+ }
145
+ export async function uploadPresignedMultipartParts(options) {
146
+ const concurrency = options.concurrency ?? MULTIPART_UPLOAD_CONCURRENCY;
147
+ let uploadedBytes = 0;
148
+ const credited = new Set();
149
+ const credit = (partNumber, length) => {
150
+ if (credited.has(partNumber))
151
+ return;
152
+ credited.add(partNumber);
153
+ uploadedBytes += length;
154
+ options.onProgress?.(uploadedBytes, options.totalSize);
155
+ };
156
+ const pendingPartNumbers = async () => {
157
+ const listed = await options.listParts();
158
+ const pending = [];
159
+ for (let partNumber = 1; partNumber <= options.partCount; partNumber++) {
160
+ const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
161
+ if (partIsAuthoritativelyComplete(listed, partNumber, length)) {
162
+ credit(partNumber, length);
163
+ continue;
164
+ }
165
+ pending.push(partNumber);
166
+ }
167
+ return pending;
168
+ };
169
+ const uploadOne = async (partNumber) => {
170
+ const length = expectedPartByteLength(options.totalSize, options.partSizeBytes, partNumber, options.partCount);
171
+ const start = partByteOffset(options.partSizeBytes, partNumber);
172
+ let lastError;
173
+ for (let attempt = 0; attempt <= MULTIPART_PART_MAX_RETRIES; attempt++) {
174
+ if (options.signal?.aborted)
175
+ throw abortError(options.signal);
176
+ try {
177
+ const signed = await options.presignPart(partNumber);
178
+ const partLength = Number.isInteger(signed.partSizeBytes) ? signed.partSizeBytes : length;
179
+ await options.putPart({
180
+ url: signed.url,
181
+ headers: signed.headers ?? {},
182
+ partNumber,
183
+ start,
184
+ length: partLength,
185
+ });
186
+ credit(partNumber, length);
187
+ return;
188
+ }
189
+ catch (error) {
190
+ lastError = error;
191
+ if (!isRetryablePartError(error, options.signal) ||
192
+ attempt === MULTIPART_PART_MAX_RETRIES) {
193
+ throw error;
194
+ }
195
+ await sleep(MULTIPART_PART_RETRY_BASE_MS * 2 ** attempt, options.signal);
196
+ }
197
+ }
198
+ throw lastError;
199
+ };
200
+ let pending = await pendingPartNumbers();
201
+ if (pending.length > 0) {
202
+ await mapPool(pending, concurrency, options.signal, uploadOne);
203
+ }
204
+ pending = await pendingPartNumbers();
205
+ if (pending.length > 0) {
206
+ await mapPool(pending, concurrency, options.signal, uploadOne);
207
+ pending = await pendingPartNumbers();
208
+ }
209
+ if (pending.length > 0) {
210
+ throw new Error(`Upload incomplete: ${pending.length} part(s) missing from storage before complete`);
211
+ }
212
+ }
package/dist/page.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Lists answer one page, `{ items, nextCursor }`, whether the route pages by
3
+ * cursor or answers everything at once. Awaiting a list gives the page; iterating
4
+ * it with `for await` walks every item of every page (the CLI's `--all`).
5
+ */
6
+ export interface PageShape {
7
+ /** The key of the route's answer that holds the array. */
8
+ key: string;
9
+ paging: 'cursor' | 'none';
10
+ }
11
+ export interface Page<T, R = unknown> {
12
+ items: T[];
13
+ /** Pass as `cursor` for the next page; null on the last one. */
14
+ nextCursor: string | null;
15
+ /** The route's whole answer. */
16
+ raw: R;
17
+ }
18
+ type Fetch<R> = (cursor: string | undefined) => Promise<R>;
19
+ export declare function toPage<T, R>(shape: PageShape, body: R): Page<T, R>;
20
+ export declare class PagePromise<T, R = unknown> implements PromiseLike<Page<T, R>>, AsyncIterable<T> {
21
+ private readonly shape;
22
+ private readonly cursor;
23
+ private readonly fetchPage;
24
+ private first?;
25
+ constructor(shape: PageShape, cursor: string | undefined, fetchPage: Fetch<R>);
26
+ private load;
27
+ then<A = Page<T, R>, B = never>(onfulfilled?: ((value: Page<T, R>) => A | PromiseLike<A>) | null, onrejected?: ((reason: unknown) => B | PromiseLike<B>) | null): Promise<A | B>;
28
+ [Symbol.asyncIterator](): AsyncIterator<T>;
29
+ }
30
+ export {};
package/dist/page.js ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Lists answer one page, `{ items, nextCursor }`, whether the route pages by
3
+ * cursor or answers everything at once. Awaiting a list gives the page; iterating
4
+ * it with `for await` walks every item of every page (the CLI's `--all`).
5
+ */
6
+ export function toPage(shape, body) {
7
+ const record = (body ?? {});
8
+ const items = record[shape.key] ?? [];
9
+ const nextCursor = shape.paging === 'cursor' ? (record.nextCursor ?? null) : null;
10
+ return { items, nextCursor, raw: body };
11
+ }
12
+ export class PagePromise {
13
+ shape;
14
+ cursor;
15
+ fetchPage;
16
+ first;
17
+ constructor(shape, cursor, fetchPage) {
18
+ this.shape = shape;
19
+ this.cursor = cursor;
20
+ this.fetchPage = fetchPage;
21
+ }
22
+ load(cursor) {
23
+ return this.fetchPage(cursor).then((body) => toPage(this.shape, body));
24
+ }
25
+ then(onfulfilled, onrejected) {
26
+ this.first ??= this.load(this.cursor);
27
+ return this.first.then(onfulfilled, onrejected);
28
+ }
29
+ async *[Symbol.asyncIterator]() {
30
+ let page = await this.then((p) => p);
31
+ for (;;) {
32
+ yield* page.items;
33
+ if (!page.nextCursor)
34
+ return;
35
+ page = await this.load(page.nextCursor);
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,85 @@
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 { type Core } from './core.js';
7
+ import { DatasetsReviewsResource as DatasetsReviewsBase, EmailServersResource as EmailServersBase, ExperimentsResource as ExperimentsBase, FilesResource as FilesBase, RunsResource as RunsBase, TemplatesResource as TemplatesBase, type ResourceImpls } from './generated/resources.gen.js';
8
+ import type { DatasetReviewDetail, EmailServer, EmailServerCreateBody, ExperimentDetail, RunEvent, Template, File as UploadedFile } from './generated/types.gen.js';
9
+ import type { FileInput } from './lib/files.js';
10
+ import { type UploadableFile, type UploadOptions } from './upload-file.js';
11
+ type Signal = {
12
+ signal?: AbortSignal;
13
+ };
14
+ type Wait = {
15
+ wait?: boolean;
16
+ timeoutMs?: number;
17
+ };
18
+ /** Poll `read` until `done`, backing off from 2 s to 5 s; out of time raises with the last record. */
19
+ export declare function waitUntil<T>(core: Core, read: () => Promise<T>, done: (record: T) => boolean, options?: {
20
+ timeoutMs?: number;
21
+ signal?: AbortSignal;
22
+ first?: T;
23
+ }): Promise<T>;
24
+ export declare const runSettled: (run: {
25
+ state?: string;
26
+ }) => boolean;
27
+ export declare class Runs extends RunsBase {
28
+ /**
29
+ * The run's events, oldest first, every page. With `follow`, keeps reading
30
+ * until the run is final (the CLI's `runs logs --follow`).
31
+ */
32
+ logs(run: string, options?: {
33
+ cursor?: string;
34
+ follow?: boolean;
35
+ pollMs?: number;
36
+ } & Signal): AsyncGenerator<RunEvent>;
37
+ /** The files of a run (all, or the given artifact paths), with their bytes. */
38
+ download(run: string, options?: {
39
+ paths?: string[];
40
+ } & Signal): Promise<Array<{
41
+ path: string;
42
+ content: Blob;
43
+ }>>;
44
+ }
45
+ export declare class Experiments extends ExperimentsBase {
46
+ #private;
47
+ /** An experiment with its runs and scores. With `wait`, polls until it is final. */
48
+ get(experiment: string, options?: Wait & Signal): Promise<ExperimentDetail>;
49
+ /** Stop an experiment's runs that have not finished. */
50
+ cancel(experiment: string, options?: Signal): Promise<unknown>;
51
+ }
52
+ export declare class DatasetsReviews extends DatasetsReviewsBase {
53
+ #private;
54
+ /** A dataset review: progress, decisions, notes. With `wait`, polls until it is closed. */
55
+ get(review: string, options?: Wait & Signal): Promise<DatasetReviewDetail>;
56
+ /** Comment on one example of a review (optionally on one field). */
57
+ comment(review: string, example: string, options: {
58
+ text: string;
59
+ field?: string;
60
+ } & Signal): Promise<unknown>;
61
+ /** Close a review; open decisions stay as they are. */
62
+ close(review: string, options?: Signal): Promise<DatasetReviewDetail>;
63
+ }
64
+ export declare class Templates extends TemplatesBase {
65
+ /**
66
+ * Upload a DOCX or XLSX template: a new one, or a new revision of `replace`
67
+ * (a template id).
68
+ */
69
+ upload(file: UploadableFile, options?: {
70
+ name?: string;
71
+ description?: string;
72
+ replace?: string;
73
+ filename?: string;
74
+ } & Signal): Promise<Template>;
75
+ }
76
+ export declare class EmailServers extends EmailServersBase {
77
+ /** Create the server of this name, or update it (secrets are write-only). */
78
+ set(name: string, config: Omit<EmailServerCreateBody, 'name'> & Signal): Promise<EmailServer>;
79
+ }
80
+ export declare class Files extends FilesBase {
81
+ /** Upload a file once; pass `{ $fileId: file.id }` as a run input, to as many runs as you like. */
82
+ upload(file: FileInput | Uint8Array | ArrayBuffer, options?: UploadOptions): Promise<UploadedFile>;
83
+ }
84
+ export declare const RESOURCE_IMPLS: ResourceImpls;
85
+ export {};