@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 +132 -44
- package/dist/convex/index.d.ts +5 -4
- package/dist/convex/index.js +3 -3
- package/dist/handler.d.ts +19 -3
- package/dist/handler.js +60 -113
- package/dist/index.d.ts +68 -10
- package/dist/index.js +97 -24
- package/dist/next/index.d.ts +7 -6
- package/dist/next/index.js +5 -5
- package/dist/tanstack-start/index.d.ts +6 -5
- package/dist/tanstack-start/index.js +3 -3
- package/dist/utils.js +312 -0
- package/dist/video-generation-result.d.ts +76 -161
- package/package.json +2 -1
- package/dist/video-generation-result.js +0 -216
package/dist/handler.js
CHANGED
|
@@ -1,67 +1,5 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
//#region src/webhooks/utils.ts
|
|
3
|
-
/** Environment variable used when no webhook secret is passed explicitly. */
|
|
4
|
-
const WEBHOOK_SECRET_ENV_VAR = "MYNTH_WEBHOOK_SECRET";
|
|
5
|
-
/** Hex-encoded HMAC-SHA256 digests are always 32 bytes. */
|
|
6
|
-
const SIGNATURE_PATTERN = /^[0-9a-f]{64}$/i;
|
|
7
|
-
const TIMESTAMP_PATTERN = /^\d{1,15}$/;
|
|
8
|
-
const encoder = new TextEncoder();
|
|
9
|
-
/** Read the webhook secret without assuming a Node.js runtime. */
|
|
10
|
-
function getWebhookSecretFromEnv() {
|
|
11
|
-
if (typeof process !== "undefined" && process.env) return process.env[WEBHOOK_SECRET_ENV_VAR];
|
|
12
|
-
}
|
|
13
|
-
function parseSignatureHeader(signatureHeader) {
|
|
14
|
-
let timestamp;
|
|
15
|
-
const signatures = [];
|
|
16
|
-
for (const part of signatureHeader.split(",")) {
|
|
17
|
-
const separator = part.indexOf("=");
|
|
18
|
-
if (separator === -1) continue;
|
|
19
|
-
const key = part.slice(0, separator).trim();
|
|
20
|
-
const value = part.slice(separator + 1).trim();
|
|
21
|
-
if (key === "t" && TIMESTAMP_PATTERN.test(value)) timestamp = value;
|
|
22
|
-
else if (key === "v1" && SIGNATURE_PATTERN.test(value)) signatures.push(hexToBytes(value));
|
|
23
|
-
}
|
|
24
|
-
if (timestamp === void 0 || signatures.length === 0) return null;
|
|
25
|
-
return {
|
|
26
|
-
timestamp,
|
|
27
|
-
signatures
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Verify a Mynth HMAC-SHA256 signature against the raw request body.
|
|
32
|
-
*
|
|
33
|
-
* Rejects timestamps more than five minutes from `now` to limit replays. The
|
|
34
|
-
* comparison runs inside Web Crypto, so it does not leak timing information.
|
|
35
|
-
*/
|
|
36
|
-
async function verifySignature(body, signatureHeader, secret, now = Date.now()) {
|
|
37
|
-
const parsed = parseSignatureHeader(signatureHeader);
|
|
38
|
-
if (!parsed) return false;
|
|
39
|
-
const ageSeconds = Math.floor(now / 1e3) - Number(parsed.timestamp);
|
|
40
|
-
if (Math.abs(ageSeconds) > 300) return false;
|
|
41
|
-
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
42
|
-
name: "HMAC",
|
|
43
|
-
hash: "SHA-256"
|
|
44
|
-
}, false, ["verify"]);
|
|
45
|
-
const message = concatBytes(encoder.encode(`${parsed.timestamp}.`), body);
|
|
46
|
-
for (const signature of parsed.signatures) if (await crypto.subtle.verify("HMAC", key, signature, message)) return true;
|
|
47
|
-
return false;
|
|
48
|
-
}
|
|
49
|
-
function hexToBytes(hex) {
|
|
50
|
-
const bytes = new Uint8Array(hex.length / 2);
|
|
51
|
-
for (let i = 0; i < bytes.length; i++) bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
52
|
-
return bytes;
|
|
53
|
-
}
|
|
54
|
-
function concatBytes(a, b) {
|
|
55
|
-
const bytes = new Uint8Array(a.length + b.length);
|
|
56
|
-
bytes.set(a);
|
|
57
|
-
bytes.set(b, a.length);
|
|
58
|
-
return bytes;
|
|
59
|
-
}
|
|
60
|
-
//#endregion
|
|
1
|
+
import { _ as toImageAltResult, a as parseWebhookEvent, c as toVideoGenerationResult, d as taskFailureFromWebhook, f as toImageUpscaleResult, g as toImageGenerationResult, h as toImageRateResult, i as getWebhookSecretFromEnv, m as toImageRemoveBackgroundResult, n as WEBHOOK_SIGNATURE_HEADER, p as toImageReviewResult, r as WEBHOOK_TIMESTAMP_HEADER, s as verifySignature, t as WEBHOOK_ID_HEADER, u as completedTaskFromWebhook } from "./utils.js";
|
|
61
2
|
//#region src/webhooks/handler.ts
|
|
62
|
-
const WEBHOOK_EVENT_HEADER = "X-Mynth-Event";
|
|
63
|
-
const WEBHOOK_DELIVERY_HEADER = "X-Mynth-Delivery";
|
|
64
|
-
const WEBHOOK_SIGNATURE_HEADER = "X-Mynth-Signature";
|
|
65
3
|
/** Maps every webhook event to the callback name the framework helpers accept. */
|
|
66
4
|
const EVENT_HANDLER_NAMES = {
|
|
67
5
|
"task.image.generate.completed": "imageTaskCompleted",
|
|
@@ -79,78 +17,87 @@ const EVENT_HANDLER_NAMES = {
|
|
|
79
17
|
"task.video.generate.completed": "videoTaskCompleted",
|
|
80
18
|
"task.video.generate.failed": "videoTaskFailed"
|
|
81
19
|
};
|
|
82
|
-
/** Builds each event's callback argument from
|
|
20
|
+
/** Builds each event's callback argument from the event. */
|
|
83
21
|
const EVENT_ARGUMENTS = {
|
|
84
|
-
"task.image.generate.completed": (
|
|
85
|
-
"task.image.generate.failed": (
|
|
86
|
-
...taskFailureFromWebhook(
|
|
87
|
-
metadata:
|
|
22
|
+
"task.image.generate.completed": (event) => toImageGenerationResult(completedTaskFromWebhook(event)),
|
|
23
|
+
"task.image.generate.failed": (event) => ({
|
|
24
|
+
...taskFailureFromWebhook(event),
|
|
25
|
+
metadata: event.data.request.metadata
|
|
88
26
|
}),
|
|
89
|
-
"task.image.rate.completed": (
|
|
27
|
+
"task.image.rate.completed": (event) => toImageRateResult(completedTaskFromWebhook(event)),
|
|
90
28
|
"task.image.rate.failed": taskFailureFromWebhook,
|
|
91
|
-
"task.image.alt.completed": (
|
|
29
|
+
"task.image.alt.completed": (event) => toImageAltResult(completedTaskFromWebhook(event)),
|
|
92
30
|
"task.image.alt.failed": taskFailureFromWebhook,
|
|
93
|
-
"task.image.review.completed": (
|
|
31
|
+
"task.image.review.completed": (event) => toImageReviewResult(completedTaskFromWebhook(event)),
|
|
94
32
|
"task.image.review.failed": taskFailureFromWebhook,
|
|
95
|
-
"task.image.remove_background.completed": (
|
|
96
|
-
"task.image.remove_background.failed": (
|
|
97
|
-
...taskFailureFromWebhook(
|
|
98
|
-
metadata:
|
|
33
|
+
"task.image.remove_background.completed": (event) => toImageRemoveBackgroundResult(completedTaskFromWebhook(event)),
|
|
34
|
+
"task.image.remove_background.failed": (event) => ({
|
|
35
|
+
...taskFailureFromWebhook(event),
|
|
36
|
+
metadata: event.data.request.metadata
|
|
99
37
|
}),
|
|
100
|
-
"task.image.upscale.completed": (
|
|
101
|
-
"task.image.upscale.failed": (
|
|
102
|
-
...taskFailureFromWebhook(
|
|
103
|
-
metadata:
|
|
38
|
+
"task.image.upscale.completed": (event) => toImageUpscaleResult(completedTaskFromWebhook(event)),
|
|
39
|
+
"task.image.upscale.failed": (event) => ({
|
|
40
|
+
...taskFailureFromWebhook(event),
|
|
41
|
+
metadata: event.data.request.metadata
|
|
104
42
|
}),
|
|
105
|
-
"task.video.generate.completed": (
|
|
106
|
-
"task.video.generate.failed": (
|
|
107
|
-
...taskFailureFromWebhook(
|
|
108
|
-
metadata:
|
|
43
|
+
"task.video.generate.completed": (event) => toVideoGenerationResult(completedTaskFromWebhook(event)),
|
|
44
|
+
"task.video.generate.failed": (event) => ({
|
|
45
|
+
...taskFailureFromWebhook(event),
|
|
46
|
+
metadata: event.data.request.metadata
|
|
109
47
|
})
|
|
110
48
|
};
|
|
111
49
|
/**
|
|
112
|
-
* Verify a
|
|
50
|
+
* Verify a Mynth webhook request and dispatch its event to the matching callback.
|
|
113
51
|
*
|
|
114
|
-
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
52
|
+
* Signed deliveries (registered webhooks) answer `400` for a missing header, a
|
|
53
|
+
* missing or invalid signature, a timestamp more than five minutes off, a
|
|
54
|
+
* malformed body, or a body `id` other than `webhook-id`. Unsigned deliveries
|
|
55
|
+
* (custom URLs) are accepted only with the `unsigned` option, and answer `401`
|
|
56
|
+
* when its `verify` refuses them.
|
|
57
|
+
*
|
|
58
|
+
* Answers `200` for events without a callback, including event types newer
|
|
59
|
+
* than this SDK. Callback errors, and events that do not build into a result,
|
|
60
|
+
* propagate, so the framework answers `5xx` and Mynth retries the delivery.
|
|
120
61
|
*/
|
|
121
62
|
async function handleWebhookRequest(request, eventHandlers, createContext, options) {
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const deliveryId = request.headers.get(WEBHOOK_DELIVERY_HEADER);
|
|
126
|
-
const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
|
|
127
|
-
if (!event || !deliveryId || !signature) return badRequest();
|
|
63
|
+
const id = request.headers.get(WEBHOOK_ID_HEADER);
|
|
64
|
+
const timestamp = request.headers.get(WEBHOOK_TIMESTAMP_HEADER);
|
|
65
|
+
if (!id || !timestamp) return badRequest();
|
|
128
66
|
const body = new Uint8Array(await request.arrayBuffer());
|
|
129
|
-
if (
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
67
|
+
if (options.unsigned) {
|
|
68
|
+
if (!await options.unsigned.verify(request)) return unauthorized();
|
|
69
|
+
} else {
|
|
70
|
+
const secret = options.webhookSecret ?? getWebhookSecretFromEnv();
|
|
71
|
+
if (!secret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass it as an option or set the environment variable.");
|
|
72
|
+
const signature = request.headers.get(WEBHOOK_SIGNATURE_HEADER);
|
|
73
|
+
if (!signature) return badRequest();
|
|
74
|
+
if (!await verifySignature({
|
|
75
|
+
id,
|
|
76
|
+
timestamp,
|
|
77
|
+
signature,
|
|
78
|
+
body,
|
|
79
|
+
secret
|
|
80
|
+
})) return badRequest();
|
|
81
|
+
}
|
|
82
|
+
const event = parseWebhookEvent(body, id);
|
|
83
|
+
if (!event) return badRequest();
|
|
84
|
+
const context = createContext(event);
|
|
85
|
+
await eventHandlers.onEvent?.(event, context);
|
|
86
|
+
if (!Object.hasOwn(EVENT_HANDLER_NAMES, event.type)) return ok();
|
|
87
|
+
const handler = eventHandlers[EVENT_HANDLER_NAMES[event.type]];
|
|
134
88
|
if (!handler) return ok();
|
|
135
|
-
const toArgument = EVENT_ARGUMENTS[
|
|
136
|
-
await handler(toArgument(
|
|
89
|
+
const toArgument = EVENT_ARGUMENTS[event.type];
|
|
90
|
+
await handler(toArgument(event), context);
|
|
137
91
|
return ok();
|
|
138
92
|
}
|
|
139
|
-
function parsePayload(body) {
|
|
140
|
-
let payload;
|
|
141
|
-
try {
|
|
142
|
-
payload = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
|
|
143
|
-
} catch {
|
|
144
|
-
return null;
|
|
145
|
-
}
|
|
146
|
-
if (typeof payload !== "object" || payload === null || !("event" in payload) || typeof payload.event !== "string" || !("task" in payload) || typeof payload.task !== "object" || payload.task === null || !("id" in payload.task) || typeof payload.task.id !== "string") return null;
|
|
147
|
-
return payload;
|
|
148
|
-
}
|
|
149
93
|
function ok() {
|
|
150
94
|
return new Response("OK", { status: 200 });
|
|
151
95
|
}
|
|
152
96
|
function badRequest() {
|
|
153
97
|
return new Response("Bad Request", { status: 400 });
|
|
154
98
|
}
|
|
99
|
+
function unauthorized() {
|
|
100
|
+
return new Response("Unauthorized", { status: 401 });
|
|
101
|
+
}
|
|
155
102
|
//#endregion
|
|
156
103
|
export { handleWebhookRequest as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -6,11 +6,11 @@ import { _ as AvailableVideoModel, a as ImageRemoveBackgroundResult, b as VideoR
|
|
|
6
6
|
export declare class MynthAPIError extends Error {
|
|
7
7
|
/** HTTP status code of the failed request */
|
|
8
8
|
readonly status: number;
|
|
9
|
-
/** Error code from the API response, if available */
|
|
9
|
+
/** Error code from the API response, if available, e.g. `insufficient_balance` */
|
|
10
10
|
readonly code?: string | undefined;
|
|
11
11
|
/**
|
|
12
|
-
* One entry per invalid field when `code` is `
|
|
13
|
-
*
|
|
12
|
+
* One entry per invalid or unknown field when `code` is `validation_error`.
|
|
13
|
+
* `message` already states all of them.
|
|
14
14
|
*/
|
|
15
15
|
readonly issues?: ReadonlyArray<MynthAPIErrorIssue> | undefined;
|
|
16
16
|
constructor(message: string, status: number, code?: string, issues?: ReadonlyArray<MynthAPIErrorIssue>);
|
|
@@ -156,6 +156,53 @@ export declare class TaskAsync<ResultT> {
|
|
|
156
156
|
private sleep;
|
|
157
157
|
}
|
|
158
158
|
//#endregion
|
|
159
|
+
//#region src/webhooks/utils.d.ts
|
|
160
|
+
/** The headers of a webhook request, from a `Headers` or a Node-style header object. */
|
|
161
|
+
type WebhookHeaders = Headers | Record<string, string | string[] | undefined>;
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/webhooks/verify.d.ts
|
|
164
|
+
/** A webhook request failed verification: unsigned, wrongly signed, stale, or not an event. */
|
|
165
|
+
export declare class MynthWebhookVerificationError extends Error {
|
|
166
|
+
constructor(message: string);
|
|
167
|
+
}
|
|
168
|
+
/** A webhook request as it arrived. */
|
|
169
|
+
type MynthWebhookRequest = {
|
|
170
|
+
/**
|
|
171
|
+
* The raw body, exactly as received. Parsing and serializing the JSON again
|
|
172
|
+
* can change the bytes, and the signature covers the bytes.
|
|
173
|
+
*/
|
|
174
|
+
body: string | Uint8Array | ArrayBuffer;
|
|
175
|
+
/** A `Headers` object, or a Node-style header record such as `req.headers`. */
|
|
176
|
+
headers: WebhookHeaders;
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* Verify a signed Mynth webhook and return its event.
|
|
180
|
+
*
|
|
181
|
+
* Checks the Standard Webhooks signature over `webhook-id`, `webhook-timestamp`
|
|
182
|
+
* and the raw body, rejects a timestamp more than five minutes off, and checks
|
|
183
|
+
* that the body's `id` is the `webhook-id`. Deduplicate on `event.id`: every
|
|
184
|
+
* delivery of the event repeats it.
|
|
185
|
+
*
|
|
186
|
+
* An event type newer than this SDK is returned as is, so keep a `default`
|
|
187
|
+
* branch when you switch on `event.type`.
|
|
188
|
+
*
|
|
189
|
+
* @param secret - The webhook's `whsec_` secret. Defaults to MYNTH_WEBHOOK_SECRET.
|
|
190
|
+
* @throws {MynthWebhookVerificationError} If the request is not a valid, signed event
|
|
191
|
+
* @throws {Error} If there is no secret, or it is not a `whsec_` secret
|
|
192
|
+
*
|
|
193
|
+
* @example
|
|
194
|
+
* ```typescript
|
|
195
|
+
* const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
|
|
196
|
+
*
|
|
197
|
+
* switch (event.type) {
|
|
198
|
+
* case "task.image.generate.completed":
|
|
199
|
+
* console.log(event.data.result.images);
|
|
200
|
+
* break;
|
|
201
|
+
* }
|
|
202
|
+
* ```
|
|
203
|
+
*/
|
|
204
|
+
export declare function verifyWebhook(request: MynthWebhookRequest, secret?: string | undefined): Promise<MynthSDKTypes.WebhookEvent>;
|
|
205
|
+
//#endregion
|
|
159
206
|
//#region src/index.d.ts
|
|
160
207
|
/**
|
|
161
208
|
* Configuration options for the Mynth client.
|
|
@@ -297,6 +344,7 @@ declare class MynthImage {
|
|
|
297
344
|
* ```typescript
|
|
298
345
|
* const taskAsync = await image.generateAsync({
|
|
299
346
|
* prompt: "A futuristic cityscape",
|
|
347
|
+
* generate_public_access_token: true,
|
|
300
348
|
* });
|
|
301
349
|
*
|
|
302
350
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -427,7 +475,10 @@ declare class MynthImage {
|
|
|
427
475
|
*
|
|
428
476
|
* @example
|
|
429
477
|
* ```typescript
|
|
430
|
-
* const taskAsync = await image.removeBackgroundAsync({
|
|
478
|
+
* const taskAsync = await image.removeBackgroundAsync({
|
|
479
|
+
* url: "https://...",
|
|
480
|
+
* generate_public_access_token: true,
|
|
481
|
+
* });
|
|
431
482
|
*
|
|
432
483
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
433
484
|
* ```
|
|
@@ -439,7 +490,7 @@ declare class MynthImage {
|
|
|
439
490
|
*
|
|
440
491
|
* Mynth picks the model. `effort` sets the price, so it has no default. The
|
|
441
492
|
* upscaled image can be at most 4096x4096 pixels; a larger request fails
|
|
442
|
-
* with `
|
|
493
|
+
* with `output_too_large` and is not charged.
|
|
443
494
|
*
|
|
444
495
|
* @param request - Image URL or local file, size, and effort, plus optional output, destination, webhook, and metadata
|
|
445
496
|
* @returns An ImageUpscaleResult with the enlarged image
|
|
@@ -459,7 +510,12 @@ declare class MynthImage {
|
|
|
459
510
|
*
|
|
460
511
|
* @example
|
|
461
512
|
* ```typescript
|
|
462
|
-
* const taskAsync = await image.upscaleAsync({
|
|
513
|
+
* const taskAsync = await image.upscaleAsync({
|
|
514
|
+
* url: "https://...",
|
|
515
|
+
* size: "2x",
|
|
516
|
+
* effort: "low",
|
|
517
|
+
* generate_public_access_token: true,
|
|
518
|
+
* });
|
|
463
519
|
*
|
|
464
520
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
465
521
|
* ```
|
|
@@ -523,7 +579,8 @@ declare class MynthVideo {
|
|
|
523
579
|
* Start video generation without waiting for completion.
|
|
524
580
|
*
|
|
525
581
|
* The preferred entry point for server code: hand `taskAsync.id` and
|
|
526
|
-
* `taskAsync.access.publicAccessToken` to the browser
|
|
582
|
+
* `taskAsync.access.publicAccessToken` to the browser (pass
|
|
583
|
+
* `generate_public_access_token: true` to get one), or register a webhook,
|
|
527
584
|
* instead of holding a connection open for the length of a render.
|
|
528
585
|
*
|
|
529
586
|
* @param request - Video generation request parameters
|
|
@@ -534,6 +591,7 @@ declare class MynthVideo {
|
|
|
534
591
|
* const taskAsync = await video.generateAsync({
|
|
535
592
|
* model: "prunaai/p-video",
|
|
536
593
|
* prompt: "A neon city street in the rain",
|
|
594
|
+
* generate_public_access_token: true,
|
|
537
595
|
* });
|
|
538
596
|
*
|
|
539
597
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -560,11 +618,11 @@ declare class MynthVideo {
|
|
|
560
618
|
* video pins a concrete model, the returned estimate is exact.
|
|
561
619
|
*
|
|
562
620
|
* @param request - The same request you would pass to `generate()`
|
|
563
|
-
* @returns The estimated cost in USD
|
|
621
|
+
* @returns The estimated cost in USD, as the API returns it
|
|
564
622
|
*
|
|
565
623
|
* @example
|
|
566
624
|
* ```typescript
|
|
567
|
-
* const {
|
|
625
|
+
* const { estimated_cost } = await video.estimate({
|
|
568
626
|
* model: "google/gemini-omni-flash-1.1",
|
|
569
627
|
* prompt: "A timelapse of clouds over a canyon",
|
|
570
628
|
* duration: 10,
|
|
@@ -636,4 +694,4 @@ declare class Mynth {
|
|
|
636
694
|
get video(): MynthVideo;
|
|
637
695
|
}
|
|
638
696
|
//#endregion
|
|
639
|
-
export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ImageAltResult, type ImageGenerationResult, type ImageRateResult, type ImageRemoveBackgroundResult, type ImageReviewResult, type ImageUpscaleResult, type ModelCapability, Mynth, Mynth as default, type MynthAPIErrorIssue, type MynthCompletedTask, type MynthGeneratedImage, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthOutputImage, type MynthOutputVideo, type MynthRequestOptions, type MynthSDKTypes, type MynthTaskFailure, MynthVideo, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoGenerationResult, type VideoInputRole, type VideoResolutionTier };
|
|
697
|
+
export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, type AvailableModel, type AvailableVideoModel, type ImageAltResult, type ImageGenerationResult, type ImageRateResult, type ImageRemoveBackgroundResult, type ImageReviewResult, type ImageUpscaleResult, type ModelCapability, Mynth, Mynth as default, type MynthAPIErrorIssue, type MynthCompletedTask, type MynthGeneratedImage, MynthImage, type MynthModel, type MynthModelPricing, MynthModels, type MynthOptions, type MynthOutputImage, type MynthOutputVideo, type MynthRequestOptions, type MynthSDKTypes, type MynthTaskFailure, MynthVideo, type MynthWebhookRequest, type TaskAsyncAccess, type TaskAsyncWaitOptions, type VideoGenerationResult, type VideoInputRole, type VideoResolutionTier };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { _ as toImageAltResult, a as parseWebhookEvent, c as toVideoGenerationResult, f as toImageUpscaleResult, g as toImageGenerationResult, h as toImageRateResult, i as getWebhookSecretFromEnv, l as completedTaskFromData, m as toImageRemoveBackgroundResult, n as WEBHOOK_SIGNATURE_HEADER, o as readHeader, p as toImageReviewResult, r as WEBHOOK_TIMESTAMP_HEADER, s as verifySignature, t as WEBHOOK_ID_HEADER } from "./utils.js";
|
|
2
2
|
//#region src/constants.ts
|
|
3
3
|
/** Base URL for the Mynth API */
|
|
4
4
|
const API_URL = "https://api.mynth.io";
|
|
@@ -400,11 +400,11 @@ const AVAILABLE_VIDEO_MODELS = [
|
|
|
400
400
|
var MynthAPIError = class extends Error {
|
|
401
401
|
/** HTTP status code of the failed request */
|
|
402
402
|
status;
|
|
403
|
-
/** Error code from the API response, if available */
|
|
403
|
+
/** Error code from the API response, if available, e.g. `insufficient_balance` */
|
|
404
404
|
code;
|
|
405
405
|
/**
|
|
406
|
-
* One entry per invalid field when `code` is `
|
|
407
|
-
*
|
|
406
|
+
* One entry per invalid or unknown field when `code` is `validation_error`.
|
|
407
|
+
* `message` already states all of them.
|
|
408
408
|
*/
|
|
409
409
|
issues;
|
|
410
410
|
constructor(message, status, code, issues) {
|
|
@@ -416,8 +416,9 @@ var MynthAPIError = class extends Error {
|
|
|
416
416
|
}
|
|
417
417
|
};
|
|
418
418
|
function createApiError(data, status) {
|
|
419
|
-
const
|
|
420
|
-
|
|
419
|
+
const body = typeof data === "object" && data !== null ? data : {};
|
|
420
|
+
const error = typeof body.error === "object" && body.error !== null ? body.error : {};
|
|
421
|
+
return new MynthAPIError(typeof error.message === "string" && error.message || `Request failed with status ${status}`, status, typeof error.code === "string" ? error.code : void 0, Array.isArray(error.issues) ? error.issues : void 0);
|
|
421
422
|
}
|
|
422
423
|
/** An error body that is not JSON (a proxy's HTML page, say) still yields an API error. */
|
|
423
424
|
async function readErrorBody(response) {
|
|
@@ -825,6 +826,67 @@ async function resolveInputs(client, inputs, { signal } = {}) {
|
|
|
825
826
|
});
|
|
826
827
|
}
|
|
827
828
|
//#endregion
|
|
829
|
+
//#region src/webhooks/verify.ts
|
|
830
|
+
/** A webhook request failed verification: unsigned, wrongly signed, stale, or not an event. */
|
|
831
|
+
var MynthWebhookVerificationError = class extends Error {
|
|
832
|
+
constructor(message) {
|
|
833
|
+
super(message);
|
|
834
|
+
this.name = "MynthWebhookVerificationError";
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
function toBytes(body) {
|
|
838
|
+
if (typeof body === "string") return new TextEncoder().encode(body);
|
|
839
|
+
return body instanceof Uint8Array ? body : new Uint8Array(body);
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* Verify a signed Mynth webhook and return its event.
|
|
843
|
+
*
|
|
844
|
+
* Checks the Standard Webhooks signature over `webhook-id`, `webhook-timestamp`
|
|
845
|
+
* and the raw body, rejects a timestamp more than five minutes off, and checks
|
|
846
|
+
* that the body's `id` is the `webhook-id`. Deduplicate on `event.id`: every
|
|
847
|
+
* delivery of the event repeats it.
|
|
848
|
+
*
|
|
849
|
+
* An event type newer than this SDK is returned as is, so keep a `default`
|
|
850
|
+
* branch when you switch on `event.type`.
|
|
851
|
+
*
|
|
852
|
+
* @param secret - The webhook's `whsec_` secret. Defaults to MYNTH_WEBHOOK_SECRET.
|
|
853
|
+
* @throws {MynthWebhookVerificationError} If the request is not a valid, signed event
|
|
854
|
+
* @throws {Error} If there is no secret, or it is not a `whsec_` secret
|
|
855
|
+
*
|
|
856
|
+
* @example
|
|
857
|
+
* ```typescript
|
|
858
|
+
* const event = await verifyWebhook({ body: await request.text(), headers: request.headers });
|
|
859
|
+
*
|
|
860
|
+
* switch (event.type) {
|
|
861
|
+
* case "task.image.generate.completed":
|
|
862
|
+
* console.log(event.data.result.images);
|
|
863
|
+
* break;
|
|
864
|
+
* }
|
|
865
|
+
* ```
|
|
866
|
+
*/
|
|
867
|
+
async function verifyWebhook(request, secret = getWebhookSecretFromEnv()) {
|
|
868
|
+
if (!secret) throw new Error("MYNTH_WEBHOOK_SECRET is required. Either pass the secret or set the environment variable.");
|
|
869
|
+
const id = readHeader(request.headers, WEBHOOK_ID_HEADER);
|
|
870
|
+
const timestamp = readHeader(request.headers, WEBHOOK_TIMESTAMP_HEADER);
|
|
871
|
+
const signature = readHeader(request.headers, WEBHOOK_SIGNATURE_HEADER);
|
|
872
|
+
if (!id || !timestamp || !signature) throw new MynthWebhookVerificationError(`Missing ${[
|
|
873
|
+
!id && "webhook-id",
|
|
874
|
+
!timestamp && "webhook-timestamp",
|
|
875
|
+
!signature && "webhook-signature"
|
|
876
|
+
].filter(Boolean).join(", ")} header. Only registered webhooks are signed.`);
|
|
877
|
+
const body = toBytes(request.body);
|
|
878
|
+
if (!await verifySignature({
|
|
879
|
+
id,
|
|
880
|
+
timestamp,
|
|
881
|
+
signature,
|
|
882
|
+
body,
|
|
883
|
+
secret
|
|
884
|
+
})) throw new MynthWebhookVerificationError("The webhook signature does not match, or its timestamp is more than five minutes off.");
|
|
885
|
+
const event = parseWebhookEvent(body, id);
|
|
886
|
+
if (!event) throw new MynthWebhookVerificationError("The webhook body is not a Mynth event for this webhook-id.");
|
|
887
|
+
return event;
|
|
888
|
+
}
|
|
889
|
+
//#endregion
|
|
828
890
|
//#region src/index.ts
|
|
829
891
|
/**
|
|
830
892
|
* Attempts to read the API key from environment variables.
|
|
@@ -928,6 +990,7 @@ var MynthImage = class {
|
|
|
928
990
|
* ```typescript
|
|
929
991
|
* const taskAsync = await image.generateAsync({
|
|
930
992
|
* prompt: "A futuristic cityscape",
|
|
993
|
+
* generate_public_access_token: true,
|
|
931
994
|
* });
|
|
932
995
|
*
|
|
933
996
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -943,9 +1006,9 @@ var MynthImage = class {
|
|
|
943
1006
|
inputs,
|
|
944
1007
|
destination: request.destination ?? this.defaultDestination
|
|
945
1008
|
}, { signal })).data;
|
|
946
|
-
return new TaskAsync(data.
|
|
1009
|
+
return new TaskAsync(data.task_id, {
|
|
947
1010
|
client: this.client,
|
|
948
|
-
pat: data.
|
|
1011
|
+
pat: data.public_access_token,
|
|
949
1012
|
resultFactory: (data) => toImageGenerationResult(completedTaskFromData(data, "Image generation"))
|
|
950
1013
|
});
|
|
951
1014
|
}
|
|
@@ -1013,7 +1076,7 @@ var MynthImage = class {
|
|
|
1013
1076
|
...rest,
|
|
1014
1077
|
url
|
|
1015
1078
|
})).data;
|
|
1016
|
-
return new TaskAsync(data.
|
|
1079
|
+
return new TaskAsync(data.task_id, {
|
|
1017
1080
|
client: this.client,
|
|
1018
1081
|
resultFactory: (taskData) => toImageRateResult(completedTaskFromData(taskData, "Image rate"))
|
|
1019
1082
|
});
|
|
@@ -1055,7 +1118,7 @@ var MynthImage = class {
|
|
|
1055
1118
|
async createAltTask(request) {
|
|
1056
1119
|
const url = await this.resolveUrlOrFile(request);
|
|
1057
1120
|
const data = (await this.client.post(ALT_IMAGE_PATH, { url })).data;
|
|
1058
|
-
return new TaskAsync(data.
|
|
1121
|
+
return new TaskAsync(data.task_id, {
|
|
1059
1122
|
client: this.client,
|
|
1060
1123
|
resultFactory: (taskData) => toImageAltResult(completedTaskFromData(taskData, "Image alt"))
|
|
1061
1124
|
});
|
|
@@ -1092,7 +1155,7 @@ var MynthImage = class {
|
|
|
1092
1155
|
...rest,
|
|
1093
1156
|
url
|
|
1094
1157
|
})).data;
|
|
1095
|
-
return new TaskAsync(data.
|
|
1158
|
+
return new TaskAsync(data.task_id, {
|
|
1096
1159
|
client: this.client,
|
|
1097
1160
|
resultFactory: (taskData) => toImageReviewResult(completedTaskFromData(taskData, "Image review"))
|
|
1098
1161
|
});
|
|
@@ -1123,7 +1186,10 @@ var MynthImage = class {
|
|
|
1123
1186
|
*
|
|
1124
1187
|
* @example
|
|
1125
1188
|
* ```typescript
|
|
1126
|
-
* const taskAsync = await image.removeBackgroundAsync({
|
|
1189
|
+
* const taskAsync = await image.removeBackgroundAsync({
|
|
1190
|
+
* url: "https://...",
|
|
1191
|
+
* generate_public_access_token: true,
|
|
1192
|
+
* });
|
|
1127
1193
|
*
|
|
1128
1194
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
1129
1195
|
* ```
|
|
@@ -1139,9 +1205,9 @@ var MynthImage = class {
|
|
|
1139
1205
|
url,
|
|
1140
1206
|
destination: request.destination ?? this.defaultDestination
|
|
1141
1207
|
})).data;
|
|
1142
|
-
return new TaskAsync(data.
|
|
1208
|
+
return new TaskAsync(data.task_id, {
|
|
1143
1209
|
client: this.client,
|
|
1144
|
-
pat: data.
|
|
1210
|
+
pat: data.public_access_token,
|
|
1145
1211
|
resultFactory: (taskData) => toImageRemoveBackgroundResult(completedTaskFromData(taskData, "Image remove background"))
|
|
1146
1212
|
});
|
|
1147
1213
|
}
|
|
@@ -1150,7 +1216,7 @@ var MynthImage = class {
|
|
|
1150
1216
|
*
|
|
1151
1217
|
* Mynth picks the model. `effort` sets the price, so it has no default. The
|
|
1152
1218
|
* upscaled image can be at most 4096x4096 pixels; a larger request fails
|
|
1153
|
-
* with `
|
|
1219
|
+
* with `output_too_large` and is not charged.
|
|
1154
1220
|
*
|
|
1155
1221
|
* @param request - Image URL or local file, size, and effort, plus optional output, destination, webhook, and metadata
|
|
1156
1222
|
* @returns An ImageUpscaleResult with the enlarged image
|
|
@@ -1172,7 +1238,12 @@ var MynthImage = class {
|
|
|
1172
1238
|
*
|
|
1173
1239
|
* @example
|
|
1174
1240
|
* ```typescript
|
|
1175
|
-
* const taskAsync = await image.upscaleAsync({
|
|
1241
|
+
* const taskAsync = await image.upscaleAsync({
|
|
1242
|
+
* url: "https://...",
|
|
1243
|
+
* size: "2x",
|
|
1244
|
+
* effort: "low",
|
|
1245
|
+
* generate_public_access_token: true,
|
|
1246
|
+
* });
|
|
1176
1247
|
*
|
|
1177
1248
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
1178
1249
|
* ```
|
|
@@ -1188,9 +1259,9 @@ var MynthImage = class {
|
|
|
1188
1259
|
url,
|
|
1189
1260
|
destination: request.destination ?? this.defaultDestination
|
|
1190
1261
|
})).data;
|
|
1191
|
-
return new TaskAsync(data.
|
|
1262
|
+
return new TaskAsync(data.task_id, {
|
|
1192
1263
|
client: this.client,
|
|
1193
|
-
pat: data.
|
|
1264
|
+
pat: data.public_access_token,
|
|
1194
1265
|
resultFactory: (taskData) => toImageUpscaleResult(completedTaskFromData(taskData, "Image upscale"))
|
|
1195
1266
|
});
|
|
1196
1267
|
}
|
|
@@ -1260,7 +1331,8 @@ var MynthVideo = class {
|
|
|
1260
1331
|
* Start video generation without waiting for completion.
|
|
1261
1332
|
*
|
|
1262
1333
|
* The preferred entry point for server code: hand `taskAsync.id` and
|
|
1263
|
-
* `taskAsync.access.publicAccessToken` to the browser
|
|
1334
|
+
* `taskAsync.access.publicAccessToken` to the browser (pass
|
|
1335
|
+
* `generate_public_access_token: true` to get one), or register a webhook,
|
|
1264
1336
|
* instead of holding a connection open for the length of a render.
|
|
1265
1337
|
*
|
|
1266
1338
|
* @param request - Video generation request parameters
|
|
@@ -1271,6 +1343,7 @@ var MynthVideo = class {
|
|
|
1271
1343
|
* const taskAsync = await video.generateAsync({
|
|
1272
1344
|
* model: "prunaai/p-video",
|
|
1273
1345
|
* prompt: "A neon city street in the rain",
|
|
1346
|
+
* generate_public_access_token: true,
|
|
1274
1347
|
* });
|
|
1275
1348
|
*
|
|
1276
1349
|
* return { id: taskAsync.id, access: taskAsync.access };
|
|
@@ -1301,11 +1374,11 @@ var MynthVideo = class {
|
|
|
1301
1374
|
* video pins a concrete model, the returned estimate is exact.
|
|
1302
1375
|
*
|
|
1303
1376
|
* @param request - The same request you would pass to `generate()`
|
|
1304
|
-
* @returns The estimated cost in USD
|
|
1377
|
+
* @returns The estimated cost in USD, as the API returns it
|
|
1305
1378
|
*
|
|
1306
1379
|
* @example
|
|
1307
1380
|
* ```typescript
|
|
1308
|
-
* const {
|
|
1381
|
+
* const { estimated_cost } = await video.estimate({
|
|
1309
1382
|
* model: "google/gemini-omni-flash-1.1",
|
|
1310
1383
|
* prompt: "A timelapse of clouds over a canyon",
|
|
1311
1384
|
* duration: 10,
|
|
@@ -1326,9 +1399,9 @@ var MynthVideo = class {
|
|
|
1326
1399
|
}
|
|
1327
1400
|
async createGenerationTask(request) {
|
|
1328
1401
|
const data = (await this.client.post(GENERATE_VIDEO_PATH, await this.toRequestBody(request))).data;
|
|
1329
|
-
return new TaskAsync(data.
|
|
1402
|
+
return new TaskAsync(data.task_id, {
|
|
1330
1403
|
client: this.client,
|
|
1331
|
-
pat: data.
|
|
1404
|
+
pat: data.public_access_token,
|
|
1332
1405
|
polling: VIDEO_POLLING,
|
|
1333
1406
|
resultFactory: (taskData) => toVideoGenerationResult(completedTaskFromData(taskData, "Video generation"))
|
|
1334
1407
|
});
|
|
@@ -1407,4 +1480,4 @@ var Mynth = class {
|
|
|
1407
1480
|
}
|
|
1408
1481
|
};
|
|
1409
1482
|
//#endregion
|
|
1410
|
-
export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, Mynth, Mynth as default, MynthAPIError, MynthImage, MynthModels, MynthVideo, TaskAsync, TaskAsyncFetchError, TaskAsyncTaskFailedError, TaskAsyncTaskFetchError, TaskAsyncTimeoutError, TaskAsyncUnauthorizedError };
|
|
1483
|
+
export { AVAILABLE_MODELS, AVAILABLE_VIDEO_MODELS, Mynth, Mynth as default, MynthAPIError, MynthImage, MynthModels, MynthVideo, MynthWebhookVerificationError, TaskAsync, TaskAsyncFetchError, TaskAsyncTaskFailedError, TaskAsyncTaskFetchError, TaskAsyncTimeoutError, TaskAsyncUnauthorizedError, verifyWebhook };
|
package/dist/next/index.d.ts
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
+
import { p as MynthSDKTypes } from "../video-generation-result.js";
|
|
1
2
|
import { n as WebhookHandlerOptions, t as WebhookEventHandlers } from "../handler.js";
|
|
2
3
|
//#region src/next/index.d.ts
|
|
3
4
|
export type MynthWebhookHandlerContext = {
|
|
4
5
|
/** The original request received by the Next.js Route Handler. */
|
|
5
6
|
request: Request;
|
|
6
7
|
/**
|
|
7
|
-
* The `
|
|
8
|
-
* it and skip IDs you have already handled.
|
|
8
|
+
* The verified event. `event.id` is the `webhook-id`: every delivery of the
|
|
9
|
+
* event repeats it, so store it and skip IDs you have already handled.
|
|
9
10
|
*/
|
|
10
|
-
|
|
11
|
+
event: MynthSDKTypes.WebhookEvent;
|
|
11
12
|
};
|
|
12
13
|
export type MynthWebhookEventHandlers = WebhookEventHandlers<MynthWebhookHandlerContext>;
|
|
13
14
|
export type MynthWebhookHandlerOptions = WebhookHandlerOptions;
|
|
14
15
|
/**
|
|
15
|
-
* Create a Next.js App Router handler for
|
|
16
|
+
* Create a Next.js App Router handler for Mynth webhooks.
|
|
16
17
|
*
|
|
17
18
|
* @example
|
|
18
19
|
* ```ts
|
|
@@ -20,8 +21,8 @@ export type MynthWebhookHandlerOptions = WebhookHandlerOptions;
|
|
|
20
21
|
* import { mynthWebhookHandler } from "@mynthio/sdk/next";
|
|
21
22
|
*
|
|
22
23
|
* export const POST = mynthWebhookHandler({
|
|
23
|
-
* imageTaskCompleted: async (result, {
|
|
24
|
-
* console.log(
|
|
24
|
+
* imageTaskCompleted: async (result, { event }) => {
|
|
25
|
+
* console.log(event.id, result.taskId);
|
|
25
26
|
* },
|
|
26
27
|
* });
|
|
27
28
|
* ```
|