@trigger.dev/core 3.0.0-beta.35 → 3.0.0-beta.37

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 (37) hide show
  1. package/dist/{catalog-BUwiuDbt.d.mts → catalog-XTlJQaMn.d.mts} +3 -3
  2. package/dist/{catalog-eKgqBHUA.d.ts → catalog-dRKTgwQ7.d.ts} +3 -3
  3. package/dist/{manager-uPyMRN8k.d.mts → manager-JkbddlcO.d.mts} +19 -19
  4. package/dist/{manager-uPyMRN8k.d.ts → manager-JkbddlcO.d.ts} +19 -19
  5. package/dist/{messages-l9PdIyKF.d.mts → messages-9lty-Du5.d.mts} +139 -166
  6. package/dist/{messages-l9PdIyKF.d.ts → messages-9lty-Du5.d.ts} +139 -166
  7. package/dist/{schemas-b8tRw8dX.d.mts → schemas-r4ZP9S-F.d.mts} +2 -2
  8. package/dist/{schemas-b8tRw8dX.d.ts → schemas-r4ZP9S-F.d.ts} +2 -2
  9. package/dist/v3/dev/index.d.mts +1 -1
  10. package/dist/v3/dev/index.d.ts +1 -1
  11. package/dist/v3/index.d.mts +587 -122
  12. package/dist/v3/index.d.ts +587 -122
  13. package/dist/v3/index.js +749 -348
  14. package/dist/v3/index.js.map +1 -1
  15. package/dist/v3/index.mjs +740 -347
  16. package/dist/v3/index.mjs.map +1 -1
  17. package/dist/v3/otel/index.js +1 -1
  18. package/dist/v3/otel/index.js.map +1 -1
  19. package/dist/v3/otel/index.mjs +1 -1
  20. package/dist/v3/otel/index.mjs.map +1 -1
  21. package/dist/v3/prod/index.d.mts +2 -2
  22. package/dist/v3/prod/index.d.ts +2 -2
  23. package/dist/v3/workers/index.d.mts +6 -6
  24. package/dist/v3/workers/index.d.ts +6 -6
  25. package/dist/v3/workers/index.js +465 -52
  26. package/dist/v3/workers/index.js.map +1 -1
  27. package/dist/v3/workers/index.mjs +465 -52
  28. package/dist/v3/workers/index.mjs.map +1 -1
  29. package/dist/v3/zodMessageHandler.d.mts +1 -1
  30. package/dist/v3/zodMessageHandler.d.ts +1 -1
  31. package/dist/v3/zodfetch.d.mts +194 -10
  32. package/dist/v3/zodfetch.d.ts +194 -10
  33. package/dist/v3/zodfetch.js +336 -38
  34. package/dist/v3/zodfetch.js.map +1 -1
  35. package/dist/v3/zodfetch.mjs +320 -37
  36. package/dist/v3/zodfetch.mjs.map +1 -1
  37. package/package.json +1 -1
package/dist/v3/index.mjs CHANGED
@@ -29,7 +29,7 @@ var __privateMethod = (obj, member, method) => {
29
29
  };
30
30
 
31
31
  // package.json
