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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{catalog-dRKTgwQ7.d.ts → catalog-Tdea4K0I.d.mts} +43 -3
  2. package/dist/{catalog-XTlJQaMn.d.mts → catalog-yeAHwmSe.d.ts} +43 -3
  3. package/dist/{manager-JkbddlcO.d.mts → manager-S98VaLUy.d.mts} +244 -1
  4. package/dist/{manager-JkbddlcO.d.ts → manager-S98VaLUy.d.ts} +244 -1
  5. package/dist/{messages-9lty-Du5.d.mts → messages-BD0yXLtn.d.mts} +2370 -141
  6. package/dist/{messages-9lty-Du5.d.ts → messages-BD0yXLtn.d.ts} +2370 -141
  7. package/dist/{schemas-r4ZP9S-F.d.mts → schemas-XNxZYXOy.d.mts} +199 -33
  8. package/dist/{schemas-r4ZP9S-F.d.ts → schemas-XNxZYXOy.d.ts} +199 -33
  9. package/dist/v3/dev/index.d.mts +1 -1
  10. package/dist/v3/dev/index.d.ts +1 -1
  11. package/dist/v3/index.d.mts +117 -52
  12. package/dist/v3/index.d.ts +117 -52
  13. package/dist/v3/index.js +204 -58
  14. package/dist/v3/index.js.map +1 -1
  15. package/dist/v3/index.mjs +199 -58
  16. package/dist/v3/index.mjs.map +1 -1
  17. package/dist/v3/otel/index.js +15 -5
  18. package/dist/v3/otel/index.js.map +1 -1
  19. package/dist/v3/otel/index.mjs +15 -5
  20. package/dist/v3/otel/index.mjs.map +1 -1
  21. package/dist/v3/prod/index.d.mts +2 -2
  22. package/dist/v3/prod/index.d.ts +2 -2
  23. package/dist/v3/prod/index.js.map +1 -1
  24. package/dist/v3/prod/index.mjs.map +1 -1
  25. package/dist/v3/workers/index.d.mts +54 -8
  26. package/dist/v3/workers/index.d.ts +54 -8
  27. package/dist/v3/workers/index.js +404 -43
  28. package/dist/v3/workers/index.js.map +1 -1
  29. package/dist/v3/workers/index.mjs +402 -44
  30. package/dist/v3/workers/index.mjs.map +1 -1
  31. package/dist/v3/zodIpc.js.map +1 -1
  32. package/dist/v3/zodIpc.mjs.map +1 -1
  33. package/dist/v3/zodMessageHandler.d.mts +1 -1
  34. package/dist/v3/zodMessageHandler.d.ts +1 -1
  35. package/dist/v3/zodfetch.d.mts +1 -1
  36. package/dist/v3/zodfetch.d.ts +1 -1
  37. package/package.json +1 -1
@@ -15,6 +15,7 @@ var formDataEncoder = require('form-data-encoder');
15
15
  var stream = require('stream');
16
16
  var preciseDate = require('@google-cloud/precise-date');
17
17
  var util = require('util');
18
+ var promises = require('timers/promises');
18
19
 
19
20
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
21
 
