@trigger.dev/sdk 2.2.6 → 2.2.7

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.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _trigger_dev_core from '@trigger.dev/core';
2
- import { RunTaskBodyInput, CompleteTaskBodyV2Input, FailTaskBodyInput, SendEvent, SendEventOptions, StatusUpdate, UpdateTriggerSourceBodyV2, TriggerSource, RegisterTriggerBodyV2, RegisterSourceEventV2, ScheduleMetadata, GetRunOptionsWithTaskDetails, GetRunsOptions, InvokeOptions, EphemeralEventDispatcherRequestBody, LogLevel, RuntimeEnvironmentType, DisplayProperty, TriggerMetadata, EventFilter, HttpEndpointMetadata, RequestFilter, Prettify, HandleTriggerSource, Logger, RegisterTriggerSource, SerializableJson, ConnectionAuth, NormalizedResponse, HttpSourceResponseMetadata, IntervalOptions, CronOptions, ScheduledPayload, DeserializedJson, ServerTask, CachedTask, InitialStatusUpdate, FetchRequestInit, FetchRetryOptions, FetchTimeoutOptions, FetchPollOperation, RunTaskOptions, IntegrationMetadata, QueueOptions, IntegrationConfig, JobMetadata, RunNotification, MissingConnectionNotificationPayload, MissingConnectionResolvedNotificationPayload, ErrorWithStack, ApiEventLog, RedactString } from '@trigger.dev/core';
2
+ import { RunTaskBodyInput, CompleteTaskBodyV2Input, FailTaskBodyInput, SendEvent, SendEventOptions, StatusUpdate, UpdateTriggerSourceBodyV2, TriggerSource, RegisterTriggerBodyV2, RegisterSourceEventV2, ScheduleMetadata, GetRunOptionsWithTaskDetails, GetRunsOptions, InvokeOptions, EphemeralEventDispatcherRequestBody, LogLevel, RuntimeEnvironmentType, DisplayProperty, TriggerMetadata, EventFilter, SuccessfulRunNotification, FailedRunNotification, HttpEndpointMetadata, RequestFilter, Prettify, HandleTriggerSource, Logger, RegisterTriggerSource, SerializableJson, ConnectionAuth, NormalizedResponse, HttpSourceResponseMetadata, IntervalOptions, CronOptions, ScheduledPayload, DeserializedJson, ServerTask, CachedTask, InitialStatusUpdate, FetchRequestInit, FetchRetryOptions, FetchTimeoutOptions, FetchPollOperation, RunTaskOptions, IntegrationMetadata, QueueOptions, IntegrationConfig, JobMetadata, RunNotification, MissingConnectionNotificationPayload, MissingConnectionResolvedNotificationPayload, ErrorWithStack, ApiEventLog, RedactString } from '@trigger.dev/core';
3
3
  export { ConnectionAuth, DisplayProperty, EventFilter, Logger, NormalizedRequest, OverridableRunTaskOptions, Prettify, RedactString, RegisteredOptionsDiff, RunTaskOptions, SourceEventOption } from '@trigger.dev/core';
4
4
  import * as zod from 'zod';
5
5
  import { z, ZodType, TypeOf } from 'zod';
@@ -730,6 +730,48 @@ declare class TriggerStatus {
730
730
  }>;
731
731
  }
732
732
 
