@capacms/sdk 1.0.0-next.1 → 1.0.0-next.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +487 -0
  2. package/README.md +1810 -183
  3. package/bin/capa-codegen.js +192 -5
  4. package/bin/capa.js +235 -0
  5. package/bin/graphql-project.js +142 -0
  6. package/bin/project-env.js +58 -0
  7. package/dist/client.d.ts +89 -4
  8. package/dist/client.js +40 -5
  9. package/dist/codegen.d.ts +55 -0
  10. package/dist/codegen.js +320 -39
  11. package/dist/config.d.ts +5 -36
  12. package/dist/config.js +47 -1
  13. package/dist/esm/image/index.d.ts +187 -0
  14. package/dist/esm/image/index.js +353 -0
  15. package/dist/esm/image/shared-params.generated.d.ts +314 -0
  16. package/dist/esm/image/shared-params.generated.js +680 -0
  17. package/dist/esm/nextjs/image-loader.d.ts +60 -0
  18. package/dist/esm/nextjs/image-loader.js +67 -0
  19. package/dist/esm/nextjs/overlay.d.ts +30 -0
  20. package/dist/esm/nextjs/overlay.js +75 -0
  21. package/dist/esm/overlay/index.d.ts +32 -0
  22. package/dist/esm/overlay/index.js +576 -0
  23. package/dist/esm/overlay/protocol.d.ts +187 -0
  24. package/dist/esm/overlay/protocol.js +240 -0
  25. package/dist/esm/package.json +4 -0
  26. package/dist/graphql-codegen.d.ts +117 -0
  27. package/dist/graphql-codegen.js +705 -0
  28. package/dist/http.js +1 -1
  29. package/dist/image/index.d.ts +187 -0
  30. package/dist/image/index.js +362 -0
  31. package/dist/image/shared-params.generated.d.ts +314 -0
  32. package/dist/image/shared-params.generated.js +700 -0
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +2 -1
  35. package/dist/next/attrs.d.ts +84 -10
  36. package/dist/next/attrs.js +119 -2
  37. package/dist/next/client.d.ts +176 -32
  38. package/dist/next/client.js +212 -90
  39. package/dist/next/entry-fields.d.ts +203 -0
  40. package/dist/next/entry-fields.js +2 -0
  41. package/dist/next/errors.d.ts +136 -0
  42. package/dist/next/errors.js +214 -0
  43. package/dist/next/field-names.d.ts +37 -0
  44. package/dist/next/field-names.js +145 -0
  45. package/dist/next/graphql/build.d.ts +27 -0
  46. package/dist/next/graphql/build.js +98 -0
  47. package/dist/next/graphql/documents.d.ts +67 -0
  48. package/dist/next/graphql/documents.js +35 -0
  49. package/dist/next/graphql/edit-mode.d.ts +16 -0
  50. package/dist/next/graphql/edit-mode.js +93 -0
  51. package/dist/next/graphql/filter-values.d.ts +34 -0
  52. package/dist/next/graphql/filter-values.js +96 -0
  53. package/dist/next/graphql/introspection.d.ts +89 -0
  54. package/dist/next/graphql/introspection.js +102 -0
  55. package/dist/next/graphql/plan.d.ts +115 -0
  56. package/dist/next/graphql/plan.js +531 -0
  57. package/dist/next/graphql/request.d.ts +228 -0
  58. package/dist/next/graphql/request.js +283 -0
  59. package/dist/next/graphql/rest.d.ts +66 -0
  60. package/dist/next/graphql/rest.js +502 -0
  61. package/dist/next/graphql/selection.d.ts +55 -0
  62. package/dist/next/graphql/selection.js +212 -0
  63. package/dist/next/graphql/sha256.d.ts +13 -0
  64. package/dist/next/graphql/sha256.js +86 -0
  65. package/dist/next/graphql/summary.d.ts +83 -0
  66. package/dist/next/graphql/summary.js +151 -0
  67. package/dist/next/graphql/tree-layout.d.ts +36 -0
  68. package/dist/next/graphql/tree-layout.js +20 -0
  69. package/dist/next/graphql/tree.d.ts +171 -0
  70. package/dist/next/graphql/tree.js +258 -0
  71. package/dist/next/graphql/typed.d.ts +261 -0
  72. package/dist/next/graphql/typed.js +146 -0
  73. package/dist/next/index.d.ts +30 -5
  74. package/dist/next/index.js +32 -1
  75. package/dist/next/inflate.d.ts +51 -0
  76. package/dist/next/inflate.js +243 -0
  77. package/dist/next/key-family.d.ts +31 -0
  78. package/dist/next/key-family.js +66 -0
  79. package/dist/next/select-types.d.ts +58 -5
  80. package/dist/next/system-keys.d.ts +27 -0
  81. package/dist/next/system-keys.js +42 -0
  82. package/dist/nextjs/image-loader.d.ts +60 -0
  83. package/dist/nextjs/image-loader.js +71 -0
  84. package/dist/nextjs/index.d.ts +484 -5
  85. package/dist/nextjs/index.js +688 -6
  86. package/dist/nextjs/overlay.d.ts +30 -0
  87. package/dist/nextjs/overlay.js +78 -0
  88. package/dist/overlay/index.d.ts +14 -2
  89. package/dist/overlay/index.js +282 -43
  90. package/dist/overlay/protocol.d.ts +98 -2
  91. package/dist/overlay/protocol.js +151 -4
  92. package/dist/webhooks.d.ts +8 -0
  93. package/package.json +63 -15
