@murumets-ee/media 0.71.0 → 0.72.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.
- package/dist/admin.d.mts.map +1 -1
- package/dist/admin.mjs +1 -1
- package/dist/backfill-D2Ubblh3.mjs +2 -0
- package/dist/backfill-D2Ubblh3.mjs.map +1 -0
- package/dist/backfill-trigger-BFL1L7_j.mjs +2 -0
- package/dist/backfill-trigger-BFL1L7_j.mjs.map +1 -0
- package/dist/backlog-D-H5VUQA.mjs +2 -0
- package/dist/backlog-D-H5VUQA.mjs.map +1 -0
- package/dist/client.d.mts +55 -7
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/crop-editor.d.mts +60 -0
- package/dist/crop-editor.d.mts.map +1 -0
- package/dist/crop-editor.mjs +2 -0
- package/dist/crop-editor.mjs.map +1 -0
- package/dist/crop-rect-B-AJ2pWm.mjs +2 -0
- package/dist/crop-rect-B-AJ2pWm.mjs.map +1 -0
- package/dist/crop-rect-C-SbjoxK.d.mts +59 -0
- package/dist/crop-rect-C-SbjoxK.d.mts.map +1 -0
- package/dist/crop.d.mts +2 -1
- package/dist/crop.mjs +1 -1
- package/dist/definitions-LJpgrdxd.mjs +2 -0
- package/dist/definitions-LJpgrdxd.mjs.map +1 -0
- package/dist/deps-CzHEhyJK.mjs +2 -0
- package/dist/deps-CzHEhyJK.mjs.map +1 -0
- package/dist/derive-media-type-C38ZA_Cl.mjs +2 -0
- package/dist/derive-media-type-C38ZA_Cl.mjs.map +1 -0
- package/dist/en-A8YzaZ51.mjs +2 -0
- package/dist/en-A8YzaZ51.mjs.map +1 -0
- package/dist/entity-CsDdjKz6.mjs +2 -0
- package/dist/entity-CsDdjKz6.mjs.map +1 -0
- package/dist/et-CXvu8U31.mjs +2 -0
- package/dist/et-CXvu8U31.mjs.map +1 -0
- package/dist/generate-variants-zyPjaGcy.mjs +2 -0
- package/dist/generate-variants-zyPjaGcy.mjs.map +1 -0
- package/dist/i18n.mjs +1 -1
- package/dist/i18n.mjs.map +1 -1
- package/dist/image-styles-settings.d.mts +8 -1
- package/dist/image-styles-settings.d.mts.map +1 -1
- package/dist/image-styles-settings.mjs +1 -1
- package/dist/image-styles-settings.mjs.map +1 -1
- package/dist/image-styles.d.mts +35 -21
- package/dist/image-styles.d.mts.map +1 -1
- package/dist/image-styles.mjs +1 -2
- package/dist/image-styles.mjs.map +1 -1
- package/dist/index.d.mts +16 -42
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/media-config-DmcTxuDM.mjs +2 -0
- package/dist/media-config-DmcTxuDM.mjs.map +1 -0
- package/dist/owned-delete-Cn_KFFjS.mjs +2 -0
- package/dist/owned-delete-Cn_KFFjS.mjs.map +1 -0
- package/dist/picker.d.mts +1 -94
- package/dist/picker.d.mts.map +1 -1
- package/dist/picker.mjs +1 -2
- package/dist/picker.mjs.map +1 -1
- package/dist/plugin.d.mts +2 -1
- package/dist/plugin.d.mts.map +1 -1
- package/dist/plugin.mjs +1 -1
- package/dist/plugin.mjs.map +1 -1
- package/dist/process-image-Deedtkh4.mjs +2 -0
- package/dist/process-image-Deedtkh4.mjs.map +1 -0
- package/dist/processing.d.mts +201 -7
- package/dist/processing.d.mts.map +1 -1
- package/dist/processing.mjs +1 -1
- package/dist/public-resolver.d.mts +1 -1
- package/dist/public-resolver.mjs +1 -1
- package/dist/public-resolver.mjs.map +1 -1
- package/dist/query-client.d.mts +1 -1
- package/dist/query-client.mjs +1 -1
- package/dist/regenerate-variants-Cp3sNHkT.mjs +2 -0
- package/dist/regenerate-variants-Cp3sNHkT.mjs.map +1 -0
- package/dist/register-BSGkELj0.mjs +2 -0
- package/dist/register-BSGkELj0.mjs.map +1 -0
- package/dist/resolve-image-styles-pf7Nd3Zf.mjs +2 -0
- package/dist/resolve-image-styles-pf7Nd3Zf.mjs.map +1 -0
- package/dist/routes-BJ23Cp0g.mjs +2 -0
- package/dist/routes-BJ23Cp0g.mjs.map +1 -0
- package/dist/ru-Dj-ax8s_.mjs +2 -0
- package/dist/ru-Dj-ax8s_.mjs.map +1 -0
- package/dist/schedule-DREjg2ji.mjs +2 -0
- package/dist/schedule-DREjg2ji.mjs.map +1 -0
- package/dist/shapes-40dHtTb-.d.mts +90 -0
- package/dist/shapes-40dHtTb-.d.mts.map +1 -0
- package/dist/shapes-BlKW-0C1.mjs +2 -0
- package/dist/shapes-BlKW-0C1.mjs.map +1 -0
- package/dist/slot-CY4isqmN.mjs +2 -0
- package/dist/slot-CY4isqmN.mjs.map +1 -0
- package/dist/{types-CnORVkLZ.d.mts → types-CgkJF5dc.d.mts} +85 -5
- package/dist/types-CgkJF5dc.d.mts.map +1 -0
- package/dist/types-DwzblZfW.d.mts +97 -0
- package/dist/types-DwzblZfW.d.mts.map +1 -0
- package/dist/variant-key-Cki4n-42.mjs +2 -0
- package/dist/variant-key-Cki4n-42.mjs.map +1 -0
- package/dist/variant-plan-DV8hsMdz.mjs +2 -0
- package/dist/variant-plan-DV8hsMdz.mjs.map +1 -0
- package/package.json +21 -8
- package/dist/client-CSOH7Zun.mjs +0 -2
- package/dist/client-CSOH7Zun.mjs.map +0 -1
- package/dist/en-0YnQ_Qz-.mjs +0 -2
- package/dist/en-0YnQ_Qz-.mjs.map +0 -1
- package/dist/entity-CNxAERYG.mjs +0 -2
- package/dist/entity-CNxAERYG.mjs.map +0 -1
- package/dist/entity-DKFCdQJT.mjs +0 -2
- package/dist/entity-DKFCdQJT.mjs.map +0 -1
- package/dist/et-BIxGYWVK.mjs +0 -2
- package/dist/et-BIxGYWVK.mjs.map +0 -1
- package/dist/image-styles-settings-DEnu-V2E.mjs +0 -2
- package/dist/image-styles-settings-DEnu-V2E.mjs.map +0 -1
- package/dist/plugin-B_ZtfiAc.mjs +0 -2
- package/dist/plugin-B_ZtfiAc.mjs.map +0 -1
- package/dist/process-image-WByEHTXQ.mjs +0 -2
- package/dist/process-image-WByEHTXQ.mjs.map +0 -1
- package/dist/regenerate-variants-2Lmo5kf8.mjs +0 -2
- package/dist/regenerate-variants-2Lmo5kf8.mjs.map +0 -1
- package/dist/regenerate-variants-B9AXXN6N.mjs +0 -2
- package/dist/regenerate-variants-B9AXXN6N.mjs.map +0 -1
- package/dist/resolve-image-styles-Cakg1Qpp.mjs +0 -2
- package/dist/resolve-image-styles-Cakg1Qpp.mjs.map +0 -1
- package/dist/resolve-image-styles-iN9JbZYf.mjs +0 -2
- package/dist/resolve-image-styles-iN9JbZYf.mjs.map +0 -1
- package/dist/routes-C7Fx-055.mjs +0 -2
- package/dist/routes-C7Fx-055.mjs.map +0 -1
- package/dist/ru-UUTBfsMF.mjs +0 -2
- package/dist/ru-UUTBfsMF.mjs.map +0 -1
- package/dist/types-CnORVkLZ.d.mts.map +0 -1
- package/dist/usage-CVAqkS6h.mjs +0 -2
- package/dist/usage-CVAqkS6h.mjs.map +0 -1
- package/dist/variant-key-JBTJXPL1.mjs +0 -2
- package/dist/variant-key-JBTJXPL1.mjs.map +0 -1
- package/dist/variant-key-RKke2RfS.mjs +0 -2
- package/dist/variant-key-RKke2RfS.mjs.map +0 -1
package/dist/processing.d.mts
CHANGED
|
@@ -1,5 +1,89 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as ImageVocabulary, i as ImageStyle, n as ImageFormat, r as ImageShape } from "./types-CgkJF5dc.mjs";
|
|
2
|
+
import { a as ResolvedShape, c as VariantConfig, i as NATURAL_SHAPE, l as buildVariantConfig, n as DEFAULT_IMAGE_SHAPES, o as ShapeAlias, r as DEFAULT_IMAGE_VOCABULARY, s as UnmappedStyle, t as DEFAULT_IMAGE_LADDER, u as resolveStyleName } from "./shapes-40dHtTb-.mjs";
|
|
2
3
|
|
|
4
|
+
//#region src/variant-plan.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* The hard ceiling on variants per image, whatever the configuration says.
|
|
7
|
+
*
|
|
8
|
+
* The vocabulary is bounded (`MAX_SHAPES` × `MAX_LADDER_RUNGS`), but legacy
|
|
9
|
+
* styles predate those bounds and each becomes a shape, so the product is not.
|
|
10
|
+
* Every variant is a decode-extract-resize-encode on the generating process, so
|
|
11
|
+
* this is the cap that keeps one upload from being an amplification vector. The
|
|
12
|
+
* seeded vocabulary plans at most 30 (four shapes and `natural`, six rungs).
|
|
13
|
+
* What it drops is COUNTED in {@link VariantPlan.dropped}, never silent.
|
|
14
|
+
*/
|
|
15
|
+
declare const MAX_VARIANTS_PER_IMAGE = 64;
|
|
16
|
+
/** The region `extract()` takes, in integral pixels of the image as drawn. */
|
|
17
|
+
interface PixelRect {
|
|
18
|
+
readonly left: number;
|
|
19
|
+
readonly top: number;
|
|
20
|
+
readonly width: number;
|
|
21
|
+
readonly height: number;
|
|
22
|
+
}
|
|
23
|
+
/** One variant to generate. */
|
|
24
|
+
interface PlannedVariant {
|
|
25
|
+
readonly shape: string;
|
|
26
|
+
/** The width to ask sharp for. Never above what {@link extract} supplies. */
|
|
27
|
+
readonly width: number;
|
|
28
|
+
/** The height to ask sharp for — derived from the shape's ratio. */
|
|
29
|
+
readonly height: number;
|
|
30
|
+
readonly extract: PixelRect;
|
|
31
|
+
readonly format: ImageFormat;
|
|
32
|
+
readonly quality: number;
|
|
33
|
+
/** {@link variantFingerprint} of this variant's recipe — goes into its key. */
|
|
34
|
+
readonly fingerprint: string;
|
|
35
|
+
}
|
|
36
|
+
interface VariantPlan {
|
|
37
|
+
readonly variants: readonly PlannedVariant[];
|
|
38
|
+
/** How many variants {@link MAX_VARIANTS_PER_IMAGE} cut off. */
|
|
39
|
+
readonly dropped: number;
|
|
40
|
+
}
|
|
41
|
+
/** What the plan needs from the media row. Untrusted — both are read leniently. */
|
|
42
|
+
interface VariantPlanInput {
|
|
43
|
+
readonly focalPoint?: unknown;
|
|
44
|
+
readonly crops?: unknown;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Plan every variant a photograph of `source` dimensions gets under `config`.
|
|
48
|
+
*
|
|
49
|
+
* `source` must be the DRAWN size (post-EXIF orientation) of the actual file —
|
|
50
|
+
* `getImageDimensions`, not the row's client-measured `width`/`height` — since
|
|
51
|
+
* the regions are cut from the file.
|
|
52
|
+
*/
|
|
53
|
+
declare function planVariants(source: {
|
|
54
|
+
readonly width: number;
|
|
55
|
+
readonly height: number;
|
|
56
|
+
}, config: VariantConfig, input: VariantPlanInput): VariantPlan;
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/jobs/variant-state.d.ts
|
|
59
|
+
/** One generated (shape × rung) variant, as recorded. */
|
|
60
|
+
interface StoredShapedVariant {
|
|
61
|
+
readonly shape: string;
|
|
62
|
+
/** The rung the variant was PLANNED at — part of its key. */
|
|
63
|
+
readonly rung: number;
|
|
64
|
+
/** What the file actually is (F003). */
|
|
65
|
+
readonly width: number;
|
|
66
|
+
readonly height: number;
|
|
67
|
+
readonly format: string;
|
|
68
|
+
readonly key: string;
|
|
69
|
+
}
|
|
70
|
+
/** Everything the original's metadata says about its variants. */
|
|
71
|
+
interface VariantState {
|
|
72
|
+
/** Legacy style name → key (`metadata.variants`). */
|
|
73
|
+
readonly legacy: ReadonlyMap<string, string>;
|
|
74
|
+
/** Legacy style name → the {@link legacyRecipe} its file was made with. */
|
|
75
|
+
readonly legacyRecipes: ReadonlyMap<string, string>;
|
|
76
|
+
readonly shaped: readonly StoredShapedVariant[];
|
|
77
|
+
/** Keys a failed pass uploaded that no reader should resolve yet — see the module doc. */
|
|
78
|
+
readonly unconfirmed: readonly string[];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Read the variant state off an original's metadata. Lenient: the column is
|
|
82
|
+
* caller-shaped JSON, so a malformed entry is dropped rather than trusted, and
|
|
83
|
+
* a file that predates this module reads as its legacy map alone.
|
|
84
|
+
*/
|
|
85
|
+
declare function readVariantState(metadata: unknown): VariantState;
|
|
86
|
+
//#endregion
|
|
3
87
|
//#region src/process-image.d.ts
|
|
4
88
|
/** Result of processing an image through Sharp */
|
|
5
89
|
interface ProcessedImage {
|
|
@@ -31,6 +115,45 @@ declare function isProcessableImage(mimeType: string): boolean;
|
|
|
31
115
|
* @returns Metadata (width/height) and variant buffers
|
|
32
116
|
*/
|
|
33
117
|
declare function processImage(buffer: Buffer, styles: Record<string, ImageStyle>): Promise<ProcessedImage>;
|
|
118
|
+
/** One generated (shape × rung) variant. */
|
|
119
|
+
interface ShapedVariant extends ProcessedVariant {
|
|
120
|
+
readonly shape: string;
|
|
121
|
+
/** The width the plan ASKED for. It names the key; it is not a claim about the file. */
|
|
122
|
+
readonly plannedWidth: number;
|
|
123
|
+
/** Goes into the key — see `deriveShapedVariantKey`. */
|
|
124
|
+
readonly fingerprint: string;
|
|
125
|
+
}
|
|
126
|
+
/** A photograph's shaped variants. */
|
|
127
|
+
interface ShapedImage {
|
|
128
|
+
/** The image as a browser draws it (post-EXIF orientation). */
|
|
129
|
+
width: number;
|
|
130
|
+
height: number;
|
|
131
|
+
variants: ShapedVariant[];
|
|
132
|
+
/** Variants the per-image cap cut off (`MAX_VARIANTS_PER_IMAGE`) — for the caller to log. */
|
|
133
|
+
dropped: number;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Generate every (shape × rung) variant `config` calls for (images D003).
|
|
137
|
+
*
|
|
138
|
+
* The region comes from {@link planVariants} — `crops[shape]`, else the focal
|
|
139
|
+
* point's window for that ratio, else the whole image — and sharp runs
|
|
140
|
+
* `rotate() → extract() → resize()` in that order:
|
|
141
|
+
*
|
|
142
|
+
* - `rotate()` first, so `extract()` works in the coordinates a browser DRAWS
|
|
143
|
+
* (measured, R013). The crop and the focal point are stored in that space.
|
|
144
|
+
* - `extract()` BEFORE `resize()` — what sharp documents for pre-resize
|
|
145
|
+
* extraction, and the only way to express a rect at all: `resize({position})`
|
|
146
|
+
* takes nine gravities and two strategies and throws on coordinates (C5).
|
|
147
|
+
*
|
|
148
|
+
* 🔴 The variant records `info.width`/`info.height` — what sharp RETURNED —
|
|
149
|
+
* never the rung it asked for (F003). `withoutEnlargement` silently returns a
|
|
150
|
+
* smaller file than requested, and a `640w` descriptor on a 400px file makes a
|
|
151
|
+
* browser's `srcset` choice wrong in the direction it never corrects (R007).
|
|
152
|
+
* The plan never asks for more than the region supplies, so today the two
|
|
153
|
+
* agree; recording the real one is what keeps them agreeing when they don't.
|
|
154
|
+
*/
|
|
155
|
+
declare function generateShapedVariants(buffer: Buffer, config: VariantConfig, input: VariantPlanInput): Promise<ShapedImage>;
|
|
156
|
+
declare function renderPlannedVariant(buffer: Buffer, planned: PlannedVariant): Promise<ShapedVariant>;
|
|
34
157
|
/**
|
|
35
158
|
* Extract only image dimensions (no variant generation).
|
|
36
159
|
* Useful for getting width/height when styles are empty.
|
|
@@ -42,17 +165,46 @@ declare function getImageDimensions(buffer: Buffer): Promise<{
|
|
|
42
165
|
//#endregion
|
|
43
166
|
//#region src/variant-key.d.ts
|
|
44
167
|
/**
|
|
45
|
-
* Variant key derivation
|
|
168
|
+
* Variant key derivation — where a generated variant lives in storage.
|
|
46
169
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
170
|
+
* Two key shapes coexist (images D005):
|
|
171
|
+
*
|
|
172
|
+
* **Legacy** — one file per image STYLE, keyed by the style name alone:
|
|
49
173
|
*
|
|
50
|
-
* Convention:
|
|
51
174
|
* Original: uploads/2026/02/{uuid}/photo.jpg
|
|
52
175
|
* Variant: uploads/2026/02/{uuid}/thumbnail_photo.webp
|
|
176
|
+
*
|
|
177
|
+
* Sound only while nothing about a variant can change. It stays exactly as it
|
|
178
|
+
* is: every row that has not been regenerated under the shape model still has
|
|
179
|
+
* its files there, and ticketing derives its thumbnails with it.
|
|
180
|
+
*
|
|
181
|
+
* **Shaped** — one file per (shape × rung), carrying a FINGERPRINT of the
|
|
182
|
+
* recipe that produced it:
|
|
183
|
+
*
|
|
184
|
+
* Variant: uploads/2026/02/{uuid}/variants/photo_portrait_640w_1k2x9a0.webp
|
|
185
|
+
*
|
|
186
|
+
* The moment an editor can re-crop, a name-only key serves different bytes at
|
|
187
|
+
* the same URL, and every cache in front of it — the CDN, the browser, the
|
|
188
|
+
* content-api response that inlined the URL — keeps the old picture. So the
|
|
189
|
+
* fingerprint is of the EFFECTIVE recipe: the integral pixel rect actually
|
|
190
|
+
* extracted, the output box and the quality (R013). Same recipe → same key → a
|
|
191
|
+
* backfill that re-derives it uploads nothing. Different recipe → different key
|
|
192
|
+
* → every cache misses correctly, because it is a different file. No
|
|
193
|
+
* timestamps, no salt: determinism is what makes the backfill idempotent.
|
|
194
|
+
*
|
|
195
|
+
* ⚠️ A query-string cache-buster is not an alternative. Storage keys are what
|
|
196
|
+
* `getPublicUrls` resolves, so a query string is not part of the identity and
|
|
197
|
+
* the stale file is still the file (D005 (d); Craft's issue #3685 is that
|
|
198
|
+
* failure in a shipping product).
|
|
199
|
+
*
|
|
200
|
+
* The shaped keys live in a `variants/` directory beside the original, which is
|
|
201
|
+
* what makes the two shapes impossible to confuse: a legacy key is always a
|
|
202
|
+
* direct child of the original's directory (a style name cannot contain `/`),
|
|
203
|
+
* and both stay under the original's own prefix — which ticketing's
|
|
204
|
+
* prefix-ownership check relies on.
|
|
53
205
|
*/
|
|
54
206
|
/**
|
|
55
|
-
* Derive a variant storage key from the original key + style name.
|
|
207
|
+
* Derive a LEGACY variant storage key from the original key + style name.
|
|
56
208
|
*
|
|
57
209
|
* @param originalKey - The original file's storage key
|
|
58
210
|
* @param styleName - The image style name (e.g., 'thumbnail', 'medium')
|
|
@@ -60,6 +212,48 @@ declare function getImageDimensions(buffer: Buffer): Promise<{
|
|
|
60
212
|
* @returns The derived variant key
|
|
61
213
|
*/
|
|
62
214
|
declare function deriveVariantKey(originalKey: string, styleName: string, format?: string): string;
|
|
215
|
+
/** Everything that determines a shaped variant's bytes, apart from the source file itself. */
|
|
216
|
+
interface VariantRecipe {
|
|
217
|
+
/** The region `extract()` takes, in integral pixels of the image as DRAWN (post-EXIF). */
|
|
218
|
+
readonly extract: {
|
|
219
|
+
readonly left: number;
|
|
220
|
+
readonly top: number;
|
|
221
|
+
readonly width: number;
|
|
222
|
+
readonly height: number;
|
|
223
|
+
};
|
|
224
|
+
/** The box the region is resized to. */
|
|
225
|
+
readonly width: number;
|
|
226
|
+
readonly height: number;
|
|
227
|
+
readonly quality: number;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* A short deterministic fingerprint of a {@link VariantRecipe}: 32-bit FNV-1a
|
|
231
|
+
* over a canonical string, as 7 base-36 characters.
|
|
232
|
+
*
|
|
233
|
+
* Not cryptographic and not meant to be — it only has to differ between two
|
|
234
|
+
* recipes for the SAME file, shape and width, and nothing an attacker controls
|
|
235
|
+
* chooses between colliding recipes. Pure JS rather than `node:crypto` so the
|
|
236
|
+
* key can be derived in any realm that needs to name a variant.
|
|
237
|
+
*/
|
|
238
|
+
declare function variantFingerprint(recipe: VariantRecipe): string;
|
|
239
|
+
/** The parts a shaped variant key is made of. */
|
|
240
|
+
interface ShapedVariantKeyParts {
|
|
241
|
+
/** The shape name (`square`, `natural`, …). */
|
|
242
|
+
readonly shape: string;
|
|
243
|
+
/** The rung the variant was PLANNED at — part of the name, not a claim about the file. */
|
|
244
|
+
readonly width: number;
|
|
245
|
+
/** {@link variantFingerprint} of the recipe. */
|
|
246
|
+
readonly fingerprint: string;
|
|
247
|
+
/** Output format — the extension. */
|
|
248
|
+
readonly format: string;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Derive a SHAPED variant storage key (images D005).
|
|
252
|
+
*
|
|
253
|
+
* `photo.jpg` + `{portrait, 640, 1k2x9a0, webp}` →
|
|
254
|
+
* `<dir>/variants/photo_portrait_640w_1k2x9a0.webp`.
|
|
255
|
+
*/
|
|
256
|
+
declare function deriveShapedVariantKey(originalKey: string, parts: ShapedVariantKeyParts): string;
|
|
63
257
|
//#endregion
|
|
64
|
-
export { type ImageStyle, type ProcessedImage, type ProcessedVariant, deriveVariantKey, getImageDimensions, isProcessableImage, processImage };
|
|
258
|
+
export { DEFAULT_IMAGE_LADDER, DEFAULT_IMAGE_SHAPES, DEFAULT_IMAGE_VOCABULARY, type ImageFormat, type ImageShape, type ImageStyle, type ImageVocabulary, MAX_VARIANTS_PER_IMAGE, NATURAL_SHAPE, type PixelRect, type PlannedVariant, type ProcessedImage, type ProcessedVariant, type ResolvedShape, type ShapeAlias, type ShapedImage, type ShapedVariant, type ShapedVariantKeyParts, type StoredShapedVariant, type UnmappedStyle, type VariantConfig, type VariantPlan, type VariantPlanInput, type VariantRecipe, type VariantState, buildVariantConfig, deriveShapedVariantKey, deriveVariantKey, generateShapedVariants, getImageDimensions, isProcessableImage, planVariants, processImage, readVariantState, renderPlannedVariant, resolveStyleName, variantFingerprint };
|
|
65
259
|
//# sourceMappingURL=processing.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"processing.d.mts","names":[],"sources":["../src/process-image.ts","../src/variant-key.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"processing.d.mts","names":[],"sources":["../src/variant-plan.ts","../src/jobs/variant-state.ts","../src/process-image.ts","../src/variant-key.ts"],"mappings":";;;;AAoEsB;AAGtB;;;;;;;;AAGkB;AANI,cArBT,sBAAA;;UAGI,SAAA;EAAA,SACN,IAAA;EAAA,SACA,GAAA;EAAA,SACA,KAAA;EAAA,SACA,MAAA;AAAA;;UAIM,cAAA;EAAA,SACN,KAAA;EA8FG;EAAA,SA5FH,KAAA;EAyFU;EAAA,SAvFV,MAAA;EAAA,SACA,OAAA,EAAS,SAAA;EAAA,SACT,MAAA,EAAQ,WAAW;EAAA,SACnB,OAAA;EAsFF;EAAA,SApFE,WAAA;AAAA;AAAA,UAGM,WAAA;EAAA,SACN,QAAA,WAAmB,cAAc;;WAEjC,OAAA;AAAA;ACvBX;AAAA,UD2BiB,gBAAA;EAAA,SACN,UAAA;EAAA,SACA,KAAK;AAAA;;;;;;;;iBAqEA,YAAA,CACd,MAAA;EAAA,SAAmB,KAAA;EAAA,SAAwB,MA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,CAAQ,aAAA;;;;;iBAmDW,kBAAA,CACpB,MAAA,EAAQ,MAAA,GACP,OAAO;EAAG,KAAA;EAAe,MAAA;AAAA;;;;;;;AFjM5B;;;;AAAmC;AAGnC;;;;;;;;;AAIiB;AAIjB;;;;;;;;;;;;;;AAUsB;AAGtB;;;;;;;;AAGkB;AAIlB;;;;iBG9BgB,gBAAA,CAAiB,WAAA,UAAqB,SAAA,UAAmB,MAAA;AHqGzE;AAAA,UG5FiB,aAAA;;WAEN,OAAA;IAAA,SACE,IAAA;IAAA,SACA,GAAA;IAAA,SACA,KAAA;IAAA,SACA,MAAA;EAAA;EHuFgC;EAAA,SGpFlC,KAAA;EAAA,SACA,MAAA;EAAA,SACA,OAAA;AAAA;;;;AHqFG;;;;ACtGd;;iBE6BgB,kBAAA,CAAmB,MAAqB,EAAb,aAAa;;UAkBvC,qBAAA;EFzCN;EAAA,SE2CA,KAAA;EFzCA;EAAA,SE2CA,KAAA;EF3CG;EAAA,SE6CH,WAAA;EFzCkB;EAAA,SE2ClB,MAAA;AAAA;;;;;;;iBASK,sBAAA,CAAuB,WAAA,UAAqB,KAAA,EAAO,qBAAqB"}
|
package/dist/processing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{a as e,n as t,r as n,s as r,t as i,u as a}from"./shapes-BlKW-0C1.mjs";import{n as o,r as s,t as c}from"./variant-key-Cki4n-42.mjs";import{n as l,t as u}from"./variant-plan-DV8hsMdz.mjs";import{a as d,i as f,m as p,n as m,o as h,r as g}from"./process-image-Deedtkh4.mjs";export{i as DEFAULT_IMAGE_LADDER,t as DEFAULT_IMAGE_SHAPES,n as DEFAULT_IMAGE_VOCABULARY,u as MAX_VARIANTS_PER_IMAGE,e as NATURAL_SHAPE,r as buildVariantConfig,c as deriveShapedVariantKey,o as deriveVariantKey,m as generateShapedVariants,g as getImageDimensions,f as isProcessableImage,l as planVariants,d as processImage,p as readVariantState,h as renderPlannedVariant,a as resolveStyleName,s as variantFingerprint};
|
package/dist/public-resolver.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{s as e}from"./focal-point-BWhtJzef.mjs";import{t}from"./async-cache-C_Ycvs7b.mjs";async function n(t,n,r={}){let i=new Map,a=[...new Set(t)];if(a.length===0)return i;let o=await n.readMedia(a,r.locale);if(o.length===0)return i;let s=await n.imageStyles(),c=Object.entries(s),l=[],u=new Map;for(let e of o){if(typeof e.fileKey!=`string`||e.fileKey===``)continue;let t=c.map(([t,r])=>[t,n.variantKey(e.fileKey,t,r.format??`webp`)]);u.set(e.id,{fileKey:e.fileKey,variantKeys:t}),l.push(e.fileKey,...t.map(([,e])=>e))}let d=await n.getPublicUrls(l);for(let t of o){let n=u.get(t.id);if(!n)continue;let r=d.get(n.fileKey);if(r===void 0)continue;let a={};for(let[e,t]of n.variantKeys){let n=d.get(t);n!==void 0&&(a[e]=n)}i.set(t.id,{id:t.id,url:r,mimeType:t.mimeType??null,width:t.width??null,height:t.height??null,alt:t.alt??null,title:t.title??null,variants:a,focalPoint:e(t.focalPoint)})}return i}function r(e,t,n=Date.now){let r=null;return async()=>{let i=n();if(r&&i-r.at<t)return r.value;let a=e();return r={value:a,at:i},a.catch(()=>{r?.value===a&&(r=null)}),a}}function i(){let e=r(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{resolveImageStyles:t}=await import(`./resolve-image-styles-
|
|
1
|
+
import{s as e}from"./focal-point-BWhtJzef.mjs";import{t}from"./async-cache-C_Ycvs7b.mjs";async function n(t,n,r={}){let i=new Map,a=[...new Set(t)];if(a.length===0)return i;let o=await n.readMedia(a,r.locale);if(o.length===0)return i;let s=await n.imageStyles(),c=Object.entries(s),l=[],u=new Map;for(let e of o){if(typeof e.fileKey!=`string`||e.fileKey===``)continue;let t=c.map(([t,r])=>[t,n.variantKey(e.fileKey,t,r.format??`webp`)]);u.set(e.id,{fileKey:e.fileKey,variantKeys:t}),l.push(e.fileKey,...t.map(([,e])=>e))}let d=await n.getPublicUrls(l);for(let t of o){let n=u.get(t.id);if(!n)continue;let r=d.get(n.fileKey);if(r===void 0)continue;let a={};for(let[e,t]of n.variantKeys){let n=d.get(t);n!==void 0&&(a[e]=n)}i.set(t.id,{id:t.id,url:r,mimeType:t.mimeType??null,width:t.width??null,height:t.height??null,alt:t.alt??null,title:t.title??null,variants:a,focalPoint:e(t.focalPoint)})}return i}function r(e,t,n=Date.now){let r=null;return async()=>{let i=n();if(r&&i-r.at<t)return r.value;let a=e();return r={value:a,at:i},a.catch(()=>{r?.value===a&&(r=null)}),a}}function i(){let e=r(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{resolveImageStyles:t}=await import(`./resolve-image-styles-pf7Nd3Zf.mjs`).then(e=>e.r);return t(e())},3e4);return async(t,r={})=>{let[{createMediaQueryClient:i},{getSharedStorageClient:a},{deriveVariantKey:o}]=await Promise.all([import(`./query-client.mjs`),import(`./client.mjs`),import(`./variant-key-Cki4n-42.mjs`).then(e=>e.i)]),[s,c]=await Promise.all([i(),a()]);return n(t,{readMedia:async(e,t)=>{let{schemaRegistry:n}=await import(`@murumets-ee/db`),{getTableColumns:r,inArray:i}=await import(`drizzle-orm`),a=n.get(`media`);if(!a)return[];let o=r(a).id;return o?await s.findMany({where:i(o,[...e]),limit:e.length,...t!==void 0&&{locale:t}}):[]},getPublicUrls:e=>c.getPublicUrls(e),imageStyles:e,variantKey:o},r)}}let a;async function o(e,t){return a??=i(),s(await a(e,t))}function s(e){let t=new Map;for(let[n,r]of e)r.mimeType?.startsWith(`image/`)===!0&&t.set(n,{url:r.url,alt:r.alt,width:r.width,height:r.height});return t}export{t as cacheOnceUnlessRejected,i as createPublicMediaResolver,r as memoiseWithTtl,o as resolveCanvasImages,n as resolvePublicMedia,s as toCanvasImages};
|
|
2
2
|
//# sourceMappingURL=public-resolver.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public-resolver.mjs","names":[],"sources":["../src/public-resolver.ts"],"sourcesContent":["/**\n * The PUBLIC media resolver — media as data, for a consumer that builds its own\n * markup (plan/api phase 06, D021).\n *\n * **Why not `resolveMediaRefs`.** That helper parses `[media:type:id:variant]`\n * tags out of a text string and substitutes rendered HTML (`<img …>`, `<a\n * href=…>`) through per-type renderers. Right for a server-rendered page, wrong\n * for an HTTP API: a frontend needs `{url, width, height, alt}` so it can emit\n * its own `<picture>` with its own `srcset`, not a pre-baked tag it has to parse\n * back apart. Nothing here deprecates `resolveMediaRefs`; the API simply uses a\n * different, data-shaped path.\n *\n * **Why the entity cannot just be whitelisted.** `Media` is a real entity, but\n * it has no `url` field and cannot have one: what is stored is `fileKey`, and\n * the URL is DERIVED by the storage layer, which also decides whether it is a\n * direct public link or a time-limited signed one. Serving `media` as an\n * ordinary whitelisted entity would hand a consumer a storage key — useless for\n * rendering, and a gratuitous disclosure of storage layout.\n *\n * **This resolver can never emit a signed URL, structurally.** It asks storage\n * for PUBLIC urls (`getPublicUrls`) rather than asking for \"a url\" and\n * inspecting what came back. The second shape produces a signed URL on the\n * happy path and relies on a later check to suppress it — and a signed URL is a\n * bearer capability that outlives the permission check that minted it, on a\n * response the public role is deliberately allowed to cache. There is no branch\n * here to forget.\n *\n * D021 permits a permission-gated scoped URL for NON-public principals on\n * responses already forced to `no-store`. It is deliberately not built: no\n * consumer needs it, and an unexercised signed-URL branch is a check that\n * cannot fail. The shape is fixed so nobody re-derives it; the path waits for a\n * named consumer.\n */\n\nimport type { PgColumn } from 'drizzle-orm/pg-core'\n\nexport { cacheOnceUnlessRejected } from './async-cache.js'\n\nimport { type FocalPoint, readFocalPoint } from './crop/focal-point.js'\nimport type { ImageStyle } from './types.js'\n\n/**\n * One media item as it reaches an HTTP consumer.\n *\n * A STRUCTURAL match for `@murumets-ee/content-api`'s `MediaProjection`, not an\n * import of it: `content-api` is a leaf that this package's consumers wire into\n * by hand, exactly like `ContentApiResolution` mirrors content's\n * `ResolveResult`. The app that wires the two is where TypeScript checks they\n * agree.\n *\n * `width`/`height` ride along because a frontend needs them to reserve layout\n * space before the image loads; omitting them forces either a layout shift or a\n * second request, and the second request is the 4+N failure D001 exists to\n * prevent. `alt`/`title` are translatable on the Media entity, so this\n * projection is locale-dependent.\n */\nexport interface PublicMediaProjection {\n id: string\n url: string\n mimeType: string | null\n width: number | null\n height: number | null\n alt: string | null\n title: string | null\n /**\n * Variant URLs by image-style name, INLINED as data rather than handed over\n * as a URL pattern to interpolate.\n *\n * Two reasons, and the second is a security property. D008's rule is that a\n * client derives nothing — a consumer that constructs URLs from a pattern\n * encodes an assumption the server never published, and nothing can detect\n * when it goes stale. And a URL pattern is necessarily public-SHAPED: the\n * moment a consumer can build its own URL, the server has lost the ability to\n * decide what that consumer may address, and the \"never a signed URL\"\n * guarantee becomes unenforceable because the consumer stopped asking.\n *\n * The payload multiplier is bounded by CONFIGURATION, not by content: the set\n * of image styles is operator-chosen and neither the caller nor the editor can\n * grow it. So this needs no `?populate=`-style opt-in — unlike reference\n * expansion, where the caller could otherwise drag arbitrarily large targets\n * in. A style whose variant file is missing or not public is simply absent.\n */\n variants: Record<string, string>\n /**\n * Where the subject is, as `{ x, y }` fractions of the image (images D002).\n *\n * ALWAYS present: a row with no focal point, or one whose stored value is\n * unusable, projects as the centre, so no consumer branches on absence (D010).\n * It rides the PROJECTION and never the stored block ref — the resolver\n * substitutes fresh data on every read, so a point edited today reaches a page\n * saved last year with nothing rewritten (D007).\n */\n focalPoint: FocalPoint\n}\n\n/** The Media rows this resolver needs. Structural, so any read path can supply them. */\nexport interface PublicMediaRow {\n id: string\n fileKey: string\n mimeType?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n title?: string | null\n /** The stored `media.focalPoint` — untrusted here, read through `readFocalPoint`. */\n focalPoint?: unknown\n}\n\nexport interface PublicMediaResolverDeps {\n /**\n * Read media rows by id through a PUBLISHED-ONLY path.\n *\n * **The wiring must guarantee this** — pass a `MediaQueryClient`/`QueryClient`\n * read, never an `AdminClient` one. This module cannot enforce the choice (it\n * is injected), and an admin read would surface unpublished media on the\n * anonymous surface. Same posture, and same reason, as\n * `ContentApiResolution.resolvePath`.\n */\n readMedia: (ids: readonly string[], locale?: string) => Promise<PublicMediaRow[]>\n /**\n * Public URLs for a batch of storage keys. Anything missing or non-public is\n * ABSENT from the map — see `StorageClient.getPublicUrls`, which is the ask-\n * for-public shape this whole module rests on.\n */\n getPublicUrls: (keys: readonly string[]) => Promise<Map<string, string>>\n /** The configured image styles. Operator-owned; neither caller nor editor grows it. */\n imageStyles: () => Promise<Record<string, ImageStyle>>\n /** Derives a variant's storage key from the original's. */\n variantKey: (fileKey: string, styleName: string, format: string) => string\n}\n\n/**\n * Resolve media ids to public projections.\n *\n * Ids that do not exist, are unpublished for this caller, or whose file is not\n * public are ABSENT from the returned map — one absence, four causes, exactly\n * as phase 05's failure semantics require. The caller renders without them.\n *\n * Cost is THREE round trips at most, regardless of batch size: the image-style\n * lookup (usually served from the caller's cache — see\n * {@link createPublicMediaResolver}), one entity read, and one storage read\n * covering every original and every variant key. Emphatically NOT\n * N×(styles+1), which is what a per-item convenience method would have made it.\n * The storage read is internally chunked when the key count exceeds what one\n * query may carry, so \"one storage read\" is `ceil(keys / 500)` in the extreme.\n */\nexport async function resolvePublicMedia(\n ids: readonly string[],\n deps: PublicMediaResolverDeps,\n opts: { locale?: string | undefined } = {},\n): Promise<Map<string, PublicMediaProjection>> {\n const out = new Map<string, PublicMediaProjection>()\n const unique = [...new Set(ids)]\n if (unique.length === 0) return out\n\n const rows = await deps.readMedia(unique, opts.locale)\n if (rows.length === 0) return out\n\n const styles = await deps.imageStyles()\n const styleEntries = Object.entries(styles)\n\n // Every key we might need — originals AND variants — resolved in one storage\n // query. `getPublicUrls` returns nothing for a key that is missing or not\n // public, so a private original drops the whole item and a private variant\n // drops only that variant.\n const keysToLookUp: string[] = []\n /** Per row: its original key, plus (styleName → variant key). */\n const perRow = new Map<string, { fileKey: string; variantKeys: Array<[string, string]> }>()\n\n for (const row of rows) {\n if (typeof row.fileKey !== 'string' || row.fileKey === '') continue\n const variantKeys: Array<[string, string]> = styleEntries.map(([name, style]) => [\n name,\n deps.variantKey(row.fileKey, name, style.format ?? 'webp'),\n ])\n perRow.set(row.id, { fileKey: row.fileKey, variantKeys })\n keysToLookUp.push(row.fileKey, ...variantKeys.map(([, key]) => key))\n }\n\n const publicUrls = await deps.getPublicUrls(keysToLookUp)\n\n for (const row of rows) {\n const keys = perRow.get(row.id)\n if (!keys) continue\n const url = publicUrls.get(keys.fileKey)\n // No public URL for the ORIGINAL → the item does not resolve at all. Not\n // \"resolves with variants only\": the variants of a private original are an\n // accident of processing, not a sanctioned public view of it.\n if (url === undefined) continue\n\n const variants: Record<string, string> = {}\n for (const [styleName, variantKey] of keys.variantKeys) {\n const variantUrl = publicUrls.get(variantKey)\n if (variantUrl !== undefined) variants[styleName] = variantUrl\n }\n\n out.set(row.id, {\n id: row.id,\n url,\n mimeType: row.mimeType ?? null,\n width: row.width ?? null,\n height: row.height ?? null,\n alt: row.alt ?? null,\n title: row.title ?? null,\n variants,\n focalPoint: readFocalPoint(row.focalPoint),\n })\n }\n\n return out\n}\n\n/**\n * Wire {@link resolvePublicMedia} to the running app — the one line an app puts\n * into `createContentApiHandler({ resolveMedia })`.\n *\n * Every dependency is resolved through the PUBLIC read path:\n * `MediaQueryClient` (so the publish filter, the `view` gate and locale merging\n * all apply, and `alt`/`title` come back in the requested locale), and\n * `StorageClient.getPublicUrls` (which has no signed-URL branch at all).\n *\n * Imports are dynamic for the same reason `createMediaQueryClient`'s are: this\n * must be callable from a route module without dragging the storage/settings\n * graph into whatever bundle imports it.\n */\n/**\n * A single-value cache with a wall-clock TTL.\n *\n * Extracted rather than inlined so it can be tested with an injected clock:\n * the thing being asserted is time-dependent, and new stateful code on the\n * anonymous request path with no coverage is how a cache ends up serving the\n * wrong thing for a window nobody measured.\n *\n * Caches the PROMISE, not the settled value, so concurrent callers arriving\n * before the first load resolves share it. Caching only the value would let N\n * simultaneous requests each start their own read — the stampede this memo\n * exists to remove, on the one path where bursts are expected.\n *\n * A rejection is still NOT pinned for the TTL: the entry is dropped when the\n * promise rejects, so the next call retries rather than replaying a transient\n * outage for the rest of the window.\n */\nexport function memoiseWithTtl<T>(\n load: () => Promise<T>,\n ttlMs: number,\n now: () => number = Date.now,\n): () => Promise<T> {\n let cached: { value: Promise<T>; at: number } | null = null\n return async () => {\n const t = now()\n if (cached && t - cached.at < ttlMs) return cached.value\n const value = load()\n cached = { value, at: t }\n value.catch(() => {\n // Only clear OUR entry — a later call may already have replaced it.\n if (cached?.value === value) cached = null\n })\n return value\n }\n}\n\nexport function createPublicMediaResolver(): (\n ids: readonly string[],\n opts?: { locale?: string | undefined },\n) => Promise<Map<string, PublicMediaProjection>> {\n // The image-style set, memoised with a SHORT TTL.\n //\n // `resolveImageStyles` reads the settings DB and is documented as not cached,\n // so without this every media pass costs a settings query — and there is more\n // than one pass per response (the root rows, plus one per `?populate=`\n // expansion group), on an anonymous request path. A process-lifetime cache\n // would be wrong in the other direction: image styles are ADMIN-EDITABLE at\n // runtime, so it would serve a stale style set until redeploy.\n //\n // 30s mirrors the TTL `content-api` uses for its permission checker, and the\n // bound is the same shape: per process, so a multi-instance deployment sees a\n // new style within one TTL of each instance's own expiry. The cost of being\n // stale here is a variant URL for a style that was just added or removed —\n // the \"missing or not public\" path already handles it as an absent variant.\n const STYLES_TTL_MS = 30_000\n const imageStyles = memoiseWithTtl(async (): Promise<Record<string, ImageStyle>> => {\n const { getApp } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('./resolve-image-styles.js')\n return resolveImageStyles(getApp())\n }, STYLES_TTL_MS)\n\n return async (ids, opts = {}) => {\n const [{ createMediaQueryClient }, { getSharedStorageClient }, { deriveVariantKey }] =\n await Promise.all([\n import('./query-client.js'),\n import('./client.js'),\n import('./variant-key.js'),\n ])\n\n const [mediaQuery, storage] = await Promise.all([\n createMediaQueryClient(),\n getSharedStorageClient(),\n ])\n\n return resolvePublicMedia(\n ids,\n {\n readMedia: async (mediaIds, locale) => {\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { getTableColumns, inArray } = await import('drizzle-orm')\n const table = schemaRegistry.get('media')\n if (!table) return []\n // Column refs come from drizzle's own typed accessor, never from a bare\n // `table.id` — the registry hands back a dynamically-generated table\n // whose property access is untyped, so reaching through it would put an\n // `any` straight into the WHERE clause.\n const columns = getTableColumns(table) as Record<string, PgColumn>\n const idColumn = columns.id\n if (!idColumn) return []\n const rows = await mediaQuery.findMany({\n where: inArray(idColumn, [...mediaIds]),\n limit: mediaIds.length,\n ...(locale !== undefined && { locale }),\n })\n return rows as unknown as PublicMediaRow[]\n },\n getPublicUrls: (keys) => storage.getPublicUrls(keys),\n imageStyles,\n variantKey: deriveVariantKey,\n },\n opts,\n )\n }\n}\n\n/**\n * One image the CANVAS can draw for a media id — the shape `@murumets-ee/blocks`'\n * `CanvasImageResolver` asks for, declared structurally so this package does not\n * depend on blocks.\n */\nexport interface CanvasImage {\n readonly url: string\n readonly alt: string | null\n readonly width: number | null\n readonly height: number | null\n}\n\nlet canvasResolver: ReturnType<typeof createPublicMediaResolver> | undefined\n\n/**\n * Media ids → images the block-editor CANVAS may draw: a BOUND `field.media()`\n * column (frontend-delivery F112) and a collection card's picture.\n *\n * The ready-made `blocksPlugin({ resolveImages })` value, so an app wires one lazy\n * line instead of copying a resolver (frontend-delivery D025 — no builder's\n * manual):\n *\n * ```ts\n * blocksPlugin({\n * resolveImages: async (ids, opts) =>\n * (await import('@murumets-ee/media/public')).resolveCanvasImages(ids, opts),\n * })\n * ```\n *\n * Two properties are the point, not conveniences:\n *\n * - **The SAME public resolver content-api uses**, so the canvas cannot show an\n * image the published site would not (a private asset draws as empty on both).\n * - **Images only.** A `field.media({ kind: 'image' })` constrains only the\n * picker's list (editor F116), so a video or PDF can sit in the column; drawn\n * through an `<img>` it would be a broken image. Anything that is not\n * `image/*` is left out, and the canvas draws its empty placeholder instead.\n *\n * The resolver is built once per process — it memoises the image-style set, which\n * a fresh one per call would re-read.\n */\nexport async function resolveCanvasImages(\n ids: readonly string[],\n opts: { locale: string },\n): Promise<Map<string, CanvasImage>> {\n canvasResolver ??= createPublicMediaResolver()\n return toCanvasImages(await canvasResolver(ids, opts))\n}\n\n/**\n * The pure half of {@link resolveCanvasImages}: keep images, drop everything else,\n * project to what the canvas draws. Exported so the filter has a test that does\n * not need a database.\n */\nexport function toCanvasImages(\n found: ReadonlyMap<string, PublicMediaProjection>,\n): Map<string, CanvasImage> {\n const images = new Map<string, CanvasImage>()\n for (const [id, media] of found) {\n if (media.mimeType?.startsWith('image/') !== true) continue\n images.set(id, { url: media.url, alt: media.alt, width: media.width, height: media.height })\n }\n return images\n}\n"],"mappings":"yFAkJA,eAAsB,EACpB,EACA,EACA,EAAwC,CAAC,EACI,CAC7C,IAAM,EAAM,IAAI,IACV,EAAS,CAAC,GAAG,IAAI,IAAI,CAAG,CAAC,EAC/B,GAAI,EAAO,SAAW,EAAG,OAAO,EAEhC,IAAM,EAAO,MAAM,EAAK,UAAU,EAAQ,EAAK,MAAM,EACrD,GAAI,EAAK,SAAW,EAAG,OAAO,EAE9B,IAAM,EAAS,MAAM,EAAK,YAAY,EAChC,EAAe,OAAO,QAAQ,CAAM,EAMpC,EAAyB,CAAC,EAE1B,EAAS,IAAI,IAEnB,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,OAAO,EAAI,SAAY,UAAY,EAAI,UAAY,GAAI,SAC3D,IAAM,EAAuC,EAAa,KAAK,CAAC,EAAM,KAAW,CAC/E,EACA,EAAK,WAAW,EAAI,QAAS,EAAM,EAAM,QAAU,MAAM,CAC3D,CAAC,EACD,EAAO,IAAI,EAAI,GAAI,CAAE,QAAS,EAAI,QAAS,aAAY,CAAC,EACxD,EAAa,KAAK,EAAI,QAAS,GAAG,EAAY,KAAK,EAAG,KAAS,CAAG,CAAC,CACrE,CAEA,IAAM,EAAa,MAAM,EAAK,cAAc,CAAY,EAExD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAO,EAAO,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,MAAM,QAAQ,IAAI,CAC9C,EAAuB,EACvB,EAAuB,CACzB,CAAC,EAED,OAAO,EACL,EACA,CACE,UAAW,MAAO,EAAU,IAAW,CACrC,GAAM,CAAE,kBAAmB,MAAM,OAAO,mBAClC,CAAE,kBAAiB,WAAY,MAAM,OAAO,eAC5C,EAAQ,EAAe,IAAI,OAAO,EACxC,GAAI,CAAC,EAAO,MAAO,CAAC,EAMpB,IAAM,EADU,EAAgB,CACT,CAAC,CAAC,GAOzB,OANK,EAME,MALY,EAAW,SAAS,CACrC,MAAO,EAAQ,EAAU,CAAC,GAAG,CAAQ,CAAC,EACtC,MAAO,EAAS,OAChB,GAAI,IAAW,IAAA,IAAa,CAAE,QAAO,CACvC,CAAC,EALqB,CAAC,CAOzB,EACA,cAAgB,GAAS,EAAQ,cAAc,CAAI,EACnD,cACA,WAAY,CACd,EACA,CACF,CACF,CACF,CAcA,IAAI,EA6BJ,eAAsB,EACpB,EACA,EACmC,CAEnC,MADA,KAAmB,EAA0B,EACtC,EAAe,MAAM,EAAe,EAAK,CAAI,CAAC,CACvD,CAOA,SAAgB,EACd,EAC0B,CAC1B,IAAM,EAAS,IAAI,IACnB,IAAK,GAAM,CAAC,EAAI,KAAU,EACpB,EAAM,UAAU,WAAW,QAAQ,IAAM,IAC7C,EAAO,IAAI,EAAI,CAAE,IAAK,EAAM,IAAK,IAAK,EAAM,IAAK,MAAO,EAAM,MAAO,OAAQ,EAAM,MAAO,CAAC,EAE7F,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"public-resolver.mjs","names":[],"sources":["../src/public-resolver.ts"],"sourcesContent":["/**\n * The PUBLIC media resolver — media as data, for a consumer that builds its own\n * markup (plan/api phase 06, D021).\n *\n * **Why not `resolveMediaRefs`.** That helper parses `[media:type:id:variant]`\n * tags out of a text string and substitutes rendered HTML (`<img …>`, `<a\n * href=…>`) through per-type renderers. Right for a server-rendered page, wrong\n * for an HTTP API: a frontend needs `{url, width, height, alt}` so it can emit\n * its own `<picture>` with its own `srcset`, not a pre-baked tag it has to parse\n * back apart. Nothing here deprecates `resolveMediaRefs`; the API simply uses a\n * different, data-shaped path.\n *\n * **Why the entity cannot just be whitelisted.** `Media` is a real entity, but\n * it has no `url` field and cannot have one: what is stored is `fileKey`, and\n * the URL is DERIVED by the storage layer, which also decides whether it is a\n * direct public link or a time-limited signed one. Serving `media` as an\n * ordinary whitelisted entity would hand a consumer a storage key — useless for\n * rendering, and a gratuitous disclosure of storage layout.\n *\n * **This resolver can never emit a signed URL, structurally.** It asks storage\n * for PUBLIC urls (`getPublicUrls`) rather than asking for \"a url\" and\n * inspecting what came back. The second shape produces a signed URL on the\n * happy path and relies on a later check to suppress it — and a signed URL is a\n * bearer capability that outlives the permission check that minted it, on a\n * response the public role is deliberately allowed to cache. There is no branch\n * here to forget.\n *\n * D021 permits a permission-gated scoped URL for NON-public principals on\n * responses already forced to `no-store`. It is deliberately not built: no\n * consumer needs it, and an unexercised signed-URL branch is a check that\n * cannot fail. The shape is fixed so nobody re-derives it; the path waits for a\n * named consumer.\n */\n\nimport type { PgColumn } from 'drizzle-orm/pg-core'\n\nexport { cacheOnceUnlessRejected } from './async-cache.js'\n\nimport { type FocalPoint, readFocalPoint } from './crop/focal-point.js'\nimport type { ImageStyle } from './types.js'\n\n/**\n * One media item as it reaches an HTTP consumer.\n *\n * A STRUCTURAL match for `@murumets-ee/content-api`'s `MediaProjection`, not an\n * import of it: `content-api` is a leaf that this package's consumers wire into\n * by hand, exactly like `ContentApiResolution` mirrors content's\n * `ResolveResult`. The app that wires the two is where TypeScript checks they\n * agree.\n *\n * `width`/`height` ride along because a frontend needs them to reserve layout\n * space before the image loads; omitting them forces either a layout shift or a\n * second request, and the second request is the 4+N failure D001 exists to\n * prevent. `alt`/`title` are translatable on the Media entity, so this\n * projection is locale-dependent.\n */\nexport interface PublicMediaProjection {\n id: string\n url: string\n mimeType: string | null\n width: number | null\n height: number | null\n alt: string | null\n title: string | null\n /**\n * Variant URLs by image-style name, INLINED as data rather than handed over\n * as a URL pattern to interpolate.\n *\n * Two reasons, and the second is a security property. D008's rule is that a\n * client derives nothing — a consumer that constructs URLs from a pattern\n * encodes an assumption the server never published, and nothing can detect\n * when it goes stale. And a URL pattern is necessarily public-SHAPED: the\n * moment a consumer can build its own URL, the server has lost the ability to\n * decide what that consumer may address, and the \"never a signed URL\"\n * guarantee becomes unenforceable because the consumer stopped asking.\n *\n * The payload multiplier is bounded by CONFIGURATION, not by content: the set\n * of image styles is operator-chosen and neither the caller nor the editor can\n * grow it. So this needs no `?populate=`-style opt-in — unlike reference\n * expansion, where the caller could otherwise drag arbitrarily large targets\n * in. A style whose variant file is missing or not public is simply absent.\n */\n variants: Record<string, string>\n /**\n * Where the subject is, as `{ x, y }` fractions of the image (images D002).\n *\n * ALWAYS present: a row with no focal point, or one whose stored value is\n * unusable, projects as the centre, so no consumer branches on absence (D010).\n * It rides the PROJECTION and never the stored block ref — the resolver\n * substitutes fresh data on every read, so a point edited today reaches a page\n * saved last year with nothing rewritten (D007).\n */\n focalPoint: FocalPoint\n}\n\n/** The Media rows this resolver needs. Structural, so any read path can supply them. */\nexport interface PublicMediaRow {\n id: string\n fileKey: string\n mimeType?: string | null\n width?: number | null\n height?: number | null\n alt?: string | null\n title?: string | null\n /** The stored `media.focalPoint` — untrusted here, read through `readFocalPoint`. */\n focalPoint?: unknown\n}\n\nexport interface PublicMediaResolverDeps {\n /**\n * Read media rows by id through a PUBLISHED-ONLY path.\n *\n * **The wiring must guarantee this** — pass a `MediaQueryClient`/`QueryClient`\n * read, never an `AdminClient` one. This module cannot enforce the choice (it\n * is injected), and an admin read would surface unpublished media on the\n * anonymous surface. Same posture, and same reason, as\n * `ContentApiResolution.resolvePath`.\n */\n readMedia: (ids: readonly string[], locale?: string) => Promise<PublicMediaRow[]>\n /**\n * Public URLs for a batch of storage keys. Anything missing or non-public is\n * ABSENT from the map — see `StorageClient.getPublicUrls`, which is the ask-\n * for-public shape this whole module rests on.\n */\n getPublicUrls: (keys: readonly string[]) => Promise<Map<string, string>>\n /** The configured image styles. Operator-owned; neither caller nor editor grows it. */\n imageStyles: () => Promise<Record<string, ImageStyle>>\n /** Derives a variant's storage key from the original's. */\n variantKey: (fileKey: string, styleName: string, format: string) => string\n}\n\n/**\n * Resolve media ids to public projections.\n *\n * Ids that do not exist, are unpublished for this caller, or whose file is not\n * public are ABSENT from the returned map — one absence, four causes, exactly\n * as phase 05's failure semantics require. The caller renders without them.\n *\n * Cost is THREE round trips at most, regardless of batch size: the image-style\n * lookup (usually served from the caller's cache — see\n * {@link createPublicMediaResolver}), one entity read, and one storage read\n * covering every original and every variant key. Emphatically NOT\n * N×(styles+1), which is what a per-item convenience method would have made it.\n * The storage read is internally chunked when the key count exceeds what one\n * query may carry, so \"one storage read\" is `ceil(keys / 500)` in the extreme.\n */\nexport async function resolvePublicMedia(\n ids: readonly string[],\n deps: PublicMediaResolverDeps,\n opts: { locale?: string | undefined } = {},\n): Promise<Map<string, PublicMediaProjection>> {\n const out = new Map<string, PublicMediaProjection>()\n const unique = [...new Set(ids)]\n if (unique.length === 0) return out\n\n const rows = await deps.readMedia(unique, opts.locale)\n if (rows.length === 0) return out\n\n const styles = await deps.imageStyles()\n const styleEntries = Object.entries(styles)\n\n // Every key we might need — originals AND variants — resolved in one storage\n // query. `getPublicUrls` returns nothing for a key that is missing or not\n // public, so a private original drops the whole item and a private variant\n // drops only that variant.\n const keysToLookUp: string[] = []\n /** Per row: its original key, plus (styleName → variant key). */\n const perRow = new Map<string, { fileKey: string; variantKeys: Array<[string, string]> }>()\n\n for (const row of rows) {\n if (typeof row.fileKey !== 'string' || row.fileKey === '') continue\n const variantKeys: Array<[string, string]> = styleEntries.map(([name, style]) => [\n name,\n deps.variantKey(row.fileKey, name, style.format ?? 'webp'),\n ])\n perRow.set(row.id, { fileKey: row.fileKey, variantKeys })\n keysToLookUp.push(row.fileKey, ...variantKeys.map(([, key]) => key))\n }\n\n const publicUrls = await deps.getPublicUrls(keysToLookUp)\n\n for (const row of rows) {\n const keys = perRow.get(row.id)\n if (!keys) continue\n const url = publicUrls.get(keys.fileKey)\n // No public URL for the ORIGINAL → the item does not resolve at all. Not\n // \"resolves with variants only\": the variants of a private original are an\n // accident of processing, not a sanctioned public view of it.\n if (url === undefined) continue\n\n const variants: Record<string, string> = {}\n for (const [styleName, variantKey] of keys.variantKeys) {\n const variantUrl = publicUrls.get(variantKey)\n if (variantUrl !== undefined) variants[styleName] = variantUrl\n }\n\n out.set(row.id, {\n id: row.id,\n url,\n mimeType: row.mimeType ?? null,\n width: row.width ?? null,\n height: row.height ?? null,\n alt: row.alt ?? null,\n title: row.title ?? null,\n variants,\n focalPoint: readFocalPoint(row.focalPoint),\n })\n }\n\n return out\n}\n\n/**\n * Wire {@link resolvePublicMedia} to the running app — the one line an app puts\n * into `createContentApiHandler({ resolveMedia })`.\n *\n * Every dependency is resolved through the PUBLIC read path:\n * `MediaQueryClient` (so the publish filter, the `view` gate and locale merging\n * all apply, and `alt`/`title` come back in the requested locale), and\n * `StorageClient.getPublicUrls` (which has no signed-URL branch at all).\n *\n * Imports are dynamic for the same reason `createMediaQueryClient`'s are: this\n * must be callable from a route module without dragging the storage/settings\n * graph into whatever bundle imports it.\n */\n/**\n * A single-value cache with a wall-clock TTL.\n *\n * Extracted rather than inlined so it can be tested with an injected clock:\n * the thing being asserted is time-dependent, and new stateful code on the\n * anonymous request path with no coverage is how a cache ends up serving the\n * wrong thing for a window nobody measured.\n *\n * Caches the PROMISE, not the settled value, so concurrent callers arriving\n * before the first load resolves share it. Caching only the value would let N\n * simultaneous requests each start their own read — the stampede this memo\n * exists to remove, on the one path where bursts are expected.\n *\n * A rejection is still NOT pinned for the TTL: the entry is dropped when the\n * promise rejects, so the next call retries rather than replaying a transient\n * outage for the rest of the window.\n */\nexport function memoiseWithTtl<T>(\n load: () => Promise<T>,\n ttlMs: number,\n now: () => number = Date.now,\n): () => Promise<T> {\n let cached: { value: Promise<T>; at: number } | null = null\n return async () => {\n const t = now()\n if (cached && t - cached.at < ttlMs) return cached.value\n const value = load()\n cached = { value, at: t }\n value.catch(() => {\n // Only clear OUR entry — a later call may already have replaced it.\n if (cached?.value === value) cached = null\n })\n return value\n }\n}\n\nexport function createPublicMediaResolver(): (\n ids: readonly string[],\n opts?: { locale?: string | undefined },\n) => Promise<Map<string, PublicMediaProjection>> {\n // The image-style set, memoised with a SHORT TTL.\n //\n // `resolveImageStyles` reads the settings DB and is documented as not cached,\n // so without this every media pass costs a settings query — and there is more\n // than one pass per response (the root rows, plus one per `?populate=`\n // expansion group), on an anonymous request path. A process-lifetime cache\n // would be wrong in the other direction: image styles are ADMIN-EDITABLE at\n // runtime, so it would serve a stale style set until redeploy.\n //\n // 30s mirrors the TTL `content-api` uses for its permission checker, and the\n // bound is the same shape: per process, so a multi-instance deployment sees a\n // new style within one TTL of each instance's own expiry. The cost of being\n // stale here is a variant URL for a style that was just added or removed —\n // the \"missing or not public\" path already handles it as an absent variant.\n const STYLES_TTL_MS = 30_000\n const imageStyles = memoiseWithTtl(async (): Promise<Record<string, ImageStyle>> => {\n const { getApp } = await import('@murumets-ee/core')\n const { resolveImageStyles } = await import('./resolve-image-styles.js')\n return resolveImageStyles(getApp())\n }, STYLES_TTL_MS)\n\n return async (ids, opts = {}) => {\n const [{ createMediaQueryClient }, { getSharedStorageClient }, { deriveVariantKey }] =\n await Promise.all([\n import('./query-client.js'),\n import('./client.js'),\n import('./variant-key.js'),\n ])\n\n const [mediaQuery, storage] = await Promise.all([\n createMediaQueryClient(),\n getSharedStorageClient(),\n ])\n\n return resolvePublicMedia(\n ids,\n {\n readMedia: async (mediaIds, locale) => {\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { getTableColumns, inArray } = await import('drizzle-orm')\n const table = schemaRegistry.get('media')\n if (!table) return []\n // Column refs come from drizzle's own typed accessor, never from a bare\n // `table.id` — the registry hands back a dynamically-generated table\n // whose property access is untyped, so reaching through it would put an\n // `any` straight into the WHERE clause.\n const columns = getTableColumns(table) as Record<string, PgColumn>\n const idColumn = columns.id\n if (!idColumn) return []\n const rows = await mediaQuery.findMany({\n where: inArray(idColumn, [...mediaIds]),\n limit: mediaIds.length,\n ...(locale !== undefined && { locale }),\n })\n return rows as unknown as PublicMediaRow[]\n },\n getPublicUrls: (keys) => storage.getPublicUrls(keys),\n imageStyles,\n variantKey: deriveVariantKey,\n },\n opts,\n )\n }\n}\n\n/**\n * One image the CANVAS can draw for a media id — the shape `@murumets-ee/blocks`'\n * `CanvasImageResolver` asks for, declared structurally so this package does not\n * depend on blocks.\n */\nexport interface CanvasImage {\n readonly url: string\n readonly alt: string | null\n readonly width: number | null\n readonly height: number | null\n}\n\nlet canvasResolver: ReturnType<typeof createPublicMediaResolver> | undefined\n\n/**\n * Media ids → images the block-editor CANVAS may draw: a BOUND `field.media()`\n * column (frontend-delivery F112) and a collection card's picture.\n *\n * The ready-made `blocksPlugin({ resolveImages })` value, so an app wires one lazy\n * line instead of copying a resolver (frontend-delivery D025 — no builder's\n * manual):\n *\n * ```ts\n * blocksPlugin({\n * resolveImages: async (ids, opts) =>\n * (await import('@murumets-ee/media/public')).resolveCanvasImages(ids, opts),\n * })\n * ```\n *\n * Two properties are the point, not conveniences:\n *\n * - **The SAME public resolver content-api uses**, so the canvas cannot show an\n * image the published site would not (a private asset draws as empty on both).\n * - **Images only.** A `field.media({ kind: 'image' })` constrains only the\n * picker's list (editor F116), so a video or PDF can sit in the column; drawn\n * through an `<img>` it would be a broken image. Anything that is not\n * `image/*` is left out, and the canvas draws its empty placeholder instead.\n *\n * The resolver is built once per process — it memoises the image-style set, which\n * a fresh one per call would re-read.\n */\nexport async function resolveCanvasImages(\n ids: readonly string[],\n opts: { locale: string },\n): Promise<Map<string, CanvasImage>> {\n canvasResolver ??= createPublicMediaResolver()\n return toCanvasImages(await canvasResolver(ids, opts))\n}\n\n/**\n * The pure half of {@link resolveCanvasImages}: keep images, drop everything else,\n * project to what the canvas draws. Exported so the filter has a test that does\n * not need a database.\n */\nexport function toCanvasImages(\n found: ReadonlyMap<string, PublicMediaProjection>,\n): Map<string, CanvasImage> {\n const images = new Map<string, CanvasImage>()\n for (const [id, media] of found) {\n if (media.mimeType?.startsWith('image/') !== true) continue\n images.set(id, { url: media.url, alt: media.alt, width: media.width, height: media.height })\n }\n return images\n}\n"],"mappings":"yFAkJA,eAAsB,EACpB,EACA,EACA,EAAwC,CAAC,EACI,CAC7C,IAAM,EAAM,IAAI,IACV,EAAS,CAAC,GAAG,IAAI,IAAI,CAAG,CAAC,EAC/B,GAAI,EAAO,SAAW,EAAG,OAAO,EAEhC,IAAM,EAAO,MAAM,EAAK,UAAU,EAAQ,EAAK,MAAM,EACrD,GAAI,EAAK,SAAW,EAAG,OAAO,EAE9B,IAAM,EAAS,MAAM,EAAK,YAAY,EAChC,EAAe,OAAO,QAAQ,CAAM,EAMpC,EAAyB,CAAC,EAE1B,EAAS,IAAI,IAEnB,IAAK,IAAM,KAAO,EAAM,CACtB,GAAI,OAAO,EAAI,SAAY,UAAY,EAAI,UAAY,GAAI,SAC3D,IAAM,EAAuC,EAAa,KAAK,CAAC,EAAM,KAAW,CAC/E,EACA,EAAK,WAAW,EAAI,QAAS,EAAM,EAAM,QAAU,MAAM,CAC3D,CAAC,EACD,EAAO,IAAI,EAAI,GAAI,CAAE,QAAS,EAAI,QAAS,aAAY,CAAC,EACxD,EAAa,KAAK,EAAI,QAAS,GAAG,EAAY,KAAK,EAAG,KAAS,CAAG,CAAC,CACrE,CAEA,IAAM,EAAa,MAAM,EAAK,cAAc,CAAY,EAExD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAO,EAAO,IAAI,EAAI,EAAE,EAC9B,GAAI,CAAC,EAAM,SACX,IAAM,EAAM,EAAW,IAAI,EAAK,OAAO,EAIvC,GAAI,IAAQ,IAAA,GAAW,SAEvB,IAAM,EAAmC,CAAC,EAC1C,IAAK,GAAM,CAAC,EAAW,KAAe,EAAK,YAAa,CACtD,IAAM,EAAa,EAAW,IAAI,CAAU,EACx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AAQ,EAAe,IAAI,OAAO,EACxC,GAAI,CAAC,EAAO,MAAO,CAAC,EAMpB,IAAM,EADU,EAAgB,CACT,CAAC,CAAC,GAOzB,OANK,EAME,MALY,EAAW,SAAS,CACrC,MAAO,EAAQ,EAAU,CAAC,GAAG,CAAQ,CAAC,EACtC,MAAO,EAAS,OAChB,GAAI,IAAW,IAAA,IAAa,CAAE,QAAO,CACvC,CAAC,EALqB,CAAC,CAOzB,EACA,cAAgB,GAAS,EAAQ,cAAc,CAAI,EACnD,cACA,WAAY,CACd,EACA,CACF,CACF,CACF,CAcA,IAAI,EA6BJ,eAAsB,EACpB,EACA,EACmC,CAEnC,MADA,KAAmB,EAA0B,EACtC,EAAe,MAAM,EAAe,EAAK,CAAI,CAAC,CACvD,CAOA,SAAgB,EACd,EAC0B,CAC1B,IAAM,EAAS,IAAI,IACnB,IAAK,GAAM,CAAC,EAAI,KAAU,EACpB,EAAM,UAAU,WAAW,QAAQ,IAAM,IAC7C,EAAO,IAAI,EAAI,CAAE,IAAK,EAAM,IAAK,IAAK,EAAM,IAAK,MAAO,EAAM,MAAO,OAAQ,EAAM,MAAO,CAAC,EAE7F,OAAO,CACT"}
|
package/dist/query-client.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { l as MediaRecord, m as Media } from "./types-CgkJF5dc.mjs";
|
|
2
2
|
import { CountOptions, FindByIdOptions, FindManyOptions, QueryClient } from "@murumets-ee/entity/query";
|
|
3
3
|
|
|
4
4
|
//#region src/query-client.d.ts
|
package/dist/query-client.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=class{query;constructor(e){this.query=e.query}async findById(e,t){return this.query.findById(e,t)}async findMany(e){return this.query.findMany(e)}async count(e){return this.query.count(e)}};async function t(){let{createQueryClient:t}=await import(`@murumets-ee/core/clients`),{Media:n}=await import(`./entity-
|
|
1
|
+
var e=class{query;constructor(e){this.query=e.query}async findById(e,t){return this.query.findById(e,t)}async findMany(e){return this.query.findMany(e)}async count(e){return this.query.count(e)}};async function t(){let{createQueryClient:t}=await import(`@murumets-ee/core/clients`),{Media:n}=await import(`./entity-CsDdjKz6.mjs`).then(e=>e.n);return new e({query:t(n)})}export{e as MediaQueryClient,t as createMediaQueryClient};
|
|
2
2
|
//# sourceMappingURL=query-client.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createVariantDeps as e}from"./deps-CzHEhyJK.mjs";import{generateMediaVariants as t}from"./generate-variants-zyPjaGcy.mjs";import"server-only";async function n(n){let{app:r,storage:i,logger:a}=n,{AdminClient:o}=await import(`@murumets-ee/entity/admin`),{Media:s}=await import(`./entity-CsDdjKz6.mjs`).then(e=>e.n),{schemaRegistry:c}=await import(`@murumets-ee/db`),{and:l,asc:u,eq:d,gt:f}=await import(`drizzle-orm`),p=new o({entity:s,db:r.db.readWrite,logger:a,contextResolver:n.contextResolver}),m=c.get(`media`);if(!m)throw Error(`Media schema not registered`);let h=await e(r,{media:p,storage:i}),g={total:0,processed:0,skipped:0,errors:0},_=null;for(a?.info(`Starting variant regeneration (inline — no queue in this app)`);;){let e=await p.findMany({where:_?l(d(m.mediaType,`image`),f(m.id,_)):d(m.mediaType,`image`),orderBy:u(m.id),limit:100}),n=e[e.length-1];if(!n)break;_=n.id,g.total+=e.length;for(let n of e)try{let e=await t(n.id,h);e.status===`generated`||e.status===`stale`?g.processed++:g.skipped++}catch(e){g.errors++,a?.error({id:n.id,error:e},`Failed to regenerate variants for media record`)}if(e.length<100)break}return a?.info(g,`Variant regeneration complete`),g}export{n as regenerateAllVariants};
|
|
2
|
+
//# sourceMappingURL=regenerate-variants-Cp3sNHkT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"regenerate-variants-Cp3sNHkT.mjs","names":[],"sources":["../src/regenerate-variants.ts"],"sourcesContent":["/**\n * Synchronous library regeneration — the path for an app WITHOUT the queue\n * plugin only.\n *\n * With a queue, the regenerate button queues `media:variants-backfill` instead\n * (`jobs/backfill.ts`): bounded, resumable, off the request, with the site\n * serving throughout. This loop is what a queueless app keeps, so it does not\n * silently lose the button — it runs inside the request, as it always has.\n *\n * It runs the SAME per-photograph pass the worker does (`generateMediaVariants`),\n * so it inherits its order (images F002): new files first, then the pointer,\n * then — only then — deletion of what they superseded. The previous version of\n * this file deleted every variant of a photograph before generating any, so a\n * removed style lost its files with nothing replacing them and every variant\n * URL 404'd for as long as the run took.\n *\n * Per-image errors are logged and counted, never stop the loop.\n */\n\nimport 'server-only'\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport type { ContextResolver } from '@murumets-ee/entity'\nimport type { StorageClient } from '@murumets-ee/storage'\nimport { createVariantDeps } from './jobs/deps.js'\nimport { generateMediaVariants } from './jobs/generate-variants.js'\n\nconst BATCH_SIZE = 100\n\nexport interface RegenerateOptions {\n /** Toolkit app (provides db + the variant configuration). */\n app: ToolkitApp\n storage: StorageClient\n logger?: Logger\n /** Security context resolver — passed through to AdminClient. */\n contextResolver?: ContextResolver\n}\n\nexport interface RegenerateResult {\n /** Total image media records found */\n total: number\n /** Passes that ran (including ones that found nothing to do) */\n processed: number\n /** Skipped (non-processable mimeType, original missing, row gone) */\n skipped: number\n /** Failed with errors */\n errors: number\n}\n\n/** Regenerate variants for every image, in keyset pages of {@link BATCH_SIZE}. */\nexport async function regenerateAllVariants(options: RegenerateOptions): Promise<RegenerateResult> {\n const { app, storage, logger } = options\n const { AdminClient } = await import('@murumets-ee/entity/admin')\n const { Media } = await import('./entity.js')\n const { schemaRegistry } = await import('@murumets-ee/db')\n const { and, asc, eq, gt } = await import('drizzle-orm')\n\n const admin = new AdminClient<typeof Media.allFields>({\n entity: Media,\n db: app.db.readWrite,\n logger,\n contextResolver: options.contextResolver,\n })\n const table = schemaRegistry.get('media')\n if (!table) throw new Error('Media schema not registered')\n\n const deps = await createVariantDeps(app, { media: admin, storage })\n const result: RegenerateResult = { total: 0, processed: 0, skipped: 0, errors: 0 }\n let cursor: string | null = null\n\n logger?.info('Starting variant regeneration (inline — no queue in this app)')\n\n for (;;) {\n const batch = await admin.findMany({\n where: cursor\n ? and(eq(table.mediaType, 'image'), gt(table.id, cursor))\n : eq(table.mediaType, 'image'),\n orderBy: asc(table.id),\n limit: BATCH_SIZE,\n })\n const last = batch[batch.length - 1]\n if (!last) break\n cursor = last.id\n result.total += batch.length\n\n for (const record of batch) {\n try {\n const outcome = await generateMediaVariants(record.id, deps)\n if (outcome.status === 'generated' || outcome.status === 'stale') result.processed++\n else result.skipped++\n } catch (err) {\n result.errors++\n logger?.error(\n { id: record.id, error: err },\n 'Failed to regenerate variants for media record',\n )\n }\n }\n\n if (batch.length < BATCH_SIZE) break\n }\n\n logger?.info(result, 'Variant regeneration complete')\n return result\n}\n"],"mappings":"qJAkDA,eAAsB,EAAsB,EAAuD,CACjG,GAAM,CAAE,MAAK,UAAS,UAAW,EAC3B,CAAE,eAAgB,MAAM,OAAO,6BAC/B,CAAE,SAAU,MAAM,OAAO,wBAAc,CAAA,KAAA,GAAA,EAAA,CAAA,EACvC,CAAE,kBAAmB,MAAM,OAAO,mBAClC,CAAE,MAAK,MAAK,KAAI,MAAO,MAAM,OAAO,eAEpC,EAAQ,IAAI,EAAoC,CACpD,OAAQ,EACR,GAAI,EAAI,GAAG,UACX,SACA,gBAAiB,EAAQ,eAC3B,CAAC,EACK,EAAQ,EAAe,IAAI,OAAO,EACxC,GAAI,CAAC,EAAO,MAAU,MAAM,6BAA6B,EAEzD,IAAM,EAAO,MAAM,EAAkB,EAAK,CAAE,MAAO,EAAO,SAAQ,CAAC,EAC7D,EAA2B,CAAE,MAAO,EAAG,UAAW,EAAG,QAAS,EAAG,OAAQ,CAAE,EAC7E,EAAwB,KAI5B,IAFA,GAAQ,KAAK,+DAA+D,IAEnE,CACP,IAAM,EAAQ,MAAM,EAAM,SAAS,CACjC,MAAO,EACH,EAAI,EAAG,EAAM,UAAW,OAAO,EAAG,EAAG,EAAM,GAAI,CAAM,CAAC,EACtD,EAAG,EAAM,UAAW,OAAO,EAC/B,QAAS,EAAI,EAAM,EAAE,EACrB,MAAO,GACT,CAAC,EACK,EAAO,EAAM,EAAM,OAAS,GAClC,GAAI,CAAC,EAAM,MACX,EAAS,EAAK,GACd,EAAO,OAAS,EAAM,OAEtB,IAAK,IAAM,KAAU,EACnB,GAAI,CACF,IAAM,EAAU,MAAM,EAAsB,EAAO,GAAI,CAAI,EACvD,EAAQ,SAAW,aAAe,EAAQ,SAAW,QAAS,EAAO,YACpE,EAAO,SACd,OAAS,EAAK,CACZ,EAAO,SACP,GAAQ,MACN,CAAE,GAAI,EAAO,GAAI,MAAO,CAAI,EAC5B,gDACF,CACF,CAGF,GAAI,EAAM,OAAS,IAAY,KACjC,CAGA,OADA,GAAQ,KAAK,EAAQ,+BAA+B,EAC7C,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as e,i as t,l as n,s as r,t as i}from"./definitions-LJpgrdxd.mjs";import{n as a}from"./slot-CY4isqmN.mjs";import{runAsCli as o}from"@murumets-ee/core";async function s(s){if(!s.plugins.has(`@murumets-ee/queue`))return;let{defineJob:c,registerJob:l}=await import(`@murumets-ee/queue/client`),u=c({name:i,description:`Generate one photograph's image variants (every shape × width, plus fixed styles), record them on the original, then delete the ones they supersede.`,schema:e,idempotencyKey:r}),d=c({name:t,description:`Walk the image library and queue a variant pass for every photograph — after a shape, width or style changes. Bounded and resumable; the site keeps serving throughout.`,schema:n,defaultRetries:2});l(u,async t=>{let{mediaId:n}=e.parse(t.payload);await o(async()=>{let{createJobVariantDeps:e}=await import(`./deps-CzHEhyJK.mjs`),{generateMediaVariants:t}=await import(`./generate-variants-zyPjaGcy.mjs`),r=await t(n,await e(s));s.logger.info(r,`media variants: pass finished`)})}),l(d,async e=>{n.parse(e.payload),await o(async()=>{let{runVariantsBackfill:t}=await import(`./backfill-D2Ubblh3.mjs`),n=await t(s,u,{walkJobId:e.id,onProgress:t=>e.updateProgress(t)});s.logger.info(n,`media variants: backfill queued`)})}),a({generateVariants:u,variantsBackfill:d})}export{s as registerMediaJobs};
|
|
2
|
+
//# sourceMappingURL=register-BSGkELj0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register-BSGkELj0.mjs","names":[],"sources":["../src/jobs/register.ts"],"sourcesContent":["/**\n * Registers the media queue jobs, and holds the handles every enqueuer uses.\n *\n * ⚠️ Imperative on purpose, and known debt: `defineJob` + `registerJob` from a\n * plugin's `server.init` is the ONE pattern the queue offers today — the same\n * one `packages/blocks/src/server/jobs/*`, `packages/commerce/src/<area>/jobs.ts`\n * and `packages/content/src/paths/jobs.ts` follow. It sits against CLAUDE.md's\n * declarative-contributions rule and is tracked as lumi-cms#497 (a declarative\n * `Plugin.jobs` slot). Do not invent a second pattern here; lift all of them\n * together when #497 lands.\n *\n * `@murumets-ee/queue/client` is imported DYNAMICALLY so an app without the\n * queue plugin (`apps/web-astro`) never loads it — it gets inline generation\n * instead (`schedule.ts`).\n */\n\nimport { runAsCli, type ToolkitApp } from '@murumets-ee/core'\nimport {\n GENERATE_VARIANTS_JOB_NAME,\n type GenerateVariantsPayload,\n generateVariantsJobKey,\n generateVariantsPayloadSchema,\n QUEUE_PLUGIN_NAME,\n VARIANTS_BACKFILL_JOB_NAME,\n type VariantsBackfillPayload,\n variantsBackfillPayloadSchema,\n} from './definitions.js'\nimport { setMediaJobs } from './slot.js'\n\n/**\n * Define and register `media:generate-variants` and `media:variants-backfill`.\n * A no-op when the app has no queue plugin. Sync-registry only — no DB — so it\n * is safe in every context `init` runs in (the Next server, `next build`, CLI).\n */\nexport async function registerMediaJobs(app: ToolkitApp): Promise<void> {\n if (!app.plugins.has(QUEUE_PLUGIN_NAME)) return\n const { defineJob, registerJob } = await import('@murumets-ee/queue/client')\n\n const generateVariants = defineJob<GenerateVariantsPayload>({\n name: GENERATE_VARIANTS_JOB_NAME,\n description:\n \"Generate one photograph's image variants (every shape × width, plus fixed styles), \" +\n 'record them on the original, then delete the ones they supersede.',\n schema: generateVariantsPayloadSchema,\n idempotencyKey: generateVariantsJobKey,\n })\n const variantsBackfill = defineJob<VariantsBackfillPayload>({\n name: VARIANTS_BACKFILL_JOB_NAME,\n description:\n 'Walk the image library and queue a variant pass for every photograph — after a shape, ' +\n 'width or style changes. Bounded and resumable; the site keeps serving throughout.',\n schema: variantsBackfillPayloadSchema,\n // Rerunning a backfill is always meaningful (the configuration may have\n // changed since), so it has no idempotency key; the passes it queues do.\n defaultRetries: 2,\n })\n\n registerJob(generateVariants, async (ctx) => {\n const { mediaId } = generateVariantsPayloadSchema.parse(ctx.payload)\n // A worker has no request, so no user: the pass reads and writes the media\n // row as the synthetic CLI admin, the same wrapping every entity-touching\n // job in this repo uses. What it writes is derived from the file, never\n // from a payload field (the payload is an id and a hash).\n await runAsCli(async () => {\n const { createJobVariantDeps } = await import('./deps.js')\n const { generateMediaVariants } = await import('./generate-variants.js')\n const outcome = await generateMediaVariants(mediaId, await createJobVariantDeps(app))\n app.logger.info(outcome, 'media variants: pass finished')\n })\n })\n\n registerJob(variantsBackfill, async (ctx) => {\n variantsBackfillPayloadSchema.parse(ctx.payload)\n await runAsCli(async () => {\n const { runVariantsBackfill } = await import('./backfill.js')\n const outcome = await runVariantsBackfill(app, generateVariants, {\n walkJobId: ctx.id,\n onProgress: (p) => ctx.updateProgress(p),\n })\n app.logger.info(outcome, 'media variants: backfill queued')\n })\n })\n\n setMediaJobs({ generateVariants, variantsBackfill })\n}\n"],"mappings":"gKAkCA,eAAsB,EAAkB,EAAgC,CACtE,GAAI,CAAC,EAAI,QAAQ,IAAA,oBAAqB,EAAG,OACzC,GAAM,CAAE,YAAW,eAAgB,MAAM,OAAO,6BAE1C,EAAmB,EAAmC,CAC1D,KAAM,EACN,YACE,uJAEF,OAAQ,EACR,eAAgB,CAClB,CAAC,EACK,EAAmB,EAAmC,CAC1D,KAAM,EACN,YACE,0KAEF,OAAQ,EAGR,eAAgB,CAClB,CAAC,EAED,EAAY,EAAkB,KAAO,IAAQ,CAC3C,GAAM,CAAE,WAAY,EAA8B,MAAM,EAAI,OAAO,EAKnE,MAAM,EAAS,SAAY,CACzB,GAAM,CAAE,wBAAyB,MAAM,OAAO,uBACxC,CAAE,yBAA0B,MAAM,OAAO,oCACzC,EAAU,MAAM,EAAsB,EAAS,MAAM,EAAqB,CAAG,CAAC,EACpF,EAAI,OAAO,KAAK,EAAS,+BAA+B,CAC1D,CAAC,CACH,CAAC,EAED,EAAY,EAAkB,KAAO,IAAQ,CAC3C,EAA8B,MAAM,EAAI,OAAO,EAC/C,MAAM,EAAS,SAAY,CACzB,GAAM,CAAE,uBAAwB,MAAM,OAAO,2BACvC,EAAU,MAAM,EAAoB,EAAK,EAAkB,CAC/D,UAAW,EAAI,GACf,WAAa,GAAM,EAAI,eAAe,CAAC,CACzC,CAAC,EACD,EAAI,OAAO,KAAK,EAAS,iCAAiC,CAC5D,CAAC,CACH,CAAC,EAED,EAAa,CAAE,mBAAkB,kBAAiB,CAAC,CACrD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{r as t,s as n}from"./shapes-BlKW-0C1.mjs";import"./variant-plan-DV8hsMdz.mjs";import{n as r}from"./media-config-DmcTxuDM.mjs";var i=e({resolveImageStyles:()=>o,resolveVariantConfig:()=>s});const a={thumbnail:{width:200,height:200,fit:`cover`,format:`webp`,quality:80}};async function o(e,t,n={}){try{let{createSettingsClient:t}=await import(`@murumets-ee/settings`),{imageStylesSettings:n}=await import(`./image-styles-settings.mjs`),r=await t(n,{app:e}).get(`imageStyles`);if(r&&Object.keys(r).length>0)return r}catch(e){if(n.strict)throw e;t?.warn({err:e},`resolveImageStyles: settings DB read failed — falling back`)}try{return r().imageStyles}catch{}return a}async function s(e,i,o={}){let s=null,c=null;try{let{createSettingsClient:t}=await import(`@murumets-ee/settings`),{imageStylesSettings:n}=await import(`./image-styles-settings.mjs`),r=await t(n,{app:e}).getAll();s=r.vocabulary,r.imageStyles&&Object.keys(r.imageStyles).length>0&&(c=r.imageStyles)}catch(e){if(o.strict)throw e;i?.warn({err:e},`resolveVariantConfig: settings DB read failed — falling back`)}let l=null;try{l=r()}catch{}let u=n({vocabulary:s??l?.vocabulary??t,styles:c??l?.imageStyles??a}),d=u.shapes.reduce((e,t)=>e+t.widths.length,0);return d>64&&i?.warn({mostPerPhotograph:d,cap:64},`resolveVariantConfig: shapes, widths and fixed styles together plan more files per photograph than the cap — the largest are trimmed`),u.unmapped.length>0&&i?.warn({unmapped:u.unmapped},`resolveVariantConfig: some image styles have no place in the shape model — they keep generating as fixed styles only`),u}export{s as n,i as r,o as t};
|
|
2
|
+
//# sourceMappingURL=resolve-image-styles-pf7Nd3Zf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-image-styles-pf7Nd3Zf.mjs","names":[],"sources":["../src/resolve-image-styles.ts"],"sourcesContent":["/**\n * Image style resolution waterfall — single source of truth for the\n * \"which styles should we use?\" question.\n *\n * Priority: settings DB (user-configured) → plugin config (from `media()`\n * factory call) → hardcoded defaults (thumbnail only).\n *\n * This replaces three near-duplicate blocks (MediaClient's private\n * resolveImageStyles + two admin-route branches) that had drifted — the\n * routes didn't treat an empty stored object as \"fall back to config\"\n * while MediaClient did. Consolidating here keeps the behavior consistent\n * and logs the DB read failure so operators can diagnose issues instead\n * of silently getting defaults.\n *\n * Not cached. MediaClient wraps this with its own per-instance cache.\n */\n\nimport type { Logger, ToolkitApp } from '@murumets-ee/core'\nimport { requireMediaConfig } from './media-config.js'\nimport { buildVariantConfig, DEFAULT_IMAGE_VOCABULARY, type VariantConfig } from './shapes.js'\nimport type { ImageStyle, ImageVocabulary, ReadonlyImageVocabulary } from './types.js'\nimport { MAX_VARIANTS_PER_IMAGE } from './variant-plan.js'\n\nconst HARDCODED_DEFAULTS: Record<string, ImageStyle> = {\n thumbnail: { width: 200, height: 200, fit: 'cover', format: 'webp', quality: 80 },\n}\n\n/**\n * `strict`: a FAILED settings read throws instead of falling back.\n *\n * The fallback is right for a reader — an image still resolves while the DB\n * blips. It is wrong for the variant job, which DELETES what the configuration\n * no longer names (images PR05): a pass that read the code defaults during an\n * outage would delete every variant of every shape the operator configured,\n * across the whole library if a backfill was running. So the job reads strictly\n * and lets the queue retry. An EMPTY stored value still falls through — that is\n * \"nothing configured\", not a failure.\n */\nexport interface ResolveOptions {\n readonly strict?: boolean\n}\n\nexport async function resolveImageStyles(\n app: ToolkitApp,\n logger?: Logger,\n options: ResolveOptions = {},\n): Promise<Record<string, ImageStyle>> {\n // 1. Settings DB (source of truth once the admin UI has saved anything).\n // An empty record counts as \"nothing configured\" — fall through. This\n // matches the pre-extraction behavior of MediaClient and fixes the\n // routes' prior behavior of showing an empty UI in that case.\n try {\n const { createSettingsClient } = await import('@murumets-ee/settings')\n const { imageStylesSettings } = await import('./image-styles-settings.js')\n const settingsClient = createSettingsClient(imageStylesSettings, { app })\n const stored = await settingsClient.get('imageStyles')\n if (stored && Object.keys(stored).length > 0) return stored\n } catch (err) {\n // Logging matters: prior silent catches masked real issues (e.g. DB\n // unavailable) as \"no styles\" and routed admins toward config fallback\n // when the real failure was infrastructure.\n if (options.strict) throw err\n logger?.warn({ err }, 'resolveImageStyles: settings DB read failed — falling back')\n }\n\n // 2. Plugin config (from the `media()` factory call in lumi.config.ts).\n try {\n return requireMediaConfig().imageStyles\n } catch {\n // Plugin not initialized (e.g. unit tests that don't call media()) —\n // fall through to hardcoded defaults. No log: this is a valid mode.\n }\n\n // 3. Hardcoded baseline — a single thumbnail style so uploads don't fail\n // in a toolkit that never registered the plugin.\n return HARDCODED_DEFAULTS\n}\n\n/**\n * The shape model (images D003) — the vocabulary and ladder, with the stored\n * fixed styles folded in (`buildVariantConfig`).\n *\n * Same namespace and same waterfall as {@link resolveImageStyles}, applied per\n * key, from ONE settings read (`getAll`):\n *\n * - `vocabulary`: stored → `media({ vocabulary })` → `DEFAULT_IMAGE_VOCABULARY`.\n * The key has no settings `default`, so \"unset\" really reads as `null` and\n * the plugin-config tier is reachable — unlike `imageStyles`, whose settings\n * default shadows its config tier (a pre-existing behaviour this leaves alone).\n * - `imageStyles`: exactly what {@link resolveImageStyles} would return, so the\n * one-rung shapes and aliases describe the styles the legacy path actually\n * generates.\n *\n * Mappings the model cannot express are logged, once per call, with the reason\n * — a style an operator configured must not silently stop mattering.\n *\n * Not cached; wrap it the way `createPublicMediaResolver` wraps\n * {@link resolveImageStyles}.\n */\nexport async function resolveVariantConfig(\n app: ToolkitApp,\n logger?: Pick<Logger, 'warn'>,\n options: ResolveOptions = {},\n): Promise<VariantConfig> {\n let storedVocabulary: ImageVocabulary | null = null\n let storedStyles: Record<string, ImageStyle> | null = null\n try {\n const { createSettingsClient } = await import('@murumets-ee/settings')\n const { imageStylesSettings } = await import('./image-styles-settings.js')\n const all = await createSettingsClient(imageStylesSettings, { app }).getAll()\n storedVocabulary = all.vocabulary\n if (all.imageStyles && Object.keys(all.imageStyles).length > 0) storedStyles = all.imageStyles\n } catch (err) {\n if (options.strict) throw err\n logger?.warn({ err }, 'resolveVariantConfig: settings DB read failed — falling back')\n }\n\n let configured: {\n vocabulary: ReadonlyImageVocabulary\n imageStyles: Record<string, ImageStyle>\n } | null = null\n try {\n configured = requireMediaConfig()\n } catch {\n // Plugin not initialized — the hardcoded tier below. Valid, as above.\n }\n\n const config = buildVariantConfig({\n vocabulary: storedVocabulary ?? configured?.vocabulary ?? DEFAULT_IMAGE_VOCABULARY,\n styles: storedStyles ?? configured?.imageStyles ?? HARDCODED_DEFAULTS,\n })\n // The settings schema bounds the vocabulary on its own; the fixed styles are a\n // different key and add one file each on top. Say so here, once per read,\n // rather than only as a `dropped` count on every upload.\n const mostPerPhotograph = config.shapes.reduce((sum, s) => sum + s.widths.length, 0)\n if (mostPerPhotograph > MAX_VARIANTS_PER_IMAGE) {\n logger?.warn(\n { mostPerPhotograph, cap: MAX_VARIANTS_PER_IMAGE },\n 'resolveVariantConfig: shapes, widths and fixed styles together plan more files per photograph than the cap — the largest are trimmed',\n )\n }\n if (config.unmapped.length > 0) {\n logger?.warn(\n { unmapped: config.unmapped },\n 'resolveVariantConfig: some image styles have no place in the shape model — they keep generating as fixed styles only',\n )\n }\n return config\n}\n"],"mappings":"wPAuBA,MAAM,EAAiD,CACrD,UAAW,CAAE,MAAO,IAAK,OAAQ,IAAK,IAAK,QAAS,OAAQ,OAAQ,QAAS,EAAG,CAClF,EAiBA,eAAsB,EACpB,EACA,EACA,EAA0B,CAAC,EACU,CAKrC,GAAI,CACF,GAAM,CAAE,wBAAyB,MAAM,OAAO,yBACxC,CAAE,uBAAwB,MAAM,OAAO,+BAEvC,EAAS,MADQ,EAAqB,EAAqB,CAAE,KAAI,CACrC,CAAC,CAAC,IAAI,aAAa,EACrD,GAAI,GAAU,OAAO,KAAK,CAAM,CAAC,CAAC,OAAS,EAAG,OAAO,CACvD,OAAS,EAAK,CAIZ,GAAI,EAAQ,OAAQ,MAAM,EAC1B,GAAQ,KAAK,CAAE,KAAI,EAAG,4DAA4D,CACpF,CAGA,GAAI,CACF,OAAO,EAAmB,CAAC,CAAC,WAC9B,MAAQ,CAGR,CAIA,OAAO,CACT,CAuBA,eAAsB,EACpB,EACA,EACA,EAA0B,CAAC,EACH,CACxB,IAAI,EAA2C,KAC3C,EAAkD,KACtD,GAAI,CACF,GAAM,CAAE,wBAAyB,MAAM,OAAO,yBACxC,CAAE,uBAAwB,MAAM,OAAO,+BACvC,EAAM,MAAM,EAAqB,EAAqB,CAAE,KAAI,CAAC,CAAC,CAAC,OAAO,EAC5E,EAAmB,EAAI,WACnB,EAAI,aAAe,OAAO,KAAK,EAAI,WAAW,CAAC,CAAC,OAAS,IAAG,EAAe,EAAI,YACrF,OAAS,EAAK,CACZ,GAAI,EAAQ,OAAQ,MAAM,EAC1B,GAAQ,KAAK,CAAE,KAAI,EAAG,8DAA8D,CACtF,CAEA,IAAI,EAGO,KACX,GAAI,CACF,EAAa,EAAmB,CAClC,MAAQ,CAER,CAEA,IAAM,EAAS,EAAmB,CAChC,WAAY,GAAoB,GAAY,YAAc,EAC1D,OAAQ,GAAgB,GAAY,aAAe,CACrD,CAAC,EAIK,EAAoB,EAAO,OAAO,QAAQ,EAAK,IAAM,EAAM,EAAE,OAAO,OAAQ,CAAC,EAanF,OAZI,EAAA,IACF,GAAQ,KACN,CAAE,oBAAmB,IAAA,EAA4B,EACjD,sIACF,EAEE,EAAO,SAAS,OAAS,GAC3B,GAAQ,KACN,CAAE,SAAU,EAAO,QAAS,EAC5B,sHACF,EAEK,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./media-config-DmcTxuDM.mjs";import{combineAdminRoutes as t,defineAdminRoute as n,runBounded as r,safeAudit as i,safeAuditMany as a}from"@murumets-ee/core";const o=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function s(e){return e!==void 0&&o.test(e)}const c=[`image`,`video`,`audio`,`document`,`other`];function l(e){return c.includes(e)}function u(e,t){if(e===null||!/^\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)?n:t}function d(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function f(e,t){return d({error:e},t)}const p={clientPromise:null};async function m(){if(!p.clientPromise){let e=(async()=>{let{getApp:e}=await import(`@murumets-ee/core`),{createStorageClient:t}=await import(`@murumets-ee/storage`),{getStorageConfig:n}=await import(`@murumets-ee/storage/plugin`),r=e();return t(n(),{app:r})})();e.catch(()=>{p.clientPromise===e&&(p.clientPromise=null)}),p.clientPromise=e}return p.clientPromise}async function h(){let{createAdminClient:e}=await import(`@murumets-ee/core/clients`),{MediaClient:t}=await import(`./client.mjs`),{Media:n}=await import(`./entity-CsDdjKz6.mjs`).then(e=>e.n),r=await m();return new t({admin:e(n),storage:r})}const g=async(e,t)=>{let{isStorageConfigured:n,getStorageConfigReason:r}=await import(`@murumets-ee/storage`),i=t.segments;if(i.length===2&&i[1]===`usage`){let e=i[0];if(!s(e))return f(`Invalid media ID format`,400);let{findMediaUsages:t}=await import(`./usage.mjs`),{getApp:n}=await import(`@murumets-ee/core`);return d({usages:await t(e,n())})}if(i.length>=2)return f(`Not found`,404);let a=i.length>0?i[0]:void 0;if(a!==void 0&&!s(a))return f(`Invalid media ID format`,400);if(!n()){let e=r()??`Storage not configured`;return i.length>0?d({error:e,configured:!1,reason:e},503):d({items:[],total:0,configured:!1,reason:e})}let o=await h();if(a!==void 0){let e=await o.findById(a);if(!e)return f(`Media not found`,404);let t=await o.getUrl(a);return d({...e,url:t})}let c=new URL(e.url),p=c.searchParams.get(`search`)??void 0,m=c.searchParams.get(`mediaType`),g=m!==null&&l(m)?m:void 0,_=Math.min(Math.max(u(c.searchParams.get(`limit`),24),1),100),v=Math.min(u(c.searchParams.get(`offset`),0),1e5),y=await o.findMany({...p!==void 0&&{search:p},...g!==void 0&&{mediaType:g},limit:_,offset:v}),b=y.items.map(e=>e.id),x=y.items.filter(e=>e.mediaType===`image`).map(e=>e.id),[S,C]=await Promise.all([o.getUrls(b),o.getVariantUrls(x,`thumbnail`)]);return d({items:y.items.map(e=>{let t=e.mediaType===`image`?C.get(e.id):void 0;return{id:e.id,title:e.title??null,alt:e.alt??null,filename:e.filename,mimeType:e.mimeType,size:e.size,mediaType:e.mediaType,url:S.get(e.id)??``,...t!==void 0&&{thumbnailUrl:t},width:e.width??null,height:e.height??null}}),total:y.total})},_=async(t,n)=>{let{isStorageConfigured:r,getStorageConfigReason:a,detectMimeType:o,isMimeTypeAllowed:s,readBoundedMultipart:c,tooLarge:l}=await import(`@murumets-ee/storage`);if(n.segments.length>0)return f(`Not found`,404);if(!r())return f(a()??`Storage not configured`,503);let{maxUploadSize:u,acceptedTypes:p}=e(),m=await c(t,u);if(!m.ok)return f(m.error,m.status);let g=m.value,_=g.get(`file`);if(!(_ instanceof File)||_.size===0)return f(`No file provided`,400);if(_.size>u){let e=l(u);return f(e.error,e.status)}let v=await h(),y=Buffer.from(await _.arrayBuffer()),{mimeType:b,mismatch:x}=await o(y,_.type||`application/octet-stream`);if(x)return f(`File content doesn't match declared type: claimed ${_.type}, detected ${b}`,400);if(!s(b,p))return f(`File type ${b} is not accepted`,415);let S=g.get(`visibility`);if(S!==null&&S!==`public`&&S!==`private`)return f(`Field 'visibility' must be 'public' or 'private'`,400);let C=await v.upload(y,{filename:_.name,mimeType:b,size:_.size,uploadedBy:n.user.id,...S!==null&&{visibility:S}}),w={id:C.media.id,title:C.media.title??null,alt:C.media.alt??null,filename:C.media.filename,mimeType:C.media.mimeType,size:C.media.size,mediaType:C.media.mediaType,url:C.url,width:C.media.width??null,height:C.media.height??null};return i(n,{action:`media.upload`,entityType:`media`,entityId:C.media.id,userId:n.user.id,...n.user.name!==void 0&&{userName:n.user.name},changes:{filename:C.media.filename,mimeType:C.media.mimeType,size:C.media.size,mediaType:C.media.mediaType}}),d(w,201)},v=async(e,t)=>{let{isStorageConfigured:n,getStorageConfigReason:r}=await import(`@murumets-ee/storage`);if(t.segments.length!==1)return f(`Not found`,404);if(!n())return f(r()??`Storage not configured`,503);let{getApp:a,getContext:o}=await import(`@murumets-ee/core`),{getMediaJobs:s}=await import(`./slot-CY4isqmN.mjs`).then(e=>e.r),c=a(),l=s();if(l){let{enqueueVariantsBackfill:e}=await import(`./backfill-trigger-BFL1L7_j.mjs`),{jobId:n,alreadyRunning:r}=await e(c,l.variantsBackfill);i(t,{action:`media.regenerate_variants`,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name},metadata:{mode:`queued`,jobId:n,alreadyRunning:r}});let{getVariantBacklog:a}=await import(`./backlog-D-H5VUQA.mjs`).then(e=>e.t);return d({mode:`queued`,jobId:n,alreadyRunning:r,backlog:await a(c).catch(()=>null)},202)}let{regenerateAllVariants:u}=await import(`./regenerate-variants-Cp3sNHkT.mjs`),{createStorageClient:p}=await import(`@murumets-ee/storage`),{getStorageConfig:m}=await import(`@murumets-ee/storage/plugin`),h=await u({app:c,storage:p(m(),{app:c}),logger:c.logger.child({media:!0}),contextResolver:()=>{let e=o();if(!(!e?.user||!e?.checker))return{user:e.user,checker:e.checker,...e.scope!==void 0&&{scope:e.scope}}}});return i(t,{action:`media.regenerate_variants`,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name},metadata:{mode:`inline`,total:h.total,processed:h.processed,errors:h.errors}}),d({mode:`inline`,...h})},y=16*1024;async function b(e){let t=Number(e.headers.get(`content-length`));if(Number.isFinite(t)&&t>y)return{error:`Request body exceeds the maximum size`,status:413};let n=e.body,r;if(n===null){if(r=await e.text(),Buffer.byteLength(r,`utf8`)>y)return{error:`Request body exceeds the maximum size`,status:413}}else{let e=n.getReader(),t=[],i=0;try{for(;;){let{done:n,value:r}=await e.read();if(n)break;if(r!==void 0){if(i+=r.byteLength,i>y)return await e.cancel().catch(()=>void 0),{error:`Request body exceeds the maximum size`,status:413};t.push(r)}}}finally{e.releaseLock()}r=Buffer.concat(t).toString(`utf8`)}let i;try{i=JSON.parse(r)}catch{return{error:`Invalid JSON body`,status:400}}if(typeof i!=`object`||!i||Array.isArray(i))return{error:`Body must be a JSON object`,status:400};let a=i.ids;if(!Array.isArray(a)||a.length===0)return{error:`Body must contain "ids" array`,status:400};if(a.length>100)return{error:`Bulk delete limited to 100 items per request`,status:400};let o=[];for(let e of a){if(typeof e!=`string`||!s(e))return{error:`Body "ids" must contain valid media IDs`,status:400};o.push(e)}return{ids:o}}const x=async(e,t)=>{let n=t.segments;if(n.length===0){let n=await b(e);if(`error`in n)return f(n.error,n.status);let{isStorageConfigured:i,getStorageConfigReason:o}=await import(`@murumets-ee/storage`);if(!i())return f(o()??`Storage not configured`,503);let s=await h(),c=await r(n.ids,async e=>{try{return await s.delete(e),{status:`fulfilled`,id:e}}catch(t){return{status:`rejected`,id:e,reason:t}}}),l=c.filter(e=>e.status===`fulfilled`).map(e=>e.id);await a(t,l.map(e=>({action:`media.delete`,entityType:`media`,entityId:e,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name},metadata:{bulk:!0}})));let u=c.find(e=>e.status===`rejected`);if(u&&u.status===`rejected`)throw u.reason;return d({deleted:l.length})}if(n.length>1)return f(`Not found`,404);let o=n[0];if(!s(o))return f(`Invalid media ID format`,400);let{isStorageConfigured:c,getStorageConfigReason:l}=await import(`@murumets-ee/storage`);return c()?(await(await h()).delete(o),i(t,{action:`media.delete`,entityType:`media`,entityId:o,userId:t.user.id,...t.user.name!==void 0&&{userName:t.user.name}}),d({deleted:1})):f(l()??`Storage not configured`,503)},S=[`admin`,`editor`,`agent`,`viewer`],C=[`admin`,`editor`];function w(){return t([n({prefix:`media`,path:``,method:`GET`,permission:`media:view`,defaultRoles:S,matchAnyPath:!0,description:`Read media — list, single item, or referencing-entity usage report.`,handler:g}),n({prefix:`media`,path:``,method:`POST`,permission:`media:create`,defaultRoles:C,description:"Upload a media file (multipart FormData with `file` field).",handler:_}),n({prefix:`media`,path:`regenerate-variants`,method:`POST`,permission:`media:create`,defaultRoles:C,description:`Catch every image up with the current shapes, widths and styles — queued as a background backfill (synchronous only when the app has no queue).`,handler:v}),n({prefix:`media`,path:``,method:`DELETE`,permission:`media:delete`,defaultRoles:C,matchAnyPath:!0,description:`Delete a media record + its storage object.`,handler:x})])}export{w as t};
|
|
2
|
+
//# sourceMappingURL=routes-BJ23Cp0g.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes-BJ23Cp0g.mjs","names":[],"sources":["../src/admin/routes.ts"],"sourcesContent":["/**\n * Media admin routes — one static `defineAdminRoute` per HTTP method.\n *\n * **URL surface served by this module:**\n *\n * - GET /api/admin/media — list with search/filter + URLs\n * - GET /api/admin/media/<id> — single record with URL\n * - GET /api/admin/media/<id>/usage — entities referencing this media\n * - POST /api/admin/media — upload (multipart FormData)\n * - POST /api/admin/media/regenerate-variants — queue the library variant backfill\n * (synchronous only in a queueless app)\n * - DELETE /api/admin/media/<id> — delete + storage cleanup\n * - DELETE /api/admin/media — bulk delete (body.ids[], ≤100)\n *\n * Standard entity CRUD (PATCH with translations) falls through to the\n * generic entity handler — add `Media` to `entities` in your handler config.\n *\n * **Why per-method `defineAdminRoute`** (vs. the previous top-level\n * `resource: 'media'` + auto-mapped permission):\n *\n * - The wrapper (`guardedHandler` from `@murumets-ee/core`) owns the\n * permission gate, `permission.denied` audit, and 403 body shape\n * uniformly with every other migrated plugin. The previous shape\n * relied on `METHOD_TO_ACTION` auto-mapping at the api-handler\n * dispatch level which couldn't emit per-route audit metadata.\n * - Inline `if (!checkPermission('media', 'create')) ...` defenses\n * at the regenerate-variants / upload / delete branches are now\n * redundant — the wrapper enforces the permission BEFORE the\n * handler runs.\n *\n * **`matchAnyPath` rationale:** media's URL surface predates the\n * static-second-segment convention every other plugin follows\n * (`/taxonomy/<vocab>/<id>`, `/settings/<namespace>/<rest>`). The\n * second segment under `/media` is the media id itself — a runtime\n * UUID — which the dispatcher's literal `segments[0]` match would\n * miss for every request. The catch-all flag declares \"this entry\n * claims every (prefix, method) sub-path no other entry matched\" so\n * the existing URL contract works under the per-method dispatch\n * model. Static POST sub-paths (`regenerate-variants`) take\n * precedence over the catch-all entry on POST. See\n * `DefineAdminRouteSpec.matchAnyPath` in `@murumets-ee/core` for the\n * full contract.\n *\n * **Default roles:** broad for view (`['admin', 'editor', 'agent',\n * 'viewer']`), narrower for writes (`['admin', 'editor']`).\n * Conservative starting point — apps can grant more via the\n * Permissions UI.\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { mediaRoutes } from '@murumets-ee/media/admin'\n * import { Media } from '@murumets-ee/media'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [Article, Media],\n * routes: [...mediaRoutes()],\n * })\n * ```\n */\n\nimport {\n type AdminRoute,\n type AdminRouteHandler,\n combineAdminRoutes,\n defineAdminRoute,\n runBounded,\n safeAudit,\n safeAuditMany,\n} from '@murumets-ee/core'\nimport type { MediaClient } from '../client.js'\nimport { readMediaConfig } from '../media-config.js'\nimport type { MediaPickerItem, MediaPickerListResult } from '../picker/types.js'\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction isValidUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value)\n}\n\n/**\n * Closed enum of allowed `mediaType` filter values, in lockstep with the\n * `mediaType` field on the Media entity. The list MUST match\n * `MediaListOptions.mediaType` (declared in `../types.js`) — TypeScript\n * doesn't link the two automatically, so the small drift risk is\n * accepted in exchange for not pulling a runtime dep on the entity\n * schema package just to read its enum.\n *\n * Used as both the runtime allowlist (`isAllowedMediaType`) and the\n * source of truth for the narrowed type the guard produces — keeping\n * `as` casts off the handler's hot path.\n */\nconst ALLOWED_MEDIA_TYPES = ['image', 'video', 'audio', 'document', 'other'] as const\ntype AllowedMediaType = (typeof ALLOWED_MEDIA_TYPES)[number]\n\nfunction isAllowedMediaType(value: string): value is AllowedMediaType {\n // Cast to readonly string[] so the typed-tuple `includes` check works\n // with an arbitrary string input — `Array.prototype.includes`'s\n // signature on a typed tuple only accepts members of the tuple\n // (TS 4.9+ literal-narrowing), which is exactly what we want to\n // sidestep here.\n return (ALLOWED_MEDIA_TYPES as readonly string[]).includes(value)\n}\n\n/**\n * Hard cap on the `offset` query param. The dispatcher's allowed-pages\n * model is `limit ∈ [1, 100]`; even with the max page size that's\n * 1000 pages before hitting MAX_OFFSET, which is well beyond any\n * realistic admin-UI scroll depth. Forces slow-discard offset attacks\n * (`?offset=999999999`) to revert to a sane upper bound. Cursor-based\n * pagination would let this go higher, but the media list is\n * offset-based by convention with the entity-list shell.\n */\nconst MAX_OFFSET = 100_000\n\n/**\n * Strict non-negative integer parser for query params.\n *\n * `Number(raw)` silently coerces blanks (`'' → 0`), hex (`'0x05' → 5`),\n * exponent notation (`'1e2' → 100`), and signed (`'+5'/'-5'`) values —\n * all of which pass a downstream `Number.isInteger(n) && n >= 0` check.\n * Pre-filtering with `/^\\d+$/` keeps the contract honest: \"if you don't\n * send a pure non-negative integer string, you get the default.\" Same\n * pattern as `packages/taxonomy/src/admin/routes.ts:handleGet` tree\n * branch from PR-C-taxonomy.\n */\nfunction parseUintParam(raw: string | null, fallback: number): number {\n if (raw === null || !/^\\d+$/.test(raw)) return fallback\n const parsed = Number(raw)\n // The regex above stops hex / exponent / signed / whitespace / blank\n // inputs, but a long digit-only string still slips past — `Number(...)`\n // returns `Infinity` past ~309 digits, and precision is lost past\n // 2^53. Both would propagate through `client.findMany`'s\n // `offset: parsed` into a Postgres query that either crashes the\n // driver (`Infinity` is not a valid bigint) or silently rounds (the\n // 2^53 precision-loss boundary). Reject via `Number.isSafeInteger`\n // so overflowing inputs revert to `fallback` like every other\n // malformed value.\n if (!Number.isSafeInteger(parsed)) return fallback\n return parsed\n}\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction jsonResponse(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction jsonError(message: string, status: number): Response {\n return jsonResponse({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Per-request MediaClient factory + cached storage client\n// ---------------------------------------------------------------------------\n//\n// MediaClient and its AdminClient MUST be built per-request — AdminClient's\n// context resolver is captured eagerly at construction (see\n// buildContextResolver in @murumets-ee/core/clients). A module-level singleton\n// would bake the first request's user + tenant scope into every subsequent\n// request's writes — a cross-request permission/scope leak.\n//\n// Storage config is process-global and safe to cache once.\n\ntype StorageClient = Awaited<ReturnType<typeof import('@murumets-ee/storage').createStorageClient>>\n\ninterface StorageState {\n clientPromise: Promise<StorageClient> | null\n}\n\n// Module-level state. `null` once eviction fires on a rejection so the next\n// request gets a fresh resolution attempt (see `getStorage`'s `.catch`).\nconst storageState: StorageState = { clientPromise: null }\n\n/**\n * Resolve the process-wide storage client. The pending-promise slot is\n * cleared on rejection so a transient `createStorageClient` failure\n * (DB hiccup, misconfig) doesn't poison every subsequent media request\n * for the lifetime of the Node process. Same pattern as\n * `packages/taxonomy/src/admin/routes.ts:getClient` from PR-C-taxonomy.\n */\nasync function getStorage(): Promise<StorageClient> {\n if (!storageState.clientPromise) {\n const pending = (async () => {\n const { getApp } = await import('@murumets-ee/core')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n const app = getApp()\n return createStorageClient(getStorageConfig(), { app })\n })()\n // Clear the slot on rejection so a transient failure doesn't poison\n // every subsequent request. `pending.catch(handler)` attaches a\n // synchronous rejection listener that resets the cached slot — the\n // handler returns `undefined`, NOT a re-throw — so the new\n // `.catch`-returned promise resolves, but we never await or hold\n // that promise. The ORIGINAL `pending` (stored in\n // `storageState.clientPromise`) is what callers `await`, and it's\n // still in its rejected state — so the caller observing this\n // resolution sees the underlying error. The `.catch` also marks\n // the rejection as \"handled\" for Node's unhandled-rejection\n // tracker. `storageState.clientPromise` holds the original `pending`\n // so concurrent in-flight callers share one resolution.\n pending.catch(() => {\n if (storageState.clientPromise === pending) storageState.clientPromise = null\n })\n storageState.clientPromise = pending\n }\n return storageState.clientPromise\n}\n\nasync function getMediaClient(): Promise<MediaClient> {\n const { createAdminClient } = await import('@murumets-ee/core/clients')\n const { MediaClient } = await import('../client.js')\n const { Media } = await import('../entity.js')\n const storage = await getStorage()\n const admin = createAdminClient(Media)\n return new MediaClient({ admin, storage })\n}\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\nconst handleGet: AdminRouteHandler = async (req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n const segments = ctx.segments\n\n // GET /media/<id>/usage — DB-only lookup, safe even when storage is\n // unconfigured. Validate the UUID first so a malformed id 400s\n // uniformly with the storage-configured branch below.\n if (segments.length === 2 && segments[1] === 'usage') {\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { findMediaUsages } = await import('../usage.js')\n const { getApp } = await import('@murumets-ee/core')\n const app = getApp()\n const usages = await findMediaUsages(id, app)\n return jsonResponse({ usages })\n }\n\n // Reject unknown sub-paths explicitly. The wrapper-gate has already\n // passed (caller has `media:view`); a handler-level 404 here matches\n // the dispatcher's miss-shape so unknown URLs don't fall through to\n // the single-id branch and 400/500 with a misleading reason. The\n // only valid 2-segment URL is `<id>/usage`, which was already\n // claimed by the early-return above — anything else with >=2\n // segments is not a recognized media route.\n if (segments.length >= 2) return jsonError('Not found', 404)\n\n // GET /media/<id> — validate UUID up front so a bad request still\n // 400s when storage happens to be unconfigured (matches DELETE).\n const singleId = segments.length > 0 ? segments[0] : undefined\n if (singleId !== undefined && !isValidUuid(singleId)) {\n return jsonError('Invalid media ID format', 400)\n }\n\n // Everything below needs a working storage client. If env isn't\n // wired, return a structured \"disabled\" response rather than 500 —\n // the media list page renders a banner and new admins can finish\n // onboarding without being blocked on a crash loop.\n if (!isStorageConfigured()) {\n const reason = getStorageConfigReason() ?? 'Storage not configured'\n if (segments.length > 0) {\n // Single item — treat as not-found-ish to avoid leaking\n // existence; include reason so the UI can surface it.\n return jsonResponse({ error: reason, configured: false, reason }, 503)\n }\n // GET /media — empty list + disabled flag for the picker's banner.\n const response: MediaPickerListResult & { configured: false; reason: string } = {\n items: [],\n total: 0,\n configured: false,\n reason,\n }\n return jsonResponse(response)\n }\n\n const client = await getMediaClient()\n\n // GET /media/<id> — single item with URL (full record for EntityForm + picker)\n if (singleId !== undefined) {\n const record = await client.findById(singleId)\n if (!record) return jsonError('Media not found', 404)\n\n const url = await client.getUrl(singleId)\n return jsonResponse({ ...record, url })\n }\n\n // GET /media — list with search/filter + batch URL resolution\n const url = new URL(req.url)\n const search = url.searchParams.get('search') ?? undefined\n // mediaType MUST be validated against the entity's closed enum before\n // it reaches `client.findMany` — the previous shape force-cast the raw\n // query value with `as 'image' | ...` which is a type-system lie. A\n // bogus value like `?mediaType=bogus` would parameterize into\n // `WHERE media_type = 'bogus'` (no SQL injection — Drizzle is\n // parameterized — but the row count is silently zero, which is\n // confusing). Empty string from `?mediaType=` is also passed-through\n // by the prior `?? undefined` shape since empty string is not null.\n // Allowlist + type guard drops bogus / empty values cleanly so the\n // filter is omitted instead of applied with a no-match value.\n const rawMediaType = url.searchParams.get('mediaType')\n const mediaType =\n rawMediaType !== null && isAllowedMediaType(rawMediaType) ? rawMediaType : undefined\n // Strict parsing keeps the contract honest — see `parseUintParam`\n // JSDoc. Cap limit to [1, 100] and offset to [0, MAX_OFFSET] so a\n // request can't ask for an unboundedly large page nor force a\n // slow-discard scan with `?offset=99999999`.\n const limit = Math.min(Math.max(parseUintParam(url.searchParams.get('limit'), 24), 1), 100)\n const offset = Math.min(parseUintParam(url.searchParams.get('offset'), 0), MAX_OFFSET)\n\n const result = await client.findMany({\n ...(search !== undefined && { search }),\n ...(mediaType !== undefined && { mediaType }),\n limit,\n offset,\n })\n\n // Resolve original URLs for all items, but thumbnail variants ONLY for\n // images — a video/audio/document/other id will never have a `thumbnail`\n // variant, so asking `getVariantUrls` to resolve one is pure waste (a\n // storage lookup that falls through to the original, then gets discarded\n // below anyway). `media-list-page.tsx` filters the same way.\n const ids = result.items.map((item) => item.id)\n const imageIds = result.items.filter((item) => item.mediaType === 'image').map((item) => item.id)\n const [urlMap, thumbMap] = await Promise.all([\n client.getUrls(ids),\n client.getVariantUrls(imageIds, 'thumbnail'),\n ])\n\n const items: (MediaPickerItem & { thumbnailUrl?: string })[] = result.items.map((item) => {\n // F115: `getVariantUrls` falls back to the ORIGINAL asset URL for any id\n // with no `thumbnail` variant — correct for an image that just hasn't\n // been processed yet, wrong for a video/audio/document/other row, which\n // will never have one. Gating on `mediaType` keeps `thumbnailUrl` ABSENT\n // rather than pointing a consumer's `<img src>` at a `.mp4`.\n const thumbnailUrl = item.mediaType === 'image' ? thumbMap.get(item.id) : undefined\n return {\n id: item.id,\n title: item.title ?? null,\n alt: item.alt ?? null,\n filename: item.filename,\n mimeType: item.mimeType,\n size: item.size,\n mediaType: item.mediaType,\n url: urlMap.get(item.id) ?? '',\n ...(thumbnailUrl !== undefined && { thumbnailUrl }),\n width: item.width ?? null,\n height: item.height ?? null,\n }\n })\n\n const response: MediaPickerListResult = { items, total: result.total }\n return jsonResponse(response)\n}\n\nconst handleUpload: AdminRouteHandler = async (req, ctx) => {\n const {\n isStorageConfigured,\n getStorageConfigReason,\n detectMimeType,\n isMimeTypeAllowed,\n readBoundedMultipart,\n tooLarge,\n } = await import('@murumets-ee/storage')\n\n // Upload is registered at `path: ''` (NOT matchAnyPath) — the\n // dispatcher only invokes this handler when segments=[]. The api-\n // handler ALSO rejects empty/whitespace-only first segments with a\n // 400 before any plugin dispatcher runs (see\n // `packages/admin-ui/src/server/api-handler/index.ts` segment-\n // validation block). So this guard is defense-in-depth — per HANDOFF\n // §\"Defense-in-depth `&& segments[i]` guards are fine\" — protecting\n // against a future framework invariant change that lets a non-empty\n // segment reach a `path: ''` static entry.\n if (ctx.segments.length > 0) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n // The plugin's `maxUploadSize` / `acceptedTypes`, from the registry the\n // merge step filled before any init — see `media-config.ts` (F007).\n const { maxUploadSize, acceptedTypes } = readMediaConfig()\n\n // F007: bound the body BEFORE `formData()` makes it resident — and before\n // building a MediaClient for a request that is about to be refused.\n const envelope = await readBoundedMultipart(req, maxUploadSize)\n if (!envelope.ok) return jsonError(envelope.error, envelope.status)\n const formData = envelope.value\n\n const file = formData.get('file')\n // FormData `get` returns string | File | null. Reject anything that\n // isn't a File so the typed `file.size`/`file.arrayBuffer()` below\n // is safe without a runtime cast.\n if (!(file instanceof File) || file.size === 0) {\n return jsonError('No file provided', 400)\n }\n\n // The envelope bound covers the whole body; this covers the file, before\n // `arrayBuffer()` copies it.\n if (file.size > maxUploadSize) {\n const refused = tooLarge(maxUploadSize)\n return jsonError(refused.error, refused.status)\n }\n\n const client = await getMediaClient()\n\n const buffer = Buffer.from(await file.arrayBuffer())\n\n // Detect actual MIME type from file content (prevents spoofing).\n const { mimeType, mismatch } = await detectMimeType(\n buffer,\n file.type || 'application/octet-stream',\n )\n if (mismatch) {\n return jsonError(\n `File content doesn't match declared type: claimed ${file.type}, detected ${mimeType}`,\n 400,\n )\n }\n // `acceptedTypes` against the DETECTED type, so a renamed file cannot\n // claim its way past the allowlist.\n if (!isMimeTypeAllowed(mimeType, acceptedTypes)) {\n return jsonError(`File type ${mimeType} is not accepted`, 415)\n }\n\n // Per-upload visibility, DEFAULTING TO PRIVATE — the caller opts in.\n //\n // This route serves two populations with opposite needs. The media picker\n // uploads publishable web assets: a page's hero image MUST be public or the\n // public site resolves it to `null` and renders no images at all, with a 200\n // on every page and one warn log (F030). `packages/rent-ui`'s inspection\n // wizard posts to this SAME route with handover and return photos — vehicle\n // and apartment condition shots, plates, interiors, occasionally documents —\n // which must stay behind time-limited signed urls.\n //\n // Deny-by-default decides the direction, and the asymmetry is the argument:\n // forget the opt-in and an image is invisible, which is annoying, visible and\n // fixable; default to public and forget an opt-out and those photos become\n // permanently world-readable. A missed opt-in cannot leak. So the default is\n // unchanged (`private` via StorageClient's own fallback) and rent's caller is\n // untouched — it sends nothing and behaves exactly as before.\n const visibilityRaw = formData.get('visibility')\n if (visibilityRaw !== null && visibilityRaw !== 'public' && visibilityRaw !== 'private') {\n return jsonError(\"Field 'visibility' must be 'public' or 'private'\", 400)\n }\n const result = await client.upload(buffer, {\n filename: file.name,\n mimeType,\n size: file.size,\n uploadedBy: ctx.user.id,\n ...(visibilityRaw !== null && { visibility: visibilityRaw }),\n })\n\n const item: MediaPickerItem = {\n id: result.media.id,\n title: result.media.title ?? null,\n alt: result.media.alt ?? null,\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n url: result.url,\n width: result.media.width ?? null,\n height: result.media.height ?? null,\n }\n\n safeAudit(ctx, {\n action: 'media.upload',\n entityType: 'media',\n entityId: result.media.id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n changes: {\n filename: result.media.filename,\n mimeType: result.media.mimeType,\n size: result.media.size,\n mediaType: result.media.mediaType,\n },\n })\n\n return jsonResponse(item, 201)\n}\n\nconst handleRegenerateVariants: AdminRouteHandler = async (_req, ctx) => {\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n\n // Static POST path='regenerate-variants' — the dispatcher only invokes\n // this handler when `segments[0] === 'regenerate-variants'`. Trailing\n // segments (e.g. POST /media/regenerate-variants/extra) aren't a\n // supported sub-route.\n if (ctx.segments.length !== 1) return jsonError('Not found', 404)\n\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const { getApp, getContext } = await import('@murumets-ee/core')\n const { getMediaJobs } = await import('../jobs/slot.js')\n const app = getApp()\n\n // With a queue: queue the library walk and return at once (images D004, S6).\n // The walk queues one pass per photograph; the Queue page and the media\n // library count them down while the site keeps serving.\n const jobs = getMediaJobs()\n if (jobs) {\n const { enqueueVariantsBackfill } = await import('../jobs/backfill-trigger.js')\n const { jobId, alreadyRunning } = await enqueueVariantsBackfill(app, jobs.variantsBackfill)\n safeAudit(ctx, {\n action: 'media.regenerate_variants',\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n metadata: { mode: 'queued', jobId, alreadyRunning },\n })\n const { getVariantBacklog } = await import('../jobs/backlog.js')\n const backlog = await getVariantBacklog(app).catch(() => null)\n return jsonResponse({ mode: 'queued', jobId, alreadyRunning, backlog }, 202)\n }\n\n // No queue in this app: the synchronous loop it always had, now additive.\n const { regenerateAllVariants } = await import('../regenerate-variants.js')\n const { createStorageClient } = await import('@murumets-ee/storage')\n const { getStorageConfig } = await import('@murumets-ee/storage/plugin')\n const storage = createStorageClient(getStorageConfig(), { app })\n\n const result = await regenerateAllVariants({\n app,\n storage,\n logger: app.logger.child({ media: true }),\n contextResolver: () => {\n const requestCtx = getContext()\n if (!requestCtx?.user || !requestCtx?.checker) return undefined\n return {\n user: requestCtx.user,\n checker: requestCtx.checker,\n ...(requestCtx.scope !== undefined && { scope: requestCtx.scope }),\n }\n },\n })\n\n safeAudit(ctx, {\n action: 'media.regenerate_variants',\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n metadata: {\n mode: 'inline',\n total: result.total,\n processed: result.processed,\n errors: result.errors,\n },\n })\n\n return jsonResponse({ mode: 'inline', ...result })\n}\n\n/**\n * Cap on a bulk delete — the same number the generic entity CRUD route's own\n * bulk delete uses (`entity-crud.ts`'s `MAX_BULK_DELETE`), so a caller sees\n * one consistent limit regardless of which admin list it is deleting from.\n */\nconst MAX_BULK_DELETE = 100\n\n/**\n * Bound on the bulk-delete request body. A body here is `{ ids: string[] }`\n * of short UUID strings — generous headroom for {@link MAX_BULK_DELETE} of\n * them (each ~38 bytes quoted-and-comma'd).\n */\nconst MAX_BULK_DELETE_BODY_BYTES = 16 * 1024\n\n/** A validated bulk-delete request, or the error response to send instead. */\ntype BulkDeleteBody = { ids: string[] } | { error: string; status: number }\n\n/**\n * Read and parse the bulk-delete body, refusing anything past\n * {@link MAX_BULK_DELETE_BODY_BYTES}.\n *\n * `content-length` alone is NOT a bound — it is client-supplied, so a\n * chunked request (no header at all) or a spoofed small one sails through a\n * header-only check straight into an unbounded `req.json()` buffering\n * whatever the caller sends (review finding, entity-table PR06). Streamed\n * and byte-counted instead, same shape `entity-crud.ts`'s `readJsonBody`\n * uses for arbitrary write bodies — this one is sized for a much smaller,\n * closed shape, not copied wholesale, because `@murumets-ee/media` must not\n * depend on `@murumets-ee/admin-ui` (wrong dependency direction).\n */\nasync function readBulkDeleteBody(req: Request): Promise<BulkDeleteBody> {\n const declared = Number(req.headers.get('content-length'))\n if (Number.isFinite(declared) && declared > MAX_BULK_DELETE_BODY_BYTES) {\n return { error: 'Request body exceeds the maximum size', status: 413 }\n }\n\n const body = req.body\n let text: string\n if (body === null) {\n text = await req.text()\n if (Buffer.byteLength(text, 'utf8') > MAX_BULK_DELETE_BODY_BYTES) {\n return { error: 'Request body exceeds the maximum size', status: 413 }\n }\n } else {\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n if (value === undefined) continue\n total += value.byteLength\n if (total > MAX_BULK_DELETE_BODY_BYTES) {\n // Stop pulling — without the cancel the peer keeps sending into a\n // reader nobody drains, which is the connection this refusal\n // exists to end.\n await reader.cancel().catch(() => undefined)\n return { error: 'Request body exceeds the maximum size', status: 413 }\n }\n chunks.push(value)\n }\n } finally {\n reader.releaseLock()\n }\n text = Buffer.concat(chunks).toString('utf8')\n }\n\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch {\n return { error: 'Invalid JSON body', status: 400 }\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n return { error: 'Body must be a JSON object', status: 400 }\n }\n\n const ids = (raw as Record<string, unknown>).ids\n if (!Array.isArray(ids) || ids.length === 0) {\n return { error: 'Body must contain \"ids\" array', status: 400 }\n }\n if (ids.length > MAX_BULK_DELETE) {\n return { error: `Bulk delete limited to ${MAX_BULK_DELETE} items per request`, status: 400 }\n }\n\n // Reject anything that isn't a well-formed media id before any mutation —\n // `client.delete()` would otherwise throw mid-batch, leaving a partially\n // deleted set for a request that was malformed from the start.\n //\n // `Array.isArray` narrows to `any[]` (its lib.es5.d.ts signature is\n // `arg is any[]`), so without the cast below every read of the loop\n // variable counts as an `any` against `verify:types` — `as unknown[]`\n // resets it to a type `typeof`/`isValidUuid` still narrow correctly, one\n // step later than the guard that actually proves it.\n const validated: string[] = []\n for (const id of ids as unknown[]) {\n if (typeof id !== 'string' || !isValidUuid(id)) {\n return { error: 'Body \"ids\" must contain valid media IDs', status: 400 }\n }\n validated.push(id)\n }\n return { ids: validated }\n}\n\nconst handleDelete: AdminRouteHandler = async (req, ctx) => {\n const segments = ctx.segments\n\n // DELETE /media — no id supplied. Bulk delete (body: { ids: string[] }),\n // matching the generic entity CRUD route's own bulk shape — `EntityList`'s\n // \"Delete selected\" always sends this, and Media's `matchAnyPath` DELETE\n // entry claims the whole `/media` prefix, so without this branch that\n // request lands here and gets refused with \"Media ID required\" (found via\n // browser verification, entity-table PR06 — S8's demonstration on a real\n // Media list is what surfaced it: nothing before this PR had exercised a\n // bulk delete against the live Media admin page).\n if (segments.length === 0) {\n const parsed = await readBulkDeleteBody(req)\n if ('error' in parsed) return jsonError(parsed.error, parsed.status)\n\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n if (!isStorageConfigured()) {\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n const client = await getMediaClient()\n // MAX_BULK_DELETE bounds the TOTAL; `runBounded` bounds the CONCURRENCY —\n // each `delete()` does entity DB work AND storage object/metadata work,\n // so 100 ids fired via a bare `Promise.all` would open up to 100 of both\n // at once, which is exactly the shared-pool-contention shape CLAUDE.md's\n // \"No Unbounded Fan-Out\" rule exists to catch (CodeRabbit CLI finding,\n // entity-table PR06). The worker catches internally and returns a\n // settled-shaped result instead of letting `runBounded` see a rejection —\n // that keeps its own fail-fast behavior from firing, so this stays\n // allSettled-equivalent: every id gets attempted regardless of a sibling's\n // failure, and the audit trail for the ones that DID succeed survives one\n // that didn't (`safeAuditMany` below would otherwise be skipped entirely\n // on any rejection, auditing NONE of them). The first failure is still\n // rethrown after the audit write, so the response shape is unchanged —\n // no new 207-partial-success contract.\n const results = await runBounded(parsed.ids, async (id) => {\n try {\n await client.delete(id)\n return { status: 'fulfilled' as const, id }\n } catch (reason) {\n return { status: 'rejected' as const, id, reason }\n }\n })\n const deletedIds = results.filter((r) => r.status === 'fulfilled').map((r) => r.id)\n\n // ONE batched write, awaited — not N unawaited `safeAudit` calls racing\n // the connection pool after the response is already decided (review\n // finding, entity-table PR06; `safeAuditMany`'s own docblock names this\n // exact loop shape as the reason it exists).\n await safeAuditMany(\n ctx,\n deletedIds.map((id) => ({\n action: 'media.delete',\n entityType: 'media',\n entityId: id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n metadata: { bulk: true },\n })),\n )\n\n const failure = results.find((r) => r.status === 'rejected')\n if (failure && failure.status === 'rejected') throw failure.reason\n\n return jsonResponse({ deleted: deletedIds.length })\n }\n\n // Reject sub-paths beyond /<id> — DELETE /media/<id>/usage etc.\n if (segments.length > 1) return jsonError('Not found', 404)\n\n const id = segments[0]\n if (!isValidUuid(id)) return jsonError('Invalid media ID format', 400)\n\n const { isStorageConfigured, getStorageConfigReason } = await import('@murumets-ee/storage')\n if (!isStorageConfigured()) {\n // Can't safely delete — MediaClient needs storage to remove the\n // actual object, and partial delete (DB row gone, object orphaned)\n // would leak storage. Surface the reason so the UI can display it.\n return jsonError(getStorageConfigReason() ?? 'Storage not configured', 503)\n }\n\n // AdminClient.delete() checks entity_refs and throws\n // ReferencedEntityError if this media is still referenced. The\n // error bubbles to the caller's error handler which returns 409\n // with usage details.\n const client = await getMediaClient()\n await client.delete(id)\n\n safeAudit(ctx, {\n action: 'media.delete',\n entityType: 'media',\n entityId: id,\n userId: ctx.user.id,\n ...(ctx.user.name !== undefined && { userName: ctx.user.name }),\n })\n\n return jsonResponse({ deleted: 1 })\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Default roles for view: broad reach across the admin shell.\n *\n * `BUILT_IN_ROLES` in `packages/auth/src/permissions.ts` is\n * `['admin', 'public', 'authenticated', 'agent', 'customer']` — `admin` is\n * hardcoded as an unconditional yes in `buildPermissionChecker`,\n * `agent` is the only non-admin built-in that flows through\n * `buildInitialRoleDefinitions()` + `upsertBuiltInRoles` with default\n * media access (`customer` seeds with zero permissions — see that\n * function's JSDoc). The `agent` entry in this list is what gives ops\n * agents read-only media access on first boot of a fresh install.\n *\n * `editor` and `viewer` are CONVENTIONAL app-defined roles —\n * apps that follow the scaffold pattern create them as part of\n * their own role catalog. Including them in `defaultRoles` doesn't\n * seed them (the seeder only iterates the built-ins above), but\n * the values DO flow into the process-local permission catalog\n * (see `registerPermission` in `@murumets-ee/core`), which the\n * forthcoming Permission Matrix UI (PR-D) reads to show \"this\n * route's recommended default grants\" against the app's actual\n * role set. The catalog is also the mechanism via which a future\n * upgrade of `upsertBuiltInRoles` could extend the seed surface\n * to app-defined roles without each plugin having to re-declare\n * its defaults.\n */\nconst VIEW_DEFAULT_ROLES = ['admin', 'editor', 'agent', 'viewer'] as const\n\n/** Default roles for create/delete — narrower than view. */\nconst WRITE_DEFAULT_ROLES = ['admin', 'editor'] as const\n\n/**\n * Build admin API routes for media management.\n *\n * Returns `AdminRoute[]` from `combineAdminRoutes` — one entry per\n * `(prefix, method)` after grouping. Callers spread the result into\n * their top-level routes list: `routes: [...mediaRoutes()]`.\n *\n * Four `defineAdminRoute` entries:\n *\n * - GET matchAnyPath with `media:view` defaultRoles: VIEW_DEFAULT_ROLES\n * - POST path='' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - POST path='regenerate-variants' `media:create` defaultRoles: WRITE_DEFAULT_ROLES\n * - DELETE matchAnyPath with `media:delete` defaultRoles: WRITE_DEFAULT_ROLES\n *\n * Permissions are auto-registered by the entity catalog\n * (`buildResourceCatalog` in `@murumets-ee/auth`) AND by\n * `registerPermission` inside `defineAdminRoute`. Idempotent —\n * `registerPermission` unions `defaultRoles` on repeat registration,\n * so the framework's two pathways agree on the final grant set.\n *\n * Standard entity CRUD (PATCH with translations) is NOT registered\n * here — it falls through to the generic entity handler. Add `Media`\n * to the `entities` array in your handler config to enable it.\n */\nexport function mediaRoutes(): AdminRoute[] {\n const entries = [\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'GET',\n permission: 'media:view',\n defaultRoles: VIEW_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Read media — list, single item, or referencing-entity usage report.',\n handler: handleGet,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description: 'Upload a media file (multipart FormData with `file` field).',\n handler: handleUpload,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: 'regenerate-variants',\n method: 'POST',\n permission: 'media:create',\n defaultRoles: WRITE_DEFAULT_ROLES,\n description:\n 'Catch every image up with the current shapes, widths and styles — queued as a background ' +\n 'backfill (synchronous only when the app has no queue).',\n handler: handleRegenerateVariants,\n }),\n defineAdminRoute({\n prefix: 'media',\n path: '',\n method: 'DELETE',\n permission: 'media:delete',\n defaultRoles: WRITE_DEFAULT_ROLES,\n matchAnyPath: true,\n description: 'Delete a media record + its storage object.',\n handler: handleDelete,\n }),\n ]\n\n return combineAdminRoutes(entries)\n}\n"],"mappings":"+KA+EA,MAAM,EAAU,kEAEhB,SAAS,EAAY,EAA4C,CAC/D,OAAO,IAAU,IAAA,IAAa,EAAQ,KAAK,CAAK,CAClD,CAcA,MAAM,EAAsB,CAAC,QAAS,QAAS,QAAS,WAAY,OAAO,EAG3E,SAAS,EAAmB,EAA0C,CAMpE,OAAQ,EAA0C,SAAS,CAAK,CAClE,CAwBA,SAAS,EAAe,EAAoB,EAA0B,CACpE,GAAI,IAAQ,MAAQ,CAAC,QAAQ,KAAK,CAAG,EAAG,OAAO,EAC/C,IAAM,EAAS,OAAO,CAAG,EAWzB,OADK,OAAO,cAAc,CAAM,EACzB,EADmC,CAE5C,CAMA,SAAS,EAAa,EAAe,EAAS,IAAe,CAC3D,OAAO,IAAI,SAAS,KAAK,UAAU,CAAI,EAAG,CACxC,SACA,QAAS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,CACH,CAEA,SAAS,EAAU,EAAiB,EAA0B,CAC5D,OAAO,EAAa,CAAE,MAAO,CAAQ,EAAG,CAAM,CAChD,CAsBA,MAAM,EAA6B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