@pithy-sh/storage 0.2.10 → 0.3.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.
@@ -3,7 +3,8 @@
3
3
  import type { StorageConfig } from "../config/config";
4
4
  import { StorageObject } from "../data/storageObject";
5
5
  import { type StorageDatabase } from "../data/tables";
6
- import type { ObjectStore, UploadedPart } from "../object/store";
6
+ import type { ObjectStore } from "../object/store";
7
+ import type { UploadedPart } from "../object/uploadedPart";
7
8
  import type { CompleteUploadInput, CopyObjectInput, CreateShareInput, CreateUploadInput, ListObjectsQuery, UpdateObjectInput } from "./schemas";
8
9
  /**
9
10
  * The storage request handlers — pure functions over injected dependencies, so every branch is tested
@@ -11,7 +12,7 @@ import type { CompleteUploadInput, CopyObjectInput, CreateShareInput, CreateUplo
11
12
  * these dependencies from the request env and maps their results onto responses.
12
13
  *
13
14
  * **Request shape is not validated here.** Each route declares its own schemas with
14
- * `zValidator(target, Schema, validationHook)` and hands the handler the already-parsed value, so a
15
+ * `validate(target, Schema)` and hands the handler the already-parsed value, so a
15
16
  * malformed request is refused before a dependency is resolved or a row is read. What survives in
16
17
  * these handlers is everything a request schema cannot express — ownership, quota, upload state —
17
18
  * which is the whole of what they were ever really about.
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/http/handlers.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAA+C,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAUnG,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEjE,OAAO,KAAK,EACV,mBAAmB,EACnB,eAAe,EACf,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,WAAW,CAAC;AAE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AQG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,iBAAiB,CAAC,CA8ClH;AAED;;;;;;;GAOG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,IAAI,CAAA;CAAE,CAAC,CAOxG;AAED,gDAAgD;AAChD,wBAAsB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAe5G;AAED;;;;;;GAMG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,IAAI,CAAA;CAAE,CAAC,CAe/G;AAED;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAc3F"}
@@ -0,0 +1,167 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * What the storage routes return as JSON, as Zod objects a client can validate against and the OpenAPI
6
+ * contract can describe. The byte-serving routes (`GET` and `HEAD /storage/:id`, `GET /s/:token`) answer
7
+ * with the object itself rather than JSON, and `routes.ts` describes those inline.
8
+ *
9
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. These describe JSON on
10
+ * the wire, so a date is the ISO-8601 string `c.json` writes, and nothing here carries a codec or a
11
+ * transform: parsing a response hands back exactly what went in, which is what lets
12
+ * `routes.workers.test.ts` parse a real answer and compare it with the original.
13
+ *
14
+ * **A field added here later is `.optional()` as well as `.nullable()`.** A client generated from the
15
+ * contract reads Workers on older releases too, and a required key they cannot send fails it outright.
16
+ */
17
+ /** A stored file as a client sees it. The object key and the R2 upload id never appear. */
18
+ export declare const StorageObjectResponse: z.ZodObject<{
19
+ id: z.ZodString;
20
+ path: z.ZodString;
21
+ ownerId: z.ZodNullable<z.ZodString>;
22
+ contentType: z.ZodString;
23
+ size: z.ZodNullable<z.ZodNumber>;
24
+ visibility: z.ZodEnum<{
25
+ private: "private";
26
+ public: "public";
27
+ }>;
28
+ checksum: z.ZodNullable<z.ZodString>;
29
+ status: z.ZodEnum<{
30
+ failed: "failed";
31
+ pending: "pending";
32
+ stored: "stored";
33
+ }>;
34
+ createdAt: z.ZodISODateTime;
35
+ updatedAt: z.ZodISODateTime;
36
+ }, z.core.$strip>;
37
+ export type StorageObjectResponse = z.infer<typeof StorageObjectResponse>;
38
+ /** One part of a multipart upload, with the URL its bytes go to. */
39
+ export declare const UploadPartTargetResponse: z.ZodObject<{
40
+ partNumber: z.ZodNumber;
41
+ offset: z.ZodNumber;
42
+ length: z.ZodNumber;
43
+ url: z.ZodString;
44
+ }, z.core.$strip>;
45
+ export type UploadPartTargetResponse = z.infer<typeof UploadPartTargetResponse>;
46
+ /** Where the bytes go: one URL, or one per part. */
47
+ export declare const UploadTargetResponse: z.ZodDiscriminatedUnion<[z.ZodObject<{
48
+ kind: z.ZodLiteral<"single">;
49
+ url: z.ZodString;
50
+ }, z.core.$strip>, z.ZodObject<{
51
+ kind: z.ZodLiteral<"multipart">;
52
+ uploadId: z.ZodString;
53
+ partSize: z.ZodNumber;
54
+ parts: z.ZodArray<z.ZodObject<{
55
+ partNumber: z.ZodNumber;
56
+ offset: z.ZodNumber;
57
+ length: z.ZodNumber;
58
+ url: z.ZodString;
59
+ }, z.core.$strip>>;
60
+ }, z.core.$strip>], "kind">;
61
+ export type UploadTargetResponse = z.infer<typeof UploadTargetResponse>;
62
+ /** What starting an upload returns. */
63
+ export declare const UploadInitResponse: z.ZodObject<{
64
+ object: z.ZodObject<{
65
+ id: z.ZodString;
66
+ path: z.ZodString;
67
+ ownerId: z.ZodNullable<z.ZodString>;
68
+ contentType: z.ZodString;
69
+ size: z.ZodNullable<z.ZodNumber>;
70
+ visibility: z.ZodEnum<{
71
+ private: "private";
72
+ public: "public";
73
+ }>;
74
+ checksum: z.ZodNullable<z.ZodString>;
75
+ status: z.ZodEnum<{
76
+ failed: "failed";
77
+ pending: "pending";
78
+ stored: "stored";
79
+ }>;
80
+ createdAt: z.ZodISODateTime;
81
+ updatedAt: z.ZodISODateTime;
82
+ }, z.core.$strip>;
83
+ upload: z.ZodDiscriminatedUnion<[z.ZodObject<{
84
+ kind: z.ZodLiteral<"single">;
85
+ url: z.ZodString;
86
+ }, z.core.$strip>, z.ZodObject<{
87
+ kind: z.ZodLiteral<"multipart">;
88
+ uploadId: z.ZodString;
89
+ partSize: z.ZodNumber;
90
+ parts: z.ZodArray<z.ZodObject<{
91
+ partNumber: z.ZodNumber;
92
+ offset: z.ZodNumber;
93
+ length: z.ZodNumber;
94
+ url: z.ZodString;
95
+ }, z.core.$strip>>;
96
+ }, z.core.$strip>], "kind">;
97
+ }, z.core.$strip>;
98
+ export type UploadInitResponse = z.infer<typeof UploadInitResponse>;
99
+ /** One page of the caller's files. */
100
+ export declare const ObjectListResponse: z.ZodObject<{
101
+ objects: z.ZodArray<z.ZodObject<{
102
+ id: z.ZodString;
103
+ path: z.ZodString;
104
+ ownerId: z.ZodNullable<z.ZodString>;
105
+ contentType: z.ZodString;
106
+ size: z.ZodNullable<z.ZodNumber>;
107
+ visibility: z.ZodEnum<{
108
+ private: "private";
109
+ public: "public";
110
+ }>;
111
+ checksum: z.ZodNullable<z.ZodString>;
112
+ status: z.ZodEnum<{
113
+ failed: "failed";
114
+ pending: "pending";
115
+ stored: "stored";
116
+ }>;
117
+ createdAt: z.ZodISODateTime;
118
+ updatedAt: z.ZodISODateTime;
119
+ }, z.core.$strip>>;
120
+ cursor: z.ZodOptional<z.ZodString>;
121
+ }, z.core.$strip>;
122
+ export type ObjectListResponse = z.infer<typeof ObjectListResponse>;
123
+ /** Where a resuming client stands. */
124
+ export declare const UploadPartsResponse: z.ZodObject<{
125
+ uploadId: z.ZodString;
126
+ partSize: z.ZodNumber;
127
+ partCount: z.ZodNumber;
128
+ uploaded: z.ZodArray<z.ZodObject<{
129
+ partNumber: z.ZodNumber;
130
+ etag: z.ZodString;
131
+ size: z.ZodNumber;
132
+ }, z.core.$strip>>;
133
+ missing: z.ZodArray<z.ZodObject<{
134
+ partNumber: z.ZodNumber;
135
+ offset: z.ZodNumber;
136
+ length: z.ZodNumber;
137
+ url: z.ZodString;
138
+ }, z.core.$strip>>;
139
+ }, z.core.$strip>;
140
+ export type UploadPartsResponse = z.infer<typeof UploadPartsResponse>;
141
+ /** A presigned direct-download URL. */
142
+ export declare const PresignedUrlResponse: z.ZodObject<{
143
+ url: z.ZodString;
144
+ expiresInSeconds: z.ZodNumber;
145
+ }, z.core.$strip>;
146
+ export type PresignedUrlResponse = z.infer<typeof PresignedUrlResponse>;
147
+ /** What deleting a file returns. */
148
+ export declare const ObjectDeletedResponse: z.ZodObject<{
149
+ id: z.ZodString;
150
+ deleted: z.ZodLiteral<true>;
151
+ }, z.core.$strip>;
152
+ export type ObjectDeletedResponse = z.infer<typeof ObjectDeletedResponse>;
153
+ /** A minted share link. */
154
+ export declare const ShareResponse: z.ZodObject<{
155
+ token: z.ZodString;
156
+ objectId: z.ZodString;
157
+ expiresAt: z.ZodNullable<z.ZodISODateTime>;
158
+ createdAt: z.ZodISODateTime;
159
+ }, z.core.$strip>;
160
+ export type ShareResponse = z.infer<typeof ShareResponse>;
161
+ /** What revoking a share link returns. */
162
+ export declare const ShareRevokedResponse: z.ZodObject<{
163
+ token: z.ZodString;
164
+ revokedAt: z.ZodISODateTime;
165
+ }, z.core.$strip>;
166
+ export type ShareRevokedResponse = z.infer<typeof ShareRevokedResponse>;
167
+ //# sourceMappingURL=responses.d.ts.map
@@ -0,0 +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O,oBAAoB,CAAC,CAAC;AAExE,oCAAoC;AACpC,eAAO,MAAM,qBAAqB;;;iBAKE,CAAC;AACrC,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE1E,2BAA2B;AAC3B,eAAO,MAAM,aAAa;;;;;iBAYyB,CAAC;AACpD,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AAE1D,0CAA0C;AAC1C,eAAO,MAAM,oBAAoB;;;iBAKS,CAAC;AAC3C,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
@@ -0,0 +1,91 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { StorageObjectStatus, StorageVisibility } from "../data/storageObject.js";
4
+ import { UploadedPart } from "../object/uploadedPart.js";
5
+ import { z } from "zod";
6
+ //#region src/http/responses.ts
7
+ /**
8
+ * What the storage routes return as JSON, as Zod objects a client can validate against and the OpenAPI
9
+ * contract can describe. The byte-serving routes (`GET` and `HEAD /storage/:id`, `GET /s/:token`) answer
10
+ * with the object itself rather than JSON, and `routes.ts` describes those inline.
11
+ *
12
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. These describe JSON on
13
+ * the wire, so a date is the ISO-8601 string `c.json` writes, and nothing here carries a codec or a
14
+ * transform: parsing a response hands back exactly what went in, which is what lets
15
+ * `routes.workers.test.ts` parse a real answer and compare it with the original.
16
+ *
17
+ * **A field added here later is `.optional()` as well as `.nullable()`.** A client generated from the
18
+ * contract reads Workers on older releases too, and a required key they cannot send fails it outright.
19
+ */
20
+ /** A stored file as a client sees it. The object key and the R2 upload id never appear. */
21
+ const StorageObjectResponse = z.object({
22
+ id: z.string().describe("The file's id. What every other route takes as `:id`."),
23
+ path: z.string().describe("The file's logical path, as the owner named it. Never an R2 key."),
24
+ ownerId: z.string().nullable().describe("The id of the user who owns the file, or null for a system-owned file."),
25
+ contentType: z.string().describe("The file's MIME type: as declared at upload, replaced at completion by the type R2 stored."),
26
+ size: z.number().int().nullable().describe("The file's size in bytes: as declared at upload, replaced at completion by what R2 stored."),
27
+ visibility: StorageVisibility,
28
+ checksum: z.string().nullable().describe("Lowercase hex SHA-256 the client reported at completion, or R2's own when it reported none. Null until stored."),
29
+ status: StorageObjectStatus,
30
+ createdAt: z.iso.datetime().describe("When the upload was started, ISO-8601."),
31
+ updatedAt: z.iso.datetime().describe("When the record last changed, ISO-8601.")
32
+ }).describe("One stored file, without its object key or upload id.");
33
+ /** One part of a multipart upload, with the URL its bytes go to. */
34
+ const UploadPartTargetResponse = z.object({
35
+ partNumber: z.number().int().describe("The part's 1-based index within the upload."),
36
+ offset: z.number().int().describe("Where the part starts in the file, in bytes from 0."),
37
+ length: z.number().int().describe("How many bytes the part carries."),
38
+ url: z.string().describe("The presigned URL to PUT exactly these bytes to. Valid for an hour.")
39
+ }).describe("One part of a multipart upload and where to send it.");
40
+ /** Where the bytes go: one URL, or one per part. */
41
+ const UploadTargetResponse = z.discriminatedUnion("kind", [z.object({
42
+ kind: z.literal("single").describe("One PUT carries the whole file."),
43
+ url: z.string().describe("The presigned URL to PUT the whole file to. It signs the declared size.")
44
+ }).describe("A single-PUT upload."), z.object({
45
+ kind: z.literal("multipart").describe("The file goes up in parts, each to its own URL."),
46
+ uploadId: z.string().describe("R2's id for the multipart upload."),
47
+ partSize: z.number().int().describe("The size of every part but the last, in bytes."),
48
+ parts: z.array(UploadPartTargetResponse).describe("Every part, in order, each with its own URL.")
49
+ }).describe("A multipart upload, used once the file is past the configured threshold.")]).describe("Where to send the file's bytes.");
50
+ /** What starting an upload returns. */
51
+ const UploadInitResponse = z.object({
52
+ object: StorageObjectResponse,
53
+ upload: UploadTargetResponse
54
+ }).describe("The upload was started: the pending file's record, and where its bytes go.");
55
+ /** One page of the caller's files. */
56
+ const ObjectListResponse = z.object({
57
+ objects: z.array(StorageObjectResponse).describe("The caller's files on this page, ordered by logical path."),
58
+ cursor: z.string().optional().describe("Pass this back as `cursor` to read the next page. Absent on the last page.")
59
+ }).describe("One page of the caller's files.");
60
+ /** Where a resuming client stands. */
61
+ const UploadPartsResponse = z.object({
62
+ uploadId: z.string().describe("R2's id for the multipart upload."),
63
+ partSize: z.number().int().describe("The size of every part but the last, in bytes."),
64
+ partCount: z.number().int().describe("How many parts the upload has in all."),
65
+ uploaded: z.array(UploadedPart).describe("The parts R2 already holds. Do not send these again."),
66
+ missing: z.array(UploadPartTargetResponse).describe("The parts still to send, each with a freshly presigned URL.")
67
+ }).describe("A multipart upload's progress: what R2 holds, and a live URL for every part it does not.");
68
+ /** A presigned direct-download URL. */
69
+ const PresignedUrlResponse = z.object({
70
+ url: z.string().describe("A presigned GET for the file's bytes. Anyone holding it can read them until it lapses."),
71
+ expiresInSeconds: z.number().int().describe("How long the URL works, in seconds from now.")
72
+ }).describe("A short-lived direct-download URL that bypasses the Worker.");
73
+ /** What deleting a file returns. */
74
+ const ObjectDeletedResponse = z.object({
75
+ id: z.string().describe("The id of the file that was deleted."),
76
+ deleted: z.literal(true).describe("Always true: the file, its record and its share links are gone.")
77
+ }).describe("The file was deleted.");
78
+ /** A minted share link. */
79
+ const ShareResponse = z.object({
80
+ token: z.string().describe("The share token. The link is the share path followed by this, and it is the credential."),
81
+ objectId: z.string().describe("The id of the file the link reads."),
82
+ expiresAt: z.iso.datetime().nullable().describe("When the link stops working, ISO-8601, or null when it never expires."),
83
+ createdAt: z.iso.datetime().describe("When the link was minted, ISO-8601.")
84
+ }).describe("A revocable share link for one file.");
85
+ /** What revoking a share link returns. */
86
+ const ShareRevokedResponse = z.object({
87
+ token: z.string().describe("The share token that was revoked."),
88
+ revokedAt: z.iso.datetime().describe("When the link was first revoked, ISO-8601. Revoking again keeps this time.")
89
+ }).describe("The share link was revoked.");
90
+ //#endregion
91
+ export { ObjectDeletedResponse, ObjectListResponse, PresignedUrlResponse, ShareResponse, ShareRevokedResponse, StorageObjectResponse, UploadInitResponse, UploadPartTargetResponse, UploadPartsResponse, UploadTargetResponse };
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAKtD,OAAO,EAML,KAAK,WAAW,EASjB,MAAM,YAAY,CAAC;AAqBpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,MAAM,WAAW,oBAAoB;IACnC,mCAAmC;IACnC,MAAM,EAAE,aAAa,CAAC;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qGAAqG;IACrG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;CAClE;AAuDD,mFAAmF;AACnF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,oBAAoB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAiJtG"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAKtD,OAAO,EAML,KAAK,WAAW,EASjB,MAAM,YAAY,CAAC;AA+BpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,MAAM,WAAW,oBAAoB;IACnC,mCAAmC;IACnC,MAAM,EAAE,aAAa,CAAC;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,qGAAqG;IACrG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;CAClE;AAqED,mFAAmF;AACnF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,oBAAoB,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAyQtG"}
@@ -5,11 +5,12 @@ import { STORAGE_R2_SECRET } from "../secret/registry.js";
5
5
  import { objectStore } from "../object/store.js";
