@mynthio/sdk 0.0.49 → 0.0.50

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/README.md CHANGED
@@ -88,6 +88,7 @@ Use `generateAsync()` when you want to trigger work now and fetch the final task
88
88
  const taskAsync = await mynth.image.generateAsync({
89
89
  prompt: "A cinematic fantasy castle on a cliff",
90
90
  model: "google/gemini-3.1-flash-image",
91
+ generate_public_access_token: true,
91
92
  });
92
93
 
93
94
  console.log(taskAsync.id);
@@ -97,7 +98,7 @@ const completedTask = await taskAsync.wait();
97
98
  console.log(completedTask.urls);
98
99
  ```
99
100
 
100
- `taskAsync.access.publicAccessToken` is safe to send to the client. It is scoped to that single task, so you can poll task state from the browser without exposing your API key or building your own polling proxy.
101
+ `taskAsync.access.publicAccessToken` is set when the request asks for it with `generate_public_access_token: true`. It is safe to send to the client: it is scoped to that single task, so you can poll task state from the browser without exposing your API key or building your own polling proxy.
101
102
 
102
103
  You can use it as a Bearer token against:
103
104
 
@@ -110,6 +111,7 @@ Example:
110
111
  const taskAsync = await mynth.image.generateAsync({
111
112
  prompt: "A cinematic fantasy castle on a cliff",
112
113
  model: "google/gemini-3.1-flash-image",
114
+ generate_public_access_token: true,
113
115
  });
114
116
 
115
117
  const taskId = taskAsync.id;
@@ -172,21 +174,17 @@ const task = await mynth.image.generate({
172
174
  model: "google/gemini-3-pro-image-preview",
173
175
  size: {
174
176
  type: "aspect_ratio",
175
- aspectRatio: "4:5",
177
+ aspect_ratio: "4:5",
176
178
  },
177
179
  count: 2,
178
180
  output: {
179
181
  format: "webp",
180
182
  },
181
183
  webhook: {
182
- dashboard: false,
183
- custom: [{ url: "https://your-app.com/api/mynth-webhook" }],
184
- },
185
- access: {
186
- pat: {
187
- enabled: true,
188
- },
184
+ registered: false,
185
+ custom: [{ url: "https://your-app.com/api/mynth-webhook?token=your-secret-token" }],
189
186
  },
187
+ generate_public_access_token: true,
190
188
  rating: {
191
189
  mode: "custom",
192
190
  levels: [
@@ -211,7 +209,9 @@ const task = await mynth.image.generate({
211
209
  });
212
210
  ```
213
211
 
214
- `access.pat.enabled` controls whether the create-task response includes a short-lived Public Access Token for browser-side polling. It defaults to `true`.
212
+ Request fields are the API's own, in snake_case, and the API rejects a field it does not know. `generate_public_access_token` asks for a short-lived Public Access Token for browser-side polling, as `taskAsync.access.publicAccessToken`. It defaults to `false`.
213
+
214
+ `webhook.registered: false` skips the webhooks registered on your account for this task. `webhook.custom` sends this task's events to other URLs, unsigned: use https and a public host, and put a secret token in the URL so your handler can check it (see [Unsigned custom webhooks](#unsigned-custom-webhooks)). Mynth only ever shows `scheme://host` of a custom URL back.
215
215
 
216
216
  `output` is optional. Set `output.format` to `png`, `jpg`, or `webp`. When it is omitted, the result keeps the format the provider delivered.
217
217
 
@@ -280,8 +280,8 @@ Examples:
280
280
  ```ts
281
281
  size: "landscape";
282
282
  size: "auto";
283
- size: { type: "aspect_ratio", aspectRatio: "16:9" };
284
- size: { type: "aspect_ratio", aspectRatio: "4:5", scale: "4k" };
283
+ size: { type: "aspect_ratio", aspect_ratio: "16:9" };
284
+ size: { type: "aspect_ratio", aspect_ratio: "4:5", scale: "4k" };
285
285
  size: { type: "auto" };
286
286
  ```
287
287
 
