@open-pioneer/vite-plugin-pioneer 6.0.3 → 7.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.
package/dist/index.js CHANGED
@@ -1,184 +1,202 @@
1
- // src/codegenPlugin.ts
2
- import { readFile as readFile3 } from "node:fs/promises";
3
- import { dirname as dirname4 } from "node:path";
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
4
3
  import { cwd } from "node:process";
5
- import { RuntimeSupport as RuntimeSupport3 } from "@open-pioneer/build-common";
6
- import { normalizePath as normalizePath5 } from "vite";
7
-
8
- // src/codegen/generateAppMetadata.ts
9
- import { RuntimeSupport } from "@open-pioneer/build-common";
10
-
11
- // src/codegen/shared.ts
12
- import { existsSync } from "fs";
13
- import { basename, dirname, posix } from "node:path/posix";
14
- import { join } from "path/posix";
4
+ import { BUILD_CONFIG_NAME, PackageMetadataV1, RuntimeSupport, createPackageConfigFromBuildConfig, createPackageConfigFromPackageMetadata, loadBuildConfig } from "@open-pioneer/build-common";
15
5
  import { normalizePath } from "vite";
16
- var VIRTUAL_PREFIX = "\0open-pioneer:";
17
- var VIRTUAL_PREFIX_RE = /\0open-pioneer:(?<suffix>.*)/;
18
- var APP_MODULE = "@@open-pioneer-app";
19
- var APP_META_QUERY = "open-pioneer-app";
20
- var APP_META_RE = /[?&]open-pioneer-app(?:$|&)/;
21
- var APP_PACKAGES_QUERY = "open-pioneer-packages";
22
- var APP_PACKAGES_RE = /[?&]open-pioneer-packages(?:$|&)/;
23
- var APP_CSS_QUERY = "open-pioneer-styles";
24
- var APP_CSS_RE = /[?&]open-pioneer-styles(?:$|&)/;
25
- var APP_I18N_INDEX_QUERY = "open-pioneer-i18n-index";
26
- var APP_I18N_INDEX_RE = /[?&]open-pioneer-i18n-index(?:$|&)/;
27
- var APP_I18N_QUERY = "open-pioneer-i18n";
28
- var APP_I18N_RE = /[?&]open-pioneer-i18n(?:$|&)/;
29
- var APP_I18N_LOCALE_RE = /[?&]locale=(?<locale>.*?)(?:$|&)/;
30
- var PACKAGE_HOOKS_MODULE = "@@open-pioneer-react-hooks";
31
- var SOURCE_INFO_MODULE = "@@open-pioneer-source-info";
32
- var SOURCE_INFO_MODULE_MODULE_PATH_RE = /@@open-pioneer-source-info\/(?<module_path>.*)&lang=js$/;
33
- var SOURCE_FILE_RE = /^(.*?)(?:\?|$)/;
34
- var VIRTUAL_ID_FILTER = [/^\0?open-pioneer:/, /[?&]open-pioneer/, /@@open-pioneer/];
6
+ import { existsSync } from "fs";
7
+ import posix$1, { basename, dirname as dirname$1, posix as posix$2 } from "node:path/posix";
8
+ import { join as join$1 } from "path/posix";
9
+ import generateModule from "@babel/generator";
10
+ import templateModule from "@babel/template";
11
+ import nodesModule from "@babel/types";
12
+ import { readFile as readFile$1, realpath } from "fs/promises";
13
+ import { basename as basename$1, dirname as dirname$2, posix as posix$3 } from "path";
14
+ import { ResolverFactory } from "oxc-resolver";
15
+ import { glob } from "tinyglobby";
16
+ import pkg from "debug";
17
+ import * as fs from "node:fs";
18
+ import { existsSync as existsSync$1 } from "node:fs";
19
+ import { findDepPkgJsonPath } from "vitefu";
20
+ import { load } from "js-yaml";
21
+ import { z } from "zod";
22
+ import { createErrorMap, fromZodError } from "zod-validation-error";
23
+ //#region src/codegen/shared.ts
24
+ /**
25
+ * MODULE ID ENCODING
26
+ * ==================
27
+ *
28
+ * There are two encoding schemes for virtual modules in this file:
29
+ *
30
+ * 1. Leading null byte, e.g. `\0open-pioneer:deployment`.
31
+ * This is used for "global" modules that are not scoped to a specific file, app or package.
32
+ * This encoding is the usual practice in the rollup / vite ecosystem, making it very reliable.
33
+ * It has the disadvantage that the generated files show up "somewhere" in the browser debugger.
34
+ * 2. Magic filenames, e.g. /path/to/app/@@open-pioneer-app.
35
+ * These use a different prefix ("@@") for file names so they show up next to the relevant location,
36
+ * for example as if they were developed in a specific package.
37
+ * This was needed for both better debugging experience and to make some imports work well.
38
+ */
39
+ const VIRTUAL_PREFIX = "\0open-pioneer:";
40
+ const VIRTUAL_PREFIX_RE = /\0open-pioneer:(?<suffix>.*)/;
41
+ const APP_MODULE = "@@open-pioneer-app";
42
+ const APP_META_QUERY = "open-pioneer-app";
43
+ const APP_META_RE = /[?&]open-pioneer-app(?:$|&)/;
44
+ const APP_PACKAGES_QUERY = "open-pioneer-packages";
45
+ const APP_PACKAGES_RE = /[?&]open-pioneer-packages(?:$|&)/;
46
+ const APP_CSS_QUERY = "open-pioneer-styles";
47
+ const APP_CSS_RE = /[?&]open-pioneer-styles(?:$|&)/;
48
+ const APP_I18N_INDEX_QUERY = "open-pioneer-i18n-index";
49
+ const APP_I18N_INDEX_RE = /[?&]open-pioneer-i18n-index(?:$|&)/;
50
+ const APP_I18N_QUERY = "open-pioneer-i18n";
51
+ const APP_I18N_RE = /[?&]open-pioneer-i18n(?:$|&)/;
52
+ const APP_I18N_LOCALE_RE = /[?&]locale=(?<locale>.*?)(?:$|&)/;
53
+ const PACKAGE_HOOKS_MODULE = "@@open-pioneer-react-hooks";
54
+ const SOURCE_INFO_MODULE = "@@open-pioneer-source-info";
55
+ const SOURCE_INFO_MODULE_MODULE_PATH_RE = /@@open-pioneer-source-info\/(?<module_path>.*)&lang=js$/;
56
+ const SOURCE_FILE_RE = /^(.*?)(?:\?|$)/;
57
+ /**
58
+ * Filter for rolldown.
59
+ *
60
+ * These regular expressions should match against our virtual modules (see above)
61
+ * but should filter out as many unrelated module ids as possible for performance.
62
+ */
63
+ const VIRTUAL_ID_FILTER = [
64
+ /^\0?open-pioneer:/,
65
+ /[?&]open-pioneer/,
66
+ /@@open-pioneer/
67
+ ];
68
+ /**
69
+ * Takes a module id as input and parses it.
70
+ * If this plugin is not responsible to load the module id, this function returns `undefined`.
71
+ *
72
+ * Otherwise, the module is parsed into an object and returned.
73
+ */
35
74
  function parseVirtualModuleId(inputModuleId) {
36
- var _a;
37
- const moduleId = normalizePath(inputModuleId);
38
- if (!moduleId) {
39
- return void 0;
40
- }
41
- if (moduleId.startsWith("\0")) {
42
- const virtualPrefixMatch = inputModuleId.match(VIRTUAL_PREFIX_RE);
43
- if (virtualPrefixMatch) {
44
- const suffix = (_a = virtualPrefixMatch.groups) == null ? void 0 : _a["suffix"];
45
- if (suffix === "deployment") {
46
- return { type: "deployment" };
47
- }
48
- }
49
- return void 0;
50
- }
51
- const sourceFile = getSourceFile(moduleId);
52
- if (!sourceFile) {
53
- return void 0;
54
- }
55
- const base = basename(sourceFile);
56
- if (base === PACKAGE_HOOKS_MODULE) {
57
- return {
58
- type: "package-hooks",
59
- packageDirectory: dirname(sourceFile)
60
- };
61
- }
62
- const sourceInfoMatch = moduleId.match(SOURCE_INFO_MODULE_MODULE_PATH_RE);
63
- if (sourceInfoMatch) {
64
- return parseSourceInfoModule(moduleId, sourceInfoMatch);
65
- }
66
- if (base === APP_MODULE) {
67
- return parseAppModuleId(sourceFile, moduleId);
68
- }
69
- return void 0;
75
+ const moduleId = normalizePath(inputModuleId);
76
+ if (!moduleId) return;
77
+ if (moduleId.startsWith("\0")) {
78
+ const virtualPrefixMatch = inputModuleId.match(VIRTUAL_PREFIX_RE);
79
+ if (virtualPrefixMatch) {
80
+ if (virtualPrefixMatch.groups?.["suffix"] === "deployment") return { type: "deployment" };
81
+ }
82
+ return;
83
+ }
84
+ const sourceFile = getSourceFile(moduleId);
85
+ if (!sourceFile) return;
86
+ const base = basename(sourceFile);
87
+ if (base === PACKAGE_HOOKS_MODULE) return {
88
+ type: "package-hooks",
89
+ packageDirectory: dirname$1(sourceFile)
90
+ };
91
+ const sourceInfoMatch = moduleId.match(SOURCE_INFO_MODULE_MODULE_PATH_RE);
92
+ if (sourceInfoMatch) return parseSourceInfoModule(moduleId, sourceInfoMatch);
93
+ if (base === APP_MODULE) return parseAppModuleId(sourceFile, moduleId);
70
94
  }
71
95
  function parseSourceInfoModule(moduleId, sourceInfoMatch) {
72
- var _a;
73
- const encodedModulePath = (_a = sourceInfoMatch == null ? void 0 : sourceInfoMatch.groups) == null ? void 0 : _a["module_path"];
74
- if (!encodedModulePath) {
75
- throw new Error(`Missing module path in source info module id: ${moduleId}`);
76
- }
77
- const relativeModulePath = decodeURIComponent(encodedModulePath);
78
- const moduleRoot = moduleId.substring(0, moduleId.indexOf(`${SOURCE_INFO_MODULE}`));
79
- if (!moduleRoot) {
80
- throw new Error(
81
- `Cannot determine module root directory for source info module id: ${moduleId}`
82
- );
83
- }
84
- const fullModulePath = join(moduleRoot, relativeModulePath);
85
- const packageJsonPath = findPackageJson(dirname(fullModulePath), moduleRoot);
86
- if (!packageJsonPath) {
87
- throw new Error(`Cannot determine package.json for source info module id: ${moduleId}`);
88
- }
89
- const packageDirectory = dirname(packageJsonPath);
90
- return { type: "source-info", modulePath: relativeModulePath, packageDirectory };
96
+ const encodedModulePath = sourceInfoMatch?.groups?.["module_path"];
97
+ if (!encodedModulePath) throw new Error(`Missing module path in source info module id: ${moduleId}`);
98
+ const relativeModulePath = decodeURIComponent(encodedModulePath);
99
+ const moduleRoot = moduleId.substring(0, moduleId.indexOf(`${SOURCE_INFO_MODULE}`));
100
+ if (!moduleRoot) throw new Error(`Cannot determine module root directory for source info module id: ${moduleId}`);
101
+ const packageJsonPath = findPackageJson(dirname$1(join$1(moduleRoot, relativeModulePath)), moduleRoot);
102
+ if (!packageJsonPath) throw new Error(`Cannot determine package.json for source info module id: ${moduleId}`);
103
+ return {
104
+ type: "source-info",
105
+ modulePath: relativeModulePath,
106
+ packageDirectory: dirname$1(packageJsonPath)
107
+ };
91
108
  }
92
109
  function parseAppModuleId(sourceFile, moduleId) {
93
- var _a, _b;
94
- const packageDirectory = dirname(sourceFile);
95
- if (moduleId.match(APP_META_RE)) {
96
- const type = "app-meta";
97
- return { type, packageDirectory };
98
- } else if (moduleId.match(APP_PACKAGES_RE)) {
99
- const type = "app-packages";
100
- return { type, packageDirectory };
101
- } else if (moduleId.match(APP_CSS_RE)) {
102
- if (moduleId.endsWith(".map")) {
103
- return void 0;
104
- }
105
- const type = "app-css";
106
- return { type, packageDirectory };
107
- } else if (moduleId.match(APP_I18N_INDEX_RE)) {
108
- const type = "app-i18n-index";
109
- return { type, packageDirectory };
110
- } else if (moduleId.match(APP_I18N_RE)) {
111
- const type = "app-i18n";
112
- const locale = (_b = (_a = moduleId.match(APP_I18N_LOCALE_RE)) == null ? void 0 : _a.groups) == null ? void 0 : _b["locale"];
113
- if (!locale) {
114
- throw new Error("Missing locale name in i18n module request");
115
- }
116
- return { type, packageDirectory, locale };
117
- }
118
- throw new Error(`Unexpected module id: ${moduleId}`);
110
+ const packageDirectory = dirname$1(sourceFile);
111
+ if (moduleId.match(APP_META_RE)) return {
112
+ type: "app-meta",
113
+ packageDirectory
114
+ };
115
+ else if (moduleId.match(APP_PACKAGES_RE)) return {
116
+ type: "app-packages",
117
+ packageDirectory
118
+ };
119
+ else if (moduleId.match(APP_CSS_RE)) {
120
+ if (moduleId.endsWith(".map")) return;
121
+ return {
122
+ type: "app-css",
123
+ packageDirectory
124
+ };
125
+ } else if (moduleId.match(APP_I18N_INDEX_RE)) return {
126
+ type: "app-i18n-index",
127
+ packageDirectory
128
+ };
129
+ else if (moduleId.match(APP_I18N_RE)) {
130
+ const type = "app-i18n";
131
+ const locale = moduleId.match(APP_I18N_LOCALE_RE)?.groups?.["locale"];
132
+ if (!locale) throw new Error("Missing locale name in i18n module request");
133
+ return {
134
+ type,
135
+ packageDirectory,
136
+ locale
137
+ };
138
+ }
139
+ throw new Error(`Unexpected module id: ${moduleId}`);
119
140
  }
141
+ /**
142
+ * Serializes the given virtual module descriptor into a module id string.
143
+ */
120
144
  function serializeModuleId(mod) {
121
- switch (mod.type) {
122
- case "package-hooks":
123
- return `${mod.packageDirectory}/${PACKAGE_HOOKS_MODULE}`;
124
- case "source-info":
125
- return serializeSourceInfoModule(mod);
126
- case "app-meta":
127
- return `${mod.packageDirectory}/${APP_MODULE}?${APP_META_QUERY}`;
128
- case "app-packages":
129
- return `${mod.packageDirectory}/${APP_MODULE}?${APP_PACKAGES_QUERY}`;
130
- case "app-css":
131
- return `${mod.packageDirectory}/${APP_MODULE}?${APP_CSS_QUERY}`;
132
- case "app-i18n-index":
133
- return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_INDEX_QUERY}`;
134
- case "app-i18n":
135
- return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_QUERY}&locale=${mod.locale}`;
136
- case "deployment":
137
- return `${VIRTUAL_PREFIX}deployment`;
138
- }
145
+ switch (mod.type) {
146
+ case "package-hooks": return `${mod.packageDirectory}/${PACKAGE_HOOKS_MODULE}`;
147
+ case "source-info": return serializeSourceInfoModule(mod);
148
+ case "app-meta": return `${mod.packageDirectory}/${APP_MODULE}?${APP_META_QUERY}`;
149
+ case "app-packages": return `${mod.packageDirectory}/${APP_MODULE}?${APP_PACKAGES_QUERY}`;
150
+ case "app-css": return `${mod.packageDirectory}/${APP_MODULE}?${APP_CSS_QUERY}`;
151
+ case "app-i18n-index": return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_INDEX_QUERY}`;
152
+ case "app-i18n": return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_QUERY}&locale=${mod.locale}`;
153
+ case "deployment": return `${VIRTUAL_PREFIX}deployment`;
154
+ }
139
155
  }
140
156
  function serializeSourceInfoModule(mod) {
141
- const packageDirectory = mod.packageDirectory;
142
- const modulePath = mod.modulePath;
143
- const normalizedModulePath = normalizePath(modulePath);
144
- const relativeModulePath = posix.relative(packageDirectory, normalizedModulePath);
145
- if (relativeModulePath.match(/^\.\.?[\\/]/)) {
146
- throw new Error("Internal error: unexpected relative path");
147
- }
148
- return `${mod.packageDirectory}/${SOURCE_INFO_MODULE}/${encodeURIComponent(relativeModulePath)}&lang=js`;
157
+ const packageDirectory = mod.packageDirectory;
158
+ const modulePath = mod.modulePath;
159
+ const normalizedModulePath = normalizePath(modulePath);
160
+ const relativeModulePath = posix$2.relative(packageDirectory, normalizedModulePath);
161
+ if (relativeModulePath.match(/^\.\.?[\\/]/)) throw new Error("Internal error: unexpected relative path");
162
+ return `${mod.packageDirectory}/${SOURCE_INFO_MODULE}/${encodeURIComponent(relativeModulePath)}&lang=js`;
149
163
  }
150
164
  function getSourceFile(moduleId) {
151
- var _a;
152
- const sourceFile = (_a = moduleId.match(SOURCE_FILE_RE)) == null ? void 0 : _a[1];
153
- if (!sourceFile || moduleId[0] == "\0") {
154
- return void 0;
155
- }
156
- return sourceFile;
165
+ const sourceFile = moduleId.match(SOURCE_FILE_RE)?.[1];
166
+ if (!sourceFile || moduleId[0] == "\0") return;
167
+ return sourceFile;
157
168
  }
158
169
  function findPackageJson(startDir, rootDir) {
159
- let dir = startDir;
160
- while (dir) {
161
- const candidate = join(dir, "package.json");
162
- if (existsSync(candidate)) {
163
- return candidate;
164
- }
165
- if (normalizePath(dir) == normalizePath(rootDir)) {
166
- return void 0;
167
- }
168
- const parent = dirname(dir);
169
- dir = parent === dir || parent === "." ? "" : parent;
170
- }
171
- return void 0;
170
+ let dir = startDir;
171
+ while (dir) {
172
+ const candidate = join$1(dir, "package.json");
173
+ if (existsSync(candidate)) return candidate;
174
+ if (normalizePath(dir) == normalizePath(rootDir)) return;
175
+ const parent = dirname$1(dir);
176
+ dir = parent === dir || parent === "." ? "" : parent;
177
+ }
172
178
  }