6
6
  import { requireAuth } from "./guard.js";
7
7
  import { abortUpload, completeUpload, copyObject, createShare, deleteObject, initUpload, listObjects, listUploadParts, presignObject, readableObject, resolveShare, revokeShare, updateObject } from "./handlers.js";
8
+ import { ObjectDeletedResponse, ObjectListResponse, PresignedUrlResponse, ShareResponse, ShareRevokedResponse, StorageObjectResponse, UploadInitResponse, UploadPartsResponse } from "./responses.js";
8
9
  import { CompleteUploadInput, CopyObjectInput, CreateShareInput, CreateUploadInput, ListObjectsQuery, ObjectIdParam, ObjectReadQuery, ShareTokenParam, UpdateObjectInput } from "./schemas.js";
9
10
  import { parseConditions, parseRangeHeader, rangeNotSatisfiable, serveMetadata, serveObject, toObjectRange } from "./serve.js";
10
11
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
11
- import { zValidator } from "@hono/zod-validator";
12
- import { validationHook } from "@pithy-sh/core/src/http/validation";
12
+ import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
13
+ import { validate } from "@pithy-sh/core/src/http/validation";
13
14
  //#region src/http/routes.ts
14
15
  /**
15
16
  * Read one binding, or fail with a message naming the binding and how to add it. A `?.` here would
@@ -51,6 +52,20 @@ function shareToken() {
51
52
  const binary = String.fromCharCode(...bytes);
52
53
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53
54
  }
55
+ /** `requireAuth()` lets either a bearer token or a session through. */
56
+ const AUTHENTICATED = ["bearer", "session"];
57
+ /** What a byte read can answer: the whole file, the range asked for, or nothing new since the caller's copy. */
58
+ const BYTE_RESPONSES = {
59
+ 200: {
60
+ description: "The whole file. Served as its stored type, or as `application/octet-stream` when none was stored or the stored one could run in a browser.",
61
+ contentType: "application/octet-stream"
62
+ },
63
+ 206: {
64
+ description: "The byte range the `Range` header asked for.",
65
+ contentType: "application/octet-stream"
66
+ },
67
+ 304: { description: "The caller's copy matches `If-None-Match`. No body." }
68
+ };
54
69
  /** Register the storage sub-router. Returned as the capability's `routes` hook. */
