@usethrottle/builder-react 0.4.2 → 0.5.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.
@@ -1,5 +1,5 @@
1
1
  import { ComponentType, ReactNode } from 'react';
2
- import { WidgetDefinition, WidgetNode, SettingValue, DataSourceDescriptor, PageDocument, FrozenAsset, SavedSectionsAnswer, CodeRuntimeAnswer } from '@usethrottle/builder-schema';
2
+ import { TemplateName, RootNode, StoreRoutes, WidgetDefinition, WidgetNode, SettingValue, DataSourceDescriptor, PageDocument, FrozenAsset, SavedSectionsAnswer, CodeRuntimeAnswer } from '@usethrottle/builder-schema';
3
3
  import { BuilderClient, BuilderBundle } from '@usethrottle/builder';
4
4
 
5
5
  /** A count of rendered nodes with a ceiling. One per custom widget render. */
@@ -19,6 +19,74 @@ declare class RenderBudget {
19
19
  */
20
20
  type Budget = Pick<RenderBudget, 'limit' | 'used' | 'exhausted' | 'take'>;
21
21
 
22
+ /** The route a template loader serves: the matched path, its dynamic params and the query string. */
23
+ type TemplateRoute = {
24
+ path: string;
25
+ params: Record<string, string>;
26
+ query: Record<string, string | string[]>;
27
+ };
28
+ /**
29
+ * What a template's widgets read (spec §5.1): the loaded catalog or shopper data of the route. Each field
30
+ * is plain data a loader resolved on the server; the owning stream (T-P, T-L, T-A) narrows its own field.
31
+ */
32
+ type TemplateContext = {
33
+ product?: unknown;
34
+ listing?: unknown;
35
+ cart?: unknown;
36
+ customer?: unknown;
37
+ route: TemplateRoute;
38
+ };
39
+ /** The answer of a template loader. */
40
+ type TemplateLoadResult = {
41
+ status: 'ok';
42
+ context: TemplateContext;
43
+ } | {
44
+ status: 'not-found';
45
+ } | {
46
+ status: 'redirect';
47
+ to: string;
48
+ } | {
49
+ status: 'unavailable';
50
+ };
51
+ /** Reads what one template needs for one request. */
52
+ type TemplateLoader = (args: {
53
+ params: Record<string, string | string[] | undefined>;
54
+ searchParams: Record<string, string | string[] | undefined>;
55
+ route: TemplateRoute;
56
+ }) => Promise<TemplateLoadResult>;
57
+ /** The sections of a document: what `PageDocument.sections` holds. */
58
+ type DocumentNodes = RootNode[];
59
+ /** What a widget pack contributes for one template: its loader and its default composition. */
60
+ type PackTemplateContribution = {
61
+ name: TemplateName;
62
+ loader: TemplateLoader;
63
+ /** The pack's default composition of the template, optionally one of its `variants`. */
64
+ defaultComposition: (variant?: string) => DocumentNodes;
65
+ variants?: string[];
66
+ /**
67
+ * A component the template body is rendered inside, once, for state its widgets share (the product page's selected
68
+ * variant, a listing's filters): `createBuilderRoute` and `BuilderTemplate` draw
69
+ * `<Root context document>{template body}</Root>`, on the server, for the loaded template, its unavailable state
70
+ * and the pack's default composition. `document` is the template's `PageDocument`. A client component reference
71
+ * is fine; it receives plain data only. Without it the body is drawn as it is.
72
+ */
73
+ Root?: ComponentType<{
74
+ context: TemplateContext;
75
+ document: unknown;
76
+ children: ReactNode;
77
+ }>;
78
+ };
79
+ /** What the store hands the template route (spec §5.1). */
80
+ type BuilderRouteConfig = {
81
+ site: LoadedSite;
82
+ packs: readonly WidgetPack[];
83
+ /** Catalog route prefixes the store serves (`shop`, `collection`, ...), by template name. */
84
+ catalogRoutes?: Partial<Record<TemplateName, string>>;
85
+ /** Paths of the store templates the merchant renamed (`routes.store`). */
86
+ storeRoutes?: Partial<StoreRoutes>;
87
+ loaders: Partial<Record<TemplateName, TemplateLoader>>;
88
+ };
89
+
22
90
  /** Resolved data by binding key (`bindingKey`), plus `context.*` entries a slot supplies. */
23
91
  type DataMap = Record<string, unknown>;
24
92
  type WidgetRenderProps = {
@@ -85,6 +153,8 @@ type WidgetPack = {
85
153
  dataSources: PackDataSource[];
86
154
  linkTargets?: LinkTargetProvider;
87
155
  slots?: SlotPoint[];
156
+ /** The templates the pack contributes: loaders and default compositions (spec §5.1). */
157
+ templates?: PackTemplateContribution[];
88
158
  };
89
159
  /** A page document as the store reads it (a published snapshot). */
90
160
  type PageAssets = Record<string, FrozenAsset>;
@@ -129,10 +199,19 @@ type LoadedSite = {
129
199
  locale: string;
130
200
  generation: number;
131
201
  siteVersion: number;
202
+ /**
203
+ * The instant `loadSite` read the site (ISO 8601, stamped on the server). Time rules (announcement schedules)
204
+ * are evaluated at this instant while rendering, so server HTML and the first client render agree.
205
+ */
206
+ loadedAt?: string;
132
207
  /** The origin media files must be on (https). Images from anywhere else are refused. */
133
208
  mediaOrigin: string;
134
209
  /** Site settings resolved for the locale (localized values are strings). */
135
210
  settings: Record<string, unknown>;
211
+ /** The site answer's `theme` (beside `settings`): `customCssHref` is the Builder's stylesheet for CSS over 4 KB. */
212
+ theme?: {
213
+ customCssHref?: string;
214
+ };
136
215
  header: LoadedPart;
137
216
  footer: LoadedPart;
138
217
  slots: Record<string, LoadedPart>;
@@ -154,6 +233,12 @@ type ClientOptions = {
154
233
  builderKey?: string | undefined;
155
234
  };
156
235
 
236
+ type CanonicalKind = 'page' | 'listing' | 'product' | 'search';
237
+ /**
238
+ * The canonical form of a URL the store is serving: no fragment, and no query except `?page` on a listing, so sort,
239
+ * filter and tracking parameters all canonicalize to the listing itself (spec §11.4: listing pages keep `?page=`).
240
+ */
241
+ declare function canonicalFor(url: string | URL, kind: CanonicalKind): string;
157
242
  /** A store's own answer for where a page lives: it gets the default and returns a site path (or null for the default). */
158
243
  type PagePathResolver = (page: {
159
244
  slug: string;
@@ -161,4 +246,4 @@ type PagePathResolver = (page: {
161
246
  path: string;
162
247
  }) => string | null | undefined;
163
248
 
164
- export { type BundleAsk as B, type ClientOptions as C, type LoadedPage as L, type PagePathResolver as P, type WidgetPack as W, type LoadedRedirect as a, type LoadedSite as b, getBundle as g };
249
+ export { type BuilderRouteConfig as B, type CanonicalKind as C, type LoadedPage as L, type PagePathResolver as P, type TemplateContext as T, type WidgetPack as W, type BundleAsk as a, type ClientOptions as b, type LoadedPart as c, type LoadedRedirect as d, type LoadedSite as e, canonicalFor as f, getBundle as g };
package/dist/server.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
4
 
@@ -12,70 +12,155 @@
12
12
 
13
13
 
14
14
 
15
- var _chunkXHTZWZPNcjs = require('./chunk-XHTZWZPN.cjs');
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+ var _chunkUNL4JWZScjs = require('./chunk-UNL4JWZS.cjs');
16
26
 
17
27
  // src/server/load-site.ts
18
28
  var _builder = require('@usethrottle/builder');
29
+ function siteThemeOf(site) {
30
+ const theme = site.theme;
31
+ return typeof _optionalChain([theme, 'optionalAccess', _2 => _2.customCssHref]) === "string" ? { theme: { customCssHref: theme.customCssHref } } : {};
32
+ }
19
33
  async function loadSite(options) {
20
34
  const { locale, slots = [], packs = [], page, mediaOrigin = "", currency } = options;
21
- const client = _chunkXHTZWZPNcjs.clientOf.call(void 0, options);
35
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
22
36
  let bundle;
23
37
  try {
24
- bundle = await _chunkXHTZWZPNcjs.getBundle.call(void 0, { client, locale, slots, page });
38
+ bundle = await _chunkUNL4JWZScjs.getBundle.call(void 0, { client, locale, slots, page });
25
39
  } catch (error) {
26
40
  if (!(error instanceof _builder.BuilderUnavailableError) || client.mode === "build") throw error;
27
- _chunkXHTZWZPNcjs.warnOnce.call(void 0, "site-unavailable", `The Builder could not be read (${error.reason}); the store renders without its Builder header, footer and slots`);
41
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "site-unavailable", `The Builder could not be read (${error.reason}); the store renders without its Builder header, footer and slots`);
28
42
  return { status: "unavailable", locale };
29
43
  }
30
- const registry = _chunkXHTZWZPNcjs.createRendererRegistry.call(void 0, packs);
44
+ const registry = _chunkUNL4JWZScjs.createRendererRegistry.call(void 0, packs);
31
45
  const names = Object.keys(bundle.slots);
32
46
  const withShared = (loaded) => ({
33
47
  ...loaded,
34
48
  ...(_nullishCoalesce(loaded.savedSections, () => ( bundle.savedSections))) === void 0 ? {} : { savedSections: _nullishCoalesce(loaded.savedSections, () => ( bundle.savedSections)) }
35
49
  });
36
50
  const documents = [bundle.header, bundle.footer, ...names.map((n) => bundle.slots[n])].map(withShared);
37
- const data = await _chunkXHTZWZPNcjs.staticDataFor.call(void 0, documents, registry, locale, currency);
51
+ const data = await _chunkUNL4JWZScjs.staticDataFor.call(void 0, documents, registry, locale, currency);
38
52
  return {
39
53
  status: "ok",
40
54
  locale,
41
55
  generation: bundle.generation,
42
56
  siteVersion: bundle.site.siteVersion,
57
+ loadedAt: (/* @__PURE__ */ new Date()).toISOString(),
43
58
  mediaOrigin,
44
59
  settings: bundle.site.settings,
45
- header: _chunkXHTZWZPNcjs.partOf.call(void 0, bundle.header, data, bundle),
46
- footer: _chunkXHTZWZPNcjs.partOf.call(void 0, bundle.footer, data, bundle),
47
- slots: Object.fromEntries(names.map((name) => [name, _chunkXHTZWZPNcjs.partOf.call(void 0, bundle.slots[name], data, bundle)]))
60
+ ...siteThemeOf(bundle.site),
61
+ header: _chunkUNL4JWZScjs.partOf.call(void 0, bundle.header, data, bundle),
62
+ footer: _chunkUNL4JWZScjs.partOf.call(void 0, bundle.footer, data, bundle),
63
+ slots: Object.fromEntries(names.map((name) => [name, _chunkUNL4JWZScjs.partOf.call(void 0, bundle.slots[name], data, bundle)]))
48
64
  };
49
65
  }
50
66
 
51
67
  // src/server/sitemap.ts
52
68
 
53
- async function builderSitemap(options) {
69
+ var SITEMAP_MAX_URLS = 5e4;
70
+ var isRec = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
71
+ function sitemapRulesOf(settings) {
72
+ const seo = isRec(settings.seo) ? settings.seo : {};
73
+ const rules = isRec(seo.sitemap) ? seo.sitemap : {};
74
+ return { pages: rules.pages !== false, exclude: Array.isArray(rules.exclude) ? rules.exclude.filter((x) => typeof x === "string") : [] };
75
+ }
76
+ function excluded(rules, pathname, slug) {
77
+ return rules.some((rule) => {
78
+ if (rule.startsWith("/")) return rule.endsWith("*") ? pathname.startsWith(rule.slice(0, -1)) : pathname === rule || pathname === `${rule}/`;
79
+ return slug !== void 0 && rule === slug;
80
+ });
81
+ }
82
+ var xmlEscape = (text) => text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
83
+ function safeLoc(loc, origin) {
84
+ try {
85
+ const parsed = new URL(loc);
86
+ return parsed.origin === origin ? xmlEscape(parsed.href) : null;
87
+ } catch (e) {
88
+ return null;
89
+ }
90
+ }
91
+ var pathnameOf = (url) => {
92
+ try {
93
+ return new URL(url).pathname;
94
+ } catch (e2) {
95
+ return url;
96
+ }
97
+ };
98
+ async function builderSitemapParts(options, extras = {}) {
99
+ const origin = _chunkUNL4JWZScjs.originOf.call(void 0, options.storeUrl);
100
+ const entries = await pageEntries(options, origin);
101
+ if (origin === void 0) return { parts: [] };
102
+ const rules = sitemapRulesOf(await settingsOf(options));
103
+ const seen = new Set(entries.map((entry) => entry.url));
104
+ for (const contributor of _nullishCoalesce(extras.contributors, () => ( []))) {
105
+ try {
106
+ for await (const item of contributor()) {
107
+ const loc = typeof item.loc === "string" ? safeLoc(item.loc, origin) : null;
108
+ if (loc === null || seen.has(loc)) continue;
109
+ if (excluded(rules.exclude, pathnameOf(loc))) continue;
110
+ seen.add(loc);
111
+ const when = item.lastmod === void 0 ? void 0 : new Date(item.lastmod);
112
+ entries.push({ url: loc, ...when === void 0 || Number.isNaN(when.getTime()) ? {} : { lastModified: when } });
113
+ }
114
+ } catch (error) {
115
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "sitemap-contributor", `A sitemap contributor failed (${error instanceof Error ? error.message : "unknown error"}); the sitemap leaves out its URLs`);
116
+ }
117
+ }
118
+ const parts = [];
119
+ for (let from = 0; from < entries.length; from += SITEMAP_MAX_URLS) parts.push(entries.slice(from, from + SITEMAP_MAX_URLS));
120
+ if (parts.length < 2) return { parts };
121
+ const items = parts.map((_, index) => `<sitemap><loc>${xmlEscape(origin)}/sitemap/${String(index)}.xml</loc></sitemap>`).join("");
122
+ return { parts, indexXml: `<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${items}</sitemapindex>` };
123
+ }
124
+ async function builderSitemap(options, extras = {}) {
125
+ return (await builderSitemapParts(options, extras)).parts.flat();
126
+ }
127
+ async function settingsOf(options) {
128
+ try {
129
+ return (await _chunkUNL4JWZScjs.clientOf.call(void 0, options).site({ locale: _nullishCoalesce(options.locale, () => ( "en")) })).settings;
130
+ } catch (e3) {
131
+ return {};
132
+ }
133
+ }
134
+ async function pageEntries(options, origin) {
54
135
  if (options.client === void 0 && (options.builderKey === void 0 || options.builderKey === "")) {
55
- _chunkXHTZWZPNcjs.warnOnce.call(void 0, "sitemap-no-key", "builderSitemap has no builderKey (is THROTTLE_BUILDER_KEY set?); the sitemap leaves out the Builder pages");
136
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "sitemap-no-key", "builderSitemap has no builderKey (is THROTTLE_BUILDER_KEY set?); the sitemap leaves out the Builder pages");
56
137
  return [];
57
138
  }
58
- const client = _chunkXHTZWZPNcjs.clientOf.call(void 0, options);
59
- const origin = _chunkXHTZWZPNcjs.originOf.call(void 0, options.storeUrl);
139
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
60
140
  if (origin === void 0) {
61
- _chunkXHTZWZPNcjs.warnOnce.call(void 0, "sitemap-origin", "builderSitemap needs a storeUrl (https://shop.example.com) that is an http(s) origin. The Builder does not publish the store URL.");
141
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "sitemap-origin", "builderSitemap needs a storeUrl (https://shop.example.com) that is an http(s) origin. The Builder does not publish the store URL.");
62
142
  return [];
63
143
  }
64
144
  const locale = _nullishCoalesce(options.locale, () => ( "en"));
65
145
  try {
66
146
  const pages = await client.pages.list();
67
147
  const { settings } = await client.site({ locale });
148
+ const rules = sitemapRulesOf(settings);
149
+ if (!rules.pages) return [];
68
150
  const indexable = await withoutNoindex(client, pages, locale);
69
- const { list } = _chunkXHTZWZPNcjs.siteLocales.call(void 0, settings);
151
+ const { list } = _chunkUNL4JWZScjs.siteLocales.call(void 0, settings);
70
152
  const prefixes = options.localeRoute !== true ? [void 0] : list.length > 0 ? list : [locale];
71
153
  return indexable.flatMap((page) => {
72
- const path = _chunkXHTZWZPNcjs.pagePathOf.call(void 0, settings, page, options.pagePath);
73
- if (path === null) return [];
74
- return prefixes.map((prefix) => ({ url: `${origin}${_chunkXHTZWZPNcjs.localized.call(void 0, path, prefix)}`, lastModified: new Date(page.updatedAt) }));
154
+ const path = _chunkUNL4JWZScjs.pagePathOf.call(void 0, settings, page, options.pagePath);
155
+ if (path === null || excluded(rules.exclude, path, page.slug)) return [];
156
+ return prefixes.flatMap((prefix) => {
157
+ const url = safeLoc(`${origin}${_chunkUNL4JWZScjs.localized.call(void 0, path, prefix)}`, origin);
158
+ return url === null ? [] : [{ url, lastModified: new Date(page.updatedAt) }];
159
+ });
75
160
  });
76
161
  } catch (error) {
77
162
  if (!(error instanceof _builder.BuilderUnavailableError) || client.mode === "build") throw error;
78
- _chunkXHTZWZPNcjs.warnOnce.call(void 0, "sitemap-unavailable", `The Builder could not be read (${error.reason}); the sitemap leaves out its pages`);
163
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "sitemap-unavailable", `The Builder could not be read (${error.reason}); the sitemap leaves out its pages`);
79
164
  return [];
80
165
  }
81
166
  }
@@ -89,22 +174,88 @@ async function withoutNoindex(client, pages, locale) {
89
174
  slice.map(
90
175
  (page) => client.pages.get(page.slug, { locale }).catch((error) => {
91
176
  if (error instanceof _builder.BuilderNotFoundError) return "gone";
92
- _chunkXHTZWZPNcjs.warnOnce.call(void 0, "sitemap-page-read", `A page could not be read for the sitemap (${error instanceof Error ? error.message : "unknown error"}); it stays listed`);
177
+ _chunkUNL4JWZScjs.warnOnce.call(void 0, "sitemap-page-read", `A page could not be read for the sitemap (${error instanceof Error ? error.message : "unknown error"}); it stays listed`);
93
178
  return void 0;
94
179
  })
95
180
  )
96
181
  );
97
182
  slice.forEach((page, index) => {
98
183
  const answer = answers[index];
99
- if (answer === "gone" || answer !== void 0 && (_chunkXHTZWZPNcjs.isRedirect.call(void 0, answer) || _chunkXHTZWZPNcjs.pageSeoOf.call(void 0, answer).noindex)) skip.add(page.slug);
184
+ if (answer === "gone" || answer !== void 0 && (_chunkUNL4JWZScjs.isRedirect.call(void 0, answer) || _chunkUNL4JWZScjs.pageSeoOf.call(void 0, answer).noindex)) skip.add(page.slug);
100
185
  });
101
186
  }