173
-
174
- // src/codegen/generateAppMetadata.ts
179
+ //#endregion
180
+ //#region src/codegen/generateAppMetadata.ts
181
+ /**
182
+ * Generates the main app metadata module.
183
+ * It delegates the actual metadata generation to auxiliary modules.
184
+ */
175
185
  function generateAppMetadata(packageDirectory, metadataModuleId, runtimeMetadataVersion) {
176
- const packagesModule = serializeModuleId({ type: "app-packages", packageDirectory });
177
- const cssModule = serializeModuleId({ type: "app-css", packageDirectory }) + "&inline&lang.scss";
178
- const i18nModule = serializeModuleId({ type: "app-i18n-index", packageDirectory });
179
- const features = RuntimeSupport.getRuntimeFeatures(runtimeMetadataVersion);
180
- const boxMessages = features.supportsMessageBox;
181
- return `
186
+ const packagesModule = serializeModuleId({
187
+ type: "app-packages",
188
+ packageDirectory
189
+ });
190
+ const cssModule = serializeModuleId({
191
+ type: "app-css",
192
+ packageDirectory
193
+ }) + "&inline&lang.scss";
194
+ const i18nModule = serializeModuleId({
195
+ type: "app-i18n-index",
196
+ packageDirectory
197
+ });
198
+ const boxMessages = RuntimeSupport.getRuntimeFeatures(runtimeMetadataVersion).supportsMessageBox;
199
+ return `
182
200
  import { createBox } from ${JSON.stringify(metadataModuleId)};
183
201
  import packages from ${JSON.stringify(packagesModule)};
184
202
  import stylesString from ${JSON.stringify(cssModule)};
@@ -229,27 +247,26 @@ export {
229
247
  };
230
248
  `.trim();
231
249
  }
232
-
233
- // src/codegen/generateCombinedCss.ts
250
+ //#endregion
251
+ //#region src/codegen/generateCombinedCss.ts
252
+ /**
253
+ * Generates a css file that imports the css file defined by the packages.
254
+ */
234
255
  function generateCombinedCss(packages) {
235
- const cssImport = (file) => `@import ${JSON.stringify(file)};`;
236
- return packages.filter((pkg2) => !!pkg2.cssFilePath).map((pkg2) => cssImport(pkg2.cssFilePath)).join("\n");
256
+ const cssImport = (file) => `@import ${JSON.stringify(file)};`;
257
+ return packages.filter((pkg) => !!pkg.cssFilePath).map((pkg) => cssImport(pkg.cssFilePath)).join("\n");
237
258
  }
238
-
239
- // src/ReportableError.ts
240
- var ReportableError = class extends Error {
241
- };
242
-
243
- // src/utils/babelDeps.ts
244
- import generateModule from "@babel/generator";
245
- import templateModule from "@babel/template";
246
- import nodesModule from "@babel/types";
247
- var generate = generateModule.default || generateModule;
248
- var template = templateModule.default || templateModule;
249
- var nodes = nodesModule;
250
-
251
- // src/codegen/generateI18n.ts
252
- var INDEX_TEMPLATE = template.program(`
259
+ //#endregion
260
+ //#region src/ReportableError.ts
261
+ var ReportableError = class extends Error {};
262
+ //#endregion
263
+ //#region src/utils/babelDeps.ts
264
+ const generate = generateModule.default || generateModule;
265
+ const template = templateModule.default || templateModule;
266
+ const nodes = nodesModule;
267
+ //#endregion
268
+ //#region src/codegen/generateI18n.ts
269
+ const INDEX_TEMPLATE = template.program(`
253
270
  export const locales = %%LOCALES_ARRAY%%;
254
271
 
255
272
  export function loadMessages(locale) {
@@ -257,118 +274,93 @@ var INDEX_TEMPLATE = template.program(`
257
274
  throw new Error(\`Unsupported locale: '\${locale}'\`);
258
275
  }
259
276
  `);
260
- var IMPORT_TEMPLATE = template.statement(`
277
+ const IMPORT_TEMPLATE = template.statement(`
261
278
  return import(%%MODULE_ID%%).then(mod => mod.default);
262
279
  `);
263
- var MESSAGES_TEMPLATE = template.program(`
280
+ const MESSAGES_TEMPLATE = template.program(`
264
281
  const messages = JSON.parse(%%SERIALIZED%%);
265
282
  export default messages;
266
283
  `);
284
+ /**
285
+ * Generates a lookup table for the languages supported by the given application.
286
+ */
267
287
  function generateI18nIndex(packageDirectory, locales) {
268
- const localesArray = nodes.arrayExpression(
269
- locales.map((locale) => nodes.stringLiteral(locale))
270
- );
271
- const switchStmt = nodes.switchStatement(
272
- nodes.identifier("locale"),
273
- locales.map((locale) => {
274
- const localeModuleId = serializeModuleId({
275
- type: "app-i18n",
276
- packageDirectory,
277
- locale
278
- });
279
- const importStatement = IMPORT_TEMPLATE({
280
- MODULE_ID: nodes.stringLiteral(localeModuleId)
281
- });
282
- return nodes.switchCase(nodes.stringLiteral(locale), [importStatement]);
283
- })
284
- );
285
- const program = INDEX_TEMPLATE({
286
- LOCALES_ARRAY: localesArray,
287
- LOCALE_SWITCH: switchStmt
288
- });
289
- return generate(program).code;
288
+ const localesArray = nodes.arrayExpression(locales.map((locale) => nodes.stringLiteral(locale)));
289
+ const switchStmt = nodes.switchStatement(nodes.identifier("locale"), locales.map((locale) => {
290
+ const localeModuleId = serializeModuleId({
291
+ type: "app-i18n",
292
+ packageDirectory,
293
+ locale
294
+ });
295
+ const importStatement = IMPORT_TEMPLATE({ MODULE_ID: nodes.stringLiteral(localeModuleId) });
296
+ return nodes.switchCase(nodes.stringLiteral(locale), [importStatement]);
297
+ }));
298
+ return generate(INDEX_TEMPLATE({
299
+ LOCALES_ARRAY: localesArray,
300
+ LOCALE_SWITCH: switchStmt
301
+ })).code;
290
302
  }
303
+ /**
304
+ * Generates a messages module containing a single default export: the messages record.
305
+ *
306
+ * Messages are taken from the given packages (for the specified locale).
307
+ */
291
308
  async function generateI18nMessages(options) {
292
- const { locale, appName, packages, loadI18n } = options;
293
- const packageMessages = /* @__PURE__ */ new Map();
294
- const packagesNeedingMessages = /* @__PURE__ */ new Set();
295
- let packageOverrides;
296
- for (const pkg2 of packages) {
297
- if (pkg2.i18nPaths.size !== 0) {
298
- packagesNeedingMessages.add(pkg2.name);
299
- }
300
- const filePath = pkg2.i18nPaths.get(locale);
301
- if (!filePath) {
302
- continue;
303
- }
304
- const { messages, overrides } = await loadI18n(pkg2, filePath);
305
- if (pkg2.name === appName) {
306
- packageOverrides = overrides;
307
- } else if (overrides) {
308
- throw new ReportableError(
309
- `Unexpected 'overrides' block in '${filePath}'. Overrides are only supported in the app.`
310
- );
311
- }
312
- packageMessages.set(pkg2.name, messages);
313
- }
314
- if (packageOverrides) {
315
- for (const [packageName, messages] of packageOverrides.entries()) {
316
- const existingMessages = packageMessages.get(packageName);
317
- if (!existingMessages) {
318
- packageMessages.set(packageName, messages);
319
- continue;
320
- }
321
- const updatedMessages = new Map([...existingMessages, ...messages]);
322
- packageMessages.set(packageName, updatedMessages);
323
- }
324
- }
325
- for (const packageName of packagesNeedingMessages) {
326
- const messages = packageMessages.get(packageName);
327
- if (!messages) {
328
- throw new ReportableError(
329
- `Package '${packageName}' does not support locale '${locale}'. Either update the package or add messages from the app via 'overrides'.`
330
- );
331
- }
332
- }
333
- const allMessages = {};
334
- for (const [packageName, messages] of packageMessages.entries()) {
335
- allMessages[packageName] = Object.fromEntries(messages.entries());
336
- }
337
- const serialized = JSON.stringify(allMessages);
338
- const program = MESSAGES_TEMPLATE({
339
- SERIALIZED: nodes.stringLiteral(serialized)
340
- });
341
- return generate(program).code;
309
+ const { locale, appName, packages, loadI18n } = options;
310
+ const packageMessages = /* @__PURE__ */ new Map();
311
+ const packagesNeedingMessages = /* @__PURE__ */ new Set();
312
+ let packageOverrides;
313
+ for (const pkg of packages) {
314
+ if (pkg.i18nPaths.size !== 0) packagesNeedingMessages.add(pkg.name);
315
+ const filePath = pkg.i18nPaths.get(locale);
316
+ if (!filePath) continue;
317
+ const { messages, overrides } = await loadI18n(pkg, filePath);
318
+ if (pkg.name === appName) packageOverrides = overrides;
319
+ else if (overrides) throw new ReportableError(`Unexpected 'overrides' block in '${filePath}'. Overrides are only supported in the app.`);
320
+ packageMessages.set(pkg.name, messages);
321
+ }
322
+ if (packageOverrides) for (const [packageName, messages] of packageOverrides.entries()) {
323
+ const existingMessages = packageMessages.get(packageName);
324
+ if (!existingMessages) {
325
+ packageMessages.set(packageName, messages);
326
+ continue;
327
+ }
328
+ const updatedMessages = new Map([...existingMessages, ...messages]);
329
+ packageMessages.set(packageName, updatedMessages);
330
+ }
331
+ for (const packageName of packagesNeedingMessages) if (!packageMessages.get(packageName)) throw new ReportableError(`Package '${packageName}' does not support locale '${locale}'. Either update the package or add messages from the app via 'overrides'.`);
332
+ const allMessages = {};
333
+ for (const [packageName, messages] of packageMessages.entries()) allMessages[packageName] = Object.fromEntries(messages.entries());
334
+ const serialized = JSON.stringify(allMessages);
335
+ return generate(MESSAGES_TEMPLATE({ SERIALIZED: nodes.stringLiteral(serialized) })).code;
342
336
  }
343
-
344
- // src/codegen/IdGenerator.ts
337
+ //#endregion
338
+ //#region src/codegen/IdGenerator.ts
345
339
  var IdGenerator = class {
346
- #existing = /* @__PURE__ */ new Map();
347
- /**
348
- * Returns a unique identifier (in the context of this instance) that resembles the input value.
349
- */
350
- generate(input) {
351
- const clean = cleanName(input);
352
- const existing = this.#existing;
353
- const count = existing.get(clean) ?? 0;
354
- existing.set(clean, count + 1);
355
- return count === 0 ? clean : `${clean}_${count}`;
356
- }
340
+ #existing = /* @__PURE__ */ new Map();
341
+ /**
342
+ * Returns a unique identifier (in the context of this instance) that resembles the input value.
343
+ */
344
+ generate(input) {
345
+ const clean = cleanName(input);
346
+ const existing = this.#existing;
347
+ const count = existing.get(clean) ?? 0;
348
+ existing.set(clean, count + 1);
349
+ return count === 0 ? clean : `${clean}_${count}`;
350
+ }
357
351
  };
358
352
  function cleanName(input) {
359
- let clean = input.replace(/[^A-Za-z0-9_]+/g, "_");
360
- clean = clean.replace(/[\d_]+$/, "");
361
- if (/^\d/.test(clean)) {
362
- clean = "_" + clean;
363
- }
364
- return clean || "var";
353
+ let clean = input.replace(/[^A-Za-z0-9_]+/g, "_");
354
+ clean = clean.replace(/[\d_]+$/, "");
355
+ if (/^\d/.test(clean)) clean = "_" + clean;
356
+ return clean || "var";
365
357
  }
366
-
367
- // src/codegen/generatePackagesMetadata.ts
368
- var SERVICE_IMPORT = template.statement(`
358
+ //#endregion
359
+ //#region src/codegen/generatePackagesMetadata.ts
360
+ const SERVICE_IMPORT = template.statement(`
369
361
  import { %%SERVICE_NAME%% as %%IMPORT_NAME%% } from %%IMPORT_SOURCE%%;
370
362
  `);
371
- var PKG_OBJECT = template.expression(`
363
+ const PKG_OBJECT = template.expression(`
372
364
  {
373
365
  name: %%PACKAGE_NAME%%,
374
366
  services: %%PACKAGE_SERVICES%%,
@@ -376,7 +368,7 @@ var PKG_OBJECT = template.expression(`
376
368
  properties: %%PROPERTIES%%
377
369
  }
378
370
  `);
379
- var SERVICE_OBJECT = template.expression(`
371
+ const SERVICE_OBJECT = template.expression(`
380
372
  {
381
373
  name: %%SERVICE_NAME%%,
382
374
  clazz: %%SERVICE_IMPORT%%,
@@ -384,1589 +376,1238 @@ var SERVICE_OBJECT = template.expression(`
384
376
  references: %%SERVICE_REFERENCES%%
385
377
  }
386
378
  `);
387
- var INTERFACE_OBJECT = template.expression(`
379
+ const INTERFACE_OBJECT = template.expression(`
388
380
  {
389
381
  name: %%INTERFACE_NAME%%,
390
382
  qualifier: %%QUALIFIER%%
391
383
  }
392
384
  `);
393
- var REFERENCE_OBJECT = template.expression(`
385
+ const REFERENCE_OBJECT = template.expression(`
394
386
  {
395
387
  name: %%INTERFACE_NAME%%,
396
388
  qualifier: %%QUALIFIER%%,
397
389
  all: %%ALL%%
398
390
  }
399
391
  `);
400
- var UI_OBJECT = template.expression(`
392
+ const UI_OBJECT = template.expression(`
401
393
  {
402
394
  references: %%UI_REFERENCES%%
403
395
  }
404
396
  `);
405
- var PROPERTY_OBJECT = template.expression(`
397
+ const PROPERTY_OBJECT = template.expression(`
406
398
  {
407
399
  value: %%VALUE%%,
408
400
  required: %%REQUIRED%%
409
401
  }
410
402
  `);
403
+ /**
404
+ * Generates a combined metadata structure that is essentially a Record<string, metadata.PackageMetadata>.
405
+ * The object contents must match the shape required by the runtime (declared in runtime/metadata/index.ts).
406
+ */
411
407
  function generatePackagesMetadata({ appName, packages }) {
412
- const idGenerator = new IdGenerator();
413
- const packagesMetadata = nodes.objectExpression([]);
414
- const imports = [];
415
- let overrides;
416
- for (const pkg2 of packages) {
417
- if (pkg2.name === appName) {
418
- overrides = pkg2.config.overrides;
419
- } else if (pkg2.config.overrides) {
420
- throw new ReportableError(
421
- `Unexpected 'overrides' in package '${pkg2.name}'. Overrides are only supported in the app.`
422
- );
423
- }
424
- }
425
- for (const pkg2 of packages) {
426
- const packageOverrides = overrides == null ? void 0 : overrides.get(pkg2.name);
427
- const packageMetadata = generatePackageMetadata(pkg2, {
428
- enableService(serviceName) {
429
- var _a, _b;
430
- return ((_b = (_a = packageOverrides == null ? void 0 : packageOverrides.services) == null ? void 0 : _a.get(serviceName)) == null ? void 0 : _b.enabled) ?? true;
431
- },
432
- importServiceClass(variableName, className, moduleId) {
433
- const id = idGenerator.generate(variableName);
434
- const renderedImporter = SERVICE_IMPORT({
435
- SERVICE_NAME: nodes.identifier(className),
436
- IMPORT_NAME: nodes.identifier(id),
437
- IMPORT_SOURCE: nodes.stringLiteral(moduleId)
438
- });
439
- imports.push(renderedImporter);
440
- return id;
441
- }
442
- });
443
- packagesMetadata.properties.push(
444
- nodes.objectProperty(nodes.stringLiteral(pkg2.name), packageMetadata)
445
- );
446
- }
447
- const program = nodes.program([...imports, nodes.exportDefaultDeclaration(packagesMetadata)]);
448
- return generate(program).code;
408
+ const idGenerator = new IdGenerator();
409
+ const packagesMetadata = nodes.objectExpression([]);
410
+ const imports = [];
411
+ let overrides;
412
+ for (const pkg of packages) if (pkg.name === appName) overrides = pkg.config.overrides;
413
+ else if (pkg.config.overrides) throw new ReportableError(`Unexpected 'overrides' in package '${pkg.name}'. Overrides are only supported in the app.`);
414
+ for (const pkg of packages) {
415
+ const packageOverrides = overrides?.get(pkg.name);
416
+ const packageMetadata = generatePackageMetadata(pkg, {
417
+ enableService(serviceName) {
418
+ return packageOverrides?.services?.get(serviceName)?.enabled ?? true;
419
+ },
420
+ importServiceClass(variableName, className, moduleId) {
421
+ const id = idGenerator.generate(variableName);
422
+ const renderedImporter = SERVICE_IMPORT({
423
+ SERVICE_NAME: nodes.identifier(className),
424
+ IMPORT_NAME: nodes.identifier(id),
425
+ IMPORT_SOURCE: nodes.stringLiteral(moduleId)
426
+ });
427
+ imports.push(renderedImporter);
428
+ return id;
429
+ }
430
+ });
431
+ packagesMetadata.properties.push(nodes.objectProperty(nodes.stringLiteral(pkg.name), packageMetadata));
432
+ }
433
+ return generate(nodes.program([...imports, nodes.exportDefaultDeclaration(packagesMetadata)])).code;
449
434
  }
450
- function generatePackageMetadata(pkg2, options) {
451
- const servicesObject = nodes.objectExpression([]);
452
- for (const service of pkg2.config.services.values()) {
453
- if (!options.enableService(service.serviceName)) {
454
- continue;
455
- }
456
- if (!pkg2.servicesModulePath) {
457
- throw new ReportableError(
458
- `Package '${pkg2.name}' must have a valid services module (typically 'services.ts' or 'services.js').
459
- The entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`
460
- );
461
- }
462
- const importName = options.importServiceClass(
463
- pkg2.name + "_" + service.serviceName,
464
- service.serviceName,
465
- pkg2.servicesModulePath
466
- );
467
- const serviceObject = SERVICE_OBJECT({
468
- SERVICE_NAME: nodes.stringLiteral(service.serviceName),
469
- SERVICE_IMPORT: nodes.identifier(importName),
470
- SERVICE_INTERFACES: nodes.arrayExpression(
471
- service.provides.map(
472
- (p) => INTERFACE_OBJECT({
473
- INTERFACE_NAME: nodes.stringLiteral(p.interfaceName),
474
- QUALIFIER: p.qualifier == null ? undefinedNode() : nodes.stringLiteral(p.qualifier)
475
- })
476
- )
477
- ),
478
- SERVICE_REFERENCES: nodes.objectExpression(
479
- Array.from(service.references.entries()).map(
480
- ([referenceName, referenceConfig]) => nodes.objectProperty(
481
- nodes.stringLiteral(referenceName),
482
- referenceObject(referenceConfig)
483
- )
484
- )
485
- )
486
- });
487
- servicesObject.properties.push(
488
- nodes.objectProperty(nodes.stringLiteral(service.serviceName), serviceObject)
489
- );
490
- }
491
- const uiObject = UI_OBJECT({
492
- UI_REFERENCES: nodes.arrayExpression(pkg2.config.uiReferences.map((r) => referenceObject(r)))
493
- });
494
- const propertiesObject = nodes.objectExpression(
495
- Array.from(pkg2.config.properties.values()).map(
496
- (prop) => nodes.objectProperty(
497
- nodes.stringLiteral(prop.propertyName),
498
- PROPERTY_OBJECT({
499
- VALUE: jsonToExpression(prop.defaultValue),
500
- REQUIRED: nodes.booleanLiteral(prop.required)
501
- })
502
- )
503
- )
504
- );
505
- const pkgObject = PKG_OBJECT({
506
- PACKAGE_NAME: nodes.stringLiteral(pkg2.name),
507
- PACKAGE_SERVICES: servicesObject,
508
- PACKAGE_UI: uiObject,
509
- PROPERTIES: propertiesObject
510
- });
511
- return pkgObject;
435
+ /**
436
+ * Generates the metadata object for a single package.
437
+ * As a side effect, service imports for required service classes will be emitted through a callback.
438
+ */
439
+ function generatePackageMetadata(pkg, options) {
440
+ const servicesObject = nodes.objectExpression([]);
441
+ for (const service of pkg.config.services.values()) {
442
+ if (!options.enableService(service.serviceName)) continue;
443
+ if (!pkg.servicesModulePath) throw new ReportableError(`Package '${pkg.name}' must have a valid services module (typically 'services.ts' or 'services.js').\nThe entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`);
444
+ const importName = options.importServiceClass(pkg.name + "_" + service.serviceName, service.serviceName, pkg.servicesModulePath);
445
+ const serviceObject = SERVICE_OBJECT({
446
+ SERVICE_NAME: nodes.stringLiteral(service.serviceName),
447
+ SERVICE_IMPORT: nodes.identifier(importName),
448
+ SERVICE_INTERFACES: nodes.arrayExpression(service.provides.map((p) => INTERFACE_OBJECT({
449
+ INTERFACE_NAME: nodes.stringLiteral(p.interfaceName),
450
+ QUALIFIER: p.qualifier == null ? undefinedNode() : nodes.stringLiteral(p.qualifier)
451
+ }))),
452
+ SERVICE_REFERENCES: nodes.objectExpression(Array.from(service.references.entries()).map(([referenceName, referenceConfig]) => nodes.objectProperty(nodes.stringLiteral(referenceName), referenceObject(referenceConfig))))
453
+ });
454
+ servicesObject.properties.push(nodes.objectProperty(nodes.stringLiteral(service.serviceName), serviceObject));
455
+ }
456
+ const uiObject = UI_OBJECT({ UI_REFERENCES: nodes.arrayExpression(pkg.config.uiReferences.map((r) => referenceObject(r))) });
457
+ const propertiesObject = nodes.objectExpression(Array.from(pkg.config.properties.values()).map((prop) => nodes.objectProperty(nodes.stringLiteral(prop.propertyName), PROPERTY_OBJECT({
458
+ VALUE: jsonToExpression(prop.defaultValue),
459
+ REQUIRED: nodes.booleanLiteral(prop.required)
460
+ }))));
461
+ return PKG_OBJECT({
462
+ PACKAGE_NAME: nodes.stringLiteral(pkg.name),
463
+ PACKAGE_SERVICES: servicesObject,
464
+ PACKAGE_UI: uiObject,
465
+ PROPERTIES: propertiesObject
466
+ });
512
467
  }
513
468
  function jsonToExpression(json) {
514
- if (json == null) {
515
- return nodes.nullLiteral();
516
- }
517
- if (typeof json === "string") {
518
- return nodes.stringLiteral(json);
519
- }
520
- if (typeof json === "number") {
521
- return nodes.numericLiteral(json);
522
- }
523
- if (typeof json === "boolean") {
524
- return nodes.booleanLiteral(json);
525
- }
526
- if (Array.isArray(json)) {
527
- return nodes.arrayExpression(json.map((item) => jsonToExpression(item)));
528
- }
529
- if (typeof json === "object") {
530
- return nodes.objectExpression(
531
- Object.entries(json).map(
532
- ([name, value]) => nodes.objectProperty(nodes.stringLiteral(name), jsonToExpression(value))
533
- )
534
- );
535
- }
536
- throw new Error(`Unexpected value while serializing JSON: ${json}.`);
469
+ if (json == null) return nodes.nullLiteral();
470
+ if (typeof json === "string") return nodes.stringLiteral(json);
471
+ if (typeof json === "number") return nodes.numericLiteral(json);
472
+ if (typeof json === "boolean") return nodes.booleanLiteral(json);
473
+ if (Array.isArray(json)) return nodes.arrayExpression(json.map((item) => jsonToExpression(item)));
474
+ if (typeof json === "object") return nodes.objectExpression(Object.entries(json).map(([name, value]) => nodes.objectProperty(nodes.stringLiteral(name), jsonToExpression(value))));
475
+ throw new Error(`Unexpected value while serializing JSON: ${json}.`);
537
476
  }
538
477
  function referenceObject(ref) {
539
- return REFERENCE_OBJECT({
540
- INTERFACE_NAME: nodes.stringLiteral(ref.interfaceName),
541
- QUALIFIER: ref.qualifier ? nodes.stringLiteral(ref.qualifier) : undefinedNode(),
542
- ALL: nodes.booleanLiteral(ref.type === "all" ? true : false)
543
- // TODO: Rework internal app format
544
- });
478
+ return REFERENCE_OBJECT({
479
+ INTERFACE_NAME: nodes.stringLiteral(ref.interfaceName),
480
+ QUALIFIER: ref.qualifier ? nodes.stringLiteral(ref.qualifier) : undefinedNode(),
481
+ ALL: nodes.booleanLiteral(ref.type === "all" ? true : false)
482
+ });
545
483
  }
546
484
  function undefinedNode() {
547
- return nodes.unaryExpression("void", nodes.numericLiteral(0));
485
+ return nodes.unaryExpression("void", nodes.numericLiteral(0));
548
486
  }
549
-
550
- // src/deployment/index.ts
551
- var SENTINEL_FILENAME = "__base_url_sentinel__";
487
+ //#endregion
488
+ //#region src/deployment/index.ts
489
+ const SENTINEL_FILENAME = "__base_url_sentinel__";
490
+ /**
491
+ * Provides a virtual module that returns metadata about the current deployment.
492
+ * This is the implementation of `open-pioneer:deployment`.
493
+ *
494
+ * NOTE: This works by creating a (dummy) asset file and computing the URL to it.
495
+ * There does not seem to be a more elegant way.
496
+ * See also https://github.com/vitejs/vite/discussions/21251
497
+ */
552
498
  var DeploymentModule = class {
553
- #isDev;
554
- #configuredBaseUrl;
555
- #assetId;
556
- constructor(isDev, configuredBaseUrl) {
557
- this.#isDev = isDev;
558
- this.#configuredBaseUrl = configuredBaseUrl;
559
- }
560
- onStart(ctx) {
561
- if (this.#isDev) {
562
- return;
563
- }
564
- if (this.#assetId) {
565
- throw new Error("Illegal state: onStart() was already called");
566
- }
567
- this.#assetId = ctx.emitFile({
568
- type: "asset",
569
- fileName: SENTINEL_FILENAME,
570
- source: "This file should be deleted after the build."
571
- });
572
- }
573
- onGenerateBundle(bundle) {
574
- if (!this.#isDev) {
575
- delete bundle[SENTINEL_FILENAME];
576
- }
577
- }
578
- onLoadModule() {
579
- if (this.#isDev) {
580
- let baseUrl = this.#configuredBaseUrl;
581
- if (!baseUrl || baseUrl === "./") {
582
- baseUrl = "/";
583
- }
584
- return `export const baseUrl = new URL(${JSON.stringify(baseUrl)}, window.origin).href;`;
585
- }
586
- return `
499
+ #isDev;
500
+ #configuredBaseUrl;
501
+ #assetId;
502
+ constructor(isDev, configuredBaseUrl) {
503
+ this.#isDev = isDev;
504
+ this.#configuredBaseUrl = configuredBaseUrl;
505
+ }
506
+ onStart(ctx) {
507
+ if (this.#isDev) return;
508
+ if (this.#assetId) throw new Error("Illegal state: onStart() was already called");
509
+ this.#assetId = ctx.emitFile({
510
+ type: "asset",
511
+ fileName: SENTINEL_FILENAME,
512
+ source: "This file should be deleted after the build."
513
+ });
514
+ }
515
+ onGenerateBundle(bundle) {
516
+ if (!this.#isDev) delete bundle[SENTINEL_FILENAME];
517
+ }
518
+ onLoadModule() {
519
+ if (this.#isDev) {
520
+ let baseUrl = this.#configuredBaseUrl;
521
+ if (!baseUrl || baseUrl === "./") baseUrl = "/";
522
+ return `export const baseUrl = new URL(${JSON.stringify(baseUrl)}, window.origin).href;`;
523
+ }
524
+ return `
587
525
  const assetUrl = "__VITE_ASSET__${this.#assetId}__";
588
526
  export const baseUrl = new URL("./", assetUrl).href;
589
527
  `;
590
- }
528
+ }
591
529
  };
592
-
593
- // src/metadata/Context.ts
530
+ //#endregion
531
+ //#region src/metadata/Context.ts
594
532
  function createMetadataContextFromRolldown(ctx) {
595
- return {
596
- addWatchFile: (id) => {
597
- ctx.addWatchFile(id);
598
- },
599
- resolveLocalFile: async (moduleId, _packageName, packageDirectory) => {
600
- const importer = `${packageDirectory}/package.json`;
601
- const result = await ctx.resolve(moduleId, importer, {
602
- skipSelf: true
603
- });
604
- return result == null ? void 0 : result.id;
605
- },
606
- warn: (message) => {
607
- ctx.warn(message);
608
- }
609
- };
533
+ return {
534
+ addWatchFile: (id) => {
535
+ ctx.addWatchFile(id);
536
+ },
537
+ resolveLocalFile: async (moduleId, _packageName, packageDirectory) => {
538
+ const importer = `${packageDirectory}/package.json`;
539
+ return (await ctx.resolve(moduleId, importer, { skipSelf: true }))?.id;
540
+ },
541
+ warn: (message) => {
542
+ ctx.warn(message);
543
+ }
544
+ };
610
545
  }
611
-
612
- // src/metadata/findTrailsPackages.ts
613
- import { realpath } from "fs/promises";
614
- import { dirname as dirname2, posix as posix3 } from "path";
615
- import { ResolverFactory } from "oxc-resolver";
616
- import { glob } from "tinyglobby";
617
- import { normalizePath as normalizePath3 } from "vite";
618
-
619
- // src/utils/debug.ts
620
- import pkg from "debug";
621
- var { debug } = pkg;
546
+ //#endregion
547
+ //#region src/utils/debug.ts
548
+ const { debug: debug$5 } = pkg;
622
549
  function createDebugger(namespace) {
623
- const logger = debug(namespace);
624
- return function debugFunction(...args) {
625
- logger(...args);
626
- };
550
+ const logger = debug$5(namespace);
551
+ return function debugFunction(...args) {
552
+ logger(...args);
553
+ };
627
554
  }
628
-
629
- // src/metadata/loadPackageMetadata.ts
630
- import { existsSync as existsSync2 } from "node:fs";
631
- import { readFile } from "node:fs/promises";
632
- import { join as join2 } from "node:path";
633
- import posix2 from "node:path/posix";
634
- import {
635
- BUILD_CONFIG_NAME,
636
- PackageMetadataV1,
637
- createPackageConfigFromBuildConfig,
638
- createPackageConfigFromPackageMetadata,
639
- loadBuildConfig
640
- } from "@open-pioneer/build-common";
641
- import { normalizePath as normalizePath2 } from "vite";
642
-
643
- // src/utils/fileUtils.ts
644
- import * as fs from "node:fs";
645
- import { isAbsolute, relative } from "node:path";
555
+ //#endregion
556
+ //#region src/utils/fileUtils.ts
557
+ /**
558
+ * Asynchronously checks for the existence of `file`.
559
+ */
646
560
  function fileExists(file) {
647
- return fs.promises.access(file, fs.constants.F_OK).then(() => true).catch(() => false);
561
+ return fs.promises.access(file, fs.constants.F_OK).then(() => true).catch(() => false);
648
562
  }
563
+ /**
564
+ * Returns true if `candidate` is a child of `directory`.
565
+ */
649
566
  function isInDirectory(candidate, directory) {
650
- const rel = relative(directory, candidate);
651
- const isChild = rel && !rel.startsWith("..") && !isAbsolute(rel);
652
- return !!isChild;
567
+ const rel = relative(directory, candidate);
568
+ return !!(rel && !rel.startsWith("..") && !isAbsolute(rel));
653
569
  }
654
-
655
- // src/utils/package.ts
656
- var PACKAGE_NAME = "@open-pioneer/vite-plugin-pioneer";
657
-
658
- // src/metadata/loadPackageMetadata.ts
659
- var isDebug = !!process.env.DEBUG;
660
- var debug2 = createDebugger("open-pioneer:metadata");
570
+ //#endregion
571
+ //#region src/utils/package.ts
572
+ const PACKAGE_NAME = "@open-pioneer/vite-plugin-pioneer";
573
+ //#endregion
574
+ //#region src/metadata/loadPackageMetadata.ts
575
+ const isDebug$4 = !!process.env.DEBUG;
576
+ const debug$4 = createDebugger("open-pioneer:metadata");
577
+ /**
578
+ * This function is called to read a package's metadata during build
579
+ * (for internal and external packages).
580
+ *
581
+ * Depending on the location of the package either reads build config (source package)
582
+ * or serialized metadata from package.json.
583
+ */
661
584
  async function loadPackageMetadata(ctx, packageDir, options) {
662
- return await new PackageMetadataReader(ctx, packageDir, options).readPackageMetadata();
585
+ return await new PackageMetadataReader(ctx, packageDir, options).readPackageMetadata();
663
586
  }
664
587
  var PackageMetadataReader = class {
665
- #ctx;
666
- #packageDir;
667
- #sourceRoot;
668
- #packageJsonPath;
669
- #importedFrom;
670
- #allowMissingBuildConfig;
671
- constructor(ctx, packageDir, options) {
672
- this.#ctx = ctx;
673
- this.#packageDir = packageDir;
674
- this.#sourceRoot = options.sourceRoot;
675
- this.#packageJsonPath = join2(packageDir, "package.json");
676
- this.#importedFrom = options.importedFrom;
677
- this.#allowMissingBuildConfig = (options == null ? void 0 : options.allowMissingBuildConfigInLocalPackage) ?? false;
678
- }
679
- /**
680
- * Reads package metadata for the configured package.
681
- */
682
- async readPackageMetadata() {
683
- const ctx = this.#ctx;
684
- const packageDir = this.#packageDir;
685
- const packageJsonPath = this.#packageJsonPath;
686
- const sourceRoot = this.#sourceRoot;
687
- const mode = isLocalPackage(packageDir, sourceRoot) ? "local" : "external";
688
- isDebug && debug2(`Visiting package directory ${packageDir} in mode ${mode}.`);
689
- ctx.addWatchFile(packageJsonPath);
690
- const {
691
- name: packageName,
692
- version: packageVersion,
693
- dependencies,
694
- frameworkMetadata
695
- } = await parsePackageJson(packageJsonPath);
696
- const configResult = await this.#readConfig(mode, packageName, frameworkMetadata);
697
- if (!configResult) {
698
- return {
699
- type: "plain",
700
- name: packageName,
701
- version: packageVersion,
702
- directory: packageDir
703
- };
704
- }
705
- const { config, configPath } = configResult;
706
- let servicesModuleId;
707
- let servicesModulePath;
708
- if (config.services.size) {
709
- const localModuleId = config.servicesModule ?? "./services";
710
- servicesModuleId = posix2.join(packageName, localModuleId);
711
- try {
712
- servicesModulePath = await this.#resolveServicesModule(
713
- mode,
714
- packageName,
715
- localModuleId
716
- );
717
- } catch (e) {
718
- throw new ReportableError(
719
- `Failed to resolve services entry point for package ${packageDir}`,
720
- { cause: e }
721
- );
722
- }
723
- }
724
- let cssFile;
725
- if (config.styles) {
726
- try {
727
- cssFile = await resolveLocalFile(ctx, packageDir, packageName, config.styles);
728
- } catch (e) {
729
- throw new ReportableError(`Failed to resolve css file for package ${packageDir}`, {
730
- cause: e
731
- });
732
- }
733
- if (!cssFile) {
734
- throw new ReportableError(
735
- `Failed to find css file '${config.styles}' in ${packageDir}`
736
- );
737
- }
738
- }
739
- const i18nPaths = /* @__PURE__ */ new Map();
740
- for (const locale of config.languages) {
741
- if (i18nPaths.has(locale)) {
742
- throw new ReportableError(`Locale '${locale}' was defined twice in ${configPath}`);
743
- }
744
- const path = join2(packageDir, "i18n", `${locale}.yaml`);
745
- i18nPaths.set(locale, normalizePath2(path));
746
- }
747
- return {
748
- type: "pioneer-package",
749
- name: packageName,
750
- version: packageVersion,
751
- directory: packageDir,
752
- packageJsonPath,
753
- servicesModuleId,
754
- servicesModulePath,
755
- cssFilePath: cssFile,
756
- i18nPaths,
757
- get locales() {
758
- return Array.from(i18nPaths.keys());
759
- },
760
- dependencies,
761
- config
762
- };
763
- }
764
- /**
765
- * Attempts to read the package's metadata/configuration, depending on mode.
766
- */
767
- async #readConfig(mode, packageName, frameworkMetadata) {
768
- const ctx = this.#ctx;
769
- const packageDir = this.#packageDir;
770
- switch (mode) {
771
- /** External packages must have framework metadata in their package.json (or they are not considered Open Pioneer Trails packages at all). */
772
- case "external": {
773
- if (!frameworkMetadata) {
774
- return void 0;
775
- }
776
- return this.#parsePackageConfigFromMetadata(packageName, frameworkMetadata);
777
- }
778
- /** Local packages may have either a build.config (the common case) or a built package.json for testing, but never both. */
779
- case "local": {
780
- const buildConfigPath = join2(packageDir, BUILD_CONFIG_NAME);
781
- const buildConfigExists = existsSync2(buildConfigPath);
782
- if (buildConfigExists && frameworkMetadata) {
783
- throw new Error(
784
- `Package '${packageName}' at ${packageDir} contains both framework metadata in its package.json and a ${BUILD_CONFIG_NAME}. Mixing both formats is not supported. Metadata in package.json files is only intended for distributed packages.`
785
- );
786
- }
787
- if (frameworkMetadata) {
788
- ctx.warn(
789
- `Using framework metadata from package.json instead of ${BUILD_CONFIG_NAME} in ${packageDir}, make sure that this intended.`
790
- );
791
- return this.#parsePackageConfigFromMetadata(packageName, frameworkMetadata);
792
- }
793
- return this.#parsePackageConfigFromBuildConfig(buildConfigPath);
794
- }
795
- }
796
- }
797
- /**
798
- * Attempts to resolve the package's services entry point (e.g. ./services.ts), depending on mode.
799
- */
800
- async #resolveServicesModule(mode, packageName, moduleId) {
801
- const importedFrom = this.#importedFrom;
802
- if (mode === "external" && importedFrom) {
803
- return posix2.join(packageName, moduleId);
804
- } else {
805
- return await resolveLocalFile(this.#ctx, this.#packageDir, packageName, moduleId);
806
- }
807
- }
808
- /**
809
- * Attempts to read the package configuration from the package.json's metadata value.
810
- * Note that the value may not be present at this point if the package does not use Open Pioneer Trails metadata.
811
- */
812
- async #parsePackageConfigFromMetadata(packageName, frameworkMetadata) {
813
- const packageDir = this.#packageDir;
814
- const packageJsonPath = this.#packageJsonPath;
815
- const metadataResult = PackageMetadataV1.parsePackageMetadata(frameworkMetadata);
816
- if (metadataResult.type === "error") {
817
- if (metadataResult.code === "unsupported-version") {
818
- throw new ReportableError(
819
- `Package '${packageName}' in ${packageDir} uses an unsupported package metadata version. The latest version supported by this plugin is ${PackageMetadataV1.LATEST_VERSION}. Try updating ${PACKAGE_NAME}.
820
-
821
- ` + metadataResult.message,
822
- { cause: metadataResult.cause }
823
- );
824
- }
825
- throw new ReportableError(
826
- `Failed to parse metadata of package '${packageName}' in ${packageDir}: ${metadataResult.message}`,
827
- { cause: metadataResult.cause }
828
- );
829
- }
830
- return {
831
- configPath: packageJsonPath,
832
- config: createPackageConfigFromPackageMetadata(metadataResult.value)
833
- };
834
- }
835
- async #parsePackageConfigFromBuildConfig(buildConfigPath) {
836
- const ctx = this.#ctx;
837
- const packageDir = this.#packageDir;
838
- let buildConfig;
839
- ctx.addWatchFile(normalizePath2(buildConfigPath));
840
- if (await fileExists(buildConfigPath)) {
841
- ctx.addWatchFile(normalizePath2(buildConfigPath));
842
- try {
843
- buildConfig = await loadBuildConfig(buildConfigPath);
844
- } catch (e) {
845
- const cause = e instanceof Error ? e.cause : String(e);
846
- throw new ReportableError(
847
- `Failed to load build config ${buildConfigPath}. ${cause}`,
848
- {
849
- cause: e
850
- }
851
- );
852
- }
853
- } else if (!this.#allowMissingBuildConfig) {
854
- throw new ReportableError(`Expected a ${BUILD_CONFIG_NAME} in ${packageDir}`);
855
- } else {
856
- return void 0;
857
- }
858
- return {
859
- configPath: buildConfigPath,
860
- config: createPackageConfigFromBuildConfig(buildConfig)
861
- };
862
- }
588
+ #ctx;
589
+ #packageDir;
590
+ #sourceRoot;
591
+ #packageJsonPath;
592
+ #importedFrom;
593
+ #allowMissingBuildConfig;
594
+ constructor(ctx, packageDir, options) {
595
+ this.#ctx = ctx;
596
+ this.#packageDir = packageDir;
597
+ this.#sourceRoot = options.sourceRoot;
598
+ this.#packageJsonPath = join(packageDir, "package.json");
599
+ this.#importedFrom = options.importedFrom;
600
+ this.#allowMissingBuildConfig = options?.allowMissingBuildConfigInLocalPackage ?? false;
601
+ }
602
+ /**
603
+ * Reads package metadata for the configured package.
604
+ */
605
+ async readPackageMetadata() {
606
+ const ctx = this.#ctx;
607
+ const packageDir = this.#packageDir;
608
+ const packageJsonPath = this.#packageJsonPath;
609
+ const sourceRoot = this.#sourceRoot;
610
+ const mode = isLocalPackage(packageDir, sourceRoot) ? "local" : "external";
611
+ isDebug$4 && debug$4(`Visiting package directory ${packageDir} in mode ${mode}.`);
612
+ ctx.addWatchFile(packageJsonPath);
613
+ const { name: packageName, version: packageVersion, dependencies, frameworkMetadata } = await parsePackageJson(packageJsonPath);
614
+ const configResult = await this.#readConfig(mode, packageName, frameworkMetadata);
615
+ if (!configResult) return {
616
+ type: "plain",
617
+ name: packageName,
618
+ version: packageVersion,
619
+ directory: packageDir
620
+ };
621
+ const { config, configPath } = configResult;
622
+ let servicesModuleId;
623
+ let servicesModulePath;
624
+ if (config.services.size) {
625
+ const localModuleId = config.servicesModule ?? "./services";
626
+ servicesModuleId = posix$1.join(packageName, localModuleId);
627
+ try {
628
+ servicesModulePath = await this.#resolveServicesModule(mode, packageName, localModuleId);
629
+ } catch (e) {
630
+ throw new ReportableError(`Failed to resolve services entry point for package ${packageDir}`, { cause: e });
631
+ }
632
+ }
633
+ let cssFile;
634
+ if (config.styles) {
635
+ try {
636
+ cssFile = await resolveLocalFile(ctx, packageDir, packageName, config.styles);
637
+ } catch (e) {
638
+ throw new ReportableError(`Failed to resolve css file for package ${packageDir}`, { cause: e });
639
+ }
640
+ if (!cssFile) throw new ReportableError(`Failed to find css file '${config.styles}' in ${packageDir}`);
641
+ }
642
+ const i18nPaths = /* @__PURE__ */ new Map();
643
+ for (const locale of config.languages) {
644
+ if (i18nPaths.has(locale)) throw new ReportableError(`Locale '${locale}' was defined twice in ${configPath}`);
645
+ const path = join(packageDir, "i18n", `${locale}.yaml`);
646
+ i18nPaths.set(locale, normalizePath(path));
647
+ }
648
+ return {
649
+ type: "pioneer-package",
650
+ name: packageName,
651
+ version: packageVersion,
652
+ directory: packageDir,
653
+ packageJsonPath,
654
+ servicesModuleId,
655
+ servicesModulePath,
656
+ cssFilePath: cssFile,
657
+ i18nPaths,
658
+ get locales() {
659
+ return Array.from(i18nPaths.keys());
660
+ },
661
+ dependencies,
662
+ config
663
+ };
664
+ }
665
+ /**
666
+ * Attempts to read the package's metadata/configuration, depending on mode.
667
+ */
668
+ async #readConfig(mode, packageName, frameworkMetadata) {
669
+ const ctx = this.#ctx;
670
+ const packageDir = this.#packageDir;
671
+ switch (mode) {
672
+ /** External packages must have framework metadata in their package.json (or they are not considered Open Pioneer Trails packages at all). */
673
+ case "external":
674
+ if (!frameworkMetadata) return;
675
+ return this.#parsePackageConfigFromMetadata(packageName, frameworkMetadata);
676
+ /** Local packages may have either a build.config (the common case) or a built package.json for testing, but never both. */
677
+ case "local": {
678
+ const buildConfigPath = join(packageDir, BUILD_CONFIG_NAME);
679
+ if (existsSync$1(buildConfigPath) && frameworkMetadata) throw new Error(`Package '${packageName}' at ${packageDir} contains both framework metadata in its package.json and a ${BUILD_CONFIG_NAME}. Mixing both formats is not supported. Metadata in package.json files is only intended for distributed packages.`);
680
+ if (frameworkMetadata) {
681
+ ctx.warn(`Using framework metadata from package.json instead of ${BUILD_CONFIG_NAME} in ${packageDir}, make sure that this intended.`);
682
+ return this.#parsePackageConfigFromMetadata(packageName, frameworkMetadata);
683
+ }
684
+ return this.#parsePackageConfigFromBuildConfig(buildConfigPath);
685
+ }
686
+ }
687
+ }
688
+ /**
689
+ * Attempts to resolve the package's services entry point (e.g. ./services.ts), depending on mode.
690
+ */
691
+ async #resolveServicesModule(mode, packageName, moduleId) {
692
+ const importedFrom = this.#importedFrom;
693
+ if (mode === "external" && importedFrom)
694
+ /**
695
+ * FIXME: This is a workaround for a weird interaction with vite's dependency optimizer and virtual modules.
696
+ * We are trying to import a real file here (e.g. ./node_modules/.../@open-pioneer/some-package/services.js)
697
+ * and we would like to do so via a fully resolved path.
698
+ *
699
+ * However, when using a fully resolved path AND using vite's dev mode AND if that code used by that file
700
+ * is already used elsewhere in the app (and thus optimized) we end up with a "working" import that produces duplicate code
701
+ * (one copy from vite's optimizer in node_modules/.vite and one copy via the direct fully resolved path).
702
+ *
703
+ * By using an unresolved path we bypass this issue as it appears that vite's resolve pipeline handles this correctly -
704
+ * there is no duplicate code in manual experiments.
705
+ *
706
+ * Because this is an unresolved import (e.g. @open-pioneer/some-package/services) from the app's virtual packages module
707
+ * this package must be reachable from the app. For this reason we currently must use pnpm's "shamefully-hoist" option :(
708
+ */
709
+ return posix$1.join(packageName, moduleId);
710
+ else return await resolveLocalFile(this.#ctx, this.#packageDir, packageName, moduleId);
711
+ }
712
+ /**
713
+ * Attempts to read the package configuration from the package.json's metadata value.
714
+ * Note that the value may not be present at this point if the package does not use Open Pioneer Trails metadata.
715
+ */
716
+ async #parsePackageConfigFromMetadata(packageName, frameworkMetadata) {
717
+ const packageDir = this.#packageDir;
718
+ const packageJsonPath = this.#packageJsonPath;
719
+ const metadataResult = PackageMetadataV1.parsePackageMetadata(frameworkMetadata);
720
+ if (metadataResult.type === "error") {
721
+ if (metadataResult.code === "unsupported-version") throw new ReportableError(`Package '${packageName}' in ${packageDir} uses an unsupported package metadata version. The latest version supported by this plugin is ${PackageMetadataV1.LATEST_VERSION}. Try updating ${PACKAGE_NAME}.\n\n` + metadataResult.message, { cause: metadataResult.cause });
722
+ throw new ReportableError(`Failed to parse metadata of package '${packageName}' in ${packageDir}: ${metadataResult.message}`, { cause: metadataResult.cause });
723
+ }
724
+ return {
725
+ configPath: packageJsonPath,
726
+ config: createPackageConfigFromPackageMetadata(metadataResult.value)
727
+ };
728
+ }
729
+ async #parsePackageConfigFromBuildConfig(buildConfigPath) {
730
+ const ctx = this.#ctx;
731
+ const packageDir = this.#packageDir;
732
+ let buildConfig;
733
+ ctx.addWatchFile(normalizePath(buildConfigPath));
734
+ if (await fileExists(buildConfigPath)) {
735
+ ctx.addWatchFile(normalizePath(buildConfigPath));
736
+ try {
737
+ buildConfig = await loadBuildConfig(buildConfigPath);
738
+ } catch (e) {
739
+ throw new ReportableError(`Failed to load build config ${buildConfigPath}. ${e instanceof Error ? e.cause : String(e)}`, { cause: e });
740
+ }
741
+ } else if (!this.#allowMissingBuildConfig) throw new ReportableError(`Expected a ${BUILD_CONFIG_NAME} in ${packageDir}`);
742
+ else return;
743
+ return {
744
+ configPath: buildConfigPath,
745
+ config: createPackageConfigFromBuildConfig(buildConfig)
746
+ };
747
+ }
863
748
  };