@@ -471,11 +471,12 @@ const result = await mynth.image.removeBackground({
471
471
  console.log(result.metadata.productId);
472
472
  ```
473
473
 
474
- Use `removeBackgroundAsync()` to create the task without waiting. It returns a public access token, like `generateAsync()`:
474
+ Use `removeBackgroundAsync()` to create the task without waiting. Like `generateAsync()`, it returns a public access token when you ask for one:
475
475
 
476
476
  ```ts
477
477
  const taskAsync = await mynth.image.removeBackgroundAsync({
478
478
  url: "https://example.com/product.jpg",
479
+ generate_public_access_token: true,
479
480
  });
480
481
 
481
482
  return { id: taskAsync.id, access: taskAsync.access };
@@ -496,7 +497,7 @@ console.log(result.image.url); // upscaled image
496
497
  console.log(result.image.width, result.image.height); // e.g. 2048 1536
497
498
  ```
498
499
 
499
- `effort` sets the price: `low` is fast and sharp, `high` rebuilds fine detail such as small text and faces. `size` is `"2x"` or `"4x"`, or `{ type: "scale", factor: 2 | 4 }`. The upscaled image can be at most 4096x4096 pixels; a larger request fails with `OUTPUT_TOO_LARGE` and is not charged.
500
+ `effort` sets the price: `low` is fast and sharp, `high` rebuilds fine detail such as small text and faces. `size` is `"2x"` or `"4x"`, or `{ type: "scale", factor: 2 | 4 }`. The upscaled image can be at most 4096x4096 pixels; a larger request fails with `output_too_large` and is not charged.
500
501
 
501
502
  The result keeps the format the provider returned. Set `output.format` to always get `png`, `jpg`, or `webp`.
502
503
  `upscale()` also takes a local `file`, plus `destination`, `webhook`, and `metadata` like `generate()`:
@@ -514,13 +515,14 @@ const result = await mynth.image.upscale({
514
515
  console.log(result.metadata.productId);
515
516
  ```
516
517
 
517
- Use `upscaleAsync()` to create the task without waiting. It returns a public access token, like `generateAsync()`:
518
+ Use `upscaleAsync()` to create the task without waiting. Like `generateAsync()`, it returns a public access token when you ask for one:
518
519
 
519
520
  ```ts
520
521
  const taskAsync = await mynth.image.upscaleAsync({
521
522
  url: "https://example.com/product.jpg",
522
523
  size: "2x",
523
524
  effort: "low",
525
+ generate_public_access_token: true,
524
526
  });
525
527
 
526
528
  return { id: taskAsync.id, access: taskAsync.access };
@@ -567,7 +569,7 @@ const src = image.url ?? image.mynthUrl;
567
569
 
568
570
  ```ts
569
571
  if (task.failures.length > 0) {
570
- console.warn(task.failures); // [{ code: "PROVIDER_ERROR", message: "..." }]
572
+ console.warn(task.failures); // [{ code: "provider_error", message: "..." }]
571
573
  }
572
574
  ```
573
575
 
@@ -594,10 +596,10 @@ const models = await mynth.models.list();
594
596
  console.log(models[0]);
595
597
  // {
596
598
  // id: "black-forest-labs/flux.2-pro",
597
- // displayName: "FLUX.2 Pro",
599
+ // display_name: "FLUX.2 Pro",
598
600
  // type: "image",
599
- // modes: { "txt->img": {}, "img->img": { inputs: { rules: [...], maxTotal: 4 } } },
600
- // pricing: { perImage: { base: "0.05" } }
601
+ // modes: { "txt->img": {}, "img->img": { inputs: { rules: [...], max_total: 4 } } },
602
+ // pricing: { per_image: { base: "0.05" } }
601
603
  // }
602
604
  ```
603
605
 
@@ -608,9 +610,9 @@ price per second of output, keyed by resolution tier.
608
610
  ```ts
609
611
  for (const model of models) {
610
612
  if (model.type === "video") {
611
- console.log(model.id, model.pricing?.perSecond["720p"], Object.keys(model.modes));
613
+ console.log(model.id, model.pricing?.per_second["720p"], Object.keys(model.modes));
612
614
  } else {
613
- console.log(model.id, model.pricing?.perImage.base, Object.keys(model.modes));
615
+ console.log(model.id, model.pricing?.per_image.base, Object.keys(model.modes));
614
616
  }
615
617
  }
616
618
  ```
@@ -710,12 +712,13 @@ Prefer `generateAsync()` on the server and let the browser (or a webhook) pick t
710
712
  const taskAsync = await mynth.video.generateAsync({
711
713
  model: "bytedance/seedance-2.0-mini",
712
714
  prompt: "A neon city street in the rain",
715
+ generate_public_access_token: true,
713
716
  });
714
717
 
715
718
  return { id: taskAsync.id, access: taskAsync.access };
716
719
  ```
717
720
 
718
- `taskAsync.access.publicAccessToken` works exactly as it does for images: scoped to that one task, safe to send to the client, and usable against `GET /tasks/:id/status` and `GET /tasks/:id/result`.
721
+ `taskAsync.access.publicAccessToken` works exactly as it does for images: requested with `generate_public_access_token: true`, scoped to that one task, safe to send to the client, and usable against `GET /tasks/:id/status` and `GET /tasks/:id/result`.
719
722
 
720
723
  ### Duration, Resolution and Audio
721
724
 
@@ -752,7 +755,7 @@ Local files are uploaded to temporary input storage before the request, in a sin
752
755
  Video is priced per render, so you can price a request before running it. The endpoint validates the request the same way `generate()` does, which makes it a pre-flight check as well as a cost lookup:
753
756
 
754
757
  ```ts
755
- const { estimatedCost } = await mynth.video.estimate({
758
+ const { estimated_cost } = await mynth.video.estimate({
756
759
  model: "google/gemini-omni-flash-1.1",
757
760
  prompt: "A timelapse of clouds over a canyon",
758
761
  duration: 10,
@@ -760,7 +763,7 @@ const { estimatedCost } = await mynth.video.estimate({
760
763
  });
761
764
  ```
762
765
 
763
- Because the model is always concrete, the estimate is exact.
766
+ `estimate()` returns the API's own response, so its fields are snake_case. Because the model is always concrete, the estimate is exact.
764
767
 
765
768
  ### Working With Video Results
766
769
 
@@ -777,7 +780,7 @@ console.log(task.metadata);
777
780
  console.log(task.raw);
778
781
  ```
779
782
 
780
- Each video has `id`, `url`, `mynthUrl`, `cost`, `duration`, `resolution`, and `audio`.
783
+ Each video has `id`, `url`, `mynthUrl`, `cost`, `duration`, `resolution`, and `audio`. `url` is `null` when the video could not be delivered there; `mynthUrl` is always set.
781
784
 
782
785
  ### Video Models
783
786
 
@@ -814,7 +817,7 @@ Each of these supports generated audio.
814
817
 
815
818
  ## TypeScript Types
816
819
 
817
- The SDK exports the request and payload types via `MynthSDKTypes`.
820
+ The SDK exports the request, task and webhook event types via `MynthSDKTypes`. They describe the API's own data, so their fields are snake_case; the SDK's own surface (methods, options, result objects such as `task.taskId`) is camelCase.
818
821
 
819
822
  ```ts
820
823
  import type { MynthSDKTypes } from "@mynthio/sdk";
@@ -825,12 +828,64 @@ const request: MynthSDKTypes.ImageGenerationRequest = {
825
828
  };
826
829
  ```
827
830
 
828
- ## Next.js Integration
831
+ ## Webhooks
832
+
833
+ Mynth delivers webhooks the [Standard Webhooks](https://www.standardwebhooks.com) way. Every delivery is a `POST` with an event body and these headers:
834
+
835
+ - `webhook-id`: the event ID, `evt_...`. The same for every delivery of the event, and the same as the body's `id`
836
+ - `webhook-timestamp`: when this attempt was sent, in Unix seconds
837
+ - `webhook-signature`: `v1,<base64>`, only on deliveries to a webhook registered in the dashboard or through the API
838
+
839
+ ```json
840
+ {
841
+ "id": "evt_01KE7Y9M3R8T2QXN5BVC4WJ6HD",
842
+ "type": "task.image.generate.completed",
843
+ "timestamp": "2026-10-04T10:00:12.000Z",
844
+ "data": {
845
+ "id": "tsk_...",
846
+ "type": "image.generate",
847
+ "status": "completed",
848
+ "request": {},
849
+ "result": {}
850
+ }
851
+ }
852
+ ```
853
+
854
+ `data` is the task exactly as `GET /tasks/{id}` returns it. Deliveries are retried for about 72 hours, so the same event can arrive more than once: store `event.id` and skip IDs you have already handled.
855
+
856
+ ### Verify an event
857
+
858
+ `verifyWebhook()` checks the signature against the raw body, rejects a timestamp more than five minutes off, checks that the body's `id` is the `webhook-id`, and returns the typed event. It runs on Web Crypto, so it works in Node, edge runtimes and Workers.
859
+
860
+ ```ts
861
+ import { verifyWebhook } from "@mynthio/sdk";
862
+
863
+ export async function POST(request: Request) {
864
+ const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
865
+
866
+ switch (event.type) {
867
+ case "task.image.generate.completed":
868
+ await saveImages(event.data.id, event.data.result.images);
869
+ break;
870
+ case "task.image.generate.failed":
871
+ await markTaskFailed(event.data.id, event.data.errors);
872
+ break;
873
+ }
874
+
875
+ return new Response(null, { status: 204 });
876
+ }
877
+ ```
878
+
879
+ The secret defaults to `MYNTH_WEBHOOK_SECRET`; pass it as the second argument otherwise. A failed check throws `MynthWebhookVerificationError`, which your handler should answer with a `400`. Keep a `default` branch: an event type newer than your SDK version is returned as is.
880
+
881
+ The framework helpers below do the same verification and hand each event to a typed callback.
882
+
883
+ ### Next.js Integration
829
884
 
830
885
  Use the App Router helper to verify and route registered Mynth webhooks. Add the signing secret shown when you create the webhook:
831
886
 
832
887
  ```env
833
- MYNTH_WEBHOOK_SECRET=wbs_...
888
+ MYNTH_WEBHOOK_SECRET=whsec_...
834
889
  ```
835
890
 
836
891
  Create a Route Handler:
@@ -840,9 +895,8 @@ Create a Route Handler:
840
895
  import { mynthWebhookHandler } from "@mynthio/sdk/next";
841
896
 
842
897
  export const POST = mynthWebhookHandler({
843
- imageTaskCompleted: async (result, { request }) => {
844
- console.log("Completed task:", result.taskId);
845
- console.log("Received at:", request.url);
898
+ imageTaskCompleted: async (result, { event, request }) => {
899
+ console.log("Event:", event.id, "received at:", request.url);
846
900
 
847
901
  await saveImages(result.taskId, result.images);
848
902
  },
@@ -855,13 +909,33 @@ export const POST = mynthWebhookHandler({
855
909
  });
856
910
  ```
857
911
 
858
- The helper reads the raw body, verifies `X-Mynth-Signature`, rejects signatures older than five minutes, and checks `X-Mynth-Event` before calling a typed handler. A completed callback receives the same result that `generate()`, `upscale()` and the other methods return, so `result.images`, `result.cost` and `result.metadata` work the same in both places. A failed callback receives `{ taskId, errors, metadata, raw }`; `metadata` is there for task types whose request takes it. The last handler argument contains the original `request` and `deliveryId`, the `X-Mynth-Delivery` value that every retry repeats.
912
+ The helper reads the raw body, verifies the signature, rejects a timestamp more than five minutes off, and checks the event before calling a typed callback. A completed callback receives the same result that `generate()`, `upscale()` and the other methods return, so `result.images`, `result.cost` and `result.metadata` work the same in both places. A failed callback receives `{ taskId, errors, metadata, raw }`; `metadata` is there for task types whose request takes it. The last argument holds the original `request` and the verified `event`.
913
+
914
+ `onEvent` receives every event, typed, before its callback runs, including event types newer than the SDK. Events without a callback are answered `200`, so Mynth does not retry them.
915
+
916
+ The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `event.id` and skipping IDs you have already handled, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
859
917
 
860
- The route must be publicly reachable, so exclude it from authentication middleware. Make callback side effects idempotent by storing `deliveryId` and skipping IDs you have already handled, and enqueue slow work before returning. Callback errors are propagated so Mynth can retry the delivery.
918
+ Pass `{ webhookSecret: "whsec_..." }` as the second argument only when the application does not use `MYNTH_WEBHOOK_SECRET`.
919
+
920
+ ### Unsigned custom webhooks
921
+
922
+ A request can send its events to URLs of its own with `webhook.custom`. Those deliveries are not signed: put a secret token in the URL, and check it with the `unsigned` option. The helpers then skip signature verification and answer `401` when `verify` returns `false`. Without the option, an unsigned delivery is answered `400`.
923
+
924
+ ```ts
925
+ export const POST = mynthWebhookHandler(
926
+ { imageTaskCompleted: async (result, { event }) => saveImages(result.taskId, result.images) },
927
+ {
928
+ unsigned: {
929
+ verify: (request) =>
930
+ new URL(request.url).searchParams.get("token") === process.env.MY_WEBHOOK_TOKEN,
931
+ },
932
+ },
933
+ );
934
+ ```
861
935
 
862
- Pass `{ webhookSecret: "wbs_..." }` as the second argument only when the application does not use `MYNTH_WEBHOOK_SECRET`. This helper accepts signed, registered webhooks; per-request custom webhooks are not signed.
936
+ Compare the token in constant time if an attacker could time your endpoint. Mynth only ever shows `scheme://host` of a custom URL back, so a token in the path or query does not leak through the task.
863
937
 
864
- ## TanStack Start Integration
938
+ ### TanStack Start Integration
865
939
 
866
940
  Mount the webhook helper directly on a TanStack Start server route:
867
941
 
@@ -874,9 +948,8 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
874
948
  server: {
875
949
  handlers: {
876
950
  POST: mynthWebhookHandler({
877
- imageTaskCompleted: async (result, { request, params, context }) => {
878
- console.log("Completed task:", result.taskId);
879
- console.log("Received at:", request.url);
951
+ imageTaskCompleted: async (result, { event, request, params, context }) => {
952
+ console.log("Event:", event.id, "received at:", request.url);
880
953
  await saveImages(result.taskId, result.images);
881
954
  },
882
955
  imageTaskFailed: async (failure) => {
@@ -888,9 +961,9 @@ export const Route = createFileRoute("/api/webhooks/mynth")({
888
961
  });
889
962
  ```
890
963
 
891
- Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, TanStack Start middleware context, and `deliveryId`.
964
+ Set `MYNTH_WEBHOOK_SECRET` in the server environment, or pass `webhookSecret` as the second argument. Event callbacks receive the original request, route params, TanStack Start middleware context, and the verified `event`.
892
965
 
893
- ## Convex Integration
966
+ ### Convex Integration
894
967
 
895
968
  The package includes a Convex HTTP action helper for webhook verification and event routing.
896
969
 
@@ -898,8 +971,8 @@ The package includes a Convex HTTP action helper for webhook verification and ev
898
971
  import { mynthWebhookAction } from "@mynthio/sdk/convex";
899
972
 
900
973
  export const mynthWebhook = mynthWebhookAction({
901
- imageTaskCompleted: async (result, { context }) => {
902
- console.log("Completed task:", result.taskId);
974
+ imageTaskCompleted: async (result, { context, event }) => {
975
+ console.log("Completed task:", result.taskId, "event:", event.id);
903
976
  console.log(result.images);
904
977
  },
905
978
  imageTaskFailed: async (failure) => {
@@ -950,7 +1023,7 @@ export const mynthWebhook = mynthWebhookAction({
950
1023
  });
951
1024
  ```
952
1025
 
953
- Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicitly as the second argument to `mynthWebhookAction(...)`.
1026
+ Set `MYNTH_WEBHOOK_SECRET` in your environment, or pass `webhookSecret` explicitly as the second argument to `mynthWebhookAction(...)`. The `unsigned` option works the same as in the Next.js helper.
954
1027
 
955
1028
  ## Error Handling
956
1029
 
@@ -975,7 +1048,7 @@ try {
975
1048
  console.log(task.urls);
976
1049
  } catch (error) {
977
1050
  if (error instanceof MynthAPIError) {
978
- // `message` says what to fix. On a VALIDATION_ERROR, `issues` lists each invalid field.
1051
+ // `message` says what to fix. On a validation_error, `issues` lists each invalid field.
979
1052
  console.error(error.status, error.code, error.message, error.issues);
980
1053
  } else if (error instanceof TaskAsyncTimeoutError) {
981
1054
  console.error("Task polling timed out");
@@ -991,6 +1064,21 @@ try {
991
1064
  }
992
1065
  ```
993
1066
 
1067
+ ## Migrating from 0.0.49
1068
+
1069
+ 0.0.50 follows the stable API, which changed in one go. Nothing in it is backward compatible:
1070
+
1071
+ - Request fields are snake_case, and the API now rejects a field it does not know. `size.aspectRatio` is `size.aspect_ratio`.
1072
+ - `access: { pat: { enabled } }` is `generate_public_access_token: true`, and it now defaults to `false`: pass it to get `taskAsync.access.publicAccessToken` from `generateAsync()`, `removeBackgroundAsync()`, `upscaleAsync()` and `video.generateAsync()`.
1073
+ - `webhook.dashboard` is `webhook.registered`.
1074
+ - `MynthAPIError.code` and every task error code are lowercase: `validation_error`, `insufficient_balance`, `provider_error`.
1075
+ - API data the SDK returns as is is snake_case: `MynthSDKTypes.TaskData` (`user_id`, `api_key_id`, `created_at`, `updated_at`), the model catalog (`display_name`, `per_image`, `per_second`, `max_total`) and `video.estimate()` (`estimated_cost`, `estimate_kind`).
1076
+ - A video's `url` can be `null`, like an image's. `result.urls` skips it.
1077
+ - Webhooks follow Standard Webhooks. Every registered webhook got a new `whsec_...` signing secret: copy it from the dashboard into `MYNTH_WEBHOOK_SECRET`. `X-Mynth-Event`, `X-Mynth-Delivery` and `X-Mynth-Signature` are gone; deliveries carry `webhook-id`, `webhook-timestamp` and `webhook-signature`.
1078
+ - The webhook body is an event, `{ id, type, timestamp, data }`, with the task in `data`. `MynthSDKTypes.WebhookPayload` and its variants are replaced by `MynthSDKTypes.WebhookEvent`, and `verifyWebhook()` returns one.
1079
+ - Webhook callbacks get `{ event }` in their last argument instead of `deliveryId`. Deduplicate on `event.id`.
1080
+ - Unsigned deliveries to a custom URL are refused unless the helper gets the `unsigned` option.
1081
+
994
1082
  ## Documentation
995
1083
 
996
1084
  For product documentation and API guides, visit [mynth.io/docs](https://mynth.io/docs).
@@ -1,3 +1,4 @@
1
+ import { p as MynthSDKTypes } from "../video-generation-result.js";
1
2
  import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
2
3
  import { GenericActionCtx, PublicHttpAction } from "convex/server";
3
4
  //#region src/convex/index.d.ts
@@ -8,10 +9,10 @@ export type MynthWebhookActionContext<T extends AnyActionCtx = AnyActionCtx> = {
8
9
  /** The request received by the Convex HTTP action. Its body has already been read. */
9
10
  request: Request;
10
11
  /**
11
- * The `X-Mynth-Delivery` ID. Every retry of a delivery repeats it, so store
12
- * it and skip IDs you have already handled.
12
+ * The verified event. `event.id` is the `webhook-id`: every delivery of the
13
+ * event repeats it, so store it and skip IDs you have already handled.
13
14
  */
14
- deliveryId: string;
15
+ event: MynthSDKTypes.WebhookEvent;
15
16
  };
16
17
  /**
17
18
  * Event handlers for Mynth webhook events.
@@ -22,7 +23,7 @@ export type EventHandlers<T extends AnyActionCtx = AnyActionCtx> = WebhookEventH
22
23
  */
23
24
  export type MynthWebhookActionOptions = WebhookHandlerOptions;
24
25
  /**
25
- * Create a Convex HTTP action for signed Mynth webhooks.
26
+ * Create a Convex HTTP action for Mynth webhooks.
26
27
  *
27
28
  * @example
28
29
  * ```typescript
@@ -2,7 +2,7 @@ import { t as handleWebhookRequest } from "../handler.js";
2
2
  import { httpActionGeneric } from "convex/server";
3
3
  //#region src/convex/index.ts
4
4
  /**
5
- * Create a Convex HTTP action for signed Mynth webhooks.
5
+ * Create a Convex HTTP action for Mynth webhooks.
6
6
  *
7
7
  * @example
8
8
  * ```typescript
@@ -31,10 +31,10 @@ import { httpActionGeneric } from "convex/server";
31
31
  * ```
32
32
  */
33
33
  function mynthWebhookAction(eventHandlers, options = {}) {
34
- return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (deliveryId) => ({
34
+ return httpActionGeneric((context, request) => handleWebhookRequest(request, eventHandlers, (event) => ({
35
35
  context,
36
36
  request,
37
- deliveryId
37
+ event
38
38
  }), options));
39
39
  }
40
40
  //#endregion
package/dist/handler.d.ts CHANGED
@@ -17,7 +17,7 @@ declare const EVENT_HANDLER_NAMES: {
17
17
  readonly "task.video.generate.completed": "videoTaskCompleted";
18
18
  readonly "task.video.generate.failed": "videoTaskFailed";
19
19
  };
20
- type WebhookEvent = MynthSDKTypes.WebhookPayload["event"];
20
+ type WebhookEventType = MynthSDKTypes.WebhookEventType;
21
21
  /**
22
22
  * What each event's callback receives: the same result that polling returns,
23
23
  * or a {@link MynthTaskFailure}.
@@ -38,11 +38,27 @@ type WebhookEventArguments = {
38
38
  "task.video.generate.completed": VideoGenerationResult;
39
39
  "task.video.generate.failed": MynthTaskFailure<MynthSDKTypes.VideoGenerationRequest>;
40
40
  };
41
- /** Event callbacks shared by every framework helper, keyed by handler name. */
42
- type WebhookEventHandlers<TContext> = { [TEvent in WebhookEvent as (typeof EVENT_HANDLER_NAMES)[TEvent]]?: (argument: WebhookEventArguments[TEvent], context: TContext) => void | Promise<void>; };
41
+ /**
42
+ * Event callbacks shared by every framework helper, keyed by handler name,
43
+ * and `onEvent`, which receives every event, including types newer than this
44
+ * SDK, before its typed callback runs. `TContext` carries the verified event:
45
+ * deduplicate on `event.id`, which every delivery repeats.
46
+ */
47
+ type WebhookEventHandlers<TContext> = { [TType in WebhookEventType as (typeof EVENT_HANDLER_NAMES)[TType]]?: (argument: WebhookEventArguments[TType], context: TContext) => void | Promise<void>; } & {
48
+ onEvent?: (event: MynthSDKTypes.WebhookEvent, context: TContext) => void | Promise<void>;
49
+ };
43
50
  type WebhookHandlerOptions = {
44
51
  /** Defaults to MYNTH_WEBHOOK_SECRET, read when each request arrives. */
45
52
  webhookSecret?: string;
53
+ /**
54
+ * Accept unsigned deliveries: a custom webhook URL set on the request.
55
+ * Signatures are not checked at all; `verify` decides instead, usually by
56
+ * checking a secret token you put in the URL. Answers `401` when it returns
57
+ * `false`. Without this, an unsigned delivery answers `400`.
58
+ */
59
+ unsigned?: {
60
+ verify: (request: Request) => boolean | Promise<boolean>;
61
+ };
46
62
  };
47
63
  //#endregion
48
64
  export { WebhookHandlerOptions as n, WebhookEventHandlers as t };