@kanorio/sdk 1.1.0 → 1.2.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.1.0";
6
+ export declare const KANORIO_SDK_VERSION = "1.2.0";
7
7
  export declare const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
8
8
  export interface ErrorEnvelope {
9
9
  error: {
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.1.0";
6
+ export const KANORIO_SDK_VERSION = "1.2.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)
@@ -0,0 +1,77 @@
1
+ /**
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
+ *
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.
7
+ * See "Filtering, fields and expand" in the developer documentation for the asset fields.
8
+ */
9
+ /** One entry of the `assets` map in a Delivery API response (the fields these helpers read) */
10
+ export interface ImageAssetLike {
11
+ url: string;
12
+ width?: number | null;
13
+ height?: number | null;
14
+ alt?: string | null;
15
+ focus?: {
16
+ x: number;
17
+ y: number;
18
+ } | null;
19
+ placeholder?: string | null;
20
+ edgeColor?: string | null;
21
+ }
22
+ /** The `assets` map of a Delivery API response: asset id to asset */
23
+ export type ImageAssetMapLike = Readonly<Record<string, ImageAssetLike | undefined>>;
24
+ export interface ResolvedImage {
25
+ url: string;
26
+ /** Pixel size of the original; null when unknown (an external URL, an SVG) */
27
+ width: number | null;
28
+ height: number | null;
29
+ /** Alt text written where the image is used, otherwise the asset's own; null when there is none */
30
+ 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;
36
+ /** Tiny blurred preview as a data URL, for a blur-up `<img>` or Next.js `blurDataURL`; null when there is none */
37
+ placeholder: string | null;
38
+ /** The solid color shared by all four edges, for the background behind `object-fit: contain`; null when there is none */
39
+ edgeColor: string | null;
40
+ }
41
+ export type ImageFit = "scale-down" | "contain" | "cover" | "crop" | "pad";
42
+ export interface ImageUrlOptions {
43
+ /** Output width in pixels */
44
+ width: number;
45
+ /** Output height in pixels. With a height, `fit` defaults to `cover` (crop to fill); without one, to `scale-down` (never enlarge) */
46
+ height?: number;
47
+ fit?: ImageFit;
48
+ }
49
+ export interface ImageSrcSetOptions {
50
+ /** Widths to offer, in pixels. Default: 400, 800, 1200, 1600 */
51
+ widths?: readonly number[];
52
+ }
53
+ /** Widths `srcSet` offers by default: phones up to a desktop article column on a high-density screen */
54
+ export declare const DEFAULT_IMAGE_WIDTHS: readonly number[];
55
+ /** True when the URL is an image Kanorio can resize (not an external URL, not an SVG or a file) */
56
+ export declare function isResizableImageUrl(src: string | null | undefined): src is string;
57
+ /**
58
+ * Resolve an image field value: an asset id is looked up in `assets`, a full URL is returned as is.
59
+ * Returns `undefined` for an empty value and for an asset id that is not in the map (the file was removed).
60
+ */
61
+ export declare function resolveImage(value: string | null | undefined, assets: ImageAssetMapLike | null | undefined): ResolvedImage | undefined;
62
+ /**
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.
65
+ */
66
+ export declare function imageUrl(src: string, options: ImageUrlOptions): string;
67
+ /**
68
+ * A `srcset` value offering the image at several widths (never enlarged), for `<img srcset>` together with `sizes`.
69
+ * Returns `undefined` for a URL Kanorio cannot resize: leave `srcset` off and use `src` alone.
70
+ */
71
+ export declare function imageSrcSet(src: string, options?: ImageSrcSetOptions): string | undefined;
72
+ export declare const image: {
73
+ readonly resolve: typeof resolveImage;
74
+ readonly url: typeof imageUrl;
75
+ readonly srcSet: typeof imageSrcSet;
76
+ readonly isResizable: typeof isResizableImageUrl;
77
+ };
package/dist/image.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
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
+ *
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.
7
+ * See "Filtering, fields and expand" in the developer documentation for the asset fields.
8
+ */
9
+ /** Widths `srcSet` offers by default: phones up to a desktop article column on a high-density screen */
10
+ export const DEFAULT_IMAGE_WIDTHS = [400, 800, 1200, 1600];
11
+ const ABSOLUTE_URL = /^https?:\/\//i;
12
+ /**
13
+ * A Kanorio image URL, split before its last path segment (the variant: `public`, or a size such as `w=800,fit=scale-down`).
14
+ * Both hosts Kanorio has served images from are recognized.
15
+ */
16
+ const KANORIO_IMAGE_URL = /^(https:\/\/(?:[a-z0-9-]+\.kanorio\.com\/cdn-cgi\/imagedelivery|imagedelivery\.net)\/[^/?#]+\/[^/?#]+)\/[^/?#]+$/i;
17
+ /** True when the URL is an image Kanorio can resize (not an external URL, not an SVG or a file) */
18
+ export function isResizableImageUrl(src) {
19
+ return typeof src === "string" && KANORIO_IMAGE_URL.test(src.trim());
20
+ }
21
+ function positiveInt(value) {
22
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.round(value) : null;
23
+ }
24
+ /**
25
+ * Resolve an image field value: an asset id is looked up in `assets`, a full URL is returned as is.
26
+ * Returns `undefined` for an empty value and for an asset id that is not in the map (the file was removed).
27
+ */
28
+ export function resolveImage(value, assets) {
29
+ const trimmed = typeof value === "string" ? value.trim() : "";
30
+ if (!trimmed)
31
+ return undefined;
32
+ if (ABSOLUTE_URL.test(trimmed)) {
33
+ return { url: trimmed, width: null, height: null, alt: null, focus: null, placeholder: null, edgeColor: null };
34
+ }
35
+ const asset = assets?.[trimmed];
36
+ if (!asset?.url)
37
+ return undefined;
38
+ return {
39
+ url: asset.url,
40
+ width: asset.width ?? null,
41
+ height: asset.height ?? null,
42
+ alt: asset.alt ?? null,
43
+ focus: asset.focus ?? null,
44
+ placeholder: asset.placeholder ?? null,
45
+ edgeColor: asset.edgeColor ?? null,
46
+ };
47
+ }
48
+ /**
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.
51
+ */
52
+ export function imageUrl(src, options) {
53
+ const match = KANORIO_IMAGE_URL.exec(src.trim());
54
+ 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}`;
60
+ }
61
+ /**
62
+ * A `srcset` value offering the image at several widths (never enlarged), for `<img srcset>` together with `sizes`.
63
+ * Returns `undefined` for a URL Kanorio cannot resize: leave `srcset` off and use `src` alone.
64
+ */
65
+ export function imageSrcSet(src, options = {}) {
66
+ if (!isResizableImageUrl(src))
67
+ return undefined;
68
+ const widths = [...new Set((options.widths ?? DEFAULT_IMAGE_WIDTHS).map((w) => positiveInt(w)).filter((w) => w !== null))].sort((a, b) => a - b);
69
+ if (widths.length === 0)
70
+ return undefined;
71
+ return widths.map((width) => `${imageUrl(src, { width })} ${width}w`).join(", ");
72
+ }
73
+ export const image = {
74
+ resolve: resolveImage,
75
+ url: imageUrl,
76
+ srcSet: imageSrcSet,
77
+ isResizable: isResizableImageUrl,
78
+ };
package/dist/index.d.ts CHANGED
@@ -6,7 +6,8 @@ export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, type ManagementCli
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, type ListingKey, type ListingState, type SeoRewriteFramework, type NextSeoRewriteRule, type SeoRewritesOptions, type DeliveryJsonLdResult, type SitemapEntry, type SitemapEntriesResult, type SeoHelpers, } from "./seo.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";
10
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";
11
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";
12
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
@@ -5,7 +5,8 @@ export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, } from "./manageme
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";
7
7
  export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, } from "./customer-oauth.js";
8
- export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, } from "./seo.js";
8
+ export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, seoMetadata, shareImageOf, } from "./seo.js";
9
+ export { image, resolveImage, imageUrl, imageSrcSet, isResizableImageUrl, DEFAULT_IMAGE_WIDTHS, } from "./image.js";
9
10
  export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, } from "./shared/api/delivery/cache-tags.js";
10
11
  export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, } from "./locales.js";
11
12
  export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from "./revalidate.js";
package/dist/next.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Next.js adapters. They have no dependency on `next`: the return values match the shapes Next.js expects
3
+ * (`Metadata` from `generateMetadata`, an image `loader`, `images.remotePatterns`), so they work with the Next.js version you have.
4
+ *
5
+ * ```ts
6
+ * // app/blog/[slug]/page.tsx
7
+ * import { seoMetadata } from "@kanorio/sdk";
8
+ * import { toNextMetadata } from "@kanorio/sdk/next";
9
+ *
10
+ * export async function generateMetadata({ params }) {
11
+ * const data = await loadPost((await params).slug);
12
+ * return data ? toNextMetadata(seoMetadata(data.item, { siteUrl: SITE_URL, site })) : {};
13
+ * }
14
+ * ```
15
+ */
16
+ import type { SeoMetadata } from "./seo.js";
17
+ /** The part of Next.js `Metadata` these helpers fill in. Assignable to `Metadata` from `next` */
18
+ export interface NextMetadataLike {
19
+ title?: string;
20
+ description?: string;
21
+ keywords?: string[];
22
+ alternates?: {
23
+ canonical?: string;
24
+ languages?: Record<string, string>;
25
+ };
26
+ robots: {
27
+ index: boolean;
28
+ follow: boolean;
29
+ };
30
+ openGraph: {
31
+ title?: string;
32
+ description?: string;
33
+ url?: string;
34
+ images?: Array<{
35
+ url: string;
36
+ alt?: string;
37
+ }>;
38
+ };
39
+ twitter: {
40
+ card: "summary" | "summary_large_image";
41
+ title?: string;
42
+ description?: string;
43
+ images?: string[];
44
+ };
45
+ }
46
+ /**
47
+ * Turn `seoMetadata(...)` into the object `generateMetadata` returns. The title has no site name: add it with `title.template` in the root layout,
48
+ * and set `metadataBase` there when `canonical` is a path.
49
+ */
50
+ export declare function toNextMetadata(metadata: SeoMetadata): NextMetadataLike;
51
+ /**
52
+ * An image loader for `next/image`: Kanorio's edge resizes the image, so Next.js does not have to.
53
+ * Use it per image (`<Image loader={kanorioImageLoader} ... />`) or for the whole app (`images.loaderFile` pointing at a file that
54
+ * default-exports it). Images Kanorio cannot resize (external URLs, SVG) are returned unchanged.
55
+ */
56
+ export declare function kanorioImageLoader({ src, width }: {
57
+ src: string;
58
+ width: number;
59
+ quality?: number;
60
+ }): 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
+ protocol: "https";
64
+ hostname: string;
65
+ pathname: string;
66
+ }>;
package/dist/next.js ADDED
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Next.js adapters. They have no dependency on `next`: the return values match the shapes Next.js expects
3
+ * (`Metadata` from `generateMetadata`, an image `loader`, `images.remotePatterns`), so they work with the Next.js version you have.
4
+ *
5
+ * ```ts
6
+ * // app/blog/[slug]/page.tsx
7
+ * import { seoMetadata } from "@kanorio/sdk";
8
+ * import { toNextMetadata } from "@kanorio/sdk/next";
9
+ *
10
+ * export async function generateMetadata({ params }) {
11
+ * const data = await loadPost((await params).slug);
12
+ * return data ? toNextMetadata(seoMetadata(data.item, { siteUrl: SITE_URL, site })) : {};
13
+ * }
14
+ * ```
15
+ */
16
+ import { imageUrl } from "./image.js";
17
+ /**
18
+ * Turn `seoMetadata(...)` into the object `generateMetadata` returns. The title has no site name: add it with `title.template` in the root layout,
19
+ * and set `metadataBase` there when `canonical` is a path.
20
+ */
21
+ export function toNextMetadata(metadata) {
22
+ const { openGraph } = metadata;
23
+ const hasLanguages = Object.keys(metadata.languages).length > 0;
24
+ const image = openGraph.image;
25
+ return {
26
+ ...(metadata.title ? { title: metadata.title } : {}),
27
+ ...(metadata.description ? { description: metadata.description } : {}),
28
+ ...(metadata.keywords ? { keywords: metadata.keywords } : {}),
29
+ ...(metadata.canonical || hasLanguages
30
+ ? { alternates: { ...(metadata.canonical ? { canonical: metadata.canonical } : {}), ...(hasLanguages ? { languages: metadata.languages } : {}) } }
31
+ : {}),
32
+ robots: { index: metadata.robots.index, follow: metadata.robots.follow },
33
+ openGraph: {
34
+ ...(openGraph.title ? { title: openGraph.title } : {}),
35
+ ...(openGraph.description ? { description: openGraph.description } : {}),
36
+ ...(metadata.canonical ? { url: metadata.canonical } : {}),
37
+ ...(image ? { images: [{ url: image.url, ...(image.alt ? { alt: image.alt } : {}) }] } : {}),
38
+ },
39
+ twitter: {
40
+ card: metadata.twitterCard,
41
+ ...(openGraph.title ? { title: openGraph.title } : {}),
42
+ ...(openGraph.description ? { description: openGraph.description } : {}),
43
+ ...(image ? { images: [image.url] } : {}),
44
+ },
45
+ };
46
+ }
47
+ /**
48
+ * An image loader for `next/image`: Kanorio's edge resizes the image, so Next.js does not have to.
49
+ * Use it per image (`<Image loader={kanorioImageLoader} ... />`) or for the whole app (`images.loaderFile` pointing at a file that
50
+ * default-exports it). Images Kanorio cannot resize (external URLs, SVG) are returned unchanged.
51
+ */
52
+ export function kanorioImageLoader({ src, width }) {
53
+ return imageUrl(src, { width });
54
+ }
55
+ /** `images.remotePatterns` entries for Kanorio's image host, for `next.config` when you use `next/image` without the loader */
56
+ export const kanorioRemotePatterns = [
57
+ { protocol: "https", hostname: "img.kanorio.com", pathname: "/**" },
58
+ ];
package/dist/seo.d.ts CHANGED
@@ -4,9 +4,11 @@
4
4
  * - `fetchDeliveryJsonLd({ siteUrl, path })`: fetches a path's Schema.org JSON-LD `@graph` and a safely escaped `<script>` string
5
5
  * - `fetchSitemapEntries({ siteUrl })`: `sitemap.xml` as data, for front ends that build their own sitemap and merge it in
6
6
  * - `listingRobots(site, key)`: the robots value of a list page, from `listings` in `/api/v1/site`
7
+ * - `seoMetadata(input, options)`: the `<head>` values of a post, a category, tag or author page, or a page, by the rules the hosted site uses
8
+ * - `shareImageOf(input)`: the image for `og:image`, already resolved by Kanorio
7
9
  */
8
10
  import type { components as DeliveryComponents } from "./generated/delivery.js";
9
- import { buildAlternates, languageSwitcher } from "./locales.js";
11
+ import { buildAlternates, languageSwitcher, type SiteLocaleMeta } from "./locales.js";
10
12
  export type ListingState = DeliveryComponents["schemas"]["ListingState"];
11
13
  export type ListingKey = keyof NonNullable<DeliveryComponents["schemas"]["SiteMeta"]["listings"]>;
12
14
  export type SeoRewriteFramework = "next" | "astro";
@@ -91,6 +93,115 @@ export declare function fetchSitemapEntries(options: {
91
93
  export declare function listingRobots(site: {
92
94
  listings?: Partial<Record<ListingKey, ListingState>> | null;
93
95
  }, key: ListingKey): "index, follow" | "noindex, follow" | null;
96
+ /** The SEO fields of a blog post, category, tag or author (`fieldData.seo` of a collection item) */
97
+ export interface ItemSeoFields {
98
+ title?: string | null;
99
+ description?: string | null;
100
+ keywords?: readonly string[] | null;
101
+ ogTitle?: string | null;
102
+ ogDescription?: string | null;
103
+ ogImageAlt?: string | null;
104
+ canonical?: string | null;
105
+ robotsIndex?: string | null;
106
+ robotsFollow?: string | null;
107
+ twitterCard?: string | null;
108
+ }
109
+ /** The SEO fields of a page (`page.seo` of `GET /pages/{slug}`). `ogImage` is already the URL to use: the chosen share image, cropped, or the generated title card */
110
+ export interface PageSeoFields {
111
+ seoTitle?: string | null;
112
+ seoDescription?: string | null;
113
+ seoKeywords?: readonly string[] | null;
114
+ ogTitle?: string | null;
115
+ ogDescription?: string | null;
116
+ ogImage?: string | null;
117
+ ogImageAlt?: string | null;
118
+ canonicalUrl?: string | null;
119
+ robotsIndex?: string | null;
120
+ robotsFollow?: string | null;
121
+ twitterCard?: string | null;
122
+ }
123
+ interface LocalizedResponseFields {
124
+ /** Path of the page on the site, in the locale of the response */
125
+ path?: string | null;
126
+ resolvedLocale?: string | null;
127
+ availableLocales?: readonly string[] | null;
128
+ localePaths?: Readonly<Record<string, string>> | null;
129
+ }
130
+ /** A collection item from the Delivery API that has a page of its own: a blog post, a category, a tag or an author */
131
+ export interface SeoItemInput extends LocalizedResponseFields {
132
+ fieldData: {
133
+ title?: unknown;
134
+ name?: unknown;
135
+ excerpt?: unknown;
136
+ seo?: ItemSeoFields | null;
137
+ share_image?: {
138
+ url: string;
139
+ alt?: string | null;
140
+ } | null;
141
+ [key: string]: unknown;
142
+ };
143
+ }
144
+ /** A page from `GET /pages/{slug}` */
145
+ export interface SeoPageInput extends LocalizedResponseFields {
146
+ title?: string | null;
147
+ seo?: PageSeoFields | null;
148
+ }
149
+ export type SeoInput = SeoItemInput | SeoPageInput;
150
+ export interface SeoMetadataOptions {
151
+ /** Your front end's public URL, without a trailing slash (`https://www.example.com`). Without it `canonical` is a path and there is no hreflang */
152
+ siteUrl?: string;
153
+ /** The `GET /api/v1/site` response. Needed on multilingual sites for hreflang and the canonical of a translated page */
154
+ site?: SiteLocaleMeta | null;
155
+ /** The locale in the URL of this request (`locale` from `resolveRequestLocale`); defaults to the locale the content was served in */
156
+ requestLocale?: string | null;
157
+ /**
158
+ * The page's path in the primary locale's space (no locale prefix), when the response does not carry one:
159
+ * an item of a custom collection without `pathTemplate`, or a page you route yourself
160
+ */
161
+ path?: string;
162
+ }
163
+ export interface ShareImage {
164
+ url: string;
165
+ /** Alt text for the image; null when neither the author nor the image has one */
166
+ alt: string | null;
167
+ }
168
+ /** Everything a page's `<head>` needs, as plain values. `toNextMetadata` in `@kanorio/sdk/next` turns it into a Next.js `Metadata` object */
169
+ export interface SeoMetadata {
170
+ /** The page's own title, without the site name: add the site name in your layout */
171
+ title: string | null;
172
+ description: string | null;
173
+ keywords: string[] | null;
174
+ /** The canonical URL (absolute when `siteUrl` is given, otherwise a path); null when the response carries no path and none was passed */
175
+ canonical: string | null;
176
+ /** hreflang to URL, including `x-default`; empty on single-language sites, on pages without a translation, and without `siteUrl` and `site` */
177
+ languages: Record<string, string>;
178
+ robots: {
179
+ index: boolean;
180
+ follow: boolean;
181
+ };
182
+ openGraph: {
183
+ title: string | null;
184
+ description: string | null;
185
+ image: ShareImage | null;
186
+ };
187
+ twitterCard: "summary" | "summary_large_image";
188
+ }
189
+ /**
190
+ * 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
+ * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
192
+ * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
193
+ */
194
+ export declare function shareImageOf(input: SeoInput): ShareImage | null;
195
+ /**
196
+ * 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
198
+ * - 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
+ * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
200
+ * - robots: `noindex` and `nofollow` when the author set them
201
+ * - share image: `shareImageOf(input)`; its alt text falls back to the title
202
+ * - share title and description: what the author wrote for sharing, else the SEO title and description
203
+ */
204
+ export declare function seoMetadata(input: SeoInput, options?: SeoMetadataOptions): SeoMetadata;
94
205
  export interface SeoHelpers {
95
206
  rewrites(options: {
96
207
  framework: "next";
@@ -113,8 +224,13 @@ export declare const seo: {
113
224
  readonly jsonLd: typeof fetchDeliveryJsonLd;
114
225
  readonly sitemapEntries: typeof fetchSitemapEntries;
115
226
  readonly listingRobots: typeof listingRobots;
227
+ /** The `<head>` values of a post, a category, tag or author page, or a page */
228
+ readonly metadata: typeof seoMetadata;
229
+ /** The image for `og:image`, already resolved by Kanorio */
230
+ readonly shareImage: typeof shareImageOf;
116
231
  /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
117
232
  readonly alternates: typeof buildAlternates;
118
233
  readonly languageSwitcher: typeof languageSwitcher;
119
234
  readonly create: typeof createSeoHelpers;
120
235
  };
236
+ export {};
package/dist/seo.js CHANGED
@@ -4,9 +4,11 @@
4
4
  * - `fetchDeliveryJsonLd({ siteUrl, path })`: fetches a path's Schema.org JSON-LD `@graph` and a safely escaped `<script>` string
5
5
  * - `fetchSitemapEntries({ siteUrl })`: `sitemap.xml` as data, for front ends that build their own sitemap and merge it in
6
6
  * - `listingRobots(site, key)`: the robots value of a list page, from `listings` in `/api/v1/site`
7
+ * - `seoMetadata(input, options)`: the `<head>` values of a post, a category, tag or author page, or a page, by the rules the hosted site uses
8
+ * - `shareImageOf(input)`: the image for `og:image`, already resolved by Kanorio
7
9
  */
8
10
  import { deliveryBaseUrl, parseDeliveryCacheTags } from "./delivery.js";
9
- import { buildAlternates, languageSwitcher } from "./locales.js";
11
+ import { buildAlternates, languageSwitcher, requestLocaleOf } from "./locales.js";
10
12
  const SEO_REWRITE_PATHS = [
11
13
  { source: "/sitemap.xml", apiPath: "/seo/sitemap.xml" },
12
14
  { source: "/robots.txt", apiPath: "/seo/robots.txt" },
@@ -103,6 +105,92 @@ export function listingRobots(site, key) {
103
105
  return null;
104
106
  return state === "live" ? "index, follow" : "noindex, follow";
105
107
  }
108
+ const text = (value) => (typeof value === "string" && value.trim() ? value.trim() : null);
109
+ function isItemInput(input) {
110
+ return typeof input.fieldData === "object" && input.fieldData !== null;
111
+ }
112
+ /**
113
+ * 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
+ * else, for a post, its cover, the generated title card or the first image in the body. Same image the hosted site uses.
115
+ * Reads `fieldData.share_image` of a collection item, or `seo.ogImage` of a page. Returns `null` when there is none.
116
+ */
117
+ export function shareImageOf(input) {
118
+ if (isItemInput(input)) {
119
+ const image = input.fieldData.share_image;
120
+ const url = text(image?.url);
121
+ return url ? { url, alt: text(image?.alt) ?? text(input.fieldData.seo?.ogImageAlt) } : null;
122
+ }
123
+ const url = text(input.seo?.ogImage);
124
+ return url ? { url, alt: text(input.seo?.ogImageAlt) } : null;
125
+ }
126
+ /**
127
+ * 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
129
+ * - 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
+ * - hreflang: every locale that has a published translation (needs `siteUrl` and `site`)
131
+ * - robots: `noindex` and `nofollow` when the author set them
132
+ * - share image: `shareImageOf(input)`; its alt text falls back to the title
133
+ * - share title and description: what the author wrote for sharing, else the SEO title and description
134
+ */
135
+ export function seoMetadata(input, options = {}) {
136
+ const item = isItemInput(input);
137
+ const itemSeo = item ? input.fieldData.seo ?? {} : {};
138
+ const pageSeo = item ? {} : input.seo ?? {};
139
+ const ownTitle = item ? text(input.fieldData.title) ?? text(input.fieldData.name) : text(input.title);
140
+ 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;
142
+ const keywordList = item ? itemSeo.keywords : pageSeo.seoKeywords;
143
+ const keywords = keywordList && keywordList.length > 0 ? [...keywordList] : null;
144
+ const shared = item ? itemSeo : pageSeo;
145
+ const customCanonical = item ? text(itemSeo.canonical) : text(pageSeo.canonicalUrl);
146
+ const site = options.site ?? null;
147
+ const siteUrl = options.siteUrl ? options.siteUrl.replace(/\/+$/, "") : null;
148
+ const primaryLocale = site?.primaryLocale ?? null;
149
+ const resolvedLocale = input.resolvedLocale ?? null;
150
+ // The author's canonical is an address for the primary-locale page: a translated page ignores it
151
+ const servedInPrimary = !primaryLocale || !resolvedLocale || resolvedLocale === primaryLocale;
152
+ // The path in the primary locale's space: given by the caller, else from `localePaths`, else the response path with its locale prefix removed
153
+ const responsePath = text(input.path);
154
+ const primaryPath = text(options.path) ??
155
+ (primaryLocale ? text(input.localePaths?.[primaryLocale]) : null) ??
156
+ (responsePath ? (site ? requestLocaleOf(responsePath, site).pathname : responsePath) : null);
157
+ let canonical = null;
158
+ let languages = {};
159
+ if (primaryPath && siteUrl && site) {
160
+ const alternates = buildAlternates({
161
+ siteUrl,
162
+ site,
163
+ path: primaryPath,
164
+ requestLocale: options.requestLocale ?? resolvedLocale,
165
+ resolvedLocale,
166
+ availableLocales: input.availableLocales ?? null,
167
+ localePaths: input.localePaths ?? null,
168
+ });
169
+ canonical = alternates.canonical;
170
+ languages = alternates.languages;
171
+ }
172
+ else if (responsePath ?? primaryPath) {
173
+ const path = (responsePath ?? primaryPath);
174
+ canonical = siteUrl ? `${siteUrl}${path === "/" ? "" : path}` : path;
175
+ }
176
+ if (customCanonical && servedInPrimary)
177
+ canonical = customCanonical;
178
+ const image = shareImageOf(input);
179
+ return {
180
+ title,
181
+ description,
182
+ keywords,
183
+ canonical,
184
+ languages,
185
+ robots: { index: text(shared.robotsIndex) !== "noindex", follow: text(shared.robotsFollow) !== "nofollow" },
186
+ openGraph: {
187
+ title: text(shared.ogTitle) ?? title,
188
+ description: text(shared.ogDescription) ?? description,
189
+ image: image ? { url: image.url, alt: image.alt ?? ownTitle } : null,
190
+ },
191
+ twitterCard: text(shared.twitterCard) === "summary" ? "summary" : "summary_large_image",
192
+ };
193
+ }
106
194
  export function createSeoHelpers(options) {
107
195
  function rewrites(opts) {
108
196
  return seoRewrites({ siteUrl: options.siteUrl, framework: opts.framework });
@@ -118,6 +206,10 @@ export const seo = {
118
206
  jsonLd: fetchDeliveryJsonLd,
119
207
  sitemapEntries: fetchSitemapEntries,
120
208
  listingRobots,
209
+ /** The `<head>` values of a post, a category, tag or author page, or a page */
210
+ metadata: seoMetadata,
211
+ /** The image for `og:image`, already resolved by Kanorio */
212
+ shareImage: shareImageOf,
121
213
  /** A page's canonical and hreflang on multilingual sites (`locales.alternates`) */
122
214
  alternates: buildAlternates,
123
215
  languageSwitcher,
@@ -130,6 +130,8 @@ export declare const eventCacheTags: {
130
130
  readonly schemaChanged: (input: {
131
131
  collectionKey: string;
132
132
  }) => string[];
133
+ /** A form's definition changed, it was paused or resumed, or it moved to or from the trash: the form's own response in every locale */
134
+ readonly formChanged: (formId: string) => string[];
133
135
  /** The locale set changed (enabled, disabled, removed, prefix, order, primary): the language switcher and hreflang are on every page */
134
136
  readonly localeChanged: (siteId: string) => string[];
135
137
  /** A full-site translation finished: every response in that locale */
@@ -160,6 +160,8 @@ export const eventCacheTags = {
160
160
  },
161
161
  /** The field structure changed: the collection list, the item list and every single-item response of the collection (projected fields changed) */
162
162
  schemaChanged: (input) => [cacheTag.collections(), cacheTag.collection(input.collectionKey), cacheTag.collectionItems(input.collectionKey)],
163
+ /** A form's definition changed, it was paused or resumed, or it moved to or from the trash: the form's own response in every locale */
164
+ formChanged: (formId) => [cacheTag.form(formId)],
163
165
  /** The locale set changed (enabled, disabled, removed, prefix, order, primary): the language switcher and hreflang are on every page */
164
166
  localeChanged: (siteId) => [cacheTag.site(siteId)],
165
167
  /** A full-site translation finished: every response in that locale */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kanorio/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Typed fetch clients and headless helpers (SEO rewrites, JSON-LD, webhook revalidateTag) for the Kanorio Management API, Content Delivery API and Customer API.",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -25,6 +25,7 @@
25
25
  "directory": "packages/sdk"
26
26
  },
27
27
  "type": "module",
28
+ "sideEffects": false,
28
29
  "main": "./dist/index.js",
29
30
  "types": "./dist/index.d.ts",
30
31
  "exports": {
@@ -63,6 +64,10 @@
63
64
  "./preview": {
64
65
  "types": "./dist/preview.d.ts",
65
66
  "default": "./dist/preview.js"
67
+ },
68
+ "./next": {
69
+ "types": "./dist/next.d.ts",
70
+ "default": "./dist/next.js"
66
71
  }
67
72
  },
68
73
  "files": [