@qooal/vault 0.0.0-stage → 0.1.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/server.js ADDED
@@ -0,0 +1,357 @@
1
+ import {
2
+ VAULT_API_BASE,
3
+ VaultApiError,
4
+ abortError,
5
+ apiErrorFrom,
6
+ backoffMs,
7
+ idempotencyKey,
8
+ isRetryableStatus,
9
+ seg,
10
+ sleep
11
+ } from "./chunks/chunk-Z5XT6XS2.js";
12
+ import {
13
+ VaultGrammarError,
14
+ parseVaultPath,
15
+ vaultUrl
16
+ } from "./chunks/chunk-PEWIUW3U.js";
17
+ import {
18
+ base64Url,
19
+ keyVersionChar,
20
+ pathSigningInput,
21
+ signDownload,
22
+ signHlsPrefix,
23
+ signPath,
24
+ verifyPath,
25
+ verifyToken
26
+ } from "./chunks/chunk-MKUYQFGG.js";
27
+
28
+ // src/server/client.ts
29
+ function assetQueryString(q = {}) {
30
+ const p = new URLSearchParams();
31
+ const put = (k, v) => {
32
+ if (v !== void 0) p.append(k, String(v));
33
+ };
34
+ put("q", q.q);
35
+ put("folder", q.folder);
36
+ put("recursive", q.recursive);
37
+ if (q.type?.length) put("type", q.type.join(","));
38
+ if (q.class?.length) put("class", q.class.join(","));
39
+ if (q.format?.length) put("format", q.format.join(","));
40
+ for (const t of q.tag ?? []) put("tag", t);
41
+ put("tagMode", q.tagMode);
42
+ if (q.access?.length) put("access", q.access.join(","));
43
+ if (q.state?.length) put("state", q.state.join(","));
44
+ for (const f of q.field ?? []) put("field", `${f.key}:${f.value}`);
45
+ put("createdFrom", q.createdFrom);
46
+ put("createdTo", q.createdTo);
47
+ put("minBytes", q.minBytes);
48
+ put("maxBytes", q.maxBytes);
49
+ put("sort", q.sort);
50
+ put("order", q.order);
51
+ put("cursor", q.cursor);
52
+ put("limit", q.limit);
53
+ const s = p.toString();
54
+ return s ? `?${s}` : "";
55
+ }
56
+ var L = (lib) => `/libraries/${seg(lib)}`;
57
+ var A = (lib, asset) => `${L(lib)}/assets/${seg(asset)}`;
58
+ var U = (lib, upload) => `${L(lib)}/uploads/${seg(upload)}`;
59
+ function createVaultClient(options) {
60
+ if (!/^qk_(live|test)_[A-Za-z0-9_-]+$/.test(options.apiKey ?? ""))
61
+ throw new TypeError("createVaultClient: apiKey must be a Qooal API key (qk_live_… or qk_test_…)");
62
+ if (typeof window !== "undefined" && typeof document !== "undefined" && !options.dangerouslyAllowBrowser)
63
+ throw new Error("createVaultClient runs on your server: an API key in a browser is public. Use an upload ticket.");
64
+ const base = (options.baseUrl ?? VAULT_API_BASE).replace(/\/+$/, "");
65
+ const f = options.fetch ?? globalThis.fetch.bind(globalThis);
66
+ const retries = options.retries ?? 2;
67
+ const delay = options.retryDelay ?? ((attempt, after) => after !== null ? Math.min(after, 30) * 1e3 : backoffMs(attempt));
68
+ async function request(method, path, init = {}) {
69
+ const signal = init.opts?.signal;
70
+ const headers = {
71
+ accept: "application/json",
72
+ authorization: `Bearer ${options.apiKey}`
73
+ };
74
+ if (init.body !== void 0) headers["content-type"] = "application/json";
75
+ if (init.idem) headers["idempotency-key"] = init.opts?.idempotencyKey ?? idempotencyKey();
76
+ if (init.ifMatch) headers["if-match"] = init.ifMatch;
77
+ const retry = init.retry ?? (method === "GET" || method === "DELETE" || init.idem ? "all" : "unprocessed");
78
+ for (let attempt = 0; ; attempt++) {
79
+ if (signal?.aborted) throw abortError(signal);
80
+ let err;
81
+ try {
82
+ const r = await f(`${base}${path}`, {
83
+ method,
84
+ headers,
85
+ body: init.body === void 0 ? null : JSON.stringify(init.body),
86
+ signal: signal ?? null
87
+ });
88
+ const text = await r.text();
89
+ if (r.ok) return text ? JSON.parse(text) : void 0;
90
+ err = apiErrorFrom(r.status, text, r.headers.get("retry-after"));
91
+ } catch (e) {
92
+ if (signal?.aborted) throw abortError(signal);
93
+ if (e instanceof SyntaxError) throw e;
94
+ err = new VaultApiError({ status: 0, code: "network", message: e instanceof Error ? e.message : String(e) });
95
+ }
96
+ const again = retry === "all" ? isRetryableStatus(err.status) : err.status === 429 || err.status === 503;
97
+ if (attempt >= retries || !again) throw err;
98
+ await sleep(delay(attempt, err.retryAfter), signal);
99
+ }
100
+ }
101
+ return {
102
+ // Libraries (read only on the public surface)
103
+ listLibraries: (o) => request("GET", "/libraries", { opts: o }),
104
+ getLibrary: (lib, o) => request("GET", L(lib), { opts: o }),
105
+ getUsage: (lib, range = "cycle", o) => request("GET", `${L(lib)}/usage?range=${range}`, { opts: o }),
106
+ // Folders
107
+ listFolders: (lib, o) => request("GET", `${L(lib)}/folders`, { opts: o }),
108
+ createFolder: (lib, path, o) => request("POST", `${L(lib)}/folders`, { body: { path }, idem: true, opts: o }),
109
+ updateFolder: (lib, folder, path, o) => request("PATCH", `${L(lib)}/folders/${seg(folder)}`, { body: { path }, opts: o }),
110
+ deleteFolder: (lib, folder, o) => request("DELETE", `${L(lib)}/folders/${seg(folder)}`, { opts: o }),
111
+ // Assets
112
+ listAssets: (lib, query, o) => request("GET", `${L(lib)}/assets${assetQueryString(query)}`, { opts: o }),
113
+ getAsset: (lib, asset, o) => request("GET", A(lib, asset), { opts: o }),
114
+ lookupAsset: (lib, resourceType, publicId, o) => request(
115
+ "GET",
116
+ `${L(lib)}/assets/lookup?${new URLSearchParams({ resourceType, publicId }).toString()}`,
117
+ { opts: o }
118
+ ),
119
+ updateAsset: (lib, asset, patch, o) => request("PATCH", A(lib, asset), {
120
+ body: patch,
121
+ opts: o,
122
+ ...o?.ifMatch ? { ifMatch: o.ifMatch } : {}
123
+ }),
124
+ deleteAsset: (lib, asset, o) => request("DELETE", A(lib, asset), { opts: o }),
125
+ restoreAsset: (lib, asset, o) => request("POST", `${A(lib, asset)}/actions/restore`, { body: {}, idem: true, opts: o }),
126
+ regenerateAsset: (lib, asset, o) => request("POST", `${A(lib, asset)}/actions/regenerate`, { body: {}, idem: true, opts: o }),
127
+ bulkAssets: (lib, ids, action, o) => request("POST", `${L(lib)}/assets/actions/bulk`, {
128
+ body: { ids, action },
129
+ idem: true,
130
+ opts: o
131
+ }),
132
+ listVersions: (lib, asset, o) => request("GET", `${A(lib, asset)}/versions`, { opts: o }),
133
+ restoreVersion: (lib, asset, version, o) => request("POST", `${A(lib, asset)}/versions/${version}/actions/restore`, {
134
+ body: {},
135
+ idem: true,
136
+ opts: o
137
+ }),
138
+ // Signed URLs and download links
139
+ signUrl: (lib, asset, input = {}, o) => request("POST", `${A(lib, asset)}/urls`, { body: input, opts: o }),
140
+ createDownloadLink: (lib, asset, input, o) => request("POST", `${A(lib, asset)}/download-links`, {
141
+ body: input,
142
+ idem: true,
143
+ opts: o
144
+ }),
145
+ listDownloadLinks: (lib, query = {}, o) => {
146
+ const p = new URLSearchParams();
147
+ if (query.asset) p.set("asset", query.asset);
148
+ if (query.cursor) p.set("cursor", query.cursor);
149
+ if (query.limit !== void 0) p.set("limit", String(query.limit));
150
+ const qs = p.toString();
151
+ return request("GET", `${L(lib)}/download-links${qs ? `?${qs}` : ""}`, {
152
+ opts: o
153
+ });
154
+ },
155
+ revokeDownloadLink: (lib, link, o) => request("DELETE", `${L(lib)}/download-links/${seg(link)}`, { opts: o }),
156
+ // Uploads: server-side uploads, URL imports and the direct-upload routes
157
+ createUpload: (lib, input, o) => request("POST", `${L(lib)}/uploads`, { body: input, idem: true, opts: o }),
158
+ importFromUrl: (lib, input, o) => request("POST", `${L(lib)}/uploads`, { body: input, idem: true, opts: o }),
159
+ requestUploadParts: (lib, upload, partNumbers, o) => request("POST", `${U(lib, upload)}/parts`, {
160
+ body: { partNumbers },
161
+ retry: "all",
162
+ opts: o
163
+ }).then((r) => r.parts),
164
+ getUpload: (lib, upload, o) => request("GET", U(lib, upload), { opts: o }),
165
+ completeUpload: (lib, upload, parts, o) => request("POST", `${U(lib, upload)}/complete`, { body: parts ? { parts } : {}, opts: o }),
166
+ abortUpload: (lib, upload, o) => request("DELETE", U(lib, upload), { opts: o }),
167
+ // Upload tickets: mint one per browser session and hand it to the widget
168
+ createUploadTicket: (lib, input = {}, o) => request("POST", `${L(lib)}/upload-tickets`, { body: input, idem: true, opts: o }),
169
+ revokeUploadTicket: (lib, ticket, o) => request("DELETE", `${L(lib)}/upload-tickets/${seg(ticket)}`, { opts: o }),
170
+ // Transform presets
171
+ listTransformPresets: (lib, o) => request("GET", `${L(lib)}/transform-presets`, { opts: o }),
172
+ getTransformPreset: (lib, preset, o) => request("GET", `${L(lib)}/transform-presets/${seg(preset)}`, { opts: o }),
173
+ createTransformPreset: (lib, input, o) => request("POST", `${L(lib)}/transform-presets`, { body: input, idem: true, opts: o }),
174
+ updateTransformPreset: (lib, preset, patch, o) => request("PATCH", `${L(lib)}/transform-presets/${seg(preset)}`, { body: patch, opts: o }),
175
+ deleteTransformPreset: (lib, preset, o) => request("DELETE", `${L(lib)}/transform-presets/${seg(preset)}`, { opts: o }),
176
+ // Upload presets (signed only)
177
+ listUploadPresets: (lib, o) => request("GET", `${L(lib)}/upload-presets`, { opts: o }),
178
+ getUploadPreset: (lib, preset, o) => request("GET", `${L(lib)}/upload-presets/${seg(preset)}`, { opts: o }),
179
+ createUploadPreset: (lib, input, o) => request("POST", `${L(lib)}/upload-presets`, {
180
+ body: { ...input, mode: "signed" },
181
+ idem: true,
182
+ opts: o
183
+ }),
184
+ updateUploadPreset: (lib, preset, patch, o) => request("PATCH", `${L(lib)}/upload-presets/${seg(preset)}`, { body: patch, opts: o }),
185
+ deleteUploadPreset: (lib, preset, o) => request("DELETE", `${L(lib)}/upload-presets/${seg(preset)}`, { opts: o }),
186
+ // Strict-mode allowlist
187
+ listAllowedTransforms: (lib, o) => request("GET", `${L(lib)}/allowed-transforms`, { opts: o }),
188
+ allowTransform: (lib, transformation, o) => request("POST", `${L(lib)}/allowed-transforms`, { body: { transformation }, opts: o }),
189
+ removeAllowedTransform: (lib, hash, o) => request("DELETE", `${L(lib)}/allowed-transforms/${seg(hash)}`, { opts: o })
190
+ };
191
+ }
192
+ function split(o = {}) {
193
+ const { signal, idempotencyKey: key, ...client } = o;
194
+ const req = {};
195
+ if (signal) req.signal = signal;
196
+ if (key) req.idempotencyKey = key;
197
+ return [client, req];
198
+ }
199
+ function createUploadTicket(apiKey, library, input = {}, options) {
200
+ const [client, req] = split(options);
201
+ return createVaultClient({ ...client, apiKey }).createUploadTicket(library, input, req);
202
+ }
203
+ function createDownloadLink(apiKey, library, asset, input, options) {
204
+ const [client, req] = split(options);
205
+ return createVaultClient({ ...client, apiKey }).createDownloadLink(library, asset, input, req);
206
+ }
207
+
208
+ // src/server/sign-url.ts
209
+ function decodeBase64(text) {
210
+ const clean = text.trim().replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
211
+ if (!/^[A-Za-z0-9+/]*$/.test(clean) || clean.length % 4 === 1) throw new TypeError("not base64");
212
+ const bin = atob(clean + "=".repeat((4 - clean.length % 4) % 4));
213
+ const out = new Uint8Array(bin.length);
214
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
215
+ return out;
216
+ }
217
+ function keyBytes(key) {
218
+ const bytes = typeof key.key === "string" ? decodeBase64(key.key) : key.key;
219
+ if (bytes.length !== 32) throw new RangeError("a Vault signing key is 32 bytes");
220
+ return bytes;
221
+ }
222
+ function expSeconds(v) {
223
+ if (v === void 0) return void 0;
224
+ const s = v instanceof Date ? Math.floor(v.getTime() / 1e3) : v;
225
+ if (!Number.isInteger(s) || s <= 0) throw new RangeError("expiresAt must be a positive whole number of seconds");
226
+ return s;
227
+ }
228
+ async function signVaultUrl(url, key, opts = {}) {
229
+ let origin = "";
230
+ let path = url;
231
+ if (/^https?:\/\//i.test(url)) {
232
+ const u = new URL(url);
233
+ if (u.search) throw new VaultGrammarError("bad_query", "sign the URL without a query");
234
+ origin = u.origin;
235
+ path = u.pathname;
236
+ } else if (path.includes("?")) throw new VaultGrammarError("bad_query", "sign the URL without a query");
237
+ const prefix = opts.library ? `/${opts.library}` : "";
238
+ const parsed = parseVaultPath(`${prefix}${path}`);
239
+ if (parsed.signature !== null) throw new VaultGrammarError("bad_signature_format", "the URL is already signed");
240
+ if (parsed.hls !== null) throw new VaultGrammarError("bad_value", "HLS children are authorized by tok, not signed");
241
+ const exp = expSeconds(opts.expiresAt);
242
+ if (parsed.delivery === "authenticated" && exp === void 0)
243
+ throw new VaultGrammarError("bad_query", "authenticated delivery needs expiresAt");
244
+ const canonical = parseVaultPath(parsed.canonicalPath);
245
+ const sig = await signPath(keyBytes(key), key.version, canonical.library, canonical.signedPart, exp);
246
+ const head = `/${canonical.library}/${canonical.resource}/${canonical.delivery}/`;
247
+ const rest = canonical.canonicalPath.slice(head.length);
248
+ const signedPath = `${head}${sig}/${rest}${exp !== void 0 ? `?exp=${exp}` : ""}`;
249
+ return `${origin}${prefix ? signedPath.slice(prefix.length) : signedPath}`;
250
+ }
251
+ function signedVaultUrl(lib, publicId, key, opts = {}) {
252
+ const { expiresAt, library, ...build } = opts;
253
+ const sign = {};
254
+ if (expiresAt !== void 0) sign.expiresAt = expiresAt;
255
+ if (library !== void 0) sign.library = library;
256
+ return signVaultUrl(vaultUrl(lib, publicId, build), key, sign);
257
+ }
258
+
259
+ // src/server/webhook.ts
260
+ var VaultWebhookError = class extends Error {
261
+ code;
262
+ constructor(code, detail) {
263
+ super(detail ? `${code}: ${detail}` : code);
264
+ this.name = "VaultWebhookError";
265
+ this.code = code;
266
+ }
267
+ };
268
+ function header(headers, name) {
269
+ if (typeof headers.get === "function") return headers.get(name);
270
+ for (const [k, v] of Object.entries(headers))
271
+ if (k.toLowerCase() === name) return Array.isArray(v) ? v.join(" ") : v ?? null;
272
+ return null;
273
+ }
274
+ function secretBytes(secret) {
275
+ const body = secret.startsWith("whsec_") ? secret.slice(6) : secret;
276
+ try {
277
+ const bytes = decodeBase64(body);
278
+ if (bytes.length < 16) throw new TypeError("short");
279
+ return bytes;
280
+ } catch {
281
+ throw new VaultWebhookError("bad_secret", "expected whsec_ followed by base64");
282
+ }
283
+ }
284
+ function sameBytes(a, b) {
285
+ if (a.length !== b.length) return false;
286
+ let diff = 0;
287
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
288
+ return diff === 0;
289
+ }
290
+ async function webhookSignature(secret, id, timestamp, body) {
291
+ const enc = new TextEncoder();
292
+ const head = enc.encode(`${id}.${timestamp}.`);
293
+ const tail = typeof body === "string" ? enc.encode(body) : body;
294
+ const msg = new Uint8Array(head.length + tail.length);
295
+ msg.set(head, 0);
296
+ msg.set(tail, head.length);
297
+ const key = await globalThis.crypto.subtle.importKey(
298
+ "raw",
299
+ secretBytes(secret),
300
+ { name: "HMAC", hash: "SHA-256" },
301
+ false,
302
+ ["sign"]
303
+ );
304
+ return new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, msg));
305
+ }
306
+ async function verifyWebhook(body, headers, secret, opts = {}) {
307
+ const id = header(headers, "webhook-id");
308
+ const ts = header(headers, "webhook-timestamp");
309
+ const sigs = header(headers, "webhook-signature");
310
+ if (!id || !ts || !sigs) throw new VaultWebhookError("missing_headers");
311
+ if (!/^\d{1,12}$/.test(ts.trim())) throw new VaultWebhookError("bad_timestamp");
312
+ const tolerance = opts.toleranceSeconds ?? 300;
313
+ const now = opts.now ?? Math.floor(Date.now() / 1e3);
314
+ if (Math.abs(now - Number(ts.trim())) > tolerance) throw new VaultWebhookError("timestamp_out_of_range");
315
+ const offered = [];
316
+ for (const part of sigs.trim().split(/\s+/)) {
317
+ const comma = part.indexOf(",");
318
+ if (comma < 0 || part.slice(0, comma) !== "v1") continue;
319
+ try {
320
+ offered.push(decodeBase64(part.slice(comma + 1)));
321
+ } catch {
322
+ }
323
+ }
324
+ let ok = false;
325
+ for (const s of typeof secret === "string" ? [secret] : secret) {
326
+ const want = await webhookSignature(s, id, ts.trim(), body);
327
+ for (const got of offered) if (sameBytes(want, got)) ok = true;
328
+ }
329
+ if (!ok) throw new VaultWebhookError("no_valid_signature");
330
+ try {
331
+ return JSON.parse(typeof body === "string" ? body : new TextDecoder().decode(body));
332
+ } catch {
333
+ throw new VaultWebhookError("bad_body", "the body is not JSON");
334
+ }
335
+ }
336
+ export {
337
+ VAULT_API_BASE,
338
+ VaultApiError,
339
+ VaultWebhookError,
340
+ assetQueryString,
341
+ base64Url,
342
+ createDownloadLink,
343
+ createUploadTicket,
344
+ createVaultClient,
345
+ decodeBase64,
346
+ keyVersionChar,
347
+ pathSigningInput,
348
+ signDownload,
349
+ signHlsPrefix,
350
+ signPath,
351
+ signVaultUrl,
352
+ signedVaultUrl,
353
+ verifyPath,
354
+ verifyToken,
355
+ verifyWebhook,
356
+ webhookSignature
357
+ };
package/dist/sign.js ADDED
@@ -0,0 +1,20 @@
1
+ import {
2
+ base64Url,
3
+ keyVersionChar,
4
+ pathSigningInput,
5
+ signDownload,
6
+ signHlsPrefix,
7
+ signPath,
8
+ verifyPath,
9
+ verifyToken
10
+ } from "./chunks/chunk-MKUYQFGG.js";
11
+ export {
12
+ base64Url,
13
+ keyVersionChar,
14
+ pathSigningInput,
15
+ signDownload,
16
+ signHlsPrefix,
17
+ signPath,
18
+ verifyPath,
19
+ verifyToken
20
+ };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Shared plumbing for the browser uploader and the server client: the error type for API answers (problem+json),
3
+ * Idempotency-Key generation and retry backoff. No dependencies; runs in browsers, Node and edge runtimes.
4
+ */
5
+ /** The public API's base URL. */
6
+ export declare const VAULT_API_BASE = "https://api.qooal.com/v1/vault";
7
+ /** One problem+json field error: a JSON pointer into the request body and a code. */
8
+ export interface VaultFieldError {
9
+ pointer: string;
10
+ code: string;
11
+ message?: string;
12
+ }
13
+ /**
14
+ * An HTTP answer from Qooal Vault that was not a success. `code` is the problem's `code` (for example `forbidden`),
15
+ * `reason` the Vault-specific reason (for example `storage_quota_exceeded`). `status` 0 means the request never
16
+ * got an answer (network failure).
17
+ */
18
+ export declare class VaultApiError extends Error {
19
+ readonly status: number;
20
+ readonly code: string;
21
+ readonly reason: string | null;
22
+ readonly errors: VaultFieldError[];
23
+ readonly requestId: string | null;
24
+ /** seconds, from `Retry-After` (429) */
25
+ readonly retryAfter: number | null;
26
+ constructor(init: {
27
+ status: number;
28
+ code: string;
29
+ reason?: string | null;
30
+ message?: string;
31
+ errors?: VaultFieldError[];
32
+ requestId?: string | null;
33
+ retryAfter?: number | null;
34
+ });
35
+ }
36
+ /** Builds a VaultApiError from a status, the response text and its `Retry-After` header. */
37
+ export declare function apiErrorFrom(status: number, text: string, retryAfter: string | null): VaultApiError;
38
+ /** True for answers worth repeating: no answer, 408, 425, 429 and 5xx. */
39
+ export declare function isRetryableStatus(status: number): boolean;
40
+ /** Full-jitter exponential backoff: attempt 0 → up to 500 ms, then 1 s, 2 s, … capped at 8 s. */
41
+ export declare function backoffMs(attempt: number): number;
42
+ /** The AbortError for a signal (its reason when the caller gave one). */
43
+ export declare function abortError(signal: AbortSignal | undefined): unknown;
44
+ /** Waits `ms`, rejecting early with the abort reason. */
45
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
46
+ /** A UUIDv7 (time-ordered) for `Idempotency-Key` headers. */
47
+ export declare function idempotencyKey(): string;
48
+ /** `encodeURIComponent` for one path segment (library slugs and IDs). */
49
+ export declare function seg(s: string): string;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@qooal/vault`: Qooal Vault's URL builder (runs anywhere) and the wire types.
3
+ *
4
+ * Uploads are in `@qooal/vault/upload`, React components in `@qooal/vault/react`, the next/image loader in
5
+ * `@qooal/vault/next` and signing, tickets, webhooks and the API client in `@qooal/vault/server`.
6
+ */
7
+ export type { VaultAccess, VaultAsset, VaultAssetPage, VaultAssetQuery, VaultAssetState, VaultAssetVersion, VaultBulkAction, VaultCompletedPart, VaultCreatedDownloadLink, VaultDownloadLink, VaultDownloadLinkInput, VaultFileClass, VaultFolder, VaultHeader, VaultHost, VaultISODate, VaultLibrary, VaultLibrarySettings, VaultMeter, VaultPage, VaultPlanId, VaultScanStatus, VaultSignedUrl, VaultSignUrlInput, VaultTransformPreset, VaultUploadFromUrlInput, VaultUploadInput, VaultUploadInstructions, VaultUploadPart, VaultUploadPreset, VaultUploadStatus, VaultUploadTicket, VaultUploadTicketInput, VaultUrlImportInstructions, VaultUsage, VaultUsageSnapshot, VaultVideo, VaultWebhookAsset, VaultWebhookEvent, VaultWebhookEventType, } from "./types.js";
8
+ export { assertPublicId, canonicalTransformation, type ParsedVaultPath, parseTransformation, parseVaultPath, srcSet, VAULT_PLACEHOLDER_HOSTS, type VaultCrop, type VaultDelivery, type VaultGrammarCode, VaultGrammarError, type VaultGravity, type VaultHostName, type VaultResourceType, type VaultTransformation, type VaultUrlLibrary, type VaultUrlOptions, vaultLibraryUrls, vaultSignedPart, vaultUrl, } from "./url.js";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `@qooal/vault/next` (Next 16): a `next/image` loader that lets Vault resize and pick the format, so
3
+ * Next's own optimizer never fetches the bytes.
4
+ *
5
+ * ```ts
6
+ * // next.config.ts
7
+ * export default { images: { loader: "custom", loaderFile: "./vault-loader.ts" } };
8
+ * // vault-loader.ts
9
+ * export { vaultLoader as default } from "@qooal/vault/next";
10
+ * ```
11
+ * Then `<Image src="https://media.qooalcdn.com/acme-shop/image/upload/shoes/red" width={800} height={600} alt="…" />`.
12
+ * For bare public IDs (`src="shoes/red"`), export `createVaultLoader({ library: "https://media.qooalcdn.com/acme-shop" })`.
13
+ *
14
+ * The loader sets `w` to the width Next asks for (a given `h` scales with it), adds `f_auto` unless a format is fixed,
15
+ * and maps Next's `quality` to `q_<n>` (the default 75 keeps Vault's `q_auto`). Public delivery only: a signed URL
16
+ * cannot be resized without signing again.
17
+ */
18
+ import { type VaultUrlLibrary } from "./url.js";
19
+ /** What next/image passes to a loader. */
20
+ export interface VaultLoaderProps {
21
+ src: string;
22
+ width: number;
23
+ quality?: number;
24
+ }
25
+ export interface VaultLoaderOptions {
26
+ /** base URL (with the slug) for bare public IDs; full Vault URLs need nothing */
27
+ library?: VaultUrlLibrary;
28
+ /** the library's width steps: request the step the edge would snap to, saving a redirect */
29
+ widthSteps?: readonly number[];
30
+ /** a base transformation for bare public IDs (full URLs keep their own) */
31
+ transformation?: string;
32
+ /** Next's default quality, which maps to `q_auto`; default 75 */
33
+ defaultQuality?: number;
34
+ }
35
+ /** Creates a loader; `vaultLoader` is the one with no options (full Vault URLs as `src`). */
36
+ export declare function createVaultLoader(options?: VaultLoaderOptions): (props: VaultLoaderProps) => string;
37
+ /** The next/image loader for full Vault URLs. */
38
+ export declare const vaultLoader: (props: VaultLoaderProps) => string;
39
+ export default vaultLoader;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `@qooal/vault/react` (React 19, client components): `VaultImage`, `VaultVideo` and `VaultUploader`.
3
+ *
4
+ * - `VaultImage`: a responsive `<img>` with a srcset from width steps, `sizes`, lazy loading and a dominant-colour
5
+ * placeholder.
6
+ * - `VaultVideo`: HLS natively (Safari, iOS) or through hls.js, imported only when needed (install `hls.js`), with
7
+ * the MP4 fallback and the poster.
8
+ * - `VaultUploader`: the `<qooal-vault-uploader>` element with React callbacks.
9
+ */
10
+ import { type ImgHTMLAttributes, type ReactElement, type VideoHTMLAttributes } from "react";
11
+ import type { VaultAsset } from "../types.js";
12
+ import { type VaultUploaderElementOptions } from "../upload/element.js";
13
+ import type { VaultUrlLibrary } from "../url.js";
14
+ import { type VaultImageOptions } from "./props.js";
15
+ export { DEFAULT_WIDTHS, type VaultImageAttributes, type VaultImageOptions, type VaultVideoOptions, type VaultVideoSources, vaultImageProps, vaultVideoSources, } from "./props.js";
16
+ /** The asset fields the components read (a full VaultAsset fits). */
17
+ export type VaultImageAsset = Pick<VaultAsset, "publicId" | "version" | "width" | "height" | "dominantColor"> & {
18
+ altText?: string | null;
19
+ };
20
+ type ImgRest = Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "srcSet" | "sizes" | "width" | "height" | "alt">;
21
+ export type VaultImageProps = ImgRest & Omit<VaultImageOptions, "publicId"> & {
22
+ /** the public ID; or pass `asset` */
23
+ publicId?: string;
24
+ /** an asset from the API: fills publicId, version, width, height, dominantColor and alt */
25
+ asset?: VaultImageAsset;
26
+ /** alternative text; required unless `asset.altText` is set (use "" for decorative images) */
27
+ alt?: string;
28
+ /** above the fold: eager loading and `fetchPriority="high"` */
29
+ priority?: boolean;
30
+ };
31
+ /** A responsive Vault image. */
32
+ export declare function VaultImage(props: VaultImageProps): ReactElement;
33
+ /** The part of hls.js the player uses. */
34
+ export interface HlsLike {
35
+ loadSource(url: string): void;
36
+ attachMedia(media: HTMLMediaElement): void;
37
+ destroy(): void;
38
+ }
39
+ export interface HlsModuleLike {
40
+ isSupported(): boolean;
41
+ new (config?: Record<string, unknown>): HlsLike;
42
+ }
43
+ export type VaultVideoProps = Omit<VideoHTMLAttributes<HTMLVideoElement>, "src" | "poster"> & {
44
+ library: VaultUrlLibrary;
45
+ publicId: string;
46
+ version?: number;
47
+ /** the poster URL; default the Vault poster; `false` for none */
48
+ poster?: string | false;
49
+ /** a signed HLS master URL for `authenticated` videos (mint it on your server); default the public one */
50
+ src?: string;
51
+ /** how hls.js is loaded; default `import("hls.js")` */
52
+ loadHls?: () => Promise<HlsModuleLike>;
53
+ };
54
+ /** A Vault video: native HLS where the browser has it, hls.js elsewhere, the MP4 when neither works. */
55
+ export declare function VaultVideo(props: VaultVideoProps): ReactElement;
56
+ export interface VaultUploaderProps {
57
+ library: string;
58
+ /** a `vtk_…` ticket minted by your backend */
59
+ ticket?: string;
60
+ /** your backend route that answers `{"ticket": "vtk_…"}` to a POST */
61
+ ticketEndpoint?: string;
62
+ /** an unsigned preset (needs `turnstileSitekey`) */
63
+ preset?: string;
64
+ turnstileSitekey?: string;
65
+ apiBase?: string;
66
+ accept?: string;
67
+ multiple?: boolean;
68
+ maxFiles?: number;
69
+ maxBytes?: number;
70
+ folderId?: string;
71
+ publicId?: string;
72
+ tags?: string[];
73
+ /** ignored: an upload always takes the ticket's access (set it with `createUploadTicket({ access })`) */
74
+ access?: "public" | "private" | "authenticated";
75
+ theme?: "light" | "dark" | "auto";
76
+ label?: string;
77
+ /** form field name: the uploaded asset IDs are submitted with the form */
78
+ name?: string;
79
+ disabled?: boolean;
80
+ /** accept pastes anywhere on the page */
81
+ globalPaste?: boolean;
82
+ /** hide the camera button on touch devices */
83
+ noCamera?: boolean;
84
+ className?: string;
85
+ /** JS-only settings: a ticket function, a Turnstile provider, labels, a custom fetch */
86
+ options?: VaultUploaderElementOptions;
87
+ onUpload?: (asset: VaultAsset, file: File) => void;
88
+ onError?: (error: unknown, file: File) => void;
89
+ onProgress?: (loaded: number, total: number, file: File) => void;
90
+ onComplete?: (assets: VaultAsset[]) => void;
91
+ }
92
+ /** The upload element, wrapped for React. */
93
+ export declare function VaultUploader(props: VaultUploaderProps): ReactElement;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Pure helpers behind the React components (and usable without React): the `<img>` attributes for a responsive Vault
3
+ * image and the sources of a Vault video. Built on the URL builder, so every URL is canonical.
4
+ */
5
+ import { type VaultUrlLibrary } from "../url.js";
6
+ /** Default srcset widths (px), a common device ladder. A library with width steps snaps them on the edge. */
7
+ export declare const DEFAULT_WIDTHS: readonly number[];
8
+ export interface VaultImageOptions {
9
+ /** a library base URL including the slug, or `{urls}` (a `VaultLibrary` fits) */
10
+ library: VaultUrlLibrary;
11
+ publicId: string;
12
+ /** the base transformation; `w` is set per srcset width and a given `h` scales with it */
13
+ transformation?: string;
14
+ /** a fixed output format (extension); default `f_auto` (AVIF or WebP when the browser takes them) */
15
+ format?: string;
16
+ version?: number;
17
+ /** srcset widths; default DEFAULT_WIDTHS (or the library's width steps, when you pass them) */
18
+ widths?: readonly number[];
19
+ /** the rendered width in CSS px; also used for `width` and the srcset (1x and 2x when `sizes` is not given) */
20
+ width?: number;
21
+ height?: number;
22
+ /** the `sizes` attribute; default `<width>px` with a width, else `100vw` */
23
+ sizes?: string;
24
+ /** the asset's dominant colour (`#rrggbb`): painted behind the image while it loads */
25
+ dominantColor?: string | null;
26
+ }
27
+ export interface VaultImageAttributes {
28
+ src: string;
29
+ srcSet: string;
30
+ sizes: string;
31
+ width?: number;
32
+ height?: number;
33
+ /** a background colour placeholder (LQIP), when `dominantColor` is a `#rrggbb` */
34
+ placeholder: string | null;
35
+ }
36
+ /** The attributes of a responsive `<img>` for a public Vault image. */
37
+ export declare function vaultImageProps(o: VaultImageOptions): VaultImageAttributes;
38
+ export interface VaultVideoOptions {
39
+ library: VaultUrlLibrary;
40
+ publicId: string;
41
+ version?: number;
42
+ /** the poster's image transformation; default `c_limit,w_1280` */
43
+ posterTransformation?: string;
44
+ /** the poster's format; default `jpg` */
45
+ posterFormat?: "jpg" | "png" | "webp" | "avif";
46
+ }
47
+ export interface VaultVideoSources {
48
+ /** the HLS master playlist on the video host */
49
+ hls: string;
50
+ /** the 720p MP4 fallback */
51
+ mp4: string;
52
+ /** the poster on the media host */
53
+ poster: string;
54
+ }
55
+ /** The URLs of a public Vault video. */
56
+ export declare function vaultVideoSources(o: VaultVideoOptions): VaultVideoSources;