@trigger.dev/sdk 4.7.4 → 4.8.0-webhooks.20261015065339

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/commonjs/v3/ai.d.ts +560 -8
  2. package/dist/commonjs/v3/ai.js +2263 -178
  3. package/dist/commonjs/v3/ai.js.map +1 -1
  4. package/dist/commonjs/v3/chat.d.ts +23 -0
  5. package/dist/commonjs/v3/chat.js.map +1 -1
  6. package/dist/commonjs/v3/index.d.ts +2 -0
  7. package/dist/commonjs/v3/index.js +23 -17
  8. package/dist/commonjs/v3/index.js.map +1 -1
  9. package/dist/commonjs/v3/modelFileDownload.d.ts +10 -0
  10. package/dist/commonjs/v3/modelFileDownload.js +164 -0
  11. package/dist/commonjs/v3/modelFileDownload.js.map +1 -0
  12. package/dist/commonjs/v3/test/index.d.ts +2 -1
  13. package/dist/commonjs/v3/test/index.js +4 -1
  14. package/dist/commonjs/v3/test/index.js.map +1 -1
  15. package/dist/commonjs/v3/test/mock-channel-connector.d.ts +172 -0
  16. package/dist/commonjs/v3/test/mock-channel-connector.js +173 -0
  17. package/dist/commonjs/v3/test/mock-channel-connector.js.map +1 -0
  18. package/dist/commonjs/v3/test/mock-chat-agent.d.ts +81 -1
  19. package/dist/commonjs/v3/test/mock-chat-agent.js +137 -10
  20. package/dist/commonjs/v3/test/mock-chat-agent.js.map +1 -1
  21. package/dist/commonjs/v3/transcriptStorage.d.ts +44 -1
  22. package/dist/commonjs/v3/transcriptStorage.js +24 -0
  23. package/dist/commonjs/v3/transcriptStorage.js.map +1 -1
  24. package/dist/commonjs/v3/webhookWaiters.d.ts +80 -0
  25. package/dist/commonjs/v3/webhookWaiters.js +156 -0
  26. package/dist/commonjs/v3/webhookWaiters.js.map +1 -0
  27. package/dist/commonjs/v3/webhooks.d.ts +178 -2
  28. package/dist/commonjs/v3/webhooks.js +322 -1
  29. package/dist/commonjs/v3/webhooks.js.map +1 -1
  30. package/dist/commonjs/version.js +1 -1
  31. package/dist/esm/v3/ai.d.ts +560 -8
  32. package/dist/esm/v3/ai.js +2257 -178
  33. package/dist/esm/v3/ai.js.map +1 -1
  34. package/dist/esm/v3/chat.d.ts +23 -0
  35. package/dist/esm/v3/chat.js.map +1 -1
  36. package/dist/esm/v3/index.d.ts +2 -0
  37. package/dist/esm/v3/index.js +1 -0
  38. package/dist/esm/v3/index.js.map +1 -1
  39. package/dist/esm/v3/modelFileDownload.d.ts +10 -0
  40. package/dist/esm/v3/modelFileDownload.js +161 -0
  41. package/dist/esm/v3/modelFileDownload.js.map +1 -0
  42. package/dist/esm/v3/test/index.d.ts +2 -1
  43. package/dist/esm/v3/test/index.js +2 -1
  44. package/dist/esm/v3/test/index.js.map +1 -1
  45. package/dist/esm/v3/test/mock-channel-connector.d.ts +172 -0
  46. package/dist/esm/v3/test/mock-channel-connector.js +170 -0
  47. package/dist/esm/v3/test/mock-channel-connector.js.map +1 -0
  48. package/dist/esm/v3/test/mock-chat-agent.d.ts +81 -1
  49. package/dist/esm/v3/test/mock-chat-agent.js +137 -11
  50. package/dist/esm/v3/test/mock-chat-agent.js.map +1 -1
  51. package/dist/esm/v3/transcriptStorage.d.ts +44 -1
  52. package/dist/esm/v3/transcriptStorage.js +24 -0
  53. package/dist/esm/v3/transcriptStorage.js.map +1 -1
  54. package/dist/esm/v3/webhookWaiters.d.ts +80 -0
  55. package/dist/esm/v3/webhookWaiters.js +149 -0
  56. package/dist/esm/v3/webhookWaiters.js.map +1 -0
  57. package/dist/esm/v3/webhooks.d.ts +178 -2
  58. package/dist/esm/v3/webhooks.js +318 -1
  59. package/dist/esm/v3/webhooks.js.map +1 -1
  60. package/dist/esm/version.js +1 -1
  61. package/docs/ai-chat/actions.mdx +6 -1
  62. package/docs/ai-chat/backend.mdx +34 -0
  63. package/docs/ai-chat/pending-messages.mdx +2 -0
  64. package/docs/ai-chat/reference.mdx +50 -2
  65. package/docs/mcp-tools.mdx +76 -0
  66. package/docs/webhooks/channels.mdx +128 -0
  67. package/docs/webhooks/connect.mdx +80 -0
  68. package/docs/webhooks/deliveries.mdx +92 -0
  69. package/docs/webhooks/filters.mdx +109 -0
  70. package/docs/webhooks/human-in-the-loop.mdx +149 -0
  71. package/docs/webhooks/linear.mdx +185 -0
  72. package/docs/webhooks/overview.mdx +99 -0
  73. package/docs/webhooks/session-routing.mdx +132 -0
  74. package/docs/webhooks/slack.mdx +360 -0
  75. package/docs/webhooks/sources.mdx +217 -0
  76. package/docs/webhooks/waiters.mdx +170 -0
  77. package/package.json +3 -2
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhookWaiterPromise = void 0;
4
+ exports.createWebhookWaiter = createWebhookWaiter;
5
+ exports.waitForWebhookWaiter = waitForWebhookWaiter;
6
+ exports.cancelWebhookWaiter = cancelWebhookWaiter;
7
+ const api_1 = require("@opentelemetry/api");
8
+ const v3_1 = require("@trigger.dev/core/v3");
9
+ const ioSerialization_1 = require("@trigger.dev/core/v3/utils/ioSerialization");
10
+ const tracer_js_1 = require("./tracer.js");
11
+ /**
12
+ * Register a waiter on an endpoint: the next matching delivery that arrives after this call resumes
13
+ * whoever waits on it. Create it before doing whatever makes the provider send the webhook, and match
14
+ * on values you control (like your own order id in the event's metadata). Works inside a run and from
15
+ * your backend.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const waiter = await webhooks.waiter.create(payments, {
20
+ * match: { "event.data.object.metadata.orderId": order.id, "event.type": "payment_intent.succeeded" },
21
+ * timeout: "1h",
22
+ * });
23
+ * await stripe.paymentIntents.create({ amount: 4200, currency: "usd", metadata: { orderId: order.id } });
24
+ * const { event } = await webhooks.waiter.wait(waiter).unwrap();
25
+ * ```
26
+ */
27
+ async function createWebhookWaiter(endpoint, options = {}, requestOptions) {
28
+ const apiClient = v3_1.apiClientManager.clientOrThrow();
29
+ const idempotencyKey = (await (0, v3_1.makeIdempotencyKey)(options.idempotencyKey)) ?? globalThis.crypto.randomUUID();
30
+ const timeout = options.timeout instanceof Date ? options.timeout.toISOString() : options.timeout;
31
+ try {
32
+ const result = await apiClient.createWebhookWaiter(endpoint.id, {
33
+ ...(options.match ? { match: options.match } : {}),
34
+ ...(options.filter ? { filter: options.filter } : {}),
35
+ ...(timeout ? { timeout } : {}),
36
+ ...(options.tags ? { tags: options.tags } : {}),
37
+ idempotencyKey,
38
+ ...(options.idempotencyKeyTTL ? { idempotencyKeyTTL: options.idempotencyKeyTTL } : {}),
39
+ }, (0, v3_1.mergeRequestOptions)({
40
+ tracer: tracer_js_1.tracer,
41
+ name: "webhooks.waiter.create()",
42
+ icon: "wait",
43
+ attributes: {
44
+ endpoint: endpoint.id,
45
+ ...(options.match ? { match: Object.keys(options.match).join(", ") } : {}),
46
+ },
47
+ onResponseBody: (body, span) => span.setAttribute("id", body.id),
48
+ }, requestOptions));
49
+ return result;
50
+ }
51
+ catch (error) {
52
+ throw toWebhookWaiterError(error);
53
+ }
54
+ }
55
+ function toWebhookWaiterError(error) {
56
+ if (!(error instanceof v3_1.ApiError))
57
+ return error;
58
+ const body = error.body;
59
+ const message = typeof body?.error === "string" ? body.error : error.message;
60
+ switch (error.code) {
61
+ case "webhook_waiter_limit":
62
+ return new v3_1.WebhookWaiterLimitError(body?.reason ?? "endpoint_limit", message);
63
+ case "webhook_endpoint_not_found":
64
+ return new v3_1.WebhookEndpointNotFoundError(message);
65
+ case "webhook_filter_invalid":
66
+ return new v3_1.WebhookFilterError(message);
67
+ default:
68
+ return error;
69
+ }
70
+ }
71
+ /** A waiter's result. `.unwrap()` returns the output or throws its typed error. */
72
+ class WebhookWaiterPromise extends Promise {
73
+ unwrap() {
74
+ return this.then((result) => {
75
+ if (result.ok)
76
+ return result.output;
77
+ throw result.error;
78
+ });
79
+ }
80
+ }
81
+ exports.WebhookWaiterPromise = WebhookWaiterPromise;
82
+ function waiterIdOf(waiter) {
83
+ return typeof waiter === "string" ? waiter : waiter.id;
84
+ }
85
+ /**
86
+ * Suspend the current run until the waiter matches a delivery, times out or is cancelled. Only inside
87
+ * `task.run()`. The result's error is a `WaitpointTimeoutError` or a `WebhookWaiterCancelledError`.
88
+ */
89
+ function waitForWebhookWaiter(waiter) {
90
+ return new WebhookWaiterPromise(async (resolve, reject) => {
91
+ try {
92
+ const ctx = v3_1.taskContext.ctx;
93
+ if (!ctx) {
94
+ throw new Error("webhooks.waiter.wait can only be used from inside a task.run()");
95
+ }
96
+ const apiClient = v3_1.apiClientManager.clientOrThrow();
97
+ const waiterId = waiterIdOf(waiter);
98
+ const result = await tracer_js_1.tracer.startActiveSpan("webhooks.waiter.wait()", async (span) => {
99
+ const response = await apiClient.waitForWaitpointToken({
100
+ runFriendlyId: ctx.run.id,
101
+ waitpointFriendlyId: waiterId,
102
+ });
103
+ if (!response.success) {
104
+ throw new Error(`Failed to wait for webhook waiter ${waiterId}`);
105
+ }
106
+ const completion = await v3_1.runtime.waitUntil(waiterId);
107
+ const data = completion.output
108
+ ? await (0, ioSerialization_1.conditionallyImportAndParsePacket)({ data: completion.output, dataType: completion.outputType ?? "application/json" }, apiClient)
109
+ : undefined;
110
+ if (completion.ok) {
111
+ return { ok: true, output: data };
112
+ }
113
+ const failure = data;
114
+ const error = failure?.name === "WebhookWaiterCancelledError"
115
+ ? new v3_1.WebhookWaiterCancelledError(failure.message)
116
+ : new v3_1.WaitpointTimeoutError(failure?.message ?? "The webhook waiter timed out");
117
+ span.recordException(error);
118
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR });
119
+ return { ok: false, error };
120
+ }, {
121
+ attributes: {
122
+ [v3_1.SemanticInternalAttributes.STYLE_ICON]: "wait",
123
+ [v3_1.SemanticInternalAttributes.ENTITY_TYPE]: "waitpoint",
124
+ [v3_1.SemanticInternalAttributes.ENTITY_ID]: waiterId,
125
+ id: waiterId,
126
+ ...(0, v3_1.accessoryAttributes)({
127
+ items: [{ text: waiterId, variant: "normal" }],
128
+ style: "codepath",
129
+ }),
130
+ },
131
+ });
132
+ resolve(result);
133
+ }
134
+ catch (error) {
135
+ reject(error);
136
+ }
137
+ });
138
+ }
139
+ /**
140
+ * Cancel a waiter: frees its slot and fails its wait with `WebhookWaiterCancelledError`. If a delivery
141
+ * already claimed it, this is too late and the waiting run resumes with that delivery.
142
+ */
143
+ async function cancelWebhookWaiter(waiter, requestOptions) {
144
+ const apiClient = v3_1.apiClientManager.clientOrThrow();
145
+ const waiterId = waiterIdOf(waiter);
146
+ const result = await apiClient.cancelWebhookWaiter(waiterId, (0, v3_1.mergeRequestOptions)({
147
+ tracer: tracer_js_1.tracer,
148
+ name: "webhooks.waiter.cancel()",
149
+ icon: "wait",
150
+ attributes: { id: waiterId },
151
+ }, requestOptions));
152
+ return result.cancelled
153
+ ? { cancelled: true }
154
+ : { cancelled: false, reason: "too_late", deliveryId: result.deliveryId ?? "" };
155
+ }
156
+ //# sourceMappingURL=webhookWaiters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhookWaiters.js","sourceRoot":"","sources":["../../../src/v3/webhookWaiters.ts"],"names":[],"mappings":";;;;;;AAAA,4CAAoD;AACpD,6CAwB8B;AAC9B,gFAA+F;AAC/F,2CAAqC;AA4CrC;;;;;;;;;;;;;;;GAeG;AACI,KAAK,8BAQV,QAAmB,EACnB,OAAO,GAGH,EAAE,EACN,cAAkC;IAElC,MAAM,SAAS,GAAG,qBAAgB,CAAC,aAAa,EAAE,CAAC;IACnD,MAAM,cAAc,GAClB,CAAC,MAAM,IAAA,uBAAkB,EAAC,OAAO,CAAC,cAAc,CAAC,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;IACvF,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,YAAY,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC;IAElG,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,mBAAmB,C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ACD,cAAc,CACf,CACF,CAAC;IACF,OAAO,MAAM,CAAC,SAAS;QACrB,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE;QACrB,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,EAAE,EAAE,CAAC;AACpF,CAAC"}
@@ -1,4 +1,8 @@
1
1
  import { Webhook } from "@trigger.dev/core/v3";
