@trigger.dev/sdk 2.1.8 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +42 -0
- package/dist/index.js +19 -4
- package/dist/index.js.map +1 -1
- package/package.json +4 -6
package/dist/index.d.ts
CHANGED
|
@@ -568,6 +568,27 @@ declare class ApiClient {
|
|
|
568
568
|
output?: any;
|
|
569
569
|
nextCursor?: string | undefined;
|
|
570
570
|
}>;
|
|
571
|
+
cancelRun(runId: string): Promise<{
|
|
572
|
+
id: string;
|
|
573
|
+
startedAt: Date | null;
|
|
574
|
+
completedAt: Date | null;
|
|
575
|
+
status: "PENDING" | "CANCELED" | "QUEUED" | "WAITING_ON_CONNECTIONS" | "PREPROCESSING" | "STARTED" | "SUCCESS" | "FAILURE" | "TIMED_OUT" | "ABORTED" | "UNRESOLVED_AUTH" | "INVALID_PAYLOAD";
|
|
576
|
+
updatedAt: Date | null;
|
|
577
|
+
tasks: _trigger_dev_core.RunTaskWithSubtasks[];
|
|
578
|
+
statuses: {
|
|
579
|
+
label: string;
|
|
580
|
+
key: string;
|
|
581
|
+
history: {
|
|
582
|
+
label?: string | undefined;
|
|
583
|
+
state?: "loading" | "success" | "failure" | undefined;
|
|
584
|
+
data?: Record<string, _trigger_dev_core.SerializableJson> | undefined;
|
|
585
|
+
}[];
|
|
586
|
+
data?: Record<string, _trigger_dev_core.SerializableJson> | undefined;
|
|
587
|
+
state?: "loading" | "success" | "failure" | undefined;
|
|
588
|
+
}[];
|
|
589
|
+
output?: any;
|
|
590
|
+
nextCursor?: string | undefined;
|
|
591
|
+
}>;
|
|
571
592
|
getRunStatuses(runId: string): Promise<{
|
|
572
593
|
statuses: {
|
|
573
594
|
label: string;
|
|
@@ -1249,6 +1270,27 @@ declare class TriggerClient {
|
|
|
1249
1270
|
output?: any;
|
|
1250
1271
|
nextCursor?: string | undefined;
|
|
1251
1272
|
}>;
|
|
1273
|
+
cancelRun(runId: string): Promise<{
|
|
1274
|
+
id: string;
|
|
1275
|
+
startedAt: Date | null;
|
|
1276
|
+
completedAt: Date | null;
|
|
1277
|
+
status: "PENDING" | "CANCELED" | "QUEUED" | "WAITING_ON_CONNECTIONS" | "PREPROCESSING" | "STARTED" | "SUCCESS" | "FAILURE" | "TIMED_OUT" | "ABORTED" | "UNRESOLVED_AUTH" | "INVALID_PAYLOAD";
|
|
1278
|
+
updatedAt: Date | null;
|
|
1279
|
+
tasks: _trigger_dev_core.RunTaskWithSubtasks[];
|
|
1280
|
+
statuses: {
|
|
1281
|
+
label: string;
|
|
1282
|
+
key: string;
|
|
1283
|
+
history: {
|
|
1284
|
+
label?: string | undefined;
|
|
1285
|
+
state?: "loading" | "success" | "failure" | undefined;
|
|
1286
|
+
data?: Record<string, _trigger_dev_core.SerializableJson> | undefined;
|
|
1287
|
+
}[];
|
|
1288
|
+
data?: Record<string, _trigger_dev_core.SerializableJson> | undefined;
|
|
1289
|
+
state?: "loading" | "success" | "failure" | undefined;
|
|
1290
|
+
}[];
|
|
1291
|
+
output?: any;
|
|
1292
|
+
nextCursor?: string | undefined;
|
|
1293
|
+
}>;
|
|
1252
1294
|
getRuns(jobSlug: string, options?: GetRunsOptions): Promise<{
|
|
1253
1295
|
runs: {
|
|
1254
1296
|
id: string;
|
package/dist/index.js
CHANGED
|
@@ -155,7 +155,6 @@ var import_core7 = require("@trigger.dev/core");
|
|
|
155
155
|
|
|
156
156
|
// src/apiClient.ts
|
|
157
157
|
var import_core = require("@trigger.dev/core");
|
|
158
|
-
var import_node_fetch = __toESM(require("node-fetch"));
|
|
159
158
|
var import_zod = require("zod");
|
|
160
159
|
var _apiUrl, _options, _logger, _apiKey, apiKey_fn;
|
|
161
160
|
var ApiClient = class {
|
|
@@ -174,7 +173,7 @@ var ApiClient = class {
|
|
|
174
173
|
url: options.url,
|
|
175
174
|
name: options.name
|
|
176
175
|
});
|
|
177
|
-
const response = await (
|
|
176
|
+
const response = await fetch(`${__privateGet(this, _apiUrl)}/api/v1/endpoints`, {
|
|
178
177
|
method: "POST",
|
|
179
178
|
headers: {
|
|
180
179
|
"Content-Type": "application/json",
|
|
@@ -394,6 +393,19 @@ var ApiClient = class {
|
|
|
394
393
|
}
|
|
395
394
|
});
|
|
396
395
|
}
|
|
396
|
+
async cancelRun(runId) {
|
|
397
|
+
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
398
|
+
__privateGet(this, _logger).debug("Cancelling Run", {
|
|
399
|
+
runId
|
|
400
|
+
});
|
|
401
|
+
return await zodfetch(import_core.GetRunSchema, `${__privateGet(this, _apiUrl)}/api/v1/runs/${runId}/cancel`, {
|
|
402
|
+
method: "POST",
|
|
403
|
+
headers: {
|
|
404
|
+
"Content-Type": "application/json",
|
|
405
|
+
Authorization: `Bearer ${apiKey}`
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
}
|
|
397
409
|
async getRunStatuses(runId) {
|
|
398
410
|
const apiKey = await __privateMethod(this, _apiKey, apiKey_fn).call(this);
|
|
399
411
|
__privateGet(this, _logger).debug("Getting Run statuses", {
|
|
@@ -454,7 +466,7 @@ function getApiKey(key) {
|
|
|
454
466
|
}
|
|
455
467
|
__name(getApiKey, "getApiKey");
|
|
456
468
|
async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url, requestInit, options) {
|
|
457
|
-
const response = await (
|
|
469
|
+
const response = await fetch(url, requestInit);
|
|
458
470
|
if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
|
|
459
471
|
return;
|
|
460
472
|
}
|
|
@@ -484,7 +496,7 @@ async function zodfetchWithVersions(versionedSchemaMap, unversionedSchema, url,
|
|
|
484
496
|
}
|
|
485
497
|
__name(zodfetchWithVersions, "zodfetchWithVersions");
|
|
486
498
|
async function zodfetch(schema, url, requestInit, options) {
|
|
487
|
-
const response = await (
|
|
499
|
+
const response = await fetch(url, requestInit);
|
|
488
500
|
if ((!requestInit || requestInit.method === "GET") && response.status === 404 && options?.optional) {
|
|
489
501
|
return;
|
|
490
502
|
}
|
|
@@ -2056,6 +2068,9 @@ var TriggerClient = class {
|
|
|
2056
2068
|
async getRun(runId, options) {
|
|
2057
2069
|
return __privateGet(this, _client2).getRun(runId, options);
|
|
2058
2070
|
}
|
|
2071
|
+
async cancelRun(runId) {
|
|
2072
|
+
return __privateGet(this, _client2).cancelRun(runId);
|
|
2073
|
+
}
|
|
2059
2074
|
async getRuns(jobSlug, options) {
|
|
2060
2075
|
return __privateGet(this, _client2).getRuns(jobSlug, options);
|
|
2061
2076
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../src/triggerClient.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/retry.ts","../src/status.ts","../src/ioWithIntegrations.ts","../src/utils/typedAsyncLocalStorage.ts","../src/runLocalStorage.ts","../src/triggers/dynamic.ts","../src/triggers/eventTrigger.ts","../src/utils/formatSchemaErrors.ts","../src/triggers/scheduled.ts","../src/triggers/externalSource.ts","../src/triggers/notifications.ts"],"sourcesContent":["export * from \"./job\";\nexport * from \"./triggerClient\";\nexport * from \"./integrations\";\nexport * from \"./triggers/eventTrigger\";\nexport * from \"./triggers/externalSource\";\nexport * from \"./triggers/dynamic\";\nexport * from \"./triggers/scheduled\";\nexport * from \"./triggers/notifications\";\nexport * from \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/core\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\nexport { retry } from \"./retry\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/core\";\n\nexport type Task = ServerTask;\n\nimport { ApiEventLog } from \"@trigger.dev/core\";\nexport type SentEvent = ApiEventLog;\n\n/*\n * This function is used to create a redacted string that can be used in the headers of a fetch request.\n * It is used to prevent the string from being logged in trigger.dev.\n * You can use it like this:\n *\n * await io.backgroundFetch<SomeResponseType>(\"https://example.com\", {\n * headers: {\n * Authorization: redactString`Bearer ${ACCESS_TOKEN}`,\n * },\n * })\n */\nexport function redactString(\n strings: TemplateStringsArray,\n ...interpolations: string[]\n): RedactString {\n return {\n __redactedString: true,\n strings: strings.raw as string[],\n interpolations,\n };\n}\n","export function slugifyId(input: string): string {\n // Replace any number of spaces with a single dash\n const replaceSpacesWithDash = input.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Remove any non-URL-safe characters\n const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, \"\");\n\n return removeNonUrlSafeChars;\n}\n","import { IntegrationConfig, JobMetadata, LogLevel, QueueOptions } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext, TriggerEventType } from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n> = {\n /** The `id` property is used to uniquely identify the Job. Only change this if you want to create a new Job. */\n id: string;\n /** The `name` of the Job that you want to appear in the dashboard and logs. You can change this without creating a new Job. */\n name: string;\n /** The `version` property is used to version your Job. A new version will be created if you change this property. We recommend using [semantic versioning](https://www.baeldung.com/cs/semantic-versioning), e.g. `1.0.3`. */\n version: string;\n /** The `trigger` property is used to define when the Job should run. There are currently the following Trigger types:\n - [cronTrigger](https://trigger.dev/docs/sdk/crontrigger)\n - [intervalTrigger](https://trigger.dev/docs/sdk/intervaltrigger)\n - [eventTrigger](https://trigger.dev/docs/sdk/eventtrigger)\n - [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger)\n - [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule)\n - integration Triggers, like webhooks. See the [integrations](https://trigger.dev/docs/integrations) page for more information. */\n trigger: TTrigger;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the Job. The level is inherited from the client if you omit this property. */\n logLevel?: LogLevel;\n /** Imports the specified integrations into the Job. The integrations will be available on the `io` object in the `run()` function with the same name as the key. For example:\n ```ts\n client.defineJob({\n //... other options\n integrations: {\n slack,\n gh: github,\n },\n run: async (payload, io, ctx) => {\n //slack is available on io.slack\n io.slack.postMessage(...);\n //github is available on io.gh\n io.gh.addIssueLabels(...);\n }\n });\n ``` */\n integrations?: TIntegrations;\n /** @deprecated This property is deprecated and no longer effects the execution of the Job\n * */\n queue?: QueueOptions | string;\n /** The `enabled` property is used to enable or disable the Job. If you disable a Job, it will not run. */\n enabled?: boolean;\n /** This function gets called automatically when a Run is Triggered.\n * This is where you put the code you want to run for a Job. You can use normal code in here and you can also use Tasks. You can return a value from this function and it will be sent back to the Trigger API.\n * @param payload The payload of the event\n * @param io An object that contains the integrations that you specified in the `integrations` property and other useful functions like delays and running Tasks.\n * @param context An object that contains information about the Organization, Job, Run and more.\n */\n run: (\n payload: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n context: TriggerContext\n ) => Promise<any>;\n\n // @internal\n __internal?: boolean;\n};\n\nexport type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any>\n ? TEvent\n : never;\n\nexport type JobIO<TJob> = TJob extends Job<any, infer TIntegrations>\n ? IOWithIntegrations<TIntegrations>\n : never;\n\n/** A [Job](https://trigger.dev/docs/documentation/concepts/jobs) is used to define the [Trigger](https://trigger.dev/docs/documentation/concepts/triggers), metadata, and what happens when it runs. */\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n /** An instance of [TriggerClient](/sdk/triggerclient) that is used to send events\n to the Trigger API. */\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\" ? this.options.enabled : true;\n }\n\n get name() {\n return this.options.name;\n }\n\n get trigger() {\n return this.options.trigger;\n }\n\n get version() {\n return this.options.version;\n }\n\n get logLevel() {\n return this.options.logLevel;\n }\n\n get integrations(): Record<string, IntegrationConfig> {\n return Object.keys(this.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = this.options.integrations![key];\n\n acc[key] = {\n id: integration.id,\n metadata: integration.metadata,\n authSource: integration.authSource,\n };\n\n return acc;\n },\n {}\n );\n }\n\n toJSON(): JobMetadata {\n // @ts-ignore\n const internal = this.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: this.id,\n name: this.name,\n version: this.version,\n event: this.trigger.event,\n trigger: this.trigger.toJSON(),\n integrations: this.integrations,\n startPosition: \"latest\", // this is deprecated, leaving this for now to make sure newer clients work with older servers\n enabled: this.enabled,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\n }\n\n // Make sure the id is valid (must only contain alphanumeric characters and dashes)\n // Make sure the version is valid (must be a valid semver version)\n #validate() {\n if (!this.version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/)) {\n throw new Error(\n `Invalid job version: \"${this.version}\". Job versions must be valid semver versions.`\n );\n }\n }\n}\n","import {\n API_VERSIONS,\n ConnectionAuth,\n DeserializedJson,\n ErrorWithStackSchema,\n GetRunOptionsWithTaskDetails,\n GetRunsOptions,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n HttpSourceResponseMetadata,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n IntegrationConfig,\n JobMetadata,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT_V2,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadataV2,\n StatusUpdate,\n} from \"@trigger.dev/core\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ParsedPayloadSchemaError,\n ResumeWithTaskError,\n RetryWithTaskError,\n YieldExecutionError,\n} from \"./errors\";\nimport { TriggerIntegration } from \"./integrations\";\nimport { IO, IOStats } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job, JobOptions } from \"./job\";\nimport { runLocalStorage } from \"./runLocalStorage\";\nimport { DynamicTrigger, DynamicTriggerOptions } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport { DynamicIntervalOptions, DynamicSchedule } from \"./triggers/scheduled\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEventV2> = {\n name: REGISTER_SOURCE_EVENT_V2,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchemaV2.parse,\n};\n\nexport type TriggerClientOptions = {\n /** The `id` property is used to uniquely identify the client.\n */\n id: string;\n /** The `apiKey` property is the API Key for your Trigger.dev environment. We\n recommend using an environment variable to store your API Key. */\n apiKey?: string;\n /** The `apiUrl` property is an optional property that specifies the API URL. You\n only need to specify this if you are not using Trigger.dev Cloud and are\n running your own Trigger.dev instance. */\n apiUrl?: string;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the TriggerClient. The level is inherited by all Jobs that use this Client, unless they also specify a `logLevel`. */\n logLevel?: LogLevel;\n /** Very verbose log messages, defaults to false. */\n verbose?: boolean;\n /** Default is unset and off. If set to true it will log to the server's console as well as the Trigger.dev platform */\n ioLogLocalEnabled?: boolean;\n};\n\nexport type AuthResolverResult = {\n type: \"apiKey\" | \"oauth\";\n token: string;\n additionalFields?: Record<string, string>;\n};\n\nexport type TriggerAuthResolver = (\n ctx: TriggerContext,\n integration: TriggerIntegration\n) => Promise<AuthResolverResult | void | undefined>;\n\n/** A [TriggerClient](https://trigger.dev/docs/documentation/concepts/client-adaptors) is used to connect to a specific [Project](https://trigger.dev/docs/documentation/concepts/projects) by using an [API Key](https://trigger.dev/docs/documentation/concepts/environments-apikeys). */\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> = {};\n #registeredSources: Record<string, SourceMetadataV2> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> = {};\n #authResolvers: Record<string, TriggerAuthResolver> = {};\n\n #client: ApiClient;\n #internalLogger: Logger;\n id: string;\n\n constructor(options: Prettify<TriggerClientOptions>) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#internalLogger = new Logger(\"trigger.dev\", this.#options.verbose ? \"debug\" : \"log\", [\n \"output\",\n \"noopTasksSet\",\n ]);\n }\n\n async handleRequest(request: Request): Promise<NormalizedResponse> {\n this.#internalLogger.debug(\"handling request\", {\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n method: request.method,\n });\n\n const apiKey = request.headers.get(\"x-trigger-api-key\");\n const triggerVersion = request.headers.get(\"x-trigger-version\");\n\n const authorization = this.authorized(apiKey);\n\n switch (authorization) {\n case \"authorized\": {\n break;\n }\n case \"missing-client\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: client missing apiKey\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n }\n\n if (request.method !== \"POST\") {\n return {\n status: 405,\n body: {\n message: \"Method not allowed (only POST is allowed)\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n const action = request.headers.get(\"x-trigger-action\");\n\n if (!action) {\n return {\n status: 400,\n body: {\n message: \"Missing x-trigger-action header\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n switch (action) {\n case \"PING\": {\n const endpointId = request.headers.get(\"x-trigger-endpoint-id\");\n\n if (!endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: \"Missing endpoint ID\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"INDEX_ENDPOINT\": {\n const body: IndexEndpointResponse = {\n jobs: this.#buildJobsIndex(),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map((trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n registerSourceJob: {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n version: trigger.source.version,\n },\n })),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(([id, jobs]) => ({\n id,\n jobs,\n })),\n };\n\n // if the x-trigger-job-id header is not set, we return all jobs\n return {\n status: 200,\n body,\n headers: this.#standardResponseHeaders,\n };\n }\n case \"INITIALIZE_TRIGGER\": {\n const json = await request.json();\n const body = InitializeTriggerBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid trigger body\",\n },\n };\n }\n\n const dynamicTrigger = this.#registeredDynamicTriggers[body.data.id];\n\n if (!dynamicTrigger) {\n return {\n status: 404,\n body: {\n message: \"Dynamic trigger not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: dynamicTrigger.registeredTriggerForParams(body.data.params),\n headers: this.#standardResponseHeaders,\n };\n }\n case \"EXECUTE_JOB\": {\n const json = await request.json();\n const execution = RunJobBodySchema.safeParse(json);\n\n if (!execution.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid execution\",\n },\n };\n }\n\n const job = this.#registeredJobs[execution.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#executeJob(execution.data, job, triggerVersion);\n\n return {\n status: 200,\n body: results,\n headers: this.#standardResponseHeaders,\n };\n }\n case \"PREPROCESS_RUN\": {\n const json = await request.json();\n const body = PreprocessRunBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid body\",\n },\n };\n }\n\n const job = this.#registeredJobs[body.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#preprocessRun(body.data, job);\n\n return {\n status: 200,\n body: {\n abort: results.abort,\n properties: results.properties,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"DELIVER_HTTP_SOURCE_REQUEST\": {\n const headers = HttpSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const dynamicId = headers.data[\"x-ts-dynamic-id\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n const data = headers.data[\"x-ts-data\"];\n const auth = headers.data[\"x-ts-auth\"];\n const inputMetadata = headers.data[\"x-ts-metadata\"];\n\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n auth,\n metadata: inputMetadata,\n };\n\n const { response, events, metadata } = await this.#handleHttpSourceRequest(\n source,\n sourceRequest\n );\n\n return {\n status: 200,\n body: {\n events,\n response,\n metadata,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"VALIDATE\": {\n return {\n status: 200,\n body: {\n ok: true,\n endpointId: this.id,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n defineJob<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n >(options: JobOptions<TTrigger, TIntegrations>) {\n return new Job<TTrigger, TIntegrations>(this, options);\n }\n\n defineAuthResolver(\n integration: TriggerIntegration,\n resolver: TriggerAuthResolver\n ): TriggerClient {\n this.#authResolvers[integration.id] = resolver;\n\n return this;\n }\n\n defineDynamicSchedule(options: DynamicIntervalOptions): DynamicSchedule {\n return new DynamicSchedule(this, options);\n }\n\n defineDynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n >(\n options: DynamicTriggerOptions<TEventSpec, TExternalSource>\n ): DynamicTrigger<TEventSpec, TExternalSource> {\n return new DynamicTrigger(this, options);\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n this.defineJob({\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n name: `Register dynamic trigger ${trigger.id}`,\n version: trigger.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { dynamicTriggerId: [trigger.id] },\n }),\n integrations: {\n integration: trigger.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await trigger.source.register(event.source.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: event.source.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(job: Job<Trigger<any>, any>, trigger: DynamicTrigger<any, any>): void {\n const jobs = this.#jobMetadataByDynamicTriggers[trigger.id] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#jobMetadataByDynamicTriggers[trigger.id] = jobs;\n }\n\n attachSource(options: {\n key: string;\n source: ExternalSource<any, any>;\n event: EventSpecification<any>;\n params: any;\n options?: Record<string, string[]>;\n }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#internalLogger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n version: \"2\",\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n options: {},\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.authSource,\n },\n registerSourceJob: {\n id: options.key,\n version: options.source.version,\n },\n };\n }\n\n //combined the previous source options with this one, making sure to include event\n const newOptions = deepMergeOptions(\n {\n event: typeof options.event.name === \"string\" ? [options.event.name] : options.event.name,\n },\n options.options ?? {}\n );\n registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\n id: options.key,\n name: options.key,\n version: options.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { source: { key: [options.key] } },\n }),\n integrations: {\n integration: options.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await options.source.register(options.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: options.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachDynamicSchedule(key: string): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n this.#registeredSchedules[key] = jobs;\n }\n\n attachDynamicScheduleToJob(key: string, job: Job<Trigger<any>, any>): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#registeredSchedules[key] = jobs;\n }\n\n async registerTrigger(id: string, key: string, options: RegisterTriggerBodyV2) {\n return this.#client.registerTrigger(this.id, id, key, options);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n /** You can call this function from anywhere in your backend to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.\n * @param event The event to send.\n * @param options Options for sending the event.\n * @returns A promise that resolves to the event details\n */\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\n }\n\n async cancelEvent(eventId: string) {\n return this.#client.cancelEvent(eventId);\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n return this.#client.updateStatus(runId, id, status);\n }\n\n async registerSchedule(id: string, key: string, schedule: ScheduleMetadata) {\n return this.#client.registerSchedule(this.id, id, key, schedule);\n }\n\n async unregisterSchedule(id: string, key: string) {\n return this.#client.unregisterSchedule(this.id, id, key);\n }\n\n async getEvent(eventId: string) {\n return this.#client.getEvent(eventId);\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n return this.#client.getRun(runId, options);\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n return this.#client.getRuns(jobSlug, options);\n }\n\n async getRunStatuses(runId: string) {\n return this.#client.getRunStatuses(runId);\n }\n\n authorized(\n apiKey?: string | null\n ): \"authorized\" | \"unauthorized\" | \"missing-client\" | \"missing-header\" {\n if (typeof apiKey !== \"string\") {\n return \"missing-header\";\n }\n\n const localApiKey = this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n\n if (!localApiKey) {\n return \"missing-client\";\n }\n\n return apiKey === localApiKey ? \"authorized\" : \"unauthorized\";\n }\n\n apiKey() {\n return this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(body: PreprocessRunBody, job: Job<Trigger<EventSpecification<any>>, any>) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];\n\n return {\n abort: false,\n properties,\n };\n }\n\n async #executeJob(\n body: RunJobBody,\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>,\n triggerVersion: string | null\n ): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.id,\n version: job.version,\n triggerVersion,\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\n cachedTasksCursor: body.cachedTaskCursor,\n yieldedExecutions: body.yieldedExecutions ?? [],\n noopTasksSet: body.noopTasksSet,\n apiClient: this.#client,\n logger: this.#internalLogger,\n client: this,\n context,\n jobLogLevel: job.logLevel ?? this.#options.logLevel ?? \"info\",\n jobLogger: this.#options.ioLogLocalEnabled\n ? new Logger(job.id, job.logLevel ?? this.#options.logLevel ?? \"info\")\n : undefined,\n serverVersion: triggerVersion,\n });\n\n const resolvedConnections = await this.#resolveConnections(\n context,\n job.options.integrations,\n body.connections\n );\n\n if (!resolvedConnections.ok) {\n return {\n status: \"UNRESOLVED_AUTH_ERROR\",\n issues: resolvedConnections.issues,\n };\n }\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n resolvedConnections.data,\n job.options.integrations\n );\n\n try {\n const output = await runLocalStorage.runWith({ io, ctx: context }, () => {\n return job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n });\n\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n if (error instanceof YieldExecutionError) {\n return { status: \"YIELD_EXECUTION\", key: error.key };\n }\n\n if (error instanceof ParsedPayloadSchemaError) {\n return { status: \"INVALID_PAYLOAD\", errors: error.schemaErrors };\n }\n\n if (error instanceof ResumeWithTaskError) {\n return { status: \"RESUME_WITH_TASK\", task: error.task };\n }\n\n if (error instanceof RetryWithTaskError) {\n return {\n status: \"RETRY_WITH_TASK\",\n task: error.task,\n error: error.cause,\n retryAt: error.retryAt,\n };\n }\n\n if (error instanceof CanceledWithTaskError) {\n return {\n status: \"CANCELED\",\n task: error.task,\n };\n }\n\n if (error instanceof RetryWithTaskError) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.task,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n task: error.task,\n };\n }\n\n const errorWithStack = ErrorWithStackSchema.safeParse(error);\n\n if (errorWithStack.success) {\n return { status: \"ERROR\", error: errorWithStack.data };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, environment, job, run, source } = execution;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(body: PreprocessRunBody): TriggerPreprocessContext {\n const { event, organization, environment, job, run, account } = body;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account,\n };\n }\n\n async #handleHttpSourceRequest(\n source: {\n key: string;\n dynamicId?: string;\n secret: string;\n data: any;\n params: any;\n auth?: ConnectionAuth;\n metadata?: DeserializedJson;\n },\n sourceRequest: Request\n ): Promise<{\n response: NormalizedResponse;\n events: SendEvent[];\n metadata?: HttpSourceResponseMetadata;\n }> {\n this.#internalLogger.debug(\"Handling HTTP source request\", {\n source,\n });\n\n if (source.dynamicId) {\n const dynamicTrigger = this.#registeredDynamicTriggers[source.dynamicId];\n\n if (!dynamicTrigger) {\n this.#internalLogger.debug(\"No dynamic trigger registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await dynamicTrigger.source.handle(\n source,\n sourceRequest,\n this.#internalLogger\n );\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#internalLogger.debug(\"No handler registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await handler(source, sourceRequest);\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n async #resolveConnections(\n ctx: TriggerContext,\n integrations?: Record<string, TriggerIntegration>,\n connections?: Record<string, ConnectionAuth>\n ): Promise<\n | { ok: true; data: Record<string, ConnectionAuth> }\n | { ok: false; issues: Record<string, { id: string; error: string }> }\n > {\n if (!integrations) {\n return { ok: true, data: {} };\n }\n\n const resolvedAuthResults = await Promise.all(\n Object.keys(integrations).map(async (key) => {\n const integration = integrations[key];\n const auth = (connections ?? {})[key];\n\n const result = await this.#resolveConnection(ctx, integration, auth);\n\n if (result.ok) {\n return {\n ok: true as const,\n auth: result.auth,\n key,\n };\n } else {\n return {\n ok: false as const,\n error: result.error,\n key,\n };\n }\n })\n );\n\n const allResolved = resolvedAuthResults.every((result) => result.ok);\n\n if (allResolved) {\n return {\n ok: true,\n data: resolvedAuthResults.reduce((acc: Record<string, ConnectionAuth>, result) => {\n acc[result.key] = result.auth!;\n\n return acc;\n }, {}),\n };\n } else {\n return {\n ok: false,\n issues: resolvedAuthResults.reduce(\n (acc: Record<string, { id: string; error: string }>, result) => {\n if (result.ok) {\n return acc;\n }\n\n const integration = integrations[result.key];\n\n acc[result.key] = { id: integration.id, error: result.error };\n\n return acc;\n },\n {}\n ),\n };\n }\n }\n\n async #resolveConnection(\n ctx: TriggerContext,\n integration: TriggerIntegration,\n auth?: ConnectionAuth\n ): Promise<{ ok: true; auth: ConnectionAuth | undefined } | { ok: false; error: string }> {\n if (auth) {\n return { ok: true, auth };\n }\n\n const authResolver = this.#authResolvers[integration.id];\n\n if (!authResolver) {\n if (integration.authSource === \"HOSTED\") {\n return {\n ok: false,\n error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`,\n };\n }\n\n return {\n ok: true,\n auth: undefined,\n };\n }\n\n try {\n const resolvedAuth = await authResolver(ctx, integration);\n\n if (!resolvedAuth) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`,\n };\n }\n\n return {\n ok: true,\n auth:\n resolvedAuth.type === \"apiKey\"\n ? {\n type: \"apiKey\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n }\n : {\n type: \"oauth2\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n },\n };\n } catch (resolverError) {\n if (resolverError instanceof Error) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`,\n };\n } else if (typeof resolverError === \"string\") {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`,\n };\n }\n\n return {\n ok: false,\n error: `Auth could not be resolved for ${\n integration.id\n }: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`,\n };\n }\n }\n\n #buildJobsIndex(): IndexEndpointResponse[\"jobs\"] {\n return Object.values(this.#registeredJobs).map((job) => this.#buildJobIndex(job));\n }\n\n #buildJobIndex(job: Job<Trigger<any>, any>): IndexEndpointResponse[\"jobs\"][number] {\n const internal = job.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: job.id,\n name: job.name,\n version: job.version,\n event: job.trigger.event,\n trigger: job.trigger.toJSON(),\n integrations: this.#buildJobIntegrations(job),\n startPosition: \"latest\", // job is deprecated, leaving job for now to make sure newer clients work with older servers\n enabled: job.enabled,\n preprocessRuns: job.trigger.preprocessRuns,\n internal,\n };\n }\n\n #buildJobIntegrations(\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"] {\n return Object.keys(job.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = job.options.integrations![key];\n\n acc[key] = this.#buildJobIntegration(integration);\n\n return acc;\n },\n {}\n );\n }\n\n #buildJobIntegration(\n integration: TriggerIntegration\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"][string] {\n const authSource = this.#authResolvers[integration.id] ? \"RESOLVER\" : integration.authSource;\n\n return {\n id: integration.id,\n metadata: integration.metadata,\n authSource,\n };\n }\n\n #logIOStats(stats: IOStats) {\n this.#internalLogger.debug(\"IO stats\", {\n stats,\n });\n }\n\n get #standardResponseHeaders() {\n return {\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n };\n }\n}\n\nfunction dynamicTriggerRegisterSourceJobId(id: string) {\n return `register-dynamic-trigger-${id}`;\n}\n\ntype Options = Record<string, string[]>;\n\nfunction deepMergeOptions(obj1: Options, obj2: Options): Options {\n const mergedOptions: Options = { ...obj1 };\n\n for (const key in obj2) {\n if (obj2.hasOwnProperty(key)) {\n if (key in mergedOptions) {\n mergedOptions[key] = [...mergedOptions[key], ...obj2[key]];\n } else {\n mergedOptions[key] = obj2[key];\n }\n }\n }\n\n return mergedOptions;\n}\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n FailTaskBodyInput,\n GetEventSchema,\n GetRunOptionsWithTaskDetails,\n GetRunSchema,\n GetRunsOptions,\n GetRunsSchema,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBodyV2,\n RegisterTriggerBodyV2,\n GetRunStatusesSchema,\n JobRunStatusRecordSchema,\n StatusUpdate,\n urlWithSearchParams,\n RunTaskResponseWithCachedTasksBodySchema,\n API_VERSIONS,\n} from \"@trigger.dev/core\";\n\nimport fetch, { type RequestInit } from \"node-fetch\";\nimport { z } from \"zod\";\n\nexport type ApiClientOptions = {\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport type EndpointRecord = {\n id: string;\n name: string;\n url: string;\n};\n\nexport type HttpSourceRecord = {\n id: string;\n key: string;\n managed: boolean;\n url: string;\n status: \"PENDING\" | \"ACTIVE\" | \"INACTIVE\";\n secret?: string;\n data?: any;\n};\n\nexport type RunRecord = {\n id: string;\n jobId: string;\n callbackUrl: string;\n event: ApiEventLog;\n};\n\nexport class ApiClient {\n #apiUrl: string;\n #options: ApiClientOptions;\n #logger: Logger;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl = this.#options.apiUrl ?? process.env.TRIGGER_API_URL ?? \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: { url: string; name: string }): Promise<EndpointRecord> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Registering endpoint\", {\n url: options.url,\n name: options.name,\n });\n\n const response = await fetch(`${this.#apiUrl}/api/v1/endpoints`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n url: options.url,\n name: options.name,\n }),\n });\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(`Failed to register entry point, got status code ${response.status}`);\n }\n\n return await response.json();\n }\n\n async runTask(\n runId: string,\n task: RunTaskBodyInput,\n options: { cachedTasksCursor?: string } = {}\n ) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetchWithVersions(\n {\n [API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: RunTaskResponseWithCachedTasksBodySchema,\n },\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Idempotency-Key\": task.idempotencyKey,\n \"X-Cached-Tasks-Cursor\": options.cachedTasksCursor ?? \"\",\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Complete Task\", {\n task,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/complete`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async failTask(runId: string, id: string, body: FailTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Fail Task\", {\n id,\n runId,\n body,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/fail`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n }\n );\n }\n\n async sendEvent(event: SendEvent, options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending event\", {\n event,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ event, options }),\n });\n }\n\n async cancelEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling event\", {\n eventId,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events/${eventId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Update status\", {\n id,\n status,\n });\n\n return await zodfetch(\n JobRunStatusRecordSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/statuses/${id}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(status),\n }\n );\n }\n\n async updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBodyV2\n ): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating http source\", {\n source,\n });\n\n const response = await zodfetch(\n TriggerSourceSchema,\n `${this.#apiUrl}/api/v2/${client}/sources/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(source),\n }\n );\n\n return response;\n }\n\n async registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBodyV2\n ): Promise<RegisterSourceEventV2> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchemaV2,\n `${this.#apiUrl}/api/v2/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n async registerSchedule(client: string, id: string, key: string, payload: ScheduleMetadata) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering schedule\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterScheduleResponseBodySchema,\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ id: key, ...payload }),\n }\n );\n\n return response;\n }\n\n async unregisterSchedule(client: string, id: string, key: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"unregistering schedule\", {\n id,\n });\n\n const response = await zodfetch(\n z.object({ ok: z.boolean() }),\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`,\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n\n return response;\n }\n\n async getAuth(client: string, id: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"getting auth\", {\n id,\n });\n\n const response = await zodfetch(\n ConnectionAuthSchema,\n `${this.#apiUrl}/api/v1/${client}/auth/${id}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n },\n {\n optional: true,\n }\n );\n\n return response;\n }\n\n async getEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Event\", {\n eventId,\n });\n\n return await zodfetch(GetEventSchema, `${this.#apiUrl}/api/v1/events/${eventId}`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run\", {\n runId,\n });\n\n return await zodfetch(\n GetRunSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/runs/${runId}`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async getRunStatuses(runId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run statuses\", {\n runId,\n });\n\n return await zodfetch(GetRunStatusesSchema, `${this.#apiUrl}/api/v1/runs/${runId}/statuses`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Runs\", {\n jobSlug,\n });\n\n return await zodfetch(\n GetRunsSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/jobs/${jobSlug}/runs`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async #apiKey() {\n const apiKey = getApiKey(this.#options.apiKey);\n\n if (apiKey.status === \"invalid\") {\n throw new Error(\"Invalid API key\");\n\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\"Trigger.dev error\")}: Invalid API key (\"${chalk.italic(\n // apiKey.apiKey\n // )}\"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n } else if (apiKey.status === \"missing\") {\n throw new Error(\"Missing API key\");\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\n // \"Trigger.dev error\"\n // )}: Missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n }\n\n return apiKey.apiKey;\n }\n}\n\nfunction getApiKey(key?: string) {\n const apiKey = key ?? process.env.TRIGGER_API_KEY;\n\n if (!apiKey) {\n return { status: \"missing\" as const };\n }\n\n // Validate the api_key format (should be tr_{env}_XXXXX)\n const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);\n\n if (!isValid) {\n return { status: \"invalid\" as const, apiKey };\n }\n\n return { status: \"valid\" as const, apiKey };\n}\n\ntype VersionedResponseBodyMap = {\n [key: string]: z.ZodTypeAny;\n};\n\n// The resulting type should be a discriminating union\n// For example, if the TVersions param is { \"2023_09_29\": z.string() } and the TUnversioned param is z.number(), the resulting type should be:\n// type VersionedResponseBody = { version: \"2023_09_29\"; body: string } | { version: \"unversioned\"; body: number }\ntype VersionedResponseBody<\n TVersions extends VersionedResponseBodyMap,\n TUnversioned extends z.ZodTypeAny,\n> =\n | {\n [TVersion in keyof TVersions]: {\n version: TVersion;\n body: z.infer<TVersions[TVersion]>;\n };\n }[keyof TVersions]\n | {\n version: \"unversioned\";\n body: z.infer<TUnversioned>;\n };\n\nasync function zodfetchWithVersions<\n TVersionedResponseBodyMap extends VersionedResponseBodyMap,\n TUnversionedResponseBodySchema extends z.ZodTypeAny,\n TOptional extends boolean = false,\n>(\n versionedSchemaMap: TVersionedResponseBodyMap,\n unversionedSchema: TUnversionedResponseBodySchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<\n TOptional extends true\n ? VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema> | undefined\n : VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema>\n> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n const version = response.headers.get(\"trigger-version\");\n\n if (!version) {\n return {\n version: \"unversioned\",\n body: unversionedSchema.parse(jsonBody),\n };\n }\n\n const versionedSchema = versionedSchemaMap[version];\n\n if (!versionedSchema) {\n throw new Error(`Unknown version ${version}`);\n }\n\n return {\n version,\n body: versionedSchema.parse(jsonBody),\n };\n}\n\nasync function zodfetch<TResponseSchema extends z.ZodTypeAny, TOptional extends boolean = false>(\n schema: TResponseSchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<\n TOptional extends true ? z.infer<TResponseSchema> | undefined : z.infer<TResponseSchema>\n> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n return schema.parse(jsonBody);\n}\n","import { ErrorWithStack, SchemaError, ServerTask } from \"@trigger.dev/core\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport class CanceledWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class YieldExecutionError {\n constructor(public key: string) {}\n}\n\nexport class ParsedPayloadSchemaError {\n constructor(public schemaErrors: SchemaError[]) {}\n}\n\n/** Use this function if you're using a `try/catch` block to catch errors.\n * It checks if a thrown error is a special internal error that you should ignore.\n * If this returns `true` then you must rethrow the error: `throw err;`\n * @param err The error to check\n * @returns `true` if the error is a Trigger Error, `false` otherwise.\n */\nexport function isTriggerError(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError | CanceledWithTaskError {\n return (\n err instanceof ResumeWithTaskError ||\n err instanceof RetryWithTaskError ||\n err instanceof CanceledWithTaskError ||\n err instanceof YieldExecutionError\n );\n}\n","import {\n API_VERSIONS,\n BloomFilter,\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n InitialStatusUpdate,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJsonSchema,\n ServerTask,\n UpdateTriggerSourceBodyV2,\n supportsFeature,\n} from \"@trigger.dev/core\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n YieldExecutionError,\n isTriggerError,\n} from \"./errors\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { ExternalSource, ExternalSourceParams } from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { TriggerStatus } from \"./status\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n cachedTasksCursor?: string;\n yieldedExecutions?: Array<string>;\n noopTasksSet?: string;\n serverVersion?: string | null;\n};\n\ntype JsonPrimitive = string | number | boolean | null | undefined | Date | symbol;\ntype JsonArray = Json[];\ntype JsonRecord<T> = { [Property in keyof T]: Json };\nexport type Json<T = any> = JsonPrimitive | JsonArray | JsonRecord<T>;\n\nexport type RunTaskErrorCallback = (\n error: unknown,\n task: IOTask,\n io: IO\n) =>\n | { retryAt?: Date; error?: Error; jitter?: number; skipRetrying?: boolean }\n | Error\n | undefined\n | void;\n\nexport type IOStats = {\n initialCachedTasks: number;\n lazyLoadedCachedTasks: number;\n executedTasks: number;\n cachedTaskHits: number;\n cachedTaskMisses: number;\n noopCachedTaskHits: number;\n noopCachedTaskMisses: number;\n};\n\nexport class IO {\n private _id: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _jobLogger?: Logger;\n private _jobLogLevel: LogLevel;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _cachedTasksCursor?: string;\n private _context: TriggerContext;\n private _yieldedExecutions: Array<string>;\n private _noopTasksBloomFilter: BloomFilter | undefined;\n private _stats: IOStats;\n private _serverVersion: string;\n\n get stats() {\n return this._stats;\n }\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger = options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n\n this._stats = {\n initialCachedTasks: 0,\n lazyLoadedCachedTasks: 0,\n executedTasks: 0,\n cachedTaskHits: 0,\n cachedTaskMisses: 0,\n noopCachedTaskHits: 0,\n noopCachedTaskMisses: 0,\n };\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.idempotencyKey, task);\n });\n\n this._stats.initialCachedTasks = options.cachedTasks.length;\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n this._yieldedExecutions = options.yieldedExecutions ?? [];\n\n if (options.noopTasksSet) {\n this._noopTasksBloomFilter = BloomFilter.deserialize(\n options.noopTasksSet,\n BloomFilter.NOOP_TASK_SET_SIZE\n );\n }\n\n this._cachedTasksCursor = options.cachedTasksCursor;\n this._serverVersion = options.serverVersion ?? \"unversioned\";\n }\n\n /** @internal */\n get runId() {\n return this._id;\n }\n\n /** @internal */\n get triggerClient() {\n return this._triggerClient;\n }\n\n /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */\n get logger() {\n return new IOLogger(async (level, message, data) => {\n let logLevel: LogLevel = \"info\";\n\n if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\n async (task) => {\n switch (level) {\n case \"LOG\": {\n this._jobLogger?.log(message, data);\n logLevel = \"log\";\n break;\n }\n case \"DEBUG\": {\n this._jobLogger?.debug(message, data);\n logLevel = \"debug\";\n break;\n }\n case \"INFO\": {\n this._jobLogger?.info(message, data);\n logLevel = \"info\";\n break;\n }\n case \"WARN\": {\n this._jobLogger?.warn(message, data);\n logLevel = \"warn\";\n break;\n }\n case \"ERROR\": {\n this._jobLogger?.error(message, data);\n logLevel = \"error\";\n break;\n }\n }\n },\n {\n name: \"log\",\n icon: \"log\",\n description: message,\n params: data,\n properties: [{ label: \"Level\", text: level }],\n style: { style: \"minimal\", variant: level.toLowerCase() },\n noop: true,\n }\n );\n }\n });\n }\n\n /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.\n */\n async wait(key: string | any[], seconds: number) {\n return await this.runTask(key, async (task) => {}, {\n name: \"wait\",\n icon: \"clock\",\n params: { seconds },\n noop: true,\n delayUntil: new Date(Date.now() + seconds * 1000),\n style: { style: \"minimal\" },\n });\n }\n\n /** `io.createStatus()` allows you to set a status with associated data during the Run. Statuses can be used by your UI using the react package \n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.\n * @returns a TriggerStatus object that you can call `update()` on, to update the status.\n * @example \n * ```ts\n * client.defineJob(\n //...\n run: async (payload, io, ctx) => {\n const generatingImages = await io.createStatus(\"generating-images\", {\n label: \"Generating Images\",\n state: \"loading\",\n data: {\n progress: 0.1,\n },\n });\n\n //...do stuff\n\n await generatingImages.update(\"completed-generation\", {\n label: \"Generated images\",\n state: \"success\",\n data: {\n progress: 1.0,\n urls: [\"http://...\"]\n },\n });\n\n //...\n });\n * ```\n */\n async createStatus(\n key: IntegrationTaskKey,\n initialStatus: InitialStatusUpdate\n ): Promise<TriggerStatus> {\n const id = typeof key === \"string\" ? key : key.join(\"-\");\n const status = new TriggerStatus(id, this);\n await status.update(key, initialStatus);\n return status;\n }\n\n /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetch<TResponseData>(\n key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n async (task) => {\n return task.output;\n },\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\n operation: \"fetch\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ],\n }\n )) as TResponseData;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent even will trigger any Jobs that are listening for that event (based on the name).\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.\n * @param options Options for sending the event.\n */\n async sendEvent(key: string | any[], event: SendEvent, options?: SendEventOptions) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n },\n {\n name: \"sendEvent\",\n params: { event, options },\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ],\n }\n );\n }\n\n async getEvent(key: string | any[], id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.getEvent(id);\n },\n {\n name: \"getEvent\",\n params: { id },\n properties: [\n {\n label: \"id\",\n text: id,\n },\n ],\n }\n );\n }\n\n /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay\n * @param key\n * @param eventId\n * @returns\n */\n async cancelEvent(key: string | any[], eventId: string) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.cancelEvent(eventId);\n },\n {\n name: \"cancelEvent\",\n params: {\n eventId,\n },\n properties: [\n {\n label: \"id\",\n text: eventId,\n },\n ],\n }\n );\n }\n\n async updateSource(key: string | any[], options: { key: string } & UpdateTriggerSourceBodyV2) {\n return this.runTask(\n key,\n async (task) => {\n return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);\n },\n {\n name: \"Update Source\",\n description: \"Update Source\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n redact: {\n paths: [\"secret\"],\n },\n }\n );\n }\n\n /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @param options The options for the interval.\n * @returns A promise that has information about the interval.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n },\n {\n name: \"register-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"seconds\", text: options.seconds.toString() },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterInterval(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.\n * @param options The options for the CRON schedule.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n },\n {\n name: \"register-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"cron\", text: options.cron },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterCron(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.\n * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.\n * @param params The params for the trigger.\n * @deprecated Use `DynamicTrigger.register` instead.\n */\n async registerTrigger<\n TTrigger extends DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>,\n >(\n key: string | any[],\n trigger: TTrigger,\n id: string,\n params: ExternalSourceParams<TTrigger[\"source\"]>\n ): Promise<{ id: string; key: string } | undefined> {\n return await this.runTask(\n key,\n async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n async (subtask1) => {\n return trigger.register(id, params);\n },\n {\n name: \"register-source\",\n }\n );\n\n return {\n id: registration.id,\n key: registration.source.key,\n };\n },\n {\n name: \"register-trigger\",\n properties: [\n { label: \"trigger\", text: trigger.id },\n { label: \"id\", text: id },\n ],\n params: params as any,\n }\n );\n }\n\n async getAuth(key: string | any[], clientId?: string): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.getAuth(clientId);\n },\n { name: \"get-auth\" }\n );\n }\n\n /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.\n *\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.\n * @param options The options of how you'd like to run and log the Task.\n * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.\n * @returns A Promise that resolves with the returned value of the callback.\n */\n async runTask<T extends Json<T> | void>(\n key: string | any[],\n callback: (task: ServerTask, io: IO) => Promise<T>,\n options?: RunTaskOptions,\n onError?: RunTaskErrorCallback\n ): Promise<T> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey([this._id, parentId ?? \"\", key].flat());\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask && cachedTask.status === \"COMPLETED\") {\n this._logger.debug(\"Using completed cached task\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskHits++;\n\n return cachedTask.output as T;\n }\n\n if (options?.noop && this._noopTasksBloomFilter) {\n if (this._noopTasksBloomFilter.test(idempotencyKey)) {\n this._logger.debug(\"task idempotency key exists in noopTasksBloomFilter\", {\n idempotencyKey,\n });\n\n this._stats.noopCachedTaskHits++;\n\n return {} as T;\n }\n }\n\n const response = await this._apiClient.runTask(\n this._id,\n {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...(options ?? {}),\n parentId,\n },\n {\n cachedTasksCursor: this._cachedTasksCursor,\n }\n );\n\n const task =\n response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS\n ? response.body.task\n : response.body;\n\n if (response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {\n this._cachedTasksCursor = response.body.cachedTasks?.cursor;\n\n for (const cachedTask of response.body.cachedTasks?.tasks ?? []) {\n if (!this._cachedTasks.has(cachedTask.idempotencyKey)) {\n this._cachedTasks.set(cachedTask.idempotencyKey, cachedTask);\n\n this._logger.debug(\"Injecting lazy loaded task into task cache\", {\n idempotencyKey: cachedTask.idempotencyKey,\n });\n\n this._stats.lazyLoadedCachedTasks++;\n }\n }\n }\n\n if (task.status === \"CANCELED\") {\n this._logger.debug(\"Task canceled\", {\n idempotencyKey,\n task,\n });\n\n throw new CanceledWithTaskError(task);\n }\n\n if (task.status === \"COMPLETED\") {\n if (task.noop) {\n this._logger.debug(\"Noop Task completed\", {\n idempotencyKey,\n });\n\n this._noopTasksBloomFilter?.add(task.idempotencyKey);\n } else {\n this._logger.debug(\"Cache miss\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskMisses++;\n this.#addToCachedTasks(task);\n }\n\n return task.output as T;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : \"Task errored\");\n }\n\n const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n if (task.status === \"WAITING\" && task.callbackUrl) {\n this._logger.debug(\"Waiting for remote callback\", {\n idempotencyKey,\n task,\n });\n return {} as T;\n }\n\n const output = SerializableJsonSchema.parse(result) as T;\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n const completedTask = await this._apiClient.completeTask(this._id, task.id, {\n output: output ?? undefined,\n properties: task.outputProperties ?? undefined,\n });\n\n this._stats.executedTasks++;\n\n if (completedTask.status === \"CANCELED\") {\n throw new CanceledWithTaskError(completedTask);\n }\n\n return output;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n let skipRetrying = false;\n\n if (onError) {\n try {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n if (onErrorResult instanceof Error) {\n error = onErrorResult;\n } else {\n skipRetrying = !!onErrorResult.skipRetrying;\n\n if (onErrorResult.retryAt && !skipRetrying) {\n const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);\n\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n }\n } catch (innerError) {\n if (isTriggerError(innerError)) {\n throw innerError;\n }\n\n error = innerError;\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options?.retry && !skipRetrying) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n retryAt\n );\n }\n }\n\n if (parsedError.success) {\n await this._apiClient.failTask(this._id, task.id, {\n error: parsedError.data,\n });\n } else {\n await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\n });\n\n if (task.callbackUrl) {\n await this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n throw new ResumeWithTaskError(task);\n }\n\n if (task.status === \"RUNNING\" && typeof task.operation === \"string\") {\n this._logger.debug(\"Task running operation\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n /**\n * `io.yield()` allows you to yield execution of the current run and resume it in a new function execution. Similar to `io.wait()` but does not create a task and resumes execution immediately.\n */\n yield(key: string) {\n if (!supportsFeature(\"yieldExecution\", this._serverVersion)) {\n console.warn(\n \"[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.\"\n );\n\n return;\n }\n\n if (this._yieldedExecutions.includes(key)) {\n return;\n }\n\n throw new YieldExecutionError(key);\n }\n\n /**\n * `io.brb()` is an alias of `io.yield()`\n */\n brb = this.yield.bind(this);\n\n /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](/sdk/io/runtask).\n * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.\n * @param tryCallback The code you wish to run\n * @param catchCallback Thhis will be called if the Task fails. The callback receives the error\n * @returns A Promise that resolves with the returned value or the error\n */\n async try<TResult, TCatchResult>(\n tryCallback: () => Promise<TResult>,\n catchCallback: (error: unknown) => Promise<TCatchResult>\n ): Promise<TResult | TCatchResult> {\n try {\n return await tryCallback();\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n return await catchCallback(error);\n }\n }\n\n #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\n }\n}\n\n// Generate a stable idempotency key for the key material, using a stable json stringification\nasync function generateIdempotencyKey(keyMaterial: any[]) {\n const keys = keyMaterial.map((key) => {\n if (typeof key === \"string\") {\n return key;\n }\n\n return stableStringify(key);\n });\n\n const key = keys.join(\":\");\n\n const hash = await webcrypto.subtle.digest(\"SHA-256\", Buffer.from(key));\n\n return Buffer.from(hash).toString(\"hex\");\n}\n\nfunction stableStringify(obj: any): string {\n function sortKeys(obj: any): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n\n for (const key of sortedKeys) {\n sortedObj[key] = sortKeys(obj[key]);\n }\n\n return sortedObj;\n }\n\n const sortedObj = sortKeys(obj);\n return JSON.stringify(sortedObj);\n}\n\ntype CallbackFunction = (\n level: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"LOG\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n /** Log: essential messages */\n log(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"LOG\", message, properties);\n }\n\n /** For debugging: the least important log level */\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n\n /** Info: the second least important log level */\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n\n /** Warnings: the third most important log level */\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n\n /** Error: The second most important log level */\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n","import type { RetryOptions } from \"@trigger.dev/core\";\nimport { calculateRetryAt } from \"@trigger.dev/core\";\n\nexport { calculateRetryAt };\nexport type { RetryOptions };\n\nexport const retry = {\n standardBackoff: {\n limit: 8,\n factor: 1.8,\n minTimeoutInMs: 500,\n maxTimeoutInMs: 30000,\n randomize: true,\n },\n} as const satisfies Record<string, RetryOptions>;\n","import { DisplayProperty, StatusUpdate } from \"@trigger.dev/core\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport class TriggerStatus {\n constructor(\n private id: string,\n private io: IO\n ) {}\n\n async update(key: IntegrationTaskKey, status: StatusUpdate) {\n const properties: DisplayProperty[] = [];\n\n if (status.label) {\n properties.push({\n label: \"Label\",\n text: status.label,\n });\n }\n\n if (status.state) {\n properties.push({\n label: \"State\",\n text: status.state,\n });\n }\n\n return await this.io.runTask(\n key,\n async (task) => {\n return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);\n },\n {\n name: status.label ?? `Status update`,\n icon: \"bell\",\n params: {\n ...status,\n },\n properties,\n }\n );\n }\n}\n","import { ConnectionAuth } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<TIntegrations extends Record<string, TriggerIntegration>>(\n io: IO,\n auths?: Record<string, ConnectionAuth | undefined>,\n integrations?: TIntegrations\n): IOWithIntegrations<TIntegrations> {\n if (!integrations) {\n return io as IOWithIntegrations<TIntegrations>;\n }\n\n const connections = Object.entries(integrations).reduce(\n (acc, [connectionKey, integration]) => {\n let auth = auths?.[connectionKey];\n\n acc[connectionKey] = {\n integration,\n auth,\n };\n\n return acc;\n },\n {} as Record<\n string,\n {\n integration: TriggerIntegration;\n auth?: ConnectionAuth;\n }\n >\n );\n\n return new Proxy(io, {\n get(target, prop, receiver) {\n // We can return the original io back if the prop is __io\n if (prop === \"__io\") {\n return io;\n }\n\n if (typeof prop === \"string\" && prop in connections) {\n const { integration, auth } = connections[prop];\n return integration.cloneForRun(io, prop, auth);\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n }) as IOWithIntegrations<TIntegrations>;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport class TypedAsyncLocalStorage<T> {\n private storage: AsyncLocalStorage<T>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<T>();\n }\n\n runWith<R extends (...args: any[]) => Promise<any>>(context: T, fn: R): Promise<ReturnType<R>> {\n return this.storage.run(context, fn);\n }\n\n getStore(): T | undefined {\n return this.storage.getStore();\n }\n}\n","import { IO } from \"./io\";\nimport { TriggerContext } from \"./types\";\nimport { TypedAsyncLocalStorage } from \"./utils/typedAsyncLocalStorage\";\n\nexport type RunStore = {\n io: IO;\n ctx: TriggerContext;\n};\n\nexport const runLocalStorage = new TypedAsyncLocalStorage<RunStore>();\n","import {\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\nimport { runLocalStorage } from \"../runLocalStorage\";\nimport { EventFilter } from \"@trigger.dev/core\";\n\n/** Options for a DynamicTrigger */\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> = {\n /** Used to uniquely identify a DynamicTrigger */\n id: string;\n /** An event from an [Integration](https://trigger.dev/docs/integrations) package that you want to attach to the DynamicTrigger. The event types will come through to the payload in your Job's run. */\n event: TEventSpec;\n /** An external source fron an [Integration](https://trigger.dev/docs/integrations) package\n * @example \n * ```ts\n * import { events } from \"@trigger.dev/github\";\n * \n * const dynamicOnIssueOpened = client.defineDynamicTrigger({\n id: \"github-issue-opened\",\n event: events.onIssueOpened,\n source: github.sources.repo,\n });\n * ```\n */\n source: TExternalSource;\n};\n\n/** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime. */\nexport class DynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpec>\n{\n #client: TriggerClient;\n #options: DynamicTriggerOptions<TEventSpec, TExternalSource>;\n source: TExternalSource;\n\n /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the dynamic trigger.\n * */\n constructor(client: TriggerClient, options: DynamicTriggerOptions<TEventSpec, TExternalSource>) {\n this.#client = client;\n this.#options = options;\n this.source = options.source;\n\n client.attachDynamicTrigger(this);\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.#options.id,\n };\n }\n\n get id() {\n return this.#options.id;\n }\n\n get event() {\n return this.#options.event;\n }\n\n // @internal\n registeredTriggerForParams(\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): RegisterTriggerBodyV2 {\n const key = slugifyId(this.source.key(params));\n\n return {\n rule: {\n event: this.event.name,\n source: this.event.source,\n payload: deepMergeFilters(\n this.source.filter(params),\n this.event.filter ?? {},\n options.filter ?? {}\n ),\n },\n source: {\n version: \"2\",\n key,\n channel: this.source.channel,\n params,\n //todo add other options here\n options: {\n event: typeof this.event.name === \"string\" ? [this.event.name] : this.event.name,\n },\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.authSource,\n },\n },\n accountId: options.accountId,\n };\n }\n\n /** Use this method to register a new configuration with the DynamicTrigger.\n * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.\n * @param params The params for the configuration.\n * @param options Options for the configuration.\n * @param options.accountId The accountId to associate with the configuration.\n * @param options.filter The filter to use for the configuration.\n *\n */\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): Promise<RegisterSourceEventV2> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options)\n );\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options)\n );\n },\n {\n name: \"Register Dynamic Trigger\",\n properties: [\n { label: \"Dynamic Trigger ID\", text: this.id },\n { label: \"ID\", text: key },\n ],\n params: params as any,\n }\n );\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import { EventFilter, TriggerMetadata, deepMergeFilters } from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, EventSpecificationExample, SchemaParser, Trigger } from \"../types\";\nimport { formatSchemaErrors } from \"../utils/formatSchemaErrors\";\nimport { ParsedPayloadSchemaError } from \"../errors\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n event: TEventSpecification;\n name?: string | string[];\n source?: string;\n filter?: EventFilter;\n};\n\nexport class EventTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n #options: EventTriggerOptions<TEventSpecification>;\n\n constructor(options: EventTriggerOptions<TEventSpecification>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.#options.name ?? this.#options.event.title,\n rule: {\n event: this.#options.name ?? this.#options.event.name,\n source: this.#options.source ?? \"trigger.dev\",\n payload: deepMergeFilters(this.#options.filter ?? {}, this.#options.event.filter ?? {}),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\n/** Configuration options for an EventTrigger */\ntype TriggerOptions<TEvent> = {\n /** The name of the event you are subscribing to. Must be an exact match (case sensitive). To trigger on multiple possible events, pass in an array of event names */\n name: string | string[];\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: SchemaParser<TEvent>;\n /** You can use this to filter events based on the source. */\n source?: string;\n /** Used to filter which events trigger the Job\n * @example\n * filter:\n * ```ts\n * {\n * name: [\"John\", \"Jane\"],\n * age: [18, 21]\n * }\n * ```\n *\n * This filter would match against an event with the following data:\n * ```json\n * {\n * \"name\": \"Jane\",\n * \"age\": 18,\n * \"location\": \"San Francisco\"\n * }\n * ```\n */\n filter?: EventFilter;\n\n examples?: EventSpecificationExample[];\n};\n\n/** `eventTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to subscribe to an event a Job from [a sent event](https://trigger.dev/docs/sdk/triggerclient/instancemethods/sendevent)\n * @param options options for the EventTrigger\n */\nexport function eventTrigger<TEvent extends any = any>(\n options: TriggerOptions<TEvent>\n): Trigger<EventSpecification<TEvent>> {\n return new EventTrigger({\n name: options.name,\n filter: options.filter,\n event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n examples: options.examples,\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n const results = options.schema.safeParse(rawPayload);\n\n if (!results.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));\n }\n\n return results.data;\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import type { SchemaError } from \"@trigger.dev/core\";\nimport { SchemaParserIssue } from \"../types\";\n\nexport function formatSchemaErrors(errors: SchemaParserIssue[]): SchemaError[] {\n return errors.map((error) => {\n const { path, message } = error;\n return { path: path.map(String), message };\n });\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\nimport { runLocalStorage } from \"../runLocalStorage\";\n\ntype ScheduledEventSpecification = EventSpecification<ScheduledPayload>;\n\nconst examples = [\n {\n id: \"now\",\n name: \"Now\",\n icon: \"clock\",\n payload: {\n ts: currentDate.marker,\n lastTimestamp: currentDate.marker,\n },\n },\n];\n\nexport class IntervalTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: IntervalOptions) {}\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-interval\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"Interval\",\n text: `${this.options.seconds}s`,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"interval\",\n options: {\n seconds: this.options.seconds,\n },\n },\n };\n }\n}\n\n/** `intervalTrigger()` is set as a [Job's trigger](/sdk/job) to trigger a Job at a recurring interval.\n * @param options An object containing options about the interval.\n */\nexport function intervalTrigger(options: IntervalOptions) {\n return new IntervalTrigger(options);\n}\n\nexport class CronTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: CronOptions) {}\n\n get event() {\n const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n });\n\n return {\n name: \"trigger.scheduled\",\n title: \"Cron Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-cron\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"cron\",\n text: this.options.cron,\n },\n {\n label: \"Schedule\",\n text: humanReadable,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"cron\",\n options: {\n cron: this.options.cron,\n },\n },\n };\n }\n}\n\n/** `cronTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to trigger a Job on a recurring schedule using a CRON expression.\n * @param options An object containing options about the CRON schedule.\n */\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\n/** DynamicSchedule options\n * @param id Used to uniquely identify a DynamicSchedule\n */\nexport type DynamicIntervalOptions = { id: string };\n\n/** DynamicSchedule` allows you to define a scheduled trigger that can be configured dynamically at runtime. */\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n /**\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the schedule.\n */\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\n ) {\n client.attachDynamicSchedule(this.options.id);\n }\n\n get id() {\n return this.options.id;\n }\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Dynamic Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-dynamic\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n };\n }\n\n async register(key: string, metadata: ScheduleMetadata) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.registerSchedule(this.id, key, metadata);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.client.registerSchedule(this.id, key, metadata);\n },\n {\n name: \"Register Schedule\",\n icon: metadata.type === \"cron\" ? \"schedule-cron\" : \"schedule-interval\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n params: metadata,\n }\n );\n }\n\n async unregister(key: string) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"unregister\"],\n async (task) => {\n return this.client.unregisterSchedule(this.id, key);\n },\n {\n name: \"Unregister Schedule\",\n icon: \"schedule\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n }\n );\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicScheduleToJob(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\n}\n","import {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n HttpSourceResponseMetadata,\n Logger,\n NormalizedResponse,\n RegisterTriggerSource,\n SendEvent,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, SchemaParser, Trigger, TriggerContext } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { SerializableJson } from \"@trigger.dev/core\";\nimport { ConnectionAuth } from \"@trigger.dev/core\";\nimport { Prettify } from \"@trigger.dev/core\";\n\nexport type HttpSourceEvent = {\n url: string;\n method: string;\n headers: Record<string, string>;\n rawBody?: Buffer | null;\n};\n\ntype SmtpSourceEvent = {\n from: string;\n to: string;\n subject: string;\n body: string;\n};\n\ntype SqsSourceEvent = {\n body: string;\n};\n\ntype ExternalSourceChannelMap = {\n HTTP: {\n event: Request;\n register: {\n url: string;\n };\n };\n SMTP: {\n event: SmtpSourceEvent;\n register: {};\n };\n SQS: {\n event: SqsSourceEvent;\n register: {};\n };\n};\n\ntype ChannelNames = keyof ExternalSourceChannelMap;\n\ntype TriggerOptionDiff = {\n desired: string[];\n missing: string[];\n orphaned: string[];\n};\n\ntype TriggerOptionDiffs<TTriggerOptionDefinitions extends Record<string, string[]> = any> =\n TriggerOptionsRecordWithEvent<TriggerOptionDiff, TTriggerOptionDefinitions>;\n\ntype TriggerOptionsRecordWithEvent<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]>,\n> = {\n event: TValue;\n} & TriggerOptionRecord<TValue, TTriggerOptionDefinitions>;\n\nexport type TriggerOptionRecord<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n [K in keyof TTriggerOptionDefinitions]: TValue;\n};\n\ntype RegisterFunctionEvent<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterSourceEvent<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n id: string;\n source: RegisterTriggerSource;\n dynamicTriggerId?: string;\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunctionOutput<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n secret?: string;\n data?: SerializableJson;\n options: TriggerOptionsRecordWithEvent<string[], TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (\n event: RegisterFunctionEvent<TChannel, TParams, TTriggerOptionDefinitions>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<RegisterFunctionOutput<TTriggerOptionDefinitions> | undefined>;\n\nexport type HandlerEvent<TChannel extends ChannelNames, TParams extends any = any> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: Prettify<Omit<HandleTriggerSource, \"params\"> & { params: TParams }>;\n};\n\ntype HandlerFunction<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerIntegration extends TriggerIntegration,\n> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger,\n integration: TTriggerIntegration,\n auth?: ConnectionAuth\n) => Promise<{\n events: SendEvent[];\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n} | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (params: TParams, options?: TTriggerOptionDefinitions) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n id: string;\n version: string;\n schema: SchemaParser<TParams>;\n optionSchema?: SchemaParser<TTriggerOptionDefinitions>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel, TTriggerOptionDefinitions>;\n filter?: FilterFunction<TParams, TTriggerOptionDefinitions>;\n handler: HandlerFunction<TChannel, TParams, TIntegration>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<\n TChannel,\n TIntegration,\n TParams,\n TTriggerOptionDefinitions\n >\n ) {\n this.channel = channel;\n }\n\n async handle(\n source: HandleTriggerSource,\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"],\n logger: Logger\n ) {\n return this.options.handler(\n {\n source: { ...source, params: source.params as TParams },\n rawEvent,\n },\n logger,\n this.options.integration\n );\n }\n\n filter(params: TParams, options?: TTriggerOptionDefinitions): EventFilter {\n return this.options.filter?.(params, options) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(\n params: TParams,\n registerEvent: RegisterSourceEvent<TTriggerOptionDefinitions>,\n io: IO,\n ctx: TriggerContext\n ) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(source, \"channel\");\n const { result: channelWithoutType } = omit(channel, \"type\");\n\n const updates = await this.options.register(\n {\n ...event,\n source: { ...sourceWithoutChannel, ...channelWithoutType },\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n key(params: TParams): string {\n const parts = [this.options.id, this.channel];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return parts.join(\"-\");\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type ExternalSourceParams<TExternalSource extends ExternalSource<any, any, any>> =\n TExternalSource extends ExternalSource<any, infer TParams, any> ? TParams : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n options: TriggerOptionRecord<string[], TTriggerOptionDefinitions>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: ExternalSourceTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"External Source\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params, this.options.options),\n this.event.filter ?? {},\n this.options.params.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.attachSource({\n key: slugifyId(this.options.source.key(this.options.params)),\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n options: this.options.options,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n\nexport function omit<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n key: K\n): { result: Omit<T, K>; ommited: T[K] } {\n const result: any = {};\n\n for (const k of Object.keys(obj)) {\n if (k === key) continue;\n\n result[k] = obj[k];\n }\n\n return { result, ommited: obj[key] };\n}\n","import {\n MISSING_CONNECTION_NOTIFICATION,\n MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n MissingConnectionNotificationPayload,\n MissingConnectionNotificationPayloadSchema,\n MissingConnectionResolvedNotificationPayload,\n MissingConnectionResolvedNotificationPayloadSchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionResolvedNotification({ integrations });\n}\n\ntype MissingConnectionNotificationSpecification =\n EventSpecification<MissingConnectionNotificationPayload>;\n\ntype MissingConnectionNotificationOptions = {\n integrations: Array<TriggerIntegration>;\n};\n\nexport class MissingConnectionNotification\n implements Trigger<MissingConnectionNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_NOTIFICATION,\n title: \"Missing Connection Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n\ntype MissingConnectionResolvedNotificationSpecification =\n EventSpecification<MissingConnectionResolvedNotificationPayload>;\n\nexport class MissingConnectionResolvedNotification\n implements Trigger<MissingConnectionResolvedNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n title: \"Missing Connection Resolved Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionResolvedNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAAQ,qBAAqB,EAAA;AAEjF,SAAOC;AACT;AARgBL;;;ACIhB;AAsEO,IAAM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;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CanB;AAkDN,IAAME,wCAAN,MAAMA;EAGXC,YAAoBC,SAA+C;mBAA/CA;EAAgD;EAEpE,IAAIC,QAAQ;AACV,WAAO;MACLC,MAAMwB;MACNtB,OAAO;MACPC,QAAQ;MACRC,MAAM;MACNC,cAAcoB,gEAAmDlB;MACjEC,YAAY;QACV;UACEC,OAAO;UACPC,MAAM,KAAKZ,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE,EAAEC,KAAK,IAAA;QACxD;;IAEJ;EACF;EAEAC,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;AjB7CN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","logLevel","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","toJSON","internal","__internal","event","startPosition","preprocessRuns","match","Error","import_core","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","runTask","runId","task","zodfetchWithVersions","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","RunTaskResponseWithCachedTasksBodySchema","ServerTaskSchema","idempotencyKey","cachedTasksCursor","completeTask","id","zodfetch","failTask","sendEvent","event","ApiEventLogSchema","cancelEvent","eventId","updateStatus","JobRunStatusRecordSchema","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchemaV2","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getEvent","GetEventSchema","getRun","GetRunSchema","urlWithSearchParams","getRunStatuses","GetRunStatusesSchema","getRuns","jobSlug","GetRunsSchema","getApiKey","TRIGGER_API_KEY","isValid","match","versionedSchemaMap","unversionedSchema","requestInit","errorMessage","jsonBody","version","get","parse","versionedSchema","schema","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","YieldExecutionError","key","ParsedPayloadSchemaError","schemaErrors","isTriggerError","err","import_core","import_core","retry","standardBackoff","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","TriggerStatus","constructor","id","io","update","key","status","properties","label","push","text","state","runTask","task","triggerClient","updateStatus","runId","name","icon","params","IO","constructor","options","brb","yield","bind","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","_stats","initialCachedTasks","lazyLoadedCachedTasks","executedTasks","cachedTaskHits","cachedTaskMisses","noopCachedTaskHits","noopCachedTaskMisses","cachedTasks","forEach","task","set","idempotencyKey","length","_taskStorage","AsyncLocalStorage","_context","context","_yieldedExecutions","yieldedExecutions","noopTasksSet","_noopTasksBloomFilter","BloomFilter","deserialize","NOOP_TASK_SET_SIZE","_cachedTasksCursor","cachedTasksCursor","_serverVersion","serverVersion","stats","runId","triggerClient","IOLogger","level","message","data","satisfiesLogLevel","runTask","log","debug","info","warn","error","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","createStatus","initialStatus","join","status","TriggerStatus","update","backgroundFetch","url","requestInit","retry","urlObject","URL","output","hostname","pathname","operation","method","sendEvent","event","getEvent","cancelEvent","eventId","updateSource","redact","paths","registerInterval","dynamicSchedule","register","type","toString","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","source","getAuth","clientId","callback","onError","parentId","getStore","taskId","generateIdempotencyKey","flat","cachedTask","get","test","response","displayKey","undefined","version","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","body","cursor","tasks","has","CanceledWithTaskError","add","Error","JSON","stringify","executeTask","result","callbackUrl","SerializableJsonSchema","parse","completedTask","completeTask","outputProperties","isTriggerError","skipRetrying","onErrorResult","retryAt","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","innerError","calculateRetryAt","attempts","failTask","run","ResumeWithTaskError","supportsFeature","console","includes","YieldExecutionError","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","Proxy","get","target","prop","receiver","cloneForRun","value","Reflect","bind","import_node_async_hooks","TypedAsyncLocalStorage","constructor","storage","AsyncLocalStorage","runWith","context","fn","run","getStore","runLocalStorage","TypedAsyncLocalStorage","import_core","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","key","slugifyId","rule","name","payload","deepMergeFilters","filter","version","channel","integration","metadata","authSource","accountId","register","runStore","runLocalStorage","getStore","registerTrigger","io","runTask","task","properties","label","text","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","import_core","formatSchemaErrors","errors","map","error","path","message","String","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","examples","parsePayload","rawPayload","schema","results","safeParse","success","ParsedPayloadSchemaError","formatSchemaErrors","error","issues","data","import_core","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","humanReadable","cronstrue","toString","cron","throwExceptionOnParseError","cronTrigger","DynamicSchedule","client","attachDynamicSchedule","register","key","metadata","runStore","runLocalStorage","getStore","registerSchedule","io","runTask","task","params","unregister","unregisterSchedule","attachDynamicScheduleToJob","registerSourceEvent","name","REGISTER_SOURCE_EVENT_V2","title","source","icon","parsePayload","RegisterSourceEventSchemaV2","parse","_options","_client","TriggerClient","constructor","options","id","ApiClient","Logger","verbose","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","triggerVersion","authorization","authorized","status","body","message","action","endpointId","ok","error","jobs","sources","values","dynamicTriggers","map","trigger","registerSourceJob","dynamicTriggerRegisterSourceJobId","version","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","job","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequestNeedsBody","sourceRequestInit","undefined","duplex","sourceRequest","Request","key","dynamicId","secret","auth","inputMetadata","metadata","response","events","defineJob","Job","defineAuthResolver","integration","resolver","defineDynamicSchedule","DynamicSchedule","defineDynamicTrigger","DynamicTrigger","attach","attachToJob","attachDynamicTrigger","EventTrigger","event","filter","dynamicTriggerId","integrations","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","authSource","newOptions","deepMergeOptions","attachDynamicSchedule","attachDynamicScheduleToJob","registerTrigger","getAuth","sendEvent","cancelEvent","eventId","updateStatus","runId","registerSchedule","schedule","unregisterSchedule","getEvent","getRun","getRuns","jobSlug","getRunStatuses","localApiKey","process","env","TRIGGER_API_KEY","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","cachedTasksCursor","cachedTaskCursor","yieldedExecutions","noopTasksSet","apiClient","logger","client","jobLogLevel","logLevel","jobLogger","ioLogLocalEnabled","serverVersion","resolvedConnections","connections","issues","ioWithConnections","createIOWithIntegrations","output","runLocalStorage","runWith","stats","YieldExecutionError","ParsedPayloadSchemaError","errors","schemaErrors","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","resolvedAuthResults","Promise","all","keys","result","allResolved","every","reduce","acc","authResolver","resolvedAuth","type","accessToken","token","additionalFields","resolverError","Error","JSON","stringify","internal","toJSON","startPosition","enabled","preprocessRuns","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","obj1","obj2","mergedOptions","hasOwnProperty","import_core","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","integration","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","import_core","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils.ts","../src/job.ts","../src/triggerClient.ts","../src/apiClient.ts","../src/errors.ts","../src/io.ts","../src/retry.ts","../src/status.ts","../src/ioWithIntegrations.ts","../src/utils/typedAsyncLocalStorage.ts","../src/runLocalStorage.ts","../src/triggers/dynamic.ts","../src/triggers/eventTrigger.ts","../src/utils/formatSchemaErrors.ts","../src/triggers/scheduled.ts","../src/triggers/externalSource.ts","../src/triggers/notifications.ts"],"sourcesContent":["export * from \"./job\";\nexport * from \"./triggerClient\";\nexport * from \"./integrations\";\nexport * from \"./triggers/eventTrigger\";\nexport * from \"./triggers/externalSource\";\nexport * from \"./triggers/dynamic\";\nexport * from \"./triggers/scheduled\";\nexport * from \"./triggers/notifications\";\nexport * from \"./io\";\nexport * from \"./types\";\n\nimport { ServerTask } from \"@trigger.dev/core\";\nimport { RedactString } from \"./types\";\nexport { isTriggerError } from \"./errors\";\nexport { retry } from \"./retry\";\n\nexport type { NormalizedRequest, EventFilter } from \"@trigger.dev/core\";\n\nexport type Task = ServerTask;\n\nimport { ApiEventLog } from \"@trigger.dev/core\";\nexport type SentEvent = ApiEventLog;\n\n/*\n * This function is used to create a redacted string that can be used in the headers of a fetch request.\n * It is used to prevent the string from being logged in trigger.dev.\n * You can use it like this:\n *\n * await io.backgroundFetch<SomeResponseType>(\"https://example.com\", {\n * headers: {\n * Authorization: redactString`Bearer ${ACCESS_TOKEN}`,\n * },\n * })\n */\nexport function redactString(\n strings: TemplateStringsArray,\n ...interpolations: string[]\n): RedactString {\n return {\n __redactedString: true,\n strings: strings.raw as string[],\n interpolations,\n };\n}\n","export function slugifyId(input: string): string {\n // Replace any number of spaces with a single dash\n const replaceSpacesWithDash = input.toLowerCase().replace(/\\s+/g, \"-\");\n\n // Remove any non-URL-safe characters\n const removeNonUrlSafeChars = replaceSpacesWithDash.replace(/[^a-zA-Z0-9-._~]/g, \"\");\n\n return removeNonUrlSafeChars;\n}\n","import { IntegrationConfig, JobMetadata, LogLevel, QueueOptions } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { TriggerClient } from \"./triggerClient\";\nimport type { EventSpecification, Trigger, TriggerContext, TriggerEventType } from \"./types\";\nimport { slugifyId } from \"./utils\";\n\nexport type JobOptions<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n> = {\n /** The `id` property is used to uniquely identify the Job. Only change this if you want to create a new Job. */\n id: string;\n /** The `name` of the Job that you want to appear in the dashboard and logs. You can change this without creating a new Job. */\n name: string;\n /** The `version` property is used to version your Job. A new version will be created if you change this property. We recommend using [semantic versioning](https://www.baeldung.com/cs/semantic-versioning), e.g. `1.0.3`. */\n version: string;\n /** The `trigger` property is used to define when the Job should run. There are currently the following Trigger types:\n - [cronTrigger](https://trigger.dev/docs/sdk/crontrigger)\n - [intervalTrigger](https://trigger.dev/docs/sdk/intervaltrigger)\n - [eventTrigger](https://trigger.dev/docs/sdk/eventtrigger)\n - [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger)\n - [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule)\n - integration Triggers, like webhooks. See the [integrations](https://trigger.dev/docs/integrations) page for more information. */\n trigger: TTrigger;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the Job. The level is inherited from the client if you omit this property. */\n logLevel?: LogLevel;\n /** Imports the specified integrations into the Job. The integrations will be available on the `io` object in the `run()` function with the same name as the key. For example:\n ```ts\n client.defineJob({\n //... other options\n integrations: {\n slack,\n gh: github,\n },\n run: async (payload, io, ctx) => {\n //slack is available on io.slack\n io.slack.postMessage(...);\n //github is available on io.gh\n io.gh.addIssueLabels(...);\n }\n });\n ``` */\n integrations?: TIntegrations;\n /** @deprecated This property is deprecated and no longer effects the execution of the Job\n * */\n queue?: QueueOptions | string;\n /** The `enabled` property is used to enable or disable the Job. If you disable a Job, it will not run. */\n enabled?: boolean;\n /** This function gets called automatically when a Run is Triggered.\n * This is where you put the code you want to run for a Job. You can use normal code in here and you can also use Tasks. You can return a value from this function and it will be sent back to the Trigger API.\n * @param payload The payload of the event\n * @param io An object that contains the integrations that you specified in the `integrations` property and other useful functions like delays and running Tasks.\n * @param context An object that contains information about the Organization, Job, Run and more.\n */\n run: (\n payload: TriggerEventType<TTrigger>,\n io: IOWithIntegrations<TIntegrations>,\n context: TriggerContext\n ) => Promise<any>;\n\n // @internal\n __internal?: boolean;\n};\n\nexport type JobPayload<TJob> = TJob extends Job<Trigger<EventSpecification<infer TEvent>>, any>\n ? TEvent\n : never;\n\nexport type JobIO<TJob> = TJob extends Job<any, infer TIntegrations>\n ? IOWithIntegrations<TIntegrations>\n : never;\n\n/** A [Job](https://trigger.dev/docs/documentation/concepts/jobs) is used to define the [Trigger](https://trigger.dev/docs/documentation/concepts/triggers), metadata, and what happens when it runs. */\nexport class Job<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n> {\n readonly options: JobOptions<TTrigger, TIntegrations>;\n\n client: TriggerClient;\n\n constructor(\n /** An instance of [TriggerClient](/sdk/triggerclient) that is used to send events\n to the Trigger API. */\n client: TriggerClient,\n options: JobOptions<TTrigger, TIntegrations>\n ) {\n this.client = client;\n this.options = options;\n this.#validate();\n\n client.attach(this);\n }\n\n get id() {\n return slugifyId(this.options.id);\n }\n\n get enabled() {\n return typeof this.options.enabled === \"boolean\" ? this.options.enabled : true;\n }\n\n get name() {\n return this.options.name;\n }\n\n get trigger() {\n return this.options.trigger;\n }\n\n get version() {\n return this.options.version;\n }\n\n get logLevel() {\n return this.options.logLevel;\n }\n\n get integrations(): Record<string, IntegrationConfig> {\n return Object.keys(this.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = this.options.integrations![key];\n\n acc[key] = {\n id: integration.id,\n metadata: integration.metadata,\n authSource: integration.authSource,\n };\n\n return acc;\n },\n {}\n );\n }\n\n toJSON(): JobMetadata {\n // @ts-ignore\n const internal = this.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: this.id,\n name: this.name,\n version: this.version,\n event: this.trigger.event,\n trigger: this.trigger.toJSON(),\n integrations: this.integrations,\n startPosition: \"latest\", // this is deprecated, leaving this for now to make sure newer clients work with older servers\n enabled: this.enabled,\n preprocessRuns: this.trigger.preprocessRuns,\n internal,\n };\n }\n\n // Make sure the id is valid (must only contain alphanumeric characters and dashes)\n // Make sure the version is valid (must be a valid semver version)\n #validate() {\n if (!this.version.match(/^(\\d+)\\.(\\d+)\\.(\\d+)$/)) {\n throw new Error(\n `Invalid job version: \"${this.version}\". Job versions must be valid semver versions.`\n );\n }\n }\n}\n","import {\n API_VERSIONS,\n ConnectionAuth,\n DeserializedJson,\n ErrorWithStackSchema,\n GetRunOptionsWithTaskDetails,\n GetRunsOptions,\n HandleTriggerSource,\n HttpSourceRequestHeadersSchema,\n HttpSourceResponseMetadata,\n IndexEndpointResponse,\n InitializeTriggerBodySchema,\n IntegrationConfig,\n JobMetadata,\n LogLevel,\n Logger,\n NormalizedResponse,\n PreprocessRunBody,\n PreprocessRunBodySchema,\n Prettify,\n REGISTER_SOURCE_EVENT_V2,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n RunJobBody,\n RunJobBodySchema,\n RunJobResponse,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n SourceMetadataV2,\n StatusUpdate,\n} from \"@trigger.dev/core\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ParsedPayloadSchemaError,\n ResumeWithTaskError,\n RetryWithTaskError,\n YieldExecutionError,\n} from \"./errors\";\nimport { TriggerIntegration } from \"./integrations\";\nimport { IO, IOStats } from \"./io\";\nimport { createIOWithIntegrations } from \"./ioWithIntegrations\";\nimport { Job, JobOptions } from \"./job\";\nimport { runLocalStorage } from \"./runLocalStorage\";\nimport { DynamicTrigger, DynamicTriggerOptions } from \"./triggers/dynamic\";\nimport { EventTrigger } from \"./triggers/eventTrigger\";\nimport { ExternalSource } from \"./triggers/externalSource\";\nimport { DynamicIntervalOptions, DynamicSchedule } from \"./triggers/scheduled\";\nimport type {\n EventSpecification,\n Trigger,\n TriggerContext,\n TriggerPreprocessContext,\n} from \"./types\";\n\nconst registerSourceEvent: EventSpecification<RegisterSourceEventV2> = {\n name: REGISTER_SOURCE_EVENT_V2,\n title: \"Register Source\",\n source: \"internal\",\n icon: \"register-source\",\n parsePayload: RegisterSourceEventSchemaV2.parse,\n};\n\nexport type TriggerClientOptions = {\n /** The `id` property is used to uniquely identify the client.\n */\n id: string;\n /** The `apiKey` property is the API Key for your Trigger.dev environment. We\n recommend using an environment variable to store your API Key. */\n apiKey?: string;\n /** The `apiUrl` property is an optional property that specifies the API URL. You\n only need to specify this if you are not using Trigger.dev Cloud and are\n running your own Trigger.dev instance. */\n apiUrl?: string;\n /** The `logLevel` property is an optional property that specifies the level of\n logging for the TriggerClient. The level is inherited by all Jobs that use this Client, unless they also specify a `logLevel`. */\n logLevel?: LogLevel;\n /** Very verbose log messages, defaults to false. */\n verbose?: boolean;\n /** Default is unset and off. If set to true it will log to the server's console as well as the Trigger.dev platform */\n ioLogLocalEnabled?: boolean;\n};\n\nexport type AuthResolverResult = {\n type: \"apiKey\" | \"oauth\";\n token: string;\n additionalFields?: Record<string, string>;\n};\n\nexport type TriggerAuthResolver = (\n ctx: TriggerContext,\n integration: TriggerIntegration\n) => Promise<AuthResolverResult | void | undefined>;\n\n/** A [TriggerClient](https://trigger.dev/docs/documentation/concepts/client-adaptors) is used to connect to a specific [Project](https://trigger.dev/docs/documentation/concepts/projects) by using an [API Key](https://trigger.dev/docs/documentation/concepts/environments-apikeys). */\nexport class TriggerClient {\n #options: TriggerClientOptions;\n #registeredJobs: Record<string, Job<Trigger<EventSpecification<any>>, any>> = {};\n #registeredSources: Record<string, SourceMetadataV2> = {};\n #registeredHttpSourceHandlers: Record<\n string,\n (\n source: HandleTriggerSource,\n request: Request\n ) => Promise<{\n events: Array<SendEvent>;\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n } | void>\n > = {};\n #registeredDynamicTriggers: Record<\n string,\n DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>\n > = {};\n #jobMetadataByDynamicTriggers: Record<string, Array<{ id: string; version: string }>> = {};\n #registeredSchedules: Record<string, Array<{ id: string; version: string }>> = {};\n #authResolvers: Record<string, TriggerAuthResolver> = {};\n\n #client: ApiClient;\n #internalLogger: Logger;\n id: string;\n\n constructor(options: Prettify<TriggerClientOptions>) {\n this.id = options.id;\n this.#options = options;\n this.#client = new ApiClient(this.#options);\n this.#internalLogger = new Logger(\"trigger.dev\", this.#options.verbose ? \"debug\" : \"log\", [\n \"output\",\n \"noopTasksSet\",\n ]);\n }\n\n async handleRequest(request: Request): Promise<NormalizedResponse> {\n this.#internalLogger.debug(\"handling request\", {\n url: request.url,\n headers: Object.fromEntries(request.headers.entries()),\n method: request.method,\n });\n\n const apiKey = request.headers.get(\"x-trigger-api-key\");\n const triggerVersion = request.headers.get(\"x-trigger-version\");\n\n const authorization = this.authorized(apiKey);\n\n switch (authorization) {\n case \"authorized\": {\n break;\n }\n case \"missing-client\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: client missing apiKey\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"missing-header\": {\n return {\n status: 401,\n body: {\n message: \"Unauthorized: missing x-trigger-api-key header\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"unauthorized\": {\n return {\n status: 401,\n body: {\n message: `Forbidden: client apiKey mismatch: Make sure you are using the correct API Key for your environment`,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n }\n\n if (request.method !== \"POST\") {\n return {\n status: 405,\n body: {\n message: \"Method not allowed (only POST is allowed)\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n const action = request.headers.get(\"x-trigger-action\");\n\n if (!action) {\n return {\n status: 400,\n body: {\n message: \"Missing x-trigger-action header\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n switch (action) {\n case \"PING\": {\n const endpointId = request.headers.get(\"x-trigger-endpoint-id\");\n\n if (!endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: \"Missing endpoint ID\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n if (this.id !== endpointId) {\n return {\n status: 200,\n body: {\n ok: false,\n error: `Endpoint ID mismatch error. Expected ${this.id}, got ${endpointId}`,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n return {\n status: 200,\n body: {\n ok: true,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"INDEX_ENDPOINT\": {\n const body: IndexEndpointResponse = {\n jobs: this.#buildJobsIndex(),\n sources: Object.values(this.#registeredSources),\n dynamicTriggers: Object.values(this.#registeredDynamicTriggers).map((trigger) => ({\n id: trigger.id,\n jobs: this.#jobMetadataByDynamicTriggers[trigger.id] ?? [],\n registerSourceJob: {\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n version: trigger.source.version,\n },\n })),\n dynamicSchedules: Object.entries(this.#registeredSchedules).map(([id, jobs]) => ({\n id,\n jobs,\n })),\n };\n\n // if the x-trigger-job-id header is not set, we return all jobs\n return {\n status: 200,\n body,\n headers: this.#standardResponseHeaders,\n };\n }\n case \"INITIALIZE_TRIGGER\": {\n const json = await request.json();\n const body = InitializeTriggerBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid trigger body\",\n },\n };\n }\n\n const dynamicTrigger = this.#registeredDynamicTriggers[body.data.id];\n\n if (!dynamicTrigger) {\n return {\n status: 404,\n body: {\n message: \"Dynamic trigger not found\",\n },\n };\n }\n\n return {\n status: 200,\n body: dynamicTrigger.registeredTriggerForParams(body.data.params),\n headers: this.#standardResponseHeaders,\n };\n }\n case \"EXECUTE_JOB\": {\n const json = await request.json();\n const execution = RunJobBodySchema.safeParse(json);\n\n if (!execution.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid execution\",\n },\n };\n }\n\n const job = this.#registeredJobs[execution.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#executeJob(execution.data, job, triggerVersion);\n\n return {\n status: 200,\n body: results,\n headers: this.#standardResponseHeaders,\n };\n }\n case \"PREPROCESS_RUN\": {\n const json = await request.json();\n const body = PreprocessRunBodySchema.safeParse(json);\n\n if (!body.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid body\",\n },\n };\n }\n\n const job = this.#registeredJobs[body.data.job.id];\n\n if (!job) {\n return {\n status: 404,\n body: {\n message: \"Job not found\",\n },\n };\n }\n\n const results = await this.#preprocessRun(body.data, job);\n\n return {\n status: 200,\n body: {\n abort: results.abort,\n properties: results.properties,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"DELIVER_HTTP_SOURCE_REQUEST\": {\n const headers = HttpSourceRequestHeadersSchema.safeParse(\n Object.fromEntries(request.headers.entries())\n );\n\n if (!headers.success) {\n return {\n status: 400,\n body: {\n message: \"Invalid headers\",\n },\n };\n }\n\n const sourceRequestNeedsBody = headers.data[\"x-ts-http-method\"] !== \"GET\";\n\n const sourceRequestInit: RequestInit = {\n method: headers.data[\"x-ts-http-method\"],\n headers: headers.data[\"x-ts-http-headers\"],\n body: sourceRequestNeedsBody ? request.body : undefined,\n };\n\n if (sourceRequestNeedsBody) {\n try {\n // @ts-ignore\n sourceRequestInit.duplex = \"half\";\n } catch (error) {\n // ignore\n }\n }\n\n const sourceRequest = new Request(headers.data[\"x-ts-http-url\"], sourceRequestInit);\n\n const key = headers.data[\"x-ts-key\"];\n const dynamicId = headers.data[\"x-ts-dynamic-id\"];\n const secret = headers.data[\"x-ts-secret\"];\n const params = headers.data[\"x-ts-params\"];\n const data = headers.data[\"x-ts-data\"];\n const auth = headers.data[\"x-ts-auth\"];\n const inputMetadata = headers.data[\"x-ts-metadata\"];\n\n const source = {\n key,\n dynamicId,\n secret,\n params,\n data,\n auth,\n metadata: inputMetadata,\n };\n\n const { response, events, metadata } = await this.#handleHttpSourceRequest(\n source,\n sourceRequest\n );\n\n return {\n status: 200,\n body: {\n events,\n response,\n metadata,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n case \"VALIDATE\": {\n return {\n status: 200,\n body: {\n ok: true,\n endpointId: this.id,\n },\n headers: this.#standardResponseHeaders,\n };\n }\n }\n\n return {\n status: 405,\n body: {\n message: \"Method not allowed\",\n },\n headers: this.#standardResponseHeaders,\n };\n }\n\n defineJob<\n TTrigger extends Trigger<EventSpecification<any>>,\n TIntegrations extends Record<string, TriggerIntegration> = {},\n >(options: JobOptions<TTrigger, TIntegrations>) {\n return new Job<TTrigger, TIntegrations>(this, options);\n }\n\n defineAuthResolver(\n integration: TriggerIntegration,\n resolver: TriggerAuthResolver\n ): TriggerClient {\n this.#authResolvers[integration.id] = resolver;\n\n return this;\n }\n\n defineDynamicSchedule(options: DynamicIntervalOptions): DynamicSchedule {\n return new DynamicSchedule(this, options);\n }\n\n defineDynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n >(\n options: DynamicTriggerOptions<TEventSpec, TExternalSource>\n ): DynamicTrigger<TEventSpec, TExternalSource> {\n return new DynamicTrigger(this, options);\n }\n\n attach(job: Job<Trigger<any>, any>): void {\n this.#registeredJobs[job.id] = job;\n\n job.trigger.attachToJob(this, job);\n }\n\n attachDynamicTrigger(trigger: DynamicTrigger<any, any>): void {\n this.#registeredDynamicTriggers[trigger.id] = trigger;\n\n this.defineJob({\n id: dynamicTriggerRegisterSourceJobId(trigger.id),\n name: `Register dynamic trigger ${trigger.id}`,\n version: trigger.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { dynamicTriggerId: [trigger.id] },\n }),\n integrations: {\n integration: trigger.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await trigger.source.register(event.source.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: event.source.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachJobToDynamicTrigger(job: Job<Trigger<any>, any>, trigger: DynamicTrigger<any, any>): void {\n const jobs = this.#jobMetadataByDynamicTriggers[trigger.id] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#jobMetadataByDynamicTriggers[trigger.id] = jobs;\n }\n\n attachSource(options: {\n key: string;\n source: ExternalSource<any, any>;\n event: EventSpecification<any>;\n params: any;\n options?: Record<string, string[]>;\n }): void {\n this.#registeredHttpSourceHandlers[options.key] = async (s, r) => {\n return await options.source.handle(s, r, this.#internalLogger);\n };\n\n let registeredSource = this.#registeredSources[options.key];\n\n if (!registeredSource) {\n registeredSource = {\n version: \"2\",\n channel: options.source.channel,\n key: options.key,\n params: options.params,\n options: {},\n integration: {\n id: options.source.integration.id,\n metadata: options.source.integration.metadata,\n authSource: options.source.integration.authSource,\n },\n registerSourceJob: {\n id: options.key,\n version: options.source.version,\n },\n };\n }\n\n //combined the previous source options with this one, making sure to include event\n const newOptions = deepMergeOptions(\n {\n event: typeof options.event.name === \"string\" ? [options.event.name] : options.event.name,\n },\n options.options ?? {}\n );\n registeredSource.options = deepMergeOptions(registeredSource.options, newOptions);\n\n this.#registeredSources[options.key] = registeredSource;\n\n new Job(this, {\n id: options.key,\n name: options.key,\n version: options.source.version,\n trigger: new EventTrigger({\n event: registerSourceEvent,\n filter: { source: { key: [options.key] } },\n }),\n integrations: {\n integration: options.source.integration,\n },\n run: async (event, io, ctx) => {\n const updates = await options.source.register(options.params, event, io, ctx);\n\n if (!updates) {\n // TODO: do something here?\n return;\n }\n\n return await io.updateSource(\"update-source\", {\n key: options.key,\n ...updates,\n });\n },\n __internal: true,\n });\n }\n\n attachDynamicSchedule(key: string): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n this.#registeredSchedules[key] = jobs;\n }\n\n attachDynamicScheduleToJob(key: string, job: Job<Trigger<any>, any>): void {\n const jobs = this.#registeredSchedules[key] ?? [];\n\n jobs.push({ id: job.id, version: job.version });\n\n this.#registeredSchedules[key] = jobs;\n }\n\n async registerTrigger(id: string, key: string, options: RegisterTriggerBodyV2) {\n return this.#client.registerTrigger(this.id, id, key, options);\n }\n\n async getAuth(id: string) {\n return this.#client.getAuth(this.id, id);\n }\n\n /** You can call this function from anywhere in your backend to send an event. The other way to send an event is by using [`io.sendEvent()`](https://trigger.dev/docs/sdk/io/sendevent) from inside a `run()` function.\n * @param event The event to send.\n * @param options Options for sending the event.\n * @returns A promise that resolves to the event details\n */\n async sendEvent(event: SendEvent, options?: SendEventOptions) {\n return this.#client.sendEvent(event, options);\n }\n\n async cancelEvent(eventId: string) {\n return this.#client.cancelEvent(eventId);\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n return this.#client.updateStatus(runId, id, status);\n }\n\n async registerSchedule(id: string, key: string, schedule: ScheduleMetadata) {\n return this.#client.registerSchedule(this.id, id, key, schedule);\n }\n\n async unregisterSchedule(id: string, key: string) {\n return this.#client.unregisterSchedule(this.id, id, key);\n }\n\n async getEvent(eventId: string) {\n return this.#client.getEvent(eventId);\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n return this.#client.getRun(runId, options);\n }\n\n async cancelRun(runId: string) {\n return this.#client.cancelRun(runId);\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n return this.#client.getRuns(jobSlug, options);\n }\n\n async getRunStatuses(runId: string) {\n return this.#client.getRunStatuses(runId);\n }\n\n authorized(\n apiKey?: string | null\n ): \"authorized\" | \"unauthorized\" | \"missing-client\" | \"missing-header\" {\n if (typeof apiKey !== \"string\") {\n return \"missing-header\";\n }\n\n const localApiKey = this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n\n if (!localApiKey) {\n return \"missing-client\";\n }\n\n return apiKey === localApiKey ? \"authorized\" : \"unauthorized\";\n }\n\n apiKey() {\n return this.#options.apiKey ?? process.env.TRIGGER_API_KEY;\n }\n\n async #preprocessRun(body: PreprocessRunBody, job: Job<Trigger<EventSpecification<any>>, any>) {\n const context = this.#createPreprocessRunContext(body);\n\n const parsedPayload = job.trigger.event.parsePayload(body.event.payload ?? {});\n\n const properties = job.trigger.event.runProperties?.(parsedPayload) ?? [];\n\n return {\n abort: false,\n properties,\n };\n }\n\n async #executeJob(\n body: RunJobBody,\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>,\n triggerVersion: string | null\n ): Promise<RunJobResponse> {\n this.#internalLogger.debug(\"executing job\", {\n execution: body,\n job: job.id,\n version: job.version,\n triggerVersion,\n });\n\n const context = this.#createRunContext(body);\n\n const io = new IO({\n id: body.run.id,\n cachedTasks: body.tasks,\n cachedTasksCursor: body.cachedTaskCursor,\n yieldedExecutions: body.yieldedExecutions ?? [],\n noopTasksSet: body.noopTasksSet,\n apiClient: this.#client,\n logger: this.#internalLogger,\n client: this,\n context,\n jobLogLevel: job.logLevel ?? this.#options.logLevel ?? \"info\",\n jobLogger: this.#options.ioLogLocalEnabled\n ? new Logger(job.id, job.logLevel ?? this.#options.logLevel ?? \"info\")\n : undefined,\n serverVersion: triggerVersion,\n });\n\n const resolvedConnections = await this.#resolveConnections(\n context,\n job.options.integrations,\n body.connections\n );\n\n if (!resolvedConnections.ok) {\n return {\n status: \"UNRESOLVED_AUTH_ERROR\",\n issues: resolvedConnections.issues,\n };\n }\n\n const ioWithConnections = createIOWithIntegrations(\n io,\n resolvedConnections.data,\n job.options.integrations\n );\n\n try {\n const output = await runLocalStorage.runWith({ io, ctx: context }, () => {\n return job.options.run(\n job.trigger.event.parsePayload(body.event.payload ?? {}),\n ioWithConnections,\n context\n );\n });\n\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n return { status: \"SUCCESS\", output };\n } catch (error) {\n if (this.#options.verbose) {\n this.#logIOStats(io.stats);\n }\n\n if (error instanceof YieldExecutionError) {\n return { status: \"YIELD_EXECUTION\", key: error.key };\n }\n\n if (error instanceof ParsedPayloadSchemaError) {\n return { status: \"INVALID_PAYLOAD\", errors: error.schemaErrors };\n }\n\n if (error instanceof ResumeWithTaskError) {\n return { status: \"RESUME_WITH_TASK\", task: error.task };\n }\n\n if (error instanceof RetryWithTaskError) {\n return {\n status: \"RETRY_WITH_TASK\",\n task: error.task,\n error: error.cause,\n retryAt: error.retryAt,\n };\n }\n\n if (error instanceof CanceledWithTaskError) {\n return {\n status: \"CANCELED\",\n task: error.task,\n };\n }\n\n if (error instanceof RetryWithTaskError) {\n const errorWithStack = ErrorWithStackSchema.safeParse(error.cause);\n\n if (errorWithStack.success) {\n return {\n status: \"ERROR\",\n error: errorWithStack.data,\n task: error.task,\n };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n task: error.task,\n };\n }\n\n const errorWithStack = ErrorWithStackSchema.safeParse(error);\n\n if (errorWithStack.success) {\n return { status: \"ERROR\", error: errorWithStack.data };\n }\n\n return {\n status: \"ERROR\",\n error: { message: \"Unknown error\" },\n };\n }\n }\n\n #createRunContext(execution: RunJobBody): TriggerContext {\n const { event, organization, environment, job, run, source } = execution;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account: execution.account,\n source,\n };\n }\n\n #createPreprocessRunContext(body: PreprocessRunBody): TriggerPreprocessContext {\n const { event, organization, environment, job, run, account } = body;\n\n return {\n event: {\n id: event.id,\n name: event.name,\n context: event.context,\n timestamp: event.timestamp,\n },\n organization,\n environment,\n job,\n run,\n account,\n };\n }\n\n async #handleHttpSourceRequest(\n source: {\n key: string;\n dynamicId?: string;\n secret: string;\n data: any;\n params: any;\n auth?: ConnectionAuth;\n metadata?: DeserializedJson;\n },\n sourceRequest: Request\n ): Promise<{\n response: NormalizedResponse;\n events: SendEvent[];\n metadata?: HttpSourceResponseMetadata;\n }> {\n this.#internalLogger.debug(\"Handling HTTP source request\", {\n source,\n });\n\n if (source.dynamicId) {\n const dynamicTrigger = this.#registeredDynamicTriggers[source.dynamicId];\n\n if (!dynamicTrigger) {\n this.#internalLogger.debug(\"No dynamic trigger registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await dynamicTrigger.source.handle(\n source,\n sourceRequest,\n this.#internalLogger\n );\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n const handler = this.#registeredHttpSourceHandlers[source.key];\n\n if (!handler) {\n this.#internalLogger.debug(\"No handler registered for HTTP source\", {\n source,\n });\n\n return {\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n events: [],\n };\n }\n\n const results = await handler(source, sourceRequest);\n\n if (!results) {\n return {\n events: [],\n response: {\n status: 200,\n body: {\n ok: true,\n },\n },\n };\n }\n\n return {\n events: results.events,\n response: results.response ?? {\n status: 200,\n body: {\n ok: true,\n },\n },\n metadata: results.metadata,\n };\n }\n\n async #resolveConnections(\n ctx: TriggerContext,\n integrations?: Record<string, TriggerIntegration>,\n connections?: Record<string, ConnectionAuth>\n ): Promise<\n | { ok: true; data: Record<string, ConnectionAuth> }\n | { ok: false; issues: Record<string, { id: string; error: string }> }\n > {\n if (!integrations) {\n return { ok: true, data: {} };\n }\n\n const resolvedAuthResults = await Promise.all(\n Object.keys(integrations).map(async (key) => {\n const integration = integrations[key];\n const auth = (connections ?? {})[key];\n\n const result = await this.#resolveConnection(ctx, integration, auth);\n\n if (result.ok) {\n return {\n ok: true as const,\n auth: result.auth,\n key,\n };\n } else {\n return {\n ok: false as const,\n error: result.error,\n key,\n };\n }\n })\n );\n\n const allResolved = resolvedAuthResults.every((result) => result.ok);\n\n if (allResolved) {\n return {\n ok: true,\n data: resolvedAuthResults.reduce((acc: Record<string, ConnectionAuth>, result) => {\n acc[result.key] = result.auth!;\n\n return acc;\n }, {}),\n };\n } else {\n return {\n ok: false,\n issues: resolvedAuthResults.reduce(\n (acc: Record<string, { id: string; error: string }>, result) => {\n if (result.ok) {\n return acc;\n }\n\n const integration = integrations[result.key];\n\n acc[result.key] = { id: integration.id, error: result.error };\n\n return acc;\n },\n {}\n ),\n };\n }\n }\n\n async #resolveConnection(\n ctx: TriggerContext,\n integration: TriggerIntegration,\n auth?: ConnectionAuth\n ): Promise<{ ok: true; auth: ConnectionAuth | undefined } | { ok: false; error: string }> {\n if (auth) {\n return { ok: true, auth };\n }\n\n const authResolver = this.#authResolvers[integration.id];\n\n if (!authResolver) {\n if (integration.authSource === \"HOSTED\") {\n return {\n ok: false,\n error: `Something went wrong: Integration ${integration.id} is missing auth credentials from Trigger.dev`,\n };\n }\n\n return {\n ok: true,\n auth: undefined,\n };\n }\n\n try {\n const resolvedAuth = await authResolver(ctx, integration);\n\n if (!resolvedAuth) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver returned null or undefined`,\n };\n }\n\n return {\n ok: true,\n auth:\n resolvedAuth.type === \"apiKey\"\n ? {\n type: \"apiKey\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n }\n : {\n type: \"oauth2\",\n accessToken: resolvedAuth.token,\n additionalFields: resolvedAuth.additionalFields,\n },\n };\n } catch (resolverError) {\n if (resolverError instanceof Error) {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw. ${resolverError.name}: ${resolverError.message}`,\n };\n } else if (typeof resolverError === \"string\") {\n return {\n ok: false,\n error: `Auth could not be resolved for ${integration.id}: auth resolver threw an error: ${resolverError}`,\n };\n }\n\n return {\n ok: false,\n error: `Auth could not be resolved for ${\n integration.id\n }: auth resolver threw an unknown error: ${JSON.stringify(resolverError)}`,\n };\n }\n }\n\n #buildJobsIndex(): IndexEndpointResponse[\"jobs\"] {\n return Object.values(this.#registeredJobs).map((job) => this.#buildJobIndex(job));\n }\n\n #buildJobIndex(job: Job<Trigger<any>, any>): IndexEndpointResponse[\"jobs\"][number] {\n const internal = job.options.__internal as JobMetadata[\"internal\"];\n\n return {\n id: job.id,\n name: job.name,\n version: job.version,\n event: job.trigger.event,\n trigger: job.trigger.toJSON(),\n integrations: this.#buildJobIntegrations(job),\n startPosition: \"latest\", // job is deprecated, leaving job for now to make sure newer clients work with older servers\n enabled: job.enabled,\n preprocessRuns: job.trigger.preprocessRuns,\n internal,\n };\n }\n\n #buildJobIntegrations(\n job: Job<Trigger<any>, Record<string, TriggerIntegration>>\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"] {\n return Object.keys(job.options.integrations ?? {}).reduce(\n (acc: Record<string, IntegrationConfig>, key) => {\n const integration = job.options.integrations![key];\n\n acc[key] = this.#buildJobIntegration(integration);\n\n return acc;\n },\n {}\n );\n }\n\n #buildJobIntegration(\n integration: TriggerIntegration\n ): IndexEndpointResponse[\"jobs\"][number][\"integrations\"][string] {\n const authSource = this.#authResolvers[integration.id] ? \"RESOLVER\" : integration.authSource;\n\n return {\n id: integration.id,\n metadata: integration.metadata,\n authSource,\n };\n }\n\n #logIOStats(stats: IOStats) {\n this.#internalLogger.debug(\"IO stats\", {\n stats,\n });\n }\n\n get #standardResponseHeaders() {\n return {\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n };\n }\n}\n\nfunction dynamicTriggerRegisterSourceJobId(id: string) {\n return `register-dynamic-trigger-${id}`;\n}\n\ntype Options = Record<string, string[]>;\n\nfunction deepMergeOptions(obj1: Options, obj2: Options): Options {\n const mergedOptions: Options = { ...obj1 };\n\n for (const key in obj2) {\n if (obj2.hasOwnProperty(key)) {\n if (key in mergedOptions) {\n mergedOptions[key] = [...mergedOptions[key], ...obj2[key]];\n } else {\n mergedOptions[key] = obj2[key];\n }\n }\n }\n\n return mergedOptions;\n}\n","import {\n ApiEventLog,\n ApiEventLogSchema,\n CompleteTaskBodyInput,\n ConnectionAuthSchema,\n FailTaskBodyInput,\n GetEventSchema,\n GetRunOptionsWithTaskDetails,\n GetRunSchema,\n GetRunsOptions,\n GetRunsSchema,\n LogLevel,\n Logger,\n RegisterScheduleResponseBodySchema,\n RegisterSourceEventSchemaV2,\n RegisterSourceEventV2,\n RunTaskBodyInput,\n ScheduleMetadata,\n SendEvent,\n SendEventOptions,\n ServerTaskSchema,\n TriggerSource,\n TriggerSourceSchema,\n UpdateTriggerSourceBodyV2,\n RegisterTriggerBodyV2,\n GetRunStatusesSchema,\n JobRunStatusRecordSchema,\n StatusUpdate,\n urlWithSearchParams,\n RunTaskResponseWithCachedTasksBodySchema,\n API_VERSIONS,\n} from \"@trigger.dev/core\";\n\nimport { z } from \"zod\";\n\nexport type ApiClientOptions = {\n apiKey?: string;\n apiUrl?: string;\n logLevel?: LogLevel;\n};\n\nexport type EndpointRecord = {\n id: string;\n name: string;\n url: string;\n};\n\nexport type HttpSourceRecord = {\n id: string;\n key: string;\n managed: boolean;\n url: string;\n status: \"PENDING\" | \"ACTIVE\" | \"INACTIVE\";\n secret?: string;\n data?: any;\n};\n\nexport type RunRecord = {\n id: string;\n jobId: string;\n callbackUrl: string;\n event: ApiEventLog;\n};\n\nexport class ApiClient {\n #apiUrl: string;\n #options: ApiClientOptions;\n #logger: Logger;\n\n constructor(options: ApiClientOptions) {\n this.#options = options;\n\n this.#apiUrl = this.#options.apiUrl ?? process.env.TRIGGER_API_URL ?? \"https://api.trigger.dev\";\n this.#logger = new Logger(\"trigger.dev\", this.#options.logLevel);\n }\n\n async registerEndpoint(options: { url: string; name: string }): Promise<EndpointRecord> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Registering endpoint\", {\n url: options.url,\n name: options.name,\n });\n\n const response = await fetch(`${this.#apiUrl}/api/v1/endpoints`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n url: options.url,\n name: options.name,\n }),\n });\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(`Failed to register entry point, got status code ${response.status}`);\n }\n\n return await response.json();\n }\n\n async runTask(\n runId: string,\n task: RunTaskBodyInput,\n options: { cachedTasksCursor?: string } = {}\n ) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Running Task\", {\n task,\n });\n\n return await zodfetchWithVersions(\n {\n [API_VERSIONS.LAZY_LOADED_CACHED_TASKS]: RunTaskResponseWithCachedTasksBodySchema,\n },\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Idempotency-Key\": task.idempotencyKey,\n \"X-Cached-Tasks-Cursor\": options.cachedTasksCursor ?? \"\",\n \"Trigger-Version\": API_VERSIONS.LAZY_LOADED_CACHED_TASKS,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async completeTask(runId: string, id: string, task: CompleteTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Complete Task\", {\n task,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/complete`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(task),\n }\n );\n }\n\n async failTask(runId: string, id: string, body: FailTaskBodyInput) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Fail Task\", {\n id,\n runId,\n body,\n });\n\n return await zodfetch(\n ServerTaskSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/tasks/${id}/fail`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n }\n );\n }\n\n async sendEvent(event: SendEvent, options: SendEventOptions = {}) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Sending event\", {\n event,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ event, options }),\n });\n }\n\n async cancelEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling event\", {\n eventId,\n });\n\n return await zodfetch(ApiEventLogSchema, `${this.#apiUrl}/api/v1/events/${eventId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async updateStatus(runId: string, id: string, status: StatusUpdate) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Update status\", {\n id,\n status,\n });\n\n return await zodfetch(\n JobRunStatusRecordSchema,\n `${this.#apiUrl}/api/v1/runs/${runId}/statuses/${id}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(status),\n }\n );\n }\n\n async updateSource(\n client: string,\n key: string,\n source: UpdateTriggerSourceBodyV2\n ): Promise<TriggerSource> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"activating http source\", {\n source,\n });\n\n const response = await zodfetch(\n TriggerSourceSchema,\n `${this.#apiUrl}/api/v2/${client}/sources/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(source),\n }\n );\n\n return response;\n }\n\n async registerTrigger(\n client: string,\n id: string,\n key: string,\n payload: RegisterTriggerBodyV2\n ): Promise<RegisterSourceEventV2> {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering trigger\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterSourceEventSchemaV2,\n `${this.#apiUrl}/api/v2/${client}/triggers/${id}/registrations/${key}`,\n {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n }\n );\n\n return response;\n }\n\n async registerSchedule(client: string, id: string, key: string, payload: ScheduleMetadata) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"registering schedule\", {\n id,\n payload,\n });\n\n const response = await zodfetch(\n RegisterScheduleResponseBodySchema,\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ id: key, ...payload }),\n }\n );\n\n return response;\n }\n\n async unregisterSchedule(client: string, id: string, key: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"unregistering schedule\", {\n id,\n });\n\n const response = await zodfetch(\n z.object({ ok: z.boolean() }),\n `${this.#apiUrl}/api/v1/${client}/schedules/${id}/registrations/${encodeURIComponent(key)}`,\n {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n\n return response;\n }\n\n async getAuth(client: string, id: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"getting auth\", {\n id,\n });\n\n const response = await zodfetch(\n ConnectionAuthSchema,\n `${this.#apiUrl}/api/v1/${client}/auth/${id}`,\n {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n },\n {\n optional: true,\n }\n );\n\n return response;\n }\n\n async getEvent(eventId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Event\", {\n eventId,\n });\n\n return await zodfetch(GetEventSchema, `${this.#apiUrl}/api/v1/events/${eventId}`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRun(runId: string, options?: GetRunOptionsWithTaskDetails) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run\", {\n runId,\n });\n\n return await zodfetch(\n GetRunSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/runs/${runId}`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async cancelRun(runId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Cancelling Run\", {\n runId,\n });\n\n return await zodfetch(GetRunSchema, `${this.#apiUrl}/api/v1/runs/${runId}/cancel`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRunStatuses(runId: string) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Run statuses\", {\n runId,\n });\n\n return await zodfetch(GetRunStatusesSchema, `${this.#apiUrl}/api/v1/runs/${runId}/statuses`, {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n });\n }\n\n async getRuns(jobSlug: string, options?: GetRunsOptions) {\n const apiKey = await this.#apiKey();\n\n this.#logger.debug(\"Getting Runs\", {\n jobSlug,\n });\n\n return await zodfetch(\n GetRunsSchema,\n urlWithSearchParams(`${this.#apiUrl}/api/v1/jobs/${jobSlug}/runs`, options),\n {\n method: \"GET\",\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n }\n );\n }\n\n async #apiKey() {\n const apiKey = getApiKey(this.#options.apiKey);\n\n if (apiKey.status === \"invalid\") {\n throw new Error(\"Invalid API key\");\n\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\"Trigger.dev error\")}: Invalid API key (\"${chalk.italic(\n // apiKey.apiKey\n // )}\"), please set the TRIGGER_API_KEY environment variable or pass the apiKey option to a valid value. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n } else if (apiKey.status === \"missing\") {\n throw new Error(\"Missing API key\");\n // const chalk = (await import(\"chalk\")).default;\n // const terminalLink = (await import(\"terminal-link\")).default;\n\n // throw new Error(\n // `${chalk.red(\n // \"Trigger.dev error\"\n // )}: Missing an API key, please set the TRIGGER_API_KEY environment variable or pass the apiKey option to the Trigger constructor. ${terminalLink(\n // \"Get your API key here\",\n // \"https://app.trigger.dev\",\n // {\n // fallback(text, url) {\n // return `${text} 👉 ${url}`;\n // },\n // }\n // )}`\n // );\n }\n\n return apiKey.apiKey;\n }\n}\n\nfunction getApiKey(key?: string) {\n const apiKey = key ?? process.env.TRIGGER_API_KEY;\n\n if (!apiKey) {\n return { status: \"missing\" as const };\n }\n\n // Validate the api_key format (should be tr_{env}_XXXXX)\n const isValid = apiKey.match(/^tr_[a-z]+_[a-zA-Z0-9]+$/);\n\n if (!isValid) {\n return { status: \"invalid\" as const, apiKey };\n }\n\n return { status: \"valid\" as const, apiKey };\n}\n\ntype VersionedResponseBodyMap = {\n [key: string]: z.ZodTypeAny;\n};\n\n// The resulting type should be a discriminating union\n// For example, if the TVersions param is { \"2023_09_29\": z.string() } and the TUnversioned param is z.number(), the resulting type should be:\n// type VersionedResponseBody = { version: \"2023_09_29\"; body: string } | { version: \"unversioned\"; body: number }\ntype VersionedResponseBody<\n TVersions extends VersionedResponseBodyMap,\n TUnversioned extends z.ZodTypeAny,\n> =\n | {\n [TVersion in keyof TVersions]: {\n version: TVersion;\n body: z.infer<TVersions[TVersion]>;\n };\n }[keyof TVersions]\n | {\n version: \"unversioned\";\n body: z.infer<TUnversioned>;\n };\n\nasync function zodfetchWithVersions<\n TVersionedResponseBodyMap extends VersionedResponseBodyMap,\n TUnversionedResponseBodySchema extends z.ZodTypeAny,\n TOptional extends boolean = false,\n>(\n versionedSchemaMap: TVersionedResponseBodyMap,\n unversionedSchema: TUnversionedResponseBodySchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<\n TOptional extends true\n ? VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema> | undefined\n : VersionedResponseBody<TVersionedResponseBodyMap, TUnversionedResponseBodySchema>\n> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n const version = response.headers.get(\"trigger-version\");\n\n if (!version) {\n return {\n version: \"unversioned\",\n body: unversionedSchema.parse(jsonBody),\n };\n }\n\n const versionedSchema = versionedSchemaMap[version];\n\n if (!versionedSchema) {\n throw new Error(`Unknown version ${version}`);\n }\n\n return {\n version,\n body: versionedSchema.parse(jsonBody),\n };\n}\n\nasync function zodfetch<TResponseSchema extends z.ZodTypeAny, TOptional extends boolean = false>(\n schema: TResponseSchema,\n url: string,\n requestInit?: RequestInit,\n options?: {\n errorMessage?: string;\n optional?: TOptional;\n }\n): Promise<\n TOptional extends true ? z.infer<TResponseSchema> | undefined : z.infer<TResponseSchema>\n> {\n const response = await fetch(url, requestInit);\n\n if (\n (!requestInit || requestInit.method === \"GET\") &&\n response.status === 404 &&\n options?.optional\n ) {\n // @ts-ignore\n return;\n }\n\n if (response.status >= 400 && response.status < 500) {\n const body = await response.json();\n\n throw new Error(body.error);\n }\n\n if (response.status !== 200) {\n throw new Error(\n options?.errorMessage ?? `Failed to fetch ${url}, got status code ${response.status}`\n );\n }\n\n const jsonBody = await response.json();\n\n return schema.parse(jsonBody);\n}\n","import { ErrorWithStack, SchemaError, ServerTask } from \"@trigger.dev/core\";\n\nexport class ResumeWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class RetryWithTaskError {\n constructor(\n public cause: ErrorWithStack,\n public task: ServerTask,\n public retryAt: Date\n ) {}\n}\n\nexport class CanceledWithTaskError {\n constructor(public task: ServerTask) {}\n}\n\nexport class YieldExecutionError {\n constructor(public key: string) {}\n}\n\nexport class ParsedPayloadSchemaError {\n constructor(public schemaErrors: SchemaError[]) {}\n}\n\n/** Use this function if you're using a `try/catch` block to catch errors.\n * It checks if a thrown error is a special internal error that you should ignore.\n * If this returns `true` then you must rethrow the error: `throw err;`\n * @param err The error to check\n * @returns `true` if the error is a Trigger Error, `false` otherwise.\n */\nexport function isTriggerError(\n err: unknown\n): err is ResumeWithTaskError | RetryWithTaskError | CanceledWithTaskError {\n return (\n err instanceof ResumeWithTaskError ||\n err instanceof RetryWithTaskError ||\n err instanceof CanceledWithTaskError ||\n err instanceof YieldExecutionError\n );\n}\n","import {\n API_VERSIONS,\n BloomFilter,\n CachedTask,\n ConnectionAuth,\n CronOptions,\n ErrorWithStackSchema,\n FetchRequestInit,\n FetchRetryOptions,\n InitialStatusUpdate,\n IntervalOptions,\n LogLevel,\n Logger,\n RunTaskOptions,\n SendEvent,\n SendEventOptions,\n SerializableJsonSchema,\n ServerTask,\n UpdateTriggerSourceBodyV2,\n supportsFeature,\n} from \"@trigger.dev/core\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { webcrypto } from \"node:crypto\";\nimport { ApiClient } from \"./apiClient\";\nimport {\n CanceledWithTaskError,\n ResumeWithTaskError,\n RetryWithTaskError,\n YieldExecutionError,\n isTriggerError,\n} from \"./errors\";\nimport { calculateRetryAt } from \"./retry\";\nimport { TriggerClient } from \"./triggerClient\";\nimport { DynamicTrigger } from \"./triggers/dynamic\";\nimport { ExternalSource, ExternalSourceParams } from \"./triggers/externalSource\";\nimport { DynamicSchedule } from \"./triggers/scheduled\";\nimport { EventSpecification, TaskLogger, TriggerContext } from \"./types\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { TriggerStatus } from \"./status\";\n\nexport type IOTask = ServerTask;\n\nexport type IOOptions = {\n id: string;\n apiClient: ApiClient;\n client: TriggerClient;\n context: TriggerContext;\n logger?: Logger;\n logLevel?: LogLevel;\n jobLogger?: Logger;\n jobLogLevel: LogLevel;\n cachedTasks?: Array<CachedTask>;\n cachedTasksCursor?: string;\n yieldedExecutions?: Array<string>;\n noopTasksSet?: string;\n serverVersion?: string | null;\n};\n\ntype JsonPrimitive = string | number | boolean | null | undefined | Date | symbol;\ntype JsonArray = Json[];\ntype JsonRecord<T> = { [Property in keyof T]: Json };\nexport type Json<T = any> = JsonPrimitive | JsonArray | JsonRecord<T>;\n\nexport type RunTaskErrorCallback = (\n error: unknown,\n task: IOTask,\n io: IO\n) =>\n | { retryAt?: Date; error?: Error; jitter?: number; skipRetrying?: boolean }\n | Error\n | undefined\n | void;\n\nexport type IOStats = {\n initialCachedTasks: number;\n lazyLoadedCachedTasks: number;\n executedTasks: number;\n cachedTaskHits: number;\n cachedTaskMisses: number;\n noopCachedTaskHits: number;\n noopCachedTaskMisses: number;\n};\n\nexport class IO {\n private _id: string;\n private _apiClient: ApiClient;\n private _triggerClient: TriggerClient;\n private _logger: Logger;\n private _jobLogger?: Logger;\n private _jobLogLevel: LogLevel;\n private _cachedTasks: Map<string, CachedTask>;\n private _taskStorage: AsyncLocalStorage<{ taskId: string }>;\n private _cachedTasksCursor?: string;\n private _context: TriggerContext;\n private _yieldedExecutions: Array<string>;\n private _noopTasksBloomFilter: BloomFilter | undefined;\n private _stats: IOStats;\n private _serverVersion: string;\n\n get stats() {\n return this._stats;\n }\n\n constructor(options: IOOptions) {\n this._id = options.id;\n this._apiClient = options.apiClient;\n this._triggerClient = options.client;\n this._logger = options.logger ?? new Logger(\"trigger.dev\", options.logLevel);\n this._cachedTasks = new Map();\n this._jobLogger = options.jobLogger;\n this._jobLogLevel = options.jobLogLevel;\n\n this._stats = {\n initialCachedTasks: 0,\n lazyLoadedCachedTasks: 0,\n executedTasks: 0,\n cachedTaskHits: 0,\n cachedTaskMisses: 0,\n noopCachedTaskHits: 0,\n noopCachedTaskMisses: 0,\n };\n\n if (options.cachedTasks) {\n options.cachedTasks.forEach((task) => {\n this._cachedTasks.set(task.idempotencyKey, task);\n });\n\n this._stats.initialCachedTasks = options.cachedTasks.length;\n }\n\n this._taskStorage = new AsyncLocalStorage();\n this._context = options.context;\n this._yieldedExecutions = options.yieldedExecutions ?? [];\n\n if (options.noopTasksSet) {\n this._noopTasksBloomFilter = BloomFilter.deserialize(\n options.noopTasksSet,\n BloomFilter.NOOP_TASK_SET_SIZE\n );\n }\n\n this._cachedTasksCursor = options.cachedTasksCursor;\n this._serverVersion = options.serverVersion ?? \"unversioned\";\n }\n\n /** @internal */\n get runId() {\n return this._id;\n }\n\n /** @internal */\n get triggerClient() {\n return this._triggerClient;\n }\n\n /** Used to send log messages to the [Run log](https://trigger.dev/docs/documentation/guides/viewing-runs). */\n get logger() {\n return new IOLogger(async (level, message, data) => {\n let logLevel: LogLevel = \"info\";\n\n if (Logger.satisfiesLogLevel(logLevel, this._jobLogLevel)) {\n await this.runTask(\n [message, level],\n async (task) => {\n switch (level) {\n case \"LOG\": {\n this._jobLogger?.log(message, data);\n logLevel = \"log\";\n break;\n }\n case \"DEBUG\": {\n this._jobLogger?.debug(message, data);\n logLevel = \"debug\";\n break;\n }\n case \"INFO\": {\n this._jobLogger?.info(message, data);\n logLevel = \"info\";\n break;\n }\n case \"WARN\": {\n this._jobLogger?.warn(message, data);\n logLevel = \"warn\";\n break;\n }\n case \"ERROR\": {\n this._jobLogger?.error(message, data);\n logLevel = \"error\";\n break;\n }\n }\n },\n {\n name: \"log\",\n icon: \"log\",\n description: message,\n params: data,\n properties: [{ label: \"Level\", text: level }],\n style: { style: \"minimal\", variant: level.toLowerCase() },\n noop: true,\n }\n );\n }\n });\n }\n\n /** `io.wait()` waits for the specified amount of time before continuing the Job. Delays work even if you're on a serverless platform with timeouts, or if your server goes down. They utilize [resumability](https://trigger.dev/docs/documentation/concepts/resumability) to ensure that the Run can be resumed after the delay.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param seconds The number of seconds to wait. This can be very long, serverless timeouts are not an issue.\n */\n async wait(key: string | any[], seconds: number) {\n return await this.runTask(key, async (task) => {}, {\n name: \"wait\",\n icon: \"clock\",\n params: { seconds },\n noop: true,\n delayUntil: new Date(Date.now() + seconds * 1000),\n style: { style: \"minimal\" },\n });\n }\n\n /** `io.createStatus()` allows you to set a status with associated data during the Run. Statuses can be used by your UI using the react package \n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param initialStatus The initial status you want this status to have. You can update it during the rub using the returned object.\n * @returns a TriggerStatus object that you can call `update()` on, to update the status.\n * @example \n * ```ts\n * client.defineJob(\n //...\n run: async (payload, io, ctx) => {\n const generatingImages = await io.createStatus(\"generating-images\", {\n label: \"Generating Images\",\n state: \"loading\",\n data: {\n progress: 0.1,\n },\n });\n\n //...do stuff\n\n await generatingImages.update(\"completed-generation\", {\n label: \"Generated images\",\n state: \"success\",\n data: {\n progress: 1.0,\n urls: [\"http://...\"]\n },\n });\n\n //...\n });\n * ```\n */\n async createStatus(\n key: IntegrationTaskKey,\n initialStatus: InitialStatusUpdate\n ): Promise<TriggerStatus> {\n const id = typeof key === \"string\" ? key : key.join(\"-\");\n const status = new TriggerStatus(id, this);\n await status.update(key, initialStatus);\n return status;\n }\n\n /** `io.backgroundFetch()` fetches data from a URL that can take longer that the serverless timeout. The actual `fetch` request is performed on the Trigger.dev platform, and the response is sent back to you.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param url The URL to fetch from.\n * @param requestInit The options for the request\n * @param retry The options for retrying the request if it fails\n * An object where the key is a status code pattern and the value is a retrying strategy.\n * Supported patterns are:\n * - Specific status codes: 429\n * - Ranges: 500-599\n * - Wildcards: 2xx, 3xx, 4xx, 5xx\n */\n async backgroundFetch<TResponseData>(\n key: string | any[],\n url: string,\n requestInit?: FetchRequestInit,\n retry?: FetchRetryOptions\n ): Promise<TResponseData> {\n const urlObject = new URL(url);\n\n return (await this.runTask(\n key,\n async (task) => {\n return task.output;\n },\n {\n name: `fetch ${urlObject.hostname}${urlObject.pathname}`,\n params: { url, requestInit, retry },\n operation: \"fetch\",\n icon: \"background\",\n noop: false,\n properties: [\n {\n label: \"url\",\n text: url,\n url,\n },\n {\n label: \"method\",\n text: requestInit?.method ?? \"GET\",\n },\n {\n label: \"background\",\n text: \"true\",\n },\n ],\n }\n )) as TResponseData;\n }\n\n /** `io.sendEvent()` allows you to send an event from inside a Job run. The sent even will trigger any Jobs that are listening for that event (based on the name).\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param event The event to send. The event name must match the name of the event that your Jobs are listening for.\n * @param options Options for sending the event.\n */\n async sendEvent(key: string | any[], event: SendEvent, options?: SendEventOptions) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.sendEvent(event, options);\n },\n {\n name: \"sendEvent\",\n params: { event, options },\n properties: [\n {\n label: \"name\",\n text: event.name,\n },\n ...(event?.id ? [{ label: \"ID\", text: event.id }] : []),\n ],\n }\n );\n }\n\n async getEvent(key: string | any[], id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.getEvent(id);\n },\n {\n name: \"getEvent\",\n params: { id },\n properties: [\n {\n label: \"id\",\n text: id,\n },\n ],\n }\n );\n }\n\n /** `io.cancelEvent()` allows you to cancel an event that was previously sent with `io.sendEvent()`. This will prevent any Jobs from running that are listening for that event if the event was sent with a delay\n * @param key\n * @param eventId\n * @returns\n */\n async cancelEvent(key: string | any[], eventId: string) {\n return await this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.cancelEvent(eventId);\n },\n {\n name: \"cancelEvent\",\n params: {\n eventId,\n },\n properties: [\n {\n label: \"id\",\n text: eventId,\n },\n ],\n }\n );\n }\n\n async updateSource(key: string | any[], options: { key: string } & UpdateTriggerSourceBodyV2) {\n return this.runTask(\n key,\n async (task) => {\n return await this._apiClient.updateSource(this._triggerClient.id, options.key, options);\n },\n {\n name: \"Update Source\",\n description: \"Update Source\",\n properties: [\n {\n label: \"key\",\n text: options.key,\n },\n ],\n params: options,\n redact: {\n paths: [\"secret\"],\n },\n }\n );\n }\n\n /** `io.registerInterval()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular interval.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @param options The options for the interval.\n * @returns A promise that has information about the interval.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerInterval(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: IntervalOptions\n ) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"interval\",\n options,\n });\n },\n {\n name: \"register-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"seconds\", text: options.seconds.toString() },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterInterval()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerInterval()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterInterval(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-interval\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerCron()` allows you to register a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that will trigger any jobs it's attached to on a regular CRON schedule.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to register a new schedule on.\n * @param id A unique id for the schedule. This is used to identify and unregister the schedule later.\n * @param options The options for the CRON schedule.\n * @deprecated Use `DynamicSchedule.register` instead.\n */\n async registerCron(\n key: string | any[],\n dynamicSchedule: DynamicSchedule,\n id: string,\n options: CronOptions\n ) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.register(id, {\n type: \"cron\",\n options,\n });\n },\n {\n name: \"register-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n { label: \"cron\", text: options.cron },\n ],\n params: options,\n }\n );\n }\n\n /** `io.unregisterCron()` allows you to unregister a [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) that was previously registered with `io.registerCron()`.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param dynamicSchedule The [DynamicSchedule](https://trigger.dev/docs/sdk/dynamicschedule) to unregister a schedule on.\n * @param id A unique id for the interval. This is used to identify and unregister the interval later.\n * @deprecated Use `DynamicSchedule.unregister` instead.\n */\n async unregisterCron(key: string | any[], dynamicSchedule: DynamicSchedule, id: string) {\n return await this.runTask(\n key,\n async (task) => {\n return dynamicSchedule.unregister(id);\n },\n {\n name: \"unregister-cron\",\n properties: [\n { label: \"schedule\", text: dynamicSchedule.id },\n { label: \"id\", text: id },\n ],\n }\n );\n }\n\n /** `io.registerTrigger()` allows you to register a [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) with the specified trigger params.\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param trigger The [DynamicTrigger](https://trigger.dev/docs/sdk/dynamictrigger) to register.\n * @param id A unique id for the trigger. This is used to identify and unregister the trigger later.\n * @param params The params for the trigger.\n * @deprecated Use `DynamicTrigger.register` instead.\n */\n async registerTrigger<\n TTrigger extends DynamicTrigger<EventSpecification<any>, ExternalSource<any, any, any>>,\n >(\n key: string | any[],\n trigger: TTrigger,\n id: string,\n params: ExternalSourceParams<TTrigger[\"source\"]>\n ): Promise<{ id: string; key: string } | undefined> {\n return await this.runTask(\n key,\n async (task) => {\n const registration = await this.runTask(\n \"register-source\",\n async (subtask1) => {\n return trigger.register(id, params);\n },\n {\n name: \"register-source\",\n }\n );\n\n return {\n id: registration.id,\n key: registration.source.key,\n };\n },\n {\n name: \"register-trigger\",\n properties: [\n { label: \"trigger\", text: trigger.id },\n { label: \"id\", text: id },\n ],\n params: params as any,\n }\n );\n }\n\n async getAuth(key: string | any[], clientId?: string): Promise<ConnectionAuth | undefined> {\n if (!clientId) {\n return;\n }\n\n return this.runTask(\n key,\n async (task) => {\n return await this._triggerClient.getAuth(clientId);\n },\n { name: \"get-auth\" }\n );\n }\n\n /** `io.runTask()` allows you to run a [Task](https://trigger.dev/docs/documentation/concepts/tasks) from inside a Job run. A Task is a resumable unit of a Run that can be retried, resumed and is logged. [Integrations](https://trigger.dev/docs/integrations) use Tasks internally to perform their actions.\n *\n * @param key Should be a stable and unique key inside the `run()`. See [resumability](https://trigger.dev/docs/documentation/concepts/resumability) for more information.\n * @param callback The callback that will be called when the Task is run. The callback receives the Task and the IO as parameters.\n * @param options The options of how you'd like to run and log the Task.\n * @param onError The callback that will be called when the Task fails. The callback receives the error, the Task and the IO as parameters. If you wish to retry then return an object with a `retryAt` property.\n * @returns A Promise that resolves with the returned value of the callback.\n */\n async runTask<T extends Json<T> | void>(\n key: string | any[],\n callback: (task: ServerTask, io: IO) => Promise<T>,\n options?: RunTaskOptions,\n onError?: RunTaskErrorCallback\n ): Promise<T> {\n const parentId = this._taskStorage.getStore()?.taskId;\n\n if (parentId) {\n this._logger.debug(\"Using parent task\", {\n parentId,\n key,\n options,\n });\n }\n\n const idempotencyKey = await generateIdempotencyKey([this._id, parentId ?? \"\", key].flat());\n\n const cachedTask = this._cachedTasks.get(idempotencyKey);\n\n if (cachedTask && cachedTask.status === \"COMPLETED\") {\n this._logger.debug(\"Using completed cached task\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskHits++;\n\n return cachedTask.output as T;\n }\n\n if (options?.noop && this._noopTasksBloomFilter) {\n if (this._noopTasksBloomFilter.test(idempotencyKey)) {\n this._logger.debug(\"task idempotency key exists in noopTasksBloomFilter\", {\n idempotencyKey,\n });\n\n this._stats.noopCachedTaskHits++;\n\n return {} as T;\n }\n }\n\n const response = await this._apiClient.runTask(\n this._id,\n {\n idempotencyKey,\n displayKey: typeof key === \"string\" ? key : undefined,\n noop: false,\n ...(options ?? {}),\n parentId,\n },\n {\n cachedTasksCursor: this._cachedTasksCursor,\n }\n );\n\n const task =\n response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS\n ? response.body.task\n : response.body;\n\n if (response.version === API_VERSIONS.LAZY_LOADED_CACHED_TASKS) {\n this._cachedTasksCursor = response.body.cachedTasks?.cursor;\n\n for (const cachedTask of response.body.cachedTasks?.tasks ?? []) {\n if (!this._cachedTasks.has(cachedTask.idempotencyKey)) {\n this._cachedTasks.set(cachedTask.idempotencyKey, cachedTask);\n\n this._logger.debug(\"Injecting lazy loaded task into task cache\", {\n idempotencyKey: cachedTask.idempotencyKey,\n });\n\n this._stats.lazyLoadedCachedTasks++;\n }\n }\n }\n\n if (task.status === \"CANCELED\") {\n this._logger.debug(\"Task canceled\", {\n idempotencyKey,\n task,\n });\n\n throw new CanceledWithTaskError(task);\n }\n\n if (task.status === \"COMPLETED\") {\n if (task.noop) {\n this._logger.debug(\"Noop Task completed\", {\n idempotencyKey,\n });\n\n this._noopTasksBloomFilter?.add(task.idempotencyKey);\n } else {\n this._logger.debug(\"Cache miss\", {\n idempotencyKey,\n });\n\n this._stats.cachedTaskMisses++;\n this.#addToCachedTasks(task);\n }\n\n return task.output as T;\n }\n\n if (task.status === \"ERRORED\") {\n this._logger.debug(\"Task errored\", {\n idempotencyKey,\n task,\n });\n\n throw new Error(task.error ?? task?.output ? JSON.stringify(task.output) : \"Task errored\");\n }\n\n const executeTask = async () => {\n try {\n const result = await callback(task, this);\n\n if (task.status === \"WAITING\" && task.callbackUrl) {\n this._logger.debug(\"Waiting for remote callback\", {\n idempotencyKey,\n task,\n });\n return {} as T;\n }\n\n const output = SerializableJsonSchema.parse(result) as T;\n\n this._logger.debug(\"Completing using output\", {\n idempotencyKey,\n task,\n });\n\n const completedTask = await this._apiClient.completeTask(this._id, task.id, {\n output: output ?? undefined,\n properties: task.outputProperties ?? undefined,\n });\n\n this._stats.executedTasks++;\n\n if (completedTask.status === \"CANCELED\") {\n throw new CanceledWithTaskError(completedTask);\n }\n\n return output;\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n let skipRetrying = false;\n\n if (onError) {\n try {\n const onErrorResult = onError(error, task, this);\n\n if (onErrorResult) {\n if (onErrorResult instanceof Error) {\n error = onErrorResult;\n } else {\n skipRetrying = !!onErrorResult.skipRetrying;\n\n if (onErrorResult.retryAt && !skipRetrying) {\n const parsedError = ErrorWithStackSchema.safeParse(onErrorResult.error);\n\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n onErrorResult.retryAt\n );\n }\n }\n }\n } catch (innerError) {\n if (isTriggerError(innerError)) {\n throw innerError;\n }\n\n error = innerError;\n }\n }\n\n const parsedError = ErrorWithStackSchema.safeParse(error);\n\n if (options?.retry && !skipRetrying) {\n const retryAt = calculateRetryAt(options.retry, task.attempts - 1);\n\n if (retryAt) {\n throw new RetryWithTaskError(\n parsedError.success ? parsedError.data : { message: \"Unknown error\" },\n task,\n retryAt\n );\n }\n }\n\n if (parsedError.success) {\n await this._apiClient.failTask(this._id, task.id, {\n error: parsedError.data,\n });\n } else {\n await this._apiClient.failTask(this._id, task.id, {\n error: { message: JSON.stringify(error), name: \"Unknown Error\" },\n });\n }\n\n throw error;\n }\n };\n\n if (task.status === \"WAITING\") {\n this._logger.debug(\"Task waiting\", {\n idempotencyKey,\n task,\n });\n\n if (task.callbackUrl) {\n await this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n throw new ResumeWithTaskError(task);\n }\n\n if (task.status === \"RUNNING\" && typeof task.operation === \"string\") {\n this._logger.debug(\"Task running operation\", {\n idempotencyKey,\n task,\n });\n\n throw new ResumeWithTaskError(task);\n }\n\n return this._taskStorage.run({ taskId: task.id }, executeTask);\n }\n\n /**\n * `io.yield()` allows you to yield execution of the current run and resume it in a new function execution. Similar to `io.wait()` but does not create a task and resumes execution immediately.\n */\n yield(key: string) {\n if (!supportsFeature(\"yieldExecution\", this._serverVersion)) {\n console.warn(\n \"[trigger.dev] io.yield() is not support by the version of the Trigger.dev server you are using, you will need to upgrade your self-hosted Trigger.dev instance.\"\n );\n\n return;\n }\n\n if (this._yieldedExecutions.includes(key)) {\n return;\n }\n\n throw new YieldExecutionError(key);\n }\n\n /**\n * `io.brb()` is an alias of `io.yield()`\n */\n brb = this.yield.bind(this);\n\n /** `io.try()` allows you to run Tasks and catch any errors that are thrown, it's similar to a normal `try/catch` block but works with [io.runTask()](/sdk/io/runtask).\n * A regular `try/catch` block on its own won't work as expected with Tasks. Internally `runTask()` throws some special errors to control flow execution. This is necessary to deal with resumability, serverless timeouts, and retrying Tasks.\n * @param tryCallback The code you wish to run\n * @param catchCallback Thhis will be called if the Task fails. The callback receives the error\n * @returns A Promise that resolves with the returned value or the error\n */\n async try<TResult, TCatchResult>(\n tryCallback: () => Promise<TResult>,\n catchCallback: (error: unknown) => Promise<TCatchResult>\n ): Promise<TResult | TCatchResult> {\n try {\n return await tryCallback();\n } catch (error) {\n if (isTriggerError(error)) {\n throw error;\n }\n\n return await catchCallback(error);\n }\n }\n\n #addToCachedTasks(task: ServerTask) {\n this._cachedTasks.set(task.idempotencyKey, task);\n }\n}\n\n// Generate a stable idempotency key for the key material, using a stable json stringification\nasync function generateIdempotencyKey(keyMaterial: any[]) {\n const keys = keyMaterial.map((key) => {\n if (typeof key === \"string\") {\n return key;\n }\n\n return stableStringify(key);\n });\n\n const key = keys.join(\":\");\n\n const hash = await webcrypto.subtle.digest(\"SHA-256\", Buffer.from(key));\n\n return Buffer.from(hash).toString(\"hex\");\n}\n\nfunction stableStringify(obj: any): string {\n function sortKeys(obj: any): any {\n if (typeof obj !== \"object\" || obj === null) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortKeys);\n }\n\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n\n for (const key of sortedKeys) {\n sortedObj[key] = sortKeys(obj[key]);\n }\n\n return sortedObj;\n }\n\n const sortedObj = sortKeys(obj);\n return JSON.stringify(sortedObj);\n}\n\ntype CallbackFunction = (\n level: \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"LOG\",\n message: string,\n properties?: Record<string, any>\n) => Promise<void>;\n\nexport class IOLogger implements TaskLogger {\n constructor(private callback: CallbackFunction) {}\n\n /** Log: essential messages */\n log(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"LOG\", message, properties);\n }\n\n /** For debugging: the least important log level */\n debug(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"DEBUG\", message, properties);\n }\n\n /** Info: the second least important log level */\n info(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"INFO\", message, properties);\n }\n\n /** Warnings: the third most important log level */\n warn(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"WARN\", message, properties);\n }\n\n /** Error: The second most important log level */\n error(message: string, properties?: Record<string, any>): Promise<void> {\n return this.callback(\"ERROR\", message, properties);\n }\n}\n","import type { RetryOptions } from \"@trigger.dev/core\";\nimport { calculateRetryAt } from \"@trigger.dev/core\";\n\nexport { calculateRetryAt };\nexport type { RetryOptions };\n\nexport const retry = {\n standardBackoff: {\n limit: 8,\n factor: 1.8,\n minTimeoutInMs: 500,\n maxTimeoutInMs: 30000,\n randomize: true,\n },\n} as const satisfies Record<string, RetryOptions>;\n","import { DisplayProperty, StatusUpdate } from \"@trigger.dev/core\";\nimport { IntegrationTaskKey } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport class TriggerStatus {\n constructor(\n private id: string,\n private io: IO\n ) {}\n\n async update(key: IntegrationTaskKey, status: StatusUpdate) {\n const properties: DisplayProperty[] = [];\n\n if (status.label) {\n properties.push({\n label: \"Label\",\n text: status.label,\n });\n }\n\n if (status.state) {\n properties.push({\n label: \"State\",\n text: status.state,\n });\n }\n\n return await this.io.runTask(\n key,\n async (task) => {\n return await this.io.triggerClient.updateStatus(this.io.runId, this.id, status);\n },\n {\n name: status.label ?? `Status update`,\n icon: \"bell\",\n params: {\n ...status,\n },\n properties,\n }\n );\n }\n}\n","import { ConnectionAuth } from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"./integrations\";\nimport { IO } from \"./io\";\n\nexport function createIOWithIntegrations<TIntegrations extends Record<string, TriggerIntegration>>(\n io: IO,\n auths?: Record<string, ConnectionAuth | undefined>,\n integrations?: TIntegrations\n): IOWithIntegrations<TIntegrations> {\n if (!integrations) {\n return io as IOWithIntegrations<TIntegrations>;\n }\n\n const connections = Object.entries(integrations).reduce(\n (acc, [connectionKey, integration]) => {\n let auth = auths?.[connectionKey];\n\n acc[connectionKey] = {\n integration,\n auth,\n };\n\n return acc;\n },\n {} as Record<\n string,\n {\n integration: TriggerIntegration;\n auth?: ConnectionAuth;\n }\n >\n );\n\n return new Proxy(io, {\n get(target, prop, receiver) {\n // We can return the original io back if the prop is __io\n if (prop === \"__io\") {\n return io;\n }\n\n if (typeof prop === \"string\" && prop in connections) {\n const { integration, auth } = connections[prop];\n return integration.cloneForRun(io, prop, auth);\n }\n\n const value = Reflect.get(target, prop, receiver);\n return typeof value == \"function\" ? value.bind(target) : value;\n },\n }) as IOWithIntegrations<TIntegrations>;\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport class TypedAsyncLocalStorage<T> {\n private storage: AsyncLocalStorage<T>;\n\n constructor() {\n this.storage = new AsyncLocalStorage<T>();\n }\n\n runWith<R extends (...args: any[]) => Promise<any>>(context: T, fn: R): Promise<ReturnType<R>> {\n return this.storage.run(context, fn);\n }\n\n getStore(): T | undefined {\n return this.storage.getStore();\n }\n}\n","import { IO } from \"./io\";\nimport { TriggerContext } from \"./types\";\nimport { TypedAsyncLocalStorage } from \"./utils/typedAsyncLocalStorage\";\n\nexport type RunStore = {\n io: IO;\n ctx: TriggerContext;\n};\n\nexport const runLocalStorage = new TypedAsyncLocalStorage<RunStore>();\n","import {\n RegisterSourceEventV2,\n RegisterTriggerBodyV2,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { ExternalSource, ExternalSourceParams } from \"./externalSource\";\nimport { runLocalStorage } from \"../runLocalStorage\";\nimport { EventFilter } from \"@trigger.dev/core\";\n\n/** Options for a DynamicTrigger */\nexport type DynamicTriggerOptions<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> = {\n /** Used to uniquely identify a DynamicTrigger */\n id: string;\n /** An event from an [Integration](https://trigger.dev/docs/integrations) package that you want to attach to the DynamicTrigger. The event types will come through to the payload in your Job's run. */\n event: TEventSpec;\n /** An external source fron an [Integration](https://trigger.dev/docs/integrations) package\n * @example \n * ```ts\n * import { events } from \"@trigger.dev/github\";\n * \n * const dynamicOnIssueOpened = client.defineDynamicTrigger({\n id: \"github-issue-opened\",\n event: events.onIssueOpened,\n source: github.sources.repo,\n });\n * ```\n */\n source: TExternalSource;\n};\n\n/** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime. */\nexport class DynamicTrigger<\n TEventSpec extends EventSpecification<any>,\n TExternalSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpec>\n{\n #client: TriggerClient;\n #options: DynamicTriggerOptions<TEventSpec, TExternalSource>;\n source: TExternalSource;\n\n /** `DynamicTrigger` allows you to define a trigger that can be configured dynamically at runtime.\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the dynamic trigger.\n * */\n constructor(client: TriggerClient, options: DynamicTriggerOptions<TEventSpec, TExternalSource>) {\n this.#client = client;\n this.#options = options;\n this.source = options.source;\n\n client.attachDynamicTrigger(this);\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.#options.id,\n };\n }\n\n get id() {\n return this.#options.id;\n }\n\n get event() {\n return this.#options.event;\n }\n\n // @internal\n registeredTriggerForParams(\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): RegisterTriggerBodyV2 {\n const key = slugifyId(this.source.key(params));\n\n return {\n rule: {\n event: this.event.name,\n source: this.event.source,\n payload: deepMergeFilters(\n this.source.filter(params),\n this.event.filter ?? {},\n options.filter ?? {}\n ),\n },\n source: {\n version: \"2\",\n key,\n channel: this.source.channel,\n params,\n //todo add other options here\n options: {\n event: typeof this.event.name === \"string\" ? [this.event.name] : this.event.name,\n },\n integration: {\n id: this.source.integration.id,\n metadata: this.source.integration.metadata,\n authSource: this.source.integration.authSource,\n },\n },\n accountId: options.accountId,\n };\n }\n\n /** Use this method to register a new configuration with the DynamicTrigger.\n * @param key The key for the configuration. This will be used to identify the configuration when it is triggered.\n * @param params The params for the configuration.\n * @param options Options for the configuration.\n * @param options.accountId The accountId to associate with the configuration.\n * @param options.filter The filter to use for the configuration.\n *\n */\n async register(\n key: string,\n params: ExternalSourceParams<TExternalSource>,\n options: { accountId?: string; filter?: EventFilter } = {}\n ): Promise<RegisterSourceEventV2> {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options)\n );\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.#client.registerTrigger(\n this.id,\n key,\n this.registeredTriggerForParams(params, options)\n );\n },\n {\n name: \"Register Dynamic Trigger\",\n properties: [\n { label: \"Dynamic Trigger ID\", text: this.id },\n { label: \"ID\", text: key },\n ],\n params: params as any,\n }\n );\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpec>, any>): void {\n triggerClient.attachJobToDynamicTrigger(job, this);\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n","import { EventFilter, TriggerMetadata, deepMergeFilters } from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, EventSpecificationExample, SchemaParser, Trigger } from \"../types\";\nimport { formatSchemaErrors } from \"../utils/formatSchemaErrors\";\nimport { ParsedPayloadSchemaError } from \"../errors\";\n\ntype EventTriggerOptions<TEventSpecification extends EventSpecification<any>> = {\n event: TEventSpecification;\n name?: string | string[];\n source?: string;\n filter?: EventFilter;\n};\n\nexport class EventTrigger<TEventSpecification extends EventSpecification<any>>\n implements Trigger<TEventSpecification>\n{\n #options: EventTriggerOptions<TEventSpecification>;\n\n constructor(options: EventTriggerOptions<TEventSpecification>) {\n this.#options = options;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.#options.name ?? this.#options.event.title,\n rule: {\n event: this.#options.name ?? this.#options.event.name,\n source: this.#options.source ?? \"trigger.dev\",\n payload: deepMergeFilters(this.#options.filter ?? {}, this.#options.event.filter ?? {}),\n },\n };\n }\n\n get event() {\n return this.#options.event;\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>): void {}\n\n get preprocessRuns() {\n return false;\n }\n}\n\n/** Configuration options for an EventTrigger */\ntype TriggerOptions<TEvent> = {\n /** The name of the event you are subscribing to. Must be an exact match (case sensitive). To trigger on multiple possible events, pass in an array of event names */\n name: string | string[];\n /** A [Zod](https://trigger.dev/docs/documentation/guides/zod) schema that defines the shape of the event payload.\n * The default is `z.any()` which is `any`.\n * */\n schema?: SchemaParser<TEvent>;\n /** You can use this to filter events based on the source. */\n source?: string;\n /** Used to filter which events trigger the Job\n * @example\n * filter:\n * ```ts\n * {\n * name: [\"John\", \"Jane\"],\n * age: [18, 21]\n * }\n * ```\n *\n * This filter would match against an event with the following data:\n * ```json\n * {\n * \"name\": \"Jane\",\n * \"age\": 18,\n * \"location\": \"San Francisco\"\n * }\n * ```\n */\n filter?: EventFilter;\n\n examples?: EventSpecificationExample[];\n};\n\n/** `eventTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to subscribe to an event a Job from [a sent event](https://trigger.dev/docs/sdk/triggerclient/instancemethods/sendevent)\n * @param options options for the EventTrigger\n */\nexport function eventTrigger<TEvent extends any = any>(\n options: TriggerOptions<TEvent>\n): Trigger<EventSpecification<TEvent>> {\n return new EventTrigger({\n name: options.name,\n filter: options.filter,\n event: {\n name: options.name,\n title: \"Event\",\n source: options.source ?? \"trigger.dev\",\n icon: \"custom-event\",\n examples: options.examples,\n parsePayload: (rawPayload: any) => {\n if (options.schema) {\n const results = options.schema.safeParse(rawPayload);\n\n if (!results.success) {\n throw new ParsedPayloadSchemaError(formatSchemaErrors(results.error.issues));\n }\n\n return results.data;\n }\n\n return rawPayload as any;\n },\n },\n });\n}\n","import type { SchemaError } from \"@trigger.dev/core\";\nimport { SchemaParserIssue } from \"../types\";\n\nexport function formatSchemaErrors(errors: SchemaParserIssue[]): SchemaError[] {\n return errors.map((error) => {\n const { path, message } = error;\n return { path: path.map(String), message };\n });\n}\n","import {\n CronOptions,\n IntervalOptions,\n ScheduleMetadata,\n ScheduledPayload,\n ScheduledPayloadSchema,\n TriggerMetadata,\n currentDate,\n} from \"@trigger.dev/core\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\nimport cronstrue from \"cronstrue\";\nimport { runLocalStorage } from \"../runLocalStorage\";\n\ntype ScheduledEventSpecification = EventSpecification<ScheduledPayload>;\n\nconst examples = [\n {\n id: \"now\",\n name: \"Now\",\n icon: \"clock\",\n payload: {\n ts: currentDate.marker,\n lastTimestamp: currentDate.marker,\n },\n },\n];\n\nexport class IntervalTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: IntervalOptions) {}\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-interval\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"Interval\",\n text: `${this.options.seconds}s`,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"interval\",\n options: {\n seconds: this.options.seconds,\n },\n },\n };\n }\n}\n\n/** `intervalTrigger()` is set as a [Job's trigger](/sdk/job) to trigger a Job at a recurring interval.\n * @param options An object containing options about the interval.\n */\nexport function intervalTrigger(options: IntervalOptions) {\n return new IntervalTrigger(options);\n}\n\nexport class CronTrigger implements Trigger<ScheduledEventSpecification> {\n constructor(private options: CronOptions) {}\n\n get event() {\n const humanReadable = cronstrue.toString(this.options.cron, {\n throwExceptionOnParseError: false,\n });\n\n return {\n name: \"trigger.scheduled\",\n title: \"Cron Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-cron\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n properties: [\n {\n label: \"cron\",\n text: this.options.cron,\n },\n {\n label: \"Schedule\",\n text: humanReadable,\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"scheduled\",\n schedule: {\n type: \"cron\",\n options: {\n cron: this.options.cron,\n },\n },\n };\n }\n}\n\n/** `cronTrigger()` is set as a [Job's trigger](https://trigger.dev/docs/sdk/job) to trigger a Job on a recurring schedule using a CRON expression.\n * @param options An object containing options about the CRON schedule.\n */\nexport function cronTrigger(options: CronOptions) {\n return new CronTrigger(options);\n}\n\n/** DynamicSchedule options\n * @param id Used to uniquely identify a DynamicSchedule\n */\nexport type DynamicIntervalOptions = { id: string };\n\n/** DynamicSchedule` allows you to define a scheduled trigger that can be configured dynamically at runtime. */\nexport class DynamicSchedule implements Trigger<ScheduledEventSpecification> {\n /**\n * @param client The `TriggerClient` instance to use for registering the trigger.\n * @param options The options for the schedule.\n */\n constructor(\n private client: TriggerClient,\n private options: DynamicIntervalOptions\n ) {\n client.attachDynamicSchedule(this.options.id);\n }\n\n get id() {\n return this.options.id;\n }\n\n get event() {\n return {\n name: \"trigger.scheduled\",\n title: \"Dynamic Schedule\",\n source: \"trigger.dev\",\n icon: \"schedule-dynamic\",\n examples,\n parsePayload: ScheduledPayloadSchema.parse,\n };\n }\n\n async register(key: string, metadata: ScheduleMetadata) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.registerSchedule(this.id, key, metadata);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"register\"],\n async (task) => {\n return this.client.registerSchedule(this.id, key, metadata);\n },\n {\n name: \"Register Schedule\",\n icon: metadata.type === \"cron\" ? \"schedule-cron\" : \"schedule-interval\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n params: metadata,\n }\n );\n }\n\n async unregister(key: string) {\n const runStore = runLocalStorage.getStore();\n\n if (!runStore) {\n return this.client.unregisterSchedule(this.id, key);\n }\n\n const { io } = runStore;\n\n return await io.runTask(\n [key, \"unregister\"],\n async (task) => {\n return this.client.unregisterSchedule(this.id, key);\n },\n {\n name: \"Unregister Schedule\",\n icon: \"schedule\",\n properties: [\n { label: \"Dynamic Schedule\", text: this.id },\n { label: \"Schedule ID\", text: key },\n ],\n }\n );\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<ScheduledEventSpecification>, any>\n ): void {\n triggerClient.attachDynamicScheduleToJob(this.options.id, job);\n }\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"dynamic\",\n id: this.options.id,\n };\n }\n}\n","import {\n DisplayProperty,\n EventFilter,\n HandleTriggerSource,\n HttpSourceResponseMetadata,\n Logger,\n NormalizedResponse,\n RegisterTriggerSource,\n SendEvent,\n TriggerMetadata,\n deepMergeFilters,\n} from \"@trigger.dev/core\";\nimport { IOWithIntegrations, TriggerIntegration } from \"../integrations\";\nimport { IO } from \"../io\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport type { EventSpecification, SchemaParser, Trigger, TriggerContext } from \"../types\";\nimport { slugifyId } from \"../utils\";\nimport { SerializableJson } from \"@trigger.dev/core\";\nimport { ConnectionAuth } from \"@trigger.dev/core\";\nimport { Prettify } from \"@trigger.dev/core\";\n\nexport type HttpSourceEvent = {\n url: string;\n method: string;\n headers: Record<string, string>;\n rawBody?: Buffer | null;\n};\n\ntype SmtpSourceEvent = {\n from: string;\n to: string;\n subject: string;\n body: string;\n};\n\ntype SqsSourceEvent = {\n body: string;\n};\n\ntype ExternalSourceChannelMap = {\n HTTP: {\n event: Request;\n register: {\n url: string;\n };\n };\n SMTP: {\n event: SmtpSourceEvent;\n register: {};\n };\n SQS: {\n event: SqsSourceEvent;\n register: {};\n };\n};\n\ntype ChannelNames = keyof ExternalSourceChannelMap;\n\ntype TriggerOptionDiff = {\n desired: string[];\n missing: string[];\n orphaned: string[];\n};\n\ntype TriggerOptionDiffs<TTriggerOptionDefinitions extends Record<string, string[]> = any> =\n TriggerOptionsRecordWithEvent<TriggerOptionDiff, TTriggerOptionDefinitions>;\n\ntype TriggerOptionsRecordWithEvent<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]>,\n> = {\n event: TValue;\n} & TriggerOptionRecord<TValue, TTriggerOptionDefinitions>;\n\nexport type TriggerOptionRecord<\n TValue,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n [K in keyof TTriggerOptionDefinitions]: TValue;\n};\n\ntype RegisterFunctionEvent<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n source: {\n active: boolean;\n data?: any;\n secret: string;\n } & ExternalSourceChannelMap[TChannel][\"register\"];\n params: TParams;\n};\n\ntype RegisterSourceEvent<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n id: string;\n source: RegisterTriggerSource;\n dynamicTriggerId?: string;\n options: TriggerOptionDiffs<TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunctionOutput<TTriggerOptionDefinitions extends Record<string, string[]> = any> = {\n secret?: string;\n data?: SerializableJson;\n options: TriggerOptionsRecordWithEvent<string[], TTriggerOptionDefinitions>;\n};\n\ntype RegisterFunction<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (\n event: RegisterFunctionEvent<TChannel, TParams, TTriggerOptionDefinitions>,\n io: IOWithIntegrations<{ integration: TIntegration }>,\n ctx: TriggerContext\n) => Promise<RegisterFunctionOutput<TTriggerOptionDefinitions> | undefined>;\n\nexport type HandlerEvent<TChannel extends ChannelNames, TParams extends any = any> = {\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"];\n source: Prettify<Omit<HandleTriggerSource, \"params\"> & { params: TParams }>;\n};\n\ntype HandlerFunction<\n TChannel extends ChannelNames,\n TParams extends any,\n TTriggerIntegration extends TriggerIntegration,\n> = (\n event: HandlerEvent<TChannel, TParams>,\n logger: Logger,\n integration: TTriggerIntegration,\n auth?: ConnectionAuth\n) => Promise<{\n events: SendEvent[];\n response?: NormalizedResponse;\n metadata?: HttpSourceResponseMetadata;\n} | void>;\n\ntype KeyFunction<TParams extends any> = (params: TParams) => string;\ntype FilterFunction<\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = (params: TParams, options?: TTriggerOptionDefinitions) => EventFilter;\n\ntype ExternalSourceOptions<\n TChannel extends ChannelNames,\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n id: string;\n version: string;\n schema: SchemaParser<TParams>;\n optionSchema?: SchemaParser<TTriggerOptionDefinitions>;\n integration: TIntegration;\n register: RegisterFunction<TIntegration, TParams, TChannel, TTriggerOptionDefinitions>;\n filter?: FilterFunction<TParams, TTriggerOptionDefinitions>;\n handler: HandlerFunction<TChannel, TParams, TIntegration>;\n key: KeyFunction<TParams>;\n properties?: (params: TParams) => DisplayProperty[];\n};\n\nexport class ExternalSource<\n TIntegration extends TriggerIntegration,\n TParams extends any,\n TChannel extends ChannelNames = ChannelNames,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> {\n channel: TChannel;\n\n constructor(\n channel: TChannel,\n private options: ExternalSourceOptions<\n TChannel,\n TIntegration,\n TParams,\n TTriggerOptionDefinitions\n >\n ) {\n this.channel = channel;\n }\n\n async handle(\n source: HandleTriggerSource,\n rawEvent: ExternalSourceChannelMap[TChannel][\"event\"],\n logger: Logger\n ) {\n return this.options.handler(\n {\n source: { ...source, params: source.params as TParams },\n rawEvent,\n },\n logger,\n this.options.integration\n );\n }\n\n filter(params: TParams, options?: TTriggerOptionDefinitions): EventFilter {\n return this.options.filter?.(params, options) ?? {};\n }\n\n properties(params: TParams): DisplayProperty[] {\n return this.options.properties?.(params) ?? [];\n }\n\n async register(\n params: TParams,\n registerEvent: RegisterSourceEvent<TTriggerOptionDefinitions>,\n io: IO,\n ctx: TriggerContext\n ) {\n const { result: event, ommited: source } = omit(registerEvent, \"source\");\n const { result: sourceWithoutChannel, ommited: channel } = omit(source, \"channel\");\n const { result: channelWithoutType } = omit(channel, \"type\");\n\n const updates = await this.options.register(\n {\n ...event,\n source: { ...sourceWithoutChannel, ...channelWithoutType },\n params,\n },\n io as IOWithIntegrations<{ integration: TIntegration }>,\n ctx\n );\n\n return updates;\n }\n\n key(params: TParams): string {\n const parts = [this.options.id, this.channel];\n\n parts.push(this.options.key(params));\n parts.push(this.integration.id);\n\n return parts.join(\"-\");\n }\n\n get integration() {\n return this.options.integration;\n }\n\n get integrationConfig() {\n return {\n id: this.integration.id,\n metadata: this.integration.metadata,\n };\n }\n\n get id() {\n return this.options.id;\n }\n\n get version() {\n return this.options.version;\n }\n}\n\nexport type ExternalSourceParams<TExternalSource extends ExternalSource<any, any, any>> =\n TExternalSource extends ExternalSource<any, infer TParams, any> ? TParams : never;\n\nexport type ExternalSourceTriggerOptions<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n TTriggerOptionDefinitions extends Record<string, string[]> = any,\n> = {\n event: TEventSpecification;\n source: TEventSource;\n params: ExternalSourceParams<TEventSource>;\n options: TriggerOptionRecord<string[], TTriggerOptionDefinitions>;\n};\n\nexport class ExternalSourceTrigger<\n TEventSpecification extends EventSpecification<any>,\n TEventSource extends ExternalSource<any, any, any>,\n> implements Trigger<TEventSpecification>\n{\n constructor(private options: ExternalSourceTriggerOptions<TEventSpecification, TEventSource>) {}\n\n get event() {\n return this.options.event;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: \"External Source\",\n rule: {\n event: this.event.name,\n payload: deepMergeFilters(\n this.options.source.filter(this.options.params, this.options.options),\n this.event.filter ?? {},\n this.options.params.filter ?? {}\n ),\n source: this.event.source,\n },\n properties: this.options.source.properties(this.options.params),\n };\n }\n\n attachToJob(triggerClient: TriggerClient, job: Job<Trigger<TEventSpecification>, any>) {\n triggerClient.attachSource({\n key: slugifyId(this.options.source.key(this.options.params)),\n source: this.options.source,\n event: this.options.event,\n params: this.options.params,\n options: this.options.options,\n });\n }\n\n get preprocessRuns() {\n return true;\n }\n}\n\nexport function omit<T extends Record<string, unknown>, K extends keyof T>(\n obj: T,\n key: K\n): { result: Omit<T, K>; ommited: T[K] } {\n const result: any = {};\n\n for (const k of Object.keys(obj)) {\n if (k === key) continue;\n\n result[k] = obj[k];\n }\n\n return { result, ommited: obj[key] };\n}\n","import {\n MISSING_CONNECTION_NOTIFICATION,\n MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n MissingConnectionNotificationPayload,\n MissingConnectionNotificationPayloadSchema,\n MissingConnectionResolvedNotificationPayload,\n MissingConnectionResolvedNotificationPayloadSchema,\n TriggerMetadata,\n} from \"@trigger.dev/core\";\nimport { TriggerIntegration } from \"../integrations\";\nimport { Job } from \"../job\";\nimport { TriggerClient } from \"../triggerClient\";\nimport { EventSpecification, Trigger } from \"../types\";\n\nexport function missingConnectionNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionNotification({ integrations });\n}\n\nexport function missingConnectionResolvedNotification(integrations: Array<TriggerIntegration>) {\n return new MissingConnectionResolvedNotification({ integrations });\n}\n\ntype MissingConnectionNotificationSpecification =\n EventSpecification<MissingConnectionNotificationPayload>;\n\ntype MissingConnectionNotificationOptions = {\n integrations: Array<TriggerIntegration>;\n};\n\nexport class MissingConnectionNotification\n implements Trigger<MissingConnectionNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_NOTIFICATION,\n title: \"Missing Connection Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n\ntype MissingConnectionResolvedNotificationSpecification =\n EventSpecification<MissingConnectionResolvedNotificationPayload>;\n\nexport class MissingConnectionResolvedNotification\n implements Trigger<MissingConnectionResolvedNotificationSpecification>\n{\n constructor(private options: MissingConnectionNotificationOptions) {}\n\n get event() {\n return {\n name: MISSING_CONNECTION_RESOLVED_NOTIFICATION,\n title: \"Missing Connection Resolved Notification\",\n source: \"trigger.dev\",\n icon: \"connection-alert\",\n parsePayload: MissingConnectionResolvedNotificationPayloadSchema.parse,\n properties: [\n {\n label: \"Integrations\",\n text: this.options.integrations.map((i) => i.id).join(\", \"),\n },\n ],\n };\n }\n\n attachToJob(\n triggerClient: TriggerClient,\n job: Job<Trigger<MissingConnectionResolvedNotificationSpecification>, any>\n ): void {}\n\n get preprocessRuns() {\n return false;\n }\n\n toJSON(): TriggerMetadata {\n return {\n type: \"static\",\n title: this.event.title,\n rule: {\n event: this.event.name,\n source: \"trigger.dev\",\n payload: {\n client: {\n id: this.options.integrations.map((i) => i.id),\n },\n },\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAO,SAASA,UAAUC,OAAuB;AAE/C,QAAMC,wBAAwBD,MAAME,YAAW,EAAGC,QAAQ,QAAQ,GAAA;AAGlE,QAAMC,wBAAwBH,sBAAsBE,QAAQ,qBAAqB,EAAA;AAEjF,SAAOC;AACT;AARgBL;;;ACIhB;AAsEO,IAAMM,MAAN,MAAMA;EAQXC,YAGEC,QACAC,SACA;AAqEF;AApEE,SAAKD,SAASA;AACd,SAAKC,UAAUA;AACf,0BAAK,wBAAL;AAEAD,WAAOE,OAAO,IAAI;EACpB;EAEA,IAAIC,KAAK;AACP,WAAOC,UAAU,KAAKH,QAAQE,EAAE;EAClC;EAEA,IAAIE,UAAU;AACZ,WAAO,OAAO,KAAKJ,QAAQI,YAAY,YAAY,KAAKJ,QAAQI,UAAU;EAC5E;EAEA,IAAIC,OAAO;AACT,WAAO,KAAKL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,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CanB;AAkDN,IAAME,wCAAN,MAAMA;EAGXC,YAAoBC,SAA+C;mBAA/CA;EAAgD;EAEpE,IAAIC,QAAQ;AACV,WAAO;MACLC,MAAMwB;MACNtB,OAAO;MACPC,QAAQ;MACRC,MAAM;MACNC,cAAcoB,gEAAmDlB;MACjEC,YAAY;QACV;UACEC,OAAO;UACPC,MAAM,KAAKZ,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE,EAAEC,KAAK,IAAA;QACxD;;IAEJ;EACF;EAEAC,YACEC,eACAC,KACM;EAAC;EAET,IAAIC,iBAAiB;AACnB,WAAO;EACT;EAEAC,SAA0B;AACxB,WAAO;MACLC,MAAM;MACNlB,OAAO,KAAKH,MAAMG;MAClBmB,MAAM;QACJtB,OAAO,KAAKA,MAAMC;QAClBG,QAAQ;QACRmB,SAAS;UACPC,QAAQ;YACNV,IAAI,KAAKf,QAAQL,aAAakB,IAAI,CAACC,MAAMA,EAAEC,EAAE;UAC/C;QACF;MACF;IACF;EACF;AACF;AA7CajB;;;AjB7CN,SAAS8B,aACdC,YACGC,gBACW;AACd,SAAO;IACLC,kBAAkB;IAClBF,SAASA,QAAQG;IACjBF;EACF;AACF;AATgBF;","names":["slugifyId","input","replaceSpacesWithDash","toLowerCase","replace","removeNonUrlSafeChars","Job","constructor","client","options","attach","id","slugifyId","enabled","name","trigger","version","logLevel","integrations","Object","keys","reduce","acc","key","integration","metadata","authSource","toJSON","internal","__internal","event","startPosition","preprocessRuns","match","Error","import_core","ApiClient","constructor","options","apiUrl","process","env","TRIGGER_API_URL","Logger","logLevel","registerEndpoint","apiKey","debug","url","name","response","fetch","method","headers","Authorization","body","JSON","stringify","status","json","Error","error","runTask","runId","task","zodfetchWithVersions","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","RunTaskResponseWithCachedTasksBodySchema","ServerTaskSchema","idempotencyKey","cachedTasksCursor","completeTask","id","zodfetch","failTask","sendEvent","event","ApiEventLogSchema","cancelEvent","eventId","updateStatus","JobRunStatusRecordSchema","updateSource","client","key","source","TriggerSourceSchema","registerTrigger","payload","RegisterSourceEventSchemaV2","registerSchedule","RegisterScheduleResponseBodySchema","unregisterSchedule","z","object","ok","boolean","encodeURIComponent","getAuth","ConnectionAuthSchema","Accept","optional","getEvent","GetEventSchema","getRun","GetRunSchema","urlWithSearchParams","cancelRun","getRunStatuses","GetRunStatusesSchema","getRuns","jobSlug","GetRunsSchema","getApiKey","TRIGGER_API_KEY","isValid","match","versionedSchemaMap","unversionedSchema","requestInit","errorMessage","jsonBody","version","get","parse","versionedSchema","schema","ResumeWithTaskError","constructor","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","YieldExecutionError","key","ParsedPayloadSchemaError","schemaErrors","isTriggerError","err","import_core","import_core","retry","standardBackoff","limit","factor","minTimeoutInMs","maxTimeoutInMs","randomize","TriggerStatus","constructor","id","io","update","key","status","properties","label","push","text","state","runTask","task","triggerClient","updateStatus","runId","name","icon","params","IO","constructor","options","brb","yield","bind","_id","id","_apiClient","apiClient","_triggerClient","client","_logger","logger","Logger","logLevel","_cachedTasks","Map","_jobLogger","jobLogger","_jobLogLevel","jobLogLevel","_stats","initialCachedTasks","lazyLoadedCachedTasks","executedTasks","cachedTaskHits","cachedTaskMisses","noopCachedTaskHits","noopCachedTaskMisses","cachedTasks","forEach","task","set","idempotencyKey","length","_taskStorage","AsyncLocalStorage","_context","context","_yieldedExecutions","yieldedExecutions","noopTasksSet","_noopTasksBloomFilter","BloomFilter","deserialize","NOOP_TASK_SET_SIZE","_cachedTasksCursor","cachedTasksCursor","_serverVersion","serverVersion","stats","runId","triggerClient","IOLogger","level","message","data","satisfiesLogLevel","runTask","log","debug","info","warn","error","name","icon","description","params","properties","label","text","style","variant","toLowerCase","noop","wait","key","seconds","delayUntil","Date","now","createStatus","initialStatus","join","status","TriggerStatus","update","backgroundFetch","url","requestInit","retry","urlObject","URL","output","hostname","pathname","operation","method","sendEvent","event","getEvent","cancelEvent","eventId","updateSource","redact","paths","registerInterval","dynamicSchedule","register","type","toString","unregisterInterval","unregister","registerCron","cron","unregisterCron","registerTrigger","trigger","registration","subtask1","source","getAuth","clientId","callback","onError","parentId","getStore","taskId","generateIdempotencyKey","flat","cachedTask","get","test","response","displayKey","undefined","version","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","body","cursor","tasks","has","CanceledWithTaskError","add","Error","JSON","stringify","executeTask","result","callbackUrl","SerializableJsonSchema","parse","completedTask","completeTask","outputProperties","isTriggerError","skipRetrying","onErrorResult","retryAt","parsedError","ErrorWithStackSchema","safeParse","RetryWithTaskError","success","innerError","calculateRetryAt","attempts","failTask","run","ResumeWithTaskError","supportsFeature","console","includes","YieldExecutionError","try","tryCallback","catchCallback","keyMaterial","keys","map","stableStringify","hash","webcrypto","subtle","digest","Buffer","from","obj","sortKeys","Array","isArray","sortedKeys","Object","sort","sortedObj","createIOWithIntegrations","io","auths","integrations","connections","Object","entries","reduce","acc","connectionKey","integration","auth","Proxy","get","target","prop","receiver","cloneForRun","value","Reflect","bind","import_node_async_hooks","TypedAsyncLocalStorage","constructor","storage","AsyncLocalStorage","runWith","context","fn","run","getStore","runLocalStorage","TypedAsyncLocalStorage","import_core","_options","DynamicTrigger","constructor","client","options","source","attachDynamicTrigger","toJSON","type","id","event","registeredTriggerForParams","params","key","slugifyId","rule","name","payload","deepMergeFilters","filter","version","channel","integration","metadata","authSource","accountId","register","runStore","runLocalStorage","getStore","registerTrigger","io","runTask","task","properties","label","text","attachToJob","triggerClient","job","attachJobToDynamicTrigger","preprocessRuns","import_core","formatSchemaErrors","errors","map","error","path","message","String","_options","EventTrigger","constructor","options","toJSON","type","title","name","event","rule","source","payload","deepMergeFilters","filter","attachToJob","triggerClient","job","preprocessRuns","eventTrigger","icon","examples","parsePayload","rawPayload","schema","results","safeParse","success","ParsedPayloadSchemaError","formatSchemaErrors","error","issues","data","import_core","examples","id","name","icon","payload","ts","currentDate","marker","lastTimestamp","IntervalTrigger","constructor","options","event","title","source","parsePayload","ScheduledPayloadSchema","parse","properties","label","text","seconds","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","schedule","intervalTrigger","CronTrigger","humanReadable","cronstrue","toString","cron","throwExceptionOnParseError","cronTrigger","DynamicSchedule","client","attachDynamicSchedule","register","key","metadata","runStore","runLocalStorage","getStore","registerSchedule","io","runTask","task","params","unregister","unregisterSchedule","attachDynamicScheduleToJob","registerSourceEvent","name","REGISTER_SOURCE_EVENT_V2","title","source","icon","parsePayload","RegisterSourceEventSchemaV2","parse","_options","_client","TriggerClient","constructor","options","id","ApiClient","Logger","verbose","handleRequest","request","debug","url","headers","Object","fromEntries","entries","method","apiKey","get","triggerVersion","authorization","authorized","status","body","message","action","endpointId","ok","error","jobs","sources","values","dynamicTriggers","map","trigger","registerSourceJob","dynamicTriggerRegisterSourceJobId","version","dynamicSchedules","json","InitializeTriggerBodySchema","safeParse","success","dynamicTrigger","data","registeredTriggerForParams","params","execution","RunJobBodySchema","job","results","PreprocessRunBodySchema","abort","properties","HttpSourceRequestHeadersSchema","sourceRequestNeedsBody","sourceRequestInit","undefined","duplex","sourceRequest","Request","key","dynamicId","secret","auth","inputMetadata","metadata","response","events","defineJob","Job","defineAuthResolver","integration","resolver","defineDynamicSchedule","DynamicSchedule","defineDynamicTrigger","DynamicTrigger","attach","attachToJob","attachDynamicTrigger","EventTrigger","event","filter","dynamicTriggerId","integrations","run","io","ctx","updates","register","updateSource","__internal","attachJobToDynamicTrigger","push","attachSource","s","r","handle","registeredSource","channel","authSource","newOptions","deepMergeOptions","attachDynamicSchedule","attachDynamicScheduleToJob","registerTrigger","getAuth","sendEvent","cancelEvent","eventId","updateStatus","runId","registerSchedule","schedule","unregisterSchedule","getEvent","getRun","cancelRun","getRuns","jobSlug","getRunStatuses","localApiKey","process","env","TRIGGER_API_KEY","context","parsedPayload","payload","runProperties","IO","cachedTasks","tasks","cachedTasksCursor","cachedTaskCursor","yieldedExecutions","noopTasksSet","apiClient","logger","client","jobLogLevel","logLevel","jobLogger","ioLogLocalEnabled","serverVersion","resolvedConnections","connections","issues","ioWithConnections","createIOWithIntegrations","output","runLocalStorage","runWith","stats","YieldExecutionError","ParsedPayloadSchemaError","errors","schemaErrors","ResumeWithTaskError","task","RetryWithTaskError","cause","retryAt","CanceledWithTaskError","errorWithStack","ErrorWithStackSchema","organization","environment","timestamp","account","handler","resolvedAuthResults","Promise","all","keys","result","allResolved","every","reduce","acc","authResolver","resolvedAuth","type","accessToken","token","additionalFields","resolverError","Error","JSON","stringify","internal","toJSON","startPosition","enabled","preprocessRuns","API_VERSIONS","LAZY_LOADED_CACHED_TASKS","obj1","obj2","mergedOptions","hasOwnProperty","import_core","ExternalSource","constructor","channel","options","handle","source","rawEvent","logger","handler","params","integration","filter","properties","register","registerEvent","io","ctx","result","event","ommited","omit","sourceWithoutChannel","channelWithoutType","updates","key","parts","id","push","join","integrationConfig","metadata","version","ExternalSourceTrigger","toJSON","type","title","rule","name","payload","deepMergeFilters","attachToJob","triggerClient","job","attachSource","slugifyId","preprocessRuns","obj","k","Object","keys","import_core","missingConnectionNotification","integrations","MissingConnectionNotification","missingConnectionResolvedNotification","MissingConnectionResolvedNotification","constructor","options","event","name","MISSING_CONNECTION_NOTIFICATION","title","source","icon","parsePayload","MissingConnectionNotificationPayloadSchema","parse","properties","label","text","map","i","id","join","attachToJob","triggerClient","job","preprocessRuns","toJSON","type","rule","payload","client","MISSING_CONNECTION_RESOLVED_NOTIFICATION","MissingConnectionResolvedNotificationPayloadSchema","redactString","strings","interpolations","__redactedString","raw"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trigger.dev/sdk",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "trigger.dev Node.JS SDK",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"./package.json": "./package.json"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@trigger.dev/core": "^2.
|
|
22
|
+
"@trigger.dev/core": "^2.2.0",
|
|
23
23
|
"chalk": "^5.2.0",
|
|
24
24
|
"cronstrue": "^2.21.0",
|
|
25
25
|
"debug": "^4.3.4",
|
|
@@ -27,18 +27,16 @@
|
|
|
27
27
|
"get-caller-file": "^2.0.5",
|
|
28
28
|
"git-remote-origin-url": "^4.0.0",
|
|
29
29
|
"git-repo-info": "^2.1.1",
|
|
30
|
-
"node-fetch": "2.6.x",
|
|
31
30
|
"slug": "^6.0.0",
|
|
32
31
|
"terminal-link": "^3.0.0",
|
|
33
32
|
"ulid": "^2.3.0",
|
|
34
33
|
"uuid": "^9.0.0",
|
|
35
34
|
"ws": "^8.11.0",
|
|
36
|
-
"zod": "3.
|
|
35
|
+
"zod": "3.22.3"
|
|
37
36
|
},
|
|
38
37
|
"devDependencies": {
|
|
39
38
|
"@types/debug": "^4.1.7",
|
|
40
39
|
"@types/node": "18",
|
|
41
|
-
"@types/node-fetch": "2.6.x",
|
|
42
40
|
"@types/slug": "^5.0.3",
|
|
43
41
|
"@types/uuid": "^9.0.0",
|
|
44
42
|
"@types/ws": "^8.5.3",
|
|
@@ -50,7 +48,7 @@
|
|
|
50
48
|
"@trigger.dev/tsconfig": "0.0.0"
|
|
51
49
|
},
|
|
52
50
|
"engines": {
|
|
53
|
-
"node": ">=
|
|
51
|
+
"node": ">=18.0.0"
|
|
54
52
|
},
|
|
55
53
|
"scripts": {
|
|
56
54
|
"clean": "rimraf dist",
|