864
749
  async function parsePackageJson(packageJsonPath) {
865
- var _a, _b;
866
- if (!await fileExists(packageJsonPath)) {
867
- throw new ReportableError(`Expected a 'package.json' file at ${packageJsonPath}`);
868
- }
869
- let packageJsonContent;
870
- try {
871
- packageJsonContent = JSON.parse(await readFile(packageJsonPath, "utf-8"));
872
- } catch (e) {
873
- throw new ReportableError(`Failed to read ${packageJsonPath}`, { cause: e });
874
- }
875
- const packageName = packageJsonContent.name;
876
- if (typeof packageName !== "string") {
877
- throw new ReportableError(`Expected 'name' to be a string in ${packageJsonPath}`);
878
- }
879
- const version = packageJsonContent.version;
880
- if (version != null && typeof version !== "string") {
881
- throw new ReportableError(`Expected 'version' to be a string in ${packageJsonPath}`);
882
- }
883
- const dependencies = packageJsonContent.dependencies ?? {};
884
- if (typeof dependencies !== "object") {
885
- throw new ReportableError(`Expected a valid 'dependencies' object in ${packageJsonPath}`);
886
- }
887
- const peerDependencies = packageJsonContent.peerDependencies ?? {};
888
- if (typeof peerDependencies !== "object") {
889
- throw new ReportableError(
890
- `Expected a valid 'peerDependencies' object in ${packageJsonPath}`
891
- );
892
- }
893
- const optionalDependencies = packageJsonContent.optionalDependencies ?? {};
894
- if (typeof optionalDependencies !== "object") {
895
- throw new ReportableError(
896
- `Expected a valid 'optionalDependencies' object in ${packageJsonPath}`
897
- );
898
- }
899
- const deps = /* @__PURE__ */ new Map();
900
- const addDep = (packageName2, optional) => {
901
- let dep = deps.get(packageName2);
902
- if (!dep) {
903
- dep = {
904
- packageName: packageName2,
905
- optional
906
- };
907
- deps.set(packageName2, dep);
908
- } else {
909
- dep.optional &&= optional;
910
- }
911
- };
912
- for (const depName of Object.keys(dependencies)) {
913
- addDep(depName, false);
914
- }
915
- for (const depName of Object.keys(peerDependencies)) {
916
- addDep(depName, ((_b = (_a = packageJsonContent == null ? void 0 : packageJsonContent.peerDependenciesMeta) == null ? void 0 : _a[depName]) == null ? void 0 : _b.optional) ?? false);
917
- }
918
- for (const depName of Object.keys(optionalDependencies)) {
919
- addDep(depName, true);
920
- }
921
- const frameworkMetadata = packageJsonContent[PackageMetadataV1.PACKAGE_JSON_KEY] ?? void 0;
922
- return {
923
- name: packageName,
924
- version: version ?? void 0,
925
- dependencies: Array.from(deps.values()),
926
- frameworkMetadata
927
- };
750
+ if (!await fileExists(packageJsonPath)) throw new ReportableError(`Expected a 'package.json' file at ${packageJsonPath}`);
751
+ let packageJsonContent;
752
+ try {
753
+ packageJsonContent = JSON.parse(await readFile(packageJsonPath, "utf-8"));
754
+ } catch (e) {
755
+ throw new ReportableError(`Failed to read ${packageJsonPath}`, { cause: e });
756
+ }
757
+ const packageName = packageJsonContent.name;
758
+ if (typeof packageName !== "string") throw new ReportableError(`Expected 'name' to be a string in ${packageJsonPath}`);
759
+ const version = packageJsonContent.version;
760
+ if (version != null && typeof version !== "string") throw new ReportableError(`Expected 'version' to be a string in ${packageJsonPath}`);
761
+ const dependencies = packageJsonContent.dependencies ?? {};
762
+ if (typeof dependencies !== "object") throw new ReportableError(`Expected a valid 'dependencies' object in ${packageJsonPath}`);
763
+ const peerDependencies = packageJsonContent.peerDependencies ?? {};
764
+ if (typeof peerDependencies !== "object") throw new ReportableError(`Expected a valid 'peerDependencies' object in ${packageJsonPath}`);
765
+ const optionalDependencies = packageJsonContent.optionalDependencies ?? {};
766
+ if (typeof optionalDependencies !== "object") throw new ReportableError(`Expected a valid 'optionalDependencies' object in ${packageJsonPath}`);
767
+ const deps = /* @__PURE__ */ new Map();
768
+ const addDep = (packageName, optional) => {
769
+ let dep = deps.get(packageName);
770
+ if (!dep) {
771
+ dep = {
772
+ packageName,
773
+ optional
774
+ };
775
+ deps.set(packageName, dep);
776
+ } else dep.optional &&= optional;
777
+ };
778
+ for (const depName of Object.keys(dependencies)) addDep(depName, false);
779
+ for (const depName of Object.keys(peerDependencies)) addDep(depName, packageJsonContent?.peerDependenciesMeta?.[depName]?.optional ?? false);
780
+ for (const depName of Object.keys(optionalDependencies)) addDep(depName, true);
781
+ const frameworkMetadata = packageJsonContent[PackageMetadataV1.PACKAGE_JSON_KEY] ?? void 0;
782
+ return {
783
+ name: packageName,
784
+ version: version ?? void 0,
785
+ dependencies: Array.from(deps.values()),
786
+ frameworkMetadata
787
+ };
928
788
  }
