@thedatagrid/docs-kit 0.3.0 → 0.4.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 (177) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +149 -4
  3. package/dist/code/demoFiles.d.ts.map +1 -1
  4. package/dist/code/demoFiles.js +2 -2
  5. package/dist/code/demoFiles.js.map +1 -1
  6. package/dist/code/index.d.ts +1 -0
  7. package/dist/code/index.d.ts.map +1 -1
  8. package/dist/code/index.js +1 -0
  9. package/dist/code/index.js.map +1 -1
  10. package/dist/code/regions.d.ts +2 -1
  11. package/dist/code/regions.d.ts.map +1 -1
  12. package/dist/code/regions.js +12 -8
  13. package/dist/code/regions.js.map +1 -1
  14. package/dist/code/vueBlocks.d.ts +3 -0
  15. package/dist/code/vueBlocks.d.ts.map +1 -0
  16. package/dist/code/vueBlocks.js +29 -0
  17. package/dist/code/vueBlocks.js.map +1 -0
  18. package/dist/demos/build.d.ts +5 -2
  19. package/dist/demos/build.d.ts.map +1 -1
  20. package/dist/demos/build.js +244 -85
  21. package/dist/demos/build.js.map +1 -1
  22. package/dist/demos/compile/core.d.ts +9 -1
  23. package/dist/demos/compile/core.d.ts.map +1 -1
  24. package/dist/demos/compile/core.js +19 -8
  25. package/dist/demos/compile/core.js.map +1 -1
  26. package/dist/demos/compile/vue.d.ts +107 -0
  27. package/dist/demos/compile/vue.d.ts.map +1 -0
  28. package/dist/demos/compile/vue.js +187 -0
  29. package/dist/demos/compile/vue.js.map +1 -0
  30. package/dist/demos/config.d.ts +27 -7
  31. package/dist/demos/config.d.ts.map +1 -1
  32. package/dist/demos/config.js.map +1 -1
  33. package/dist/demos/index.d.ts +3 -2
  34. package/dist/demos/index.d.ts.map +1 -1
  35. package/dist/demos/index.js +1 -0
  36. package/dist/demos/index.js.map +1 -1
  37. package/dist/demos/pages.d.ts +1 -1
  38. package/dist/demos/pages.d.ts.map +1 -1
  39. package/dist/demos/pages.js +4 -1
  40. package/dist/demos/pages.js.map +1 -1
  41. package/dist/demos/runtime/vue.d.ts +3 -0
  42. package/dist/demos/runtime/vue.d.ts.map +1 -0
  43. package/dist/demos/runtime/vue.js +15 -0
  44. package/dist/demos/runtime/vue.js.map +1 -0
  45. package/dist/demos/worker/compile.worker.js +3 -22
  46. package/dist/demos/worker/compile.worker.js.map +1 -1
  47. package/dist/demos/worker/compileVue.worker.d.ts +2 -0
  48. package/dist/demos/worker/compileVue.worker.d.ts.map +1 -0
  49. package/dist/demos/worker/compileVue.worker.js +11 -0
  50. package/dist/demos/worker/compileVue.worker.js.map +1 -0
  51. package/dist/demos/worker/start.d.ts +7 -0
  52. package/dist/demos/worker/start.d.ts.map +1 -0
  53. package/dist/demos/worker/start.js +27 -0
  54. package/dist/demos/worker/start.js.map +1 -0
  55. package/dist/fork/codesandbox.d.ts +15 -1
  56. package/dist/fork/codesandbox.d.ts.map +1 -1
  57. package/dist/fork/codesandbox.js +30 -19
  58. package/dist/fork/codesandbox.js.map +1 -1
  59. package/dist/fork/index.d.ts +18 -0
  60. package/dist/fork/index.d.ts.map +1 -1
  61. package/dist/fork/index.js +18 -0
  62. package/dist/fork/index.js.map +1 -1
  63. package/dist/fork/stackblitz.d.ts +18 -0
  64. package/dist/fork/stackblitz.d.ts.map +1 -0
  65. package/dist/fork/stackblitz.js +98 -0
  66. package/dist/fork/stackblitz.js.map +1 -0
  67. package/dist/frameworks/index.d.ts +4 -0
  68. package/dist/frameworks/index.d.ts.map +1 -0
  69. package/dist/frameworks/index.js +4 -0
  70. package/dist/frameworks/index.js.map +1 -0
  71. package/dist/frameworks/preference.d.ts +10 -0
  72. package/dist/frameworks/preference.d.ts.map +1 -0
  73. package/dist/frameworks/preference.js +34 -0
  74. package/dist/frameworks/preference.js.map +1 -0
  75. package/dist/frameworks/react/FrameworkBanner.d.ts +34 -0
  76. package/dist/frameworks/react/FrameworkBanner.d.ts.map +1 -0
  77. package/dist/frameworks/react/FrameworkBanner.js +50 -0
  78. package/dist/frameworks/react/FrameworkBanner.js.map +1 -0
  79. package/dist/frameworks/react/FrameworkContent.d.ts +21 -0
  80. package/dist/frameworks/react/FrameworkContent.d.ts.map +1 -0
  81. package/dist/frameworks/react/FrameworkContent.js +25 -0
  82. package/dist/frameworks/react/FrameworkContent.js.map +1 -0
  83. package/dist/frameworks/react/FrameworkLinks.d.ts +16 -0
  84. package/dist/frameworks/react/FrameworkLinks.d.ts.map +1 -0
  85. package/dist/frameworks/react/FrameworkLinks.js +50 -0
  86. package/dist/frameworks/react/FrameworkLinks.js.map +1 -0
  87. package/dist/frameworks/react/FrameworkSwitcher.d.ts +27 -0
  88. package/dist/frameworks/react/FrameworkSwitcher.d.ts.map +1 -0
  89. package/dist/frameworks/react/FrameworkSwitcher.js +42 -0
  90. package/dist/frameworks/react/FrameworkSwitcher.js.map +1 -0
  91. package/dist/frameworks/react/index.d.ts +6 -0
  92. package/dist/frameworks/react/index.d.ts.map +1 -0
  93. package/dist/frameworks/react/index.js +6 -0
  94. package/dist/frameworks/react/index.js.map +1 -0
  95. package/dist/frameworks/react/useFrameworkPreference.d.ts +32 -0
  96. package/dist/frameworks/react/useFrameworkPreference.d.ts.map +1 -0
  97. package/dist/frameworks/react/useFrameworkPreference.js +45 -0
  98. package/dist/frameworks/react/useFrameworkPreference.js.map +1 -0
  99. package/dist/frameworks/routeTree.d.ts +24 -0
  100. package/dist/frameworks/routeTree.d.ts.map +1 -0
  101. package/dist/frameworks/routeTree.js +31 -0
  102. package/dist/frameworks/routeTree.js.map +1 -0
  103. package/dist/frameworks/routing.d.ts +105 -0
  104. package/dist/frameworks/routing.d.ts.map +1 -0
  105. package/dist/frameworks/routing.js +142 -0
  106. package/dist/frameworks/routing.js.map +1 -0
  107. package/dist/frameworks/styles.css +104 -0
  108. package/dist/react/Demo.d.ts +12 -0
  109. package/dist/react/Demo.d.ts.map +1 -1
  110. package/dist/react/Demo.js +10 -4
  111. package/dist/react/Demo.js.map +1 -1
  112. package/dist/react/DemoShell.d.ts +5 -1
  113. package/dist/react/DemoShell.d.ts.map +1 -1
  114. package/dist/react/DemoShell.js +9 -6
  115. package/dist/react/DemoShell.js.map +1 -1
  116. package/dist/react/editor.d.ts.map +1 -1
  117. package/dist/react/editor.js +3 -0
  118. package/dist/react/editor.js.map +1 -1
  119. package/dist/react/fork.d.ts +4 -3
  120. package/dist/react/fork.d.ts.map +1 -1
  121. package/dist/react/fork.js +6 -5
  122. package/dist/react/fork.js.map +1 -1
  123. package/dist/react/styles.css +10 -0
  124. package/dist/remark/index.d.ts +2 -0
  125. package/dist/remark/index.d.ts.map +1 -1
  126. package/dist/remark/index.js +2 -0
  127. package/dist/remark/index.js.map +1 -1
  128. package/dist/remark/remarkDemoFences.d.ts +13 -0
  129. package/dist/remark/remarkDemoFences.d.ts.map +1 -1
  130. package/dist/remark/remarkDemoFences.js +48 -4
  131. package/dist/remark/remarkDemoFences.js.map +1 -1
  132. package/dist/remark/remarkFrameworkLinks.d.ts +36 -0
  133. package/dist/remark/remarkFrameworkLinks.d.ts.map +1 -0
  134. package/dist/remark/remarkFrameworkLinks.js +77 -0
  135. package/dist/remark/remarkFrameworkLinks.js.map +1 -0
  136. package/dist/remark/remarkFrameworkText.d.ts +16 -0
  137. package/dist/remark/remarkFrameworkText.d.ts.map +1 -0
  138. package/dist/remark/remarkFrameworkText.js +39 -0
  139. package/dist/remark/remarkFrameworkText.js.map +1 -0
  140. package/package.json +29 -4
  141. package/src/code/demoFiles.ts +2 -2
  142. package/src/code/index.ts +1 -0
  143. package/src/code/regions.ts +14 -8
  144. package/src/code/vueBlocks.ts +25 -0
  145. package/src/demos/build.ts +293 -99
  146. package/src/demos/compile/core.ts +27 -7
  147. package/src/demos/compile/vue.ts +259 -0
  148. package/src/demos/config.ts +44 -7
  149. package/src/demos/index.ts +13 -0
  150. package/src/demos/pages.ts +4 -2
  151. package/src/demos/runtime/vue.ts +17 -0
  152. package/src/demos/worker/compile.worker.ts +3 -30
  153. package/src/demos/worker/compileVue.worker.ts +13 -0
  154. package/src/demos/worker/start.ts +35 -0
  155. package/src/fork/codesandbox.ts +43 -21
  156. package/src/fork/index.ts +25 -0
  157. package/src/fork/stackblitz.ts +107 -0
  158. package/src/frameworks/index.ts +21 -0
  159. package/src/frameworks/preference.ts +35 -0
  160. package/src/frameworks/react/FrameworkBanner.tsx +112 -0
  161. package/src/frameworks/react/FrameworkContent.tsx +33 -0
  162. package/src/frameworks/react/FrameworkLinks.tsx +52 -0
  163. package/src/frameworks/react/FrameworkSwitcher.tsx +78 -0
  164. package/src/frameworks/react/index.ts +10 -0
  165. package/src/frameworks/react/useFrameworkPreference.ts +91 -0
  166. package/src/frameworks/routeTree.ts +54 -0
  167. package/src/frameworks/routing.ts +194 -0
  168. package/src/frameworks/styles.css +104 -0
  169. package/src/react/Demo.tsx +21 -2
  170. package/src/react/DemoShell.tsx +15 -7
  171. package/src/react/editor.ts +2 -0
  172. package/src/react/fork.ts +12 -5
  173. package/src/react/styles.css +10 -0
  174. package/src/remark/index.ts +6 -0
  175. package/src/remark/remarkDemoFences.ts +58 -3
  176. package/src/remark/remarkFrameworkLinks.ts +96 -0
  177. package/src/remark/remarkFrameworkText.ts +44 -0