2
+ import type { WebhookSource, InferWebhookEvent, AnyWebhookSource, ValidateWebhookFilter, NarrowWebhookEvent, ChatEvent, ValidatedWebhookKey, WebhookResponseConfig, WebhookUrlSecretConfig, WebhookVerifierConfig, StripeWebhookEvent, GitHubWebhookEvent, TaskRunContext, AnyWebhookEndpoint, InferWebhookEndpointEvent, WebhookEndpoint, WebhookEndpointContext } from "@trigger.dev/core/v3";
3
+ import { cancelWebhookWaiter, createWebhookWaiter, waitForWebhookWaiter } from "./webhookWaiters.js";
4
+ import { type Task } from "./shared.js";
5
+ import { type WebhookProviderId } from "@trigger.dev/core/webhooks";
2
6
  /**
3
7
  * The type of error thrown when a webhook fails to parse or verify
4
8
  */
@@ -14,6 +18,153 @@ type ConstructEventOptions = {
14
18
  /** Signature header as string, Buffer, or string array */
15
19
  header: string | Buffer | Array<string>;
16
20
  };
21
+ /**
22
+ * The verifier configs a hosted endpoint can enforce. A `url-secret` placed in the path is excluded:
23
+ * the hosted ingress URL is fixed per endpoint, so there is no path segment for the caller to choose,
24
+ * and the server refuses such a declaration at deploy time. Use `placement: "query"` instead.
25
+ */
26
+ export type HostedWebhookVerifierConfig = Exclude<WebhookVerifierConfig, WebhookUrlSecretConfig> | (Omit<WebhookUrlSecretConfig, "placement"> & {
27
+ placement: "query";
28
+ });
29
+ export declare const webhookSources: {
30
+ readonly custom: <T = unknown>(config: HostedWebhookVerifierConfig, options?: {
31
+ /** Instructions for an AI agent registering an endpoint on this source with the provider. */
32
+ setupPrompt?: string;
33
+ /**
34
+ * How the endpoint answers the provider. `{ acceptedBody: "empty" }` acknowledges with an empty
35
+ * 200, for providers that show the response to a user (Slack slash commands).
36
+ */
37
+ response?: WebhookResponseConfig;
38
+ }) => WebhookSource<T>;
39
+ readonly stripe: <TEvent = StripeWebhookEvent>(opts?: {
40
+ toleranceSeconds?: number;
41
+ }) => WebhookSource<TEvent>;
42
+ readonly github: <TEvent = GitHubWebhookEvent>() => WebhookSource<TEvent>;
43
+ readonly svix: <T = unknown>() => WebhookSource<T>;
44
+ readonly standardWebhooks: <T = unknown>() => WebhookSource<T>;
45
+ readonly square: <T = unknown>() => WebhookSource<T>;
46
+ /**
47
+ * Discord: asymmetric Ed25519 over `{timestamp}{body}`. The "secret" stored on the endpoint is the
48
+ * application PUBLIC KEY (hex by default); there is no shared secret. Discord's response contract
49
+ * is declared as data on the artifact: the `{ type: 0 }` PING sent when the URL is saved is answered
50
+ * with a bodiless 204 and never recorded, accepted events are acknowledged with 204, and a bad
51
+ * signature gets 401.
52
+ */
53
+ readonly discord: <T = unknown>(opts?: {
54
+ publicKeyEncoding?: "raw-hex" | "pem";
55
+ }) => WebhookSource<T>;
56
+ /**
57
+ * Per-provider producers over shared presets. Each is a thin wrapper: same verifier config as the
58
+ * preset it references, differing only in `provider` (routing + picker identity) and who provisions
59
+ * the secret. Pass the provider's own published type for full typing, e.g. clerk<WebhookEvent>().
60
+ */
61
+ readonly clerk: <T = unknown>() => WebhookSource<T>;
62
+ readonly resend: <T = unknown>() => WebhookSource<T>;
63
+ readonly openai: <T = unknown>() => WebhookSource<T>;
64
+ readonly replicate: <T = unknown>() => WebhookSource<T>;
65
+ readonly recallai: <T = unknown>() => WebhookSource<T>;
66
+ readonly brex: <T = unknown>() => WebhookSource<T>;
67
+ readonly composio: <T = unknown>() => WebhookSource<T>;
68
+ readonly gitlab: <T = unknown>() => WebhookSource<T>;
69
+ /**
70
+ * WhatsApp Cloud API (Meta): `X-Hub-Signature-256` HMAC over the raw body, keyed by the App Secret,
71
+ * which Meta issues and you paste in as the endpoint's signing secret (it cannot be generated here).
72
+ * Meta verifies the callback URL with a GET carrying `hub.mode`, `hub.verify_token` and
73
+ * `hub.challenge`; the endpoint answers it when the token equals the verify token generated in
74
+ * the endpoint's Connect panel, which you paste into Meta's Verify Token field.
75
+ */
76
+ readonly whatsapp: <T = unknown>() => WebhookSource<T>;
77
+ };
78
+ type CamelCase<S extends string> = S extends `${infer Head}-${infer Tail}` ? `${Head}${Capitalize<CamelCase<Tail>>}` : S;
79
+ /**
80
+ * Per-provider producers generated from the core config table (kind "config"). Each carries the
81
+ * provider's own HMAC verifier config and stays in lockstep with the round-trip-tested configs.
82
+ * The method is the provider id in camel case (`cal-com` is `webhooks.calCom()`); the emitted
83
+ * `provider` keeps the id itself.
84
+ */
85
+ export type ProviderProducers = {
86
+ [K in Exclude<WebhookProviderId, "zoom"> as CamelCase<K>]: <TEvent = unknown>() => WebhookSource<TEvent>;
87
+ };
88
+ export declare const providerProducers: Omit<ProviderProducers, "slack">;
89
+ export type WebhookEndpointOptions<TIdentifier extends string, TSource extends AnyWebhookSource> = {
90
+ /** The endpoint id. Subscribers reference the endpoint, and it names the endpoint's URL. */
91
+ id: TIdentifier;
92
+ /** The provider source: how deliveries are verified and who issues the signing secret. */
93
+ source: TSource;
94
+ description?: string;
95
+ /** Arbitrary metadata, passed to every subscriber and waiter as `endpoint.metadata`. */
96
+ metadata?: Record<string, unknown>;
97
+ };
98
+ /**
99
+ * Declare a webhook endpoint: one URL you register with the provider. Subscribe to it with
100
+ * `webhook({ endpoint })`, `chat.event({ endpoint })` or a channel connector, and wait on it with
101
+ * `webhooks.waiter.create(endpoint, ...)`. An endpoint with no subscribers still gets a URL.
102
+ */
103
+ export declare function defineWebhookEndpoint<TIdentifier extends string, TSource extends AnyWebhookSource>(options: WebhookEndpointOptions<TIdentifier, TSource>): WebhookEndpoint<InferWebhookEvent<TSource>> & {
104
+ id: TIdentifier;
105
+ };
106
+ export type WebhookOnEventParams<TEvent> = {
107
+ /** The verified event body, typed by the endpoint's source. */
108
+ event: TEvent;
109
+ /** The inbound request headers (case-insensitive, Web `Headers`). e.g. headers.get("x-github-event"). */
110
+ headers: Headers;
111
+ /** The endpoint the delivery arrived on. Unset when the task is triggered by hand without one. */
112
+ endpoint?: WebhookEndpointContext;
113
+ ctx: TaskRunContext;
114
+ };
115
+ export type WebhookOptions<TIdentifier extends string, TEndpoint extends AnyWebhookEndpoint, TEvent = InferWebhookEndpointEvent<TEndpoint>> = {
116
+ id: TIdentifier;
117
+ /** The endpoint this task subscribes to. */
118
+ endpoint: TEndpoint;
119
+ /**
120
+ * Optional server-side filter (a type-safe string DSL checked against the event shape). A delivery
121
+ * this subscriber's filter rejects is still recorded, and other subscribers on the endpoint still
122
+ * get it. e.g. `"event.action == 'created' && event.repository.private == false"`.
123
+ */
124
+ filter?: string;
125
+ /** Gets the event narrowed by the filter's `event.<field> == '<value>'` clauses. */
126
+ onEvent: (params: WebhookOnEventParams<TEvent>) => Promise<void> | void;
127
+ };
128
+ /**
129
+ * What a webhook task runs on: the verified event, the delivery headers and the endpoint. The hosted
130
+ * ingress sends it for every delivery; triggering the handle by hand (`myWebhook.trigger({ event })`,
131
+ * a replay, a test) sends the same shape, so `onEvent` sees the event either way.
132
+ */
133
+ export type WebhookTaskPayload<TEvent> = {
134
+ event: TEvent;
135
+ headers?: Record<string, string>;
136
+ endpoint?: WebhookEndpointContext;
137
+ };
138
+ export type WebhookHandle<TIdentifier extends string, TEvent> = Task<TIdentifier, WebhookTaskPayload<TEvent>, void>;
139
+ export declare function webhook<TIdentifier extends string, TEndpoint extends AnyWebhookEndpoint, const TFilter extends string = string>(options: WebhookOptions<TIdentifier, TEndpoint, NarrowWebhookEvent<InferWebhookEndpointEvent<TEndpoint>, TFilter>> & {
140
+ filter?: ValidateWebhookFilter<InferWebhookEndpointEvent<TEndpoint>, TFilter>;
141
+ }): WebhookHandle<TIdentifier, NarrowWebhookEvent<InferWebhookEndpointEvent<TEndpoint>, TFilter>>;
142
+ export declare function chatEvent<TEndpoint extends AnyWebhookEndpoint, const TId extends string = string, const TKey extends string = string, const TType extends string = TId, const TFilter extends string = string>(options: {
143
+ id: TId;
144
+ /** The endpoint this event subscribes to. */
145
+ endpoint: TEndpoint;
146
+ /**
147
+ * The session each delivery goes to, as a template: `{event.x}` reads the event, `{header.x}` a
148
+ * header and `{webhook.x}` the endpoint, and `{a || b}` falls back to `b` when `a` is empty. e.g.
149
+ * `"{webhook.externalRef}:{event.data.object.customer}"`.
150
+ */
151
+ key: ValidatedWebhookKey<NarrowWebhookEvent<InferWebhookEndpointEvent<TEndpoint>, TFilter>, TKey>;
152
+ /** The `action.type` the handler reads. Optional; defaults to `id`. */
153
+ type?: TType;
154
+ /**
155
+ * Optional server-side filter (same type-safe DSL as `webhook()`); a non-match is recorded FILTERED
156
+ * and not routed. Narrows the action's `event` like `webhook()`'s `onEvent`.
157
+ */
158
+ filter?: ValidateWebhookFilter<InferWebhookEndpointEvent<TEndpoint>, TFilter>;
159
+ }): ChatEvent<TType, NarrowWebhookEvent<InferWebhookEndpointEvent<TEndpoint>, TFilter>>;
160
+ export type { ChatEvent, AnyChatEvent, ChatEventAction, ChatEventActions, WebhookKeyMeta, } from "@trigger.dev/core/v3";
161
+ /**
162
+ * Compiles a key template to its stored form. Each placeholder names its namespace the way a filter
163
+ * path does: `{event.x}` reads the event body (stored as `{body.x}`), `{header.x}` a header and
164
+ * `{webhook.x}` the endpoint. A placeholder without one of those namespaces throws.
165
+ */
166
+ export declare function normalizeKeyString(key: string): string;
167
+ export type { CreateWebhookEndpointParams } from "@trigger.dev/core/v3";
17
168
  /**
18
169
  * Interface describing the webhook utilities
19
170
  */
