@lykosjs/cloudinary 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +381 -2
  3. package/dist/cloudinary-manager.d.ts +17 -0
  4. package/dist/cloudinary-manager.js +51 -0
  5. package/dist/cloudinary-manager.js.map +1 -0
  6. package/dist/files/file-manager.d.ts +13 -0
  7. package/dist/files/file-manager.js +77 -0
  8. package/dist/files/file-manager.js.map +1 -0
  9. package/dist/files/file-type.d.ts +3 -0
  10. package/dist/files/file-type.js +10 -0
  11. package/dist/files/file-type.js.map +1 -0
  12. package/dist/files/types.d.ts +17 -0
  13. package/dist/files/types.js +5 -0
  14. package/dist/files/types.js.map +1 -0
  15. package/dist/images/image-manager.d.ts +26 -0
  16. package/dist/images/image-manager.js +210 -0
  17. package/dist/images/image-manager.js.map +1 -0
  18. package/dist/images/image-type.d.ts +6 -0
  19. package/dist/images/image-type.js +32 -0
  20. package/dist/images/image-type.js.map +1 -0
  21. package/dist/images/types.d.ts +43 -0
  22. package/dist/images/types.js +2 -0
  23. package/dist/images/types.js.map +1 -0
  24. package/dist/index.d.ts +5 -0
  25. package/dist/index.js +3 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/shared/byte-utils.d.ts +1 -0
  28. package/dist/shared/byte-utils.js +2 -0
  29. package/dist/shared/byte-utils.js.map +1 -0
  30. package/dist/shared/concurrency.d.ts +12 -0
  31. package/dist/shared/concurrency.js +33 -0
  32. package/dist/shared/concurrency.js.map +1 -0
  33. package/dist/shared/destroy-batch.d.ts +10 -0
  34. package/dist/shared/destroy-batch.js +31 -0
  35. package/dist/shared/destroy-batch.js.map +1 -0
  36. package/dist/shared/destroy-resource.d.ts +5 -0
  37. package/dist/shared/destroy-resource.js +23 -0
  38. package/dist/shared/destroy-resource.js.map +1 -0
  39. package/dist/shared/error-message.d.ts +1 -0
  40. package/dist/shared/error-message.js +11 -0
  41. package/dist/shared/error-message.js.map +1 -0
  42. package/dist/shared/normalize-folder.d.ts +1 -0
  43. package/dist/shared/normalize-folder.js +22 -0
  44. package/dist/shared/normalize-folder.js.map +1 -0
  45. package/dist/shared/public-id.d.ts +10 -0
  46. package/dist/shared/public-id.js +49 -0
  47. package/dist/shared/public-id.js.map +1 -0
  48. package/dist/shared/upload-batch.d.ts +16 -0
  49. package/dist/shared/upload-batch.js +91 -0
  50. package/dist/shared/upload-batch.js.map +1 -0
  51. package/dist/shared/upload-stream.d.ts +13 -0
  52. package/dist/shared/upload-stream.js +36 -0
  53. package/dist/shared/upload-stream.js.map +1 -0
  54. package/dist/shared/validate-blob.d.ts +12 -0
  55. package/dist/shared/validate-blob.js +21 -0
  56. package/dist/shared/validate-blob.js.map +1 -0
  57. package/dist/types/config.d.ts +92 -0
  58. package/dist/types/config.js +54 -0
  59. package/dist/types/config.js.map +1 -0
  60. package/dist/videos/types.d.ts +20 -0
  61. package/dist/videos/types.js +2 -0
  62. package/dist/videos/types.js.map +1 -0
  63. package/dist/videos/video-manager.d.ts +13 -0
  64. package/dist/videos/video-manager.js +80 -0
  65. package/dist/videos/video-manager.js.map +1 -0
  66. package/dist/videos/video-type.d.ts +3 -0
  67. package/dist/videos/video-type.js +27 -0
  68. package/dist/videos/video-type.js.map +1 -0
  69. package/package.json +47 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zen Allaham - LykosJS - @lykosjs/cloudinary
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO ELYKOS SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,382 @@
1
- # Temporary Holding Version
1
+ # ☁️ @lykosjs/cloudinary
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **A secure, type-safe Cloudinary upload manager for images, files, and videos, built for Bun and modern JavaScript runtimes.**
4
+
5
+ `@lykosjs/cloudinary` wraps the Cloudinary SDK with a small, predictable API for uploading and deleting images, PDF/ZIP files, and videos. Every upload is validated before it leaves your server: size first, then the real content type read from the file's bytes.
6
+
7
+ Designed with security-conscious defaults, it can be used independently or alongside the LykosJS framework.
8
+
9
+ [![npm version](https://img.shields.io/npm/v/@lykosjs/cloudinary)](https://www.npmjs.com/package/@lykosjs/cloudinary)
10
+ [![npm downloads](https://img.shields.io/npm/dm/@lykosjs/cloudinary)](https://www.npmjs.com/package/@lykosjs/cloudinary)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-supported-blue)](https://www.typescriptlang.org/)
12
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
13
+
14
+ ---
15
+
16
+ ## ✨ Features
17
+
18
+ - **Three managers in one** — `images`, `files`, and `videos`, each with its own limits and allowed types.
19
+ - **Content-based validation** — The type is detected from the file's first bytes, never from the spoofable `file.type`.
20
+ - **Size limits** — Files over the limit are rejected before any upload starts (5 MB images, 10 MB files, 100 MB videos by default).
21
+ - **Safe defaults** — SVG is not accepted unless you explicitly allow it.
22
+ - **Batch operations** — Upload or delete many resources with bounded concurrency. A failed batch upload removes what was already uploaded.
23
+ - **Streaming uploads** — Files and videos are streamed to Cloudinary instead of being loaded fully into memory.
24
+ - **No global state** — Credentials are passed per instance, with no module-level `cloudinary.config()` side effect.
25
+ - **URL helper** — Build resized and optimized image delivery URLs.
26
+ - **Structured errors** — Failures are `HttpError`s with meaningful status codes.
27
+ - **TypeScript support** — Fully typed configuration, options, and results.
28
+
29
+ ## 📦 Installation
30
+
31
+ ```bash
32
+ bun add @lykosjs/cloudinary
33
+ ```
34
+
35
+ Or with npm:
36
+
37
+ ```bash
38
+ npm install @lykosjs/cloudinary
39
+ ```
40
+
41
+ `lykosjs` is a peer dependency and must be installed in your project.
42
+
43
+ ## 🚀 Quick start
44
+
45
+ ```ts
46
+ import { CloudinaryManager } from '@lykosjs/cloudinary'
47
+
48
+ const cloudinary = new CloudinaryManager({
49
+ cloudName: process.env.CLOUDINARY_CLOUD_NAME!,
50
+ apiKey: process.env.CLOUDINARY_API_KEY!,
51
+ apiSecret: process.env.CLOUDINARY_API_SECRET!,
52
+ })
53
+
54
+ // Upload an image
55
+ const image = await cloudinary.images.uploadImage(file, 'avatars')
56
+ console.log(image.url, image.publicId)
57
+
58
+ // Delete it
59
+ await cloudinary.images.destroyImage(image.publicId)
60
+ ```
61
+
62
+ Or read the credentials from `CLOUDINARY_CLOUD_NAME`, `CLOUDINARY_API_KEY`, and `CLOUDINARY_API_SECRET`:
63
+
64
+ ```ts
65
+ const cloudinary = CloudinaryManager.fromEnv()
66
+ ```
67
+
68
+ ## 📖 API reference
69
+
70
+ ### `CloudinaryManager`
71
+
72
+ ```ts
73
+ new CloudinaryManager(config: CloudinaryManagerConfig, options?: CloudinaryManagerOptions)
74
+ ```
75
+
76
+ The constructor throws `HttpError(500)` when `cloudName`, `apiKey`, or `apiSecret` is missing. It exposes three managers:
77
+
78
+ | Property | Manager | Handles |
79
+ | -------- | -------------- | ----------------------------------- |
80
+ | `images` | `ImageManager` | Images, plus delivery URL building |
81
+ | `files` | `FileManager` | PDF and ZIP files (stored as `raw`) |
82
+ | `videos` | `VideoManager` | MP4, WebM, and QuickTime videos |
83
+
84
+ ### `CloudinaryManager.fromEnv()`
85
+
86
+ ```ts
87
+ CloudinaryManager.fromEnv(env?: Record<string, string | undefined>): CloudinaryManager
88
+ ```
89
+
90
+ Reads the three `CLOUDINARY_*` variables from `process.env` (or from the `env` object you pass) and throws `HttpError(500)` naming the first one that is missing or empty.
91
+
92
+ ### Images — `cloudinary.images`
93
+
94
+ #### `uploadImage()`
95
+
96
+ ```ts
97
+ uploadImage(file: Blob, folder: string, options?: UploadOptions): Promise<UploadedImage>
98
+ ```
99
+
100
+ Validates and uploads an image. `File` extends `Blob`, so a `File` from `request.formData()` works directly.
101
+
102
+ ```ts
103
+ const image = await cloudinary.images.uploadImage(file, 'products', {
104
+ tags: ['product'],
105
+ maxFileSize: 2 * 1024 * 1024,
106
+ allowedTypes: ['image/jpeg', 'image/png'],
107
+ })
108
+ ```
109
+
110
+ Returns:
111
+
112
+ ```ts
113
+ interface UploadedImage {
114
+ url: string // HTTPS delivery URL
115
+ publicId: string // store this, you need it to delete the image
116
+ width: number
117
+ height: number
118
+ format: string
119
+ bytes: number
120
+ }
121
+ ```
122
+
123
+ `UploadOptions` accepts `publicId`, `tags`, `maxFileSize`, and `allowedTypes`.
124
+
125
+ #### `uploadImagesMany()`
126
+
127
+ ```ts
128
+ uploadImagesMany(files: readonly Blob[], folder: string, options?: UploadManyOptions): Promise<UploadedImage[]>
129
+ ```
130
+
131
+ Uploads several images in parallel (`concurrency` defaults to `3`) and returns them in the original order. If any upload fails, the images that already succeeded are deleted and the first error is thrown, so you never end up with orphaned images. `publicId` is not available in batch uploads.
132
+
133
+ #### `destroyImage()` / `destroyImagesMany()`
134
+
135
+ ```ts
136
+ await cloudinary.images.destroyImage('avatars/abc123')
137
+ await cloudinary.images.destroyImagesMany(['avatars/a', 'avatars/b'], {
138
+ concurrency: 5,
139
+ })
140
+ ```
141
+
142
+ Deleted images are also invalidated on the CDN. Deleting an image that does not exist throws `HttpError(404)`. `destroyImagesMany` removes duplicate IDs, attempts every deletion, then throws the first error (in input order) if any failed.
143
+
144
+ #### `url()`
145
+
146
+ Builds a delivery URL with optional resizing and format options.
147
+
148
+ ```ts
149
+ const thumb = cloudinary.images.url(image.publicId, {
150
+ width: 200,
151
+ height: 200,
152
+ crop: 'fill',
153
+ quality: 'auto',
154
+ format: 'auto',
155
+ })
156
+ ```
157
+
158
+ | Option | Values |
159
+ | --------- | ----------------------------------------------------------------- |
160
+ | `width` | Positive integer |
161
+ | `height` | Positive integer |
162
+ | `crop` | `'fill'`, `'fit'`, `'scale'`, `'limit'`, `'thumb'` |
163
+ | `quality` | Integer from `1` to `100`, or `'auto'` |
164
+ | `format` | `'auto'`, `'jpg'`, `'jpeg'`, `'png'`, `'gif'`, `'webp'`, `'avif'` |
165
+
166
+ `crop` defaults to `'limit'` when a width or height is set. Invalid values throw `HttpError(400)`.
167
+
168
+ ### Files — `cloudinary.files`
169
+
170
+ ```ts
171
+ const file = await cloudinary.files.uploadFile(pdf, 'documents', {
172
+ tags: ['invoice'],
173
+ })
174
+ // { url, publicId, bytes, mimeType: 'application/pdf' }
175
+
176
+ const many = await cloudinary.files.uploadFilesMany([a, b, c], 'documents', {
177
+ concurrency: 3,
178
+ })
179
+
180
+ await cloudinary.files.destroyFile(file.publicId)
181
+ await cloudinary.files.destroyFilesMany(many.map((item) => item.publicId))
182
+ ```
183
+
184
+ Accepts PDF and ZIP files. The ZIP type also covers `.docx`, `.xlsx`, and `.pptx`, which are ZIP containers. Unless you pass a `publicId`, a random one is generated and includes the file extension (for example `3f2a…c1.pdf`). Raw files are stored with their extension as part of the public ID, so always pass the full `publicId` back to `destroyFile()`.
185
+
186
+ ```ts
187
+ interface UploadedFile {
188
+ url: string
189
+ publicId: string
190
+ bytes: number
191
+ mimeType: 'application/pdf' | 'application/zip'
192
+ }
193
+ ```
194
+
195
+ ### Videos — `cloudinary.videos`
196
+
197
+ ```ts
198
+ const video = await cloudinary.videos.uploadVideo(file, 'lessons', {
199
+ tags: ['intro'],
200
+ })
201
+ // { url, publicId, width, height, format, bytes, duration }
202
+
203
+ const many = await cloudinary.videos.uploadVideosMany([a, b], 'lessons', {
204
+ concurrency: 2,
205
+ })
206
+
207
+ await cloudinary.videos.destroyVideo(video.publicId)
208
+ await cloudinary.videos.destroyVideosMany(many.map((item) => item.publicId))
209
+ ```
210
+
211
+ Accepts MP4, WebM, and QuickTime (`.mov`). `duration` is in seconds. Image formats that share the MP4 container (AVIF, HEIC) are rejected as videos.
212
+
213
+ ### Batch behavior (files and videos)
214
+
215
+ `uploadFilesMany()` and `uploadVideosMany()` share the same safe batch flow:
216
+
217
+ 1. Every file is validated **before** any upload starts, so one bad file fails the batch without wasting uploads.
218
+ 2. Uploads run with bounded concurrency. After the first failure, no new uploads are started.
219
+ 3. Everything that already uploaded is deleted, and the first error (by input order) is thrown.
220
+ 4. Results keep the original input order.
221
+
222
+ If the cleanup itself fails for some resources, an `AggregateError` is thrown containing the original error followed by one error per resource that could not be removed.
223
+
224
+ ### `extractPublicId()`
225
+
226
+ Gets the public ID from a Cloudinary delivery URL, for when only the URL was stored.
227
+
228
+ ```ts
229
+ import { extractPublicId } from '@lykosjs/cloudinary'
230
+
231
+ const publicId = extractPublicId(user.avatarUrl)
232
+ if (publicId) await cloudinary.images.destroyImage(publicId)
233
+ ```
234
+
235
+ Returns `null` for non-Cloudinary URLs. It strips the file extension, so it is meant for **images and videos**. Raw files keep their extension in the public ID, so store the `publicId` returned by `uploadFile()` instead. If a URL contains transformations but no version segment (`v123`), they cannot be told apart from folders, so prefer storing the public ID.
236
+
237
+ ## ⚙️ Configuration
238
+
239
+ ```ts
240
+ new CloudinaryManager(
241
+ { cloudName, apiKey, apiSecret },
242
+ {
243
+ images: {
244
+ maxFileSize: 2 * 1024 * 1024,
245
+ allowedTypes: ['image/jpeg', 'image/png'],
246
+ },
247
+ files: { maxFileSize: 20 * 1024 * 1024 },
248
+ videos: { maxFileSize: 50 * 1024 * 1024, allowedTypes: ['video/mp4'] },
249
+ },
250
+ )
251
+ ```
252
+
253
+ ### `CloudinaryManagerOptions`
254
+
255
+ | Option | Default | Description |
256
+ | --------------------- | ------------------------------------------------------------------ | --------------------------- |
257
+ | `images.maxFileSize` | `5242880` (5 MB) | Maximum image size in bytes |
258
+ | `images.allowedTypes` | `image/jpeg`, `image/png`, `image/gif`, `image/webp`, `image/avif` | Accepted image types |
259
+ | `files.maxFileSize` | `10485760` (10 MB) | Maximum file size in bytes |
260
+ | `files.allowedTypes` | `application/pdf`, `application/zip` | Accepted file types |
261
+ | `videos.maxFileSize` | `104857600` (100 MB) | Maximum video size in bytes |
262
+ | `videos.allowedTypes` | `video/mp4`, `video/webm`, `video/quicktime` | Accepted video types |
263
+
264
+ `maxFileSize` and `allowedTypes` can also be overridden per upload.
265
+
266
+ ### Batch concurrency
267
+
268
+ | Operation | Default |
269
+ | ---------------------------- | ------- |
270
+ | Image and file batch uploads | `3` |
271
+ | Video batch uploads | `2` |
272
+ | Batch deletions | `5` |
273
+
274
+ For files, videos, and deletions, `concurrency` must be an integer from `1` to `10`, otherwise `HttpError(400)` is thrown.
275
+
276
+ ## 🚨 Errors
277
+
278
+ | Status | Cause |
279
+ | ------ | ------------------------------------------------------------------------ |
280
+ | `400` | Empty file, empty or unsafe folder, invalid public ID, or invalid option |
281
+ | `404` | Deleting a resource that does not exist |
282
+ | `413` | File larger than the size limit |
283
+ | `415` | Content is not an allowed type |
284
+ | `500` | Missing Cloudinary credentials |
285
+ | `502` | Cloudinary rejected or failed the request |
286
+
287
+ Folders are normalized and validated: leading and trailing slashes are removed, and empty segments, `.`, `..`, control characters, and names over 255 characters are rejected.
288
+
289
+ ## 🔐 Security best practices
290
+
291
+ ### 1. Keep the API secret on the server
292
+
293
+ Never expose `CLOUDINARY_API_SECRET` to the browser or commit it to version control.
294
+
295
+ ### 2. Do not trust `file.type`
296
+
297
+ It is set by the client. This package checks the real file signature instead, so a script renamed to `.png` or `.pdf` is rejected.
298
+
299
+ ### 3. Keep size limits tight
300
+
301
+ Set `maxFileSize` to the smallest value your use case allows, for example 1 to 2 MB for avatars.
302
+
303
+ ### 4. Allow only the types you need
304
+
305
+ Restrict `allowedTypes` per use case. For example, an avatar endpoint should accept only `image/jpeg`, `image/png`, and `image/webp`.
306
+
307
+ ### 5. Be careful with SVG
308
+
309
+ SVG files can contain scripts, so they are rejected by default. Only add `'image/svg+xml'` to `allowedTypes` if you trust the uploader or sanitize the file yourself.
310
+
311
+ ### 6. Do not let users choose the folder
312
+
313
+ Build the `folder` argument on the server, for example from the authenticated user's ID, instead of passing user input directly.
314
+
315
+ ## 🧩 Integration with LykosjS
316
+
317
+ ```ts
318
+ import { CloudinaryManager } from '@lykosjs/cloudinary'
319
+
320
+ const cloudinary = CloudinaryManager.fromEnv()
321
+
322
+ app.POST('/avatar', async (ctx, reply) => {
323
+ const form = await ctx.request.formData()
324
+ const file = form.get('avatar')
325
+
326
+ if (!(file instanceof File)) {
327
+ return reply.BadRequest({ message: 'Avatar file is required' })
328
+ }
329
+
330
+ const image = await cloudinary.images.uploadImage(file, 'avatars', {
331
+ maxFileSize: 2 * 1024 * 1024,
332
+ allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
333
+ })
334
+
335
+ return reply.OK({ url: image.url, publicId: image.publicId })
336
+ })
337
+ ```
338
+
339
+ **Integration note:** The example assumes that `HttpError` thrown by the manager is converted into an HTTP response by your LykosJS error handling, and that `BadRequest` exists in your response helper. Adapt it if your application behaves differently.
340
+
341
+ ## 🧪 Testing
342
+
343
+ ```bash
344
+ bun test
345
+ ```
346
+
347
+ The tests mock the Cloudinary SDK, so no credentials or network access are needed. The test suite covers:
348
+
349
+ - Constructor and `fromEnv()` validation.
350
+ - Size, folder, and public ID validation.
351
+ - Content-based type detection for images, files, and videos.
352
+ - Single and batch uploads, including cleanup after a failed batch.
353
+ - Single and batch deletion.
354
+ - URL building and public ID extraction.
355
+
356
+ Always run the full test suite before publishing a new release.
357
+
358
+ ## 📚 Dependencies
359
+
360
+ - [`cloudinary`](https://www.npmjs.com/package/cloudinary) for uploads, deletion, and URL generation.
361
+ - `lykosjs` (peer dependency) for `HttpError`.
362
+
363
+ ## 🤝 Contributing
364
+
365
+ Contributions, bug reports, and suggestions are welcome.
366
+
367
+ 1. Reproduce the issue or describe the proposed improvement.
368
+ 2. Add or update tests.
369
+ 3. Run the full test suite.
370
+ 4. Update documentation when the public API changes.
371
+
372
+ Please ensure validation-related changes preserve the content-based type checks and size limits.
373
+
374
+ ## 📄 License
375
+
376
+ See the [`LICENSE`](LICENSE) file in this repository.
377
+
378
+ ## Part of the LykosJS ecosystem
379
+
380
+ `@lykosjs/cloudinary` provides focused media upload management that can be used independently or integrated into LykosJS applications.
381
+
382
+ **Simple API. Explicit validation. Predictable behavior.**
@@ -0,0 +1,17 @@
1
+ import type { CloudinaryManagerConfig } from './types/config';
2
+ import type { CloudinaryManagerOptions } from './types/config';
3
+ import { ImageManager } from './images/image-manager';
4
+ import { FileManager } from './files/file-manager';
5
+ import { VideoManager } from './videos/video-manager';
6
+ export declare class CloudinaryManager {
7
+ private readonly credentials;
8
+ readonly images: ImageManager;
9
+ readonly files: FileManager;
10
+ readonly videos: VideoManager;
11
+ constructor(config: CloudinaryManagerConfig, options?: CloudinaryManagerOptions);
12
+ /**
13
+ * Creates a manager from CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY and
14
+ * CLOUDINARY_API_SECRET.
15
+ */
16
+ static fromEnv(env?: Record<string, string | undefined>, options?: Pick<CloudinaryManagerConfig, 'maxFileSize' | 'allowedTypes'>): CloudinaryManager;
17
+ }
@@ -0,0 +1,51 @@
1
+ import { HttpError } from 'lykosjs';
2
+ import { ImageManager } from './images/image-manager';
3
+ import { FileManager } from './files/file-manager';
4
+ import { VideoManager } from './videos/video-manager';
5
+ export class CloudinaryManager {
6
+ credentials;
7
+ images;
8
+ files;
9
+ videos;
10
+ constructor(config, options = {}) {
11
+ if (!config.cloudName)
12
+ throw new HttpError(500, 'Cloudinary cloud name is required');
13
+ if (!config.apiKey)
14
+ throw new HttpError(500, 'Cloudinary API key is required');
15
+ if (!config.apiSecret)
16
+ throw new HttpError(500, 'Cloudinary API secret is required');
17
+ this.credentials = {
18
+ cloud_name: config.cloudName,
19
+ api_key: config.apiKey,
20
+ api_secret: config.apiSecret,
21
+ };
22
+ this.images = new ImageManager(this.credentials, options.images);
23
+ this.files = new FileManager(this.credentials, options.files);
24
+ this.videos = new VideoManager(this.credentials, options.videos);
25
+ }
26
+ /**
27
+ * Creates a manager from CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY and
28
+ * CLOUDINARY_API_SECRET.
29
+ */
30
+ static fromEnv(env = process.env, options = {}) {
31
+ const cloudName = env.CLOUDINARY_CLOUD_NAME;
32
+ const apiKey = env.CLOUDINARY_API_KEY;
33
+ const apiSecret = env.CLOUDINARY_API_SECRET;
34
+ if (!cloudName) {
35
+ throw new HttpError(500, 'CLOUDINARY_CLOUD_NAME environment variable is required');
36
+ }
37
+ if (!apiKey) {
38
+ throw new HttpError(500, 'CLOUDINARY_API_KEY environment variable is required');
39
+ }
40
+ if (!apiSecret) {
41
+ throw new HttpError(500, 'CLOUDINARY_API_SECRET environment variable is required');
42
+ }
43
+ return new CloudinaryManager({
44
+ cloudName,
45
+ apiKey,
46
+ apiSecret,
47
+ ...options,
48
+ });
49
+ }
50
+ }
51
+ //# sourceMappingURL=cloudinary-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudinary-manager.js","sourceRoot":"","sources":["../src/cloudinary-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAInC,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAClD,OAAO,EA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EAAE,CAAC;YACf,MAAM,IAAI,SAAS,CAAC,GAAG,EAAE,wDAAwD,CAAC,CAAA;QACpF,CAAC;QAED,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,IAAI,SAAS,CAAC,GAAG,EAAE,qDAAqD,CAAC,CAAA;QACjF,CAAC;QAED,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,MAAM,IAAI,SAAS,CAAC,GAAG,EAAE,wDAAwD,CAAC,CAAA;QACpF,CAAC;QAED,OAAO,IAAI,iBAAiB,CAAC;YAC3B,SAAS;YACT,MAAM;YACN,SAAS;YACT,GAAG,OAAO;SACX,CAAC,CAAA;IACJ,CAAC;CACF"}
@@ -0,0 +1,13 @@
1
+ import { type UploadedFile, type UploadFileOptions, type UploadFilesManyOptions } from './types';
2
+ import type { CloudinaryCredentials, CloudinaryManagerOptions, DestroyManyOptions } from '../types/config';
3
+ export declare class FileManager {
4
+ private readonly credentials;
5
+ private readonly maxFileSize;
6
+ private readonly allowedTypes;
7
+ constructor(credentials: CloudinaryCredentials, options?: CloudinaryManagerOptions['files']);
8
+ uploadFile(file: Blob, folder: string, options?: UploadFileOptions): Promise<UploadedFile>;
9
+ uploadFilesMany(files: readonly Blob[], folder: string, options?: UploadFilesManyOptions): Promise<UploadedFile[]>;
10
+ destroyFile(publicId: string): Promise<void>;
11
+ destroyFilesMany(publicIds: readonly string[], options?: DestroyManyOptions): Promise<void>;
12
+ private validateFile;
13
+ }
@@ -0,0 +1,77 @@
1
+ import { HttpError } from 'lykosjs';
2
+ import { v2 as cloudinary } from 'cloudinary';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { normalizeFolder } from '../shared/normalize-folder';
5
+ import { isValidPublicId } from '../shared/public-id';
6
+ import { validateBlob } from '../shared/validate-blob';
7
+ import { uploadBlobStream } from '../shared/upload-stream';
8
+ import { uploadBatch } from '../shared/upload-batch';
9
+ import { destroyBatch } from '../shared/destroy-batch';
10
+ import { assertConcurrency } from '../shared/concurrency';
11
+ import { detectFileType } from './file-type';
12
+ import { FILE_EXTENSIONS, } from './types';
13
+ import { DEFAULT_ALLOWED_FILE_TYPES, DEFAULT_MAX_FILE_BYTES, DEFAULT_UPLOAD_CONCURRENCY, DEFAULT_DESTROY_CONCURRENCY, } from '../types/config';
14
+ export class FileManager {
15
+ credentials;
16
+ maxFileSize;
17
+ allowedTypes;
18
+ constructor(credentials, options = {}) {
19
+ this.credentials = credentials;
20
+ this.maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_BYTES;
21
+ this.allowedTypes = options.allowedTypes ?? DEFAULT_ALLOWED_FILE_TYPES;
22
+ }
23
+ async uploadFile(file, folder, options = {}) {
24
+ const targetFolder = normalizeFolder(folder);
25
+ if (options.publicId !== undefined && !isValidPublicId(options.publicId)) {
26
+ throw new HttpError(400, 'Invalid public ID');
27
+ }
28
+ const mimeType = await this.validateFile(file, options);
29
+ const result = await uploadBlobStream(file, this.credentials, {
30
+ folder: targetFolder,
31
+ resource_type: 'raw',
32
+ public_id: options.publicId ?? `${randomUUID()}.${FILE_EXTENSIONS[mimeType]}`,
33
+ ...(options.tags?.length ? { tags: options.tags } : {}),
34
+ });
35
+ return {
36
+ url: result.secure_url,
37
+ publicId: result.public_id,
38
+ bytes: result.bytes,
39
+ mimeType,
40
+ };
41
+ }
42
+ async uploadFilesMany(files, folder, options = {}) {
43
+ const { concurrency = DEFAULT_UPLOAD_CONCURRENCY, ...uploadOptions } = options;
44
+ assertConcurrency(concurrency);
45
+ normalizeFolder(folder);
46
+ return uploadBatch(files, concurrency, (file) => this.validateFile(file, uploadOptions), (file) => this.uploadFile(file, folder, uploadOptions), (publicId) => this.destroyFile(publicId));
47
+ }
48
+ async destroyFile(publicId) {
49
+ if (typeof publicId !== 'string' || !publicId.trim()) {
50
+ throw new HttpError(400, 'Public ID is required');
51
+ }
52
+ const destroyOptions = {
53
+ ...this.credentials,
54
+ resource_type: 'raw',
55
+ invalidate: true,
56
+ };
57
+ const result = await cloudinary.uploader.destroy(publicId, destroyOptions);
58
+ if (result.result === 'not found') {
59
+ throw new HttpError(404, 'File not found');
60
+ }
61
+ if (result.result !== 'ok') {
62
+ throw new HttpError(502, 'Failed to destroy file');
63
+ }
64
+ }
65
+ async destroyFilesMany(publicIds, options = {}) {
66
+ await destroyBatch(publicIds, options.concurrency ?? DEFAULT_DESTROY_CONCURRENCY, (publicId) => this.destroyFile(publicId));
67
+ }
68
+ validateFile(file, options) {
69
+ return validateBlob(file, {
70
+ maxFileSize: options.maxFileSize ?? this.maxFileSize,
71
+ allowedTypes: options.allowedTypes ?? this.allowedTypes,
72
+ detect: detectFileType,
73
+ label: 'file',
74
+ });
75
+ }
76
+ }
77
+ //# sourceMappingURL=file-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-manager.js","sourceRoot":"","sources":["../../src/files/file-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACnC,OAAO,EAAE,EAAE,IAAI,UAAU,EAAE,MAAM,YAAY,CAAA;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAA;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAA;AAEzD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAE5C,OAAO,EACL,eAAe,GAKhB,MAAM,SAAS,CAAA;AAEhB,OAAO,EACL,0BAA0B,EAC1B,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,GAC5B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wBAAwB,CAAC,CAAA;QACpD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,gBAAgB,CACpB,SAA4B,EAC5B,OAAO,GAAuB,EAAE;QAEhC,MAAM,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,WAAW,IAAI,2BAA2B,EAAE,CAAC,QAAQ,EAAE,EAAE,CAC7F,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAC3B,CAAA;IACH,CAAC;IAEO,YAAY,CAAC,IAAU,EAAE,OAA0B;QACzD,OAAO,YAAY,CAAC,IAAI,EAAE;YACxB,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,IAAI,CAAC,WAAW;YACpD,YAAY,EAAE,OAAO,CAAC,YAAY,IAAI,IAAI,CAAC,YAAY;YACvD,MAAM,EAAE,cAAc;YACtB,KAAK,EAAE,MAAM;SACd,CAAC,CAAA;IACJ,CAAC;CACF"}
@@ -0,0 +1,3 @@
1
+ import type { FileMimeType } from './types';
2
+ /** Detects the real file type from the first bytes. ZIP also covers docx/xlsx/pptx. */
3
+ export declare function detectFileType(bytes: Uint8Array): FileMimeType | null;
@@ -0,0 +1,10 @@
1
+ import { startsWith } from '../shared/byte-utils';
2
+ /** Detects the real file type from the first bytes. ZIP also covers docx/xlsx/pptx. */
3
+ export function detectFileType(bytes) {
4
+ if (startsWith(bytes, [0x25, 0x50, 0x44, 0x46, 0x2d]))
5
+ return 'application/pdf';
6
+ if (startsWith(bytes, [0x50, 0x4b, 0x03, 0x04]))
7
+ return 'application/zip';
8
+ return null;
9
+ }
10
+ //# sourceMappingURL=file-type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-type.js","sourceRoot":"","sources":["../../src/files/file-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAA;AAGjD,uFAAuF;AACvF,MAAM,UAAU,cAAc,CAAC,KAAiB;IAC/C,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACpD,OAAO,iBAAiB,CAAA;IACzB,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QAAE,OAAO,iBAAiB,CAAA;IACzE,OAAO,IAAI,CAAA;AACZ,CAAC"}
@@ -0,0 +1,17 @@
1
+ export type FileMimeType = 'application/pdf' | 'application/zip';
2
+ export interface UploadedFile {
3
+ url: string;
4
+ publicId: string;
5
+ bytes: number;
6
+ mimeType: FileMimeType;
7
+ }
8
+ export interface UploadFileOptions {
9
+ publicId?: string;
10
+ tags?: string[];
11
+ maxFileSize?: number;
12
+ allowedTypes?: readonly FileMimeType[];
13
+ }
14
+ export interface UploadFilesManyOptions extends Omit<UploadFileOptions, 'publicId'> {
15
+ concurrency?: number;
16
+ }
17
+ export declare const FILE_EXTENSIONS: Record<FileMimeType, string>;
@@ -0,0 +1,5 @@
1
+ export const FILE_EXTENSIONS = {
2
+ 'application/pdf': 'pdf',
3
+ 'application/zip': 'zip'
4
+ };
5
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/files/types.ts"],"names":[],"mappings":"AAuBA,MAAM,CAAC,MAAM,eAAe,GAAiC;IAC5D,iBAAiB,EAAE,KAAK;IACxB,iBAAiB,EAAE,KAAK;CACxB,CAAA"}
@@ -0,0 +1,26 @@
1
+ import type { UploadedImage, UploadManyOptions, UploadOptions, UrlOptions } from './types';
2
+ import { type CloudinaryCredentials, type CloudinaryManagerOptions, type DestroyManyOptions } from '../types/config';
3
+ export declare class ImageManager {
4
+ private readonly credentials;
5
+ private readonly maxFileSize;
6
+ private readonly allowedTypes;
7
+ constructor(credentials: CloudinaryCredentials, options?: CloudinaryManagerOptions['images']);
8
+ /**
9
+ * Validates and uploads an image. Throws HttpError 400 (empty file or bad
10
+ * folder), 413 (too large), 415 (unsupported type) or 502 (Cloudinary failure).
11
+ */
12
+ uploadImage(file: Blob, folder: string, options?: UploadOptions): Promise<UploadedImage>;
13
+ /**
14
+ * Uploads several images. If any upload fails, the ones that already
15
+ * succeeded are deleted and the first error is thrown.
16
+ */
17
+ uploadImagesMany(files: readonly Blob[], folder: string, options?: UploadManyOptions): Promise<UploadedImage[]>;
18
+ /** Deletes an image. Deleting an image that does not exist is not an error. */
19
+ destroyImage(publicId: string): Promise<void>;
20
+ /** Deletes several images. Every deletion is attempted, then the first error is thrown. */
21
+ destroyImagesMany(publicIds: readonly string[], options?: DestroyManyOptions): Promise<void>;
22
+ /** Builds a delivery URL with optional resizing and format options. */
23
+ url(publicId: string, options?: UrlOptions): string;
24
+ private uploadBuffer;
25
+ private readAndValidate;
26
+ }