@xyd-js/documan 0.1.0-xyd.6 → 0.1.0-xyd.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,238 +1,1133 @@
1
- // src/run/build.ts
2
- import path from "node:path";
3
- import fs from "node:fs";
4
- import { fileURLToPath } from "node:url";
1
+ // src/build.ts
2
+ import path2 from "path";
3
+ import fs2 from "fs";
4
+ import { fileURLToPath as fileURLToPath2 } from "url";
5
5
  import { build as viteBuild } from "vite";
6
6
  import tsconfigPaths from "vite-tsconfig-paths";
7
- import { reactRouter } from "@xyd-js/react-router-dev/vite";
8
- import { vitePlugins as xydContentVitePlugins } from "@xyd-js/content";
9
- import { pluginZero } from "@xyd-js/plugin-zero";
7
+
8
+ // src/utils.ts
9
+ import path from "path";
10
+ import fs from "fs";
11
+ import { fileURLToPath } from "url";
12
+ import { execSync } from "child_process";
13
+ import crypto from "crypto";
14
+ import { createServer } from "vite";
15
+ import { reactRouter } from "@react-router/dev/vite";
16
+ import { IconSet } from "@iconify/tools";
17
+ import { readSettings, pluginDocs } from "@xyd-js/plugin-docs";
18
+ import { vitePlugins as xydContentVitePlugins } from "@xyd-js/content/vite";
19
+
20
+ // src/const.ts
21
+ var HOST_FOLDER_PATH = ".xyd/host";
22
+ var CACHE_FOLDER_PATH = ".xyd/.cache";
23
+ var BUILD_FOLDER_PATH = ".xyd/build";
24
+ var SUPPORTED_SETTINGS_FILES = [
25
+ "docs.json",
26
+ "docs.ts",
27
+ "docs.tsx"
28
+ ];
29
+ var SUPPORTED_CONTENT_FILES = [
30
+ ".md",
31
+ ".mdx"
32
+ ];
33
+
34
+ // src/cli.ts
35
+ import readline from "readline";
36
+ import cliSpinners from "cli-spinners";
37
+ var CLI = class {
38
+ spinner;
39
+ spinnerInterval = null;
40
+ currentFrame = 0;
41
+ currentMessage = "";
42
+ isSpinning = false;
43
+ constructor(spinnerType = "dots") {
44
+ this.spinner = cliSpinners[spinnerType];
45
+ }
46
+ startSpinner(message) {
47
+ if (this.isSpinning) {
48
+ this.stopSpinner();
49
+ }
50
+ this.currentMessage = message;
51
+ this.isSpinning = true;
52
+ this.currentFrame = 0;
53
+ this.write(`${this.spinner.frames[0]} ${this.currentMessage}`);
54
+ this.spinnerInterval = setInterval(() => {
55
+ const frame = this.spinner.frames[this.currentFrame];
56
+ this.write(`${frame} ${this.currentMessage}`);
57
+ this.currentFrame = (this.currentFrame + 1) % this.spinner.frames.length;
58
+ }, this.spinner.interval);
59
+ }
60
+ stopSpinner() {
61
+ if (this.spinnerInterval) {
62
+ clearInterval(this.spinnerInterval);
63
+ this.spinnerInterval = null;
64
+ }
65
+ this.isSpinning = false;
66
+ this.clearLine();
67
+ }
68
+ clearLine() {
69
+ readline.clearLine(process.stdout, 0);
70
+ readline.cursorTo(process.stdout, 0);
71
+ }
72
+ write(message) {
73
+ this.clearLine();
74
+ process.stdout.write(message);
75
+ }
76
+ log(message) {
77
+ if (this.isSpinning) {
78
+ this.stopSpinner();
79
+ }
80
+ console.log(message);
81
+ }
82
+ error(message) {
83
+ if (this.isSpinning) {
84
+ this.stopSpinner();
85
+ }
86
+ console.error(message);
87
+ }
88
+ updateMessage(message) {
89
+ this.currentMessage = message;
90
+ }
91
+ };
92
+ var cli = new CLI();
93
+
94
+ // src/utils.ts
10
95
  var __filename = fileURLToPath(import.meta.url);
11
96
  var __dirname = path.dirname(__filename);