@@ -0,0 +1,700 @@
1
+ "use strict";
2
+ // GENERATED by scripts/shared-image.js from packages/shared/src/image/params.ts, the rules the API serves
3
+ // /files/* by. Do not edit: change the source, and the API and this package follow.
4
+ /**
5
+ * Query parsing, validation and canonicalisation for `GET /files/*`
6
+ * (ADMIN_UI_OVERHAUL §0i.1, "The image processor, made tight").
7
+ *
8
+ * PURE ON PURPOSE. Nothing here touches sharp, the network or the database, so
9
+ * the whole parameter surface — every accepted value, every rejection, and the
10
+ * canonical spelling of every URL — is testable without a server and without a
11
+ * live Backblaze object. That matters for this route in particular: its eight
12
+ * parity fixtures are all 400/404 cases because a DB hit immediately leaves the
13
+ * process (docs/TURBINE_PORT_NOTES.md, "Deferred to the P6 cloud parity pass"),
14
+ * so the transform surface has no golden coverage at all unless it is reachable
15
+ * from a unit test.
16
+ *
17
+ * THE RULE THAT SHAPES EVERYTHING BELOW: a caller that sends only today's three
18
+ * parameters (`width`, `height`, `blur`) must get today's response. Every
19
+ * default here is therefore today's behaviour, and the one place that could
20
+ * have broken it — the canonical-query redirect — is deliberately gated on a
21
+ * NEW parameter being present. See `canonicalise`.
22
+ *
23
+ * WHY IT LIVES IN @capa/shared. `@capacms/sdk` builds image URLs, and a URL
24
+ * that is not spelled the way `canonicalise` spells it costs every first view
25
+ * a 301 that the edge then keeps for a year. So the SDK compiles this file into
26
+ * its own build rather than keeping a second copy of the rules, and its tests
27
+ * run what it builds back through `canonicalise`. The API imports it from here.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.FRACTION_DECIMALS = exports.FOCAL_PARAMS = exports.NEW_PARAMS = exports.LEGACY_PARAMS = exports.AVIF_DEFAULT_QUALITY = exports.DEFAULT_QUALITY = exports.MAX_BLUR = exports.MIN_BLUR = exports.MAX_OUTPUT_EDGE = exports.OUTPUT_MIME = void 0;
31
+ exports.defaultQuality = defaultQuality;
32
+ exports.droppableQuality = droppableQuality;
33
+ exports.parseImageParams = parseImageParams;
34
+ exports.canonicalise = canonicalise;
35
+ exports.canonicalQuery = canonicalQuery;
36
+ exports.buildSignature = buildSignature;
37
+ exports.resolveAutoFormat = resolveAutoFormat;
38
+ exports.roundFraction = roundFraction;
39
+ exports.readFocalPoint = readFocalPoint;
40
+ exports.readCrop = readCrop;
41
+ exports.isStoredFocalPoint = isStoredFocalPoint;
42
+ exports.isStoredCrop = isStoredCrop;
43
+ exports.parseFocalParams = parseFocalParams;
44
+ exports.isCoverCrop = isCoverCrop;
45
+ exports.followsStoredFocal = followsStoredFocal;
46
+ exports.appliedFocal = appliedFocal;
47
+ exports.focalRegion = focalRegion;
48
+ /** Content type emitted for each explicitly requestable output format. */
49
+ exports.OUTPUT_MIME = {
50
+ webp: "image/webp",
51
+ avif: "image/avif",
52
+ jpeg: "image/jpeg",
53
+ png: "image/png",
54
+ };
55
+ /**
56
+ * The longest edge this route will ever produce.
57
+ *
58
+ * A cap rather than a clamp, because a clamp makes two different URLs return
59
+ * the same bytes and therefore occupy two edge objects for one representation.
60
+ * 4096 is the §0i.1 figure; it is also comfortably above any real layout width
61
+ * at dpr 3 (1365 CSS px).
62
+ */
63
+ exports.MAX_OUTPUT_EDGE = 4096;
64
+ /** Today's blur bounds, previously applied as a silent clamp. */
65
+ exports.MIN_BLUR = 1;
66
+ exports.MAX_BLUR = 256;
67
+ /** Default quality for lossy outputs except AVIF. Ignored for png, which is lossless. */
68
+ exports.DEFAULT_QUALITY = 80;
69
+ /**
70
+ * AVIF's own default quality (Penelope Hospitality onboarding, #300). At 80,
71
+ * AVIF came back larger than WebP at 80; 60 at effort 2 is 16 to 18% smaller
72
+ * than WebP with equal or better SSIM on eight client photos. The route's
73
+ * encoder and the effort live in apps/api (image-transform.ts); the number
74
+ * lives here because canonicalQuery has to know it (see droppableQuality).
75
+ */
76
+ exports.AVIF_DEFAULT_QUALITY = 60;
77
+ /**
78
+ * The quality an encode into `output` uses when the URL names none.
79
+ *
80
+ * The route only ever calls this with a format the URL asked for, explicitly or
81
+ * through `auto`: with no `format` and no `quality` it selects no encoder at
82
+ * all and the source keeps its own format (`resolveOutputFormat`).
83
+ */
84
+ function defaultQuality(output) {
85
+ return output === "avif" ? exports.AVIF_DEFAULT_QUALITY : exports.DEFAULT_QUALITY;
86
+ }
87
+ /**
88
+ * The `quality` canonicalQuery drops from a URL with this `format`, or null
89
+ * when it keeps every value.
90
+ *
91
+ * CANONICALISATION MUST NEVER CHANGE WHAT A URL RENDERS. A value may be dropped
92
+ * only when the URL without it encodes at that same value. After #300 gave
93
+ * AVIF its own default, dropping 80 everywhere sent `format=avif&quality=80`
94
+ * to `format=avif`, which is quality 60.
95
+ *
96
+ * - `avif`: null. 80 is not AVIF's default, so it must stay. 60 is, and could
97
+ * be dropped without changing the bytes; it is KEPT ON PURPOSE. The SDK's
98
+ * frozen URLs (#316, and @capacms/sdk's own tests) include
99
+ * `format=avif&quality=60`, which would start taking a 301; and an explicit
100
+ * number keeps meaning that number if AVIF's default is retuned, which
101
+ * `format=avif` does not. The cost is two edge objects for one image when a
102
+ * caller spells the default out.
103
+ * - `auto`: null. Negotiation picks AVIF (default 60) or WebP or the source's
104
+ * own format (default 80), so no single value means "no quality" for every
105
+ * browser.
106
+ * - `webp`, `jpeg`, `png` and no format: DEFAULT_QUALITY, as before.
107
+ *
108
+ * KNOWN GAP, older than #300 and left as it is because a URL with no `format`
109
+ * keeps its spelling: with no format the output follows the SOURCE, which a URL
110
+ * cannot see. `?quality=80&width=200` on an AVIF or HEIF source is an AVIF at
111
+ * 80, and `?width=200` keeps sharp's own AVIF default (50). `?quality=80` with
112
+ * nothing else redirects to the bare URL, which is the stored file, not a
113
+ * re-encode.
114
+ */
115
+ function droppableQuality(format) {
116
+ if (format === "avif" || format === "auto")
117
+ return null;
118
+ return exports.DEFAULT_QUALITY;
119
+ }
120
+ /**
121
+ * The parameters that existed before §0i.1.
122
+ *
123
+ * A URL built only from these is GRANDFATHERED: it is treated as already
124
+ * canonical and is never redirected, however it is spelled. Without this, every
125
+ * live `?width=100&height=50` in every customer's markup would start taking a
126
+ * 301 — which is not a behaviour anyone asked to change, and "keep today's
127
+ * calls byte-identical" outranks de-duplicating an edge object that has been
128
+ * duplicated for years already.
129
+ */
130
+ exports.LEGACY_PARAMS = new Set(["width", "height", "blur"]);
131
+ /** Parameters introduced by §0i.1. Their presence is what enables canonicalisation. */
132
+ exports.NEW_PARAMS = new Set(["format", "quality", "fit", "dpr", "upscale", "keepMetadata"]);
133
+ /**
134
+ * Fastify gives `?a=1&a=2` as an array. A repeated parameter has no defensible
135
+ * meaning here and silently picking one is exactly the "never silently ignored"
136
+ * failure §0i.1 calls out, so it is a rejection.
137
+ */
138
+ function single(raw, param) {
139
+ if (raw === undefined || raw === null)
140
+ return { ok: true };
141
+ if (Array.isArray(raw)) {
142
+ return { ok: false, rejection: { error: `\`${param}\` was given more than once`, param } };
143
+ }
144
+ if (typeof raw !== "string") {
145
+ return { ok: false, rejection: { error: `\`${param}\` must be a single value`, param } };
146
+ }
147
+ return { ok: true, value: raw };
148
+ }
149
+ /**
150
+ * Strict integer parse.
151
+ *
152
+ * `parseInt` is what this route used to do and it is the reason `?width=abc`
153
+ * was a 500: `parseInt("abc")` is NaN, NaN reaches sharp, sharp throws, and the
154
+ * outer catch turns a bad request into "Failed to process file". `parseInt`
155
+ * also accepts `12px` and `0x10`. Neither is a width.
156
+ */
157
+ function strictInt(value) {
158
+ if (!/^-?\d+$/.test(value.trim()))
159
+ return null;
160
+ const n = Number(value.trim());
161
+ return Number.isSafeInteger(n) ? n : null;
162
+ }
163
+ function strictNumber(value) {
164
+ if (!/^-?\d+(\.\d+)?$/.test(value.trim()))
165
+ return null;
166
+ const n = Number(value.trim());
167
+ return Number.isFinite(n) ? n : null;
168
+ }
169
+ const BOOL_TRUE = new Set(["1", "true"]);
170
+ const BOOL_FALSE = new Set(["0", "false"]);
171
+ /**
172
+ * Parse and validate the whole query in one pass.
173
+ *
174
+ * Unknown VALUES for a known parameter are rejected. Unknown KEYS are not:
175
+ * `?v=3` cache-busters and analytics tags are real traffic on a public CDN
176
+ * origin, and turning them into 400s would break callers who are not using the
177
+ * image surface at all. They are carried through canonicalisation untouched.
178
+ */
179
+ function parseImageParams(query) {
180
+ const reject = (error, param) => ({ ok: false, rejection: { error, param } });
181
+ // --- dpr first: it multiplies the dimensions, so the cap has to see it.
182
+ const dprRaw = single(query.dpr, "dpr");
183
+ if (!dprRaw.ok)
184
+ return { ok: false, rejection: dprRaw.rejection };
185
+ let dpr = 1;
186
+ if (dprRaw.value !== undefined) {
187
+ const n = strictNumber(dprRaw.value);
188
+ if (n === null || n < 1 || n > 3) {
189
+ return reject("`dpr` must be a number between 1 and 3", "dpr");
190
+ }
191
+ dpr = n;
192
+ }
193
+ const dimension = (name) => {
194
+ const raw = single(query[name], name);
195
+ if (!raw.ok)
196
+ return raw;
197
+ if (raw.value === undefined)
198
+ return { ok: true };
199
+ const n = strictInt(raw.value);
200
+ if (n === null || n < 1) {
201
+ return { ok: false, rejection: { error: `\`${name}\` must be a positive integer`, param: name } };
202
+ }
203
+ const effective = Math.round(n * dpr);
204
+ if (effective > exports.MAX_OUTPUT_EDGE) {
205
+ return {
206
+ ok: false,
207
+ rejection: {
208
+ error: `\`${name}\` × \`dpr\` is ${effective}px; the maximum output edge is ${exports.MAX_OUTPUT_EDGE}px`,
209
+ param: name,
210
+ },
211
+ };
212
+ }
213
+ return { ok: true, value: effective };
214
+ };
215
+ const w = dimension("width");
216
+ if (!w.ok)
217
+ return { ok: false, rejection: w.rejection };
218
+ const h = dimension("height");
219
+ if (!h.ok)
220
+ return { ok: false, rejection: h.rejection };
221
+ const blurRaw = single(query.blur, "blur");
222
+ if (!blurRaw.ok)
223
+ return { ok: false, rejection: blurRaw.rejection };
224
+ let blur;
225
+ if (blurRaw.value !== undefined) {
226
+ const n = strictInt(blurRaw.value);
227
+ // This used to be `Math.max(1, Math.min(256, parseInt(blur)))` — a silent
228
+ // clamp, so `blur=99999` and `blur=256` were one representation under two
229
+ // URLs, and `blur=abc` was a 500.
230
+ if (n === null || n < exports.MIN_BLUR || n > exports.MAX_BLUR) {
231
+ return reject(`\`blur\` must be an integer between ${exports.MIN_BLUR} and ${exports.MAX_BLUR}`, "blur");
232
+ }
233
+ blur = n;
234
+ }
235
+ const formatRaw = single(query.format, "format");
236
+ if (!formatRaw.ok)
237
+ return { ok: false, rejection: formatRaw.rejection };
238
+ let format;
239
+ if (formatRaw.value !== undefined) {
240
+ const v = formatRaw.value.trim().toLowerCase();
241
+ const canon = v === "jpg" ? "jpeg" : v;
242
+ if (canon !== "webp" && canon !== "avif" && canon !== "jpeg" && canon !== "png" && canon !== "auto") {
243
+ return reject("`format` must be one of webp, avif, jpeg, png, auto", "format");
244
+ }
245
+ format = canon;
246
+ }
247
+ const qualityRaw = single(query.quality, "quality");
248
+ if (!qualityRaw.ok)
249
+ return { ok: false, rejection: qualityRaw.rejection };
250
+ let quality;
251
+ if (qualityRaw.value !== undefined) {
252
+ const n = strictInt(qualityRaw.value);
253
+ if (n === null || n < 1 || n > 100) {
254
+ return reject("`quality` must be an integer between 1 and 100", "quality");
255
+ }
256
+ quality = n;
257
+ }
258
+ const fitRaw = single(query.fit, "fit");
259
+ if (!fitRaw.ok)
260
+ return { ok: false, rejection: fitRaw.rejection };
261
+ let fit = "inside";
262
+ if (fitRaw.value !== undefined) {
263
+ const v = fitRaw.value.trim().toLowerCase();
264
+ if (v !== "inside" && v !== "cover" && v !== "contain") {
265
+ return reject("`fit` must be one of inside, cover, contain", "fit");
266
+ }
267
+ fit = v;
268
+ }
269
+ const flag = (name) => {
270
+ const raw = single(query[name], name);
271
+ if (!raw.ok)
272
+ return raw;
273
+ if (raw.value === undefined)
274
+ return { ok: true, value: false };
275
+ const v = raw.value.trim().toLowerCase();
276
+ if (BOOL_TRUE.has(v))
277
+ return { ok: true, value: true };
278
+ if (BOOL_FALSE.has(v))
279
+ return { ok: true, value: false };
280
+ return { ok: false, rejection: { error: `\`${name}\` must be 0 or 1`, param: name } };
281
+ };
282
+ const upscale = flag("upscale");
283
+ if (!upscale.ok)
284
+ return { ok: false, rejection: upscale.rejection };
285
+ const keepMetadata = flag("keepMetadata");
286
+ if (!keepMetadata.ok)
287
+ return { ok: false, rejection: keepMetadata.rejection };
288
+ /**
289
+ * What counts as "the caller asked for a transform".
290
+ *
291
+ * `fit`, `dpr` and `upscale` only modify a resize, so on their own they
292
+ * change nothing — a URL carrying just `?fit=cover` must stay the pass-through
293
+ * it is today. `keepMetadata` likewise: there is nothing to strip if we are
294
+ * not re-encoding.
295
+ */
296
+ const wantsTransform = w.value !== undefined ||
297
+ h.value !== undefined ||
298
+ blur !== undefined ||
299
+ format !== undefined ||
300
+ quality !== undefined;
301
+ return {
302
+ ok: true,
303
+ params: {
304
+ width: w.value,
305
+ height: h.value,
306
+ blur,
307
+ format,
308
+ quality,
309
+ fit,
310
+ dpr,
311
+ upscale: upscale.value,
312
+ keepMetadata: keepMetadata.value,
313
+ wantsTransform,
314
+ },
315
+ };
316
+ }
317
+ /** Render a number the way the canonical URL spells it (no trailing zeros). */
318
+ function num(n) {
319
+ return String(Number(n));
320
+ }
321
+ /**
322
+ * One key or value of the canonical query, percent-encoded so that a browser
323
+ * sends it back byte for byte.
324
+ *
325
+ * `encodeURIComponent` leaves `'` as it is, but a browser's URL parser
326
+ * percent-encodes `'` in the query of an http(s) URL. A redirect whose Location
327
+ * carried a raw `'` was therefore requested as `%27`, which is not the spelling
328
+ * this module wrote, so it was redirected again, forever. Every other
329
+ * character `encodeURIComponent` leaves alone (`!` `(` `)` `*` `~` and the
330
+ * unreserved set) a browser leaves alone too.
331
+ */
332
+ function encodePart(text) {
333
+ return encodeURIComponent(text).replace(/'/g, "%27");
334
+ }
335
+ /**
336
+ * `fp` and `rect` are comma lists, spelled with bare commas: a browser sends a
337
+ * query's `,` as it is, so `fp=0.25,0.5` comes back byte for byte, and reads
338
+ * better than `fp=0.25%2C0.5`. Only where they are parameters; an unknown key
339
+ * keeps `encodePart`'s spelling, as before.
340
+ */
341
+ function listValue(key, options) {
342
+ return options.focal === true && exports.FOCAL_PARAMS.has(key);
343
+ }
344
+ function encodeList(value) {
345
+ return value.split(",").map(encodePart).join(",");
346
+ }
347
+ /**
348
+ * The canonical spelling of a query, so `?width=200&format=webp` and
349
+ * `?format=webp&width=200` are one edge object rather than two.
350
+ *
351
+ * GATED, DELIBERATELY. Canonicalisation only applies once the caller uses a
352
+ * parameter introduced by §0i.1. A URL made only of `width`/`height`/`blur` is
353
+ * declared canonical as received, whatever its key order — see LEGACY_PARAMS
354
+ * for why. The gate is also what keeps the `files-404-params-ignored` parity
355
+ * fixture (`?width=100&height=50&blur=9`) from becoming a 301.
356
+ *
357
+ * @param rawQuery the query string as received, without the leading `?`
358
+ */
359
+ function canonicalise(rawQuery, params, options = {}) {
360
+ const received = new URLSearchParams(rawQuery);
361
+ const usesNewParam = [...received.keys()].some((k) => exports.NEW_PARAMS.has(k) || (options.focal === true && exports.FOCAL_PARAMS.has(k)));
362
+ if (!usesNewParam)
363
+ return { query: rawQuery, isCanonical: true };
364
+ const query = canonicalQuery(rawQuery, params, options);
365
+ return { query, isCanonical: query === rawQuery };
366
+ }
367
+ /**
368
+ * The canonical spelling itself, without `canonicalise`'s gate.
369
+ *
370
+ * `canonicalise` is this plus the LEGACY_PARAMS grandfather clause. For a query
371
+ * that uses a new parameter the two agree; for one made only of
372
+ * `width`/`height`/`blur` this still sorts and re-spells it, which the API
373
+ * accepts as canonical too, since the gate declares any legacy spelling
374
+ * canonical. So a URL built with this is never redirected, whichever
375
+ * parameters it carries. @capacms/sdk builds every image URL with it.
376
+ *
377
+ * @param rawQuery the query string, without the leading `?`; read only for the
378
+ * keys this module does not know, which are kept
379
+ */
380
+ function canonicalQuery(rawQuery, params, options = {}) {
381
+ const received = new URLSearchParams(rawQuery);
382
+ const keys = [...new Set([...received.keys()])];
383
+ const out = new Map();
384
+ // Known parameters are re-rendered from the PARSED value, so `width=0200`,
385
+ // `format=JPG` and `upscale=true` all collapse onto one spelling. Defaults are
386
+ // dropped: a URL that asks for the default is the same representation as one
387
+ // that does not mention it. `quality` only where that is true for every
388
+ // output the URL can produce (droppableQuality).
389
+ //
390
+ // `width`/`height` are re-rendered PRE-dpr, because dpr stays in the URL as
391
+ // its own term; folding it into the dimension would make `?width=200&dpr=2`
392
+ // redirect to `?width=400`, which is a different request as far as the caller
393
+ // who wrote it is concerned.
394
+ if (params.width !== undefined)
395
+ out.set("width", num(Math.round(params.width / params.dpr)));
396
+ if (params.height !== undefined)
397
+ out.set("height", num(Math.round(params.height / params.dpr)));
398
+ if (params.blur !== undefined)
399
+ out.set("blur", num(params.blur));
400
+ if (params.format !== undefined)
401
+ out.set("format", params.format);
402
+ if (params.quality !== undefined && params.quality !== droppableQuality(params.format))
403
+ out.set("quality", num(params.quality));
404
+ if (params.fit !== "inside")
405
+ out.set("fit", params.fit);
406
+ if (params.dpr !== 1)
407
+ out.set("dpr", num(params.dpr));
408
+ if (params.upscale)
409
+ out.set("upscale", "1");
410
+ if (params.keepMetadata)
411
+ out.set("keepMetadata", "1");
412
+ if (options.focal === true) {
413
+ if (params.focalPoint !== undefined)
414
+ out.set("fp", fractions([params.focalPoint.x, params.focalPoint.y]));
415
+ if (params.rect !== undefined)
416
+ out.set("rect", fractions([params.rect.x, params.rect.y, params.rect.width, params.rect.height]));
417
+ }
418
+ // Unknown keys are preserved verbatim (first value wins, repeats collapse),
419
+ // so a cache-buster survives the redirect instead of being silently dropped.
420
+ //
421
+ // An empty pair (`&=`, an empty key with an empty value) is dropped: written
422
+ // back it would be an empty segment, which parses to nothing, so the URL it
423
+ // redirected to was itself redirected again.
424
+ for (const key of keys) {
425
+ if (exports.LEGACY_PARAMS.has(key) || exports.NEW_PARAMS.has(key))
426
+ continue;
427
+ if (options.focal === true && exports.FOCAL_PARAMS.has(key))
428
+ continue;
429
+ const value = received.get(key) ?? "";
430
+ if (key === "" && value === "")
431
+ continue;
432
+ out.set(key, value);
433
+ }
434
+ const sorted = [...out.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
435
+ return sorted
436
+ .map(([k, v]) => (v === "" ? encodePart(k) : `${encodePart(k)}=${listValue(k, options) ? encodeList(v) : encodePart(v)}`))
437
+ .join("&");
438
+ }
439
+ /**
440
+ * A stable string identifying the transform, for the ETag.
441
+ *
442
+ * Built from the RESOLVED parameters rather than the URL, so two spellings of
443
+ * one representation share an ETag even when the redirect is not in play.
444
+ * `auto` resolves per request, so the caller passes the resolved format in.
445
+ */
446
+ function buildSignature(params, resolvedFormat) {
447
+ if (!params.wantsTransform)
448
+ return "raw";
449
+ const parts = [];
450
+ if (params.width !== undefined)
451
+ parts.push(`w${params.width}`);
452
+ if (params.height !== undefined)
453
+ parts.push(`h${params.height}`);
454
+ if (params.width !== undefined || params.height !== undefined) {
455
+ parts.push(`f${params.fit}`);
456
+ if (params.upscale)
457
+ parts.push("up");
458
+ }
459
+ if (params.blur !== undefined)
460
+ parts.push(`b${params.blur}`);
461
+ if (resolvedFormat)
462
+ parts.push(`o${resolvedFormat}`);
463
+ if (params.quality !== undefined)
464
+ parts.push(`q${params.quality}`);
465
+ if (params.keepMetadata)
466
+ parts.push("meta");
467
+ // The crop and the focal point this transform applies (`appliedFocal`), from
468
+ // the URL or from the file, so a new focal point on the file is a new ETag
469
+ // under the same URL. Colons, not the URL's commas: If-None-Match is a
470
+ // comma-separated list, and an ETag with a comma in it never matches its
471
+ // own revalidation (files.ts ifNoneMatchSatisfied), so every one would be a
472
+ // full 200.
473
+ if (params.rect !== undefined)
474
+ parts.push(`r${fractions([params.rect.x, params.rect.y, params.rect.width, params.rect.height], ":")}`);
475
+ if (params.focalPoint !== undefined)
476
+ parts.push(`p${fractions([params.focalPoint.x, params.focalPoint.y], ":")}`);
477
+ return parts.join("_") || "raw";
478
+ }
479
+ /**
480
+ * Which concrete format `format=auto` resolves to for this request.
481
+ *
482
+ * Returns null when the client advertises neither modern format, in which case
483
+ * the source format is kept — `auto` never makes a response worse than the
484
+ * object already is.
485
+ *
486
+ * `q=0` is an explicit REFUSAL in RFC 9110 content negotiation, not a weak
487
+ * preference, so an entry carrying it is skipped rather than matched.
488
+ */
489
+ function resolveAutoFormat(accept) {
490
+ if (!accept)
491
+ return null;
492
+ const offered = new Map();
493
+ for (const entry of accept.split(",")) {
494
+ const [type, ...paramParts] = entry.split(";");
495
+ const name = type.trim().toLowerCase();
496
+ if (!name)
497
+ continue;
498
+ let q = 1;
499
+ for (const p of paramParts) {
500
+ const m = /^\s*q\s*=\s*([\d.]+)\s*$/i.exec(p);
501
+ if (m)
502
+ q = Number(m[1]);
503
+ }
504
+ offered.set(name, Number.isFinite(q) ? q : 1);
505
+ }
506
+ if ((offered.get("image/avif") ?? 0) > 0)
507
+ return "avif";
508
+ if ((offered.get("image/webp") ?? 0) > 0)
509
+ return "webp";
510
+ return null;
511
+ }
512
+ /** `fp` and `rect`: parameters only where the focal point and crop are on. */
513
+ exports.FOCAL_PARAMS = new Set(["fp", "rect"]);
514
+ /** Decimal places a fraction keeps: a ten-thousandth, under a pixel up to 10,000 px. */
515
+ exports.FRACTION_DECIMALS = 4;
516
+ /** Slack for `x + width <= 1` after rounding to FRACTION_DECIMALS. */
517
+ const FRACTION_EPSILON = 1e-9;
518
+ /** A number rounded to FRACTION_DECIMALS. */
519
+ function roundFraction(n) {
520
+ const scale = 10 ** exports.FRACTION_DECIMALS;
521
+ return Math.round(n * scale) / scale;
522
+ }
523
+ function fraction(value) {
524
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1)
525
+ return null;
526
+ return roundFraction(value);
527
+ }
528
+ function plainObject(value) {
529
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
530
+ }
531
+ /**
532
+ * A focal point from stored metadata or a request body, or null when it is
533
+ * not one: an object whose `x` and `y` are numbers from 0 to 1.
534
+ */
535
+ function readFocalPoint(value) {
536
+ const v = plainObject(value);
537
+ if (!v)
538
+ return null;
539
+ const x = fraction(v.x);
540
+ const y = fraction(v.y);
541
+ return x === null || y === null ? null : { x, y };
542
+ }
543
+ /**
544
+ * A crop from stored metadata or a request body, or null when it is not one:
545
+ * `x`, `y`, `width` and `height` from 0 to 1, a width and a height above 0,
546
+ * and inside the image.
547
+ */
548
+ function readCrop(value) {
549
+ const v = plainObject(value);
550
+ if (!v)
551
+ return null;
552
+ const x = fraction(v.x);
553
+ const y = fraction(v.y);
554
+ const width = fraction(v.width);
555
+ const height = fraction(v.height);
556
+ if (x === null || y === null || width === null || height === null)
557
+ return null;
558
+ if (width <= 0 || height <= 0)
559
+ return null;
560
+ if (x + width > 1 + FRACTION_EPSILON || y + height > 1 + FRACTION_EPSILON)
561
+ return null;
562
+ return { x, y, width, height };
563
+ }
564
+ /** True when `value` has exactly these own keys, in any order. */
565
+ function hasExactly(value, keys) {
566
+ const own = Object.keys(value);
567
+ return own.length === keys.length && keys.every((key) => own.includes(key));
568
+ }
569
+ /**
570
+ * A focal point exactly as the api stores one (`normaliseFocalPatch` in
571
+ * apps/api routes/v2/file-uploads.ts): `{ x, y }` and no other key, numbers
572
+ * from 0 to 1. Stricter than `readFocalPoint`, which reads one out of any
573
+ * object that has them: this is the test for "ENG-5959 wrote this", which a
574
+ * replace carries over and the legacy routes hide. Anything else under the
575
+ * name is a project's own metadata and is left alone.
576
+ */
577
+ function isStoredFocalPoint(value) {
578
+ const v = plainObject(value);
579
+ return v !== null && hasExactly(v, ["x", "y"]) && readFocalPoint(v) !== null;
580
+ }
581
+ /** A crop exactly as the api stores one: `{ x, y, width, height }` and no other key. See `isStoredFocalPoint`. */
582
+ function isStoredCrop(value) {
583
+ const v = plainObject(value);
584
+ return v !== null && hasExactly(v, ["x", "y", "width", "height"]) && readCrop(v) !== null;
585
+ }
586
+ /** Numbers as the canonical URL spells them: comma separated, no trailing zeros. */
587
+ function fractions(values, separator = ",") {
588
+ return values.map((n) => String(roundFraction(n))).join(separator);
589
+ }
590
+ /** `0.25,0.5` into numbers, or null when any part is not a plain decimal. */
591
+ function decimalList(text, count) {
592
+ const parts = text.split(",");
593
+ if (parts.length !== count)
594
+ return null;
595
+ const out = [];
596
+ for (const part of parts) {
597
+ const n = strictNumber(part);
598
+ if (n === null)
599
+ return null;
600
+ out.push(n);
601
+ }
602
+ return out;
603
+ }
604
+ /**
605
+ * `fp` and `rect`, for a project with the focal point and crop on. The route
606
+ * calls it after it knows the file's project; anywhere else the two are
607
+ * unknown keys and this is never called.
608
+ */
609
+ function parseFocalParams(query) {
610
+ const reject = (error, param) => ({ ok: false, rejection: { error, param } });
611
+ const fpRaw = single(query.fp, "fp");
612
+ if (!fpRaw.ok)
613
+ return { ok: false, rejection: fpRaw.rejection };
614
+ let focalPoint;
615
+ if (fpRaw.value !== undefined) {
616
+ const list = decimalList(fpRaw.value, 2);
617
+ const read = list ? readFocalPoint({ x: list[0], y: list[1] }) : null;
618
+ if (!read)
619
+ return reject("`fp` must be two numbers from 0 to 1, x,y", "fp");
620
+ focalPoint = read;
621
+ }
622
+ const rectRaw = single(query.rect, "rect");
623
+ if (!rectRaw.ok)
624
+ return { ok: false, rejection: rectRaw.rejection };
625
+ let rect;
626
+ if (rectRaw.value !== undefined) {
627
+ const list = decimalList(rectRaw.value, 4);
628
+ const read = list ? readCrop({ x: list[0], y: list[1], width: list[2], height: list[3] }) : null;
629
+ if (!read) {
630
+ return reject("`rect` must be four numbers from 0 to 1, x,y,width,height, with a width and a height above 0, inside the image", "rect");
631
+ }
632
+ rect = read;
633
+ }
634
+ return { ok: true, focalPoint, rect };
635
+ }
636
+ /**
637
+ * The crop and focal point a request applies: the URL's, else the file's,
638
+ * and the file's only for a `fit=cover` crop to both a width and a height.
639
+ * A blur placeholder keeps its own square geometry and applies only a `rect`
640
+ * the URL names.
641
+ */
642
+ /**
643
+ * A crop to a shape: `fit=cover` with a width and a height, and no blur. The
644
+ * one request the file's stored focal point and crop apply to.
645
+ */
646
+ function isCoverCrop(params) {
647
+ return params.fit === "cover" && params.width !== undefined && params.height !== undefined && params.blur === undefined;
648
+ }
649
+ /**
650
+ * True when this request's bytes depend on the file's STORED focal point or
651
+ * crop: a cover crop that does not name both `fp` and `rect` itself. Its
652
+ * bytes change under the same URL when an editor saves either, so a browser
653
+ * must not keep them as long as an immutable variant (`GET /files/*`).
654
+ */
655
+ function followsStoredFocal(params) {
656
+ return isCoverCrop(params) && (params.focalPoint === undefined || params.rect === undefined);
657
+ }
658
+ function appliedFocal(params, stored) {
659
+ const cover = isCoverCrop(params);
660
+ const rect = params.rect ?? (cover ? stored?.crop ?? null : null);
661
+ const focalPoint = cover ? params.focalPoint ?? stored?.focalPoint ?? null : null;
662
+ return { rect, focalPoint };
663
+ }
664
+ /**
665
+ * The part of the source to cut out before the resize, or null for none.
666
+ *
667
+ * `source` is the image as a person sees it. `target` is the `fit=cover` box
668
+ * (width and height after dpr), or null for any other request. The crop is cut
669
+ * first; with a target and a focal point, the window of the target's shape
670
+ * that a cover resize would keep is then moved, inside the crop, so its centre
671
+ * is as close to the focal point as the crop allows. Without a focal point the
672
+ * crop alone is returned and the resize centres in it as it always has.
673
+ *
674
+ * The window is the largest of the target's shape that fits the crop, so the
675
+ * resize that follows scales it to the target without cutting anything more.
676
+ */
677
+ function focalRegion(source, target, rect, focalPoint) {
678
+ const W = Math.max(1, Math.round(source.width));
679
+ const H = Math.max(1, Math.round(source.height));
680
+ let region = { left: 0, top: 0, width: W, height: H };
681
+ if (rect) {
682
+ const left = Math.min(W - 1, Math.round(rect.x * W));
683
+ const top = Math.min(H - 1, Math.round(rect.y * H));
684
+ region = {
685
+ left,
686
+ top,
687
+ width: Math.max(1, Math.min(W - left, Math.round(rect.width * W))),
688
+ height: Math.max(1, Math.min(H - top, Math.round(rect.height * H))),
689
+ };
690
+ }
691
+ if (!target || !focalPoint)
692
+ return rect ? region : null;
693
+ const scale = Math.max(target.width / region.width, target.height / region.height);
694
+ const width = Math.max(1, Math.min(region.width, Math.round(target.width / scale)));
695
+ const height = Math.max(1, Math.min(region.height, Math.round(target.height / scale)));
696
+ const clamp = (value, lo, hi) => Math.min(hi, Math.max(lo, value));
697
+ const left = clamp(Math.round(focalPoint.x * W - width / 2), region.left, region.left + region.width - width);
698
+ const top = clamp(Math.round(focalPoint.y * H - height / 2), region.top, region.top + region.height - height);
699
+ return { left, top, width, height };
700
+ }