@nulib/canopy 0.0.0 → 2.0.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.
Files changed (141) hide show
  1. package/bin/canopy.js +16 -0
  2. package/lib/AGENTS.md +107 -0
  3. package/lib/base-path.js +67 -0
  4. package/lib/build/appearance.js +76 -0
  5. package/lib/build/assets.js +30 -0
  6. package/lib/build/build.js +350 -0
  7. package/lib/build/dev.js +1355 -0
  8. package/lib/build/devtoast.config.json +6 -0
  9. package/lib/build/devtoast.css +14 -0
  10. package/lib/build/facets.js +19 -0
  11. package/lib/build/fonts.js +105 -0
  12. package/lib/build/iiif.js +2990 -0
  13. package/lib/build/log.js +31 -0
  14. package/lib/build/mdx.js +1967 -0
  15. package/lib/build/package-names.js +111 -0
  16. package/lib/build/pages.js +420 -0
  17. package/lib/build/rehype-task-list-labels.js +54 -0
  18. package/lib/build/runtimes.js +141 -0
  19. package/lib/build/search-index.js +55 -0
  20. package/lib/build/search-text.js +160 -0
  21. package/lib/build/search-workflow.js +72 -0
  22. package/lib/build/search.js +302 -0
  23. package/lib/build/sitemap.js +197 -0
  24. package/lib/build/styles.js +140 -0
  25. package/lib/build/theme-tokens.js +78 -0
  26. package/lib/build/ui-styles.js +25 -0
  27. package/lib/build/upgrade-notices.js +121 -0
  28. package/lib/cli.js +64 -0
  29. package/lib/common.js +580 -0
  30. package/lib/components/bibliography.js +197 -0
  31. package/lib/components/featured.js +237 -0
  32. package/lib/components/hero-slider-runtime.js +215 -0
  33. package/lib/components/image-story-runtime-entry.js +249 -0
  34. package/lib/components/map-runtime.js +114 -0
  35. package/lib/components/metadata-index.js +32 -0
  36. package/lib/components/nav-place.js +227 -0
  37. package/lib/components/navigation.js +381 -0
  38. package/lib/components/referenced.js +217 -0
  39. package/lib/components/slider-runtime-entry.js +106 -0
  40. package/lib/components/timeline-runtime.js +80 -0
  41. package/lib/components/viewer-runtime-entry.js +88 -0
  42. package/lib/config-path.js +78 -0
  43. package/lib/default-locale.js +113 -0
  44. package/lib/discovery/browser-loader.js +107 -0
  45. package/lib/discovery/browser.js +115 -0
  46. package/lib/discovery/config.js +25 -0
  47. package/lib/discovery/envelope.js +124 -0
  48. package/lib/discovery/export.js +226 -0
  49. package/lib/discovery/ingestion.js +62 -0
  50. package/lib/discovery/pagination.js +66 -0
  51. package/lib/discovery/provenance.js +79 -0
  52. package/lib/discovery/search.js +81 -0
  53. package/lib/discovery/tools.js +155 -0
  54. package/lib/discovery/validation.js +121 -0
  55. package/lib/head.js +154 -0
  56. package/lib/iiif/thumbnail.js +402 -0
  57. package/lib/index.js +9 -0
  58. package/lib/locale-runtime.js +69 -0
  59. package/lib/locales.js +203 -0
  60. package/lib/orchestrator.js +231 -0
  61. package/lib/page-context.js +24 -0
  62. package/lib/search/bundle.js +25 -0
  63. package/lib/search/data.js +202 -0
  64. package/lib/search/engine.js +86 -0
  65. package/lib/search/index-cache.js +95 -0
  66. package/lib/search/search-app.jsx +835 -0
  67. package/lib/search/search-engine-runtime.js +44 -0
  68. package/lib/search/search-form-runtime.js +462 -0
  69. package/lib/search/search.js +676 -0
  70. package/package.json +109 -3
  71. package/types/base-path.d.ts +4 -0
  72. package/types/orchestrator.d.ts +17 -0
  73. package/ui/dist/index.mjs +7358 -0
  74. package/ui/dist/index.mjs.map +7 -0
  75. package/ui/dist/server.mjs +12731 -0
  76. package/ui/dist/server.mjs.map +7 -0
  77. package/ui/fonts/OFL.txt +98 -0
  78. package/ui/fonts/google-sans-flex-latin-ext.woff2 +0 -0
  79. package/ui/fonts/google-sans-flex-latin.woff2 +0 -0
  80. package/ui/fonts/source-serif-4-italic-latin-ext.woff2 +0 -0
  81. package/ui/fonts/source-serif-4-italic-latin.woff2 +0 -0
  82. package/ui/fonts/source-serif-4-latin-ext.woff2 +0 -0
  83. package/ui/fonts/source-serif-4-latin.woff2 +0 -0
  84. package/ui/styles/base/_common.scss +97 -0
  85. package/ui/styles/base/_heading.scss +61 -0
  86. package/ui/styles/base/_markdown.scss +188 -0
  87. package/ui/styles/base/_type.scss +51 -0
  88. package/ui/styles/base/_utilities.scss +7 -0
  89. package/ui/styles/base/index.scss +5 -0
  90. package/ui/styles/components/_article-card.scss +108 -0
  91. package/ui/styles/components/_band.scss +104 -0
  92. package/ui/styles/components/_bibliography.scss +88 -0
  93. package/ui/styles/components/_buttons.scss +143 -0
  94. package/ui/styles/components/_card.scss +109 -0
  95. package/ui/styles/components/_diagram.scss +76 -0
  96. package/ui/styles/components/_feature.scss +66 -0
  97. package/ui/styles/components/_footer.scss +136 -0
  98. package/ui/styles/components/_gallery.scss +476 -0
  99. package/ui/styles/components/_image-story.scss +56 -0
  100. package/ui/styles/components/_interstitial-hero.scss +625 -0
  101. package/ui/styles/components/_layout.scss +83 -0
  102. package/ui/styles/components/_map.scss +296 -0
  103. package/ui/styles/components/_metadata-index.scss +68 -0
  104. package/ui/styles/components/_nav-tree.scss +80 -0
  105. package/ui/styles/components/_referenced-items.scss +69 -0
  106. package/ui/styles/components/_sub-navigation.scss +208 -0
  107. package/ui/styles/components/_swoosh.scss +50 -0
  108. package/ui/styles/components/_timeline.scss +350 -0
  109. package/ui/styles/components/_work.scss +71 -0
  110. package/ui/styles/components/header/_header.scss +294 -0
  111. package/ui/styles/components/header/_logo.scss +99 -0
  112. package/ui/styles/components/header/_navbar.scss +143 -0
  113. package/ui/styles/components/header/index.scss +3 -0
  114. package/ui/styles/components/iiif/_image.scss +32 -0
  115. package/ui/styles/components/iiif/_slider.scss +5 -0
  116. package/ui/styles/components/iiif/index.scss +2 -0
  117. package/ui/styles/components/index.scss +25 -0
  118. package/ui/styles/components/modal/_modal.scss +130 -0
  119. package/ui/styles/components/modal/index.scss +1 -0
  120. package/ui/styles/components/search/_filters.scss +259 -0
  121. package/ui/styles/components/search/_form.scss +187 -0
  122. package/ui/styles/components/search/_panel.scss +7 -0
  123. package/ui/styles/components/search/_results.scss +241 -0
  124. package/ui/styles/components/search/_tabs.scss +60 -0
  125. package/ui/styles/components/search/index.scss +4 -0
  126. package/ui/styles/index.css +5007 -0
  127. package/ui/styles/index.scss +11 -0
  128. package/ui/styles/settings/_breakpoints.scss +7 -0
  129. package/ui/styles/settings/_focus.scss +15 -0
  130. package/ui/styles/settings/_tokens.scss +170 -0
  131. package/ui/styles/settings/_type.scss +126 -0
  132. package/ui/styles/version-parity.css +116 -0
  133. package/ui/tailwind-canopy-iiif-plugin.js +39 -0
  134. package/ui/tailwind-canopy-iiif-preset.js +32 -0
  135. package/ui/tailwind-config.d.ts +29 -0
  136. package/ui/tailwind-config.js +159 -0
  137. package/ui/tailwind-default.config.mjs +4 -0
  138. package/ui/theme-color.js +130 -0
  139. package/ui/theme-palette.js +337 -0
  140. package/ui/theme.js +153 -0
  141. package/README.md +0 -3