@@ -1,15 +1,20 @@
1
1
  /**
2
- * Prebuilds every `content/**\/*.demo.tsx` into a static iframe page under
3
- * `<outDir>/<content-relative id>/index.html`:
2
+ * Prebuilds every demo entry (`content/**\/*.demo.tsx`, and
3
+ * `content/**\/*.demo.vue` for a Vue framework) into a static iframe page
4
+ * under `<outDir>/<content-relative id>/index.html`:
4
5
  *
5
6
  * - `_lib/`: the import map's targets. Each package the demos import (and the
6
7
  * configured libraries, built from source) is an ESM entry; one split build,
7
- * so shared code (React) exists once.
8
+ * so shared code (React, Vue) exists once.
8
9
  * - `_runtime/`: the iframe runtime + framework adapter + site bootstrap.
9
10
  * - `<id>/demo-[hash].js`: the demo's own code, every bare import external.
10
- * - `_editor/`: the compile worker and esbuild.wasm for in-browser rebuilds.
11
+ * - `_editor/`: the compile workers and esbuild.wasm for in-browser rebuilds.
11
12
  * - `manifest.json`: what the docs UI needs (import map, editor, demos).
12
13
  *
14
+ * The primary framework builds into `<outDir>`. Each framework under
15
+ * `config.frameworks` builds the same way into `<outDir>/_<framework>`, with
16
+ * its own import map, runtime and manifest; `_editor` is shared.
17
+ *
13
18
  * `watch: true` keeps esbuild contexts alive, rebuilds on content / library
14
19
  * changes and streams `{ type: 'demo' }` events so open iframes reload.
15
20
  */