102
187
  return pages.filter((page) => !skip.has(page.slug));
103
188
  }
104
189
 
190
+ // src/server/robots.ts
191
+ var isRec2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
192
+ var DEFAULT_ROBOTS_DISALLOW = [
193
+ "/cart",
194
+ "/account",
195
+ "/sign-in",
196
+ "/sign-up",
197
+ "/order/",
198
+ "/search"
199
+ ];
200
+ var MAX_EXTRA_LINES = 50;
201
+ var MAX_LINE = 200;
202
+ var CONTROL = new RegExp(`[\\x00-\\x1F\\x7F\\x85${String.fromCharCode(8232, 8233)}]`, "u");
203
+ var DIRECTIVE = /^(?:(?:User-agent|Allow|Disallow|Crawl-delay|Sitemap)\s*:|#)/iu;
204
+ var BLOCKS_ALL = /^Disallow\s*:\s*\/\*?\s*(?:#.*)?$/iu;
205
+ var USER_AGENT = /^User-agent\s*:\s*([^#]*?)\s*(?:#.*)?$/iu;
206
+ var validLine = (value) => typeof value === "string" && value.trim() !== "" && value.length <= MAX_LINE && !CONTROL.test(value);
207
+ function validExtras(values) {
208
+ const kept = [];
209
+ let agents = ["*"];
210
+ let started = false;
211
+ let inRules = false;
212
+ for (const value of values) {
213
+ if (!validLine(value)) continue;
214
+ const line = value.trim();
215
+ if (!DIRECTIVE.test(line)) continue;
216
+ const agent = USER_AGENT.exec(line);
217
+ if (agent !== null) {
218
+ agents = !started || inRules ? [_nullishCoalesce(agent[1], () => ( ""))] : [...agents, _nullishCoalesce(agent[1], () => ( ""))];
219
+ started = true;
220
+ inRules = false;
221
+ } else if (/^(?:Allow|Disallow|Crawl-delay)\s*:/iu.test(line)) {
222
+ if (BLOCKS_ALL.test(line) && agents.includes("*")) continue;
223
+ inRules = true;
224
+ }
225
+ kept.push(line);
226
+ }
227
+ return kept;
228
+ }
229
+ var validDisallow = (value) => validLine(value) && value.trim() !== "/";
230
+ function siteOriginOf(site, options = {}) {
231
+ const settings = _nullishCoalesce(site.settings, () => ( {}));
232
+ const seo = isRec2(settings.seo) ? settings.seo : {};
233
+ return _nullishCoalesce(_nullishCoalesce(_chunkUNL4JWZScjs.originOf.call(void 0, typeof seo.canonicalBase === "string" ? seo.canonicalBase : void 0), () => ( _chunkUNL4JWZScjs.originOf.call(void 0, options.storeUrl))), () => ( _chunkUNL4JWZScjs.originOf.call(void 0, typeof settings.storeUrl === "string" ? settings.storeUrl : void 0)));
234
+ }
235
+ function builderRobots(site, options = {}) {
236
+ const settings = _nullishCoalesce(site.settings, () => ( {}));
237
+ const seo = isRec2(settings.seo) ? settings.seo : {};
238
+ const robots = isRec2(seo.robots) ? seo.robots : {};
239
+ const disallow = Array.isArray(robots.disallow) ? robots.disallow.filter(validDisallow) : [...DEFAULT_ROBOTS_DISALLOW];
240
+ const extra = Array.isArray(robots.extra) ? validExtras(robots.extra).slice(0, MAX_EXTRA_LINES) : [];
241
+ const origin = siteOriginOf(site, options);
242
+ return [
243
+ "User-agent: *",
244
+ ...disallow.map((path) => `Disallow: ${path}`),
245
+ ...origin === void 0 ? [] : [`Sitemap: ${origin}/sitemap.xml`],
246
+ ...extra,
247
+ ""
248
+ ].join("\n");
249
+ }
250
+ function builderRobotsResponse(site, options = {}) {
251
+ return new Response(builderRobots(site, options), {
252
+ headers: { "content-type": "text/plain; charset=utf-8" }
253
+ });
254
+ }
255
+
105
256
  // src/server/static-params.ts
106
257
  async function builderStaticParams(options) {
107
- const client = _chunkXHTZWZPNcjs.clientOf.call(void 0, options);
258
+ const client = _chunkUNL4JWZScjs.clientOf.call(void 0, options);
108
259
  if (client.mode !== "build")
109
260
  throw new TypeError(
110
261
  'builderStaticParams generates every page of a frozen release: give it a client made with createBuilderClient({ mode: "build" }). A live store keeps its pages dynamic.'
@@ -123,4 +274,20 @@ async function builderStaticParams(options) {
123
274
 
124
275
 
125
276
 
126
- exports.BuilderNotFoundError = _builder.BuilderNotFoundError; exports.BuilderUnavailableError = _builder.BuilderUnavailableError; exports.builderSitemap = builderSitemap; exports.builderStaticParams = builderStaticParams; exports.getBundle = _chunkXHTZWZPNcjs.getBundle; exports.loadBuilderPage = _chunkXHTZWZPNcjs.loadBuilderPage; exports.loadSite = loadSite;
277
+
278
+
279
+
280
+
281
+
282
+
283
+
284
+
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+ exports.BuilderNotFoundError = _builder.BuilderNotFoundError; exports.BuilderUnavailableError = _builder.BuilderUnavailableError; exports.DEFAULT_ROBOTS_DISALLOW = DEFAULT_ROBOTS_DISALLOW; exports.SITEMAP_MAX_URLS = SITEMAP_MAX_URLS; exports.breadcrumbJsonLd = _chunkUNL4JWZScjs.breadcrumbJsonLd; exports.builderRobots = builderRobots; exports.builderRobotsResponse = builderRobotsResponse; exports.builderSitemap = builderSitemap; exports.builderSitemapParts = builderSitemapParts; exports.builderStaticParams = builderStaticParams; exports.faqJsonLd = _chunkUNL4JWZScjs.faqJsonLd; exports.getBundle = _chunkUNL4JWZScjs.getBundle; exports.isOwnPath = _chunkUNL4JWZScjs.isOwnPath; exports.jsonLdString = _chunkUNL4JWZScjs.jsonLdString; exports.loadBuilderPage = _chunkUNL4JWZScjs.loadBuilderPage; exports.loadBuilderPageByPath = _chunkUNL4JWZScjs.loadBuilderPageByPath; exports.loadBuilderTemplate = _chunkUNL4JWZScjs.loadBuilderTemplate; exports.loadOwnPagePaths = _chunkUNL4JWZScjs.loadOwnPagePaths; exports.loadSite = loadSite; exports.localBusinessJsonLd = _chunkUNL4JWZScjs.localBusinessJsonLd; exports.organizationJsonLd = _chunkUNL4JWZScjs.organizationJsonLd; exports.siteOriginOf = siteOriginOf; exports.webSiteJsonLd = _chunkUNL4JWZScjs.webSiteJsonLd;
package/dist/server.d.cts CHANGED
@@ -1,8 +1,9 @@
1
- import { C as ClientOptions, W as WidgetPack, b as LoadedSite, L as LoadedPage, a as LoadedRedirect, P as PagePathResolver } from './seo-CNZ9DrlU.cjs';
2
- export { B as BundleAsk, g as getBundle } from './seo-CNZ9DrlU.cjs';
1
+ import { b as ClientOptions, W as WidgetPack, e as LoadedSite, L as LoadedPage, d as LoadedRedirect, c as LoadedPart, P as PagePathResolver } from './seo-iX2POfOp.cjs';
2
+ export { a as BundleAsk, g as getBundle } from './seo-iX2POfOp.cjs';
3
+ import { TemplateAnswer } from '@usethrottle/builder';
3
4
  export { BuilderNotFoundError, BuilderUnavailableError } from '@usethrottle/builder';
5
+ import { TemplateName } from '@usethrottle/builder-schema';
4
6
  import 'react';
5
- import '@usethrottle/builder-schema';
6
7
 
7
8
  type LoadSiteOptions = ClientOptions & {
8
9
  locale: string;
@@ -43,6 +44,19 @@ type LoadBuilderPageOptions = ClientOptions & {
43
44
  /** The shopper's currency, as for `loadSite({ currency })`. */
44
45
  currency?: string;
45
46
  };
47
+ /** A page's own path (`/about`, D39): not the legacy `/` and `/pages/...` answers the page route covers. */
48
+ declare const isOwnPath: (path: unknown) => path is string;
49
+ /**
50
+ * Reads the page that answers at its own path, or the redirect of an older path of a page (`slug_redirects`).
51
+ * Uses the client's `pages.getByPath` when it has one; otherwise the page list (its summaries carry `path`), which
52
+ * also answers a 308 for a listed slug whose own path has moved. An older path that is no longer any page's slug
53
+ * is only found by `getByPath` (no Worker call is made per unknown path). Rejects with `BuilderNotFoundError` when nothing is at the path.
54
+ */
55
+ declare function loadBuilderPageByPath(options: Omit<LoadBuilderPageOptions, 'slug'> & {
56
+ path: string;
57
+ }): Promise<LoadedPage | LoadedRedirect>;
58
+ /** The own paths (`/about`) of the published pages, for `BuilderProvider`'s `ownPagePaths`. */
59
+ declare function loadOwnPagePaths(options: ClientOptions): Promise<string[]>;
46
60
  /**
47
61
  * Reads one published page for a request. Data of the page's non-perShopper
48
62
  * sources is resolved here, each distinct binding once, into `initialData`;
@@ -54,6 +68,25 @@ type LoadBuilderPageOptions = ClientOptions & {
54
68
  */
55
69
  declare function loadBuilderPage(options: LoadBuilderPageOptions): Promise<LoadedPage | LoadedRedirect>;
56
70
 
71
+ type LoadBuilderTemplateOptions = ClientOptions & {
72
+ name: TemplateName;
73
+ locale: string;
74
+ packs?: readonly WidgetPack[];
75
+ /** The shopper's currency, as for `loadBuilderPage`. */
76
+ currency?: string | undefined;
77
+ /** What the bundle answer holds once for every document (saved sections, code runtime). */
78
+ shared?: Pick<TemplateAnswer, 'savedSections' | 'code'>;
79
+ };
80
+ /**
81
+ * Reads one published template (`client.getTemplate`) for a request, with the data of its non-perShopper sources
82
+ * resolved once. `context.*` bindings are the loader's and are not resolved here. An unpublished template is an empty
83
+ * document, never an error; `BuilderUnavailableError` is the client's own answer when it has no last good one.
84
+ */
85
+ declare function loadBuilderTemplate(options: LoadBuilderTemplateOptions): Promise<{
86
+ part: LoadedPart;
87
+ meta: TemplateAnswer['meta'];
88
+ }>;
89
+
57
90
  type BuilderSitemapOptions = ClientOptions & {
58
91
  /** The store's origin (`https://shop.example.com`). The Builder does not publish it, so it is required: without a valid one the sitemap is empty. */
59
92
  storeUrl?: string;
@@ -67,11 +100,142 @@ type BuilderSitemapOptions = ClientOptions & {
67
100
  /** Where your store serves a page, as for `createBuilderPage`. Pass the same function. */
68
101
  pagePath?: PagePathResolver;
69
102
  };
70
- /** The published pages as sitemap entries. An unavailable Builder, or no key at all, gives an empty list and a warning, never a failed sitemap (a build-mode client fails the build instead). */
71
- declare function builderSitemap(options: BuilderSitemapOptions): Promise<{
103
+ /** URLs per sitemap file (the sitemaps.org limit). */
104
+ declare const SITEMAP_MAX_URLS = 50000;
105
+ /** A source of extra URLs (the catalog pack's products, collections, ...). `loc` is an absolute URL on the store's origin. */
106
+ type SitemapContributor = () => AsyncIterable<{
107
+ loc: string;
108
+ lastmod?: Date | string | undefined;
109
+ }>;
110
+ type BuilderSitemapExtras = {
111
+ contributors?: readonly SitemapContributor[] | undefined;
112
+ };
113
+ type SitemapEntry = {
72
114
  url: string;
73
- lastModified: Date;
74
- }[]>;
115
+ lastModified?: Date;
116
+ };
117
+ /**
118
+ * The sitemap in files of at most 50,000 URLs, with the XML of the sitemap index when there is more than one
119
+ * (`<origin>/sitemap/<n>.xml`, Next's `generateSitemaps` numbering). Pages first, then each contributor; a URL is
120
+ * listed once; a contributor that throws, or answers another origin, loses only that URL or source.
121
+ */
122
+ declare function builderSitemapParts(options: BuilderSitemapOptions, extras?: BuilderSitemapExtras): Promise<{
123
+ parts: SitemapEntry[][];
124
+ indexXml?: string;
125
+ }>;
126
+ /**
127
+ * The published pages (and the contributors' URLs) as sitemap entries. An unavailable Builder, or no key at all, gives an
128
+ * empty list and a warning, never a failed sitemap (a build-mode client fails the build instead). Beyond 50,000 URLs use
129
+ * `builderSitemapParts`.
130
+ */
131
+ declare function builderSitemap(options: BuilderSitemapOptions, extras?: BuilderSitemapExtras): Promise<SitemapEntry[]>;
132
+
133
+ type Rec = Record<string, unknown>;
134
+ /** The default disallow list (spec §11.4). */
135
+ declare const DEFAULT_ROBOTS_DISALLOW: readonly ["/cart", "/account", "/sign-in", "/sign-up", "/order/", "/search"];
136
+ /** The site as the SEO helpers read it: the published settings (v1 or v2; the v2 `seo` fields are all optional). */
137
+ type SeoSite = {
138
+ settings?: Rec | undefined;
139
+ };
140
+ type SeoSiteOptions = {
141
+ /** The store's origin, the base of the `Sitemap:` line when the settings carry no `seo.canonicalBase`. */
142
+ storeUrl?: string | undefined;
143
+ };
144
+ /** The site origin for absolute URLs: `seo.canonicalBase`, else `storeUrl` (an option, then `settings.storeUrl`). */
145
+ declare function siteOriginOf(site: SeoSite, options?: SeoSiteOptions): string | undefined;
146
+ /**
147
+ * The text of `robots.txt`: `User-agent: *`, the disallow list (the site's, else the default), a `Sitemap:` line, then up
148
+ * to 50 extra lines the merchant wrote. An extra line is kept only when it is one plain line that starts with a robots
149
+ * directive (`User-agent`, `Allow`, `Disallow`, `Crawl-delay`, `Sitemap`) or `#`, and is not a bare `Disallow: /`.
150
+ *
151
+ * Next's `app/robots.ts` must return a `MetadataRoute.Robots` object, not text, so do NOT use this there: serve it from
152
+ * `app/robots.txt/route.ts` with `builderRobotsResponse` (or `new Response(builderRobots(...))`).
153
+ */
154
+ declare function builderRobots(site: SeoSite, options?: SeoSiteOptions): string;
155
+ /** `builderRobots` as a `text/plain` response, for an `app/robots.txt/route.ts` handler (`export const GET = ...`). */
156
+ declare function builderRobotsResponse(site: SeoSite, options?: SeoSiteOptions): Response;
157
+
158
+ /** JSON-LD builders (spec §11.4). Each answers a plain object with the schema.org required properties. */
159
+ type JsonLd = Record<string, unknown>;
160
+ declare function organizationJsonLd(input: {
161
+ name: string;
162
+ url: string;
163
+ logo?: string | undefined;
164
+ sameAs?: readonly string[] | undefined;
165
+ }): {
166
+ sameAs?: string[] | undefined;
167
+ logo?: string | undefined;
168
+ '@context': "https://schema.org";
169
+ '@type': "Organization";
170
+ name: string;
171
+ url: string;
172
+ };
173
+ /** `WebSite` with a `SearchAction` that targets the store's search route (`/search?q=` by default). */
174
+ declare function webSiteJsonLd(input: {
175
+ name: string;
176
+ url: string;
177
+ searchPath?: string | undefined;
178
+ }): {
179
+ '@context': "https://schema.org";
180
+ '@type': "WebSite";
181
+ name: string;
182
+ url: string;
183
+ potentialAction: {
184
+ '@type': "SearchAction";
185
+ target: {
186
+ '@type': "EntryPoint";
187
+ urlTemplate: string;
188
+ };
189
+ 'query-input': string;
190
+ };
191
+ };
192
+ declare function breadcrumbJsonLd(items: readonly {
193
+ name: string;
194
+ url: string;
195
+ }[]): {
196
+ '@context': "https://schema.org";
197
+ '@type': "BreadcrumbList";
198
+ itemListElement: {
199
+ '@type': "ListItem";
200
+ position: number;
201
+ name: string;
202
+ item: string;
203
+ }[];
204
+ };
205
+ declare function faqJsonLd(items: readonly {
206
+ question: string;
207
+ answer: string;
208
+ }[]): {
209
+ '@context': "https://schema.org";
210
+ '@type': "FAQPage";
211
+ mainEntity: {
212
+ '@type': "Question";
213
+ name: string;
214
+ acceptedAnswer: {
215
+ '@type': "Answer";
216
+ text: string;
217
+ };
218
+ }[];
219
+ };
220
+ /** `LocalBusiness` (or `Store`): name and address are the required properties. */
221
+ declare function localBusinessJsonLd(input: {
222
+ name: string;
223
+ url: string;
224
+ address: string;
225
+ phone?: string | undefined;
226
+ openingHours?: readonly string[] | undefined;
227
+ type?: 'LocalBusiness' | 'Store' | undefined;
228
+ }): {
229
+ openingHours?: string[] | undefined;
230
+ telephone?: string | undefined;
231
+ '@context': "https://schema.org";
232
+ '@type': "LocalBusiness" | "Store";
233
+ name: string;
234
+ url: string;
235
+ address: string;
236
+ };
237
+ /** The text for `<script type="application/ld+json">`: `<` is escaped so a value cannot close the element. */
238
+ declare function jsonLdString(value: unknown): string;
75
239
 
76
240
  type BuilderStaticParamsOptions = ClientOptions & {
77
241
  /** The dynamic segment of the route, as in `createBuilderPage({ fromParams })`. Default `handle`. */
@@ -92,4 +256,4 @@ type BuilderStaticParamsOptions = ClientOptions & {
92
256
  */
93
257
  declare function builderStaticParams(options: BuilderStaticParamsOptions): Promise<Record<string, string>[]>;
94
258
 
95
- export { type BuilderSitemapOptions, type BuilderStaticParamsOptions, type LoadBuilderPageOptions, type LoadSiteOptions, LoadedPage, LoadedRedirect, LoadedSite, builderSitemap, builderStaticParams, loadBuilderPage, loadSite };
259
+ export { type BuilderSitemapExtras, type BuilderSitemapOptions, type BuilderStaticParamsOptions, DEFAULT_ROBOTS_DISALLOW, type JsonLd, type LoadBuilderPageOptions, type LoadBuilderTemplateOptions, type LoadSiteOptions, LoadedPage, LoadedRedirect, LoadedSite, SITEMAP_MAX_URLS, type SeoSite, type SeoSiteOptions, type SitemapContributor, type SitemapEntry, breadcrumbJsonLd, builderRobots, builderRobotsResponse, builderSitemap, builderSitemapParts, builderStaticParams, faqJsonLd, isOwnPath, jsonLdString, loadBuilderPage, loadBuilderPageByPath, loadBuilderTemplate, loadOwnPagePaths, loadSite, localBusinessJsonLd, organizationJsonLd, siteOriginOf, webSiteJsonLd };