12
- async function build() {
13
- const resp = await pluginZero();
14
- if (!resp) {
15
- throw new Error("PluginZero not found");
97
+ async function appInit(options) {
98
+ const readPreloadSettings = await readSettings();
99
+ if (!readPreloadSettings) {
100
+ return null;
101
+ }
102
+ const preloadSettings = typeof readPreloadSettings === "string" ? JSON.parse(readPreloadSettings) : readPreloadSettings;
103
+ {
104
+ if (!preloadSettings.integrations?.search) {
105
+ preloadSettings.integrations = {
106
+ ...preloadSettings.integrations || {},
107
+ search: {
108
+ orama: true
109
+ }
110
+ };
111
+ }
112
+ const plugins = integrationsToPlugins(preloadSettings.integrations);
113
+ if (preloadSettings.plugins) {
114
+ preloadSettings.plugins = [...plugins, ...preloadSettings.plugins];
115
+ } else {
116
+ preloadSettings.plugins = plugins;
117
+ }
16
118
  }
17
- const buildDir = path.join(process.cwd(), ".xyd/build");
119
+ let resolvedPlugins = [];
18
120
  {
19
- const packageJsonPath = path.join(buildDir, "package.json");
20
- const packageJsonContent = {
21
- type: "module",
22
- scripts: {},
23
- dependencies: {},
24
- devDependencies: {}
121
+ resolvedPlugins = await loadPlugins(preloadSettings) || [];
122
+ const userUniformVitePlugins = [];
123
+ const componentPlugins = [];
124
+ resolvedPlugins?.forEach((p) => {
125
+ if (p.uniform) {
126
+ userUniformVitePlugins.push(...p.uniform);
127
+ }
128
+ if (p.components) {
129
+ componentPlugins.push(...p.components);
130
+ }
131
+ });
132
+ globalThis.__xydUserUniformVitePlugins = userUniformVitePlugins;
133
+ globalThis.__xydUserComponents = componentPlugins;
134
+ }
135
+ const respPluginDocs = await pluginDocs(options);
136
+ if (!respPluginDocs) {
137
+ throw new Error("PluginDocs not found");
138
+ }
139
+ if (!respPluginDocs.settings) {
140
+ throw new Error("Settings not found in respPluginDocs");
141
+ }
142
+ respPluginDocs.settings.plugins = [
143
+ ...respPluginDocs.settings?.plugins || [],
144
+ ...preloadSettings.plugins || []
145
+ ];
146
+ globalThis.__xydBasePath = respPluginDocs.basePath;
147
+ globalThis.__xydSettings = respPluginDocs.settings;
148
+ globalThis.__xydPagePathMapping = respPluginDocs.pagePathMapping;
149
+ return {
150
+ respPluginDocs,
151
+ resolvedPlugins
152
+ };
153
+ }
154
+ function virtualComponentsPlugin() {
155
+ return {
156
+ name: "xyd-plugin-virtual-components",
157
+ resolveId(id) {
158
+ if (id === "virtual:xyd-user-components") {
159
+ return id + ".jsx";
160
+ }
161
+ return null;
162
+ },
163
+ async load(id) {
164
+ if (id === "virtual:xyd-user-components.jsx") {
165
+ const userComponents = globalThis.__xydUserComponents || [];
166
+ if (userComponents.length > 0 && userComponents[0]?.dist) {
167
+ const imports = userComponents.map(
168
+ (component, index) => `import Component${index} from '${component.dist}';`
169
+ ).join("\n");
170
+ const componentObjects = userComponents.map(
171
+ (component, index) => `{
172
+ component: Component${index},
173
+ name: '${component.name}',
174
+ dist: '${component.dist}'
175
+ }`
176
+ ).join(",\n ");
177
+ return `
178
+ // Pre-bundled at build time - no async loading needed
179
+ ${imports}
180
+
181
+ export const components = [
182
+ ${componentObjects}
183
+ ];
184
+ `;
185
+ }
186
+ return `
187
+ export const components = globalThis.__xydUserComponents || {}
188
+ `;
189
+ }
190
+ return null;
191
+ }
192
+ };
193
+ }
194
+ function virtualProvidersPlugin(settings) {
195
+ return {
196
+ name: "xyd-plugin-virtual-providers",
197
+ enforce: "pre",
198
+ resolveId(id) {
199
+ if (id === "virtual:xyd-analytics-providers") {
200
+ return id;
201
+ }
202
+ },
203
+ async load(id) {
204
+ if (id === "virtual:xyd-analytics-providers") {
205
+ const providers = Object.keys(settings?.integrations?.analytics || {});
206
+ const imports = providers.map(
207
+ (provider) => `import { default as ${provider}Provider } from '@pluganalytics/provider-${provider}'`
208
+ ).join("\n");
209
+ const cases = providers.map(
210
+ (provider) => `case '${provider}': return ${provider}Provider`
211
+ ).join("\n");
212
+ return `
213
+ ${imports}
214
+
215
+ export const loadProvider = async (provider) => {
216
+ switch (provider) {
217
+ ${cases}
218
+ default:
219
+ console.error(\`Provider \${provider} not found\`)
220
+ return null
221
+ }
222
+ }
223
+ `;
224
+ }
225
+ }
226
+ };
227
+ }
228
+ function commonVitePlugins(respPluginDocs, resolvedPlugins) {
229
+ const userVitePlugins = resolvedPlugins.map((p) => p.vite).flat() || [];
230
+ return [
231
+ ...xydContentVitePlugins({
232
+ toc: {
233
+ maxDepth: respPluginDocs.settings.theme?.maxTocDepth || 2
234
+ },
235
+ settings: respPluginDocs.settings
236
+ }),
237
+ ...respPluginDocs.vitePlugins,
238
+ reactRouter(),
239
+ virtualComponentsPlugin(),
240
+ virtualProvidersPlugin(respPluginDocs.settings),
241
+ pluginIconSet(respPluginDocs.settings),
242
+ ...userVitePlugins
243
+ ];
244
+ }
245
+ function pluginIconSet(settings) {
246
+ const DEFAULT_ICON_SET = "lucide";
247
+ async function fetchIconSet(name, version) {
248
+ if (name.startsWith("http://") || name.startsWith("https://")) {
249
+ try {
250
+ const iconsResp = await fetch(name);
251
+ const iconsData = await iconsResp.json();
252
+ const iconSet = new IconSet(iconsData);
253
+ return { icons: iconsData, iconSet };
254
+ } catch (error) {
255
+ console.warn(`Failed to fetch from URL ${name}:`, error);
256
+ }
257
+ }
258
+ const tryReadFile = (filePath) => {
259
+ try {
260
+ if (!fs.existsSync(filePath)) {
261
+ console.warn(`File does not exist: ${filePath}`);
262
+ return null;
263
+ }
264
+ const fileContent = fs.readFileSync(filePath, "utf-8");
265
+ try {
266
+ const iconsData = JSON.parse(fileContent);
267
+ const iconSet = new IconSet(iconsData);
268
+ return { icons: iconsData, iconSet };
269
+ } catch (parseError) {
270
+ console.warn(`Invalid JSON in file ${filePath}:`, parseError);
271
+ return null;
272
+ }
273
+ } catch (error) {
274
+ console.warn(`Failed to read file ${filePath}:`, error);
275
+ return null;
276
+ }
25
277
  };
26
- if (!fs.existsSync(buildDir)) {
27
- fs.mkdirSync(buildDir, { recursive: true });
278
+ if (path.isAbsolute(name)) {
279
+ const result = tryReadFile(name);
280
+ if (result) return result;
281
+ }
282
+ if (name.startsWith(".")) {
283
+ const fullPath = path.join(process.cwd(), name);
284
+ const result = tryReadFile(fullPath);
285
+ if (result) return result;
286
+ }
287
+ const cdnUrl = version ? `https://cdn.jsdelivr.net/npm/@iconify-json/${name}@${version}/icons.json` : `https://cdn.jsdelivr.net/npm/@iconify-json/${name}/icons.json`;
288
+ try {
289
+ const iconsResp = await fetch(cdnUrl);
290
+ const iconsData = await iconsResp.json();
291
+ const iconSet = new IconSet(iconsData);
292
+ return { icons: iconsData, iconSet };
293
+ } catch (error) {
294
+ throw new Error(`Failed to load icon set from any source (file or CDN): ${name}`);
295
+ }
296
+ }
297
+ async function processIconSet(iconSet, icons, noPrefix) {
298
+ const resp = /* @__PURE__ */ new Map();
299
+ for (const icon of Object.keys(icons.icons)) {
300
+ const svg = iconSet.toSVG(icon);
301
+ if (!svg) continue;
302
+ let prefix = noPrefix ? void 0 : iconSet.prefix;
303
+ const iconName = prefix ? `${prefix}:${icon}` : icon;
304
+ resp.set(iconName, { svg: svg.toString() });
305
+ }
306
+ return resp;
307
+ }
308
+ async function addIconsToMap(resp, name, version, noPrefix) {
309
+ const { icons, iconSet } = await fetchIconSet(name, version);
310
+ const newIcons = await processIconSet(iconSet, icons, noPrefix);
311
+ newIcons.forEach((value, key) => resp.set(key, value));
312
+ }
313
+ async function processIconLibrary(library) {
314
+ const resp = /* @__PURE__ */ new Map();
315
+ if (typeof library === "string") {
316
+ await addIconsToMap(resp, library);
317
+ } else if (Array.isArray(library)) {
318
+ for (const item of library) {
319
+ if (typeof item === "string") {
320
+ await addIconsToMap(resp, item);
321
+ } else {
322
+ const { name, version, default: isDefault, noprefix } = item;
323
+ const noPrefix = isDefault || noprefix === true;
324
+ await addIconsToMap(resp, name, version, noPrefix);
325
+ }
326
+ }
327
+ } else {
328
+ const { name, version, default: isDefault, noprefix } = library;
329
+ const noPrefix = isDefault || noprefix === true;
330
+ await addIconsToMap(resp, name, version, noPrefix);
331
+ }
332
+ return resp;
333
+ }
334
+ return {
335
+ name: "xyd-plugin-icon-set",
336
+ enforce: "pre",
337
+ resolveId(id) {
338
+ if (id === "virtual:xyd-icon-set") {
339
+ return id;
340
+ }
341
+ },
342
+ async load(id) {
343
+ if (id === "virtual:xyd-icon-set") {
344
+ let resp;
345
+ if (settings.theme?.icons?.library) {
346
+ resp = await processIconLibrary(settings.theme.icons.library);
347
+ } else {
348
+ resp = await processIconLibrary([
349
+ {
350
+ name: DEFAULT_ICON_SET,
351
+ default: true
352
+ }
353
+ ]);
354
+ }
355
+ return `
356
+ export const iconSet = ${JSON.stringify(Object.fromEntries(resp))};
357
+ `;
358
+ }
359
+ }
360
+ };
361
+ }
362
+ function getHostPath() {
363
+ if (process.env.XYD_DEV_MODE) {
364
+ if (process.env.XYD_HOST) {
365
+ return path.resolve(process.env.XYD_HOST);
366
+ }
367
+ return path.join(__dirname, "../../../", HOST_FOLDER_PATH);
368
+ }
369
+ return path.join(process.cwd(), HOST_FOLDER_PATH);
370
+ }
371
+ function getAppRoot() {
372
+ return getHostPath();
373
+ }
374
+ function getPublicPath() {
375
+ return path.join(process.cwd(), "public");
376
+ }
377
+ function getBuildPath() {
378
+ return path.join(
379
+ process.cwd(),
380
+ BUILD_FOLDER_PATH
381
+ );
382
+ }
383
+ function getDocsPluginBasePath() {
384
+ return path.join(getHostPath(), "./plugins/xyd-plugin-docs");
385
+ }
386
+ async function loadPlugins(settings) {
387
+ const resolvedPlugins = [];
388
+ for (const plugin of settings.plugins || []) {
389
+ let pluginName;
390
+ let pluginArgs = [];
391
+ if (typeof plugin === "string") {
392
+ pluginName = plugin;
393
+ pluginArgs = [];
394
+ } else if (Array.isArray(plugin)) {
395
+ pluginName = plugin[0];
396
+ pluginArgs = plugin.slice(1);
397
+ } else {
398
+ console.error(`Currently only string and array plugins are supported, got: ${plugin}`);
399
+ return [];
400
+ }
401
+ let mod;
402
+ try {
403
+ mod = await import(pluginName);
404
+ } catch (e) {
405
+ pluginName = path.join(process.cwd(), pluginName);
406
+ const pluginPreview = await createServer({
407
+ optimizeDeps: {
408
+ include: []
409
+ }
410
+ });
411
+ mod = await pluginPreview.ssrLoadModule(pluginName);
412
+ }
413
+ if (!mod.default) {
414
+ console.error(`Plugin ${plugin} has no default export`);
415
+ continue;
416
+ }
417
+ let pluginInstance = mod.default(...pluginArgs);
418
+ if (typeof pluginInstance === "function") {
419
+ const plug = pluginInstance(settings);
420
+ resolvedPlugins.push(plug);
421
+ continue;
422
+ }
423
+ resolvedPlugins.push(pluginInstance);
424
+ }
425
+ return resolvedPlugins;
426
+ }
427
+ function integrationsToPlugins(integrations) {
428
+ const plugins = [];
429
+ let foundSearchIntegation = 0;
430
+ if (integrations?.search?.orama) {
431
+ if (typeof integrations.search.orama === "boolean") {
432
+ plugins.push("@xyd-js/plugin-orama");
433
+ } else {
434
+ plugins.push(["@xyd-js/plugin-orama", integrations.search.orama]);
435
+ }
436
+ foundSearchIntegation++;
437
+ }
438
+ if (integrations?.search?.algolia) {
439
+ plugins.push(["@xyd-js/plugin-algolia", integrations.search.algolia]);
440
+ foundSearchIntegation++;
441
+ }
442
+ if (foundSearchIntegation > 1) {
443
+ throw new Error("Only one search integration is allowed");
444
+ }
445
+ return plugins;
446
+ }
447
+ async function preWorkspaceSetup(options = {}) {
448
+ await ensureFoldersExist();
449
+ if (!options.force) {
450
+ if (await shouldSkipHostSetup()) {
451
+ return true;
452
+ }
453
+ }
454
+ const hostTemplate = process.env.XYD_DEV_MODE ? path.resolve(__dirname, "../../xyd-host") : path.resolve(__dirname, "../../host");
455
+ const hostPath = getHostPath();
456
+ await copyHostTemplate(hostTemplate, hostPath);
457
+ let pluginDocsPath;
458
+ if (process.env.XYD_DEV_MODE) {
459
+ pluginDocsPath = path.resolve(__dirname, "../../xyd-plugin-docs");
460
+ } else {
461
+ pluginDocsPath = path.resolve(__dirname, "../../plugin-docs");
462
+ }
463
+ const pagesSourcePath = path.join(pluginDocsPath, "src/pages");
464
+ const pagesTargetPath = path.join(hostPath, "plugins/xyd-plugin-docs/src/pages");
465
+ if (fs.existsSync(pagesSourcePath)) {
466
+ await copyHostTemplate(pagesSourcePath, pagesTargetPath);
467
+ } else {
468
+ console.warn(`Pages source path does not exist: ${pagesSourcePath}`);
469
+ }
470
+ }
471
+ function calculateFolderChecksum(folderPath) {
472
+ const hash = crypto.createHash("sha256");
473
+ const ignorePatterns = [...getGitignorePatterns(folderPath), ".xydchecksum", "node_modules", "dist", ".react-router", "package-lock.json", "pnpm-lock.yaml"];
474
+ function processFile(filePath) {
475
+ const relativePath = path.relative(folderPath, filePath);
476
+ const content = fs.readFileSync(filePath);
477
+ hash.update(relativePath);
478
+ hash.update(content);
479
+ }
480
+ function processDirectory(dirPath) {
481
+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });
482
+ entries.sort((a, b) => a.name.localeCompare(b.name));
483
+ for (const entry of entries) {
484
+ const sourceEntry = path.join(dirPath, entry.name);
485
+ if (shouldIgnoreEntry(entry.name, ignorePatterns)) {
486
+ continue;
487
+ }
488
+ if (entry.name === ".git") {
489
+ continue;
490
+ }
491
+ if (entry.isDirectory()) {
492
+ processDirectory(sourceEntry);
493
+ } else {
494
+ processFile(sourceEntry);
495
+ }
496
+ }
497
+ }
498
+ processDirectory(folderPath);
499
+ return hash.digest("hex");
500
+ }
501
+ function getGitignorePatterns(folderPath) {
502
+ const gitignorePath = path.join(folderPath, ".gitignore");
503
+ if (fs.existsSync(gitignorePath)) {
504
+ const gitignoreContent = fs.readFileSync(gitignorePath, "utf-8");
505
+ return gitignoreContent.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
506
+ }
507
+ return [];
508
+ }
509
+ function shouldIgnoreEntry(entryName, ignorePatterns) {
510
+ return ignorePatterns.some((pattern) => {
511
+ const regex = new RegExp(pattern.replace(/\*/g, ".*"));
512
+ return regex.test(entryName);
513
+ });
514
+ }
515
+ async function copyHostTemplate(sourcePath, targetPath) {
516
+ if (!fs.existsSync(sourcePath)) {
517
+ throw new Error(`Host template source path does not exist: ${sourcePath}`);
518
+ }
519
+ if (fs.existsSync(targetPath)) {
520
+ fs.rmSync(targetPath, { recursive: true, force: true });
521
+ }
522
+ fs.mkdirSync(targetPath, { recursive: true });
523
+ const ignorePatterns = getGitignorePatterns(sourcePath);
524
+ const entries = fs.readdirSync(sourcePath, { withFileTypes: true });
525
+ for (const entry of entries) {
526
+ const sourceEntry = path.join(sourcePath, entry.name);
527
+ const targetEntry = path.join(targetPath, entry.name);
528
+ if (shouldIgnoreEntry(entry.name, ignorePatterns)) {
529
+ continue;
530
+ }
531
+ if (entry.name === ".git") {
532
+ continue;
533
+ }
534
+ if (entry.isDirectory()) {
535
+ await copyHostTemplate(sourceEntry, targetEntry);
536
+ } else {
537
+ fs.copyFileSync(sourceEntry, targetEntry);
538
+ if (entry.name === "package.json" && process.env.XYD_DEV_MODE) {
539
+ const packageJsonPath = targetEntry;
540
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
541
+ packageJson.name = "xyd-host-dev";
542
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
543
+ }
544
+ }
545
+ }
546
+ }
547
+ async function ensureFoldersExist() {
548
+ const folders = [CACHE_FOLDER_PATH];
549
+ for (const folder of folders) {
550
+ const fullPath = path.resolve(process.cwd(), folder);
551
+ if (!fs.existsSync(fullPath)) {
552
+ fs.mkdirSync(fullPath, { recursive: true });
553
+ }
554
+ }
555
+ }
556
+ async function postWorkspaceSetup(settings) {
557
+ const spinner = new CLI("dots");
558
+ try {
559
+ spinner.startSpinner("Installing xyd framework...");
560
+ const hostPath = getHostPath();
561
+ const packageJsonPath = path.join(hostPath, "package.json");
562
+ if (!fs.existsSync(packageJsonPath)) {
563
+ console.warn("No package.json found in host path");
564
+ return;
28
565
  }
29
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContent, null, 2), "utf8");
566
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
567
+ if (!packageJson.dependencies) {
568
+ packageJson.dependencies = {};
569
+ }
570
+ for (const plugin of settings.plugins || []) {
571
+ let pluginName;
572
+ if (typeof plugin === "string") {
573
+ pluginName = plugin;
574
+ } else if (Array.isArray(plugin)) {
575
+ pluginName = plugin[0];
576
+ } else {
577
+ continue;
578
+ }
579
+ if (pluginName.startsWith("@xyd-js/")) {
580
+ continue;
581
+ }
582
+ const isValidNpmPackage = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(pluginName);
583
+ if (isValidNpmPackage) {
584
+ const hostPackageJsonPath = path.join(hostPath, "package.json");
585
+ if (fs.existsSync(hostPackageJsonPath)) {
586
+ const hostPackageJson = JSON.parse(fs.readFileSync(hostPackageJsonPath, "utf-8"));
587
+ const deps = hostPackageJson.dependencies || {};
588
+ const matchingDep = Object.entries(deps).find(([depName]) => {
589
+ return depName === pluginName;
590
+ });
591
+ if (matchingDep) {
592
+ packageJson.dependencies[pluginName] = matchingDep[1];
593
+ } else {
594
+ console.warn(`no matching dependency found for: ${pluginName} in: ${hostPackageJsonPath}`);
595
+ }
596
+ } else {
597
+ console.warn(`no host package.json found in: ${hostPath}`);
598
+ }
599
+ } else if (!pluginName.startsWith(".") && !pluginName.startsWith("/")) {
600
+ console.warn(`invalid plugin name: ${pluginName}`);
601
+ }
602
+ }
603
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
604
+ await nodeInstallPackages(hostPath);
605
+ spinner.stopSpinner();
606
+ spinner.log("\u2714 Local xyd framework installed successfully");
607
+ } catch (error) {
608
+ spinner.stopSpinner();
609
+ spinner.error("\u274C Failed to install xyd framework");
610
+ throw error;
611
+ }
612
+ }
613
+ function nodeInstallPackages(hostPath) {
614
+ const cmd = process.env.XYD_DEV_MODE ? "pnpm i" : "pnpm i";
615
+ const execOptions = {
616
+ cwd: hostPath,
617
+ env: {
618
+ ...process.env,
619
+ NODE_ENV: ""
620
+ // since 'production' does not install it well,
621
+ }
622
+ };
623
+ const customRegistry = process.env.XYD_NPM_REGISTRY || process.env.npm_config_registry;
624
+ if (customRegistry) {
625
+ if (!execOptions.env) {
626
+ execOptions.env = {};
627
+ }
628
+ execOptions.env["npm_config_registry"] = customRegistry;
629
+ }
630
+ if (process.env.XYD_VERBOSE) {
631
+ execOptions.stdio = "inherit";
632
+ }
633
+ execSync(cmd, execOptions);
634
+ }
635
+ async function shouldSkipHostSetup() {
636
+ const hostPath = getHostPath();
637
+ if (!fs.existsSync(hostPath)) {
638
+ return false;
639
+ }
640
+ const currentChecksum = calculateFolderChecksum(hostPath);
641
+ const storedChecksum = getStoredChecksum();
642
+ if (!storedChecksum || storedChecksum !== currentChecksum) {
643
+ return false;
644
+ }
645
+ return true;
646
+ }
647
+ function getStoredChecksum() {
648
+ const checksumPath = path.join(getHostPath(), ".xydchecksum");
649
+ if (!fs.existsSync(checksumPath)) {
650
+ return null;
651
+ }
652
+ try {
653
+ return fs.readFileSync(checksumPath, "utf-8").trim();
654
+ } catch (error) {
655
+ console.error("Error reading checksum file:", error);
656
+ return null;
657
+ }
658
+ }
659
+ function storeChecksum(checksum) {
660
+ const checksumPath = path.join(getHostPath(), ".xydchecksum");
661
+ try {
662
+ fs.writeFileSync(checksumPath, checksum);
663
+ } catch (error) {
664
+ console.error("Error writing checksum file:", error);
665
+ }
666
+ }
667
+
668
+ // src/build.ts
669
+ async function build() {
670
+ const skip = await preWorkspaceSetup({
671
+ force: true
672
+ });
673
+ const inited = await appInit();
674
+ if (!inited) {
675
+ return;
676
+ }
677
+ const { respPluginDocs, resolvedPlugins } = inited;
678
+ const commonRunVitePlugins = commonVitePlugins(respPluginDocs, resolvedPlugins);
679
+ const appRoot = getAppRoot();
680
+ if (!skip) {
681
+ await postWorkspaceSetup(respPluginDocs.settings);
682
+ const newChecksum = calculateFolderChecksum(getHostPath());
683
+ storeChecksum(newChecksum);
684
+ }
685
+ {
686
+ await setupInstallableEnvironmentV2();
30
687
  }
31
688
  try {
32
689
  await viteBuild({
33
- root: path.join(__dirname, "../host"),
34
- // @ts-ignore
690
+ mode: "production",
691
+ root: appRoot,
35
692
  plugins: [
36
- ...xydContentVitePlugins({
37
- toc: {
38
- minDepth: 2
39
- }
40
- }),
41
- reactRouter({
42
- outDir: buildDir,
43
- routes: resp.routes
44
- }),
45
- tsconfigPaths(),
46
- ...resp.vitePlugins
693
+ ...commonRunVitePlugins,
694
+ tsconfigPaths()
47
695
  ],
48
696
  optimizeDeps: {
49
697
  include: ["react/jsx-runtime"]
698
+ },
699
+ define: {
700
+ "process.env.NODE_ENV": JSON.stringify("production"),
701
+ "process.env": {}
702
+ },
703
+ resolve: {
704
+ alias: {
705
+ process: "process/browser"
706
+ }
50
707
  }
51
708
  });
52
709
  await viteBuild({
53
- root: path.join(__dirname, "../host"),
710
+ mode: "production",
711
+ root: appRoot,
54
712
  build: {
55
713
  ssr: true
56
714
  },
57
- // @ts-ignore
58
715
  plugins: [
59
- ...xydContentVitePlugins({
60
- toc: {
61
- minDepth: 2
62
- }
63
- }),
64
- reactRouter({
65
- outDir: buildDir,
66
- routes: resp.routes
67
- }),
68
- tsconfigPaths(),
69
- ...resp.vitePlugins
716
+ fixManifestPlugin(appRoot),
717
+ ...commonRunVitePlugins
70
718
  ],
71
719
  optimizeDeps: {
72
720
  include: ["react/jsx-runtime"]
721
+ },
722
+ define: {
723
+ "process.env.NODE_ENV": JSON.stringify("production"),
724
+ "process.env": {}
725
+ },
726
+ resolve: {
727
+ alias: {
728
+ process: "process/browser"
729
+ }
73
730
  }
74
731
  });
75
- console.log("Build completed successfully.");
76
732
  } catch (error) {
77
733
  console.error("Build failed:", error);
78
734
  }
79
735
  }