@@ -17,12 +22,13 @@ import crypto from 'node:crypto';
17
22
  import fs from 'node:fs';
18
23
  import { createRequire } from 'node:module';
19
24
  import path from 'node:path';
20
- import { fileURLToPath } from 'node:url';
25
+ import { fileURLToPath, pathToFileURL } from 'node:url';
21
26
  import * as esbuild from 'esbuild';
22
27
 
23
28
  import { bareImports, collectDemoFiles } from '../code/demoFiles.ts';
24
29
  import { demoBuildOptions, externalImportsPlugin, matchesStub } from './compile/core.ts';
25
- import type { DemoManifest, DocsKitConfig, LibrarySource } from './config.ts';
30
+ import { createVueModules, vueFilesPlugin, type VueSfcCompiler } from './compile/vue.ts';
31
+ import type { DemoFramework, DemoManifest, DocsKitConfig, FrameworkConfig, LibrarySource } from './config.ts';
26
32
  import { startDevEvents } from './devEvents.ts';
27
33
  import { demoPageHtml, themeInitScript } from './html.ts';
28
34
  import { defaultRouteForPage, findDocsLinks, findFiles } from './pages.ts';
@@ -33,7 +39,42 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
33
39
  const EXT = import.meta.url.endsWith('.ts') ? '.ts' : '.js';
34
40
  const kitFile = (rel: string) => path.join(HERE, `${rel}${EXT}`);
35
41
 
36
- const FRAMEWORK_SPECIFIERS = { react: ['react', 'react/jsx-runtime', 'react-dom/client'] };
42
+ type FrameworkTraits = {
43
+ /** Always in the import map: what the runtime adapter and compiled demos import. */
44
+ specifiers: string[];
45
+ demoSuffix: string;
46
+ /** Kit module and export of the iframe runtime's adapter. */
47
+ adapter: [file: string, name: string];
48
+ /** Kit module of the editor's compile worker. */
49
+ worker: [file: string, outName: string];
50
+ jsxImportSource?: string;
51
+ define?: Record<string, string>;
52
+ };
53
+
54
+ const FRAMEWORKS: Record<DemoFramework, FrameworkTraits> = {
55
+ react: {
56
+ specifiers: ['react', 'react/jsx-runtime', 'react-dom/client'],
57
+ demoSuffix: '.demo.tsx',
58
+ adapter: ['runtime/react', 'reactAdapter'],
59
+ worker: ['worker/compile.worker', 'compile-worker'],
60
+ },
61
+ vue: {
62
+ specifiers: ['vue', 'vue/jsx-runtime'],
63
+ demoSuffix: '.demo.vue',
64
+ adapter: ['runtime/vue', 'vueAdapter'],
65
+ worker: ['worker/compileVue.worker', 'compile-worker-vue'],
66
+ jsxImportSource: 'vue',
67
+ // the feature flags of Vue's bundler build
68
+ define: {
69
+ __VUE_OPTIONS_API__: 'true',
70
+ __VUE_PROD_DEVTOOLS__: 'false',
71
+ __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false',
72
+ },
73
+ },
74
+ };
75
+
76
+ /** Top-level keys a framework under `frameworks` doesn't inherit. */
77
+ const FRAMEWORK_SPECIFIC = ['demoSuffix', 'libraries', 'include', 'stubImports', 'bootstrap', 'css', 'fork'] as const;
37
78
 