929
789
  async function resolveLocalFile(ctx, packageDir, packageName, localModuleId) {
930
- if (!localModuleId.startsWith("./")) {
931
- localModuleId = `./${localModuleId}`;
932
- }
933
- return await ctx.resolveLocalFile(localModuleId, packageName, packageDir);
790
+ if (!localModuleId.startsWith("./")) localModuleId = `./${localModuleId}`;
791
+ return await ctx.resolveLocalFile(localModuleId, packageName, packageDir);
934
792
  }
935
- var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
793
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
936
794
  function isLocalPackage(file, sourceDir) {
937
- return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);
795
+ return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);
938
796
  }
939
-
940
- // src/metadata/findTrailsPackages.ts
941
- var isDebug2 = !!process.env.DEBUG;
942
- var debug3 = createDebugger("open-pioneer:metadata");
797
+ //#endregion
798
+ //#region src/metadata/findTrailsPackages.ts
799
+ const isDebug$3 = !!process.env.DEBUG;
800
+ const debug$3 = createDebugger("open-pioneer:metadata");
943
801
  async function findTrailsPackages(sourceRoot) {
944
- const ctx = createDummyContext();
945
- const packageResolver = ResolverFactory.default();
946
- const localPackageJsonFiles = await glob("**/package.json", {
947
- cwd: sourceRoot,
948
- absolute: true,
949
- ignore: ["**/node_modules/**"]
950
- });
951
- const seen = /* @__PURE__ */ new Set();
952
- const workQueue = [];
953
- const visit = (packageDirectory) => {
954
- const normalizedPath = normalizePath3(packageDirectory);
955
- if (seen.has(normalizedPath)) {
956
- return;
957
- }
958
- seen.add(normalizedPath);
959
- workQueue.push(normalizedPath);
960
- };
961
- for (const file of localPackageJsonFiles) {
962
- visit(dirname2(file));
963
- }
964
- const trailsPackages = [];
965
- while (workQueue.length) {
966
- const packageDirectory = workQueue.pop();
967
- const pkg2 = await loadPackageMetadata(ctx, packageDirectory, {
968
- sourceRoot,
969
- importedFrom: void 0,
970
- allowMissingBuildConfigInLocalPackage: true
971
- });
972
- if (pkg2.type === "plain") {
973
- continue;
974
- }
975
- trailsPackages.push(pkg2);
976
- for (const dependency of pkg2.dependencies) {
977
- const depResult = await packageResolver.async(
978
- packageDirectory,
979
- dependency.packageName + "/package.json"
980
- );
981
- if (depResult.path) {
982
- const depPath = await realpath(dirname2(depResult.path));
983
- visit(depPath);
984
- }
985
- }
986
- }
987
- trailsPackages.sort((p1, p2) => p1.name.localeCompare(p2.name, "en"));
988
- return trailsPackages;
802
+ const ctx = createDummyContext();
803
+ const packageResolver = ResolverFactory.default();
804
+ const localPackageJsonFiles = await glob("**/package.json", {
805
+ cwd: sourceRoot,
806
+ absolute: true,
807
+ ignore: ["**/node_modules/**"]
808
+ });
809
+ const seen = /* @__PURE__ */ new Set();
810
+ const workQueue = [];
811
+ const visit = (packageDirectory) => {
812
+ const normalizedPath = normalizePath(packageDirectory);
813
+ if (seen.has(normalizedPath)) return;
814
+ seen.add(normalizedPath);
815
+ workQueue.push(normalizedPath);
816
+ };
817
+ for (const file of localPackageJsonFiles) visit(dirname$2(file));
818
+ const trailsPackages = [];
819
+ while (workQueue.length) {
820
+ const packageDirectory = workQueue.pop();
821
+ const pkg = await loadPackageMetadata(ctx, packageDirectory, {
822
+ sourceRoot,
823
+ importedFrom: void 0,
824
+ allowMissingBuildConfigInLocalPackage: true
825
+ });
826
+ if (pkg.type === "plain") continue;
827
+ trailsPackages.push(pkg);
828
+ for (const dependency of pkg.dependencies) {
829
+ const depResult = await packageResolver.async(packageDirectory, dependency.packageName + "/package.json");
830
+ if (depResult.path) visit(await realpath(dirname$2(depResult.path)));
831
+ }
832
+ }
833
+ trailsPackages.sort((p1, p2) => p1.name.localeCompare(p2.name, "en"));
834
+ return trailsPackages;
989
835
  }
