@open-pioneer/vite-plugin-pioneer 7.1.2 → 7.2.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,24 +1,24 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { readFile, realpath, stat } from "node:fs/promises";
2
2
  import { dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
3
3
  import { cwd } from "node:process";
4
- import { BUILD_CONFIG_NAME, PackageMetadataV1, RuntimeSupport, createPackageConfigFromBuildConfig, createPackageConfigFromPackageMetadata, loadBuildConfig } from "@open-pioneer/build-common";
4
+ import { BUILD_CONFIG_NAME, PackageMetadataV1, RuntimeSupport, copyPublicAssetDirectory, createPackageConfigFromBuildConfig, createPackageConfigFromPackageMetadata, loadBuildConfig } from "@open-pioneer/build-common";
5
5
  import { normalizePath } from "vite";
6
6
  import { existsSync } from "fs";
7
7
  import posix$1, { basename, dirname as dirname$1, posix as posix$2 } from "node:path/posix";
8
8
  import { join as join$1 } from "path/posix";
9
9
  import { print } from "esrap";
10
10
  import ts from "esrap/languages/ts";
11
- import { readFile as readFile$1, realpath } from "fs/promises";
11
+ import { readFile as readFile$1, realpath as realpath$1 } from "fs/promises";
12
12
  import { basename as basename$1, dirname as dirname$2, posix as posix$3 } from "path";
13
- import { ResolverFactory } from "oxc-resolver";
14
13
  import { glob } from "tinyglobby";
14
+ import { findDepPkgJsonPath } from "vitefu";
15
15
  import pkg from "debug";
16
16
  import * as fs from "node:fs";
17
17
  import { existsSync as existsSync$1 } from "node:fs";
18
- import { findDepPkgJsonPath } from "vitefu";
19
18
  import { load } from "js-yaml";
20
19
  import { z } from "zod";
21
20
  import { createErrorMap, fromZodError } from "zod-validation-error";
21
+ import sirv from "sirv";
22
22
  // src/codegen/shared.ts
23
23
  /**
24
24
  * MODULE ID ENCODING
@@ -30,6 +30,12 @@ import { createErrorMap, fromZodError } from "zod-validation-error";
30
30
  * This is used for "global" modules that are not scoped to a specific file, app or package.
31
31
  * This encoding is the usual practice in the rollup / vite ecosystem, making it very reliable.
32
32
  * It has the disadvantage that the generated files show up "somewhere" in the browser debugger.
33
+ *
34
+ * The assets module of a package that passes through vite's dependency optimizer also uses
35
+ * this scheme, e.g. `\0open-pioneer:package-assets:/path/to/package`.
36
+ * That id is written into the optimized bundle, where a magic filename outside the root
37
+ * cannot be told apart from a root-relative URL.
38
+ *
33
39
  * 2. Magic filenames, e.g. /path/to/app/@@open-pioneer-app.
34
40
  * These use a different prefix ("@@") for file names so they show up next to the relevant location,
35
41
  * for example as if they were developed in a specific package.
@@ -56,6 +62,8 @@ const TEST_SUPPORT_MODULE = "@@open-pioneer-test-support";
56
62
  const TEST_SUPPORT_LOCALE_RE = /[?&]locale=(?<locale>.*?)(?:$|&)/;
57
63
  const SOURCE_INFO_MODULE = "@@open-pioneer-source-info";
58
64
  const SOURCE_INFO_MODULE_MODULE_PATH_RE = /@@open-pioneer-source-info\/(?<module_path>.*)&lang=js$/;
65
+ const PACKAGE_ASSETS_MODULE = "@@open-pioneer-assets";
66
+ const OPTIMIZED_PACKAGE_ASSETS_SUFFIX = "package-assets:";
59
67
  const SOURCE_FILE_RE = /^(.*?)(?:\?|$)/;
60
68
  /**
61
69
  * Filter for rolldown.
@@ -80,7 +88,12 @@ function parseVirtualModuleId(inputModuleId) {
80
88
  if (moduleId.startsWith("\0")) {
81
89
  const virtualPrefixMatch = inputModuleId.match(VIRTUAL_PREFIX_RE);
82
90
  if (virtualPrefixMatch) {
83
- if (virtualPrefixMatch.groups?.["suffix"] === "deployment") return { type: "deployment" };
91
+ const suffix = virtualPrefixMatch.groups?.["suffix"];
92
+ if (suffix === "deployment") return { type: "deployment" };
93
+ if (suffix?.startsWith(OPTIMIZED_PACKAGE_ASSETS_SUFFIX)) return {
94
+ type: "package-assets",
95
+ packageDirectory: suffix.slice(15)
96
+ };
84
97
  }
85
98
  return;
86
99
  }
@@ -91,6 +104,10 @@ function parseVirtualModuleId(inputModuleId) {
91
104
  type: "package-hooks",
92
105
  packageDirectory: dirname$1(sourceFile)
93
106
  };
107
+ if (base === PACKAGE_ASSETS_MODULE) return {
108
+ type: "package-assets",
109
+ packageDirectory: dirname$1(sourceFile)
110
+ };
94
111
  if (base === TEST_SUPPORT_MODULE) return {
95
112
  type: "test-support",
96
113
  packageDirectory: dirname$1(sourceFile),
@@ -160,6 +177,7 @@ function serializeModuleId(mod) {
160
177
  case "app-i18n-index": return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_INDEX_QUERY}`;
161
178
  case "app-i18n": return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_QUERY}&locale=${mod.locale}`;
162
179
  case "deployment": return `${VIRTUAL_PREFIX}deployment`;
180
+ case "package-assets": return `${mod.packageDirectory}/${PACKAGE_ASSETS_MODULE}`;
163
181
  case "test-support": {
164
182
  let result = `${mod.packageDirectory}/${TEST_SUPPORT_MODULE}`;
165
183
  if (mod.locale) result += `?locale=${mod.locale}`;
@@ -167,6 +185,15 @@ function serializeModuleId(mod) {
167
185
  }
168
186
  }
169
187
  }
188
+ /**
189
+ * Returns the id of the assets module for an import inside an optimized dependency.
190
+ * It parses to the same module as the magic filename that `serializeModuleId` returns.
191
+ */
192
+ function serializeOptimizedVirtualModuleId(mod) {
193
+ switch (mod.kind) {
194
+ case "package-assets": return `${VIRTUAL_PREFIX}${OPTIMIZED_PACKAGE_ASSETS_SUFFIX}${mod.packageDirectory}`;
195
+ }
196
+ }
170
197
  function serializeSourceInfoModule(mod) {
171
198
  const packageDirectory = mod.packageDirectory;
172
199
  const modulePath = mod.modulePath;
@@ -640,6 +667,24 @@ function referenceObject(ref) {
640
667
  function optionalString(value) {
641
668
  return value == null ? undefinedValue() : literal(value);
642
669
  }
670
+ // src/codegen/generatePublicAssetsModule.ts
671
+ /**
672
+ * Returns the module content to implement the `open-pioneer:assets` module.
673
+ *
674
+ * `packageDir` is the package's asset directory relative to the base URL.
675
+ * It may contain any number of slashes, and ends with a slash.
676
+ */
677
+ function generatePublicAssetsModule(packageDir) {
678
+ if (!packageDir.endsWith("/")) throw new Error("The package directory must end with '/'");
679
+ return `
680
+ import { baseUrl } from "open-pioneer:deployment";
681
+
682
+ export const publicAssetsUrl = new URL(${JSON.stringify(packageDir)}, baseUrl).href;
683
+ export function getPublicAssetUrl(localAssetPath) {
684
+ return new URL(localAssetPath, publicAssetsUrl).href;
685
+ }
686
+ `.trim();
687
+ }
643
688
  // src/codegen/generateTestSupport.ts
644
689
  /**
645
690
  * Generates the `open-pioneer:test-support` module for a package.
@@ -724,9 +769,9 @@ function createMetadataContextFromRolldown(ctx) {
724
769
  };
725
770
  }
726
771
  // src/utils/debug.ts
727
- const { debug: debug$5 } = pkg;
772
+ const { debug: debug$6 } = pkg;
728
773
  function createDebugger(namespace) {
729
- const logger = debug$5(namespace);
774
+ const logger = debug$6(namespace);
730
775
  return function debugFunction(...args) {
731
776
  logger(...args);
732
777
  };
@@ -747,9 +792,45 @@ function isInDirectory(candidate, directory) {
747
792
  }
748
793
  // src/utils/package.ts
749
794
  const PACKAGE_NAME = "@open-pioneer/vite-plugin-pioneer";
795
+ // src/metadata/resolvePublicAssetDir.ts
796
+ /**
797
+ * Resolves one public asset directory of the package in `packageDir` to an absolute real path.
798
+ */
799
+ async function resolvePublicAssetDir(packageName, packageDir, entry) {
800
+ let path;
801
+ let src;
802
+ switch (entry.type) {
803
+ case "local":
804
+ src = entry.src;
805
+ path = resolve(packageDir, entry.src);
806
+ break;
807
+ case "dependency": {
808
+ src = `${entry.packageName}/${entry.src}`;
809
+ const packageJsonPath = await findDepPkgJsonPath(entry.packageName, packageDir);
810
+ if (!packageJsonPath) throw new ReportableError(`Failed to find package '${entry.packageName}' for the public asset directory '${src}' of package '${packageName}'. Is the dependency installed correctly?`);
811
+ path = resolve(dirname(packageJsonPath), entry.src);
812
+ break;
813
+ }
814
+ }
815
+ let directory;
816
+ try {
817
+ directory = await realpath(path);
818
+ } catch (e) {
819
+ const problem = isNotFoundError(e) ? "does not exist" : "cannot be read";
820
+ throw new ReportableError(`The public asset directory '${src}' of package '${packageName}' ${problem}: ${path}`, { cause: e });
821
+ }
822
+ if (!(await stat(directory)).isDirectory()) throw new ReportableError(`The public asset directory '${src}' of package '${packageName}' is not a directory: ${directory}`);
823
+ return {
824
+ directory,
825
+ dest: entry.dest
826
+ };
827
+ }
828
+ function isNotFoundError(e) {
829
+ return e instanceof Error && "code" in e && e.code === "ENOENT";
830
+ }
750
831
  // src/metadata/loadPackageMetadata.ts
751
- const isDebug$4 = !!process.env.DEBUG;
752
- const debug$4 = createDebugger("open-pioneer:metadata");
832
+ const isDebug$5 = !!process.env.DEBUG;
833
+ const debug$5 = createDebugger("open-pioneer:metadata");
753
834
  /**
754
835
  * This function is called to read a package's metadata during build
755
836
  * (for source and published packages).
@@ -784,7 +865,7 @@ var PackageMetadataReader = class {
784
865
  const packageJsonPath = this.#packageJsonPath;
785
866
  const sourceRoot = this.#sourceRoot;
786
867
  const mode = isSourcePackage(packageDir, sourceRoot) ? "source" : "published";
787
- isDebug$4 && debug$4(`Visiting package directory ${packageDir} in mode ${mode}.`);
868
+ isDebug$5 && debug$5(`Visiting package directory ${packageDir} in mode ${mode}.`);
788
869
  ctx.addWatchFile(packageJsonPath);
789
870
  const { name: packageName, version: packageVersion, dependencies, packageMetadata } = await parsePackageJson(packageJsonPath);
790
871
  const configResult = await this.#readConfig(mode, packageName, packageMetadata);
@@ -815,6 +896,7 @@ var PackageMetadataReader = class {
815
896
  }
816
897
  if (!cssFile) throw new ReportableError(`Failed to find css file '${config.styles}' in ${packageDir}`);
817
898
  }
899
+ const publicAssets = await resolvePublicAssetDirs(packageName, packageDir, config.publicAssets);
818
900
  const i18nPaths = /* @__PURE__ */ new Map();
819
901
  for (const locale of config.languages) {
820
902
  if (i18nPaths.has(locale)) throw new ReportableError(`Locale '${locale}' was defined twice in ${configPath}`);
@@ -830,6 +912,7 @@ var PackageMetadataReader = class {
830
912
  servicesModuleId,
831
913
  servicesModulePath,
832
914
  cssFilePath: cssFile,
915
+ publicAssets,
833
916
  i18nPaths,
834
917
  get locales() {
835
918
  return Array.from(i18nPaths.keys());
@@ -966,16 +1049,20 @@ async function resolveLocalFile(ctx, packageDir, packageName, localModuleId) {
966
1049
  if (!localModuleId.startsWith("./")) localModuleId = `./${localModuleId}`;
967
1050
  return await ctx.resolveLocalFile(localModuleId, packageName, packageDir);
968
1051
  }
1052
+ async function resolvePublicAssetDirs(packageName, packageDir, publicAssets) {
1053
+ const directories = await Promise.all(publicAssets.map((entry) => resolvePublicAssetDir(packageName, packageDir, entry)));
1054
+ if (isDebug$5) for (const { directory, dest } of directories) debug$5("Package %s serves %s as public assets at '%s'", packageName, directory, dest || ".");
1055
+ return directories;
1056
+ }
969
1057
  const NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
970
1058
  function isSourcePackage(file, sourceDir) {
971
1059
  return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);
972
1060
  }
973
1061
  // src/metadata/findTrailsPackages.ts
974
- const isDebug$3 = !!process.env.DEBUG;
975
- const debug$3 = createDebugger("open-pioneer:metadata");
1062
+ const isDebug$4 = !!process.env.DEBUG;
1063
+ const debug$4 = createDebugger("open-pioneer:metadata");
976
1064
  async function findTrailsPackages(sourceRoot) {
977
1065
  const ctx = createDummyContext();
978
- const packageResolver = ResolverFactory.default();
979
1066
  const localPackageJsonFiles = await glob("**/package.json", {
980
1067
  cwd: sourceRoot,
981
1068
  absolute: true,
@@ -1001,8 +1088,8 @@ async function findTrailsPackages(sourceRoot) {
1001
1088
  if (pkg.type === "plain") continue;
1002
1089
  trailsPackages.push(pkg);
1003
1090
  for (const dependency of pkg.dependencies) {
1004
- const depResult = await packageResolver.async(packageDirectory, dependency.packageName + "/package.json");
1005
- if (depResult.path) visit(await realpath(dirname$2(depResult.path)));
1091
+ const depPackageJsonPath = await findDepPkgJsonPath(dependency.packageName, packageDirectory);
1092
+ if (depPackageJsonPath) visit(dirname$2(await realpath$1(depPackageJsonPath)));
1006
1093
  }
1007
1094
  }
1008
1095
  trailsPackages.sort((p1, p2) => p1.name.localeCompare(p2.name, "en"));
@@ -1015,7 +1102,7 @@ function createDummyContext() {
1015
1102
  return posix$3.join(packageName, moduleId);
1016
1103
  },
1017
1104
  warn(message) {
1018
- isDebug$3 && debug$3("Problem during trails package discovery: %s", message);
1105
+ isDebug$4 && debug$4("Problem during trails package discovery: %s", message);
1019
1106
  }
1020
1107
  };
1021
1108
  }
@@ -1156,8 +1243,8 @@ function gatherOverrides(data) {
1156
1243
  return overrides;
1157
1244
  }
1158
1245
  // src/metadata/MetadataRepository.ts
1159
- const isDebug$2 = !!process.env.DEBUG;
1160
- const debug$2 = createDebugger("open-pioneer:metadata");
1246
+ const isDebug$3 = !!process.env.DEBUG;
1247
+ const debug$3 = createDebugger("open-pioneer:metadata");
1161
1248
  /**
1162
1249
  * Provides metadata about apps and packages.
1163
1250
  * Metadata is read from disk on demand and will then be cached
@@ -1166,6 +1253,7 @@ const debug$2 = createDebugger("open-pioneer:metadata");
1166
1253
  var MetadataRepository = class {
1167
1254
  #sourceRoot;
1168
1255
  #packageMetadataCache;
1256
+ #packagesByName = /* @__PURE__ */ new Map();
1169
1257
  #i18nCache;
1170
1258
  /**
1171
1259
  * @param sourceRoot Source folder on disk, needed to detect source packages
@@ -1176,6 +1264,7 @@ var MetadataRepository = class {
1176
1264
  this.#i18nCache = this.#createI18nCache();
1177
1265
  }
1178
1266
  reset() {
1267
+ this.#packagesByName.clear();
1179
1268
  this.#packageMetadataCache = this.#createPackageMetadataCache();
1180
1269
  this.#i18nCache = this.#createI18nCache();
1181
1270
  }
@@ -1188,6 +1277,19 @@ var MetadataRepository = class {
1188
1277
  this.#i18nCache.invalidate(path);
1189
1278
  }
1190
1279
  /**
1280
+ * Returns the metadata of the Trails package named `packageName`, if it has already been loaded.
1281
+ * It is not loaded on demand, because the package's location is only known from a dependency graph.
1282
+ */
1283
+ getLoadedPackage(packageName) {
1284
+ return this.#packagesByName.get(packageName);
1285
+ }
1286
+ /**
1287
+ * Returns the metadata of all Trails packages that have been loaded since the last reset.
1288
+ */
1289
+ getLoadedPackages() {
1290
+ return Array.from(this.#packagesByName.values());
1291
+ }
1292
+ /**
1191
1293
  * Returns the combined application metadata of the app in `appDirectory`.
1192
1294
  * Starting from the app's package.json, dependencies will be visited recursively.
1193
1295
  *
@@ -1195,7 +1297,7 @@ var MetadataRepository = class {
1195
1297
  * will be returned here.
1196
1298
  */
1197
1299
  async getAppMetadata(ctx, appDirectory) {
1198
- isDebug$2 && debug$2(`Request for app metadata of ${appDirectory}`);
1300
+ isDebug$3 && debug$3(`Request for app metadata of ${appDirectory}`);
1199
1301
  const graph = await this.#analyzeDependencyGraph(ctx, appDirectory);
1200
1302
  if (!graph) throw new ReportableError(`Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid source package.`);
1201
1303
  const { rootPackage: appPackage, packages } = graph;
@@ -1210,13 +1312,14 @@ var MetadataRepository = class {
1210
1312
  };
1211
1313
  }
1212
1314
  /**
1213
- * Returns the dependency graph of the package in `packageDirectory` that imports `open-pioneer:test-support`.
1315
+ * Returns the dependency graph of the package in `packageDirectory`, which imports `importedModule`.
1214
1316
  * The package is not an app, so none of the app-only checks (such as the runtime metadata version) run.
1317
+ * `importedModule` only names the module in the error for a plain package.
1215
1318
  */
1216
- async getTestSupportMetadata(ctx, packageDirectory) {
1217
- isDebug$2 && debug$2(`Request for test support metadata of ${packageDirectory}`);
1319
+ async getTestDependencyGraph(ctx, packageDirectory, importedModule) {
1320
+ isDebug$3 && debug$3(`Request for the test dependency graph of package at ${packageDirectory}`);
1218
1321
  const graph = await this.#analyzeDependencyGraph(ctx, packageDirectory);
1219
- if (!graph) throw new ReportableError(`'open-pioneer:test-support' can only be imported from a Trails package. The package in ${packageDirectory} has neither a ${BUILD_CONFIG_NAME} nor package metadata.`);
1322
+ if (!graph) throw new ReportableError(`'${importedModule}' can only be imported from a Trails package. The package in ${packageDirectory} has neither a ${BUILD_CONFIG_NAME} nor package metadata.`);
1220
1323
  return graph;
1221
1324
  }
1222
1325
  /**
@@ -1245,7 +1348,7 @@ var MetadataRepository = class {
1245
1348
  if (!packageSeenByDirectory.has(packageMetadata.directory)) {
1246
1349
  packageSeenByDirectory.add(packageMetadata.directory);
1247
1350
  await visitDependencies(packageMetadata.dependencies, packageMetadata.packageJsonPath);
1248
- } else isDebug$2 && debug$2(`Skipping already visited package at %s`, packageMetadata.directory);
1351
+ } else isDebug$3 && debug$3(`Skipping already visited package at %s`, packageMetadata.directory);
1249
1352
  });
1250
1353
  return await Promise.all(jobs);
1251
1354
  };
@@ -1259,14 +1362,14 @@ var MetadataRepository = class {
1259
1362
  * Returns package metadata associated with the given package.
1260
1363
  */
1261
1364
  async #getPackageMetadata(ctx, loc) {
1262
- isDebug$2 && debug$2(`Request for package metadata of ${formatPackageLocation(loc)}`);
1365
+ isDebug$3 && debug$3(`Request for package metadata of ${formatPackageLocation(loc)}`);
1263
1366
  const packageDir = await this.#resolvePackageLocation(loc);
1264
1367
  if (!packageDir) return;
1265
1368
  const importedFrom = loc.type === "absolute" ? void 0 : loc.importedFrom;
1266
1369
  const entry = await this.#packageMetadataCache.get(packageDir, ctx, importedFrom);
1267
1370
  propagateWatchFiles(entry.watchFiles, ctx);
1268
1371
  if (entry.metadata.type === "plain") {
1269
- isDebug$2 && debug$2(`Skipping package '${packageDir}'.`);
1372
+ isDebug$3 && debug$3(`Skipping package '${packageDir}'.`);
1270
1373
  return;
1271
1374
  }
1272
1375
  return entry.metadata;
@@ -1280,18 +1383,18 @@ var MetadataRepository = class {
1280
1383
  return i18n;
1281
1384
  }
1282
1385
  async #resolvePackageLocation(loc) {
1283
- if (loc.type === "absolute") return await realpath(loc.directory);
1386
+ if (loc.type === "absolute") return await realpath$1(loc.directory);
1284
1387
  const { packageName, optional } = loc.dependency;
1285
1388
  const packagePath = await findDepPkgJsonPath(packageName, loc.importedFrom);
1286
1389
  if (!packagePath) {
1287
1390
  if (optional) {
1288
- isDebug$2 && debug$2(`Optional package '${packageName}' was not found.`);
1391
+ isDebug$3 && debug$3(`Optional package '${packageName}' was not found.`);
1289
1392
  return;
1290
1393
  }
1291
1394
  throw new ReportableError(`Failed to find package '${packageName}' (from '${loc.importedFrom}'), is the dependency installed correctly?`);
1292
1395
  }
1293
- const packageDir = dirname$2(await realpath(packagePath));
1294
- isDebug$2 && debug$2(`Found package '${packageName}' at ${packageDir}`);
1396
+ const packageDir = dirname$2(await realpath$1(packagePath));
1397
+ isDebug$3 && debug$3(`Found package '${packageName}' at ${packageDir}`);
1295
1398
  return packageDir;
1296
1399
  }
1297
1400
  #createI18nCache() {
@@ -1300,7 +1403,7 @@ var MetadataRepository = class {
1300
1403
  return normalizePath(path);
1301
1404
  },
1302
1405
  async getValue(path, ctx) {
1303
- isDebug$2 && debug$2(`Loading i18n file ${path}`);
1406
+ isDebug$3 && debug$3(`Loading i18n file ${path}`);
1304
1407
  ctx.addWatchFile(path);
1305
1408
  return {
1306
1409
  i18n: await loadI18nFile(path),
@@ -1308,22 +1411,22 @@ var MetadataRepository = class {
1308
1411
  };
1309
1412
  },
1310
1413
  onInvalidate(path) {
1311
- isDebug$2 && debug$2(`Removed cache entry for i18n file ${path}`);
1414
+ isDebug$3 && debug$3(`Removed cache entry for i18n file ${path}`);
1312
1415
  },
1313
1416
  onCachedReturn(path) {
1314
- isDebug$2 && debug$2(`Returning cached entry for i18n file ${path}`);
1417
+ isDebug$3 && debug$3(`Returning cached entry for i18n file ${path}`);
1315
1418
  }
1316
1419
  });
1317
1420
  }
1318
1421
  #createPackageMetadataCache() {
1319
1422
  const sourceRoot = this.#sourceRoot;
1423
+ const packagesByName = this.#packagesByName;
1320
1424
  return new Cache({
1321
- _byName: /* @__PURE__ */ new Map(),
1322
1425
  getId(directory) {
1323
1426
  return normalizePath(directory);
1324
1427
  },
1325
1428
  async getValue(directory, ctx, importedFrom) {
1326
- isDebug$2 && debug$2(`Loading metadata for package at ${directory} (imported from ${importedFrom ?? "N/A"})`);
1429
+ isDebug$3 && debug$3(`Loading metadata for package at ${directory} (imported from ${importedFrom ?? "N/A"})`);
1327
1430
  const watchFiles = /* @__PURE__ */ new Set();
1328
1431
  const metadata = await loadPackageMetadata({
1329
1432
  resolveLocalFile: ctx.resolveLocalFile.bind(ctx),
@@ -1336,11 +1439,11 @@ var MetadataRepository = class {
1336
1439
  sourceRoot,
1337
1440
  importedFrom
1338
1441
  });
1339
- isDebug$2 && debug$2(`Metadata for '${metadata.name}': %O`, metadata);
1442
+ isDebug$3 && debug$3(`Metadata for '${metadata.name}': %O`, metadata);
1340
1443
  if (metadata.type === "pioneer-package") {
1341
- const existingMetadata = this._byName.get(metadata.name);
1444
+ const existingMetadata = packagesByName.get(metadata.name);
1342
1445
  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)}`);
1343
- this._byName.set(metadata.name, metadata);
1446
+ packagesByName.set(metadata.name, metadata);
1344
1447
  }
1345
1448
  return {
1346
1449
  metadata,
@@ -1348,11 +1451,11 @@ var MetadataRepository = class {
1348
1451
  };
1349
1452
  },
1350
1453
  onInvalidate(directory, entry) {
1351
- isDebug$2 && debug$2(`Removed cache entry for '${entry.metadata.name}'`);
1352
- this._byName.delete(entry.metadata.name);
1454
+ isDebug$3 && debug$3(`Removed cache entry for '${entry.metadata.name}'`);
1455
+ packagesByName.delete(entry.metadata.name);
1353
1456
  },
1354
1457
  onCachedReturn(directory, entry) {
1355
- isDebug$2 && debug$2(`Returning cached metadata for '${entry.metadata.name}'`);
1458
+ isDebug$3 && debug$3(`Returning cached metadata for '${entry.metadata.name}'`);
1356
1459
  }
1357
1460
  });
1358
1461
  }
@@ -1368,7 +1471,7 @@ function detectRuntimeMetadataVersion(packages) {
1368
1471
  case "unsupported-version": throw new ReportableError(`Runtime metadata version ${metadataVersion} of ${runtimePackage.name} is not supported.
1369
1472
  This plugin supports versions ^${RuntimeSupport.CURRENT_METADATA_MAJOR}.`);
1370
1473
  }
1371
- isDebug$2 && debug$2("Detected runtime version %s", versionResult);
1474
+ isDebug$3 && debug$3("Detected runtime version %s", versionResult);
1372
1475
  return versionResult;
1373
1476
  }
1374
1477
  function propagateWatchFiles(watchFiles, ctx) {
@@ -1398,12 +1501,12 @@ function formatPackage(packageMetadata) {
1398
1501
  return str;
1399
1502
  }
1400
1503
  // src/metadata/validateI18nConfig.ts
1401
- const isDebug$1 = !!process.env.DEBUG;
1402
- const debug$1 = createDebugger("open-pioneer:validateI18nConfig");
1504
+ const isDebug$2 = !!process.env.DEBUG;
1505
+ const debug$2 = createDebugger("open-pioneer:validateI18nConfig");
1403
1506
  async function validateI18nConfig(ctx, repository, appMetadata) {
1404
1507
  const locales = appMetadata.locales;
1405
1508
  for (const pkg of appMetadata.packages) {
1406
- isDebug$1 && debug$1("Checking i18n files of package %s", pkg.name);
1509
+ isDebug$2 && debug$2("Checking i18n files of package %s", pkg.name);
1407
1510
  await checkPackageI18nFiles(ctx, pkg, locales);
1408
1511
  }
1409
1512
  await checkAppI18n(ctx, repository, appMetadata);
@@ -1412,13 +1515,13 @@ async function checkPackageI18nFiles(ctx, pkg, locales) {
1412
1515
  for (const locale of locales) {
1413
1516
  const filePath = pkg.i18nPaths.get(locale);
1414
1517
  if (!filePath) {
1415
- isDebug$1 && debug$1("Package does not support locale '%s'", locale);
1518
+ isDebug$2 && debug$2("Package does not support locale '%s'", locale);
1416
1519
  continue;
1417
1520
  }
1418
- isDebug$1 && debug$1("Checking i18n file %s", filePath);
1521
+ isDebug$2 && debug$2("Checking i18n file %s", filePath);
1419
1522
  ctx.addWatchFile(filePath);
1420
1523
  if (!await fileExists(filePath)) throw new ReportableError(`I18n file in package '${pkg.name}' for locale '${locale}' does not exist: '${filePath}'.`);
1421
- else isDebug$1 && debug$1("i18n file %s exists", filePath);
1524
+ else isDebug$2 && debug$2("i18n file %s exists", filePath);
1422
1525
  }
1423
1526
  }
1424
1527
  async function checkAppI18n(ctx, repository, appMetadata) {
@@ -1454,6 +1557,125 @@ async function checkAppI18n(ctx, repository, appMetadata) {
1454
1557
  const formattedPackageErrors = getPackageErrors();
1455
1558
  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}.`);
1456
1559
  }
1560
+ // src/publicAssets/constants.ts
1561
+ /** The directory below the output root that holds the public assets of all packages in an app build. */
1562
+ const PACKAGE_ASSETS_DIR = "packages";
1563
+ /** The URL segment below the base URL that holds the public assets of all packages in the dev server. */
1564
+ const PUBLIC_ASSETS_URL_PREFIX = "@package-assets";
1565
+ // src/publicAssets/packageSlug.ts
1566
+ const SCOPE_SEPARATOR = "~";
1567
+ /**
1568
+ * Encodes a package name as a single URL path segment.
1569
+ *
1570
+ * - Unscoped package names are returned unchanged.
1571
+ * - Scoped package names are escaped to produce a single file name: `@scope/name` --> `scope~name`.
1572
+ */
1573
+ function packageNameToSlug(packageName) {
1574
+ if (!packageName.startsWith("@")) return packageName;
1575
+ return packageName.slice(1).replace("/", SCOPE_SEPARATOR);
1576
+ }
1577
+ /**
1578
+ * Reverses {@link packageNameToSlug}.
1579
+ */
1580
+ function slugToPackageName(slug) {
1581
+ if (!slug.includes(SCOPE_SEPARATOR)) return slug;
1582
+ return "@" + slug.replace(SCOPE_SEPARATOR, "/");
1583
+ }
1584
+ // src/publicAssets/copyPublicAssets.ts
1585
+ /**
1586
+ * Copies the public assets of `packages` to `<outDir>/packages/<packageSlug>/`.
1587
+ */
1588
+ async function copyPublicAssets({ packages, outDir }) {
1589
+ const packagesWithAssets = packages.filter((pkg) => pkg.publicAssets.length > 0);
1590
+ await Promise.all(packagesWithAssets.map((pkg) => copyPackageAssets(pkg, outDir)));
1591
+ }
1592
+ async function copyPackageAssets(pkg, outDir) {
1593
+ const packageDir = join(outDir, PACKAGE_ASSETS_DIR, packageNameToSlug(pkg.name));
1594
+ for (const { directory, dest } of pkg.publicAssets.toReversed()) await copyPublicAssetDirectory(directory, join(packageDir, dest));
1595
+ }
1596
+ // src/publicAssets/servePublicAssets.ts
1597
+ const isDebug$1 = !!process.env.DEBUG;
1598
+ const debug$1 = createDebugger("open-pioneer:public-assets");
1599
+ /**
1600
+ * Serves public package assets in the dev server.
1601
+ *
1602
+ * Packages are looked up in the metadata repository, so a package must be loaded there when the request arrives.
1603
+ * This works because the page loads the code of a package before it requests the package's assets,
1604
+ * and loading the code loads the metadata.
1605
+ *
1606
+ * Files are read on request, so the middleware neither scans nor watches the directories.
1607
+ */
1608
+ function createPublicAssetsMiddleware(repository, base) {
1609
+ const prefix = base + "@package-assets/";
1610
+ const handlers = /* @__PURE__ */ new Map();
1611
+ const getHandler = (directory) => {
1612
+ let handler = handlers.get(directory);
1613
+ if (!handler) {
1614
+ handler = sirv(directory, {
1615
+ dev: true,
1616
+ etag: true,
1617
+ extensions: []
1618
+ });
1619
+ handlers.set(directory, handler);
1620
+ }
1621
+ return handler;
1622
+ };
1623
+ isDebug$1 && debug$1("Serving public assets below %s", prefix);
1624
+ return (req, res, next) => {
1625
+ const url = req.url;
1626
+ if (req.method !== "GET" && req.method !== "HEAD" || !url?.startsWith(prefix)) return next();
1627
+ let path;
1628
+ try {
1629
+ path = decodeURI(url.slice(prefix.length).replace(/[?#].*$/, ""));
1630
+ } catch {
1631
+ isDebug$1 && debug$1("Rejecting %s: the path is not a valid URI", url);
1632
+ return replyWithStatus(res, 400, "Bad request: invalid path");
1633
+ }
1634
+ const [slug, ...assetPath] = path.split(/[/\\]/).filter((segment) => segment !== "");
1635
+ if (!slug || assetPath.length === 0) {
1636
+ isDebug$1 && debug$1("Rejecting %s: the path names no file of a package", url);
1637
+ return replyWithStatus(res, 404, "File not found");
1638
+ }
1639
+ const packageName = slugToPackageName(slug);
1640
+ const directories = repository.getLoadedPackage(packageName)?.publicAssets;
1641
+ if (!directories) {
1642
+ isDebug$1 && debug$1("Rejecting %s: package %s has not been loaded (yet)", url, packageName);
1643
+ return replyWithStatus(res, 404, "Package assets not found");
1644
+ }
1645
+ const candidates = findCandidates(directories, assetPath);
1646
+ const serveCandidate = (index) => {
1647
+ const candidate = candidates[index];
1648
+ if (!candidate) {
1649
+ isDebug$1 && debug$1("Rejecting %s: no public asset directory of package %s contains the file", url, packageName);
1650
+ return replyWithStatus(res, 404, "File not found");
1651
+ }
1652
+ req.url = "/" + candidate.path.map(encodeURI).join("/");
1653
+ getHandler(candidate.directory)(req, res, () => serveCandidate(index + 1));
1654
+ };
1655
+ serveCandidate(0);
1656
+ };
1657
+ }
1658
+ /**
1659
+ * Returns the directories that may contain the file.
1660
+ */
1661
+ function findCandidates(directories, segments) {
1662
+ const candidates = [];
1663
+ for (const { directory, dest } of directories) {
1664
+ const destSegments = dest === "" ? [] : dest.split("/");
1665
+ if (!destSegments.every((segment, i) => segments[i] === segment)) continue;
1666
+ const remainder = segments.slice(destSegments.length);
1667
+ if (remainder.length === 0 || remainder.some((s) => s.startsWith("."))) continue;
1668
+ candidates.push({
1669
+ directory,
1670
+ path: remainder
1671
+ });
1672
+ }
1673
+ return candidates;
1674
+ }
1675
+ function replyWithStatus(res, statusCode, message) {
1676
+ res.statusCode = statusCode;
1677
+ res.end(message);
1678
+ }
1457
1679
  // src/codegenPlugin.ts
1458
1680
  const isDebug = !!process.env.DEBUG;
1459
1681
  const debug = createDebugger("open-pioneer:codegen");
@@ -1464,6 +1686,7 @@ function codegenPlugin() {
1464
1686
  let resolvedRoot;
1465
1687
  let repository;
1466
1688
  let deploymentModule;
1689
+ let publicAssetsCopied = false;
1467
1690
  return {
1468
1691
  name: "pioneer:codegen",
1469
1692
  async config(userConfig, env) {
@@ -1477,6 +1700,9 @@ function codegenPlugin() {
1477
1700
  resolvedRoot = normalizePath(config.root);
1478
1701
  deploymentModule = new DeploymentModule(isDev, config.base);
1479
1702
  },
1703
+ configureServer(server) {
1704
+ server.middlewares.use(createPublicAssetsMiddleware(repository, server.config.base));
1705
+ },
1480
1706
  configureVitest(context) {
1481
1707
  context.defineCacheKeyGenerator(({ id }) => {
1482
1708
  if (parseVirtualModuleId(id)) return false;
@@ -1489,6 +1715,7 @@ function codegenPlugin() {
1489
1715
  },
1490
1716
  async buildStart() {
1491
1717
  repository?.reset();
1718
+ publicAssetsCopied = false;
1492
1719
  deploymentModule.onStart(this);
1493
1720
  },
1494
1721
  resolveId: {
@@ -1498,7 +1725,7 @@ function codegenPlugin() {
1498
1725
  if (!importer) return;
1499
1726
  if (moduleId.startsWith("/") && !moduleId.startsWith(resolvedRoot + "/") && MAGIC_FILENAME_RE.test(moduleId)) {
1500
1727
  const absoluteId = resolvedRoot + moduleId;
1501
- if (parseVirtualModuleId(absoluteId)) return absoluteId;
1728
+ if (await fileExists(absoluteId.slice(0, absoluteId.search(MAGIC_FILENAME_RE))) && parseVirtualModuleId(absoluteId)) return absoluteId;
1502
1729
  }
1503
1730
  if (parseVirtualModuleId(moduleId)) return moduleId;
1504
1731
  let virtualModule;
@@ -1523,6 +1750,10 @@ function codegenPlugin() {
1523
1750
  packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1524
1751
  });
1525
1752
  case "deployment": return serializeModuleId({ type: "deployment" });
1753
+ case "assets": return serializeModuleId({
1754
+ type: "package-assets",
1755
+ packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1756
+ });
1526
1757
  case "test-support":
1527
1758
  if (!isTestRun) throw new ReportableError("'open-pioneer:test-support' may only be imported from tests.");
1528
1759
  return serializeModuleId({
@@ -1554,13 +1785,20 @@ function codegenPlugin() {
1554
1785
  isDebug && debug("Generated hooks code: %O", generatedSourceCode);
1555
1786
  return jsModule(generatedSourceCode);
1556
1787
  }
1788
+ if (mod.type === "package-assets") {
1789
+ if (isTestRun) await repository.getTestDependencyGraph(createMetadataContextFromRolldown(this), dirname(packageJsonPath), "open-pioneer:assets");
1790
+ const packageName = await getPackageName(this, packageJsonPath);
1791
+ const generatedSourceCode = generatePublicAssetsModule(`${isDev ? PUBLIC_ASSETS_URL_PREFIX : PACKAGE_ASSETS_DIR}/${packageNameToSlug(packageName)}/`);
1792
+ isDebug && debug("Generated assets code: %O", generatedSourceCode);
1793
+ return jsModule(generatedSourceCode);
1794
+ }
1557
1795
  if (mod.type === "source-info") {
1558
1796
  const packageName = await getPackageName(this, packageJsonPath);
1559
1797
  return jsModule(RuntimeSupport.generateSourceInfo(packageName, mod.modulePath));
1560
1798
  }
1561
1799
  const ctx = createMetadataContextFromRolldown(this);
1562
1800
  if (mod.type === "test-support") {
1563
- const { rootPackage, packages } = await repository.getTestSupportMetadata(ctx, dirname(packageJsonPath));
1801
+ const { rootPackage, packages } = await repository.getTestDependencyGraph(ctx, dirname(packageJsonPath), "open-pioneer:test-support");
1564
1802
  const generatedSourceCode = await generateTestSupport({
1565
1803
  rootPackage,
1566
1804
  locale: mod.locale,
@@ -1620,6 +1858,18 @@ function codegenPlugin() {
1620
1858
  },
1621
1859
  generateBundle(_options, bundle) {
1622
1860
  deploymentModule.onGenerateBundle(bundle);
1861
+ },
1862
+ async writeBundle() {
1863
+ if (this.environment.name !== "client" || publicAssetsCopied) return;
1864
+ publicAssetsCopied = true;
1865
+ try {
1866
+ await copyPublicAssets({
1867
+ packages: repository.getLoadedPackages(),
1868
+ outDir: resolve(this.environment.config.root, this.environment.config.build.outDir)
1869
+ });
1870
+ } catch (e) {
1871
+ reportError(this, e, isDev);
1872
+ }
1623
1873
  }
1624
1874
  };
1625
1875
  }
@@ -1638,7 +1888,7 @@ async function resolvePackageJson(ctx, mod) {
1638
1888
  async function configureDevOptimizer(userConfig, rootDir) {
1639
1889
  return { optimizeDeps: {
1640
1890
  include: await getOptimizeDepsIncludes(rootDir),
1641
- rolldownOptions: { plugins: [createOptimizeDepsRolldownPlugin()] }
1891
+ rolldownOptions: { plugins: [createOptimizeDepsRolldownPlugin(rootDir)] }
1642
1892
  } };
1643
1893
  }
1644
1894
  /**
@@ -1665,17 +1915,27 @@ async function getOptimizeDepsIncludes(rootDir) {
1665
1915
  }
1666
1916
  /**
1667
1917
  * Creates a rolldown plugin for use during Vite's dependency optimization phase.
1668
- * It marks all `open-pioneer:*` virtual module imports as external so that they
1669
- * are left untouched by rolldown and can later be handled by the normal Vite plugin.
1918
+ * It marks all `open-pioneer:*` virtual module imports as external, so that the normal
1919
+ * Vite plugin handles them later.
1670
1920
  */
1671
- function createOptimizeDepsRolldownPlugin() {
1921
+ function createOptimizeDepsRolldownPlugin(rootDir) {
1672
1922
  return {
1673
1923
  name: "pioneer:optimize-deps",
1674
- resolveId(id) {
1675
- if (/^open-pioneer:/.test(id)) return {
1676
- id,
1677
- external: true
1678
- };
1924
+ resolveId: {
1925
+ filter: { id: /^open-pioneer:/ },
1926
+ handler(id, importer) {
1927
+ if (id === "open-pioneer:assets" && importer) return {
1928
+ id: serializeOptimizedVirtualModuleId({
1929
+ kind: "package-assets",
1930
+ packageDirectory: getPackageDirectoryFromImporter(importer, rootDir)
1931
+ }),
1932
+ external: true
1933
+ };
1934
+ return {
1935
+ id,
1936
+ external: true
1937
+ };
1938
+ }
1679
1939
  }
1680
1940
  };
1681
1941
  }