@benjavicente/convex-r2 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +274 -2
  4. package/dist/browser/index.d.ts +33 -0
  5. package/dist/browser/index.js +57 -0
  6. package/dist/client/index.d.ts +105 -0
  7. package/dist/client/index.js +75 -0
  8. package/dist/component/_generated/api.d.ts +39 -0
  9. package/dist/component/_generated/api.js +30 -0
  10. package/dist/component/_generated/component.d.ts +90 -0
  11. package/dist/component/_generated/component.js +10 -0
  12. package/dist/component/_generated/dataModel.d.ts +45 -0
  13. package/dist/component/_generated/dataModel.js +10 -0
  14. package/dist/component/_generated/server.d.ts +136 -0
  15. package/dist/component/_generated/server.js +79 -0
  16. package/dist/component/convex.config.d.ts +8 -0
  17. package/dist/component/convex.config.js +11 -0
  18. package/dist/component/r2.d.ts +39 -0
  19. package/dist/component/r2.js +77 -0
  20. package/dist/component/schema.d.ts +37 -0
  21. package/dist/component/schema.js +20 -0
  22. package/dist/component/sigv4.d.ts +23 -0
  23. package/dist/component/sigv4.js +63 -0
  24. package/dist/component/uploads.d.ts +161 -0
  25. package/dist/component/uploads.js +346 -0
  26. package/dist/component/validators.d.ts +74 -0
  27. package/dist/component/validators.js +30 -0
  28. package/package.json +63 -3
  29. package/src/browser/index.ts +86 -0
  30. package/src/client/index.ts +157 -0
  31. package/src/component/_generated/api.ts +56 -0
  32. package/src/component/_generated/component.ts +111 -0
  33. package/src/component/_generated/dataModel.ts +60 -0
  34. package/src/component/_generated/server.ts +173 -0
  35. package/src/component/convex.config.ts +12 -0
  36. package/src/component/r2.ts +90 -0
  37. package/src/component/schema.ts +23 -0
  38. package/src/component/sigv4.ts +102 -0
  39. package/src/component/uploads.ts +378 -0
  40. package/src/component/validators.ts +40 -0
  41. package/src/test.ts +14 -0
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Generated `ComponentApi` utility.
3
+ *
4
+ * THIS CODE IS AUTOMATICALLY GENERATED.
5
+ *
6
+ * To regenerate, run `npx convex dev`.
7
+ * @module
8
+ */
9
+ import type { FunctionReference } from "convex/server";
10
+ /**
11
+ * A utility for referencing a Convex component's exposed API.
12
+ *
13
+ * Useful when expecting a parameter like `components.myComponent`.
14
+ * Usage:
15
+ * ```ts
16
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
17
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
18
+ * }
19
+ * ```
20
+ */
21
+ export type ComponentApi<Name extends string | undefined = string | undefined> = {
22
+ uploads: {
23
+ confirm: FunctionReference<"action", "internal", {
24
+ uploadId: string;
25
+ }, {
26
+ status: "ready";
27
+ } | {
28
+ status: "notUploaded";
29
+ } | {
30
+ reason: string;
31
+ status: "rejected";
32
+ } | {
33
+ status: "missing";
34
+ }, Name>;
35
+ confirmStored: FunctionReference<"mutation", "internal", {
36
+ uploadId: string;
37
+ }, {
38
+ status: "ready";
39
+ } | {
40
+ status: "notUploaded";
41
+ } | {
42
+ reason: string;
43
+ status: "rejected";
44
+ } | {
45
+ status: "missing";
46
+ }, Name>;
47
+ get: FunctionReference<"query", "internal", {
48
+ uploadId: string;
49
+ }, {
50
+ bucket: string;
51
+ contentType: string;
52
+ key: string;
53
+ link: string;
54
+ name: string;
55
+ sha256: string;
56
+ size: number;
57
+ uploadId: string;
58
+ } | null, Name>;
59
+ getUrl: FunctionReference<"query", "internal", {
60
+ disposition?: "inline" | "attachment";
61
+ expiresIn?: number;
62
+ uploadId: string;
63
+ }, string | null, Name>;
64
+ remove: FunctionReference<"mutation", "internal", {
65
+ uploadId: string;
66
+ }, null, Name>;
67
+ request: FunctionReference<"mutation", "internal", {
68
+ bucket?: string;
69
+ context: any;
70
+ file: {
71
+ contentType: string;
72
+ name: string;
73
+ sha256: string;
74
+ size: number;
75
+ };
76
+ keyPrefix: string;
77
+ onConfirm: import("convex/server").FunctionHandle_future<"mutation", any, any>;
78
+ rules: {
79
+ contentTypes: Array<string>;
80
+ maxSize: number;
81
+ };
82
+ }, {
83
+ expiresAt: number;
84
+ headers: Record<string, string>;
85
+ key: string;
86
+ uploadId: string;
87
+ url: string;
88
+ }, Name>;
89
+ };
90
+ };
@@ -0,0 +1,10 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+ export {};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Generated data model types.
3
+ *
4
+ * THIS CODE IS AUTOMATICALLY GENERATED.
5
+ *
6
+ * To regenerate, run `npx convex dev`.
7
+ * @module
8
+ */
9
+ import type { DataModelFromSchemaDefinition, DocumentByName, TableNamesInDataModel, SystemTableNames } from "convex/server";
10
+ import type { GenericId } from "convex/values";
11
+ import schema from "../schema.js";
12
+ /**
13
+ * The names of all of your Convex tables.
14
+ */
15
+ export type TableNames = TableNamesInDataModel<DataModel>;
16
+ /**
17
+ * The type of a document stored in Convex.
18
+ *
19
+ * @typeParam TableName - A string literal type of the table name (like "users").
20
+ */
21
+ export type Doc<TableName extends TableNames> = DocumentByName<DataModel, TableName>;
22
+ /**
23
+ * An identifier for a document in Convex.
24
+ *
25
+ * Convex documents are uniquely identified by their `Id`, which is accessible
26
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
27
+ *
28
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
29
+ *
30
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
31
+ * strings when type checking.
32
+ *
33
+ * @typeParam TableName - A string literal type of the table name (like "users").
34
+ */
35
+ export type Id<TableName extends TableNames | SystemTableNames> = GenericId<TableName>;
36
+ /**
37
+ * A type describing your Convex data model.
38
+ *
39
+ * This type includes information about what tables you have, the type of
40
+ * documents stored in those tables, and the indexes defined on them.
41
+ *
42
+ * This type is used to parameterize methods like `queryGeneric` and
43
+ * `mutationGeneric` to make them type-safe.
44
+ */
45
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -0,0 +1,10 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated data model types.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+ import schema from "../schema.js";
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Generated utilities for implementing server-side Convex query and mutation functions.
3
+ *
4
+ * THIS CODE IS AUTOMATICALLY GENERATED.
5
+ *
6
+ * To regenerate, run `npx convex dev`.
7
+ * @module
8
+ */
9
+ import type { ActionBuilder, HttpActionBuilder, MutationBuilder, QueryBuilder, GenericActionCtx, GenericMutationCtx, GenericQueryCtx, GenericDatabaseReader, GenericDatabaseWriter } from "convex/server";
10
+ import type { DataModel } from "./dataModel.js";
11
+ /**
12
+ * Typesafe environment variables.
13
+ *
14
+ * This includes platform-provided env vars and any variables declared in
15
+ * `convex.config.ts`.
16
+ */
17
+ type Env = {
18
+ readonly CONVEX_CLOUD_URL: string;
19
+ readonly CONVEX_SITE_URL: string;
20
+ readonly R2_ACCESS_KEY_ID: string;
21
+ readonly R2_ACCOUNT_ID: string;
22
+ readonly R2_BUCKET: string | undefined;
23
+ readonly R2_SECRET_ACCESS_KEY: string;
24
+ };
25
+ /**
26
+ * Define a query in this Convex app's public API.
27
+ *
28
+ * This function will be allowed to read your Convex database and will be accessible from the client.
29
+ *
30
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
31
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
32
+ */
33
+ export declare const query: QueryBuilder<DataModel, "public">;
34
+ /**
35
+ * Define a query that is only accessible from other Convex functions (but not from the client).
36
+ *
37
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
38
+ *
39
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
40
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
41
+ */
42
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
43
+ /**
44
+ * Define a mutation in this Convex app's public API.
45
+ *
46
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
47
+ *
48
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
49
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export declare const mutation: MutationBuilder<DataModel, "public">;
52
+ /**
53
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
54
+ *
55
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
56
+ *
57
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
58
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
59
+ */
60
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
61
+ /**
62
+ * Define an action in this Convex app's public API.
63
+ *
64
+ * An action is a function which can execute any JavaScript code, including non-deterministic
65
+ * code and code with side-effects, like calling third-party services.
66
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
67
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
68
+ *
69
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
70
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export declare const action: ActionBuilder<DataModel, "public">;
73
+ /**
74
+ * Define an action that is only accessible from other Convex functions (but not from the client).
75
+ *
76
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
77
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
78
+ */
79
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
80
+ /**
81
+ * Define an HTTP action.
82
+ *
83
+ * The wrapped function will be used to respond to HTTP requests received
84
+ * by a Convex deployment if the requests matches the path and method where
85
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
86
+ *
87
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
88
+ * and a Fetch API `Request` object as its second.
89
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
90
+ */
91
+ export declare const httpAction: HttpActionBuilder;
92
+ export declare const env: Env;
93
+ /**
94
+ * A set of services for use within Convex query functions.
95
+ *
96
+ * The query context is passed as the first argument to any Convex query
97
+ * function run on the server.
98
+ *
99
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
100
+ */
101
+ export type QueryCtx = GenericQueryCtx<DataModel>;
102
+ /**
103
+ * A set of services for use within Convex mutation functions.
104
+ *
105
+ * The mutation context is passed as the first argument to any Convex mutation
106
+ * function run on the server.
107
+ *
108
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
109
+ */
110
+ export type MutationCtx = GenericMutationCtx<DataModel>;
111
+ /**
112
+ * A set of services for use within Convex action functions.
113
+ *
114
+ * The action context is passed as the first argument to any Convex action
115
+ * function run on the server.
116
+ */
117
+ export type ActionCtx = GenericActionCtx<DataModel>;
118
+ /**
119
+ * An interface to read from the database within Convex query functions.
120
+ *
121
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
122
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
123
+ * building a query.
124
+ */
125
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
126
+ /**
127
+ * An interface to read from and write to the database within Convex mutation
128
+ * functions.
129
+ *
130
+ * Convex guarantees that all writes within a single mutation are
131
+ * executed atomically, so you never have to worry about partial writes leaving
132
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
133
+ * for the guarantees Convex provides your functions.
134
+ */
135
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
136
+ export {};
@@ -0,0 +1,79 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+ import { actionGeneric, httpActionGeneric, queryGeneric, mutationGeneric, internalActionGeneric, internalMutationGeneric, internalQueryGeneric, } from "convex/server";
11
+ /**
12
+ * Define a query in this Convex app's public API.
13
+ *
14
+ * This function will be allowed to read your Convex database and will be accessible from the client.
15
+ *
16
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
17
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
18
+ */
19
+ export const query = queryGeneric;
20
+ /**
21
+ * Define a query that is only accessible from other Convex functions (but not from the client).
22
+ *
23
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
24
+ *
25
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
26
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
27
+ */
28
+ export const internalQuery = internalQueryGeneric;
29
+ /**
30
+ * Define a mutation in this Convex app's public API.
31
+ *
32
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
33
+ *
34
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
35
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
36
+ */
37
+ export const mutation = mutationGeneric;
38
+ /**
39
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
40
+ *
41
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
42
+ *
43
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
44
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
45
+ */
46
+ export const internalMutation = internalMutationGeneric;
47
+ /**
48
+ * Define an action in this Convex app's public API.
49
+ *
50
+ * An action is a function which can execute any JavaScript code, including non-deterministic
51
+ * code and code with side-effects, like calling third-party services.
52
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
53
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
54
+ *
55
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
56
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
57
+ */
58
+ export const action = actionGeneric;
59
+ /**
60
+ * Define an action that is only accessible from other Convex functions (but not from the client).
61
+ *
62
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
63
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
64
+ */
65
+ export const internalAction = internalActionGeneric;
66
+ /**
67
+ * Define an HTTP action.
68
+ *
69
+ * The wrapped function will be used to respond to HTTP requests received
70
+ * by a Convex deployment if the requests matches the path and method where
71
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
72
+ *
73
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
74
+ * and a Fetch API `Request` object as its second.
75
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
76
+ */
77
+ export const httpAction = httpActionGeneric;
78
+ export const env = globalThis
79
+ .process.env;
@@ -0,0 +1,8 @@
1
+ declare const _default: import("convex/server").ComponentDefinition<any, {
2
+ readonly R2_ACCOUNT_ID: import("convex/values").VString<string, "required">;
3
+ readonly R2_ACCESS_KEY_ID: import("convex/values").VString<string, "required">;
4
+ readonly R2_SECRET_ACCESS_KEY: import("convex/values").VString<string, "required">;
5
+ /** Bucket used when a call doesn't name one. */
6
+ readonly R2_BUCKET: import("convex/values").VString<string | undefined, "optional">;
7
+ }>;
8
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import { defineComponent } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export default defineComponent("r2", {
4
+ env: {
5
+ R2_ACCOUNT_ID: v.string(),
6
+ R2_ACCESS_KEY_ID: v.string(),
7
+ R2_SECRET_ACCESS_KEY: v.string(),
8
+ /** Bucket used when a call doesn't name one. */
9
+ R2_BUCKET: v.optional(v.string()),
10
+ },
11
+ });
@@ -0,0 +1,39 @@
1
+ import { type PresignOptions } from "./sigv4.js";
2
+ /** Reads the R2 config from the component's env. Call it inside handlers only. */
3
+ export declare function r2Config(): {
4
+ accountId: string;
5
+ credentials: {
6
+ accessKeyId: string;
7
+ secretAccessKey: string;
8
+ };
9
+ };
10
+ export declare function resolveBucket(bucket: string | undefined): string;
11
+ export declare function objectUrl(accountId: string, bucket: string, key: string): string;
12
+ export declare function dashboardLink(accountId: string, bucket: string, key: string): string;
13
+ export declare function presignObject(bucket: string, key: string, options: Omit<PresignOptions, "url" | "now"> & {
14
+ now?: number;
15
+ }): Promise<string>;
16
+ /** Hex SHA-256 to the base64 form of `x-amz-checksum-sha256`. */
17
+ export declare function hexToBase64(value: string): string;
18
+ export declare function base64ToHex(value: string): string;
19
+ export type ObjectHead = {
20
+ size: number;
21
+ contentType: string | null;
22
+ sha256: string | null;
23
+ };
24
+ /** HEADs an object. Returns null when it doesn't exist. Needs an action (fetch). */
25
+ /** Signed into the HEAD: R2 only returns the SHA-256 when asked. */
26
+ export declare const HEAD_SIGNED_HEADERS: {
27
+ "x-amz-checksum-mode": string;
28
+ };
29
+ /**
30
+ * Not signed: Cloudflare compresses text responses and then drops
31
+ * Content-Length, even on HEAD, unless the response is asked uncompressed.
32
+ */
33
+ export declare const HEAD_HEADERS: {
34
+ "x-amz-checksum-mode": string;
35
+ "Accept-Encoding": string;
36
+ };
37
+ export declare function headObject(bucket: string, key: string): Promise<ObjectHead | null>;
38
+ /** Deletes an object. Deleting a missing object succeeds. Needs an action (fetch). */
39
+ export declare function deleteObject(bucket: string, key: string): Promise<void>;
@@ -0,0 +1,77 @@
1
+ import { env } from "./_generated/server.js";
2
+ import { encodePath, presign } from "./sigv4.js";
3
+ /** Reads the R2 config from the component's env. Call it inside handlers only. */
4
+ export function r2Config() {
5
+ return {
6
+ accountId: env.R2_ACCOUNT_ID,
7
+ credentials: { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY },
8
+ };
9
+ }
10
+ export function resolveBucket(bucket) {
11
+ const resolved = bucket ?? env.R2_BUCKET;
12
+ if (!resolved) {
13
+ throw new Error("No R2 bucket: pass `bucket` or set the component's R2_BUCKET env var");
14
+ }
15
+ return resolved;
16
+ }
17
+ export function objectUrl(accountId, bucket, key) {
18
+ return `https://${accountId}.r2.cloudflarestorage.com/${encodePath(bucket)}/${encodePath(key)}`;
19
+ }
20
+ export function dashboardLink(accountId, bucket, key) {
21
+ return `https://dash.cloudflare.com/${accountId}/r2/default/buckets/${encodePath(bucket)}/objects/${encodeURIComponent(key)}/details`;
22
+ }
23
+ export async function presignObject(bucket, key, options) {
24
+ const { accountId, credentials } = r2Config();
25
+ return presign(credentials, {
26
+ ...options,
27
+ url: objectUrl(accountId, bucket, key),
28
+ now: options.now ?? Date.now(),
29
+ });
30
+ }
31
+ /** Hex SHA-256 to the base64 form of `x-amz-checksum-sha256`. */
32
+ export function hexToBase64(value) {
33
+ const bytes = value.match(/../g).map((pair) => parseInt(pair, 16));
34
+ return btoa(String.fromCharCode(...bytes));
35
+ }
36
+ export function base64ToHex(value) {
37
+ return Array.from(atob(value), (c) => c.charCodeAt(0).toString(16).padStart(2, "0")).join("");
38
+ }
39
+ /** HEADs an object. Returns null when it doesn't exist. Needs an action (fetch). */
40
+ /** Signed into the HEAD: R2 only returns the SHA-256 when asked. */
41
+ export const HEAD_SIGNED_HEADERS = { "x-amz-checksum-mode": "ENABLED" };
42
+ /**
43
+ * Not signed: Cloudflare compresses text responses and then drops
44
+ * Content-Length, even on HEAD, unless the response is asked uncompressed.
45
+ */
46
+ export const HEAD_HEADERS = { ...HEAD_SIGNED_HEADERS, "Accept-Encoding": "identity" };
47
+ export async function headObject(bucket, key) {
48
+ const url = await presignObject(bucket, key, {
49
+ method: "HEAD",
50
+ headers: HEAD_SIGNED_HEADERS,
51
+ expiresIn: 60,
52
+ });
53
+ const response = await fetch(url, { method: "HEAD", headers: HEAD_HEADERS });
54
+ if (response.status === 404)
55
+ return null;
56
+ if (!response.ok)
57
+ throw new Error(`R2 HEAD ${key} failed: ${response.status}`);
58
+ // Throwing lets the caller retry; reading a missing length as 0 would
59
+ // reject and delete a good file.
60
+ const length = response.headers.get("content-length");
61
+ if (length === null)
62
+ throw new Error(`R2 HEAD ${key} returned no Content-Length`);
63
+ const checksum = response.headers.get("x-amz-checksum-sha256");
64
+ return {
65
+ size: Number(length),
66
+ contentType: response.headers.get("content-type"),
67
+ sha256: checksum ? base64ToHex(checksum) : null,
68
+ };
69
+ }
70
+ /** Deletes an object. Deleting a missing object succeeds. Needs an action (fetch). */
71
+ export async function deleteObject(bucket, key) {
72
+ const url = await presignObject(bucket, key, { method: "DELETE", expiresIn: 60 });
73
+ const response = await fetch(url, { method: "DELETE" });
74
+ if (!response.ok && response.status !== 404) {
75
+ throw new Error(`R2 DELETE ${key} failed: ${response.status}`);
76
+ }
77
+ }
@@ -0,0 +1,37 @@
1
+ declare const _default: import("convex/server").SchemaDefinition<{
2
+ /** One row per R2 object, created before its upload URL is signed. */
3
+ uploads: import("convex/server").TableDefinition<import("convex/values").VObject<{
4
+ bucket: string;
5
+ contentType: string;
6
+ key: string;
7
+ name: string;
8
+ pending?: {
9
+ context: any;
10
+ expiresAt: number;
11
+ onConfirm: import("convex/server").FunctionHandle_future<"mutation", any, any>;
12
+ } | undefined;
13
+ sha256: string;
14
+ size: number;
15
+ }, {
16
+ name: import("convex/values").VString<string, "required">;
17
+ contentType: import("convex/values").VString<string, "required">;
18
+ size: import("convex/values").VFloat64<number, "required">;
19
+ sha256: import("convex/values").VString<string, "required">;
20
+ bucket: import("convex/values").VString<string, "required">;
21
+ /** `<keyPrefix>/<upload id>`; empty only between insert and patch. */
22
+ key: import("convex/values").VString<string, "required">;
23
+ /** Present until the upload is confirmed; a row without it is ready. */
24
+ pending: import("convex/values").VObject<{
25
+ context: any;
26
+ expiresAt: number;
27
+ onConfirm: import("convex/server").FunctionHandle_future<"mutation", any, any>;
28
+ } | undefined, {
29
+ /** When the upload URL expires. */
30
+ expiresAt: import("convex/values").VFloat64<number, "required">;
31
+ /** Handle of the app's mutation, run with `{ upload, context }`. */
32
+ onConfirm: import("convex/values").VFunction<import("convex/server").FunctionHandle_future<"mutation", any, any>, "required">;
33
+ context: import("convex/values").VAny<any, "required", string>;
34
+ }, "optional", "context" | "expiresAt" | "onConfirm" | `context.${string}`>;
35
+ }, "required", "bucket" | "contentType" | "key" | "name" | "pending" | "pending.context" | "pending.expiresAt" | "pending.onConfirm" | "sha256" | "size" | `pending.context.${string}`>, {}, {}, {}>;
36
+ }, true>;
37
+ export default _default;
@@ -0,0 +1,20 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { fileValidator } from "./validators.js";
4
+ export default defineSchema({
5
+ /** One row per R2 object, created before its upload URL is signed. */
6
+ uploads: defineTable({
7
+ bucket: v.string(),
8
+ /** `<keyPrefix>/<upload id>`; empty only between insert and patch. */
9
+ key: v.string(),
10
+ ...fileValidator.fields,
11
+ /** Present until the upload is confirmed; a row without it is ready. */
12
+ pending: v.optional(v.object({
13
+ /** When the upload URL expires. */
14
+ expiresAt: v.number(),
15
+ /** Handle of the app's mutation, run with `{ upload, context }`. */
16
+ onConfirm: v.function({ fnType: "mutation" }),
17
+ context: v.any(),
18
+ })),
19
+ }),
20
+ });
@@ -0,0 +1,23 @@
1
+ export type Credentials = {
2
+ accessKeyId: string;
3
+ secretAccessKey: string;
4
+ };
5
+ export type PresignOptions = {
6
+ method: "GET" | "HEAD" | "PUT" | "DELETE";
7
+ /** Full object URL, e.g. `https://<account>.r2.cloudflarestorage.com/<bucket>/<key>`. */
8
+ url: string;
9
+ /** Headers the request must send with these exact values. */
10
+ headers?: Record<string, string>;
11
+ /** Extra query parameters to sign, e.g. `response-content-disposition`. */
12
+ query?: Record<string, string>;
13
+ expiresIn: number;
14
+ /** Signing time, in milliseconds since the epoch. */
15
+ now: number;
16
+ region?: string;
17
+ };
18
+ /** RFC 3986 encoding, as SigV4 requires. */
19
+ export declare function uriEncode(value: string): string;
20
+ /** Encodes each segment of an unencoded object path. */
21
+ export declare function encodePath(path: string): string;
22
+ /** Returns a presigned URL. The caller must send `headers` unchanged. */
23
+ export declare function presign(credentials: Credentials, options: PresignOptions): Promise<string>;
@@ -0,0 +1,63 @@
1
+ // Minimal AWS Signature V4 query presigning for R2's S3 API, on WebCrypto only.
2
+ // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
3
+ const encoder = new TextEncoder();
4
+ /** RFC 3986 encoding, as SigV4 requires. */
5
+ export function uriEncode(value) {
6
+ return encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
7
+ }
8
+ /** Encodes each segment of an unencoded object path. */
9
+ export function encodePath(path) {
10
+ return path.split("/").map(uriEncode).join("/");
11
+ }
12
+ function hex(buffer) {
13
+ return Array.from(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, "0")).join("");
14
+ }
15
+ async function sha256Hex(value) {
16
+ return hex(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
17
+ }
18
+ async function hmac(key, value) {
19
+ const cryptoKey = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
20
+ return crypto.subtle.sign("HMAC", cryptoKey, encoder.encode(value));
21
+ }
22
+ /** Returns a presigned URL. The caller must send `headers` unchanged. */
23
+ export async function presign(credentials, options) {
24
+ const region = options.region ?? "auto";
25
+ const url = new URL(options.url);
26
+ const amzDate = new Date(options.now).toISOString().replace(/[:-]|\.\d{3}/g, "");
27
+ const date = amzDate.slice(0, 8);
28
+ const scope = `${date}/${region}/s3/aws4_request`;
29
+ const headers = new Map([["host", url.host]]);
30
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
31
+ headers.set(name.toLowerCase(), value.trim().replace(/\s+/g, " "));
32
+ }
33
+ const headerNames = [...headers.keys()].sort();
34
+ const signedHeaders = headerNames.join(";");
35
+ const query = {
36
+ ...options.query,
37
+ "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
38
+ "X-Amz-Credential": `${credentials.accessKeyId}/${scope}`,
39
+ "X-Amz-Date": amzDate,
40
+ "X-Amz-Expires": String(options.expiresIn),
41
+ "X-Amz-SignedHeaders": signedHeaders,
42
+ };
43
+ const canonicalQuery = Object.keys(query)
44
+ .sort()
45
+ .map((name) => `${uriEncode(name)}=${uriEncode(query[name])}`)
46
+ .join("&");
47
+ // `url.pathname` must already be encoded with `encodePath`.
48
+ const canonicalUri = url.pathname;
49
+ const canonicalRequest = [
50
+ options.method,
51
+ canonicalUri,
52
+ canonicalQuery,
53
+ headerNames.map((name) => `${name}:${headers.get(name)}\n`).join(""),
54
+ signedHeaders,
55
+ "UNSIGNED-PAYLOAD",
56
+ ].join("\n");
57
+ const stringToSign = ["AWS4-HMAC-SHA256", amzDate, scope, await sha256Hex(canonicalRequest)].join("\n");
58
+ let key = encoder.encode(`AWS4${credentials.secretAccessKey}`);
59
+ for (const part of [date, region, "s3", "aws4_request"])
60
+ key = await hmac(key, part);
61
+ const signature = hex(await hmac(key, stringToSign));
62
+ return `${url.origin}${canonicalUri}?${canonicalQuery}&X-Amz-Signature=${signature}`;
63
+ }