990
836
  function createDummyContext() {
991
- return {
992
- addWatchFile(_file) {
993
- },
994
- async resolveLocalFile(moduleId, _packageDir, packageName) {
995
- return posix3.join(packageName, moduleId);
996
- },
997
- warn(message) {
998
- isDebug2 && debug3("Problem during trails package discovery: %s", message);
999
- }
1000
- };
837
+ return {
838
+ addWatchFile(_file) {},
839
+ async resolveLocalFile(moduleId, _packageDir, packageName) {
840
+ return posix$3.join(packageName, moduleId);
841
+ },
842
+ warn(message) {
843
+ isDebug$3 && debug$3("Problem during trails package discovery: %s", message);
844
+ }
845
+ };
1001
846
  }
1002
-
1003
- // src/metadata/MetadataRepository.ts
1004
- import { realpath as realpath2 } from "fs/promises";
1005
- import { basename as basename2, dirname as dirname3 } from "path";
1006
- import { BUILD_CONFIG_NAME as BUILD_CONFIG_NAME2, RuntimeSupport as RuntimeSupport2 } from "@open-pioneer/build-common";
1007
- import { normalizePath as normalizePath4 } from "vite";
1008
- import { findDepPkgJsonPath } from "vitefu";
1009
-
1010
- // src/utils/Cache.ts
847
+ //#endregion
848
+ //#region src/utils/Cache.ts
849
+ /**
850
+ * A simple cache implementing read-through semantics.
851
+ *
852
+ * The {@link CacheProvider} passed to the cache's constructor
853
+ * implements the actual computation of values.
854
+ *
855
+ * The cache deduplicates computations and caches their results
856
+ * until they are invalidated.
857
+ */
1011
858
  var Cache = class {
1012
- #values = /* @__PURE__ */ new Map();
1013
- #jobs = /* @__PURE__ */ new Map();
1014
- #provider;
1015
- constructor(provider) {
1016
- this.#provider = provider;
1017
- }
1018
- /**
1019
- * Removes an entry associated with the given key.
1020
- */
1021
- invalidate(key) {
1022
- var _a, _b;
1023
- const id = this.#provider.getId(key);
1024
- const oldValue = this.#values.get(id);
1025
- this.#values.delete(id);
1026
- this.#jobs.delete(id);
1027
- if (oldValue) {
1028
- (_b = (_a = this.#provider).onInvalidate) == null ? void 0 : _b.call(_a, key, oldValue);
1029
- }
1030
- }
1031
- /**
1032
- * Retrieves the value associated with `key`.
1033
- * A cached result will be used if present, otherwise the
1034
- * cache provider will be called.
1035
- *
1036
- * Note: computations may throw errors.
1037
- * Errors will not be cached.
1038
- *
1039
- * @param key the lookup key
1040
- * @param context an arbitrary set of values that will be forwarded to the provider
1041
- * should be provider be called.
1042
- * @returns the value associated with `key`
1043
- */
1044
- async get(key, ...context) {
1045
- var _a;
1046
- const provider = this.#provider;
1047
- const id = provider.getId(key);
1048
- const values = this.#values;
1049
- const existingValue = values.get(id);
1050
- if (existingValue) {
1051
- (_a = provider.onCachedReturn) == null ? void 0 : _a.call(provider, key, existingValue);
1052
- return Promise.resolve(existingValue);
1053
- }
1054
- const jobs = this.#jobs;
1055
- const existingJob = jobs.get(id);
1056
- if (existingJob) {
1057
- return existingJob;
1058
- }
1059
- const job = provider.getValue(key, ...context);
1060
- jobs.set(id, job);
1061
- try {
1062
- const value = await job;
1063
- if (jobs.get(id) === job) {
1064
- values.set(id, value);
1065
- }
1066
- return value;
1067
- } finally {
1068
- if (jobs.get(id) === job) {
1069
- jobs.delete(id);
1070
- }
1071
- }
1072
- }
859
+ #values = /* @__PURE__ */ new Map();
860
+ #jobs = /* @__PURE__ */ new Map();
861
+ #provider;
862
+ constructor(provider) {
863
+ this.#provider = provider;
864
+ }
865
+ /**
866
+ * Removes an entry associated with the given key.
867
+ */
868
+ invalidate(key) {
869
+ const id = this.#provider.getId(key);
870
+ const oldValue = this.#values.get(id);
871
+ this.#values.delete(id);
872
+ this.#jobs.delete(id);
873
+ if (oldValue) this.#provider.onInvalidate?.(key, oldValue);
874
+ }
875
+ /**
876
+ * Retrieves the value associated with `key`.
877
+ * A cached result will be used if present, otherwise the
878
+ * cache provider will be called.
879
+ *
880
+ * Note: computations may throw errors.
881
+ * Errors will not be cached.
882
+ *
883
+ * @param key the lookup key
884
+ * @param context an arbitrary set of values that will be forwarded to the provider
885
+ * should be provider be called.
886
+ * @returns the value associated with `key`
887
+ */
888
+ async get(key, ...context) {
889
+ const provider = this.#provider;
890
+ const id = provider.getId(key);
891
+ const values = this.#values;
892
+ const existingValue = values.get(id);
893
+ if (existingValue) {
894
+ provider.onCachedReturn?.(key, existingValue);
895
+ return Promise.resolve(existingValue);
896
+ }
897
+ const jobs = this.#jobs;
898
+ const existingJob = jobs.get(id);
899
+ if (existingJob) return existingJob;
900
+ const job = provider.getValue(key, ...context);
901
+ jobs.set(id, job);
902
+ try {
903
+ const value = await job;
904
+ if (jobs.get(id) === job) values.set(id, value);
905
+ return value;
906
+ } finally {
907
+ if (jobs.get(id) === job) jobs.delete(id);
908
+ }
909
+ }
1073
910
  };
1074
-
1075
- // src/metadata/parseI18nYaml.ts
1076
- import { readFile as readFile2 } from "fs/promises";
1077
- import { load as loadYaml } from "js-yaml";
1078
- import { z } from "zod";
1079
- import { createErrorMap, fromZodError } from "zod-validation-error";
1080
- var MESSAGES_SCHEMA = z.lazy(
1081
- () => z.record(
1082
- z.string(),
1083
- z.union([z.string(), MESSAGES_SCHEMA], {
1084
- error: "String or a nested record of messages"
1085
- })
1086
- ).nullish()
1087
- );
1088
- var I18N_SCHEMA = z.strictObject({
1089
- messages: MESSAGES_SCHEMA.nullish().optional(),
1090
- overrides: z.record(z.string(), MESSAGES_SCHEMA).nullish().optional()
911
+ //#endregion
912
+ //#region src/metadata/parseI18nYaml.ts
913
+ const MESSAGES_SCHEMA = z.lazy(() => z.record(z.string(), z.union([z.string(), MESSAGES_SCHEMA], { error: "String or a nested record of messages" })).nullish());
914
+ const I18N_SCHEMA = z.strictObject({
915
+ messages: MESSAGES_SCHEMA.nullish().optional(),
916
+ overrides: z.record(z.string(), MESSAGES_SCHEMA).nullish().optional()
1091
917
  }).nullish();
918
+ /**
919
+ * Loads an i18n.yaml file from the file system and parses it.
920
+ */
1092
921
  async function loadI18nFile(path) {
1093
- let content;
1094
- try {
1095
- content = await readFile2(path, "utf-8");
1096
- } catch (e) {
1097
- throw new ReportableError(`Failed to read ${path}`, { cause: e });
1098
- }
1099
- try {
1100
- return parseI18nYaml(content);
1101
- } catch (e) {
1102
- throw new ReportableError(`Failed to parse ${path}`, { cause: e });
1103
- }
922
+ let content;
923
+ try {
924
+ content = await readFile$1(path, "utf-8");
925
+ } catch (e) {
926
+ throw new ReportableError(`Failed to read ${path}`, { cause: e });
927
+ }
928
+ try {
929
+ return parseI18nYaml(content);
930
+ } catch (e) {
931
+ throw new ReportableError(`Failed to parse ${path}`, { cause: e });
932
+ }
1104
933
  }
934
+ /**
935
+ * Parses an i18n yaml document.
936
+ */
1105
937
  function parseI18nYaml(yaml) {
1106
- let data = void 0;
1107
- if (yaml.trim()) {
1108
- data = loadYaml(yaml);
1109
- }
1110
- return parseI18nFile(data);
938
+ let data = void 0;
939
+ if (yaml.trim()) data = load(yaml);
940
+ return parseI18nFile(data);
1111
941
  }
1112
- var ERROR_MAP = createErrorMap();
942
+ const ERROR_MAP = createErrorMap();
943
+ /**
944
+ * Parses the JavaScript object representing an i18n file.
945
+ */
1113
946
  function parseI18nFile(data) {
1114
- const result = I18N_SCHEMA.safeParse(data, {
1115
- error: ERROR_MAP
1116
- });
1117
- if (!result.success) {
1118
- throw fromZodError(result.error);
1119
- }
1120
- const rawI18n = result.data;
1121
- const messages = gatherMessages((rawI18n == null ? void 0 : rawI18n.messages) ?? void 0);
1122
- let overrides;
1123
- if (typeof (rawI18n == null ? void 0 : rawI18n.overrides) === "object") {
1124
- overrides = gatherOverrides((rawI18n == null ? void 0 : rawI18n.overrides) ?? void 0);
1125
- }
1126
- return { messages, overrides };
947
+ const result = I18N_SCHEMA.safeParse(data, { error: ERROR_MAP });
948
+ if (!result.success) throw fromZodError(result.error);
949
+ const rawI18n = result.data;
950
+ const messages = gatherMessages(rawI18n?.messages ?? void 0);
951
+ let overrides;
952
+ if (typeof rawI18n?.overrides === "object") overrides = gatherOverrides(rawI18n?.overrides ?? void 0);
953
+ return {
954
+ messages,
955
+ overrides
956
+ };
1127
957
  }
1128
958
  function gatherMessages(data) {
1129
- const messages = /* @__PURE__ */ new Map();
1130
- const prefix = [];
1131
- const visitChildren = (record) => {
1132
- for (const [key, value] of Object.entries(record)) {
1133
- if (typeof value === "string") {
1134
- visitMessage(key, value);
1135
- } else if (value) {
1136
- prefix.push(key);
1137
- visitChildren(value);
1138
- prefix.pop();
1139
- }
1140
- }
1141
- };
1142
- const visitMessage = (key, message) => {
1143
- const id = [...prefix, key].join(".");
1144
- if (messages.has(id)) {
1145
- throw new Error(`Message '${id}' was already defined.`);
1146
- }
1147
- messages.set(id, message);
1148
- };
1149
- if (data) {
1150
- visitChildren(data);
1151
- }
1152
- return messages;
959
+ const messages = /* @__PURE__ */ new Map();
960
+ const prefix = [];
961
+ const visitChildren = (record) => {
962
+ for (const [key, value] of Object.entries(record)) if (typeof value === "string") visitMessage(key, value);
963
+ else if (value) {
964
+ prefix.push(key);
965
+ visitChildren(value);
966
+ prefix.pop();
967
+ }
968
+ };
969
+ const visitMessage = (key, message) => {
970
+ const id = [...prefix, key].join(".");
971
+ if (messages.has(id)) throw new Error(`Message '${id}' was already defined.`);
972
+ messages.set(id, message);
973
+ };
974
+ if (data) visitChildren(data);
975
+ return messages;
1153
976
  }
1154
977
  function gatherOverrides(data) {
1155
- const overrides = /* @__PURE__ */ new Map();
1156
- if (data) {
1157
- for (const [key, value] of Object.entries(data)) {
1158
- const messages = gatherMessages(value ?? void 0);
1159
- overrides.set(key, messages);
1160
- }
1161
- }
1162
- return overrides;
978
+ const overrides = /* @__PURE__ */ new Map();
979
+ if (data) for (const [key, value] of Object.entries(data)) {
980
+ const messages = gatherMessages(value ?? void 0);
981
+ overrides.set(key, messages);
982
+ }
983
+ return overrides;
1163
984
  }
1164
-
1165
- // src/metadata/MetadataRepository.ts
1166
- var isDebug3 = !!process.env.DEBUG;
1167
- var debug4 = createDebugger("open-pioneer:metadata");
985
+ //#endregion
986
+ //#region src/metadata/MetadataRepository.ts
987
+ const isDebug$2 = !!process.env.DEBUG;
988
+ const debug$2 = createDebugger("open-pioneer:metadata");
989
+ /**
990
+ * Provides metadata about apps and packages.
991
+ * Metadata is read from disk on demand and will then be cached
992
+ * until one of the file dependencies has changed.
993
+ */
1168
994
  var MetadataRepository = class {
1169
- #sourceRoot;
1170
- // Key: package directory on disk, value: existing metadata
1171
- #packageMetadataCache;
1172
- // Cache for the contents of i18n files.
1173
- // Key: path on disk.
1174
- #i18nCache;
1175
- /**
1176
- * @param sourceRoot Source folder on disk, needed to detect 'local' packages
1177
- */
1178
- constructor(sourceRoot) {
1179
- this.#sourceRoot = sourceRoot;
1180
- this.#packageMetadataCache = this.#createPackageMetadataCache();
1181
- this.#i18nCache = this.#createI18nCache();
1182
- }
1183
- reset() {
1184
- this.#packageMetadataCache = this.#createPackageMetadataCache();
1185
- this.#i18nCache = this.#createI18nCache();
1186
- }
1187
- /**
1188
- * Called by the plugin when a file has been changed.
1189
- * The cached data associated with that file (if any) will be removed.
1190
- */
1191
- onFileChanged(path) {
1192
- if (isPackageJson(path) || isBuildConfig(path)) {
1193
- this.#packageMetadataCache.invalidate(dirname3(path));
1194
- }
1195
- this.#i18nCache.invalidate(path);
1196
- }
1197
- /**
1198
- * Returns the combined application metadata of the app in `appDirectory`.
1199
- * Starting from the app's package.json, dependencies will be visited recursively.
1200
- *
1201
- * For packages that use our package extensions (services etc.), metadata will be gathered and
1202
- * will be returned here.
1203
- */
1204
- async getAppMetadata(ctx, appDirectory) {
1205
- isDebug3 && debug4(`Request for app metadata of ${appDirectory}`);
1206
- const appPackageMetadata = await this.#getPackageMetadata(ctx, {
1207
- type: "absolute",
1208
- directory: appDirectory
1209
- });
1210
- if (!appPackageMetadata) {
1211
- throw new ReportableError(
1212
- `Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid local package.`
1213
- );
1214
- }
1215
- const appLocales = Array.from(appPackageMetadata.i18nPaths.keys());
1216
- const packageMetadataByName = /* @__PURE__ */ new Map();
1217
- const packageSeenByDirectory = /* @__PURE__ */ new Set();
1218
- packageMetadataByName.set(appPackageMetadata.name, appPackageMetadata);
1219
- packageSeenByDirectory.add(appPackageMetadata.directory);
1220
- const visitDependencies = async (dependencies, importedFrom) => {
1221
- const jobs = dependencies.map(async (dependency) => {
1222
- const packageMetadata = await this.#getPackageMetadata(ctx, {
1223
- type: "unresolved",
1224
- dependency,
1225
- importedFrom
1226
- });
1227
- if (!packageMetadata) {
1228
- return;
1229
- }
1230
- if (!packageMetadataByName.has(packageMetadata.name)) {
1231
- packageMetadataByName.set(packageMetadata.name, packageMetadata);
1232
- }
1233
- if (!packageSeenByDirectory.has(packageMetadata.directory)) {
1234
- packageSeenByDirectory.add(packageMetadata.directory);
1235
- await visitDependencies(
1236
- packageMetadata.dependencies,
1237
- packageMetadata.packageJsonPath
1238
- );
1239
- } else {
1240
- isDebug3 && debug4(`Skipping already visited package at %s`, packageMetadata.directory);
1241
- }
1242
- });
1243
- return await Promise.all(jobs);
1244
- };
1245
- await visitDependencies(
1246
- appPackageMetadata.dependencies,
1247
- appPackageMetadata.packageJsonPath
1248
- );
1249
- const packages = Array.from(packageMetadataByName.values());
1250
- const runtimeMetadataVersion = detectRuntimeMetadataVersion(packages);
1251
- const appMetadata = {
1252
- name: appPackageMetadata.name,
1253
- directory: appPackageMetadata.directory,
1254
- locales: appLocales,
1255
- packageJsonPath: appPackageMetadata.packageJsonPath,
1256
- appPackage: appPackageMetadata,
1257
- packages,
1258
- runtimeMetadataVersion
1259
- };
1260
- return appMetadata;
1261
- }
1262
- /**
1263
- * Returns package metadata associated with the given package.
1264
- */
1265
- async #getPackageMetadata(ctx, loc) {
1266
- isDebug3 && debug4(`Request for package metadata of ${formatPackageLocation(loc)}`);
1267
- const packageDir = await this.#resolvePackageLocation(loc);
1268
- if (!packageDir) {
1269
- return void 0;
1270
- }
1271
- const importedFrom = loc.type === "absolute" ? void 0 : loc.importedFrom;
1272
- const entry = await this.#packageMetadataCache.get(packageDir, ctx, importedFrom);
1273
- propagateWatchFiles(entry.watchFiles, ctx);
1274
- if (entry.metadata.type === "plain") {
1275
- isDebug3 && debug4(`Skipping package '${packageDir}'.`);
1276
- return void 0;
1277
- }
1278
- return entry.metadata;
1279
- }
1280
- /**
1281
- * Returns the parsed contents of the given i18n file.
1282
- */
1283
- async getI18nFile(ctx, path) {
1284
- const { i18n, watchFiles } = await this.#i18nCache.get(path, ctx);
1285
- propagateWatchFiles(watchFiles, ctx);
1286
- return i18n;
1287
- }
1288
- async #resolvePackageLocation(loc) {
1289
- if (loc.type === "absolute") {
1290
- return await realpath2(loc.directory);
1291
- }
1292
- const { packageName, optional } = loc.dependency;
1293
- const packagePath = await findDepPkgJsonPath(packageName, loc.importedFrom);
1294
- if (!packagePath) {
1295
- if (optional) {
1296
- isDebug3 && debug4(`Optional package '${packageName}' was not found.`);
1297
- return void 0;
1298
- }
1299
- throw new ReportableError(
1300
- `Failed to find package '${packageName}' (from '${loc.importedFrom}'), is the dependency installed correctly?`
1301
- );
1302
- }
1303
- const packageDir = dirname3(await realpath2(packagePath));
1304
- isDebug3 && debug4(`Found package '${packageName}' at ${packageDir}`);
1305
- return packageDir;
1306
- }
1307
- #createI18nCache() {
1308
- return new Cache({
1309
- getId(path) {
1310
- return normalizePath4(path);
1311
- },
1312
- async getValue(path, ctx) {
1313
- isDebug3 && debug4(`Loading i18n file ${path}`);
1314
- ctx.addWatchFile(path);
1315
- const entry = {
1316
- i18n: await loadI18nFile(path),
1317
- watchFiles: /* @__PURE__ */ new Set([path])
1318
- };
1319
- return entry;
1320
- },
1321
- onInvalidate(path) {
1322
- isDebug3 && debug4(`Removed cache entry for i18n file ${path}`);
1323
- },
1324
- onCachedReturn(path) {
1325
- isDebug3 && debug4(`Returning cached entry for i18n file ${path}`);
1326
- }
1327
- });
1328
- }
1329
- #createPackageMetadataCache() {
1330
- const sourceRoot = this.#sourceRoot;
1331
- const provider = {
1332
- _byName: /* @__PURE__ */ new Map(),
1333
- getId(directory) {
1334
- return normalizePath4(directory);
1335
- },
1336
- async getValue(directory, ctx, importedFrom) {
1337
- isDebug3 && debug4(
1338
- `Loading metadata for package at ${directory} (imported from ${importedFrom ?? "N/A"})`
1339
- );
1340
- const watchFiles = /* @__PURE__ */ new Set();
1341
- const trackingCtx = {
1342
- resolveLocalFile: ctx.resolveLocalFile.bind(ctx),
1343
- addWatchFile(id) {
1344
- ctx.addWatchFile(id);
1345
- watchFiles.add(id);
1346
- },
1347
- warn: ctx.warn.bind(ctx)
1348
- };
1349
- const metadata = await loadPackageMetadata(trackingCtx, directory, {
1350
- sourceRoot,
1351
- importedFrom
1352
- });
1353
- isDebug3 && debug4(`Metadata for '${metadata.name}': %O`, metadata);
1354
- if (metadata.type === "pioneer-package") {
1355
- const existingMetadata = this._byName.get(metadata.name);
1356
- if (existingMetadata && normalizePath4(existingMetadata.directory) !== normalizePath4(metadata.directory)) {
1357
- const message = `Encountered the package '${metadata.name}' at two different locations.
1358
- Trails packages cannot be used more than once in the same application.
1359
- All packages must use a common version of '${metadata.name}'.
1360
-
1361
- 1. ${formatPackage(existingMetadata)}
1362
-
1363
- 2. ${formatPackage(metadata)}`;
1364
- throw new ReportableError(message);
1365
- }
1366
- this._byName.set(metadata.name, metadata);
1367
- }
1368
- return {
1369
- metadata,
1370
- watchFiles
1371
- };
1372
- },
1373
- onInvalidate(directory, entry) {
1374
- isDebug3 && debug4(`Removed cache entry for '${entry.metadata.name}'`);
1375
- this._byName.delete(entry.metadata.name);
1376
- },
1377
- onCachedReturn(directory, entry) {
1378
- isDebug3 && debug4(`Returning cached metadata for '${entry.metadata.name}'`);
1379
- }
1380
- };
1381
- return new Cache(provider);
1382
- }
995
+ #sourceRoot;
996
+ #packageMetadataCache;
997
+ #i18nCache;
998
+ /**
999
+ * @param sourceRoot Source folder on disk, needed to detect 'local' packages
1000
+ */
1001
+ constructor(sourceRoot) {
1002
+ this.#sourceRoot = sourceRoot;
1003
+ this.#packageMetadataCache = this.#createPackageMetadataCache();
1004
+ this.#i18nCache = this.#createI18nCache();
1005
+ }
1006
+ reset() {
1007
+ this.#packageMetadataCache = this.#createPackageMetadataCache();
1008
+ this.#i18nCache = this.#createI18nCache();
1009
+ }
1010
+ /**
1011
+ * Called by the plugin when a file has been changed.
1012
+ * The cached data associated with that file (if any) will be removed.
1013
+ */
1014
+ onFileChanged(path) {
1015
+ if (isPackageJson(path) || isBuildConfig(path)) this.#packageMetadataCache.invalidate(dirname$2(path));
1016
+ this.#i18nCache.invalidate(path);
1017
+ }
1018
+ /**
1019
+ * Returns the combined application metadata of the app in `appDirectory`.
1020
+ * Starting from the app's package.json, dependencies will be visited recursively.
1021
+ *
1022
+ * For packages that use our package extensions (services etc.), metadata will be gathered and
1023
+ * will be returned here.
1024
+ */
1025
+ async getAppMetadata(ctx, appDirectory) {
1026
+ isDebug$2 && debug$2(`Request for app metadata of ${appDirectory}`);
1027
+ const appPackageMetadata = await this.#getPackageMetadata(ctx, {
1028
+ type: "absolute",
1029
+ directory: appDirectory
1030
+ });
1031
+ if (!appPackageMetadata) throw new ReportableError(`Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid local package.`);
1032
+ const appLocales = Array.from(appPackageMetadata.i18nPaths.keys());
1033
+ const packageMetadataByName = /* @__PURE__ */ new Map();
1034
+ const packageSeenByDirectory = /* @__PURE__ */ new Set();
1035
+ packageMetadataByName.set(appPackageMetadata.name, appPackageMetadata);
1036
+ packageSeenByDirectory.add(appPackageMetadata.directory);
1037
+ const visitDependencies = async (dependencies, importedFrom) => {
1038
+ const jobs = dependencies.map(async (dependency) => {
1039
+ const packageMetadata = await this.#getPackageMetadata(ctx, {
1040
+ type: "unresolved",
1041
+ dependency,
1042
+ importedFrom
1043
+ });
1044
+ if (!packageMetadata) return;
1045
+ if (!packageMetadataByName.has(packageMetadata.name)) packageMetadataByName.set(packageMetadata.name, packageMetadata);
1046
+ if (!packageSeenByDirectory.has(packageMetadata.directory)) {
1047
+ packageSeenByDirectory.add(packageMetadata.directory);
1048
+ await visitDependencies(packageMetadata.dependencies, packageMetadata.packageJsonPath);
1049
+ } else isDebug$2 && debug$2(`Skipping already visited package at %s`, packageMetadata.directory);
1050
+ });
1051
+ return await Promise.all(jobs);
1052
+ };
1053
+ await visitDependencies(appPackageMetadata.dependencies, appPackageMetadata.packageJsonPath);
1054
+ const packages = Array.from(packageMetadataByName.values());
1055
+ const runtimeMetadataVersion = detectRuntimeMetadataVersion(packages);
1056
+ return {
1057
+ name: appPackageMetadata.name,
1058
+ directory: appPackageMetadata.directory,
1059
+ locales: appLocales,
1060
+ packageJsonPath: appPackageMetadata.packageJsonPath,
1061
+ appPackage: appPackageMetadata,
1062
+ packages,
1063
+ runtimeMetadataVersion
1064
+ };
1065
+ }
1066
+ /**
1067
+ * Returns package metadata associated with the given package.
1068
+ */
1069
+ async #getPackageMetadata(ctx, loc) {
1070
+ isDebug$2 && debug$2(`Request for package metadata of ${formatPackageLocation(loc)}`);
1071
+ const packageDir = await this.#resolvePackageLocation(loc);
1072
+ if (!packageDir) return;
1073
+ const importedFrom = loc.type === "absolute" ? void 0 : loc.importedFrom;
1074
+ const entry = await this.#packageMetadataCache.get(packageDir, ctx, importedFrom);
1075
+ propagateWatchFiles(entry.watchFiles, ctx);
1076
+ if (entry.metadata.type === "plain") {
1077
+ isDebug$2 && debug$2(`Skipping package '${packageDir}'.`);
1078
+ return;
1079
+ }
1080
+ return entry.metadata;
1081
+ }
1082
+ /**
1083
+ * Returns the parsed contents of the given i18n file.
1084
+ */
1085
+ async getI18nFile(ctx, path) {
1086
+ const { i18n, watchFiles } = await this.#i18nCache.get(path, ctx);
1087
+ propagateWatchFiles(watchFiles, ctx);
1088
+ return i18n;
1089
+ }
1090
+ async #resolvePackageLocation(loc) {
1091
+ if (loc.type === "absolute") return await realpath(loc.directory);
1092
+ const { packageName, optional } = loc.dependency;
1093
+ const packagePath = await findDepPkgJsonPath(packageName, loc.importedFrom);
1094
+ if (!packagePath) {
1095
+ if (optional) {
1096
+ isDebug$2 && debug$2(`Optional package '${packageName}' was not found.`);
1097
+ return;
1098
+ }
1099
+ throw new ReportableError(`Failed to find package '${packageName}' (from '${loc.importedFrom}'), is the dependency installed correctly?`);
1100
+ }
1101
+ const packageDir = dirname$2(await realpath(packagePath));
1102
+ isDebug$2 && debug$2(`Found package '${packageName}' at ${packageDir}`);
1103
+ return packageDir;
1104
+ }
1105
+ #createI18nCache() {
1106
+ return new Cache({
1107
+ getId(path) {
1108
+ return normalizePath(path);
1109
+ },
1110
+ async getValue(path, ctx) {
1111
+ isDebug$2 && debug$2(`Loading i18n file ${path}`);
1112
+ ctx.addWatchFile(path);
1113
+ return {
1114
+ i18n: await loadI18nFile(path),
1115
+ watchFiles: /* @__PURE__ */ new Set([path])
1116
+ };
1117
+ },
1118
+ onInvalidate(path) {
1119
+ isDebug$2 && debug$2(`Removed cache entry for i18n file ${path}`);
1120
+ },
1121
+ onCachedReturn(path) {
1122
+ isDebug$2 && debug$2(`Returning cached entry for i18n file ${path}`);
1123
+ }
1124
+ });
1125
+ }
1126
+ #createPackageMetadataCache() {
1127
+ const sourceRoot = this.#sourceRoot;
1128
+ return new Cache({
1129
+ _byName: /* @__PURE__ */ new Map(),
1130
+ getId(directory) {
1131
+ return normalizePath(directory);
1132
+ },
1133
+ async getValue(directory, ctx, importedFrom) {
1134
+ isDebug$2 && debug$2(`Loading metadata for package at ${directory} (imported from ${importedFrom ?? "N/A"})`);
1135
+ const watchFiles = /* @__PURE__ */ new Set();
1136
+ const metadata = await loadPackageMetadata({
1137
+ resolveLocalFile: ctx.resolveLocalFile.bind(ctx),
1138
+ addWatchFile(id) {
1139
+ ctx.addWatchFile(id);
1140
+ watchFiles.add(id);
1141
+ },
1142
+ warn: ctx.warn.bind(ctx)
1143
+ }, directory, {
1144
+ sourceRoot,
1145
+ importedFrom
1146
+ });
1147
+ isDebug$2 && debug$2(`Metadata for '${metadata.name}': %O`, metadata);
1148
+ if (metadata.type === "pioneer-package") {
1149
+ const existingMetadata = this._byName.get(metadata.name);
1150
+ if (existingMetadata && normalizePath(existingMetadata.directory) !== normalizePath(metadata.directory)) throw new ReportableError(`Encountered the package '${metadata.name}' at two different locations.\nTrails packages cannot be used more than once in the same application.\nAll packages must use a common version of '${metadata.name}'.\n\n1. ${formatPackage(existingMetadata)}\n\n2. ${formatPackage(metadata)}`);
1151
+ this._byName.set(metadata.name, metadata);
1152
+ }
1153
+ return {
1154
+ metadata,
1155
+ watchFiles
1156
+ };
1157
+ },
1158
+ onInvalidate(directory, entry) {
1159
+ isDebug$2 && debug$2(`Removed cache entry for '${entry.metadata.name}'`);
1160
+ this._byName.delete(entry.metadata.name);
1161
+ },
1162
+ onCachedReturn(directory, entry) {
1163
+ isDebug$2 && debug$2(`Returning cached metadata for '${entry.metadata.name}'`);
1164
+ }
1165
+ });
1166
+ }
1383
1167
  };