@@ -110,6 +111,10 @@ var SemanticInternalAttributes = {
110
111
  TASK_EXPORT_NAME: "ctx.task.exportName",
111
112
  QUEUE_NAME: "ctx.queue.name",
112
113
  QUEUE_ID: "ctx.queue.id",
114
+ MACHINE_PRESET_NAME: "ctx.machine.name",
115
+ MACHINE_PRESET_CPU: "ctx.machine.cpu",
116
+ MACHINE_PRESET_MEMORY: "ctx.machine.memory",
117
+ MACHINE_PRESET_CENTS_PER_MS: "ctx.machine.centsPerMs",
113
118
  SPAN_PARTIAL: "$span.partial",
114
119
  SPAN_ID: "$span.span_id",
115
120
  OUTPUT: "$output",
@@ -133,7 +138,9 @@ var SemanticInternalAttributes = {
133
138
  RETRY_DELAY: "retry.delay",
134
139
  RETRY_COUNT: "retry.count",
135
140
  LINK_TITLE: "$link.title",
136
- IDEMPOTENCY_KEY: "ctx.run.idempotencyKey"
141
+ IDEMPOTENCY_KEY: "ctx.run.idempotencyKey",
142
+ USAGE_DURATION_MS: "$usage.durationMs",
143
+ USAGE_COST_IN_CENTS: "$usage.costInCents"
137
144
  };
138
145
 
139
146
  // src/v3/utils/flattenAttributes.ts
@@ -279,7 +286,11 @@ var _TaskContextAPI = class _TaskContextAPI {
279
286
  [SemanticInternalAttributes.ORGANIZATION_SLUG]: this.ctx.organization.slug,
280
287
  [SemanticInternalAttributes.ORGANIZATION_NAME]: this.ctx.organization.name,
281
288
  [SemanticInternalAttributes.BATCH_ID]: this.ctx.batch?.id,
282
- [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey
289
+ [SemanticInternalAttributes.IDEMPOTENCY_KEY]: this.ctx.run.idempotencyKey,
290
+ [SemanticInternalAttributes.MACHINE_PRESET_NAME]: this.ctx.machine?.name,
291
+ [SemanticInternalAttributes.MACHINE_PRESET_CPU]: this.ctx.machine?.cpu,
292
+ [SemanticInternalAttributes.MACHINE_PRESET_MEMORY]: this.ctx.machine?.memory,
293
+ [SemanticInternalAttributes.MACHINE_PRESET_CENTS_PER_MS]: this.ctx.machine?.centsPerMs
283
294
  };
284
295
  }
285
296
  return {};
@@ -361,7 +372,7 @@ function getEnvVar(name) {
361
372
  __name(getEnvVar, "getEnvVar");
362
373
 
363
374
  // package.json
364
- var version = "3.0.0-beta.37";
375
+ var version = "3.0.0-beta.38";
365
376
 
366
377
  // src/v3/otel/tracingSDK.ts
367
378
  var _a;
@@ -404,7 +415,7 @@ var _TracingSDK = class _TracingSDK {
404
415
  [SemanticInternalAttributes.CLI_VERSION]: version
405
416
  })).merge(config.resource ?? new resources.Resource({})).merge(new resources.Resource(envResourceAttributes));