@@ -0,0 +1,676 @@
1
+ const React = require('react');
2
+ const ReactDOMServer = require('react-dom/server');
3
+ const crypto = require('crypto');
4
+ const {
5
+ fs,
6
+ fsp,
7
+ path,
8
+ CONTENT_DIR,
9
+ rootRelativeHref,
10
+ ensureDirSync,
11
+ OUT_DIR,
12
+ htmlShell,
13
+ canopyBodyClassForType,
14
+ readSearchPageMetadata,
15
+ resolveLocaleFromHref,
16
+ getLocaleRouteEntries,
17
+ getDefaultRoute,
18
+ getDefaultLocaleCode,
19
+ getSiteTitle,
20
+ } = require('../common');
21
+ const {buildLocaleRuntimeScript} = require('../locales');
22
+ const { resolveCanopyConfigPath } = require('../config-path');
23
+ const { flexSearchPlugin } = require('./bundle');
24
+ const { esbuildPackageNames } = require('../build/package-names');
25
+ const { printSearchHeadingNotice } = require('../build/upgrade-notices');
26
+
27
+ const SEARCH_TEMPLATES_ALIAS = '__CANOPY_SEARCH_RESULT_TEMPLATES__';
28
+ const SEARCH_TEMPLATES_CACHE_DIR = path.resolve('.cache/search');
29
+ const SEARCH_TEMPLATE_FILES = [
30
+ { key: 'figure', filename: '_result-figure.mdx' },
31
+ { key: 'article', filename: '_result-article.mdx' },
32
+ ];
33
+
34
+ function resolveSearchTemplatePath(filename) {
35
+ try {
36
+ const candidate = path.join(CONTENT_DIR, 'search', filename);
37
+ if (fs.existsSync(candidate)) return candidate;
38
+ } catch (_) {}
39
+ return null;
40
+ }
41
+
42
+ async function buildSearchTemplatesModule() {
43
+ ensureDirSync(SEARCH_TEMPLATES_CACHE_DIR);
44
+ const outPath = path.join(SEARCH_TEMPLATES_CACHE_DIR, 'result-templates-entry.js');
45
+ const fallback = resolveSearchTemplatePath('_result.mdx');
46
+ const lines = [
47
+ '// Auto-generated search result templates map',
48
+ ];
49
+ for (const spec of SEARCH_TEMPLATE_FILES) {
50
+ const templateName = `${spec.key}Template`;
51
+ const specific = resolveSearchTemplatePath(spec.filename);
52
+ const resolved = specific || fallback;
53
+ if (resolved) {
54
+ lines.push(`import ${templateName} from ${JSON.stringify(resolved)};`);
55
+ } else {
56
+ lines.push(`const ${templateName} = null;`);
57
+ }
58
+ lines.push(`export const ${spec.key} = ${templateName};`);
59
+ }
60
+ lines.push(`export default { ${SEARCH_TEMPLATE_FILES.map((spec) => spec.key).join(', ')} };`);
61
+ await fsp.writeFile(outPath, lines.join('\n'), 'utf8');
62
+ return outPath;
63
+ }
64
+
65
+ function createResultTemplatesAliasPlugin(entryPath) {
66
+ return {
67
+ name: 'canopy-search-result-templates',
68
+ setup(build) {
69
+ build.onResolve({ filter: new RegExp(`^${SEARCH_TEMPLATES_ALIAS.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`) }, () => ({
70
+ path: entryPath,
71
+ }));
72
+ },
73
+ };
74
+ }
75
+
76
+ function createSearchMdxPlugin() {
77
+ return {
78
+ name: 'canopy-search-mdx',
79
+ setup(build) {
80
+ build.onResolve({ filter: /\.mdx$/ }, (args) => ({
81
+ path: path.resolve(args.resolveDir, args.path),
82
+ namespace: 'canopy-search-mdx',
83
+ }));
84
+ build.onLoad({ filter: /.*/, namespace: 'canopy-search-mdx' }, async (args) => {
85
+ const { compile } = await import('@mdx-js/mdx');
86
+ const source = await fsp.readFile(args.path, 'utf8');
87
+ const compiled = await compile(source, {
88
+ jsx: true,
89
+ development: false,
90
+ providerImportSource: '@mdx-js/react',
91
+ format: 'mdx',
92
+ });
93
+ return {
94
+ contents: String(compiled),
95
+ loader: 'jsx',
96
+ resolveDir: path.dirname(args.path),
97
+ };
98
+ });
99
+ },
100
+ };
101
+ }
102
+
103
+ function getSearchRouteEntries() {
104
+ let entries = getLocaleRouteEntries('search');
105
+ if (!entries.length) {
106
+ entries = [
107
+ {
108
+ locale: getDefaultLocaleCode(),
109
+ route: getDefaultRoute('search'),
110
+ isDefault: true,
111
+ },
112
+ ];
113
+ }
114
+ return entries;
115
+ }
116
+
117
+ function resolveSearchOutputRelative(routeValue) {
118
+ const defaultRoute = getDefaultRoute('search') || 'search';
119
+ const trimmed = typeof routeValue === 'string' ? routeValue.trim().replace(/^\/+|\/+$/g, '') : '';
120
+ return path.join(trimmed || defaultRoute, 'index.html');
121
+ }
122
+
123
+ async function ensureSearchRuntime() {
124
+ ensureDirSync(OUT_DIR);
125
+ let esbuild = null;
126
+ try { esbuild = require('../../ui/node_modules/esbuild'); } catch (_) { try { esbuild = require('esbuild'); } catch (_) {} }
127
+ if (!esbuild) throw new Error('Search runtime bundling requires esbuild. Install dependencies before building.');
128
+ const entry = path.join(__dirname, 'search-app.jsx');
129
+ const scriptsDir = path.join(OUT_DIR, 'scripts');
130
+ ensureDirSync(scriptsDir);
131
+ const outFile = path.join(scriptsDir, 'search.js');
132
+ const templatesEntry = await buildSearchTemplatesModule();
133
+ const templatesPlugin = createResultTemplatesAliasPlugin(templatesEntry);
134
+ const mdxPlugin = createSearchMdxPlugin();
135
+ // Ensure a global React shim is available to reduce search.js size
136
+ try {
137
+ const scriptsDir = path.join(OUT_DIR, 'scripts');
138
+ ensureDirSync(scriptsDir);
139
+ const vendorFile = path.join(scriptsDir, 'react-globals.js');
140
+ const globalsEntry = `
141
+ import React from 'react';
142
+ import * as ReactDOM from 'react-dom';
143
+ import { createRoot, hydrateRoot } from 'react-dom/client';
144
+ (function(){ try{ window.React = React; window.ReactDOM = ReactDOM; window.ReactDOMClient = { createRoot, hydrateRoot }; }catch(e){} })();
145
+ `;
146
+ await esbuild.build({
147
+ stdin: { contents: globalsEntry, resolveDir: process.cwd(), loader: 'js', sourcefile: 'react-globals-entry.js' },
148
+ outfile: vendorFile,
149
+ platform: 'browser',
150
+ format: 'iife',
151
+ bundle: true,
152
+ sourcemap: false,
153
+ target: ['es2020'],
154
+ logLevel: 'silent',
155
+ minify: true,
156
+ define: { 'process.env.NODE_ENV': '"production"' },
157
+ });
158
+ } catch (_) {}
159
+ // 1.x loaded FlexSearch from here as a global; the runtime bundles it now.
160
+ try {
161
+ await fsp.rm(path.join(OUT_DIR, 'scripts', 'flexsearch-globals.js'), { force: true });
162
+ } catch (_) {}
163
+ const shimReactPlugin = {
164
+ name: 'shim-react-globals',
165
+ setup(build) {
166
+ build.onResolve({ filter: /^react$/ }, () => ({ path: 'react', namespace: 'react-shim' }));
167
+ build.onLoad({ filter: /.*/, namespace: 'react-shim' }, () => ({
168
+ contents: [
169
+ "const R = (typeof window!=='undefined' && window.React) || {};\n",
170
+ "export default R;\n",
171
+ // Common hooks and APIs used by deps
172
+ "export const Children = R.Children;\n",
173
+ "export const Component = R.Component;\n",
174
+ "export const Fragment = R.Fragment;\n",
175
+ "export const createElement = R.createElement;\n",
176
+ "export const cloneElement = R.cloneElement;\n",
177
+ "export const createContext = R.createContext;\n",
178
+ "export const forwardRef = R.forwardRef;\n",
179
+ "export const memo = R.memo;\n",
180
+ "export const startTransition = R.startTransition;\n",
181
+ "export const isValidElement = R.isValidElement;\n",
182
+ "export const useEffect = R.useEffect;\n",
183
+ "export const useLayoutEffect = R.useLayoutEffect;\n",
184
+ "export const useMemo = R.useMemo;\n",
185
+ "export const useState = R.useState;\n",
186
+ "export const useRef = R.useRef;\n",
187
+ "export const useCallback = R.useCallback;\n",
188
+ "export const useContext = R.useContext;\n",
189
+ "export const useReducer = R.useReducer;\n",
190
+ "export const useId = R.useId;\n",
191
+ "export const useSyncExternalStore = R.useSyncExternalStore;\n",
192
+ ].join(''),
193
+ loader: 'js',
194
+ }));
195
+ build.onResolve({ filter: /^react\/jsx-runtime$/ }, () => ({ path: 'react/jsx-runtime', namespace: 'react-jsx-shim' }));
196
+ build.onResolve({ filter: /^react\/jsx-dev-runtime$/ }, () => ({ path: 'react/jsx-dev-runtime', namespace: 'react-jsx-shim' }));
197
+ build.onLoad({ filter: /.*/, namespace: 'react-jsx-shim' }, () => ({
198
+ contents: [
199
+ "const R = (typeof window!=='undefined' && window.React) || {};\n",
200
+ "const Fragment = R.Fragment || 'div';\n",
201
+ "const createElement = typeof R.createElement === 'function' ? R.createElement.bind(R) : null;\n",
202
+ "function normalizeProps(props, key){\n",
203
+ " if (key !== undefined && key !== null) {\n",
204
+ " props = props && typeof props === 'object' ? { ...props, key } : { key };\n",
205
+ " }\n",
206
+ " return props || {};\n",
207
+ "}\n",
208
+ "function jsx(type, props, key){\n",
209
+ " if (!createElement) return null;\n",
210
+ " return createElement(type, normalizeProps(props, key));\n",
211
+ "}\n",
212
+ "const jsxs = jsx;\n",
213
+ "const jsxDEV = jsx;\n",
214
+ "export { jsx, jsxs, jsxDEV, Fragment };\n",
215
+ "export default { jsx, jsxs, jsxDEV, Fragment };\n",
216
+ ].join(''),
217
+ loader: 'js',
218
+ }));
219
+ build.onResolve({ filter: /^react-dom\/client$/ }, () => ({ path: 'react-dom/client', namespace: 'rdc-shim' }));
220
+ build.onLoad({ filter: /.*/, namespace: 'rdc-shim' }, () => ({
221
+ contents: [
222
+ "const C = (typeof window!=='undefined' && window.ReactDOMClient) || {};\n",
223
+ "export const createRoot = C.createRoot;\n",
224
+ "export const hydrateRoot = C.hydrateRoot;\n",
225
+ ].join(''),
226
+ loader: 'js',
227
+ }));
228
+ build.onResolve({ filter: /^react-dom$/ }, () => ({ path: 'react-dom', namespace: 'rd-shim' }));
229
+ build.onLoad({ filter: /.*/, namespace: 'rd-shim' }, () => ({
230
+ contents: "export default (typeof window!=='undefined' && window.ReactDOM) || {};\n",
231
+ loader: 'js',
232
+ }));
233
+ }
234
+ };
235
+ try {
236
+ const entryExists = (() => { try { return require('fs').existsSync(entry); } catch (_) { return false; } })();
237
+ const commonBuild = {
238
+ outfile: outFile,
239
+ platform: 'browser',
240
+ format: 'iife',
241
+ bundle: true,
242
+ sourcemap: true,
243
+ minify: true,
244
+ target: ['es2020'],
245
+ logLevel: 'silent',
246
+ // The site's result templates may import this package by its 1.x name.
247
+ plugins: [esbuildPackageNames(), shimReactPlugin, flexSearchPlugin(), templatesPlugin, mdxPlugin],
248
+ external: ['@nulib/clover', '@nulib/clover/*'],
249
+ };
250
+ if (!entryExists) throw new Error('Search runtime entry missing: ' + entry);
251
+ await esbuild.build({ entryPoints: [entry], ...commonBuild });
252
+ } catch (e) {
253
+ console.error('Search: bundle error:', e && e.message ? e.message : e);
254
+ return;
255
+ }
256
+ try {
257
+ const { logLine } = require('../build/log');
258
+ let size = 0; try { const st = fs.statSync(outFile); size = st.size || 0; } catch (_) {}
259
+ const kb = size ? ` (${(size/1024).toFixed(1)} KB)` : '';
260
+ const rel = path.relative(process.cwd(), outFile).split(path.sep).join('/');
261
+ logLine(`✓ Wrote ${rel}${kb}`, 'cyan');
262
+ } catch (_) {}
263
+ }
264
+
265
+ async function buildSearchPage() {
266
+ for (const entry of getSearchRouteEntries()) {
267
+ await buildSearchPageForEntry(entry);
268
+ }
269
+ }
270
+
271
+ async function buildSearchPageForEntry(routeEntry) {
272
+ try {
273
+ const defaultRoute = getDefaultRoute('search') || 'search';
274
+ const routeBase =
275
+ routeEntry && typeof routeEntry.route === 'string'
276
+ ? routeEntry.route
277
+ : defaultRoute;
278
+ const relativeOutput = resolveSearchOutputRelative(routeBase);
279
+ const outPath = path.join(OUT_DIR, relativeOutput);
280
+ ensureDirSync(path.dirname(outPath));
281
+ const searchLayoutPath = path.join(path.resolve('content'), 'search', '_layout.mdx');
282
+ if (!require('../common').fs.existsSync(searchLayoutPath)) {
283
+ throw new Error('Missing required file: content/search/_layout.mdx');
284
+ }
285
+ const mdx = require('../build/mdx');
286
+ const normalizedRoute = routeBase ? routeBase.replace(/^\/+|\/+$/g, '') : '';
287
+ const fileHref = rootRelativeHref(relativeOutput.split(path.sep).join('/'));
288
+ const prettyHref =
289
+ normalizedRoute && normalizedRoute !== defaultRoute
290
+ ? rootRelativeHref(`${normalizedRoute}/`)
291
+ : fileHref;
292
+ const searchPageMeta = readSearchPageMetadata() || {};
293
+ let pageTitle =
294
+ typeof searchPageMeta.title === 'string' && searchPageMeta.title.trim()
295
+ ? searchPageMeta.title.trim()
296
+ : 'Search';
297
+ // `search.page.title` is written in the site's default language; a search page in
298
+ // another is titled in its own words, its locale's `common.nouns.search` (3.1.2;
299
+ // ACCESSIBILITY.md C42), as its title is its `h1` too.
300
+ if (routeEntry && routeEntry.locale && !routeEntry.isDefault) {
301
+ try {
302
+ const { readLocaleMessages } = require('../locales');
303
+ const messages = readLocaleMessages(routeEntry.locale) || {};
304
+ const word = messages.common && messages.common.nouns && messages.common.nouns.search;
305
+ if (typeof word === 'string' && word.trim()) pageTitle = word.trim();
306
+ } catch (_) {}
307
+ }
308
+ const pageDescription =
309
+ typeof searchPageMeta.description === 'string'
310
+ ? searchPageMeta.description
311
+ : '';
312
+ const siteTitle = typeof getSiteTitle === 'function' ? getSiteTitle() : '';
313
+ const pageDetails = {
314
+ title: pageTitle,
315
+ description: pageDescription,
316
+ href: prettyHref,
317
+ url: prettyHref,
318
+ type: 'search',
319
+ canonical: prettyHref,
320
+ meta: {
321
+ title: pageTitle,
322
+ description: pageDescription,
323
+ type: 'search',
324
+ url: prettyHref,
325
+ canonical: prettyHref,
326
+ },
327
+ };
328
+ const fallbackLocale = resolveLocaleFromHref(prettyHref);
329
+ const pageLocale =
330
+ (routeEntry && routeEntry.locale) ||
331
+ fallbackLocale ||
332
+ getDefaultLocaleCode();
333
+ pageDetails.locale = pageLocale;
334
+ if (pageDetails.meta) pageDetails.meta.locale = pageLocale;
335
+ const rendered = await mdx.compileMdxFile(searchLayoutPath, outPath, null, {
336
+ page: pageDetails,
337
+ });
338
+ const body = rendered && rendered.body ? rendered.body : '';
339
+ const head = rendered && rendered.head ? rendered.head : '';
340
+ if (!body) throw new Error('Search: content/search/_layout.mdx produced empty output');
341
+ // A site's own 1.x layout may give the page no `h1`; said once (`upgrade-notices.js`).
342
+ printSearchHeadingNotice(body);
343
+ const importMap = '';
344
+ const jsAbs = path.join(OUT_DIR, 'scripts', 'search.js');
345
+ let jsRel = path.relative(path.dirname(outPath), jsAbs).split(path.sep).join('/');
346
+ let v = '';
347
+ try { const st = require('fs').statSync(jsAbs); v = `?v=${Math.floor(st.mtimeMs || Date.now())}`; } catch (_) {}
348
+ jsRel = jsRel + v;
349
+ const vendorReactAbs = path.join(OUT_DIR, 'scripts', 'react-globals.js');
350
+ const vendorSearchFormAbs = path.join(OUT_DIR, 'scripts', 'canopy-search-form.js');
351
+ function verRel(abs) {
352
+ let rel = path.relative(path.dirname(outPath), abs).split(path.sep).join('/');
353
+ try { const st = require('fs').statSync(abs); rel += `?v=${Math.floor(st.mtimeMs || Date.now())}`; } catch (_) {}
354
+ return rel;
355
+ }
356
+ const vendorTags = `<script src="${verRel(vendorReactAbs)}"></script><script src="${verRel(vendorSearchFormAbs)}"></script>`;
357
+ let customRuntimeTag = '';
358
+ if (body && body.indexOf('data-canopy-client-component') !== -1) {
359
+ try {
360
+ await mdx.ensureCustomClientRuntime();
361
+ const runtimeAbs = path.join(OUT_DIR, 'scripts', 'canopy-custom-components.js');
362
+ let rel = path.relative(path.dirname(outPath), runtimeAbs).split(path.sep).join('/');
363
+ try { const st = require('fs').statSync(runtimeAbs); rel += `?v=${Math.floor(st.mtimeMs || Date.now())}`; } catch (_) {}
364
+ customRuntimeTag = `<script type="module" src="${rel}"></script>`;
365
+ } catch (e) {
366
+ console.warn('[search] failed to build custom client runtime:', e && (e.message || e));
367
+ }
368
+ }
369
+ let headExtra = vendorTags + head + importMap + customRuntimeTag;
370
+ try {
371
+ const localeScript = buildLocaleRuntimeScript(pageLocale);
372
+ if (localeScript) headExtra = localeScript + headExtra;
373
+ } catch (_) {}
374
+ if (siteTitle && typeof siteTitle === 'string') {
375
+ const siteTitleScript = `<script>window.CANOPY_SITE_TITLE=${JSON.stringify(siteTitle)}</script>`;
376
+ headExtra = siteTitleScript + headExtra;
377
+ }
378
+ try {
379
+ const { BASE_PATH } = require('../common');
380
+ if (BASE_PATH) {
381
+ headExtra = `<script>window.CANOPY_BASE_PATH=${JSON.stringify(BASE_PATH)}</script>` + headExtra;
382
+ }
383
+ } catch (_) {}
384
+ const bodyClass = canopyBodyClassForType('search');
385
+ let html = htmlShell({ title: pageTitle, body, cssHref: null, scriptHref: jsRel, headExtra, bodyClass, lang: pageLocale });
386
+ try { html = require('../common').applyBaseToHtml(html); } catch (_) {}
387
+ await fsp.writeFile(outPath, html, 'utf8');
388
+ console.log('Search: Built', path.relative(process.cwd(), outPath));
389
+ } catch (e) {
390
+ console.warn('Search: Failed to build page', e && (e.message || e));
391
+ throw e;
392
+ }
393
+ }
394
+
395
+ function toSafeString(val, defaultValue = '') {
396
+ try { return String(val == null ? defaultValue : val); } catch (_) { return defaultValue; }
397
+ }
398
+
399
+ function sanitizeMetadataValues(list) {
400
+ const arr = Array.isArray(list) ? list : [];
401
+ const out = [];
402
+ const seen = new Set();
403
+ for (const val of arr) {
404
+ if (val && typeof val === 'object' && Array.isArray(val.values)) {
405
+ for (const v of val.values) {
406
+ const str = toSafeString(v, '').trim();
407
+ if (!str) continue;
408
+ const clipped = str.length > 500 ? str.slice(0, 500) + '…' : str;
409
+ if (seen.has(clipped)) continue;
410
+ seen.add(clipped);
411
+ out.push(clipped);
412
+ }
413
+ continue;
414
+ }
415
+ const str = toSafeString(val, '').trim();
416
+ if (!str) continue;
417
+ const clipped = str.length > 500 ? str.slice(0, 500) + '…' : str;
418
+ if (seen.has(clipped)) continue;
419
+ seen.add(clipped);
420
+ out.push(clipped);
421
+ }
422
+ return out;
423
+ }
424
+
425
+ function sanitizeRecordForIndex(r) {
426
+ const title = toSafeString(r && r.title, '');
427
+ const type = toSafeString(r && r.type, 'page');
428
+ const safeTitle = title.length > 300 ? title.slice(0, 300) + '…' : title;
429
+ const out = { title: safeTitle, type };
430
+ const metadataSource =
431
+ (r && r.metadataValues) ||
432
+ (r && r.searchMetadataValues) ||
433
+ (r && r.search && r.search.metadata) ||
434
+ [];
435
+ const metadata = sanitizeMetadataValues(metadataSource);
436
+ if (metadata.length) out.metadata = metadata;
437
+ const summaryVal = toSafeString(
438
+ (r && r.summaryValue) ||
439
+ (r && r.searchSummary) ||
440
+ (r && r.search && r.search.summary),
441
+ ''
442
+ ).trim();
443
+ if (summaryVal) {
444
+ out.summary = summaryVal;
445
+ }
446
+ return out;
447
+ }
448
+
449
+ function sanitizeRecordForDisplay(r) {
450
+ const base = sanitizeRecordForIndex(r);
451
+ const out = { ...base };
452
+ if (out.metadata) delete out.metadata;
453
+ if (out.summary) out.summary = toSafeString(out.summary, '');
454
+ const locale = toSafeString(r && r.locale, '').trim();
455
+ if (locale) out.locale = locale;
456
+ if (r && r.routes && typeof r.routes === 'object') {
457
+ const normalizedRoutes = {};
458
+ Object.keys(r.routes).forEach((key) => {
459
+ const routeHref = toSafeString(r.routes[key], '');
460
+ if (!routeHref) return;
461
+ normalizedRoutes[key] = rootRelativeHref(routeHref);
462
+ });
463
+ if (Object.keys(normalizedRoutes).length) out.routes = normalizedRoutes;
464
+ }
465
+ const summaryMarkdown = toSafeString(
466
+ (r && r.summaryMarkdown) ||
467
+ (r && r.searchSummaryMarkdown) ||
468
+ (r && r.search && r.search.summaryMarkdown),
469
+ ''
470
+ ).trim();
471
+ if (summaryMarkdown) {
472
+ out.summaryMarkdown = summaryMarkdown;
473
+ }
474
+ const hrefRaw = toSafeString(r && r.href, '');
475
+ if (hrefRaw) {
476
+ out.href = rootRelativeHref(hrefRaw);
477
+ }
478
+ const thumbnail = toSafeString(r && r.thumbnail, '');
479
+ if (thumbnail) out.thumbnail = thumbnail;
480
+ // Preserve optional thumbnail dimensions for aspect ratio calculations in the UI
481
+ try {
482
+ const tw = Number(r && r.thumbnailWidth);
483
+ const th = Number(r && r.thumbnailHeight);
484
+ if (Number.isFinite(tw) && tw > 0) out.thumbnailWidth = tw;
485
+ if (Number.isFinite(th) && th > 0) out.thumbnailHeight = th;
486
+ } catch (_) {}
487
+ return out;
488
+ }
489
+
490
+ /**
491
+ * Write search datasets consumed by the runtime layers.
492
+ *
493
+ * Outputs:
494
+ * - search-index.json: compact payload (title/href/type/metadata + stable id) for FlexSearch
495
+ * - search-records.json: richer display data (thumbnail/dimensions + id) for UI rendering
496
+ */
497
+ async function writeSearchIndex(records) {
498
+ const apiDir = path.join(OUT_DIR, 'api');
499
+ ensureDirSync(apiDir);
500
+ const idxPath = path.join(apiDir, 'search-index.json');
501
+ const list = Array.isArray(records) ? records : [];
502
+ const indexRecords = list.map(sanitizeRecordForIndex);
503
+ const displayRecords = list.map(sanitizeRecordForDisplay);
504
+ for (let i = 0; i < indexRecords.length; i += 1) {
505
+ const id = String(i);
506
+ if (indexRecords[i]) indexRecords[i].id = id;
507
+ if (displayRecords[i]) displayRecords[i].id = id;
508
+ if (displayRecords[i] && !displayRecords[i].href) {
509
+ const original = list[i];
510
+ const href = original && original.href ? rootRelativeHref(String(original.href)) : '';
511
+ if (href) displayRecords[i].href = href;
512
+ }
513
+ }
514
+ const annotationsPath = path.join(apiDir, 'search-index-annotations.json');
515
+ const annotationRecords = [];
516
+ for (let i = 0; i < list.length; i += 1) {
517
+ const raw = list[i];
518
+ const annotationVal = toSafeString(
519
+ (raw && raw.annotationValue) ||
520
+ (raw && raw.searchAnnotation) ||
521
+ (raw && raw.search && raw.search.annotation),
522
+ ''
523
+ ).trim();
524
+ if (!annotationVal) continue;
525
+ annotationRecords.push({ id: String(i), annotation: annotationVal });
526
+ }
527
+
528
+ const indexJson = JSON.stringify(indexRecords);
529
+ const approxBytes = Buffer.byteLength(indexJson, 'utf8');
530
+ if (approxBytes > 10 * 1024 * 1024) {
531
+ console.warn('Search: index size is large (', Math.round(approxBytes / (1024 * 1024)), 'MB ). Consider narrowing sources.');
532
+ }
533
+ await fsp.writeFile(idxPath, indexJson, 'utf8');
534
+ try {
535
+ const { logLine } = require('../build/log');
536
+ const approxKb = Math.round(approxBytes / 1024);
537
+ logLine(
538
+ `• search-index.json written (${indexRecords.length} records, ${approxKb} KB)`,
539
+ 'blue',
540
+ { dim: true }
541
+ );
542
+ } catch (_) {}
543
+
544
+ const displayPath = path.join(apiDir, 'search-records.json');
545
+ const displayJson = JSON.stringify(displayRecords);
546
+ const displayBytes = Buffer.byteLength(displayJson, 'utf8');
547
+ await fsp.writeFile(displayPath, displayJson, 'utf8');
548
+ try {
549
+ const { logLine } = require('../build/log');
550
+ const approxKb = Math.round(displayBytes / 1024);
551
+ logLine(
552
+ `• search-records.json written (${displayRecords.length} entries, ${approxKb} KB)`,
553
+ 'blue',
554
+ { dim: true }
555
+ );
556
+ } catch (_) {}
557
+ let annotationsBytes = 0;
558
+ if (annotationRecords.length) {
559
+ const annotationsJson = JSON.stringify(annotationRecords);
560
+ annotationsBytes = Buffer.byteLength(annotationsJson, 'utf8');
561
+ await fsp.writeFile(annotationsPath, annotationsJson, 'utf8');
562
+ try {
563
+ const { logLine } = require('../build/log');
564
+ const approxKb = Math.round(annotationsBytes / 1024);
565
+ logLine(
566
+ `• search-index-annotations.json written (${annotationRecords.length} entries, ${approxKb} KB)`,
567
+ 'blue',
568
+ { dim: true }
569
+ );
570
+ } catch (_) {}
571
+ } else {
572
+ try {
573
+ if (fs.existsSync(annotationsPath)) await fsp.unlink(annotationsPath);
574
+ } catch (_) {}
575
+ }
576
+ // Also write a small metadata file with a stable version hash for cache-busting and IDB keying
577
+ try {
578
+ // The browser keeps a built index by this version (`index-cache.js`), so it covers all
579
+ // the text that index holds: the records' and their annotations'.
580
+ const version = crypto
581
+ .createHash('sha256')
582
+ .update(indexJson)
583
+ .update(annotationRecords.length ? JSON.stringify(annotationRecords) : '')
584
+ .digest('hex');
585
+ // Read optional search configuration from canopy.yml
586
+ let tabsOrder = [];
587
+ let resultsConfigEntries = [];
588
+ try {
589
+ const yaml = require('js-yaml');
590
+ const cfgPath = resolveCanopyConfigPath();
591
+ if (fs.existsSync(cfgPath)) {
592
+ const raw = fs.readFileSync(cfgPath, 'utf8');
593
+ const data = yaml.load(raw) || {};
594
+ const searchCfg = data && data.search ? data.search : {};
595
+ const tabs = searchCfg && searchCfg.tabs ? searchCfg.tabs : {};
596
+ const order = Array.isArray(tabs && tabs.order) ? tabs.order : [];
597
+ tabsOrder = order
598
+ .map((s) => String(s).trim().toLowerCase())
599
+ .filter(Boolean);
600
+ const resultsCfg =
601
+ searchCfg && searchCfg.results && typeof searchCfg.results === 'object'
602
+ ? searchCfg.results
603
+ : null;
604
+ if (resultsCfg) {
605
+ const entries = [];
606
+ Object.keys(resultsCfg).forEach((key) => {
607
+ if (!key) return;
608
+ const type = String(key).trim().toLowerCase();
609
+ if (!type) return;
610
+ if (entries.find((entry) => entry.type === type)) return;
611
+ const cfg = resultsCfg[key] && typeof resultsCfg[key] === 'object' ? resultsCfg[key] : {};
612
+ const layoutRaw = cfg && cfg.layout ? String(cfg.layout).toLowerCase() : '';
613
+ const resultRaw = cfg && cfg.result ? String(cfg.result).toLowerCase() : '';
614
+ const layout = layoutRaw === 'grid' ? 'grid' : 'list';
615
+ const result = resultRaw === 'figure' ? 'figure' : 'article';
616
+ entries.push({ type, layout, result });
617
+ });
618
+ if (entries.length) {
619
+ resultsConfigEntries = entries;
620
+ tabsOrder = entries.map((entry) => entry.type);
621
+ }
622
+ }
623
+ }
624
+ } catch (_) {}
625
+ const searchMeta = {
626
+ tabs: { order: tabsOrder },
627
+ assets: {
628
+ display: { path: 'search-records.json', bytes: displayBytes },
629
+ ...(annotationRecords.length
630
+ ? { annotations: { path: 'search-index-annotations.json', bytes: annotationsBytes } }
631
+ : {}),
632
+ },
633
+ };
634
+ if (resultsConfigEntries.length) {
635
+ const resultSettings = resultsConfigEntries.reduce((acc, entry) => {
636
+ acc[entry.type] = { layout: entry.layout, result: entry.result };
637
+ return acc;
638
+ }, {});
639
+ searchMeta.results = {
640
+ order: resultsConfigEntries.map((entry) => entry.type),
641
+ settings: resultSettings,
642
+ };
643
+ }
644
+ const meta = {
645
+ version,
646
+ records: indexRecords.length,
647
+ bytes: approxBytes,
648
+ updatedAt: new Date().toISOString(),
649
+ // Expose optional search config to the client runtime
650
+ search: searchMeta,
651
+ };
652
+ const metaPath = path.join(apiDir, 'index.json');
653
+ await fsp.writeFile(metaPath, JSON.stringify(meta, null, 2), 'utf8');
654
+ try {
655
+ const { logLine } = require('../build/log');
656
+ logLine(`✓ Search index version ${version.slice(0, 8)} (${indexRecords.length} records)`, 'cyan');
657
+ } catch (_) {}
658
+ } catch (_) {}
659
+ }
660
+
661
+ // Compatibility: keep ensureResultTemplate as a no-op builder (template unused by React search)
662
+ async function ensureResultTemplate() {
663
+ try {
664
+ const { path } = require('../common');
665
+ const p = path.join(OUT_DIR, 'search-result.html');
666
+ await fsp.writeFile(p, '', 'utf8');
667
+ } catch (_) {}
668
+ }
669
+
670
+ module.exports = {
671
+ ensureSearchRuntime,
672
+ ensureResultTemplate,
673
+ buildSearchPage,
674
+ writeSearchIndex,
675
+ resolveSearchOutputRelative,
676
+ };