@capacms/sdk 1.0.0-next.10 → 1.0.0-next.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +37 -0
- package/README.md +122 -0
- package/dist/client.d.ts +84 -4
- package/dist/client.js +23 -5
- package/dist/esm/image/index.d.ts +69 -2
- package/dist/esm/image/index.js +108 -5
- package/dist/esm/image/shared-params.generated.d.ts +126 -2
- package/dist/esm/image/shared-params.generated.js +224 -5
- package/dist/image/index.d.ts +69 -2
- package/dist/image/index.js +109 -4
- package/dist/image/shared-params.generated.d.ts +126 -2
- package/dist/image/shared-params.generated.js +235 -6
- package/dist/index.d.ts +1 -1
- package/dist/next/entry-fields.d.ts +43 -2
- package/dist/next/graphql/tree.js +9 -0
- package/dist/next/index.d.ts +1 -1
- package/dist/webhooks.d.ts +8 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,43 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- Webhook endpoints gain an optional `localeEvents` boolean, on
|
|
6
|
+
`WebhookEndpoint` and in `CreateWebhookEndpointInput` and
|
|
7
|
+
`UpdateWebhookEndpointInput`. True sends each language's saves, publishes
|
|
8
|
+
and unpublishes to the endpoint; they are marked by `data.localeVersionId`.
|
|
9
|
+
The API sends and reads the key only for a project the locales flag serves.
|
|
10
|
+
Additive: every endpoint without it is the one returned before.
|
|
11
|
+
- Image placeholders, focal points and crops, all additive. `EntryMedia`
|
|
12
|
+
gains optional `blurDataURL`, `averageColor`, `dominantColor`, `palette`,
|
|
13
|
+
`blurhash`, `focalPoint` and `crop`, which `/api/` sends only for a project
|
|
14
|
+
that has them; new types `MediaFocalPoint` and `MediaCrop`. `imageUrl` and
|
|
15
|
+
`srcSet` name a media value's focal point and crop as `fp` and `rect` in a
|
|
16
|
+
crop to a shape (`fit: "cover"` with a width and a height), spelled as
|
|
17
|
+
Capa's CDN serves them, so a moved focal point is a new URL. They take
|
|
18
|
+
`focalPoint` and `crop` options too, and export the `ImageFocalPoint` and
|
|
19
|
+
`ImageCrop` types. Every other URL, and every URL of an image without them,
|
|
20
|
+
is the one built before. `imagePlaceholder(image)` gives next/image's
|
|
21
|
+
`placeholder` and `blurDataURL` props, and `placeholderColor(image)` the
|
|
22
|
+
image's average or dominant colour. `toTree` keeps those keys when a
|
|
23
|
+
selection names them. The builders' default media fields are unchanged,
|
|
24
|
+
since a project without them refuses a query that selects them.
|
|
25
|
+
- 1.0.0-next.11. The legacy client returns the related entries `/v2/api`
|
|
26
|
+
sends. `listContent` returns them as `Page.relations`, the map the API sends
|
|
27
|
+
beside the rows: each related entry once, keyed by its id, with its fields
|
|
28
|
+
under `data` (`RelatedEntry`). It is `{}` at depth 0, the default, and when
|
|
29
|
+
an answer has no map (`structure=tree`). `getContentById` and `findOne` take
|
|
30
|
+
`withRelations: true` and return `{ data, id, relations, meta, cacheTags }`
|
|
31
|
+
from the same request, or `null`; without it they return the row as before.
|
|
32
|
+
A `withRelations` known only at run time (a `boolean`, or a `ReadOneOptions`
|
|
33
|
+
value) types the result as either shape. New types: `RelatedEntry`,
|
|
34
|
+
`Relations`, `FieldValue`, `OneWithRelations` and `ReadOneOptions`. `Page`
|
|
35
|
+
and `listContent` take the related entries' type as an optional second type
|
|
36
|
+
argument. Up to next.10 the map was dropped, so a
|
|
37
|
+
site kept the answer's body through `config.fetch` to read it; it can read
|
|
38
|
+
`Page.relations` instead. A `Page` built by hand, in a test, now needs
|
|
39
|
+
`relations: {}`. `/api/` is unchanged and has no such map: a related entry
|
|
40
|
+
comes back nested where the select expanded it, or with `shape: "flat"`
|
|
41
|
+
once in `included`.
|
|
5
42
|
- Live preview shows the text being typed, in 1.0.0-next.10. The overlay's
|
|
6
43
|
`ready` lists `features: ["patch"]`, and it takes the admin's `patch`
|
|
7
44
|
message: the unsaved value of a plain text, number or option field, with the
|
package/README.md
CHANGED
|
@@ -374,6 +374,66 @@ declare const cover: EntryMedia | null;
|
|
|
374
374
|
const candidates = srcSet(cover, [640, 1280, 1920], { aspectRatio: 16 / 9, fit: "cover", format: "webp" });
|
|
375
375
|
```
|
|
376
376
|
|
|
377
|
+
### Focal points and crops
|
|
378
|
+
|
|
379
|
+
Where your project has focal points and crops, an editor can mark the spot
|
|
380
|
+
in an image that matters most, and the part of it to show, in the media
|
|
381
|
+
library. `/api/` then sends them on every image as `focalPoint` (`{ x, y }`)
|
|
382
|
+
and `crop` (`{ x, y, width, height }`), fractions of the image from 0 to 1,
|
|
383
|
+
or `null` where none is set.
|
|
384
|
+
|
|
385
|
+
Capa's CDN uses them for every crop to a shape, `fit: "cover"` with both a
|
|
386
|
+
`width` and a `height`: it cuts the crop first, then centres the shape on the
|
|
387
|
+
focal point as far as the crop allows. Every other request is unchanged.
|
|
388
|
+
`imageUrl` and `srcSet` name them in those URLs as `fp` and `rect`, so a
|
|
389
|
+
moved focal point gives a new URL rather than the old crop from a cache:
|
|
390
|
+
|
|
391
|
+
```ts
|
|
392
|
+
import { imageUrl } from "@capacms/sdk/image";
|
|
393
|
+
|
|
394
|
+
const hero = { id: "f1", url: "https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg", alt: "Terrace", type: "image", width: 2400, height: 1600, focalPoint: { x: 0.25, y: 0.75 }, crop: null };
|
|
395
|
+
|
|
396
|
+
imageUrl(hero, { width: 400, height: 400, fit: "cover", format: "webp" });
|
|
397
|
+
// https://cdn.capacms.com/files/sunns_1790971326210_d54fed020806.jpg?fit=cover&format=webp&fp=0.25,0.75&height=400&width=400
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
The `focalPoint` and `crop` options replace the media value's for one URL,
|
|
401
|
+
and a `crop` option applies to any resize. Both need focal points and crops
|
|
402
|
+
on for the project: elsewhere the CDN ignores `fp` and `rect`. An image
|
|
403
|
+
without them, a URL or a file key gets the same URL as before.
|
|
404
|
+
|
|
405
|
+
### Placeholders
|
|
406
|
+
|
|
407
|
+
Where your project has image placeholders, `/api/` sends each image's
|
|
408
|
+
`blurDataURL` (a blurred copy 20 pixels on its long side, as a data URL),
|
|
409
|
+
`averageColor` and `dominantColor` (`#rrggbb`), `palette` (up to five
|
|
410
|
+
colours, largest first) and `blurhash`, each `null` where there is none.
|
|
411
|
+
`imagePlaceholder(image)` turns one into next/image's props, and
|
|
412
|
+
`placeholderColor(image)` gives a colour to paint the space with while the
|
|
413
|
+
image loads:
|
|
414
|
+
|
|
415
|
+
```tsx
|
|
416
|
+
import Image from "next/image";
|
|
417
|
+
import { imagePlaceholder, placeholderColor } from "@capacms/sdk/image";
|
|
418
|
+
import type { EntryMedia } from "@capacms/sdk/next";
|
|
419
|
+
|
|
420
|
+
export function Card({ image }: { image: EntryMedia }) {
|
|
421
|
+
if (!image.url) return null;
|
|
422
|
+
return (
|
|
423
|
+
<div style={{ backgroundColor: placeholderColor(image) }}>
|
|
424
|
+
<Image src={image.url} alt={image.alt ?? ""} width={image.width ?? 1200} height={image.height ?? 800} {...imagePlaceholder(image)} />
|
|
425
|
+
</div>
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
`imagePlaceholder` gives `{ placeholder: "blur", blurDataURL }` when the
|
|
431
|
+
image has one and `{ placeholder: "empty" }` otherwise, so it can always be
|
|
432
|
+
spread. The placeholders, `focalPoint` and `crop` are optional properties of
|
|
433
|
+
`EntryMedia`, there only for a project that has them. The GraphQL `Media`
|
|
434
|
+
type has them only there too, so select them only there; codegen writes them
|
|
435
|
+
into your types when it does.
|
|
436
|
+
|
|
377
437
|
### Plain HTML
|
|
378
438
|
|
|
379
439
|
Build the attributes wherever the page is rendered, a server template or a
|
|
@@ -482,6 +542,9 @@ default `quality`; `capaImageLoader`, the default export of
|
|
|
482
542
|
`@capacms/sdk/nextjs/image-loader`, sets neither, so each image keeps its own
|
|
483
543
|
format. Both are also exported from `@capacms/sdk/nextjs` for server code.
|
|
484
544
|
|
|
545
|
+
A `src` that `imageUrl` built with `fp` and `rect` keeps them through the
|
|
546
|
+
loader, so its crop to a shape still centres on the focal point.
|
|
547
|
+
|
|
485
548
|
The loader resizes only a full Capa URL, on `cdn.capacms.com` or
|
|
486
549
|
`api.capacms.com` (built on the CDN host, as above). Any other `src` goes
|
|
487
550
|
back unchanged: a file in `public/`, another host, or a bare name such as
|
|
@@ -1999,6 +2062,65 @@ not a UUID rather than spending a request on a certain 400. `search()` reads
|
|
|
1999
2062
|
its hits the same way, so `SearchHit.id` is `string | null` too. `/api/` has
|
|
2000
2063
|
no such collision: an entry's system keys sit beside its `fields`.
|
|
2001
2064
|
|
|
2065
|
+
### Related entries: `Page.relations`
|
|
2066
|
+
|
|
2067
|
+
A read with a `depth` sends its related entries beside the rows, once each,
|
|
2068
|
+
keyed by entry id. Since 1.0.0-next.11 that map is `Page.relations`. On a row,
|
|
2069
|
+
a relation field's `value` is an id, or a list of ids, to look up in it:
|
|
2070
|
+
|
|
2071
|
+
```ts
|
|
2072
|
+
import { createClient, type FieldValue } from "@capacms/sdk";
|
|
2073
|
+
|
|
2074
|
+
const capa = createClient({ baseUrl, apiKey, tenantId });
|
|
2075
|
+
|
|
2076
|
+
type Row = { data: Record<string, FieldValue> };
|
|
2077
|
+
|
|
2078
|
+
const page = await capa.listContent<Row>("home_page", { depth: 2, limit: 1 });
|
|
2079
|
+
const ids = (page.data[0]?.data.sections?.value ?? []) as string[];
|
|
2080
|
+
const sections = ids.map((id) => page.relations[id]).filter((s) => s !== undefined);
|
|
2081
|
+
|
|
2082
|
+
sections[0]?.modelType; // the related entry's model namespace
|
|
2083
|
+
sections[0]?.data.heading?.value; // its fields, each { type, value, sortOrder }
|
|
2084
|
+
```
|
|
2085
|
+
|
|
2086
|
+
- `depth` is how many levels to follow, up to 4. The map holds every level,
|
|
2087
|
+
flat. At depth 0, the default, it is `{}`.
|
|
2088
|
+
- A related entry keeps its fields under `data` only, so its `id` is always
|
|
2089
|
+
the entry's UUID and its `title` the title of the version the key reads,
|
|
2090
|
+
whatever the model's fields are called. The API sends more columns than `RelatedEntry` names, and
|
|
2091
|
+
they come through as sent.
|
|
2092
|
+
- An id with no entry in the map is one the key cannot read: unpublished,
|
|
2093
|
+
for a production key, or deleted.
|
|
2094
|
+
- Type the related entries yourself with a second type argument:
|
|
2095
|
+
`listContent<Row, MyRelation>(...)`.
|
|
2096
|
+
|
|
2097
|
+
The reads of one row take `withRelations: true` and return the row with the
|
|
2098
|
+
map beside it, from the same request. Without it they return the row, as
|
|
2099
|
+
before:
|
|
2100
|
+
|
|
2101
|
+
```ts
|
|
2102
|
+
import { createClient } from "@capacms/sdk";
|
|
2103
|
+
|
|
2104
|
+
const capa = createClient({ baseUrl, apiKey, tenantId });
|
|
2105
|
+
|
|
2106
|
+
const one = await capa.findOne("page", { handle: "about" }, { depth: 2, withRelations: true });
|
|
2107
|
+
if (one) {
|
|
2108
|
+
one.data; // the row findOne returns without withRelations
|
|
2109
|
+
one.id; // its entry id, as Page.ids reads it
|
|
2110
|
+
one.relations; // its related entries, as on a Page
|
|
2111
|
+
}
|
|
2112
|
+
const byId = await capa.getContentById("page", "3f6c1b4e-2a71-4d0e-9c55-8b0a1f2e7d34", { depth: 1, withRelations: true });
|
|
2113
|
+
```
|
|
2114
|
+
|
|
2115
|
+
Both are `null` when there is no such row. A `withRelations` known only at
|
|
2116
|
+
run time, such as a draft-mode flag, types the result as either shape. A site
|
|
2117
|
+
that kept the answer's body through `config.fetch` to read `relations` can
|
|
2118
|
+
read it here instead.
|
|
2119
|
+
|
|
2120
|
+
`/api/` has no such map. A relation the select expands comes back as the
|
|
2121
|
+
related entry, nested where it was selected, and with `shape: "flat"` once in
|
|
2122
|
+
`included`. See [Flat responses](#flat-responses-each-related-entry-once).
|
|
2123
|
+
|
|
2002
2124
|
### Preview is a key, not a flag
|
|
2003
2125
|
|
|
2004
2126
|
Capa shows unpublished content to a key whose environment is not
|
package/dist/client.d.ts
CHANGED
|
@@ -28,7 +28,68 @@ export interface ListOptions {
|
|
|
28
28
|
*/
|
|
29
29
|
where?: Record<string, string | number | boolean>;
|
|
30
30
|
}
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* One field of a `/v2/api` entry as Capa stores it: `{ type, value, sortOrder }`.
|
|
33
|
+
* A relation field's `value` is the related entry's id, or a list of ids.
|
|
34
|
+
*/
|
|
35
|
+
export interface FieldValue<V = unknown> {
|
|
36
|
+
type?: string;
|
|
37
|
+
value: V;
|
|
38
|
+
sortOrder?: number;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One entry of `relations`: a related entry as `/v2/api` sends it.
|
|
43
|
+
*
|
|
44
|
+
* Unlike a row of `data`, it keeps its fields under `data` only, so `id` is
|
|
45
|
+
* always the entry's UUID and `title` the served version's title, whatever the
|
|
46
|
+
* model's fields are called. `modelType` is its model's namespace. The API
|
|
47
|
+
* sends more columns than these (`tenantId`, `tags`, `dataModel`, its
|
|
48
|
+
* versions), and they come through as sent.
|
|
49
|
+
*/
|
|
50
|
+
export interface RelatedEntry<D = Record<string, FieldValue>> {
|
|
51
|
+
id: string;
|
|
52
|
+
modelId: string;
|
|
53
|
+
/** The related entry's model namespace. */
|
|
54
|
+
modelType: string;
|
|
55
|
+
title: string | null;
|
|
56
|
+
data: D;
|
|
57
|
+
createdAt: string;
|
|
58
|
+
updatedAt: string;
|
|
59
|
+
[key: string]: unknown;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A read's related entries by entry id, at every level down to `depth`, each
|
|
63
|
+
* once however many rows name it. `{}` at depth 0, the default. An id a row
|
|
64
|
+
* holds with no entry here is one the key cannot read: unpublished for a
|
|
65
|
+
* production key, or deleted.
|
|
66
|
+
*/
|
|
67
|
+
export type Relations<R = RelatedEntry> = Record<string, R>;
|
|
68
|
+
/**
|
|
69
|
+
* `getContentById` and `findOne` with `withRelations: true`: the row they
|
|
70
|
+
* return without it, and what the same answer carried beside it.
|
|
71
|
+
*/
|
|
72
|
+
export interface OneWithRelations<T, R = RelatedEntry> {
|
|
73
|
+
data: T;
|
|
74
|
+
/** The row's instance id, read as `Page.ids` reads it (`instanceIdOf`). */
|
|
75
|
+
id: string | null;
|
|
76
|
+
relations: Relations<R>;
|
|
77
|
+
meta: Page<T>["meta"];
|
|
78
|
+
cacheTags: string[];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What `getContentById` and `findOne` take. A literal `withRelations: true`
|
|
82
|
+
* types the result as `OneWithRelations`, a literal `false` or none as the row,
|
|
83
|
+
* and a `boolean` (or a value of this type) as either.
|
|
84
|
+
*/
|
|
85
|
+
export interface ReadOneOptions extends Pick<ListOptions, "depth"> {
|
|
86
|
+
/**
|
|
87
|
+
* Return `{ data, id, relations, meta, cacheTags }` in place of the row, so
|
|
88
|
+
* its related entries can be read. Sent nowhere: the request is the same.
|
|
89
|
+
*/
|
|
90
|
+
withRelations?: boolean;
|
|
91
|
+
}
|
|
92
|
+
export interface Page<T, R = RelatedEntry> {
|
|
32
93
|
data: T[];
|
|
33
94
|
/**
|
|
34
95
|
* Instance ids positionally matching `data`, `null` only when the API sent
|
|
@@ -36,6 +97,11 @@ export interface Page<T> {
|
|
|
36
97
|
* which is the model's own field whenever one is named `id`.
|
|
37
98
|
*/
|
|
38
99
|
ids: (string | null)[];
|
|
100
|
+
/**
|
|
101
|
+
* The related entries of `data`, by id: `page.relations[row.data.author.value]`.
|
|
102
|
+
* Read with `depth` of 1 or more; see `Relations`.
|
|
103
|
+
*/
|
|
104
|
+
relations: Relations<R>;
|
|
39
105
|
meta: {
|
|
40
106
|
total?: number;
|
|
41
107
|
totalPages?: number;
|
|
@@ -48,9 +114,23 @@ export interface Page<T> {
|
|
|
48
114
|
cacheTags: string[];
|
|
49
115
|
}
|
|
50
116
|
export interface CapaClient {
|
|
51
|
-
listContent<T = Record<string, unknown
|
|
52
|
-
getContentById<T = Record<string, unknown
|
|
53
|
-
|
|
117
|
+
listContent<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, options?: ListOptions): Promise<Page<T, R>>;
|
|
118
|
+
getContentById<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, id: string, options: ReadOneOptions & {
|
|
119
|
+
withRelations: true;
|
|
120
|
+
}): Promise<OneWithRelations<T, R> | null>;
|
|
121
|
+
getContentById<T = Record<string, unknown>>(namespace: string, id: string, options?: ReadOneOptions & {
|
|
122
|
+
withRelations?: false;
|
|
123
|
+
}): Promise<T | null>;
|
|
124
|
+
/** A `ReadOneOptions` value, or a `withRelations` known only at run time: either shape. */
|
|
125
|
+
getContentById<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, id: string, options?: ReadOneOptions): Promise<T | OneWithRelations<T, R> | null>;
|
|
126
|
+
findOne<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, where: Record<string, string | number | boolean>, options: ReadOneOptions & {
|
|
127
|
+
withRelations: true;
|
|
128
|
+
}): Promise<OneWithRelations<T, R> | null>;
|
|
129
|
+
findOne<T = Record<string, unknown>>(namespace: string, where: Record<string, string | number | boolean>, options?: ReadOneOptions & {
|
|
130
|
+
withRelations?: false;
|
|
131
|
+
}): Promise<T | null>;
|
|
132
|
+
/** A `ReadOneOptions` value, or a `withRelations` known only at run time: either shape. */
|
|
133
|
+
findOne<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, where: Record<string, string | number | boolean>, options?: ReadOneOptions): Promise<T | OneWithRelations<T, R> | null>;
|
|
54
134
|
search(q: string, options?: {
|
|
55
135
|
namespace?: string;
|
|
56
136
|
limit?: number;
|
package/dist/client.js
CHANGED
|
@@ -65,6 +65,14 @@ function contentQuery(options = {}) {
|
|
|
65
65
|
q[k] = v;
|
|
66
66
|
return q;
|
|
67
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* A content answer as a `Page`. A `structure=tree` answer (asked for through
|
|
70
|
+
* `where`) carries no relations map, and gets `{}`.
|
|
71
|
+
*/
|
|
72
|
+
function pageOf(body, cacheTags) {
|
|
73
|
+
const rows = body.data ?? [];
|
|
74
|
+
return { data: rows, ids: rows.map(instanceIdOf), relations: body.relations ?? {}, meta: body.meta ?? {}, cacheTags };
|
|
75
|
+
}
|
|
68
76
|
/**
|
|
69
77
|
* `/v2` answers every `cap_` key "Invalid API key", which reads as a bad key
|
|
70
78
|
* rather than the wrong client, so one is refused here before the tenant id is
|
|
@@ -85,11 +93,20 @@ function createClient(config) {
|
|
|
85
93
|
const resolved = (0, config_1.resolveConfig)(config);
|
|
86
94
|
async function listContent(namespace, options = {}) {
|
|
87
95
|
const { body, cacheTags } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, contentQuery(options));
|
|
88
|
-
|
|
89
|
-
|
|
96
|
+
return pageOf(body, cacheTags);
|
|
97
|
+
}
|
|
98
|
+
/** The first row of a page: alone, or with what the answer carried beside it. */
|
|
99
|
+
function one(page, options) {
|
|
100
|
+
const row = page.data[0];
|
|
101
|
+
if (row === undefined)
|
|
102
|
+
return null;
|
|
103
|
+
if (options.withRelations !== true)
|
|
104
|
+
return row;
|
|
105
|
+
return { data: row, id: page.ids[0] ?? null, relations: page.relations, meta: page.meta, cacheTags: page.cacheTags };
|
|
90
106
|
}
|
|
91
107
|
return {
|
|
92
108
|
listContent,
|
|
109
|
+
// `Promise<any>` here and on findOne: CapaClient's overloads type the result by `withRelations`.
|
|
93
110
|
async getContentById(namespace, id, options = {}) {
|
|
94
111
|
// Fail here rather than spending a request on a guaranteed 400. See
|
|
95
112
|
// instanceIdOf: for a shadowing model, the "id" on a listContent row is
|
|
@@ -100,8 +117,8 @@ function createClient(config) {
|
|
|
100
117
|
`of \`row.id\`: the model "${namespace}" has a field named "id" that overwrites the ` +
|
|
101
118
|
`instance id in that response. See #4628.`);
|
|
102
119
|
}
|
|
103
|
-
const { body } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, { ids: id, depth: options.depth, limit: 1 });
|
|
104
|
-
return (body
|
|
120
|
+
const { body, cacheTags } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, { ids: id, depth: options.depth, limit: 1 });
|
|
121
|
+
return one(pageOf(body, cacheTags), options);
|
|
105
122
|
},
|
|
106
123
|
/**
|
|
107
124
|
* One row matched by field values — `findOne("shopify_page", {handle})`.
|
|
@@ -114,8 +131,9 @@ function createClient(config) {
|
|
|
114
131
|
* the right fix, and belongs in Capa rather than here.
|
|
115
132
|
*/
|
|
116
133
|
async findOne(namespace, where, options = {}) {
|
|
134
|
+
// `withRelations` rides along in the spread; contentQuery sends only the keys it knows.
|
|
117
135
|
const page = await listContent(namespace, { ...options, where, limit: 1 });
|
|
118
|
-
return page
|
|
136
|
+
return one(page, options);
|
|
119
137
|
},
|
|
120
138
|
async search(q, options = {}) {
|
|
121
139
|
const text = String(q ?? "").trim();
|
|
@@ -9,21 +9,33 @@
|
|
|
9
9
|
* from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
|
|
10
10
|
* compiled in from @capa/shared at build time), so the two cannot drift.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* Four rules beside the API's:
|
|
13
13
|
* - Nothing is enlarged. When the image's own width is known (the `/api/`
|
|
14
14
|
* media shape carries it), a request for more pixels than it has is brought
|
|
15
15
|
* down to its size, keeping the requested shape.
|
|
16
16
|
* - `format=auto` is only sent when asked for.
|
|
17
17
|
* - A URL that is not a Capa image comes back unchanged.
|
|
18
|
+
* - A crop to a shape (`fit: "cover"` with a width and a height) of a media
|
|
19
|
+
* value that carries an editor's focal point or crop names them in the URL
|
|
20
|
+
* (`fp`, `rect`), so moving the focal point gives a new URL rather than a
|
|
21
|
+
* copy cached under the old one. A media value without them, and a URL or
|
|
22
|
+
* a key without `fp` or `rect`, builds exactly the URL it always did.
|
|
18
23
|
*
|
|
19
24
|
* A stored URL on `api.capacms.com/files/` (older uploads) names the same file
|
|
20
25
|
* as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
|
|
21
26
|
* where a resized copy is cached at the edge rather than made again by the
|
|
22
27
|
* origin on every request.
|
|
23
28
|
*/
|
|
24
|
-
import { MAX_OUTPUT_EDGE, type ImageFit, type ImageFormat } from "./shared-params.generated.js";
|
|
29
|
+
import { MAX_OUTPUT_EDGE, type CropRect, type FocalPoint, type ImageFit, type ImageFormat } from "./shared-params.generated.js";
|
|
25
30
|
export type { ImageFit, ImageFormat };
|
|
26
31
|
export { MAX_OUTPUT_EDGE };
|
|
32
|
+
/**
|
|
33
|
+
* The spot in an image an editor marked as the one that matters most, as
|
|
34
|
+
* fractions of the image from 0 to 1: `x` from the left, `y` from the top.
|
|
35
|
+
*/
|
|
36
|
+
export type ImageFocalPoint = FocalPoint;
|
|
37
|
+
/** The part of an image an editor chose to show, as fractions of the image from 0 to 1. */
|
|
38
|
+
export type ImageCrop = CropRect;
|
|
27
39
|
/** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
|
|
28
40
|
export declare const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
|
|
29
41
|
/**
|
|
@@ -43,6 +55,14 @@ export interface ImageLike {
|
|
|
43
55
|
height?: number | null;
|
|
44
56
|
/** The file's kind. Anything but `image` (or a missing kind) is returned unchanged. */
|
|
45
57
|
type?: string | null;
|
|
58
|
+
/**
|
|
59
|
+
* The editor's focal point, where `/api/` sends one. A crop to a shape
|
|
60
|
+
* (`fit: "cover"` with a width and a height) centres on it, and its URL
|
|
61
|
+
* names it as `fp`.
|
|
62
|
+
*/
|
|
63
|
+
focalPoint?: ImageFocalPoint | null;
|
|
64
|
+
/** The editor's crop, where `/api/` sends one. A crop to a shape stays inside it, and its URL names it as `rect`. */
|
|
65
|
+
crop?: ImageCrop | null;
|
|
46
66
|
}
|
|
47
67
|
/** A media value, a full CDN URL, or a file key (`sunns_1790971326210_d54fed020806.jpg`). */
|
|
48
68
|
export type ImageSource = string | ImageLike;
|
|
@@ -66,6 +86,14 @@ export interface ImageOptions {
|
|
|
66
86
|
* currently returns JPEG, so use `webp` until that is fixed.
|
|
67
87
|
*/
|
|
68
88
|
format?: ImageFormat;
|
|
89
|
+
/**
|
|
90
|
+
* The focal point for a crop to a shape (`fit: "cover"` with a width and a
|
|
91
|
+
* height), in place of the media value's. Other requests have nothing to
|
|
92
|
+
* centre, so it is left out of their URL.
|
|
93
|
+
*/
|
|
94
|
+
focalPoint?: ImageFocalPoint | null;
|
|
95
|
+
/** A crop, in place of the media value's. It applies to any resize, and on its own crops the image. */
|
|
96
|
+
crop?: ImageCrop | null;
|
|
69
97
|
}
|
|
70
98
|
/** The options `srcSet` takes: each candidate's width comes from its list, and its height from `aspectRatio`. */
|
|
71
99
|
export interface SrcSetOptions {
|
|
@@ -74,6 +102,10 @@ export interface SrcSetOptions {
|
|
|
74
102
|
fit?: ImageFit;
|
|
75
103
|
quality?: number;
|
|
76
104
|
format?: ImageFormat;
|
|
105
|
+
/** As `imageUrl`'s: applies to each candidate cropped to a shape (`aspectRatio` with `fit: "cover"`). */
|
|
106
|
+
focalPoint?: ImageFocalPoint | null;
|
|
107
|
+
/** As `imageUrl`'s: applies to every candidate. */
|
|
108
|
+
crop?: ImageCrop | null;
|
|
77
109
|
}
|
|
78
110
|
/**
|
|
79
111
|
* The URL of a Capa image, resized as `options` say, spelled exactly as Capa's
|
|
@@ -118,3 +150,38 @@ export declare function srcSet(image: ImageSource | null | undefined, widths: re
|
|
|
118
150
|
* ```
|
|
119
151
|
*/
|
|
120
152
|
export declare function sizes(breakpoints: Readonly<Record<number, string>>, fallback?: string): string;
|
|
153
|
+
/**
|
|
154
|
+
* What `/api/` sends of an image's placeholders, where Capa makes them: a
|
|
155
|
+
* tiny blurred copy as a data URL, and its colours.
|
|
156
|
+
*/
|
|
157
|
+
export interface PlaceholderLike {
|
|
158
|
+
blurDataURL?: string | null;
|
|
159
|
+
averageColor?: string | null;
|
|
160
|
+
dominantColor?: string | null;
|
|
161
|
+
}
|
|
162
|
+
/** next/image's `placeholder` and `blurDataURL` props, to spread onto an `<Image>`. */
|
|
163
|
+
export type ImagePlaceholder = {
|
|
164
|
+
placeholder: "blur";
|
|
165
|
+
blurDataURL: string;
|
|
166
|
+
} | {
|
|
167
|
+
placeholder: "empty";
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* next/image's placeholder props for a media value: `placeholder="blur"` with
|
|
171
|
+
* its `blurDataURL` when it has one, and `placeholder="empty"` otherwise, so
|
|
172
|
+
* the result can always be spread:
|
|
173
|
+
*
|
|
174
|
+
* ```tsx
|
|
175
|
+
* <Image src={imageUrl(hero)} alt={hero.alt ?? ""} width={1200} height={800} {...imagePlaceholder(hero)} />
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
export declare function imagePlaceholder(image: PlaceholderLike | null | undefined): ImagePlaceholder;
|
|
179
|
+
/**
|
|
180
|
+
* A colour to paint an image's space with while it loads, as `#rrggbb`: its
|
|
181
|
+
* average colour, else its dominant one, else undefined.
|
|
182
|
+
*
|
|
183
|
+
* ```tsx
|
|
184
|
+
* <div style={{ backgroundColor: placeholderColor(hero) }}>...</div>
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
export declare function placeholderColor(image: PlaceholderLike | null | undefined): string | undefined;
|
package/dist/esm/image/index.js
CHANGED
|
@@ -9,19 +9,24 @@
|
|
|
9
9
|
* from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
|
|
10
10
|
* compiled in from @capa/shared at build time), so the two cannot drift.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* Four rules beside the API's:
|
|
13
13
|
* - Nothing is enlarged. When the image's own width is known (the `/api/`
|
|
14
14
|
* media shape carries it), a request for more pixels than it has is brought
|
|
15
15
|
* down to its size, keeping the requested shape.
|
|
16
16
|
* - `format=auto` is only sent when asked for.
|
|
17
17
|
* - A URL that is not a Capa image comes back unchanged.
|
|
18
|
+
* - A crop to a shape (`fit: "cover"` with a width and a height) of a media
|
|
19
|
+
* value that carries an editor's focal point or crop names them in the URL
|
|
20
|
+
* (`fp`, `rect`), so moving the focal point gives a new URL rather than a
|
|
21
|
+
* copy cached under the old one. A media value without them, and a URL or
|
|
22
|
+
* a key without `fp` or `rect`, builds exactly the URL it always did.
|
|
18
23
|
*
|
|
19
24
|
* A stored URL on `api.capacms.com/files/` (older uploads) names the same file
|
|
20
25
|
* as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
|
|
21
26
|
* where a resized copy is cached at the edge rather than made again by the
|
|
22
27
|
* origin on every request.
|
|
23
28
|
*/
|
|
24
|
-
import { canonicalQuery, LEGACY_PARAMS, MAX_OUTPUT_EDGE, NEW_PARAMS, parseImageParams, } from "./shared-params.generated.js";
|
|
29
|
+
import { canonicalQuery, FOCAL_PARAMS, LEGACY_PARAMS, MAX_OUTPUT_EDGE, NEW_PARAMS, parseFocalParams, parseImageParams, readCrop, readFocalPoint, } from "./shared-params.generated.js";
|
|
25
30
|
export { MAX_OUTPUT_EDGE };
|
|
26
31
|
/** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
|
|
27
32
|
export const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
|
|
@@ -63,20 +68,31 @@ function positive(value) {
|
|
|
63
68
|
function hasScheme(text) {
|
|
64
69
|
return /^[a-z][a-z0-9+.-]*:/i.test(text);
|
|
65
70
|
}
|
|
71
|
+
/** What a media value says about itself: its size, and an editor's focal point and crop when they are well formed. */
|
|
72
|
+
function known(image) {
|
|
73
|
+
const out = { intrinsicWidth: positive(image?.width), intrinsicHeight: positive(image?.height) };
|
|
74
|
+
const focalPoint = image ? readFocalPoint(image.focalPoint) : null;
|
|
75
|
+
const crop = image ? readCrop(image.crop) : null;
|
|
76
|
+
if (focalPoint)
|
|
77
|
+
out.focalPoint = focalPoint;
|
|
78
|
+
if (crop)
|
|
79
|
+
out.crop = crop;
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
66
82
|
/** A string or `url` as a Capa image, or why not. */
|
|
67
83
|
function resolveUrl(text, image) {
|
|
68
84
|
if (hasScheme(text)) {
|
|
69
85
|
const url = capaFileUrl(text);
|
|
70
86
|
if (url === null)
|
|
71
87
|
return { unchanged: text };
|
|
72
|
-
return { target: { url,
|
|
88
|
+
return { target: { url, ...known(image) } };
|
|
73
89
|
}
|
|
74
90
|
// A path (`/logo.png`, `//host/x`) is the site's own or another host's.
|
|
75
91
|
if (text === "" || text.startsWith("/"))
|
|
76
92
|
return { unchanged: text };
|
|
77
93
|
// A file key, which may hold folders: each segment is encoded on its own.
|
|
78
94
|
const path = text.split("/").map(encodeURIComponent).join("/");
|
|
79
|
-
return { target: { url: new URL(`${CAPA_CDN_ORIGIN}${FILES_PATH}${path}`),
|
|
95
|
+
return { target: { url: new URL(`${CAPA_CDN_ORIGIN}${FILES_PATH}${path}`), ...known(image) } };
|
|
80
96
|
}
|
|
81
97
|
function resolve(image) {
|
|
82
98
|
if (image === null || image === undefined)
|
|
@@ -162,10 +178,65 @@ function build(fn, target, options) {
|
|
|
162
178
|
const parsed = parseImageParams(query);
|
|
163
179
|
if (!parsed.ok)
|
|
164
180
|
fail(fn, parsed.rejection.error);
|
|
165
|
-
const
|
|
181
|
+
const focal = focalParams(fn, target, options, parsed.params, search);
|
|
182
|
+
// With no focal point or crop to name, the URL is spelled as it always was:
|
|
183
|
+
// an `fp` or `rect` already in it is an unknown key, kept as it is.
|
|
184
|
+
const canonical = focal === null ? canonicalQuery(search, parsed.params) : canonicalQuery(search, focal, { focal: true });
|
|
166
185
|
const href = `${url.origin}${url.pathname}${canonical ? `?${canonical}` : ""}${url.hash}`;
|
|
167
186
|
return { href, width: parsed.params.width };
|
|
168
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* The parameters with the focal point and crop this URL names, or null when
|
|
190
|
+
* it names none of its own making.
|
|
191
|
+
*
|
|
192
|
+
* Capa's CDN crops a request to a shape (`fit=cover` with a width and a
|
|
193
|
+
* height) around the focal point and inside the crop an editor set on the
|
|
194
|
+
* file, whether the URL names them or not. Named in the URL, a moved focal
|
|
195
|
+
* point is a new URL, so no browser or edge keeps the old crop under it. A
|
|
196
|
+
* crop given as an option applies to any resize, as the CDN applies a `rect`
|
|
197
|
+
* it is sent. Options win over the media value, which wins over an `fp` or
|
|
198
|
+
* `rect` the URL already had. With none of them, null: the URL is spelled as
|
|
199
|
+
* it always was.
|
|
200
|
+
*/
|
|
201
|
+
function focalParams(fn, target, options, params, search) {
|
|
202
|
+
let askedFocal;
|
|
203
|
+
if (options.focalPoint !== undefined && options.focalPoint !== null) {
|
|
204
|
+
const read = readFocalPoint(options.focalPoint);
|
|
205
|
+
if (read === null)
|
|
206
|
+
fail(fn, "`focalPoint` must be { x, y }, numbers from 0 to 1");
|
|
207
|
+
askedFocal = read;
|
|
208
|
+
}
|
|
209
|
+
let askedCrop;
|
|
210
|
+
if (options.crop !== undefined && options.crop !== null) {
|
|
211
|
+
const read = readCrop(options.crop);
|
|
212
|
+
if (read === null)
|
|
213
|
+
fail(fn, "`crop` must be { x, y, width, height }, numbers from 0 to 1 with a width and a height above 0, inside the image");
|
|
214
|
+
askedCrop = read;
|
|
215
|
+
}
|
|
216
|
+
const cover = params.fit === "cover" && params.width !== undefined && params.height !== undefined && params.blur === undefined;
|
|
217
|
+
const focalPoint = cover ? askedFocal ?? target.focalPoint : undefined;
|
|
218
|
+
const rect = askedCrop ?? (cover ? target.crop : undefined);
|
|
219
|
+
// What the URL already said (a URL this function built, handed back to it,
|
|
220
|
+
// as next/image hands its loader a `src`), kept where nothing here replaces
|
|
221
|
+
// it, and spelled as the CDN spells it. One the CDN would refuse stays an
|
|
222
|
+
// unknown key, as it is, unless something here replaces it.
|
|
223
|
+
const own = {};
|
|
224
|
+
for (const [key, value] of new URLSearchParams(search))
|
|
225
|
+
if (FOCAL_PARAMS.has(key) && !(key in own))
|
|
226
|
+
own[key] = value;
|
|
227
|
+
const ownFocal = parseFocalParams(own);
|
|
228
|
+
const kept = ownFocal.ok ? ownFocal : {};
|
|
229
|
+
const fp = focalPoint ?? kept.focalPoint;
|
|
230
|
+
const r = rect ?? kept.rect;
|
|
231
|
+
if (fp === undefined && r === undefined)
|
|
232
|
+
return null;
|
|
233
|
+
const out = { ...params };
|
|
234
|
+
if (fp !== undefined)
|
|
235
|
+
out.focalPoint = fp;
|
|
236
|
+
if (r !== undefined)
|
|
237
|
+
out.rect = r;
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
169
240
|
export function imageUrl(image, options = {}) {
|
|
170
241
|
const resolved = resolve(image);
|
|
171
242
|
if (resolved === null)
|
|
@@ -216,6 +287,8 @@ export function srcSet(image, widths, options = {}) {
|
|
|
216
287
|
fit: options.fit,
|
|
217
288
|
quality: options.quality,
|
|
218
289
|
format: options.format,
|
|
290
|
+
focalPoint: options.focalPoint,
|
|
291
|
+
crop: options.crop,
|
|
219
292
|
});
|
|
220
293
|
if (seen.has(href))
|
|
221
294
|
continue;
|
|
@@ -248,3 +321,33 @@ export function sizes(breakpoints, fallback = "100vw") {
|
|
|
248
321
|
rules.sort(([a], [b]) => b - a);
|
|
249
322
|
return [...rules.map(([px, size]) => `(min-width: ${px}px) ${size}`), fallback.trim()].join(", ");
|
|
250
323
|
}
|
|
324
|
+
const BLUR_DATA_URL = /^data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}$/i;
|
|
325
|
+
const HEX_COLOUR = /^#[0-9a-f]{6}$/i;
|
|
326
|
+
/**
|
|
327
|
+
* next/image's placeholder props for a media value: `placeholder="blur"` with
|
|
328
|
+
* its `blurDataURL` when it has one, and `placeholder="empty"` otherwise, so
|
|
329
|
+
* the result can always be spread:
|
|
330
|
+
*
|
|
331
|
+
* ```tsx
|
|
332
|
+
* <Image src={imageUrl(hero)} alt={hero.alt ?? ""} width={1200} height={800} {...imagePlaceholder(hero)} />
|
|
333
|
+
* ```
|
|
334
|
+
*/
|
|
335
|
+
export function imagePlaceholder(image) {
|
|
336
|
+
const blur = image?.blurDataURL;
|
|
337
|
+
return typeof blur === "string" && BLUR_DATA_URL.test(blur) ? { placeholder: "blur", blurDataURL: blur } : { placeholder: "empty" };
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* A colour to paint an image's space with while it loads, as `#rrggbb`: its
|
|
341
|
+
* average colour, else its dominant one, else undefined.
|
|
342
|
+
*
|
|
343
|
+
* ```tsx
|
|
344
|
+
* <div style={{ backgroundColor: placeholderColor(hero) }}>...</div>
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
347
|
+
export function placeholderColor(image) {
|
|
348
|
+
for (const colour of [image?.averageColor, image?.dominantColor]) {
|
|
349
|
+
if (typeof colour === "string" && HEX_COLOUR.test(colour))
|
|
350
|
+
return colour.toLowerCase();
|
|
351
|
+
}
|
|
352
|
+
return undefined;
|
|
353
|
+
}
|