@puzzle-ui/media 0.0.0-stage → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +305 -2
  2. package/ai/instructions.md +70 -0
  3. package/ai/manifest.json +10 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/adapters-Bon320yF.js +481 -0
  6. package/dist/adapters-Bon320yF.js.map +1 -0
  7. package/dist/adapters-C4N2gqSK.d.cts +63 -0
  8. package/dist/adapters-DXycRsjJ.cjs +492 -0
  9. package/dist/adapters-DXycRsjJ.cjs.map +1 -0
  10. package/dist/adapters-DhPviL_C.d.ts +63 -0
  11. package/dist/browser/index.cjs +200 -0
  12. package/dist/browser/index.cjs.map +1 -0
  13. package/dist/browser/index.d.cts +89 -0
  14. package/dist/browser/index.d.ts +89 -0
  15. package/dist/browser/index.js +195 -0
  16. package/dist/browser/index.js.map +1 -0
  17. package/dist/image-processing-B1lRPpsg.cjs +444 -0
  18. package/dist/image-processing-B1lRPpsg.cjs.map +1 -0
  19. package/dist/image-processing-XkoQ8NT7.js +400 -0
  20. package/dist/image-processing-XkoQ8NT7.js.map +1 -0
  21. package/dist/image-worker.cjs +36 -0
  22. package/dist/image-worker.cjs.map +1 -0
  23. package/dist/image-worker.d.cts +1 -0
  24. package/dist/image-worker.d.ts +1 -0
  25. package/dist/image-worker.js +37 -0
  26. package/dist/image-worker.js.map +1 -0
  27. package/dist/index-8Seqy-LJ.d.ts +297 -0
  28. package/dist/index-BP0ikbAS.d.cts +297 -0
  29. package/dist/index.cjs +38 -0
  30. package/dist/index.d.cts +4 -0
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.js +3 -0
  33. package/dist/media-validation-By6karZu.cjs +361 -0
  34. package/dist/media-validation-By6karZu.cjs.map +1 -0
  35. package/dist/media-validation-OyjGVUq3.js +230 -0
  36. package/dist/media-validation-OyjGVUq3.js.map +1 -0
  37. package/dist/media.types-dzfu0Nep.d.cts +127 -0
  38. package/dist/media.types-dzfu0Nep.d.ts +127 -0
  39. package/dist/processing.types-CPaSB88L.d.ts +238 -0
  40. package/dist/processing.types-Dd2XT8Qr.d.cts +238 -0
  41. package/dist/src-8d6s1iWH.js +1286 -0
  42. package/dist/src-8d6s1iWH.js.map +1 -0
  43. package/dist/src-C7WU7ovP.cjs +1363 -0
  44. package/dist/src-C7WU7ovP.cjs.map +1 -0
  45. package/dist/testing/adapters.cjs +4 -0
  46. package/dist/testing/adapters.d.cts +2 -0
  47. package/dist/testing/adapters.d.ts +2 -0
  48. package/dist/testing/adapters.js +1 -0
  49. package/dist/testing/index.cjs +264 -0
  50. package/dist/testing/index.cjs.map +1 -0
  51. package/dist/testing/index.d.cts +14 -0
  52. package/dist/testing/index.d.ts +14 -0
  53. package/dist/testing/index.js +260 -0
  54. package/dist/testing/index.js.map +1 -0
  55. package/package.json +84 -4