1384
1168
  function detectRuntimeMetadataVersion(packages) {
1385
- var _a;
1386
- const runtimePackage = packages.find((p) => p.name === RuntimeSupport2.RUNTIME_PACKAGE_NAME);
1387
- if (!runtimePackage) {
1388
- return RuntimeSupport2.DEFAULT_METADATA_VERSION;
1389
- }
1390
- const metadataVersion = (_a = runtimePackage.config.runtimeMeta) == null ? void 0 : _a.metadataVersion;
1391
- if (!metadataVersion) {
1392
- return RuntimeSupport2.DEFAULT_METADATA_VERSION;
1393
- }
1394
- const versionResult = RuntimeSupport2.getSupportedRuntimeMetadataVersion(metadataVersion);
1395
- if (typeof versionResult != "string" && "code" in versionResult) {
1396
- switch (versionResult.code) {
1397
- case "invalid-version":
1398
- throw new ReportableError(`Invalid metadata version ${metadataVersion}`, {
1399
- cause: versionResult.error
1400
- });
1401
- case "unsupported-version":
1402
- throw new ReportableError(
1403
- `Runtime metadata version ${metadataVersion} of ${runtimePackage.name} is not supported.
1404
- This plugin supports versions ^${RuntimeSupport2.CURRENT_METADATA_MAJOR}.`
1405
- );
1406
- }
1407
- }
1408
- isDebug3 && debug4("Detected runtime version %s", versionResult);
1409
- return versionResult;
1169
+ const runtimePackage = packages.find((p) => p.name === RuntimeSupport.RUNTIME_PACKAGE_NAME);
1170
+ if (!runtimePackage) return RuntimeSupport.DEFAULT_METADATA_VERSION;
1171
+ const metadataVersion = runtimePackage.config.runtimeMeta?.metadataVersion;
1172
+ if (!metadataVersion) return RuntimeSupport.DEFAULT_METADATA_VERSION;
1173
+ const versionResult = RuntimeSupport.getSupportedRuntimeMetadataVersion(metadataVersion);
1174
+ if (typeof versionResult != "string" && "code" in versionResult) switch (versionResult.code) {
1175
+ case "invalid-version": throw new ReportableError(`Invalid metadata version ${metadataVersion}`, { cause: versionResult.error });
1176
+ case "unsupported-version": throw new ReportableError(`Runtime metadata version ${metadataVersion} of ${runtimePackage.name} is not supported.
1177
+ This plugin supports versions ^${RuntimeSupport.CURRENT_METADATA_MAJOR}.`);
1178
+ }
1179
+ isDebug$2 && debug$2("Detected runtime version %s", versionResult);
1180
+ return versionResult;
1410
1181
  }
1411
1182
  function propagateWatchFiles(watchFiles, ctx) {
1412
- for (const file of watchFiles) {
1413
- ctx.addWatchFile(file);
1414
- }
1183
+ for (const file of watchFiles) ctx.addWatchFile(file);
1415
1184
  }
1416
1185
  function formatPackageLocation(loc) {
1417
- switch (loc.type) {
1418
- case "absolute":
1419
- return `${loc.directory}`;
1420
- case "unresolved": {
1421
- let name = `'${loc.dependency.packageName}'`;
1422
- if (loc.dependency.optional) {
1423
- name += " (optional)";
1424
- }
1425
- return `${name} required by ${loc.importedFrom}`;
1426
- }
1427
- }
1186
+ switch (loc.type) {
1187
+ case "absolute": return `${loc.directory}`;
1188
+ case "unresolved": {
1189
+ let name = `'${loc.dependency.packageName}'`;
1190
+ if (loc.dependency.optional) name += " (optional)";
1191
+ return `${name} required by ${loc.importedFrom}`;
1192
+ }
1193
+ }
1428
1194
  }
1429
- var PACKAGE_JSON_RE = /[\\/]package\.json($|\?)/;
1195
+ const PACKAGE_JSON_RE = /[\\/]package\.json($|\?)/;
1430
1196
  function isPackageJson(file) {
1431
- return PACKAGE_JSON_RE.test(file);
1197
+ return PACKAGE_JSON_RE.test(file);
1432
1198
  }
1433
1199
  function isBuildConfig(file) {
1434
- return basename2(file) === BUILD_CONFIG_NAME2;
1200
+ return basename$1(file) === BUILD_CONFIG_NAME;
1435
1201
  }
1436
1202
  function formatPackage(packageMetadata) {
1437
- let str = `${packageMetadata.name}`;
1438
- if (packageMetadata.version != null) {
1439
- str += `@${packageMetadata.version}`;
1440
- }
1441
- str += ` at ${packageMetadata.directory}`;
1442
- return str;
1203
+ let str = `${packageMetadata.name}`;
1204
+ if (packageMetadata.version != null) str += `@${packageMetadata.version}`;
1205
+ str += ` at ${packageMetadata.directory}`;
1206
+ return str;
1443
1207
  }
