@nulib/canopy 0.0.0 → 2.0.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.
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,80 @@
1
+ import React from 'react';
2
+ import { createRoot, hydrateRoot } from 'react-dom/client';
3
+ import { Timeline } from '../../ui/dist/index.mjs';
4
+
5
+ function ready(fn) {
6
+ if (typeof document === 'undefined') return;
7
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fn, { once: true });
8
+ else fn();
9
+ }
10
+
11
+ function parseProps(el) {
12
+ try {
13
+ const script = el.querySelector('script[type="application/json"]');
14
+ if (script) return JSON.parse(script.textContent || '{}');
15
+ const raw = el.getAttribute('data-props') || '{}';
16
+ return JSON.parse(raw);
17
+ } catch (_) {
18
+ return {};
19
+ }
20
+ }
21
+
22
+ function mount(el) {
23
+ try {
24
+ if (!el || el.getAttribute('data-canopy-timeline-mounted') === '1') return;
25
+ const props = parseProps(el);
26
+ const dataNode = el.querySelector('script[type="application/json"]');
27
+ if (dataNode && dataNode.parentNode === el) {
28
+ dataNode.parentNode.removeChild(dataNode);
29
+ }
30
+ if (el.childElementCount > 0) {
31
+ hydrateRoot(el, React.createElement(Timeline, props));
32
+ } else {
33
+ const root = createRoot(el);
34
+ root.render(React.createElement(Timeline, props));
35
+ }
36
+ el.setAttribute('data-canopy-timeline-mounted', '1');
37
+ } catch (error) {
38
+ try {
39
+ console.warn('[canopy][timeline] failed to mount timeline', error);
40
+ } catch (_) {}
41
+ }
42
+ }
43
+
44
+ function scan() {
45
+ try {
46
+ document
47
+ .querySelectorAll('[data-canopy-timeline]:not([data-canopy-timeline-mounted="1"])')
48
+ .forEach(mount);
49
+ } catch (_) {}
50
+ }
51
+
52
+ function observe() {
53
+ try {
54
+ const obs = new MutationObserver((mutations) => {
55
+ const toMount = [];
56
+ mutations.forEach((mutation) => {
57
+ mutation.addedNodes &&
58
+ mutation.addedNodes.forEach((node) => {
59
+ if (!(node instanceof Element)) return;
60
+ if (node.matches && node.matches('[data-canopy-timeline]')) toMount.push(node);
61
+ const inner = node.querySelectorAll
62
+ ? node.querySelectorAll('[data-canopy-timeline]')
63
+ : [];
64
+ inner && inner.forEach && inner.forEach((el) => toMount.push(el));
65
+ });
66
+ });
67
+ if (toMount.length) Promise.resolve().then(() => toMount.forEach(mount));
68
+ });
69
+ obs.observe(document.documentElement || document.body, {
70
+ childList: true,
71
+ subtree: true,
72
+ });
73
+ } catch (_) {}
74
+ }
75
+
76
+ ready(() => {
77
+ if (typeof document === 'undefined') return;
78
+ scan();
79
+ observe();
80
+ });
@@ -0,0 +1,88 @@
1
+ import React from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+
4
+ import { cloverImage, cloverScroll, cloverViewer } from '../../ui/dist/index.mjs';
5
+
6
+ function ready(fn) {
7
+ if (typeof document === 'undefined') return;
8
+ if (document.readyState === 'loading') {
9
+ document.addEventListener('DOMContentLoaded', fn, { once: true });
10
+ } else {
11
+ fn();
12
+ }
13
+ }
14
+
15
+ function parseProps(el) {
16
+ try {
17
+ const script = el.querySelector('script[type="application/json"]');
18
+ if (script) return JSON.parse(script.textContent || '{}');
19
+ const raw = el.getAttribute('data-props') || '{}';
20
+ return JSON.parse(raw);
21
+ } catch (_) {
22
+ return {};
23
+ }
24
+ }
25
+
26
+ /*
27
+ * Clover 4 (`@nulib/clover`), a part at a time: each loads from its own entry, so esbuild
28
+ * reaches only that part's modules rather than every part the Default template shares
29
+ * through the package's main entry. Canopy's MDX props, as 1.x authors write them, are
30
+ * translated into Clover's (`ui/src/iiif/clover-compat.js`).
31
+ */
32
+ const componentLoaders = {
33
+ // The Viewer in Clover's Default template, handed in so it loads with the Viewer.
34
+ viewer: () =>
35
+ Promise.all([
36
+ import('@nulib/clover/viewer'),
37
+ import('@nulib/clover/templates'),
38
+ import('@nulib/clover/helpers'),
39
+ ]).then(([viewer, templates, helpers]) => cloverViewer(viewer, templates, helpers)),
40
+ // Scroll, for now Clover's Document template, until its text reader is built.
41
+ scroll: () =>
42
+ Promise.all([
43
+ import('@nulib/clover/viewer'),
44
+ import('@nulib/clover/templates'),
45
+ ]).then(([viewer, templates]) => cloverScroll(viewer, templates)),
46
+ // Image: one Canvas, deep zoom where its image has a service.
47
+ image: () => import('@nulib/clover/canvas').then(cloverImage),
48
+ };
49
+
50
+ const componentCache = new Map();
51
+
52
+ function resolveComponent(key) {
53
+ if (!componentLoaders[key]) return Promise.resolve(null);
54
+ if (!componentCache.has(key)) {
55
+ componentCache.set(key, componentLoaders[key]().catch((error) => {
56
+ console.error('[canopy] Clover failed to load', error);
57
+ return null;
58
+ }));
59
+ }
60
+ return componentCache.get(key);
61
+ }
62
+
63
+ function mountAll(selector, key) {
64
+ try {
65
+ const nodes = document.querySelectorAll(selector);
66
+ if (!nodes || !nodes.length) return;
67
+ const rootApi = typeof createRoot === 'function' ? createRoot : null;
68
+ if (!React || !rootApi) return;
69
+ resolveComponent(key).then((Component) => {
70
+ if (!Component) return;
71
+ nodes.forEach((el) => {
72
+ try {
73
+ if (el.__canopyHydrated) return;
74
+ const props = parseProps(el);
75
+ const root = rootApi(el);
76
+ root.render(React.createElement(Component, props));
77
+ el.__canopyHydrated = true;
78
+ } catch (_) {}
79
+ });
80
+ });
81
+ } catch (_) {}
82
+ }
83
+
84
+ ready(() => {
85
+ mountAll('[data-canopy-viewer]', 'viewer');
86
+ mountAll('[data-canopy-scroll]', 'scroll');
87
+ mountAll('[data-canopy-image]', 'image');
88
+ });
@@ -0,0 +1,78 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const DEFAULT_CONFIG_NAME = 'canopy.yml';
5
+
6
+ function toAbsolute(value) {
7
+ if (!value && value !== 0) return '';
8
+ const stringValue = String(value).trim();
9
+ if (!stringValue) return '';
10
+ try {
11
+ return path.resolve(stringValue);
12
+ } catch (_) {
13
+ return '';
14
+ }
15
+ }
16
+
17
+ function fileExists(p) {
18
+ try {
19
+ return !!(p && fs.existsSync(p));
20
+ } catch (_) {
21
+ return false;
22
+ }
23
+ }
24
+
25
+ function isConfigPresent(root, fileName) {
26
+ if (!root) return false;
27
+ const candidate = path.resolve(root, fileName);
28
+ return fileExists(candidate);
29
+ }
30
+
31
+ function resolveWorkspaceRoot(options = {}) {
32
+ const candidates = [];
33
+ if (options && options.cwd) candidates.push(options.cwd);
34
+ candidates.push(process.env.INIT_CWD || '');
35
+ candidates.push(process.env.GITHUB_WORKSPACE || '');
36
+ candidates.push(process.cwd());
37
+
38
+ const seen = new Set();
39
+ for (const raw of candidates) {
40
+ const abs = toAbsolute(raw);
41
+ if (!abs || seen.has(abs)) continue;
42
+ seen.add(abs);
43
+ if (fileExists(abs)) return abs;
44
+ }
45
+ return process.cwd();
46
+ }
47
+
48
+ function resolveCanopyConfigPath(options = {}) {
49
+ const explicit = options && options.configPath ? String(options.configPath).trim() : '';
50
+ const override = options && options.configFile ? String(options.configFile).trim() : '';
51
+ const envOverride = String(process.env.CANOPY_CONFIG || '').trim();
52
+ const fileName = override || envOverride || DEFAULT_CONFIG_NAME;
53
+
54
+ const roots = [];
55
+ const primaryRoot = resolveWorkspaceRoot(options);
56
+ if (primaryRoot) roots.push(primaryRoot);
57
+ const cwdFallback = toAbsolute(process.cwd());
58
+ if (cwdFallback && !roots.includes(cwdFallback)) roots.push(cwdFallback);
59
+ const githubWorkspace = toAbsolute(process.env.GITHUB_WORKSPACE || '');
60
+ if (githubWorkspace && !roots.includes(githubWorkspace)) roots.push(githubWorkspace);
61
+
62
+ if (explicit) {
63
+ const base = roots[0] || process.cwd();
64
+ return path.isAbsolute(explicit) ? explicit : path.resolve(base, explicit);
65
+ }
66
+
67
+ for (const root of roots) {
68
+ if (isConfigPresent(root, fileName)) return path.resolve(root, fileName);
69
+ }
70
+
71
+ const fallbackRoot = roots[0] || process.cwd();
72
+ return path.resolve(fallbackRoot, fileName);
73
+ }
74
+
75
+ module.exports = {
76
+ resolveWorkspaceRoot,
77
+ resolveCanopyConfigPath,
78
+ };
@@ -0,0 +1,113 @@
1
+ /**
2
+ * This file is auto-generated from content/locale.yml.
3
+ * Run `node packages/helpers/locales/sync-default-locale.js` after updating locale copy.
4
+ */
5
+ module.exports = {
6
+ routes: {
7
+ search: '/search',
8
+ works: '/works'
9
+ },
10
+ common: {
11
+ actions: {
12
+ open: 'Open',
13
+ close: 'Close',
14
+ clear: 'Clear',
15
+ clear_all: 'Clear all',
16
+ done: 'Done',
17
+ show: 'Show',
18
+ hide: 'Hide',
19
+ view_work: 'View work',
20
+ copy: 'Copy'
21
+ },
22
+ nouns: {
23
+ search: 'Search',
24
+ filters: 'Filters',
25
+ results: 'results',
26
+ values: 'values',
27
+ types: 'types',
28
+ items: 'items',
29
+ navigation: 'navigation',
30
+ section_navigation: 'section navigation',
31
+ content_navigation: 'content navigation',
32
+ primary_navigation: 'Primary navigation',
33
+ metadata: 'metadata',
34
+ gallery: 'gallery',
35
+ gallery_thumbnails: 'gallery thumbnails',
36
+ map: 'map',
37
+ map_data: 'map data',
38
+ map_locations: 'map locations',
39
+ item_label: 'Item',
40
+ details: 'details',
41
+ breadcrumb: 'Breadcrumb',
42
+ home: 'Home',
43
+ suggestion: 'suggestion',
44
+ suggestions: 'suggestions'
45
+ },
46
+ types: {
47
+ work: 'Works',
48
+ page: 'Pages',
49
+ docs: 'Docs'
50
+ },
51
+ statuses: {
52
+ loading: 'Loading…',
53
+ empty_short: 'No {content}',
54
+ empty_detail: 'No {content} available.',
55
+ unavailable: '{content} unavailable.',
56
+ unavailable_detail: '{content} is unavailable.',
57
+ failed: 'Unable to load {content}.',
58
+ loading_content: 'Loading {content}…',
59
+ summary_content: 'Showing {shown} of {total} {content}',
60
+ search_summary: 'Found {shown} of {total} in {type} for "{query}"',
61
+ no_matches: 'No matches found.'
62
+ },
63
+ phrases: {
64
+ placeholder_search: 'Search…',
65
+ results_label: 'Search results',
66
+ open_content: 'Open {content}',
67
+ close_content: 'Close {content}',
68
+ show_content: 'Show {content}',
69
+ hide_content: 'Hide {content}',
70
+ nav_label: '{content} navigation',
71
+ search_content: 'Search {content}',
72
+ filter_values: 'Filter {content} values',
73
+ clear_content_search: 'Clear {content} search',
74
+ none_applied: 'No {content} applied',
75
+ applied_count: '{count} {content} applied',
76
+ toggle_content: 'Toggle {content}',
77
+ scroll_direction_content: 'Scroll {direction} through {content}',
78
+ step_content: '{direction} {content}',
79
+ item_numbered: '{content} {index}',
80
+ content_key: '{content} key',
81
+ copy_code: 'Copy code to clipboard',
82
+ copied_code: 'Copied to clipboard',
83
+ count_content: '{count} {content}'
84
+ },
85
+ directions: {
86
+ left: 'left',
87
+ right: 'right',
88
+ previous: 'Previous',
89
+ next: 'Next'
90
+ },
91
+ misc: {
92
+ referenced_by: 'Referenced by',
93
+ on_this_page: 'On this page'
94
+ },
95
+ appearance: {
96
+ label: 'Appearance',
97
+ system: 'System',
98
+ light: 'Light',
99
+ dark: 'Dark'
100
+ },
101
+ carousel: {
102
+ label: 'Featured content',
103
+ role: 'carousel',
104
+ slide_role: 'slide',
105
+ slide: '{index} of {total}',
106
+ previous: 'Previous slide',
107
+ next: 'Next slide',
108
+ go_to: 'Go to slide {index}',
109
+ stop: 'Pause the slideshow',
110
+ start: 'Play the slideshow'
111
+ }
112
+ }
113
+ };
@@ -0,0 +1,107 @@
1
+ const { validateCatalog } = require('./validation');
2
+
3
+ function createBrowserLoader({ catalogUrl, origin, fetch: fetchJson, signal }) {
4
+ const catalog = new URL(catalogUrl);
5
+ const directory = new URL('.', catalog);
6
+
7
+ function resolveUrl(value) {
8
+ const url = new URL(value, catalog);
9
+ if (
10
+ !['http:', 'https:'].includes(url.protocol) ||
11
+ url.origin !== origin ||
12
+ url.username ||
13
+ url.password ||
14
+ url.search ||
15
+ url.hash ||
16
+ !url.pathname.startsWith(directory.pathname) ||
17
+ /%(?:2f|5c|00)/i.test(url.pathname)
18
+ ) {
19
+ throw new Error('IIIF discovery data must use a public URL within this site’s catalog.');
20
+ }
21
+ return url.href;
22
+ }
23
+
24
+ const resolvedCatalogUrl = resolveUrl(catalog.href);
25
+ const requests = new Map();
26
+
27
+ async function readJson(value, transform = (data) => data) {
28
+ const url = resolveUrl(value);
29
+ if (!requests.has(url)) {
30
+ const request = Promise.resolve()
31
+ .then(() =>
32
+ fetchJson(url, {
33
+ signal,
34
+ credentials: 'omit',
35
+ redirect: 'error',
36
+ cache: 'no-cache',
37
+ }),
38
+ )
39
+ .then((response) => {
40
+ if (!response.ok) {
41
+ throw new Error(`IIIF discovery data could not be loaded (HTTP ${response.status}).`);
42
+ }
43
+ if (response.url) resolveUrl(response.url);
44
+ return response.json();
45
+ })
46
+ .then(transform)
47
+ .catch((error) => {
48
+ requests.delete(url);
49
+ throw error;
50
+ });
51
+ requests.set(url, request);
52
+ if (requests.size > 65) {
53
+ const oldest = [...requests.keys()].find((key) => key !== resolvedCatalogUrl);
54
+ requests.delete(oldest);
55
+ }
56
+ }
57
+ return requests.get(url);
58
+ }
59
+
60
+ return {
61
+ loadCatalog: () =>
62
+ readJson(resolvedCatalogUrl, (data) => {
63
+ validateCatalog(data);
64
+ if (typeof data.datasetVersion !== 'string') {
65
+ throw new Error('The IIIF discovery catalog has an invalid dataset version.');
66
+ }
67
+ const ids = new Set();
68
+ const resources = data.resources.map((record) => {
69
+ if (
70
+ !record ||
71
+ typeof record.id !== 'string' ||
72
+ !record.id ||
73
+ ids.has(record.id) ||
74
+ !['Collection', 'Manifest'].includes(record.type) ||
75
+ typeof record.snapshotUrl !== 'string' ||
76
+ !record.snapshotUrl
77
+ ) {
78
+ throw new Error('The IIIF discovery catalog contains an invalid resource.');
79
+ }
80
+ ids.add(record.id);
81
+ const citation = record.citationUrl
82
+ ? new URL(record.citationUrl, new URL('../../', catalog))
83
+ : null;
84
+ return {
85
+ ...record,
86
+ snapshotUrl: resolveUrl(record.snapshotUrl),
87
+ citationUrl:
88
+ citation &&
89
+ ['http:', 'https:'].includes(citation.protocol) &&
90
+ !citation.username &&
91
+ !citation.password
92
+ ? citation.href
93
+ : null,
94
+ };
95
+ });
96
+ return { ...data, resources };
97
+ }),
98
+ loadResource: (record) => {
99
+ if (!record || typeof record.snapshotUrl !== 'string' || !record.snapshotUrl) {
100
+ throw new Error('This IIIF resource has no published snapshot.');
101
+ }
102
+ return readJson(record.snapshotUrl);
103
+ },
104
+ };
105
+ }
106
+
107
+ module.exports = { createBrowserLoader };
@@ -0,0 +1,115 @@
1
+ const { createDiscoveryTools } = require('./tools');
2
+ const { createBrowserLoader } = require('./browser-loader');
3
+
4
+ const registrationKey = Symbol.for('canopy.iiif.webmcp');
5
+
6
+ function executeWithCancellation(tool, input, options, registrationSignal) {
7
+ const signals = [options?.signal, registrationSignal].filter(Boolean);
8
+ return new Promise((resolve, reject) => {
9
+ let settled = false;
10
+ const finish = (callback, value) => {
11
+ if (settled) return;
12
+ settled = true;
13
+ signals.forEach((signal) => signal.removeEventListener('abort', cancel));
14
+ callback(value);
15
+ };
16
+ const cancel = () => {
17
+ const error = new Error('IIIF tool execution was cancelled.');
18
+ error.name = 'AbortError';
19
+ finish(reject, error);
20
+ };
21
+ if (signals.some((signal) => signal.aborted)) return cancel();
22
+ signals.forEach((signal) => signal.addEventListener('abort', cancel, { once: true }));
23
+ Promise.resolve()
24
+ .then(() => !settled && tool.execute(input, options))
25
+ .then(
26
+ (result) => finish(resolve, result),
27
+ (error) => finish(reject, error),
28
+ );
29
+ });
30
+ }
31
+
32
+ function initializeWebMcp({
33
+ document: doc = globalThis.document,
34
+ window: win = globalThis.window,
35
+ script = doc?.currentScript,
36
+ fetch: fetchJson = win?.fetch?.bind(win),
37
+ } = {}) {
38
+ let modelContext;
39
+ try {
40
+ modelContext = doc?.modelContext;
41
+ } catch {
42
+ return null;
43
+ }
44
+ if (!modelContext?.registerTool || !win?.addEventListener || !fetchJson) return null;
45
+ if (doc[registrationKey]) return doc[registrationKey];
46
+ const catalogPath = script?.getAttribute('data-canopy-discovery');
47
+ if (!catalogPath) return null;
48
+
49
+ let controller;
50
+ let disposed = false;
51
+ const stop = () => {
52
+ controller?.abort();
53
+ controller = null;
54
+ };
55
+ const state = {
56
+ ready: null,
57
+ dispose() {
58
+ disposed = true;
59
+ stop();
60
+ win.removeEventListener('pagehide', stop);
61
+ win.removeEventListener('pageshow', restore);
62
+ if (doc[registrationKey] === state) delete doc[registrationKey];
63
+ },
64
+ };
65
+
66
+ async function start() {
67
+ if (disposed || controller) return false;
68
+ const registration = new (win.AbortController || AbortController)();
69
+ controller = registration;
70
+ try {
71
+ const loaders = createBrowserLoader({
72
+ catalogUrl: new URL(catalogPath, doc.baseURI).href,
73
+ origin: new URL(win.location.href).origin,
74
+ fetch: fetchJson,
75
+ signal: registration.signal,
76
+ });
77
+ const tools = createDiscoveryTools(loaders);
78
+ await Promise.all(
79
+ tools.map((tool) =>
80
+ Promise.resolve().then(() =>
81
+ modelContext.registerTool(
82
+ {
83
+ ...tool,
84
+ execute: (input, options) =>
85
+ executeWithCancellation(tool, input, options, registration.signal),
86
+ },
87
+ { signal: registration.signal },
88
+ ),
89
+ ),
90
+ ),
91
+ );
92
+ return !registration.signal.aborted;
93
+ } catch (error) {
94
+ const cancelled = registration.signal.aborted;
95
+ registration.abort();
96
+ if (controller === registration) controller = null;
97
+ if (!cancelled) win.console?.warn('[Canopy] IIIF tools could not be registered.', error);
98
+ return false;
99
+ }
100
+ }
101
+
102
+ function restore(event) {
103
+ if (event.persisted) state.ready = start();
104
+ }
105
+
106
+ doc[registrationKey] = state;
107
+ win.addEventListener('pagehide', stop);
108
+ win.addEventListener('pageshow', restore);
109
+ state.ready = start();
110
+ return state;
111
+ }
112
+
113
+ module.exports = { initializeWebMcp };
114
+
115
+ if (typeof document !== 'undefined') initializeWebMcp();
@@ -0,0 +1,25 @@
1
+ const fs = require('node:fs');
2
+ const yaml = require('js-yaml');
3
+ const { resolveCanopyConfigPath } = require('../config-path');
4
+
5
+ function webMcpEnabled(config) {
6
+ const value = config?.webmcp;
7
+ if (value === undefined) return true;
8
+ if (typeof value !== 'boolean') throw new TypeError('webmcp must be true or false.');
9
+ return value;
10
+ }
11
+ function readWebMcpEnabled() {
12
+ try {
13
+ return webMcpEnabled(yaml.load(fs.readFileSync(resolveCanopyConfigPath(), 'utf8')));
14
+ } catch (error) {
15
+ if (error.code === 'ENOENT') return true;
16
+ throw error;
17
+ }
18
+ }
19
+ function webMcpScriptTag(withBase) {
20
+ if (!readWebMcpEnabled()) return '';
21
+ const escape = (value) =>
22
+ String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
23
+ return `<script defer src="${escape(withBase('/scripts/canopy-webmcp.js'))}" data-canopy-discovery="${escape(withBase('/api/discovery/index.json'))}"></script>`;
24
+ }
25
+ module.exports = { webMcpEnabled, readWebMcpEnabled, webMcpScriptTag };