@kanorio/sdk 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/http.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * and reads the Deprecation and Sunset headers (RFC 9745, RFC 8594). No business logic.
4
4
  */
5
5
  import { type ServerKeyOptions } from "./server-key.js";
6
- export declare const KANORIO_SDK_VERSION = "1.2.0";
6
+ export declare const KANORIO_SDK_VERSION = "1.4.0";
7
7
  export declare const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
8
8
  export interface ErrorEnvelope {
9
9
  error: {
@@ -29,7 +29,7 @@ export declare class KanorioApiError extends Error {
29
29
  }
30
30
  /**
31
31
  * The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
32
- * On a server this means the write needs a server key; `message` says exactly what to do.
32
+ * API requests are not normally challenged; `message` says what to check (on a server, sending a server key avoids it).
33
33
  */
34
34
  export declare class KanorioEdgeChallengeError extends KanorioApiError {
35
35
  constructor(message: string);
package/dist/http.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * and reads the Deprecation and Sunset headers (RFC 9745, RFC 8594). No business logic.
4
4
  */
5
5
  import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
6
- export const KANORIO_SDK_VERSION = "1.2.0";
6
+ export const KANORIO_SDK_VERSION = "1.4.0";
7
7
  export const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
8
8
  export function isErrorEnvelope(value) {
9
9
  if (typeof value !== "object" || value === null)
@@ -36,7 +36,7 @@ export class KanorioApiError extends Error {
36
36
  }
37
37
  /**
38
38
  * The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
39
- * On a server this means the write needs a server key; `message` says exactly what to do.
39
+ * API requests are not normally challenged; `message` says what to check (on a server, sending a server key avoids it).
40
40
  */
41
41
  export class KanorioEdgeChallengeError extends KanorioApiError {
42
42
  constructor(message) {
package/dist/image.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Image helpers for a front end you host yourself: turn a field value into an image, and an image URL into the size you need.
3
3
  *
4
- * Kanorio serves images from `img.kanorio.com`. The URL of an image in the `assets` map ends in `/public` (the original).
5
- * Replace that last segment with a size (`w=800,fit=scale-down`) and the edge resizes the image; any width works.
6
- * `url` and `srcSet` do that replacement for you. They return other URLs (an external image, a file) unchanged.
4
+ * Kanorio serves images from `img.kanorio.com`. The URL of an image in the `assets` map delivers the original size (its `width` and `height`).
5
+ * Replace the last path segment with a size (`w=800,fit=scale-down`) and the edge resizes the image; any width works.
6
+ * `url` and `srcSet` do that replacement for you and keep the author's crop: a URL that is already cropped or padded to a shape
7
+ * (such as `fieldData.share_image`) stays that shape at the new width. They return other URLs (an external image, a file) unchanged.
8
+ * Give `url` the image from `resolve` rather than its URL and a crop keeps the focal point the owner set in the media library.
7
9
  * See "Filtering, fields and expand" in the developer documentation for the asset fields.
8
10
  */
9
11
  /** One entry of the `assets` map in a Delivery API response (the fields these helpers read) */
@@ -12,10 +14,7 @@ export interface ImageAssetLike {
12
14
  width?: number | null;
13
15
  height?: number | null;
14
16
  alt?: string | null;
15
- focus?: {
16
- x: number;
17
- y: number;
18
- } | null;
17
+ focus?: ImageFocus | null;
19
18
  placeholder?: string | null;
20
19
  edgeColor?: string | null;
21
20
  }
@@ -26,25 +25,51 @@ export interface ResolvedImage {
26
25
  /** Pixel size of the original; null when unknown (an external URL, an SVG) */
27
26
  width: number | null;
28
27
  height: number | null;
29
- /** Alt text written where the image is used, otherwise the asset's own; null when there is none */
28
+ /** The `alt` you passed (the item's `imageAlt` for this image), otherwise the asset's; null when there is none */
30
29
  alt: string | null;
31
- /** Focal point as 0 to 1 coordinates, for `object-position` when you crop; null when unset or centered */
32
- focus: {
33
- x: number;
34
- y: number;
35
- } | null;
30
+ /**
31
+ * Focal point as 0 to 1 coordinates; null when unset or centered. Pass the resolved image to `url` and a crop keeps it in frame;
32
+ * when CSS crops (`object-fit: cover`), use it for `object-position`
33
+ */
34
+ focus: ImageFocus | null;
36
35
  /** Tiny blurred preview as a data URL, for a blur-up `<img>` or Next.js `blurDataURL`; null when there is none */
37
36
  placeholder: string | null;
38
37
  /** The solid color shared by all four edges, for the background behind `object-fit: contain`; null when there is none */
39
38
  edgeColor: string | null;
40
39
  }
41
40
  export type ImageFit = "scale-down" | "contain" | "cover" | "crop" | "pad";
41
+ /** A focal point as 0 to 1 coordinates on the original image: `x` from the left edge, `y` from the top */
42
+ export interface ImageFocus {
43
+ x: number;
44
+ y: number;
45
+ }
46
+ /**
47
+ * The image `url` and `srcSet` work on: an image URL from the API, or an image from `resolveImage` (or an `assets` entry),
48
+ * whose `focus` is then kept in frame when the URL crops
49
+ */
50
+ export type ImageSource = string | {
51
+ url: string;
52
+ focus?: ImageFocus | null;
53
+ };
42
54
  export interface ImageUrlOptions {
43
55
  /** Output width in pixels */
44
56
  width: number;
45
57
  /** Output height in pixels. With a height, `fit` defaults to `cover` (crop to fill); without one, to `scale-down` (never enlarge) */
46
58
  height?: number;
47
59
  fit?: ImageFit;
60
+ /**
61
+ * The point to keep in frame when the image is cropped (a `height` with fit `cover` or `crop`), as 0 to 1 coordinates.
62
+ * Defaults to the `focus` of `src` when you pass a resolved image; `null` crops around the center. Not used for a URL that is
63
+ * already framed (one with a crop or a focal point of its own, such as `share_image`) or when nothing is cropped.
64
+ */
65
+ focus?: ImageFocus | null;
66
+ }
67
+ export interface ResolveImageOptions {
68
+ /**
69
+ * Alt text written for this image where the item uses it: `item.imageAlt[fieldId]?.[assetId]`.
70
+ * It wins over the asset's alt from the `assets` map; leave it out, or pass null or an empty string, to use the asset's.
71
+ */
72
+ alt?: string | null;
48
73
  }
49
74
  export interface ImageSrcSetOptions {
50
75
  /** Widths to offer, in pixels. Default: 400, 800, 1200, 1600 */
@@ -56,19 +81,24 @@ export declare const DEFAULT_IMAGE_WIDTHS: readonly number[];
56
81
  export declare function isResizableImageUrl(src: string | null | undefined): src is string;
57
82
  /**
58
83
  * Resolve an image field value: an asset id is looked up in `assets`, a full URL is returned as is.
84
+ * Pass the item's `imageAlt` for this image as `alt` so the alt written where the item uses it wins over the asset's default:
85
+ * `resolveImage(item.fieldData.cover, assets, { alt: item.imageAlt.cover?.[item.fieldData.cover] })`.
59
86
  * Returns `undefined` for an empty value and for an asset id that is not in the map (the file was removed).
60
87
  */
61
- export declare function resolveImage(value: string | null | undefined, assets: ImageAssetMapLike | null | undefined): ResolvedImage | undefined;
88
+ export declare function resolveImage(value: string | null | undefined, assets: ImageAssetMapLike | null | undefined, options?: ResolveImageOptions): ResolvedImage | undefined;
62
89
  /**
63
- * The URL of an image at a given size. `src` is an image URL from the API (`assets[id].url`, or `resolveImage(...).url`).
64
- * A URL Kanorio cannot resize is returned unchanged, so it is safe to call on any image URL.
90
+ * The URL of an image at a given size. `src` is an image URL from the API (`assets[id].url`, `share_image.url`), or the image
91
+ * `resolveImage` returns: then a crop keeps its focal point in frame (`options.focus` overrides it).
92
+ * The crop in `src` is kept (the area the author framed, the focal point, the padding color); a cropped or padded `src` keeps its shape
93
+ * when you give only a width. A URL Kanorio cannot resize is returned unchanged, so it is safe to call on any image URL.
65
94
  */
66
- export declare function imageUrl(src: string, options: ImageUrlOptions): string;
95
+ export declare function imageUrl(src: ImageSource, options: ImageUrlOptions): string;
67
96
  /**
68
97
  * A `srcset` value offering the image at several widths (never enlarged), for `<img srcset>` together with `sizes`.
98
+ * `src` is an image URL or a resolved image, as for `imageUrl`.
69
99
  * Returns `undefined` for a URL Kanorio cannot resize: leave `srcset` off and use `src` alone.
70
100
  */
71
- export declare function imageSrcSet(src: string, options?: ImageSrcSetOptions): string | undefined;
101
+ export declare function imageSrcSet(src: ImageSource, options?: ImageSrcSetOptions): string | undefined;
72
102
  export declare const image: {
73
103
  readonly resolve: typeof resolveImage;
74
104
  readonly url: typeof imageUrl;
package/dist/image.js CHANGED
@@ -1,9 +1,11 @@
1
1
  /**
2
2
  * Image helpers for a front end you host yourself: turn a field value into an image, and an image URL into the size you need.
3
3
  *
4
- * Kanorio serves images from `img.kanorio.com`. The URL of an image in the `assets` map ends in `/public` (the original).
5
- * Replace that last segment with a size (`w=800,fit=scale-down`) and the edge resizes the image; any width works.
6
- * `url` and `srcSet` do that replacement for you. They return other URLs (an external image, a file) unchanged.
4
+ * Kanorio serves images from `img.kanorio.com`. The URL of an image in the `assets` map delivers the original size (its `width` and `height`).
5
+ * Replace the last path segment with a size (`w=800,fit=scale-down`) and the edge resizes the image; any width works.
6
+ * `url` and `srcSet` do that replacement for you and keep the author's crop: a URL that is already cropped or padded to a shape
7
+ * (such as `fieldData.share_image`) stays that shape at the new width. They return other URLs (an external image, a file) unchanged.
8
+ * Give `url` the image from `resolve` rather than its URL and a crop keeps the focal point the owner set in the media library.
7
9
  * See "Filtering, fields and expand" in the developer documentation for the asset fields.
8
10
  */
9
11
  /** Widths `srcSet` offers by default: phones up to a desktop article column on a high-density screen */
@@ -13,7 +15,21 @@ const ABSOLUTE_URL = /^https?:\/\//i;
13
15
  * A Kanorio image URL, split before its last path segment (the variant: `public`, or a size such as `w=800,fit=scale-down`).
14
16
  * Both hosts Kanorio has served images from are recognized.
15
17
  */
16
- const KANORIO_IMAGE_URL = /^(https:\/\/(?:[a-z0-9-]+\.kanorio\.com\/cdn-cgi\/imagedelivery|imagedelivery\.net)\/[^/?#]+\/[^/?#]+)\/[^/?#]+$/i;
18
+ const KANORIO_IMAGE_URL = /^(https:\/\/(?:[a-z0-9-]+\.kanorio\.com\/cdn-cgi\/imagedelivery|imagedelivery\.net)\/[^/?#]+\/[^/?#]+)\/([^/?#]+)$/i;
19
+ /** Fits that produce an exact output shape: a URL with one of them (and `w` and `h`) is a cropped or padded image */
20
+ const FIXED_SHAPE_FITS = new Set(["crop", "cover", "pad"]);
21
+ /** The options in the last path segment (`trim=0;120;0;80,w=1200,h=630,fit=crop`); empty for a named variant such as `public` */
22
+ function variantOptions(variant) {
23
+ const options = new Map();
24
+ if (!variant.includes("="))
25
+ return options;
26
+ for (const part of variant.split(",")) {
27
+ const at = part.indexOf("=");
28
+ if (at > 0)
29
+ options.set(part.slice(0, at), part.slice(at + 1));
30
+ }
31
+ return options;
32
+ }
17
33
  /** True when the URL is an image Kanorio can resize (not an external URL, not an SVG or a file) */
18
34
  export function isResizableImageUrl(src) {
19
35
  return typeof src === "string" && KANORIO_IMAGE_URL.test(src.trim());
@@ -23,14 +39,17 @@ function positiveInt(value) {
23
39
  }
24
40
  /**
25
41
  * Resolve an image field value: an asset id is looked up in `assets`, a full URL is returned as is.
42
+ * Pass the item's `imageAlt` for this image as `alt` so the alt written where the item uses it wins over the asset's default:
43
+ * `resolveImage(item.fieldData.cover, assets, { alt: item.imageAlt.cover?.[item.fieldData.cover] })`.
26
44
  * Returns `undefined` for an empty value and for an asset id that is not in the map (the file was removed).
27
45
  */
28
- export function resolveImage(value, assets) {
46
+ export function resolveImage(value, assets, options = {}) {
29
47
  const trimmed = typeof value === "string" ? value.trim() : "";
30
48
  if (!trimmed)
31
49
  return undefined;
50
+ const writtenAlt = typeof options.alt === "string" && options.alt.trim() ? options.alt.trim() : null;
32
51
  if (ABSOLUTE_URL.test(trimmed)) {
33
- return { url: trimmed, width: null, height: null, alt: null, focus: null, placeholder: null, edgeColor: null };
52
+ return { url: trimmed, width: null, height: null, alt: writtenAlt, focus: null, placeholder: null, edgeColor: null };
34
53
  }
35
54
  const asset = assets?.[trimmed];
36
55
  if (!asset?.url)
@@ -39,31 +58,70 @@ export function resolveImage(value, assets) {
39
58
  url: asset.url,
40
59
  width: asset.width ?? null,
41
60
  height: asset.height ?? null,
42
- alt: asset.alt ?? null,
61
+ alt: writtenAlt ?? asset.alt ?? null,
43
62
  focus: asset.focus ?? null,
44
63
  placeholder: asset.placeholder ?? null,
45
64
  edgeColor: asset.edgeColor ?? null,
46
65
  };
47
66
  }
67
+ /** `x`×`y` for the `gravity` option, or null for a point that is not usable or is the center (where a crop goes anyway) */
68
+ function gravityOf(focus) {
69
+ if (!focus || !Number.isFinite(focus.x) || !Number.isFinite(focus.y))
70
+ return null;
71
+ const coordinate = (value) => Math.round(Math.min(1, Math.max(0, value)) * 1000) / 1000;
72
+ const x = coordinate(focus.x);
73
+ const y = coordinate(focus.y);
74
+ return x === 0.5 && y === 0.5 ? null : `${x}x${y}`;
75
+ }
48
76
  /**
49
- * The URL of an image at a given size. `src` is an image URL from the API (`assets[id].url`, or `resolveImage(...).url`).
50
- * A URL Kanorio cannot resize is returned unchanged, so it is safe to call on any image URL.
77
+ * The URL of an image at a given size. `src` is an image URL from the API (`assets[id].url`, `share_image.url`), or the image
78
+ * `resolveImage` returns: then a crop keeps its focal point in frame (`options.focus` overrides it).
79
+ * The crop in `src` is kept (the area the author framed, the focal point, the padding color); a cropped or padded `src` keeps its shape
80
+ * when you give only a width. A URL Kanorio cannot resize is returned unchanged, so it is safe to call on any image URL.
51
81
  */
52
82
  export function imageUrl(src, options) {
53
- const match = KANORIO_IMAGE_URL.exec(src.trim());
83
+ const url = typeof src === "string" ? src : src.url;
84
+ const match = KANORIO_IMAGE_URL.exec(url.trim());
54
85
  const width = positiveInt(options.width);
55
- if (!match || !width)
56
- return src;
57
- const height = positiveInt(options.height);
58
- const fit = options.fit ?? (height ? "cover" : "scale-down");
59
- return `${match[1]}/w=${width}${height ? `,h=${height}` : ""},fit=${fit}`;
86
+ if (!match?.[1] || !width)
87
+ return url;
88
+ const current = variantOptions(match[2] ?? "");
89
+ let height = positiveInt(options.height);
90
+ let fit = options.fit;
91
+ const currentFit = current.get("fit") ?? "";
92
+ const currentWidth = Number(current.get("w"));
93
+ const currentHeight = Number(current.get("h"));
94
+ const fixedShape = FIXED_SHAPE_FITS.has(currentFit) && currentWidth > 0 && currentHeight > 0;
95
+ if (!height && !fit && fixedShape) {
96
+ height = Math.max(1, Math.round((width * currentHeight) / currentWidth));
97
+ fit = currentFit;
98
+ }
99
+ fit ??= height ? "cover" : "scale-down";
100
+ const trim = current.get("trim");
101
+ // A framed URL (cropped or padded to a shape, cut to an area, or carrying a focal point) keeps the crop it has:
102
+ // the owner's focus is a point on the original, and a centered crop the author framed would move toward it
103
+ const framed = fixedShape || Boolean(trim) || current.has("gravity");
104
+ const focus = options.focus !== undefined ? options.focus : typeof src === "string" ? null : (src.focus ?? null);
105
+ const crops = Boolean(height) && (fit === "cover" || fit === "crop");
106
+ const gravity = current.get("gravity") ?? (crops && !framed ? gravityOf(focus) : null);
107
+ const background = current.get("background");
108
+ const parts = [
109
+ ...(trim ? [`trim=${trim}`] : []),
110
+ `w=${width}`,
111
+ ...(height ? [`h=${height}`] : []),
112
+ `fit=${fit}`,
113
+ ...(gravity ? [`gravity=${gravity}`] : []),
114
+ ...(background ? [`background=${background}`] : []),
115
+ ];
116
+ return `${match[1]}/${parts.join(",")}`;
60
117
  }
61
118
  /**
62
119
  * A `srcset` value offering the image at several widths (never enlarged), for `<img srcset>` together with `sizes`.
120
+ * `src` is an image URL or a resolved image, as for `imageUrl`.
63
121
  * Returns `undefined` for a URL Kanorio cannot resize: leave `srcset` off and use `src` alone.
64
122
  */
65
123
  export function imageSrcSet(src, options = {}) {
66
- if (!isResizableImageUrl(src))
124
+ if (!isResizableImageUrl(typeof src === "string" ? src : src.url))
67
125
  return undefined;
68
126
  const widths = [...new Set((options.widths ?? DEFAULT_IMAGE_WIDTHS).map((w) => positiveInt(w)).filter((w) => w !== null))].sort((a, b) => a - b);
69
127
  if (widths.length === 0)
package/dist/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, type DeprecationNotice, type HttpClientOptions, type HttpClient, } from "./http.js";
2
2
  export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, type ServerKeyOptions, type VisitorIpSource, type VisitorIpOptions, } from "./server-key.js";
3
3
  export type { TypedClient, TypedRequest, SuccessResponseOf } from "./typed.js";
4
- export { paginate, listAll, type ListPage } from "./paginate.js";
4
+ export { paginate, paginatePages, listAll, listAllWithAssets, type ListPage, type ListPageWithAssets, type ListWithAssets, } from "./paginate.js";
5
5
  export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, type ManagementClient, type ManagementClientOptions, type ManagementPaths, } from "./management.js";
6
6
  export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, type DeliveryClient, type DeliveryClientOptions, type DeliveryPaths, } from "./delivery.js";
7
7
  export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, type CustomerClient, type CustomerClientOptions, type CustomerContentClientLike, type CustomerPaths, type CustomerTokenSource, } from "./customer.js";
8
8
  export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, type CompleteHostedLoginOptions, type HostedLoginGrant, type HostedLoginUrlParams, type StartHostedLoginOptions, } from "./customer-oauth.js";
9
- export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, seoMetadata, shareImageOf, type ItemSeoFields, type PageSeoFields, type SeoItemInput, type SeoPageInput, type SeoInput, type SeoMetadataOptions, type SeoMetadata, type ShareImage, type ListingKey, type ListingState, type SeoRewriteFramework, type NextSeoRewriteRule, type SeoRewritesOptions, type DeliveryJsonLdResult, type SitemapEntry, type SitemapEntriesResult, type SeoHelpers, } from "./seo.js";
10
- export { image, resolveImage, imageUrl, imageSrcSet, isResizableImageUrl, DEFAULT_IMAGE_WIDTHS, type ImageAssetLike, type ImageAssetMapLike, type ResolvedImage, type ImageFit, type ImageUrlOptions, type ImageSrcSetOptions, } from "./image.js";
9
+ export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, seoMetadata, shareImageOf, type ItemSeoFields, type PageSeoFields, type SeoItemInput, type SeoPageInput, type SeoInput, type SeoMetadataOptions, type SeoMetadata, type ShareImage, type ShareImageSource, type ListingKey, type ListingState, type SeoRewriteFramework, type NextSeoRewriteRule, type SeoRewritesOptions, type DeliveryJsonLdResult, type SitemapEntry, type SitemapEntriesResult, type SeoHelpers, } from "./seo.js";
10
+ export { image, resolveImage, imageUrl, imageSrcSet, isResizableImageUrl, DEFAULT_IMAGE_WIDTHS, type ImageAssetLike, type ImageAssetMapLike, type ResolvedImage, type ImageFit, type ImageFocus, type ImageSource, type ImageUrlOptions, type ImageSrcSetOptions, type ResolveImageOptions, } from "./image.js";
11
11
  export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, type TranslationCacheScope, } from "./shared/api/delivery/cache-tags.js";
12
12
  export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, type BuildAlternatesOptions, type PageAlternates, type HreflangLink, type SiteLocaleMeta, type LocaleRoute, type RequestLocaleResult, type SiteAlternates, } from "./locales.js";
13
13
  export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, type VerifyWebhookSignatureOptions, type ParsedWebhookSignature, type WebhookEnvelope, type RevalidateHandlerOptions, } from "./revalidate.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, } from "./http.js";
2
2
  export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, } from "./server-key.js";
3
- export { paginate, listAll } from "./paginate.js";
3
+ export { paginate, paginatePages, listAll, listAllWithAssets, } from "./paginate.js";
4
4
  export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, } from "./management.js";
5
5
  export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, } from "./delivery.js";
6
6
  export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, } from "./customer.js";
