@scenario-labs/sdk 0.2.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +44 -8
  3. package/client.d.mts +36 -16
  4. package/client.d.mts.map +1 -1
  5. package/client.d.ts +36 -16
  6. package/client.d.ts.map +1 -1
  7. package/client.js +21 -11
  8. package/client.js.map +1 -1
  9. package/client.mjs +21 -11
  10. package/client.mjs.map +1 -1
  11. package/core/pagination.d.mts +153 -0
  12. package/core/pagination.d.mts.map +1 -0
  13. package/core/pagination.d.ts +153 -0
  14. package/core/pagination.d.ts.map +1 -0
  15. package/core/pagination.js +276 -0
  16. package/core/pagination.js.map +1 -0
  17. package/core/pagination.mjs +263 -0
  18. package/core/pagination.mjs.map +1 -0
  19. package/index.d.mts +3 -0
  20. package/index.d.mts.map +1 -1
  21. package/index.d.ts +3 -0
  22. package/index.d.ts.map +1 -1
  23. package/index.js +9 -1
  24. package/index.js.map +1 -1
  25. package/index.mjs +3 -0
  26. package/index.mjs.map +1 -1
  27. package/internal/request-options.d.mts +1 -1
  28. package/internal/request-options.d.mts.map +1 -1
  29. package/internal/request-options.d.ts +1 -1
  30. package/internal/request-options.d.ts.map +1 -1
  31. package/lib/models.d.mts +34 -2
  32. package/lib/models.d.mts.map +1 -1
  33. package/lib/models.d.ts +34 -2
  34. package/lib/models.d.ts.map +1 -1
  35. package/lib/models.js +39 -2
  36. package/lib/models.js.map +1 -1
  37. package/lib/models.mjs +37 -1
  38. package/lib/models.mjs.map +1 -1
  39. package/lib/scenario.d.mts +2 -0
  40. package/lib/scenario.d.mts.map +1 -1
  41. package/lib/scenario.d.ts +2 -0
  42. package/lib/scenario.d.ts.map +1 -1
  43. package/lib/scenario.js +2 -0
  44. package/lib/scenario.js.map +1 -1
  45. package/lib/scenario.mjs +2 -0
  46. package/lib/scenario.mjs.map +1 -1
  47. package/lib/upload.d.mts +89 -0
  48. package/lib/upload.d.mts.map +1 -0
  49. package/lib/upload.d.ts +89 -0
  50. package/lib/upload.d.ts.map +1 -0
  51. package/lib/upload.js +193 -0
  52. package/lib/upload.js.map +1 -0
  53. package/lib/upload.mjs +156 -0
  54. package/lib/upload.mjs.map +1 -0
  55. package/lib/workflow.d.mts +19 -3
  56. package/lib/workflow.d.mts.map +1 -1
  57. package/lib/workflow.d.ts +19 -3
  58. package/lib/workflow.d.ts.map +1 -1
  59. package/lib/workflow.js +26 -5
  60. package/lib/workflow.js.map +1 -1
  61. package/lib/workflow.mjs +26 -5
  62. package/lib/workflow.mjs.map +1 -1
  63. package/lib/workflow_import_validator.d.mts +40 -0
  64. package/lib/workflow_import_validator.d.mts.map +1 -0
  65. package/lib/workflow_import_validator.d.ts +40 -0
  66. package/lib/workflow_import_validator.d.ts.map +1 -0
  67. package/lib/workflow_import_validator.js +69 -0
  68. package/lib/workflow_import_validator.js.map +1 -0
  69. package/lib/workflow_import_validator.mjs +64 -0
  70. package/lib/workflow_import_validator.mjs.map +1 -0
  71. package/lib/workflow_validator.d.mts +22 -0
  72. package/lib/workflow_validator.d.mts.map +1 -0
  73. package/lib/workflow_validator.d.ts +22 -0
  74. package/lib/workflow_validator.d.ts.map +1 -0
  75. package/lib/workflow_validator.js +124 -0
  76. package/lib/workflow_validator.js.map +1 -0
  77. package/lib/workflow_validator.mjs +121 -0
  78. package/lib/workflow_validator.mjs.map +1 -0
  79. package/package.json +11 -1
  80. package/pagination.d.mts +2 -0
  81. package/pagination.d.mts.map +1 -0
  82. package/pagination.d.ts +2 -0
  83. package/pagination.d.ts.map +1 -0
  84. package/pagination.js +6 -0
  85. package/pagination.js.map +1 -0
  86. package/pagination.mjs +2 -0
  87. package/pagination.mjs.map +1 -0
  88. package/resources/assets/assets.d.mts +631 -648
  89. package/resources/assets/assets.d.mts.map +1 -1
  90. package/resources/assets/assets.d.ts +631 -648
  91. package/resources/assets/assets.d.ts.map +1 -1
  92. package/resources/assets/assets.js +5 -4
  93. package/resources/assets/assets.js.map +1 -1
  94. package/resources/assets/assets.mjs +5 -4
  95. package/resources/assets/assets.mjs.map +1 -1
  96. package/resources/assets/index.d.mts +1 -1
  97. package/resources/assets/index.d.mts.map +1 -1
  98. package/resources/assets/index.d.ts +1 -1
  99. package/resources/assets/index.d.ts.map +1 -1
  100. package/resources/assets/index.js.map +1 -1
  101. package/resources/assets/index.mjs.map +1 -1
  102. package/resources/collections/assets.d.mts +8 -2
  103. package/resources/collections/assets.d.mts.map +1 -1
  104. package/resources/collections/assets.d.ts +8 -2
  105. package/resources/collections/assets.d.ts.map +1 -1
  106. package/resources/collections/assets.js +2 -2
  107. package/resources/collections/assets.js.map +1 -1
  108. package/resources/collections/assets.mjs +2 -2
  109. package/resources/collections/assets.mjs.map +1 -1
  110. package/resources/collections/collections.d.mts +42 -53
  111. package/resources/collections/collections.d.mts.map +1 -1
  112. package/resources/collections/collections.d.ts +42 -53
  113. package/resources/collections/collections.d.ts.map +1 -1
  114. package/resources/collections/collections.js +5 -1
  115. package/resources/collections/collections.js.map +1 -1
  116. package/resources/collections/collections.mjs +5 -1
  117. package/resources/collections/collections.mjs.map +1 -1
  118. package/resources/collections/index.d.mts +3 -3
  119. package/resources/collections/index.d.mts.map +1 -1
  120. package/resources/collections/index.d.ts +3 -3
  121. package/resources/collections/index.d.ts.map +1 -1
  122. package/resources/collections/index.js.map +1 -1
  123. package/resources/collections/index.mjs +2 -2
  124. package/resources/collections/index.mjs.map +1 -1
  125. package/resources/collections/models.d.mts +8 -2
  126. package/resources/collections/models.d.mts.map +1 -1
  127. package/resources/collections/models.d.ts +8 -2
  128. package/resources/collections/models.d.ts.map +1 -1
  129. package/resources/collections/models.js +2 -2
  130. package/resources/collections/models.js.map +1 -1
  131. package/resources/collections/models.mjs +2 -2
  132. package/resources/collections/models.mjs.map +1 -1
  133. package/resources/index.d.mts +7 -7
  134. package/resources/index.d.mts.map +1 -1
  135. package/resources/index.d.ts +7 -7
  136. package/resources/index.d.ts.map +1 -1
  137. package/resources/index.js.map +1 -1
  138. package/resources/index.mjs.map +1 -1
  139. package/resources/jobs.d.mts +369 -380
  140. package/resources/jobs.d.mts.map +1 -1
  141. package/resources/jobs.d.ts +369 -380
  142. package/resources/jobs.d.ts.map +1 -1
  143. package/resources/jobs.js +2 -1
  144. package/resources/jobs.js.map +1 -1
  145. package/resources/jobs.mjs +2 -1
  146. package/resources/jobs.mjs.map +1 -1
  147. package/resources/models/index.d.mts +1 -1
  148. package/resources/models/index.d.mts.map +1 -1
  149. package/resources/models/index.d.ts +1 -1
  150. package/resources/models/index.d.ts.map +1 -1
  151. package/resources/models/index.js.map +1 -1
  152. package/resources/models/index.mjs.map +1 -1
  153. package/resources/models/models.d.mts +956 -967
  154. package/resources/models/models.d.mts.map +1 -1
  155. package/resources/models/models.d.ts +956 -967
  156. package/resources/models/models.d.ts.map +1 -1
  157. package/resources/models/models.js +2 -1
  158. package/resources/models/models.js.map +1 -1
  159. package/resources/models/models.mjs +2 -1
  160. package/resources/models/models.mjs.map +1 -1
  161. package/resources/models/train.d.mts +38 -38
  162. package/resources/models/train.d.mts.map +1 -1
  163. package/resources/models/train.d.ts +38 -38
  164. package/resources/models/train.d.ts.map +1 -1
  165. package/resources/search.d.mts +215 -295
  166. package/resources/search.d.mts.map +1 -1
  167. package/resources/search.d.ts +215 -295
  168. package/resources/search.d.ts.map +1 -1
  169. package/resources/search.js +9 -2
  170. package/resources/search.js.map +1 -1
  171. package/resources/search.mjs +9 -2
  172. package/resources/search.mjs.map +1 -1
  173. package/resources/tags.d.mts +23 -35
  174. package/resources/tags.d.mts.map +1 -1
  175. package/resources/tags.d.ts +23 -35
  176. package/resources/tags.d.ts.map +1 -1
  177. package/resources/tags.js +2 -1
  178. package/resources/tags.js.map +1 -1
  179. package/resources/tags.mjs +2 -1
  180. package/resources/tags.mjs.map +1 -1
  181. package/resources/workflows.d.mts +688 -704
  182. package/resources/workflows.d.mts.map +1 -1
  183. package/resources/workflows.d.ts +688 -704
  184. package/resources/workflows.d.ts.map +1 -1
  185. package/resources/workflows.js +5 -1
  186. package/resources/workflows.js.map +1 -1
  187. package/resources/workflows.mjs +5 -1
  188. package/resources/workflows.mjs.map +1 -1
  189. package/src/client.ts +118 -15
  190. package/src/core/pagination.ts +497 -0
  191. package/src/index.ts +9 -0
  192. package/src/internal/request-options.ts +1 -1
  193. package/src/lib/models.ts +62 -2
  194. package/src/lib/scenario.ts +2 -0
  195. package/src/lib/upload.ts +250 -0
  196. package/src/lib/workflow.ts +39 -5
  197. package/src/lib/workflow_import_validator.ts +104 -0
  198. package/src/lib/workflow_validator.ts +167 -0
  199. package/src/pagination.ts +2 -0
  200. package/src/resources/assets/assets.ts +971 -905
  201. package/src/resources/assets/index.ts +3 -0
  202. package/src/resources/collections/assets.ts +14 -2
  203. package/src/resources/collections/collections.ts +49 -56
  204. package/src/resources/collections/index.ts +15 -2
  205. package/src/resources/collections/models.ts +14 -2
  206. package/src/resources/index.ts +10 -1
  207. package/src/resources/jobs.ts +613 -622
  208. package/src/resources/models/index.ts +1 -0
  209. package/src/resources/models/models.ts +1118 -1130
  210. package/src/resources/models/train.ts +40 -40
  211. package/src/resources/search.ts +239 -327
  212. package/src/resources/tags.ts +32 -39
  213. package/src/resources/workflows.ts +850 -864
  214. package/src/version.ts +1 -1
  215. package/version.d.mts +1 -1
  216. package/version.d.ts +1 -1
  217. package/version.js +1 -1
  218. package/version.mjs +1 -1
