@puzzle-ui/media-cloudflare 0.0.0-stage → 0.17.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/README.md +71 -2
- package/ai/instructions.md +20 -0
- package/ai/manifest.json +10 -0
- package/dist/LICENSE +21 -0
- package/dist/bucket-provisioner.cjs +37 -0
- package/dist/bucket-provisioner.cjs.map +1 -0
- package/dist/bucket-provisioner.d.cts +16 -0
- package/dist/bucket-provisioner.d.ts +16 -0
- package/dist/bucket-provisioner.js +37 -0
- package/dist/bucket-provisioner.js.map +1 -0
- package/dist/errors.cjs +35 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.cts +17 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +32 -0
- package/dist/errors.js.map +1 -0
- package/dist/images-processor.cjs +100 -0
- package/dist/images-processor.cjs.map +1 -0
- package/dist/images-processor.d.cts +15 -0
- package/dist/images-processor.d.ts +15 -0
- package/dist/images-processor.js +100 -0
- package/dist/images-processor.js.map +1 -0
- package/dist/index.cjs +28 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -0
- package/dist/metadata-store.cjs +69 -0
- package/dist/metadata-store.cjs.map +1 -0
- package/dist/metadata-store.d.cts +23 -0
- package/dist/metadata-store.d.ts +23 -0
- package/dist/metadata-store.js +69 -0
- package/dist/metadata-store.js.map +1 -0
- package/dist/r2-adapter.cjs +393 -0
- package/dist/r2-adapter.cjs.map +1 -0
- package/dist/r2-adapter.d.cts +40 -0
- package/dist/r2-adapter.d.ts +40 -0
- package/dist/r2-adapter.js +393 -0
- package/dist/r2-adapter.js.map +1 -0
- package/dist/s3-signer.cjs +106 -0
- package/dist/s3-signer.cjs.map +1 -0
- package/dist/s3-signer.d.cts +20 -0
- package/dist/s3-signer.d.ts +20 -0
- package/dist/s3-signer.js +105 -0
- package/dist/s3-signer.js.map +1 -0
- package/dist/types.d.cts +212 -0
- package/dist/types.d.ts +212 -0
- package/dist/utils.cjs +59 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.cts +10 -0
- package/dist/utils.d.ts +10 -0
- package/dist/utils.js +51 -0
- package/dist/utils.js.map +1 -0
- package/package.json +59 -4
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// src/s3-signer.ts
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
const encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
4
|
+
const hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
5
|
+
const sha256Hex = async (value) => hex(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
|
|
6
|
+
const hmac = async (key, value) => {
|
|
7
|
+
const rawKey = key instanceof Uint8Array ? key.slice().buffer : key.slice(0);
|
|
8
|
+
const cryptoKey = await crypto.subtle.importKey("raw", rawKey, {
|
|
9
|
+
name: "HMAC",
|
|
10
|
+
hash: "SHA-256"
|
|
11
|
+
}, false, ["sign"]);
|
|
12
|
+
return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(value));
|
|
13
|
+
};
|
|
14
|
+
const pathFor = (base, bucketName, key) => {
|
|
15
|
+
return `/${[
|
|
16
|
+
...base.pathname.split("/").filter(Boolean),
|
|
17
|
+
bucketName,
|
|
18
|
+
...key.split("/")
|
|
19
|
+
].map(encode).join("/")}`;
|
|
20
|
+
};
|
|
21
|
+
const formatDate = (date) => {
|
|
22
|
+
const iso = date.toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
23
|
+
return {
|
|
24
|
+
dateStamp: iso.slice(0, 10).replaceAll("-", ""),
|
|
25
|
+
amzDate: iso.replaceAll("-", "").replaceAll(":", "")
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
const canonicalQuery = (values) => Object.entries(values).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${encode(key)}=${encode(value)}`).join("&");
|
|
29
|
+
/**
|
|
30
|
+
* Worker-compatible AWS Signature Version 4 presigner for R2's
|
|
31
|
+
* S3-compatible endpoint. Credentials stay in the server/Worker that creates
|
|
32
|
+
* the signer; only the resulting short-lived target is returned to callers.
|
|
33
|
+
*/
|
|
34
|
+
var CloudflareR2S3UrlSigner = class {
|
|
35
|
+
endpoint;
|
|
36
|
+
bucketName;
|
|
37
|
+
accessKeyId;
|
|
38
|
+
secretAccessKey;
|
|
39
|
+
region;
|
|
40
|
+
now;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.endpoint = new URL(options.endpoint);
|
|
43
|
+
if (this.endpoint.protocol !== "https:") throw new TypeError("R2 S3 endpoints must use HTTPS.");
|
|
44
|
+
if (!options.bucketName || !options.accessKeyId || !options.secretAccessKey) throw new TypeError("R2 S3 signing requires a bucket and access credentials.");
|
|
45
|
+
this.bucketName = options.bucketName;
|
|
46
|
+
this.accessKeyId = options.accessKeyId;
|
|
47
|
+
this.secretAccessKey = options.secretAccessKey;
|
|
48
|
+
this.region = options.region ?? "auto";
|
|
49
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
50
|
+
}
|
|
51
|
+
signUpload(input) {
|
|
52
|
+
return this.presign("PUT", input.key, input.expiresAt, {}, input.contentType);
|
|
53
|
+
}
|
|
54
|
+
signMultipartPart(input) {
|
|
55
|
+
return this.presign("PUT", input.key, input.expiresAt, {
|
|
56
|
+
partNumber: String(input.partNumber),
|
|
57
|
+
uploadId: input.uploadId
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
signRead(input) {
|
|
61
|
+
return this.presign("GET", input.key, input.expiresAt, {});
|
|
62
|
+
}
|
|
63
|
+
async presign(method, key, expiresAt, extraQuery, contentType) {
|
|
64
|
+
const now = this.now();
|
|
65
|
+
const ttlSeconds = Math.ceil((expiresAt.getTime() - now.getTime()) / 1e3);
|
|
66
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > 604800) throw new RangeError("R2 signed URL expiry must be between one second and seven days.");
|
|
67
|
+
const { dateStamp, amzDate } = formatDate(now);
|
|
68
|
+
const path = pathFor(this.endpoint, this.bucketName, key);
|
|
69
|
+
const query = {
|
|
70
|
+
...extraQuery,
|
|
71
|
+
"X-Amz-Algorithm": "AWS4-HMAC-SHA256",
|
|
72
|
+
"X-Amz-Credential": `${this.accessKeyId}/${dateStamp}/${this.region}/s3/aws4_request`,
|
|
73
|
+
"X-Amz-Date": amzDate,
|
|
74
|
+
"X-Amz-Expires": String(ttlSeconds),
|
|
75
|
+
"X-Amz-SignedHeaders": "host"
|
|
76
|
+
};
|
|
77
|
+
const queryString = canonicalQuery(query);
|
|
78
|
+
const canonicalRequest = [
|
|
79
|
+
method,
|
|
80
|
+
path,
|
|
81
|
+
queryString,
|
|
82
|
+
`host:${this.endpoint.host}\n`,
|
|
83
|
+
"host",
|
|
84
|
+
"UNSIGNED-PAYLOAD"
|
|
85
|
+
].join("\n");
|
|
86
|
+
const stringToSign = [
|
|
87
|
+
"AWS4-HMAC-SHA256",
|
|
88
|
+
amzDate,
|
|
89
|
+
`${dateStamp}/${this.region}/s3/aws4_request`,
|
|
90
|
+
await sha256Hex(canonicalRequest)
|
|
91
|
+
].join("\n");
|
|
92
|
+
const dateKey = await hmac(encoder.encode(`AWS4${this.secretAccessKey}`), dateStamp);
|
|
93
|
+
const regionKey = await hmac(dateKey, this.region);
|
|
94
|
+
const serviceKey = await hmac(regionKey, "s3");
|
|
95
|
+
const signingKey = await hmac(serviceKey, "aws4_request");
|
|
96
|
+
const signature = hex(await hmac(signingKey, stringToSign));
|
|
97
|
+
return {
|
|
98
|
+
url: `${this.endpoint.origin}${path}?${queryString}&X-Amz-Signature=${signature}`,
|
|
99
|
+
...method === "PUT" && contentType ? { headers: { "content-type": contentType } } : {}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
export { CloudflareR2S3UrlSigner as CloudflareR2S3Signer, CloudflareR2S3UrlSigner };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=s3-signer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"s3-signer.js","names":[],"sources":["../src/s3-signer.ts"],"sourcesContent":["import type {\n CloudflareMediaUrlSigner,\n CloudflareMediaUrlTarget,\n CloudflareR2S3UrlSignerOptions,\n} from \"./types\";\n\nconst encoder = new TextEncoder();\n\nconst encode = (value: string): string =>\n encodeURIComponent(value).replace(/[!'()*]/g, (character) =>\n `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\nconst sha256Hex = async (value: string): Promise<string> =>\n hex(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value)));\n\nconst hmac = async (\n key: ArrayBuffer | Uint8Array,\n value: string,\n): Promise<ArrayBuffer> => {\n const rawKey =\n key instanceof Uint8Array ? key.slice().buffer : key.slice(0);\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n rawKey,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(value));\n};\n\nconst pathFor = (base: URL, bucketName: string, key: string): string => {\n const segments = [\n ...base.pathname.split(\"/\").filter(Boolean),\n bucketName,\n ...key.split(\"/\"),\n ];\n return `/${segments.map(encode).join(\"/\")}`;\n};\n\nconst formatDate = (date: Date): { dateStamp: string; amzDate: string } => {\n const iso = date.toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n return {\n dateStamp: iso.slice(0, 10).replaceAll(\"-\", \"\"),\n amzDate: iso.replaceAll(\"-\", \"\").replaceAll(\":\", \"\"),\n };\n};\n\nconst canonicalQuery = (\n values: Readonly<Record<string, string>>,\n): string =>\n Object.entries(values)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => `${encode(key)}=${encode(value)}`)\n .join(\"&\");\n\n/**\n * Worker-compatible AWS Signature Version 4 presigner for R2's\n * S3-compatible endpoint. Credentials stay in the server/Worker that creates\n * the signer; only the resulting short-lived target is returned to callers.\n */\nexport class CloudflareR2S3UrlSigner implements CloudflareMediaUrlSigner {\n private readonly endpoint: URL;\n private readonly bucketName: string;\n private readonly accessKeyId: string;\n private readonly secretAccessKey: string;\n private readonly region: string;\n private readonly now: () => Date;\n\n constructor(options: CloudflareR2S3UrlSignerOptions) {\n this.endpoint = new URL(options.endpoint);\n if (this.endpoint.protocol !== \"https:\") {\n throw new TypeError(\"R2 S3 endpoints must use HTTPS.\");\n }\n if (!options.bucketName || !options.accessKeyId || !options.secretAccessKey) {\n throw new TypeError(\"R2 S3 signing requires a bucket and access credentials.\");\n }\n this.bucketName = options.bucketName;\n this.accessKeyId = options.accessKeyId;\n this.secretAccessKey = options.secretAccessKey;\n this.region = options.region ?? \"auto\";\n this.now = options.now ?? (() => new Date());\n }\n\n signUpload(input: Parameters<CloudflareMediaUrlSigner[\"signUpload\"]>[0]): Promise<CloudflareMediaUrlTarget> {\n return this.presign(\"PUT\", input.key, input.expiresAt, {}, input.contentType);\n }\n\n signMultipartPart(\n input: Parameters<CloudflareMediaUrlSigner[\"signMultipartPart\"]>[0],\n ): Promise<CloudflareMediaUrlTarget> {\n return this.presign(\"PUT\", input.key, input.expiresAt, {\n partNumber: String(input.partNumber),\n uploadId: input.uploadId,\n });\n }\n\n signRead(\n input: Parameters<CloudflareMediaUrlSigner[\"signRead\"]>[0],\n ): Promise<CloudflareMediaUrlTarget> {\n return this.presign(\"GET\", input.key, input.expiresAt, {});\n }\n\n private async presign(\n method: \"GET\" | \"PUT\",\n key: string,\n expiresAt: Date,\n extraQuery: Readonly<Record<string, string>>,\n contentType?: string,\n ): Promise<CloudflareMediaUrlTarget> {\n const now = this.now();\n const ttlSeconds = Math.ceil((expiresAt.getTime() - now.getTime()) / 1000);\n if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > 604800) {\n throw new RangeError(\"R2 signed URL expiry must be between one second and seven days.\");\n }\n const { dateStamp, amzDate } = formatDate(now);\n const path = pathFor(this.endpoint, this.bucketName, key);\n const query = {\n ...extraQuery,\n \"X-Amz-Algorithm\": \"AWS4-HMAC-SHA256\",\n \"X-Amz-Credential\": `${this.accessKeyId}/${dateStamp}/${this.region}/s3/aws4_request`,\n \"X-Amz-Date\": amzDate,\n \"X-Amz-Expires\": String(ttlSeconds),\n \"X-Amz-SignedHeaders\": \"host\",\n };\n const queryString = canonicalQuery(query);\n const host = this.endpoint.host;\n const canonicalRequest = [\n method,\n path,\n queryString,\n `host:${host}\\n`,\n \"host\",\n \"UNSIGNED-PAYLOAD\",\n ].join(\"\\n\");\n const scope = `${dateStamp}/${this.region}/s3/aws4_request`;\n const stringToSign = [\n \"AWS4-HMAC-SHA256\",\n amzDate,\n scope,\n await sha256Hex(canonicalRequest),\n ].join(\"\\n\");\n const dateKey = await hmac(encoder.encode(`AWS4${this.secretAccessKey}`), dateStamp);\n const regionKey = await hmac(dateKey, this.region);\n const serviceKey = await hmac(regionKey, \"s3\");\n const signingKey = await hmac(serviceKey, \"aws4_request\");\n const signature = hex(await hmac(signingKey, stringToSign));\n return {\n url: `${this.endpoint.origin}${path}?${queryString}&X-Amz-Signature=${signature}`,\n ...(method === \"PUT\" && contentType\n ? { headers: { \"content-type\": contentType } }\n : {}),\n };\n }\n}\n\nexport { CloudflareR2S3UrlSigner as CloudflareR2S3Signer };\n"],"mappings":";AAMA,MAAM,UAAU,IAAI,YAAY;AAEhC,MAAM,UAAU,UACd,mBAAmB,KAAK,CAAC,CAAC,QAAQ,aAAa,cAC7C,IAAI,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GACvD;AAEF,MAAM,OAAO,UACX,CAAC,GAAG,IAAI,WAAW,KAAK,CAAC,CAAC,CACvB,KAAK,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SA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GACvB;GACA;GACA;GACA,QALW,KAAK,SAAS,KAKZ;GACb;GACA;EACF,CAAC,CAAC,KAAK,IAAI;EAEX,MAAM,eAAe;GACnB;GACA;GACA,GAJe,UAAU,GAAG,KAAK,OAAO;GAKxC,MAAM,UAAU,gBAAgB;EAClC,CAAC,CAAC,KAAK,IAAI;EACX,MAAM,UAAU,MAAM,KAAK,QAAQ,OAAO,OAAO,KAAK,iBAAiB,GAAG,SAAS;EACnF,MAAM,YAAY,MAAM,KAAK,SAAS,KAAK,MAAM;EACjD,MAAM,aAAa,MAAM,KAAK,WAAW,IAAI;EAC7C,MAAM,aAAa,MAAM,KAAK,YAAY,cAAc;EACxD,MAAM,YAAY,IAAI,MAAM,KAAK,YAAY,YAAY,CAAC;EAC1D,OAAO;GACL,KAAK,GAAG,KAAK,SAAS,SAAS,KAAK,GAAG,YAAY,mBAAmB;GACtE,GAAI,WAAW,SAAS,cACpB,EAAE,SAAS,EAAE,gBAAgB,YAAY,EAAE,IAC3C,CAAC;EACP;CACF;AACF"}
|
package/dist/types.d.cts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { MediaAsset, MediaChecksum, MediaImageProfile, MediaObjectReference, MediaStoredObject, MediaUploadSession } from "@puzzle-ui/media";
|
|
2
|
+
export type R2PutValue = ArrayBuffer | ArrayBufferView | Blob | ReadableStream<Uint8Array> | string | Uint8Array;
|
|
3
|
+
export type R2HttpMetadata = {
|
|
4
|
+
readonly contentType?: string;
|
|
5
|
+
readonly contentLanguage?: string;
|
|
6
|
+
readonly contentDisposition?: string;
|
|
7
|
+
readonly contentEncoding?: string;
|
|
8
|
+
readonly cacheControl?: string;
|
|
9
|
+
readonly cacheExpiry?: Date;
|
|
10
|
+
};
|
|
11
|
+
export type R2ObjectLike = {
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly size: number;
|
|
14
|
+
readonly etag?: string;
|
|
15
|
+
readonly uploaded?: Date;
|
|
16
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
17
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
18
|
+
readonly arrayBuffer: () => Promise<ArrayBuffer>;
|
|
19
|
+
};
|
|
20
|
+
export type R2ListResultLike = {
|
|
21
|
+
readonly objects: readonly R2ObjectLike[];
|
|
22
|
+
readonly truncated: boolean;
|
|
23
|
+
readonly cursor?: string;
|
|
24
|
+
};
|
|
25
|
+
export type R2MultipartPart = {
|
|
26
|
+
readonly partNumber: number;
|
|
27
|
+
readonly etag: string;
|
|
28
|
+
};
|
|
29
|
+
export interface R2MultipartUploadLike {
|
|
30
|
+
readonly uploadId?: string;
|
|
31
|
+
uploadPart(partNumber: number, value: R2PutValue): Promise<{
|
|
32
|
+
readonly etag: string;
|
|
33
|
+
}>;
|
|
34
|
+
complete(parts: readonly R2MultipartPart[]): Promise<R2ObjectLike | void>;
|
|
35
|
+
abort(): Promise<void>;
|
|
36
|
+
listParts?(): Promise<readonly R2MultipartPart[]>;
|
|
37
|
+
}
|
|
38
|
+
export interface R2BucketLike {
|
|
39
|
+
put(key: string, value: R2PutValue, options?: {
|
|
40
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
41
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
42
|
+
}): Promise<R2ObjectLike | void | null>;
|
|
43
|
+
get(key: string): Promise<R2ObjectLike | null>;
|
|
44
|
+
head(key: string): Promise<R2ObjectLike | null>;
|
|
45
|
+
delete(key: string): Promise<void>;
|
|
46
|
+
list?(options?: {
|
|
47
|
+
readonly cursor?: string;
|
|
48
|
+
readonly limit?: number;
|
|
49
|
+
readonly prefix?: string;
|
|
50
|
+
}): Promise<R2ListResultLike>;
|
|
51
|
+
createMultipartUpload?(key: string, options?: {
|
|
52
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
53
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
54
|
+
}): Promise<R2MultipartUploadLike>;
|
|
55
|
+
resumeMultipartUpload?(key: string, uploadId: string): R2MultipartUploadLike;
|
|
56
|
+
}
|
|
57
|
+
export type CloudflareMediaUrlTarget = {
|
|
58
|
+
readonly url: string;
|
|
59
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* R2 Worker bindings do not issue presigned URLs. Applications can inject a
|
|
63
|
+
* signer backed by their S3-compatible endpoint, a gateway, or their own
|
|
64
|
+
* authenticated upload route.
|
|
65
|
+
*/
|
|
66
|
+
export interface CloudflareMediaUrlSigner {
|
|
67
|
+
signUpload(input: {
|
|
68
|
+
readonly tenantId: string;
|
|
69
|
+
readonly key: string;
|
|
70
|
+
readonly contentType: string;
|
|
71
|
+
readonly expiresAt: Date;
|
|
72
|
+
readonly expectedSize?: number;
|
|
73
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
74
|
+
signMultipartPart(input: {
|
|
75
|
+
readonly tenantId: string;
|
|
76
|
+
readonly key: string;
|
|
77
|
+
readonly uploadId: string;
|
|
78
|
+
readonly partNumber: number;
|
|
79
|
+
readonly expiresAt: Date;
|
|
80
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
81
|
+
signRead(input: {
|
|
82
|
+
readonly tenantId: string;
|
|
83
|
+
readonly key: string;
|
|
84
|
+
readonly expiresAt: Date;
|
|
85
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
86
|
+
}
|
|
87
|
+
export type CloudflareMediaBucketContext = {
|
|
88
|
+
readonly tenantId: string;
|
|
89
|
+
readonly bucketName?: string;
|
|
90
|
+
};
|
|
91
|
+
export type CloudflareMediaBucketTarget = {
|
|
92
|
+
readonly bucket: R2BucketLike;
|
|
93
|
+
readonly signer: CloudflareMediaUrlSigner;
|
|
94
|
+
readonly bucketName?: string;
|
|
95
|
+
};
|
|
96
|
+
export type CloudflareMediaBucketResolver = (context: CloudflareMediaBucketContext) => CloudflareMediaBucketTarget | Promise<CloudflareMediaBucketTarget>;
|
|
97
|
+
/**
|
|
98
|
+
* A resolver is useful for tenant-specific R2 buckets or S3-compatible R2
|
|
99
|
+
* clients. It deliberately exposes only the operations needed by this package,
|
|
100
|
+
* avoiding a dependency on a particular S3 SDK.
|
|
101
|
+
*/
|
|
102
|
+
export interface CloudflareMediaS3CompatibleResolver {
|
|
103
|
+
resolve(context: CloudflareMediaBucketContext): Promise<CloudflareMediaBucketTarget>;
|
|
104
|
+
}
|
|
105
|
+
export type CloudflareMediaBucketSource = CloudflareMediaBucketTarget | CloudflareMediaBucketResolver | CloudflareMediaS3CompatibleResolver;
|
|
106
|
+
export type CloudflareMediaStaticBucket = CloudflareMediaBucketTarget;
|
|
107
|
+
export type CloudflareMediaDynamicBucketResolver = CloudflareMediaBucketResolver | CloudflareMediaS3CompatibleResolver;
|
|
108
|
+
export type CloudflareUploadRecord = {
|
|
109
|
+
readonly session: MediaUploadSession;
|
|
110
|
+
readonly tenantId: string;
|
|
111
|
+
readonly key: string;
|
|
112
|
+
readonly contentType: string;
|
|
113
|
+
readonly fileName: string;
|
|
114
|
+
readonly uploadId?: string;
|
|
115
|
+
readonly partSizeBytes?: number;
|
|
116
|
+
};
|
|
117
|
+
export type CloudflareObjectRecord = {
|
|
118
|
+
readonly object: MediaStoredObject;
|
|
119
|
+
readonly key: string;
|
|
120
|
+
};
|
|
121
|
+
export interface CloudflareMediaMetadataStore {
|
|
122
|
+
saveUpload(record: CloudflareUploadRecord): Promise<void>;
|
|
123
|
+
getUpload(id: string): Promise<CloudflareUploadRecord | null>;
|
|
124
|
+
updateUpload(id: string, update: Partial<Pick<CloudflareUploadRecord, "session">>): Promise<CloudflareUploadRecord | null>;
|
|
125
|
+
listExpiredUploads(before: Date, first: number, tenantId?: string): Promise<readonly CloudflareUploadRecord[]>;
|
|
126
|
+
saveObject(record: CloudflareObjectRecord): Promise<void>;
|
|
127
|
+
getObject(key: string, tenantId?: string): Promise<CloudflareObjectRecord | null>;
|
|
128
|
+
deleteObject(key: string, tenantId?: string): Promise<boolean>;
|
|
129
|
+
listObjects(input: {
|
|
130
|
+
readonly first: number;
|
|
131
|
+
readonly cursor?: string;
|
|
132
|
+
readonly olderThan?: Date;
|
|
133
|
+
readonly tenantId?: string;
|
|
134
|
+
}): Promise<readonly CloudflareObjectRecord[]>;
|
|
135
|
+
}
|
|
136
|
+
export type CloudflareR2MediaObjectStorageOptions = {
|
|
137
|
+
readonly bucket: CloudflareMediaBucketSource;
|
|
138
|
+
readonly metadataStore: CloudflareMediaMetadataStore;
|
|
139
|
+
readonly tenantId?: string;
|
|
140
|
+
readonly bucketName?: string;
|
|
141
|
+
readonly idFactory?: () => string;
|
|
142
|
+
readonly now?: () => Date;
|
|
143
|
+
readonly maxSignedUrlTtlMs?: number;
|
|
144
|
+
readonly maxListPageSize?: number;
|
|
145
|
+
};
|
|
146
|
+
export type CloudflareR2MediaObjectStorageAdapterOptions = CloudflareR2MediaObjectStorageOptions;
|
|
147
|
+
export type CloudflareR2BucketProvisionerApi = {
|
|
148
|
+
getBucket(name: string): Promise<CloudflareR2BucketInfo | null>;
|
|
149
|
+
createBucket(input: {
|
|
150
|
+
readonly name: string;
|
|
151
|
+
readonly locationHint?: string;
|
|
152
|
+
}): Promise<CloudflareR2BucketInfo>;
|
|
153
|
+
};
|
|
154
|
+
export type CloudflareR2BucketInfo = {
|
|
155
|
+
readonly name: string;
|
|
156
|
+
readonly creationDate?: Date;
|
|
157
|
+
readonly location?: string;
|
|
158
|
+
};
|
|
159
|
+
export type CloudflareR2BucketProvisionerOptions = {
|
|
160
|
+
readonly api: CloudflareR2BucketProvisionerApi;
|
|
161
|
+
readonly nameForTenant?: (tenantId: string) => string;
|
|
162
|
+
};
|
|
163
|
+
export type CloudflareR2S3UrlSignerOptions = {
|
|
164
|
+
readonly endpoint: string;
|
|
165
|
+
readonly bucketName: string;
|
|
166
|
+
readonly accessKeyId: string;
|
|
167
|
+
readonly secretAccessKey: string;
|
|
168
|
+
readonly region?: string;
|
|
169
|
+
readonly now?: () => Date;
|
|
170
|
+
};
|
|
171
|
+
export type CloudflareImagesSource = string | ArrayBuffer | Uint8Array | Blob | ReadableStream<Uint8Array>;
|
|
172
|
+
export type CloudflareImagesOutputLike = {
|
|
173
|
+
response(): Promise<Response | {
|
|
174
|
+
readonly arrayBuffer: () => Promise<ArrayBuffer>;
|
|
175
|
+
readonly headers?: Headers;
|
|
176
|
+
}>;
|
|
177
|
+
};
|
|
178
|
+
export type CloudflareImagesTransformLike = {
|
|
179
|
+
output(options?: {
|
|
180
|
+
readonly format?: string;
|
|
181
|
+
readonly quality?: number;
|
|
182
|
+
}): CloudflareImagesOutputLike;
|
|
183
|
+
};
|
|
184
|
+
export type CloudflareImagesInputLike = {
|
|
185
|
+
transform(options: {
|
|
186
|
+
readonly width?: number;
|
|
187
|
+
readonly height?: number;
|
|
188
|
+
readonly fit?: "scale-down" | "contain" | "cover" | "crop" | "pad";
|
|
189
|
+
}): CloudflareImagesTransformLike;
|
|
190
|
+
};
|
|
191
|
+
export interface CloudflareImagesBinding {
|
|
192
|
+
input(source: CloudflareImagesSource): CloudflareImagesInputLike;
|
|
193
|
+
}
|
|
194
|
+
export type CloudflareImagesVariantWriteInput = {
|
|
195
|
+
readonly asset: MediaAsset;
|
|
196
|
+
readonly profile: MediaImageProfile;
|
|
197
|
+
readonly bytes: Uint8Array;
|
|
198
|
+
readonly mimeType: string;
|
|
199
|
+
readonly checksum: MediaChecksum;
|
|
200
|
+
};
|
|
201
|
+
export type CloudflareImagesProcessorOptions = {
|
|
202
|
+
readonly images: CloudflareImagesBinding;
|
|
203
|
+
readonly source: (asset: MediaAsset) => CloudflareImagesSource | Promise<CloudflareImagesSource>;
|
|
204
|
+
readonly writeVariant: (input: CloudflareImagesVariantWriteInput) => Promise<{
|
|
205
|
+
readonly object: MediaObjectReference;
|
|
206
|
+
readonly size?: number;
|
|
207
|
+
readonly mimeType?: string;
|
|
208
|
+
readonly width?: number;
|
|
209
|
+
readonly height?: number;
|
|
210
|
+
}>;
|
|
211
|
+
readonly idFactory?: () => string;
|
|
212
|
+
};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { MediaAsset, MediaChecksum, MediaImageProfile, MediaObjectReference, MediaStoredObject, MediaUploadSession } from "@puzzle-ui/media";
|
|
2
|
+
export type R2PutValue = ArrayBuffer | ArrayBufferView | Blob | ReadableStream<Uint8Array> | string | Uint8Array;
|
|
3
|
+
export type R2HttpMetadata = {
|
|
4
|
+
readonly contentType?: string;
|
|
5
|
+
readonly contentLanguage?: string;
|
|
6
|
+
readonly contentDisposition?: string;
|
|
7
|
+
readonly contentEncoding?: string;
|
|
8
|
+
readonly cacheControl?: string;
|
|
9
|
+
readonly cacheExpiry?: Date;
|
|
10
|
+
};
|
|
11
|
+
export type R2ObjectLike = {
|
|
12
|
+
readonly key: string;
|
|
13
|
+
readonly size: number;
|
|
14
|
+
readonly etag?: string;
|
|
15
|
+
readonly uploaded?: Date;
|
|
16
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
17
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
18
|
+
readonly arrayBuffer: () => Promise<ArrayBuffer>;
|
|
19
|
+
};
|
|
20
|
+
export type R2ListResultLike = {
|
|
21
|
+
readonly objects: readonly R2ObjectLike[];
|
|
22
|
+
readonly truncated: boolean;
|
|
23
|
+
readonly cursor?: string;
|
|
24
|
+
};
|
|
25
|
+
export type R2MultipartPart = {
|
|
26
|
+
readonly partNumber: number;
|
|
27
|
+
readonly etag: string;
|
|
28
|
+
};
|
|
29
|
+
export interface R2MultipartUploadLike {
|
|
30
|
+
readonly uploadId?: string;
|
|
31
|
+
uploadPart(partNumber: number, value: R2PutValue): Promise<{
|
|
32
|
+
readonly etag: string;
|
|
33
|
+
}>;
|
|
34
|
+
complete(parts: readonly R2MultipartPart[]): Promise<R2ObjectLike | void>;
|
|
35
|
+
abort(): Promise<void>;
|
|
36
|
+
listParts?(): Promise<readonly R2MultipartPart[]>;
|
|
37
|
+
}
|
|
38
|
+
export interface R2BucketLike {
|
|
39
|
+
put(key: string, value: R2PutValue, options?: {
|
|
40
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
41
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
42
|
+
}): Promise<R2ObjectLike | void | null>;
|
|
43
|
+
get(key: string): Promise<R2ObjectLike | null>;
|
|
44
|
+
head(key: string): Promise<R2ObjectLike | null>;
|
|
45
|
+
delete(key: string): Promise<void>;
|
|
46
|
+
list?(options?: {
|
|
47
|
+
readonly cursor?: string;
|
|
48
|
+
readonly limit?: number;
|
|
49
|
+
readonly prefix?: string;
|
|
50
|
+
}): Promise<R2ListResultLike>;
|
|
51
|
+
createMultipartUpload?(key: string, options?: {
|
|
52
|
+
readonly httpMetadata?: R2HttpMetadata;
|
|
53
|
+
readonly customMetadata?: Readonly<Record<string, string>>;
|
|
54
|
+
}): Promise<R2MultipartUploadLike>;
|
|
55
|
+
resumeMultipartUpload?(key: string, uploadId: string): R2MultipartUploadLike;
|
|
56
|
+
}
|
|
57
|
+
export type CloudflareMediaUrlTarget = {
|
|
58
|
+
readonly url: string;
|
|
59
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* R2 Worker bindings do not issue presigned URLs. Applications can inject a
|
|
63
|
+
* signer backed by their S3-compatible endpoint, a gateway, or their own
|
|
64
|
+
* authenticated upload route.
|
|
65
|
+
*/
|
|
66
|
+
export interface CloudflareMediaUrlSigner {
|
|
67
|
+
signUpload(input: {
|
|
68
|
+
readonly tenantId: string;
|
|
69
|
+
readonly key: string;
|
|
70
|
+
readonly contentType: string;
|
|
71
|
+
readonly expiresAt: Date;
|
|
72
|
+
readonly expectedSize?: number;
|
|
73
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
74
|
+
signMultipartPart(input: {
|
|
75
|
+
readonly tenantId: string;
|
|
76
|
+
readonly key: string;
|
|
77
|
+
readonly uploadId: string;
|
|
78
|
+
readonly partNumber: number;
|
|
79
|
+
readonly expiresAt: Date;
|
|
80
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
81
|
+
signRead(input: {
|
|
82
|
+
readonly tenantId: string;
|
|
83
|
+
readonly key: string;
|
|
84
|
+
readonly expiresAt: Date;
|
|
85
|
+
}): Promise<CloudflareMediaUrlTarget>;
|
|
86
|
+
}
|
|
87
|
+
export type CloudflareMediaBucketContext = {
|
|
88
|
+
readonly tenantId: string;
|
|
89
|
+
readonly bucketName?: string;
|
|
90
|
+
};
|
|
91
|
+
export type CloudflareMediaBucketTarget = {
|
|
92
|
+
readonly bucket: R2BucketLike;
|
|
93
|
+
readonly signer: CloudflareMediaUrlSigner;
|
|
94
|
+
readonly bucketName?: string;
|
|
95
|
+
};
|
|
96
|
+
export type CloudflareMediaBucketResolver = (context: CloudflareMediaBucketContext) => CloudflareMediaBucketTarget | Promise<CloudflareMediaBucketTarget>;
|
|
97
|
+
/**
|
|
98
|
+
* A resolver is useful for tenant-specific R2 buckets or S3-compatible R2
|
|
99
|
+
* clients. It deliberately exposes only the operations needed by this package,
|
|
100
|
+
* avoiding a dependency on a particular S3 SDK.
|
|
101
|
+
*/
|
|
102
|
+
export interface CloudflareMediaS3CompatibleResolver {
|
|
103
|
+
resolve(context: CloudflareMediaBucketContext): Promise<CloudflareMediaBucketTarget>;
|
|
104
|
+
}
|
|
105
|
+
export type CloudflareMediaBucketSource = CloudflareMediaBucketTarget | CloudflareMediaBucketResolver | CloudflareMediaS3CompatibleResolver;
|
|
106
|
+
export type CloudflareMediaStaticBucket = CloudflareMediaBucketTarget;
|
|
107
|
+
export type CloudflareMediaDynamicBucketResolver = CloudflareMediaBucketResolver | CloudflareMediaS3CompatibleResolver;
|
|
108
|
+
export type CloudflareUploadRecord = {
|
|
109
|
+
readonly session: MediaUploadSession;
|
|
110
|
+
readonly tenantId: string;
|
|
111
|
+
readonly key: string;
|
|
112
|
+
readonly contentType: string;
|
|
113
|
+
readonly fileName: string;
|
|
114
|
+
readonly uploadId?: string;
|
|
115
|
+
readonly partSizeBytes?: number;
|
|
116
|
+
};
|
|
117
|
+
export type CloudflareObjectRecord = {
|
|
118
|
+
readonly object: MediaStoredObject;
|
|
119
|
+
readonly key: string;
|
|
120
|
+
};
|
|
121
|
+
export interface CloudflareMediaMetadataStore {
|
|
122
|
+
saveUpload(record: CloudflareUploadRecord): Promise<void>;
|
|
123
|
+
getUpload(id: string): Promise<CloudflareUploadRecord | null>;
|
|
124
|
+
updateUpload(id: string, update: Partial<Pick<CloudflareUploadRecord, "session">>): Promise<CloudflareUploadRecord | null>;
|
|
125
|
+
listExpiredUploads(before: Date, first: number, tenantId?: string): Promise<readonly CloudflareUploadRecord[]>;
|
|
126
|
+
saveObject(record: CloudflareObjectRecord): Promise<void>;
|
|
127
|
+
getObject(key: string, tenantId?: string): Promise<CloudflareObjectRecord | null>;
|
|
128
|
+
deleteObject(key: string, tenantId?: string): Promise<boolean>;
|
|
129
|
+
listObjects(input: {
|
|
130
|
+
readonly first: number;
|
|
131
|
+
readonly cursor?: string;
|
|
132
|
+
readonly olderThan?: Date;
|
|
133
|
+
readonly tenantId?: string;
|
|
134
|
+
}): Promise<readonly CloudflareObjectRecord[]>;
|
|
135
|
+
}
|
|
136
|
+
export type CloudflareR2MediaObjectStorageOptions = {
|
|
137
|
+
readonly bucket: CloudflareMediaBucketSource;
|
|
138
|
+
readonly metadataStore: CloudflareMediaMetadataStore;
|
|
139
|
+
readonly tenantId?: string;
|
|
140
|
+
readonly bucketName?: string;
|
|
141
|
+
readonly idFactory?: () => string;
|
|
142
|
+
readonly now?: () => Date;
|
|
143
|
+
readonly maxSignedUrlTtlMs?: number;
|
|
144
|
+
readonly maxListPageSize?: number;
|
|
145
|
+
};
|
|
146
|
+
export type CloudflareR2MediaObjectStorageAdapterOptions = CloudflareR2MediaObjectStorageOptions;
|
|
147
|
+
export type CloudflareR2BucketProvisionerApi = {
|
|
148
|
+
getBucket(name: string): Promise<CloudflareR2BucketInfo | null>;
|
|
149
|
+
createBucket(input: {
|
|
150
|
+
readonly name: string;
|
|
151
|
+
readonly locationHint?: string;
|
|
152
|
+
}): Promise<CloudflareR2BucketInfo>;
|
|
153
|
+
};
|
|
154
|
+
export type CloudflareR2BucketInfo = {
|
|
155
|
+
readonly name: string;
|
|
156
|
+
readonly creationDate?: Date;
|
|
157
|
+
readonly location?: string;
|
|
158
|
+
};
|
|
159
|
+
export type CloudflareR2BucketProvisionerOptions = {
|
|
160
|
+
readonly api: CloudflareR2BucketProvisionerApi;
|
|
161
|
+
readonly nameForTenant?: (tenantId: string) => string;
|
|
162
|
+
};
|
|
163
|
+
export type CloudflareR2S3UrlSignerOptions = {
|
|
164
|
+
readonly endpoint: string;
|
|
165
|
+
readonly bucketName: string;
|
|
166
|
+
readonly accessKeyId: string;
|
|
167
|
+
readonly secretAccessKey: string;
|
|
168
|
+
readonly region?: string;
|
|
169
|
+
readonly now?: () => Date;
|
|
170
|
+
};
|
|
171
|
+
export type CloudflareImagesSource = string | ArrayBuffer | Uint8Array | Blob | ReadableStream<Uint8Array>;
|
|
172
|
+
export type CloudflareImagesOutputLike = {
|
|
173
|
+
response(): Promise<Response | {
|
|
174
|
+
readonly arrayBuffer: () => Promise<ArrayBuffer>;
|
|
175
|
+
readonly headers?: Headers;
|
|
176
|
+
}>;
|
|
177
|
+
};
|
|
178
|
+
export type CloudflareImagesTransformLike = {
|
|
179
|
+
output(options?: {
|
|
180
|
+
readonly format?: string;
|
|
181
|
+
readonly quality?: number;
|
|
182
|
+
}): CloudflareImagesOutputLike;
|
|
183
|
+
};
|
|
184
|
+
export type CloudflareImagesInputLike = {
|
|
185
|
+
transform(options: {
|
|
186
|
+
readonly width?: number;
|
|
187
|
+
readonly height?: number;
|
|
188
|
+
readonly fit?: "scale-down" | "contain" | "cover" | "crop" | "pad";
|
|
189
|
+
}): CloudflareImagesTransformLike;
|
|
190
|
+
};
|
|
191
|
+
export interface CloudflareImagesBinding {
|
|
192
|
+
input(source: CloudflareImagesSource): CloudflareImagesInputLike;
|
|
193
|
+
}
|
|
194
|
+
export type CloudflareImagesVariantWriteInput = {
|
|
195
|
+
readonly asset: MediaAsset;
|
|
196
|
+
readonly profile: MediaImageProfile;
|
|
197
|
+
readonly bytes: Uint8Array;
|
|
198
|
+
readonly mimeType: string;
|
|
199
|
+
readonly checksum: MediaChecksum;
|
|
200
|
+
};
|
|
201
|
+
export type CloudflareImagesProcessorOptions = {
|
|
202
|
+
readonly images: CloudflareImagesBinding;
|
|
203
|
+
readonly source: (asset: MediaAsset) => CloudflareImagesSource | Promise<CloudflareImagesSource>;
|
|
204
|
+
readonly writeVariant: (input: CloudflareImagesVariantWriteInput) => Promise<{
|
|
205
|
+
readonly object: MediaObjectReference;
|
|
206
|
+
readonly size?: number;
|
|
207
|
+
readonly mimeType?: string;
|
|
208
|
+
readonly width?: number;
|
|
209
|
+
readonly height?: number;
|
|
210
|
+
}>;
|
|
211
|
+
readonly idFactory?: () => string;
|
|
212
|
+
};
|
package/dist/utils.cjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const require_errors = require("./errors.cjs");
|
|
2
|
+
let _puzzle_ui_media = require("@puzzle-ui/media");
|
|
3
|
+
// src/utils.ts
|
|
4
|
+
const validateTenantId = (tenantId) => {
|
|
5
|
+
if (typeof tenantId !== "string" || tenantId.trim() === "") throw new _puzzle_ui_media.MediaValidationError("tenantId must be a non-empty string.");
|
|
6
|
+
if (tenantId.length > 200 || /[\u0000-\u001f\u007f]/.test(tenantId)) throw new _puzzle_ui_media.MediaValidationError("tenantId contains unsupported characters.");
|
|
7
|
+
return tenantId;
|
|
8
|
+
};
|
|
9
|
+
const validateUploadConstraints = (input) => {
|
|
10
|
+
validateTenantId(input.tenantId);
|
|
11
|
+
if (typeof input.fileName !== "string" || input.fileName.trim() === "") throw new _puzzle_ui_media.MediaValidationError("fileName must be a non-empty string.");
|
|
12
|
+
if (input.fileName.length > 512 || /[\u0000-\u001f\u007f]/.test(input.fileName)) throw new _puzzle_ui_media.MediaValidationError("fileName contains unsupported characters.");
|
|
13
|
+
if (typeof input.contentType !== "string" || !/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(input.contentType)) throw new _puzzle_ui_media.MediaValidationError("contentType must be a valid MIME type.");
|
|
14
|
+
if (input.expectedSize !== void 0 && (!Number.isSafeInteger(input.expectedSize) || input.expectedSize < 1)) throw new _puzzle_ui_media.MediaValidationError("expectedSize must be a positive safe integer.");
|
|
15
|
+
validatePositiveInteger(input.expiresInMs, "expiresInMs");
|
|
16
|
+
if (input.objectPrefix !== void 0) {
|
|
17
|
+
if (input.objectPrefix.trim() === "" || input.objectPrefix.startsWith("/") || input.objectPrefix.includes("\\") || input.objectPrefix.split("/").some((segment) => segment === "." || segment === "..") || /[\u0000-\u001f\u007f]/.test(input.objectPrefix)) throw new _puzzle_ui_media.MediaValidationError("objectPrefix must be a safe relative prefix.");
|
|
18
|
+
}
|
|
19
|
+
const expectedChecksum = input.expectedChecksum ? (0, _puzzle_ui_media.normalizeMediaChecksum)(input.expectedChecksum) : void 0;
|
|
20
|
+
return {
|
|
21
|
+
...input,
|
|
22
|
+
tenantId: input.tenantId.trim(),
|
|
23
|
+
contentType: input.contentType.toLowerCase(),
|
|
24
|
+
...expectedChecksum ? { expectedChecksum } : {}
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const validatePositiveInteger = (value, name) => {
|
|
28
|
+
if (!Number.isSafeInteger(value) || value < 1) throw new _puzzle_ui_media.MediaValidationError(`${name} must be a positive safe integer.`);
|
|
29
|
+
};
|
|
30
|
+
const validateExpiry = (value, name, max) => {
|
|
31
|
+
validatePositiveInteger(value, name);
|
|
32
|
+
if (value > max) throw new _puzzle_ui_media.MediaValidationError(`${name} exceeds the configured limit.`);
|
|
33
|
+
};
|
|
34
|
+
const createTenantObjectKey = (tenantId, uploadId, fileName, prefix) => {
|
|
35
|
+
const safeName = fileName.replace(/[^\w.\-]+/g, "_").replace(/^\.*/, "") || "file";
|
|
36
|
+
return `${prefix ? `${prefix.replace(/\/+$/g, "")}/` : ""}tenants/${encodeURIComponent(tenantId)}/${uploadId}/${safeName}`;
|
|
37
|
+
};
|
|
38
|
+
const normalizeReference = (object) => (0, _puzzle_ui_media.normalizeMediaObjectReference)(object);
|
|
39
|
+
const sha256 = async (bytes) => {
|
|
40
|
+
if (!globalThis.crypto?.subtle) throw new require_errors.CloudflareMediaValidationError("Web Crypto is required for checksum verification.");
|
|
41
|
+
const digest = await globalThis.crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
|
|
42
|
+
return {
|
|
43
|
+
algorithm: "sha256",
|
|
44
|
+
value: [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("")
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
const checksumEquals = (left, right) => (0, _puzzle_ui_media.normalizeMediaChecksum)(left).value === (0, _puzzle_ui_media.normalizeMediaChecksum)(right).value;
|
|
48
|
+
const cursorForObject = (key) => encodeURIComponent(key);
|
|
49
|
+
exports.checksumEquals = checksumEquals;
|
|
50
|
+
exports.createTenantObjectKey = createTenantObjectKey;
|
|
51
|
+
exports.cursorForObject = cursorForObject;
|
|
52
|
+
exports.normalizeReference = normalizeReference;
|
|
53
|
+
exports.sha256 = sha256;
|
|
54
|
+
exports.validateExpiry = validateExpiry;
|
|
55
|
+
exports.validatePositiveInteger = validatePositiveInteger;
|
|
56
|
+
exports.validateTenantId = validateTenantId;
|
|
57
|
+
exports.validateUploadConstraints = validateUploadConstraints;
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=utils.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["MediaValidationError","normalizeMediaChecksum","normalizeMediaObjectReference","CloudflareMediaValidationError"],"sources":["../src/utils.ts"],"sourcesContent":["import {\n MediaValidationError,\n normalizeMediaChecksum,\n normalizeMediaObjectReference,\n} from \"@puzzle-ui/media\";\nimport type {\n MediaChecksum,\n MediaObjectReference,\n MediaUploadConstraints,\n} from \"@puzzle-ui/media\";\nimport { CloudflareMediaValidationError } from \"./errors\";\n\nexport const validateTenantId = (tenantId: string): string => {\n if (typeof tenantId !== \"string\" || tenantId.trim() === \"\") {\n throw new MediaValidationError(\"tenantId must be a non-empty string.\");\n }\n if (tenantId.length > 200 || /[\\u0000-\\u001f\\u007f]/.test(tenantId)) {\n throw new MediaValidationError(\"tenantId contains unsupported characters.\");\n }\n return tenantId;\n};\n\nexport const validateUploadConstraints = (\n input: MediaUploadConstraints,\n): MediaUploadConstraints => {\n validateTenantId(input.tenantId);\n if (typeof input.fileName !== \"string\" || input.fileName.trim() === \"\") {\n throw new MediaValidationError(\"fileName must be a non-empty string.\");\n }\n if (input.fileName.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(input.fileName)) {\n throw new MediaValidationError(\"fileName contains unsupported characters.\");\n }\n if (\n typeof input.contentType !== \"string\" ||\n !/^[a-z0-9!#$&^_.+-]+\\/[a-z0-9!#$&^_.+-]+$/i.test(input.contentType)\n ) {\n throw new MediaValidationError(\"contentType must be a valid MIME type.\");\n }\n if (\n input.expectedSize !== undefined &&\n (!Number.isSafeInteger(input.expectedSize) || input.expectedSize < 1)\n ) {\n throw new MediaValidationError(\"expectedSize must be a positive safe integer.\");\n }\n validatePositiveInteger(input.expiresInMs, \"expiresInMs\");\n if (input.objectPrefix !== undefined) {\n if (\n input.objectPrefix.trim() === \"\" ||\n input.objectPrefix.startsWith(\"/\") ||\n input.objectPrefix.includes(\"\\\\\") ||\n input.objectPrefix.split(\"/\").some((segment) => segment === \".\" || segment === \"..\") ||\n /[\\u0000-\\u001f\\u007f]/.test(input.objectPrefix)\n ) {\n throw new MediaValidationError(\"objectPrefix must be a safe relative prefix.\");\n }\n }\n const expectedChecksum = input.expectedChecksum\n ? normalizeMediaChecksum(input.expectedChecksum)\n : undefined;\n return {\n ...input,\n tenantId: input.tenantId.trim(),\n contentType: input.contentType.toLowerCase(),\n ...(expectedChecksum ? { expectedChecksum } : {}),\n };\n};\n\nexport const validatePositiveInteger = (value: number, name: string): void => {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new MediaValidationError(`${name} must be a positive safe integer.`);\n }\n};\n\nexport const validateExpiry = (\n value: number,\n name: string,\n max: number,\n): void => {\n validatePositiveInteger(value, name);\n if (value > max) {\n throw new MediaValidationError(`${name} exceeds the configured limit.`);\n }\n};\n\nexport const createTenantObjectKey = (\n tenantId: string,\n uploadId: string,\n fileName: string,\n prefix?: string,\n): string => {\n const safeName = fileName.replace(/[^\\w.\\-]+/g, \"_\").replace(/^\\.*/, \"\") || \"file\";\n const safePrefix = prefix ? `${prefix.replace(/\\/+$/g, \"\")}/` : \"\";\n return `${safePrefix}tenants/${encodeURIComponent(tenantId)}/${uploadId}/${safeName}`;\n};\n\nexport const normalizeReference = (object: MediaObjectReference): MediaObjectReference =>\n normalizeMediaObjectReference(object);\n\nexport const sha256 = async (bytes: Uint8Array): Promise<MediaChecksum> => {\n if (!globalThis.crypto?.subtle) {\n throw new CloudflareMediaValidationError(\"Web Crypto is required for checksum verification.\");\n }\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new Uint8Array(bytes),\n );\n return {\n algorithm: \"sha256\",\n value: [...new Uint8Array(digest)]\n .map((byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\"),\n };\n};\n\nexport const checksumEquals = (\n left: MediaChecksum,\n right: MediaChecksum,\n): boolean => normalizeMediaChecksum(left).value === normalizeMediaChecksum(right).value;\n\nexport const cursorForObject = (key: string): string =>\n encodeURIComponent(key);\n"],"mappings":";;;AAYA,MAAa,oBAAoB,aAA6B;CAC5D,IAAI,OAAO,aAAa,YAAY,SAAS,KAAK,MAAM,IACtD,MAAM,IAAIA,iBAAAA,qBAAqB,sCAAsC;CAEvE,IAAI,SAAS,SAAS,OAAO,wBAAwB,KAAK,QAAQ,GAChE,MAAM,IAAIA,iBAAAA,qBAAqB,2CAA2C;CAE5E,OAAO;AACT;AAEA,MAAa,6BACX,UAC2B;CAC3B,iBAA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,wBAAwB,OAAO,IAAI;CACnC,IAAI,QAAQ,KACV,MAAM,IAAIA,iBAAAA,qBAAqB,GAAG,KAAK,+BAA+B;AAE1E;AAEA,MAAa,yBACX,UACA,UACA,UACA,WACW;CACX,MAAM,WAAW,SAAS,QAAQ,cAAc,GAAG,CAAC,CAAC,QAAQ,QAAQ,EAAE,KAAK;CAE5E,OAAO,GADY,SAAS,GAAG,OAAO,QAAQ,SAAS,EAAE,EAAE,KAAK,GAC3C,UAAU,mBAAmB,QAAQ,EAAE,GAAG,SAAS,GAAG;AAC7E;AAEA,MAAa,sBAAsB,YAAA,GACjCE,iBAAAA,8BAAAA,CAA8B,MAAM;AAEtC,MAAa,SAAS,OAAO,UAA8C;CACzE,IAAI,CAAC,WAAW,QAAQ,QACtB,MAAM,IAAIC,eAAAA,+BAA+B,mDAAmD;CAE9F,MAAM,SAAS,MAAM,WAAW,OAAO,OAAO,OAC5C,WACA,IAAI,WAAW,KAAK,CACtB;CACA,OAAO;EACL,WAAW;EACX,OAAO,CAAC,GAAG,IAAI,WAAW,MAAM,CAAC,CAAC,CAC/B,KAAK,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CACjD,KAAK,EAAE;CACZ;AACF;AAEA,MAAa,kBACX,MACA,WAAA,GACYF,iBAAAA,uBAAAA,CAAuB,IAAI,CAAC,CAAC,WAAA,GAAUA,iBAAAA,uBAAAA,CAAuB,KAAK,CAAC,CAAC;AAEnF,MAAa,mBAAmB,QAC9B,mBAAmB,GAAG"}
|
package/dist/utils.d.cts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { MediaChecksum, MediaObjectReference, MediaUploadConstraints } from "@puzzle-ui/media";
|
|
2
|
+
export declare const validateTenantId: (tenantId: string) => string;
|
|
3
|
+
export declare const validateUploadConstraints: (input: MediaUploadConstraints) => MediaUploadConstraints;
|
|
4
|
+
export declare const validatePositiveInteger: (value: number, name: string) => void;
|
|
5
|
+
export declare const validateExpiry: (value: number, name: string, max: number) => void;
|
|
6
|
+
export declare const createTenantObjectKey: (tenantId: string, uploadId: string, fileName: string, prefix?: string) => string;
|
|
7
|
+
export declare const normalizeReference: (object: MediaObjectReference) => MediaObjectReference;
|
|
8
|
+
export declare const sha256: (bytes: Uint8Array) => Promise<MediaChecksum>;
|
|
9
|
+
export declare const checksumEquals: (left: MediaChecksum, right: MediaChecksum) => boolean;
|
|
10
|
+
export declare const cursorForObject: (key: string) => string;
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { MediaChecksum, MediaObjectReference, MediaUploadConstraints } from "@puzzle-ui/media";
|
|
2
|
+
export declare const validateTenantId: (tenantId: string) => string;
|
|
3
|
+
export declare const validateUploadConstraints: (input: MediaUploadConstraints) => MediaUploadConstraints;
|
|
4
|
+
export declare const validatePositiveInteger: (value: number, name: string) => void;
|
|
5
|
+
export declare const validateExpiry: (value: number, name: string, max: number) => void;
|
|
6
|
+
export declare const createTenantObjectKey: (tenantId: string, uploadId: string, fileName: string, prefix?: string) => string;
|
|
7
|
+
export declare const normalizeReference: (object: MediaObjectReference) => MediaObjectReference;
|
|
8
|
+
export declare const sha256: (bytes: Uint8Array) => Promise<MediaChecksum>;
|
|
9
|
+
export declare const checksumEquals: (left: MediaChecksum, right: MediaChecksum) => boolean;
|
|
10
|
+
export declare const cursorForObject: (key: string) => string;
|