@crabcrop/mcp 0.1.0 → 0.10.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.
@@ -1,10 +1,15 @@
1
1
  /**
2
2
  * Parse a crabcrop URL (or bare path) back into its pieces and
3
3
  * explain each segment, mirroring the server's grammar. This is
4
- * the canonical implementation: the playground keeps a plain-JS
5
- * copy for its no-build static page, and both are pinned to the
6
- * same verdict corpus (audit PL-10, P-3).
4
+ * the one JavaScript implementation of the grammar (issue #482):
5
+ * the typed builders in operations.ts validate with the checks
6
+ * exported here, and the playground serves this module's build
7
+ * (playground/sdk/, refreshed by scripts/sync_playground_sdk.py,
8
+ * whose --check fails on drift or on a second copy). Every
9
+ * surface is pinned to the same verdict corpora (audit PL-10,
10
+ * P-3).
7
11
  */
12
+ import { MAX_DIMENSION } from "./limits.js";
8
13
  export const FILTER_DESCRIPTIONS = {
9
14
  grayscale: "convert to grayscale",
10
15
  invert: "invert the colors",
@@ -13,19 +18,27 @@ export const FILTER_DESCRIPTIONS = {
13
18
  blurfaces: "blur detected faces (needs a face model on the server)",
14
19
  brighten: "brighten by the given amount (-255..255)",
15
20
  contrast: "contrast in percent, -100..100 (0 is unchanged, -100 is flat)",
21
+ gamma: "gamma correction with divisor g, 0 < g <= 10: each channel becomes 255 * (v / 255)^(1 / g) (1 is unchanged, above 1 brightens midtones)",
22
+ exposure: "exposure in stops, -10..10: multiply the linear light by 2^stops (0 is unchanged, positive brightens, negative darkens)",
23
+ highlights_shadows: "adjust the highlights and shadows ranges independently: two percents, each -100..100 (0 is unchanged)",
24
+ vibrance: "saturation weighted toward the muted colors: percent, -100..100 (0 is unchanged; vivid colors and skin tones are protected)",
16
25
  huerotate: "rotate the hue by the given degrees",
17
26
  rotate: "rotate by the given angle in degrees; the canvas expands to fit",
18
- quality: "output quality 1..100, or `auto` for perceptual targeting",
19
- format: "force the output format",
27
+ quality: "output quality 1..100, or `auto` for perceptual targeting; or per-format values in one list (quality(80,jpeg:90,webp:75)), resolved after format negotiation",
28
+ palette: "write PNG output as an indexed (palette) image with at most this many colors, 2..256; ignored by the other formats",
29
+ format: "force the output format; a format also takes its encoder options (format(jpeg,progressive), format(png,interlace), format(webp,method:6,sns:50)); an option its encoder cannot honour is refused",
20
30
  fill: "the background color other operations pad with",
21
31
  facepad: "how much a face crop expands around the face",
22
32
  pixelatefaces: "pixelate detected faces (needs a face model on the server)",
23
33
  blurclass: "blur every detected object of the named class (needs a detection model on the server)",
24
34
  pixelateclass: "pixelate every detected object of the named class (needs a detection model on the server)",
35
+ recolorclass: "recolor every detected object of the named class to the given color (needs a detection model on the server)",
25
36
  removebg: "remove the background (needs an AI model on the server)",
37
+ studio: "studio mode: `product` composites the subject onto a backdrop (bg: white, a RRGGBB color, brand, or none) with a synthesized contact shadow (shadow: soft, strong, or none), scaled and centered to a pad margin (pad: 0..40, default 10); `scene` keeps the photograph's scene, reframing it on the detected subject with light and color correction (pad only) (needs an AI model on the server)",
26
38
  keep_profile: "keep the source color profile instead of converting to sRGB",
27
39
  upscale: "AI upscale by the given factor (needs an AI model on the server)",
28
40
  equalize: "histogram equalization",
41
+ enhance: "gentle per-channel auto-levels (0.5th percentile to 0, 99.5th to 255)",
29
42
  saturation: "saturation factor, 0..255 (0 is grayscale, 1 is identity)",
30
43
  sharpen: "sharpen by the given amount",
31
44
  text: "draw a text overlay (needs a font on the server)",
@@ -33,7 +46,7 @@ export const FILTER_DESCRIPTIONS = {
33
46
  curve: "tone curve: remap the named channel (rgb, r, g, or b) through 2 to 16 x,y control points, linearly interpolated, ends clamped",
34
47
  convolution: "convolve with a 3x3 or 5x5 kernel: 9 or 25 row-major values (plain decimals, -1024..1024), then a normalize flag (0 or 1); edges replicate",
35
48
  noise: "add monochrome film grain: one deterministic noise value per pixel on all channels, strength 0..100 percent of full scale (0 is a no-op)",
36
- trim: "trim uniform borders",
49
+ trim: "trim uniform borders; the five-argument form (tolerance,left,top,right,bottom) also removes that many pixels per side after the tolerance pass",
37
50
  dpr: "device pixel ratio the sizes are multiplied by",
38
51
  watermark: "overlay a watermark image",
39
52
  max_bytes: "cap the output size, lowering quality to fit",
@@ -48,8 +61,8 @@ export const FILTER_DESCRIPTIONS = {
48
61
  blur_region: "gaussian-blur the rectangle (x,y,w,h) in pixels at this point in the chain (redaction)",
49
62
  overlay: "composite another image over the result: (url,x,y,alpha,blend[,width %]) with blend normal, multiply, screen, or overlay",
50
63
  pixelate_region: "pixelate the rectangle (x,y,w,h) in pixels at this point in the chain (redaction)",
64
+ remove_region: "erase the rectangle (x,y,w,h) in pixels at this point in the chain and inpaint it from the surrounding pixels (AI region removal)",
51
65
  };
52
- const MAX_DIMENSION = 16383;
53
66
  function parseDimension(part) {
54
67
  let flip = false;
55
68
  let digits = part;
@@ -96,29 +109,98 @@ function sizeBlurb(seg) {
96
109
  ].filter(Boolean);
97
110
  return `resize to ${describe(size.w, "width")} by ${describe(size.h, "height")}${flips.length ? ` (${flips.join(", ")})` : ""}`;
98
111
  }
112
+ // The grammar's closed sets, declared once for the explainer
113
+ // and the typed builders (issue #482). Each is `as const` so
114
+ // test/grammar-sets.test.ts can check it against the union
115
+ // type operations.ts gives callers: a value added to one side
116
+ // only fails the type check.
117
+ /** Crop alignments (url.rs parse_align); `center` is the bare `crop:WxH`. */
118
+ export const CROP_ALIGNS = ["center", "smart", "face", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
119
+ /** Text overlay anchors (url.rs Anchor::parse). */
120
+ export const TEXT_ANCHORS = [
121
+ "top-left",
122
+ "top-center",
123
+ "top-right",
124
+ "center-left",
125
+ "center",
126
+ "center-right",
127
+ "bottom-left",
128
+ "bottom-center",
129
+ "bottom-right",
130
+ ];
131
+ /** Output formats `format(...)` names; `jpg` is an input alias of `jpeg`. */
132
+ export const IMAGE_FORMATS = ["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"];
133
+ /**
134
+ * Formats a per-format `quality(...)` entry names, in
135
+ * canonical (name) order: the still formats, since a video
136
+ * format's quality is not the server's to set. `jpg` is
137
+ * accepted as the input alias of `jpeg`.
138
+ */
139
+ export const QUALITY_FORMATS = ["avif", "gif", "jpeg", "jxl", "png", "webp"];
140
+ /** JPEG chroma subsamplings `format(jpeg,subsampling:...)` takes. */
141
+ export const JPEG_SUBSAMPLINGS = [444, 422, 420];
142
+ /** Overlay blend modes. */
143
+ export const BLEND_MODES = ["normal", "multiply", "screen", "overlay"];
144
+ /** Channels `curve(...)` remaps. */
145
+ export const CURVE_CHANNELS = ["rgb", "r", "g", "b"];
146
+ /** Modes `studio(...)` runs. */
147
+ export const STUDIO_MODES = ["product", "scene"];
148
+ /** Named backdrops for `studio(product,bg:...)`; any RRGGBB color also works. */
149
+ export const STUDIO_BACKDROPS = ["white", "brand", "none"];
150
+ /** Contact shadow strengths for `studio(product, ...)`. */
151
+ export const STUDIO_SHADOWS = ["soft", "strong", "none"];
152
+ /** Factors `upscale(...)` takes. */
153
+ export const UPSCALE_FACTORS = [2, 4];
154
+ /** Device pixel ratios `dpr(...)` takes. */
155
+ export const DPR_FACTORS = [1, 1.5, 2, 3];
156
+ /** Shapes `mask(...)` cuts. */
157
+ export const MASK_SHAPES = ["circle", "ellipse"];
158
+ /** Axes `flip(...)` mirrors across. */
159
+ export const FLIP_AXES = ["h", "v"];
160
+ /** Whether `value` is a member of the closed set `list`. */
161
+ export function isOneOf(list, value) {
162
+ return list.includes(value);
163
+ }
164
+ /**
165
+ * The objects crop's cap on distinct class names (url.rs
166
+ * MAX_OBJECTS_CLASSES).
167
+ */
168
+ export const MAX_OBJECTS_CLASSES = 32;
169
+ /**
170
+ * A detection class name as the server's parse_class_name
171
+ * takes it, already trimmed: 1 to 64 UTF-8 bytes (bytes, not
172
+ * UTF-16 code units, as on the server) of letters, digits,
173
+ * space, `_`, `.`, `-`, `/`.
174
+ */
175
+ export function isClassName(name) {
176
+ return (name.length >= 1 &&
177
+ new TextEncoder().encode(name).length <= 64 &&
178
+ /^[\p{L}\p{N} _.\-/]+$/u.test(name));
179
+ }
180
+ /**
181
+ * The key a class name folds to when the objects crop drops
182
+ * repeats. The server compares names with
183
+ * `eq_ignore_ascii_case` (url.rs parse_crop_align), so only
184
+ * A to Z fold: `E` and `e` are one class, `É` and `é` are two
185
+ * (issue #482).
186
+ */
187
+ export function classFoldKey(name) {
188
+ return name.replace(/[A-Z]/g, (c) => c.toLowerCase());
189
+ }
99
190
  const NO_ARG_FILTERS = new Set([
100
191
  "grayscale",
101
192
  "invert",
102
193
  "no_upscale",
103
194
  "equalize",
195
+ "enhance",
104
196
  "removebg",
105
197
  "keep_profile",
106
198
  "sepia",
107
199
  "blurfaces",
108
200
  "pixelatefaces",
109
201
  ]);
110
- const FORMAT_NAMES = new Set(["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"]);
111
- const ANCHOR_NAMES = new Set([
112
- "top-left",
113
- "top-center",
114
- "top-right",
115
- "center-left",
116
- "center",
117
- "center-right",
118
- "bottom-left",
119
- "bottom-center",
120
- "bottom-right",
121
- ]);
202
+ const FORMAT_NAMES = new Set(IMAGE_FORMATS);
203
+ const ANCHOR_NAMES = new Set(TEXT_ANCHORS);
122
204
  function isIntIn(s, min, max) {
123
205
  // Rust's integer from_str syntax: an optional sign (the
124
206
  // unsigned parsers accept '+' too), then digits.
@@ -163,9 +245,24 @@ function validateFilter(name, args) {
163
245
  return args === null ? null : bad;
164
246
  }
165
247
  switch (name) {
166
- case "trim":
167
- return args === null || isIntIn(args, 0, 255) ? null : bad;
248
+ case "trim": {
249
+ if (args === null)
250
+ return null;
251
+ const parts = args.split(",");
252
+ if (parts.length === 1)
253
+ return isIntIn(parts[0], 0, 255) ? null : bad;
254
+ return parts.length === 5 &&
255
+ isIntIn(parts[0], 0, 255) &&
256
+ parts.slice(1).every((p) => isIntIn(p, 0, 4294967295))
257
+ ? null
258
+ : bad;
259
+ }
168
260
  case "blur":
261
+ // The server's blur bound (url.rs MAX_BLUR_SIGMA):
262
+ // positive and at most 512.
263
+ return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 512
264
+ ? null
265
+ : bad;
169
266
  case "sharpen":
170
267
  return args !== null && isFloat(args) && Number(args) > 0 ? null : bad;
171
268
  case "brighten":
@@ -176,14 +273,103 @@ function validateFilter(name, args) {
176
273
  return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
177
274
  ? null
178
275
  : bad;
276
+ case "gamma":
277
+ return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 10
278
+ ? null
279
+ : bad;
280
+ case "exposure":
281
+ return args !== null && isFloat(args) && Number(args) >= -10 && Number(args) <= 10
282
+ ? null
283
+ : bad;
284
+ case "highlights_shadows": {
285
+ if (args === null)
286
+ return bad;
287
+ const parts = args.split(",");
288
+ return parts.length === 2 &&
289
+ parts.every((p) => isFloat(p) && Number(p) >= -100 && Number(p) <= 100)
290
+ ? null
291
+ : bad;
292
+ }
293
+ case "vibrance":
294
+ return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
295
+ ? null
296
+ : bad;
179
297
  case "saturation":
180
298
  return args !== null && isFloat(args) && Number(args) >= 0 && Number(args) <= 255
181
299
  ? null
182
300
  : bad;
183
- case "quality":
184
- return args === "auto" || (args !== null && isIntIn(args, 1, 100)) ? null : bad;
185
- case "format":
186
- return args !== null && FORMAT_NAMES.has(args) ? null : bad;
301
+ case "quality": {
302
+ if (args === null)
303
+ return bad;
304
+ if (args === "auto" || isIntIn(args, 1, 100))
305
+ return null;
306
+ // Per-format list (issue #319): at most one bare
307
+ // fallback, at most one entry per format, no video
308
+ // formats (their quality is not the server's to set).
309
+ const seen = new Set();
310
+ let fallbackSeen = false;
311
+ for (const part of args.split(",")) {
312
+ const colon = part.indexOf(":");
313
+ if (colon === -1) {
314
+ if (fallbackSeen || !(part === "auto" || isIntIn(part, 1, 100)))
315
+ return bad;
316
+ fallbackSeen = true;
317
+ }
318
+ else {
319
+ const name = part.slice(0, colon);
320
+ const value = part.slice(colon + 1);
321
+ const canonical = name === "jpg" ? "jpeg" : name;
322
+ if (!isOneOf(QUALITY_FORMATS, canonical))
323
+ return bad;
324
+ if (seen.has(canonical))
325
+ return bad;
326
+ seen.add(canonical);
327
+ if (!(value === "auto" || isIntIn(value, 1, 100)))
328
+ return bad;
329
+ }
330
+ }
331
+ return seen.size + (fallbackSeen ? 1 : 0) > 0 ? null : bad;
332
+ }
333
+ case "palette":
334
+ return args !== null && isIntIn(args, 2, 256) ? null : bad;
335
+ case "format": {
336
+ if (args === null)
337
+ return bad;
338
+ // A format name plus its encoder options (issue #319),
339
+ // each validated against the format it belongs to.
340
+ const parts = args.split(",");
341
+ const [name, ...options] = parts;
342
+ if (!FORMAT_NAMES.has(name))
343
+ return bad;
344
+ const seen = new Set();
345
+ for (const option of options) {
346
+ const key = option.includes(":") ? option.slice(0, option.indexOf(":")) : option;
347
+ if (seen.has(key))
348
+ return bad;
349
+ seen.add(key);
350
+ if (name === "jpeg" || name === "jpg") {
351
+ if (option === "progressive")
352
+ continue;
353
+ if (JPEG_SUBSAMPLINGS.some((s) => option === `subsampling:${s}`))
354
+ continue;
355
+ return bad;
356
+ }
357
+ if (name === "png") {
358
+ if (option === "interlace")
359
+ continue;
360
+ return bad;
361
+ }
362
+ if (name === "webp") {
363
+ if (/^method:[0-6]$/.test(option))
364
+ continue;
365
+ if (/^sns:\d+$/.test(option) && isIntIn(option.slice(4), 0, 100))
366
+ continue;
367
+ return bad;
368
+ }
369
+ return bad;
370
+ }
371
+ return null;
372
+ }
187
373
  case "rgb": {
188
374
  if (args === null)
189
375
  return bad;
@@ -194,7 +380,7 @@ function validateFilter(name, args) {
194
380
  if (args === null)
195
381
  return bad;
196
382
  const parts = args.split(",");
197
- if (!["rgb", "r", "g", "b"].includes(parts[0]))
383
+ if (!isOneOf(CURVE_CHANNELS, parts[0]))
198
384
  return bad;
199
385
  const coords = parts.slice(1);
200
386
  if (coords.length < 4 || coords.length > 32 || coords.length % 2 !== 0)
@@ -225,11 +411,56 @@ function validateFilter(name, args) {
225
411
  ? null
226
412
  : bad;
227
413
  case "upscale":
228
- return args !== null && /^[+-]?\d+$/.test(args) && (Number(args) === 2 || Number(args) === 4)
414
+ return args !== null && /^[+-]?\d+$/.test(args) && isOneOf(UPSCALE_FACTORS, Number(args))
229
415
  ? null
230
416
  : bad;
417
+ case "studio": {
418
+ // The server's studio grammar (url.rs parse_studio):
419
+ // the mode (`product` or `scene`) first, then named
420
+ // `key:value` arguments, each key at most once.
421
+ // Product takes `bg`, `shadow`, and `pad`; scene
422
+ // takes `pad` only, because a backdrop and a shadow
423
+ // are product concepts (naming one under scene is a
424
+ // bad argument, not a silent no-op).
425
+ if (args === null)
426
+ return bad;
427
+ const parts = args.split(",");
428
+ const mode = parts[0];
429
+ if (!isOneOf(STUDIO_MODES, mode))
430
+ return bad;
431
+ const seen = new Set();
432
+ for (const part of parts.slice(1)) {
433
+ const cut = part.indexOf(":");
434
+ if (cut === -1)
435
+ return bad;
436
+ const key = part.slice(0, cut);
437
+ const value = part.slice(cut + 1);
438
+ if (seen.has(key))
439
+ return bad;
440
+ seen.add(key);
441
+ if (key === "pad") {
442
+ // The pad parses as a Rust u8 (an optional `+`,
443
+ // then digits; no minus sign, not even `-0`) and
444
+ // is bounded to 40.
445
+ if (!/^\+?\d+$/.test(value) || BigInt(value) > 40n)
446
+ return bad;
447
+ }
448
+ else if (mode === "product" && key === "bg") {
449
+ if (!isOneOf(STUDIO_BACKDROPS, value) && !/^[0-9a-fA-F]{6}$/.test(value))
450
+ return bad;
451
+ }
452
+ else if (mode === "product" && key === "shadow") {
453
+ if (!isOneOf(STUDIO_SHADOWS, value))
454
+ return bad;
455
+ }
456
+ else {
457
+ return bad;
458
+ }
459
+ }
460
+ return null;
461
+ }
231
462
  case "dpr":
232
- return args !== null && isFloat(args) && [1, 1.5, 2, 3].includes(Number(args))
463
+ return args !== null && isFloat(args) && isOneOf(DPR_FACTORS, Number(args))
233
464
  ? null
234
465
  : bad;
235
466
  case "rotate":
@@ -243,7 +474,7 @@ function validateFilter(name, args) {
243
474
  return bad;
244
475
  const parts = args.split(",");
245
476
  return (parts.length === 1 || parts.length === 4) &&
246
- parts.every((p) => isIntIn(p, 0, 16383))
477
+ parts.every((p) => isIntIn(p, 0, MAX_DIMENSION))
247
478
  ? null
248
479
  : bad;
249
480
  }
@@ -252,13 +483,13 @@ function validateFilter(name, args) {
252
483
  return bad;
253
484
  const parts = args.split(",");
254
485
  return parts.length === 2 &&
255
- isIntIn(parts[0], 1, 16383) &&
486
+ isIntIn(parts[0], 0, MAX_DIMENSION) &&
256
487
  /^[0-9a-fA-F]{6}$/.test(parts[1])
257
488
  ? null
258
489
  : bad;
259
490
  }
260
491
  case "mask":
261
- return args === "circle" || args === "ellipse" ? null : bad;
492
+ return isOneOf(MASK_SHAPES, args) ? null : bad;
262
493
  case "duotone": {
263
494
  if (args === null)
264
495
  return bad;
@@ -268,9 +499,9 @@ function validateFilter(name, args) {
268
499
  case "monochrome":
269
500
  return args !== null && /^[0-9a-fA-F]{6}$/.test(args) ? null : bad;
270
501
  case "pixelate":
271
- return args !== null && isIntIn(args, 1, 16383) ? null : bad;
502
+ return args !== null && isIntIn(args, 1, MAX_DIMENSION) ? null : bad;
272
503
  case "flip":
273
- return args === "h" || args === "v" ? null : bad;
504
+ return isOneOf(FLIP_AXES, args) ? null : bad;
274
505
  case "overlay": {
275
506
  if (args === null)
276
507
  return bad;
@@ -288,7 +519,7 @@ function validateFilter(name, args) {
288
519
  rest = fields.slice(0, -1);
289
520
  }
290
521
  const blend = rest[rest.length - 1];
291
- if (!["normal", "multiply", "screen", "overlay"].includes(blend))
522
+ if (!isOneOf(BLEND_MODES, blend))
292
523
  return bad;
293
524
  if (!isIntIn(rest[rest.length - 2], 0, 100))
294
525
  return bad;
@@ -304,22 +535,27 @@ function validateFilter(name, args) {
304
535
  if (args === null)
305
536
  return bad;
306
537
  const decoded = percentDecodable(args);
307
- if (decoded === null)
538
+ return decoded !== null && isClassName(decoded.trim()) ? null : bad;
539
+ }
540
+ case "recolorclass": {
541
+ if (args === null)
308
542
  return bad;
309
- const name = decoded.trim();
310
- return name.length >= 1 &&
311
- new TextEncoder().encode(name).length <= 64 &&
312
- /^[\p{L}\p{N} _.\-/]+$/u.test(name)
313
- ? null
314
- : bad;
543
+ const cut = args.lastIndexOf(",");
544
+ if (cut < 0)
545
+ return bad;
546
+ if (!/^[0-9a-fA-F]{6}$/.test(args.slice(cut + 1)))
547
+ return bad;
548
+ const decoded = percentDecodable(args.slice(0, cut));
549
+ return decoded !== null && isClassName(decoded.trim()) ? null : bad;
315
550
  }
316
551
  case "blur_region":
317
- case "pixelate_region": {
552
+ case "pixelate_region":
553
+ case "remove_region": {
318
554
  if (args === null)
319
555
  return bad;
320
556
  const parts = args.split(",");
321
557
  return parts.length === 4 &&
322
- parts.every((p) => isIntIn(p, 0, 16383)) &&
558
+ parts.every((p) => isIntIn(p, 0, MAX_DIMENSION)) &&
323
559
  Number(parts[2]) >= 1 &&
324
560
  Number(parts[3]) >= 1
325
561
  ? null
@@ -373,9 +609,30 @@ function validateFilter(name, args) {
373
609
  }
374
610
  }
375
611
  function explainFilters(rest) {
376
- // The server splits the list naively on ':'; a ':' inside
377
- // parentheses is not special there either.
378
- const parts = rest.split(":");
612
+ // The server splits the list on the ':' separators that
613
+ // sit outside parentheses (url.rs split_filter_chain):
614
+ // an argument list may itself contain ':' (the studio
615
+ // filter's named arguments are `key:value`), so a naive
616
+ // split would cut those filters apart. Unbalanced
617
+ // parentheses leave the tail in one part, which then
618
+ // fails its own parse, as on the server.
619
+ const parts = [];
620
+ let depth = 0;
621
+ let start = 0;
622
+ for (let i = 0; i < rest.length; i++) {
623
+ const c = rest[i];
624
+ if (c === "(") {
625
+ depth += 1;
626
+ }
627
+ else if (c === ")") {
628
+ depth = Math.max(0, depth - 1);
629
+ }
630
+ else if (c === ":" && depth === 0) {
631
+ parts.push(rest.slice(start, i));
632
+ start = i + 1;
633
+ }
634
+ }
635
+ parts.push(rest.slice(start));
379
636
  const blurbs = [];
380
637
  for (const part of parts) {
381
638
  const match = part.match(/^([a-z_0-9]+)(?:\((.*)\))?$/);
@@ -396,8 +653,58 @@ function explainFilters(rest) {
396
653
  }
397
654
  return { detail: blurbs.join("; ") };
398
655
  }
399
- const ALIGN_NAMES = new Set(["center", "smart", "face", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"]);
656
+ const ALIGN_NAMES = new Set(CROP_ALIGNS);
400
657
  const U64_MAX = 18446744073709551615n;
658
+ /**
659
+ * The objects crop alignment (url.rs parse_objects, ported):
660
+ * `objects(<class>[,<class>...])[:<scale>]`. Returns the
661
+ * decoded class names (duplicates folded ASCII-only, first
662
+ * spelling kept, as the server's canonical form folds them)
663
+ * and the scale, or null when the server would reject the
664
+ * form. The 32-class cap counts distinct names, as the
665
+ * server's does: repeats are free, and a 33rd distinct name
666
+ * rejects the form (issue #408).
667
+ */
668
+ function parseObjectsAlign(align) {
669
+ if (!align.startsWith("objects("))
670
+ return null;
671
+ const inner = align.slice("objects(".length);
672
+ const close = inner.indexOf(")");
673
+ if (close < 0)
674
+ return null;
675
+ const list = inner.slice(0, close);
676
+ const tail = inner.slice(close + 1);
677
+ let scale = 1;
678
+ if (tail !== "") {
679
+ if (!tail.startsWith(":"))
680
+ return null;
681
+ const text = tail.slice(1);
682
+ if (!isFloat(text))
683
+ return null;
684
+ scale = Number(text);
685
+ if (!(scale > 0) || scale > 100)
686
+ return null;
687
+ }
688
+ const parts = list.split(",");
689
+ const classes = [];
690
+ const seen = new Set();
691
+ for (const part of parts) {
692
+ const decoded = percentDecodable(part);
693
+ if (decoded === null)
694
+ return null;
695
+ const name = decoded.trim();
696
+ if (!isClassName(name))
697
+ return null;
698
+ const key = classFoldKey(name);
699
+ if (!seen.has(key)) {
700
+ if (classes.length === MAX_OBJECTS_CLASSES)
701
+ return null;
702
+ seen.add(key);
703
+ classes.push(name);
704
+ }
705
+ }
706
+ return classes.length > 0 ? { classes, scale } : null;
707
+ }
401
708
  function explainSegment(seg, nowSeconds) {
402
709
  if (seg.startsWith("exp:")) {
403
710
  const value = seg.slice(4);
@@ -463,9 +770,45 @@ function explainSegment(seg, nowSeconds) {
463
770
  return {
464
771
  kind: "debug",
465
772
  title: "Debug view",
466
- detail: "the response is a diagnostic image instead of the transform result: the canvas the next crop operates on, with the chosen focal point (magenta crosshair), the focal rectangle when one is in play, detected face boxes (amber), and the crop window outline (blue); with no crop it shows the focal analysis of the final image; debug responses are never cached and are served with Cache-Control: no-store; animated sources and video formats are refused with 400",
773
+ detail: "the response is a diagnostic image instead of the transform result: the canvas the next crop operates on, with the chosen focal point (magenta crosshair), the focal rectangle when one is in play, the detection boxes that fed the decision (amber), and the crop window outline (blue); with no crop it shows the focal analysis of the final image; debug responses are never cached and are served with Cache-Control: no-store; animated sources and video formats are refused with 400",
467
774
  };
468
775
  }
776
+ if (seg.startsWith("frame:")) {
777
+ const rest = seg.slice(6);
778
+ // The server's frame grammar (url.rs parse_frame): the
779
+ // poster keyword, or a strict decimal (no sign, no
780
+ // exponent, no leading dot) as seconds up to 86400 or,
781
+ // with a % suffix, as a percent up to 100.
782
+ const decimal = (text, max) => /^\d+(\.\d+)?$/.test(text) && Number(text) <= max;
783
+ if (rest === "poster") {
784
+ return { kind: "operation", title: "Frame", detail: "render the video source's poster frame" };
785
+ }
786
+ if (rest.endsWith("%") && decimal(rest.slice(0, -1), 100)) {
787
+ return { kind: "operation", title: "Frame", detail: `render the frame ${rest} through the video source` };
788
+ }
789
+ if (!rest.endsWith("%") && decimal(rest, 86400)) {
790
+ return { kind: "operation", title: "Frame", detail: `render the frame at ${rest} seconds into the video source` };
791
+ }
792
+ return {
793
+ kind: "operation",
794
+ title: "Frame",
795
+ error: `malformed frame segment: ${seg} (want frame:poster, frame:<seconds> up to 86400, or frame:<percent>% up to 100; the server answers 400)`,
796
+ };
797
+ }
798
+ if (seg.startsWith("page:")) {
799
+ const rest = seg.slice(5);
800
+ // The server's page grammar (url.rs parse_page): ASCII
801
+ // digits, leading zeros allowed, 1 to 999999.
802
+ const digits = rest.replace(/^0+/, "");
803
+ if (!/^\d+$/.test(rest) || digits === "" || digits.length > 6) {
804
+ return {
805
+ kind: "operation",
806
+ title: "Page",
807
+ error: `malformed page segment: ${seg} (want page:<n> with n from 1 to 999999; the server answers 400)`,
808
+ };
809
+ }
810
+ return { kind: "operation", title: "Page", detail: `render page ${Number(digits)} of the PDF source` };
811
+ }
469
812
  if (seg.startsWith("preset:")) {
470
813
  const name = seg.slice(7);
471
814
  if (!name) {
@@ -507,17 +850,53 @@ function explainSegment(seg, nowSeconds) {
507
850
  }
508
851
  return { kind: "operation", title: "Focal rectangle", detail: `set the focal rectangle ${rest} for the next crop (left x top : right x bottom)` };
509
852
  }
853
+ if (seg.startsWith("focalpoint:")) {
854
+ const rest = seg.slice(11);
855
+ const colon = rest.indexOf(":");
856
+ const point = colon === -1 ? rest : rest.slice(0, colon);
857
+ const zoomText = colon === -1 ? null : rest.slice(colon + 1);
858
+ const xy = point.split("x");
859
+ const ok = xy.length === 2 &&
860
+ isFloat(xy[0]) &&
861
+ isFloat(xy[1]) &&
862
+ Number(xy[0]) >= 0 &&
863
+ Number(xy[0]) <= 1 &&
864
+ Number(xy[1]) >= 0 &&
865
+ Number(xy[1]) <= 1 &&
866
+ (zoomText === null ||
867
+ (isFloat(zoomText) && Number(zoomText) > 0 && Number(zoomText) <= 100));
868
+ if (!ok) {
869
+ return {
870
+ kind: "operation",
871
+ title: "Focal point",
872
+ error: `malformed focalpoint segment: ${seg} (want focalpoint:<x>x<y>[:<zoom>] with x and y in 0..1 and zoom in (0, 100])`,
873
+ };
874
+ }
875
+ return {
876
+ kind: "operation",
877
+ title: "Focal point",
878
+ detail: `set the focal point ${point} at zoom ${zoomText ?? "1"} for the next crop (fractions of the image dimensions; zoom above 1 tightens the crop around the point)`,
879
+ };
880
+ }
510
881
  if (seg.startsWith("crop:")) {
511
882
  const rest = seg.slice(5);
512
883
  const idx = rest.indexOf(":");
513
884
  const dims = idx === -1 ? rest : rest.slice(0, idx);
514
885
  const align = idx === -1 ? "center" : rest.slice(idx + 1);
515
886
  const cropSize = parseSizeSegment(dims);
516
- if (!cropSize || !isExactBox(cropSize) || !ALIGN_NAMES.has(align)) {
887
+ const objects = align.startsWith("objects") ? parseObjectsAlign(align) : null;
888
+ if (!cropSize || !isExactBox(cropSize) || (!ALIGN_NAMES.has(align) && objects === null)) {
517
889
  return {
518
890
  kind: "operation",
519
891
  title: "Crop",
520
- error: `malformed crop segment: ${seg} (want crop:<w>x<h>[:center|smart|face|top|bottom|left|right|top-left|top-right|bottom-left|bottom-right], pixels only, no flips)`,
892
+ error: `malformed crop segment: ${seg} (want crop:<w>x<h>[:center|smart|face|top|bottom|left|right|top-left|top-right|bottom-left|bottom-right|objects(<class>[,<class>...])[:<scale>]], pixels only, no flips)`,
893
+ };
894
+ }
895
+ if (objects !== null) {
896
+ return {
897
+ kind: "operation",
898
+ title: "Crop",
899
+ detail: `crop to the aspect of ${dims} and resize to it; alignment: objects (${objects.classes.join(", ")}): frame the union of every detection of the named classes, the union box scaled by ${objects.scale} about its center and the crop centered on it; needs a detection model on the server, and falls back to the plain center crop of the same size when none of the classes is detected`,
521
900
  };
522
901
  }
523
902
  return { kind: "operation", title: "Crop", detail: `crop to the aspect of ${dims} and resize to it; alignment: ${align === "center" ? "center (or the focal point for smart)" : align}` };
@@ -557,8 +936,41 @@ function explainSegment(seg, nowSeconds) {
557
936
  if (parseSizeSegment(seg)) {
558
937
  return { kind: "operation", title: "Resize", detail: sizeBlurb(seg) };
559
938
  }
939
+ if (isSizeShaped(seg)) {
940
+ // The server's dispatch (url.rs size_shaped, issue #228):
941
+ // a segment shaped like a size that fails the size
942
+ // grammar is a malformed size, not the start of the
943
+ // source, so the request is a 400 rather than a fetch
944
+ // of a nonsense source.
945
+ return {
946
+ kind: "operation",
947
+ title: "Resize",
948
+ error: `malformed size segment: ${seg} (each side is a pixel count up to ${MAX_DIMENSION}, 0, or orig; the server answers 400)`,
949
+ };
950
+ }
560
951
  return null; // Not an operation: the source starts here.
561
952
  }
953
+ /**
954
+ * The server's size-shape test (url.rs size_shaped), ported:
955
+ * an `x` joining two parts, at least one of them a dimension
956
+ * spelling (digits, `orig`, or empty, with an optional flip
957
+ * sign), and no `.` or `:` anywhere, the punctuation that
958
+ * marks URL text.
959
+ */
960
+ function isSizeShaped(seg) {
961
+ const x = seg.indexOf("x");
962
+ if (x === -1)
963
+ return false;
964
+ const left = seg.slice(0, x);
965
+ const right = seg.slice(x + 1);
966
+ if (left.includes(".") || right.includes(".") || seg.includes(":"))
967
+ return false;
968
+ const spelling = (part) => {
969
+ const digits = part.startsWith("-") ? part.slice(1) : part;
970
+ return digits === "" || digits === "orig" || /^\d+$/.test(digits);
971
+ };
972
+ return spelling(left) || spelling(right);
973
+ }
562
974
  /**
563
975
  * Parse a crabcrop URL (or bare path) back into its pieces,
564
976
  * explaining each segment. Mirrors the server's dispatch:
@@ -589,6 +1001,21 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
589
1001
  path = path.slice(0, cut);
590
1002
  }
591
1003
  const errors = [];
1004
+ // A sealed URL is a single segment: the token carries
1005
+ // the whole remainder encrypted, so there is no slash
1006
+ // and nothing visible to itemize (issue #388).
1007
+ const sealedWhole = path.match(/^(?:([A-Za-z0-9_-]{1,32}):)?s1\.([A-Za-z0-9_-]+)$/);
1008
+ if (sealedWhole) {
1009
+ const signature = {
1010
+ kind: "sealed",
1011
+ value: `s1.${sealedWhole[2]}`,
1012
+ detail: "sealed token (AES-256-GCM): the operations and source are encrypted inside it, so there is nothing visible to itemize; the server opens it and serves the URL it carries",
1013
+ };
1014
+ if (sealedWhole[1]) {
1015
+ signature.keyId = sealedWhole[1];
1016
+ }
1017
+ return { signature, segments: [], source: "", remainder: "", errors: [] };
1018
+ }
592
1019
  const slash = path.indexOf("/");
593
1020
  if (slash === -1) {
594
1021
  return { signature: null, segments: [], source: "", remainder: "", errors: ["no signature segment: the path is a single segment"] };
@@ -597,6 +1024,22 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
597
1024
  const remainder = path.slice(slash + 1);
598
1025
  let signature;
599
1026
  const keyed = signatureRaw.match(/^([A-Za-z0-9_-]{1,32}):([0-9a-f]{64})$/);
1027
+ const sealedTok = signatureRaw.match(/^(?:([A-Za-z0-9_-]{1,32}):)?s1\.([A-Za-z0-9_-]+)$/);
1028
+ if (sealedTok) {
1029
+ // A sealed token with a trailing path (issue #388):
1030
+ // the server opens the token and serves the URL it
1031
+ // carries; the visible remainder behind it is not
1032
+ // part of that URL, so there is nothing to itemize.
1033
+ signature = {
1034
+ kind: "sealed",
1035
+ value: `s1.${sealedTok[2]}`,
1036
+ detail: "sealed token (AES-256-GCM): the operations and source are encrypted inside it; the server opens it and serves the URL it carries, and anything visible after the token is not part of that URL",
1037
+ };
1038
+ if (sealedTok[1]) {
1039
+ signature.keyId = sealedTok[1];
1040
+ }
1041
+ return { signature, segments: [], source: "", remainder, errors };
1042
+ }
600
1043
  if (signatureRaw === "unsafe") {
601
1044
  signature = { kind: "unsafe", value: signatureRaw, detail: "unsigned; the server honors it only with CRABCROP_ALLOW_UNSAFE or in presets-only deployments" };
602
1045
  }
@@ -610,6 +1053,10 @@ export function explainUrl(input, nowSeconds = Math.floor(Date.now() / 1000)) {
610
1053
  signature = { kind: "invalid", value: signatureRaw, detail: "lowercase hex, but not a full 64-character HMAC tag: the server will answer 403" };
611
1054
  errors.push("malformed signature segment");
612
1055
  }
1056
+ else if (/^(?:[A-Za-z0-9_-]{1,32}:)?s\d+\./.test(signatureRaw)) {
1057
+ signature = { kind: "invalid", value: signatureRaw, detail: "a sealed-token shape this scheme does not open (an unknown version marker, or a malformed token body): the server answers the uniform 403 refusal, indistinguishable from a token that fails to open" };
1058
+ errors.push("malformed signature segment");
1059
+ }
613
1060
  else {
614
1061
  signature = { kind: "invalid", value: signatureRaw, detail: "not `unsafe` and not lowercase hex: the server rejects it as malformed (400)" };
615
1062
  errors.push("malformed signature segment");