@trigger.dev/core 0.0.0-v3-trigger-dirs-20240423123825 → 0.0.0-v3-update-command-20240423125505

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 (65) hide show
  1. package/dist/v3/index.d.mts +17310 -260
  2. package/dist/v3/index.d.ts +17310 -260
  3. package/dist/v3/index.js +2569 -794
  4. package/dist/v3/index.js.map +1 -1
  5. package/dist/v3/index.mjs +2545 -796
  6. package/dist/v3/index.mjs.map +1 -1
  7. package/dist/v3/otel/index.js +38 -62
  8. package/dist/v3/otel/index.js.map +1 -1
  9. package/dist/v3/otel/index.mjs +38 -62
  10. package/dist/v3/otel/index.mjs.map +1 -1
  11. package/package.json +7 -71
  12. package/dist/catalog-e2OUDZEa.d.mts +0 -6645
  13. package/dist/catalog-ndN7py2b.d.ts +0 -6645
  14. package/dist/manager-M9GLDnhJ.d.mts +0 -1158
  15. package/dist/manager-M9GLDnhJ.d.ts +0 -1158
  16. package/dist/messages-AriaDDm0.d.mts +0 -8696
  17. package/dist/messages-AriaDDm0.d.ts +0 -8696
  18. package/dist/v3/dev/index.d.mts +0 -28
  19. package/dist/v3/dev/index.d.ts +0 -28
  20. package/dist/v3/dev/index.js +0 -93
  21. package/dist/v3/dev/index.js.map +0 -1
  22. package/dist/v3/dev/index.mjs +0 -91
  23. package/dist/v3/dev/index.mjs.map +0 -1
  24. package/dist/v3/prod/index.d.mts +0 -45
  25. package/dist/v3/prod/index.d.ts +0 -45
  26. package/dist/v3/prod/index.js +0 -205
  27. package/dist/v3/prod/index.js.map +0 -1
  28. package/dist/v3/prod/index.mjs +0 -203
  29. package/dist/v3/prod/index.mjs.map +0 -1
  30. package/dist/v3/utils/structuredLogger.d.mts +0 -31
  31. package/dist/v3/utils/structuredLogger.d.ts +0 -31
  32. package/dist/v3/utils/structuredLogger.js +0 -88
  33. package/dist/v3/utils/structuredLogger.js.map +0 -1
  34. package/dist/v3/utils/structuredLogger.mjs +0 -86
  35. package/dist/v3/utils/structuredLogger.mjs.map +0 -1
  36. package/dist/v3/workers/index.d.mts +0 -94
  37. package/dist/v3/workers/index.d.ts +0 -94
  38. package/dist/v3/workers/index.js +0 -2660
  39. package/dist/v3/workers/index.js.map +0 -1
  40. package/dist/v3/workers/index.mjs +0 -2644
  41. package/dist/v3/workers/index.mjs.map +0 -1
  42. package/dist/v3/zodIpc.d.mts +0 -32
  43. package/dist/v3/zodIpc.d.ts +0 -32
  44. package/dist/v3/zodIpc.js +0 -268
  45. package/dist/v3/zodIpc.js.map +0 -1
  46. package/dist/v3/zodIpc.mjs +0 -266
  47. package/dist/v3/zodIpc.mjs.map +0 -1
  48. package/dist/v3/zodMessageHandler.d.mts +0 -69
  49. package/dist/v3/zodMessageHandler.d.ts +0 -69
  50. package/dist/v3/zodMessageHandler.js +0 -168
  51. package/dist/v3/zodMessageHandler.js.map +0 -1
  52. package/dist/v3/zodMessageHandler.mjs +0 -163
  53. package/dist/v3/zodMessageHandler.mjs.map +0 -1
  54. package/dist/v3/zodNamespace.d.mts +0 -3663
  55. package/dist/v3/zodNamespace.d.ts +0 -3663
  56. package/dist/v3/zodNamespace.js +0 -356
  57. package/dist/v3/zodNamespace.js.map +0 -1
  58. package/dist/v3/zodNamespace.mjs +0 -354
  59. package/dist/v3/zodNamespace.mjs.map +0 -1
  60. package/dist/v3/zodSocket.d.mts +0 -88
  61. package/dist/v3/zodSocket.d.ts +0 -88
  62. package/dist/v3/zodSocket.js +0 -309
  63. package/dist/v3/zodSocket.js.map +0 -1
  64. package/dist/v3/zodSocket.mjs +0 -305
  65. package/dist/v3/zodSocket.mjs.map +0 -1