package/README.md CHANGED
@@ -1,3 +1,306 @@
1
- # Temporary Holding Version
1
+ # `@puzzle-ui/media`
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
+ Provider-neutral media contracts and services for Puzzle. The package separates
4
+ binary object storage from `@puzzle-ui/storage` record persistence and includes
5
+ opt-in browser helpers for image preparation and video preflight. It does not
6
+ include a production storage provider, queue, image codec, transcoder, HTTP API,
7
+ or UI component.
8
+
9
+ ## Availability and local workspace use
10
+
11
+ `@puzzle-ui/media` is not published to npm yet. `npm install @puzzle-ui/media`
12
+ and `bun add @puzzle-ui/media` will not work until a release is published; no
13
+ version is available to install from the registry.
14
+
15
+ To try it in this repository, add it as a workspace dependency to the consuming
16
+ app or package:
17
+
18
+ ```json
19
+ {
20
+ "dependencies": {
21
+ "@puzzle-ui/media": "workspace:*"
22
+ }
23
+ }
24
+ ```
25
+
26
+ The root Bun workspace includes `packages/*`. From the repository root, run
27
+ `bun install`, then build the package before importing its `dist` exports:
28
+
29
+ ```sh
30
+ bun run --filter @puzzle-ui/media build
31
+ ```
32
+
33
+ ## Entry points
34
+
35
+ - `@puzzle-ui/media`: media records, validation, object/processing contracts,
36
+ asset/folder services, and lifecycle/cleanup helpers.
37
+ - `@puzzle-ui/media/browser`: browser-only image crop/resize/variants and local
38
+ video metadata/poster utilities. Import is SSR-safe; call only in a browser.
39
+ - `@puzzle-ui/media/testing`: in-memory adapters and reusable Bun conformance
40
+ runners.
41
+ - `@puzzle-ui/media/testing/adapters`: in-memory adapters without the Bun test
42
+ runner dependency, for Node.js and other test environments. The adapters are
43
+ test tools, not production storage/queue providers.
44
+
45
+ ## Metadata and binary storage
46
+
47
+ Use the declared `StorageAdapter` public API for records and a separate
48
+ `MediaObjectStorageAdapter` for file bytes. A storage provider must report
49
+ `conditionalWrites` for asset/folder mutations, `cursorPagination` for lists,
50
+ and `uniqueConstraints` for folder names and idempotent usage registration.
51
+ Services fail explicitly when a required capability is unavailable.
52
+
53
+ ```ts
54
+ import {
55
+ createMediaAssetService,
56
+ createMediaFolderService,
57
+ } from "@puzzle-ui/media";
58
+
59
+ const folders = createMediaFolderService({ storage });
60
+ const assets = createMediaAssetService({ storage, objectStorage });
61
+ await Promise.all([folders.ready, assets.ready]);
62
+
63
+ const folder = await folders.create({
64
+ tenantId: "tenant-123",
65
+ name: "Campaign",
66
+ actorId: "user-456",
67
+ });
68
+
69
+ // Create assets only after the server has completed and validated the upload.
70
+ const asset = await assets.create({
71
+ tenantId: "tenant-123",
72
+ folderId: folder.id,
73
+ originalName: "hero.png",
74
+ metadata: {
75
+ kind: "image",
76
+ mimeType: "image/png",
77
+ size: verifiedObject.size,
78
+ width: 1600,
79
+ height: 900,
80
+ checksum: verifiedObject.checksum,
81
+ },
82
+ object: verifiedObject.object,
83
+ altText: "A mountain landscape",
84
+ });
85
+ ```
86
+
87
+ The asset service checks that the completed object exists in the same tenant
88
+ and that its stored MIME type and byte count match the supplied metadata. The
89
+ host server must still verify file signatures, policy, quota, tenant access,
90
+ and permissions; a client-supplied MIME type or checksum is not proof of file
91
+ contents. Object keys are internal references, not asset IDs or public URLs.
92
+ The Fullstack Media server exposes an optional `verifyUploadedContent` hook for
93
+ host byte inspection before asset creation; it does not inspect signatures when
94
+ that hook is absent. Hosts using the domain service directly must arrange their
95
+ own inspection.
96
+
97
+ Asset lists support tenant, folder, kind, status, sort, tags-any/tags-all, and
98
+ SHA-256 checksum filters. Tag/checksum filtering scans cursor pages in bounded
99
+ batches; continue with the returned cursor when a batch is exhausted.
100
+
101
+ Equal checksums do not trigger deduplication. Distinct asset IDs may refer to
102
+ identical bytes in the same or different tenants; checksum is a content
103
+ fingerprint, not a unique identifier or a cross-tenant lookup key.
104
+
105
+ `MediaAsset` stores `crop`, `focalPoint`, and `hotspots` separately. Focal points
106
+ use a normalized `{ x, y }` pair compatible with the UI's
107
+ `NormalizedImagePoint`; omit `focalPoint` in an update to preserve it and pass
108
+ `null` to clear it.
109
+ Point hotspots omit both dimensions or use `width: 0, height: 0`; area hotspots
110
+ use positive dimensions within the image bounds. When projecting a point with
111
+ omitted dimensions to Pieces, supply zeros for its width and height.
112
+
113
+ Asset updates, folder moves/renames/deletes, and restores require an
114
+ `expectedRevision`. Folder deletion is restricted to empty folders. Asset
115
+ deletion is soft by default and blocked while Media-owned usages are registered.
116
+ `assets.get(tenantId, assetId)` hides soft-deleted assets; trusted server-side
117
+ administrative workflows can pass `{ includeDeleted: true }` to retrieve them
118
+ within the same tenant for restore or permanent-deletion checks.
119
+ `MediaAssetService.permanentlyDelete` only checks its own `MediaAssetUsage`
120
+ records; it cannot see CMS-owned `CmsMediaUsage` records. Apps combining Media
121
+ and CMS must also guard permanent deletion against CMS and any other
122
+ host-owned references. When using Fullstack, provide `assertCanDeleteAsset` to
123
+ `createMediaServer`; that guard runs before object deletion and should query
124
+ CMS usage data for the asset's tenant. Direct service integrations must perform
125
+ an equivalent host-side guard.
126
+
127
+ Permanent deletion requires an already soft-deleted asset with no Media-owned
128
+ usages. It conditionally removes metadata first, then attempts to delete
129
+ original and variant objects. Its result reports any object-deletion failures
130
+ so cleanup can retry those orphans. Serialize or transactionally coordinate
131
+ reference registration/removal and deletion across domains and server
132
+ processes; separate Media and CMS usage collections do not close that race.
133
+
134
+ ## Object-storage adapter contract
135
+
136
+ Implement `MediaObjectStorageAdapter` on the server. It covers single and
137
+ multipart upload intents, per-part targets, completion, abort, object metadata,
138
+ short-lived read targets, deletion, object listing, and expired-upload listing.
139
+ Completion should be idempotent and verify the actual uploaded size and any
140
+ requested checksum. Provider keys and multipart IDs must remain server-side.
141
+
142
+ Upload/read targets and their headers are short-lived bearer credentials:
143
+ return them only to the intended caller, never persist or log them, and enforce
144
+ expiration, allowed size/type, tenant ownership, and authorization in the host
145
+ server. The contract does not itself issue HTTP requests or validate file
146
+ signatures.
147
+
148
+ ```ts
149
+ import type { MediaObjectStorageAdapter } from "@puzzle-ui/media";
150
+
151
+ const objectStorage: MediaObjectStorageAdapter = createConfiguredObjectStore();
152
+ ```
153
+
154
+ ## Asset and folder services
155
+
156
+ `createMediaAssetService` provides tenant-scoped create/get/list/update,
157
+ revision-checked soft-delete/restore/permanent-delete, usage registration, and
158
+ cleanup helpers. `createMediaFolderService` provides tenant-scoped create/list,
159
+ rename/move, cycle checks, and restricted soft-delete/restore. Both register
160
+ their collections through `StorageAdapter.registerCollection`.
161
+
162
+ Soft-deleted folder names remain reserved by the portable sibling-name unique
163
+ constraint until `folders.permanentlyDelete(...)` removes the empty folder.
164
+
165
+ `cleanupExpiredMediaUploads` aborts expired upload sessions. The
166
+ `cleanupOrphanedMediaObjects` helper deletes only objects older than the
167
+ provided cutoff that are not referenced by any stored asset or variant; use a
168
+ conservative cutoff to avoid racing active uploads or processing jobs. Run
169
+ cleanup with server-only credentials and suitable operational monitoring.
170
+
171
+ ## Audit storage
172
+
173
+ `createMediaAuditService` stores sanitized audit events using the metadata
174
+ adapter and requires an explicit policy for `audit:write` and `audit:read`.
175
+ Use a trusted service actor for writes and resolve the tenant and reader on the
176
+ server for queries. Records contain actor, tenant, resource, action, result,
177
+ and timestamp—not request bodies, signed targets, headers, or object keys.
178
+ The host controls retention and authorization, including whether a reader may
179
+ access a tenant. The list supports resource/result filters and cursor paging,
180
+ ordered by ID rather than time; scan all pages and restart scans to find
181
+ later inserts that sort before an earlier cursor.
182
+
183
+ The Fullstack Media server's optional `onAudit` callback can write to this
184
+ service. It is not atomic with the media mutation; failed writes are reported
185
+ but the mutation may already have committed. Direct domain/worker operations
186
+ also require explicit audit calls. Use a host-owned transactional integration
187
+ when atomic mutation and audit persistence are required.
188
+
189
+ ## Processing contracts and service
190
+
191
+ `MediaProcessor` and `VideoTranscoder` are injected provider/worker interfaces.
192
+ `MediaProcessingQueueAdapter` defines idempotent enqueue, leased claims,
193
+ worker-owned lease renewal, progress, retryable failure, dead-letter,
194
+ completion, and cancellation semantics. `createMediaProcessingService` updates the asset lifecycle and
195
+ checks each processor-produced object against object storage before marking a
196
+ variant ready. It rejects missing processors and missing/mismatched output
197
+ objects; it does not pretend a no-op succeeded.
198
+
199
+ Profiles are caller-configured. Processors receive the job ID and idempotency
200
+ key so their writes can be made idempotent. The host should use a durable queue
201
+ with atomic claims and leases in production; the in-memory queue is for tests
202
+ only. Retriable failures use capped exponential backoff; permanent/exhausted
203
+ failures stay visible on the job and asset.
204
+
205
+ ## Browser utilities
206
+
207
+ ```ts
208
+ import {
209
+ cropImage,
210
+ createImageVariants,
211
+ readVideoMetadata,
212
+ createVideoPoster,
213
+ resizeImage,
214
+ } from "@puzzle-ui/media/browser";
215
+
216
+ const cropped = await cropImage(file, {
217
+ crop: { x: 0.1, y: 0.1, width: 0.8, height: 0.8 },
218
+ maxWidth: 1200,
219
+ format: "image/webp",
220
+ signal: abortController.signal,
221
+ });
222
+
223
+ const resized = await resizeImage(file, {
224
+ maxWidth: 1600,
225
+ maxHeight: 1200,
226
+ format: "image/webp",
227
+ fallbackFormat: "image/png",
228
+ quality: 0.84,
229
+ signal: abortController.signal,
230
+ });
231
+
232
+ const variants = await createImageVariants(file, {
233
+ retainOriginal: true,
234
+ profiles: [
235
+ { name: "mobile", maxWidth: 480 },
236
+ { name: "desktop", maxWidth: 1600, format: "image/webp" },
237
+ ],
238
+ });
239
+
240
+ const video = await readVideoMetadata(videoFile, {
241
+ maxSizeBytes: 500_000_000,
242
+ maxDurationSeconds: 900,
243
+ });
244
+ const poster = await createVideoPoster(videoFile, {
245
+ maxWidth: 640,
246
+ maxHeight: 360,
247
+ signal: abortController.signal,
248
+ });
249
+ ```
250
+
251
+ Image dimensions are reduced without upscaling and aspect ratio is preserved.
252
+ `cropImage` accepts normalized coordinates relative to the original, oriented
253
+ image, including values returned by `ImageCropper`. Its optional `maxWidth` and
254
+ `maxHeight` constrain the cropped output; without them it uses the cropped
255
+ source dimensions. Fractional dimensions are rounded down and crops covering
256
+ less than one source pixel in either dimension are rejected. Like `resizeImage`,
257
+ it returns an encoded Blob, original and output dimensions, actual format,
258
+ fallback status, and a suggested filename. It does not modify the source.
259
+ Re-encoding uses browser canvas decoding (including browser EXIF orientation
260
+ handling where supported), removes original metadata, and preserves alpha when
261
+ the selected/fallback format does. Browser codecs differ; the actual output
262
+ format and `usedFallbackFormat` are returned. The original is returned only
263
+ when `retainOriginal` is explicitly true and may contain EXIF/GPS data.
264
+
265
+ When using the ESM build and module workers, `OffscreenCanvas`, and
266
+ `createImageBitmap` are available, image preparation runs in a dedicated
267
+ worker. The CommonJS build processes images on the current thread. Aborting
268
+ terminates an active worker.
269
+ If the worker cannot start or the image cannot be decoded in it, processing
270
+ falls back to the current thread using `OffscreenCanvas` or an HTML canvas.
271
+ Worker startup failures are reported through the console; failures after
272
+ startup are surfaced as errors. Configure the application's `worker-src`
273
+ Content Security Policy and bundler to allow the emitted same-origin worker
274
+ asset and its imports. Verify this in the deployed application; a blocked or
275
+ unavailable worker means image preparation may run on the UI thread.
276
+ Video helpers read metadata and extract a local poster frame only; they do not transcode.
277
+ Browser decoding, codec support, and poster frame extraction depend on the
278
+ user's browser and the input file.
279
+
280
+ All browser APIs are accessed when a helper is called, not at module import, so
281
+ the subpath can be imported in SSR code without touching `window` or `document`.
282
+
283
+ ## Testing adapters
284
+
285
+ The testing export contains:
286
+
287
+ - `InMemoryMediaObjectStorageAdapter`
288
+ - `InMemoryMediaProcessingQueueAdapter`
289
+ - `runMediaObjectStorageConformance`
290
+ - `runMediaProcessingQueueConformance`
291
+
292
+ Conformance fixtures supply isolated adapters and the upload operation needed
293
+ to exercise direct-upload targets. `bun run test:browser` builds the package and
294
+ uses the repository's existing Playwright tooling to exercise the browser
295
+ subpath in Chromium. It verifies image output bounds, original retention, video
296
+ metadata/poster extraction from a finite-duration WebM fixture, and object-URL
297
+ cleanup on unsupported input, corrupt media, and abort. Browser tests require
298
+ Playwright Chromium to be installed.
299
+ Run the package checks:
300
+
301
+ ```sh
302
+ bun run build
303
+ bun run typecheck
304
+ bun run test
305
+ bun run test:browser
306
+ ```
@@ -0,0 +1,70 @@
1
+ # `@puzzle-ui/media`
2
+
3
+ Use Media for provider-neutral asset/folder/variant metadata, object-storage
4
+ ports, image/video processing contracts, metadata services, and optional
5
+ browser utilities. It is not a React component library, HTTP API, database
6
+ adapter, or storage provider.
7
+
8
+ `@puzzle-ui/media` is not published to npm yet. Do not instruct users to install
9
+ it from npm or Bun's registry before a release. For local use in this monorepo,
10
+ add `"@puzzle-ui/media": "workspace:*"` to the consuming package's dependencies,
11
+ run `bun install` from the repository root, and build it with
12
+ `bun run --filter @puzzle-ui/media build` before consuming its `dist` exports.
13
+
14
+ ```ts
15
+ import {
16
+ createMediaAssetService,
17
+ createMediaFolderService,
18
+ } from "@puzzle-ui/media";
19
+ import { cropImage, resizeImage, createVideoPoster } from "@puzzle-ui/media/browser";
20
+ ```
21
+
22
+ The root entry uses the public `@puzzle-ui/storage` `StorageAdapter` only for
23
+ metadata. Binary files belong to a separate `MediaObjectStorageAdapter`.
24
+ Services require tenant scope, conditional writes for mutations, cursor
25
+ pagination for lists, and unique constraints for folder/usage guarantees. Applications
26
+ must authorize every operation on their server; IDs and browser state do not
27
+ grant access.
28
+
29
+ `createMediaAuditService` persists sanitized events and requires a host policy
30
+ for tenant-scoped `audit:read` and `audit:write`. Use a trusted service actor
31
+ for writes; never record signed targets, credentials, or request bodies. Its
32
+ ID-ordered cursor scans are not chronological and audit writes are not atomic
33
+ with media mutations. Fullstack's optional `onAudit` can feed it; direct
34
+ domain and worker operations require separate host auditing.
35
+
36
+ Checksums are fingerprints, not unique IDs: duplicate content remains distinct
37
+ assets, including within a tenant. `MediaAsset.focalPoint` is a separate
38
+ nullable normalized `{ x, y }` point; omit it in updates to preserve the value
39
+ and pass `null` to clear it.
40
+ Point hotspots omit both dimensions or use two zero dimensions; area hotspots
41
+ use positive dimensions. Supply zero dimensions when projecting a point
42
+ without dimensions into a Pieces media component.
43
+
44
+ `MediaAssetService` sees only its own `MediaAssetUsage` rows, not CMS
45
+ `CmsMediaUsage`. For apps combining Media and CMS, use Fullstack's host-provided
46
+ `assertCanDeleteAsset` guard (or an equivalent server-side guard) to check CMS
47
+ and other host references before permanent deletion. Coordinate reference
48
+ changes and deletion across domains/processes; the separate collections do not
49
+ provide a shared transaction. `assets.get` hides soft-deleted assets by default;
50
+ only trusted, authorized server-side workflows should use
51
+ `{ includeDeleted: true }` to retrieve them within the tenant.
52
+
53
+ Browser helpers defer browser API access until invoked, so importing the
54
+ subpath during SSR is safe. Call them only in a browser and pass an
55
+ `AbortSignal` for cancellable work. Use `cropImage` to export normalized
56
+ `ImageCropper` values relative to the original, oriented image; it optionally
57
+ limits output dimensions without upscaling. Image variants are re-encoded to strip
58
+ metadata; retaining an original is explicit and may retain EXIF/GPS data.
59
+ The ESM build uses a module worker for image preparation when supported,
60
+ falling back to the current thread when worker startup or decoding is
61
+ unavailable; CommonJS always uses the current thread. Configure CSP and
62
+ bundler handling for the emitted worker; abort terminates it.
63
+ Video helpers read local metadata and create a poster only. They do not
64
+ transcode video.
65
+
66
+ For in-memory test adapters in Node.js, import
67
+ `@puzzle-ui/media/testing/adapters`. The `@puzzle-ui/media/testing` entry also
68
+ exports conformance runners and requires Bun's test runtime.
69
+
70
+ See the package [README](../README.md) for adapter lifecycles and API details.
@@ -0,0 +1,10 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "packageName": "@puzzle-ui/media",
4
+ "instructionVersion": 1,
5
+ "contentFile": "instructions.md",
6
+ "instructionDependencies": [
7
+ "@puzzle-ui/storage"
8
+ ],
9
+ "documentationUrl": "https://puzzle-ui.com/docs/media"
10
+ }
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sjoerd van Den Berg
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 EVENT 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.