406
417
  const traceProvider = new sdkTraceNode.NodeTracerProvider({
407
- forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 500,
418
+ forceFlushTimeoutMillis: config.forceFlushTimeoutMillis,
408
419
  resource: commonResources,
409
420
  spanLimits: {
410
421
  attributeCountLimit: OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,
@@ -417,7 +428,7 @@ var _TracingSDK = class _TracingSDK {
417
428
  });
418
429
  const spanExporter = new exporterTraceOtlpHttp.OTLPTraceExporter({
419
430
  url: `${config.url}/v1/traces`,
420
- timeoutMillis: config.forceFlushTimeoutMillis ?? 1e3
431
+ timeoutMillis: config.forceFlushTimeoutMillis
421
432
  });
422
433
  traceProvider.addSpanProcessor(new TaskContextSpanProcessor(getEnvVar("OTEL_BATCH_PROCESSING_ENABLED") === "1" ? new sdkTraceNode.BatchSpanProcessor(spanExporter, {
423
434
  maxExportBatchSize: parseInt(getEnvVar("OTEL_SPAN_MAX_EXPORT_BATCH_SIZE") ?? "64"),
@@ -509,6 +520,41 @@ function recordSpanException(span, error) {
509
520
  });
510
521
  }
511
522
  __name(recordSpanException, "recordSpanException");
523
+ var MachineCpu = zod.z.union([
524
+ zod.z.literal(0.25),
525
+ zod.z.literal(0.5),
526
+ zod.z.literal(1),
527
+ zod.z.literal(2),
528
+ zod.z.literal(4)
529
+ ]);
530
+ var MachineMemory = zod.z.union([
531
+ zod.z.literal(0.25),
532
+ zod.z.literal(0.5),
533
+ zod.z.literal(1),
534
+ zod.z.literal(2),
535
+ zod.z.literal(4),
536
+ zod.z.literal(8)
537
+ ]);
538
+ var MachinePresetName = zod.z.enum([
539
+ "micro",
540
+ "small-1x",
541
+ "small-2x",
542
+ "medium-1x",
543
+ "medium-2x",
544
+ "large-1x",
545
+ "large-2x"
546
+ ]);
547
+ var MachineConfig = zod.z.object({
548
+ cpu: MachineCpu.optional(),
549
+ memory: MachineMemory.optional(),
550
+ preset: MachinePresetName.optional()
551
+ });
552
+ var MachinePreset = zod.z.object({
553
+ name: MachinePresetName,
554
+ cpu: zod.z.number(),
555
+ memory: zod.z.number(),
556
+ centsPerMs: zod.z.number()
557
+ });
512
558
  var TaskRunBuiltInError = zod.z.object({
513
559
  type: zod.z.literal("BUILT_IN_ERROR"),
514
560
  name: zod.z.string(),
@@ -570,7 +616,11 @@ var TaskRun = zod.z.object({
570
616
  tags: zod.z.array(zod.z.string()),
571
617
  isTest: zod.z.boolean().default(false),
572
618
  createdAt: zod.z.coerce.date(),
573
- idempotencyKey: zod.z.string().optional()
619
+ startedAt: zod.z.coerce.date().default(() => /* @__PURE__ */ new Date()),
620
+ idempotencyKey: zod.z.string().optional(),
621
+ durationMs: zod.z.number().default(0),
622
+ costInCents: zod.z.number().default(0),
623
+ baseCostInCents: zod.z.number().default(0)
574
624
  });
575
625
  var TaskRunExecutionTask = zod.z.object({
576
626
  id: zod.z.string(),
@@ -621,7 +671,8 @@ var TaskRunExecution = zod.z.object({
621
671
  environment: TaskRunExecutionEnvironment,
622
672
  organization: TaskRunExecutionOrganization,
623
673
  project: TaskRunExecutionProject,
624
- batch: TaskRunExecutionBatch.optional()
674
+ batch: TaskRunExecutionBatch.optional(),
675
+ machine: MachinePreset.optional()
625
676
  });
626
677
  var TaskRunContext = zod.z.object({
627
678
  task: TaskRunExecutionTask,
@@ -637,25 +688,31 @@ var TaskRunContext = zod.z.object({
637
688
  environment: TaskRunExecutionEnvironment,
638
689
  organization: TaskRunExecutionOrganization,
639
690
  project: TaskRunExecutionProject,
640
- batch: TaskRunExecutionBatch.optional()
691
+ batch: TaskRunExecutionBatch.optional(),
692
+ machine: MachinePreset.optional()
641
693
  });
642
694
  var TaskRunExecutionRetry = zod.z.object({
643
695
  timestamp: zod.z.number(),
644
696
  delay: zod.z.number(),
645
697
  error: zod.z.unknown().optional()
646
698
  });
699
+ var TaskRunExecutionUsage = zod.z.object({
700
+ durationMs: zod.z.number()
701
+ });
647
702
  var TaskRunFailedExecutionResult = zod.z.object({
648
703
  ok: zod.z.literal(false),
649
704
  id: zod.z.string(),
650
705
  error: TaskRunError,
651
706
  retry: TaskRunExecutionRetry.optional(),
652
- skippedRetrying: zod.z.boolean().optional()
707
+ skippedRetrying: zod.z.boolean().optional(),
708
+ usage: TaskRunExecutionUsage.optional()
653
709
  });
654
710
  var TaskRunSuccessfulExecutionResult = zod.z.object({
655
711
  ok: zod.z.literal(true),
656
712
  id: zod.z.string(),
657
713
  output: zod.z.string().optional(),
658
- outputType: zod.z.string()
714
+ outputType: zod.z.string(),
715
+ usage: TaskRunExecutionUsage.optional()
659
716
  });
660
717
  var TaskRunExecutionResult = zod.z.discriminatedUnion("ok", [
661
718
  TaskRunSuccessfulExecutionResult,
@@ -673,26 +730,6 @@ zod.z.enum([
673
730
  "DEVELOPMENT",
674
731
  "PREVIEW"
675
732
  ]);
676
- var MachineCpu = zod.z.union([
677
- zod.z.literal(0.25),
678
- zod.z.literal(0.5),
679
- zod.z.literal(1),
680
- zod.z.literal(2),
681
- zod.z.literal(4)
682
- ]).default(0.5);
683
- var MachineMemory = zod.z.union([
684
- zod.z.literal(0.25),
685
- zod.z.literal(0.5),
686
- zod.z.literal(1),
687
- zod.z.literal(2),
688
- zod.z.literal(4),
689
- zod.z.literal(8)
690
- ]).default(1);
691
- var Machine = zod.z.object({
692
- version: zod.z.literal("v1").default("v1"),
693
- cpu: MachineCpu,
694
- memory: MachineMemory
695
- });
696
733
  zod.z.object({
697
734
  execution: TaskRunExecution,
698
735
  traceContext: zod.z.record(zod.z.unknown()),
@@ -703,7 +740,8 @@ var ProdTaskRunExecution = TaskRunExecution.extend({
703
740
  id: zod.z.string(),
704
741
  contentHash: zod.z.string(),
705
742
  version: zod.z.string()
706
- })
743
+ }),
744
+ machine: MachinePreset
707
745
  });
708
746
  zod.z.object({
709
747
  execution: ProdTaskRunExecution,
@@ -807,7 +845,7 @@ zod.z.object({
807
845
  packageVersion: zod.z.string(),
808
846
  queue: QueueOptions.optional(),
809
847
  retry: RetryOptions.optional(),
810
- machine: Machine.partial().optional(),
848
+ machine: MachineConfig.optional(),
811
849
  triggerSource: zod.z.string().optional()
812
850
  });
813
851
  zod.z.object({
@@ -819,7 +857,7 @@ zod.z.object({
819
857
  packageVersion: zod.z.string(),
820
858
  queue: QueueOptions.optional(),
821
859
  retry: RetryOptions.optional(),
822
- machine: Machine.partial().optional(),
860
+ machine: MachineConfig.optional(),
823
861
  triggerSource: zod.z.string().optional(),
824
862
  filePath: zod.z.string(),
825
863
  exportName: zod.z.string()
@@ -879,7 +917,7 @@ var TaskResource = zod.z.object({
879
917
  exportName: zod.z.string(),
880
918
  queue: QueueOptions.optional(),
881
919
  retry: RetryOptions.optional(),
882
- machine: Machine.partial().optional(),
920
+ machine: MachineConfig.optional(),
883
921
  triggerSource: zod.z.string().optional()
884
922
  });
885
923
  var BackgroundWorkerMetadata = zod.z.object({
@@ -1042,19 +1080,30 @@ zod.z.object({
1042
1080
  You can use this to remove the schedule, update it, etc */
1043
1081
  scheduleId: zod.z.string(),
1044
1082
  /** When the task was scheduled to run.
1045
- * Note this will be slightly different from `new Date()` because it takes a few ms to run the task. */
1083
+ * Note this will be slightly different from `new Date()` because it takes a few ms to run the task.
1084
+ *
1085
+ * This date is UTC. To output it as a string with a timezone you would do this:
1086
+ * ```ts
1087
+ * const formatted = payload.timestamp.toLocaleString("en-US", {
1088
+ timeZone: payload.timezone,
1089
+ });
1090
+ ``` */
1046
1091
  timestamp: zod.z.date(),
1047
1092
  /** When the task was last run (it has been).
1048
- This can be undefined if it's never been run */
1093
+ This can be undefined if it's never been run. This date is UTC. */
1049
1094
  lastTimestamp: zod.z.date().optional(),
1050
1095
  /** You can optionally provide an external id when creating the schedule.
1051
1096
  Usually you would use a userId or some other unique identifier.
1052
1097
  This defaults to undefined if you didn't provide one. */
1053
1098
  externalId: zod.z.string().optional(),
1099
+ /** The IANA timezone the schedule is set to. The default is UTC.
1100
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1101
+ */
1102
+ timezone: zod.z.string(),
1054
1103
  /** The next 5 dates this task is scheduled to run */
1055
1104
  upcoming: zod.z.array(zod.z.date())
1056
1105
  });
1057
- zod.z.object({
1106
+ var CreateScheduleOptions = zod.z.object({
1058
1107
  /** The id of the task you want to attach to. */
1059
1108
  task: zod.z.string(),
1060
1109
  /** The schedule in CRON format.
@@ -1074,15 +1123,29 @@ zod.z.object({
1074
1123
 
1075
1124
  */
1076
1125
  cron: zod.z.string(),
1077
- /** (Optional) You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1126
+ /** You can only create one schedule with this key. If you use it twice, the second call will update the schedule.
1078
1127
  *
1079
- * This is useful if you don't want to create duplicate schedules for a user. */
1080
- deduplicationKey: zod.z.string().optional(),
1128
+ * This is required to prevent you from creating duplicate schedules. */
1129
+ deduplicationKey: zod.z.string(),
1081
1130
  /** Optionally, you can specify your own IDs (like a user ID) and then use it inside the run function of your task.
1082
1131
  *
1083
1132
  * This allows you to have per-user CRON tasks.
1084
1133
  */
1085
- externalId: zod.z.string().optional()
1134
+ externalId: zod.z.string().optional(),
1135
+ /** Optionally, you can specify a timezone in the IANA format. If unset it will use UTC.
1136
+ * If specified then the CRON will be evaluated in that timezone and will respect daylight savings.
1137
+ *
1138
+ * If you set the CRON to `0 0 * * *` and the timezone to `America/New_York` then the task will run at midnight in New York time, no matter whether it's daylight savings or not.
1139
+ *
1140
+ * You can see the full list of supported timezones here: https://cloud.trigger.dev/timezones
1141
+ *
1142
+ * @example "America/New_York", "Europe/London", "Asia/Tokyo", "Africa/Cairo"
1143
+ *
1144
+ */
1145
+ timezone: zod.z.string().optional()
1146
+ });
1147
+ CreateScheduleOptions.omit({
1148
+ deduplicationKey: true
1086
1149
  });
1087
1150
  var ScheduleGenerator = zod.z.object({
1088
1151
  type: zod.z.literal("CRON"),
@@ -1096,6 +1159,7 @@ var ScheduleObject = zod.z.object({
1096
1159
  deduplicationKey: zod.z.string().nullish(),
1097
1160
  externalId: zod.z.string().nullish(),
1098
1161
  generator: ScheduleGenerator,
1162
+ timezone: zod.z.string(),
1099
1163
  nextRun: zod.z.coerce.date().nullish(),
1100
1164
  environments: zod.z.array(zod.z.object({
1101
1165
  id: zod.z.string(),
@@ -1118,6 +1182,9 @@ zod.z.object({
1118
1182
  page: zod.z.number().optional(),
1119
1183
  perPage: zod.z.number().optional()
1120
1184
  });
1185
+ zod.z.object({
1186
+ timezones: zod.z.array(zod.z.string())
1187
+ });
1121
1188
  var RunStatus = zod.z.enum([
1122
1189
  /// Task hasn't been deployed yet but is waiting to be executed
1123
1190
  "WAITING_FOR_DEPLOY",
@@ -2472,7 +2539,7 @@ var _TaskExecutor = class _TaskExecutor {
2472
2539
  this._importedConfig = options.importedConfig;
2473
2540
  this._handleErrorFn = options.handleErrorFn;
2474
2541
  }
2475
- async execute(execution, worker, traceContext) {
2542
+ async execute(execution, worker, traceContext, usage2) {
2476
2543
  const ctx = TaskRunContext.parse(execution);
2477
2544
  const attemptMessage = `Attempt ${execution.attempt.number}`;
2478
2545
  const originalPacket = {
@@ -2573,7 +2640,9 @@ var _TaskExecutor = class _TaskExecutor {
2573
2640
  })
2574
2641
  }
2575
2642
  }, this._tracer.extractContext(traceContext));
2576
- return result;
2643
+ return {
2644
+ result
2645
+ };
2577
2646
  }
2578
2647
  };
2579
2648
  _callRun = new WeakSet();
@@ -3229,9 +3298,300 @@ var _StandardTaskCatalog = class _StandardTaskCatalog {
3229
3298
  __name(_StandardTaskCatalog, "StandardTaskCatalog");
3230
3299
  var StandardTaskCatalog = _StandardTaskCatalog;
3231
3300
 
3301
+ // src/v3/usage/noopUsageManager.ts
3302
+ var _NoopUsageManager = class _NoopUsageManager {
3303
+ disable() {
3304
+ }
3305
+ start() {
3306
+ return {
3307
+ sample: () => ({
3308
+ cpuTime: 0,
3309
+ wallTime: 0
3310
+ })
3311
+ };
3312
+ }
3313
+ stop(measurement) {
3314
+ return measurement.sample();
3315
+ }
3316
+ pauseAsync(cb) {
3317
+ return cb();
3318
+ }
3319
+ sample() {
3320
+ return void 0;
3321
+ }
3322
+ };
3323
+ __name(_NoopUsageManager, "NoopUsageManager");
3324
+ var NoopUsageManager = _NoopUsageManager;
3325
+
3326
+ // src/v3/usage/api.ts
3327
+ var API_NAME4 = "usage";
3328
+ var NOOP_USAGE_MANAGER = new NoopUsageManager();
3329
+ var _getUsageManager, getUsageManager_fn;
3330
+ var _UsageAPI = class _UsageAPI {
3331
+ constructor() {
3332
+ __privateAdd(this, _getUsageManager);
3333
+ }
3334
+ static getInstance() {
3335
+ if (!this._instance) {
3336
+ this._instance = new _UsageAPI();
3337
+ }
3338
+ return this._instance;
3339
+ }
3340
+ setGlobalUsageManager(manager) {
3341
+ return registerGlobal(API_NAME4, manager);
3342
+ }
3343
+ disable() {
3344
+ __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).disable();
3345
+ unregisterGlobal(API_NAME4);
3346
+ }
3347
+ start() {
3348
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).start();
3349
+ }
3350
+ stop(measurement) {
3351
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).stop(measurement);
3352
+ }
3353
+ pauseAsync(cb) {
3354
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).pauseAsync(cb);
3355
+ }
3356
+ sample() {
3357
+ return __privateMethod(this, _getUsageManager, getUsageManager_fn).call(this).sample();
3358
+ }
3359
+ };
3360
+ _getUsageManager = new WeakSet();
3361
+ getUsageManager_fn = /* @__PURE__ */ __name(function() {
3362
+ return getGlobal(API_NAME4) ?? NOOP_USAGE_MANAGER;
3363
+ }, "#getUsageManager");
3364
+ __name(_UsageAPI, "UsageAPI");
3365
+ var UsageAPI = _UsageAPI;
3366
+
3367
+ // src/v3/usage-api.ts
3368
+ var usage = UsageAPI.getInstance();
3369
+
3370
+ // src/v3/clock/clock.ts
3371
+ function calculateDurationInMs(start, end) {
3372
+ const [startSeconds, startNanoseconds] = start;
3373
+ const [endSeconds, endNanoseconds] = end;
3374
+ const seconds = endSeconds - startSeconds;
3375
+ const nanoseconds = endNanoseconds - startNanoseconds;
3376
+ return Math.floor(seconds * 1e3 + nanoseconds / 1e6);
3377
+ }
3378
+ __name(calculateDurationInMs, "calculateDurationInMs");
3379
+
3380
+ // src/v3/usage/devUsageManager.ts
3381
+ var _a2;
3382
+ var DevUsageMeasurement = (_a2 = class {
3383
+ constructor(id, startedAt = clock.preciseNow()) {
3384
+ this.id = id;
3385
+ this.startedAt = startedAt;
3386
+ this._pauses = /* @__PURE__ */ new Map();
3387
+ }
3388
+ stop() {
3389
+ this._endedAt = clock.preciseNow();
3390
+ }
3391
+ sample() {
3392
+ const endedAt = this._endedAt ?? clock.preciseNow();
3393
+ const wallTime = this.startedAt ? calculateDurationInMs(this.startedAt, endedAt) : 0;
3394
+ if (wallTime === 0) {
3395
+ return {
3396
+ cpuTime: 0,
3397
+ wallTime: 0
3398
+ };
3399
+ }
3400
+ const totalPauses = Array.from(this._pauses.values()).reduce((total, pause) => {
3401
+ return total + calculateDurationInMs(pause.start, pause.end ?? endedAt);
3402
+ }, 0);
3403
+ const cpuTime = wallTime - totalPauses;
3404
+ return {
3405
+ wallTime,
3406
+ cpuTime
3407
+ };
3408
+ }
3409
+ registerPause(pauseId, start, end) {
3410
+ this._pauses.set(pauseId, {
3411
+ start,
3412
+ end
3413
+ });
3414
+ }
3415
+ }, __name(_a2, "DevUsageMeasurement"), _a2);
3416
+ var _DevUsageManager = class _DevUsageManager {
3417
+ constructor() {
3418
+ __publicField(this, "_currentMeasurements", /* @__PURE__ */ new Map());
3419
+ __publicField(this, "_pauses", /* @__PURE__ */ new Map());
3420
+ }
3421
+ disable() {
3422
+ }
3423
+ sample() {
3424
+ return this._firstMeasurement?.sample();
3425
+ }
3426
+ start() {
3427
+ const id = generateRandomString();
3428
+ const measurement = new DevUsageMeasurement(id);
3429
+ if (!this._firstMeasurement) {
3430
+ this._firstMeasurement = measurement;
3431
+ }
3432
+ this._currentMeasurements.set(id, measurement);
3433
+ return measurement;
3434
+ }
3435
+ stop(measurement) {
3436
+ measurement.stop();
3437
+ const sample = measurement.sample();
3438
+ this._currentMeasurements.delete(measurement.id);
3439
+ return sample;
3440
+ }
3441
+ async pauseAsync(cb) {
3442
+ const pauseId = generateRandomString();
3443
+ const pauseStart = clock.preciseNow();
3444
+ try {
3445
+ this._pauses.set(pauseId, {
3446
+ start: pauseStart
3447
+ });
3448
+ for (const measurement of this._currentMeasurements.values()) {
3449
+ measurement.registerPause(pauseId, pauseStart);
3450
+ }
3451
+ return await cb();
3452
+ } finally {
3453
+ const pauseEnd = clock.preciseNow();
3454
+ this._pauses.set(pauseId, {
3455
+ start: pauseStart,
3456
+ end: pauseEnd
3457
+ });
3458
+ for (const measurement of this._currentMeasurements.values()) {
3459
+ measurement.registerPause(pauseId, pauseStart, pauseEnd);
3460
+ }
3461
+ }
3462
+ }
3463
+ };
3464
+ __name(_DevUsageManager, "DevUsageManager");
3465
+ var DevUsageManager = _DevUsageManager;
3466
+ function generateRandomString() {
3467
+ let result = "";
3468
+ const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3469
+ const charactersLength = characters.length;
3470
+ for (var i = 0; i < 16; i++) {
3471
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
3472
+ }
3473
+ return result;
3474
+ }
3475
+ __name(generateRandomString, "generateRandomString");
3476
+
3477
+ // src/v3/usage/usageClient.ts
3478
+ var _UsageClient = class _UsageClient {
3479
+ constructor(url, jwt) {
3480
+ this.url = url;
3481
+ this.jwt = jwt;
3482
+ }
3483
+ async sendUsageEvent(event) {
3484
+ try {
3485
+ const response = await fetch(this.url, {
3486
+ method: "POST",
3487
+ body: JSON.stringify(event),
3488
+ headers: {
3489
+ "content-type": "application/json",
3490
+ "x-trigger-jwt": this.jwt,
3491
+ accept: "application/json",
3492
+ authorization: `Bearer ${apiClientManager.accessToken}`
3493
+ }
3494
+ });
3495
+ if (response.ok) {
3496
+ const renewedJwt = response.headers.get("x-trigger-jwt");
3497
+ if (renewedJwt) {
3498
+ this.jwt = renewedJwt;
3499
+ }
3500
+ }
3501
+ } catch (error) {
3502
+ console.error(`Failed to send usage event: ${error}`);
3503
+ }
3504
+ }
3505
+ };
3506
+ __name(_UsageClient, "UsageClient");
3507
+ var UsageClient = _UsageClient;
3508
+
3509
+ // src/v3/usage/prodUsageManager.ts
3510
+ var _startReportingHeartbeat, startReportingHeartbeat_fn, _reportUsage, reportUsage_fn;
3511
+ var _ProdUsageManager = class _ProdUsageManager {
3512
+ constructor(delegageUsageManager, options) {
3513
+ __privateAdd(this, _startReportingHeartbeat);
3514
+ __privateAdd(this, _reportUsage);
3515
+ this.delegageUsageManager = delegageUsageManager;
3516
+ this.options = options;
3517
+ if (this.options.url && this.options.jwt) {
3518
+ this._usageClient = new UsageClient(this.options.url, this.options.jwt);
3519
+ }
3520
+ }
3521
+ get isReportingEnabled() {
3522
+ return typeof this._usageClient !== "undefined";
3523
+ }
3524
+ disable() {
3525
+ this.delegageUsageManager.disable();
3526
+ this._abortController?.abort();
3527
+ }
3528
+ sample() {
3529
+ return this._measurement?.sample();
3530
+ }
3531
+ start() {
3532
+ if (!this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3533
+ return this.delegageUsageManager.start();
3534
+ }
3535
+ if (!this._measurement) {
3536
+ this._measurement = this.delegageUsageManager.start();
3537
+ __privateMethod(this, _startReportingHeartbeat, startReportingHeartbeat_fn).call(this).catch(console.error);
3538
+ return this._measurement;
3539
+ }
3540
+ return this.delegageUsageManager.start();
3541
+ }
3542
+ stop(measurement) {
3543
+ return this.delegageUsageManager.stop(measurement);
3544
+ }
3545
+ async pauseAsync(cb) {
3546
+ return this.delegageUsageManager.pauseAsync(cb);
3547
+ }
3548
+ async flush() {
3549
+ return await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3550
+ }
3551
+ };
3552
+ _startReportingHeartbeat = new WeakSet();
3553
+ startReportingHeartbeat_fn = /* @__PURE__ */ __name(async function() {
3554
+ if (!this._measurement || !this.isReportingEnabled || !this.options.heartbeatIntervalMs) {
3555
+ return;
3556
+ }
3557
+ this._abortController = new AbortController();
3558
+ for await (const _ of promises.setInterval(this.options.heartbeatIntervalMs)) {
3559
+ if (this._abortController.signal.aborted) {
3560
+ break;
3561
+ }
3562
+ await __privateMethod(this, _reportUsage, reportUsage_fn).call(this);
3563
+ }
3564
+ }, "#startReportingHeartbeat");
3565
+ _reportUsage = new WeakSet();
3566
+ reportUsage_fn = /* @__PURE__ */ __name(async function() {
3567
+ if (!this._measurement) {
3568
+ return;
3569
+ }
3570
+ if (!this.isReportingEnabled) {
3571
+ return;
3572
+ }
3573
+ const client = this._usageClient;
3574
+ if (!client) {
3575
+ return;
3576
+ }
3577
+ const sample = this._measurement.sample();
3578
+ const cpuTimeSinceLastSample = this._lastSample ? sample.cpuTime - this._lastSample.cpuTime : sample.cpuTime;
3579
+ this._lastSample = sample;
3580
+ if (cpuTimeSinceLastSample <= 0) {
3581
+ return;
3582
+ }
3583
+ await client.sendUsageEvent({
3584
+ durationMs: cpuTimeSinceLastSample
3585
+ });
3586
+ }, "#reportUsage");
3587
+ __name(_ProdUsageManager, "ProdUsageManager");
3588
+ var ProdUsageManager = _ProdUsageManager;
3589
+
3232
3590
  exports.ConsoleInterceptor = ConsoleInterceptor;
3591
+ exports.DevUsageManager = DevUsageManager;
3233
3592
  exports.DurableClock = PreciseWallClock;
3234
3593
  exports.OtelTaskLogger = OtelTaskLogger;
3594
+ exports.ProdUsageManager = ProdUsageManager;
3235
3595
  exports.StandardTaskCatalog = StandardTaskCatalog;
3236
3596
  exports.TaskContextLogProcessor = TaskContextLogProcessor;
3237
3597
  exports.TaskContextSpanProcessor = TaskContextSpanProcessor;
@@ -3240,5 +3600,6 @@ exports.TracingSDK = TracingSDK;
3240
3600
  exports.getEnvVar = getEnvVar;
3241
3601
  exports.logLevels = logLevels;
3242
3602
  exports.recordSpanException = recordSpanException;
3603
+ exports.usage = usage;
3243
3604
  //# sourceMappingURL=out.js.map
3244
3605
  //# sourceMappingURL=index.js.map