package/dist/v3/index.mjs CHANGED
@@ -1,11 +1,22 @@
1
- import { propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
2
- import { fromZodError } from 'zod-validation-error';
3
1
  import { z } from 'zod';
2
+ import { SpanStatusCode, propagation, context, trace, DiagLogLevel, diag, DiagConsoleLogger, SpanKind } from '@opentelemetry/api';
3
+ import { fromZodError } from 'zod-validation-error';
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
- import { PreciseDate } from '@google-cloud/precise-date';
5
+ import { io } from 'socket.io-client';
6
+ import { randomUUID } from 'crypto';
6
7
  import nodePath from 'node:path';
7
- import { logs } from '@opentelemetry/api-logs';
8
+ import { SeverityNumber, logs } from '@opentelemetry/api-logs';
9
+ import { PreciseDate } from '@google-cloud/precise-date';
8
10
  import humanizeDuration from 'humanize-duration';
11
+ import { setTimeout as setTimeout$1 } from 'node:timers/promises';
12
+ import util from 'node:util';
13
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
14
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
15
+ import { registerInstrumentations } from '@opentelemetry/instrumentation';
16
+ import { Resource, detectResourcesSync, processDetectorSync } from '@opentelemetry/resources';
17
+ import { LoggerProvider, BatchLogRecordProcessor, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs';
18
+ import { NodeTracerProvider, BatchSpanProcessor, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
19
+ import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
9
20
 
10
21
  var __defProp = Object.defineProperty;
11
22
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -18,433 +29,71 @@ var __accessCheck = (obj, member, msg) => {
18
29
  if (!member.has(obj))
19
30
  throw TypeError("Cannot " + msg);
20
31
  };
32
+ var __privateGet = (obj, member, getter) => {
33
+ __accessCheck(obj, member, "read from private field");
34
+ return getter ? getter.call(obj) : member.get(obj);
35
+ };
21
36
  var __privateAdd = (obj, member, value) => {
22
37
  if (member.has(obj))
23
38
  throw TypeError("Cannot add the same private member more than once");
24
39
  member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
25
40
  };
41
+ var __privateSet = (obj, member, value, setter) => {
42
+ __accessCheck(obj, member, "write to private field");
43
+ setter ? setter.call(obj, value) : member.set(obj, value);
44
+ return value;
45
+ };
46
+ var __privateWrapper = (obj, member, setter, getter) => ({
47
+ set _(value) {
48
+ __privateSet(obj, member, value, setter);
49
+ },
50
+ get _() {
51
+ return __privateGet(obj, member, getter);
52
+ }
53
+ });
26
54
  var __privateMethod = (obj, member, method) => {
27
55
  __accessCheck(obj, member, "access private method");
28
56
  return method;
29
57
  };
30
-
31
- // src/v3/apiErrors.ts
32
- var _APIError = class _APIError extends Error {
33
- constructor(status, error, message, headers) {
34
- super(`${_APIError.makeMessage(status, error, message)}`);
35
- this.status = status;
36
- this.headers = headers;
37
- const data = error;
38
- this.error = data;
39
- this.code = data?.["code"];
40
- this.param = data?.["param"];
41
- this.type = data?.["type"];
42
- }
43
- static makeMessage(status, error, message) {
44
- const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
45
- if (status && msg) {
46
- return `${status} ${msg}`;
47
- }
48
- if (status) {
49
- return `${status} status code (no body)`;
50
- }
51
- if (msg) {
52
- return msg;
53
- }
54
- return "(no status code or body)";
55
- }
56
- static generate(status, errorResponse, message, headers) {
57
- if (!status) {
58
- return new APIConnectionError({
59
- cause: castToError(errorResponse)
60
- });
61
- }
62
- const error = errorResponse?.["error"];
63
- if (status === 400) {
64
- return new BadRequestError(status, error, message, headers);
65
- }
66
- if (status === 401) {
67
- return new AuthenticationError(status, error, message, headers);
68
- }
69
- if (status === 403) {
70
- return new PermissionDeniedError(status, error, message, headers);
71
- }
72
- if (status === 404) {
73
- return new NotFoundError(status, error, message, headers);
74
- }
75
- if (status === 409) {
76
- return new ConflictError(status, error, message, headers);
77
- }
78
- if (status === 422) {
79
- return new UnprocessableEntityError(status, error, message, headers);
80
- }
81
- if (status === 429) {
82
- return new RateLimitError(status, error, message, headers);
83
- }
84
- if (status >= 500) {
85
- return new InternalServerError(status, error, message, headers);
86
- }
87
- return new _APIError(status, error, message, headers);
88
- }
89
- };
90
- __name(_APIError, "APIError");
91
- var APIError = _APIError;
92
- var _APIConnectionError = class _APIConnectionError extends APIError {
93
- constructor({ message, cause }) {
94
- super(void 0, void 0, message || "Connection error.", void 0);
95
- __publicField(this, "status");
96
- if (cause)
97
- this.cause = cause;
98
- }
99
- };
100
- __name(_APIConnectionError, "APIConnectionError");
101
- var APIConnectionError = _APIConnectionError;
102
- var _BadRequestError = class _BadRequestError extends APIError {
103
- constructor() {
104
- super(...arguments);
105
- __publicField(this, "status", 400);
106
- }
107
- };
108
- __name(_BadRequestError, "BadRequestError");
109
- var BadRequestError = _BadRequestError;
110
- var _AuthenticationError = class _AuthenticationError extends APIError {
111
- constructor() {
112
- super(...arguments);
113
- __publicField(this, "status", 401);
114
- }
115
- };
116
- __name(_AuthenticationError, "AuthenticationError");
117
- var AuthenticationError = _AuthenticationError;
118
- var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
119
- constructor() {
120
- super(...arguments);
121
- __publicField(this, "status", 403);
122
- }
123
- };
124
- __name(_PermissionDeniedError, "PermissionDeniedError");
125
- var PermissionDeniedError = _PermissionDeniedError;
126
- var _NotFoundError = class _NotFoundError extends APIError {
127
- constructor() {
128
- super(...arguments);
129
- __publicField(this, "status", 404);
130
- }
131
- };
132
- __name(_NotFoundError, "NotFoundError");
133
- var NotFoundError = _NotFoundError;
134
- var _ConflictError = class _ConflictError extends APIError {
135
- constructor() {
136
- super(...arguments);
137
- __publicField(this, "status", 409);
138
- }
139
- };
140
- __name(_ConflictError, "ConflictError");
141
- var ConflictError = _ConflictError;
142
- var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
143
- constructor() {
144
- super(...arguments);
145
- __publicField(this, "status", 422);
146
- }
147
- };
148
- __name(_UnprocessableEntityError, "UnprocessableEntityError");
149
- var UnprocessableEntityError = _UnprocessableEntityError;
150
- var _RateLimitError = class _RateLimitError extends APIError {
151
- constructor() {
152
- super(...arguments);
153
- __publicField(this, "status", 429);
154
- }
155
- };
156
- __name(_RateLimitError, "RateLimitError");
157
- var RateLimitError = _RateLimitError;
158
- var _InternalServerError = class _InternalServerError extends APIError {
159
- };
160
- __name(_InternalServerError, "InternalServerError");
161
- var InternalServerError = _InternalServerError;
162
- function castToError(err) {
163
- if (err instanceof Error)
164
- return err;
165
- return new Error(err);
166
- }
167
- __name(castToError, "castToError");
168
-
169
- // src/retry.ts
170
- function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
171
- if (!resets)
172
- return;
173
- switch (format) {
174
- case "iso_8601_duration_openai_variant": {
175
- return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
176
- }
177
- case "iso_8601": {
178
- return calculateISO8601ResetAt(resets, now);
179
- }
180
- case "unix_timestamp": {
181
- return calculateUnixTimestampResetAt(resets, now);
182
- }
183
- case "unix_timestamp_in_ms": {
184
- return calculateUnixTimestampInMsResetAt(resets, now);
185
- }
186
- }
187
- }
188
- __name(calculateResetAt, "calculateResetAt");
189
- function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
190
- if (!resets)
191
- return void 0;
192
- const resetAt = parseInt(resets, 10);
193
- if (isNaN(resetAt))
194
- return void 0;
195
- return new Date(resetAt * 1e3);
196
- }
197
- __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
198
- function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
199
- if (!resets)
200
- return void 0;
201
- const resetAt = parseInt(resets, 10);
202
- if (isNaN(resetAt))
203
- return void 0;
204
- return new Date(resetAt);
205
- }
206
- __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
207
- function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
208
- if (!resets)
209
- return void 0;
210
- const resetAt = new Date(resets);
211
- if (isNaN(resetAt.getTime()))
212
- return void 0;
213
- return resetAt;
214
- }
215
- __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
216
- function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
217
- if (!resets)
218
- return void 0;
219
- const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
220
- const match = resets.match(pattern);
221
- if (!match)
222
- return void 0;
223
- const days = parseInt(match[1], 10) || 0;
224
- const hours = parseInt(match[2], 10) || 0;
225
- const minutes = parseInt(match[3], 10) || 0;
226
- const seconds = parseFloat(match[4]) || 0;
227
- const milliseconds = parseInt(match[5], 10) || 0;
228
- const resetAt = new Date(now);
229
- resetAt.setDate(resetAt.getDate() + days);
230
- resetAt.setHours(resetAt.getHours() + hours);
231
- resetAt.setMinutes(resetAt.getMinutes() + minutes);
232
- resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
233
- resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
234
- return resetAt;
235
- }
236
- __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
237
-
238
- // src/v3/utils/retries.ts
239
- var defaultRetryOptions = {
240
- maxAttempts: 3,
241
- factor: 2,
242
- minTimeoutInMs: 1e3,
243
- maxTimeoutInMs: 6e4,
244
- randomize: true
245
- };
246
- var defaultFetchRetryOptions = {
247
- byStatus: {
248
- "429,408,409,5xx": {
249
- strategy: "backoff",
250
- ...defaultRetryOptions
251
- }
252
- },
253
- connectionError: defaultRetryOptions,
254
- timeout: defaultRetryOptions
255
- };
256
- function calculateNextRetryDelay(options, attempt) {
257
- const opts = {
258
- ...defaultRetryOptions,
259
- ...options
260
- };
261
- if (attempt >= opts.maxAttempts) {
262
- return;
263
- }
264
- const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
265
- const random = randomize ? Math.random() + 1 : 1;
266
- const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
267
- return Math.round(timeout);
268
- }
269
- __name(calculateNextRetryDelay, "calculateNextRetryDelay");
270
- function calculateResetAt2(resets, format, now = Date.now()) {
271
- const resetAt = calculateResetAt(resets, format, new Date(now));
272
- return resetAt?.getTime();
273
- }
274
- __name(calculateResetAt2, "calculateResetAt");
275
-
276
- // src/v3/zodfetch.ts
277
- var defaultRetryOptions2 = {
278
- maxAttempts: 3,
279
- factor: 2,
280
- minTimeoutInMs: 1e3,
281
- maxTimeoutInMs: 6e4,
282
- randomize: false
283
- };
284
- async function zodfetch(schema, url, requestInit, options) {
285
- return await _doZodFetch(schema, url, requestInit, options);
286
- }
287
- __name(zodfetch, "zodfetch");
288
- async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
289
- try {
290
- const response = await fetch(url, requestInitWithCache(requestInit));
291
- const responseHeaders = createResponseHeaders(response.headers);
292
- if (!response.ok) {
293
- const retryResult = shouldRetry(response, attempt, options?.retry);
294
- if (retryResult.retry) {
295
- await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
296
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
297
- } else {
298
- const errText = await response.text().catch((e) => castToError2(e).message);
299
- const errJSON = safeJsonParse(errText);
300
- const errMessage = errJSON ? void 0 : errText;
301
- throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
302
- }
303
- }
304
- const jsonBody = await response.json();
305
- const parsedResult = schema.safeParse(jsonBody);
306
- if (parsedResult.success) {
307
- return parsedResult.data;
308
- }
309
- throw fromZodError(parsedResult.error);
310
- } catch (error) {
311
- if (error instanceof APIError) {
312
- throw error;
313
- }
314
- if (options?.retry) {
315
- const retry = {
316
- ...defaultRetryOptions2,
317
- ...options.retry
318
- };
319
- const delay = calculateNextRetryDelay(retry, attempt);
320
- if (delay) {
321
- await new Promise((resolve) => setTimeout(resolve, delay));
322
- return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
323
- }
324
- }
325
- throw new APIConnectionError({
326
- cause: castToError2(error)
327
- });
328
- }
329
- }
330
- __name(_doZodFetch, "_doZodFetch");
331
- function castToError2(err) {
332
- if (err instanceof Error)
333
- return err;
334
- return new Error(err);
335
- }
336
- __name(castToError2, "castToError");
337
- function shouldRetry(response, attempt, retryOptions) {
338
- function shouldRetryForOptions() {
339
- const retry = {
340
- ...defaultRetryOptions2,
341
- ...retryOptions
342
- };
343
- const delay = calculateNextRetryDelay(retry, attempt);
344
- if (delay) {
345
- return {
346
- retry: true,
347
- delay
348
- };
349
- } else {
350
- return {
351
- retry: false
352
- };
353
- }
354
- }
355
- __name(shouldRetryForOptions, "shouldRetryForOptions");
356
- const shouldRetryHeader = response.headers.get("x-should-retry");
357
- if (shouldRetryHeader === "true")
358
- return shouldRetryForOptions();
359
- if (shouldRetryHeader === "false")
360
- return {
361
- retry: false
362
- };
363
- if (response.status === 408)
364
- return shouldRetryForOptions();
365
- if (response.status === 409)
366
- return shouldRetryForOptions();
367
- if (response.status === 429)
368
- return shouldRetryForOptions();
369
- if (response.status >= 500)
370
- return shouldRetryForOptions();
371
- return {
372
- retry: false
373
- };
374
- }
375
- __name(shouldRetry, "shouldRetry");
376
- function safeJsonParse(text) {
377
- try {
378
- return JSON.parse(text);
379
- } catch (e) {
380
- return void 0;
381
- }
382
- }
383
- __name(safeJsonParse, "safeJsonParse");
384
- function createResponseHeaders(headers) {
385
- return new Proxy(Object.fromEntries(
386
- // @ts-ignore
387
- headers.entries()
388
- ), {
389
- get(target, name) {
390
- const key = name.toString();
391
- return target[key.toLowerCase()] || target[key];
392
- }
393
- });
394
- }
395
- __name(createResponseHeaders, "createResponseHeaders");
396
- function requestInitWithCache(requestInit) {
397
- try {
398
- const withCache = {
399
- ...requestInit,
400
- cache: "no-cache"
401
- };
402
- const _ = new Request("http://localhost", withCache);
403
- return withCache;
404
- } catch (error) {
405
- return requestInit ?? {};
406
- }
407
- }
408
- __name(requestInitWithCache, "requestInitWithCache");
409
- var CreateAuthorizationCodeResponseSchema = z.object({
410
- url: z.string().url(),
411
- authorizationCode: z.string()
412
- });
413
- var GetPersonalAccessTokenRequestSchema = z.object({
414
- authorizationCode: z.string()
415
- });
416
- var GetPersonalAccessTokenResponseSchema = z.object({
417
- token: z.object({
418
- token: z.string(),
419
- obfuscatedToken: z.string()
420
- }).nullable()
421
- });
422
- var TaskRunBuiltInError = z.object({
423
- type: z.literal("BUILT_IN_ERROR"),
424
- name: z.string(),
425
- message: z.string(),
426
- stackTrace: z.string()
427
- });
428
- var TaskRunCustomErrorObject = z.object({
429
- type: z.literal("CUSTOM_ERROR"),
430
- raw: z.string()
431
- });
432
- var TaskRunStringError = z.object({
433
- type: z.literal("STRING_ERROR"),
434
- raw: z.string()
435
- });
436
- var TaskRunErrorCodes = {
437
- COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
438
- COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
439
- CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
440
- TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
441
- TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
442
- TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
443
- TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
444
- TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
445
- TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
446
- HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
447
- GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
58
+ var CreateAuthorizationCodeResponseSchema = z.object({
59
+ url: z.string().url(),
60
+ authorizationCode: z.string()
61
+ });
62
+ var GetPersonalAccessTokenRequestSchema = z.object({
63
+ authorizationCode: z.string()
64
+ });
65
+ var GetPersonalAccessTokenResponseSchema = z.object({
66
+ token: z.object({
67
+ token: z.string(),
68
+ obfuscatedToken: z.string()
69
+ }).nullable()
70
+ });
71
+ var TaskRunBuiltInError = z.object({
72
+ type: z.literal("BUILT_IN_ERROR"),
73
+ name: z.string(),
74
+ message: z.string(),
75
+ stackTrace: z.string()
76
+ });
77
+ var TaskRunCustomErrorObject = z.object({
78
+ type: z.literal("CUSTOM_ERROR"),
79
+ raw: z.string()
80
+ });
81
+ var TaskRunStringError = z.object({
82
+ type: z.literal("STRING_ERROR"),
83
+ raw: z.string()
84
+ });
85
+ var TaskRunErrorCodes = {
86
+ COULD_NOT_FIND_EXECUTOR: "COULD_NOT_FIND_EXECUTOR",
87
+ COULD_NOT_FIND_TASK: "COULD_NOT_FIND_TASK",
88
+ CONFIGURED_INCORRECTLY: "CONFIGURED_INCORRECTLY",
89
+ TASK_ALREADY_RUNNING: "TASK_ALREADY_RUNNING",
90
+ TASK_EXECUTION_FAILED: "TASK_EXECUTION_FAILED",
91
+ TASK_EXECUTION_ABORTED: "TASK_EXECUTION_ABORTED",
92
+ TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE: "TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE",
93
+ TASK_RUN_CANCELLED: "TASK_RUN_CANCELLED",
94
+ TASK_OUTPUT_ERROR: "TASK_OUTPUT_ERROR",
95
+ HANDLE_ERROR_ERROR: "HANDLE_ERROR_ERROR",
96
+ GRACEFUL_EXIT_TIMEOUT: "GRACEFUL_EXIT_TIMEOUT"
448
97
  };
449
98
  var TaskRunInternalError = z.object({
450
99
  type: z.literal("INTERNAL_ERROR"),
@@ -1883,32 +1532,492 @@ var SpanMessagingEvent = z.object({
1883
1532
  destination: z.string().optional()
1884
1533
  });
1885
1534
 
1886
- // src/v3/utils/platform.ts
1887
- var _globalThis = typeof globalThis === "object" ? globalThis : global;
1888
-
1889
- // src/v3/utils/globals.ts
1890
- var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
1891
- var _global = _globalThis;
1892
- function registerGlobal(type, instance, allowOverride = false) {
1893
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
1894
- if (!allowOverride && api[type]) {
1895
- return false;
1535
+ // src/v3/apiErrors.ts
1536
+ var _APIError = class _APIError extends Error {
1537
+ constructor(status, error, message, headers) {
1538
+ super(`${_APIError.makeMessage(status, error, message)}`);
1539
+ this.status = status;
1540
+ this.headers = headers;
1541
+ const data = error;
1542
+ this.error = data;
1543
+ this.code = data?.["code"];
1544
+ this.param = data?.["param"];
1545
+ this.type = data?.["type"];
1896
1546
  }
1897
- api[type] = instance;
1898
- return true;
1899
- }
1900
- __name(registerGlobal, "registerGlobal");
1901
- function getGlobal(type) {
1902
- return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
1903
- }
1904
- __name(getGlobal, "getGlobal");
1905
- function unregisterGlobal(type) {
1906
- const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
1907
- if (api) {
1908
- delete api[type];
1547
+ static makeMessage(status, error, message) {
1548
+ const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
1549
+ if (status && msg) {
1550
+ return `${status} ${msg}`;
1551
+ }
1552
+ if (status) {
1553
+ return `${status} status code (no body)`;
1554
+ }
1555
+ if (msg) {
1556
+ return msg;
1557
+ }
1558
+ return "(no status code or body)";
1909
1559
  }
1560
+ static generate(status, errorResponse, message, headers) {
1561
+ if (!status) {
1562
+ return new APIConnectionError({
1563
+ cause: castToError(errorResponse)
1564
+ });
1565
+ }
1566
+ const error = errorResponse?.["error"];
1567
+ if (status === 400) {
1568
+ return new BadRequestError(status, error, message, headers);
1569
+ }
1570
+ if (status === 401) {
1571
+ return new AuthenticationError(status, error, message, headers);
1572
+ }
1573
+ if (status === 403) {
1574
+ return new PermissionDeniedError(status, error, message, headers);
1575
+ }
1576
+ if (status === 404) {
1577
+ return new NotFoundError(status, error, message, headers);
1578
+ }
1579
+ if (status === 409) {
1580
+ return new ConflictError(status, error, message, headers);
1581
+ }
1582
+ if (status === 422) {
1583
+ return new UnprocessableEntityError(status, error, message, headers);
1584
+ }
1585
+ if (status === 429) {
1586
+ return new RateLimitError(status, error, message, headers);
1587
+ }
1588
+ if (status >= 500) {
1589
+ return new InternalServerError(status, error, message, headers);
1590
+ }
1591
+ return new _APIError(status, error, message, headers);
1592
+ }
1593
+ };
1594
+ __name(_APIError, "APIError");
1595
+ var APIError = _APIError;
1596
+ var _APIConnectionError = class _APIConnectionError extends APIError {
1597
+ constructor({ message, cause }) {
1598
+ super(void 0, void 0, message || "Connection error.", void 0);
1599
+ __publicField(this, "status");
1600
+ if (cause)
1601
+ this.cause = cause;
1602
+ }
1603
+ };
1604
+ __name(_APIConnectionError, "APIConnectionError");
1605
+ var APIConnectionError = _APIConnectionError;
1606
+ var _BadRequestError = class _BadRequestError extends APIError {
1607
+ constructor() {
1608
+ super(...arguments);
1609
+ __publicField(this, "status", 400);
1610
+ }
1611
+ };
1612
+ __name(_BadRequestError, "BadRequestError");
1613
+ var BadRequestError = _BadRequestError;
1614
+ var _AuthenticationError = class _AuthenticationError extends APIError {
1615
+ constructor() {
1616
+ super(...arguments);
1617
+ __publicField(this, "status", 401);
1618
+ }
1619
+ };
1620
+ __name(_AuthenticationError, "AuthenticationError");
1621
+ var AuthenticationError = _AuthenticationError;
1622
+ var _PermissionDeniedError = class _PermissionDeniedError extends APIError {
1623
+ constructor() {
1624
+ super(...arguments);
1625
+ __publicField(this, "status", 403);
1626
+ }
1627
+ };
1628
+ __name(_PermissionDeniedError, "PermissionDeniedError");
1629
+ var PermissionDeniedError = _PermissionDeniedError;
1630
+ var _NotFoundError = class _NotFoundError extends APIError {
1631
+ constructor() {
1632
+ super(...arguments);
1633
+ __publicField(this, "status", 404);
1634
+ }
1635
+ };
1636
+ __name(_NotFoundError, "NotFoundError");
1637
+ var NotFoundError = _NotFoundError;
1638
+ var _ConflictError = class _ConflictError extends APIError {
1639
+ constructor() {
1640
+ super(...arguments);
1641
+ __publicField(this, "status", 409);
1642
+ }
1643
+ };
1644
+ __name(_ConflictError, "ConflictError");
1645
+ var ConflictError = _ConflictError;
1646
+ var _UnprocessableEntityError = class _UnprocessableEntityError extends APIError {
1647
+ constructor() {
1648
+ super(...arguments);
1649
+ __publicField(this, "status", 422);
1650
+ }
1651
+ };
1652
+ __name(_UnprocessableEntityError, "UnprocessableEntityError");
1653
+ var UnprocessableEntityError = _UnprocessableEntityError;
1654
+ var _RateLimitError = class _RateLimitError extends APIError {
1655
+ constructor() {
1656
+ super(...arguments);
1657
+ __publicField(this, "status", 429);
1658
+ }
1659
+ };
1660
+ __name(_RateLimitError, "RateLimitError");
1661
+ var RateLimitError = _RateLimitError;
1662
+ var _InternalServerError = class _InternalServerError extends APIError {
1663
+ };
1664
+ __name(_InternalServerError, "InternalServerError");
1665
+ var InternalServerError = _InternalServerError;
1666
+ function castToError(err) {
1667
+ if (err instanceof Error)
1668
+ return err;
1669
+ return new Error(err);
1670
+ }
1671
+ __name(castToError, "castToError");
1672
+
1673
+ // src/retry.ts
1674
+ function calculateResetAt(resets, format, now = /* @__PURE__ */ new Date()) {
1675
+ if (!resets)
1676
+ return;
1677
+ switch (format) {
1678
+ case "iso_8601_duration_openai_variant": {
1679
+ return calculateISO8601DurationOpenAIVariantResetAt(resets, now);
1680
+ }
1681
+ case "iso_8601": {
1682
+ return calculateISO8601ResetAt(resets, now);
1683
+ }
1684
+ case "unix_timestamp": {
1685
+ return calculateUnixTimestampResetAt(resets, now);
1686
+ }
1687
+ case "unix_timestamp_in_ms": {
1688
+ return calculateUnixTimestampInMsResetAt(resets, now);
1689
+ }
1690
+ }
1691
+ }
1692
+ __name(calculateResetAt, "calculateResetAt");
1693
+ function calculateUnixTimestampResetAt(resets, now = /* @__PURE__ */ new Date()) {
1694
+ if (!resets)
1695
+ return void 0;
1696
+ const resetAt = parseInt(resets, 10);
1697
+ if (isNaN(resetAt))
1698
+ return void 0;
1699
+ return new Date(resetAt * 1e3);
1700
+ }
1701
+ __name(calculateUnixTimestampResetAt, "calculateUnixTimestampResetAt");
1702
+ function calculateUnixTimestampInMsResetAt(resets, now = /* @__PURE__ */ new Date()) {
1703
+ if (!resets)
1704
+ return void 0;
1705
+ const resetAt = parseInt(resets, 10);
1706
+ if (isNaN(resetAt))
1707
+ return void 0;
1708
+ return new Date(resetAt);
1709
+ }
1710
+ __name(calculateUnixTimestampInMsResetAt, "calculateUnixTimestampInMsResetAt");
1711
+ function calculateISO8601ResetAt(resets, now = /* @__PURE__ */ new Date()) {
1712
+ if (!resets)
1713
+ return void 0;
1714
+ const resetAt = new Date(resets);
1715
+ if (isNaN(resetAt.getTime()))
1716
+ return void 0;
1717
+ return resetAt;
1718
+ }
1719
+ __name(calculateISO8601ResetAt, "calculateISO8601ResetAt");
1720
+ function calculateISO8601DurationOpenAIVariantResetAt(resets, now = /* @__PURE__ */ new Date()) {
1721
+ if (!resets)
1722
+ return void 0;
1723
+ const pattern = /^(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+(?:\.\d+)?)s)?(?:(\d+)ms)?$/;
1724
+ const match = resets.match(pattern);
1725
+ if (!match)
1726
+ return void 0;
1727
+ const days = parseInt(match[1], 10) || 0;
1728
+ const hours = parseInt(match[2], 10) || 0;
1729
+ const minutes = parseInt(match[3], 10) || 0;
1730
+ const seconds = parseFloat(match[4]) || 0;
1731
+ const milliseconds = parseInt(match[5], 10) || 0;
1732
+ const resetAt = new Date(now);
1733
+ resetAt.setDate(resetAt.getDate() + days);
1734
+ resetAt.setHours(resetAt.getHours() + hours);
1735
+ resetAt.setMinutes(resetAt.getMinutes() + minutes);
1736
+ resetAt.setSeconds(resetAt.getSeconds() + Math.floor(seconds));
1737
+ resetAt.setMilliseconds(resetAt.getMilliseconds() + (seconds - Math.floor(seconds)) * 1e3 + milliseconds);
1738
+ return resetAt;
1739
+ }
1740
+ __name(calculateISO8601DurationOpenAIVariantResetAt, "calculateISO8601DurationOpenAIVariantResetAt");
1741
+
1742
+ // src/v3/utils/retries.ts
1743
+ var defaultRetryOptions = {
1744
+ maxAttempts: 3,
1745
+ factor: 2,
1746
+ minTimeoutInMs: 1e3,
1747
+ maxTimeoutInMs: 6e4,
1748
+ randomize: true
1749
+ };
1750
+ var defaultFetchRetryOptions = {
1751
+ byStatus: {
1752
+ "429,408,409,5xx": {
1753
+ strategy: "backoff",
1754
+ ...defaultRetryOptions
1755
+ }
1756
+ },
1757
+ connectionError: defaultRetryOptions,
1758
+ timeout: defaultRetryOptions
1759
+ };
1760
+ function calculateNextRetryDelay(options, attempt) {
1761
+ const opts = {
1762
+ ...defaultRetryOptions,
1763
+ ...options
1764
+ };
1765
+ if (attempt >= opts.maxAttempts) {
1766
+ return;
1767
+ }
1768
+ const { factor, minTimeoutInMs, maxTimeoutInMs, randomize } = opts;
1769
+ const random = randomize ? Math.random() + 1 : 1;
1770
+ const timeout = Math.min(maxTimeoutInMs, random * minTimeoutInMs * Math.pow(factor, attempt - 1));
1771
+ return Math.round(timeout);
1772
+ }
1773
+ __name(calculateNextRetryDelay, "calculateNextRetryDelay");
1774
+ function calculateResetAt2(resets, format, now = Date.now()) {
1775
+ const resetAt = calculateResetAt(resets, format, new Date(now));
1776
+ return resetAt?.getTime();
1777
+ }
1778
+ __name(calculateResetAt2, "calculateResetAt");
1779
+
1780
+ // src/v3/zodfetch.ts
1781
+ var defaultRetryOptions2 = {
1782
+ maxAttempts: 3,
1783
+ factor: 2,
1784
+ minTimeoutInMs: 1e3,
1785
+ maxTimeoutInMs: 6e4,
1786
+ randomize: false
1787
+ };
1788
+ async function zodfetch(schema, url, requestInit, options) {
1789
+ return await _doZodFetch(schema, url, requestInit, options);
1790
+ }
1791
+ __name(zodfetch, "zodfetch");
1792
+ async function _doZodFetch(schema, url, requestInit, options, attempt = 1) {
1793
+ try {
1794
+ const response = await fetch(url, requestInitWithCache(requestInit));
1795
+ const responseHeaders = createResponseHeaders(response.headers);
1796
+ if (!response.ok) {
1797
+ const retryResult = shouldRetry(response, attempt, options?.retry);
1798
+ if (retryResult.retry) {
1799
+ await new Promise((resolve) => setTimeout(resolve, retryResult.delay));
1800
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1801
+ } else {
1802
+ const errText = await response.text().catch((e) => castToError2(e).message);
1803
+ const errJSON = safeJsonParse(errText);
1804
+ const errMessage = errJSON ? void 0 : errText;
1805
+ throw APIError.generate(response.status, errJSON, errMessage, responseHeaders);
1806
+ }
1807
+ }
1808
+ const jsonBody = await response.json();
1809
+ const parsedResult = schema.safeParse(jsonBody);
1810
+ if (parsedResult.success) {
1811
+ return parsedResult.data;
1812
+ }
1813
+ throw fromZodError(parsedResult.error);
1814
+ } catch (error) {
1815
+ if (error instanceof APIError) {
1816
+ throw error;
1817
+ }
1818
+ if (options?.retry) {
1819
+ const retry = {
1820
+ ...defaultRetryOptions2,
1821
+ ...options.retry
1822
+ };
1823
+ const delay = calculateNextRetryDelay(retry, attempt);
1824
+ if (delay) {
1825
+ await new Promise((resolve) => setTimeout(resolve, delay));
1826
+ return await _doZodFetch(schema, url, requestInit, options, attempt + 1);
1827
+ }
1828
+ }
1829
+ throw new APIConnectionError({
1830
+ cause: castToError2(error)
1831
+ });
1832
+ }
1833
+ }
1834
+ __name(_doZodFetch, "_doZodFetch");
1835
+ function castToError2(err) {
1836
+ if (err instanceof Error)
1837
+ return err;
1838
+ return new Error(err);
1839
+ }
1840
+ __name(castToError2, "castToError");
1841
+ function shouldRetry(response, attempt, retryOptions) {
1842
+ function shouldRetryForOptions() {
1843
+ const retry = {
1844
+ ...defaultRetryOptions2,
1845
+ ...retryOptions
1846
+ };
1847
+ const delay = calculateNextRetryDelay(retry, attempt);
1848
+ if (delay) {
1849
+ return {
1850
+ retry: true,
1851
+ delay
1852
+ };
1853
+ } else {
1854
+ return {
1855
+ retry: false
1856
+ };
1857
+ }
1858
+ }
1859
+ __name(shouldRetryForOptions, "shouldRetryForOptions");
1860
+ const shouldRetryHeader = response.headers.get("x-should-retry");
1861
+ if (shouldRetryHeader === "true")
1862
+ return shouldRetryForOptions();
1863
+ if (shouldRetryHeader === "false")
1864
+ return {
1865
+ retry: false
1866
+ };
1867
+ if (response.status === 408)
1868
+ return shouldRetryForOptions();
1869
+ if (response.status === 409)
1870
+ return shouldRetryForOptions();
1871
+ if (response.status === 429)
1872
+ return shouldRetryForOptions();
1873
+ if (response.status >= 500)
1874
+ return shouldRetryForOptions();
1875
+ return {
1876
+ retry: false
1877
+ };
1878
+ }
1879
+ __name(shouldRetry, "shouldRetry");
1880
+ function safeJsonParse(text) {
1881
+ try {
1882
+ return JSON.parse(text);
1883
+ } catch (e) {
1884
+ return void 0;
1885
+ }
1886
+ }
1887
+ __name(safeJsonParse, "safeJsonParse");
1888
+ function createResponseHeaders(headers) {
1889
+ return new Proxy(Object.fromEntries(
1890
+ // @ts-ignore
1891
+ headers.entries()
1892
+ ), {
1893
+ get(target, name) {
1894
+ const key = name.toString();
1895
+ return target[key.toLowerCase()] || target[key];
1896
+ }
1897
+ });
1898
+ }
1899
+ __name(createResponseHeaders, "createResponseHeaders");
1900
+ function requestInitWithCache(requestInit) {
1901
+ try {
1902
+ const withCache = {
1903
+ ...requestInit,
1904
+ cache: "no-cache"
1905
+ };
1906
+ const _ = new Request("http://localhost", withCache);
1907
+ return withCache;
1908
+ } catch (error) {
1909
+ return requestInit ?? {};
1910
+ }
1911
+ }
1912
+ __name(requestInitWithCache, "requestInitWithCache");
1913
+
1914
+ // src/v3/utils/flattenAttributes.ts
1915
+ function flattenAttributes(obj, prefix) {
1916
+ const result = {};
1917
+ if (!obj) {
1918
+ return result;
1919
+ }
1920
+ if (typeof obj === "string") {
1921
+ result[prefix || ""] = obj;
1922
+ return result;
1923
+ }
1924
+ if (typeof obj === "number") {
1925
+ result[prefix || ""] = obj;
1926
+ return result;
1927
+ }
1928
+ if (typeof obj === "boolean") {
1929
+ result[prefix || ""] = obj;
1930
+ return result;
1931
+ }
1932
+ for (const [key, value] of Object.entries(obj)) {
1933
+ const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
1934
+ if (Array.isArray(value)) {
1935
+ for (let i = 0; i < value.length; i++) {
1936
+ if (typeof value[i] === "object" && value[i] !== null) {
1937
+ Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
1938
+ } else {
1939
+ result[`${newPrefix}.[${i}]`] = value[i];
1940
+ }
1941
+ }
1942
+ } else if (isRecord(value)) {
1943
+ Object.assign(result, flattenAttributes(value, newPrefix));
1944
+ } else {
1945
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
1946
+ result[newPrefix] = value;
1947
+ }
1948
+ }
1949
+ }
1950
+ return result;
1951
+ }
1952
+ __name(flattenAttributes, "flattenAttributes");
1953
+ function isRecord(value) {
1954
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1955
+ }
1956
+ __name(isRecord, "isRecord");
1957
+ function unflattenAttributes(obj) {
1958
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
1959
+ return obj;
1960
+ }
1961
+ const result = {};
1962
+ for (const [key, value] of Object.entries(obj)) {
1963
+ const parts = key.split(".").reduce((acc, part) => {
1964
+ if (detectIsArrayIndex(part)) {
1965
+ acc.push(part);
1966
+ } else {
1967
+ acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
1968
+ }
1969
+ return acc;
1970
+ }, []);
1971
+ let current = result;
1972
+ for (let i = 0; i < parts.length - 1; i++) {
1973
+ const part = parts[i];
1974
+ const isArray = detectIsArrayIndex(part);
1975
+ const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
1976
+ const nextIsArray = detectIsArrayIndex(parts[i + 1]);
1977
+ if (!current[cleanPart]) {
1978
+ current[cleanPart] = nextIsArray ? [] : {};
1979
+ }
1980
+ current = current[cleanPart];
1981
+ }
1982
+ const lastPart = parts[parts.length - 1];
1983
+ const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
1984
+ current[cleanLastPart] = value;
1985
+ }
1986
+ return result;
1987
+ }
1988
+ __name(unflattenAttributes, "unflattenAttributes");
1989
+ function detectIsArrayIndex(key) {
1990
+ const match = key.match(/^\[(\d+)\]$/);
1991
+ if (match) {
1992
+ return true;
1993
+ }
1994
+ return false;
1995
+ }
1996
+ __name(detectIsArrayIndex, "detectIsArrayIndex");
1997
+ function primitiveValueOrflattenedAttributes(obj, prefix) {
1998
+ if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
1999
+ return obj;
2000
+ }
2001
+ const attributes = flattenAttributes(obj, prefix);
2002
+ if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2003
+ return attributes[prefix];
2004
+ }
2005
+ return attributes;
1910
2006
  }
1911
- __name(unregisterGlobal, "unregisterGlobal");
2007
+ __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2008
+ var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2009
+ constructor() {
2010
+ this.storage = new AsyncLocalStorage();
2011
+ }
2012
+ runWith(context3, fn) {
2013
+ return this.storage.run(context3, fn);
2014
+ }
2015
+ getStore() {
2016
+ return this.storage.getStore();
2017
+ }
2018
+ };
2019
+ __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2020
+ var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
1912
2021
 