@@ -0,0 +1,250 @@
1
+ import type { RequestOptions } from '../internal/request-options';
2
+ import {
3
+ Uploads,
4
+ type UploadCreateParams,
5
+ type UploadCreateResponse,
6
+ type UploadRetrieveResponse,
7
+ } from '../resources/uploads';
8
+ import type { AssetRetrieveResponse } from '../resources/assets/assets';
9
+ import type { ModelRetrieveResponse } from '../resources/models/models';
10
+
11
+ type UploadKind = NonNullable<UploadCreateParams['kind']>;
12
+
13
+ /** The resolved entity returned after a successful upload, narrowed by `kind`. */
14
+ export type UploadResult<K extends UploadKind> =
15
+ K extends 'model' ? ModelRetrieveResponse : AssetRetrieveResponse;
16
+
17
+ /**
18
+ * Accepted upload inputs.
19
+ * - `string` — a local file path, read from disk (Node only; throws in browsers).
20
+ * - `Uint8Array` — raw bytes. `Buffer` is a `Uint8Array` and works too.
21
+ * - `Blob` / `File` — browser-native, or Node ≥ 18 via `fs.openAsBlob()` /
22
+ * constructors.
23
+ */
24
+ export type UploadFileInput = string | Uint8Array | Blob;
25
+
26
+ export interface UploadFileParams<K extends UploadKind> {
27
+ /**
28
+ * The file to upload. Accepts a local path (Node), a `Uint8Array` / `Buffer`,
29
+ * or a `Blob` / `File`.
30
+ */
31
+ file: UploadFileInput;
32
+ /** Original filename (e.g. `"my-model.safetensors"`). */
33
+ fileName: string;
34
+ /** MIME type (e.g. `"application/octet-stream"`, `"image/png"`). */
35
+ contentType: string;
36
+ /** The kind of upload. Determines the returned entity type. */
37
+ kind: K;
38
+ /**
39
+ * Extra asset options. Ignored when `kind === 'model'` — models don't
40
+ * produce an asset, so these options are not applicable server-side.
41
+ */
42
+ assetOptions?: UploadCreateParams['assetOptions'];
43
+ /**
44
+ * Maximum number of parts uploaded to S3 in parallel.
45
+ * @default 4
46
+ */
47
+ partConcurrency?: number;
48
+ /**
49
+ * Polling interval for the final "upload imported" check, in ms.
50
+ * @default 2000
51
+ */
52
+ pollIntervalMs?: number;
53
+ /**
54
+ * Maximum time to wait for the upload to reach a terminal state, in ms.
55
+ * Throws if exceeded.
56
+ * @default 300000
57
+ */
58
+ pollTimeoutMs?: number;
59
+ }
60
+
61
+ // AWS S3 multipart upload limits.
62
+ const MIN_PART_SIZE = 6_000_000; // 6 MB (spec minimum is 5 MiB; a bit over to be safe)
63
+ const MAX_PART_SIZE = 5_368_709_120; // 5 GiB
64
+ const MAX_PARTS = 10_000;
65
+ const MAX_FILE_SIZE = 5_497_558_138_880; // 5 TiB
66
+
67
+ // `validated` is intermediate — the server has validated the upload but
68
+ // hasn't created the asset/model yet, so `entityId` isn't populated.
69
+ // Real terminals are `imported` (asset/model created), `complete`, and
70
+ // `failed`. Everything else means "keep polling".
71
+ const TERMINAL_STATUSES = new Set(['complete', 'failed', 'imported']);
72
+
73
+ /**
74
+ * Enhanced Uploads resource.
75
+ * All original methods (`create`, `retrieve`, `triggerAction`) are inherited.
76
+ * Adds `uploadFile()` — a one-call wrapper around the 4-step upload flow:
77
+ * init → PUT parts to S3 → trigger complete → poll until imported.
78
+ */
79
+ export class EnhancedUploads extends Uploads {
80
+ /**
81
+ * Upload a file end-to-end. Computes an optimal part size (within AWS's
82
+ * 5 MiB / 5 GiB / 10,000-part bounds), uploads all parts in parallel,
83
+ * triggers completion, polls until the server has validated and imported
84
+ * the file, and returns the resolved entity.
85
+ *
86
+ * The returned type narrows on `kind`: `'model'` returns a Model,
87
+ * everything else returns an Asset.
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * // From a file path (Node)
92
+ * const { asset } = await client.uploads.uploadFile({
93
+ * file: './photo.jpg',
94
+ * fileName: 'photo.jpg',
95
+ * contentType: 'image/jpeg',
96
+ * kind: 'image',
97
+ * });
98
+ * console.log(asset.id, asset.url);
99
+ *
100
+ * // Or from bytes / Blob — anything you already have in memory
101
+ * await client.uploads.uploadFile({
102
+ * file: new Blob([pngBytes], { type: 'image/png' }),
103
+ * fileName: 'generated.png',
104
+ * contentType: 'image/png',
105
+ * kind: 'image',
106
+ * });
107
+ * ```
108
+ */
109
+ async uploadFile<K extends UploadKind>(
110
+ params: UploadFileParams<K>,
111
+ options?: RequestOptions,
112
+ ): Promise<UploadResult<K>> {
113
+ const bytes = await normalizeToBytes(params.file);
114
+ const fileSize = bytes.byteLength;
115
+
116
+ if (fileSize === 0) {
117
+ throw new Error('Cannot upload an empty file');
118
+ }
119
+ if (fileSize > MAX_FILE_SIZE) {
120
+ throw new Error(
121
+ `File size (${fileSize} bytes) exceeds the maximum allowed size of ${MAX_FILE_SIZE} bytes (5 TiB)`,
122
+ );
123
+ }
124
+
125
+ // Pick the smallest legal part size that fits within MAX_PARTS.
126
+ const requiredPartSize = Math.ceil(fileSize / MAX_PARTS);
127
+ const partSize = Math.max(MIN_PART_SIZE, requiredPartSize);
128
+ if (partSize > MAX_PART_SIZE) {
129
+ throw new Error(
130
+ `File size (${fileSize} bytes) requires a part size of ${partSize} bytes, ` +
131
+ `which exceeds the maximum part size of ${MAX_PART_SIZE} bytes (5 GiB)`,
132
+ );
133
+ }
134
+ const partsCount = Math.max(1, Math.ceil(fileSize / partSize));
135
+
136
+ // Step 1 — init upload session and receive presigned S3 URLs.
137
+ const createBody: UploadCreateParams = {
138
+ fileName: params.fileName,
139
+ fileSize,
140
+ contentType: params.contentType,
141
+ kind: params.kind,
142
+ parts: partsCount,
143
+ ...(params.kind !== 'model' && params.assetOptions ? { assetOptions: params.assetOptions } : {}),
144
+ };
145
+ const createRes: UploadCreateResponse = await this.create(createBody, options);
146
+ const session = createRes.upload;
147
+ const uploadId = session.id;
148
+ const parts = session.parts;
149
+ if (parts?.length !== partsCount) {
150
+ throw new Error(`Expected ${partsCount} presigned part URL(s), got ${parts?.length ?? 0}`);
151
+ }
152
+
153
+ // Step 2 — PUT each chunk to its presigned S3 URL, with a concurrency cap.
154
+ const concurrency = Math.max(1, params.partConcurrency ?? 4);
155
+ await uploadPartsWithConcurrency(bytes, parts, partSize, concurrency);
156
+
157
+ // Step 3 — tell the server all parts are uploaded.
158
+ await this.triggerAction(uploadId, { action: 'complete' }, options);
159
+
160
+ // Step 4 — poll until the upload has been processed into an entity.
161
+ const final = await pollUntilImported(
162
+ () => this.retrieve(uploadId, options),
163
+ params.pollIntervalMs ?? 2_000,
164
+ params.pollTimeoutMs ?? 300_000,
165
+ );
166
+
167
+ if (final.upload.status === 'failed') {
168
+ throw new Error(`Upload ${uploadId} failed: ${final.upload.errorMessage ?? '<no error message>'}`);
169
+ }
170
+ const entityId = final.upload.entityId;
171
+ if (!entityId) {
172
+ throw new Error(`Upload ${uploadId} reached status "${final.upload.status}" but has no entityId`);
173
+ }
174
+
175
+ // Fetch and return the resolved entity (narrowed by kind).
176
+ if (params.kind === 'model') {
177
+ const model = await this._client.models.retrieve(entityId);
178
+ return model as UploadResult<K>;
179
+ }
180
+ const asset = await this._client.assets.retrieve(entityId);
181
+ return asset as UploadResult<K>;
182
+ }
183
+ }
184
+
185
+ // ─────────────────────── helpers ───────────────────────
186
+
187
+ async function normalizeToBytes(input: UploadFileInput): Promise<Uint8Array> {
188
+ if (typeof input === 'string') {
189
+ // Dynamic import so browser bundlers don't pull in node:fs.
190
+ const { readFile } = await import('node:fs/promises');
191
+ return new Uint8Array(await readFile(input));
192
+ }
193
+ if (input instanceof Uint8Array) {
194
+ return input;
195
+ }
196
+ if (typeof Blob !== 'undefined' && input instanceof Blob) {
197
+ return new Uint8Array(await input.arrayBuffer());
198
+ }
199
+ throw new Error('uploadFile: unsupported input type — expected a path string, Uint8Array, or Blob');
200
+ }
201
+
202
+ async function uploadPartsWithConcurrency(
203
+ bytes: Uint8Array,
204
+ parts: Array<{ number: number; url: string; expires: string }>,
205
+ partSize: number,
206
+ concurrency: number,
207
+ ): Promise<void> {
208
+ // Sort by part number so slicing lines up with the presigned URL order.
209
+ const sorted = [...parts].sort((a, b) => a.number - b.number);
210
+
211
+ let nextIndex = 0;
212
+ const workers = Array.from({ length: concurrency }, () => worker());
213
+ await Promise.all(workers);
214
+
215
+ async function worker() {
216
+ while (true) {
217
+ const i = nextIndex++;
218
+ if (i >= sorted.length) return;
219
+ const part = sorted[i];
220
+ if (!part) continue;
221
+ const start = i * partSize;
222
+ const end = Math.min(bytes.byteLength, start + partSize);
223
+ const chunk = bytes.subarray(start, end);
224
+ const res = await fetch(part.url, { method: 'PUT', body: chunk });
225
+ if (!res.ok) {
226
+ throw new Error(
227
+ `Failed to upload part ${part.number}/${sorted.length}: ${res.status} ${res.statusText}`,
228
+ );
229
+ }
230
+ }
231
+ }
232
+ }
233
+
234
+ async function pollUntilImported(
235
+ retrieve: () => Promise<UploadRetrieveResponse>,
236
+ intervalMs: number,
237
+ timeoutMs: number,
238
+ ): Promise<UploadRetrieveResponse> {
239
+ const deadline = Date.now() + timeoutMs;
240
+ while (Date.now() < deadline) {
241
+ const res = await retrieve();
242
+ const { status } = res.upload;
243
+ // Return as soon as we have an entityId OR the upload reached a terminal state.
244
+ if (res.upload.entityId || TERMINAL_STATUSES.has(status)) {
245
+ return res;
246
+ }
247
+ await new Promise((r) => setTimeout(r, intervalMs));
248
+ }
249
+ throw new Error(`Upload did not reach a terminal status within ${timeoutMs / 1000}s`);
250
+ }
@@ -9,23 +9,30 @@ import {
9
9
  type WorkflowRunResponse,
10
10
  } from '../resources/workflows';