55
70
  function registerStorageRoutes(options) {
56
71
  const base = options.basePath ?? "/storage";
@@ -75,39 +90,94 @@ function registerStorageRoutes(options) {
75
90
  });
76
91
  };
77
92
  return (app) => {
78
- app.post(base, requireAuth(), zValidator("json", CreateUploadInput, validationHook), async (c) => {
93
+ app.post(base, describeRoute({
94
+ summary: "Start an upload.",
95
+ description: "Reserves the file and its quota, then answers with the presigned URL, or one URL per part, to PUT the bytes to. The bytes never pass through the Worker.",
96
+ verification: AUTHENTICATED,
97
+ responses: { 201: UploadInitResponse }
98
+ }), requireAuth(), validate("json", CreateUploadInput), async (c) => {
79
99
  return c.json(await initUpload(await resolve(c), c.req.valid("json")), 201);
80
100
  });
81
- app.get(base, requireAuth(), zValidator("query", ListObjectsQuery, validationHook), async (c) => {
101
+ app.get(base, describeRoute({
102
+ summary: "List the caller's files.",
103
+ verification: AUTHENTICATED,
104
+ responses: { 200: ObjectListResponse }
105
+ }), requireAuth(), validate("query", ListObjectsQuery), async (c) => {
82
106
  return c.json(await listObjects(await resolve(c), c.req.valid("query")));
83
107
  });
84
- app.delete(`${base}/shares/:token`, requireAuth(), zValidator("param", ShareTokenParam, validationHook), async (c) => {
108
+ app.delete(`${base}/shares/:token`, describeRoute({
109
+ summary: "Revoke a share link.",
110
+ description: "Takes effect on the next fetch. Revoking twice is a no-op that keeps the first time.",
111
+ verification: AUTHENTICATED,
112
+ responses: { 200: ShareRevokedResponse }
113
+ }), requireAuth(), validate("param", ShareTokenParam), async (c) => {
85
114
  return c.json(await revokeShare(await resolve(c), c.req.valid("param").token));
86
115
  });
87
- app.post(`${base}/:id/complete`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), zValidator("json", CompleteUploadInput, validationHook), async (c) => {
116
+ app.post(`${base}/:id/complete`, describeRoute({
117
+ summary: "Finish an upload.",
118
+ description: "Assembles a multipart upload, then confirms the bytes against R2. Completing a stored file again answers with it unchanged.",
119
+ verification: AUTHENTICATED,
120
+ responses: { 200: StorageObjectResponse }
121
+ }), requireAuth(), validate("param", ObjectIdParam), validate("json", CompleteUploadInput), async (c) => {
88
122
  return c.json(await completeUpload(await resolve(c), c.req.valid("param").id, c.req.valid("json")));
89
123
  });
90
- app.post(`${base}/:id/abort`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
124
+ app.post(`${base}/:id/abort`, describeRoute({
125
+ summary: "Abandon an upload.",
126
+ description: "Discards whatever R2 holds for the upload. The record stays, marked failed.",
127
+ verification: AUTHENTICATED,
128
+ responses: { 200: StorageObjectResponse }
129
+ }), requireAuth(), validate("param", ObjectIdParam), async (c) => {
91
130
  return c.json(await abortUpload(await resolve(c), c.req.valid("param").id));
92
131
  });
93
- app.get(`${base}/:id/parts`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
132
+ app.get(`${base}/:id/parts`, describeRoute({
133
+ summary: "Resume a multipart upload.",
134
+ verification: AUTHENTICATED,
135
+ responses: { 200: UploadPartsResponse }
136
+ }), requireAuth(), validate("param", ObjectIdParam), async (c) => {
94
137
  return c.json(await listUploadParts(await resolve(c), c.req.valid("param").id));
95
138
  });
96
- app.post(`${base}/:id/copy`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), zValidator("json", CopyObjectInput, validationHook), async (c) => {
139
+ app.post(`${base}/:id/copy`, describeRoute({
140
+ summary: "Copy a file.",
141
+ description: "R2 copies the bytes. The copy is a new private file with its own id.",
142
+ verification: AUTHENTICATED,
143
+ responses: { 201: StorageObjectResponse }
144
+ }), requireAuth(), validate("param", ObjectIdParam), validate("json", CopyObjectInput), async (c) => {
97
145
  return c.json(await copyObject(await resolve(c), c.req.valid("param").id, c.req.valid("json")), 201);
98
146
  });
99
- app.post(`${base}/:id/shares`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), zValidator("json", CreateShareInput, validationHook), async (c) => {
147
+ app.post(`${base}/:id/shares`, describeRoute({
148
+ summary: "Mint a share link.",
149
+ verification: AUTHENTICATED,
150
+ responses: { 201: ShareResponse }
151
+ }), requireAuth(), validate("param", ObjectIdParam), validate("json", CreateShareInput), async (c) => {
100
152
  return c.json(await createShare(await resolve(c), c.req.valid("param").id, c.req.valid("json")), 201);
101
153
  });
102
- app.get(`${base}/:id/url`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
154
+ app.get(`${base}/:id/url`, describeRoute({
155
+ summary: "Mint a direct download URL.",
156
+ description: "For a public file or one the caller owns. The URL cannot be revoked, so it lapses in five minutes.",
157
+ verification: AUTHENTICATED,
158
+ responses: { 200: PresignedUrlResponse }
159
+ }), requireAuth(), validate("param", ObjectIdParam), async (c) => {
103
160
  return c.json(await presignObject(await resolve(c), c.req.valid("param").id));
104
161
  });
105
- app.get(`${base}/:id`, zValidator("param", ObjectIdParam, validationHook), zValidator("query", ObjectReadQuery, validationHook), async (c) => {
162
+ app.get(`${base}/:id`, describeRoute({
163
+ summary: "Read a file's bytes.",
164
+ description: "Public files need no credential. A private file needs the owner's bearer token or session, and reads as missing to anyone else. Honors `Range` and `If-None-Match`.",
165
+ verification: [
166
+ "public",
167
+ "bearer",
168
+ "session"
169
+ ],
170
+ responses: BYTE_RESPONSES
171
+ }), validate("param", ObjectIdParam), validate("query", ObjectReadQuery), async (c) => {
106
172
  const deps = await resolve(c);
107
173
  const object = await readableObject(deps, c.req.valid("param").id);
108
174
  return stream(c, deps, object, c.req.valid("query").download === "1");
109
175
  });
110
- app.on("HEAD", `${base}/:id`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
176
+ app.on("HEAD", `${base}/:id`, describeRoute({
177
+ summary: "Read a file's headers without its bytes.",
178
+ verification: AUTHENTICATED,
179
+ responses: { 200: { description: "The headers a GET would carry, with no body." } }
180
+ }), requireAuth(), validate("param", ObjectIdParam), async (c) => {
111
181
  const deps = await resolve(c);
112
182
  const object = await readableObject(deps, c.req.valid("param").id);
113
183
  const metadata = await deps.store.head(object.key);
@@ -118,13 +188,27 @@ function registerStorageRoutes(options) {
118
188
  visibility: object.visibility
119
189
  });
120
190
  });
121
- app.patch(`${base}/:id`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), zValidator("json", UpdateObjectInput, validationHook), async (c) => {
191
+ app.patch(`${base}/:id`, describeRoute({
192
+ summary: "Rename a file or change who may read it.",
193
+ verification: AUTHENTICATED,
194
+ responses: { 200: StorageObjectResponse }
195
+ }), requireAuth(), validate("param", ObjectIdParam), validate("json", UpdateObjectInput), async (c) => {
122
196
  return c.json(await updateObject(await resolve(c), c.req.valid("param").id, c.req.valid("json")));
123
197
  });
124
- app.delete(`${base}/:id`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
198
+ app.delete(`${base}/:id`, describeRoute({
199
+ summary: "Delete a file.",
200
+ description: "Its share links go with it.",
201
+ verification: AUTHENTICATED,
202
+ responses: { 200: ObjectDeletedResponse }
203
+ }), requireAuth(), validate("param", ObjectIdParam), async (c) => {
125
204
  return c.json(await deleteObject(await resolve(c), c.req.valid("param").id));
126
205
  });
127
- app.get(`${share}/:token`, zValidator("param", ShareTokenParam, validationHook), zValidator("query", ObjectReadQuery, validationHook), async (c) => {
206
+ app.get(`${share}/:token`, describeRoute({
207
+ summary: "Read a file through a share link.",
208
+ description: "The token is the credential. A revoked or expired link answers 410. Honors `Range` and `If-None-Match`.",
209
+ verification: "public",
210
+ responses: BYTE_RESPONSES
211
+ }), validate("param", ShareTokenParam), validate("query", ObjectReadQuery), async (c) => {
128
212
  const deps = await resolve(c);
129
213
  const object = await resolveShare(deps, c.req.valid("param").token);
130
214
  return stream(c, deps, object, c.req.valid("query").download === "1");
@@ -8,7 +8,7 @@ import { z } from "zod";
8
8
  /**
9
9
  * The request schemas for the storage routes. Every path parameter, query string and body is parsed
10
10
  * here before a handler sees it (CLAUDE.md §Zod: validate at every boundary), declared on the route
11
- * line with `zValidator(target, Schema, validationHook)` — so reading `routes.ts` tells you what a
11
+ * line with `validate(target, Schema)` — so reading `routes.ts` tells you what a
12
12
  * route accepts without opening a handler. A failure maps to `validation/invalid_input` through
13
13
  * `fromZodError`.
14
14
  *
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { CloudflareR2Manager } from "@pithy-sh/cloudflare/src/r2/r2Manager";
4
4
  import type { R2StorageCredentials } from "../secret/registry";
5
- import { type PresignedObjects } from "./store";
5
+ import type { PresignedObjects } from "./store";
6
6
  /**
7
7
  * The SDK-friction boundary: the one file in this package that touches `@pithy-sh/cloudflare`.
8
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../../src/object/cloudflare.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAC;AAC5E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,KAAK,gBAAgB,EAAgB,MAAM,SAAS,CAAC;AAE9D;;;;;;;;;GASG;AAEH,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,gBAAgB,CAmBxE;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,oBAAoB,GAAG,gBAAgB,CAU/E"}
1
+ {"version":3,"file":"cloudflare.d.ts","sourceRoot":"","sources":["../../src/object/cloudflare.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAAE,MAAM,uCAAuC,CAAC;AAC5E,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAGhD;;;;;;;;;GASG;AAEH,gFAAgF;AAChF,wBAAgB,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,gBAAgB,CAmBxE;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,WAAW,EAAE,oBAAoB,GAAG,gBAAgB,CAU/E"}
@@ -1,6 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { UploadedPart } from "./store.js";
3
+ import { UploadedPart } from "./uploadedPart.js";
4
4
  import { CloudflareR2Manager } from "@pithy-sh/cloudflare/src/r2/r2Manager";
5
5
  //#region src/object/cloudflare.ts
6
6
  /**
@@ -5,6 +5,8 @@ import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
5
5
  import { z } from "zod";
6
6
  import { type R2StorageCredentials } from "../secret/registry";
7
7
  import type { ReportedPart } from "./multipart";
8
+ import type { UploadedPart } from "./uploadedPart";
9
+ export { UploadedPart } from "./uploadedPart";
8
10
  /**
9
11
  * `ObjectStore` — the object-plane seam, and the one piece of this package that is reusable outside it.
10
12
  *
@@ -68,13 +70,6 @@ export declare const ObjectListing: z.ZodObject<{
68
70
  cursor: z.ZodOptional<z.ZodString>;
69
71
  }, z.core.$strip>;
70
72
  export type ObjectListing = z.output<typeof ObjectListing>;
71
- /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
72
- export declare const UploadedPart: z.ZodObject<{
73
- partNumber: z.ZodNumber;
74
- etag: z.ZodString;
75
- size: z.ZodNumber;
76
- }, z.core.$strip>;
77
- export type UploadedPart = z.output<typeof UploadedPart>;
78
73
  /** How long a presigned URL stays valid. */
79
74
  export interface PresignOptions {
80
75
  /** Lifetime in seconds. Defaults to one hour — long enough for a large part, short enough to leak little. */
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/object/store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,QAAQ,EAAoC,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC5G,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE1E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,KAAK,oBAAoB,EAA4C,MAAM,oBAAoB,CAAC;AAEzG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,kEAAkE;AAClE,eAAO,MAAM,cAAc;;;;;;;;iBA2BwE,CAAC;AACpG,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,uGAAuG;AACvG,eAAO,MAAM,WAAW;;;;iBAMoD,CAAC;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAEvD,uGAAuG;AACvG,eAAO,MAAM,gBAAgB;;;;;iBAiBkE,CAAC;AAChG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE,mGAAmG;AACnG,eAAO,MAAM,aAAa;;;;;;;;;;;iBAS+E,CAAC;AAC1G,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAE3D,sGAAsG;AACtG,eAAO,MAAM,YAAY;;;;iBAMqD,CAAC;AAC/E,MAAM,MAAM,YAAY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KAAK,gBAAgB,CAAC;CACrE;AA8BD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CA6FpE"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { r2CredentialsRegistry } from "../secret/registry.js";
4
+ import { UploadedPart } from "./uploadedPart.js";
4
5
  import { r2Presigned } from "./cloudflare.js";
5
6
  import { z } from "zod";
6
7
  import { sharedSecretsStore } from "@pithy-sh/secrets/src/sharedSecretsStore";
@@ -56,12 +57,6 @@ const ObjectListing = z.object({
56
57
  objects: z.array(ObjectMetadata).describe("This page's objects, in R2's lexicographic key order."),
57
58
  cursor: z.string().min(1).optional().describe("Continuation cursor for the next page. Absent means this page was the last.")
58
59
  }).describe("One page of a bucket listing. Pagination is caller-driven — pass `cursor` back to advance.");
59
- /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
60
- const UploadedPart = z.object({
61
- partNumber: z.number().int().min(1).describe("The part's 1-based index within the upload."),
62
- etag: z.string().min(1).describe("The part's entity tag, verbatim. Pass it back unchanged to complete."),
63
- size: z.number().int().nonnegative().describe("The part's size in bytes, as R2 stored it.")
64
- }).describe("One uploaded part — the unit a resumed upload skips re-sending.");
65
60
  /** Map our range shape onto R2's — the binding's union admits exactly one of these three forms. */
66
61
  function toR2Range(range) {
67
62
  if (!range) return void 0;
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
5
+ export declare const UploadedPart: z.ZodObject<{
6
+ partNumber: z.ZodNumber;
7
+ etag: z.ZodString;
8
+ size: z.ZodNumber;
9
+ }, z.core.$strip>;
10
+ export type UploadedPart = z.output<typeof UploadedPart>;
11
+ //# sourceMappingURL=uploadedPart.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uploadedPart.d.ts","sourceRoot":"","sources":["../../src/object/uploadedPart.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAKxB,sGAAsG;AACtG,eAAO,MAAM,YAAY;;;;iBAMqD,CAAC;AAC/E,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC"}
@@ -0,0 +1,12 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ //#region src/object/uploadedPart.ts
5
+ /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
6
+ const UploadedPart = z.object({
7
+ partNumber: z.number().int().min(1).describe("The part's 1-based index within the upload."),
8
+ etag: z.string().min(1).describe("The part's entity tag, verbatim. Pass it back unchanged to complete."),
9
+ size: z.number().int().nonnegative().describe("The part's size in bytes, as R2 stored it.")
10
+ }).describe("One uploaded part — the unit a resumed upload skips re-sending.");
11
+ //#endregion
12
+ export { UploadedPart };
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/storage";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.2.10";
6
+ export declare const PACKAGE_VERSION = "0.3.0";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.generated.d.ts","sourceRoot":"","sources":["../src/version.generated.ts"],"names":[],"mappings":"AAWA,qEAAqE;AACrE,eAAO,MAAM,YAAY,sBAAsB,CAAC;AAEhD,oFAAoF;AACpF,eAAO,MAAM,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"version.generated.d.ts","sourceRoot":"","sources":["../src/version.generated.ts"],"names":[],"mappings":"AAWA,qEAAqE;AACrE,eAAO,MAAM,YAAY,sBAAsB,CAAC;AAEhD,oFAAoF;AACpF,eAAO,MAAM,eAAe,UAAU,CAAC"}
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/storage";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.2.10";
7
+ const PACKAGE_VERSION = "0.3.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/storage",
3
- "version": "0.2.10",
3
+ "version": "0.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -39,15 +39,15 @@
39
39
  "@hono/zod-validator": "^0.9.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "@pithy-sh/cloudflare": "^0.4.2",
43
- "@pithy-sh/core": "^0.9.0",
44
- "@pithy-sh/secrets": "^0.3.2",
42
+ "@pithy-sh/cloudflare": "^0.5.0",
43
+ "@pithy-sh/core": "^0.10.0",
44
+ "@pithy-sh/secrets": "^0.4.0",
45
45
  "hono": "^4.13.2",
46
46
  "kysely": "^0.29.0",
47
47
  "zod": "^4.4.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@cloudflare/vitest-plugin": "^1.0.0",
50
+ "@cloudflare/vitest-plugin": "^1.4.2",
51
51
  "@pithy-sh/cloudflare": "workspace:*",
52
52
  "@pithy-sh/core": "workspace:*",
53
53
  "@pithy-sh/secrets": "workspace:*",
@@ -60,7 +60,7 @@
60
60
  "tsdown": "^0.23.0",
61
61
  "typescript": "^7.0.2",
62
62
  "vitest": "^4.1.0",
63
- "wrangler": "^4.115.0",
63
+ "wrangler": "^4.151.0",
64
64
  "zod": "^4.4.0"
65
65
  }
66
66
  }
@@ -14,7 +14,8 @@ import {
14
14
  } from "../error/errors";
15
15
  import { deriveObjectKey } from "../object/key";
16
16
  import { collectParts, needsMultipart, planMultipart } from "../object/multipart";
17
- import type { ObjectStore, UploadedPart } from "../object/store";
17
+ import type { ObjectStore } from "../object/store";
18
+ import type { UploadedPart } from "../object/uploadedPart";
18
19
  import { assertWithinQuota, insertReservingQuota, updateSettlingQuota } from "../quota/quota";
19
20
  import type {
20
21
  CompleteUploadInput,
@@ -31,7 +32,7 @@ import type {
31
32
  * these dependencies from the request env and maps their results onto responses.
32
33
  *
33
34
  * **Request shape is not validated here.** Each route declares its own schemas with
34
- * `zValidator(target, Schema, validationHook)` and hands the handler the already-parsed value, so a
35
+ * `validate(target, Schema)` and hands the handler the already-parsed value, so a
35
36
  * malformed request is refused before a dependency is resolved or a row is read. What survives in
36
37
  * these handlers is everything a request schema cannot express — ownership, quota, upload state —
37
38
  * which is the whole of what they were ever really about.
@@ -0,0 +1,156 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import { StorageObjectStatus, StorageVisibility } from "../data/storageObject";
6
+ import { UploadedPart } from "../object/uploadedPart";
7
+
8
+ /**
9
+ * What the storage routes return as JSON, as Zod objects a client can validate against and the OpenAPI
10
+ * contract can describe. The byte-serving routes (`GET` and `HEAD /storage/:id`, `GET /s/:token`) answer
11
+ * with the object itself rather than JSON, and `routes.ts` describes those inline.
12
+ *
13
+ * `schemas.ts` bounds what a caller may send; this file states what it gets back. These describe JSON on
14
+ * the wire, so a date is the ISO-8601 string `c.json` writes, and nothing here carries a codec or a
15
+ * transform: parsing a response hands back exactly what went in, which is what lets
16
+ * `routes.workers.test.ts` parse a real answer and compare it with the original.
17
+ *
18
+ * **A field added here later is `.optional()` as well as `.nullable()`.** A client generated from the
19
+ * contract reads Workers on older releases too, and a required key they cannot send fails it outright.
20
+ */
21
+
22
+ /** A stored file as a client sees it. The object key and the R2 upload id never appear. */
23
+ export const StorageObjectResponse = z
24
+ .object({
25
+ id: z.string().describe("The file's id. What every other route takes as `:id`."),
26
+ path: z.string().describe("The file's logical path, as the owner named it. Never an R2 key."),
27
+ ownerId: z.string().nullable().describe("The id of the user who owns the file, or null for a system-owned file."),
28
+ contentType: z
29
+ .string()
30
+ .describe("The file's MIME type: as declared at upload, replaced at completion by the type R2 stored."),
31
+ size: z
32
+ .number()
33
+ .int()
34
+ .nullable()
35
+ .describe("The file's size in bytes: as declared at upload, replaced at completion by what R2 stored."),
36
+ visibility: StorageVisibility,
37
+ checksum: z
38
+ .string()
39
+ .nullable()
40
+ .describe(
41
+ "Lowercase hex SHA-256 the client reported at completion, or R2's own when it reported none. Null until stored.",
42
+ ),
43
+ status: StorageObjectStatus,
44
+ createdAt: z.iso.datetime().describe("When the upload was started, ISO-8601."),
45
+ updatedAt: z.iso.datetime().describe("When the record last changed, ISO-8601."),
46
+ })
47
+ .describe("One stored file, without its object key or upload id.");
48
+ export type StorageObjectResponse = z.infer<typeof StorageObjectResponse>;
49
+
50
+ /** One part of a multipart upload, with the URL its bytes go to. */
51
+ export const UploadPartTargetResponse = z
52
+ .object({
53
+ partNumber: z.number().int().describe("The part's 1-based index within the upload."),
54
+ offset: z.number().int().describe("Where the part starts in the file, in bytes from 0."),
55
+ length: z.number().int().describe("How many bytes the part carries."),
56
+ url: z.string().describe("The presigned URL to PUT exactly these bytes to. Valid for an hour."),
57
+ })
58
+ .describe("One part of a multipart upload and where to send it.");
59
+ export type UploadPartTargetResponse = z.infer<typeof UploadPartTargetResponse>;
60
+
61
+ /** Where the bytes go: one URL, or one per part. */
62
+ export const UploadTargetResponse = z
63
+ .discriminatedUnion("kind", [
64
+ z
65
+ .object({
66
+ kind: z.literal("single").describe("One PUT carries the whole file."),
67
+ url: z.string().describe("The presigned URL to PUT the whole file to. It signs the declared size."),
68
+ })
69
+ .describe("A single-PUT upload."),
70
+ z
71
+ .object({
72
+ kind: z.literal("multipart").describe("The file goes up in parts, each to its own URL."),
73
+ uploadId: z.string().describe("R2's id for the multipart upload."),
74
+ partSize: z.number().int().describe("The size of every part but the last, in bytes."),
75
+ parts: z.array(UploadPartTargetResponse).describe("Every part, in order, each with its own URL."),
76
+ })
77
+ .describe("A multipart upload, used once the file is past the configured threshold."),
78
+ ])
79
+ .describe("Where to send the file's bytes.");
80
+ export type UploadTargetResponse = z.infer<typeof UploadTargetResponse>;
81
+
82
+ /** What starting an upload returns. */
83
+ export const UploadInitResponse = z
84
+ .object({
85
+ object: StorageObjectResponse,
86
+ upload: UploadTargetResponse,
87
+ })
88
+ .describe("The upload was started: the pending file's record, and where its bytes go.");
89
+ export type UploadInitResponse = z.infer<typeof UploadInitResponse>;
90
+
91
+ /** One page of the caller's files. */
92
+ export const ObjectListResponse = z
93
+ .object({
94
+ objects: z.array(StorageObjectResponse).describe("The caller's files on this page, ordered by logical path."),
95
+ cursor: z
96
+ .string()
97
+ .optional()
98
+ .describe("Pass this back as `cursor` to read the next page. Absent on the last page."),
99
+ })
100
+ .describe("One page of the caller's files.");
101
+ export type ObjectListResponse = z.infer<typeof ObjectListResponse>;
102
+
103
+ /** Where a resuming client stands. */
104
+ export const UploadPartsResponse = z
105
+ .object({
106
+ uploadId: z.string().describe("R2's id for the multipart upload."),
107
+ partSize: z.number().int().describe("The size of every part but the last, in bytes."),
108
+ partCount: z.number().int().describe("How many parts the upload has in all."),
109
+ uploaded: z.array(UploadedPart).describe("The parts R2 already holds. Do not send these again."),
110
+ missing: z.array(UploadPartTargetResponse).describe("The parts still to send, each with a freshly presigned URL."),
111
+ })
112
+ .describe("A multipart upload's progress: what R2 holds, and a live URL for every part it does not.");
113
+ export type UploadPartsResponse = z.infer<typeof UploadPartsResponse>;
114
+
115
+ /** A presigned direct-download URL. */
116
+ export const PresignedUrlResponse = z
117
+ .object({
118
+ url: z.string().describe("A presigned GET for the file's bytes. Anyone holding it can read them until it lapses."),
119
+ expiresInSeconds: z.number().int().describe("How long the URL works, in seconds from now."),
120
+ })
121
+ .describe("A short-lived direct-download URL that bypasses the Worker.");
122
+ export type PresignedUrlResponse = z.infer<typeof PresignedUrlResponse>;
123
+
124
+ /** What deleting a file returns. */
125
+ export const ObjectDeletedResponse = z
126
+ .object({
127
+ id: z.string().describe("The id of the file that was deleted."),
128
+ deleted: z.literal(true).describe("Always true: the file, its record and its share links are gone."),
129
+ })
130
+ .describe("The file was deleted.");
131
+ export type ObjectDeletedResponse = z.infer<typeof ObjectDeletedResponse>;
132
+
133
+ /** A minted share link. */
134
+ export const ShareResponse = z
135
+ .object({
136
+ token: z
137
+ .string()
138
+ .describe("The share token. The link is the share path followed by this, and it is the credential."),
139
+ objectId: z.string().describe("The id of the file the link reads."),
140
+ expiresAt: z.iso
141
+ .datetime()
142
+ .nullable()
143
+ .describe("When the link stops working, ISO-8601, or null when it never expires."),
144
+ createdAt: z.iso.datetime().describe("When the link was minted, ISO-8601."),
145
+ })
146
+ .describe("A revocable share link for one file.");
147
+ export type ShareResponse = z.infer<typeof ShareResponse>;
148
+
149
+ /** What revoking a share link returns. */
150
+ export const ShareRevokedResponse = z
151
+ .object({
152
+ token: z.string().describe("The share token that was revoked."),
153
+ revokedAt: z.iso.datetime().describe("When the link was first revoked, ISO-8601. Revoking again keeps this time."),
154
+ })
155
+ .describe("The share link was revoked.");
156
+ export type ShareRevokedResponse = z.infer<typeof ShareRevokedResponse>;
@@ -2,10 +2,11 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database, R2Bucket } from "@cloudflare/workers-types";
5
- import { zValidator } from "@hono/zod-validator";
6
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
7
6
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
8
- import { validationHook } from "@pithy-sh/core/src/http/validation";
7
+ import { describeRoute, type RouteResponse } from "@pithy-sh/core/src/http/routeSpec";
8
+ import { validate } from "@pithy-sh/core/src/http/validation";
9
+ import type { VerificationStrategy } from "@pithy-sh/core/src/http/verification";
9
10
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
10
11
  import type { Context, Hono } from "hono";
11
12
  import type { StorageConfig } from "../config/config";
@@ -29,6 +30,16 @@ import {
29
30
  revokeShare,
30
31
  updateObject,
31
32
  } from "./handlers";
33
+ import {
34
+ ObjectDeletedResponse,
35
+ ObjectListResponse,
36
+ PresignedUrlResponse,
37
+ ShareResponse,
38
+ ShareRevokedResponse,
39
+ StorageObjectResponse,
40
+ UploadInitResponse,
41
+ UploadPartsResponse,
42
+ } from "./responses";
32
43
  import {
33
44
  CompleteUploadInput,
34
45
  CopyObjectInput,
@@ -164,6 +175,20 @@ function shareToken(): string {
164
175
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
165
176
  }
166
177
 
178
+ /** `requireAuth()` lets either a bearer token or a session through. */
179
+ const AUTHENTICATED: readonly VerificationStrategy[] = ["bearer", "session"];
180
+
181
+ /** What a byte read can answer: the whole file, the range asked for, or nothing new since the caller's copy. */
182
+ const BYTE_RESPONSES: Readonly<Record<number, RouteResponse>> = {
183
+ 200: {
184
+ description:
185
+ "The whole file. Served as its stored type, or as `application/octet-stream` when none was stored or the stored one could run in a browser.",
186
+ contentType: "application/octet-stream",
187
+ },
188
+ 206: { description: "The byte range the `Range` header asked for.", contentType: "application/octet-stream" },
189
+ 304: { description: "The caller's copy matches `If-None-Match`. No body." },
190
+ };
191
+
167
192
  /** Register the storage sub-router. Returned as the capability's `routes` hook. */
168
193
  export function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono<PithyHonoEnv>) => void {
169
194
  const base = options.basePath ?? "/storage";
@@ -200,19 +225,47 @@ export function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono
200
225
  };
201
226
 
202
227
  return (app) => {
203
- app.post(base, requireAuth(), zValidator("json", CreateUploadInput, validationHook), async (c) => {
204
- return c.json(await initUpload(await resolve(c), c.req.valid("json")), 201);
205
- });
228
+ app.post(
229
+ base,
230
+ describeRoute({
231
+ summary: "Start an upload.",
232
+ description:
233
+ "Reserves the file and its quota, then answers with the presigned URL, or one URL per part, to PUT the bytes to. The bytes never pass through the Worker.",
234
+ verification: AUTHENTICATED,
235
+ responses: { 201: UploadInitResponse },
236
+ }),
237
+ requireAuth(),
238
+ validate("json", CreateUploadInput),
239
+ async (c) => {
240
+ return c.json(await initUpload(await resolve(c), c.req.valid("json")), 201);
241
+ },
242
+ );
206
243
 
207
- app.get(base, requireAuth(), zValidator("query", ListObjectsQuery, validationHook), async (c) => {
208
- return c.json(await listObjects(await resolve(c), c.req.valid("query")));
209
- });
244
+ app.get(
245
+ base,
246
+ describeRoute({
247
+ summary: "List the caller's files.",
248
+ verification: AUTHENTICATED,
249
+ responses: { 200: ObjectListResponse },
250
+ }),
251
+ requireAuth(),
252
+ validate("query", ListObjectsQuery),
253
+ async (c) => {
254
+ return c.json(await listObjects(await resolve(c), c.req.valid("query")));
255
+ },
256
+ );
210
257
 
211
258
  // Static before `:id` — see the file doc comment.
212
259
  app.delete(
213
260
  `${base}/shares/:token`,
261
+ describeRoute({
262
+ summary: "Revoke a share link.",
263
+ description: "Takes effect on the next fetch. Revoking twice is a no-op that keeps the first time.",
264
+ verification: AUTHENTICATED,
265
+ responses: { 200: ShareRevokedResponse },
266
+ }),
214
267
  requireAuth(),
215
- zValidator("param", ShareTokenParam, validationHook),
268
+ validate("param", ShareTokenParam),
216
269
  async (c) => {
217
270
  return c.json(await revokeShare(await resolve(c), c.req.valid("param").token));
218
271
  },
@@ -220,30 +273,64 @@ export function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono
220
273
 
221
274
  app.post(
222
275
  `${base}/:id/complete`,
276
+ describeRoute({
277
+ summary: "Finish an upload.",
278
+ description:
279
+ "Assembles a multipart upload, then confirms the bytes against R2. Completing a stored file again answers with it unchanged.",
280
+ verification: AUTHENTICATED,
281
+ responses: { 200: StorageObjectResponse },
282
+ }),
223
283
  requireAuth(),
224
- zValidator("param", ObjectIdParam, validationHook),
225
- zValidator("json", CompleteUploadInput, validationHook),
284
+ validate("param", ObjectIdParam),
285
+ validate("json", CompleteUploadInput),
226
286
  async (c) => {
227
287
  return c.json(await completeUpload(await resolve(c), c.req.valid("param").id, c.req.valid("json")));
228
288
  },
229
289
  );
230
290
 
231
291
  // No json validator: this route reads no body, and a client that sends none must keep working.
232
- app.post(`${base}/:id/abort`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
233
- return c.json(await abortUpload(await resolve(c), c.req.valid("param").id));
234
- });
292
+ app.post(
293
+ `${base}/:id/abort`,
294
+ describeRoute({
295
+ summary: "Abandon an upload.",
296
+ description: "Discards whatever R2 holds for the upload. The record stays, marked failed.",
297
+ verification: AUTHENTICATED,
298
+ responses: { 200: StorageObjectResponse },
299
+ }),
300
+ requireAuth(),
301
+ validate("param", ObjectIdParam),
302
+ async (c) => {
303
+ return c.json(await abortUpload(await resolve(c), c.req.valid("param").id));
304
+ },
305
+ );
235
306
 
236
307
  // The resume path: what R2 already holds, and a fresh URL for every part still missing. Minting
237
308
  // on demand is what keeps a part URL's TTL short without making a stalled upload unrecoverable.
238
- app.get(`${base}/:id/parts`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
239
- return c.json(await listUploadParts(await resolve(c), c.req.valid("param").id));
240
- });
309
+ app.get(
310
+ `${base}/:id/parts`,
311
+ describeRoute({
312
+ summary: "Resume a multipart upload.",
313
+ verification: AUTHENTICATED,
314
+ responses: { 200: UploadPartsResponse },
315
+ }),
316
+ requireAuth(),
317
+ validate("param", ObjectIdParam),
318
+ async (c) => {
319
+ return c.json(await listUploadParts(await resolve(c), c.req.valid("param").id));
320
+ },
321
+ );
241
322
 
242
323
  app.post(
243
324
  `${base}/:id/copy`,
325
+ describeRoute({
326
+ summary: "Copy a file.",
327
+ description: "R2 copies the bytes. The copy is a new private file with its own id.",
328
+ verification: AUTHENTICATED,
329
+ responses: { 201: StorageObjectResponse },
330
+ }),
244
331
  requireAuth(),
245
- zValidator("param", ObjectIdParam, validationHook),
246
- zValidator("json", CopyObjectInput, validationHook),
332
+ validate("param", ObjectIdParam),
333
+ validate("json", CopyObjectInput),
247
334
  async (c) => {
248
335
  return c.json(await copyObject(await resolve(c), c.req.valid("param").id, c.req.valid("json")), 201);
249
336
  },
@@ -251,23 +338,47 @@ export function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono
251
338
 
252
339
  app.post(
253
340
  `${base}/:id/shares`,
341
+ describeRoute({
342
+ summary: "Mint a share link.",
343
+ verification: AUTHENTICATED,
344
+ responses: { 201: ShareResponse },
345
+ }),
254
346
  requireAuth(),
255
- zValidator("param", ObjectIdParam, validationHook),
256
- zValidator("json", CreateShareInput, validationHook),
347
+ validate("param", ObjectIdParam),
348
+ validate("json", CreateShareInput),
257
349
  async (c) => {
258
350
  return c.json(await createShare(await resolve(c), c.req.valid("param").id, c.req.valid("json")), 201);
259
351
  },
260
352
  );
261
353
 
262
- app.get(`${base}/:id/url`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
263
- return c.json(await presignObject(await resolve(c), c.req.valid("param").id));
264
- });
354
+ app.get(
355
+ `${base}/:id/url`,
356
+ describeRoute({
357
+ summary: "Mint a direct download URL.",
358
+ description:
359
+ "For a public file or one the caller owns. The URL cannot be revoked, so it lapses in five minutes.",
360
+ verification: AUTHENTICATED,
361
+ responses: { 200: PresignedUrlResponse },
362
+ }),
363
+ requireAuth(),
364
+ validate("param", ObjectIdParam),
365
+ async (c) => {
366
+ return c.json(await presignObject(await resolve(c), c.req.valid("param").id));
367
+ },
368
+ );
265
369
 
266
370
  // No `requireAuth`: a public object must be readable without a session. The handler authorizes.
267
371
  app.get(
268
372
  `${base}/:id`,
269
- zValidator("param", ObjectIdParam, validationHook),
270
- zValidator("query", ObjectReadQuery, validationHook),
373
+ describeRoute({
374
+ summary: "Read a file's bytes.",
375
+ description:
376
+ "Public files need no credential. A private file needs the owner's bearer token or session, and reads as missing to anyone else. Honors `Range` and `If-None-Match`.",
377
+ verification: ["public", "bearer", "session"],
378
+ responses: BYTE_RESPONSES,
379
+ }),
380
+ validate("param", ObjectIdParam),
381
+ validate("query", ObjectReadQuery),
271
382
  async (c) => {
272
383
  const deps = await resolve(c);
273
384
  const object = await readableObject(deps, c.req.valid("param").id);
@@ -275,34 +386,68 @@ export function registerStorageRoutes(options: StorageRoutesOptions): (app: Hono
275
386
  },
276
387
  );
277
388
 
278
- app.on("HEAD", `${base}/:id`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
279
- const deps = await resolve(c);
280
- const object = await readableObject(deps, c.req.valid("param").id);
281
- const metadata = await deps.store.head(object.key);
282
- if (!metadata) return c.notFound();
283
- return serveMetadata({ metadata, path: object.path, visibility: object.visibility });
284
- });
389
+ app.on(
390
+ "HEAD",
391
+ `${base}/:id`,
392
+ describeRoute({
393
+ summary: "Read a file's headers without its bytes.",
394
+ verification: AUTHENTICATED,
395
+ responses: { 200: { description: "The headers a GET would carry, with no body." } },
396
+ }),
397
+ requireAuth(),
398
+ validate("param", ObjectIdParam),
399
+ async (c) => {
400
+ const deps = await resolve(c);
401
+ const object = await readableObject(deps, c.req.valid("param").id);
402
+ const metadata = await deps.store.head(object.key);
403
+ if (!metadata) return c.notFound();
404
+ return serveMetadata({ metadata, path: object.path, visibility: object.visibility });
405
+ },
406
+ );
285
407
 
286
408
  app.patch(
287
409
  `${base}/:id`,
410
+ describeRoute({
411
+ summary: "Rename a file or change who may read it.",
412
+ verification: AUTHENTICATED,
413
+ responses: { 200: StorageObjectResponse },
414
+ }),
288
415
  requireAuth(),
289
- zValidator("param", ObjectIdParam, validationHook),
290
- zValidator("json", UpdateObjectInput, validationHook),
416
+ validate("param", ObjectIdParam),
417
+ validate("json", UpdateObjectInput),
291
418
  async (c) => {
292
419
  return c.json(await updateObject(await resolve(c), c.req.valid("param").id, c.req.valid("json")));
293
420
  },
294
421
  );
295
422
 
296
- app.delete(`${base}/:id`, requireAuth(), zValidator("param", ObjectIdParam, validationHook), async (c) => {
297
- return c.json(await deleteObject(await resolve(c), c.req.valid("param").id));
298
- });
423
+ app.delete(
424
+ `${base}/:id`,
425
+ describeRoute({
426
+ summary: "Delete a file.",
427
+ description: "Its share links go with it.",
428
+ verification: AUTHENTICATED,
429
+ responses: { 200: ObjectDeletedResponse },
430
+ }),
431
+ requireAuth(),
432
+ validate("param", ObjectIdParam),
433
+ async (c) => {
434
+ return c.json(await deleteObject(await resolve(c), c.req.valid("param").id));
435
+ },
436
+ );
299
437
 
300
438
  // Public by design: the token is the credential, and it is checked on every fetch — which is what
301
439
  // makes revocation possible at all.
302
440
  app.get(
303
441
  `${share}/:token`,
304
- zValidator("param", ShareTokenParam, validationHook),
305
- zValidator("query", ObjectReadQuery, validationHook),
442
+ describeRoute({
443
+ summary: "Read a file through a share link.",
444
+ description:
445
+ "The token is the credential. A revoked or expired link answers 410. Honors `Range` and `If-None-Match`.",
446
+ verification: "public",
447
+ responses: BYTE_RESPONSES,
448
+ }),
449
+ validate("param", ShareTokenParam),
450
+ validate("query", ObjectReadQuery),
306
451
  async (c) => {
307
452
  const deps = await resolve(c);
308
453
  const object = await resolveShare(deps, c.req.valid("param").token);
@@ -9,7 +9,7 @@ import { ReportedPart } from "../object/multipart";
9
9
  /**
10
10
  * The request schemas for the storage routes. Every path parameter, query string and body is parsed
11
11
  * here before a handler sees it (CLAUDE.md §Zod: validate at every boundary), declared on the route
12
- * line with `zValidator(target, Schema, validationHook)` — so reading `routes.ts` tells you what a
12
+ * line with `validate(target, Schema)` — so reading `routes.ts` tells you what a
13
13
  * route accepts without opening a handler. A failure maps to `validation/invalid_input` through
14
14
  * `fromZodError`.
15
15
  *
@@ -3,7 +3,8 @@
3
3
 
4
4
  import { CloudflareR2Manager } from "@pithy-sh/cloudflare/src/r2/r2Manager";
5
5
  import type { R2StorageCredentials } from "../secret/registry";
6
- import { type PresignedObjects, UploadedPart } from "./store";
6
+ import type { PresignedObjects } from "./store";
7
+ import { UploadedPart } from "./uploadedPart";
7
8
 
8
9
  /**
9
10
  * The SDK-friction boundary: the one file in this package that touches `@pithy-sh/cloudflare`.
@@ -8,6 +8,12 @@ import { z } from "zod";
8
8
  import { type R2StorageCredentials, r2CredentialsRegistry, STORAGE_R2_SECRET } from "../secret/registry";
9
9
  import { r2Presigned } from "./cloudflare";
10
10
  import type { ReportedPart } from "./multipart";
11
+ import type { UploadedPart } from "./uploadedPart";
12
+
13
+ // Re-exported, which this kit otherwise never does, because this path is a public address: the folder path
14
+ // is the import path, and `UploadedPart` was published here before it moved to `./uploadedPart` so a browser
15
+ // could import it without the S3 client (#719). Removing the line breaks every import of the old address.
16
+ export { UploadedPart } from "./uploadedPart";
11
17
 
12
18
  /**
13
19
  * `ObjectStore` — the object-plane seam, and the one piece of this package that is reusable outside it.
@@ -108,16 +114,6 @@ export const ObjectListing = z
108
114
  .describe("One page of a bucket listing. Pagination is caller-driven — pass `cursor` back to advance.");
109
115
  export type ObjectListing = z.output<typeof ObjectListing>;
110
116
 
111
- /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
112
- export const UploadedPart = z
113
- .object({
114
- partNumber: z.number().int().min(1).describe("The part's 1-based index within the upload."),
115
- etag: z.string().min(1).describe("The part's entity tag, verbatim. Pass it back unchanged to complete."),
116
- size: z.number().int().nonnegative().describe("The part's size in bytes, as R2 stored it."),
117
- })
118
- .describe("One uploaded part — the unit a resumed upload skips re-sending.");
119
- export type UploadedPart = z.output<typeof UploadedPart>;
120
-
121
117
  /** How long a presigned URL stays valid. */
122
118
  export interface PresignOptions {
123
119
  /** Lifetime in seconds. Defaults to one hour — long enough for a large part, short enough to leak little. */
@@ -0,0 +1,17 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+
6
+ // Its own module, importing nothing but zod, because `http/responses.ts` hands it to a browser and
7
+ // `./store.ts` beside it reaches the S3 client and the Workers runtime.
8
+
9
+ /** One part already stored against an in-flight multipart upload — what makes an upload resumable. */
10
+ export const UploadedPart = z
11
+ .object({
12
+ partNumber: z.number().int().min(1).describe("The part's 1-based index within the upload."),
13
+ etag: z.string().min(1).describe("The part's entity tag, verbatim. Pass it back unchanged to complete."),
14
+ size: z.number().int().nonnegative().describe("The part's size in bytes, as R2 stored it."),
15
+ })
16
+ .describe("One uploaded part — the unit a resumed upload skips re-sending.");
17
+ export type UploadedPart = z.output<typeof UploadedPart>;
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/storage";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.2.10";
16
+ export const PACKAGE_VERSION = "0.3.0";