@capacms/sdk 1.0.0-next.10 → 1.0.0-next.12

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 (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
@@ -27,7 +27,7 @@
27
27
  * run what it builds back through `canonicalise`. The API imports it from here.
28
28
  */
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
- 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;
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
31
  exports.defaultQuality = defaultQuality;
32
32
  exports.droppableQuality = droppableQuality;
33
33
  exports.parseImageParams = parseImageParams;
@@ -35,6 +35,16 @@ exports.canonicalise = canonicalise;
35
35
  exports.canonicalQuery = canonicalQuery;
36
36
  exports.buildSignature = buildSignature;
37
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;
38
48
  /** Content type emitted for each explicitly requestable output format. */
39
49
  exports.OUTPUT_MIME = {
40
50
  webp: "image/webp",
@@ -322,6 +332,18 @@ function num(n) {
322
332
  function encodePart(text) {
323
333
  return encodeURIComponent(text).replace(/'/g, "%27");
324
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
+ }
325
347
  /**
326
348
  * The canonical spelling of a query, so `?width=200&format=webp` and
327
349
  * `?format=webp&width=200` are one edge object rather than two.
@@ -334,12 +356,12 @@ function encodePart(text) {
334
356
  *
335
357
  * @param rawQuery the query string as received, without the leading `?`
336
358
  */
337
- function canonicalise(rawQuery, params) {
359
+ function canonicalise(rawQuery, params, options = {}) {
338
360
  const received = new URLSearchParams(rawQuery);
339
- const usesNewParam = [...received.keys()].some((k) => exports.NEW_PARAMS.has(k));
361
+ const usesNewParam = [...received.keys()].some((k) => exports.NEW_PARAMS.has(k) || (options.focal === true && exports.FOCAL_PARAMS.has(k)));
340
362
  if (!usesNewParam)
341
363
  return { query: rawQuery, isCanonical: true };
342
- const query = canonicalQuery(rawQuery, params);
364
+ const query = canonicalQuery(rawQuery, params, options);
343
365
  return { query, isCanonical: query === rawQuery };
344
366
  }
345
367
  /**
@@ -355,7 +377,7 @@ function canonicalise(rawQuery, params) {
355
377
  * @param rawQuery the query string, without the leading `?`; read only for the
356
378
  * keys this module does not know, which are kept
357
379
  */
358
- function canonicalQuery(rawQuery, params) {
380
+ function canonicalQuery(rawQuery, params, options = {}) {
359
381
  const received = new URLSearchParams(rawQuery);
360
382
  const keys = [...new Set([...received.keys()])];
361
383
  const out = new Map();
@@ -387,6 +409,12 @@ function canonicalQuery(rawQuery, params) {
387
409
  out.set("upscale", "1");
388
410
  if (params.keepMetadata)
389
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
+ }
390
418
  // Unknown keys are preserved verbatim (first value wins, repeats collapse),
391
419
  // so a cache-buster survives the redirect instead of being silently dropped.
392
420
  //
@@ -396,6 +424,8 @@ function canonicalQuery(rawQuery, params) {
396
424
  for (const key of keys) {
397
425
  if (exports.LEGACY_PARAMS.has(key) || exports.NEW_PARAMS.has(key))
398
426
  continue;
427
+ if (options.focal === true && exports.FOCAL_PARAMS.has(key))
428
+ continue;
399
429
  const value = received.get(key) ?? "";
400
430
  if (key === "" && value === "")
401
431
  continue;
@@ -403,7 +433,7 @@ function canonicalQuery(rawQuery, params) {
403
433
  }
404
434
  const sorted = [...out.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
405
435
  return sorted
406
- .map(([k, v]) => (v === "" ? encodePart(k) : `${encodePart(k)}=${encodePart(v)}`))
436
+ .map(([k, v]) => (v === "" ? encodePart(k) : `${encodePart(k)}=${listValue(k, options) ? encodeList(v) : encodePart(v)}`))
407
437
  .join("&");
408
438
  }
409
439
  /**
@@ -434,6 +464,16 @@ function buildSignature(params, resolvedFormat) {
434
464
  parts.push(`q${params.quality}`);
435
465
  if (params.keepMetadata)
436
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], ":")}`);
437
477
  return parts.join("_") || "raw";
438
478
  }
439
479
  /**
@@ -469,3 +509,192 @@ function resolveAutoFormat(accept) {
469
509
  return "webp";
470
510
  return null;
471
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
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createClient, instanceIdOf } from "./client";
2
- export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, Page, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
2
+ export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, FieldValue, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, OneWithRelations, Page, ReadOneOptions, RelatedEntry, Relations, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
3
3
  export type { CapaConfig } from "./config";
4
4
  export { CapaError } from "./http";
5
5
  export { WEBHOOKS_NEED_ACCESS_TOKEN } from "./webhooks";
@@ -26,14 +26,55 @@
26
26
  * Pass `enabled` to override: `true` tags an unmarked entry, `false` tags
27
27
  * nothing. Sites written before edit mode passed `isDraft` here and keep
28
28
  * working unchanged.
29
+ *
30
+ * ONE ITEM OF A LIST. `capaAttrs(entry, "faqs", { item: 2 })` tags the third
31
+ * item of the `faqs` list, so a click on it opens that item in the Capa
32
+ * editor rather than the top of the list field, and focusing the item in the
33
+ * editor outlines it on the page. `item` is the item's index, or a path of
34
+ * indexes and keys inside the field (`[2, "question"]`). It adds
35
+ * `data-capa-item`; an editor or an overlay that does not know it reads the
36
+ * element as the whole field, as before.
37
+ *
38
+ * A TOGGLE. `capaAttrs(entry, "show_banner", { shownWhen: true })` on the
39
+ * element the toggle shows lets live preview hide and show it as the editor
40
+ * flips the toggle, before the save.
29
41
  */
30
42
  export type CapaAttrs = {
31
43
  "data-capa-entry": string;
32
44
  "data-capa-field": string;
45
+ "data-capa-item"?: string;
46
+ "data-capa-shown-when"?: "true" | "false";
33
47
  } | {
34
48
  "data-capa-entry"?: undefined;
35
49
  "data-capa-field"?: undefined;
50
+ "data-capa-item"?: undefined;
51
+ "data-capa-shown-when"?: undefined;
36
52
  };
53
+ /** One item of a list field: its index, or a path of indexes and keys inside the field. */
54
+ export type CapaItem = number | string | readonly (number | string)[];
55
+ /** `capaAttrs`'s third argument, as an object. */
56
+ export interface CapaAttrsOptions {
57
+ /** Tag one item of a list field: `{ item: 2 }` is the third. */
58
+ item?: CapaItem;
59
+ /** Override edit mode, as a boolean third argument does. */
60
+ enabled?: boolean;
61
+ /**
62
+ * For an element a toggle shows: the value it is shown for. While an editor
63
+ * changes the toggle, the overlay hides the element when the unsaved value
64
+ * is not this and shows it when it is, before the save. Render the element
65
+ * with `hidden` rather than leaving it out when the saved value hides it,
66
+ * and turning the toggle on shows it at once.
67
+ */
68
+ shownWhen?: boolean;
69
+ }
70
+ /** The most segments an item path may have. Deeper than any form nests. */
71
+ export declare const ITEM_MAX_DEPTH = 16;
72
+ /**
73
+ * An item as `data-capa-item` spells it: segments joined with dots, each a
74
+ * non-negative whole number or a key of letters, digits, `_` and `-`. Null
75
+ * for anything else, and the element is then tagged as the whole field.
76
+ */
77
+ export declare function itemPath(item: CapaItem | undefined | null): string | null;
37
78
  /** `Symbol.for`, so two copies of the SDK in one bundle agree on the mark. */
38
79
  export declare const CAPA_EDIT: unique symbol;
39
80
  /** Whether an entry was read in edit mode. */
@@ -70,7 +111,7 @@ export type TaggableField<E> = unknown extends FieldsOf<E> ? E extends {
70
111
  type FieldsOf<E> = "fields" extends keyof E ? E["fields" & keyof E] : unknown;
71
112
  export declare function capaAttrs<E extends {
72
113
  id: string;
73
- }>(entry: E, field: TaggableField<E>, enabled?: boolean): CapaAttrs;
114
+ }>(entry: E, field: TaggableField<E>, options?: boolean | CapaAttrsOptions): CapaAttrs;
74
115
  /**
75
116
  * The attributes for every field of `T`, one `CapaAttrs` per field name.
76
117
  * `capa-codegen` writes `<Model>Attrs = FieldAttrs<Model>` beside each
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CAPA_EDIT = void 0;
3
+ exports.CAPA_EDIT = exports.ITEM_MAX_DEPTH = void 0;
4
+ exports.itemPath = itemPath;
4
5
  exports.isEditEntry = isEditEntry;
5
6
  exports.markEditEntries = markEditEntries;
6
7
  exports.markGraphQLEntries = markGraphQLEntries;
@@ -8,6 +9,36 @@ exports.hasGraphQLEntry = hasGraphQLEntry;
8
9
  exports.carryEditMark = carryEditMark;
9
10
  exports.capaAttrs = capaAttrs;
10
11
  exports.fieldAttrs = fieldAttrs;
12
+ /** The most segments an item path may have. Deeper than any form nests. */
13
+ exports.ITEM_MAX_DEPTH = 16;
14
+ const ITEM_KEY = /^[A-Za-z0-9_-]{1,64}$/;
15
+ /**
16
+ * An item as `data-capa-item` spells it: segments joined with dots, each a
17
+ * non-negative whole number or a key of letters, digits, `_` and `-`. Null
18
+ * for anything else, and the element is then tagged as the whole field.
19
+ */
20
+ function itemPath(item) {
21
+ if (item === undefined || item === null)
22
+ return null;
23
+ const parts = Array.isArray(item) ? item : [item];
24
+ if (parts.length === 0 || parts.length > exports.ITEM_MAX_DEPTH)
25
+ return null;
26
+ const out = [];
27
+ for (const part of parts) {
28
+ if (typeof part === "number") {
29
+ if (!Number.isSafeInteger(part) || part < 0)
30
+ return null;
31
+ out.push(String(part));
32
+ }
33
+ else if (typeof part === "string" && ITEM_KEY.test(part)) {
34
+ out.push(part);
35
+ }
36
+ else {
37
+ return null;
38
+ }
39
+ }
40
+ return out.join(".");
41
+ }
11
42
  /** `Symbol.for`, so two copies of the SDK in one bundle agree on the mark. */
12
43
  exports.CAPA_EDIT = Symbol.for("capacms.edit");
13
44
  /** Whether an entry was read in edit mode. */
@@ -100,10 +131,18 @@ function namespaceOf(entry, field) {
100
131
  const namespaces = entry[CAPA_EDIT_NAMESPACES];
101
132
  return namespaces?.[field] ?? field;
102
133
  }
103
- function capaAttrs(entry, field, enabled = isEditEntry(entry)) {
134
+ function capaAttrs(entry, field, options = isEditEntry(entry)) {
135
+ const enabled = typeof options === "boolean" ? options : (options.enabled ?? isEditEntry(entry));
104
136
  if (!enabled)
105
137
  return {};
106
- return { "data-capa-entry": entry.id, "data-capa-field": namespaceOf(entry, field) };
138
+ const attrs = { "data-capa-entry": entry.id, "data-capa-field": namespaceOf(entry, field) };
139
+ const item = typeof options === "boolean" ? null : itemPath(options.item);
140
+ if (item !== null)
141
+ attrs["data-capa-item"] = item;
142
+ if (typeof options !== "boolean" && typeof options.shownWhen === "boolean") {
143
+ attrs["data-capa-shown-when"] = options.shownWhen ? "true" : "false";
144
+ }
145
+ return attrs;
107
146
  }
108
147
  /**
109
148
  * Typed attributes for every field of one entry (M5), or of one GraphQL node:
@@ -63,6 +63,25 @@ export interface CapaNextConfig {
63
63
  * Capa lists every real URL an entry appears on. Usually set per call.
64
64
  */
65
65
  path?: string;
66
+ /**
67
+ * A draft link's token (`cap_draft_...`), sent as `Capa-Draft-Link` on every
68
+ * REST and GraphQL read. With a development key, Capa then serves that one
69
+ * entry's draft and every other entry as published, and stops serving the
70
+ * draft as soon as the link is revoked or expires. A production key ignores
71
+ * it. `@capacms/sdk/nextjs` sets it from the cookie `createPreviewRoute`
72
+ * keeps; set it yourself only for a client you build by hand.
73
+ */
74
+ draftLink?: string;
75
+ /**
76
+ * A release preview token (the `capa-release` cookie `createPreviewRoute`
77
+ * sets from a release preview link), sent as `Capa-Release`. With a
78
+ * development key, reads then serve what is live plus the releases the
79
+ * token names, and no other draft. A production key's reads ignore it.
80
+ * `@capacms/sdk/nextjs` sets it for you under draft mode (`getCapaClient`,
81
+ * `graphql`, and `draftClient` given `cookies`); `releaseToken` reads it
82
+ * for a client you build yourself.
83
+ */
84
+ release?: string;
66
85
  /** Injected for tests, non-standard runtimes, and framework fetch wrappers. */
67
86
  fetch?: typeof fetch;
68
87
  }
@@ -89,6 +108,17 @@ export interface CallOptions {
89
108
  */
90
109
  path?: string;
91
110
  }
111
+ /** What `preview()` takes beside the call options. */
112
+ export interface PreviewOptions extends CallOptions {
113
+ /**
114
+ * True only from a preview route that keeps a draft link's token and sends
115
+ * it as `draftLink` on its reads, and never turns draft mode on for one, as
116
+ * `createPreviewRoute` given `cookies` does. Sent as `Capa-Draft-Links:
117
+ * narrow`. Without it Capa answers a draft link as an invalid token, so a
118
+ * route that would turn the whole site's draft mode on never opens one.
119
+ */
120
+ draftLinks?: boolean;
121
+ }
92
122
  /**
93
123
  * One entry as `/api/entries` returns it: the system keys, and `fields`. A read
94
124
  * types `fields` from its model and select (`EntryFields`), so a relation is a
@@ -335,6 +365,12 @@ export interface PagesResource {
335
365
  }
336
366
  /** What `GET /api/preview` says a preview token names. */
337
367
  export interface PreviewClaim {
368
+ /**
369
+ * `"release"` for a release preview link, which names releases rather than
370
+ * one entry: `entryId` and `modelId` are then `""` and `namespace` null.
371
+ * Absent for one entry's preview, as before releases.
372
+ */
373
+ kind?: "entry" | "release";
338
374
  entryId: string;
339
375
  modelId: string;
340
376
  /** Null when the model has since lost its route. */
@@ -342,6 +378,17 @@ export interface PreviewClaim {
342
378
  /** Null when the path can no longer be resolved. Falls back to your routing. */
343
379
  path: string | null;
344
380
  expiresAt: string;
381
+ /**
382
+ * True for a draft link, answered only to a `preview()` call given
383
+ * `draftLinks: true`. Keep its token and send it as `draftLink`; do not turn
384
+ * draft mode on for it.
385
+ */
386
+ draftLink?: true;
387
+ /** A release preview's releases, lowest first: the later one wins where two name an entry. */
388
+ releases?: Array<{
389
+ id: string;
390
+ name: string;
391
+ }>;
345
392
  }
346
393
  /**
347
394
  * `client.graphql`: run a document, or build one from a typed selection with
@@ -404,7 +451,7 @@ export interface CapaNextClient<Q = UntypedQuery, O extends GraphQLCallOptions =
404
451
  * Takes any key the site holds, a legacy `pk_`, `sk_` or unprefixed key
405
452
  * included: Capa answers a token minted for another tenant as invalid.
406
453
  */
407
- preview(token: string, options?: CallOptions): Promise<PreviewClaim | null>;
454
+ preview(token: string, options?: PreviewOptions): Promise<PreviewClaim | null>;
408
455
  me<T = Record<string, unknown>>(options?: CallOptions): Promise<T>;
409
456
  versions<T = Record<string, unknown>>(options?: CallOptions): Promise<T>;
410
457
  graphql: GraphQLClient<Q, O>;
@@ -89,6 +89,11 @@ function resolveNextConfig(config) {
89
89
  // should surface while somebody is still writing the code. A checksum that
90
90
  // is silently dropped is a `drift` insight that never appears, which looks
91
91
  // exactly like a site that is up to date.
92
+ // The same rule: a draft link that is not a string would be sent as one,
93
+ // and serve no draft at all.
94
+ if (value.draftLink !== undefined && (typeof value.draftLink !== "string" || value.draftLink.trim() === "")) {
95
+ throw new TypeError(`@capacms/sdk/next: draftLink must be a draft link's token. Got ${JSON.stringify(value.draftLink)}.`);
96
+ }
92
97
  if (value.schemaChecksum !== undefined && value.schemaChecksum !== null) {
93
98
  if (typeof value.schemaChecksum !== "string" || !SCHEMA_CHECKSUM.test(value.schemaChecksum)) {
94
99
  throw new TypeError(`@capacms/sdk/next: schemaChecksum must be the hex checksum from your generated types, for example CAPA_SCHEMA_CHECKSUM. Got ${JSON.stringify(value.schemaChecksum)}.`);
@@ -338,7 +343,7 @@ function cacheTags(response) {
338
343
  return value.split(/\s+/).filter(Boolean);
339
344
  }
340
345
  function createRequester(config) {
341
- return async function request(path, query = new URLSearchParams(), signal, page, pagePath) {
346
+ return async function request(path, query = new URLSearchParams(), signal, page, pagePath, extra) {
342
347
  const url = new URL(config.baseUrl + path);
343
348
  query.forEach((value, key) => url.searchParams.append(key, value));
344
349
  const headers = {
@@ -359,6 +364,16 @@ function createRequester(config) {
359
364
  // still reports which schema it was generated from.
360
365
  if (config.schemaChecksum !== undefined)
361
366
  headers["Capa-Schema"] = config.schemaChecksum;
367
+ // A draft-link visit: Capa serves the linked entry's draft and nothing
368
+ // else. Absent unless set, so every other client's requests are unchanged.
369
+ if (config.draftLink !== undefined)
370
+ headers["Capa-Draft-Link"] = config.draftLink;
371
+ // A release preview (`release`): absent unless set, so every other client
372
+ // sends the requests it always sent.
373
+ if (config.release)
374
+ headers["Capa-Release"] = config.release;
375
+ if (extra)
376
+ Object.assign(headers, extra);
362
377
  const response = await config.fetchImpl(url.toString(), { method: "GET", headers, signal });
363
378
  const requestId = response.headers?.get?.("X-Request-Id") ?? "";
364
379
  const text = await response.text();
@@ -506,7 +521,23 @@ function createClient(config) {
506
521
  const query = new URLSearchParams();
507
522
  query.set("token", token);
508
523
  try {
509
- return (await request("/api/preview", query, options.signal)).body.data;
524
+ const claim = (await request("/api/preview", query, options.signal, undefined, undefined,
525
+ // Only a caller that narrows a draft link opens one (PreviewOptions).
526
+ options.draftLinks === true ? { "Capa-Draft-Links": "narrow" } : undefined)).body.data;
527
+ // A release preview names releases, not an entry: the entry keys are
528
+ // filled so a site that reads them reads a string, never undefined.
529
+ if (claim?.kind === "release") {
530
+ return {
531
+ kind: "release",
532
+ entryId: "",
533
+ modelId: "",
534
+ namespace: null,
535
+ path: claim.path ?? null,
536
+ expiresAt: claim.expiresAt,
537
+ releases: Array.isArray(claim.releases) ? claim.releases : [],
538
+ };
539
+ }
540
+ return claim;
510
541
  }
511
542
  catch (error) {
512
543
  // Invalid and expired both mean "do not enable draft mode", and a
@@ -17,7 +17,8 @@
17
17
  * unpublished for a production key, or is in a model the key cannot read;
18
18
  * - a relation list is `{ items, pageInfo }`, expanded or not;
19
19
  * - media is `{ id, url, alt, type, width, height }`, never the upload's
20
- * own keys.
20
+ * own keys, plus an image's placeholders and its focal point and crop
21
+ * where the project has them (optional, absent otherwise).
21
22
  *
22
23
  * A select the compiler can read exactly, a literal passed as its type
23
24
  * (`list<Articles, typeof select>`), types what it names. One it cannot, a
@@ -50,7 +51,25 @@ export interface RelationItems<E> {
50
51
  next: string | null;
51
52
  };
52
53
  }
53
- /** An image, video or file as `/api/` returns it. */
54
+ /** An editor's focal point: fractions of the image from 0 to 1, `x` from the left and `y` from the top. */
55
+ export interface MediaFocalPoint {
56
+ x: number;
57
+ y: number;
58
+ }
59
+ /** An editor's crop: fractions of the image from 0 to 1. */
60
+ export interface MediaCrop {
61
+ x: number;
62
+ y: number;
63
+ width: number;
64
+ height: number;
65
+ }
66
+ /**
67
+ * An image, video or file as `/api/` returns it.
68
+ *
69
+ * The keys after `height` are optional: they are on every media value of a
70
+ * project that has them, and absent from one that does not. Where they are
71
+ * there, each is null for a video or other file and for an image without one.
72
+ */
54
73
  export interface EntryMedia {
55
74
  id: string;
56
75
  url: string | null;
@@ -58,6 +77,28 @@ export interface EntryMedia {
58
77
  type: string | null;
59
78
  width: number | null;
60
79
  height: number | null;
80
+ /**
81
+ * A tiny blurred copy of the image, 20 pixels on its long side, as a data
82
+ * URL, to show while it loads: next/image's `blurDataURL`
83
+ * (`imagePlaceholder` in `@capacms/sdk/image`). With image placeholders.
84
+ */
85
+ blurDataURL?: string | null;
86
+ /** The image's average colour, `#rrggbb`, to paint its space while it loads. With image placeholders. */
87
+ averageColor?: string | null;
88
+ /** The colour that covers the most of the image, `#rrggbb`: the first of `palette`. With image placeholders. */
89
+ dominantColor?: string | null;
90
+ /** Up to five `#rrggbb` colours, the image's main colour groups, largest first. With image placeholders. */
91
+ palette?: string[] | null;
92
+ /** A BlurHash of the image (https://blurha.sh), for a decoder on the page. With image placeholders. */
93
+ blurhash?: string | null;
94
+ /**
95
+ * The spot an editor marked as the one that matters most. Capa's CDN
96
+ * centres a crop to a shape on it, and `imageUrl` names it in that URL.
97
+ * With focal points and crops.
98
+ */
99
+ focalPoint?: MediaFocalPoint | null;
100
+ /** The part of the image an editor chose to show. A crop to a shape stays inside it. With focal points and crops. */
101
+ crop?: MediaCrop | null;
61
102
  }
62
103
  /**
63
104
  * Levels of entries left to type: the root entry and 4 below it, the API's 5
@@ -202,6 +202,10 @@ export interface GraphQLTransport {
202
202
  version: string;
203
203
  contract?: number;
204
204
  schemaChecksum?: string;
205
+ /** A draft link's token, sent as `Capa-Draft-Link` (`CapaNextConfig.draftLink`). */
206
+ draftLink?: string;
207
+ /** A release preview token, sent as `Capa-Release` (`CapaNextConfig.release`). */
208
+ release?: string;
205
209
  fetchImpl: typeof fetch;
206
210
  }
207
211
  interface Payload {