@h-ai/storage 0.1.0-alpha5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [2026] [idealworld.group]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # @h-ai/storage
2
+
3
+ 对象存储模块,提供统一 `storage` 访问入口,支持 S3 兼容存储与本地文件系统。
4
+
5
+ ## 支持的后端
6
+
7
+ - S3 协议(AWS S3 / MinIO / OSS 等)
8
+ - 本地文件系统
9
+
10
+ ## 快速开始
11
+
12
+ ### Node.js 服务端
13
+
14
+ ```ts
15
+ import { storage } from '@h-ai/storage'
16
+
17
+ // 初始化(S3)
18
+ await storage.init({
19
+ type: 's3',
20
+ bucket: 'my-bucket',
21
+ region: 'us-east-1',
22
+ accessKeyId: process.env.HAI_STORAGE_S3_ACCESS_KEY!,
23
+ secretAccessKey: process.env.HAI_STORAGE_S3_SECRET_KEY!,
24
+ })
25
+
26
+ // 或本地存储
27
+ await storage.init({ type: 'local', root: '/data/uploads' })
28
+
29
+ // 上传/下载
30
+ await storage.file.put('uploads/image.png', imageBuffer, { contentType: 'image/png' })
31
+ const file = await storage.file.get('uploads/image.png')
32
+
33
+ // 签名 URL
34
+ const url = await storage.presign.getUrl('uploads/image.png', { expiresIn: 3600 })
35
+
36
+ // 关闭连接
37
+ await storage.close()
38
+ ```
39
+
40
+ ### 浏览器客户端
41
+
42
+ 浏览器环境下仅导出客户端能力(签名 URL 上传/下载),不包含 `storage` 服务对象。
43
+
44
+ ```ts
45
+ import { downloadAndSave, uploadWithPresignedUrl } from '@h-ai/storage/client'
46
+
47
+ // 业务端点路径由应用自行定义(例如 /api/files/presign-put)
48
+ const { uploadUrl } = await fetch('/api/files/presign-put').then(r => r.json())
49
+ await uploadWithPresignedUrl(uploadUrl, file)
50
+ ```
51
+
52
+ > 注意:`@h-ai/storage` 不内置 HTTP 路由;请在应用层自行实现签名 URL API。
53
+
54
+ ## API 契约(`@h-ai/storage/api`)
55
+
56
+ 独立子路径 `@h-ai/storage/api` 导出所有存储端点的 Zod Schema 和端点契约定义,客户端和服务端共享同一份类型定义,编译时保证 I/O 一致性。
57
+
58
+ ```ts
59
+ import { PresignPutInputSchema, storageEndpoints } from '@h-ai/storage/api'
60
+
61
+ // 端点契约包含 6 个端点:
62
+ // presignDownload / presignUpload / fileInfo / listFiles / deleteFile / deleteFiles
63
+
64
+ // 客户端调用
65
+ const { url } = await api.call(storageEndpoints.presignUpload, { key: 'avatar.png' })
66
+
67
+ // 服务端路由
68
+ export const POST = kit.fromContract(storageEndpoints.presignUpload, async (input) => {
69
+ const result = await storage.presign.putUrl(input.key, input)
70
+ return result.success ? result.data : kit.response.internalError(result.error.message)
71
+ })
72
+
73
+ // 独立使用 Schema 做校验
74
+ const parsed = PresignPutInputSchema.safeParse(requestBody)
75
+ if (!parsed.success) { /* 校验失败 */ }
76
+ ```
77
+
78
+ **导出的 Schema:**
79
+
80
+ - `FileMetadataSchema` — 文件元数据
81
+ - `PresignGetInputSchema` / `PresignPutInputSchema` — 签名 URL 入参
82
+ - `PresignUrlOutputSchema` — 签名 URL 出参
83
+ - `ListFilesOutputSchema` — 文件列表出参
84
+ - `DeleteFileInputSchema` / `DeleteFilesInputSchema` — 删除入参
85
+ - `FileInfoInputSchema` — 文件信息入参
86
+
87
+ **导出的类型(从 Schema 推导):**
88
+
89
+ `PresignGetInput` / `PresignPutInput` / `PresignUrlOutput` / `ListFilesOutput` / `DeleteFileInput` / `DeleteFilesInput` / `FileInfoInput`
90
+
91
+ ## API 概览
92
+
93
+ - `storage.file`
94
+ - `put/get/head/exists/delete/deleteMany/copy`
95
+ - `storage.dir`
96
+ - `list/delete`
97
+ - `storage.presign`
98
+ - `getUrl/putUrl/publicUrl`
99
+
100
+ > 注意:`publicUrl` 仅在 S3 配置了 `publicUrl` 时返回字符串;否则返回 `null`。
101
+
102
+ ## 客户端辅助函数
103
+
104
+ `@h-ai/storage/client` 还提供以下浏览器侧工具:
105
+
106
+ - `uploadWithPresignedUrl(url, data, options)`
107
+ - `downloadWithPresignedUrl(url, options)`
108
+ - `downloadAndSave(url, { filename })`
109
+ - `getFileExtension(file)`
110
+ - `getMimeType(extension)`
111
+ - `formatFileSize(bytes)`
112
+
113
+ ## 配置
114
+
115
+ - **S3**:`bucket / region / accessKeyId / secretAccessKey` 必填,可选 `endpoint / forcePathStyle / prefix / publicUrl`
116
+ - **Local**:`root` 必填,可选 `directoryMode / fileMode`
117
+
118
+ ## 错误处理
119
+
120
+ ```ts
121
+ import { HaiStorageError, storage } from '@h-ai/storage'
122
+
123
+ const result = await storage.file.get('image.png')
124
+ if (!result.success && result.error.code === HaiStorageError.NOT_INITIALIZED.code) {
125
+ // 存储未初始化
126
+ }
127
+ ```
128
+
129
+ 常用错误码:
130
+
131
+ | 错误码 | code | 说明 |
132
+ | ----------------------------------- | ----------------- | ------------------- |
133
+ | `HaiStorageError.NOT_INITIALIZED` | `hai:storage:010` | 未初始化 |
134
+ | `HaiStorageError.CONNECTION_FAILED` | `hai:storage:001` | 连接失败 |
135
+ | `HaiStorageError.OPERATION_FAILED` | `hai:storage:002` | 操作失败 |
136
+ | `HaiStorageError.NOT_FOUND` | `hai:storage:003` | 文件不存在 |
137
+ | `HaiStorageError.PERMISSION_DENIED` | `hai:storage:005` | 权限不足 |
138
+ | `HaiStorageError.PRESIGN_FAILED` | `hai:storage:013` | 预签名 URL 生成失败 |
139
+ | `HaiStorageError.CONFIG_ERROR` | `hai:storage:012` | 配置错误 |
140
+
141
+ ## 测试
142
+
143
+ ```bash
144
+ pnpm --filter @h-ai/storage test
145
+ ```
146
+
147
+ > MinIO/S3 相关测试需要 Docker 环境。
148
+
149
+ ## License
150
+
151
+ Apache-2.0
@@ -0,0 +1,167 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * @h-ai/storage/api — 存储 API 端点契约定义
5
+ *
6
+ * 所有 storage 模块的 API 端点(path + method + schema),
7
+ * 客户端和服务端都从此处引用,编译时保证一致性。
8
+ * @module storage-api-contract
9
+ */
10
+
11
+ interface EndpointDef<TInput = unknown, TOutput = unknown> {
12
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
13
+ path: string;
14
+ input: z.ZodType<TInput>;
15
+ output: z.ZodType<TOutput>;
16
+ requireAuth?: boolean;
17
+ meta?: {
18
+ summary?: string;
19
+ tags?: string[];
20
+ };
21
+ }
22
+ /**
23
+ * storage 所有 API 端点
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * // 客户端
28
+ * import { storageEndpoints } from '@h-ai/storage/api'
29
+ * const { url } = await api.call(storageEndpoints.presignUpload, { key: 'avatar.png' })
30
+ *
31
+ * // 服务端
32
+ * export const POST = kit.fromContract(storageEndpoints.presignUpload, async (input) => {
33
+ * const result = await storage.presign.putUrl(input.key, input)
34
+ * return result.success ? result.data : kit.response.internalError(result.error.message)
35
+ * })
36
+ * ```
37
+ */
38
+ declare const storageEndpoints: {
39
+ /** 获取下载签名 URL */
40
+ readonly presignDownload: EndpointDef<{
41
+ key: string;
42
+ expiresIn?: number | undefined;
43
+ }, {
44
+ url: string;
45
+ key: string;
46
+ expiresAt?: Date | undefined;
47
+ }>;
48
+ /** 获取上传签名 URL */
49
+ readonly presignUpload: EndpointDef<{
50
+ key: string;
51
+ contentType?: string | undefined;
52
+ contentLength?: number | undefined;
53
+ expiresIn?: number | undefined;
54
+ }, {
55
+ url: string;
56
+ key: string;
57
+ expiresAt?: Date | undefined;
58
+ }>;
59
+ /** 获取文件元数据 */
60
+ readonly fileInfo: EndpointDef<{
61
+ key: string;
62
+ }, {
63
+ key: string;
64
+ size: number;
65
+ contentType: string;
66
+ lastModified: Date;
67
+ etag?: string | undefined;
68
+ metadata?: Record<string, string> | undefined;
69
+ }>;
70
+ /** 列出文件 */
71
+ readonly listFiles: EndpointDef<{
72
+ prefix?: string | undefined;
73
+ maxKeys?: number | undefined;
74
+ continuationToken?: string | undefined;
75
+ delimiter?: string | undefined;
76
+ }, {
77
+ files: {
78
+ key: string;
79
+ size: number;
80
+ contentType: string;
81
+ lastModified: Date;
82
+ etag?: string | undefined;
83
+ metadata?: Record<string, string> | undefined;
84
+ }[];
85
+ commonPrefixes: string[];
86
+ isTruncated: boolean;
87
+ nextContinuationToken?: string | undefined;
88
+ }>;
89
+ /** 删除单个文件 */
90
+ readonly deleteFile: EndpointDef<{
91
+ key: string;
92
+ }, void>;
93
+ /** 批量删除文件 */
94
+ readonly deleteFiles: EndpointDef<{
95
+ keys: string[];
96
+ }, void>;
97
+ };
98
+
99
+ /**
100
+ * @h-ai/storage/api — 存储 API 契约 Schema
101
+ *
102
+ * 入参/出参 Schema,客户端和服务端共享的唯一真相源。
103
+ * @module storage-api-schemas
104
+ */
105
+
106
+ /** 文件元数据 Schema */
107
+ declare const FileMetadataSchema: z.ZodObject<{
108
+ key: z.ZodString;
109
+ size: z.ZodNumber;
110
+ contentType: z.ZodString;
111
+ lastModified: z.ZodCoercedDate<unknown>;
112
+ etag: z.ZodOptional<z.ZodString>;
113
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
114
+ }, z.core.$strip>;
115
+ /** 获取下载签名 URL 入参 */
116
+ declare const PresignGetInputSchema: z.ZodObject<{
117
+ key: z.ZodString;
118
+ expiresIn: z.ZodOptional<z.ZodNumber>;
119
+ }, z.core.$strip>;
120
+ /** 获取上传签名 URL 入参 */
121
+ declare const PresignPutInputSchema: z.ZodObject<{
122
+ key: z.ZodString;
123
+ contentType: z.ZodOptional<z.ZodString>;
124
+ contentLength: z.ZodOptional<z.ZodNumber>;
125
+ expiresIn: z.ZodOptional<z.ZodNumber>;
126
+ }, z.core.$strip>;
127
+ /** 签名 URL 出参 */
128
+ declare const PresignUrlOutputSchema: z.ZodObject<{
129
+ url: z.ZodString;
130
+ key: z.ZodString;
131
+ expiresAt: z.ZodOptional<z.ZodCoercedDate<unknown>>;
132
+ }, z.core.$strip>;
133
+ /** 文件列表出参 */
134
+ declare const ListFilesOutputSchema: z.ZodObject<{
135
+ files: z.ZodArray<z.ZodObject<{
136
+ key: z.ZodString;
137
+ size: z.ZodNumber;
138
+ contentType: z.ZodString;
139
+ lastModified: z.ZodCoercedDate<unknown>;
140
+ etag: z.ZodOptional<z.ZodString>;
141
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
142
+ }, z.core.$strip>>;
143
+ commonPrefixes: z.ZodArray<z.ZodString>;
144
+ nextContinuationToken: z.ZodOptional<z.ZodString>;
145
+ isTruncated: z.ZodBoolean;
146
+ }, z.core.$strip>;
147
+ /** 删除文件入参 */
148
+ declare const DeleteFileInputSchema: z.ZodObject<{
149
+ key: z.ZodString;
150
+ }, z.core.$strip>;
151
+ /** 批量删除文件入参 */
152
+ declare const DeleteFilesInputSchema: z.ZodObject<{
153
+ keys: z.ZodArray<z.ZodString>;
154
+ }, z.core.$strip>;
155
+ /** 获取文件信息入参 */
156
+ declare const FileInfoInputSchema: z.ZodObject<{
157
+ key: z.ZodString;
158
+ }, z.core.$strip>;
159
+ type PresignGetInput = z.infer<typeof PresignGetInputSchema>;
160
+ type PresignPutInput = z.infer<typeof PresignPutInputSchema>;
161
+ type PresignUrlOutput = z.infer<typeof PresignUrlOutputSchema>;
162
+ type ListFilesOutput = z.infer<typeof ListFilesOutputSchema>;
163
+ type DeleteFileInput = z.infer<typeof DeleteFileInputSchema>;
164
+ type DeleteFilesInput = z.infer<typeof DeleteFilesInputSchema>;
165
+ type FileInfoInput = z.infer<typeof FileInfoInputSchema>;
166
+
167
+ export { type DeleteFileInput, DeleteFileInputSchema, type DeleteFilesInput, DeleteFilesInputSchema, type FileInfoInput, FileInfoInputSchema, FileMetadataSchema, type ListFilesOutput, ListFilesOutputSchema, type PresignGetInput, PresignGetInputSchema, type PresignPutInput, PresignPutInputSchema, type PresignUrlOutput, PresignUrlOutputSchema, storageEndpoints };
@@ -0,0 +1,105 @@
1
+ import { z } from 'zod';
2
+
3
+ // src/api/storage-api-contract.ts
4
+ var FileMetadataSchema = z.object({
5
+ key: z.string(),
6
+ size: z.number(),
7
+ contentType: z.string(),
8
+ lastModified: z.coerce.date(),
9
+ etag: z.string().optional(),
10
+ metadata: z.record(z.string(), z.string()).optional()
11
+ });
12
+ var PresignGetInputSchema = z.object({
13
+ key: z.string().min(1),
14
+ expiresIn: z.number().int().min(1).optional()
15
+ });
16
+ var PresignPutInputSchema = z.object({
17
+ key: z.string().min(1),
18
+ contentType: z.string().optional(),
19
+ contentLength: z.number().int().min(1).optional(),
20
+ expiresIn: z.number().int().min(1).optional()
21
+ });
22
+ var PresignUrlOutputSchema = z.object({
23
+ url: z.string(),
24
+ key: z.string(),
25
+ expiresAt: z.coerce.date().optional()
26
+ });
27
+ var ListFilesOutputSchema = z.object({
28
+ files: z.array(FileMetadataSchema),
29
+ commonPrefixes: z.array(z.string()),
30
+ nextContinuationToken: z.string().optional(),
31
+ isTruncated: z.boolean()
32
+ });
33
+ var DeleteFileInputSchema = z.object({
34
+ key: z.string().min(1)
35
+ });
36
+ var DeleteFilesInputSchema = z.object({
37
+ keys: z.array(z.string().min(1)).min(1)
38
+ });
39
+ var FileInfoInputSchema = z.object({
40
+ key: z.string().min(1)
41
+ });
42
+
43
+ // src/api/storage-api-contract.ts
44
+ function defineEndpoint(def) {
45
+ return def;
46
+ }
47
+ var storageEndpoints = {
48
+ /** 获取下载签名 URL */
49
+ presignDownload: defineEndpoint({
50
+ method: "POST",
51
+ path: "/storage/presign/download",
52
+ input: PresignGetInputSchema,
53
+ output: PresignUrlOutputSchema,
54
+ meta: { summary: "Get presigned download URL", tags: ["storage"] }
55
+ }),
56
+ /** 获取上传签名 URL */
57
+ presignUpload: defineEndpoint({
58
+ method: "POST",
59
+ path: "/storage/presign/upload",
60
+ input: PresignPutInputSchema,
61
+ output: PresignUrlOutputSchema,
62
+ meta: { summary: "Get presigned upload URL", tags: ["storage"] }
63
+ }),
64
+ /** 获取文件元数据 */
65
+ fileInfo: defineEndpoint({
66
+ method: "POST",
67
+ path: "/storage/file/info",
68
+ input: FileInfoInputSchema,
69
+ output: FileMetadataSchema,
70
+ meta: { summary: "Get file metadata", tags: ["storage"] }
71
+ }),
72
+ /** 列出文件 */
73
+ listFiles: defineEndpoint({
74
+ method: "GET",
75
+ path: "/storage/files",
76
+ input: z.object({
77
+ prefix: z.string().optional(),
78
+ maxKeys: z.coerce.number().int().min(1).max(1e3).optional(),
79
+ continuationToken: z.string().optional(),
80
+ delimiter: z.string().optional()
81
+ }),
82
+ output: ListFilesOutputSchema,
83
+ meta: { summary: "List files by prefix", tags: ["storage"] }
84
+ }),
85
+ /** 删除单个文件 */
86
+ deleteFile: defineEndpoint({
87
+ method: "POST",
88
+ path: "/storage/file/delete",
89
+ input: DeleteFileInputSchema,
90
+ output: z.void(),
91
+ meta: { summary: "Delete a file", tags: ["storage"] }
92
+ }),
93
+ /** 批量删除文件 */
94
+ deleteFiles: defineEndpoint({
95
+ method: "POST",
96
+ path: "/storage/files/delete",
97
+ input: DeleteFilesInputSchema,
98
+ output: z.void(),
99
+ meta: { summary: "Delete multiple files", tags: ["storage"] }
100
+ })
101
+ };
102
+
103
+ export { DeleteFileInputSchema, DeleteFilesInputSchema, FileInfoInputSchema, FileMetadataSchema, ListFilesOutputSchema, PresignGetInputSchema, PresignPutInputSchema, PresignUrlOutputSchema, storageEndpoints };
104
+ //# sourceMappingURL=index.js.map
105
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/storage-api-schemas.ts","../../src/api/storage-api-contract.ts"],"names":["z"],"mappings":";;;AAYO,IAAM,kBAAA,GAAqB,EAAE,MAAA,CAAO;AAAA,EACzC,GAAA,EAAK,EAAE,MAAA,EAAO;AAAA,EACd,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,EACf,WAAA,EAAa,EAAE,MAAA,EAAO;AAAA,EACtB,YAAA,EAAc,CAAA,CAAE,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AA,EAAK;AAAA,IACf,MAAM,EAAE,OAAA,EAAS,yBAAyB,IAAA,EAAM,CAAC,SAAS,CAAA;AAAE,GAC7D;AACH","file":"index.js","sourcesContent":["/**\n * @h-ai/storage/api — 存储 API 契约 Schema\n *\n * 入参/出参 Schema,客户端和服务端共享的唯一真相源。\n * @module storage-api-schemas\n */\n\nimport { z } from 'zod'\n\n// ─── 文件元数据 ───\n\n/** 文件元数据 Schema */\nexport const FileMetadataSchema = z.object({\n key: z.string(),\n size: z.number(),\n contentType: z.string(),\n lastModified: z.coerce.date(),\n etag: z.string().optional(),\n metadata: z.record(z.string(), z.string()).optional(),\n})\n\n// ─── 签名 URL ───\n\n/** 获取下载签名 URL 入参 */\nexport const PresignGetInputSchema = z.object({\n key: z.string().min(1),\n expiresIn: z.number().int().min(1).optional(),\n})\n\n/** 获取上传签名 URL 入参 */\nexport const PresignPutInputSchema = z.object({\n key: z.string().min(1),\n contentType: z.string().optional(),\n contentLength: z.number().int().min(1).optional(),\n expiresIn: z.number().int().min(1).optional(),\n})\n\n/** 签名 URL 出参 */\nexport const PresignUrlOutputSchema = z.object({\n url: z.string(),\n key: z.string(),\n expiresAt: z.coerce.date().optional(),\n})\n\n// ─── 列表 ───\n\n/** 文件列表出参 */\nexport const ListFilesOutputSchema = z.object({\n files: z.array(FileMetadataSchema),\n commonPrefixes: z.array(z.string()),\n nextContinuationToken: z.string().optional(),\n isTruncated: z.boolean(),\n})\n\n// ─── 删除 ───\n\n/** 删除文件入参 */\nexport const DeleteFileInputSchema = z.object({\n key: z.string().min(1),\n})\n\n/** 批量删除文件入参 */\nexport const DeleteFilesInputSchema = z.object({\n keys: z.array(z.string().min(1)).min(1),\n})\n\n// ─── 文件信息 ───\n\n/** 获取文件信息入参 */\nexport const FileInfoInputSchema = z.object({\n key: z.string().min(1),\n})\n\n// ─── 推导类型 ───\n\nexport type PresignGetInput = z.infer<typeof PresignGetInputSchema>\nexport type PresignPutInput = z.infer<typeof PresignPutInputSchema>\nexport type PresignUrlOutput = z.infer<typeof PresignUrlOutputSchema>\nexport type ListFilesOutput = z.infer<typeof ListFilesOutputSchema>\nexport type DeleteFileInput = z.infer<typeof DeleteFileInputSchema>\nexport type DeleteFilesInput = z.infer<typeof DeleteFilesInputSchema>\nexport type FileInfoInput = z.infer<typeof FileInfoInputSchema>\n","/**\n * @h-ai/storage/api — 存储 API 端点契约定义\n *\n * 所有 storage 模块的 API 端点(path + method + schema),\n * 客户端和服务端都从此处引用,编译时保证一致性。\n * @module storage-api-contract\n */\n\nimport { z } from 'zod'\nimport {\n DeleteFileInputSchema,\n DeleteFilesInputSchema,\n FileInfoInputSchema,\n FileMetadataSchema,\n ListFilesOutputSchema,\n PresignGetInputSchema,\n PresignPutInputSchema,\n PresignUrlOutputSchema,\n} from './storage-api-schemas.js'\n\n// ─── 端点定义辅助(内联,避免对 @h-ai/api-client 的循环依赖) ───\n\ninterface EndpointDef<TInput = unknown, TOutput = unknown> {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n path: string\n input: z.ZodType<TInput>\n output: z.ZodType<TOutput>\n requireAuth?: boolean\n meta?: { summary?: string, tags?: string[] }\n}\n\nfunction defineEndpoint<TInput, TOutput>(def: EndpointDef<TInput, TOutput>): EndpointDef<TInput, TOutput> {\n return def\n}\n\n// ─── storage API 端点 ───\n\n/**\n * storage 所有 API 端点\n *\n * @example\n * ```ts\n * // 客户端\n * import { storageEndpoints } from '@h-ai/storage/api'\n * const { url } = await api.call(storageEndpoints.presignUpload, { key: 'avatar.png' })\n *\n * // 服务端\n * export const POST = kit.fromContract(storageEndpoints.presignUpload, async (input) => {\n * const result = await storage.presign.putUrl(input.key, input)\n * return result.success ? result.data : kit.response.internalError(result.error.message)\n * })\n * ```\n */\nexport const storageEndpoints = {\n /** 获取下载签名 URL */\n presignDownload: defineEndpoint({\n method: 'POST',\n path: '/storage/presign/download',\n input: PresignGetInputSchema,\n output: PresignUrlOutputSchema,\n meta: { summary: 'Get presigned download URL', tags: ['storage'] },\n }),\n\n /** 获取上传签名 URL */\n presignUpload: defineEndpoint({\n method: 'POST',\n path: '/storage/presign/upload',\n input: PresignPutInputSchema,\n output: PresignUrlOutputSchema,\n meta: { summary: 'Get presigned upload URL', tags: ['storage'] },\n }),\n\n /** 获取文件元数据 */\n fileInfo: defineEndpoint({\n method: 'POST',\n path: '/storage/file/info',\n input: FileInfoInputSchema,\n output: FileMetadataSchema,\n meta: { summary: 'Get file metadata', tags: ['storage'] },\n }),\n\n /** 列出文件 */\n listFiles: defineEndpoint({\n method: 'GET',\n path: '/storage/files',\n input: z.object({\n prefix: z.string().optional(),\n maxKeys: z.coerce.number().int().min(1).max(1000).optional(),\n continuationToken: z.string().optional(),\n delimiter: z.string().optional(),\n }),\n output: ListFilesOutputSchema,\n meta: { summary: 'List files by prefix', tags: ['storage'] },\n }),\n\n /** 删除单个文件 */\n deleteFile: defineEndpoint({\n method: 'POST',\n path: '/storage/file/delete',\n input: DeleteFileInputSchema,\n output: z.void(),\n meta: { summary: 'Delete a file', tags: ['storage'] },\n }),\n\n /** 批量删除文件 */\n deleteFiles: defineEndpoint({\n method: 'POST',\n path: '/storage/files/delete',\n input: DeleteFilesInputSchema,\n output: z.void(),\n meta: { summary: 'Delete multiple files', tags: ['storage'] },\n }),\n} as const\n"]}