38
79
  const ASSET_LOADERS: Record<string, esbuild.Loader> = {
39
80
  '.png': 'file',
@@ -60,8 +101,11 @@ export type BuildDemosOptions = {
60
101
  };
61
102
 
62
103
  export type BuildDemosResult = {
104
+ /** The primary framework's manifest. */
63
105
  manifest: DemoManifest;
64
- /** Ids whose page changed in the last build. */
106
+ /** Every framework's manifest. */
107
+ manifests: Partial<Record<DemoFramework, DemoManifest>>;
108
+ /** Ids whose page changed in the last build (primary framework). */
65
109
  changed: string[];
66
110
  /** Watch mode: stops watching and disposes the esbuild contexts. */
67
111
  close(): Promise<void>;
@@ -71,8 +115,33 @@ type Demo = { id: string; file: string };
71
115
 
72
116
  type Settings = ReturnType<typeof resolveSettings>;
73
117
 
74
- function resolveSettings(options: BuildDemosOptions) {
75
- const { config } = options;
118
+ type FrameworkTarget = {
119
+ framework: DemoFramework;
120
+ primary: boolean;
121
+ /** The effective config of this framework's build. */
122
+ config: DocsKitConfig;
123
+ };
124
+
125
+ /** The primary framework, then each one under `config.frameworks`. */
126
+ function frameworkTargets(config: DocsKitConfig): FrameworkTarget[] {
127
+ const primary = config.framework ?? 'react';
128
+ const { frameworks = {}, ...base } = config;
129
+ const targets: FrameworkTarget[] = [
130
+ { framework: primary, primary: true, config: { ...base, ...frameworks[primary], framework: primary } },
131
+ ];
132
+ for (const [framework, overrides] of Object.entries(frameworks) as [DemoFramework, FrameworkConfig][]) {
133
+ if (framework === primary) continue;
134
+ if (!FRAMEWORKS[framework]) throw new Error(`docs-kit: unknown framework "${framework}" in \`frameworks\``);
135
+ const shared: DocsKitConfig = { ...base };
136
+ for (const key of FRAMEWORK_SPECIFIC) delete shared[key];
137
+ targets.push({ framework, primary: false, config: { ...shared, ...overrides, framework } });
138
+ }
139
+ return targets;
140
+ }
141
+
142
+ function resolveSettings(options: BuildDemosOptions, target: FrameworkTarget) {
143
+ const { config, framework } = target;
144
+ const traits = FRAMEWORKS[framework];
76
145
  const root = path.resolve(options.configDir, config.root ?? '.');
77
146
  const production = config.production ?? process.env.NODE_ENV === 'production';
78
147
  const libraries: Record<string, LibrarySource> = {};
@@ -84,28 +153,38 @@ function resolveSettings(options: BuildDemosOptions) {
84
153
  );
85
154
  const define = {
86
155
  'process.env.NODE_ENV': JSON.stringify(production ? 'production' : 'development'),
156
+ ...traits.define,
87
157
  ...config.define,
88
158
  };
159
+ const rootOutDir = path.resolve(root, config.outDir ?? 'public/gen/demos');
160
+ const rootUrl = (config.urlRoot ?? '/gen/demos').replace(/\/+$/, '');
161
+ const subDir = target.primary ? '' : `_${framework}`;
89
162
  return {
90
163
  root,
91
164
  production,
165
+ framework,
166
+ primary: target.primary,
167
+ traits,
92
168
  contentDir: path.resolve(root, config.contentDir ?? 'content'),
93
- outDir: path.resolve(root, config.outDir ?? 'public/gen/demos'),
94
- urlRoot: (config.urlRoot ?? '/gen/demos').replace(/\/+$/, ''),
95
- demoSuffix: config.demoSuffix ?? '.demo.tsx',
169
+ /** Shared by every framework: the `_editor` assets live here. */
170
+ rootOutDir,
171
+ rootUrl,
172
+ outDir: subDir ? path.join(rootOutDir, subDir) : rootOutDir,
173
+ urlRoot: subDir ? `${rootUrl}/${subDir}` : rootUrl,
174
+ demoSuffix: config.demoSuffix ?? traits.demoSuffix,
96
175
  pageExtension: config.pageExtension ?? '.page.md',
97
176
  routeForPage: config.routeForPage ?? defaultRouteForPage,
98
177
  anchorPrefix: config.anchorPrefix ?? '',
99
178
  fenceDefaults: config.fenceDefaults,
100
- framework: config.framework ?? 'react',
101
179
  libraries,
180
+ include: config.include ?? [],
102
181
  stubImports,
103
182
  define,
104
183
  bootstrapDefine: { ...define, ...config.bootstrapDefine },
105
184
  bootstrap: config.bootstrap ? path.resolve(root, config.bootstrap) : null,
106
185
  extraCss: (config.css ?? []).map((file) => path.resolve(root, file)),
107
186
  nodePaths: config.nodePaths?.map((p) => path.resolve(root, p)) ?? [path.join(root, 'node_modules')],
108
- workDir: path.join(root, 'node_modules/.cache/docs-kit'),
187
+ workDir: path.join(root, 'node_modules/.cache/docs-kit', subDir),
109
188
  themeClasses: config.themeClasses ?? {},
110
189
  devEventsPort: config.devEventsPort ?? 4748,
111
190
  };
@@ -117,7 +196,7 @@ function discover(settings: Settings) {
117
196
  id: toPosix(path.relative(settings.contentDir, file)).slice(0, -settings.demoSuffix.length),
118
197
  }));
119
198
 
120
- const specifiers = new Set<string>(FRAMEWORK_SPECIFIERS[settings.framework]);
199
+ const specifiers = new Set<string>([...settings.traits.specifiers, ...settings.include]);
121
200
  for (const specifier of Object.keys(settings.libraries)) specifiers.add(specifier);
122
201
  const sources: string[] = [];
123
202
  for (const demo of demos) {
@@ -133,12 +212,13 @@ function discover(settings: Settings) {
133
212
 
134
213
  function writeRuntimeEntry(settings: Settings, config: DocsKitConfig): string {
135
214
  const entry = path.join(settings.workDir, 'runtime-entry.mjs');
215
+ const [adapterFile, adapterName] = settings.traits.adapter;
136
216
  const lines = [
137
217
  `import { createRuntime } from ${JSON.stringify(kitFile('runtime/iframe'))};`,
138
- `import { reactAdapter } from ${JSON.stringify(kitFile('runtime/react'))};`,
218
+ `import { ${adapterName} as adapter } from ${JSON.stringify(kitFile(adapterFile))};`,
139
219
  settings.bootstrap ? `import * as site from ${JSON.stringify(settings.bootstrap)};` : 'const site = {};',
140
220
  `export const { mount, fail } = createRuntime({`,
141
- ` adapter: reactAdapter,`,
221
+ ` adapter,`,
142
222
  ` site,`,
143
223
  ` themeStorageKey: ${JSON.stringify(config.themeStorageKey ?? null)} ?? undefined,`,
144
224
  ` defaultTheme: ${JSON.stringify(config.defaultTheme ?? 'light')},`,
@@ -150,6 +230,27 @@ function writeRuntimeEntry(settings: Settings, config: DocsKitConfig): string {
150
230
  return entry;
151
231
  }
152
232
 
233
+ /**
234
+ * `@vue/compiler-sfc` from the site's `node_modules` (an optional peer
235
+ * dependency: only loaded for a Vue framework).
236
+ */
237
+ async function loadVueCompiler(settings: Settings): Promise<VueSfcCompiler> {
238
+ const require = createRequire(path.join(settings.root, 'package.json'));
239
+ let resolved: string;
240
+ try {
241
+ resolved = require.resolve('@vue/compiler-sfc', {
242
+ paths: [settings.root, ...settings.nodePaths.map((p) => path.dirname(p))],
243
+ });
244
+ } catch {
245
+ throw new Error(
246
+ 'docs-kit: Vue demos need `@vue/compiler-sfc` (and `vue`) installed in the site: ' +
247
+ 'npm i vue && npm i -D @vue/compiler-sfc',
248
+ );
249
+ }
250
+ const loaded = (await import(pathToFileURL(resolved).href)) as { default?: unknown };
251
+ return ((loaded as { parse?: unknown }).parse ? loaded : loaded.default) as VueSfcCompiler;
252
+ }
253
+
153
254
  async function createContexts(settings: Settings, config: DocsKitConfig, demos: Demo[], vendor: VendorEntries) {
154
255
  const libraryPlugins: esbuild.Plugin[] = [];
155
256
  for (const library of Object.values(settings.libraries)) {
@@ -162,6 +263,20 @@ async function createContexts(settings: Settings, config: DocsKitConfig, demos:
162
263
  logLevel: 'silent' as const,
163
264
  loader: ASSET_LOADERS,
164
265
  };
266
+ const { jsxImportSource } = settings.traits;
267
+
268
+ // demo files only: scope ids and error messages use content-relative names
269
+ const frameworkPlugins: esbuild.Plugin[] = [];
270
+ if (settings.framework === 'vue') {
271
+ const modules = createVueModules(await loadVueCompiler(settings), { production: settings.production });
272
+ frameworkPlugins.push(
273
+ vueFilesPlugin(
274
+ modules,
275
+ (file) => fs.readFileSync(file, 'utf8'),
276
+ (file) => toPosix(path.relative(settings.contentDir, file)),
277
+ ),
278
+ );
279
+ }
165
280
 
166
281
  const vendorCtx = await esbuild.context({
167
282
  ...common,
@@ -172,6 +287,7 @@ async function createContexts(settings: Settings, config: DocsKitConfig, demos:
172
287
  platform: 'browser',
173
288
  target: 'es2022',
174
289
  jsx: 'automatic',
290
+ jsxImportSource,
175
291
  outdir: path.join(settings.outDir, '_lib'),
176
292
  entryNames: '[name]-[hash]',
177
293
  chunkNames: 'chunk-[hash]',
@@ -193,7 +309,7 @@ async function createContexts(settings: Settings, config: DocsKitConfig, demos:
193
309
 
194
310
  const runtimeCtx = await esbuild.context({
195
311
  ...common,
196
- ...demoBuildOptions({ define: settings.bootstrapDefine, minify: settings.production }),
312
+ ...demoBuildOptions({ define: settings.bootstrapDefine, minify: settings.production, jsxImportSource }),
197
313
  entryPoints: { runtime: writeRuntimeEntry(settings, config) },
198
314
  outdir: path.join(settings.outDir, '_runtime'),
199
315
  entryNames: '[name]-[hash]',
@@ -202,7 +318,7 @@ async function createContexts(settings: Settings, config: DocsKitConfig, demos:
202
318
 
203
319
  const demosCtx = await esbuild.context({
204
320
  ...common,
205
- ...demoBuildOptions({ define: settings.define, minify: settings.production }),
321
+ ...demoBuildOptions({ define: settings.define, minify: settings.production, jsxImportSource }),
206
322
  entryPoints: Object.fromEntries(demos.map((demo) => [`${demo.id}/demo`, demo.file])),
207
323
  outdir: settings.outDir,
208
324
  splitting: true,
@@ -210,41 +326,60 @@ async function createContexts(settings: Settings, config: DocsKitConfig, demos:
210
326
  chunkNames: '_chunks/chunk-[hash]',
211
327
  assetNames: '_assets/[name]-[hash]',
212
328
  sourcemap: !settings.production,
213
- plugins: [externalImportsPlugin(settings.stubImports)],
329
+ plugins: [externalImportsPlugin(settings.stubImports), ...frameworkPlugins],
214
330
  });
215
331
 
216
332
  return { vendorCtx, runtimeCtx, demosCtx };
217
333
  }
218
334
 
219
- /** Builds the compile worker and copies esbuild.wasm (hashed: they're cached as immutable). */
220
- async function buildEditorAssets(settings: Settings) {
221
- const outDir = path.join(settings.outDir, '_editor');
335
+ /** Copies esbuild.wasm (hashed: it's cached as immutable). Shared by every framework. */
336
+ function copyEsbuildWasm(settings: Settings): string {
337
+ const outDir = path.join(settings.rootOutDir, '_editor');
338
+ const require = createRequire(import.meta.url);
339
+ const wasmPath = path.join(path.dirname(require.resolve('esbuild-wasm/package.json')), 'esbuild.wasm');
340
+ const wasm = fs.readFileSync(wasmPath);
341
+ const wasmName = `esbuild-${shortHash(wasm)}.wasm`;
342
+ fs.mkdirSync(outDir, { recursive: true });
343
+ fs.writeFileSync(path.join(outDir, wasmName), wasm);
344
+ return `${settings.rootUrl}/_editor/${wasmName}`;
345
+ }
346
+
347
+ /** Builds a framework's compile worker into the shared `_editor` folder. */
348
+ async function buildCompileWorker(settings: Settings): Promise<string> {
349
+ const [workerFile, outName] = settings.traits.worker;
222
350
  const result = await esbuild.build({
223
- entryPoints: { 'compile-worker': kitFile('worker/compile.worker') },
351
+ entryPoints: { [outName]: kitFile(workerFile) },
224
352
  bundle: true,
225
353
  format: 'esm',
226
354
  platform: 'browser',
227
355
  target: 'es2022',
228
- outdir: outDir,
356
+ outdir: path.join(settings.rootOutDir, '_editor'),
229
357
  entryNames: '[name]-[hash]',
230
358
  minify: true,
231
359
  metafile: true,
232
360
  logLevel: 'silent',
233
361
  absWorkingDir: settings.root,
362
+ nodePaths: settings.nodePaths,
363
+ plugins: [
364
+ {
365
+ // the site's copy of the framework compiler, not one next to the kit
366
+ name: 'docs-kit:site-compiler',
367
+ setup(build) {
368
+ build.onResolve({ filter: /^@vue\/compiler-sfc$/ }, async (args) => {
369
+ if (args.pluginData?.docsKitSite) return undefined;
370
+ const result = await build.resolve(args.path, {
371
+ kind: args.kind,
372
+ resolveDir: settings.root,
373
+ pluginData: { docsKitSite: true },
374
+ });
375
+ return result.errors.length ? undefined : { path: result.path };
376
+ });
377
+ },
378
+ },
379
+ ],
234
380
  });
235
381
  const workerOut = Object.keys(result.metafile.outputs).find((file) => file.endsWith('.js'))!;
236
-
237
- const require = createRequire(import.meta.url);
238
- const wasmPath = path.join(path.dirname(require.resolve('esbuild-wasm/package.json')), 'esbuild.wasm');
239
- const wasm = fs.readFileSync(wasmPath);
240
- const wasmName = `esbuild-${shortHash(wasm)}.wasm`;
241
- fs.mkdirSync(outDir, { recursive: true });
242
- fs.writeFileSync(path.join(outDir, wasmName), wasm);
243
-
244
- return {
245
- worker: `${settings.urlRoot}/${toPosix(path.relative(settings.outDir, path.resolve(settings.root, workerOut)))}`,
246
- wasm: `${settings.urlRoot}/_editor/${wasmName}`,
247
- };
382
+ return `${settings.rootUrl}/${toPosix(path.relative(settings.rootOutDir, path.resolve(settings.root, workerOut)))}`;
248
383
  }
249
384
 
250
385
  function copyExtraCss(settings: Settings): string[] {
@@ -258,35 +393,51 @@ function copyExtraCss(settings: Settings): string[] {
258
393
  });
259
394
  }
260
395
 
261
- export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemosResult> {
262
- const { config, watch = false } = options;
263
- const log = options.log ?? ((message: string) => console.log(`[docs-kit] ${message}`));
264
- const settings = resolveSettings(options);
396
+ type FrameworkBuild = {
397
+ settings: Settings;
398
+ manifest(): DemoManifest;
399
+ /** Rebuilds; returns the ids whose page changed. */
400
+ run(): Promise<string[]>;
401
+ /** Re-reads the content folder; recreates the esbuild contexts when demos or imports changed. */
402
+ refresh(): Promise<void>;
403
+ dispose(): Promise<void>;
404
+ };
405
+
406
+ async function createFrameworkBuild(
407
+ options: BuildDemosOptions,
408
+ target: FrameworkTarget,
409
+ shared: { wasm: string; fenceSuffix: string; log: (message: string) => void },
410
+ ): Promise<FrameworkBuild> {
411
+ const { config } = target;
412
+ const { watch = false } = options;
413
+ const settings = resolveSettings(options, target);
414
+ const log = (message: string) => shared.log(target.primary ? message : `[${settings.framework}] ${message}`);
265
415
  const urlFor = (outFile: string) =>
266
416
  `${settings.urlRoot}/${toPosix(path.relative(settings.outDir, path.resolve(settings.root, outFile)))}`;
267
417
 
268
- // Output names are content-hashed and never pruned during a run, so start
269
- // clean: a stale page could point at bundles from an older config.
270
- fs.rmSync(settings.outDir, { recursive: true, force: true });
271
418
  fs.mkdirSync(settings.outDir, { recursive: true });
272
-
273
- const editorAssets = await buildEditorAssets(settings);
419
+ const worker = await buildCompileWorker(settings);
420
+
421
+ const vendorEntries = (specifiers: string[]) =>
422
+ writeVendorEntries({
423
+ specifiers,
424
+ libraries: settings.libraries,
425
+ root: settings.root,
426
+ nodePaths: settings.nodePaths,
427
+ workDir: path.join(settings.workDir, 'vendor'),
428
+ warn: (message) => log(`warning: ${message}`),
429
+ });
274
430
 
275
431
  let state = discover(settings);
276
- let vendor = await writeVendorEntries({
277
- specifiers: state.specifiers,
278
- libraries: settings.libraries,
279
- root: settings.root,
280
- nodePaths: settings.nodePaths,
281
- workDir: path.join(settings.workDir, 'vendor'),
282
- warn: (message) => log(`warning: ${message}`),
283
- });
432
+ let vendor = await vendorEntries(state.specifiers);
284
433
  let contexts = await createContexts(settings, config, state.demos, vendor);
285
- const devEvents = watch ? startDevEvents(settings.devEventsPort, log) : null;
286
-
287
434
  let manifest: DemoManifest | null = null;
288
435
 
289
- const runBuild = async (): Promise<string[]> => {
436
+ const dispose = async () => {
437
+ await Promise.all([contexts.vendorCtx.dispose(), contexts.runtimeCtx.dispose(), contexts.demosCtx.dispose()]);
438
+ };
439
+
440
+ const run = async (): Promise<string[]> => {
290
441
  const started = Date.now();
291
442
  const [vendorResult, runtimeResult, demosResult] = await Promise.all([
292
443
  contexts.vendorCtx.rebuild(),
@@ -311,7 +462,8 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
311
462
  const runtimeOut = Object.entries(runtimeResult.metafile!.outputs).find(([, meta]) => meta.entryPoint)!;
312
463
  const runtimeUrl = urlFor(runtimeOut[0]);
313
464
 
314
- const docsLinks = findDocsLinks(settings);
465
+ // fences name the primary framework's file; a sibling demo has the same id
466
+ const docsLinks = findDocsLinks({ ...settings, demoSuffix: shared.fenceSuffix });
315
467
  const themeScript = themeInitScript(config.themeStorageKey, config.defaultTheme ?? 'light', settings.themeClasses);
316
468
  const demoByFile = new Map(state.demos.map((demo) => [path.resolve(demo.file), demo]));
317
469
  const changed: string[] = [];
@@ -356,8 +508,13 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
356
508
  compiler:
357
509
  config.compiler?.kind === 'remote'
358
510
  ? { kind: 'remote', endpoint: config.compiler.endpoint }
359
- : { kind: 'browser', ...editorAssets },
360
- options: { define: settings.define, stubImports: settings.stubImports, minify: false },
511
+ : { kind: 'browser', worker, wasm: shared.wasm },
512
+ options: {
513
+ define: settings.define,
514
+ stubImports: settings.stubImports,
515
+ minify: false,
516
+ ...(settings.traits.jsxImportSource ? { jsxImportSource: settings.traits.jsxImportSource } : null),
517
+ },
361
518
  },
362
519
  sourceReplacements: config.sourceReplacements ?? {},
363
520
  fork: config.fork ?? {},
@@ -376,16 +533,65 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
376
533
  return changed;
377
534
  };
378
535
 
379
- const disposeContexts = async () => {
380
- await Promise.all([contexts.vendorCtx.dispose(), contexts.runtimeCtx.dispose(), contexts.demosCtx.dispose()]);
536
+ const refresh = async () => {
537
+ const next = discover(settings);
538
+ const structureChanged =
539
+ next.specifiers.join('\n') !== state.specifiers.join('\n') ||
540
+ next.demos.map((demo) => demo.id).join('\n') !== state.demos.map((demo) => demo.id).join('\n');
541
+ if (!structureChanged) return;
542
+ await dispose();
543
+ state = next;
544
+ vendor = await vendorEntries(state.specifiers);
545
+ contexts = await createContexts(settings, config, state.demos, vendor);
546
+ };
547
+
548
+ return { settings, manifest: () => manifest!, run, refresh, dispose };
549
+ }
550
+
551
+ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemosResult> {
552
+ const { watch = false } = options;
553
+ const log = options.log ?? ((message: string) => console.log(`[docs-kit] ${message}`));
554
+ const targets = frameworkTargets(options.config);
555
+ const primarySettings = resolveSettings(options, targets[0]);
556
+
557
+ // Output names are content-hashed and never pruned during a run, so start
558
+ // clean: a stale page could point at bundles from an older config.
559
+ fs.rmSync(primarySettings.rootOutDir, { recursive: true, force: true });
560
+ fs.mkdirSync(primarySettings.rootOutDir, { recursive: true });
561
+
562
+ const shared = { wasm: copyEsbuildWasm(primarySettings), fenceSuffix: primarySettings.demoSuffix, log };
563
+ const builds: FrameworkBuild[] = [];
564
+ const disposeAll = async () => {
565
+ await Promise.all(builds.map((build) => build.dispose()));
566
+ };
567
+ try {
568
+ for (const target of targets) builds.push(await createFrameworkBuild(options, target, shared));
569
+ } catch (error) {
570
+ await disposeAll();
571
+ throw error;
572
+ }
573
+ const devEvents = watch ? startDevEvents(primarySettings.devEventsPort, log) : null;
574
+
575
+ const manifests = () =>
576
+ Object.fromEntries(builds.map((build) => [build.settings.framework, build.manifest()])) as Partial<
577
+ Record<DemoFramework, DemoManifest>
578
+ >;
579
+
580
+ /** Builds every framework; each `changed` entry is a demo page to reload. */
581
+ const runAll = async () => {
582
+ const changed: { build: FrameworkBuild; id: string }[] = [];
583
+ for (const build of builds) for (const id of await build.run()) changed.push({ build, id });
584
+ return changed;
381
585
  };
586
+ const primaryIds = (changed: { build: FrameworkBuild; id: string }[]) =>
587
+ changed.filter((entry) => entry.build === builds[0]).map((entry) => entry.id);
382
588
 
383
589
  let changed: string[];
384
590
  try {
385
- changed = await runBuild();
591
+ changed = primaryIds(await runAll());
386
592
  } catch (error) {
387
593
  if (!watch) {
388
- await disposeContexts();
594
+ await disposeAll();
389
595
  throw error;
390
596
  }
391
597
  log(`initial build failed: ${(error as Error).message}`);
@@ -393,22 +599,23 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
393
599
  }
394
600
 
395
601
  if (!watch) {
396
- await disposeContexts();
397
- return { manifest: manifest!, changed, close: async () => {} };
602
+ await disposeAll();
603
+ return { manifest: builds[0].manifest(), manifests: manifests(), changed, close: async () => {} };
398
604
  }
399
605
 
400
606
  const chokidar = await import('chokidar');
401
- const watchRoots = [
402
- settings.contentDir,
403
- ...Object.values(settings.libraries).flatMap((library) =>
404
- (library.watch ?? [path.dirname(library.entry)]).map((dir) => path.resolve(settings.root, dir)),
405
- ),
406
- ...(settings.bootstrap ? [settings.bootstrap] : []),
407
- ...settings.extraCss,
408
- ];
409
- const watcher = chokidar.watch(watchRoots, {
607
+ const watchRoots = new Set<string>([primarySettings.contentDir]);
608
+ for (const { settings } of builds) {
609
+ for (const library of Object.values(settings.libraries)) {
610
+ for (const dir of library.watch ?? [path.dirname(library.entry)]) watchRoots.add(path.resolve(settings.root, dir));
611
+ }
612
+ if (settings.bootstrap) watchRoots.add(settings.bootstrap);
613
+ for (const file of settings.extraCss) watchRoots.add(file);
614
+ }
615
+ const watcher = chokidar.watch([...watchRoots], {
410
616
  ignoreInitial: true,
411
- ignored: (file: string) => file.includes(`${path.sep}node_modules${path.sep}`) || file.startsWith(settings.outDir),
617
+ ignored: (file: string) =>
618
+ file.includes(`${path.sep}node_modules${path.sep}`) || file.startsWith(primarySettings.rootOutDir),
412
619
  });
413
620
 
414
621
  let running = false;
@@ -422,25 +629,9 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
422
629
  }
423
630
  running = true;
424
631
  try {
425
- const next = discover(settings);
426
- const structureChanged =
427
- next.specifiers.join('\n') !== state.specifiers.join('\n') ||
428
- next.demos.map((demo) => demo.id).join('\n') !== state.demos.map((demo) => demo.id).join('\n');
429
- if (structureChanged) {
430
- await disposeContexts();
431
- state = next;
432
- vendor = await writeVendorEntries({
433
- specifiers: state.specifiers,
434
- libraries: settings.libraries,
435
- root: settings.root,
436
- nodePaths: settings.nodePaths,
437
- workDir: path.join(settings.workDir, 'vendor'),
438
- warn: (message) => log(`warning: ${message}`),
439
- });
440
- contexts = await createContexts(settings, config, state.demos, vendor);
441
- }
442
- for (const id of await runBuild()) {
443
- devEvents?.send({ type: 'demo', id, url: `${settings.urlRoot}/${id}/index.html` });
632
+ for (const build of builds) await build.refresh();
633
+ for (const { build, id } of await runAll()) {
634
+ devEvents?.send({ type: 'demo', id, url: `${build.settings.urlRoot}/${id}/index.html` });
444
635
  }
445
636
  } catch (error) {
446
637
  const message = (error as Error).message;
@@ -458,7 +649,7 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
458
649
  watcher.on('all', (_event, file) => {
459
650
  if (timer) clearTimeout(timer);
460
651
  timer = setTimeout(() => {
461
- log(`change: ${path.relative(settings.root, file)}`);
652
+ log(`change: ${path.relative(primarySettings.root, file)}`);
462
653
  void rebuild();
463
654
  }, 120);
464
655
  });
@@ -466,13 +657,16 @@ export async function buildDemos(options: BuildDemosOptions): Promise<BuildDemos
466
657
 
467
658
  return {
468
659
  get manifest() {
469
- return manifest!;
660
+ return builds[0].manifest();
661
+ },
662
+ get manifests() {
663
+ return manifests();
470
664
  },
471
665
  changed,
472
666
  async close() {
473
667
  await watcher.close();
474
668
  devEvents?.close();
475
- await disposeContexts();
669
+ await disposeAll();
476
670
  },
477
671
  };
478
672
  }