736
+ function setupInstallableEnvironmentV2() {
737
+ const buildDir = getBuildPath();
738
+ const packageJsonPath = path2.join(buildDir, "package.json");
739
+ const packageJsonContent = {
740
+ type: "module",
741
+ scripts: {},
742
+ dependencies: {},
743
+ devDependencies: {}
744
+ };
745
+ if (!fs2.existsSync(buildDir)) {
746
+ fs2.mkdirSync(buildDir, { recursive: true });
747
+ }
748
+ fs2.writeFileSync(packageJsonPath, JSON.stringify(packageJsonContent, null, 2), "utf8");
749
+ const buildNodeModulesPath = path2.join(buildDir, "node_modules");
750
+ const dirname = path2.dirname(fileURLToPath2(import.meta.url));
751
+ let workspaceNodeModulesPath = "";
752
+ if (process.env.XYD_DEV_MODE) {
753
+ workspaceNodeModulesPath = path2.resolve(dirname, "../../../node_modules");
754
+ } else {
755
+ workspaceNodeModulesPath = path2.resolve(dirname, "../../../");
756
+ }
757
+ console.log("workspaceNodeModulesPath", workspaceNodeModulesPath);
758
+ if (fs2.existsSync(buildNodeModulesPath)) {
759
+ if (fs2.lstatSync(buildNodeModulesPath).isSymbolicLink()) {
760
+ fs2.unlinkSync(buildNodeModulesPath);
761
+ } else {
762
+ fs2.rmSync(buildNodeModulesPath, { recursive: true, force: true });
763
+ }
764
+ }
765
+ fs2.symlinkSync(workspaceNodeModulesPath, buildNodeModulesPath, "dir");
766
+ }
767
+ function fixManifestPlugin(appRoot) {
768
+ const manifestPath = path2.join(
769
+ getBuildPath(),
770
+ "./server/.vite/manifest.json"
771
+ );
772
+ return {
773
+ name: "xyd-fix-rr-manifest",
774
+ apply: "build",
775
+ // run after manifest is generated
776
+ // 2) after bundle is written, compute prefix and strip it
777
+ writeBundle(_, bundle) {
778
+ const cwdDir = process.cwd();
779
+ let prefix = path2.relative(appRoot, cwdDir).replace(/\\/g, "/");
780
+ if (prefix) prefix += "/";
781
+ const esc = prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
782
+ const stripRe = new RegExp(`^${esc}`);
783
+ for (const fileName in bundle) {
784
+ const asset = bundle[fileName];
785
+ if (asset.type !== "asset") continue;
786
+ if (fileName.endsWith("manifest.json")) {
787
+ const manifest = JSON.parse(asset.source.toString());
788
+ const fixed = {};
789
+ for (const key of Object.keys(manifest)) {
790
+ const entry = manifest[key];
791
+ const newKey = key.replace(stripRe, "");
792
+ if (typeof entry.src === "string") {
793
+ entry.src = entry.src.replace(stripRe, "");
794
+ }
795
+ fixed[newKey] = entry;
796
+ }
797
+ asset.source = JSON.stringify(fixed, null, 2);
798
+ fs2.writeFileSync(manifestPath, asset.source, "utf8");
799
+ }
800
+ }
801
+ }
802
+ };
803
+ }
80
804
 