1444
-
1445
- // src/metadata/validateI18nConfig.ts
1446
- var isDebug4 = !!process.env.DEBUG;
1447
- var debug5 = createDebugger("open-pioneer:validateI18nConfig");
1208
+ //#endregion
1209
+ //#region src/metadata/validateI18nConfig.ts
1210
+ const isDebug$1 = !!process.env.DEBUG;
1211
+ const debug$1 = createDebugger("open-pioneer:validateI18nConfig");
1448
1212
  async function validateI18nConfig(ctx, repository, appMetadata) {
1449
- const locales = appMetadata.locales;
1450
- for (const pkg2 of appMetadata.packages) {
1451
- isDebug4 && debug5("Checking i18n files of package %s", pkg2.name);
1452
- await checkPackageI18nFiles(ctx, pkg2, locales);
1453
- }
1454
- await checkAppI18n(ctx, repository, appMetadata);
1213
+ const locales = appMetadata.locales;
1214
+ for (const pkg of appMetadata.packages) {
1215
+ isDebug$1 && debug$1("Checking i18n files of package %s", pkg.name);
1216
+ await checkPackageI18nFiles(ctx, pkg, locales);
1217
+ }
1218
+ await checkAppI18n(ctx, repository, appMetadata);
1455
1219
  }
1456
- async function checkPackageI18nFiles(ctx, pkg2, locales) {
1457
- for (const locale of locales) {
1458
- const filePath = pkg2.i18nPaths.get(locale);
1459
- if (!filePath) {
1460
- isDebug4 && debug5("Package does not support locale '%s'", locale);
1461
- continue;
1462
- }
1463
- isDebug4 && debug5("Checking i18n file %s", filePath);
1464
- ctx.addWatchFile(filePath);
1465
- if (!await fileExists(filePath)) {
1466
- throw new ReportableError(
1467
- `I18n file in package '${pkg2.name}' for locale '${locale}' does not exist: '${filePath}'.`
1468
- );
1469
- } else {
1470
- isDebug4 && debug5("i18n file %s exists", filePath);
1471
- }
1472
- }
1220
+ async function checkPackageI18nFiles(ctx, pkg, locales) {
1221
+ for (const locale of locales) {
1222
+ const filePath = pkg.i18nPaths.get(locale);
1223
+ if (!filePath) {
1224
+ isDebug$1 && debug$1("Package does not support locale '%s'", locale);
1225
+ continue;
1226
+ }
1227
+ isDebug$1 && debug$1("Checking i18n file %s", filePath);
1228
+ ctx.addWatchFile(filePath);
1229
+ if (!await fileExists(filePath)) throw new ReportableError(`I18n file in package '${pkg.name}' for locale '${locale}' does not exist: '${filePath}'.`);
1230
+ else isDebug$1 && debug$1("i18n file %s exists", filePath);
1231
+ }
1473
1232
  }
1474
1233
  async function checkAppI18n(ctx, repository, appMetadata) {
1475
- const appPackage = appMetadata.appPackage;
1476
- const appLocales = new Set(appMetadata.locales);
1477
- const appI18nFiles = await Promise.all(
1478
- Array.from(appLocales).map((locale) => {
1479
- const i18nPath = appPackage.i18nPaths.get(locale);
1480
- if (i18nPath == null) {
1481
- throw new Error(
1482
- `App package '${appPackage.name}' does not have an i18n file for locale '${locale}'.`
1483
- );
1484
- }
1485
- return repository.getI18nFile(ctx, i18nPath);
1486
- })
1487
- );
1488
- const errors = [];
1489
- for (const pkg2 of appMetadata.packages) {
1490
- const pkgLocales = pkg2.locales;
1491
- if (pkgLocales.length === 0) {
1492
- continue;
1493
- }
1494
- if (pkg2.locales.some((locale) => appLocales.has(locale))) {
1495
- continue;
1496
- }
1497
- if (appI18nFiles.some((i18nFile) => {
1498
- var _a;
1499
- return (_a = i18nFile.overrides) == null ? void 0 : _a.get(pkg2.name);
1500
- })) {
1501
- continue;
1502
- }
1503
- errors.push(pkg2);
1504
- }
1505
- if (errors.length === 0) {
1506
- return;
1507
- }
1508
- errors.sort((p1, p2) => p1.name.localeCompare(p2.name, "en"));
1509
- const getPackageErrors = () => {
1510
- const MAX = 3;
1511
- const take = Math.min(errors.length, MAX);
1512
- const remaining = errors.length - take;
1513
- let buffer = "";
1514
- for (let i = 0; i < take; ++i) {
1515
- if (i > 0) {
1516
- buffer += ", ";
1517
- }
1518
- const pkg2 = errors[i];
1519
- buffer += `'${pkg2.name}' (${pkg2.locales.toSorted().join(", ")})`;
1520
- }
1521
- if (remaining > 0) {
1522
- buffer += ` (and ${remaining} more)`;
1523
- }
1524
- return buffer;
1525
- };
1526
- const formattedAppLocales = appMetadata.locales.join(", ") || "none";
1527
- const formattedPackageErrors = getPackageErrors();
1528
- throw new ReportableError(
1529
- `Invalid i18n configuration in application at ${appMetadata.directory}:
1530
- There is no match between the locales supported by the application (${formattedAppLocales}) and the locales supported by the packages ${formattedPackageErrors}.`
1531
- );
1234
+ const appPackage = appMetadata.appPackage;
1235
+ const appLocales = new Set(appMetadata.locales);
1236
+ const appI18nFiles = await Promise.all(Array.from(appLocales).map((locale) => {
1237
+ const i18nPath = appPackage.i18nPaths.get(locale);
1238
+ if (i18nPath == null) throw new Error(`App package '${appPackage.name}' does not have an i18n file for locale '${locale}'.`);
1239
+ return repository.getI18nFile(ctx, i18nPath);
1240
+ }));
1241
+ const errors = [];
1242
+ for (const pkg of appMetadata.packages) {
1243
+ if (pkg.locales.length === 0) continue;
1244
+ if (pkg.locales.some((locale) => appLocales.has(locale))) continue;
1245
+ if (appI18nFiles.some((i18nFile) => i18nFile.overrides?.get(pkg.name))) continue;
1246
+ errors.push(pkg);
1247
+ }
1248
+ if (errors.length === 0) return;
1249
+ errors.sort((p1, p2) => p1.name.localeCompare(p2.name, "en"));
1250
+ const getPackageErrors = () => {
1251
+ const take = Math.min(errors.length, 3);
1252
+ const remaining = errors.length - take;
1253
+ let buffer = "";
1254
+ for (let i = 0; i < take; ++i) {
1255
+ if (i > 0) buffer += ", ";
1256
+ const pkg = errors[i];
1257
+ buffer += `'${pkg.name}' (${pkg.locales.toSorted().join(", ")})`;
1258
+ }
1259
+ if (remaining > 0) buffer += ` (and ${remaining} more)`;
1260
+ return buffer;
1261
+ };
1262
+ const formattedAppLocales = appMetadata.locales.join(", ") || "none";
1263
+ const formattedPackageErrors = getPackageErrors();
1264
+ throw new ReportableError(`Invalid i18n configuration in application at ${appMetadata.directory}:\nThere is no match between the locales supported by the application (${formattedAppLocales}) and the locales supported by the packages ${formattedPackageErrors}.`);
1532
1265
  }
1533
-
1534
- // src/codegenPlugin.ts
1535
- var isDebug5 = !!process.env.DEBUG;
1536
- var debug6 = createDebugger("open-pioneer:codegen");
1266
+ //#endregion
1267
+ //#region src/codegenPlugin.ts
1268
+ const isDebug = !!process.env.DEBUG;
1269
+ const debug = createDebugger("open-pioneer:codegen");
1537
1270
  function codegenPlugin() {
1538
- let isDev;
1539
- let rootDir;
1540
- let repository;
1541
- let deploymentModule;
1542
- return {
1543
- name: "pioneer:codegen",
1544
- async config(userConfig, env) {
1545
- isDev = env.command === "serve";
1546
- rootDir = userConfig.root ?? cwd();
1547
- repository = new MetadataRepository(rootDir);
1548
- if (isDev) {
1549
- return await configureDevOptimizer(userConfig, rootDir);
1550
- }
1551
- },
1552
- configResolved(config) {
1553
- deploymentModule = new DeploymentModule(isDev, config.base);
1554
- },
1555
- async buildStart() {
1556
- repository == null ? void 0 : repository.reset();
1557
- deploymentModule.onStart(this);
1558
- },
1559
- resolveId: {
1560
- filter: {
1561
- id: VIRTUAL_ID_FILTER
1562
- },
1563
- async handler(moduleId, importer) {
1564
- try {
1565
- if (!importer) {
1566
- return void 0;
1567
- }
1568
- if (parseVirtualModuleId(moduleId)) {
1569
- return moduleId;
1570
- }
1571
- let virtualModule;
1572
- try {
1573
- virtualModule = RuntimeSupport3.parseVirtualModule(moduleId);
1574
- } catch (e) {
1575
- this.error({
1576
- id: moduleId,
1577
- message: "Invalid virtual module id",
1578
- cause: e
1579
- });
1580
- }
1581
- switch (virtualModule) {
1582
- case "app":
1583
- return serializeModuleId({
1584
- type: "app-meta",
1585
- packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1586
- });
1587
- case "react-hooks":
1588
- return serializeModuleId({
1589
- type: "package-hooks",
1590
- packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1591
- });
1592
- case "source-info":
1593
- return serializeModuleId({
1594
- type: "source-info",
1595
- modulePath: importer,
1596
- packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1597
- });
1598
- case "deployment": {
1599
- return serializeModuleId({
1600
- type: "deployment"
1601
- });
1602
- }
1603
- }
1604
- } catch (e) {
1605
- reportError(this, e, isDev);
1606
- }
1607
- }
1608
- },
1609
- load: {
1610
- filter: {
1611
- id: VIRTUAL_ID_FILTER
1612
- },
1613
- async handler(moduleId) {
1614
- var _a;
1615
- try {
1616
- const mod = parseVirtualModuleId(moduleId);
1617
- if (!mod) {
1618
- return void 0;
1619
- }
1620
- isDebug5 && debug6("Loading virtual module %O", mod);
1621
- if (mod.type === "deployment") {
1622
- return jsModule(deploymentModule.onLoadModule());
1623
- }
1624
- const packageJsonPath = await resolvePackageJson(this, mod);
1625
- if (mod.type === "package-hooks") {
1626
- const directory = mod.packageDirectory;
1627
- const packageJsonPath2 = (_a = await this.resolve(directory + "/package.json")) == null ? void 0 : _a.id;
1628
- if (!packageJsonPath2) {
1629
- throw new ReportableError(
1630
- `Failed to resolve package.json in ${directory}`
1631
- );
1632
- }
1633
- const packageName = await getPackageName(this, packageJsonPath2);
1634
- const generatedSourceCode = RuntimeSupport3.generateReactHooks(
1635
- packageName,
1636
- RuntimeSupport3.REACT_INTEGRATION_MODULE_ID
1637
- );
1638
- isDebug5 && debug6("Generated hooks code: %O", generatedSourceCode);
1639
- return jsModule(generatedSourceCode);
1640
- }
1641
- if (mod.type === "source-info") {
1642
- const packageName = await getPackageName(this, packageJsonPath);
1643
- return jsModule(
1644
- RuntimeSupport3.generateSourceInfo(packageName, mod.modulePath)
1645
- );
1646
- }
1647
- const ctx = createMetadataContextFromRolldown(this);
1648
- const appMetadata = await repository.getAppMetadata(
1649
- ctx,
1650
- dirname4(packageJsonPath)
1651
- );
1652
- if (mod.type === "app-meta") {
1653
- const runtimeVersion = appMetadata.runtimeMetadataVersion;
1654
- isDebug5 && debug6("Generating app metadata for runtime version %s", runtimeVersion);
1655
- const generatedSourceCode = generateAppMetadata(
1656
- mod.packageDirectory,
1657
- RuntimeSupport3.METADATA_MODULE_ID,
1658
- runtimeVersion
1659
- );
1660
- return jsModule(generatedSourceCode);
1661
- }
1662
- switch (mod.type) {
1663
- case "app-packages": {
1664
- const generatedSourceCode = generatePackagesMetadata({
1665
- appName: appMetadata.name,
1666
- packages: appMetadata.packages
1667
- });
1668
- isDebug5 && debug6("Generated app metadata: %O", generatedSourceCode);
1669
- return jsModule(generatedSourceCode);
1670
- }
1671
- case "app-css": {
1672
- const generatedSourceCode = generateCombinedCss(appMetadata.packages);
1673
- isDebug5 && debug6("Generated app css: %O", generatedSourceCode);
1674
- return jsModule(generatedSourceCode);
1675
- }
1676
- case "app-i18n-index": {
1677
- await validateI18nConfig(ctx, repository, appMetadata);
1678
- const generatedSourceCode = generateI18nIndex(
1679
- mod.packageDirectory,
1680
- appMetadata.locales
1681
- );
1682
- isDebug5 && debug6("Generated i18n lookup: %O", generatedSourceCode);
1683
- return jsModule(generatedSourceCode);
1684
- }
1685
- case "app-i18n": {
1686
- const generatedSourceCode = await generateI18nMessages({
1687
- locale: mod.locale,
1688
- appName: appMetadata.name,
1689
- packages: appMetadata.packages,
1690
- loadI18n: async (pkg2, filePath) => {
1691
- ctx.addWatchFile(filePath);
1692
- if (!await fileExists(filePath)) {
1693
- throw new ReportableError(
1694
- `I18n file at ${filePath} does not exist.`
1695
- );
1696
- }
1697
- return repository.getI18nFile(ctx, filePath);
1698
- }
1699
- });
1700
- isDebug5 && debug6("Generated i18n messages: %O", generatedSourceCode);
1701
- return jsModule(generatedSourceCode);
1702
- }
1703
- default:
1704
- assertNever(mod.type);
1705
- }
1706
- } catch (e) {
1707
- reportError(this, e, isDev);
1708
- }
1709
- }
1710
- },
1711
- watchChange(id, _change) {
1712
- isDebug5 && debug6("File %s changed", id);
1713
- repository.onFileChanged(id);
1714
- },
1715
- generateBundle(_options, bundle) {
1716
- deploymentModule.onGenerateBundle(bundle);
1717
- }
1718
- };
1271
+ let isDev;
1272
+ let rootDir;
1273
+ let repository;
1274
+ let deploymentModule;
1275
+ return {
1276
+ name: "pioneer:codegen",
1277
+ async config(userConfig, env) {
1278
+ isDev = env.command === "serve";
1279
+ rootDir = userConfig.root ?? cwd();
1280
+ repository = new MetadataRepository(rootDir);
1281
+ if (isDev) return await configureDevOptimizer(userConfig, rootDir);
1282
+ },
1283
+ configResolved(config) {
1284
+ deploymentModule = new DeploymentModule(isDev, config.base);
1285
+ },
1286
+ async buildStart() {
1287
+ repository?.reset();
1288
+ deploymentModule.onStart(this);
1289
+ },
1290
+ resolveId: {
1291
+ filter: { id: VIRTUAL_ID_FILTER },
1292
+ async handler(moduleId, importer) {
1293
+ try {
1294
+ if (!importer) return;
1295
+ if (parseVirtualModuleId(moduleId)) return moduleId;
1296
+ let virtualModule;
1297
+ try {
1298
+ virtualModule = RuntimeSupport.parseVirtualModule(moduleId);
1299
+ } catch (e) {
1300
+ this.error({
1301
+ id: moduleId,
1302
+ message: "Invalid virtual module id",
1303
+ cause: e
1304
+ });
1305
+ }
1306
+ switch (virtualModule) {
1307
+ case "app": return serializeModuleId({
1308
+ type: "app-meta",
1309
+ packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1310
+ });
1311
+ case "react-hooks": return serializeModuleId({
1312
+ type: "package-hooks",
1313
+ packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1314
+ });
1315
+ case "source-info": return serializeModuleId({
1316
+ type: "source-info",
1317
+ modulePath: importer,
1318
+ packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1319
+ });
1320
+ case "deployment": return serializeModuleId({ type: "deployment" });
1321
+ }
1322
+ } catch (e) {
1323
+ reportError(this, e, isDev);
1324
+ }
1325
+ }
1326
+ },
1327
+ load: {
1328
+ filter: { id: VIRTUAL_ID_FILTER },
1329
+ async handler(moduleId) {
1330
+ try {
1331
+ const mod = parseVirtualModuleId(moduleId);
1332
+ if (!mod) return;
1333
+ isDebug && debug("Loading virtual module %O", mod);
1334
+ if (mod.type === "deployment") return jsModule(deploymentModule.onLoadModule());
1335
+ const packageJsonPath = await resolvePackageJson(this, mod);
1336
+ if (mod.type === "package-hooks") {
1337
+ const directory = mod.packageDirectory;
1338
+ const packageJsonPath = (await this.resolve(directory + "/package.json"))?.id;
1339
+ if (!packageJsonPath) throw new ReportableError(`Failed to resolve package.json in ${directory}`);
1340
+ const packageName = await getPackageName(this, packageJsonPath);
1341
+ const generatedSourceCode = RuntimeSupport.generateReactHooks(packageName, RuntimeSupport.REACT_INTEGRATION_MODULE_ID);
1342
+ isDebug && debug("Generated hooks code: %O", generatedSourceCode);
1343
+ return jsModule(generatedSourceCode);
1344
+ }
1345
+ if (mod.type === "source-info") {
1346
+ const packageName = await getPackageName(this, packageJsonPath);
1347
+ return jsModule(RuntimeSupport.generateSourceInfo(packageName, mod.modulePath));
1348
+ }
1349
+ const ctx = createMetadataContextFromRolldown(this);
1350
+ const appMetadata = await repository.getAppMetadata(ctx, dirname(packageJsonPath));
1351
+ if (mod.type === "app-meta") {
1352
+ const runtimeVersion = appMetadata.runtimeMetadataVersion;
1353
+ isDebug && debug("Generating app metadata for runtime version %s", runtimeVersion);
1354
+ return jsModule(generateAppMetadata(mod.packageDirectory, RuntimeSupport.METADATA_MODULE_ID, runtimeVersion));
1355
+ }
1356
+ switch (mod.type) {
1357
+ case "app-packages": {
1358
+ const generatedSourceCode = generatePackagesMetadata({
1359
+ appName: appMetadata.name,
1360
+ packages: appMetadata.packages
1361
+ });
1362
+ isDebug && debug("Generated app metadata: %O", generatedSourceCode);
1363
+ return jsModule(generatedSourceCode);
1364
+ }
1365
+ case "app-css": {
1366
+ const generatedSourceCode = generateCombinedCss(appMetadata.packages);
1367
+ isDebug && debug("Generated app css: %O", generatedSourceCode);
1368
+ return jsModule(generatedSourceCode);
1369
+ }
1370
+ case "app-i18n-index": {
1371
+ await validateI18nConfig(ctx, repository, appMetadata);
1372
+ const generatedSourceCode = generateI18nIndex(mod.packageDirectory, appMetadata.locales);
1373
+ isDebug && debug("Generated i18n lookup: %O", generatedSourceCode);
1374
+ return jsModule(generatedSourceCode);
1375
+ }
1376
+ case "app-i18n": {
1377
+ const generatedSourceCode = await generateI18nMessages({
1378
+ locale: mod.locale,
1379
+ appName: appMetadata.name,
1380
+ packages: appMetadata.packages,
1381
+ loadI18n: async (pkg, filePath) => {
1382
+ ctx.addWatchFile(filePath);
1383
+ if (!await fileExists(filePath)) throw new ReportableError(`I18n file at ${filePath} does not exist.`);
1384
+ return repository.getI18nFile(ctx, filePath);
1385
+ }
1386
+ });
1387
+ isDebug && debug("Generated i18n messages: %O", generatedSourceCode);
1388
+ return jsModule(generatedSourceCode);
1389
+ }
1390
+ default: assertNever(mod.type);
1391
+ }
1392
+ } catch (e) {
1393
+ reportError(this, e, isDev);
1394
+ }
1395
+ }
1396
+ },
1397
+ watchChange(id, _change) {
1398
+ isDebug && debug("File %s changed", id);
1399
+ repository.onFileChanged(id);
1400
+ },
1401
+ generateBundle(_options, bundle) {
1402
+ deploymentModule.onGenerateBundle(bundle);
1403
+ }
1404
+ };
1719
1405
  }
1720
1406
  async function resolvePackageJson(ctx, mod) {
1721
- var _a;
1722
- const path = (_a = await ctx.resolve(mod.packageDirectory + "/package.json")) == null ? void 0 : _a.id;
1723
- if (!path) {
1724
- throw new ReportableError(`Failed to resolve package.json in ${mod.packageDirectory}`);
1725
- }
1726
- return path;
1407
+ const path = (await ctx.resolve(mod.packageDirectory + "/package.json"))?.id;
1408
+ if (!path) throw new ReportableError(`Failed to resolve package.json in ${mod.packageDirectory}`);
1409
+ return path;
1727
1410
  }
1728
1411
  async function configureDevOptimizer(userConfig, rootDir) {
1729
- const trailsModules = await getOptimizeDepsIncludes(rootDir);
1730
- return {
1731
- optimizeDeps: {
1732
- include: trailsModules,
1733
- rolldownOptions: {
1734
- plugins: [createOptimizeDepsRolldownPlugin()]
1735
- }
1736
- }
1737
- };
1412
+ return { optimizeDeps: {
1413
+ include: await getOptimizeDepsIncludes(rootDir),
1414
+ rolldownOptions: { plugins: [createOptimizeDepsRolldownPlugin()] }
1415
+ } };
1738
1416
  }
1417
+ /**
1418
+ * Find external trails packages and add their services modules (if any)
1419
+ * to vite's `optimizeDeps.include`.
1420
+ *
1421
+ * This should reduce the number of `✨ optimized dependencies changed. reloading` events during development.
1422
+ *
1423
+ * NOTE: A better solution would be to teach vite's dependency optimizer how to interpret "open-pioneer:*",
1424
+ * so that it accurately understands the actual additional imports from trails into node modules (i.e. all services etc.).
1425
+ *
1426
+ * I couldn't get the esbuild plugin working, however.
1427
+ * This could be reattempted when vite has migrated to rolldown.
1428
+ */
1739
1429
  async function getOptimizeDepsIncludes(rootDir) {
1740
- const trailsPackages = await findTrailsPackages(rootDir);
1741
- const trailsModules = trailsPackages.flatMap((pkg2) => {
1742
- if (!/[/\\]node_modules[/\\]/.test(pkg2.directory)) {
1743
- return [];
1744
- }
1745
- const serviceModule = pkg2.servicesModuleId;
1746
- return serviceModule ? [serviceModule] : [];
1747
- });
1748
- trailsModules.push(`${RuntimeSupport3.RUNTIME_PACKAGE_NAME}/**`);
1749
- isDebug5 && debug6("Optimizing additional modules %O", trailsModules);
1750
- return trailsModules;
1430
+ const trailsModules = (await findTrailsPackages(rootDir)).flatMap((pkg) => {
1431
+ if (!/[/\\]node_modules[/\\]/.test(pkg.directory)) return [];
1432
+ const serviceModule = pkg.servicesModuleId;
1433
+ return serviceModule ? [serviceModule] : [];
1434
+ });
1435
+ trailsModules.push(`${RuntimeSupport.RUNTIME_PACKAGE_NAME}/**`);
1436
+ isDebug && debug("Optimizing additional modules %O", trailsModules);
1437
+ return trailsModules;
1751
1438
  }
1439
+ /**
1440
+ * Creates a rolldown plugin for use during Vite's dependency optimization phase.
1441
+ * It marks all `open-pioneer:*` virtual module imports as external so that they
1442
+ * are left untouched by rolldown and can later be handled by the normal Vite plugin.
1443
+ */
1752
1444
  function createOptimizeDepsRolldownPlugin() {
1753
- return {
1754
- name: "pioneer:optimize-deps",
1755
- resolveId(id) {
1756
- if (/^open-pioneer:/.test(id)) {
1757
- return { id, external: true };
1758
- }
1759
- }
1760
- };
1445
+ return {
1446
+ name: "pioneer:optimize-deps",
1447
+ resolveId(id) {
1448
+ if (/^open-pioneer:/.test(id)) return {
1449
+ id,
1450
+ external: true
1451
+ };
1452
+ }
1453
+ };
1761
1454
  }
1762
1455
  function reportError(ctx, error, isDev) {
1763
- let message;
1764
- if (error instanceof ReportableError) {
1765
- message = error.message;
1766
- } else {
1767
- message = "Internal error: " + (String(error == null ? void 0 : error.message) || "Unknown error");
1768
- }
1769
- if (isDev) {
1770
- for (const cause of getCauseMessages(error)) {
1771
- message += "\n\n";
1772
- message += `Caused by: ${cause}`;
1773
- }
1774
- }
1775
- ctx.error({
1776
- message,
1777
- // oxlint-disable-next-line @typescript-eslint/no-explicit-any
1778
- cause: error.cause,
1779
- // oxlint-disable-next-line @typescript-eslint/no-explicit-any
1780
- stack: error.stack
1781
- });
1456
+ let message;
1457
+ if (error instanceof ReportableError) message = error.message;
1458
+ else message = "Internal error: " + (String(error?.message) || "Unknown error");
1459
+ if (isDev) for (const cause of getCauseMessages(error)) {
1460
+ message += "\n\n";
1461
+ message += `Caused by: ${cause}`;
1462
+ }
1463
+ ctx.error({
1464
+ message,
1465
+ cause: error.cause,
1466
+ stack: error.stack
1467
+ });
1782
1468
  }
1783
1469
  function getPackageDirectoryFromDirectory(directory, rootDir) {
1784
- const packageJsonPath = findPackageJson(directory, rootDir);
1785
- if (!packageJsonPath) {
1786
- throw new ReportableError(`Failed to find package.json for package from '${directory}'.`);
1787
- }
1788
- const packageDir = dirname4(packageJsonPath);
1789
- return normalizePath5(packageDir);
1470
+ const packageJsonPath = findPackageJson(directory, rootDir);
1471
+ if (!packageJsonPath) throw new ReportableError(`Failed to find package.json for package from '${directory}'.`);
1472
+ return normalizePath(dirname(packageJsonPath));
1790
1473
  }
1791
1474
  function getPackageDirectoryFromImporter(importer, rootDir) {
1792
- return getPackageDirectoryFromDirectory(dirname4(importer), rootDir);
1475
+ return getPackageDirectoryFromDirectory(dirname(importer), rootDir);
1793
1476
  }
1794
1477
  async function getPackageName(ctx, packageJsonPath) {
1795
- let name;
1796
- try {
1797
- const content = await readFile3(packageJsonPath, "utf-8");
1798
- name = JSON.parse(content).name;
1799
- } catch (e) {
1800
- throw new ReportableError(`Failed to read package.json file`, { cause: e });
1801
- }
1802
- if (!name) {
1803
- throw new ReportableError(`Failed to read package name from ${packageJsonPath}.`);
1804
- }
1805
- return name;
1478
+ let name;
1479
+ try {
1480
+ const content = await readFile(packageJsonPath, "utf-8");
1481
+ name = JSON.parse(content).name;
1482
+ } catch (e) {
1483
+ throw new ReportableError(`Failed to read package.json file`, { cause: e });
1484
+ }
1485
+ if (!name) throw new ReportableError(`Failed to read package name from ${packageJsonPath}.`);
1486
+ return name;
1806
1487
  }
1807
1488
  function jsModule(code) {
1808
- return {
1809
- code,
1810
- moduleType: "js"
1811
- };
1489
+ return {
1490
+ code,
1491
+ moduleType: "js"
1492
+ };
1812
1493
  }
1813
1494
  function getCauseMessages(error) {
1814
- const causes = [];
1815
- while (1) {
1816
- const cause = error == null ? void 0 : error.cause;
1817
- if (!cause) {
1818
- break;
1819
- }
1820
- const message = cause.message;
1821
- if (!message || typeof message !== "string") {
1822
- break;
1823
- }
1824
- causes.push(message);
1825
- error = cause;
1826
- }
1827
- return causes;
1495
+ const causes = [];
1496
+ while (1) {
1497
+ const cause = error?.cause;
1498
+ if (!cause) break;
1499
+ const message = cause.message;
1500
+ if (!message || typeof message !== "string") break;
1501
+ causes.push(message);
1502
+ error = cause;
1503
+ }
1504
+ return causes;
1828
1505
  }
1829
1506
  function assertNever(x) {
1830
- throw new Error("Should not be reached: " + x);
1507
+ throw new Error("Should not be reached: " + x);
1831
1508
  }
1832
-
1833
- // src/mpaPlugin.ts
1834
- import { existsSync as existsSync3 } from "node:fs";
1835
- import { posix as posix4, resolve } from "node:path";
1836
- import { cwd as cwd2 } from "node:process";
1509
+ //#endregion
1510
+ //#region src/mpaPlugin.ts
1837
1511
  function mpaPlugin(options) {
1838
- const rootSite = (options == null ? void 0 : options.rootSite) ?? false;
1839
- const apps = (options == null ? void 0 : options.apps) || [];
1840
- const sites = (options == null ? void 0 : options.sites) || [];
1841
- let resolvedConfig;
1842
- return {
1843
- name: "pioneer:mpa",
1844
- config(config) {
1845
- const sourceRoot = config.root ?? cwd2();
1846
- const { entryPoints, appNames } = gatherEntryPoints({
1847
- apps,
1848
- sites,
1849
- rootSite,
1850
- sourceRoot
1851
- });
1852
- const rolldownOptions = {
1853
- input: entryPoints,
1854
- // Low risk solution to https://github.com/open-pioneer/trails-build-tools/issues/53 (Vite defaults to a different value).
1855
- // Note that this setting now applies to both app entry points and the JS generated by html files.
1856
- // If this way is not good enough, we can emit app chunks using `this.emitFile(...)`.
1857
- preserveEntrySignatures: "allow-extension",
1858
- output: {
1859
- entryFileNames(chunk) {
1860
- if (appNames.includes(chunk.name)) {
1861
- return "[name].js";
1862
- }
1863
- return posix4.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1864
- },
1865
- chunkFileNames(chunk) {
1866
- void chunk;
1867
- return posix4.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1868
- }
1869
- }
1870
- };
1871
- return {
1872
- build: {
1873
- rolldownOptions
1874
- }
1875
- };
1876
- },
1877
- configResolved(config) {
1878
- resolvedConfig = config;
1879
- }
1880
- };
1512
+ const rootSite = options?.rootSite ?? false;
1513
+ const apps = options?.apps || [];
1514
+ const sites = options?.sites || [];
1515
+ let resolvedConfig;
1516
+ return {
1517
+ name: "pioneer:mpa",
1518
+ config(config) {
1519
+ const sourceRoot = config.root ?? cwd();
1520
+ const { entryPoints, appNames } = gatherEntryPoints({
1521
+ apps,
1522
+ sites,
1523
+ rootSite,
1524
+ sourceRoot
1525
+ });
1526
+ return { build: { rolldownOptions: {
1527
+ input: entryPoints,
1528
+ preserveEntrySignatures: "allow-extension",
1529
+ output: {
1530
+ entryFileNames(chunk) {
1531
+ if (appNames.includes(chunk.name)) return "[name].js";
1532
+ return posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1533
+ },
1534
+ chunkFileNames(chunk) {
1535
+ return posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1536
+ }
1537
+ }
1538
+ } } };
1539
+ },
1540
+ configResolved(config) {
1541
+ resolvedConfig = config;
1542
+ }
1543
+ };
1881
1544
  }
1882
1545
  function gatherEntryPoints(options) {
1883
- let apps;
1884
- if (Array.isArray(options.apps)) {
1885
- apps = options.apps.map((appName) => {
1886
- const prefix = resolve(options.sourceRoot, "apps", appName, "app");
1887
- const path = findMatchingEntryPointFile(appName, prefix);
1888
- return {
1889
- name: appName,
1890
- path
1891
- };
1892
- });
1893
- } else {
1894
- apps = Object.entries(options.apps).map(([name, appPath]) => {
1895
- const path = resolve(options.sourceRoot, appPath);
1896
- if (!existsSync3(path)) {
1897
- throw new Error(
1898
- `Failed to find app '${name}' at ${path}. Ensure that the path is spelled correctly.`
1899
- );
1900
- }
1901
- return { name, path };
1902
- });
1903
- }
1904
- const sites = options.sites.map((sitePath) => {
1905
- const path = resolve(options.sourceRoot, sitePath, "index.html");
1906
- if (!existsSync3(path)) {
1907
- throw new Error(
1908
- `Failed to find site at ${path}. Ensure that the site name in your vite configuration is spelled correctly.`
1909
- );
1910
- }
1911
- return {
1912
- name: sitePath,
1913
- path
1914
- };
1915
- });
1916
- if (options.rootSite) {
1917
- const path = resolve(options.sourceRoot, "index.html");
1918
- if (!existsSync3(path)) {
1919
- throw new Error(
1920
- `Failed to find root site at ${path}. Create the missing file or set 'rootSite' to false.`
1921
- );
1922
- }
1923
- sites.push({
1924
- name: "index",
1925
- path
1926
- });
1927
- }
1928
- const entryPoints = {};
1929
- let entryPointCount = 0;
1930
- for (const { name, path } of [apps, sites].flat()) {
1931
- const existingPath = entryPoints[name];
1932
- if (existingPath) {
1933
- throw new Error(
1934
- `Entry point '${name}' was defined twice (paths ${existingPath} and ${path}). Remove the duplicated entry.`
1935
- );
1936
- }
1937
- entryPoints[name] = path;
1938
- ++entryPointCount;
1939
- }
1940
- if (entryPointCount === 0) {
1941
- throw new Error(
1942
- "You must configure at least one site or one app in the pioneer plugin options."
1943
- );
1944
- }
1945
- const appNames = apps.map(({ name }) => name);
1946
- return {
1947
- entryPoints,
1948
- appNames
1949
- };
1546
+ let apps;
1547
+ if (Array.isArray(options.apps)) apps = options.apps.map((appName) => {
1548
+ return {
1549
+ name: appName,
1550
+ path: findMatchingEntryPointFile(appName, resolve(options.sourceRoot, "apps", appName, "app"))
1551
+ };
1552
+ });
1553
+ else apps = Object.entries(options.apps).map(([name, appPath]) => {
1554
+ const path = resolve(options.sourceRoot, appPath);
1555
+ if (!existsSync$1(path)) throw new Error(`Failed to find app '${name}' at ${path}. Ensure that the path is spelled correctly.`);
1556
+ return {
1557
+ name,
1558
+ path
1559
+ };
1560
+ });
1561
+ const sites = options.sites.map((sitePath) => {
1562
+ const path = resolve(options.sourceRoot, sitePath, "index.html");
1563
+ if (!existsSync$1(path)) throw new Error(`Failed to find site at ${path}. Ensure that the site name in your vite configuration is spelled correctly.`);
1564
+ return {
1565
+ name: sitePath,
1566
+ path
1567
+ };
1568
+ });
1569
+ if (options.rootSite) {
1570
+ const path = resolve(options.sourceRoot, "index.html");
1571
+ if (!existsSync$1(path)) throw new Error(`Failed to find root site at ${path}. Create the missing file or set 'rootSite' to false.`);
1572
+ sites.push({
1573
+ name: "index",
1574
+ path
1575
+ });
1576
+ }
1577
+ const entryPoints = {};
1578
+ let entryPointCount = 0;
1579
+ for (const { name, path } of [apps, sites].flat()) {
1580
+ const existingPath = entryPoints[name];
1581
+ if (existingPath) throw new Error(`Entry point '${name}' was defined twice (paths ${existingPath} and ${path}). Remove the duplicated entry.`);
1582
+ entryPoints[name] = path;
1583
+ ++entryPointCount;
1584
+ }
1585
+ if (entryPointCount === 0) throw new Error("You must configure at least one site or one app in the pioneer plugin options.");
1586
+ return {
1587
+ entryPoints,
1588
+ appNames: apps.map(({ name }) => name)
1589
+ };
1950
1590
  }
1951
- var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
1591
+ const EXTENSIONS = [
1592
+ ".ts",
1593
+ ".tsx",
1594
+ ".js",
1595
+ ".jsx"
1596
+ ];
1952
1597
  function findMatchingEntryPointFile(appName, prefix) {
1953
- for (const ext of EXTENSIONS) {
1954
- const candidate = prefix + ext;
1955
- if (existsSync3(candidate)) {
1956
- return candidate;
1957
- }
1958
- }
1959
- const extensions = EXTENSIONS.join(", ");
1960
- throw new Error(
1961
- `Failed to find a matching entry point file for app '${appName}' at ${prefix}. Supported extensions are ${extensions}. Ensure that the app name is spelled correctly or create the missing file.`
1962
- );
1598
+ for (const ext of EXTENSIONS) {
1599
+ const candidate = prefix + ext;
1600
+ if (existsSync$1(candidate)) return candidate;
1601
+ }
1602
+ const extensions = EXTENSIONS.join(", ");
1603
+ throw new Error(`Failed to find a matching entry point file for app '${appName}' at ${prefix}. Supported extensions are ${extensions}. Ensure that the app name is spelled correctly or create the missing file.`);
1963
1604
  }
1964
-
1965
- // src/index.ts
1605
+ //#endregion
1606
+ //#region src/index.ts
1966
1607
  function pioneer(options) {
1967
- return [mpaPlugin(options), codegenPlugin()];
1608
+ return [mpaPlugin(options), codegenPlugin()];
1968
1609
  }
1969
- export {
1970
- pioneer
1971
- };
1972
- //# sourceMappingURL=index.js.map
1610
+ //#endregion
1611
+ export { pioneer };
1612
+
1613
+ //# sourceMappingURL=index.js.map