@@ -39,9 +190,34 @@ interface Webhooks {
39
190
  constructEvent(request: ConstructEventOptions | Request, secret: string): Promise<Webhook>;
40
191
  /** Header name used for webhook signatures */
41
192
  SIGNATURE_HEADER_NAME: string;
193
+ custom: typeof webhookSources.custom;
194
+ stripe: typeof webhookSources.stripe;
195
+ github: typeof webhookSources.github;
196
+ svix: typeof webhookSources.svix;
197
+ standardWebhooks: typeof webhookSources.standardWebhooks;
198
+ square: typeof webhookSources.square;
199
+ discord: typeof webhookSources.discord;
200
+ clerk: typeof webhookSources.clerk;
201
+ resend: typeof webhookSources.resend;
202
+ openai: typeof webhookSources.openai;
203
+ replicate: typeof webhookSources.replicate;
204
+ recallai: typeof webhookSources.recallai;
205
+ brex: typeof webhookSources.brex;
206
+ composio: typeof webhookSources.composio;
207
+ gitlab: typeof webhookSources.gitlab;
208
+ whatsapp: typeof webhookSources.whatsapp;
209
+ /** Declare the URLs providers deliver to. */
210
+ endpoint: {
211
+ define: typeof defineWebhookEndpoint;
212
+ };
213
+ /** Suspend a run until a matching webhook arrives. */
214
+ waiter: {
215
+ create: typeof createWebhookWaiter;
216
+ wait: typeof waitForWebhookWaiter;
217
+ cancel: typeof cancelWebhookWaiter;
218
+ };
42
219
  }
43
220
  /**
44
221
  * Webhook utilities for handling incoming webhook requests
45
222
  */
46
- export declare const webhooks: Webhooks;
47
- export {};
223
+ export declare const webhooks: Webhooks & Omit<ProviderProducers, "slack">;