733
+ type EventMap = {
734
+ [key: string]: (...args: any[]) => void
735
+ }
736
+
737
+ /**
738
+ * Type-safe event emitter.
739
+ *
740
+ * Use it like this:
741
+ *
742
+ * ```typescript
743
+ * type MyEvents = {
744
+ * error: (error: Error) => void;
745
+ * message: (from: string, content: string) => void;
746
+ * }
747
+ *
748
+ * const myEmitter = new EventEmitter() as TypedEmitter<MyEvents>;
749
+ *
750
+ * myEmitter.emit("error", "x") // <- Will catch this type error;
751
+ * ```
752
+ */
753
+ interface TypedEventEmitter<Events extends EventMap> {
754
+ addListener<E extends keyof Events> (event: E, listener: Events[E]): this
755
+ on<E extends keyof Events> (event: E, listener: Events[E]): this
756
+ once<E extends keyof Events> (event: E, listener: Events[E]): this
757
+ prependListener<E extends keyof Events> (event: E, listener: Events[E]): this
758
+ prependOnceListener<E extends keyof Events> (event: E, listener: Events[E]): this
759
+
760
+ off<E extends keyof Events>(event: E, listener: Events[E]): this
761
+ removeAllListeners<E extends keyof Events> (event?: E): this
762
+ removeListener<E extends keyof Events> (event: E, listener: Events[E]): this
763
+
764
+ emit<E extends keyof Events> (event: E, ...args: Parameters<Events[E]>): boolean
765
+ // The sloppy `eventNames()` return type is to mitigate type incompatibilities - see #5
766
+ eventNames (): (keyof Events | string | symbol)[]
767
+ rawListeners<E extends keyof Events> (event: E): Events[E][]
768
+ listeners<E extends keyof Events> (event: E): Events[E][]
769
+ listenerCount<E extends keyof Events> (event: E): number
770
+
771
+ getMaxListeners (): number
772
+ setMaxListeners (maxListeners: number): this
773
+ }
774
+
733
775
  interface TriggerContext {
734
776
  /** Job metadata */
735
777
  job: {
@@ -916,6 +958,11 @@ declare function waitForEventSchema(schema: z.ZodTypeAny): z.ZodObject<{
916
958
  context?: any;
917
959
  accountId?: string | undefined;
918
960
  }>;
961
+ type NotificationEvents = {
962
+ runSucceeeded: (notification: SuccessfulRunNotification<any>) => void;
963
+ runFailed: (notification: FailedRunNotification) => void;
964
+ };
965
+ type NotificationsEventEmitter = TypedEventEmitter<NotificationEvents>;
919
966
 
920
967
  type HttpEndpointOptions<TEventSpecification extends EventSpecification<any>> = {
921
968
  id: string;
@@ -1373,6 +1420,7 @@ declare class TriggerClient {
1373
1420
  #private;
1374
1421
  id: string;
1375
1422
  constructor(options: Prettify<TriggerClientOptions>);
1423
+ on: <E extends keyof NotificationEvents>(event: E, listener: NotificationEvents[E]) => NotificationsEventEmitter;
1376
1424
  handleRequest(request: Request, timeOrigin?: number): Promise<NormalizedResponse>;
1377
1425
  defineJob<TTrigger extends Trigger<EventSpecification<any>>, TIntegrations extends Record<string, TriggerIntegration> = {}, TOutput extends any = any>(options: JobOptions<TTrigger, TIntegrations, TOutput>): Job<TTrigger, TIntegrations, TOutput>;
1378
1426
  defineAuthResolver(integration: TriggerIntegration, resolver: TriggerAuthResolver): TriggerClient;
@@ -2097,6 +2145,8 @@ type JobOptions<TTrigger extends Trigger<EventSpecification<any>>, TIntegrations
2097
2145
  * @param context An object that contains information about the Organization, Job, Run and more.
2098
2146
  */
2099
2147
  run: (payload: TriggerEventType<TTrigger>, io: IOWithIntegrations<TIntegrations>, context: TriggerContext) => Promise<TOutput>;
2148
+ onSuccess?: (notification: SuccessfulRunNotification<TOutput, TriggerEventType<TTrigger>>) => void;
2149
+ onFailure?: (notification: FailedRunNotification<TriggerEventType<TTrigger>>) => void;
2100
2150
  };
2101
2151
  type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any> ? TEvent : never;
2102
2152
  type JobIO<TJob> = TJob extends Job<any, infer TIntegrations> ? IOWithIntegrations<TIntegrations> : never;
@@ -2416,4 +2466,4 @@ type Task = ServerTask;
2416
2466
  type SentEvent = ApiEventLog;
2417
2467
  declare function redactString(strings: TemplateStringsArray, ...interpolations: string[]): RedactString;
2418
2468
 
2419
- export { AuthResolverResult, BackgroundFetchResponse, CronTrigger, DynamicIntervalOptions, DynamicSchedule, DynamicTrigger, DynamicTriggerOptions, EventSpecification, EventSpecificationExample, EventSpecificationExampleSchema, EventTrigger, EventTypeFromSpecification, ExternalSource, ExternalSourceParams, ExternalSourceTrigger, ExternalSourceTriggerOptions, HandlerEvent, HttpSourceEvent, IO, IOLogger, IOOptions, IOStats, IOTask, IOWithIntegrations, IntegrationTaskKey, IntervalTrigger, InvokeTrigger, JSONOutputSerializer, Job, JobIO, JobOptions, JobPayload, Json, MissingConnectionNotification, MissingConnectionResolvedNotification, OutputSerializer, PreprocessResults, RunTaskErrorCallback, SchemaParser, SchemaParserIssue, SchemaParserResult, SentEvent, Task, TaskLogger, Trigger, TriggerAuthResolver, TriggerClient, TriggerClientOptions, TriggerContext, TriggerEventType, TriggerIntegration, TriggerInvokeType, TriggerOptionRecord, TriggerPayload, TriggerPreprocessContext, VerifyResult, WaitForEventResult, cronTrigger, eventTrigger, intervalTrigger, invokeTrigger, isTriggerError, missingConnectionNotification, missingConnectionResolvedNotification, omit, redactString, retry, verifyHmacSha256, verifyRequestSignature, waitForEventSchema };
2469
+ export { AuthResolverResult, BackgroundFetchResponse, CronTrigger, DynamicIntervalOptions, DynamicSchedule, DynamicTrigger, DynamicTriggerOptions, EventSpecification, EventSpecificationExample, EventSpecificationExampleSchema, EventTrigger, EventTypeFromSpecification, ExternalSource, ExternalSourceParams, ExternalSourceTrigger, ExternalSourceTriggerOptions, HandlerEvent, HttpSourceEvent, IO, IOLogger, IOOptions, IOStats, IOTask, IOWithIntegrations, IntegrationTaskKey, IntervalTrigger, InvokeTrigger, JSONOutputSerializer, Job, JobIO, JobOptions, JobPayload, Json, MissingConnectionNotification, MissingConnectionResolvedNotification, NotificationEvents, NotificationsEventEmitter, OutputSerializer, PreprocessResults, RunTaskErrorCallback, SchemaParser, SchemaParserIssue, SchemaParserResult, SentEvent, Task, TaskLogger, Trigger, TriggerAuthResolver, TriggerClient, TriggerClientOptions, TriggerContext, TriggerEventType, TriggerIntegration, TriggerInvokeType, TriggerOptionRecord, TriggerPayload, TriggerPreprocessContext, VerifyResult, WaitForEventResult, cronTrigger, eventTrigger, intervalTrigger, invokeTrigger, isTriggerError, missingConnectionNotification, missingConnectionResolvedNotification, omit, redactString, retry, verifyHmacSha256, verifyRequestSignature, waitForEventSchema };
package/dist/index.js CHANGED
@@ -2397,8 +2397,11 @@ var DynamicSchedule = class {
2397
2397
  };
2398
2398
  __name(DynamicSchedule, "DynamicSchedule");
2399
2399
 
2400
+ // src/triggerClient.ts
2401
+ var import_node_events = __toESM(require("events"));
2402
+
2400
2403
  // package.json
2401
- var version = "2.2.6";
2404
+ var version = "2.2.7";
2402
2405
 
2403
2406
  // src/triggerClient.ts
2404
2407
  var registerSourceEvent = {
@@ -2408,7 +2411,7 @@ var registerSourceEvent = {
2408
2411
  icon: "register-source",
2409
2412
  parsePayload: import_core8.RegisterSourceEventSchemaV2.parse
2410
2413
  };
2411
- var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn;
2414
+ var _options4, _registeredJobs, _registeredSources, _registeredHttpSourceHandlers, _registeredDynamicTriggers, _jobMetadataByDynamicTriggers, _registeredSchedules, _registeredHttpEndpoints, _authResolvers, _eventEmitter, _client2, _internalLogger, _preprocessRun, preprocessRun_fn, _executeJob, executeJob_fn, _convertErrorToExecutionResponse, convertErrorToExecutionResponse_fn, _createRunContext, createRunContext_fn, _createPreprocessRunContext, createPreprocessRunContext_fn, _handleHttpSourceRequest, handleHttpSourceRequest_fn, _handleHttpEndpointRequestForResponse, handleHttpEndpointRequestForResponse_fn, _resolveConnections, resolveConnections_fn, _resolveConnection, resolveConnection_fn, _buildJobsIndex, buildJobsIndex_fn, _buildJobIndex, buildJobIndex_fn, _buildJobIntegrations, buildJobIntegrations_fn, _buildJobIntegration, buildJobIntegration_fn, _logIOStats, logIOStats_fn, _standardResponseHeaders, standardResponseHeaders_fn, _serializeRunMetadata, serializeRunMetadata_fn, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn, _deliverFailedRunNotification, deliverFailedRunNotification_fn;
2412
2415
  var TriggerClient = class {
2413
2416
  constructor(options) {
2414
2417
  __privateAdd(this, _preprocessRun);
@@ -2426,6 +2429,9 @@ var TriggerClient = class {
2426
2429
  __privateAdd(this, _buildJobIntegration);
2427
2430
  __privateAdd(this, _logIOStats);
2428
2431
  __privateAdd(this, _standardResponseHeaders);
2432
+ __privateAdd(this, _serializeRunMetadata);
2433
+ __privateAdd(this, _deliverSuccessfulRunNotification);
2434
+ __privateAdd(this, _deliverFailedRunNotification);
2429
2435
  __privateAdd(this, _options4, void 0);
2430
2436
  __privateAdd(this, _registeredJobs, {});
2431
2437
  __privateAdd(this, _registeredSources, {});
@@ -2435,8 +2441,10 @@ var TriggerClient = class {
2435
2441
  __privateAdd(this, _registeredSchedules, {});
2436
2442
  __privateAdd(this, _registeredHttpEndpoints, {});
2437
2443
  __privateAdd(this, _authResolvers, {});
2444
+ __privateAdd(this, _eventEmitter, new import_node_events.default());
2438
2445
  __privateAdd(this, _client2, void 0);
2439
2446
  __privateAdd(this, _internalLogger, void 0);
2447
+ __publicField(this, "on", __privateGet(this, _eventEmitter).on.bind(__privateGet(this, _eventEmitter)));
2440
2448
  this.id = options.id;
2441
2449
  __privateSet(this, _options4, options);
2442
2450
  __privateSet(this, _client2, new ApiClient(__privateGet(this, _options4)));
@@ -2613,10 +2621,12 @@ var TriggerClient = class {
2613
2621
  version: job.version,
2614
2622
  triggerVersion
2615
2623
  });
2624
+ const standardHeaders = __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin);
2625
+ standardHeaders["x-trigger-run-metadata"] = __privateMethod(this, _serializeRunMetadata, serializeRunMetadata_fn).call(this, job);
2616
2626
  return {
2617
2627
  status: 200,
2618
2628
  body: results,
2619
- headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2629
+ headers: standardHeaders
2620
2630
  };
2621
2631
  }
2622
2632
  case "PREPROCESS_RUN": {
@@ -2754,6 +2764,22 @@ var TriggerClient = class {
2754
2764
  headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2755
2765
  };
2756
2766
  }
2767
+ case "RUN_NOTIFICATION": {
2768
+ const rawJson = await request.json();
2769
+ const runNotification = rawJson;
2770
+ if (runNotification.ok) {
2771
+ await __privateMethod(this, _deliverSuccessfulRunNotification, deliverSuccessfulRunNotification_fn).call(this, runNotification);
2772
+ } else {
2773
+ await __privateMethod(this, _deliverFailedRunNotification, deliverFailedRunNotification_fn).call(this, runNotification);
2774
+ }
2775
+ return {
2776
+ status: 200,
2777
+ body: {
2778
+ ok: true
2779
+ },
2780
+ headers: __privateMethod(this, _standardResponseHeaders, standardResponseHeaders_fn).call(this, timeOrigin)
2781
+ };
2782
+ }
2757
2783
  }
2758
2784
  return {
2759
2785
  status: 405,
@@ -2975,6 +3001,7 @@ _jobMetadataByDynamicTriggers = new WeakMap();
2975
3001
  _registeredSchedules = new WeakMap();
2976
3002
  _registeredHttpEndpoints = new WeakMap();
2977
3003
  _authResolvers = new WeakMap();
3004
+ _eventEmitter = new WeakMap();
2978
3005
  _client2 = new WeakMap();
2979
3006
  _internalLogger = new WeakMap();
2980
3007
  _preprocessRun = new WeakSet();
@@ -3504,6 +3531,45 @@ standardResponseHeaders_fn = /* @__PURE__ */ __name(function(start) {
3504
3531
  "X-Trigger-Request-Timing": `dur=${performance.now() - start / 1e3}`
3505
3532
  };
3506
3533
  }, "#standardResponseHeaders");
3534
+ _serializeRunMetadata = new WeakSet();
3535
+ serializeRunMetadata_fn = /* @__PURE__ */ __name(function(job4) {
3536
+ const metadata = {};
3537
+ if (__privateGet(this, _eventEmitter).listenerCount("runSucceeeded") > 0 || typeof job4.options.onSuccess === "function") {
3538
+ metadata["successSubscription"] = true;
3539
+ }
3540
+ if (__privateGet(this, _eventEmitter).listenerCount("runFailed") > 0 || typeof job4.options.onFailure === "function") {
3541
+ metadata["failedSubscription"] = true;
3542
+ }
3543
+ return JSON.stringify(metadata);
3544
+ }, "#serializeRunMetadata");
3545
+ _deliverSuccessfulRunNotification = new WeakSet();
3546
+ deliverSuccessfulRunNotification_fn = /* @__PURE__ */ __name(async function(notification) {
3547
+ __privateGet(this, _internalLogger).debug("delivering successful run notification", {
3548
+ notification
3549
+ });
3550
+ __privateGet(this, _eventEmitter).emit("runSucceeeded", notification);
3551
+ const job = __privateGet(this, _registeredJobs)[notification.job.id];
3552
+ if (!job) {
3553
+ return;
3554
+ }
3555
+ if (typeof job.options.onSuccess === "function") {
3556
+ await job.options.onSuccess(notification);
3557
+ }
3558
+ }, "#deliverSuccessfulRunNotification");
3559
+ _deliverFailedRunNotification = new WeakSet();
3560
+ deliverFailedRunNotification_fn = /* @__PURE__ */ __name(async function(notification1) {
3561
+ __privateGet(this, _internalLogger).debug("delivering failed run notification", {
3562
+ notification: notification1
3563
+ });
3564
+ __privateGet(this, _eventEmitter).emit("runFailed", notification1);
3565
+ const job = __privateGet(this, _registeredJobs)[notification1.job.id];
3566
+ if (!job) {
3567
+ return;
3568
+ }
3569
+ if (typeof job.options.onFailure === "function") {
3570
+ await job.options.onFailure(notification1);
3571
+ }
3572
+ }, "#deliverFailedRunNotification");
3507
3573
  function dynamicTriggerRegisterSourceJobId(id) {
3508
3574
  return `register-dynamic-trigger-${id}`;
3509
3575
  }