81
- // src/run/dev.ts
82
- import path2 from "node:path";
83
- import { fileURLToPath as fileURLToPath2 } from "node:url";
84
- import { createServer, searchForWorkspaceRoot } from "vite";
85
- import { reactRouter as reactRouter2 } from "@xyd-js/react-router-dev/vite";
86
- import { vitePlugins as xydContentVitePlugins2 } from "@xyd-js/content";
87
- import { pluginZero as pluginZero2 } from "@xyd-js/plugin-zero";
88
- var __filename2 = fileURLToPath2(import.meta.url);
89
- var __dirname2 = path2.dirname(__filename2);
90
- var port = process.env.XYD_PORT ? parseInt(process.env.XYD_PORT) : 5175;
91
- async function dev() {
92
- const resp = await pluginZero2();
93
- if (!resp) {
94
- throw new Error("PluginZero not found");
805
+ // src/dev.ts
806
+ import path3 from "path";
807
+ import fs3 from "fs";
808
+ import { createServer as createServer2, searchForWorkspaceRoot } from "vite";
809
+ import { readSettings as readSettings2 } from "@xyd-js/plugin-docs";
810
+ if (!process.env.ENABLE_TIMERS) {
811
+ ["time", "timeLog", "timeEnd"].forEach((method) => {
812
+ console[method] = () => {
813
+ };
814
+ });
815
+ }
816
+ var RELOADING = false;
817
+ async function dev(options) {
818
+ const spinner = new CLI("dots");
819
+ spinner.startSpinner("Preparing local xyd instance...");
820
+ const skip = await preWorkspaceSetup();
821
+ const inited = await appInit();
822
+ if (!inited) {
823
+ return;
95
824
  }
825
+ const { respPluginDocs, resolvedPlugins } = inited;
96
826
  const allowCwd = searchForWorkspaceRoot(process.cwd());
97
- const preview = await createServer({
98
- // any valid user config options, plus `mode` and `configFile`
99
- // configFile: path.join(__dirname, "../src/vite/empty-config.ts"), // TODO: bundler??
100
- // configFile: path.join(__dirname, "../"), // TODO: bundler??
101
- // root: path.join(__dirname, "../"), // TODO: bundler?
102
- root: process.env.XYD_DOCUMAN_HOST || path2.join(__dirname2, "../host"),
103
- // TODO: bundler?
827
+ const appRoot = getAppRoot();
828
+ const commonRunVitePlugins = commonVitePlugins(respPluginDocs, resolvedPlugins);
829
+ spinner.stopSpinner();
830
+ if (!skip) {
831
+ await postWorkspaceSetup(respPluginDocs.settings);
832
+ const newChecksum = calculateFolderChecksum(getHostPath());
833
+ storeChecksum(newChecksum);
834
+ }
835
+ spinner.log("\u2714 Local xyd instance is ready");
836
+ let server = null;
837
+ const port = options?.port ?? parseInt(process.env.XYD_PORT ?? "5175");
838
+ let USE_CONTEXT_ISSUE_PACKAGES = [];
839
+ {
840
+ if (process.env.XYD_DEV_MODE) {
841
+ USE_CONTEXT_ISSUE_PACKAGES = [
842
+ "react-github-btn",
843
+ "radix-ui",
844
+ "@code-hike/lighter",
845
+ "lucide-react",
846
+ "openux-js",
847
+ "pluganalytics"
848
+ ];
849
+ } else {
850
+ USE_CONTEXT_ISSUE_PACKAGES = [
851
+ "@xyd-js/theme-cosmo",
852
+ "@xyd-js/theme-opener",
853
+ "@xyd-js/theme-picasso",
854
+ "@xyd-js/theme-poetry"
855
+ ];
856
+ }
857
+ }
858
+ const preview = await createServer2({
859
+ root: appRoot,
860
+ publicDir: "/public",
104
861
  server: {
862
+ allowedHosts: [],
105
863
  port,
106
864
  fs: {
107
865
  allow: [
108
866
  allowCwd,
109
- process.env.XYD_CLI ? path2.join(__dirname2, "../../") : ""
110
- // path.join(__dirname, "../node_modules") // Ensure node_modules from xyd-documan is included
867
+ appRoot
111
868
  ]
112
869
  }
113
870
  },
871
+ define: {
872
+ "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
873
+ "process.env": {}
874
+ },
875
+ resolve: {
876
+ alias: {
877
+ process: "process/browser"
878
+ }
879
+ // preserveSymlinks: true
880
+ },
114
881
  build: {
115
882
  rollupOptions: {
116
- // Exclude package `B` from the client-side bundle
117
- external: ["@xyd-js/uniform", "@xyd-js/uniform/content", "@xyd-js/plugin-zero"]
883
+ external: []
118
884
  }
119
885
  },
120
886
  ssr: {
121
- external: ["@xyd-js/uniform", "@xyd-js/uniform/content", "@xyd-js/plugin-zero"]
122
- // noExternal: [
123
- // "@xyd-js/uniform",
124
- // "@xyd-js/uniform/content",
125
- // "@xyd-js/plugin-zero"
126
- // ],
887
+ external: []
127
888
  },
128
889
  optimizeDeps: {
129
- include: ["react/jsx-runtime"]
890
+ include: [
891
+ "react/jsx-runtime",
892
+ ...USE_CONTEXT_ISSUE_PACKAGES
893
+ ]
894
+ // exclude: ["react", "react-dom"]
130
895
  },
131
- // @ts-ignore
132
896
  plugins: [
133
- // TODO: fix plugin ts
134
- ...xydContentVitePlugins2({
135
- toc: {
136
- minDepth: 2
897
+ ...commonRunVitePlugins,
898
+ {
899
+ name: "xyd-configureServer",
900
+ configureServer(s) {
901
+ server = s;
137
902
  }
138
- }),
139
- reactRouter2({
140
- routes: resp.routes
141
- }),
142
- ...resp.vitePlugins
903
+ }
143
904
  ]
144
905
  });
906
+ const watcher = fs3.watch(allowCwd, { recursive: true }, async (eventType, filename) => {
907
+ if (RELOADING) {
908
+ return;
909
+ }
910
+ if (!filename) {
911
+ console.log("[xyd:dev-watcher] Received empty filename");
912
+ return;
913
+ }
914
+ if (!server) {
915
+ console.log("[xyd:dev-watcher] Server not ready");
916
+ return;
917
+ }
918
+ const filePath = path3.join(allowCwd, filename);
919
+ if (filePath.includes(CACHE_FOLDER_PATH)) {
920
+ return;
921
+ }
922
+ const publicPathReload = filePath.includes(getPublicPath());
923
+ if (publicPathReload) {
924
+ const relativePath = path3.relative(allowCwd, filePath);
925
+ const urlPath = "/" + relativePath.replace(/\\/g, "/");
926
+ preview.ws.send({
927
+ type: "full-reload",
928
+ path: urlPath
929
+ });
930
+ return;
931
+ }
932
+ let apiPaths = {};
933
+ if (respPluginDocs?.settings?.api) {
934
+ apiPaths = resolveApiFilePaths(process.cwd(), respPluginDocs.settings.api);
935
+ }
936
+ const apiChanged = !!apiPaths[filePath];
937
+ const isSettingsFile = SUPPORTED_SETTINGS_FILES.some((ext) => filePath.endsWith(ext));
938
+ const isContentFile = SUPPORTED_CONTENT_FILES.some((ext) => filePath.endsWith(ext));
939
+ const isWatchFile = isSettingsFile || isContentFile || apiChanged;
940
+ if (!isWatchFile) {
941
+ return;
942
+ }
943
+ if (isContentFile && eventType !== "rename") {
944
+ console.log("\u{1F504} Content file changed, refresh...", eventType);
945
+ invalidateSettings(server);
946
+ await touchLayoutPage();
947
+ return;
948
+ }
949
+ const renameContentFile = isContentFile && eventType === "rename";
950
+ if (isSettingsFile || renameContentFile) {
951
+ if (renameContentFile) {
952
+ console.log("\u{1F504} Content file renamed, refresh...");
953
+ } else {
954
+ console.log("\u{1F504} Settings file changed, refresh...");
955
+ }
956
+ if (respPluginDocs?.settings.engine?.uniform?.store) {
957
+ await appInit({
958
+ disableFSWrite: true
959
+ });
960
+ } else {
961
+ await appInit();
962
+ }
963
+ const newSettings = await readSettings2();
964
+ if (typeof newSettings !== "object") {
965
+ console.log("[xyd:dev-watcher] Settings is not an object");
966
+ return;
967
+ }
968
+ invalidateSettings(server);
969
+ await touchReactRouterConfig();
970
+ await touchLayoutPage();
971
+ server.ws.send({ type: "full-reload" });
972
+ }
973
+ });
974
+ watcher.on("error", (error) => {
975
+ console.error("[xyd:dev] File watcher error:", error);
976
+ });
145
977
  await preview.listen(port);
978
+ if (respPluginDocs.settings.navigation) {
979
+ await optimizeDepsFix(port, respPluginDocs.settings.navigation);
980
+ }
146
981
  preview.printUrls();
147
982
  preview.bindCLIShortcuts({ print: true });
983
+ preview.httpServer?.once("close", () => {
984
+ watcher.close();
985
+ });
148
986
  }
149
-
150
- // src/run/serve.ts
151
- import fs2 from "node:fs";
152
- import os from "node:os";
153
- import path3 from "node:path";
154
- import url from "node:url";
155
- import { createRequestHandler } from "@react-router/express";
156
- import compression from "compression";
157
- import express from "express";
158
- import morgan from "morgan";
159
- import sourceMapSupport from "source-map-support";
160
- import getPort from "get-port";
161
- function parseNumber(raw) {
162
- if (raw === void 0) return void 0;
163
- let maybe = Number(raw);
164
- if (Number.isNaN(maybe)) return void 0;
165
- return maybe;
166
- }
167
- async function serve() {
168
- process.env.NODE_ENV = process.env.NODE_ENV ?? "production";
169
- sourceMapSupport.install({
170
- retrieveSourceMap: function(source) {
171
- let match = source.startsWith("file://");
172
- if (match) {
173
- let filePath = url.fileURLToPath(source);
174
- let sourceMapPath = `${filePath}.map`;
175
- if (fs2.existsSync(sourceMapPath)) {
176
- return {
177
- url: source,
178
- map: fs2.readFileSync(sourceMapPath, "utf8")
179
- };
987
+ function resolveApiFilePaths(basePath, api) {
988
+ const result = {};
989
+ const apis = [api.openapi, api.graphql, api.sources].filter((s) => s !== void 0);
990
+ apis.forEach((section) => {
991
+ flattenApiFile(section).forEach((p) => {
992
+ const apiAbsPath = path3.resolve(basePath, p);
993
+ result[apiAbsPath] = true;
994
+ });
995
+ });
996
+ return result;
997
+ }
998
+ function flattenApiFile(file) {
999
+ if (!file) return [];
1000
+ if (typeof file === "string") {
1001
+ return [file];
1002
+ }
1003
+ if (Array.isArray(file)) {
1004
+ return file.flatMap(flattenApiFile);
1005
+ }
1006
+ if (typeof file === "object") {
1007
+ const obj = file;
1008
+ if (typeof obj.source === "string") {
1009
+ return [obj.source];
1010
+ }
1011
+ return Object.values(obj).flatMap(flattenApiFile);
1012
+ }
1013
+ return [];
1014
+ }
1015
+ function getFirstPageFromNavigation(navigation) {
1016
+ if (!navigation?.sidebar?.length) {
1017
+ return null;
1018
+ }
1019
+ function extractFirstPage(pages) {
1020
+ for (const page of pages) {
1021
+ if (typeof page === "string") {
1022
+ return normalizePagePath(page);
1023
+ }
1024
+ if (typeof page === "object") {
1025
+ if ("route" in page && page.pages) {
1026
+ const firstPage = extractFirstPage(page.pages);
1027
+ if (firstPage) return firstPage;
1028
+ }
1029
+ if ("pages" in page && page.pages) {
1030
+ const firstPage = extractFirstPage(page.pages);
1031
+ if (firstPage) return firstPage;
1032
+ }
1033
+ if ("page" in page && typeof page.page === "string") {
1034
+ return normalizePagePath(page.page);
180
1035
  }
181
1036
  }
182
- return null;
183
1037
  }
184
- });
185
- let port2 = parseNumber(process.env.PORT) ?? await getPort({ port: 3e3 });
186
- let buildPathArg = path3.join(process.cwd(), ".xyd/build/server/index.js");
187
- if (!buildPathArg) {
188
- console.error(`
189
- Usage: react-router-serve <server-build-path> - e.g. react-router-serve build/server/index.js`);
190
- process.exit(1);
191
- }
192
- let buildPath = path3.resolve(buildPathArg);
193
- let build2 = await import(url.pathToFileURL(buildPath).href);
194
- let onListen = () => {
195
- let address = process.env.HOST || Object.values(os.networkInterfaces()).flat().find((ip) => String(ip?.family).includes("4") && !ip?.internal)?.address;
196
- if (!address) {
197
- console.log(`[xyd-serve] http://localhost:${port2}`);
198
- } else {
199
- console.log(
200
- `[xyd-serve] http://localhost:${port2} (http://${address}:${port2})`
201
- );
1038
+ return null;
1039
+ }
1040
+ return extractFirstPage(navigation.sidebar);
1041
+ }
1042
+ function normalizePagePath(pagePath) {
1043
+ let normalized = pagePath.replace(/\.(md|mdx)$/, "");
1044
+ if (normalized.endsWith("/index") || normalized === "index") {
1045
+ normalized = normalized.replace(/\/?index$/, "");
1046
+ }
1047
+ if (normalized.startsWith("/")) {
1048
+ normalized = normalized.slice(1);
1049
+ }
1050
+ return normalized;
1051
+ }
1052
+ async function fetchFirstPage(firstPage, port) {
1053
+ const urlsToTry = [
1054
+ `http://localhost:${port}/${firstPage}`,
1055
+ `http://localhost:${port}/${firstPage}/`,
1056
+ `http://localhost:${port}/${firstPage}.html`,
1057
+ `http://localhost:${port}/${firstPage}/index.html`
1058
+ ];
1059
+ for (const url of urlsToTry) {
1060
+ try {
1061
+ const response = await fetch(url);
1062
+ if (response.ok) {
1063
+ return;
1064
+ }
1065
+ } catch (error) {
1066
+ continue;
202
1067
  }
203
- };
204
- build2 = {
205
- ...build2,
206
- assetsBuildDirectory: path3.join(process.cwd(), ".xyd/build/client")
207
- };
208
- let app = express();
209
- app.disable("x-powered-by");
210
- app.use(compression());
211
- app.use(
212
- path3.posix.join(build2.publicPath, "assets"),
213
- express.static(path3.join(build2.assetsBuildDirectory, "assets"), {
214
- immutable: true,
215
- maxAge: "1y"
216
- })
217
- );
218
- app.use(build2.publicPath, express.static(build2.assetsBuildDirectory));
219
- app.use(express.static("public", { maxAge: "1h" }));
220
- app.use(morgan("tiny"));
221
- app.all(
222
- "*",
223
- createRequestHandler({
224
- build: build2,
225
- mode: process.env.NODE_ENV
226
- })
227
- );
228
- let server = process.env.HOST ? app.listen(port2, process.env.HOST, onListen) : app.listen(port2, onListen);
229
- ["SIGTERM", "SIGINT"].forEach((signal) => {
230
- process.once(signal, () => server?.close(console.error));
1068
+ }
1069
+ }
1070
+ function invalidateSettings(server) {
1071
+ const virtualId = "virtual:xyd-settings";
1072
+ const resolvedId = virtualId + ".jsx";
1073
+ const mod = server.moduleGraph.getModuleById(resolvedId);
1074
+ if (!mod) {
1075
+ console.log("[xyd:dev-watcher] Settings module not found");
1076
+ return;
1077
+ }
1078
+ server.moduleGraph.invalidateModule(mod);
1079
+ server.ws.send({
1080
+ type: "update",
1081
+ updates: [
1082
+ {
1083
+ type: "js-update",
1084
+ path: `/@id/${resolvedId}`,
1085
+ acceptedPath: `/@id/${resolvedId}`,
1086
+ timestamp: Date.now()
1087
+ }
1088
+ ]
1089
+ });
1090
+ }
1091
+ async function touchReactRouterConfig() {
1092
+ const hostPath = getHostPath();
1093
+ const hostReactRouterConfig = path3.join(hostPath, "react-router.config.ts");
1094
+ await fs3.promises.utimes(hostReactRouterConfig, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
1095
+ }
1096
+ async function touchLayoutPage() {
1097
+ const docsPluginBasePath = getDocsPluginBasePath();
1098
+ const layoutPath = path3.join(docsPluginBasePath, "./src/pages/layout.tsx");
1099
+ await fs3.promises.utimes(layoutPath, /* @__PURE__ */ new Date(), /* @__PURE__ */ new Date());
1100
+ }
1101
+ async function optimizeDepsFix(port, navigation) {
1102
+ const firstPage = getFirstPageFromNavigation(navigation);
1103
+ if (firstPage) {
1104
+ await fetchFirstPage(firstPage, port);
1105
+ }
1106
+ }
1107
+
1108
+ // src/install.ts
1109
+ import fs4 from "fs";
1110
+ import { readSettings as readSettings3 } from "@xyd-js/plugin-docs";
1111
+ async function install() {
1112
+ const settings = await readSettings3();
1113
+ if (!settings) {
1114
+ throw new Error("cannot preload settings");
1115
+ }
1116
+ if (typeof settings === "string") {
1117
+ throw new Error("install does not support string settings");
1118
+ }
1119
+ const hostPath = getHostPath();
1120
+ if (fs4.existsSync(hostPath)) {
1121
+ fs4.rmSync(hostPath, { recursive: true, force: true });
1122
+ }
1123
+ await preWorkspaceSetup({
1124
+ force: true
231
1125
  });
1126
+ await postWorkspaceSetup(settings);
232
1127
  }
233
1128
  export {
234
1129
  build,
235
1130
  dev,
236
- serve
1131
+ install
237
1132
  };
238
1133
  //# sourceMappingURL=index.js.map