11
11
  import { type WithJob, enhanceJob } from './job';
12
+ import { validateWorkflowFlow } from './workflow_validator';
13
+ // Type-only import to break the circular `scenario.ts` ↔ `workflow.ts` graph at runtime.
14
+ import type { Scenario } from './scenario';
12
15
 
13
16
  type DefinitionFlow = WorkflowRetrieveResponse.Workflow.Flow;
14
17
  type NodeType = DefinitionFlow['type'];
15
18
 
16
19
  /**
17
20
  * Enhanced workflow object with helper methods.
18
- * Has all original workflow fields plus `findNode()`, `getNodesByType()`.
21
+ * Has all original workflow fields plus `findNode()`, `getNodesByType()`,
22
+ * `validate()`, and `run()`.
19
23
  *
20
24
  * @example
21
25
  * ```ts
22
26
  * const response = await client.workflows.retrieve(workflowId);
23
27
  * response.workflow.findNode('final_image');
24
28
  * response.workflow.getNodesByType('custom-model');
29
+ * const gen = await response.workflow.run({ body: { prompt: '...' } });
25
30
  * response.workflow.name; // original fields still work
26
31
  * ```
27
32
  */
28
33
  export class WorkflowEntity {
34
+ /** @internal */ declare readonly _client: Scenario;
35
+
29
36
  /** Find a node in the workflow definition by ID. */
30
37
  findNode(
31
38
  this: WorkflowEntity & WorkflowRetrieveResponse.Workflow,
@@ -39,9 +46,36 @@ export class WorkflowEntity {
39
46
  return this.flow.filter((node) => node.type === type);
40
47
  }
41
48
 
49
+ /**
50
+ * Validate the structural integrity of a workflow flow.
51
+ * Throws an `Error` with a human-readable message on the first violation found.
52
+ */
53
+ validate(this: WorkflowEntity & WorkflowRetrieveResponse.Workflow): void {
54
+ validateWorkflowFlow(this.flow);
55
+ }
56
+
57
+ /**
58
+ * Run this workflow. Shortcut for
59
+ * `client.workflows.run(this.id, params)`.
60
+ *
61
+ * Returns an enhanced response where `response.job` has `.wait()`.
62
+ */
63
+ run(
64
+ this: WorkflowEntity & WorkflowRetrieveResponse.Workflow,
65
+ params: WorkflowRunParams,
66
+ options?: RequestOptions,
67
+ ): APIPromise<WithJob<WorkflowRunResponse>> {
68
+ return this._client.workflows.run(this.id, params, options);
69
+ }
70
+
42
71
  /** @internal Create a WorkflowEntity from raw workflow data. */
43
- static from(data: WorkflowRetrieveResponse.Workflow): WorkflowRetrieveResponse.Workflow & WorkflowEntity {
44
- return Object.assign(Object.create(WorkflowEntity.prototype), data);
72
+ static from(
73
+ client: Scenario,
74
+ data: WorkflowRetrieveResponse.Workflow,
75
+ ): WorkflowRetrieveResponse.Workflow & WorkflowEntity {
76
+ const entity = Object.assign(Object.create(WorkflowEntity.prototype), data);
77
+ Object.defineProperty(entity, '_client', { value: client, enumerable: false });
78
+ return entity;
45
79
  }
46
80
  }
47
81
 
@@ -58,7 +92,7 @@ export type EnhancedWorkflowRetrieveResponse = Omit<WorkflowRetrieveResponse, 'w
58
92
  export class EnhancedWorkflows extends Workflows {
59
93
  /**
60
94
  * Get workflow by ID. Returns an enhanced response where `workflow` has
61
- * `findNode()` and `getNodesByType()`.
95
+ * `findNode()`, `getNodesByType()`, and `validate()`.
62
96
  */
63
97
  override retrieve(
64
98
  workflowID: string,
@@ -66,7 +100,7 @@ export class EnhancedWorkflows extends Workflows {
66
100
  ): APIPromise<EnhancedWorkflowRetrieveResponse> {
67
101
  return super.retrieve(workflowID, options)._thenUnwrap((data) => ({
68
102
  ...data,
69
- workflow: WorkflowEntity.from(data.workflow),
103
+ workflow: WorkflowEntity.from(this._client as Scenario, data.workflow),
70
104
  }));
71
105
  }
72
106
 
@@ -0,0 +1,104 @@
1
+ export class WorkflowImportError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = 'WorkflowImportError';
5
+ }
6
+ }
7
+
8
+ export type WorkflowEditorNodeType =
9
+ | 'text'
10
+ | 'asset'
11
+ | 'model'
12
+ | 'llm'
13
+ | 'transformText'
14
+ | 'splitText'
15
+ | 'ifElse'
16
+ | 'groupItems'
17
+ | 'sliceAssets'
18
+ | 'forEach'
19
+ | 'forEachEnd'
20
+ | 'stickyNote';
21
+
22
+ export const VALID_EDITOR_NODE_TYPES: readonly WorkflowEditorNodeType[] = [
23
+ 'text',
24
+ 'asset',
25
+ 'model',
26
+ 'llm',
27
+ 'transformText',
28
+ 'splitText',
29
+ 'ifElse',
30
+ 'groupItems',
31
+ 'sliceAssets',
32
+ 'forEach',
33
+ 'forEachEnd',
34
+ 'stickyNote',
35
+ ];
36
+
37
+ export interface WorkflowExportData {
38
+ version: '1.0';
39
+ name: string;
40
+ description: string;
41
+ editorInfo: {
42
+ nodes: Array<{ type: WorkflowEditorNodeType; [key: string]: unknown }>;
43
+ edges: Array<{ [key: string]: unknown }>;
44
+ inputKeys: string[];
45
+ };
46
+ inputs: unknown[];
47
+ tagSet: string[];
48
+ uiConfig?: object;
49
+ exportedAt: string;
50
+ exportedBy: string;
51
+ }
52
+
53
+ /**
54
+ * Validates a workflow export payload (e.g. from a JSON file import).
55
+ *
56
+ * Throws a `WorkflowImportError` with a human-readable message on the first
57
+ * violation found. Returns the validated data cast to `WorkflowExportData`.
58
+ *
59
+ * Checks performed:
60
+ * 1. Data is a non-null object
61
+ * 2. `version` field is present and equals "1.0"
62
+ * 3. `editorInfo` has non-empty `nodes` and `edges` arrays
63
+ * 4. Each node's `type` is a recognized editor node type
64
+ * 5. `inputs` is an array
65
+ */
66
+ export function validateEditorInfo(data: unknown): WorkflowExportData {
67
+ if (typeof data !== 'object' || data === null) {
68
+ throw new WorkflowImportError('Invalid JSON format');
69
+ }
70
+
71
+ const workflow = data as Partial<WorkflowExportData>;
72
+
73
+ if (!workflow.version) {
74
+ throw new WorkflowImportError('Missing version field');
75
+ }
76
+
77
+ if (workflow.version !== '1.0') {
78
+ throw new WorkflowImportError(`Unsupported version: ${workflow.version}`);
79
+ }
80
+
81
+ if (!workflow.editorInfo || !workflow.editorInfo.nodes || !workflow.editorInfo.edges) {
82
+ throw new WorkflowImportError('Missing editorInfo structure');
83
+ }
84
+
85
+ if (!Array.isArray(workflow.editorInfo.nodes)) {
86
+ throw new WorkflowImportError('Invalid nodes array');
87
+ }
88
+
89
+ if (!Array.isArray(workflow.editorInfo.edges)) {
90
+ throw new WorkflowImportError('Invalid edges array');
91
+ }
92
+
93
+ if (!workflow.inputs || !Array.isArray(workflow.inputs)) {
94
+ throw new WorkflowImportError('Invalid inputs array');
95
+ }
96
+
97
+ for (const node of workflow.editorInfo.nodes) {
98
+ if (!(VALID_EDITOR_NODE_TYPES as readonly string[]).includes(node.type)) {
99
+ throw new WorkflowImportError(`Invalid node type: ${node.type}`);
100
+ }
101
+ }
102
+
103
+ return workflow as WorkflowExportData;
104
+ }
@@ -0,0 +1,167 @@
1
+ const VALID_NODE_TYPES = new Set([
2
+ 'custom-model',
3
+ 'for-each',
4
+ 'generate-prompt',
5
+ 'list',
6
+ 'logic',
7
+ 'model',
8
+ 'remove-background',
9
+ 'transform',
10
+ 'user-approval',
11
+ 'workflow',
12
+ ]);
13
+
14
+ type RawRef = {
15
+ node?: unknown;
16
+ conditional?: unknown;
17
+ };
18
+
19
+ type RawInput = {
20
+ name?: unknown;
21
+ ref?: RawRef;
22
+ items?: unknown[][];
23
+ };
24
+
25
+ type RawNode = {
26
+ id?: unknown;
27
+ type?: unknown;
28
+ modelId?: unknown;
29
+ workflowId?: unknown;
30
+ logicType?: unknown;
31
+ loopBodyNodeIds?: unknown;
32
+ count?: unknown;
33
+ dependsOn?: unknown;
34
+ inputs?: unknown;
35
+ };
36
+
37
+ /**
38
+ * Validates the structural integrity of a workflow flow (array of nodes).
39
+ *
40
+ * Throws an `Error` with a human-readable message on the first violation found.
41
+ *
42
+ * Checks performed:
43
+ * 1. Every node has a non-empty string `id`
44
+ * 2. Node IDs are unique within the flow
45
+ * 3. Every node `type` is a recognized workflow node type
46
+ * 4. Per-type required fields:
47
+ * - custom-model → modelId
48
+ * - workflow → workflowId
49
+ * - logic → logicType
50
+ * - for-each → loopBodyNodeIds (non-empty) OR count (>0)
51
+ * 5. Cross-references all point to node IDs that exist in the flow:
52
+ * - dependsOn entries
53
+ * - input ref.node (excluding "workflow" which is a reserved keyword)
54
+ * - input ref.conditional entries
55
+ * - loopBodyNodeIds entries
56
+ */
57
+ export function validateWorkflowFlow(flow: unknown[]): void {
58
+ const nodeIds = new Set<string>();
59
+ const firstSeenAt = new Map<string, number>();
60
+
61
+ // Pass 1 — per-node checks (ID, type, required fields)
62
+ for (let i = 0; i < flow.length; i++) {
63
+ const node = flow[i] as RawNode;
64
+
65
+ if (typeof node.id !== 'string' || !node.id) {
66
+ throw new Error(`Node at index ${i} is missing an "id" field`);
67
+ }
68
+ if (nodeIds.has(node.id)) {
69
+ throw new Error(
70
+ `Duplicate node id "${node.id}" at index ${i} (first seen at index ${firstSeenAt.get(node.id)})`,
71
+ );
72
+ }
73
+ nodeIds.add(node.id);
74
+ firstSeenAt.set(node.id, i);
75
+
76
+ const label = `"${node.id}"`;
77
+
78
+ if (typeof node.type !== 'string' || !VALID_NODE_TYPES.has(node.type)) {
79
+ throw new Error(
80
+ `Node ${label} has invalid type "${node.type}". Valid types are: ${[...VALID_NODE_TYPES].join(', ')}`,
81
+ );
82
+ }
83
+
84
+ const type = node.type;
85
+
86
+ if (type === 'custom-model' && !node.modelId) {
87
+ throw new Error(`Node ${label} (custom-model) is missing required field "modelId"`);
88
+ }
89
+ if (type === 'workflow' && !node.workflowId) {
90
+ throw new Error(`Node ${label} (workflow) is missing required field "workflowId"`);
91
+ }
92
+ if (type === 'logic' && !node.logicType) {
93
+ throw new Error(`Node ${label} (logic) is missing required field "logicType"`);
94
+ }
95
+ if (type === 'for-each') {
96
+ const hasLoopBody = Array.isArray(node.loopBodyNodeIds) && node.loopBodyNodeIds.length > 0;
97
+ const hasCount = typeof node.count === 'number' && node.count > 0;
98
+ if (!hasLoopBody && !hasCount) {
99
+ throw new Error(
100
+ `Node ${label} (for-each) requires either "loopBodyNodeIds" (non-empty array) or "count" (positive number)`,
101
+ );
102
+ }
103
+ }
104
+ }
105
+
106
+ // Pass 2 — cross-reference checks (all node IDs are now collected)
107
+ for (const rawNode of flow) {
108
+ const node = rawNode as RawNode;
109
+ const nodeId = node.id as string;
110
+
111
+ if (Array.isArray(node.dependsOn)) {
112
+ for (const depId of node.dependsOn) {
113
+ if (typeof depId === 'string' && !nodeIds.has(depId)) {
114
+ throw new Error(`Node "${nodeId}" dependsOn unknown node "${depId}"`);
115
+ }
116
+ }
117
+ }
118
+
119
+ if (Array.isArray(node.inputs)) {
120
+ for (const input of node.inputs) {
121
+ validateInputRefs(nodeId, input as RawInput, nodeIds);
122
+ }
123
+ }
124
+
125
+ if (Array.isArray(node.loopBodyNodeIds)) {
126
+ for (const bodyId of node.loopBodyNodeIds as unknown[]) {
127
+ if (typeof bodyId === 'string' && !nodeIds.has(bodyId)) {
128
+ throw new Error(`Node "${nodeId}" loopBodyNodeIds references unknown node "${bodyId}"`);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ function validateInputRefs(nodeId: string, input: RawInput, nodeIds: Set<string>): void {
136
+ const inputName = typeof input.name === 'string' && input.name ? input.name : '(unnamed)';
137
+
138
+ if (input.ref) {
139
+ const { node: refNode, conditional } = input.ref;
140
+
141
+ // "workflow" is a reserved keyword meaning "take from the workflow's own inputs"
142
+ if (typeof refNode === 'string' && refNode !== 'workflow' && !nodeIds.has(refNode)) {
143
+ throw new Error(`Node "${nodeId}" input "${inputName}" references unknown node "${refNode}"`);
144
+ }
145
+
146
+ if (Array.isArray(conditional)) {
147
+ for (const condId of conditional) {
148
+ if (typeof condId === 'string' && !nodeIds.has(condId)) {
149
+ throw new Error(
150
+ `Node "${nodeId}" input "${inputName}" has a conditional ref pointing to unknown node "${condId}"`,
151
+ );
152
+ }
153
+ }
154
+ }
155
+ }
156
+
157
+ // Recurse into INPUTS_ARRAY sub-inputs
158
+ if (Array.isArray(input.items)) {
159
+ for (const item of input.items) {
160
+ if (Array.isArray(item)) {
161
+ for (const subInput of item) {
162
+ validateInputRefs(nodeId, subInput as RawInput, nodeIds);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ }
@@ -0,0 +1,2 @@
1
+ /** @deprecated Import from ./core/pagination instead */
2
+ export * from './core/pagination';