@crabcrop/url 0.9.5 → 0.9.7

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/explain.js CHANGED
@@ -13,9 +13,11 @@ export const FILTER_DESCRIPTIONS = {
13
13
  blurfaces: "blur detected faces (needs a face model on the server)",
14
14
  brighten: "brighten by the given amount (-255..255)",
15
15
  contrast: "contrast in percent, -100..100 (0 is unchanged, -100 is flat)",
16
+ gamma: "gamma correction with divisor g, 0 < g <= 10: each channel becomes 255 * (v / 255)^(1 / g) (1 is unchanged, above 1 brightens midtones)",
16
17
  huerotate: "rotate the hue by the given degrees",
17
18
  rotate: "rotate by the given angle in degrees; the canvas expands to fit",
18
19
  quality: "output quality 1..100, or `auto` for perceptual targeting",
20
+ palette: "write PNG output as an indexed (palette) image with at most this many colors, 2..256; ignored by the other formats",
19
21
  format: "force the output format",
20
22
  fill: "the background color other operations pad with",
21
23
  facepad: "how much a face crop expands around the face",
@@ -24,6 +26,7 @@ export const FILTER_DESCRIPTIONS = {
24
26
  pixelateclass: "pixelate every detected object of the named class (needs a detection model on the server)",
25
27
  recolorclass: "recolor every detected object of the named class to the given color (needs a detection model on the server)",
26
28
  removebg: "remove the background (needs an AI model on the server)",
29
+ 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)",
27
30
  keep_profile: "keep the source color profile instead of converting to sRGB",
28
31
  upscale: "AI upscale by the given factor (needs an AI model on the server)",
29
32
  equalize: "histogram equalization",
@@ -34,7 +37,7 @@ export const FILTER_DESCRIPTIONS = {
34
37
  curve: "tone curve: remap the named channel (rgb, r, g, or b) through 2 to 16 x,y control points, linearly interpolated, ends clamped",
35
38
  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",
36
39
  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)",
37
- trim: "trim uniform borders",
40
+ trim: "trim uniform borders; the five-argument form (tolerance,left,top,right,bottom) also removes that many pixels per side after the tolerance pass",
38
41
  dpr: "device pixel ratio the sizes are multiplied by",
39
42
  watermark: "overlay a watermark image",
40
43
  max_bytes: "cap the output size, lowering quality to fit",
@@ -165,8 +168,18 @@ function validateFilter(name, args) {
165
168
  return args === null ? null : bad;
166
169
  }
167
170
  switch (name) {
168
- case "trim":
169
- return args === null || isIntIn(args, 0, 255) ? null : bad;
171
+ case "trim": {
172
+ if (args === null)
173
+ return null;
174
+ const parts = args.split(",");
175
+ if (parts.length === 1)
176
+ return isIntIn(parts[0], 0, 255) ? null : bad;
177
+ return parts.length === 5 &&
178
+ isIntIn(parts[0], 0, 255) &&
179
+ parts.slice(1).every((p) => isIntIn(p, 0, 4294967295))
180
+ ? null
181
+ : bad;
182
+ }
170
183
  case "blur":
171
184
  case "sharpen":
172
185
  return args !== null && isFloat(args) && Number(args) > 0 ? null : bad;
@@ -178,12 +191,18 @@ function validateFilter(name, args) {
178
191
  return args !== null && isFloat(args) && Number(args) >= -100 && Number(args) <= 100
179
192
  ? null
180
193
  : bad;
194
+ case "gamma":
195
+ return args !== null && isFloat(args) && Number(args) > 0 && Number(args) <= 10
196
+ ? null
197
+ : bad;
181
198
  case "saturation":
182
199
  return args !== null && isFloat(args) && Number(args) >= 0 && Number(args) <= 255
183
200
  ? null
184
201
  : bad;
185
202
  case "quality":
186
203
  return args === "auto" || (args !== null && isIntIn(args, 1, 100)) ? null : bad;
204
+ case "palette":
205
+ return args !== null && isIntIn(args, 2, 256) ? null : bad;
187
206
  case "format":
188
207
  return args !== null && FORMAT_NAMES.has(args) ? null : bad;
189
208
  case "rgb": {
@@ -230,6 +249,55 @@ function validateFilter(name, args) {
230
249
  return args !== null && /^[+-]?\d+$/.test(args) && (Number(args) === 2 || Number(args) === 4)
231
250
  ? null
232
251
  : bad;
252
+ case "studio": {
253
+ // The server's studio grammar (url.rs parse_studio):
254
+ // the mode (`product` or `scene`) first, then named
255
+ // `key:value` arguments, each key at most once.
256
+ // Product takes `bg`, `shadow`, and `pad`; scene
257
+ // takes `pad` only, because a backdrop and a shadow
258
+ // are product concepts (naming one under scene is a
259
+ // bad argument, not a silent no-op).
260
+ if (args === null)
261
+ return bad;
262
+ const parts = args.split(",");
263
+ const mode = parts[0];
264
+ if (mode !== "product" && mode !== "scene")
265
+ return bad;
266
+ const seen = new Set();
267
+ for (const part of parts.slice(1)) {
268
+ const cut = part.indexOf(":");
269
+ if (cut === -1)
270
+ return bad;
271
+ const key = part.slice(0, cut);
272
+ const value = part.slice(cut + 1);
273
+ if (seen.has(key))
274
+ return bad;
275
+ seen.add(key);
276
+ if (key === "pad") {
277
+ // The pad parses as a Rust u8 (an optional `+`,
278
+ // then digits; no minus sign, not even `-0`) and
279
+ // is bounded to 40.
280
+ if (!/^\+?\d+$/.test(value) || BigInt(value) > 40n)
281
+ return bad;
282
+ }
283
+ else if (mode === "product" && key === "bg") {
284
+ if (value !== "white" &&
285
+ value !== "brand" &&
286
+ value !== "none" &&
287
+ !/^[0-9a-fA-F]{6}$/.test(value)) {
288
+ return bad;
289
+ }
290
+ }
291
+ else if (mode === "product" && key === "shadow") {
292
+ if (value !== "none" && value !== "soft" && value !== "strong")
293
+ return bad;
294
+ }
295
+ else {
296
+ return bad;
297
+ }
298
+ }
299
+ return null;
300
+ }
233
301
  case "dpr":
234
302
  return args !== null && isFloat(args) && [1, 1.5, 2, 3].includes(Number(args))
235
303
  ? null
@@ -394,9 +462,30 @@ function validateFilter(name, args) {
394
462
  }
395
463
  }
396
464
  function explainFilters(rest) {
397
- // The server splits the list naively on ':'; a ':' inside
398
- // parentheses is not special there either.
399
- const parts = rest.split(":");
465
+ // The server splits the list on the ':' separators that
466
+ // sit outside parentheses (url.rs split_filter_chain):
467
+ // an argument list may itself contain ':' (the studio
468
+ // filter's named arguments are `key:value`), so a naive
469
+ // split would cut those filters apart. Unbalanced
470
+ // parentheses leave the tail in one part, which then
471
+ // fails its own parse, as on the server.
472
+ const parts = [];
473
+ let depth = 0;
474
+ let start = 0;
475
+ for (let i = 0; i < rest.length; i++) {
476
+ const c = rest[i];
477
+ if (c === "(") {
478
+ depth += 1;
479
+ }
480
+ else if (c === ")") {
481
+ depth = Math.max(0, depth - 1);
482
+ }
483
+ else if (c === ":" && depth === 0) {
484
+ parts.push(rest.slice(start, i));
485
+ start = i + 1;
486
+ }
487
+ }
488
+ parts.push(rest.slice(start));
400
489
  const blurbs = [];
401
490
  for (const part of parts) {
402
491
  const match = part.match(/^([a-z_0-9]+)(?:\((.*)\))?$/);
@@ -528,6 +617,34 @@ function explainSegment(seg, nowSeconds) {
528
617
  }
529
618
  return { kind: "operation", title: "Focal rectangle", detail: `set the focal rectangle ${rest} for the next crop (left x top : right x bottom)` };
530
619
  }
620
+ if (seg.startsWith("focalpoint:")) {
621
+ const rest = seg.slice(11);
622
+ const colon = rest.indexOf(":");
623
+ const point = colon === -1 ? rest : rest.slice(0, colon);
624
+ const zoomText = colon === -1 ? null : rest.slice(colon + 1);
625
+ const xy = point.split("x");
626
+ const ok = xy.length === 2 &&
627
+ isFloat(xy[0]) &&
628
+ isFloat(xy[1]) &&
629
+ Number(xy[0]) >= 0 &&
630
+ Number(xy[0]) <= 1 &&
631
+ Number(xy[1]) >= 0 &&
632
+ Number(xy[1]) <= 1 &&
633
+ (zoomText === null ||
634
+ (isFloat(zoomText) && Number(zoomText) > 0 && Number(zoomText) <= 100));
635
+ if (!ok) {
636
+ return {
637
+ kind: "operation",
638
+ title: "Focal point",
639
+ error: `malformed focalpoint segment: ${seg} (want focalpoint:<x>x<y>[:<zoom>] with x and y in 0..1 and zoom in (0, 100])`,
640
+ };
641
+ }
642
+ return {
643
+ kind: "operation",
644
+ title: "Focal point",
645
+ 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)`,
646
+ };
647
+ }
531
648
  if (seg.startsWith("crop:")) {
532
649
  const rest = seg.slice(5);
533
650
  const idx = rest.indexOf(":");
package/dist/index.d.ts CHANGED
@@ -146,7 +146,7 @@ export { explainUrl } from "./explain.ts";
146
146
  export { FILTER_DESCRIPTIONS } from "./explain.ts";
147
147
  export type { ExplainedSegment, Explanation, SegmentKind, SignatureKind } from "./explain.ts";
148
148
  export { filter, joinOps, ops } from "./operations.ts";
149
- export type { Anchor, BlendMode, CropAlign, CurveChannel, Dimension, ImageFormat, MaskShape, } from "./operations.ts";
149
+ export type { Anchor, BlendMode, CropAlign, CurveChannel, Dimension, ImageFormat, MaskShape, StudioMode, StudioOptions, StudioShadow, } from "./operations.ts";
150
150
  /**
151
151
  * Verify a URL's signature locally. Returns true or false, or
152
152
  * null when the URL is unsigned or malformed.
@@ -23,6 +23,36 @@ export type BlendMode = "normal" | "multiply" | "screen" | "overlay";
23
23
  export type MaskShape = "circle" | "ellipse";
24
24
  /** Channels the `curve(...)` filter remaps. */
25
25
  export type CurveChannel = "rgb" | "r" | "g" | "b";
26
+ /** Modes the `studio(...)` filter runs. */
27
+ export type StudioMode = "product" | "scene";
28
+ /** Contact shadow strengths for `studio(product, ...)`. */
29
+ export type StudioShadow = "soft" | "strong" | "none";
30
+ /**
31
+ * Named arguments for the `studio(...)` filter. `bg` and
32
+ * `shadow` are product arguments only: the server rejects
33
+ * them under `scene`, so the builder throws for them there.
34
+ */
35
+ export interface StudioOptions {
36
+ /**
37
+ * The product backdrop: `"white"`, `"brand"` (the
38
+ * operator brand color, white when none is configured),
39
+ * `"none"` (the subject keeps its transparency and no
40
+ * shadow is synthesized), or a RRGGBB hex color. Unset
41
+ * means the unnamed default: the brand color when one
42
+ * is configured, else white. Naming `"white"` is not
43
+ * the default: the two can resolve differently, so they
44
+ * spell differently.
45
+ */
46
+ bg?: string;
47
+ /** Contact shadow strength; the default is `"soft"`. */
48
+ shadow?: StudioShadow;
49
+ /**
50
+ * Pad margin in percent, 0..40; the default is 10.
51
+ * Under `scene` it is the margin the reframed subject
52
+ * keeps.
53
+ */
54
+ pad?: number;
55
+ }
26
56
  /**
27
57
  * One side of a size: a pixel count (1..16383), 0 for
28
58
  * proportional, a negative count to flip that axis, or
@@ -45,6 +75,8 @@ export declare const ops: {
45
75
  cropRect(left: number, top: number, right: number, bottom: number): string;
46
76
  /** `focal:10x20:110x220` (left x top : right x bottom); steers the next crop. */
47
77
  focal(left: number, top: number, right: number, bottom: number): string;
78
+ /** `focalpoint:0.75x0.4:2` (fractions of the image dimensions, zoom optional); steers the next crop. */
79
+ focalPoint(x: number, y: number, zoom?: number): string;
48
80
  /** `pad:300x200`, optionally `:blur` or a RRGGBB fill color. */
49
81
  pad(width: number, height: number, fill?: "blur" | string): string;
50
82
  /** `preset:thumb`; expands server-side. */
@@ -90,6 +122,8 @@ export declare const filter: {
90
122
  brighten(amount: number): string;
91
123
  /** Percent contrast: -100..100 (0 unchanged, -100 flat). */
92
124
  contrast(percent: number): string;
125
+ /** Gamma correction divisor: 0 < g <= 10 (1 unchanged; above 1 brightens midtones). */
126
+ gamma(value: number): string;
93
127
  /** Rotate the hue by integer degrees. */
94
128
  hueRotate(degrees: number): string;
95
129
  /** Saturation factor: 0..255 (0 grayscale, 1 identity). */
@@ -131,13 +165,31 @@ export declare const filter: {
131
165
  rotate(angle: number): string;
132
166
  /** Trim uniform borders; tolerance 0..255, default 10. */
133
167
  trim(tolerance?: number): string;
168
+ /** Trim uniform borders, then remove pixels per side (left, top, right, bottom). */
169
+ trimSides(tolerance: number, left: number, top: number, right: number, bottom: number): string;
134
170
  /** Encoding quality 1..100, or `"auto"` for perceptual targeting. */
135
171
  quality(value: number | "auto"): string;
172
+ /** Indexed PNG output with at most this many colors, 2..256; other formats ignore it. */
173
+ palette(colors: number): string;
136
174
  format(format: ImageFormat): string;
137
175
  /** The background color other operations pad with (RRGGBB). */
138
176
  fill(color: string): string;
139
177
  /** How much a face crop expands around the face: 0..3. */
140
178
  facePad(amount: number): string;
179
+ /**
180
+ * Studio mode: `studio(product)` composites the subject
181
+ * the server's segmentation model finds onto a backdrop
182
+ * with a synthesized contact shadow, scaled and centered
183
+ * to the pad margin; `studio(scene)` keeps the
184
+ * photograph's scene, reframing it on the detected
185
+ * subject and correcting light and color. See
186
+ * {@link StudioOptions} for the named arguments.
187
+ * Arguments spelled at their defaults (shadow `soft`,
188
+ * pad 10) are omitted, matching the server's canonical
189
+ * spelling, so `studio("product", { pad: 10 })` and
190
+ * `studio("product")` are the same string.
191
+ */
192
+ studio(mode: StudioMode, options?: StudioOptions): string;
141
193
  /** AI upscale by the given factor. */
142
194
  upscale(factor: 2 | 4): string;
143
195
  /** Device pixel ratio the sizes are multiplied by. */
@@ -113,6 +113,8 @@ const ANCHORS = [
113
113
  ];
114
114
  const BLEND_MODES = ["normal", "multiply", "screen", "overlay"];
115
115
  const CURVE_CHANNELS = ["rgb", "r", "g", "b"];
116
+ const STUDIO_MODES = ["product", "scene"];
117
+ const STUDIO_SHADOWS = ["soft", "strong", "none"];
116
118
  const IMAGE_FORMATS = ["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"];
117
119
  /** Operation segments, one typed call per segment kind. */
118
120
  export const ops = {
@@ -167,6 +169,19 @@ export const ops = {
167
169
  }
168
170
  return `focal:${left}x${top}:${right}x${bottom}`;
169
171
  },
172
+ /** `focalpoint:0.75x0.4:2` (fractions of the image dimensions, zoom optional); steers the next crop. */
173
+ focalPoint(x, y, zoom = 1) {
174
+ const frac = (what, v) => {
175
+ if (!Number.isFinite(v) || v < 0 || v > 1) {
176
+ fail(what, v, "a fraction from 0 to 1");
177
+ }
178
+ return v;
179
+ };
180
+ if (!Number.isFinite(zoom) || zoom <= 0 || zoom > 100) {
181
+ fail("focalpoint zoom", zoom, "a number above 0 and at most 100");
182
+ }
183
+ return `focalpoint:${num(frac("focalpoint x", x))}x${num(frac("focalpoint y", y))}:${num(zoom)}`;
184
+ },
170
185
  /** `pad:300x200`, optionally `:blur` or a RRGGBB fill color. */
171
186
  pad(width, height, fill) {
172
187
  const box = pixelBox("pad", width, height);
@@ -265,6 +280,13 @@ export const filter = {
265
280
  contrast(percent) {
266
281
  return `contrast(${num(floatIn("contrast", percent, -100, 100))})`;
267
282
  },
283
+ /** Gamma correction divisor: 0 < g <= 10 (1 unchanged; above 1 brightens midtones). */
284
+ gamma(value) {
285
+ if (!Number.isFinite(value) || value <= 0 || value > 10) {
286
+ fail("gamma", value, "a number above 0 and at most 10");
287
+ }
288
+ return `gamma(${num(value)})`;
289
+ },
268
290
  /** Rotate the hue by integer degrees. */
269
291
  hueRotate(degrees) {
270
292
  return `huerotate(${intIn("huerotate degrees", degrees, -2147483648, 2147483647)})`;
@@ -359,12 +381,21 @@ export const filter = {
359
381
  trim(tolerance = 10) {
360
382
  return `trim(${intIn("trim tolerance", tolerance, 0, 255)})`;
361
383
  },
384
+ /** Trim uniform borders, then remove pixels per side (left, top, right, bottom). */
385
+ trimSides(tolerance, left, top, right, bottom) {
386
+ const side = (what, v) => intIn(what, v, 0, 4294967295);
387
+ return `trim(${intIn("trim tolerance", tolerance, 0, 255)},${side("trim left", left)},${side("trim top", top)},${side("trim right", right)},${side("trim bottom", bottom)})`;
388
+ },
362
389
  /** Encoding quality 1..100, or `"auto"` for perceptual targeting. */
363
390
  quality(value) {
364
391
  if (value === "auto")
365
392
  return "quality(auto)";
366
393
  return `quality(${intIn("quality", value, 1, 100)})`;
367
394
  },
395
+ /** Indexed PNG output with at most this many colors, 2..256; other formats ignore it. */
396
+ palette(colors) {
397
+ return `palette(${intIn("palette colors", colors, 2, 256)})`;
398
+ },
368
399
  format(format) {
369
400
  if (!IMAGE_FORMATS.includes(format)) {
370
401
  fail("format", format, `one of ${IMAGE_FORMATS.join(", ")}`);
@@ -379,6 +410,48 @@ export const filter = {
379
410
  facePad(amount) {
380
411
  return `facepad(${num(floatIn("facepad", amount, 0, 3))})`;
381
412
  },
413
+ /**
414
+ * Studio mode: `studio(product)` composites the subject
415
+ * the server's segmentation model finds onto a backdrop
416
+ * with a synthesized contact shadow, scaled and centered
417
+ * to the pad margin; `studio(scene)` keeps the
418
+ * photograph's scene, reframing it on the detected
419
+ * subject and correcting light and color. See
420
+ * {@link StudioOptions} for the named arguments.
421
+ * Arguments spelled at their defaults (shadow `soft`,
422
+ * pad 10) are omitted, matching the server's canonical
423
+ * spelling, so `studio("product", { pad: 10 })` and
424
+ * `studio("product")` are the same string.
425
+ */
426
+ studio(mode, options = {}) {
427
+ if (!STUDIO_MODES.includes(mode)) {
428
+ fail("studio mode", mode, `one of ${STUDIO_MODES.join(", ")}`);
429
+ }
430
+ const { bg, shadow, pad } = options;
431
+ if (mode === "scene" && (bg !== undefined || shadow !== undefined)) {
432
+ fail("studio scene options", options, "pad only: bg and shadow are product arguments");
433
+ }
434
+ const parts = [mode];
435
+ if (mode === "product") {
436
+ if (bg !== undefined) {
437
+ const value = bg === "white" || bg === "brand" || bg === "none" ? bg : hex6("studio bg", bg);
438
+ parts.push(`bg:${value}`);
439
+ }
440
+ if (shadow !== undefined) {
441
+ if (!STUDIO_SHADOWS.includes(shadow)) {
442
+ fail("studio shadow", shadow, `one of ${STUDIO_SHADOWS.join(", ")}`);
443
+ }
444
+ if (shadow !== "soft")
445
+ parts.push(`shadow:${shadow}`);
446
+ }
447
+ }
448
+ if (pad !== undefined) {
449
+ intIn("studio pad", pad, 0, 40);
450
+ if (pad !== 10)
451
+ parts.push(`pad:${pad}`);
452
+ }
453
+ return `studio(${parts.join(",")})`;
454
+ },
382
455
  /** AI upscale by the given factor. */
383
456
  upscale(factor) {
384
457
  if (factor !== 2 && factor !== 4) {
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  "test": "node --test"
22
22
  },
23
23
  "type": "module",
24
- "version": "0.9.5",
24
+ "version": "0.9.7",
25
25
  "devDependencies": {
26
26
  "@types/node": "^26.6.5",
27
27
  "typescript": "^7.0.2"