package/dist/next.d.ts CHANGED
@@ -34,6 +34,8 @@ export interface NextMetadataLike {
34
34
  images?: Array<{
35
35
  url: string;
36
36
  alt?: string;
37
+ width?: number;
38
+ height?: number;
37
39
  }>;
38
40
  };
39
41
  twitter: {
@@ -58,8 +60,12 @@ export declare function kanorioImageLoader({ src, width }: {
58
60
  width: number;
59
61
  quality?: number;
60
62
  }): string;
61
- /** `images.remotePatterns` entries for Kanorio's image host, for `next.config` when you use `next/image` without the loader */
62
- export declare const kanorioRemotePatterns: ReadonlyArray<{
63
+ /**
64
+ * `images.remotePatterns` entries for Kanorio's image host, for `next.config` when you use `next/image` without the loader:
65
+ * `images: { remotePatterns: kanorioRemotePatterns }`. It is a plain array because Next.js types `remotePatterns` as one;
66
+ * to add hosts of your own, spread it into a new array (`[...kanorioRemotePatterns, ...yours]`) rather than pushing to it.
67
+ */
68
+ export declare const kanorioRemotePatterns: Array<{
63
69
  protocol: "https";
64
70
  hostname: string;
65
71
  pathname: string;
package/dist/next.js CHANGED
@@ -34,7 +34,17 @@ export function toNextMetadata(metadata) {
34
34
  ...(openGraph.title ? { title: openGraph.title } : {}),
35
35
  ...(openGraph.description ? { description: openGraph.description } : {}),
36
36
  ...(metadata.canonical ? { url: metadata.canonical } : {}),
37
- ...(image ? { images: [{ url: image.url, ...(image.alt ? { alt: image.alt } : {}) }] } : {}),
37
+ ...(image
38
+ ? {
39
+ images: [
40
+ {
41
+ url: image.url,
42
+ ...(image.alt ? { alt: image.alt } : {}),
43
+ ...(image.width && image.height ? { width: image.width, height: image.height } : {}),
44
+ },
45
+ ],
46
+ }
47
+ : {}),
38
48
  },
39
49
  twitter: {
40
50
  card: metadata.twitterCard,
@@ -52,7 +62,11 @@ export function toNextMetadata(metadata) {
52
62
  export function kanorioImageLoader({ src, width }) {
53
63
  return imageUrl(src, { width });
54
64
  }
55
- /** `images.remotePatterns` entries for Kanorio's image host, for `next.config` when you use `next/image` without the loader */
65
+ /**
66
+ * `images.remotePatterns` entries for Kanorio's image host, for `next.config` when you use `next/image` without the loader:
67
+ * `images: { remotePatterns: kanorioRemotePatterns }`. It is a plain array because Next.js types `remotePatterns` as one;
68
+ * to add hosts of your own, spread it into a new array (`[...kanorioRemotePatterns, ...yours]`) rather than pushing to it.
69
+ */
56
70
  export const kanorioRemotePatterns = [
57
71
  { protocol: "https", hostname: "img.kanorio.com", pathname: "/**" },
58
72
  ];
@@ -7,12 +7,35 @@
7
7
  * console.log(post.slug);
8
8
  * }
9
9
  * ```
10
+ *
11
+ * Content Delivery API lists also carry a top-level `assets` map that resolves the media on that page only.
12
+ * `paginatePages` yields each page whole, and `listAllWithAssets` returns every item together with every page's `assets` merged.
10
13
  */
11
14
  export interface ListPage<T> {
12
15
  data: T[];
13
16
  hasMore: boolean;
14
17
  nextCursor: string | null;
15
18
  }
19
+ /** A list page that resolves its media in a top-level `assets` map (Content Delivery API lists) */
20
+ export interface ListPageWithAssets<T, A = unknown> extends ListPage<T> {
21
+ assets?: Readonly<Record<string, A>> | null;
22
+ }
23
+ /** Every item of a list, with the `assets` of all its pages in one map */
24
+ export interface ListWithAssets<T, A = unknown> {
25
+ data: T[];
26
+ assets: Record<string, A>;
27
+ }
28
+ /**
29
+ * Follows `nextCursor` and yields each page as the API returned it (`data`, `assets`, `access`, ...).
30
+ * Use it when you need more than the items, such as the `assets` map that resolves the images on that page.
31
+ */
32
+ export declare function paginatePages<P extends ListPage<unknown>>(fetchPage: (cursor: string | undefined) => Promise<P>): AsyncGenerator<P, void, undefined>;
33
+ /** Follows `nextCursor` and yields item by item. Each page's `assets` is dropped: use {@link paginatePages} or {@link listAllWithAssets} when you resolve images */
16
34
  export declare function paginate<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): AsyncGenerator<T, void, undefined>;
17
35
  /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
18
36
  export declare function listAll<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): Promise<T[]>;
37
+ /**
38
+ * Fetches every page and returns the items with the `assets` of every page merged into one map, so an image on any item
39
+ * resolves from the result (`image.resolve(item.fieldData.cover, result.assets)`). For small lists, as with {@link listAll}.
40
+ */
41
+ export declare function listAllWithAssets<T, A = unknown>(fetchPage: (cursor: string | undefined) => Promise<ListPageWithAssets<T, A>>): Promise<ListWithAssets<T, A>>;
package/dist/paginate.js CHANGED
@@ -7,17 +7,29 @@
7
7
  * console.log(post.slug);
8
8
  * }
9
9
  * ```
10
+ *
11
+ * Content Delivery API lists also carry a top-level `assets` map that resolves the media on that page only.
12
+ * `paginatePages` yields each page whole, and `listAllWithAssets` returns every item together with every page's `assets` merged.
10
13
  */
11
- export async function* paginate(fetchPage) {
14
+ /**
15
+ * Follows `nextCursor` and yields each page as the API returned it (`data`, `assets`, `access`, ...).
16
+ * Use it when you need more than the items, such as the `assets` map that resolves the images on that page.
17
+ */
18
+ export async function* paginatePages(fetchPage) {
12
19
  let cursor;
13
20
  for (;;) {
14
21
  const page = await fetchPage(cursor);
15
- yield* page.data;
22
+ yield page;
16
23
  if (!page.hasMore || !page.nextCursor)
17
24
  return;
18
25
  cursor = page.nextCursor;
19
26
  }
20
27
  }
28
+ /** Follows `nextCursor` and yields item by item. Each page's `assets` is dropped: use {@link paginatePages} or {@link listAllWithAssets} when you resolve images */
29
+ export async function* paginate(fetchPage) {
30
+ for await (const page of paginatePages(fetchPage))
31
+ yield* page.data;
32
+ }
21
33
  /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
22
34
  export async function listAll(fetchPage) {
23
35
  const out = [];
@@ -25,3 +37,17 @@ export async function listAll(fetchPage) {
25
37
  out.push(item);
26
38
  return out;
27
39
  }
40
+ /**
41
+ * Fetches every page and returns the items with the `assets` of every page merged into one map, so an image on any item
42
+ * resolves from the result (`image.resolve(item.fieldData.cover, result.assets)`). For small lists, as with {@link listAll}.
43
+ */
44
+ export async function listAllWithAssets(fetchPage) {
45
+ const data = [];
46
+ const assets = {};
47
+ for await (const page of paginatePages(fetchPage)) {
48
+ data.push(...page.data);
49
+ if (page.assets)
50
+ Object.assign(assets, page.assets);
51
+ }
52
+ return { data, assets };
53
+ }
package/dist/seo.d.ts CHANGED
@@ -133,10 +133,22 @@ export interface SeoItemInput extends LocalizedResponseFields {
133
133
  title?: unknown;
134
134
  name?: unknown;
135
135
  excerpt?: unknown;
136
+ /** A category's description: the description of its page when no SEO description was written */
137
+ description?: unknown;
138
+ /** An author's bio: the description of their page when no SEO description was written */
139
+ bio?: unknown;
140
+ /**
141
+ * `{ posts }`, the number of published posts of a category, tag or author. The Delivery API sends it for these three only,
142
+ * so an item with it gets the rules of a category, tag or author page (keep it when you narrow the response with `fields`)
143
+ */
144
+ counts?: unknown;
136
145
  seo?: ItemSeoFields | null;
137
146
  share_image?: {
138
147
  url: string;
139
148
  alt?: string | null;
149
+ source?: ShareImageSource | null;
150
+ width?: number | null;
151
+ height?: number | null;
140
152
  } | null;
141
153
  [key: string]: unknown;
142
154
  };
@@ -160,10 +172,23 @@ export interface SeoMetadataOptions {
160
172
  */
161
173
  path?: string;
162
174
  }
175
+ /**
176
+ * Where a share image came from: the one the author `chosen`, the post's `cover`, the `title_card` Kanorio generates from the title,
177
+ * or the first image in the body (`body_image`). Skip `title_card` when you show the share image as a list card's thumbnail
178
+ */
179
+ export type ShareImageSource = "chosen" | "cover" | "title_card" | "body_image";
163
180
  export interface ShareImage {
164
181
  url: string;
165
- /** Alt text for the image; null when neither the author nor the image has one */
182
+ /**
183
+ * Alt text for the image: what the author wrote for the share image, else the image's own. When the image the author chose
184
+ * is gone and another one is used, only that image's own alt text applies. null when there is none
185
+ */
166
186
  alt: string | null;
187
+ /** Where the image came from; null for a page (`seo.ogImage` does not say) */
188
+ source: ShareImageSource | null;
189
+ /** Pixel size `url` delivers, for `og:image:width` and `og:image:height`; null when unknown (a page, an external URL, an SVG) */
190
+ width: number | null;
191
+ height: number | null;
167
192
  }
168
193
  /** Everything a page's `<head>` needs, as plain values. `toNextMetadata` in `@kanorio/sdk/next` turns it into a Next.js `Metadata` object */
169
194
  export interface SeoMetadata {
@@ -190,14 +215,17 @@ export interface SeoMetadata {
190
215
  * The image to use as `og:image`, already resolved by Kanorio: the share image the author chose (cropped to 1200x630 the way they framed it),
191
216
  * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
192
217
  * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
218
+ * The alt text is `share_image.alt` as Kanorio resolved it, `null` included: `seo.ogImageAlt` describes the image the author chose,
219
+ * which is not the one in `share_image` when that image is gone, so it is read only when `share_image` has no `alt` at all.
193
220
  */
194
221
  export declare function shareImageOf(input: SeoInput): ShareImage | null;
195
222
  /**
196
223
  * The `<head>` values of a blog post, a category, tag or author page, or a page, by the same rules the hosted site uses:
197
- * - title and description: what the author wrote under SEO, else the item's own title and excerpt
224
+ * - title and description: what the author wrote under SEO, else the item's own title and excerpt. A category, tag or author
225
+ * (an item with `counts`) uses its name, and a category's description or an author's bio
198
226
  * - canonical: the address the author set, on the primary locale only (a translated page always points to itself); otherwise the page's own URL
199
227
  * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
200
- * - robots: `noindex` and `nofollow` when the author set them
228
+ * - robots: `noindex` and `nofollow` when the author set them; a category, tag or author with no published posts is `noindex`
201
229
  * - share image: `shareImageOf(input)`; its alt text falls back to the title
202
230
  * - share title and description: what the author wrote for sharing, else the SEO title and description
203
231
  */
package/dist/seo.js CHANGED
@@ -106,29 +106,49 @@ export function listingRobots(site, key) {
106
106
  return state === "live" ? "index, follow" : "noindex, follow";
107
107
  }
108
108
  const text = (value) => (typeof value === "string" && value.trim() ? value.trim() : null);
109
+ const pixels = (value) => (typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null);
109
110
  function isItemInput(input) {
110
111
  return typeof input.fieldData === "object" && input.fieldData !== null;
111
112
  }
113
+ /** The number of published posts of a category, tag or author (`fieldData.counts.posts`); null for any other item */
114
+ function termPostCount(fieldData) {
115
+ const counts = fieldData.counts;
116
+ if (!counts || typeof counts !== "object")
117
+ return null;
118
+ const posts = counts.posts;
119
+ return typeof posts === "number" && Number.isFinite(posts) ? posts : null;
120
+ }
112
121
  /**
113
122
  * The image to use as `og:image`, already resolved by Kanorio: the share image the author chose (cropped to 1200x630 the way they framed it),
114
123
  * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
115
124
  * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
125
+ * The alt text is `share_image.alt` as Kanorio resolved it, `null` included: `seo.ogImageAlt` describes the image the author chose,
126
+ * which is not the one in `share_image` when that image is gone, so it is read only when `share_image` has no `alt` at all.
116
127
  */
117
128
  export function shareImageOf(input) {
118
129
  if (isItemInput(input)) {
119
130
  const image = input.fieldData.share_image;
120
131
  const url = text(image?.url);
121
- return url ? { url, alt: text(image?.alt) ?? text(input.fieldData.seo?.ogImageAlt) } : null;
132
+ if (!image || !url)
133
+ return null;
134
+ return {
135
+ url,
136
+ alt: image.alt !== undefined ? text(image.alt) : text(input.fieldData.seo?.ogImageAlt),
137
+ source: image.source ?? null,
138
+ width: pixels(image.width),
139
+ height: pixels(image.height),
140
+ };
122
141
  }
123
142
  const url = text(input.seo?.ogImage);
124
- return url ? { url, alt: text(input.seo?.ogImageAlt) } : null;
143
+ return url ? { url, alt: text(input.seo?.ogImageAlt), source: null, width: null, height: null } : null;
125
144
  }
126
145
  /**
127
146
  * The `<head>` values of a blog post, a category, tag or author page, or a page, by the same rules the hosted site uses:
128
- * - title and description: what the author wrote under SEO, else the item's own title and excerpt
147
+ * - title and description: what the author wrote under SEO, else the item's own title and excerpt. A category, tag or author
148
+ * (an item with `counts`) uses its name, and a category's description or an author's bio
129
149
  * - canonical: the address the author set, on the primary locale only (a translated page always points to itself); otherwise the page's own URL
130
150
  * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
131
- * - robots: `noindex` and `nofollow` when the author set them
151
+ * - robots: `noindex` and `nofollow` when the author set them; a category, tag or author with no published posts is `noindex`
132
152
  * - share image: `shareImageOf(input)`; its alt text falls back to the title
133
153
  * - share title and description: what the author wrote for sharing, else the SEO title and description
134
154
  */
@@ -136,9 +156,22 @@ export function seoMetadata(input, options = {}) {
136
156
  const item = isItemInput(input);
137
157
  const itemSeo = item ? input.fieldData.seo ?? {} : {};
138
158
  const pageSeo = item ? {} : input.seo ?? {};
139
- const ownTitle = item ? text(input.fieldData.title) ?? text(input.fieldData.name) : text(input.title);
159
+ // A category, tag or author page: its name is the title (an author's `title` is a job title), its description or bio describes it,
160
+ // and with no published posts it is an empty list page that search engines should not index
161
+ const termPosts = item ? termPostCount(input.fieldData) : null;
162
+ const isTerm = termPosts !== null;
163
+ const ownTitle = !item
164
+ ? text(input.title)
165
+ : isTerm
166
+ ? text(input.fieldData.name) ?? text(input.fieldData.title)
167
+ : text(input.fieldData.title) ?? text(input.fieldData.name);
168
+ const ownDescription = !item
169
+ ? null
170
+ : isTerm
171
+ ? text(input.fieldData.description) ?? text(input.fieldData.bio)
172
+ : text(input.fieldData.excerpt);
140
173
  const title = (item ? text(itemSeo.title) : text(pageSeo.seoTitle)) ?? ownTitle;
141
- const description = (item ? text(itemSeo.description) ?? text(input.fieldData.excerpt) : text(pageSeo.seoDescription)) ?? null;
174
+ const description = (item ? text(itemSeo.description) : text(pageSeo.seoDescription)) ?? ownDescription;
142
175
  const keywordList = item ? itemSeo.keywords : pageSeo.seoKeywords;
143
176
  const keywords = keywordList && keywordList.length > 0 ? [...keywordList] : null;
144
177
  const shared = item ? itemSeo : pageSeo;
@@ -182,11 +215,11 @@ export function seoMetadata(input, options = {}) {
182
215
  keywords,
183
216
  canonical,
184
217
  languages,
185
- robots: { index: text(shared.robotsIndex) !== "noindex", follow: text(shared.robotsFollow) !== "nofollow" },
218
+ robots: { index: text(shared.robotsIndex) !== "noindex" && termPosts !== 0, follow: text(shared.robotsFollow) !== "nofollow" },
186
219
  openGraph: {
187
220
  title: text(shared.ogTitle) ?? title,
188
221
  description: text(shared.ogDescription) ?? description,
189
- image: image ? { url: image.url, alt: image.alt ?? ownTitle } : null,
222
+ image: image ? { ...image, alt: image.alt ?? ownTitle } : null,
190
223
  },
191
224
  twitterCard: text(shared.twitterCard) === "summary" ? "summary" : "summary_large_image",
192
225
  };