32
- var version = "3.0.0-beta.35";
32
+ var version = "3.0.0-beta.37";
33
33
  var dependencies = {
34
34
  "@google-cloud/precise-date": "^4.0.0",
35
35
  "@opentelemetry/api": "^1.8.0",
@@ -52,144 +52,6 @@ var dependencies = {
52
52
  "zod-error": "1.5.0",
53
53
  "zod-validation-error": "^1.5.0"
54
54
  };
55
-
56
- // src/v3/apiErrors.ts
57
- var _APIError = class _APIError extends Error {
58
- constructor(status, error, message, headers) {
59
- super(`${_APIError.makeMessage(status, error, message)}`);
60
- this.status = status;
61
- this.headers = headers;
62
- const data = error;
63
- this.error = data;
64
- this.code = data?.["code"];
65
- this.param = data?.["param"];
66
- this.type = data?.["type"];
67
- }
68
- static makeMessage(status, error, message) {
69
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
70
- if (status && msg) {
71
- return `${status} ${msg}`;
72
- }
73
- if (status) {
74
- return `${status} status code (no body)`;
75
- }
76
- if (msg) {
77
- return msg;
78
- }
79
- return "(no status code or body)";
80
- }
81
- static generate(status, errorResponse, message, headers) {
82
- if (!status) {
83
- return new APIConnectionError({
84
- cause: castToError(errorResponse)
85
- });
86
- }
87
- const error = errorResponse?.["error"];
88
- if (status === 400) {
89
- return new BadRequestError(status, error, message, headers);
90
- }
91
- if (status === 401) {
92
- return new AuthenticationError(status, error, message, headers);
93
- }
94
- if (status === 403) {
95
- return new PermissionDeniedError(status, error, message, headers);
96
- }
97
- if (status === 404) {
98
- return new NotFoundError(status, error, message, headers);
99
- }
100
- if (status === 409) {
101
- return new ConflictError(status, error, message, headers);
102
- }
103
- if (status === 422) {
104
- return new UnprocessableEntityError(status, error, message, headers);
105
- }
106
- if (status === 429) {
107
- return new RateLimitError(status, error, message, headers);
108
- }
109
- if (status >= 500) {
110
- return new InternalServerError(status, error, message, headers);
111
- }
112
- return new _APIError(status, error, message, headers);
113
- }
114
- };
115
- __name(_APIError, "APIError");
116
- var APIError = _APIError;
117
- var _APIConnectionError = class _APIConnectionError extends APIError {
118
- constructor({ message, cause }) {
119
- super(void 0, void 0, message || "Connection error.", void 0);
120
- __publicField(this, "status");
121
- if (cause)
122
- this.cause = cause;
123
- }
124
- };
125
- __name(_APIConnectionError, "APIConnectionError");
126
- var APIConnectionError = _APIConnectionError;
127
- var _BadRequestError = class _BadRequestError extends APIError {
128
- constructor() {
129
- super(...arguments);
130
- __publicField(this, "status", 400);
131
- }
132
- };
133
- __name(_BadRequestError, "BadRequestError");
134
- var BadRequestError = _BadRequestError;
135
- var _AuthenticationError = class _AuthenticationError extends APIError {
136
- constructor() {
137
- super(...arguments);
138
- __publicField(this, "status", 401);
139
- }
140
- };
141
- __name(_AuthenticationError, "AuthenticationError");
142
- var AuthenticationError = _AuthenticationError;
143
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
144
- constructor() {
145
- super(...arguments);
146
- __publicField(this, "status", 403);
147
- }
148
- };
149
- __name(_PermissionDeniedError, "PermissionDeniedError");
150
- var PermissionDeniedError = _PermissionDeniedError;
151
- var _NotFoundError = class _NotFoundError extends APIError {
152
- constructor() {
153
- super(...arguments);
154
- __publicField(this, "status", 404);
155
- }
156
- };
157
- __name(_NotFoundError, "NotFoundError");
158
- var NotFoundError = _NotFoundError;
159
- var _ConflictError = class _ConflictError extends APIError {
160
- constructor() {
161
- super(...arguments);
162
- __publicField(this, "status", 409);
163
- }
164
- };
165
- __name(_ConflictError, "ConflictError");
166
- var ConflictError = _ConflictError;
167
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
168
- constructor() {
169
- super(...arguments);
170
- __publicField(this, "status", 422);
171
- }
172
- };
173
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
174
- var UnprocessableEntityError = _UnprocessableEntityError;
175
- var _RateLimitError = class _RateLimitError extends APIError {
176
- constructor() {
177
- super(...arguments);
178
- __publicField(this, "status", 429);
179
- }
180
- };
181
- __name(_RateLimitError, "RateLimitError");
182
- var RateLimitError = _RateLimitError;
183
- var _InternalServerError = class _InternalServerError extends APIError {
184
- };
185
- __name(_InternalServerError, "InternalServerError");
186
- var InternalServerError = _InternalServerError;
187
- function castToError(err) {
188
- if (err instanceof Error)
189
- return err;
190
- return new Error(err);
191
- }
192
- __name(castToError, "castToError");
193
55
  var CreateAuthorizationCodeResponseSchema = z.object({
194
56
  url: z.string().url(),
195
57
  authorizationCode: z.string()
@@ -508,7 +370,16 @@ var TaskFileMetadata = z.object({
508
370
  filePath: z.string(),
509
371
  exportName: z.string()
510
372
  });
511
- var TaskMetadataWithFilePath = TaskMetadata.merge(TaskFileMetadata);
373
+ var TaskMetadataWithFilePath = z.object({
374
+ id: z.string(),
375
+ packageVersion: z.string(),
376
+ queue: QueueOptions.optional(),
377
+ retry: RetryOptions.optional(),
378
+ machine: Machine.partial().optional(),
379
+ triggerSource: z.string().optional(),
380
+ filePath: z.string(),
381
+ exportName: z.string()
382
+ });
512
383
  var PostStartCauses = z.enum([
513
384
  "index",
514
385
  "create",
@@ -577,6 +448,152 @@ var ImageDetailsMetadata = z.object({
577
448
  contentHash: z.string(),
578
449
  imageTag: z.string()
579
450
  });
451
+ function parseError(error) {
452
+ if (error instanceof Error) {
453
+ return {
454
+ type: "BUILT_IN_ERROR",
455
+ name: error.name,
456
+ message: error.message,
457
+ stackTrace: error.stack ?? ""
458
+ };
459
+ }
460
+ if (typeof error === "string") {
461
+ return {
462
+ type: "STRING_ERROR",
463
+ raw: error
464
+ };
465
+ }
466
+ try {
467
+ return {
468
+ type: "CUSTOM_ERROR",
469
+ raw: JSON.stringify(error)
470
+ };
471
+ } catch (e) {
472
+ return {
473
+ type: "CUSTOM_ERROR",
474
+ raw: String(error)
475
+ };
476
+ }
477
+ }
478
+ __name(parseError, "parseError");
479
+ function createErrorTaskError(error) {
480
+ switch (error.type) {
481
+ case "BUILT_IN_ERROR": {
482
+ const e = new Error(error.message);
483
+ e.name = error.name;
484
+ e.stack = error.stackTrace;
485
+ return e;
486
+ }
487
+ case "STRING_ERROR": {
488
+ return error.raw;
489
+ }
490
+ case "CUSTOM_ERROR": {
491
+ return JSON.parse(error.raw);
492
+ }
493
+ case "INTERNAL_ERROR": {
494
+ return new Error(`trigger.dev internal error (${error.code})`);
495
+ }
496
+ }
497
+ }
498
+ __name(createErrorTaskError, "createErrorTaskError");
499
+ var SerializedError = z.object({
500
+ message: z.string(),
501
+ name: z.string().optional(),
502
+ stackTrace: z.string().optional()
503
+ });
504
+ function createJsonErrorObject(error) {
505
+ switch (error.type) {
506
+ case "BUILT_IN_ERROR": {
507
+ return {
508
+ name: error.name,
509
+ message: error.message,
510
+ stackTrace: error.stackTrace
511
+ };
512
+ }
513
+ case "STRING_ERROR": {
514
+ return {
515
+ message: error.raw
516
+ };
517
+ }
518
+ case "CUSTOM_ERROR": {
519
+ return {
520
+ message: error.raw
521
+ };
522
+ }
523
+ case "INTERNAL_ERROR": {
524
+ return {
525
+ message: `trigger.dev internal error (${error.code})`
526
+ };
527
+ }
528
+ }
529
+ }
530
+ __name(createJsonErrorObject, "createJsonErrorObject");
531
+ function correctErrorStackTrace(stackTrace, projectDir, options) {
532
+ const [errorLine, ...traceLines] = stackTrace.split("\n");
533
+ return [
534
+ options?.removeFirstLine ? void 0 : errorLine,
535
+ ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
536
+ ].filter(Boolean).join("\n");
537
+ }
538
+ __name(correctErrorStackTrace, "correctErrorStackTrace");
539
+ var LINES_TO_IGNORE = [
540
+ /ConsoleInterceptor/,
541
+ /TriggerTracer/,
542
+ /TaskExecutor/,
543
+ /EXECUTE_TASK_RUN/,
544
+ /@trigger.dev\/core/,
545
+ /packages\/core\/src\/v3/,
546
+ /safeJsonProcess/,
547
+ /__entryPoint.ts/,
548
+ /ZodIpc/,
549
+ /startActiveSpan/,
550
+ /processTicksAndRejections/
551
+ ];
552
+ function correctStackTraceLine(line, projectDir, isDev) {
553
+ if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
554
+ return;
555
+ }
556
+ if (isDev && projectDir && !line.includes(projectDir)) {
557
+ return;
558
+ }
559
+ return line.trim();
560
+ }
561
+ __name(correctStackTraceLine, "correctStackTraceLine");
562
+ function groupTaskMetadataIssuesByTask(tasks, issues) {
563
+ return issues.reduce((acc, issue) => {
564
+ if (issue.path.length === 0) {
565
+ return acc;
566
+ }
567
+ const taskIndex = issue.path[1];
568
+ if (typeof taskIndex !== "number") {
569
+ return acc;
570
+ }
571
+ const task = tasks[taskIndex];
572
+ if (!task) {
573
+ return acc;
574
+ }
575
+ const restOfPath = issue.path.slice(2);
576
+ const taskId = task.id;
577
+ const taskName = task.exportName;
578
+ const filePath = task.filePath;
579
+ const key = taskIndex;
580
+ const existing = acc[key] ?? {
581
+ id: taskId,
582
+ exportName: taskName,
583
+ filePath,
584
+ issues: []
585
+ };
586
+ existing.issues.push({
587
+ message: issue.message,
588
+ path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
589
+ });
590
+ return {
591
+ ...acc,
592
+ [key]: existing
593
+ };
594
+ }, {});
595
+ }
596
+ __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
580
597
 
581
598
  // src/v3/schemas/api.ts
582
599
  var WhoAmIResponseSchema = z.object({
@@ -683,7 +700,8 @@ var InitializeDeploymentRequestBody = z.object({
683
700
  var DeploymentErrorData = z.object({
684
701
  name: z.string(),
685
702
  message: z.string(),
686
- stack: z.string().optional()
703
+ stack: z.string().optional(),
704
+ stderr: z.string().optional()
687
705
  });
688
706
  var GetDeploymentResponseBody = z.object({
689
707
  id: z.string(),
@@ -719,7 +737,7 @@ var ReplayRunResponse = z.object({
719
737
  id: z.string()
720
738
  });
721
739
  var CanceledRunResponse = z.object({
722
- message: z.string()
740
+ id: z.string()
723
741
  });
724
742
  var ScheduledTaskPayload = z.object({
725
743
  /** The schedule id associated with this run (you can have many schedules for the same task).
@@ -769,17 +787,18 @@ var CreateScheduleOptions = z.object({
769
787
  externalId: z.string().optional()
770
788
  });
771
789
  var UpdateScheduleOptions = CreateScheduleOptions;
790
+ var ScheduleGenerator = z.object({
791
+ type: z.literal("CRON"),
792
+ expression: z.string(),
793
+ description: z.string()
794
+ });
772
795
  var ScheduleObject = z.object({
773
796
  id: z.string(),
774
797
  task: z.string(),
775
798
  active: z.boolean(),
776
799
  deduplicationKey: z.string().nullish(),
777
800
  externalId: z.string().nullish(),
778
- generator: z.object({
779
- type: z.literal("CRON"),
780
- expression: z.string(),
781
- description: z.string()
782
- }),
801
+ generator: ScheduleGenerator,
783
802
  nextRun: z.coerce.date().nullish(),
784
803
  environments: z.array(z.object({
785
804
  id: z.string(),
@@ -803,12 +822,28 @@ var ListScheduleOptions = z.object({
803
822
  perPage: z.number().optional()
804
823
  });
805
824
  var RunStatus = z.enum([
806
- "PENDING",
825
+ /// Task hasn't been deployed yet but is waiting to be executed
826
+ "WAITING_FOR_DEPLOY",
827
+ /// Task is waiting to be executed by a worker
828
+ "QUEUED",
829
+ /// Task is currently being executed by a worker
807
830
  "EXECUTING",
808
- "PAUSED",
831
+ /// Task has failed and is waiting to be retried
832
+ "REATTEMPTING",
833
+ /// Task has been paused by the system, and will be resumed by the system
834
+ "FROZEN",
835
+ /// Task has been completed successfully
809
836
  "COMPLETED",
837
+ /// Task has been canceled by the user
838
+ "CANCELED",
839
+ /// Task has been completed with errors
810
840
  "FAILED",
811
- "CANCELED"
841
+ /// Task has crashed and won't be retried, most likely the worker ran out of resources, e.g. memory or storage
842
+ "CRASHED",
843
+ /// Task was interrupted during execution, mostly this happens in development environments
844
+ "INTERRUPTED",
845
+ /// Task has failed to complete, due to an error in the system
846
+ "SYSTEM_FAILURE"
812
847
  ]);
813
848
  var AttemptStatus = z.enum([
814
849
  "PENDING",
@@ -818,23 +853,61 @@ var AttemptStatus = z.enum([
818
853
  "FAILED",
819
854
  "CANCELED"
820
855
  ]);
821
- var RetrieveRunResponse = z.object({
856
+ var RunEnvironmentDetails = z.object({
857
+ id: z.string(),
858
+ name: z.string(),
859
+ user: z.string().optional()
860
+ });
861
+ var RunScheduleDetails = z.object({
862
+ id: z.string(),
863
+ externalId: z.string().optional(),
864
+ deduplicationKey: z.string().optional(),
865
+ generator: ScheduleGenerator
866
+ });
867
+ var CommonRunFields = {
822
868
  id: z.string(),
823
869
  status: RunStatus,
824
870
  taskIdentifier: z.string(),
825
871
  idempotencyKey: z.string().optional(),
826
872
  version: z.string().optional(),
873
+ isQueued: z.boolean(),
874
+ isExecuting: z.boolean(),
875
+ isCompleted: z.boolean(),
876
+ isSuccess: z.boolean(),
877
+ isFailed: z.boolean(),
878
+ isCancelled: z.boolean(),
879
+ isTest: z.boolean(),
827
880
  createdAt: z.coerce.date(),
828
881
  updatedAt: z.coerce.date(),
882
+ startedAt: z.coerce.date().optional(),
883
+ finishedAt: z.coerce.date().optional()
884
+ };
885
+ var RetrieveRunResponse = z.object({
886
+ ...CommonRunFields,
887
+ payload: z.any().optional(),
888
+ output: z.any().optional(),
889
+ schedule: RunScheduleDetails.optional(),
829
890
  attempts: z.array(z.object({
830
891
  id: z.string(),
831
892
  status: AttemptStatus,
832
893
  createdAt: z.coerce.date(),
833
894
  updatedAt: z.coerce.date(),
834
895
  startedAt: z.coerce.date().optional(),
835
- completedAt: z.coerce.date().optional()
896
+ completedAt: z.coerce.date().optional(),
897
+ error: SerializedError.optional()
836
898
  }).optional())
837
899
  });
900
+ var ListRunResponseItem = z.object({
901
+ ...CommonRunFields,
902
+ env: RunEnvironmentDetails
903
+ });
904
+ var ListRunResponse = z.object({
905
+ data: z.array(ListRunResponseItem),
906
+ pagination: z.object({
907
+ next: z.string().optional(),
908
+ previous: z.string().optional()
909
+ })
910
+ });
838
911
  var CreateEnvironmentVariableRequestBody = z.object({
839
912
  name: z.string(),
840
913
  value: z.string()
@@ -1170,20 +1243,13 @@ var ProviderToPlatformMessages = {
1170
1243
  error: z.object({
1171
1244
  name: z.string(),
1172
1245
  message: z.string(),
1173
- stack: z.string().optional()
1246
+ stack: z.string().optional(),
1247
+ stderr: z.string().optional()
1174
1248
  })
1175
1249
  })
1176
1250
  }
1177
1251
  };
1178
1252
  var PlatformToProviderMessages = {
1179
- HEALTH: {
1180
- message: z.object({
1181
- version: z.literal("v1").default("v1")
1182
- }),
1183
- callback: z.object({
1184
- status: z.literal("ok")
1185
- })
1186
- },
1187
1253
  INDEX: {
1188
1254
  message: z.object({
1189
1255
  version: z.literal("v1").default("v1"),
@@ -1204,7 +1270,8 @@ var PlatformToProviderMessages = {
1204
1270
  error: z.object({
1205
1271
  name: z.string(),
1206
1272
  message: z.string(),
1207
- stack: z.string().optional()
1273
+ stack: z.string().optional(),
1274
+ stderr: z.string().optional()
1208
1275
  })
1209
1276
  }),
1210
1277
  z.object({
@@ -1212,7 +1279,6 @@ var PlatformToProviderMessages = {
1212
1279
  })
1213
1280
  ])
1214
1281
  },
1215
- // TODO: this should be a shared queue message instead
1216
1282
  RESTORE: {
1217
1283
  message: z.object({
1218
1284
  version: z.literal("v1").default("v1"),
@@ -1232,21 +1298,6 @@ var PlatformToProviderMessages = {
1232
1298
  projectId: z.string(),
1233
1299
  runId: z.string()
1234
1300
  })
1235
- },
1236
- DELETE: {
1237
- message: z.object({
1238
- version: z.literal("v1").default("v1"),
1239
- name: z.string()
1240
- }),
1241
- callback: z.object({
1242
- message: z.string()
1243
- })
1244
- },
1245
- GET: {
1246
- message: z.object({
1247
- version: z.literal("v1").default("v1"),
1248
- name: z.string()
1249
- })
1250
1301
  }
1251
1302
  };
1252
1303
  var CreateWorkerMessage = z.object({
@@ -1409,7 +1460,8 @@ var CoordinatorToPlatformMessages = {
1409
1460
  error: z.object({
1410
1461
  name: z.string(),
1411
1462
  message: z.string(),
1412
- stack: z.string().optional()
1463
+ stack: z.string().optional(),
1464
+ stderr: z.string().optional()
1413
1465
  })
1414
1466
  })
1415
1467
  },
@@ -1647,7 +1699,8 @@ var ProdWorkerToCoordinatorMessages = {
1647
1699
  error: z.object({
1648
1700
  name: z.string(),
1649
1701
  message: z.string(),
1650
- stack: z.string().optional()
1702
+ stack: z.string().optional(),
1703
+ stderr: z.string().optional()
1651
1704
  })
1652
1705
  })
1653
1706
  },
@@ -2085,15 +2138,153 @@ var _TaskContextAPI = class _TaskContextAPI {
2085
2138
  return registerGlobal(API_NAME, taskContext2);
2086
2139
  }
2087
2140
  };
2088
- _getTaskContext = new WeakSet();
2089
- getTaskContext_fn = /* @__PURE__ */ __name(function() {
2090
- return getGlobal(API_NAME);
2091
- }, "#getTaskContext");
2092
- __name(_TaskContextAPI, "TaskContextAPI");
2093
- var TaskContextAPI = _TaskContextAPI;
2094
-
2095
- // src/v3/task-context-api.ts
2096
- var taskContext = TaskContextAPI.getInstance();
2141
+ _getTaskContext = new WeakSet();
2142
+ getTaskContext_fn = /* @__PURE__ */ __name(function() {
2143
+ return getGlobal(API_NAME);
2144
+ }, "#getTaskContext");
2145
+ __name(_TaskContextAPI, "TaskContextAPI");
2146
+ var TaskContextAPI = _TaskContextAPI;
2147
+
2148
+ // src/v3/task-context-api.ts
2149
+ var taskContext = TaskContextAPI.getInstance();
2150
+
2151
+ // src/v3/apiClient/errors.ts
2152
+ var _ApiError = class _ApiError extends Error {
2153
+ constructor(status, error, message, headers) {
2154
+ super(`${_ApiError.makeMessage(status, error, message)}`);
2155
+ this.status = status;
2156
+ this.headers = headers;
2157
+ const data = error;
2158
+ this.error = data;
2159
+ this.code = data?.["code"];
2160
+ this.param = data?.["param"];
2161
+ this.type = data?.["type"];
2162
+ }
2163
+ static makeMessage(status, error, message) {
2164
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
2165
+ if (status && msg) {
2166
+ return `${status} ${msg}`;
2167
+ }
2168
+ if (status) {
2169
+ return `${status} status code (no body)`;
2170
+ }
2171
+ if (msg) {
2172
+ return msg;
2173
+ }
2174
+ return "(no status code or body)";
2175
+ }
2176
+ static generate(status, errorResponse, message, headers) {
2177
+ if (!status) {
2178
+ return new ApiConnectionError({
2179
+ cause: castToError(errorResponse)
2180
+ });
2181
+ }
2182
+ const error = errorResponse?.["error"];
2183
+ if (status === 400) {
2184
+ return new BadRequestError(status, error, message, headers);
2185
+ }
2186
+ if (status === 401) {
2187
+ return new AuthenticationError(status, error, message, headers);
2188
+ }
2189
+ if (status === 403) {
2190
+ return new PermissionDeniedError(status, error, message, headers);
2191
+ }
2192
+ if (status === 404) {
2193
+ return new NotFoundError(status, error, message, headers);
2194
+ }
2195
+ if (status === 409) {
2196
+ return new ConflictError(status, error, message, headers);
2197
+ }
2198
+ if (status === 422) {
2199
+ return new UnprocessableEntityError(status, error, message, headers);
2200
+ }
2201
+ if (status === 429) {
2202
+ return new RateLimitError(status, error, message, headers);
2203
+ }
2204
+ if (status >= 500) {
2205
+ return new InternalServerError(status, error, message, headers);
2206
+ }
2207
+ return new _ApiError(status, error, message, headers);
2208
+ }
2209
+ };
2210
+ __name(_ApiError, "ApiError");
2211
+ var ApiError = _ApiError;
2212
+ var _ApiConnectionError = class _ApiConnectionError extends ApiError {
2213
+ constructor({ message, cause }) {
2214
+ super(void 0, void 0, message || "Connection error.", void 0);
2215
+ __publicField(this, "status");
2216
+ if (cause)
2217
+ this.cause = cause;
2218
+ }
2219
+ };
2220
+ __name(_ApiConnectionError, "ApiConnectionError");
2221
+ var ApiConnectionError = _ApiConnectionError;
2222
+ var _BadRequestError = class _BadRequestError extends ApiError {
2223
+ constructor() {
2224
+ super(...arguments);
2225
+ __publicField(this, "status", 400);
2226
+ }
2227
+ };
2228
+ __name(_BadRequestError, "BadRequestError");
2229
+ var BadRequestError = _BadRequestError;
2230
+ var _AuthenticationError = class _AuthenticationError extends ApiError {
2231
+ constructor() {
2232
+ super(...arguments);
2233
+ __publicField(this, "status", 401);
2234
+ }
2235
+ };
2236
+ __name(_AuthenticationError, "AuthenticationError");
2237
+ var AuthenticationError = _AuthenticationError;
2238
+ var _PermissionDeniedError = class _PermissionDeniedError extends ApiError {
2239
+ constructor() {
2240
+ super(...arguments);
2241
+ __publicField(this, "status", 403);
2242
+ }
2243
+ };
2244
+ __name(_PermissionDeniedError, "PermissionDeniedError");
2245
+ var PermissionDeniedError = _PermissionDeniedError;
2246
+ var _NotFoundError = class _NotFoundError extends ApiError {
2247
+ constructor() {
2248
+ super(...arguments);
2249
+ __publicField(this, "status", 404);
2250
+ }
2251
+ };
2252
+ __name(_NotFoundError, "NotFoundError");
2253
+ var NotFoundError = _NotFoundError;
2254
+ var _ConflictError = class _ConflictError extends ApiError {
2255
+ constructor() {
2256
+ super(...arguments);
2257
+ __publicField(this, "status", 409);
2258
+ }
2259
+ };
2260
+ __name(_ConflictError, "ConflictError");
2261
+ var ConflictError = _ConflictError;
2262
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends ApiError {
2263
+ constructor() {
2264
+ super(...arguments);
2265
+ __publicField(this, "status", 422);
2266
+ }
2267
+ };
2268
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
2269
+ var UnprocessableEntityError = _UnprocessableEntityError;
2270
+ var _RateLimitError = class _RateLimitError extends ApiError {
2271
+ constructor() {
2272
+ super(...arguments);
2273
+ __publicField(this, "status", 429);
2274
+ }
2275
+ };
2276
+ __name(_RateLimitError, "RateLimitError");
2277
+ var RateLimitError = _RateLimitError;
2278
+ var _InternalServerError = class _InternalServerError extends ApiError {
2279
+ };
2280
+ __name(_InternalServerError, "InternalServerError");
2281
+ var InternalServerError = _InternalServerError;
2282
+ function castToError(err) {
2283
+ if (err instanceof Error)
2284
+ return err;
2285
+ return new Error(err);
2286
+ }
2287
+ __name(castToError, "castToError");
2097
2288
 
2098
2289
  // src/retry.ts
2099
2290
  function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
@@ -2201,6 +2392,108 @@ function calculateResetAt2(resets, format, now = Date.now()) {
2201
2392
  return resetAt?.getTime();
2202
2393
  }
2203
2394
  __name(calculateResetAt2, "calculateResetAt");
2395
+
2396
+ // src/v3/apiClient/pagination.ts
2397
+ var _CursorPage = class _CursorPage {
2398
+ constructor(data, pagination, pageFetcher) {
2399
+ this.pageFetcher = pageFetcher;
2400
+ this.data = data;
2401
+ this.pagination = pagination;
2402
+ }
2403
+ getPaginatedItems() {
2404
+ return this.data ?? [];
2405
+ }
2406
+ hasNextPage() {
2407
+ return !!this.pagination.next;
2408
+ }
2409
+ hasPreviousPage() {
2410
+ return !!this.pagination.previous;
2411
+ }
2412
+ getNextPage() {
2413
+ if (!this.pagination.next) {
2414
+ throw new Error("No next page available");
2415
+ }
2416
+ return this.pageFetcher({
2417
+ after: this.pagination.next
2418
+ });
2419
+ }
2420
+ getPreviousPage() {
2421
+ if (!this.pagination.previous) {
2422
+ throw new Error("No previous page available");
2423
+ }
2424
+ return this.pageFetcher({
2425
+ before: this.pagination.previous
2426
+ });
2427
+ }
2428
+ async *iterPages() {
2429
+ let page = this;
2430
+ yield page;
2431
+ while (page.hasNextPage()) {
2432
+ page = await page.getNextPage();
2433
+ yield page;
2434
+ }
2435
+ }
2436
+ async *[Symbol.asyncIterator]() {
2437
+ for await (const page of this.iterPages()) {
2438
+ for (const item of page.getPaginatedItems()) {
2439
+ yield item;
2440
+ }
2441
+ }
2442
+ }
2443
+ };
2444
+ __name(_CursorPage, "CursorPage");
2445
+ var CursorPage = _CursorPage;
2446
+ var _OffsetLimitPage = class _OffsetLimitPage {
2447
+ constructor(data, pagination, pageFetcher) {
2448
+ this.pageFetcher = pageFetcher;
2449
+ this.data = data;
2450
+ this.pagination = pagination;
2451
+ }
2452
+ getPaginatedItems() {
2453
+ return this.data ?? [];
2454
+ }
2455
+ hasNextPage() {
2456
+ return this.pagination.currentPage < this.pagination.totalPages;
2457
+ }
2458
+ hasPreviousPage() {
2459
+ return this.pagination.currentPage > 1;
2460
+ }
2461
+ getNextPage() {
2462
+ if (!this.hasNextPage()) {
2463
+ throw new Error("No next page available");
2464
+ }
2465
+ return this.pageFetcher({
2466
+ page: this.pagination.currentPage + 1
2467
+ });
2468
+ }
2469
+ getPreviousPage() {
2470
+ if (!this.hasPreviousPage()) {
2471
+ throw new Error("No previous page available");
2472
+ }
2473
+ return this.pageFetcher({
2474
+ page: this.pagination.currentPage - 1
2475
+ });
2476
+ }
2477
+ async *iterPages() {
2478
+ let page = this;
2479
+ yield page;
2480
+ while (page.hasNextPage()) {
2481
+ page = await page.getNextPage();
2482
+ yield page;
2483
+ }
2484
+ }
2485
+ async *[Symbol.asyncIterator]() {
2486
+ for await (const page of this.iterPages()) {
2487
+ for (const item of page.getPaginatedItems()) {
2488
+ yield item;
2489
+ }
2490
+ }
2491
+ }
2492
+ };
2493
+ __name(_OffsetLimitPage, "OffsetLimitPage");
2494
+ var OffsetLimitPage = _OffsetLimitPage;
2495
+
2496
+ // src/v3/apiClient/core.ts
2204
2497
  var defaultRetryOptions2 = {
2205
2498
  maxAttempts: 3,
2206
2499
  factor: 2,
@@ -2208,11 +2501,62 @@ var defaultRetryOptions2 = {
2208
2501
  maxTimeoutInMs: 6e4,
2209
2502
  randomize: false
2210
2503
  };
2211
- async function zodfetch(schema, url, requestInit, options) {
2212
- return await _doZodFetch(schema, url, requestInit, options);
2504
+ function zodfetch(schema, url, requestInit, options) {
2505
+ return new ApiPromise(_doZodFetch(schema, url, requestInit, options));
2213
2506
  }
2214
2507
  __name(zodfetch, "zodfetch");
2215
- async function zodupload(schema, url, body, requestInit, options) {
2508
+ function zodfetchCursorPage(schema, url, params, requestInit, options) {
2509
+ const query = new URLSearchParams(params.query);
2510
+ if (params.limit) {
2511
+ query.set("page[size]", String(params.limit));
2512
+ }
2513
+ if (params.after) {
2514
+ query.set("page[after]", params.after);
2515
+ }
2516
+ if (params.before) {
2517
+ query.set("page[before]", params.before);
2518
+ }
2519
+ const cursorPageSchema = z.object({
2520
+ data: z.array(schema),
2521
+ pagination: z.object({
2522
+ next: z.string().optional(),
2523
+ previous: z.string().optional()
2524
+ })
2525
+ });
2526
+ const $url = new URL(url);
2527
+ $url.search = query.toString();
2528
+ const fetchResult = _doZodFetch(cursorPageSchema, $url.href, requestInit, options);
2529
+ return new CursorPagePromise(fetchResult, schema, url, params, requestInit, options);
2530
+ }
2531
+ __name(zodfetchCursorPage, "zodfetchCursorPage");
2532
+ function zodfetchOffsetLimitPage(schema, url, params, requestInit, options) {
2533
+ const query = new URLSearchParams(params.query);
2534
+ if (params.limit) {
2535
+ query.set("perPage", String(params.limit));
2536
+ }
2537
+ if (params.page) {
2538
+ query.set("page", String(params.page));
2539
+ }
2540
+ const offsetLimitPageSchema = z.object({
2541
+ data: z.array(schema),
2542
+ pagination: z.object({
2543
+ currentPage: z.coerce.number(),
2544
+ totalPages: z.coerce.number(),
2545
+ count: z.coerce.number()
2546
+ })
2547
+ });
2548
+ const $url = new URL(url);
2549
+ $url.search = query.toString();
2550
+ const fetchResult = _doZodFetch(offsetLimitPageSchema, $url.href, requestInit, options);
2551
+ return new OffsetLimitPagePromise(fetchResult, schema, url, params, requestInit, options);
2552
+ }
2553
+ __name(zodfetchOffsetLimitPage, "zodfetchOffsetLimitPage");
2554
+ function zodupload(schema, url, body, requestInit, options) {
2555
+ const finalRequestInit = createMultipartFormRequestInit(body, requestInit);
2556
+ return new ApiPromise(_doZodFetch(schema, url, finalRequestInit, options));
2557
+ }
2558
+ __name(zodupload, "zodupload");
2559
+ async function createMultipartFormRequestInit(body, requestInit) {
2216
2560
  const form = await createForm(body);
2217
2561
  const encoder = new FormDataEncoder(form);
2218
2562
  const finalHeaders = {};
@@ -2230,9 +2574,9 @@ async function zodupload(schema, url, body, requestInit, options) {
2230
2574
  // @ts-expect-error
2231
2575
  duplex: "half"
2232
2576
  };
2233
- return await _doZodFetch(schema, url, finalRequestInit, options);
2577
+ return finalRequestInit;
2234
2578
  }
2235
- __name(zodupload, "zodupload");
2579
+ __name(createMultipartFormRequestInit, "createMultipartFormRequestInit");
2236
2580
  var createForm = /* @__PURE__ */ __name(async (body) => {
2237
2581
  const form = new FormData();
2238
2582
  await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));
@@ -2240,7 +2584,8 @@ var createForm = /* @__PURE__ */ __name(async (body) => {
2240
2584
  }, "createForm");
2241
2585
  async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2242
2586
  try {
2243
- const response = await fetch(url, requestInitWithCache(requestInit));
2587
+ const $requestInit = await requestInit;
2588
+ const response = await fetch(url, requestInitWithCache($requestInit));
2244
2589
  const responseHeaders = createResponseHeaders(response.headers);
2245
2590
  if (!response.ok) {
2246
2591
  const retryResult = shouldRetry(response, attempt, options?.retry);
@@ -2251,17 +2596,20 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2251
2596
  const errText = await response.text().catch((e) => castToError2(e).message);
2252
2597
  const errJSON = safeJsonParse(errText);
2253
2598
  const errMessage = errJSON ? void 0 : errText;
2254
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
2599
+ throw ApiError.generate(response.status, errJSON, errMessage, responseHeaders);
2255
2600
  }
2256
2601
  }
2257
2602
  const jsonBody = await response.json();
2258
2603
  const parsedResult = schema.safeParse(jsonBody);
2259
2604
  if (parsedResult.success) {
2260
- return parsedResult.data;
2605
+ return {
2606
+ data: parsedResult.data,
2607
+ response
2608
+ };
2261
2609
  }
2262
2610
  throw fromZodError(parsedResult.error);
2263
2611
  } catch (error) {
2264
- if (error instanceof APIError) {
2612
+ if (error instanceof ApiError) {
2265
2613
  throw error;
2266
2614
  }
2267
2615
  if (options?.retry) {
@@ -2275,7 +2623,7 @@ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
2275
2623
  return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
2276
2624
  }
2277
2625
  }
2278
- throw new APIConnectionError({
2626
+ throw new ApiConnectionError({
2279
2627
  cause: castToError2(error)
2280
2628
  });
2281
2629
  }
@@ -2448,6 +2796,128 @@ var isUploadable = /* @__PURE__ */ __name((value) => {
2448
2796
  return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);
2449
2797
  }, "isUploadable");
2450
2798
  var isRecordLike = /* @__PURE__ */ __name((value) => value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => typeof key === "string" && typeof value[key] === "string"), "isRecordLike");
2799
+ var _ApiPromise = class _ApiPromise extends Promise {
2800
+ constructor(responsePromise) {
2801
+ super((resolve) => {
2802
+ resolve(null);
2803
+ });
2804
+ this.responsePromise = responsePromise;
2805
+ }
2806
+ /**
2807
+ * Gets the raw `Response` instance instead of parsing the response
2808
+ * data.
2809
+ *
2810
+ * If you want to parse the response body but still get the `Response`
2811
+ * instance, you can use {@link withResponse()}.
2812
+ */
2813
+ asResponse() {
2814
+ return this.responsePromise.then((p) => p.response);
2815
+ }
2816
+ /**
2817
+ * Gets the parsed response data and the raw `Response` instance.
2818
+ *
2819
+ * If you just want to get the raw `Response` instance without parsing it,
2820
+ * you can use {@link asResponse()}.
2821
+ */
2822
+ async withResponse() {
2823
+ const [data, response] = await Promise.all([
2824
+ this.parse(),
2825
+ this.asResponse()
2826
+ ]);
2827
+ return {
2828
+ data,
2829
+ response
2830
+ };
2831
+ }
2832
+ parse() {
2833
+ return this.responsePromise.then((result) => result.data);
2834
+ }
2835
+ then(onfulfilled, onrejected) {
2836
+ return this.parse().then(onfulfilled, onrejected);
2837
+ }
2838
+ catch(onrejected) {
2839
+ return this.parse().catch(onrejected);
2840
+ }
2841
+ finally(onfinally) {
2842
+ return this.parse().finally(onfinally);
2843
+ }
2844
+ };
2845
+ __name(_ApiPromise, "ApiPromise");
2846
+ var ApiPromise = _ApiPromise;
2847
+ var _fetchPage, fetchPage_fn;
2848
+ var _CursorPagePromise = class _CursorPagePromise extends ApiPromise {
2849
+ constructor(result, schema, url, params, requestInit, options) {
2850
+ super(result.then((result2) => ({
2851
+ data: new CursorPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage, fetchPage_fn).bind(this)),
2852
+ response: result2.response
2853
+ })));
2854
+ __privateAdd(this, _fetchPage);
2855
+ this.schema = schema;
2856
+ this.url = url;
2857
+ this.params = params;
2858
+ this.requestInit = requestInit;
2859
+ this.options = options;
2860
+ }
2861
+ /**
2862
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2863
+ *
2864
+ * for await (const item of client.items.list()) {
2865
+ * console.log(item)
2866
+ * }
2867
+ */
2868
+ async *[Symbol.asyncIterator]() {
2869
+ const page = await this;
2870
+ for await (const item of page) {
2871
+ yield item;
2872
+ }
2873
+ }
2874
+ };
2875
+ _fetchPage = new WeakSet();
2876
+ fetchPage_fn = /* @__PURE__ */ __name(function(params) {
2877
+ return zodfetchCursorPage(this.schema, this.url, {
2878
+ ...this.params,
2879
+ ...params
2880
+ }, this.requestInit, this.options);
2881
+ }, "#fetchPage");
2882
+ __name(_CursorPagePromise, "CursorPagePromise");
2883
+ var CursorPagePromise = _CursorPagePromise;
2884
+ var _fetchPage2, fetchPage_fn2;
2885
+ var _OffsetLimitPagePromise = class _OffsetLimitPagePromise extends ApiPromise {
2886
+ constructor(result, schema, url, params, requestInit, options) {
2887
+ super(result.then((result2) => ({
2888
+ data: new OffsetLimitPage(result2.data.data, result2.data.pagination, __privateMethod(this, _fetchPage2, fetchPage_fn2).bind(this)),
2889
+ response: result2.response
2890
+ })));
2891
+ __privateAdd(this, _fetchPage2);
2892
+ this.schema = schema;
2893
+ this.url = url;
2894
+ this.params = params;
2895
+ this.requestInit = requestInit;
2896
+ this.options = options;
2897
+ }
2898
+ /**
2899
+ * Allow auto-paginating iteration on an unawaited list call, eg:
2900
+ *
2901
+ * for await (const item of client.items.list()) {
2902
+ * console.log(item)
2903
+ * }
2904
+ */
2905
+ async *[Symbol.asyncIterator]() {
2906
+ const page = await this;
2907
+ for await (const item of page) {
2908
+ yield item;
2909
+ }
2910
+ }
2911
+ };
2912
+ _fetchPage2 = new WeakSet();
2913
+ fetchPage_fn2 = /* @__PURE__ */ __name(function(params1) {
2914
+ return zodfetchOffsetLimitPage(this.schema, this.url, {
2915
+ ...this.params,
2916
+ ...params1
2917
+ }, this.requestInit, this.options);
2918
+ }, "#fetchPage");
2919
+ __name(_OffsetLimitPagePromise, "OffsetLimitPagePromise");
2920
+ var OffsetLimitPagePromise = _OffsetLimitPagePromise;
2451
2921
 
2452
2922
  // src/v3/apiClient/index.ts
2453
2923
  var zodFetchOptions = {
@@ -2473,7 +2943,7 @@ var _ApiClient = class _ApiClient {
2473
2943
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2474
2944
  }, zodFetchOptions);
2475
2945
  } catch (error) {
2476
- if (error instanceof APIError) {
2946
+ if (error instanceof ApiError) {
2477
2947
  if (error.status === 404) {
2478
2948
  return void 0;
2479
2949
  }
@@ -2488,14 +2958,16 @@ var _ApiClient = class _ApiClient {
2488
2958
  }, zodFetchOptions);
2489
2959
  }
2490
2960
  triggerTask(taskId, body, options) {
2491
- return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/trigger`, {
2961
+ const encodedTaskId = encodeURIComponent(taskId);
2962
+ return zodfetch(TriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/trigger`, {
2492
2963
  method: "POST",
2493
2964
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2494
2965
  body: JSON.stringify(body)
2495
2966
  }, zodFetchOptions);
2496
2967
  }
2497
2968
  batchTriggerTask(taskId, body, options) {
2498
- return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${taskId}/batch`, {
2969
+ const encodedTaskId = encodeURIComponent(taskId);
2970
+ return zodfetch(BatchTriggerTaskResponse, `${this.baseUrl}/api/v1/tasks/${encodedTaskId}/batch`, {
2499
2971
  method: "POST",
2500
2972
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, options?.spanParentAsLink ?? false),
2501
2973
  body: JSON.stringify(body)
@@ -2519,6 +2991,33 @@ var _ApiClient = class _ApiClient {
2519
2991
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2520
2992
  }, zodFetchOptions);
2521
2993
  }
2994
+ listRuns(query) {
2995
+ const searchParams = createSearchQueryForListRuns(query);
2996
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/runs`, {
2997
+ query: searchParams,
2998
+ limit: query?.limit,
2999
+ after: query?.after,
3000
+ before: query?.before
3001
+ }, {
3002
+ method: "GET",
3003
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3004
+ }, zodFetchOptions);
3005
+ }
3006
+ listProjectRuns(projectRef, query) {
3007
+ const searchParams = createSearchQueryForListRuns(query);
3008
+ if (query?.env) {
3009
+ searchParams.append("filter[env]", Array.isArray(query.env) ? query.env.join(",") : query.env);
3010
+ }
3011
+ return zodfetchCursorPage(ListRunResponseItem, `${this.baseUrl}/api/v1/projects/${projectRef}/runs`, {
3012
+ query: searchParams,
3013
+ limit: query?.limit,
3014
+ after: query?.after,
3015
+ before: query?.before
3016
+ }, {
3017
+ method: "GET",
3018
+ headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
3019
+ }, zodFetchOptions);
3020
+ }
2522
3021
  replayRun(runId) {
2523
3022
  return zodfetch(ReplayRunResponse, `${this.baseUrl}/api/v1/runs/${runId}/replay`, {
2524
3023
  method: "POST",
@@ -2546,7 +3045,10 @@ var _ApiClient = class _ApiClient {
2546
3045
  if (options?.perPage) {
2547
3046
  searchParams.append("perPage", options.perPage.toString());
2548
3047
  }
2549
- return zodfetch(ListSchedulesResult, `${this.baseUrl}/api/v1/schedules${searchParams.size > 0 ? `?${searchParams}` : ""}`, {
3048
+ return zodfetchOffsetLimitPage(ScheduleObject, `${this.baseUrl}/api/v1/schedules`, {
3049
+ page: options?.page,
3050
+ limit: options?.perPage
3051
+ }, {
2550
3052
  method: "GET",
2551
3053
  headers: __privateMethod(this, _getHeaders, getHeaders_fn).call(this, false)
2552
3054
  });
@@ -2647,6 +3149,40 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2647
3149
  }, "#getHeaders");
2648
3150
  __name(_ApiClient, "ApiClient");
2649
3151
  var ApiClient = _ApiClient;
3152
+ function createSearchQueryForListRuns(query) {
3153
+ const searchParams = new URLSearchParams();
3154
+ if (query) {
3155
+ if (query.status) {
3156
+ searchParams.append("filter[status]", Array.isArray(query.status) ? query.status.join(",") : query.status);
3157
+ }
3158
+ if (query.taskIdentifier) {
3159
+ searchParams.append("filter[taskIdentifier]", Array.isArray(query.taskIdentifier) ? query.taskIdentifier.join(",") : query.taskIdentifier);
3160
+ }
3161
+ if (query.version) {
3162
+ searchParams.append("filter[version]", Array.isArray(query.version) ? query.version.join(",") : query.version);
3163
+ }
3164
+ if (query.bulkAction) {
3165
+ searchParams.append("filter[bulkAction]", query.bulkAction);
3166
+ }
3167
+ if (query.schedule) {
3168
+ searchParams.append("filter[schedule]", query.schedule);
3169
+ }
3170
+ if (typeof query.isTest === "boolean") {
3171
+ searchParams.append("filter[isTest]", String(query.isTest));
3172
+ }
3173
+ if (query.from) {
3174
+ searchParams.append("filter[createdAt][from]", query.from instanceof Date ? query.from.getTime().toString() : query.from.toString());
3175
+ }
3176
+ if (query.to) {
3177
+ searchParams.append("filter[createdAt][to]", query.to instanceof Date ? query.to.getTime().toString() : query.to.toString());
3178
+ }
3179
+ if (query.period) {
3180
+ searchParams.append("filter[createdAt][period]", query.period);
3181
+ }
3182
+ }
3183
+ return searchParams;
3184
+ }
3185
+ __name(createSearchQueryForListRuns, "createSearchQueryForListRuns");
2650
3186
  var _SimpleClock = class _SimpleClock {
2651
3187
  preciseNow() {
2652
3188
  const now = new PreciseDate();
@@ -2696,149 +3232,6 @@ var ClockAPI = _ClockAPI;
2696
3232
  // src/v3/clock-api.ts
2697
3233
  var clock = ClockAPI.getInstance();
2698
3234
 
2699
- // src/v3/errors.ts
2700
- function parseError(error) {
2701
- if (error instanceof Error) {
2702
- return {
2703
- type: "BUILT_IN_ERROR",
2704
- name: error.name,
2705
- message: error.message,
2706
- stackTrace: error.stack ?? ""
2707
- };
2708
- }
2709
- if (typeof error === "string") {
2710
- return {
2711
- type: "STRING_ERROR",
2712
- raw: error
2713
- };
2714
- }
2715
- try {
2716
- return {
2717
- type: "CUSTOM_ERROR",
2718
- raw: JSON.stringify(error)
2719
- };
2720
- } catch (e) {
2721
- return {
2722
- type: "CUSTOM_ERROR",
2723
- raw: String(error)
2724
- };
2725
- }
2726
- }
2727
- __name(parseError, "parseError");
2728
- function createErrorTaskError(error) {
2729
- switch (error.type) {
2730
- case "BUILT_IN_ERROR": {
2731
- const e = new Error(error.message);
2732
- e.name = error.name;
2733
- e.stack = error.stackTrace;
2734
- return e;
2735
- }
2736
- case "STRING_ERROR": {
2737
- return error.raw;
2738
- }
2739
- case "CUSTOM_ERROR": {
2740
- return JSON.parse(error.raw);
2741
- }
2742
- case "INTERNAL_ERROR": {
2743
- return new Error(`trigger.dev internal error (${error.code})`);
2744
- }
2745
- }
2746
- }
2747
- __name(createErrorTaskError, "createErrorTaskError");
2748
- function createJsonErrorObject(error) {
2749
- switch (error.type) {
2750
- case "BUILT_IN_ERROR": {
2751
- return {
2752
- name: error.name,
2753
- message: error.message,
2754
- stackTrace: error.stackTrace
2755
- };
2756
- }
2757
- case "STRING_ERROR": {
2758
- return {
2759
- message: error.raw
2760
- };
2761
- }
2762
- case "CUSTOM_ERROR": {
2763
- return {
2764
- message: error.raw
2765
- };
2766
- }
2767
- case "INTERNAL_ERROR": {
2768
- return {
2769
- message: `trigger.dev internal error (${error.code})`
2770
- };
2771
- }
2772
- }
2773
- }
2774
- __name(createJsonErrorObject, "createJsonErrorObject");
2775
- function correctErrorStackTrace(stackTrace, projectDir, options) {
2776
- const [errorLine, ...traceLines] = stackTrace.split("\n");
2777
- return [
2778
- options?.removeFirstLine ? void 0 : errorLine,
2779
- ...traceLines.map((line) => correctStackTraceLine(line, projectDir, options?.isDev))
2780
- ].filter(Boolean).join("\n");
2781
- }
2782
- __name(correctErrorStackTrace, "correctErrorStackTrace");
2783
- var LINES_TO_IGNORE = [
2784
- /ConsoleInterceptor/,
2785
- /TriggerTracer/,
2786
- /TaskExecutor/,
2787
- /EXECUTE_TASK_RUN/,
2788
- /@trigger.dev\/core/,
2789
- /packages\/core\/src\/v3/,
2790
- /safeJsonProcess/,
2791
- /__entryPoint.ts/,
2792
- /ZodIpc/,
2793
- /startActiveSpan/,
2794
- /processTicksAndRejections/
2795
- ];
2796
- function correctStackTraceLine(line, projectDir, isDev) {
2797
- if (LINES_TO_IGNORE.some((regex) => regex.test(line))) {
2798
- return;
2799
- }
2800
- if (isDev && projectDir && !line.includes(projectDir)) {
2801
- return;
2802
- }
2803
- return line.trim();
2804
- }
2805
- __name(correctStackTraceLine, "correctStackTraceLine");
2806
- function groupTaskMetadataIssuesByTask(tasks, issues) {
2807
- return issues.reduce((acc, issue) => {
2808
- if (issue.path.length === 0) {
2809
- return acc;
2810
- }
2811
- const taskIndex = issue.path[1];
2812
- if (typeof taskIndex !== "number") {
2813
- return acc;
2814
- }
2815
- const task = tasks[taskIndex];
2816
- if (!task) {
2817
- return acc;
2818
- }
2819
- const restOfPath = issue.path.slice(2);
2820
- const taskId = task.id;
2821
- const taskName = task.exportName;
2822
- const filePath = task.filePath;
2823
- const key = taskIndex;
2824
- const existing = acc[key] ?? {
2825
- id: taskId,
2826
- exportName: taskName,
2827
- filePath,
2828
- issues: []
2829
- };
2830
- existing.issues.push({
2831
- message: issue.message,
2832
- path: restOfPath.length === 0 ? void 0 : restOfPath.join(".")
2833
- });
2834
- return {
2835
- ...acc,
2836
- [key]: existing
2837
- };
2838
- }, {});
2839
- }
2840
- __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2841
-
2842
3235
  // src/v3/limits.ts
2843
3236
  var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2844
3237
  var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
@@ -3870,6 +4263,6 @@ function safeJsonParse2(value) {
3870
4263
  }
3871
4264
  __name(safeJsonParse2, "safeJsonParse");
3872
4265
 
3873
- export { APIConnectionError, APIError, ApiClient, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunStatus, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
4266
+ export { ApiClient, ApiConnectionError, ApiError, AttemptStatus, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateEnvironmentVariableRequestBody, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, CursorPage, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EnvironmentVariable, EnvironmentVariableResponseBody, EnvironmentVariableValue, EnvironmentVariables, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, ImportEnvironmentVariablesRequestBody, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListRunResponse, ListRunResponseItem, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, NULL_SENTINEL, NotFoundError, OFFLOAD_IO_PACKET_LENGTH_LIMIT, OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT, OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT, OTEL_LINK_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_COUNT_LIMIT, OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT, OTEL_SPAN_EVENT_COUNT_LIMIT, OffsetLimitPage, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetrieveRunResponse, RetryOptions, RunEnvironmentDetails, RunScheduleDetails, RunStatus, ScheduleGenerator, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SerializedError, SharedQueueToClientMessages, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskEventStyle, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionLazyAttemptPayload, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateEnvironmentVariableRequestBody, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createJsonErrorObject, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, groupTaskMetadataIssuesByTask, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseError, parsePacket, prettyPrintPacket, primitiveValueOrflattenedAttributes, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContext, unflattenAttributes, workerToChildMessages };
3874
4267
  //# sourceMappingURL=out.js.map
3875
4268
  //# sourceMappingURL=index.mjs.map