@ingram-tech/nk-seo 0.7.0 → 0.8.1

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/src/index.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Server entry: pure schema.org builders + the Metadata factory. No React, so
2
+ // route handlers / sitemap.ts can import these without pulling in the renderer.
3
+ // The <JsonLd> and <HreflangLinks> components live at
4
+ // "@ingram-tech/nk-seo/components".
5
+ export {
6
+ type AggregateOfferNode,
7
+ type AggregateRatingInput,
8
+ type AggregateRatingNode,
9
+ article,
10
+ type ArticleAuthor,
11
+ type ArticleAuthorNode,
12
+ type ArticleInput,
13
+ type ArticleNode,
14
+ type ArticleType,
15
+ breadcrumbList,
16
+ type BreadcrumbItem,
17
+ type BreadcrumbListNode,
18
+ type BreadcrumbPath,
19
+ createSeo,
20
+ type DataDownloadInput,
21
+ type DataDownloadNode,
22
+ dataset,
23
+ type DatasetInput,
24
+ type DatasetNode,
25
+ definedTerm,
26
+ type DefinedTermInput,
27
+ type DefinedTermNode,
28
+ definedTermSet,
29
+ type DefinedTermSetInput,
30
+ type DefinedTermSetNode,
31
+ event,
32
+ type EventInput,
33
+ type EventLocationInput,
34
+ type EventNode,
35
+ faqPage,
36
+ type FaqItem,
37
+ type FaqPageNode,
38
+ type GeoCoordinatesNode,
39
+ type GeoInput,
40
+ type ImageObjectNode,
41
+ type JsonLdNode,
42
+ type ListItemNode,
43
+ localBusiness,
44
+ type LocalBusinessInput,
45
+ type LocalBusinessNode,
46
+ type OfferInput,
47
+ type OfferNode,
48
+ organization,
49
+ type OrganizationInput,
50
+ type OrganizationNode,
51
+ person,
52
+ type PersonInput,
53
+ type PersonNode,
54
+ type PlaceNode,
55
+ type PostalAddressInput,
56
+ type PostalAddressNode,
57
+ type QuestionNode,
58
+ type Seo,
59
+ type SeoConfig,
60
+ softwareApplication,
61
+ type SoftwareApplicationInput,
62
+ type SoftwareApplicationNode,
63
+ type VirtualLocationNode,
64
+ website,
65
+ type WebsiteInput,
66
+ type WebsiteNode,
67
+ type WithContext,
68
+ type WithExtra,
69
+ } from "./schema.js";
70
+ export {
71
+ createMetadata,
72
+ type MetadataSiteConfig,
73
+ ogImageMetadata,
74
+ type OgImageMetadataInput,
75
+ type PageMetadata,
76
+ type PageMetadataInput,
77
+ type RootMetadataInput,
78
+ } from "./metadata.js";
79
+ export {
80
+ createRobots,
81
+ createSitemap,
82
+ type RobotsConfig,
83
+ type SitemapConfig,
84
+ type SitemapLanguages,
85
+ type SitemapRoute,
86
+ } from "./routes.js";
87
+ export {
88
+ hreflangAlternates,
89
+ type HreflangAlternates,
90
+ type HreflangConfig,
91
+ type HreflangLink,
92
+ } from "./alternates.js";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * JSON.stringify hardened for inline `<script>` bodies. `<` is escaped so a
3
+ * string value containing `</script>` (FAQ answers and article headlines often
4
+ * come from a CMS) cannot terminate the tag and inject markup; U+2028/2029 are
5
+ * escaped because they are valid JSON but not valid JS source.
6
+ */
7
+ // U+2028/U+2029 via RegExp() so the source stays ASCII (a literal invisible
8
+ // character would be one editor "normalization" away from silently vanishing).
9
+ const LINE_SEPARATORS = new RegExp("[\\u2028\\u2029]", "g");
10
+
11
+ export const serializeJsonLd = (data: object | object[]): string =>
12
+ JSON.stringify(data)
13
+ .replace(/</g, "\\u003c")
14
+ .replace(LINE_SEPARATORS, (char) => {
15
+ const hex = char.codePointAt(0)?.toString(16) ?? "";
16
+ return "\\u" + hex;
17
+ });
18
+
19
+ /**
20
+ * Renders one or more schema.org JSON-LD nodes into a
21
+ * `<script type="application/ld+json">`. Works in server and client components.
22
+ *
23
+ * @example
24
+ * <JsonLd data={faqPage(items)} />
25
+ * <JsonLd data={[organization(org), website(site)]} />
26
+ */
27
+ export function JsonLd({ data }: { data: object | object[] }) {
28
+ return (
29
+ <script
30
+ type="application/ld+json"
31
+ // oxlint-disable-next-line no-danger -- serializeJsonLd escapes `<`, so content strings cannot break out of the script tag
32
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
33
+ />
34
+ );
35
+ }
@@ -0,0 +1,203 @@
1
+ import type { Metadata } from "next";
2
+ import { absoluteUrl } from "./url.js";
3
+
4
+ /**
5
+ * Per-site defaults for {@link createMetadata}. Set once, reuse on every page.
6
+ */
7
+ export interface MetadataSiteConfig {
8
+ /** Absolute site origin, e.g. "https://ingram.tech". */
9
+ baseUrl: string;
10
+ /** OpenGraph `siteName`. */
11
+ siteName: string;
12
+ /**
13
+ * `title.template` emitted by `pageMetadata.root()`, e.g. "%s | Acme".
14
+ * Applies to every child page whose title is a plain string.
15
+ */
16
+ titleTemplate?: string;
17
+ /** Site-relative or absolute default OG/Twitter image. */
18
+ defaultImage?: string;
19
+ defaultImageWidth?: number;
20
+ defaultImageHeight?: number;
21
+ /**
22
+ * Default OpenGraph locale, e.g. "en_US". On a multilingual site set the
23
+ * per-page `locale` instead (or as well, as the fallback).
24
+ */
25
+ locale?: string;
26
+ /** Twitter `@handle` for `site`. */
27
+ twitterSite?: string;
28
+ /** Twitter `@handle` for `creator`. */
29
+ twitterCreator?: string;
30
+ }
31
+
32
+ /** Per-page inputs for the bound `pageMetadata` function. */
33
+ export interface PageMetadataInput {
34
+ title: string;
35
+ description: string;
36
+ /** Site-relative path of the page, e.g. "/blog/post". Used for canonical + OG url. */
37
+ path: string;
38
+ /** Overrides the site default image (site-relative or absolute). */
39
+ image?: string;
40
+ type?: "website" | "article";
41
+ keywords?: Metadata["keywords"];
42
+ noIndex?: boolean;
43
+ /**
44
+ * OpenGraph locale for this page, e.g. "fr_BE". Overrides `site.locale` —
45
+ * on a multilingual site `og:locale` has to vary per page.
46
+ */
47
+ locale?: string;
48
+ /**
49
+ * Merged into the generated `alternates` (wins on conflict). The reason it
50
+ * exists: `alternates.languages` is per-page on a localized site, and
51
+ * spreading the result to bolt it on drops the rest of the object.
52
+ * `hreflangAlternates()` returns a ready-made `languages` map.
53
+ */
54
+ alternates?: Partial<NonNullable<Metadata["alternates"]>>;
55
+ /** Merged into the generated `openGraph` (wins on conflict). */
56
+ openGraph?: Partial<NonNullable<Metadata["openGraph"]>>;
57
+ /** Merged into the generated `twitter` (wins on conflict). */
58
+ twitter?: Partial<NonNullable<Metadata["twitter"]>>;
59
+ }
60
+
61
+ /** Inputs for `pageMetadata.root()` — the root-layout metadata. */
62
+ export interface RootMetadataInput {
63
+ /** `title.default` for pages without their own. Defaults to `siteName`. */
64
+ title?: string;
65
+ description?: string;
66
+ /** Extra `Metadata` merged over the generated object (wins on conflict). */
67
+ overrides?: Metadata;
68
+ }
69
+
70
+ /**
71
+ * Returns a `pageMetadata(input)` builder that produces a Next `Metadata`
72
+ * object with a self-referencing canonical, OpenGraph, and Twitter card from
73
+ * one title/description/path. Collapses the boilerplate every site repeats.
74
+ *
75
+ * `pageMetadata.root(input?)` builds the root-layout metadata: `metadataBase`,
76
+ * the default title (plus `titleTemplate` when configured), and description —
77
+ * pages then only set their own title/description/path.
78
+ *
79
+ * @example
80
+ * export const pageMetadata = createMetadata({
81
+ * baseUrl: "https://ingram.tech",
82
+ * siteName: "Ingram Technologies",
83
+ * titleTemplate: "%s | Ingram Technologies",
84
+ * defaultImage: "/images/og.png",
85
+ * twitterSite: "@IngramTech",
86
+ * });
87
+ * // app/layout.tsx:
88
+ * export const metadata = pageMetadata.root({ description: "AI deployment." });
89
+ * // in a page:
90
+ * export const metadata = pageMetadata({ title, description, path: "/services" });
91
+ */
92
+ export function createMetadata(site: MetadataSiteConfig) {
93
+ const absolute = (path: string): string => absoluteUrl(path, site.baseUrl);
94
+
95
+ function pageMetadata(input: PageMetadataInput): Metadata {
96
+ const imagePath = input.image ?? site.defaultImage;
97
+ const imageUrl = imagePath ? absolute(imagePath) : undefined;
98
+ const url = absolute(input.path);
99
+ const locale = input.locale ?? site.locale;
100
+
101
+ return {
102
+ metadataBase: new URL(site.baseUrl),
103
+ title: input.title,
104
+ description: input.description,
105
+ ...(input.keywords ? { keywords: input.keywords } : {}),
106
+ alternates: { canonical: url, ...input.alternates },
107
+ // noindex but follow: keep link equity flowing through the page. Use a
108
+ // full robots override in the page's own metadata for nofollow too.
109
+ ...(input.noIndex ? { robots: { index: false, follow: true } } : {}),
110
+ openGraph: {
111
+ title: input.title,
112
+ description: input.description,
113
+ type: input.type ?? "website",
114
+ url,
115
+ siteName: site.siteName,
116
+ ...(locale ? { locale } : {}),
117
+ ...(imageUrl
118
+ ? {
119
+ images: [
120
+ {
121
+ url: imageUrl,
122
+ width: site.defaultImageWidth ?? 1200,
123
+ height: site.defaultImageHeight ?? 630,
124
+ alt: input.title,
125
+ },
126
+ ],
127
+ }
128
+ : {}),
129
+ ...input.openGraph,
130
+ },
131
+ twitter: {
132
+ card: "summary_large_image",
133
+ title: input.title,
134
+ description: input.description,
135
+ ...(site.twitterSite ? { site: site.twitterSite } : {}),
136
+ ...(site.twitterCreator ? { creator: site.twitterCreator } : {}),
137
+ ...(imageUrl ? { images: [imageUrl] } : {}),
138
+ ...input.twitter,
139
+ },
140
+ };
141
+ }
142
+
143
+ pageMetadata.root = function rootMetadata(input: RootMetadataInput = {}): Metadata {
144
+ const title = input.title ?? site.siteName;
145
+ return {
146
+ metadataBase: new URL(site.baseUrl),
147
+ title: site.titleTemplate
148
+ ? { default: title, template: site.titleTemplate }
149
+ : title,
150
+ ...(input.description ? { description: input.description } : {}),
151
+ ...input.overrides,
152
+ };
153
+ };
154
+
155
+ return pageMetadata;
156
+ }
157
+
158
+ export type PageMetadata = ReturnType<typeof createMetadata>;
159
+
160
+ /** Inputs for {@link ogImageMetadata}. */
161
+ export interface OgImageMetadataInput {
162
+ /** Absolute site origin, e.g. "https://acme.example". */
163
+ baseUrl: string;
164
+ /**
165
+ * Path of the image route — the route the `opengraph-image.tsx` file
166
+ * convention serves, e.g. "/opengraph-image" or "/en/opengraph-image" when
167
+ * the file sits under `app/[locale]/`.
168
+ */
169
+ path: string;
170
+ alt: string;
171
+ /** Defaults to the 1200×630 the `/og` template renders. */
172
+ width?: number;
173
+ height?: number;
174
+ }
175
+
176
+ /**
177
+ * Builds the `openGraph.images` entry for a card served by Next's
178
+ * `opengraph-image` file convention.
179
+ *
180
+ * Next attaches a file-convention image only to the segment that declares it,
181
+ * and a page's own `openGraph` object *replaces* the inherited one rather than
182
+ * merging into it — so any page returning `openGraph` from `generateMetadata`
183
+ * silently loses the card. Build the list once and spread it into every page.
184
+ *
185
+ * `createMetadata`'s `defaultImage` / per-page `image` already do this; reach
186
+ * for the standalone helper when you assemble `Metadata` by hand.
187
+ *
188
+ * @example
189
+ * const images = ogImageMetadata({
190
+ * baseUrl, path: `/${locale}/opengraph-image`, alt: "Acme",
191
+ * });
192
+ * return { title, openGraph: { title, url, images } };
193
+ */
194
+ export function ogImageMetadata(input: OgImageMetadataInput) {
195
+ return [
196
+ {
197
+ url: absoluteUrl(input.path, input.baseUrl),
198
+ width: input.width ?? 1200,
199
+ height: input.height ?? 630,
200
+ alt: input.alt,
201
+ },
202
+ ];
203
+ }
package/src/og.tsx ADDED
@@ -0,0 +1,155 @@
1
+ import { ImageResponse } from "next/og";
2
+
3
+ type ImageResponseOptions = NonNullable<ConstructorParameters<typeof ImageResponse>[1]>;
4
+
5
+ /**
6
+ * A branded Open Graph / Twitter card built with `next/og`. Lives on its own
7
+ * entry (`@ingram-tech/nk-seo/og`) because it imports `next/og` (satori + the
8
+ * resvg wasm) — the package root and `/components` stay free of it.
9
+ *
10
+ * Satori gotcha this template encodes so you don't have to: **every element
11
+ * with more than one child must set `display: "flex"`**, and you may not mix a
12
+ * text node and an element as siblings. The layout below keeps each region a
13
+ * single text node, so titles stay plain strings and the accent is carried by
14
+ * the mark — never by a coloured `<span>` inside the headline.
15
+ */
16
+ export interface OgImageOptions {
17
+ /** The headline. Kept a single text node (no inline markup) for Satori. */
18
+ title: string;
19
+ /** Secondary line under the title. */
20
+ subtitle?: string;
21
+ /** Small label above the title (e.g. a section or category). */
22
+ eyebrow?: string;
23
+ /** Bottom-left footer, e.g. the bare domain. */
24
+ footer?: string;
25
+ /** Brand name shown next to the mark, top-left. */
26
+ wordmark?: string;
27
+ /**
28
+ * Logo image rendered as the top-left mark instead of the accent square.
29
+ * Absolute URL or data URI (Satori fetches it at render time).
30
+ */
31
+ logo?: string;
32
+ /** Accent colour — the mark, and the eyebrow if present. Default indigo. */
33
+ accent?: string;
34
+ background?: string;
35
+ /** Primary text colour. */
36
+ ink?: string;
37
+ /** Secondary text colour (subtitle, footer). */
38
+ muted?: string;
39
+ size?: { width: number; height: number };
40
+ /**
41
+ * Custom fonts, passed through to `ImageResponse` (Satori accepts raw
42
+ * TTF/OTF/WOFF data). Pair with `fontFamily` to actually use them.
43
+ */
44
+ fonts?: ImageResponseOptions["fonts"];
45
+ /** Font family for the whole card. Default "sans-serif". */
46
+ fontFamily?: string;
47
+ }
48
+
49
+ const DEFAULTS = {
50
+ accent: "#565ac9",
51
+ background: "#ffffff",
52
+ ink: "#171717",
53
+ muted: "#8a8a8a",
54
+ size: { width: 1200, height: 630 },
55
+ };
56
+
57
+ /**
58
+ * Returns an `ImageResponse` for use as the body of an `opengraph-image` /
59
+ * `twitter-image` route.
60
+ *
61
+ * @example
62
+ * // app/opengraph-image.tsx
63
+ * import { ogImageResponse } from "@ingram-tech/nk-seo/og";
64
+ * export const size = { width: 1200, height: 630 };
65
+ * export const contentType = "image/png";
66
+ * export default () =>
67
+ * ogImageResponse({
68
+ * title: "Ship faster with Acme",
69
+ * subtitle: "The all-in-one platform for modern teams.",
70
+ * wordmark: "Acme",
71
+ * footer: "example.com",
72
+ * });
73
+ */
74
+ export function ogImageResponse(options: OgImageOptions): ImageResponse {
75
+ const accent = options.accent ?? DEFAULTS.accent;
76
+ const background = options.background ?? DEFAULTS.background;
77
+ const ink = options.ink ?? DEFAULTS.ink;
78
+ const muted = options.muted ?? DEFAULTS.muted;
79
+ const size = options.size ?? DEFAULTS.size;
80
+
81
+ return new ImageResponse(
82
+ <div
83
+ style={{
84
+ width: "100%",
85
+ height: "100%",
86
+ display: "flex",
87
+ flexDirection: "column",
88
+ justifyContent: "space-between",
89
+ background,
90
+ padding: "80px",
91
+ fontFamily: options.fontFamily ?? "sans-serif",
92
+ }}
93
+ >
94
+ <div style={{ display: "flex", alignItems: "center", gap: "20px" }}>
95
+ {options.logo ? (
96
+ <img src={options.logo} width={44} height={44} alt="" />
97
+ ) : (
98
+ <div
99
+ style={{
100
+ width: "44px",
101
+ height: "44px",
102
+ borderRadius: "12px",
103
+ background: accent,
104
+ }}
105
+ />
106
+ )}
107
+ {options.wordmark ? (
108
+ <div style={{ fontSize: "40px", fontWeight: 600, color: ink }}>
109
+ {options.wordmark}
110
+ </div>
111
+ ) : null}
112
+ </div>
113
+
114
+ <div style={{ display: "flex", flexDirection: "column", gap: "24px" }}>
115
+ {options.eyebrow ? (
116
+ <div
117
+ style={{
118
+ fontSize: "28px",
119
+ fontWeight: 600,
120
+ letterSpacing: "0.04em",
121
+ textTransform: "uppercase",
122
+ color: accent,
123
+ }}
124
+ >
125
+ {options.eyebrow}
126
+ </div>
127
+ ) : null}
128
+ <div
129
+ style={{
130
+ fontSize: "76px",
131
+ fontWeight: 700,
132
+ lineHeight: 1.05,
133
+ letterSpacing: "-0.02em",
134
+ color: ink,
135
+ maxWidth: "1000px",
136
+ }}
137
+ >
138
+ {options.title}
139
+ </div>
140
+ {options.subtitle ? (
141
+ <div style={{ fontSize: "34px", color: muted, maxWidth: "900px" }}>
142
+ {options.subtitle}
143
+ </div>
144
+ ) : null}
145
+ </div>
146
+
147
+ {options.footer ? (
148
+ <div style={{ fontSize: "30px", color: muted }}>{options.footer}</div>
149
+ ) : (
150
+ <div style={{ display: "flex" }} />
151
+ )}
152
+ </div>,
153
+ { ...size, ...(options.fonts ? { fonts: options.fonts } : {}) },
154
+ );
155
+ }
package/src/routes.ts ADDED
@@ -0,0 +1,170 @@
1
+ import type { MetadataRoute } from "next";
2
+ import { absoluteUrl } from "./url.js";
3
+
4
+ /**
5
+ * Route-handler helpers for `app/sitemap.ts` and `app/robots.ts`. Pure — no
6
+ * React — so they live in the package root next to the metadata factory and can
7
+ * be imported by route handlers freely.
8
+ *
9
+ * Both resolve site-relative paths against one `baseUrl` (pass your deployment's
10
+ * own origin, e.g. `getServerUrl()`), so preview / sandbox deployments advertise
11
+ * themselves and never leak the production host.
12
+ */
13
+
14
+ type ChangeFrequency = NonNullable<MetadataRoute.Sitemap[number]["changeFrequency"]>;
15
+
16
+ /** hreflang → URL map, keyed by the locale codes Next accepts. */
17
+ export type SitemapLanguages = NonNullable<
18
+ NonNullable<MetadataRoute.Sitemap[number]["alternates"]>["languages"]
19
+ >;
20
+
21
+ /** A sitemap entry. A bare string is shorthand for `{ path }`. */
22
+ export interface SitemapRoute {
23
+ /** Site-relative path (e.g. "/pricing") or an absolute URL. */
24
+ path: string;
25
+ lastModified?: string | Date;
26
+ changeFrequency?: ChangeFrequency;
27
+ /** 0.0–1.0. Defaults to 1 for "/" and {@link SitemapConfig.defaultPriority} otherwise. */
28
+ priority?: number;
29
+ /**
30
+ * Per-locale alternates of this route (hreflang → site-relative path or
31
+ * absolute URL), e.g. `{ en: "/about", fr: "/fr/about" }`. Pairs with
32
+ * `<HreflangLinks>` / `hreflangAlternates` on the page side.
33
+ */
34
+ languages?: SitemapLanguages;
35
+ }
36
+
37
+ export interface SitemapConfig {
38
+ /** Absolute site origin, e.g. "https://example.com". */
39
+ baseUrl: string;
40
+ /** The indexable routes. Strings or `SitemapRoute` objects may be mixed. */
41
+ routes: Array<string | SitemapRoute>;
42
+ /** Applied when an entry omits `lastModified`. */
43
+ lastModified?: string | Date;
44
+ /** Applied when an entry omits `changeFrequency`. */
45
+ defaultChangeFrequency?: ChangeFrequency;
46
+ /** Priority for every non-root entry that omits its own. Default 0.7. */
47
+ defaultPriority?: number;
48
+ }
49
+
50
+ const resolveLanguages = (
51
+ languages: SitemapLanguages,
52
+ baseUrl: string,
53
+ ): SitemapLanguages =>
54
+ // Object.entries/fromEntries erase the hreflang key union; the keys are
55
+ // passed through unchanged (only values are resolved), so restoring it is safe.
56
+ Object.fromEntries(
57
+ Object.entries(languages).map(([locale, path]) => [
58
+ locale,
59
+ path === undefined ? path : absoluteUrl(path, baseUrl),
60
+ ]),
61
+ ) as SitemapLanguages;
62
+
63
+ /**
64
+ * Builds a `MetadataRoute.Sitemap` from a list of routes, resolving relative
65
+ * paths against `baseUrl`. `"/"` defaults to priority 1; every other route
66
+ * defaults to `defaultPriority` (0.7).
67
+ *
68
+ * @example
69
+ * // app/sitemap.ts
70
+ * import { createSitemap } from "@ingram-tech/nk-seo";
71
+ * export default () =>
72
+ * createSitemap({
73
+ * baseUrl: getServerUrl(),
74
+ * routes: ["/", "/pricing", "/docs", "/faq"],
75
+ * });
76
+ */
77
+ export function createSitemap(config: SitemapConfig): MetadataRoute.Sitemap {
78
+ const defaultPriority = config.defaultPriority ?? 0.7;
79
+ return config.routes.map((entry) => {
80
+ const route: SitemapRoute = typeof entry === "string" ? { path: entry } : entry;
81
+ const lastModified = route.lastModified ?? config.lastModified;
82
+ const changeFrequency = route.changeFrequency ?? config.defaultChangeFrequency;
83
+ const priority = route.priority ?? (route.path === "/" ? 1 : defaultPriority);
84
+ if (priority < 0 || priority > 1) {
85
+ throw new RangeError(
86
+ `createSitemap: priority must be between 0 and 1, got ${priority} for "${route.path}"`,
87
+ );
88
+ }
89
+ return {
90
+ url: absoluteUrl(route.path, config.baseUrl),
91
+ ...(lastModified ? { lastModified } : {}),
92
+ ...(changeFrequency ? { changeFrequency } : {}),
93
+ priority,
94
+ ...(route.languages
95
+ ? {
96
+ alternates: {
97
+ languages: resolveLanguages(
98
+ route.languages,
99
+ config.baseUrl,
100
+ ),
101
+ },
102
+ }
103
+ : {}),
104
+ };
105
+ });
106
+ }
107
+
108
+ export interface RobotsConfig {
109
+ /** Absolute site origin, e.g. "https://example.com". */
110
+ baseUrl: string;
111
+ /**
112
+ * Whether this deployment is the canonical production host. When false, the
113
+ * whole site is disallowed so preview / sandbox / branch deployments never
114
+ * get indexed and dilute the real domain with duplicate content. Derive it
115
+ * from `VERCEL_ENV === "production"` (and/or a host check).
116
+ */
117
+ isProduction: boolean;
118
+ /**
119
+ * Prod-only disallow list (private routes, APIs, auth flows). Entries that
120
+ * would block `/_next` are rejected: crawlers must reach the JS/CSS under it
121
+ * to render pages, so disallowing it silently harms indexing.
122
+ */
123
+ disallow?: string[];
124
+ /** Prod allow rule. Default "/". */
125
+ allow?: string | string[];
126
+ /** Sitemap path advertised in prod. Default "/sitemap.xml". Pass null to omit. */
127
+ sitemapPath?: string | null;
128
+ }
129
+
130
+ /**
131
+ * Builds a `MetadataRoute.Robots`. On non-production hosts it returns a
132
+ * blanket `Disallow: /` — the single most-forgotten SEO safeguard on Vercel,
133
+ * where preview and branch URLs are otherwise crawlable and compete with the
134
+ * production domain.
135
+ *
136
+ * @example
137
+ * // app/robots.ts
138
+ * import { createRobots } from "@ingram-tech/nk-seo";
139
+ * export default () =>
140
+ * createRobots({
141
+ * baseUrl: getServerUrl(),
142
+ * isProduction: process.env.VERCEL_ENV === "production",
143
+ * disallow: ["/api/", "/internal/", "/login"],
144
+ * });
145
+ */
146
+ export function createRobots(config: RobotsConfig): MetadataRoute.Robots {
147
+ if (!config.isProduction) {
148
+ return { rules: { userAgent: "*", disallow: "/" } };
149
+ }
150
+ const nextAsset = config.disallow?.find((path) =>
151
+ path.trim().replace(/^\//, "").startsWith("_next"),
152
+ );
153
+ if (nextAsset !== undefined) {
154
+ throw new Error(
155
+ `createRobots: refusing to disallow "${nextAsset}". Blocking /_next stops ` +
156
+ "crawlers from fetching the JS/CSS they need to render your pages, which " +
157
+ "hurts indexing. Next.js does not block it by default and neither should you.",
158
+ );
159
+ }
160
+ const sitemapPath =
161
+ config.sitemapPath === undefined ? "/sitemap.xml" : config.sitemapPath;
162
+ return {
163
+ rules: {
164
+ userAgent: "*",
165
+ allow: config.allow ?? "/",
166
+ ...(config.disallow?.length ? { disallow: config.disallow } : {}),
167
+ },
168
+ ...(sitemapPath ? { sitemap: absoluteUrl(sitemapPath, config.baseUrl) } : {}),
169
+ };
170
+ }