1913
2022
  // src/v3/semanticInternalAttributes.ts
1914
2023
  var SemanticInternalAttributes = {
@@ -1957,27 +2066,23 @@ var SemanticInternalAttributes = {
1957
2066
  IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
1958
2067
  };
1959
2068
 
1960
- // src/v3/taskContext/index.ts
1961
- var API_NAME = "task-context";
1962
- var _getTaskContext, getTaskContext_fn;
1963
- var _TaskContextAPI = class _TaskContextAPI {
2069
+ // src/v3/tasks/taskContextManager.ts
2070
+ var _getStore, getStore_fn;
2071
+ var _TaskContextManager = class _TaskContextManager {
1964
2072
  constructor() {
1965
- __privateAdd(this, _getTaskContext);
1966
- }
1967
- static getInstance() {
1968
- if (!this._instance) {
1969
- this._instance = new _TaskContextAPI();
1970
- }
1971
- return this._instance;
2073
+ __privateAdd(this, _getStore);
2074
+ __publicField(this, "_storage", new SafeAsyncLocalStorage());
1972
2075
  }
1973
2076
  get isInsideTask() {
1974
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this) !== void 0;
2077
+ return __privateMethod(this, _getStore, getStore_fn).call(this) !== void 0;
1975
2078
  }
1976
2079
  get ctx() {
1977
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.ctx;
2080
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2081
+ return store?.ctx;
1978
2082
  }
1979
2083
  get worker() {
1980
- return __privateMethod(this, _getTaskContext, getTaskContext_fn).call(this)?.worker;
2084
+ const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2085
+ return store?.worker;
1981
2086
  }
1982
2087
  get attributes() {
1983
2088
  if (this.ctx) {
@@ -2023,22 +2128,66 @@ var _TaskContextAPI = class _TaskContextAPI {
2023
2128
  }
2024
2129
  return {};
2025
2130
  }
2026
- disable() {
2027
- unregisterGlobal(API_NAME);
2131
+ runWith(context3, fn) {
2132
+ return this._storage.runWith(context3, fn);
2133
+ }
2134
+ };
2135
+ _getStore = new WeakSet();
2136
+ getStore_fn = /* @__PURE__ */ __name(function() {
2137
+ return this._storage.getStore();
2138
+ }, "#getStore");
2139
+ __name(_TaskContextManager, "TaskContextManager");
2140
+ var TaskContextManager = _TaskContextManager;
2141
+ var taskContextManager = new TaskContextManager();
2142
+ var _TaskContextSpanProcessor = class _TaskContextSpanProcessor {
2143
+ constructor(innerProcessor) {
2144
+ this._innerProcessor = innerProcessor;
2145
+ }
2146
+ // Called when a span starts
2147
+ onStart(span, parentContext) {
2148
+ if (taskContextManager.ctx) {
2149
+ span.setAttributes(flattenAttributes({
2150
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2151
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2152
+ }, SemanticInternalAttributes.METADATA));
2153
+ }
2154
+ this._innerProcessor.onStart(span, parentContext);
2028
2155
  }
2029
- setGlobalTaskContext(taskContext2) {
2030
- return registerGlobal(API_NAME, taskContext2);
2156
+ // Delegate the rest of the methods to the wrapped processor
2157
+ onEnd(span) {
2158
+ this._innerProcessor.onEnd(span);
2159
+ }
2160
+ shutdown() {
2161
+ return this._innerProcessor.shutdown();
2162
+ }
2163
+ forceFlush() {
2164
+ return this._innerProcessor.forceFlush();
2031
2165
  }
2032
2166
  };
2033
- _getTaskContext = new WeakSet();
2034
- getTaskContext_fn = /* @__PURE__ */ __name(function() {
2035
- return getGlobal(API_NAME);
2036
- }, "#getTaskContext");
2037
- __name(_TaskContextAPI, "TaskContextAPI");
2038
- var TaskContextAPI = _TaskContextAPI;
2039
-
2040
- // src/v3/task-context-api.ts
2041
- var taskContext = TaskContextAPI.getInstance();
2167
+ __name(_TaskContextSpanProcessor, "TaskContextSpanProcessor");
2168
+ var TaskContextSpanProcessor = _TaskContextSpanProcessor;
2169
+ var _TaskContextLogProcessor = class _TaskContextLogProcessor {
2170
+ constructor(innerProcessor) {
2171
+ this._innerProcessor = innerProcessor;
2172
+ }
2173
+ forceFlush() {
2174
+ return this._innerProcessor.forceFlush();
2175
+ }
2176
+ onEmit(logRecord, context3) {
2177
+ if (taskContextManager.ctx) {
2178
+ logRecord.setAttributes(flattenAttributes({
2179
+ [SemanticInternalAttributes.ATTEMPT_ID]: taskContextManager.ctx.attempt.id,
2180
+ [SemanticInternalAttributes.ATTEMPT_NUMBER]: taskContextManager.ctx.attempt.number
2181
+ }, SemanticInternalAttributes.METADATA));
2182
+ }
2183
+ this._innerProcessor.onEmit(logRecord, context3);
2184
+ }
2185
+ shutdown() {
2186
+ return this._innerProcessor.shutdown();
2187
+ }
2188
+ };
2189
+ __name(_TaskContextLogProcessor, "TaskContextLogProcessor");
2190
+ var TaskContextLogProcessor = _TaskContextLogProcessor;
2042
2191
 
2043
2192
  // src/v3/utils/getEnv.ts
2044
2193
  function getEnvVar(name) {
@@ -2047,19 +2196,6 @@ function getEnvVar(name) {
2047
2196
  }
2048
2197
  }
2049
2198
  __name(getEnvVar, "getEnvVar");
2050
- var _SafeAsyncLocalStorage = class _SafeAsyncLocalStorage {
2051
- constructor() {
2052
- this.storage = new AsyncLocalStorage();
2053
- }
2054
- runWith(context3, fn) {
2055
- return this.storage.run(context3, fn);
2056
- }
2057
- getStore() {
2058
- return this.storage.getStore();
2059
- }
2060
- };
2061
- __name(_SafeAsyncLocalStorage, "SafeAsyncLocalStorage");
2062
- var SafeAsyncLocalStorage = _SafeAsyncLocalStorage;
2063
2199
 
2064
2200
  // src/v3/apiClient/index.ts
2065
2201
  var zodFetchOptions = {
@@ -2195,7 +2331,7 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2195
2331
  "Content-Type": "application/json",
2196
2332
  Authorization: `Bearer ${this.accessToken}`
2197
2333
  };
2198
- if (taskContext.isInsideTask) {
2334
+ if (taskContextManager.isInsideTask) {
2199
2335
  propagation.inject(context.active(), headers);
2200
2336
  if (spanParentAsLink) {
2201
2337
  headers["x-trigger-span-parent-as-link"] = "1";
@@ -2205,18 +2341,18 @@ getHeaders_fn = /* @__PURE__ */ __name(function(spanParentAsLink) {
2205
2341
  }, "#getHeaders");
2206
2342
  __name(_ApiClient, "ApiClient");
2207
2343
  var ApiClient = _ApiClient;
2208
- var _getStore, getStore_fn;
2344
+ var _getStore2, getStore_fn2;
2209
2345
  var _ApiClientManager = class _ApiClientManager {
2210
2346
  constructor() {
2211
- __privateAdd(this, _getStore);
2347
+ __privateAdd(this, _getStore2);
2212
2348
  __publicField(this, "_storage", new SafeAsyncLocalStorage());
2213
2349
  }
2214
2350
  get baseURL() {
2215
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2351
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2216
2352
  return store?.baseURL ?? getEnvVar("TRIGGER_API_URL") ?? "https://api.trigger.dev";
2217
2353
  }
2218
2354
  get accessToken() {
2219
- const store = __privateMethod(this, _getStore, getStore_fn).call(this);
2355
+ const store = __privateMethod(this, _getStore2, getStore_fn2).call(this);
2220
2356
  return store?.accessToken ?? getEnvVar("TRIGGER_SECRET_KEY");
2221
2357
  }
2222
2358
  get client() {
@@ -2229,61 +2365,736 @@ var _ApiClientManager = class _ApiClientManager {
2229
2365
  return this._storage.runWith(context3, fn);
2230
2366
  }
2231
2367
  };
2232
- _getStore = new WeakSet();
2233
- getStore_fn = /* @__PURE__ */ __name(function() {
2368
+ _getStore2 = new WeakSet();
2369
+ getStore_fn2 = /* @__PURE__ */ __name(function() {
2234
2370
  return this._storage.getStore();
2235
2371
  }, "#getStore");
2236
2372
  __name(_ApiClientManager, "ApiClientManager");
2237
2373
  var ApiClientManager = _ApiClientManager;
2238
2374
  var apiClientManager = new ApiClientManager();
2239
- var _SimpleClock = class _SimpleClock {
2240
- preciseNow() {
2241
- const now = new PreciseDate();
2242
- const nowStruct = now.toStruct();
2243
- return [
2244
- nowStruct.seconds,
2245
- nowStruct.nanos
2246
- ];
2375
+ var _ZodSchemaParsedError = class _ZodSchemaParsedError extends Error {
2376
+ constructor(error, payload) {
2377
+ super(error.message);
2378
+ this.error = error;
2379
+ this.payload = payload;
2247
2380
  }
2248
- reset() {
2381
+ };
2382
+ __name(_ZodSchemaParsedError, "ZodSchemaParsedError");
2383
+ var ZodSchemaParsedError = _ZodSchemaParsedError;
2384
+ var ZodMessageSchema = z.object({
2385
+ version: z.literal("v1").default("v1"),
2386
+ type: z.string(),
2387
+ payload: z.unknown()
2388
+ });
2389
+ var _schema, _handlers;
2390
+ var _ZodMessageHandler = class _ZodMessageHandler {
2391
+ constructor(options) {
2392
+ __privateAdd(this, _schema, void 0);
2393
+ __privateAdd(this, _handlers, void 0);
2394
+ __privateSet(this, _schema, options.schema);
2395
+ __privateSet(this, _handlers, options.messages);
2396
+ }
2397
+ async handleMessage(message) {
2398
+ const parsedMessage = this.parseMessage(message);
2399
+ if (!__privateGet(this, _handlers)) {
2400
+ throw new Error("No handlers provided");
2401
+ }
2402
+ const handler = __privateGet(this, _handlers)[parsedMessage.type];
2403
+ if (!handler) {
2404
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2405
+ return;
2406
+ }
2407
+ const ack = await handler(parsedMessage.payload);
2408
+ return ack;
2409
+ }
2410
+ parseMessage(message) {
2411
+ const parsedMessage = ZodMessageSchema.safeParse(message);
2412
+ if (!parsedMessage.success) {
2413
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2414
+ }
2415
+ const schema = __privateGet(this, _schema)[parsedMessage.data.type];
2416
+ if (!schema) {
2417
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2418
+ }
2419
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2420
+ if (!parsedPayload.success) {
2421
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2422
+ }
2423
+ return {
2424
+ type: parsedMessage.data.type,
2425
+ payload: parsedPayload.data
2426
+ };
2427
+ }
2428
+ registerHandlers(emitter, logger2) {
2429
+ const log = logger2 ?? console;
2430
+ if (!__privateGet(this, _handlers)) {
2431
+ log.info("No handlers provided");
2432
+ return;
2433
+ }
2434
+ for (const eventName of Object.keys(__privateGet(this, _schema))) {
2435
+ emitter.on(eventName, async (message, callback) => {
2436
+ log.info(`handling ${eventName}`, {
2437
+ payload: message,
2438
+ hasCallback: !!callback
2439
+ });
2440
+ let ack;
2441
+ if ("payload" in message) {
2442
+ ack = await this.handleMessage({
2443
+ type: eventName,
2444
+ ...message
2445
+ });
2446
+ } else {
2447
+ const { version, ...payload } = message;
2448
+ ack = await this.handleMessage({
2449
+ type: eventName,
2450
+ version,
2451
+ payload
2452
+ });
2453
+ }
2454
+ if (callback && typeof callback === "function") {
2455
+ callback(ack);
2456
+ }
2457
+ });
2458
+ }
2249
2459
  }
2250
2460
  };
2251
- __name(_SimpleClock, "SimpleClock");
2252
- var SimpleClock = _SimpleClock;
2461
+ _schema = new WeakMap();
2462
+ _handlers = new WeakMap();
2463
+ __name(_ZodMessageHandler, "ZodMessageHandler");
2464
+ var ZodMessageHandler = _ZodMessageHandler;
2465
+ var _schema2, _sender;
2466
+ var _ZodMessageSender = class _ZodMessageSender {
2467
+ constructor(options) {
2468
+ __privateAdd(this, _schema2, void 0);
2469
+ __privateAdd(this, _sender, void 0);
2470
+ __privateSet(this, _schema2, options.schema);
2471
+ __privateSet(this, _sender, options.sender);
2472
+ }
2473
+ async send(type, payload) {
2474
+ const schema = __privateGet(this, _schema2)[type];
2475
+ if (!schema) {
2476
+ throw new Error(`Unknown message type: ${type}`);
2477
+ }
2478
+ const parsedPayload = schema.safeParse(payload);
2479
+ if (!parsedPayload.success) {
2480
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
2481
+ }
2482
+ await __privateGet(this, _sender).call(this, {
2483
+ type,
2484
+ payload,
2485
+ version: "v1"
2486
+ });
2487
+ }
2488
+ async forwardMessage(message) {
2489
+ const parsedMessage = ZodMessageSchema.safeParse(message);
2490
+ if (!parsedMessage.success) {
2491
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2492
+ }
2493
+ const schema = __privateGet(this, _schema2)[parsedMessage.data.type];
2494
+ if (!schema) {
2495
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2496
+ }
2497
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2498
+ if (!parsedPayload.success) {
2499
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2500
+ }
2501
+ await __privateGet(this, _sender).call(this, {
2502
+ type: parsedMessage.data.type,
2503
+ payload: parsedPayload.data,
2504
+ version: "v1"
2505
+ });
2506
+ }
2507
+ };
2508
+ _schema2 = new WeakMap();
2509
+ _sender = new WeakMap();
2510
+ __name(_ZodMessageSender, "ZodMessageSender");
2511
+ var ZodMessageSender = _ZodMessageSender;
2512
+ var messageSchema = z.object({
2513
+ version: z.literal("v1").default("v1"),
2514
+ type: z.string(),
2515
+ payload: z.unknown()
2516
+ });
2517
+ var _schema3, _handlers2;
2518
+ var _ZodSocketMessageHandler = class _ZodSocketMessageHandler {
2519
+ constructor(options) {
2520
+ __privateAdd(this, _schema3, void 0);
2521
+ __privateAdd(this, _handlers2, void 0);
2522
+ __privateSet(this, _schema3, options.schema);
2523
+ __privateSet(this, _handlers2, options.handlers);
2524
+ }
2525
+ async handleMessage(message) {
2526
+ const parsedMessage = this.parseMessage(message);
2527
+ if (!__privateGet(this, _handlers2)) {
2528
+ throw new Error("No handlers provided");
2529
+ }
2530
+ const handler = __privateGet(this, _handlers2)[parsedMessage.type];
2531
+ if (!handler) {
2532
+ console.error(`No handler for message type: ${String(parsedMessage.type)}`);
2533
+ return;
2534
+ }
2535
+ const ack = await handler(parsedMessage.payload);
2536
+ return ack;
2537
+ }
2538
+ parseMessage(message) {
2539
+ const parsedMessage = messageSchema.safeParse(message);
2540
+ if (!parsedMessage.success) {
2541
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2542
+ }
2543
+ const schema = __privateGet(this, _schema3)[parsedMessage.data.type]["message"];
2544
+ if (!schema) {
2545
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2546
+ }
2547
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2548
+ if (!parsedPayload.success) {
2549
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2550
+ }
2551
+ return {
2552
+ type: parsedMessage.data.type,
2553
+ payload: parsedPayload.data
2554
+ };
2555
+ }
2556
+ registerHandlers(emitter, logger2) {
2557
+ const log = logger2 ?? console;
2558
+ if (!__privateGet(this, _handlers2)) {
2559
+ log.info("No handlers provided");
2560
+ return;
2561
+ }
2562
+ for (const eventName of Object.keys(__privateGet(this, _handlers2))) {
2563
+ emitter.on(eventName, async (message, callback) => {
2564
+ log.info(`handling ${eventName}`, {
2565
+ payload: message,
2566
+ hasCallback: !!callback
2567
+ });
2568
+ let ack;
2569
+ try {
2570
+ if ("payload" in message) {
2571
+ ack = await this.handleMessage({
2572
+ type: eventName,
2573
+ ...message
2574
+ });
2575
+ } else {
2576
+ const { version, ...payload } = message;
2577
+ ack = await this.handleMessage({
2578
+ type: eventName,
2579
+ version,
2580
+ payload
2581
+ });
2582
+ }
2583
+ } catch (error) {
2584
+ log.error("Error while handling message", {
2585
+ error
2586
+ });
2587
+ return;
2588
+ }
2589
+ if (callback && typeof callback === "function") {
2590
+ callback(ack);
2591
+ }
2592
+ });
2593
+ }
2594
+ }
2595
+ };
2596
+ _schema3 = new WeakMap();
2597
+ _handlers2 = new WeakMap();
2598
+ __name(_ZodSocketMessageHandler, "ZodSocketMessageHandler");
2599
+ var ZodSocketMessageHandler = _ZodSocketMessageHandler;
2600
+ var _schema4, _socket;
2601
+ var _ZodSocketMessageSender = class _ZodSocketMessageSender {
2602
+ constructor(options) {
2603
+ __privateAdd(this, _schema4, void 0);
2604
+ __privateAdd(this, _socket, void 0);
2605
+ __privateSet(this, _schema4, options.schema);
2606
+ __privateSet(this, _socket, options.socket);
2607
+ }
2608
+ send(type, payload) {
2609
+ const schema = __privateGet(this, _schema4)[type]["message"];
2610
+ if (!schema) {
2611
+ throw new Error(`Unknown message type: ${type}`);
2612
+ }
2613
+ const parsedPayload = schema.safeParse(payload);
2614
+ if (!parsedPayload.success) {
2615
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2616
+ }
2617
+ __privateGet(this, _socket).emit(type, {
2618
+ payload,
2619
+ version: "v1"
2620
+ });
2621
+ return;
2622
+ }
2623
+ async sendWithAck(type, payload) {
2624
+ const schema = __privateGet(this, _schema4)[type]["message"];
2625
+ if (!schema) {
2626
+ throw new Error(`Unknown message type: ${type}`);
2627
+ }
2628
+ const parsedPayload = schema.safeParse(payload);
2629
+ if (!parsedPayload.success) {
2630
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2631
+ }
2632
+ const callbackResult = await __privateGet(this, _socket).emitWithAck(type, {
2633
+ payload,
2634
+ version: "v1"
2635
+ });
2636
+ return callbackResult;
2637
+ }
2638
+ };
2639
+ _schema4 = new WeakMap();
2640
+ _socket = new WeakMap();
2641
+ __name(_ZodSocketMessageSender, "ZodSocketMessageSender");
2642
+ var ZodSocketMessageSender = _ZodSocketMessageSender;
2643
+ var _sender2, _handler, _logger;
2644
+ var _ZodSocketConnection = class _ZodSocketConnection {
2645
+ constructor(opts) {
2646
+ __privateAdd(this, _sender2, void 0);
2647
+ __privateAdd(this, _handler, void 0);
2648
+ __privateAdd(this, _logger, void 0);
2649
+ const uri = `${opts.secure ? "wss" : "ws"}://${opts.host}:${opts.port ?? (opts.secure ? "443" : "80")}/${opts.namespace}`;
2650
+ const logger2 = new SimpleStructuredLogger(opts.namespace, LogLevel.info);
2651
+ logger2.log("new zod socket", {
2652
+ uri
2653
+ });
2654
+ this.socket = io(uri, {
2655
+ transports: [
2656
+ "websocket"
2657
+ ],
2658
+ auth: {
2659
+ token: opts.authToken
2660
+ },
2661
+ extraHeaders: opts.extraHeaders,
2662
+ reconnectionDelay: 500,
2663
+ reconnectionDelayMax: 1e3
2664
+ });
2665
+ __privateSet(this, _logger, logger2.child({
2666
+ socketId: this.socket.id
2667
+ }));
2668
+ __privateSet(this, _handler, new ZodSocketMessageHandler({
2669
+ schema: opts.serverMessages,
2670
+ handlers: opts.handlers
2671
+ }));
2672
+ __privateGet(this, _handler).registerHandlers(this.socket, __privateGet(this, _logger));
2673
+ __privateSet(this, _sender2, new ZodSocketMessageSender({
2674
+ schema: opts.clientMessages,
2675
+ socket: this.socket
2676
+ }));
2677
+ this.socket.on("connect_error", async (error) => {
2678
+ __privateGet(this, _logger).error(`connect_error: ${error}`);
2679
+ if (opts.onError) {
2680
+ await opts.onError(this.socket, error, __privateGet(this, _logger));
2681
+ }
2682
+ });
2683
+ this.socket.on("connect", async () => {
2684
+ __privateGet(this, _logger).info("connect");
2685
+ if (opts.onConnection) {
2686
+ await opts.onConnection(this.socket, __privateGet(this, _handler), __privateGet(this, _sender2), __privateGet(this, _logger));
2687
+ }
2688
+ });
2689
+ this.socket.on("disconnect", async (reason, description) => {
2690
+ __privateGet(this, _logger).info("disconnect", {
2691
+ reason,
2692
+ description
2693
+ });
2694
+ if (opts.onDisconnect) {
2695
+ await opts.onDisconnect(this.socket, reason, description, __privateGet(this, _logger));
2696
+ }
2697
+ });
2698
+ }
2699
+ close() {
2700
+ this.socket.close();
2701
+ }
2702
+ connect() {
2703
+ this.socket.connect();
2704
+ }
2705
+ get send() {
2706
+ return __privateGet(this, _sender2).send.bind(__privateGet(this, _sender2));
2707
+ }
2708
+ get sendWithAck() {
2709
+ return __privateGet(this, _sender2).sendWithAck.bind(__privateGet(this, _sender2));
2710
+ }
2711
+ };
2712
+ _sender2 = new WeakMap();
2713
+ _handler = new WeakMap();
2714
+ _logger = new WeakMap();
2715
+ __name(_ZodSocketConnection, "ZodSocketConnection");
2716
+ var ZodSocketConnection = _ZodSocketConnection;
2253
2717
 
2254
- // src/v3/clock/index.ts
2255
- var API_NAME2 = "clock";
2256
- var SIMPLE_CLOCK = new SimpleClock();
2257
- var _getClock, getClock_fn;
2258
- var _ClockAPI = class _ClockAPI {
2259
- constructor() {
2260
- __privateAdd(this, _getClock);
2718
+ // src/v3/zodNamespace.ts
2719
+ var LogLevel;
2720
+ (function(LogLevel2) {
2721
+ LogLevel2[LogLevel2["log"] = 0] = "log";
2722
+ LogLevel2[LogLevel2["error"] = 1] = "error";
2723
+ LogLevel2[LogLevel2["warn"] = 2] = "warn";
2724
+ LogLevel2[LogLevel2["info"] = 3] = "info";
2725
+ LogLevel2[LogLevel2["debug"] = 4] = "debug";
2726
+ })(LogLevel || (LogLevel = {}));
2727
+ var _structuredLog, structuredLog_fn;
2728
+ var _SimpleStructuredLogger = class _SimpleStructuredLogger {
2729
+ constructor(name, level = [
2730
+ "1",
2731
+ "true"
2732
+ ].includes(process.env.DEBUG ?? "") ? LogLevel.debug : LogLevel.info, fields) {
2733
+ __privateAdd(this, _structuredLog);
2734
+ this.name = name;
2735
+ this.level = level;
2736
+ this.fields = fields;
2737
+ }
2738
+ child(fields, level) {
2739
+ return new _SimpleStructuredLogger(this.name, level, {
2740
+ ...this.fields,
2741
+ ...fields
2742
+ });
2261
2743
  }
2262
- static getInstance() {
2263
- if (!this._instance) {
2264
- this._instance = new _ClockAPI();
2744
+ log(message, ...args) {
2745
+ if (this.level < LogLevel.log)
2746
+ return;
2747
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.log, message, "log", ...args);
2748
+ }
2749
+ error(message, ...args) {
2750
+ if (this.level < LogLevel.error)
2751
+ return;
2752
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.error, message, "error", ...args);
2753
+ }
2754
+ warn(message, ...args) {
2755
+ if (this.level < LogLevel.warn)
2756
+ return;
2757
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.warn, message, "warn", ...args);
2758
+ }
2759
+ info(message, ...args) {
2760
+ if (this.level < LogLevel.info)
2761
+ return;
2762
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.info, message, "info", ...args);
2763
+ }
2764
+ debug(message, ...args) {
2765
+ if (this.level < LogLevel.debug)
2766
+ return;
2767
+ __privateMethod(this, _structuredLog, structuredLog_fn).call(this, console.debug, message, "debug", ...args);
2768
+ }
2769
+ };
2770
+ _structuredLog = new WeakSet();
2771
+ structuredLog_fn = /* @__PURE__ */ __name(function(loggerFunction, message, level, ...args) {
2772
+ const structuredLog = {
2773
+ ...args.length === 1 ? args[0] : args,
2774
+ ...this.fields,
2775
+ timestamp: /* @__PURE__ */ new Date(),
2776
+ name: this.name,
2777
+ message,
2778
+ level
2779
+ };
2780
+ loggerFunction(JSON.stringify(structuredLog));
2781
+ }, "#structuredLog");
2782
+ __name(_SimpleStructuredLogger, "SimpleStructuredLogger");
2783
+ var SimpleStructuredLogger = _SimpleStructuredLogger;
2784
+ var _logger2, _handler2;
2785
+ var _ZodNamespace = class _ZodNamespace {
2786
+ constructor(opts) {
2787
+ __privateAdd(this, _logger2, void 0);
2788
+ __privateAdd(this, _handler2, void 0);
2789
+ __privateSet(this, _logger2, opts.logger ?? new SimpleStructuredLogger(opts.name));
2790
+ __privateSet(this, _handler2, new ZodSocketMessageHandler({
2791
+ schema: opts.clientMessages,
2792
+ handlers: opts.handlers
2793
+ }));
2794
+ this.io = opts.io;
2795
+ this.namespace = this.io.of(opts.name);
2796
+ this.sender = new ZodMessageSender({
2797
+ schema: opts.serverMessages,
2798
+ sender: async (message) => {
2799
+ return new Promise((resolve, reject) => {
2800
+ try {
2801
+ this.namespace.emit(message.type, message.payload);
2802
+ resolve();
2803
+ } catch (err) {
2804
+ reject(err);
2805
+ }
2806
+ });
2807
+ }
2808
+ });
2809
+ if (opts.preAuth) {
2810
+ this.namespace.use(async (socket, next) => {
2811
+ const logger2 = __privateGet(this, _logger2).child({
2812
+ socketId: socket.id,
2813
+ socketStage: "preAuth"
2814
+ });
2815
+ if (typeof opts.preAuth === "function") {
2816
+ await opts.preAuth(socket, next, logger2);
2817
+ }
2818
+ });
2819
+ }
2820
+ if (opts.authToken) {
2821
+ this.namespace.use((socket, next) => {
2822
+ const logger2 = __privateGet(this, _logger2).child({
2823
+ socketId: socket.id,
2824
+ socketStage: "auth"
2825
+ });
2826
+ const { auth } = socket.handshake;
2827
+ if (!("token" in auth)) {
2828
+ logger2.error("no token");
2829
+ return socket.disconnect(true);
2830
+ }
2831
+ if (auth.token !== opts.authToken) {
2832
+ logger2.error("invalid token");
2833
+ return socket.disconnect(true);
2834
+ }
2835
+ logger2.info("success");
2836
+ next();
2837
+ });
2838
+ }
2839
+ if (opts.postAuth) {
2840
+ this.namespace.use(async (socket, next) => {
2841
+ const logger2 = __privateGet(this, _logger2).child({
2842
+ socketId: socket.id,
2843
+ socketStage: "auth"
2844
+ });
2845
+ if (typeof opts.postAuth === "function") {
2846
+ await opts.postAuth(socket, next, logger2);
2847
+ }
2848
+ });
2849
+ }
2850
+ this.namespace.on("connection", async (socket) => {
2851
+ const logger2 = __privateGet(this, _logger2).child({
2852
+ socketId: socket.id,
2853
+ socketStage: "connection"
2854
+ });
2855
+ logger2.info("connected");
2856
+ __privateGet(this, _handler2).registerHandlers(socket, logger2);
2857
+ socket.on("disconnect", async (reason, description) => {
2858
+ logger2.info("disconnect", {
2859
+ reason,
2860
+ description
2861
+ });
2862
+ if (opts.onDisconnect) {
2863
+ await opts.onDisconnect(socket, reason, description, logger2);
2864
+ }
2865
+ });
2866
+ socket.on("error", async (error) => {
2867
+ logger2.error("error", {
2868
+ error
2869
+ });
2870
+ if (opts.onError) {
2871
+ await opts.onError(socket, error, logger2);
2872
+ }
2873
+ });
2874
+ if (opts.onConnection) {
2875
+ await opts.onConnection(socket, __privateGet(this, _handler2), this.sender, logger2);
2876
+ }
2877
+ });
2878
+ }
2879
+ fetchSockets() {
2880
+ return this.namespace.fetchSockets();
2881
+ }
2882
+ };
2883
+ _logger2 = new WeakMap();
2884
+ _handler2 = new WeakMap();
2885
+ __name(_ZodNamespace, "ZodNamespace");
2886
+ var ZodNamespace = _ZodNamespace;
2887
+ var messageSchema2 = z.object({
2888
+ version: z.literal("v1").default("v1"),
2889
+ type: z.string(),
2890
+ payload: z.unknown()
2891
+ });
2892
+ var _schema5, _handlers3, _sender3, _a;
2893
+ var ZodIpcMessageHandler = (_a = class {
2894
+ constructor(options) {
2895
+ __privateAdd(this, _schema5, void 0);
2896
+ __privateAdd(this, _handlers3, void 0);
2897
+ __privateAdd(this, _sender3, void 0);
2898
+ __privateSet(this, _schema5, options.schema);
2899
+ __privateSet(this, _handlers3, options.handlers);
2900
+ __privateSet(this, _sender3, options.sender);
2901
+ }
2902
+ async handleMessage(message) {
2903
+ const parsedMessage = this.parseMessage(message);
2904
+ if (!__privateGet(this, _handlers3)) {
2905
+ throw new Error("No handlers provided");
2906
+ }
2907
+ const handler = __privateGet(this, _handlers3)[parsedMessage.type];
2908
+ if (!handler) {
2909
+ return;
2910
+ }
2911
+ const ack = await handler(parsedMessage.payload, __privateGet(this, _sender3));
2912
+ return ack;
2913
+ }
2914
+ parseMessage(message) {
2915
+ const parsedMessage = messageSchema2.safeParse(message);
2916
+ if (!parsedMessage.success) {
2917
+ throw new Error(`Failed to parse message: ${JSON.stringify(parsedMessage.error)}`);
2918
+ }
2919
+ const schema = __privateGet(this, _schema5)[parsedMessage.data.type]["message"];
2920
+ if (!schema) {
2921
+ throw new Error(`Unknown message type: ${parsedMessage.data.type}`);
2922
+ }
2923
+ const parsedPayload = schema.safeParse(parsedMessage.data.payload);
2924
+ if (!parsedPayload.success) {
2925
+ throw new Error(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
2926
+ }
2927
+ return {
2928
+ type: parsedMessage.data.type,
2929
+ payload: parsedPayload.data
2930
+ };
2931
+ }
2932
+ }, _schema5 = new WeakMap(), _handlers3 = new WeakMap(), _sender3 = new WeakMap(), __name(_a, "ZodIpcMessageHandler"), _a);
2933
+ var Packet = z.discriminatedUnion("type", [
2934
+ z.object({
2935
+ type: z.literal("CONNECT"),
2936
+ sessionId: z.string().optional()
2937
+ }),
2938
+ z.object({
2939
+ type: z.literal("ACK"),
2940
+ message: z.any(),
2941
+ id: z.number()
2942
+ }),
2943
+ z.object({
2944
+ type: z.literal("EVENT"),
2945
+ message: z.any(),
2946
+ id: z.number().optional()
2947
+ })
2948
+ ]);
2949
+ var _sessionId, _messageCounter, _handler3, _acks, _registerHandlers, registerHandlers_fn, _handlePacket, handlePacket_fn, _sendPacket, sendPacket_fn;
2950
+ var _ZodIpcConnection = class _ZodIpcConnection {
2951
+ constructor(opts) {
2952
+ __privateAdd(this, _registerHandlers);
2953
+ __privateAdd(this, _handlePacket);
2954
+ __privateAdd(this, _sendPacket);
2955
+ __privateAdd(this, _sessionId, void 0);
2956
+ __privateAdd(this, _messageCounter, void 0);
2957
+ __privateAdd(this, _handler3, void 0);
2958
+ __privateAdd(this, _acks, void 0);
2959
+ this.opts = opts;
2960
+ __privateSet(this, _messageCounter, 0);
2961
+ __privateSet(this, _acks, /* @__PURE__ */ new Map());
2962
+ __privateSet(this, _handler3, new ZodIpcMessageHandler({
2963
+ schema: opts.listenSchema,
2964
+ handlers: opts.handlers,
2965
+ sender: {
2966
+ send: this.send.bind(this),
2967
+ sendWithAck: this.sendWithAck.bind(this)
2968
+ }
2969
+ }));
2970
+ __privateMethod(this, _registerHandlers, registerHandlers_fn).call(this);
2971
+ }
2972
+ async connect() {
2973
+ __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2974
+ type: "CONNECT"
2975
+ });
2976
+ }
2977
+ async send(type, payload) {
2978
+ const schema = this.opts.emitSchema[type]["message"];
2979
+ if (!schema) {
2980
+ throw new Error(`Unknown message type: ${type}`);
2981
+ }
2982
+ const parsedPayload = schema.safeParse(payload);
2983
+ if (!parsedPayload.success) {
2984
+ throw new ZodSchemaParsedError(parsedPayload.error, payload);
2985
+ }
2986
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
2987
+ type: "EVENT",
2988
+ message: {
2989
+ type,
2990
+ payload,
2991
+ version: "v1"
2992
+ }
2993
+ });
2994
+ }
2995
+ async sendWithAck(type, payload, timeoutInMs) {
2996
+ const currentId = __privateWrapper(this, _messageCounter)._++;
2997
+ return new Promise(async (resolve, reject) => {
2998
+ const defaultTimeoutInMs = 2e3;
2999
+ const timeout = setTimeout(() => {
3000
+ reject(JSON.stringify({
3001
+ reason: "sendWithAck() timeout",
3002
+ timeoutInMs: timeoutInMs ?? defaultTimeoutInMs,
3003
+ type,
3004
+ payload
3005
+ }));
3006
+ }, timeoutInMs ?? defaultTimeoutInMs);
3007
+ __privateGet(this, _acks).set(currentId, {
3008
+ resolve,
3009
+ reject,
3010
+ timeout
3011
+ });
3012
+ const schema = this.opts.emitSchema[type]["message"];
3013
+ if (!schema) {
3014
+ clearTimeout(timeout);
3015
+ return reject(`Unknown message type: ${type}`);
3016
+ }
3017
+ const parsedPayload = schema.safeParse(payload);
3018
+ if (!parsedPayload.success) {
3019
+ clearTimeout(timeout);
3020
+ return reject(`Failed to parse message payload: ${JSON.stringify(parsedPayload.error)}`);
3021
+ }
3022
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3023
+ type: "EVENT",
3024
+ message: {
3025
+ type,
3026
+ payload,
3027
+ version: "v1"
3028
+ },
3029
+ id: currentId
3030
+ });
3031
+ });
3032
+ }
3033
+ };
3034
+ _sessionId = new WeakMap();
3035
+ _messageCounter = new WeakMap();
3036
+ _handler3 = new WeakMap();
3037
+ _acks = new WeakMap();
3038
+ _registerHandlers = new WeakSet();
3039
+ registerHandlers_fn = /* @__PURE__ */ __name(async function() {
3040
+ if (!this.opts.process.on) {
3041
+ return;
3042
+ }
3043
+ this.opts.process.on("message", async (message) => {
3044
+ __privateMethod(this, _handlePacket, handlePacket_fn).call(this, message);
3045
+ });
3046
+ }, "#registerHandlers");
3047
+ _handlePacket = new WeakSet();
3048
+ handlePacket_fn = /* @__PURE__ */ __name(async function(packet) {
3049
+ const parsedPacket = Packet.safeParse(packet);
3050
+ if (!parsedPacket.success) {
3051
+ return;
3052
+ }
3053
+ switch (parsedPacket.data.type) {
3054
+ case "ACK": {
3055
+ const ack = __privateGet(this, _acks).get(parsedPacket.data.id);
3056
+ if (!ack) {
3057
+ return;
3058
+ }
3059
+ clearTimeout(ack.timeout);
3060
+ ack.resolve(parsedPacket.data.message);
3061
+ break;
3062
+ }
3063
+ case "CONNECT": {
3064
+ if (!parsedPacket.data.sessionId) {
3065
+ const id = randomUUID();
3066
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3067
+ type: "CONNECT",
3068
+ sessionId: id
3069
+ });
3070
+ return;
3071
+ }
3072
+ if (__privateGet(this, _sessionId)) {
3073
+ return;
3074
+ }
3075
+ __privateSet(this, _sessionId, parsedPacket.data.sessionId);
3076
+ break;
3077
+ }
3078
+ case "EVENT": {
3079
+ const result = await __privateGet(this, _handler3).handleMessage(parsedPacket.data.message);
3080
+ if (typeof parsedPacket.data.id === "undefined") {
3081
+ return;
3082
+ }
3083
+ await __privateMethod(this, _sendPacket, sendPacket_fn).call(this, {
3084
+ type: "ACK",
3085
+ id: parsedPacket.data.id,
3086
+ message: result
3087
+ });
3088
+ break;
2265
3089
  }
2266
- return this._instance;
2267
- }
2268
- setGlobalClock(clock2) {
2269
- return registerGlobal(API_NAME2, clock2);
2270
- }
2271
- preciseNow() {
2272
- return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
2273
- }
2274
- reset() {
2275
- __privateMethod(this, _getClock, getClock_fn).call(this).reset();
2276
3090
  }
2277
- };
2278
- _getClock = new WeakSet();
2279
- getClock_fn = /* @__PURE__ */ __name(function() {
2280
- return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
2281
- }, "#getClock");
2282
- __name(_ClockAPI, "ClockAPI");
2283
- var ClockAPI = _ClockAPI;
2284
-
2285
- // src/v3/clock-api.ts
2286
- var clock = ClockAPI.getInstance();
3091
+ }, "#handlePacket");
3092
+ _sendPacket = new WeakSet();
3093
+ sendPacket_fn = /* @__PURE__ */ __name(async function(packet1) {
3094
+ await this.opts.process.send?.(packet1);
3095
+ }, "#sendPacket");
3096
+ __name(_ZodIpcConnection, "ZodIpcConnection");
3097
+ var ZodIpcConnection = _ZodIpcConnection;
2287
3098
  function parseError(error) {
2288
3099
  if (error instanceof Error) {
2289
3100
  return {
@@ -2395,146 +3206,261 @@ function groupTaskMetadataIssuesByTask(tasks, issues) {
2395
3206
  }
2396
3207
  __name(groupTaskMetadataIssuesByTask, "groupTaskMetadataIssuesByTask");
2397
3208
 
2398
- // src/v3/limits.ts
2399
- var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
2400
- var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
2401
- var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2402
- var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
2403
- var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
2404
- var OTEL_LINK_COUNT_LIMIT = 2;
2405
- var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
2406
- var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
2407
- var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
2408
- function imposeAttributeLimits(attributes) {
2409
- const newAttributes = {};
2410
- for (const [key, value] of Object.entries(attributes)) {
2411
- if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
2412
- continue;
2413
- }
2414
- if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
2415
- break;
2416
- }
2417
- newAttributes[key] = value;
3209
+ // src/v3/utils/platform.ts
3210
+ var _globalThis = typeof globalThis === "object" ? globalThis : global;
3211
+
3212
+ // src/v3/utils/globals.ts
3213
+ var GLOBAL_TRIGGER_DOT_DEV_KEY = Symbol.for(`dev.trigger.ts.api`);
3214
+ var _global = _globalThis;
3215
+ function registerGlobal(type, instance, allowOverride = false) {
3216
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] = _global[GLOBAL_TRIGGER_DOT_DEV_KEY] ?? {};
3217
+ if (!allowOverride && api[type]) {
3218
+ return false;
2418
3219
  }
2419
- return newAttributes;
3220
+ api[type] = instance;
3221
+ return true;
2420
3222
  }
2421
- __name(imposeAttributeLimits, "imposeAttributeLimits");
2422
- function calculateAttributeValueLength(value) {
2423
- if (value === void 0 || value === null) {
2424
- return 0;
3223
+ __name(registerGlobal, "registerGlobal");
3224
+ function getGlobal(type) {
3225
+ return _global[GLOBAL_TRIGGER_DOT_DEV_KEY]?.[type];
3226
+ }
3227
+ __name(getGlobal, "getGlobal");
3228
+ function unregisterGlobal(type) {
3229
+ const api = _global[GLOBAL_TRIGGER_DOT_DEV_KEY];
3230
+ if (api) {
3231
+ delete api[type];
2425
3232
  }
2426
- if (typeof value === "string") {
2427
- return value.length;
3233
+ }
3234
+ __name(unregisterGlobal, "unregisterGlobal");
3235
+
3236
+ // src/v3/runtime/noopRuntimeManager.ts
3237
+ var _NoopRuntimeManager = class _NoopRuntimeManager {
3238
+ disable() {
2428
3239
  }
2429
- if (typeof value === "number") {
2430
- return 8;
3240
+ waitForDuration(ms) {
3241
+ return Promise.resolve();
2431
3242
  }
2432
- if (typeof value === "boolean") {
2433
- return 4;
3243
+ waitUntil(date) {
3244
+ return Promise.resolve();
2434
3245
  }
2435
- if (Array.isArray(value)) {
2436
- return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3246
+ waitForTask(params) {
3247
+ return Promise.resolve({
3248
+ ok: false,
3249
+ id: params.id,
3250
+ error: {
3251
+ type: "INTERNAL_ERROR",
3252
+ code: "CONFIGURED_INCORRECTLY"
3253
+ }
3254
+ });
2437
3255
  }
2438
- return 0;
2439
- }
2440
- __name(calculateAttributeValueLength, "calculateAttributeValueLength");
3256
+ waitForBatch(params) {
3257
+ return Promise.resolve({
3258
+ id: params.id,
3259
+ items: []
3260
+ });
3261
+ }
3262
+ };
3263
+ __name(_NoopRuntimeManager, "NoopRuntimeManager");
3264
+ var NoopRuntimeManager = _NoopRuntimeManager;
2441
3265
 
2442
- // src/v3/utils/flattenAttributes.ts
2443
- function flattenAttributes(obj, prefix) {
2444
- const result = {};
2445
- if (!obj) {
2446
- return result;
3266
+ // src/v3/runtime/index.ts
3267
+ var API_NAME = "runtime";
3268
+ var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
3269
+ var _getRuntimeManager, getRuntimeManager_fn;
3270
+ var _RuntimeAPI = class _RuntimeAPI {
3271
+ constructor() {
3272
+ __privateAdd(this, _getRuntimeManager);
2447
3273
  }
2448
- if (typeof obj === "string") {
2449
- result[prefix || ""] = obj;
2450
- return result;
3274
+ static getInstance() {
3275
+ if (!this._instance) {
3276
+ this._instance = new _RuntimeAPI();
3277
+ }
3278
+ return this._instance;
2451
3279
  }
2452
- if (typeof obj === "number") {
2453
- result[prefix || ""] = obj;
2454
- return result;
3280
+ waitForDuration(ms) {
3281
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2455
3282
  }
2456
- if (typeof obj === "boolean") {
2457
- result[prefix || ""] = obj;
2458
- return result;
3283
+ waitUntil(date) {
3284
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2459
3285
  }
2460
- for (const [key, value] of Object.entries(obj)) {
2461
- const newPrefix = `${prefix ? `${prefix}.` : ""}${key}`;
2462
- if (Array.isArray(value)) {
2463
- for (let i = 0; i < value.length; i++) {
2464
- if (typeof value[i] === "object" && value[i] !== null) {
2465
- Object.assign(result, flattenAttributes(value[i], `${newPrefix}.[${i}]`));
2466
- } else {
2467
- result[`${newPrefix}.[${i}]`] = value[i];
2468
- }
2469
- }
2470
- } else if (isRecord(value)) {
2471
- Object.assign(result, flattenAttributes(value, newPrefix));
2472
- } else {
2473
- if (typeof value === "number" || typeof value === "string" || typeof value === "boolean") {
2474
- result[newPrefix] = value;
2475
- }
2476
- }
3286
+ waitForTask(params) {
3287
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
3288
+ }
3289
+ waitForBatch(params) {
3290
+ return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
3291
+ }
3292
+ setGlobalRuntimeManager(runtimeManager) {
3293
+ return registerGlobal(API_NAME, runtimeManager);
3294
+ }
3295
+ disable() {
3296
+ __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
3297
+ unregisterGlobal(API_NAME);
3298
+ }
3299
+ };
3300
+ _getRuntimeManager = new WeakSet();
3301
+ getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
3302
+ return getGlobal(API_NAME) ?? NOOP_RUNTIME_MANAGER;
3303
+ }, "#getRuntimeManager");
3304
+ __name(_RuntimeAPI, "RuntimeAPI");
3305
+ var RuntimeAPI = _RuntimeAPI;
3306
+
3307
+ // src/v3/runtime-api.ts
3308
+ var runtime = RuntimeAPI.getInstance();
3309
+ function iconStringForSeverity(severityNumber) {
3310
+ switch (severityNumber) {
3311
+ case SeverityNumber.UNSPECIFIED:
3312
+ return void 0;
3313
+ case SeverityNumber.TRACE:
3314
+ case SeverityNumber.TRACE2:
3315
+ case SeverityNumber.TRACE3:
3316
+ case SeverityNumber.TRACE4:
3317
+ return "trace";
3318
+ case SeverityNumber.DEBUG:
3319
+ case SeverityNumber.DEBUG2:
3320
+ case SeverityNumber.DEBUG3:
3321
+ case SeverityNumber.DEBUG4:
3322
+ return "debug";
3323
+ case SeverityNumber.INFO:
3324
+ case SeverityNumber.INFO2:
3325
+ case SeverityNumber.INFO3:
3326
+ case SeverityNumber.INFO4:
3327
+ return "info";
3328
+ case SeverityNumber.WARN:
3329
+ case SeverityNumber.WARN2:
3330
+ case SeverityNumber.WARN3:
3331
+ case SeverityNumber.WARN4:
3332
+ return "warn";
3333
+ case SeverityNumber.ERROR:
3334
+ case SeverityNumber.ERROR2:
3335
+ case SeverityNumber.ERROR3:
3336
+ case SeverityNumber.ERROR4:
3337
+ return "error";
3338
+ case SeverityNumber.FATAL:
3339
+ case SeverityNumber.FATAL2:
3340
+ case SeverityNumber.FATAL3:
3341
+ case SeverityNumber.FATAL4:
3342
+ return "fatal";
2477
3343
  }
2478
- return result;
2479
- }
2480
- __name(flattenAttributes, "flattenAttributes");
2481
- function isRecord(value) {
2482
- return value !== null && typeof value === "object" && !Array.isArray(value);
2483
3344
  }
2484
- __name(isRecord, "isRecord");
2485
- function unflattenAttributes(obj) {
2486
- if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
2487
- return obj;
3345
+ __name(iconStringForSeverity, "iconStringForSeverity");
3346
+ var _SimpleClock = class _SimpleClock {
3347
+ preciseNow() {
3348
+ const now = new PreciseDate();
3349
+ const nowStruct = now.toStruct();
3350
+ return [
3351
+ nowStruct.seconds,
3352
+ nowStruct.nanos
3353
+ ];
2488
3354
  }
2489
- const result = {};
2490
- for (const [key, value] of Object.entries(obj)) {
2491
- const parts = key.split(".").reduce((acc, part) => {
2492
- if (detectIsArrayIndex(part)) {
2493
- acc.push(part);
2494
- } else {
2495
- acc.push(...part.split(/\.\[(.*?)\]/).filter(Boolean));
2496
- }
2497
- return acc;
2498
- }, []);
2499
- let current = result;
2500
- for (let i = 0; i < parts.length - 1; i++) {
2501
- const part = parts[i];
2502
- const isArray = detectIsArrayIndex(part);
2503
- const cleanPart = isArray ? part.substring(1, part.length - 1) : part;
2504
- const nextIsArray = detectIsArrayIndex(parts[i + 1]);
2505
- if (!current[cleanPart]) {
2506
- current[cleanPart] = nextIsArray ? [] : {};
2507
- }
2508
- current = current[cleanPart];
3355
+ reset() {
3356
+ }
3357
+ };
3358
+ __name(_SimpleClock, "SimpleClock");
3359
+ var SimpleClock = _SimpleClock;
3360
+
3361
+ // src/v3/clock/index.ts
3362
+ var API_NAME2 = "clock";
3363
+ var SIMPLE_CLOCK = new SimpleClock();
3364
+ var _getClock, getClock_fn;
3365
+ var _ClockAPI = class _ClockAPI {
3366
+ constructor() {
3367
+ __privateAdd(this, _getClock);
3368
+ }
3369
+ static getInstance() {
3370
+ if (!this._instance) {
3371
+ this._instance = new _ClockAPI();
2509
3372
  }
2510
- const lastPart = parts[parts.length - 1];
2511
- const cleanLastPart = detectIsArrayIndex(lastPart) ? parseInt(lastPart.substring(1, lastPart.length - 1), 10) : lastPart;
2512
- current[cleanLastPart] = value;
3373
+ return this._instance;
3374
+ }
3375
+ setGlobalClock(clock2) {
3376
+ return registerGlobal(API_NAME2, clock2);
3377
+ }
3378
+ preciseNow() {
3379
+ return __privateMethod(this, _getClock, getClock_fn).call(this).preciseNow();
3380
+ }
3381
+ reset() {
3382
+ __privateMethod(this, _getClock, getClock_fn).call(this).reset();
3383
+ }
3384
+ };
3385
+ _getClock = new WeakSet();
3386
+ getClock_fn = /* @__PURE__ */ __name(function() {
3387
+ return getGlobal(API_NAME2) ?? SIMPLE_CLOCK;
3388
+ }, "#getClock");
3389
+ __name(_ClockAPI, "ClockAPI");
3390
+ var ClockAPI = _ClockAPI;
3391
+
3392
+ // src/v3/clock-api.ts
3393
+ var clock = ClockAPI.getInstance();
3394
+
3395
+ // src/v3/logger/taskLogger.ts
3396
+ var logLevels = [
3397
+ "none",
3398
+ "error",
3399
+ "warn",
3400
+ "log",
3401
+ "info",
3402
+ "debug"
3403
+ ];
3404
+ var _emitLog, emitLog_fn, _getTimestampInHrTime, getTimestampInHrTime_fn;
3405
+ var _OtelTaskLogger = class _OtelTaskLogger {
3406
+ constructor(_config) {
3407
+ __privateAdd(this, _emitLog);
3408
+ __privateAdd(this, _getTimestampInHrTime);
3409
+ this._config = _config;
3410
+ this._level = logLevels.indexOf(_config.level);
2513
3411
  }
2514
- return result;
2515
- }
2516
- __name(unflattenAttributes, "unflattenAttributes");
2517
- function detectIsArrayIndex(key) {
2518
- const match = key.match(/^\[(\d+)\]$/);
2519
- if (match) {
2520
- return true;
3412
+ debug(message, properties) {
3413
+ if (this._level < 5)
3414
+ return;
3415
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "debug", SeverityNumber.DEBUG, properties);
2521
3416
  }
2522
- return false;
2523
- }
2524
- __name(detectIsArrayIndex, "detectIsArrayIndex");
2525
- function primitiveValueOrflattenedAttributes(obj, prefix) {
2526
- if (typeof obj === "string" || typeof obj === "number" || typeof obj === "boolean" || obj === null || obj === void 0) {
2527
- return obj;
3417
+ log(message, properties) {
3418
+ if (this._level < 3)
3419
+ return;
3420
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "log", SeverityNumber.INFO, properties);
2528
3421
  }
2529
- const attributes = flattenAttributes(obj, prefix);
2530
- if (prefix !== void 0 && typeof attributes[prefix] !== "undefined" && attributes[prefix] !== null) {
2531
- return attributes[prefix];
3422
+ info(message, properties) {
3423
+ if (this._level < 4)
3424
+ return;
3425
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "info", SeverityNumber.INFO, properties);
2532
3426
  }
2533
- return attributes;
2534
- }
2535
- __name(primitiveValueOrflattenedAttributes, "primitiveValueOrflattenedAttributes");
2536
-
2537
- // src/v3/logger/taskLogger.ts
3427
+ warn(message, properties) {
3428
+ if (this._level < 2)
3429
+ return;
3430
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "warn", SeverityNumber.WARN, properties);
3431
+ }
3432
+ error(message, properties) {
3433
+ if (this._level < 1)
3434
+ return;
3435
+ __privateMethod(this, _emitLog, emitLog_fn).call(this, message, __privateMethod(this, _getTimestampInHrTime, getTimestampInHrTime_fn).call(this), "error", SeverityNumber.ERROR, properties);
3436
+ }
3437
+ trace(name, fn, options) {
3438
+ return this._config.tracer.startActiveSpan(name, fn, options);
3439
+ }
3440
+ };
3441
+ _emitLog = new WeakSet();
3442
+ emitLog_fn = /* @__PURE__ */ __name(function(message, timestamp, severityText, severityNumber, properties) {
3443
+ let attributes = {
3444
+ ...flattenAttributes(safeJsonProcess(properties))
3445
+ };
3446
+ const icon = iconStringForSeverity(severityNumber);
3447
+ if (icon !== void 0) {
3448
+ attributes[SemanticInternalAttributes.STYLE_ICON] = icon;
3449
+ }
3450
+ this._config.logger.emit({
3451
+ severityNumber,
3452
+ severityText,
3453
+ body: message,
3454
+ attributes,
3455
+ timestamp
3456
+ });
3457
+ }, "#emitLog");
3458
+ _getTimestampInHrTime = new WeakSet();
3459
+ getTimestampInHrTime_fn = /* @__PURE__ */ __name(function() {
3460
+ return clock.preciseNow();
3461
+ }, "#getTimestampInHrTime");
3462
+ __name(_OtelTaskLogger, "OtelTaskLogger");
3463
+ var OtelTaskLogger = _OtelTaskLogger;
2538
3464
  var _NoopTaskLogger = class _NoopTaskLogger {
2539
3465
  debug() {
2540
3466
  }
@@ -2552,6 +3478,25 @@ var _NoopTaskLogger = class _NoopTaskLogger {
2552
3478
  };
2553
3479
  __name(_NoopTaskLogger, "NoopTaskLogger");
2554
3480
  var NoopTaskLogger = _NoopTaskLogger;
3481
+ function safeJsonProcess(value) {
3482
+ try {
3483
+ return JSON.parse(JSON.stringify(value, jsonErrorReplacer));
3484
+ } catch {
3485
+ return value;
3486
+ }
3487
+ }
3488
+ __name(safeJsonProcess, "safeJsonProcess");
3489
+ function jsonErrorReplacer(key, value) {
3490
+ if (value instanceof Error) {
3491
+ return {
3492
+ name: value.name,
3493
+ message: value.message,
3494
+ stack: value.stack
3495
+ };
3496
+ }
3497
+ return value;
3498
+ }
3499
+ __name(jsonErrorReplacer, "jsonErrorReplacer");
2555
3500
 
2556
3501
  // src/v3/logger/index.ts
2557
3502
  var API_NAME3 = "logger";
@@ -2602,80 +3547,6 @@ var LoggerAPI = _LoggerAPI;
2602
3547
  // src/v3/logger-api.ts
2603
3548
  var logger = LoggerAPI.getInstance();
2604
3549
 
2605
- // src/v3/runtime/noopRuntimeManager.ts
2606
- var _NoopRuntimeManager = class _NoopRuntimeManager {
2607
- disable() {
2608
- }
2609
- waitForDuration(ms) {
2610
- return Promise.resolve();
2611
- }
2612
- waitUntil(date) {
2613
- return Promise.resolve();
2614
- }
2615
- waitForTask(params) {
2616
- return Promise.resolve({
2617
- ok: false,
2618
- id: params.id,
2619
- error: {
2620
- type: "INTERNAL_ERROR",
2621
- code: "CONFIGURED_INCORRECTLY"
2622
- }
2623
- });
2624
- }
2625
- waitForBatch(params) {
2626
- return Promise.resolve({
2627
- id: params.id,
2628
- items: []
2629
- });
2630
- }
2631
- };
2632
- __name(_NoopRuntimeManager, "NoopRuntimeManager");
2633
- var NoopRuntimeManager = _NoopRuntimeManager;
2634
-
2635
- // src/v3/runtime/index.ts
2636
- var API_NAME4 = "runtime";
2637
- var NOOP_RUNTIME_MANAGER = new NoopRuntimeManager();
2638
- var _getRuntimeManager, getRuntimeManager_fn;
2639
- var _RuntimeAPI = class _RuntimeAPI {
2640
- constructor() {
2641
- __privateAdd(this, _getRuntimeManager);
2642
- }
2643
- static getInstance() {
2644
- if (!this._instance) {
2645
- this._instance = new _RuntimeAPI();
2646
- }
2647
- return this._instance;
2648
- }
2649
- waitForDuration(ms) {
2650
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForDuration(ms);
2651
- }
2652
- waitUntil(date) {
2653
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitUntil(date);
2654
- }
2655
- waitForTask(params) {
2656
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForTask(params);
2657
- }
2658
- waitForBatch(params) {
2659
- return __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).waitForBatch(params);
2660
- }
2661
- setGlobalRuntimeManager(runtimeManager) {
2662
- return registerGlobal(API_NAME4, runtimeManager);
2663
- }
2664
- disable() {
2665
- __privateMethod(this, _getRuntimeManager, getRuntimeManager_fn).call(this).disable();
2666
- unregisterGlobal(API_NAME4);
2667
- }
2668
- };
2669
- _getRuntimeManager = new WeakSet();
2670
- getRuntimeManager_fn = /* @__PURE__ */ __name(function() {
2671
- return getGlobal(API_NAME4) ?? NOOP_RUNTIME_MANAGER;
2672
- }, "#getRuntimeManager");
2673
- __name(_RuntimeAPI, "RuntimeAPI");
2674
- var RuntimeAPI = _RuntimeAPI;
2675
-
2676
- // src/v3/runtime-api.ts
2677
- var runtime = RuntimeAPI.getInstance();
2678
-
2679
3550
  // src/v3/task-catalog/noopTaskCatalog.ts
2680
3551
  var _NoopTaskCatalog = class _NoopTaskCatalog {
2681
3552
  registerTaskMetadata(task) {
@@ -2700,7 +3571,7 @@ __name(_NoopTaskCatalog, "NoopTaskCatalog");
2700
3571
  var NoopTaskCatalog = _NoopTaskCatalog;
2701
3572
 
2702
3573
  // src/v3/task-catalog/index.ts
2703
- var API_NAME5 = "task-catalog";
3574
+ var API_NAME4 = "task-catalog";
2704
3575
  var NOOP_TASK_CATALOG = new NoopTaskCatalog();
2705
3576
  var _getCatalog, getCatalog_fn;
2706
3577
  var _TaskCatalogAPI = class _TaskCatalogAPI {
@@ -2714,10 +3585,10 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2714
3585
  return this._instance;
2715
3586
  }
2716
3587
  setGlobalTaskCatalog(taskCatalog2) {
2717
- return registerGlobal(API_NAME5, taskCatalog2);
3588
+ return registerGlobal(API_NAME4, taskCatalog2);
2718
3589
  }
2719
3590
  disable() {
2720
- unregisterGlobal(API_NAME5);
3591
+ unregisterGlobal(API_NAME4);
2721
3592
  }
2722
3593
  registerTaskMetadata(task) {
2723
3594
  __privateMethod(this, _getCatalog, getCatalog_fn).call(this).registerTaskMetadata(task);
@@ -2740,13 +3611,57 @@ var _TaskCatalogAPI = class _TaskCatalogAPI {
2740
3611
  };
2741
3612
  _getCatalog = new WeakSet();
2742
3613
  getCatalog_fn = /* @__PURE__ */ __name(function() {
2743
- return getGlobal(API_NAME5) ?? NOOP_TASK_CATALOG;
3614
+ return getGlobal(API_NAME4) ?? NOOP_TASK_CATALOG;
2744
3615
  }, "#getCatalog");
2745
3616
  __name(_TaskCatalogAPI, "TaskCatalogAPI");
2746
3617
  var TaskCatalogAPI = _TaskCatalogAPI;
2747
3618
 
2748
3619
  // src/v3/task-catalog-api.ts
2749
3620
  var taskCatalog = TaskCatalogAPI.getInstance();
3621
+
3622
+ // src/v3/limits.ts
3623
+ var OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT = 256;
3624
+ var OTEL_LOG_ATTRIBUTE_COUNT_LIMIT = 256;
3625
+ var OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3626
+ var OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT = 1028;
3627
+ var OTEL_SPAN_EVENT_COUNT_LIMIT = 10;
3628
+ var OTEL_LINK_COUNT_LIMIT = 2;
3629
+ var OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 10;
3630
+ var OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 10;
3631
+ var OFFLOAD_IO_PACKET_LENGTH_LIMIT = 128 * 1024;
3632
+ function imposeAttributeLimits(attributes) {
3633
+ const newAttributes = {};
3634
+ for (const [key, value] of Object.entries(attributes)) {
3635
+ if (calculateAttributeValueLength(value) > OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT) {
3636
+ continue;
3637
+ }
3638
+ if (Object.keys(newAttributes).length >= OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT) {
3639
+ break;
3640
+ }
3641
+ newAttributes[key] = value;
3642
+ }
3643
+ return newAttributes;
3644
+ }
3645
+ __name(imposeAttributeLimits, "imposeAttributeLimits");
3646
+ function calculateAttributeValueLength(value) {
3647
+ if (value === void 0 || value === null) {
3648
+ return 0;
3649
+ }
3650
+ if (typeof value === "string") {
3651
+ return value.length;
3652
+ }
3653
+ if (typeof value === "number") {
3654
+ return 8;
3655
+ }
3656
+ if (typeof value === "boolean") {
3657
+ return 4;
3658
+ }
3659
+ if (Array.isArray(value)) {
3660
+ return value.reduce((acc, v) => acc + calculateAttributeValueLength(v), 0);
3661
+ }
3662
+ return 0;
3663
+ }
3664
+ __name(calculateAttributeValueLength, "calculateAttributeValueLength");
2750
3665
  function dateDifference(date1, date2) {
2751
3666
  return Math.abs(date1.getTime() - date2.getTime());
2752
3667
  }
@@ -2788,39 +3703,256 @@ function formatDurationMilliseconds(milliseconds, options) {
2788
3703
  if (!options) {
2789
3704
  return duration;
2790
3705
  }
2791
- switch (options.style) {
2792
- case "short":
2793
- duration = duration.replace(" milliseconds", "ms");
2794
- duration = duration.replace(" millisecond", "ms");
2795
- duration = duration.replace(" seconds", "s");
2796
- duration = duration.replace(" second", "s");
2797
- duration = duration.replace(" minutes", "m");
2798
- duration = duration.replace(" minute", "m");
2799
- duration = duration.replace(" hours", "h");
2800
- duration = duration.replace(" hour", "h");
2801
- duration = duration.replace(" days", "d");
2802
- duration = duration.replace(" day", "d");
2803
- duration = duration.replace(" weeks", "w");
2804
- duration = duration.replace(" week", "w");
2805
- duration = duration.replace(" months", "mo");
2806
- duration = duration.replace(" month", "mo");
2807
- duration = duration.replace(" years", "y");
2808
- duration = duration.replace(" year", "y");
3706
+ switch (options.style) {
3707
+ case "short":
3708
+ duration = duration.replace(" milliseconds", "ms");
3709
+ duration = duration.replace(" millisecond", "ms");
3710
+ duration = duration.replace(" seconds", "s");
3711
+ duration = duration.replace(" second", "s");
3712
+ duration = duration.replace(" minutes", "m");
3713
+ duration = duration.replace(" minute", "m");
3714
+ duration = duration.replace(" hours", "h");
3715
+ duration = duration.replace(" hour", "h");
3716
+ duration = duration.replace(" days", "d");
3717
+ duration = duration.replace(" day", "d");
3718
+ duration = duration.replace(" weeks", "w");
3719
+ duration = duration.replace(" week", "w");
3720
+ duration = duration.replace(" months", "mo");
3721
+ duration = duration.replace(" month", "mo");
3722
+ duration = duration.replace(" years", "y");
3723
+ duration = duration.replace(" year", "y");
3724
+ }
3725
+ return duration;
3726
+ }
3727
+ __name(formatDurationMilliseconds, "formatDurationMilliseconds");
3728
+ function formatDurationInDays(milliseconds) {
3729
+ let duration = humanizeDuration(milliseconds, {
3730
+ maxDecimalPoints: 0,
3731
+ largest: 2,
3732
+ units: [
3733
+ "d"
3734
+ ]
3735
+ });
3736
+ return duration;
3737
+ }
3738
+ __name(formatDurationInDays, "formatDurationInDays");
3739
+ async function unboundedTimeout(delay = 0, value, options) {
3740
+ const maxDelay = 2147483647;
3741
+ const fullTimeouts = Math.floor(delay / maxDelay);
3742
+ const remainingDelay = delay % maxDelay;
3743
+ let lastTimeoutResult = await setTimeout$1(remainingDelay, value, options);
3744
+ for (let i = 0; i < fullTimeouts; i++) {
3745
+ lastTimeoutResult = await setTimeout$1(maxDelay, value, options);
3746
+ }
3747
+ return lastTimeoutResult;
3748
+ }
3749
+ __name(unboundedTimeout, "unboundedTimeout");
3750
+
3751
+ // src/v3/runtime/devRuntimeManager.ts
3752
+ var _DevRuntimeManager = class _DevRuntimeManager {
3753
+ constructor() {
3754
+ __publicField(this, "_taskWaits", /* @__PURE__ */ new Map());
3755
+ __publicField(this, "_batchWaits", /* @__PURE__ */ new Map());
3756
+ __publicField(this, "_pendingCompletionNotifications", /* @__PURE__ */ new Map());
3757
+ }
3758
+ disable() {
3759
+ }
3760
+ async waitForDuration(ms) {
3761
+ await unboundedTimeout(ms);
3762
+ }
3763
+ async waitUntil(date) {
3764
+ return this.waitForDuration(date.getTime() - Date.now());
3765
+ }
3766
+ async waitForTask(params) {
3767
+ const pendingCompletion = this._pendingCompletionNotifications.get(params.id);
3768
+ if (pendingCompletion) {
3769
+ this._pendingCompletionNotifications.delete(params.id);
3770
+ return pendingCompletion;
3771
+ }
3772
+ const promise = new Promise((resolve) => {
3773
+ this._taskWaits.set(params.id, {
3774
+ resolve
3775
+ });
3776
+ });
3777
+ return await promise;
3778
+ }
3779
+ async waitForBatch(params) {
3780
+ if (!params.runs.length) {
3781
+ return Promise.resolve({
3782
+ id: params.id,
3783
+ items: []
3784
+ });
3785
+ }
3786
+ const promise = Promise.all(params.runs.map((runId) => {
3787
+ return new Promise((resolve, reject) => {
3788
+ const pendingCompletion = this._pendingCompletionNotifications.get(runId);
3789
+ if (pendingCompletion) {
3790
+ this._pendingCompletionNotifications.delete(runId);
3791
+ resolve(pendingCompletion);
3792
+ return;
3793
+ }
3794
+ this._taskWaits.set(runId, {
3795
+ resolve
3796
+ });
3797
+ });
3798
+ }));
3799
+ const results = await promise;
3800
+ return {
3801
+ id: params.id,
3802
+ items: results
3803
+ };
3804
+ }
3805
+ resumeTask(completion, execution) {
3806
+ const wait = this._taskWaits.get(execution.run.id);
3807
+ if (!wait) {
3808
+ this._pendingCompletionNotifications.set(execution.run.id, completion);
3809
+ return;
3810
+ }
3811
+ wait.resolve(completion);
3812
+ this._taskWaits.delete(execution.run.id);
3813
+ }
3814
+ };
3815
+ __name(_DevRuntimeManager, "DevRuntimeManager");
3816
+ var DevRuntimeManager = _DevRuntimeManager;
3817
+
3818
+ // src/v3/runtime/prodRuntimeManager.ts
3819
+ var _ProdRuntimeManager = class _ProdRuntimeManager {
3820
+ constructor(ipc, options = {}) {
3821
+ this.ipc = ipc;
3822
+ this.options = options;
3823
+ this._taskWaits = /* @__PURE__ */ new Map();
3824
+ this._batchWaits = /* @__PURE__ */ new Map();
3825
+ }
3826
+ disable() {
3827
+ }
3828
+ async waitForDuration(ms) {
3829
+ const now = Date.now();
3830
+ const resolveAfterDuration = unboundedTimeout(ms, "duration");
3831
+ if (ms <= this.waitThresholdInMs) {
3832
+ await resolveAfterDuration;
3833
+ return;
3834
+ }
3835
+ const waitForRestore = new Promise((resolve, reject) => {
3836
+ this._waitForRestore = {
3837
+ resolve,
3838
+ reject
3839
+ };
3840
+ });
3841
+ const { willCheckpointAndRestore } = await this.ipc.sendWithAck("WAIT_FOR_DURATION", {
3842
+ ms,
3843
+ now
3844
+ });
3845
+ if (!willCheckpointAndRestore) {
3846
+ await resolveAfterDuration;
3847
+ return;
3848
+ }
3849
+ this.ipc.send("READY_FOR_CHECKPOINT", {});
3850
+ await Promise.race([
3851
+ waitForRestore,
3852
+ resolveAfterDuration
3853
+ ]);
3854
+ this.ipc.send("CANCEL_CHECKPOINT", {});
3855
+ }
3856
+ resumeAfterRestore() {
3857
+ if (!this._waitForRestore) {
3858
+ return;
3859
+ }
3860
+ clock.reset();
3861
+ this._waitForRestore.resolve("restore");
3862
+ this._waitForRestore = void 0;
3863
+ }
3864
+ async waitUntil(date) {
3865
+ return this.waitForDuration(date.getTime() - Date.now());
3866
+ }
3867
+ async waitForTask(params) {
3868
+ const promise = new Promise((resolve) => {
3869
+ this._taskWaits.set(params.id, {
3870
+ resolve
3871
+ });
3872
+ });
3873
+ await this.ipc.send("WAIT_FOR_TASK", {
3874
+ friendlyId: params.id
3875
+ });
3876
+ const result = await promise;
3877
+ clock.reset();
3878
+ return result;
3879
+ }
3880
+ async waitForBatch(params) {
3881
+ if (!params.runs.length) {
3882
+ return Promise.resolve({
3883
+ id: params.id,
3884
+ items: []
3885
+ });
3886
+ }
3887
+ const promise = Promise.all(params.runs.map((runId) => {
3888
+ return new Promise((resolve, reject) => {
3889
+ this._taskWaits.set(runId, {
3890
+ resolve
3891
+ });
3892
+ });
3893
+ }));
3894
+ await this.ipc.send("WAIT_FOR_BATCH", {
3895
+ batchFriendlyId: params.id,
3896
+ runFriendlyIds: params.runs
3897
+ });
3898
+ const results = await promise;
3899
+ clock.reset();
3900
+ return {
3901
+ id: params.id,
3902
+ items: results
3903
+ };
3904
+ }
3905
+ resumeTask(completion, execution) {
3906
+ const wait = this._taskWaits.get(execution.run.id);
3907
+ if (!wait) {
3908
+ return;
3909
+ }
3910
+ wait.resolve(completion);
3911
+ this._taskWaits.delete(execution.run.id);
3912
+ }
3913
+ get waitThresholdInMs() {
3914
+ return this.options.waitThresholdInMs ?? 3e4;
3915
+ }
3916
+ };
3917
+ __name(_ProdRuntimeManager, "ProdRuntimeManager");
3918
+ var ProdRuntimeManager = _ProdRuntimeManager;
3919
+ var _originClockTime, originClockTime_get, _originPreciseDate, originPreciseDate_get;
3920
+ var _PreciseWallClock = class _PreciseWallClock {
3921
+ constructor(options = {}) {
3922
+ __privateAdd(this, _originClockTime);
3923
+ __privateAdd(this, _originPreciseDate);
3924
+ this._origin = {
3925
+ clockTime: options.origin ?? process.hrtime(),
3926
+ preciseDate: options.now ?? new PreciseDate()
3927
+ };
3928
+ }
3929
+ preciseNow() {
3930
+ const elapsedHrTime = process.hrtime(__privateGet(this, _originClockTime, originClockTime_get));
3931
+ const elapsedNanoseconds = BigInt(elapsedHrTime[0]) * BigInt(1e9) + BigInt(elapsedHrTime[1]);
3932
+ const preciseDate = new PreciseDate(__privateGet(this, _originPreciseDate, originPreciseDate_get).getFullTime() + elapsedNanoseconds);
3933
+ const dateStruct = preciseDate.toStruct();
3934
+ return [
3935
+ dateStruct.seconds,
3936
+ dateStruct.nanos
3937
+ ];
3938
+ }
3939
+ reset() {
3940
+ this._origin = {
3941
+ clockTime: process.hrtime(),
3942
+ preciseDate: new PreciseDate()
3943
+ };
2809
3944
  }
2810
- return duration;
2811
- }
2812
- __name(formatDurationMilliseconds, "formatDurationMilliseconds");
2813
- function formatDurationInDays(milliseconds) {
2814
- let duration = humanizeDuration(milliseconds, {
2815
- maxDecimalPoints: 0,
2816
- largest: 2,
2817
- units: [
2818
- "d"
2819
- ]
2820
- });
2821
- return duration;
2822
- }
2823
- __name(formatDurationInDays, "formatDurationInDays");
3945
+ };
3946
+ _originClockTime = new WeakSet();
3947
+ originClockTime_get = /* @__PURE__ */ __name(function() {
3948
+ return this._origin.clockTime;
3949
+ }, "#originClockTime");
3950
+ _originPreciseDate = new WeakSet();
3951
+ originPreciseDate_get = /* @__PURE__ */ __name(function() {
3952
+ return this._origin.preciseDate;
3953
+ }, "#originPreciseDate");
3954
+ __name(_PreciseWallClock, "PreciseWallClock");
3955
+ var PreciseWallClock = _PreciseWallClock;
2824
3956
  var _TriggerTracer = class _TriggerTracer {
2825
3957
  constructor(_config) {
2826
3958
  this._config = _config;
@@ -2892,6 +4024,146 @@ var _TriggerTracer = class _TriggerTracer {
2892
4024
  };
2893
4025
  __name(_TriggerTracer, "TriggerTracer");
2894
4026
  var TriggerTracer = _TriggerTracer;
4027
+ var _handleLog, handleLog_fn, _getTimestampInHrTime2, getTimestampInHrTime_fn2, _getAttributes, getAttributes_fn;
4028
+ var _ConsoleInterceptor = class _ConsoleInterceptor {
4029
+ constructor(logger2, sendToStdIO) {
4030
+ __privateAdd(this, _handleLog);
4031
+ __privateAdd(this, _getTimestampInHrTime2);
4032
+ __privateAdd(this, _getAttributes);
4033
+ this.logger = logger2;
4034
+ this.sendToStdIO = sendToStdIO;
4035
+ }
4036
+ // Intercept the console and send logs to the OpenTelemetry logger
4037
+ // during the execution of the callback
4038
+ async intercept(console2, callback) {
4039
+ const originalConsole = {
4040
+ log: console2.log,
4041
+ info: console2.info,
4042
+ warn: console2.warn,
4043
+ error: console2.error,
4044
+ debug: console2.debug
4045
+ };
4046
+ console2.log = this.log.bind(this);
4047
+ console2.info = this.info.bind(this);
4048
+ console2.warn = this.warn.bind(this);
4049
+ console2.error = this.error.bind(this);
4050
+ console2.debug = this.debug.bind(this);
4051
+ try {
4052
+ return await callback();
4053
+ } finally {
4054
+ console2.log = originalConsole.log;
4055
+ console2.info = originalConsole.info;
4056
+ console2.warn = originalConsole.warn;
4057
+ console2.error = originalConsole.error;
4058
+ console2.debug = originalConsole.debug;
4059
+ }
4060
+ }
4061
+ debug(...args) {
4062
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.DEBUG, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Debug", ...args);
4063
+ }
4064
+ log(...args) {
4065
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Log", ...args);
4066
+ }
4067
+ info(...args) {
4068
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.INFO, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Info", ...args);
4069
+ }
4070
+ warn(...args) {
4071
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.WARN, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Warn", ...args);
4072
+ }
4073
+ error(...args) {
4074
+ __privateMethod(this, _handleLog, handleLog_fn).call(this, SeverityNumber.ERROR, __privateMethod(this, _getTimestampInHrTime2, getTimestampInHrTime_fn2).call(this), "Error", ...args);
4075
+ }
4076
+ };
4077
+ _handleLog = new WeakSet();
4078
+ handleLog_fn = /* @__PURE__ */ __name(function(severityNumber, timestamp, severityText, ...args) {
4079
+ const body = util.format(...args);
4080
+ if (this.sendToStdIO) {
4081
+ if (severityNumber === SeverityNumber.ERROR) {
4082
+ process.stderr.write(body);
4083
+ } else {
4084
+ process.stdout.write(body);
4085
+ }
4086
+ }
4087
+ const parsed = tryParseJSON(body);
4088
+ if (parsed.ok) {
4089
+ this.logger.emit({
4090
+ severityNumber,
4091
+ severityText,
4092
+ body: getLogMessage(parsed.value, severityText),
4093
+ attributes: {
4094
+ ...__privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4095
+ ...flattenAttributes(parsed.value)
4096
+ },
4097
+ timestamp
4098
+ });
4099
+ return;
4100
+ }
4101
+ this.logger.emit({
4102
+ severityNumber,
4103
+ severityText,
4104
+ body,
4105
+ attributes: __privateMethod(this, _getAttributes, getAttributes_fn).call(this, severityNumber),
4106
+ timestamp
4107
+ });
4108
+ }, "#handleLog");
4109
+ _getTimestampInHrTime2 = new WeakSet();
4110
+ getTimestampInHrTime_fn2 = /* @__PURE__ */ __name(function() {
4111
+ return clock.preciseNow();
4112
+ }, "#getTimestampInHrTime");
4113
+ _getAttributes = new WeakSet();
4114
+ getAttributes_fn = /* @__PURE__ */ __name(function(severityNumber1) {
4115
+ const icon = iconStringForSeverity(severityNumber1);
4116
+ let result = {};
4117
+ if (icon !== void 0) {
4118
+ result[SemanticInternalAttributes.STYLE_ICON] = icon;
4119
+ }
4120
+ return result;
4121
+ }, "#getAttributes");
4122
+ __name(_ConsoleInterceptor, "ConsoleInterceptor");
4123
+ var ConsoleInterceptor = _ConsoleInterceptor;
4124
+ function getLogMessage(value, fallback) {
4125
+ if (typeof value["message"] === "string") {
4126
+ return value["message"];
4127
+ }
4128
+ if (typeof value["msg"] === "string") {
4129
+ return value["msg"];
4130
+ }
4131
+ if (typeof value["body"] === "string") {
4132
+ return value["body"];
4133
+ }
4134
+ if (typeof value["error"] === "string") {
4135
+ return value["error"];
4136
+ }
4137
+ return fallback;
4138
+ }
4139
+ __name(getLogMessage, "getLogMessage");
4140
+ function tryParseJSON(value) {
4141
+ try {
4142
+ const parsed = JSON.parse(value);
4143
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
4144
+ return {
4145
+ ok: true,
4146
+ value: parsed
4147
+ };
4148
+ }
4149
+ return {
4150
+ ok: false,
4151
+ value
4152
+ };
4153
+ } catch (e) {
4154
+ return {
4155
+ ok: false,
4156
+ value
4157
+ };
4158
+ }
4159
+ }
4160
+ __name(tryParseJSON, "tryParseJSON");
4161
+
4162
+ // src/v3/utils/styleAttributes.ts
4163
+ function accessoryAttributes(accessory) {
4164
+ return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
4165
+ }
4166
+ __name(accessoryAttributes, "accessoryAttributes");
2895
4167
 
2896
4168
  // src/eventFilterMatches.ts
2897
4169
  function eventFilterMatches(payload, filter) {
@@ -3061,41 +4333,150 @@ function omit(obj, ...keys) {
3061
4333
  return result;
3062
4334
  }
3063
4335
  __name(omit, "omit");
3064
-
3065
- // src/v3/utils/styleAttributes.ts
3066
- function accessoryAttributes(accessory) {
3067
- return flattenAttributes(accessory, SemanticInternalAttributes.STYLE_ACCESSORY);
3068
- }
3069
- __name(accessoryAttributes, "accessoryAttributes");
3070
-
3071
- // package.json
3072
- var dependencies = {
3073
- "@google-cloud/precise-date": "^4.0.0",
3074
- "@opentelemetry/api": "^1.8.0",
3075
- "@opentelemetry/api-logs": "^0.48.0",
3076
- "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
3077
- "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
3078
- "@opentelemetry/instrumentation": "^0.49.1",
3079
- "@opentelemetry/resources": "^1.22.0",
3080
- "@opentelemetry/sdk-logs": "^0.49.1",
3081
- "@opentelemetry/sdk-node": "^0.49.1",
3082
- "@opentelemetry/sdk-trace-base": "^1.22.0",
3083
- "@opentelemetry/sdk-trace-node": "^1.22.0",
3084
- "@opentelemetry/semantic-conventions": "^1.22.0",
3085
- "humanize-duration": "^3.27.3",
3086
- superjson: "^2.2.1",
3087
- ulidx: "^2.2.1",
3088
- zod: "3.22.3",
3089
- "zod-error": "1.5.0",
3090
- "zod-validation-error": "^1.5.0",
3091
- "socket.io-client": "4.7.4"
4336
+ var _a2;
4337
+ var AsyncResourceDetector = (_a2 = class {
4338
+ constructor() {
4339
+ __publicField(this, "_resolved", false);
4340
+ this._promise = new Promise((resolver) => {
4341
+ this._resolver = resolver;
4342
+ });
4343
+ }
4344
+ detect(_config) {
4345
+ return new Resource({}, this._promise);
4346
+ }
4347
+ resolveWithAttributes(attributes) {
4348
+ if (!this._resolver) {
4349
+ throw new Error("Resolver not available");
4350
+ }
4351
+ if (this._resolved) {
4352
+ return;
4353
+ }
4354
+ this._resolved = true;
4355
+ this._resolver(attributes);
4356
+ }
4357
+ }, __name(_a2, "AsyncResourceDetector"), _a2);
4358
+ var _TracingSDK = class _TracingSDK {
4359
+ constructor(config) {
4360
+ this.config = config;
4361
+ this.asyncResourceDetector = new AsyncResourceDetector();
4362
+ setLogLevel(config.diagLogLevel ?? "none");
4363
+ const envResourceAttributesSerialized = getEnvVar("OTEL_RESOURCE_ATTRIBUTES");
4364
+ const envResourceAttributes = envResourceAttributesSerialized ? JSON.parse(envResourceAttributesSerialized) : {};
4365
+ const commonResources = detectResourcesSync({
4366
+ detectors: [
4367
+ this.asyncResourceDetector,
4368
+ processDetectorSync
4369
+ ]
4370
+ }).merge(new Resource({
4371
+ [SemanticResourceAttributes.CLOUD_PROVIDER]: "trigger.dev",
4372
+ [SemanticInternalAttributes.TRIGGER]: true
4373
+ })).merge(config.resource ?? new Resource({})).merge(new Resource(envResourceAttributes));
4374
+ const traceProvider = new NodeTracerProvider({
4375
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
4376
+ resource: commonResources,
4377
+ spanLimits: {
4378
+ attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
4379
+ attributeValueLengthLimit: OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,
4380
+ eventCountLimit: OTEL_SPAN_EVENT_COUNT_LIMIT,
4381
+ attributePerEventCountLimit: OTEL_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,
4382
+ linkCountLimit: OTEL_LINK_COUNT_LIMIT,
4383
+ attributePerLinkCountLimit: OTEL_ATTRIBUTE_PER_LINK_COUNT_LIMIT
4384
+ }
4385
+ });
4386
+ const spanExporter = new OTLPTraceExporter({
4387
+ url: `${config.url}/v1/traces`,
4388
+ timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
4389
+ });
4390
+ traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchSpanProcessor(spanExporter, {
4391
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4392
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_SPAN_SCHEDULED_DELAY_MILLIS") ?? "200"),
4393
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_SPAN_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4394
+ maxQueueSize: parseInt(getEnvVar("OTEL_SPAN_MAX_QUEUE_SIZE") ?? "512")
4395
+ }) : new SimpleSpanProcessor(spanExporter)));
4396
+ traceProvider.register();
4397
+ registerInstrumentations({
4398
+ instrumentations: config.instrumentations ?? [],
4399
+ tracerProvider: traceProvider
4400
+ });
4401
+ const logExporter = new OTLPLogExporter({
4402
+ url: `${config.url}/v1/logs`
4403
+ });
4404
+ const loggerProvider = new LoggerProvider({
4405
+ resource: commonResources,
4406
+ logRecordLimits: {
4407
+ attributeCountLimit: OTEL_LOG_ATTRIBUTE_COUNT_LIMIT,
4408
+ attributeValueLengthLimit: OTEL_LOG_ATTRIBUTE_VALUE_LENGTH_LIMIT
4409
+ }
4410
+ });
4411
+ loggerProvider.addLogRecordProcessor(new TaskContextLogProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new BatchLogRecordProcessor(logExporter, {
4412
+ maxExportBatchSize: parseInt(getEnvVar("OTEL_LOG_MAX_EXPORT_BATCH_SIZE") ?? "64"),
4413
+ scheduledDelayMillis: parseInt(getEnvVar("OTEL_LOG_SCHEDULED_DELAY_MILLIS") ?? "200"),
4414
+ exportTimeoutMillis: parseInt(getEnvVar("OTEL_LOG_EXPORT_TIMEOUT_MILLIS") ?? "30000"),
4415
+ maxQueueSize: parseInt(getEnvVar("OTEL_LOG_MAX_QUEUE_SIZE") ?? "512")
4416
+ }) : new SimpleLogRecordProcessor(logExporter)));
4417
+ this._logProvider = loggerProvider;
4418
+ this._spanExporter = spanExporter;
4419
+ this._traceProvider = traceProvider;
4420
+ logs.setGlobalLoggerProvider(loggerProvider);
4421
+ this.getLogger = loggerProvider.getLogger.bind(loggerProvider);
4422
+ this.getTracer = traceProvider.getTracer.bind(traceProvider);
4423
+ }
4424
+ async flush() {
4425
+ await this._traceProvider.forceFlush();
4426
+ await this._logProvider.forceFlush();
4427
+ }
4428
+ async shutdown() {
4429
+ await this._traceProvider.shutdown();
4430
+ await this._logProvider.shutdown();
4431
+ }
3092
4432
  };
4433
+ __name(_TracingSDK, "TracingSDK");
4434
+ var TracingSDK = _TracingSDK;
4435
+ function setLogLevel(level) {
4436
+ let diagLogLevel;
4437
+ switch (level) {
4438
+ case "none":
4439
+ diagLogLevel = DiagLogLevel.NONE;
4440
+ break;
4441
+ case "error":
4442
+ diagLogLevel = DiagLogLevel.ERROR;
4443
+ break;
4444
+ case "warn":
4445
+ diagLogLevel = DiagLogLevel.WARN;
4446
+ break;
4447
+ case "info":
4448
+ diagLogLevel = DiagLogLevel.INFO;
4449
+ break;
4450
+ case "debug":
4451
+ diagLogLevel = DiagLogLevel.DEBUG;
4452
+ break;
4453
+ case "verbose":
4454
+ diagLogLevel = DiagLogLevel.VERBOSE;
4455
+ break;
4456
+ case "all":
4457
+ diagLogLevel = DiagLogLevel.ALL;
4458
+ break;
4459
+ default:
4460
+ diagLogLevel = DiagLogLevel.NONE;
4461
+ }
4462
+ diag.setLogger(new DiagConsoleLogger(), diagLogLevel);
4463
+ }
4464
+ __name(setLogLevel, "setLogLevel");
3093
4465
 
3094
- // src/v3/utils/detectDependencyVersion.ts
3095
- function detectDependencyVersion(dependency) {
3096
- return dependencies[dependency];
4466
+ // src/v3/otel/index.ts
4467
+ function recordSpanException(span, error) {
4468
+ if (error instanceof Error) {
4469
+ span.recordException(error);
4470
+ } else if (typeof error === "string") {
4471
+ span.recordException(new Error(error));
4472
+ } else {
4473
+ span.recordException(new Error(JSON.stringify(error)));
4474
+ }
4475
+ span.setStatus({
4476
+ code: SpanStatusCode.ERROR
4477
+ });
3097
4478
  }
3098
- __name(detectDependencyVersion, "detectDependencyVersion");
4479
+ __name(recordSpanException, "recordSpanException");
3099
4480
 
3100
4481
  // src/v3/utils/ioSerialization.ts
3101
4482
  async function parsePacket(value) {
@@ -3365,6 +4746,374 @@ function safeJsonParse2(value) {
3365
4746
  }
3366
4747
  __name(safeJsonParse2, "safeJsonParse");
3367
4748
 
3368
- export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, Machine, MachineCpu, MachineMemory, 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, RetryOptions, 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, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, 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 };
4749
+ // src/v3/workers/taskExecutor.ts
4750
+ var _callRun, callRun_fn, _callTaskInit, callTaskInit_fn, _callTaskCleanup, callTaskCleanup_fn, _handleError, handleError_fn;
4751
+ var _TaskExecutor = class _TaskExecutor {
4752
+ constructor(task, options) {
4753
+ __privateAdd(this, _callRun);
4754
+ __privateAdd(this, _callTaskInit);
4755
+ __privateAdd(this, _callTaskCleanup);
4756
+ __privateAdd(this, _handleError);
4757
+ this.task = task;
4758
+ this._tracingSDK = options.tracingSDK;
4759
+ this._tracer = options.tracer;
4760
+ this._consoleInterceptor = options.consoleInterceptor;
4761
+ this._config = options.projectConfig;
4762
+ this._importedConfig = options.importedConfig;
4763
+ this._handleErrorFn = options.handleErrorFn;
4764
+ }
4765
+ async execute(execution, worker, traceContext) {
4766
+ const ctx = TaskRunContext.parse(execution);
4767
+ const attemptMessage = `Attempt ${execution.attempt.number}`;
4768
+ const originalPacket = {
4769
+ data: execution.run.payload,
4770
+ dataType: execution.run.payloadType
4771
+ };
4772
+ const result = await taskContextManager.runWith({
4773
+ ctx,
4774
+ worker
4775
+ }, async () => {
4776
+ this._tracingSDK.asyncResourceDetector.resolveWithAttributes({
4777
+ ...taskContextManager.attributes,
4778
+ [SemanticInternalAttributes.SDK_VERSION]: this.task.packageVersion,
4779
+ [SemanticInternalAttributes.SDK_LANGUAGE]: "typescript"
4780
+ });
4781
+ return await this._tracer.startActiveSpan(attemptMessage, async (span) => {
4782
+ return await this._consoleInterceptor.intercept(console, async () => {
4783
+ let parsedPayload;
4784
+ let initOutput;
4785
+ try {
4786
+ const payloadPacket = await conditionallyImportPacket(originalPacket, this._tracer);
4787
+ parsedPayload = await parsePacket(payloadPacket);
4788
+ initOutput = await __privateMethod(this, _callTaskInit, callTaskInit_fn).call(this, parsedPayload, ctx);
4789
+ const output = await __privateMethod(this, _callRun, callRun_fn).call(this, parsedPayload, ctx, initOutput);
4790
+ try {
4791
+ const stringifiedOutput = await stringifyIO(output);
4792
+ const finalOutput = await conditionallyExportPacket(stringifiedOutput, `${execution.attempt.id}/output`, this._tracer);
4793
+ const attributes = await createPacketAttributes(finalOutput, SemanticInternalAttributes.OUTPUT, SemanticInternalAttributes.OUTPUT_TYPE);
4794
+ if (attributes) {
4795
+ span.setAttributes(attributes);
4796
+ }
4797
+ return {
4798
+ ok: true,
4799
+ id: execution.run.id,
4800
+ output: finalOutput.data,
4801
+ outputType: finalOutput.dataType
4802
+ };
4803
+ } catch (stringifyError) {
4804
+ recordSpanException(span, stringifyError);
4805
+ return {
4806
+ ok: false,
4807
+ id: execution.run.id,
4808
+ error: {
4809
+ type: "INTERNAL_ERROR",
4810
+ code: TaskRunErrorCodes.TASK_OUTPUT_ERROR,
4811
+ message: stringifyError instanceof Error ? stringifyError.message : typeof stringifyError === "string" ? stringifyError : void 0
4812
+ }
4813
+ };
4814
+ }
4815
+ } catch (runError) {
4816
+ try {
4817
+ const handleErrorResult = await __privateMethod(this, _handleError, handleError_fn).call(this, execution, runError, parsedPayload, ctx);
4818
+ recordSpanException(span, handleErrorResult.error ?? runError);
4819
+ return {
4820
+ id: execution.run.id,
4821
+ ok: false,
4822
+ error: handleErrorResult.error ? parseError(handleErrorResult.error) : parseError(runError),
4823
+ retry: handleErrorResult.status === "retry" ? handleErrorResult.retry : void 0,
4824
+ skippedRetrying: handleErrorResult.status === "skipped"
4825
+ };
4826
+ } catch (handleErrorError) {
4827
+ recordSpanException(span, handleErrorError);
4828
+ return {
4829
+ ok: false,
4830
+ id: execution.run.id,
4831
+ error: {
4832
+ type: "INTERNAL_ERROR",
4833
+ code: TaskRunErrorCodes.HANDLE_ERROR_ERROR,
4834
+ message: handleErrorError instanceof Error ? handleErrorError.message : typeof handleErrorError === "string" ? handleErrorError : void 0
4835
+ }
4836
+ };
4837
+ }
4838
+ } finally {
4839
+ await __privateMethod(this, _callTaskCleanup, callTaskCleanup_fn).call(this, parsedPayload, ctx, initOutput);
4840
+ }
4841
+ });
4842
+ }, {
4843
+ kind: SpanKind.CONSUMER,
4844
+ attributes: {
4845
+ [SemanticInternalAttributes.STYLE_ICON]: "attempt",
4846
+ ...accessoryAttributes({
4847
+ items: [
4848
+ {
4849
+ text: ctx.task.filePath
4850
+ },
4851
+ {
4852
+ text: `${ctx.task.exportName}.run()`
4853
+ }
4854
+ ],
4855
+ style: "codepath"
4856
+ })
4857
+ }
4858
+ }, this._tracer.extractContext(traceContext));
4859
+ });
4860
+ return result;
4861
+ }
4862
+ };
4863
+ _callRun = new WeakSet();
4864
+ callRun_fn = /* @__PURE__ */ __name(async function(payload, ctx, init) {
4865
+ const runFn = this.task.fns.run;
4866
+ const middlewareFn = this.task.fns.middleware;
4867
+ if (!runFn) {
4868
+ throw new Error("Task does not have a run function");
4869
+ }
4870
+ if (!middlewareFn) {
4871
+ return runFn(payload, {
4872
+ ctx
4873
+ });
4874
+ }
4875
+ return middlewareFn(payload, {
4876
+ ctx,
4877
+ next: async () => runFn(payload, {
4878
+ ctx,
4879
+ init
4880
+ })
4881
+ });
4882
+ }, "#callRun");
4883
+ _callTaskInit = new WeakSet();
4884
+ callTaskInit_fn = /* @__PURE__ */ __name(async function(payload1, ctx1) {
4885
+ const initFn = this.task.fns.init;
4886
+ if (!initFn) {
4887
+ return {};
4888
+ }
4889
+ return this._tracer.startActiveSpan("init", async (span) => {
4890
+ return await initFn(payload1, {
4891
+ ctx: ctx1
4892
+ });
4893
+ });
4894
+ }, "#callTaskInit");
4895
+ _callTaskCleanup = new WeakSet();
4896
+ callTaskCleanup_fn = /* @__PURE__ */ __name(async function(payload2, ctx2, init1) {
4897
+ const cleanupFn = this.task.fns.cleanup;
4898
+ if (!cleanupFn) {
4899
+ return;
4900
+ }
4901
+ return this._tracer.startActiveSpan("cleanup", async (span) => {
4902
+ return await cleanupFn(payload2, {
4903
+ ctx: ctx2,
4904
+ init: init1
4905
+ });
4906
+ });
4907
+ }, "#callTaskCleanup");
4908
+ _handleError = new WeakSet();
4909
+ handleError_fn = /* @__PURE__ */ __name(async function(execution, error, payload3, ctx3) {
4910
+ const retriesConfig = this._importedConfig?.retries ?? this._config.retries;
4911
+ const retry = this.task.retry ?? retriesConfig?.default;
4912
+ if (!retry) {
4913
+ return {
4914
+ status: "noop"
4915
+ };
4916
+ }
4917
+ const delay = calculateNextRetryDelay(retry, execution.attempt.number);
4918
+ if (execution.environment.type === "DEVELOPMENT" && typeof retriesConfig?.enabledInDev === "boolean" && !retriesConfig.enabledInDev) {
4919
+ return {
4920
+ status: "skipped"
4921
+ };
4922
+ }
4923
+ return this._tracer.startActiveSpan("handleError()", async (span) => {
4924
+ const handleErrorResult = this.task.fns.handleError ? await this.task.fns.handleError(payload3, error, {
4925
+ ctx: ctx3,
4926
+ retry,
4927
+ retryDelayInMs: delay,
4928
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4929
+ }) : this._importedConfig ? await this._handleErrorFn?.(payload3, error, {
4930
+ ctx: ctx3,
4931
+ retry,
4932
+ retryDelayInMs: delay,
4933
+ retryAt: delay ? new Date(Date.now() + delay) : void 0
4934
+ }) : void 0;
4935
+ if (!handleErrorResult) {
4936
+ return typeof delay === "undefined" ? {
4937
+ status: "noop"
4938
+ } : {
4939
+ status: "retry",
4940
+ retry: {
4941
+ timestamp: Date.now() + delay,
4942
+ delay
4943
+ }
4944
+ };
4945
+ }
4946
+ if (handleErrorResult.skipRetrying) {
4947
+ return {
4948
+ status: "skipped",
4949
+ error: handleErrorResult.error
4950
+ };
4951
+ }
4952
+ if (typeof handleErrorResult.retryAt !== "undefined") {
4953
+ return {
4954
+ status: "retry",
4955
+ retry: {
4956
+ timestamp: handleErrorResult.retryAt.getTime(),
4957
+ delay: handleErrorResult.retryAt.getTime() - Date.now()
4958
+ },
4959
+ error: handleErrorResult.error
4960
+ };
4961
+ }
4962
+ if (typeof handleErrorResult.retryDelayInMs === "number") {
4963
+ return {
4964
+ status: "retry",
4965
+ retry: {
4966
+ timestamp: Date.now() + handleErrorResult.retryDelayInMs,
4967
+ delay: handleErrorResult.retryDelayInMs
4968
+ },
4969
+ error: handleErrorResult.error
4970
+ };
4971
+ }
4972
+ if (handleErrorResult.retry && typeof handleErrorResult.retry === "object") {
4973
+ const delay2 = calculateNextRetryDelay(handleErrorResult.retry, execution.attempt.number);
4974
+ return typeof delay2 === "undefined" ? {
4975
+ status: "noop",
4976
+ error: handleErrorResult.error
4977
+ } : {
4978
+ status: "retry",
4979
+ retry: {
4980
+ timestamp: Date.now() + delay2,
4981
+ delay: delay2
4982
+ },
4983
+ error: handleErrorResult.error
4984
+ };
4985
+ }
4986
+ return {
4987
+ status: "noop",
4988
+ error: handleErrorResult.error
4989
+ };
4990
+ }, {
4991
+ attributes: {
4992
+ [SemanticInternalAttributes.STYLE_ICON]: "exclamation-circle"
4993
+ }
4994
+ });
4995
+ }, "#handleError");
4996
+ __name(_TaskExecutor, "TaskExecutor");
4997
+ var TaskExecutor = _TaskExecutor;
4998
+
4999
+ // package.json
5000
+ var dependencies = {
5001
+ "@google-cloud/precise-date": "^4.0.0",
5002
+ "@opentelemetry/api": "^1.8.0",
5003
+ "@opentelemetry/api-logs": "^0.48.0",
5004
+ "@opentelemetry/exporter-logs-otlp-http": "^0.49.1",
5005
+ "@opentelemetry/exporter-trace-otlp-http": "^0.49.1",
5006
+ "@opentelemetry/instrumentation": "^0.49.1",
5007
+ "@opentelemetry/resources": "^1.22.0",
5008
+ "@opentelemetry/sdk-logs": "^0.49.1",
5009
+ "@opentelemetry/sdk-node": "^0.49.1",
5010
+ "@opentelemetry/sdk-trace-base": "^1.22.0",
5011
+ "@opentelemetry/sdk-trace-node": "^1.22.0",
5012
+ "@opentelemetry/semantic-conventions": "^1.22.0",
5013
+ "humanize-duration": "^3.27.3",
5014
+ "socket.io": "^4.7.4",
5015
+ "socket.io-client": "^4.7.4",
5016
+ superjson: "^2.2.1",
5017
+ ulidx: "^2.2.1",
5018
+ zod: "3.22.3",
5019
+ "zod-error": "1.5.0",
5020
+ "zod-validation-error": "^1.5.0"
5021
+ };
5022
+
5023
+ // src/v3/utils/detectDependencyVersion.ts
5024
+ function detectDependencyVersion(dependency) {
5025
+ return dependencies[dependency];
5026
+ }
5027
+ __name(detectDependencyVersion, "detectDependencyVersion");
5028
+
5029
+ // src/v3/task-catalog/standardTaskCatalog.ts
5030
+ var _StandardTaskCatalog = class _StandardTaskCatalog {
5031
+ constructor() {
5032
+ __publicField(this, "_taskMetadata", /* @__PURE__ */ new Map());
5033
+ __publicField(this, "_taskFunctions", /* @__PURE__ */ new Map());
5034
+ __publicField(this, "_taskFileMetadata", /* @__PURE__ */ new Map());
5035
+ }
5036
+ registerTaskMetadata(task) {
5037
+ const { fns, ...metadata } = task;
5038
+ this._taskMetadata.set(task.id, metadata);
5039
+ this._taskFunctions.set(task.id, fns);
5040
+ }
5041
+ updateTaskMetadata(id, updates) {
5042
+ const existingMetadata = this._taskMetadata.get(id);
5043
+ if (existingMetadata) {
5044
+ this._taskMetadata.set(id, {
5045
+ ...existingMetadata,
5046
+ ...updates
5047
+ });
5048
+ }
5049
+ if (updates.fns) {
5050
+ const existingFunctions = this._taskFunctions.get(id);
5051
+ if (existingFunctions) {
5052
+ this._taskFunctions.set(id, {
5053
+ ...existingFunctions,
5054
+ ...updates.fns
5055
+ });
5056
+ }
5057
+ }
5058
+ }
5059
+ registerTaskFileMetadata(id, metadata) {
5060
+ this._taskFileMetadata.set(id, metadata);
5061
+ }
5062
+ // Return all the tasks, without the functions
5063
+ getAllTaskMetadata() {
5064
+ const result = [];
5065
+ for (const [id, metadata] of this._taskMetadata) {
5066
+ const fileMetadata = this._taskFileMetadata.get(id);
5067
+ if (!fileMetadata) {
5068
+ continue;
5069
+ }
5070
+ result.push({
5071
+ ...metadata,
5072
+ ...fileMetadata
5073
+ });
5074
+ }
5075
+ return result;
5076
+ }
5077
+ getTaskMetadata(id) {
5078
+ const metadata = this._taskMetadata.get(id);
5079
+ const fileMetadata = this._taskFileMetadata.get(id);
5080
+ if (!metadata || !fileMetadata) {
5081
+ return void 0;
5082
+ }
5083
+ return {
5084
+ ...metadata,
5085
+ ...fileMetadata
5086
+ };
5087
+ }
5088
+ getTask(id) {
5089
+ const metadata = this._taskMetadata.get(id);
5090
+ const fileMetadata = this._taskFileMetadata.get(id);
5091
+ const fns = this._taskFunctions.get(id);
5092
+ if (!metadata || !fns || !fileMetadata) {
5093
+ return void 0;
5094
+ }
5095
+ return {
5096
+ ...metadata,
5097
+ ...fileMetadata,
5098
+ fns
5099
+ };
5100
+ }
5101
+ disable() {
5102
+ }
5103
+ };
5104
+ __name(_StandardTaskCatalog, "StandardTaskCatalog");
5105
+ var StandardTaskCatalog = _StandardTaskCatalog;
5106
+
5107
+ // src/v3/index.ts
5108
+ function parseTriggerTaskRequestBody(body) {
5109
+ return TriggerTaskRequestBody.safeParse(body);
5110
+ }
5111
+ __name(parseTriggerTaskRequestBody, "parseTriggerTaskRequestBody");
5112
+ function parseBatchTriggerTaskRequestBody(body) {
5113
+ return BatchTriggerTaskRequestBody.safeParse(body);
5114
+ }
5115
+ __name(parseBatchTriggerTaskRequestBody, "parseBatchTriggerTaskRequestBody");
5116
+
5117
+ export { APIConnectionError, APIError, ApiClient, ApiClientManager, AuthenticationError, BackgroundWorkerClientMessages, BackgroundWorkerMetadata, BackgroundWorkerProperties, BackgroundWorkerServerMessages, BadRequestError, BatchTaskRunExecutionResult, BatchTriggerTaskRequestBody, BatchTriggerTaskResponse, CanceledRunResponse, CancellationSpanEvent, ClientToSharedQueueMessages, Config, ConflictError, ConsoleInterceptor, CoordinatorToPlatformMessages, CoordinatorToProdWorkerMessages, CreateAuthorizationCodeResponseSchema, CreateBackgroundWorkerRequestBody, CreateBackgroundWorkerResponse, CreateScheduleOptions, CreateUploadPayloadUrlResponseBody, DeletedScheduleObject, DeploymentErrorData, DevRuntimeManager, PreciseWallClock as DurableClock, EnvironmentType, EventFilter, ExceptionEventProperties, ExceptionSpanEvent, ExternalBuildData, FetchRetryBackoffStrategy, FetchRetryByStatusOptions, FetchRetryHeadersStrategy, FetchRetryOptions, FetchRetryStrategy, FetchTimeoutOptions, FixedWindowRateLimit, GetBatchResponseBody, GetDeploymentResponseBody, GetEnvironmentVariablesResponseBody, GetPersonalAccessTokenRequestSchema, GetPersonalAccessTokenResponseSchema, GetProjectEnvResponse, GetProjectResponseBody, GetProjectsResponseBody, ImageDetailsMetadata, InitializeDeploymentRequestBody, InitializeDeploymentResponseBody, InternalServerError, ListScheduleOptions, ListSchedulesResult, LogLevel, Machine, MachineCpu, MachineMemory, 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, OtelTaskLogger, OtherSpanEvent, PRIMARY_VARIANT, PermissionDeniedError, PlatformToCoordinatorMessages, PlatformToProviderMessages, PostStartCauses, PreStopCauses, ProdChildToWorkerMessages, ProdRuntimeManager, ProdTaskRunExecution, ProdTaskRunExecutionPayload, ProdWorkerSocketData, ProdWorkerToChildMessages, ProdWorkerToCoordinatorMessages, ProviderToPlatformMessages, QueueOptions, RateLimitError, RateLimitOptions, ReplayRunResponse, RetryOptions, ScheduleObject, ScheduledTaskPayload, SemanticInternalAttributes, SharedQueueToClientMessages, SimpleStructuredLogger, SlidingWindowRateLimit, SpanEvent, SpanEvents, SpanMessagingEvent, StandardTaskCatalog, StartDeploymentIndexingRequestBody, StartDeploymentIndexingResponseBody, TaskContextSpanProcessor, TaskEventStyle, TaskExecutor, TaskFileMetadata, TaskMetadata, TaskMetadataFailedToParseData, TaskMetadataWithFilePath, TaskResource, TaskRun, TaskRunBuiltInError, TaskRunContext, TaskRunCustomErrorObject, TaskRunError, TaskRunErrorCodes, TaskRunExecution, TaskRunExecutionAttempt, TaskRunExecutionBatch, TaskRunExecutionEnvironment, TaskRunExecutionOrganization, TaskRunExecutionPayload, TaskRunExecutionProject, TaskRunExecutionQueue, TaskRunExecutionResult, TaskRunExecutionRetry, TaskRunExecutionTask, TaskRunFailedExecutionResult, TaskRunInternalError, TaskRunStringError, TaskRunSuccessfulExecutionResult, TracingSDK, TriggerTaskRequestBody, TriggerTaskResponse, TriggerTracer, UncaughtExceptionMessage, UnprocessableEntityError, UpdateScheduleOptions, WaitReason, WhoAmIResponseSchema, ZodIpcConnection, ZodMessageHandler, ZodMessageSchema, ZodMessageSender, ZodNamespace, ZodSchemaParsedError, ZodSocketConnection, ZodSocketMessageHandler, ZodSocketMessageSender, accessoryAttributes, apiClientManager, calculateNextRetryDelay, calculateResetAt2 as calculateResetAt, childToWorkerMessages, clientWebsocketMessages, clock, conditionallyExportPacket, conditionallyImportPacket, correctErrorStackTrace, createErrorTaskError, createPacketAttributes, createPacketAttributesAsJson, defaultFetchRetryOptions, defaultRetryOptions, detectDependencyVersion, eventFilterMatches, flattenAttributes, formatDuration, formatDurationInDays, formatDurationMilliseconds, formatDurationNanoseconds, getEnvVar, groupTaskMetadataIssuesByTask, iconStringForSeverity, imposeAttributeLimits, isCancellationSpanEvent, isExceptionSpanEvent, logLevels, logger, millisecondsToNanoseconds, nanosecondsToMilliseconds, omit, packetRequiresOffloading, parseBatchTriggerTaskRequestBody, parseError, parsePacket, parseTriggerTaskRequestBody, prettyPrintPacket, primitiveValueOrflattenedAttributes, recordSpanException, runtime, serverWebsocketMessages, stringPatternMatchers, stringifyIO, taskCatalog, taskContextManager, unflattenAttributes, workerToChildMessages };
3369
5118
  //# sourceMappingURL=out.js.map
3370
5119
  //# sourceMappingURL=index.mjs.map