@open-pioneer/vite-plugin-pioneer 0.5.2 → 0.6.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,46 +1,938 @@
1
- "use strict";var Ne=Object.create;var L=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Le=Object.prototype.hasOwnProperty;var je=(e,t)=>{for(var n in t)L(e,n,{get:t[n],enumerable:!0})},Z=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of be(t))!Le.call(e,i)&&i!==n&&L(e,i,{get:()=>t[i],enumerable:!(r=Fe(t,i))||r.enumerable});return e};var w=(e,t,n)=>(n=e!=null?Ne(Oe(e)):{},Z(t||!e||!e.__esModule?L(n,"default",{value:e,enumerable:!0}):n,e)),Ve=e=>Z(L({},"__esModule",{value:!0}),e);var jt={};je(jt,{pioneer:()=>Lt});module.exports=Ve(jt);var we=require("node:fs"),A=require("node:path"),_=require("vite");var X=require("debug");function j(e){let t=(0,X.debug)(e);return function(...r){t(...r)}}var te=w(require("@babel/generator")),v=w(require("@babel/template")),c=w(require("@babel/types"));var u=class extends Error{};var V=class{existing=new Map;generate(t){let n=Ue(t),r=this.existing,i=r.get(n)??0;return r.set(n,i+1),i===0?n:`${n}_${i}`}};function Ue(e){let t=e.replace(/[^A-Za-z0-9_]+/g,"_");return t=t.replace(/[\d_]+$/,""),/^\d/.test(t)&&(t="_"+t),t||"var"}var ze=v.default.statement(`
1
+ // src/codegenPlugin.ts
2
+ import { existsSync } from "node:fs";
3
+ import { dirname as dirname3, join as join2 } from "node:path";
4
+ import { normalizePath as normalizePath3 } from "vite";
5
+
6
+ // src/utils/debug.ts
7
+ import { debug } from "debug";
8
+ function createDebugger(namespace) {
9
+ const logger = debug(namespace);
10
+ return function debugFunction(...args) {
11
+ logger(...args);
12
+ };
13
+ }
14
+
15
+ // src/codegen/generatePackagesMetadata.ts
16
+ import generate from "@babel/generator";
17
+ import template from "@babel/template";
18
+ import * as nodes from "@babel/types";
19
+
20
+ // src/ReportableError.ts
21
+ var ReportableError = class extends Error {
22
+ };
23
+
24
+ // src/codegen/IdGenerator.ts
25
+ var IdGenerator = class {
26
+ existing = /* @__PURE__ */ new Map();
27
+ /**
28
+ * Returns a unique identifier (in the context of this instance) that resembles the input value.
29
+ */
30
+ generate(input) {
31
+ const clean = cleanName(input);
32
+ const existing = this.existing;
33
+ const count = existing.get(clean) ?? 0;
34
+ existing.set(clean, count + 1);
35
+ return count === 0 ? clean : `${clean}_${count}`;
36
+ }
37
+ };
38
+ function cleanName(input) {
39
+ let clean = input.replace(/[^A-Za-z0-9_]+/g, "_");
40
+ clean = clean.replace(/[\d_]+$/, "");
41
+ if (/^\d/.test(clean)) {
42
+ clean = "_" + clean;
43
+ }
44
+ return clean || "var";
45
+ }
46
+
47
+ // src/codegen/generatePackagesMetadata.ts
48
+ var SERVICE_IMPORT = template.statement(`
2
49
  import { %%SERVICE_NAME%% as %%IMPORT_NAME%% } from %%IMPORT_SOURCE%%;
3
- `),De=v.default.expression(`
50
+ `);
51
+ var PKG_OBJECT = template.expression(`
4
52
  {
5
53
  name: %%PACKAGE_NAME%%,
6
54
  services: %%PACKAGE_SERVICES%%,
7
55
  ui: %%PACKAGE_UI%%,
8
56
  properties: %%PROPERTIES%%
9
57
  }
10
- `),Te=v.default.expression(`
58
+ `);
59
+ var SERVICE_OBJECT = template.expression(`
11
60
  {
12
61
  name: %%SERVICE_NAME%%,
13
62
  clazz: %%SERVICE_IMPORT%%,
14
63
  provides: %%SERVICE_INTERFACES%%,
15
64
  references: %%SERVICE_REFERENCES%%
16
65
  }
17
- `),Je=v.default.expression(`
66
+ `);
67
+ var INTERFACE_OBJECT = template.expression(`
18
68
  {
19
69
  name: %%INTERFACE_NAME%%,
20
70
  qualifier: %%QUALIFIER%%
21
71
  }
22
- `),Ge=v.default.expression(`
72
+ `);
73
+ var REFERENCE_OBJECT = template.expression(`
23
74
  {
24
75
  name: %%INTERFACE_NAME%%,
25
76
  qualifier: %%QUALIFIER%%,
26
77
  all: %%ALL%%
27
78
  }
28
- `),Ke=v.default.expression(`
79
+ `);
80
+ var UI_OBJECT = template.expression(`
29
81
  {
30
82
  references: %%UI_REFERENCES%%
31
83
  }
32
- `),Be=v.default.expression(`
84
+ `);
85
+ var PROPERTY_OBJECT = template.expression(`
33
86
  {
34
87
  value: %%VALUE%%,
35
88
  required: %%REQUIRED%%
36
89
  }
37
- `);function ne(e){let t=new V,n=c.objectExpression([]),r=[];for(let o of e){let a=We(o,{importServiceClass(s,p,d){let l=t.generate(s),g=ze({SERVICE_NAME:c.identifier(p),IMPORT_NAME:c.identifier(l),IMPORT_SOURCE:c.stringLiteral(d)});return r.push(g),l}});n.properties.push(c.objectProperty(c.stringLiteral(o.name),a))}let i=c.program([...r,c.exportDefaultDeclaration(n)]);return(0,te.default)(i).code}function We(e,t){let n=c.objectExpression([]);for(let a of e.config.services){if(!e.servicesModulePath)throw new u(`Package '${e.name}' must have a valid services module (typically 'services.ts' or 'services.js').
38
- The entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`);let s=t.importServiceClass(e.name+"_"+a.name,a.name,e.servicesModulePath),p=Te({SERVICE_NAME:c.stringLiteral(a.name),SERVICE_IMPORT:c.identifier(s),SERVICE_INTERFACES:c.arrayExpression(a.provides.map(d=>Je({INTERFACE_NAME:c.stringLiteral(d.name),QUALIFIER:d.qualifier==null?re():c.stringLiteral(d.qualifier)}))),SERVICE_REFERENCES:c.objectExpression(Object.entries(a.references).map(([d,l])=>c.objectProperty(c.stringLiteral(d),ee(l))))});n.properties.push(c.objectProperty(c.stringLiteral(a.name),p))}let r=Ke({UI_REFERENCES:c.arrayExpression(e.config.ui.references.map(a=>ee(a)))}),i=c.objectExpression(e.config.properties.map(a=>c.objectProperty(c.stringLiteral(a.name),Be({VALUE:K(a.defaultValue),REQUIRED:c.booleanLiteral(a.required)}))));return De({PACKAGE_NAME:c.stringLiteral(e.name),PACKAGE_SERVICES:n,PACKAGE_UI:r,PROPERTIES:i})}function K(e){if(e==null)return c.nullLiteral();if(typeof e=="string")return c.stringLiteral(e);if(typeof e=="number")return c.numericLiteral(e);if(typeof e=="boolean")return c.booleanLiteral(e);if(Array.isArray(e))return c.arrayExpression(e.map(t=>K(t)));if(typeof e=="object")return c.objectExpression(Object.entries(e).map(([t,n])=>c.objectProperty(c.stringLiteral(t),K(n))));throw new Error(`Unexpected value while serializing JSON: ${e}.`)}function ee(e){return Ge({INTERFACE_NAME:c.stringLiteral(e.name),QUALIFIER:e.qualifier?c.stringLiteral(e.qualifier):re(),ALL:c.booleanLiteral(e.all??!1)})}function re(){return c.unaryExpression("void",c.numericLiteral(0))}var N=require("fs/promises"),I=require("path"),R=require("vite");var U=w(require("node:fs")),z=require("node:path");function D(e){return U.promises.access(e,U.constants.F_OK).then(()=>!0).catch(()=>!1)}function ae(e,t){let n=(0,z.relative)(t,e);return!!(n&&!n.startsWith("..")&&!(0,z.isAbsolute)(n))}var $=class{values=new Map;jobs=new Map;provider;constructor(t){this.provider=t}invalidate(t){var i,o;let n=this.provider.getId(t),r=this.values.get(n);this.values.delete(n),this.jobs.delete(n),r&&((o=(i=this.provider).onInvalidate)==null||o.call(i,t,r))}async get(t,...n){var l;let r=this.provider,i=r.getId(t),o=this.values,a=o.get(i);if(a)return(l=r.onCachedReturn)==null||l.call(r,t,a),Promise.resolve(a);let s=this.jobs,p=s.get(i);if(p)return p;let d=r.getValue(t,...n);s.set(i,d);try{let g=await d;return s.get(i)===d&&o.set(i,g),g}finally{s.get(i)===d&&s.delete(i)}}};var ie=require("node:url"),T=require("@open-pioneer/build-common"),oe=require("node:path"),qe=0;async function se(e){let n=await import(`${(0,ie.pathToFileURL)(e)}?id=${++qe}`);if(!n||!n.default)throw new Error("The module must contain a default export.");let r=n.default;return Qe(r)}function Qe(e){let t=(0,T.verifyBuildConfig)(e);return Ye(t)}function ce(e){return(0,oe.basename)(e)===T.BUILD_CONFIG_NAME}function Ye(e){return{styles:e.styles,i18n:e.i18n,services:Object.entries(e.services??{}).map(([t,n])=>He(t,n)),servicesModule:e.servicesModule,ui:et(e.ui),properties:tt(e.properties,e.propertiesMeta)}}function He(e,t){return{name:e,provides:Ze(t.provides),references:Xe(t.references)}}function Ze(e){return e?typeof e=="string"?[{name:e}]:e.map(t=>typeof t=="string"?{name:t}:t):[]}function Xe(e){return e?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,de(n)])):{}}function de(e){return typeof e=="string"?{name:e}:e}function et(e){var t;return{references:((t=e==null?void 0:e.references)==null?void 0:t.map(de))??[]}}function tt(e,t){var r;let n=[];for(let[i,o]of Object.entries(e??{})){let a=((r=t==null?void 0:t[i])==null?void 0:r.required)??!1;n.push({name:i,defaultValue:o,required:a})}return n}var pe=require("fs/promises"),le=require("js-yaml"),x=require("zod"),ge=require("zod-validation-error");var B=x.z.lazy(()=>x.z.record(x.z.union([x.z.string(),B])).nullish()),nt=x.z.strictObject({messages:B.nullish().optional(),overrides:x.z.record(B).nullish().optional()}).nullish();async function ue(e){let t;try{t=await(0,pe.readFile)(e,"utf-8")}catch(n){throw new u(`Failed to read ${e}: ${n}`)}try{return rt(t)}catch(n){throw new u(`Failed to parse ${e}: ${n}`)}}function rt(e){let t=(0,le.load)(e);return at(t)}function at(e){let t=nt.safeParse(e);if(!t.success)throw(0,ge.fromZodError)(t.error);let n=t.data;return{messages:fe((n==null?void 0:n.messages)??void 0),overrides:it((n==null?void 0:n.overrides)??void 0)}}function fe(e){let t=new Map,n=[],r=o=>{for(let[a,s]of Object.entries(o))typeof s=="string"?i(a,s):s&&(n.push(a),r(s),n.pop())},i=(o,a)=>{let s=[...n,o].join(".");if(t.has(s))throw new Error(`Message '${s}' was already defined.`);t.set(s,a)};return e&&r(e),t}function it(e){let t=new Map;if(e)for(let[n,r]of Object.entries(e)){let i=fe(r??void 0);t.set(n,i)}return t}var W=require("@open-pioneer/build-common"),y=!!process.env.DEBUG,E=j("open-pioneer:metadata"),J=class{sourceRoot;packageMetadataCache;i18nCache;constructor(t){this.sourceRoot=t,this.packageMetadataCache=this.createPackageMetadataCache(),this.i18nCache=this.createI18nCache()}reset(){this.packageMetadataCache=this.createPackageMetadataCache(),this.i18nCache=this.createI18nCache()}onFileChanged(t){(gt(t)||ce(t))&&this.packageMetadataCache.invalidate((0,I.dirname)(t)),this.i18nCache.invalidate(t)}async getAppMetadata(t,n){y&&E(`Request for app metadata of ${n}`);let r=await this.getPackageMetadata(t,{type:"absolute",directory:n});if(!r)throw new u(`Failed to parse app metadata in ${n}. Ensure that the app is a valid local package.`);let i=Array.from(r.i18nPaths.keys()),o=new Map;o.set(r.name,r);let a=async(p,d)=>{let l=p.map(async g=>{let f=await this.getPackageMetadata(t,{type:"unresolved",packageName:g,importedFrom:d});f&&(o.has(f.name)||o.set(f.name,f),await a(f.dependencies,f.packageJsonPath))});return await Promise.all(l)};return await a(r.dependencies,r.packageJsonPath),{name:r.name,directory:r.directory,locales:i,packageJsonPath:r.packageJsonPath,packages:Array.from(o.values())}}async getPackageMetadata(t,n){y&&E(`Request for package metadata of ${ct(n)}`);let r=await this.resolvePackageLocation(t,n);if(!pt(r,this.sourceRoot)){y&&E(`Skipping non-local package '${r}'.`);return}let i=await this.packageMetadataCache.get(r,t);me(i.watchFiles,t);for(let o of i.warnings)t.warn(o);return i.metadata}async getI18nFile(t,n){let{i18n:r,watchFiles:i}=await this.i18nCache.get(n,t);return me(i,t),r}async resolvePackageLocation(t,n){if(n.type==="absolute")return await(0,N.realpath)(n.directory);let r=`${n.packageName}/package.json`,i=await t.resolve(r,(0,R.normalizePath)(n.importedFrom),{skipSelf:!0});if(!i||i.external)throw new u(`Failed to find '${r}' (from '${n.importedFrom}'), is the dependency installed correctly?`);let o=await(0,N.realpath)((0,I.dirname)(i.id));return y&&E(`Found package '${n.packageName}' at ${o}`),o}createI18nCache(){return new $({getId(t){return(0,R.normalizePath)(t)},async getValue(t,n){return y&&E(`Loading i18n file ${t}`),n.addWatchFile(t),{i18n:await ue(t),watchFiles:new Set([t])}},onInvalidate(t){y&&E(`Removed cache entry for i18n file ${t}`)},onCachedReturn(t){y&&E(`Returning cached entry for i18n file ${t}`)}})}createPackageMetadataCache(){let t={_byName:new Map,getId(n){return(0,R.normalizePath)(n)},async getValue(n,r){y&&E(`Loading metadata for package at ${n}`);let i=new Set,o=[],a={resolve:r.resolve,addWatchFile(d){r.addWatchFile(d),i.add(d)},warn(d){o.push(typeof d=="string"?{message:d}:d)}},s=await ot(a,n);y&&E(`Metadata for '${s.name}': %O`,s);let p=this._byName.get(s.name);if(p&&(0,R.normalizePath)(p.directory)!==(0,R.normalizePath)(s.directory))throw new u(`Found package '${s.name}' at two different locations ${p.directory} and ${s.directory}`);return this._byName.set(s.name,s),{metadata:s,watchFiles:i,warnings:o}},onInvalidate(n,r){y&&E(`Removed cache entry for '${r.metadata.name}'`),this._byName.delete(r.metadata.name)},onCachedReturn(n,r){y&&E(`Returning cached metadata for '${r.metadata.name}'`)}};return new $(t)}};function me(e,t){for(let n of e)t.addWatchFile(n)}async function ot(e,t){y&&E(`Visiting package directory ${t}.`);let n=(0,I.join)(t,"package.json");e.addWatchFile(n);let{name:r,dependencies:i}=await st(e,n),o=(0,I.join)(t,W.BUILD_CONFIG_NAME),a;if(e.addWatchFile((0,R.normalizePath)(o)),await D(o))try{a=await se(o)}catch(l){let g=l.message||"Unknown error";throw new u(`Failed to load build config ${o}: ${g}`)}else throw new u(`Expected a ${W.BUILD_CONFIG_NAME} in ${t}`);let s;if(a.services.length)try{s=await he(e,t,a.servicesModule??"./services")}catch(l){e.warn(`Failed to resolve entry point for package ${t}: ${l}`)}let p;if(a.styles){try{p=await he(e,t,a.styles)}catch(l){throw new u(`Failed to resolve css file for package ${t}: ${l}`)}if(!p)throw new u(`Failed to find css file '${a.styles}' in ${t}`)}let d=new Map;if(a.i18n)for(let l of a.i18n){if(d.has(l))throw new u(`Locale '${l}' was defined twice in ${o}`);let g=(0,I.join)(t,"i18n",`${l}.yaml`);if(e.addWatchFile(g),!await D(g))throw new u(`i18n file '${g}' does not exist.`);d.set(l,(0,R.normalizePath)(g))}return{name:r,directory:t,packageJsonPath:n,servicesModulePath:s,cssFilePath:p,i18nPaths:d,dependencies:i,config:a}}async function st(e,t){if(!await D(t))throw new u(`Expected a 'package.json' file at ${t}`);let n;try{n=JSON.parse(await(0,N.readFile)(t,"utf-8"))}catch(a){throw new u(`Failed to read ${t}: ${a}`)}let r=n.name;if(typeof r!="string")throw new u(`Expected 'name' to be a string in ${t}`);let i=n.dependencies??{};if(typeof i!="object")throw new u(`Expected a valid 'dependencies' object in ${t}`);let o=Object.keys(i);return{name:r,dependencies:o}}async function he(e,t,n){let r=await e.resolve(`./${n}`,`${t}/package.json`,{skipSelf:!0});return r==null?void 0:r.id}function ct(e){switch(e.type){case"absolute":return`${e.directory}`;case"unresolved":return`'${e.packageName}' required by ${e.importedFrom}`}}var dt=/[\\/]node_modules[\\/]/;function pt(e,t){return ae(e,t)&&!dt.test(e)}var lt=/[\\/]package\.json($|\?)/;function gt(e){return lt.test(e)}function ye(e){let t=n=>`@import ${JSON.stringify(n)};`;return e.filter(n=>!!n.cssFilePath).map(n=>t(n.cssFilePath)).join(`
39
- `)}var F=require("node:path/posix"),Ee=require("vite"),S="@@open-pioneer-app",ut="open-pioneer-app",ft=/[?&]open-pioneer-app(?:$|&)/,mt="open-pioneer-packages",ht=/[?&]open-pioneer-packages(?:$|&)/,yt="open-pioneer-styles",Et=/[?&]open-pioneer-styles(?:$|&)/,Pt="open-pioneer-i18n-index",Mt=/[?&]open-pioneer-i18n-index(?:$|&)/,kt="open-pioneer-i18n",Ct=/[?&]open-pioneer-i18n(?:$|&)/,vt=/[?&]locale=(?<locale>.*?)(?:$|&)/,Pe="@@open-pioneer-react-hooks",Rt=/^(.*?)(?:\?|$)/;function q(e){let t=(0,Ee.normalizePath)(e);if(!t||t.includes("\\0"))return;let n=xt(t);if(!n)return;let r=(0,F.basename)(n);if(r===Pe)return{type:"package-hooks",packageDirectory:(0,F.dirname)(n)};if(r===S)return wt(n,t)}function wt(e,t){var r,i;let n=(0,F.dirname)(e);if(t.match(ft))return{type:"app-meta",packageDirectory:n};if(t.match(ht))return{type:"app-packages",packageDirectory:n};if(t.match(Et))return{type:"app-css",packageDirectory:n};if(t.match(Mt))return{type:"app-i18n-index",packageDirectory:n};if(t.match(Ct)){let o="app-i18n",a=(i=(r=t.match(vt))==null?void 0:r.groups)==null?void 0:i.locale;if(!a)throw new Error("Missing locale name in i18n module request");return{type:o,packageDirectory:n,locale:a}}throw new Error(`Unexpected module id: ${t}`)}function M(e){switch(e.type){case"package-hooks":return`${e.packageDirectory}/${Pe}`;case"app-meta":return`${e.packageDirectory}/${S}?${ut}`;case"app-packages":return`${e.packageDirectory}/${S}?${mt}`;case"app-css":return`${e.packageDirectory}/${S}?${yt}`;case"app-i18n-index":return`${e.packageDirectory}/${S}?${Pt}`;case"app-i18n":return`${e.packageDirectory}/${S}?${kt}&locale=${e.locale}`}}function xt(e){var n;let t=(n=e.match(Rt))==null?void 0:n[1];if(!(!t||e[0]=="\0"))return t}function Me(e,t){let n=M({type:"app-packages",packageDirectory:e}),r=M({type:"app-css",packageDirectory:e})+"&inline&lang.scss",i=M({type:"app-i18n-index",packageDirectory:e});return`
40
- import { createBox } from ${JSON.stringify(t)};
41
- import packages from ${JSON.stringify(n)};
42
- import stylesString from ${JSON.stringify(r)};
43
- import { locales, loadMessages } from ${JSON.stringify(i)};
90
+ `);
91
+ function generatePackagesMetadata({ appName, packages }) {
92
+ const idGenerator = new IdGenerator();
93
+ const packagesMetadata = nodes.objectExpression([]);
94
+ const imports = [];
95
+ let overrides;
96
+ for (const pkg of packages) {
97
+ if (pkg.name === appName) {
98
+ overrides = pkg.config.overrides;
99
+ } else if (pkg.config.overrides.size > 0) {
100
+ throw new ReportableError(
101
+ `Unexpected 'overrides' in package '${pkg.name}'. Overrides are only supported in the app.`
102
+ );
103
+ }
104
+ }
105
+ for (const pkg of packages) {
106
+ const packageOverrides = overrides == null ? void 0 : overrides.get(pkg.name);
107
+ const packageMetadata = generatePackageMetadata(pkg, {
108
+ enableService(serviceName) {
109
+ var _a, _b;
110
+ return ((_b = (_a = packageOverrides == null ? void 0 : packageOverrides.services) == null ? void 0 : _a.get(serviceName)) == null ? void 0 : _b.enabled) ?? true;
111
+ },
112
+ importServiceClass(variableName, className, moduleId) {
113
+ const id = idGenerator.generate(variableName);
114
+ const renderedImporter = SERVICE_IMPORT({
115
+ SERVICE_NAME: nodes.identifier(className),
116
+ IMPORT_NAME: nodes.identifier(id),
117
+ IMPORT_SOURCE: nodes.stringLiteral(moduleId)
118
+ });
119
+ imports.push(renderedImporter);
120
+ return id;
121
+ }
122
+ });
123
+ packagesMetadata.properties.push(
124
+ nodes.objectProperty(nodes.stringLiteral(pkg.name), packageMetadata)
125
+ );
126
+ }
127
+ const program2 = nodes.program([...imports, nodes.exportDefaultDeclaration(packagesMetadata)]);
128
+ return generate(program2).code;
129
+ }
130
+ function generatePackageMetadata(pkg, options) {
131
+ const servicesObject = nodes.objectExpression([]);
132
+ for (const service of pkg.config.services.values()) {
133
+ if (!options.enableService(service.serviceName)) {
134
+ continue;
135
+ }
136
+ if (!pkg.servicesModulePath) {
137
+ throw new ReportableError(
138
+ `Package '${pkg.name}' must have a valid services module (typically 'services.ts' or 'services.js').
139
+ The entry point can be configured by setting the 'servicesModule' property in the build.config.mjs.`
140
+ );
141
+ }
142
+ const importName = options.importServiceClass(
143
+ pkg.name + "_" + service.serviceName,
144
+ service.serviceName,
145
+ pkg.servicesModulePath
146
+ );
147
+ const serviceObject = SERVICE_OBJECT({
148
+ SERVICE_NAME: nodes.stringLiteral(service.serviceName),
149
+ SERVICE_IMPORT: nodes.identifier(importName),
150
+ SERVICE_INTERFACES: nodes.arrayExpression(
151
+ service.provides.map(
152
+ (p) => INTERFACE_OBJECT({
153
+ INTERFACE_NAME: nodes.stringLiteral(p.interfaceName),
154
+ QUALIFIER: p.qualifier == null ? undefinedNode() : nodes.stringLiteral(p.qualifier)
155
+ })
156
+ )
157
+ ),
158
+ SERVICE_REFERENCES: nodes.objectExpression(
159
+ Array.from(service.references.entries()).map(
160
+ ([referenceName, referenceConfig]) => nodes.objectProperty(
161
+ nodes.stringLiteral(referenceName),
162
+ referenceObject(referenceConfig)
163
+ )
164
+ )
165
+ )
166
+ });
167
+ servicesObject.properties.push(
168
+ nodes.objectProperty(nodes.stringLiteral(service.serviceName), serviceObject)
169
+ );
170
+ }
171
+ const uiObject = UI_OBJECT({
172
+ UI_REFERENCES: nodes.arrayExpression(pkg.config.uiReferences.map((r) => referenceObject(r)))
173
+ });
174
+ const propertiesObject = nodes.objectExpression(
175
+ Array.from(pkg.config.properties.values()).map(
176
+ (prop) => nodes.objectProperty(
177
+ nodes.stringLiteral(prop.propertyName),
178
+ PROPERTY_OBJECT({
179
+ VALUE: jsonToExpression(prop.defaultValue),
180
+ REQUIRED: nodes.booleanLiteral(prop.required)
181
+ })
182
+ )
183
+ )
184
+ );
185
+ const pkgObject = PKG_OBJECT({
186
+ PACKAGE_NAME: nodes.stringLiteral(pkg.name),
187
+ PACKAGE_SERVICES: servicesObject,
188
+ PACKAGE_UI: uiObject,
189
+ PROPERTIES: propertiesObject
190
+ });
191
+ return pkgObject;
192
+ }
193
+ function jsonToExpression(json) {
194
+ if (json == null) {
195
+ return nodes.nullLiteral();
196
+ }
197
+ if (typeof json === "string") {
198
+ return nodes.stringLiteral(json);
199
+ }
200
+ if (typeof json === "number") {
201
+ return nodes.numericLiteral(json);
202
+ }
203
+ if (typeof json === "boolean") {
204
+ return nodes.booleanLiteral(json);
205
+ }
206
+ if (Array.isArray(json)) {
207
+ return nodes.arrayExpression(json.map((item) => jsonToExpression(item)));
208
+ }
209
+ if (typeof json === "object") {
210
+ return nodes.objectExpression(
211
+ Object.entries(json).map(
212
+ ([name, value]) => nodes.objectProperty(nodes.stringLiteral(name), jsonToExpression(value))
213
+ )
214
+ );
215
+ }
216
+ throw new Error(`Unexpected value while serializing JSON: ${json}.`);
217
+ }
218
+ function referenceObject(ref) {
219
+ return REFERENCE_OBJECT({
220
+ INTERFACE_NAME: nodes.stringLiteral(ref.interfaceName),
221
+ QUALIFIER: ref.qualifier ? nodes.stringLiteral(ref.qualifier) : undefinedNode(),
222
+ ALL: nodes.booleanLiteral(ref.type === "all" ? true : false)
223
+ // TODO: Rework internal app format
224
+ });
225
+ }
226
+ function undefinedNode() {
227
+ return nodes.unaryExpression("void", nodes.numericLiteral(0));
228
+ }
229
+
230
+ // src/metadata/MetadataRepository.ts
231
+ import { readFile as readFile2, realpath } from "fs/promises";
232
+ import { dirname, join } from "path";
233
+ import { normalizePath, resolvePackageData } from "vite";
234
+
235
+ // src/utils/fileUtils.ts
236
+ import * as fs from "node:fs";
237
+ import { isAbsolute, relative } from "node:path";
238
+ function fileExists(file) {
239
+ return fs.promises.access(file, fs.constants.F_OK).then(() => true).catch(() => false);
240
+ }
241
+ function isInDirectory(candidate, directory) {
242
+ const rel = relative(directory, candidate);
243
+ const isChild = rel && !rel.startsWith("..") && !isAbsolute(rel);
244
+ return !!isChild;
245
+ }
246
+
247
+ // src/utils/Cache.ts
248
+ var Cache = class {
249
+ values = /* @__PURE__ */ new Map();
250
+ jobs = /* @__PURE__ */ new Map();
251
+ provider;
252
+ constructor(provider) {
253
+ this.provider = provider;
254
+ }
255
+ /**
256
+ * Removes an entry associated with the given key.
257
+ */
258
+ invalidate(key) {
259
+ var _a, _b;
260
+ const id = this.provider.getId(key);
261
+ const oldValue = this.values.get(id);
262
+ this.values.delete(id);
263
+ this.jobs.delete(id);
264
+ if (oldValue) {
265
+ (_b = (_a = this.provider).onInvalidate) == null ? void 0 : _b.call(_a, key, oldValue);
266
+ }
267
+ }
268
+ /**
269
+ * Retrieves the value associated with `key`.
270
+ * A cached result will be used if present, otherwise the
271
+ * cache provider will be called.
272
+ *
273
+ * Note: computations may throw errors.
274
+ * Errors will not be cached.
275
+ *
276
+ * @param key the lookup key
277
+ * @param context an arbitrary set of values that will be forwarded to the provider
278
+ * should be provider be called.
279
+ * @returns the value associated with `key`
280
+ */
281
+ async get(key, ...context) {
282
+ var _a;
283
+ const provider = this.provider;
284
+ const id = provider.getId(key);
285
+ const values = this.values;
286
+ const existingValue = values.get(id);
287
+ if (existingValue) {
288
+ (_a = provider.onCachedReturn) == null ? void 0 : _a.call(provider, key, existingValue);
289
+ return Promise.resolve(existingValue);
290
+ }
291
+ const jobs = this.jobs;
292
+ const existingJob = jobs.get(id);
293
+ if (existingJob) {
294
+ return existingJob;
295
+ }
296
+ const job = provider.getValue(key, ...context);
297
+ jobs.set(id, job);
298
+ try {
299
+ const value = await job;
300
+ if (jobs.get(id) === job) {
301
+ values.set(id, value);
302
+ }
303
+ return value;
304
+ } finally {
305
+ if (jobs.get(id) === job) {
306
+ jobs.delete(id);
307
+ }
308
+ }
309
+ }
310
+ };
311
+
312
+ // src/metadata/parseBuildConfig.ts
313
+ import {
314
+ BUILD_CONFIG_NAME,
315
+ createPackageConfigFromBuildConfig,
316
+ loadBuildConfig as loadBuildConfigCommon,
317
+ verifyBuildConfig
318
+ } from "@open-pioneer/build-common";
319
+ import { basename } from "node:path";
320
+ async function loadBuildConfig(path) {
321
+ const rawConfig = await loadBuildConfigCommon(path);
322
+ return createPackageConfigFromBuildConfig(rawConfig);
323
+ }
324
+ function isBuildConfig(file) {
325
+ return basename(file) === BUILD_CONFIG_NAME;
326
+ }
327
+
328
+ // src/metadata/parseI18nYaml.ts
329
+ import { readFile } from "fs/promises";
330
+ import { load as loadYaml } from "js-yaml";
331
+ import { z } from "zod";
332
+ import { fromZodError } from "zod-validation-error";
333
+ var MESSAGES_SCHEMA = z.lazy(
334
+ () => z.record(z.union([z.string(), MESSAGES_SCHEMA])).nullish()
335
+ );
336
+ var I18N_SCHEMA = z.strictObject({
337
+ messages: MESSAGES_SCHEMA.nullish().optional(),
338
+ overrides: z.record(MESSAGES_SCHEMA).nullish().optional()
339
+ }).nullish();
340
+ async function loadI18nFile(path) {
341
+ let content;
342
+ try {
343
+ content = await readFile(path, "utf-8");
344
+ } catch (e) {
345
+ throw new ReportableError(`Failed to read ${path}`, { cause: e });
346
+ }
347
+ try {
348
+ return parseI18nYaml(content);
349
+ } catch (e) {
350
+ throw new ReportableError(`Failed to parse ${path}`, { cause: e });
351
+ }
352
+ }
353
+ function parseI18nYaml(yaml) {
354
+ const data = loadYaml(yaml);
355
+ return parseI18nFile(data);
356
+ }
357
+ function parseI18nFile(data) {
358
+ const result = I18N_SCHEMA.safeParse(data);
359
+ if (!result.success) {
360
+ throw fromZodError(result.error);
361
+ }
362
+ const rawI18n = result.data;
363
+ return {
364
+ messages: gatherMessages((rawI18n == null ? void 0 : rawI18n.messages) ?? void 0),
365
+ overrides: gatherOverrides((rawI18n == null ? void 0 : rawI18n.overrides) ?? void 0)
366
+ };
367
+ }
368
+ function gatherMessages(data) {
369
+ const messages = /* @__PURE__ */ new Map();
370
+ const prefix = [];
371
+ const visitChildren = (record) => {
372
+ for (const [key, value] of Object.entries(record)) {
373
+ if (typeof value === "string") {
374
+ visitMessage(key, value);
375
+ } else if (value) {
376
+ prefix.push(key);
377
+ visitChildren(value);
378
+ prefix.pop();
379
+ }
380
+ }
381
+ };
382
+ const visitMessage = (key, message) => {
383
+ const id = [...prefix, key].join(".");
384
+ if (messages.has(id)) {
385
+ throw new Error(`Message '${id}' was already defined.`);
386
+ }
387
+ messages.set(id, message);
388
+ };
389
+ if (data) {
390
+ visitChildren(data);
391
+ }
392
+ return messages;
393
+ }
394
+ function gatherOverrides(data) {
395
+ const overrides = /* @__PURE__ */ new Map();
396
+ if (data) {
397
+ for (const [key, value] of Object.entries(data)) {
398
+ const messages = gatherMessages(value ?? void 0);
399
+ overrides.set(key, messages);
400
+ }
401
+ }
402
+ return overrides;
403
+ }
404
+
405
+ // src/metadata/MetadataRepository.ts
406
+ import {
407
+ BUILD_CONFIG_NAME as BUILD_CONFIG_NAME2,
408
+ PackageMetadataV1,
409
+ createPackageConfigFromPackageMetadata
410
+ } from "@open-pioneer/build-common";
411
+
412
+ // src/utils/package.ts
413
+ var PACKAGE_NAME = "@open-pioneer/vite-plugin-pioneer";
414
+
415
+ // src/metadata/MetadataRepository.ts
416
+ var isDebug = !!process.env.DEBUG;
417
+ var debug2 = createDebugger("open-pioneer:metadata");
418
+ var MetadataRepository = class {
419
+ sourceRoot;
420
+ // Key: package directory on disk, value: existing metadata
421
+ packageMetadataCache;
422
+ // Cache for the contents of i18n files.
423
+ // Key: path on disk.
424
+ i18nCache;
425
+ // Cache for package locations & package.json contents
426
+ packageDataCache = /* @__PURE__ */ new Map();
427
+ /**
428
+ * @param sourceRoot Source folder on disk, needed to detect 'local' packages
429
+ */
430
+ constructor(sourceRoot) {
431
+ this.sourceRoot = sourceRoot;
432
+ this.packageMetadataCache = this.createPackageMetadataCache();
433
+ this.i18nCache = this.createI18nCache();
434
+ }
435
+ reset() {
436
+ this.packageMetadataCache = this.createPackageMetadataCache();
437
+ this.i18nCache = this.createI18nCache();
438
+ this.packageDataCache.clear();
439
+ }
440
+ /**
441
+ * Called by the plugin when a file has been changed.
442
+ * The cached data associated with that file (if any) will be removed.
443
+ */
444
+ onFileChanged(path) {
445
+ if (isPackageJson(path) || isBuildConfig(path)) {
446
+ this.packageMetadataCache.invalidate(dirname(path));
447
+ }
448
+ this.i18nCache.invalidate(path);
449
+ }
450
+ /**
451
+ * Returns the combined application metadata of the app in `appDirectory`.
452
+ * Starting from the app's package.json, dependencies will be visited recursively.
453
+ *
454
+ * For packages that use our package extensions (services etc.), metadata will be gathered and
455
+ * will be returned here.
456
+ */
457
+ async getAppMetadata(ctx, appDirectory) {
458
+ isDebug && debug2(`Request for app metadata of ${appDirectory}`);
459
+ const appPackageMetadata = await this.getPackageMetadata(ctx, {
460
+ type: "absolute",
461
+ directory: appDirectory
462
+ });
463
+ if (!appPackageMetadata) {
464
+ throw new ReportableError(
465
+ `Failed to parse app metadata in ${appDirectory}. Ensure that the app is a valid local package.`
466
+ );
467
+ }
468
+ const appLocales = Array.from(appPackageMetadata.i18nPaths.keys());
469
+ const packageMetadataByName = /* @__PURE__ */ new Map();
470
+ packageMetadataByName.set(appPackageMetadata.name, appPackageMetadata);
471
+ const visitDependencies = async (dependencies, importedFrom) => {
472
+ const jobs = dependencies.map(async (dependency) => {
473
+ const packageMetadata = await this.getPackageMetadata(ctx, {
474
+ type: "unresolved",
475
+ dependency,
476
+ importedFrom
477
+ });
478
+ if (packageMetadata) {
479
+ if (!packageMetadataByName.has(packageMetadata.name)) {
480
+ packageMetadataByName.set(packageMetadata.name, packageMetadata);
481
+ }
482
+ await visitDependencies(
483
+ packageMetadata.dependencies,
484
+ packageMetadata.packageJsonPath
485
+ );
486
+ }
487
+ });
488
+ return await Promise.all(jobs);
489
+ };
490
+ await visitDependencies(
491
+ appPackageMetadata.dependencies,
492
+ appPackageMetadata.packageJsonPath
493
+ );
494
+ const appMetadata = {
495
+ name: appPackageMetadata.name,
496
+ directory: appPackageMetadata.directory,
497
+ locales: appLocales,
498
+ packageJsonPath: appPackageMetadata.packageJsonPath,
499
+ packages: Array.from(packageMetadataByName.values())
500
+ };
501
+ return appMetadata;
502
+ }
503
+ /**
504
+ * Returns package metadata associated with the given package.
505
+ */
506
+ async getPackageMetadata(ctx, loc) {
507
+ isDebug && debug2(`Request for package metadata of ${formatPackageLocation(loc)}`);
508
+ const packageDir = await this.resolvePackageLocation(loc);
509
+ if (!packageDir) {
510
+ return void 0;
511
+ }
512
+ const entry = await this.packageMetadataCache.get(packageDir, ctx);
513
+ propagateWatchFiles(entry.watchFiles, ctx);
514
+ for (const warning of entry.warnings) {
515
+ ctx.warn(warning);
516
+ }
517
+ if (entry.metadata.type === "plain") {
518
+ isDebug && debug2(`Skipping package '${packageDir}'.`);
519
+ return void 0;
520
+ }
521
+ return entry.metadata;
522
+ }
523
+ /**
524
+ * Returns the parsed contents of the given i18n file.
525
+ */
526
+ async getI18nFile(ctx, path) {
527
+ const { i18n, watchFiles } = await this.i18nCache.get(path, ctx);
528
+ propagateWatchFiles(watchFiles, ctx);
529
+ return i18n;
530
+ }
531
+ async resolvePackageLocation(loc) {
532
+ if (loc.type === "absolute") {
533
+ return await realpath(loc.directory);
534
+ }
535
+ const { packageName, optional } = loc.dependency;
536
+ const packageData = await resolvePackageData(
537
+ packageName,
538
+ loc.importedFrom,
539
+ false,
540
+ this.packageDataCache
541
+ );
542
+ if (!packageData) {
543
+ if (optional) {
544
+ isDebug && debug2(`Optional package '${packageName}' was not found.`);
545
+ return void 0;
546
+ }
547
+ throw new ReportableError(
548
+ `Failed to find package '${packageName}' (from '${loc.importedFrom}'), is the dependency installed correctly?`
549
+ );
550
+ }
551
+ const packageDir = await realpath(packageData.dir);
552
+ isDebug && debug2(`Found package '${packageName}' at ${packageDir}`);
553
+ return packageDir;
554
+ }
555
+ createI18nCache() {
556
+ return new Cache({
557
+ getId(path) {
558
+ return normalizePath(path);
559
+ },
560
+ async getValue(path, ctx) {
561
+ isDebug && debug2(`Loading i18n file ${path}`);
562
+ ctx.addWatchFile(path);
563
+ const entry = {
564
+ i18n: await loadI18nFile(path),
565
+ watchFiles: /* @__PURE__ */ new Set([path])
566
+ };
567
+ return entry;
568
+ },
569
+ onInvalidate(path) {
570
+ isDebug && debug2(`Removed cache entry for i18n file ${path}`);
571
+ },
572
+ onCachedReturn(path) {
573
+ isDebug && debug2(`Returning cached entry for i18n file ${path}`);
574
+ }
575
+ });
576
+ }
577
+ createPackageMetadataCache() {
578
+ const sourceRoot = this.sourceRoot;
579
+ const provider = {
580
+ _byName: /* @__PURE__ */ new Map(),
581
+ getId(directory) {
582
+ return normalizePath(directory);
583
+ },
584
+ async getValue(directory, ctx) {
585
+ isDebug && debug2(`Loading metadata for package at ${directory}`);
586
+ const watchFiles = /* @__PURE__ */ new Set();
587
+ const warnings = [];
588
+ const trackingCtx = {
589
+ resolve: ctx.resolve,
590
+ addWatchFile(id) {
591
+ ctx.addWatchFile(id);
592
+ watchFiles.add(id);
593
+ },
594
+ warn(msg) {
595
+ warnings.push(typeof msg === "string" ? { message: msg } : msg);
596
+ }
597
+ };
598
+ const metadata = await parsePackageMetadata(trackingCtx, directory, sourceRoot);
599
+ isDebug && debug2(`Metadata for '${metadata.name}': %O`, metadata);
600
+ if (metadata.type === "pioneer-package") {
601
+ const existingMetadata = this._byName.get(metadata.name);
602
+ if (existingMetadata && normalizePath(existingMetadata.directory) !== normalizePath(metadata.directory)) {
603
+ throw new ReportableError(
604
+ `Found package '${metadata.name}' at two different locations ${existingMetadata.directory} and ${metadata.directory}`
605
+ );
606
+ }
607
+ this._byName.set(metadata.name, metadata);
608
+ }
609
+ return {
610
+ metadata,
611
+ watchFiles,
612
+ warnings
613
+ };
614
+ },
615
+ onInvalidate(directory, entry) {
616
+ isDebug && debug2(`Removed cache entry for '${entry.metadata.name}'`);
617
+ this._byName.delete(entry.metadata.name);
618
+ },
619
+ onCachedReturn(directory, entry) {
620
+ isDebug && debug2(`Returning cached metadata for '${entry.metadata.name}'`);
621
+ }
622
+ };
623
+ return new Cache(provider);
624
+ }
625
+ };
626
+ function propagateWatchFiles(watchFiles, ctx) {
627
+ for (const file of watchFiles) {
628
+ ctx.addWatchFile(file);
629
+ }
630
+ }
631
+ async function parsePackageMetadata(ctx, packageDir, sourceRoot) {
632
+ const mode = isLocalPackage(packageDir, sourceRoot) ? "local" : "external";
633
+ isDebug && debug2(`Visiting package directory ${packageDir} in mode ${mode}.`);
634
+ const packageJsonPath = join(packageDir, "package.json");
635
+ ctx.addWatchFile(packageJsonPath);
636
+ const {
637
+ name: packageName,
638
+ dependencies,
639
+ frameworkMetadata
640
+ } = await parsePackageJson(ctx, packageJsonPath);
641
+ const configResult = await readConfig(
642
+ ctx,
643
+ packageDir,
644
+ mode,
645
+ frameworkMetadata,
646
+ packageName,
647
+ packageJsonPath
648
+ );
649
+ if (!configResult) {
650
+ return {
651
+ type: "plain",
652
+ name: packageName,
653
+ directory: packageDir
654
+ };
655
+ }
656
+ const { config, configPath } = configResult;
657
+ let servicesModule;
658
+ if (config.services.size) {
659
+ try {
660
+ servicesModule = await resolveLocalFile(
661
+ ctx,
662
+ packageDir,
663
+ config.servicesModule ?? "./services"
664
+ );
665
+ } catch (e) {
666
+ ctx.warn({
667
+ message: `Failed to resolve entry point for package ${packageDir}`,
668
+ cause: e
669
+ });
670
+ }
671
+ }
672
+ let cssFile;
673
+ if (config.styles) {
674
+ try {
675
+ cssFile = await resolveLocalFile(ctx, packageDir, config.styles);
676
+ } catch (e) {
677
+ throw new ReportableError(`Failed to resolve css file for package ${packageDir}`, {
678
+ cause: e
679
+ });
680
+ }
681
+ if (!cssFile) {
682
+ throw new ReportableError(
683
+ `Failed to find css file '${config.styles}' in ${packageDir}`
684
+ );
685
+ }
686
+ }
687
+ const i18nPaths = /* @__PURE__ */ new Map();
688
+ for (const locale of config.languages) {
689
+ if (i18nPaths.has(locale)) {
690
+ throw new ReportableError(`Locale '${locale}' was defined twice in ${configPath}`);
691
+ }
692
+ const path = join(packageDir, "i18n", `${locale}.yaml`);
693
+ ctx.addWatchFile(path);
694
+ if (!await fileExists(path)) {
695
+ throw new ReportableError(`i18n file '${path}' does not exist.`);
696
+ }
697
+ i18nPaths.set(locale, normalizePath(path));
698
+ }
699
+ return {
700
+ type: "pioneer-package",
701
+ name: packageName,
702
+ directory: packageDir,
703
+ packageJsonPath,
704
+ servicesModulePath: servicesModule,
705
+ cssFilePath: cssFile,
706
+ i18nPaths,
707
+ dependencies,
708
+ config
709
+ };
710
+ }
711
+ async function readConfig(ctx, packageDir, mode, frameworkMetadata, packageName, packageJsonPath) {
712
+ switch (mode) {
713
+ case "local": {
714
+ const buildConfigPath = join(packageDir, BUILD_CONFIG_NAME2);
715
+ let buildConfig;
716
+ ctx.addWatchFile(normalizePath(buildConfigPath));
717
+ if (await fileExists(buildConfigPath)) {
718
+ try {
719
+ buildConfig = await loadBuildConfig(buildConfigPath);
720
+ } catch (e) {
721
+ throw new ReportableError(`Failed to load build config ${buildConfigPath}`, {
722
+ cause: e
723
+ });
724
+ }
725
+ } else {
726
+ throw new ReportableError(`Expected a ${BUILD_CONFIG_NAME2} in ${packageDir}`);
727
+ }
728
+ return { configPath: buildConfigPath, config: buildConfig };
729
+ }
730
+ case "external": {
731
+ if (!frameworkMetadata) {
732
+ return void 0;
733
+ }
734
+ const metadataResult = PackageMetadataV1.parsePackageMetadata(frameworkMetadata);
735
+ if (metadataResult.type === "error") {
736
+ if (metadataResult.code === "unsupported-version") {
737
+ throw new ReportableError(
738
+ `Package '${packageName}' in ${packageDir} uses an unsupported metadata version. You will likely have to update ${PACKAGE_NAME}.
739
+
740
+ ` + metadataResult.message,
741
+ { cause: metadataResult.cause }
742
+ );
743
+ }
744
+ throw new ReportableError(
745
+ `Failed to parse metadata of package '${packageName}' in ${packageDir}: ${metadataResult.message}`,
746
+ { cause: metadataResult.cause }
747
+ );
748
+ }
749
+ return {
750
+ configPath: packageJsonPath,
751
+ config: createPackageConfigFromPackageMetadata(metadataResult.value)
752
+ };
753
+ }
754
+ }
755
+ }
756
+ async function parsePackageJson(ctx, packageJsonPath) {
757
+ if (!await fileExists(packageJsonPath)) {
758
+ throw new ReportableError(`Expected a 'package.json' file at ${packageJsonPath}`);
759
+ }
760
+ let packageJsonContent;
761
+ try {
762
+ packageJsonContent = JSON.parse(await readFile2(packageJsonPath, "utf-8"));
763
+ } catch (e) {
764
+ throw new ReportableError(`Failed to read ${packageJsonPath}`, { cause: e });
765
+ }
766
+ const packageName = packageJsonContent.name;
767
+ if (typeof packageName !== "string") {
768
+ throw new ReportableError(`Expected 'name' to be a string in ${packageJsonPath}`);
769
+ }
770
+ const dependencies = packageJsonContent.dependencies ?? {};
771
+ if (typeof dependencies !== "object") {
772
+ throw new ReportableError(`Expected a valid 'dependencies' object in ${packageJsonPath}`);
773
+ }
774
+ const peerDependencies = packageJsonContent.peerDependencies ?? {};
775
+ if (typeof peerDependencies !== "object") {
776
+ throw new ReportableError(
777
+ `Expected a valid 'peerDependencies' object in ${packageJsonPath}`
778
+ );
779
+ }
780
+ const optionalDependencies = packageJsonContent.optionalDependencies ?? {};
781
+ if (typeof optionalDependencies !== "object") {
782
+ throw new ReportableError(
783
+ `Expected a valid 'optionalDependencies' object in ${packageJsonPath}`
784
+ );
785
+ }
786
+ const allDependencies = [
787
+ ...Object.keys(dependencies).map((packageName2) => ({ packageName: packageName2, optional: false })),
788
+ ...Object.keys(peerDependencies).map((packageName2) => {
789
+ var _a, _b;
790
+ return {
791
+ packageName: packageName2,
792
+ optional: ((_b = (_a = packageJsonContent == null ? void 0 : packageJsonContent.peerDependenciesMeta) == null ? void 0 : _a[packageName2]) == null ? void 0 : _b.optional) ?? false
793
+ };
794
+ }),
795
+ ...Object.keys(optionalDependencies).map((packageName2) => ({ packageName: packageName2, optional: true }))
796
+ ];
797
+ const frameworkMetadata = packageJsonContent[PackageMetadataV1.PACKAGE_JSON_KEY] ?? void 0;
798
+ return {
799
+ name: packageName,
800
+ dependencies: allDependencies,
801
+ frameworkMetadata
802
+ };
803
+ }
804
+ async function resolveLocalFile(ctx, packageDir, localModuleId) {
805
+ const result = await ctx.resolve(`./${localModuleId}`, `${packageDir}/package.json`, {
806
+ skipSelf: true
807
+ });
808
+ return result == null ? void 0 : result.id;
809
+ }
810
+ function formatPackageLocation(loc) {
811
+ switch (loc.type) {
812
+ case "absolute":
813
+ return `${loc.directory}`;
814
+ case "unresolved": {
815
+ let name = `'${loc.dependency.packageName}'`;
816
+ if (loc.dependency.optional) {
817
+ name += " (optional)";
818
+ }
819
+ return `${name} required by ${loc.importedFrom}`;
820
+ }
821
+ }
822
+ }
823
+ var NODE_MODULES_RE = /[\\/]node_modules[\\/]/;
824
+ function isLocalPackage(file, sourceDir) {
825
+ return isInDirectory(file, sourceDir) && !NODE_MODULES_RE.test(file);
826
+ }
827
+ var PACKAGE_JSON_RE = /[\\/]package\.json($|\?)/;
828
+ function isPackageJson(file) {
829
+ return PACKAGE_JSON_RE.test(file);
830
+ }
831
+
832
+ // src/codegen/generateCombinedCss.ts
833
+ function generateCombinedCss(packages) {
834
+ const cssImport = (file) => `@import ${JSON.stringify(file)};`;
835
+ return packages.filter((pkg) => !!pkg.cssFilePath).map((pkg) => cssImport(pkg.cssFilePath)).join("\n");
836
+ }
837
+
838
+ // src/codegen/shared.ts
839
+ import { dirname as dirname2, basename as basename2 } from "node:path/posix";
840
+ import { normalizePath as normalizePath2 } from "vite";
841
+ var APP_MODULE = "@@open-pioneer-app";
842
+ var APP_META_QUERY = "open-pioneer-app";
843
+ var APP_META_RE = /[?&]open-pioneer-app(?:$|&)/;
844
+ var APP_PACKAGES_QUERY = "open-pioneer-packages";
845
+ var APP_PACKAGES_RE = /[?&]open-pioneer-packages(?:$|&)/;
846
+ var APP_CSS_QUERY = "open-pioneer-styles";
847
+ var APP_CSS_RE = /[?&]open-pioneer-styles(?:$|&)/;
848
+ var APP_I18N_INDEX_QUERY = "open-pioneer-i18n-index";
849
+ var APP_I18N_INDEX_RE = /[?&]open-pioneer-i18n-index(?:$|&)/;
850
+ var APP_I18N_QUERY = "open-pioneer-i18n";
851
+ var APP_I18N_RE = /[?&]open-pioneer-i18n(?:$|&)/;
852
+ var APP_I18N_LOCALE_RE = /[?&]locale=(?<locale>.*?)(?:$|&)/;
853
+ var PACKAGE_HOOKS_MODULE = "@@open-pioneer-react-hooks";
854
+ var SOURCE_FILE_RE = /^(.*?)(?:\?|$)/;
855
+ function parseVirtualModuleId(inputModuleId) {
856
+ const moduleId = normalizePath2(inputModuleId);
857
+ if (!moduleId || moduleId.includes("\\0")) {
858
+ return void 0;
859
+ }
860
+ const sourceFile = getSourceFile(moduleId);
861
+ if (!sourceFile) {
862
+ return void 0;
863
+ }
864
+ const base = basename2(sourceFile);
865
+ if (base === PACKAGE_HOOKS_MODULE) {
866
+ return {
867
+ type: "package-hooks",
868
+ packageDirectory: dirname2(sourceFile)
869
+ };
870
+ }
871
+ if (base === APP_MODULE) {
872
+ return parseAppModuleId(sourceFile, moduleId);
873
+ }
874
+ return void 0;
875
+ }
876
+ function parseAppModuleId(sourceFile, moduleId) {
877
+ var _a, _b;
878
+ const packageDirectory = dirname2(sourceFile);
879
+ if (moduleId.match(APP_META_RE)) {
880
+ const type = "app-meta";
881
+ return { type, packageDirectory };
882
+ } else if (moduleId.match(APP_PACKAGES_RE)) {
883
+ const type = "app-packages";
884
+ return { type, packageDirectory };
885
+ } else if (moduleId.match(APP_CSS_RE)) {
886
+ const type = "app-css";
887
+ return { type, packageDirectory };
888
+ } else if (moduleId.match(APP_I18N_INDEX_RE)) {
889
+ const type = "app-i18n-index";
890
+ return { type, packageDirectory };
891
+ } else if (moduleId.match(APP_I18N_RE)) {
892
+ const type = "app-i18n";
893
+ const locale = (_b = (_a = moduleId.match(APP_I18N_LOCALE_RE)) == null ? void 0 : _a.groups) == null ? void 0 : _b["locale"];
894
+ if (!locale) {
895
+ throw new Error("Missing locale name in i18n module request");
896
+ }
897
+ return { type, packageDirectory, locale };
898
+ }
899
+ throw new Error(`Unexpected module id: ${moduleId}`);
900
+ }
901
+ function serializeModuleId(mod) {
902
+ switch (mod.type) {
903
+ case "package-hooks":
904
+ return `${mod.packageDirectory}/${PACKAGE_HOOKS_MODULE}`;
905
+ case "app-meta":
906
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_META_QUERY}`;
907
+ case "app-packages":
908
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_PACKAGES_QUERY}`;
909
+ case "app-css":
910
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_CSS_QUERY}`;
911
+ case "app-i18n-index":
912
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_INDEX_QUERY}`;
913
+ case "app-i18n":
914
+ return `${mod.packageDirectory}/${APP_MODULE}?${APP_I18N_QUERY}&locale=${mod.locale}`;
915
+ }
916
+ }
917
+ function getSourceFile(moduleId) {
918
+ var _a;
919
+ const sourceFile = (_a = moduleId.match(SOURCE_FILE_RE)) == null ? void 0 : _a[1];
920
+ if (!sourceFile || moduleId[0] == "\0") {
921
+ return void 0;
922
+ }
923
+ return sourceFile;
924
+ }
925
+
926
+ // src/codegen/generateAppMetadata.ts
927
+ function generateAppMetadata(packageDirectory, metadataModuleId) {
928
+ const packagesModule = serializeModuleId({ type: "app-packages", packageDirectory });
929
+ const cssModule = serializeModuleId({ type: "app-css", packageDirectory }) + "&inline&lang.scss";
930
+ const i18nModule = serializeModuleId({ type: "app-i18n-index", packageDirectory });
931
+ return `
932
+ import { createBox } from ${JSON.stringify(metadataModuleId)};
933
+ import packages from ${JSON.stringify(packagesModule)};
934
+ import stylesString from ${JSON.stringify(cssModule)};
935
+ import { locales, loadMessages } from ${JSON.stringify(i18nModule)};
44
936
 
45
937
  const styles = createBox(stylesString);
46
938
  if (import.meta.hot) {
@@ -62,25 +954,475 @@ export {
62
954
  locales,
63
955
  loadMessages
64
956
  };
65
- `.trim()}var xe=require("node:fs/promises");function ke(e,t){return`
66
- import { useServiceInternal, useServicesInternal, usePropertiesInternal, useIntlInternal } from ${JSON.stringify(t)};
957
+ `.trim();
958
+ }
959
+
960
+ // src/codegenPlugin.ts
961
+ import { readFile as readFile3 } from "node:fs/promises";
67
962
 
68
- const PACKAGE_NAME = ${JSON.stringify(e)};
963
+ // src/codegen/generateReactHooks.ts
964
+ function generateReactHooks(packageName, runtimeModuleId) {
965
+ return `
966
+ import { useServiceInternal, useServicesInternal, usePropertiesInternal, useIntlInternal } from ${JSON.stringify(
967
+ runtimeModuleId
968
+ )};
969
+
970
+ const PACKAGE_NAME = ${JSON.stringify(packageName)};
69
971
  export const useService = /*@__PURE__*/ useServiceInternal.bind(undefined, PACKAGE_NAME);
70
972
  export const useServices = /*@__PURE__*/ useServicesInternal.bind(undefined, PACKAGE_NAME);
71
973
  export const useProperties = /*@__PURE__*/ usePropertiesInternal.bind(undefined, PACKAGE_NAME);
72
974
  export const useIntl = /*@__PURE__*/ useIntlInternal.bind(undefined, PACKAGE_NAME);
73
- `.trim()}var h=w(require("@babel/types")),G=w(require("@babel/template"));var Q=w(require("@babel/generator"));var It=G.default.program(`
975
+ `.trim();
976
+ }
977
+
978
+ // src/codegen/generateI18n.ts
979
+ import * as nodes2 from "@babel/types";
980
+ import template2 from "@babel/template";
981
+ import generate2 from "@babel/generator";
982
+ var INDEX_TEMPLATE = template2.program(`
74
983
  export const locales = %%LOCALES_ARRAY%%;
75
984
 
76
985
  export function loadMessages(locale) {
77
986
  %%LOCALE_SWITCH%%
78
987
  throw new Error(\`Unsupported locale: '\${locale}'\`);
79
988
  }
80
- `),At=G.default.statement(`
989
+ `);
990
+ var IMPORT_TEMPLATE = template2.statement(`
81
991
  return import(%%MODULE_ID%%).then(mod => mod.default);
82
- `),St=G.default.program(`
992
+ `);
993
+ var MESSAGES_TEMPLATE = template2.program(`
83
994
  const messages = JSON.parse(%%SERIALIZED%%);
84
995
  export default messages;
85
- `);function Ce(e,t){let n=h.arrayExpression(t.map(o=>h.stringLiteral(o))),r=h.switchStatement(h.identifier("locale"),t.map(o=>{let a=M({type:"app-i18n",packageDirectory:e,locale:o}),s=At({MODULE_ID:h.stringLiteral(a)});return h.switchCase(h.stringLiteral(o),[s])})),i=It({LOCALES_ARRAY:n,LOCALE_SWITCH:r});return(0,Q.default)(i).code}async function ve(e){let{locale:t,appName:n,packages:r,loadI18n:i}=e,o=new Map,a=new Set,s;for(let g of r){g.i18nPaths.size!==0&&a.add(g.name);let f=g.i18nPaths.get(t);if(!f)continue;let{messages:m,overrides:P}=await i(f);if(g.name===n)s=P;else if(P.size!==0)throw new u(`Unexpected 'overrides' block in '${f}'. Overrides are only supported in the app.`);o.set(g.name,m)}if(s)for(let[g,f]of s.entries()){let m=o.get(g);if(!m){o.set(g,f);continue}let P=new Map([...m,...f]);o.set(g,P)}for(let g of a)if(!o.get(g))throw new u(`Package '${g}' requires messages for locale '${t}'. Either update the package or add messages from the app via 'overrides'.`);let p={};for(let[g,f]of o.entries())p[g]=Object.fromEntries(f.entries());let d=JSON.stringify(p),l=St({SERIALIZED:h.stringLiteral(d)});return(0,Q.default)(l).code}var k=!!process.env.DEBUG,C=j("open-pioneer:codegen");function Ie(){let e=new Map,t,n,r,i,o;return{name:"pioneer:codegen",async buildStart(){e.clear(),n==null||n.reset();let a=async s=>{let p=await this.resolve(s,__filename);return p||this.error(`Failed to find '${s}'.`),p.id};i=await a("@open-pioneer/runtime/react-integration"),o=await a("@open-pioneer/runtime/metadata")},configResolved(a){t=a,n=new J(t.root)},configureServer(a){r=a,a.watcher.on("all",(s,p)=>{let d=e.get((0,_.normalizePath)(p));if(d){k&&C(`File changed: ${p}`),n.onFileChanged(p);for(let l of d){let g=a.moduleGraph.getModuleById(l);g&&(k&&C(`Triggering hmr of ${l}`),a.reloadModule(g).catch(f=>{t.logger.error(`Failed to trigger hmr: ${f}`)}))}}})},async resolveId(a,s){try{if(!s)return;if(q(a))return a;let p=()=>{let d=Nt((0,A.dirname)(s),t.root);if(!d)throw new u(`Failed to find package.json for package from '${s}'.`);let l=(0,A.dirname)(d);return(0,_.normalizePath)(l)};if(a==="open-pioneer:app")return M({type:"app-meta",packageDirectory:p()});if(a==="open-pioneer:react-hooks")return M({type:"package-hooks",packageDirectory:p()})}catch(p){Re(this,p)}},async load(a){var s,p;try{let d=q(a);if(!d)return;k&&C("Loading virtual module %O",d);let l=(s=await this.resolve(d.packageDirectory+"/package.json"))==null?void 0:s.id;if(!l)throw new u(`Failed to resolve package.json in ${d.packageDirectory}`);if(d.type==="package-hooks"){let m=d.packageDirectory,P=(p=await this.resolve(m+"/package.json"))==null?void 0:p.id;if(!P)throw new u(`Failed to resolve package.json in ${m}`);let $e=await Ft(this,P),H=ke($e,i);return k&&C("Generated hooks code: %O",H),H}if(d.type==="app-meta")return Me(d.packageDirectory,o);let g=_t(this,a,r,e),f=await n.getAppMetadata(g,(0,A.dirname)(l));switch(d.type){case"app-packages":{let m=ne(f.packages);return k&&C("Generated app metadata: %O",m),m}case"app-css":{let m=ye(f.packages);return k&&C("Generated app css: %O",m),m}case"app-i18n-index":{let m=Ce(d.packageDirectory,f.locales);return k&&C("Generated i18n lookup: %O",m),m}case"app-i18n":{let m=await ve({locale:d.locale,appName:f.name,packages:f.packages,loadI18n(P){return n.getI18nFile(g,P)}});return k&&C("Generated i18n messages: %O",m),m}}}catch(d){Re(this,d)}}}}function _t(e,t,n,r){return{warn:e.warn,resolve:e.resolve,addWatchFile:i=>{n&&(k&&C(`Adding manual watch for ${i}`),n.watcher.add(i),$t(r,i,t)),e.addWatchFile(i)}}}function Re(e,t){t instanceof u&&e.error(t);let n=String(t.message)||"Unknown error";e.error("Internal error: "+n)}function $t(e,t,n){let r=(0,_.normalizePath)(t),i=e.get(r);i||(i=new Set,e.set(r,i)),i.add(n)}function Nt(e,t){let n=e;for(;n;){let r=(0,A.join)(n,"package.json");if((0,we.existsSync)(r))return r;if((0,_.normalizePath)(n)==(0,_.normalizePath)(t))return;let i=(0,A.dirname)(n);n=i===n||i==="."?"":i}}async function Ft(e,t){let n;try{let r=await(0,xe.readFile)(t,"utf-8");n=JSON.parse(r).name}catch(r){throw new u(`Failed to read package.json file: ${r}`)}if(!n)throw new u(`Failed to read package name from ${t}.`);return n}var O=require("node:fs"),b=require("node:path"),Y=require("node:path"),Se=require("node:process");function _e(e){let t=(e==null?void 0:e.rootSite)??!1,n=(e==null?void 0:e.apps)||[],r=(e==null?void 0:e.sites)||[],i;return{name:"pioneer:mpa",config(o){let a=o.root??(0,Se.cwd)(),{entryPoints:s,appNames:p}=bt({apps:n,sites:r,rootSite:t,sourceRoot:a});return{build:{rollupOptions:{input:s,output:{entryFileNames(l){return p.includes(l.name)?"[name].js":Y.posix.join(i.build.assetsDir,"[hash:12].js")},chunkFileNames(l){return Y.posix.join(i.build.assetsDir,"[hash:12].js")}}}}}},configResolved(o){i=o}}}function bt(e){let t;Array.isArray(e.apps)?t=e.apps.map(a=>{let s=(0,b.resolve)(e.sourceRoot,"apps",a,"app"),p=Ot(a,s);return{name:a,path:p}}):t=Object.entries(e.apps).map(([a,s])=>{let p=(0,b.resolve)(e.sourceRoot,s);if(!(0,O.existsSync)(p))throw new Error(`Failed to find app '${a}' at ${p}. Ensure that the path is spelled correctly.`);return{name:a,path:p}});let n=e.sites.map(a=>{let s=(0,b.resolve)(e.sourceRoot,a,"index.html");if(!(0,O.existsSync)(s))throw new Error(`Failed to find site at ${s}. Ensure that the site name in your vite configuration is spelled correctly.`);return{name:a,path:s}});if(e.rootSite){let a=(0,b.resolve)(e.sourceRoot,"index.html");if(!(0,O.existsSync)(a))throw new Error(`Failed to find root site at ${a}. Create the missing file or set 'rootSite' to false.`);n.push({name:"index",path:a})}let r={},i=0;for(let{name:a,path:s}of[t,n].flat()){let p=r[a];if(p)throw new Error(`Entry point '${a}' was defined twice (paths ${p} and ${s}). Remove the duplicated entry.`);r[a]=s,++i}if(i===0)throw new Error("You must configure at least one site or one app in the pioneer plugin options.");let o=t.map(({name:a})=>a);return{entryPoints:r,appNames:o}}var Ae=[".ts",".tsx",".js",".jsx"];function Ot(e,t){for(let r of Ae){let i=t+r;if((0,O.existsSync)(i))return i}let n=Ae.join(", ");throw new Error(`Failed to find a matching entry point file for app '${e}' at ${t}. Supported extensions are ${n}. Ensure that the app name is spelled correctly or create the missing file.`)}function Lt(e){return[_e(e),Ie()]}0&&(module.exports={pioneer});
996
+ `);
997
+ function generateI18nIndex(packageDirectory, locales) {
998
+ const localesArray = nodes2.arrayExpression(
999
+ locales.map((locale) => nodes2.stringLiteral(locale))
1000
+ );
1001
+ const switchStmt = nodes2.switchStatement(
1002
+ nodes2.identifier("locale"),
1003
+ locales.map((locale) => {
1004
+ const localeModuleId = serializeModuleId({
1005
+ type: "app-i18n",
1006
+ packageDirectory,
1007
+ locale
1008
+ });
1009
+ const importStatement = IMPORT_TEMPLATE({
1010
+ MODULE_ID: nodes2.stringLiteral(localeModuleId)
1011
+ });
1012
+ return nodes2.switchCase(nodes2.stringLiteral(locale), [importStatement]);
1013
+ })
1014
+ );
1015
+ const program2 = INDEX_TEMPLATE({
1016
+ LOCALES_ARRAY: localesArray,
1017
+ LOCALE_SWITCH: switchStmt
1018
+ });
1019
+ return generate2(program2).code;
1020
+ }
1021
+ async function generateI18nMessages(options) {
1022
+ const { locale, appName, packages, loadI18n } = options;
1023
+ const packageMessages = /* @__PURE__ */ new Map();
1024
+ const packagesNeedingMessages = /* @__PURE__ */ new Set();
1025
+ let packageOverrides;
1026
+ for (const pkg of packages) {
1027
+ if (pkg.i18nPaths.size !== 0) {
1028
+ packagesNeedingMessages.add(pkg.name);
1029
+ }
1030
+ const filePath = pkg.i18nPaths.get(locale);
1031
+ if (!filePath) {
1032
+ continue;
1033
+ }
1034
+ const { messages, overrides } = await loadI18n(filePath);
1035
+ if (pkg.name === appName) {
1036
+ packageOverrides = overrides;
1037
+ } else if (overrides.size !== 0) {
1038
+ throw new ReportableError(
1039
+ `Unexpected 'overrides' block in '${filePath}'. Overrides are only supported in the app.`
1040
+ );
1041
+ }
1042
+ packageMessages.set(pkg.name, messages);
1043
+ }
1044
+ if (packageOverrides) {
1045
+ for (const [packageName, messages] of packageOverrides.entries()) {
1046
+ const existingMessages = packageMessages.get(packageName);
1047
+ if (!existingMessages) {
1048
+ packageMessages.set(packageName, messages);
1049
+ continue;
1050
+ }
1051
+ const updatedMessages = new Map([...existingMessages, ...messages]);
1052
+ packageMessages.set(packageName, updatedMessages);
1053
+ }
1054
+ }
1055
+ for (const packageName of packagesNeedingMessages) {
1056
+ const messages = packageMessages.get(packageName);
1057
+ if (!messages) {
1058
+ throw new ReportableError(
1059
+ `Package '${packageName}' requires messages for locale '${locale}'. Either update the package or add messages from the app via 'overrides'.`
1060
+ );
1061
+ }
1062
+ }
1063
+ const allMessages = {};
1064
+ for (const [packageName, messages] of packageMessages.entries()) {
1065
+ allMessages[packageName] = Object.fromEntries(messages.entries());
1066
+ }
1067
+ const serialized = JSON.stringify(allMessages);
1068
+ const program2 = MESSAGES_TEMPLATE({
1069
+ SERIALIZED: nodes2.stringLiteral(serialized)
1070
+ });
1071
+ return generate2(program2).code;
1072
+ }
1073
+
1074
+ // src/codegenPlugin.ts
1075
+ var isDebug2 = !!process.env.DEBUG;
1076
+ var debug3 = createDebugger("open-pioneer:codegen");
1077
+ function codegenPlugin() {
1078
+ const manualDeps = /* @__PURE__ */ new Map();
1079
+ let config;
1080
+ let repository;
1081
+ let devServer;
1082
+ let reactIntegrationId;
1083
+ let metadataId;
1084
+ return {
1085
+ name: "pioneer:codegen",
1086
+ async buildStart() {
1087
+ manualDeps.clear();
1088
+ repository == null ? void 0 : repository.reset();
1089
+ const resolve2 = async (rawModuleId) => {
1090
+ const resolvedResult = await this.resolve(rawModuleId, __filename);
1091
+ if (!resolvedResult) {
1092
+ this.error(`Failed to find '${rawModuleId}'.`);
1093
+ }
1094
+ return resolvedResult.id;
1095
+ };
1096
+ reactIntegrationId = await resolve2("@open-pioneer/runtime/react-integration");
1097
+ metadataId = await resolve2("@open-pioneer/runtime/metadata");
1098
+ },
1099
+ configResolved(resolvedConfig) {
1100
+ config = resolvedConfig;
1101
+ repository = new MetadataRepository(config.root);
1102
+ },
1103
+ configureServer(server) {
1104
+ devServer = server;
1105
+ server.watcher.on("all", (_, path) => {
1106
+ const moduleIds = manualDeps.get(normalizePath3(path));
1107
+ if (!moduleIds) {
1108
+ return;
1109
+ }
1110
+ isDebug2 && debug3(`File changed: ${path}`);
1111
+ repository.onFileChanged(path);
1112
+ for (const moduleId of moduleIds) {
1113
+ const mod = server.moduleGraph.getModuleById(moduleId);
1114
+ if (mod) {
1115
+ isDebug2 && debug3(`Triggering hmr of ${moduleId}`);
1116
+ server.reloadModule(mod).catch((err) => {
1117
+ config.logger.error(`Failed to trigger hmr`, { error: err });
1118
+ });
1119
+ }
1120
+ }
1121
+ });
1122
+ },
1123
+ async resolveId(moduleId, importer) {
1124
+ try {
1125
+ if (!importer) {
1126
+ return void 0;
1127
+ }
1128
+ if (parseVirtualModuleId(moduleId)) {
1129
+ return moduleId;
1130
+ }
1131
+ const getPackageDirectory = () => {
1132
+ const packageJsonPath = findPackageJson(dirname3(importer), config.root);
1133
+ if (!packageJsonPath) {
1134
+ throw new ReportableError(
1135
+ `Failed to find package.json for package from '${importer}'.`
1136
+ );
1137
+ }
1138
+ const packageDir = dirname3(packageJsonPath);
1139
+ return normalizePath3(packageDir);
1140
+ };
1141
+ if (moduleId === "open-pioneer:app") {
1142
+ return serializeModuleId({
1143
+ type: "app-meta",
1144
+ packageDirectory: getPackageDirectory()
1145
+ });
1146
+ }
1147
+ if (moduleId === "open-pioneer:react-hooks") {
1148
+ return serializeModuleId({
1149
+ type: "package-hooks",
1150
+ packageDirectory: getPackageDirectory()
1151
+ });
1152
+ }
1153
+ } catch (e) {
1154
+ reportError(this, e);
1155
+ }
1156
+ },
1157
+ async load(moduleId) {
1158
+ var _a, _b;
1159
+ try {
1160
+ const mod = parseVirtualModuleId(moduleId);
1161
+ if (!mod) {
1162
+ return void 0;
1163
+ }
1164
+ isDebug2 && debug3("Loading virtual module %O", mod);
1165
+ const packageJsonPath = (_a = await this.resolve(mod.packageDirectory + "/package.json")) == null ? void 0 : _a.id;
1166
+ if (!packageJsonPath) {
1167
+ throw new ReportableError(
1168
+ `Failed to resolve package.json in ${mod.packageDirectory}`
1169
+ );
1170
+ }
1171
+ if (mod.type === "package-hooks") {
1172
+ const directory = mod.packageDirectory;
1173
+ const packageJsonPath2 = (_b = await this.resolve(directory + "/package.json")) == null ? void 0 : _b.id;
1174
+ if (!packageJsonPath2) {
1175
+ throw new ReportableError(`Failed to resolve package.json in ${directory}`);
1176
+ }
1177
+ const packageName = await getPackageName(this, packageJsonPath2);
1178
+ const generatedSourceCode = generateReactHooks(packageName, reactIntegrationId);
1179
+ isDebug2 && debug3("Generated hooks code: %O", generatedSourceCode);
1180
+ return generatedSourceCode;
1181
+ }
1182
+ if (mod.type === "app-meta") {
1183
+ return generateAppMetadata(mod.packageDirectory, metadataId);
1184
+ }
1185
+ const context = buildMetadataContext(this, moduleId, devServer, manualDeps);
1186
+ const appMetadata = await repository.getAppMetadata(
1187
+ context,
1188
+ dirname3(packageJsonPath)
1189
+ );
1190
+ switch (mod.type) {
1191
+ case "app-packages": {
1192
+ const generatedSourceCode = generatePackagesMetadata({
1193
+ appName: appMetadata.name,
1194
+ packages: appMetadata.packages
1195
+ });
1196
+ isDebug2 && debug3("Generated app metadata: %O", generatedSourceCode);
1197
+ return generatedSourceCode;
1198
+ }
1199
+ case "app-css": {
1200
+ const generatedSourceCode = generateCombinedCss(appMetadata.packages);
1201
+ isDebug2 && debug3("Generated app css: %O", generatedSourceCode);
1202
+ return generatedSourceCode;
1203
+ }
1204
+ case "app-i18n-index": {
1205
+ const generatedSourceCode = generateI18nIndex(
1206
+ mod.packageDirectory,
1207
+ appMetadata.locales
1208
+ );
1209
+ isDebug2 && debug3("Generated i18n lookup: %O", generatedSourceCode);
1210
+ return generatedSourceCode;
1211
+ }
1212
+ case "app-i18n": {
1213
+ const generatedSourceCode = await generateI18nMessages({
1214
+ locale: mod.locale,
1215
+ appName: appMetadata.name,
1216
+ packages: appMetadata.packages,
1217
+ loadI18n(path) {
1218
+ return repository.getI18nFile(context, path);
1219
+ }
1220
+ });
1221
+ isDebug2 && debug3("Generated i18n messages: %O", generatedSourceCode);
1222
+ return generatedSourceCode;
1223
+ }
1224
+ }
1225
+ } catch (e) {
1226
+ reportError(this, e);
1227
+ }
1228
+ }
1229
+ };
1230
+ }
1231
+ function buildMetadataContext(ctx, moduleId, devServer, manualDeps) {
1232
+ return {
1233
+ warn: ctx.warn,
1234
+ resolve: ctx.resolve,
1235
+ addWatchFile: (id) => {
1236
+ if (devServer) {
1237
+ isDebug2 && debug3(`Adding manual watch for ${id}`);
1238
+ devServer.watcher.add(id);
1239
+ addManualDep(manualDeps, id, moduleId);
1240
+ }
1241
+ ctx.addWatchFile(id);
1242
+ }
1243
+ };
1244
+ }
1245
+ function reportError(ctx, error) {
1246
+ if (error instanceof ReportableError) {
1247
+ ctx.error(error);
1248
+ }
1249
+ const message = String(error.message) || "Unknown error";
1250
+ ctx.error({
1251
+ message: "Internal error: " + message,
1252
+ cause: error
1253
+ });
1254
+ }
1255
+ function addManualDep(manualDeps, file, moduleId) {
1256
+ const normalizedPath = normalizePath3(file);
1257
+ let moduleIds = manualDeps.get(normalizedPath);
1258
+ if (!moduleIds) {
1259
+ moduleIds = /* @__PURE__ */ new Set();
1260
+ manualDeps.set(normalizedPath, moduleIds);
1261
+ }
1262
+ moduleIds.add(moduleId);
1263
+ }
1264
+ function findPackageJson(startDir, rootDir) {
1265
+ let dir = startDir;
1266
+ while (dir) {
1267
+ const candidate = join2(dir, "package.json");
1268
+ if (existsSync(candidate)) {
1269
+ return candidate;
1270
+ }
1271
+ if (normalizePath3(dir) == normalizePath3(rootDir)) {
1272
+ return void 0;
1273
+ }
1274
+ const parent = dirname3(dir);
1275
+ dir = parent === dir || parent === "." ? "" : parent;
1276
+ }
1277
+ return void 0;
1278
+ }
1279
+ async function getPackageName(ctx, packageJsonPath) {
1280
+ let name;
1281
+ try {
1282
+ const content = await readFile3(packageJsonPath, "utf-8");
1283
+ name = JSON.parse(content).name;
1284
+ } catch (e) {
1285
+ throw new ReportableError(`Failed to read package.json file`, { cause: e });
1286
+ }
1287
+ if (!name) {
1288
+ throw new ReportableError(`Failed to read package name from ${packageJsonPath}.`);
1289
+ }
1290
+ return name;
1291
+ }
1292
+
1293
+ // src/mpaPlugin.ts
1294
+ import { existsSync as existsSync2 } from "node:fs";
1295
+ import { resolve } from "node:path";
1296
+ import { posix } from "node:path";
1297
+ import { cwd } from "node:process";
1298
+ function mpaPlugin(options) {
1299
+ const rootSite = (options == null ? void 0 : options.rootSite) ?? false;
1300
+ const apps = (options == null ? void 0 : options.apps) || [];
1301
+ const sites = (options == null ? void 0 : options.sites) || [];
1302
+ let resolvedConfig;
1303
+ return {
1304
+ name: "pioneer:mpa",
1305
+ config(config) {
1306
+ const sourceRoot = config.root ?? cwd();
1307
+ const { entryPoints, appNames } = gatherEntryPoints({
1308
+ apps,
1309
+ sites,
1310
+ rootSite,
1311
+ sourceRoot
1312
+ });
1313
+ const rollupOptions = {
1314
+ input: entryPoints,
1315
+ output: {
1316
+ entryFileNames(chunk) {
1317
+ if (appNames.includes(chunk.name)) {
1318
+ return "[name].js";
1319
+ }
1320
+ return posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1321
+ },
1322
+ chunkFileNames(chunk) {
1323
+ return posix.join(resolvedConfig.build.assetsDir, "[hash:12].js");
1324
+ }
1325
+ }
1326
+ };
1327
+ return {
1328
+ build: {
1329
+ rollupOptions
1330
+ }
1331
+ };
1332
+ },
1333
+ configResolved(config) {
1334
+ resolvedConfig = config;
1335
+ }
1336
+ };
1337
+ }
1338
+ function gatherEntryPoints(options) {
1339
+ let apps;
1340
+ if (Array.isArray(options.apps)) {
1341
+ apps = options.apps.map((appName) => {
1342
+ const prefix = resolve(options.sourceRoot, "apps", appName, "app");
1343
+ const path = findMatchingEntryPointFile(appName, prefix);
1344
+ return {
1345
+ name: appName,
1346
+ path
1347
+ };
1348
+ });
1349
+ } else {
1350
+ apps = Object.entries(options.apps).map(([name, appPath]) => {
1351
+ const path = resolve(options.sourceRoot, appPath);
1352
+ if (!existsSync2(path)) {
1353
+ throw new Error(
1354
+ `Failed to find app '${name}' at ${path}. Ensure that the path is spelled correctly.`
1355
+ );
1356
+ }
1357
+ return { name, path };
1358
+ });
1359
+ }
1360
+ const sites = options.sites.map((sitePath) => {
1361
+ const path = resolve(options.sourceRoot, sitePath, "index.html");
1362
+ if (!existsSync2(path)) {
1363
+ throw new Error(
1364
+ `Failed to find site at ${path}. Ensure that the site name in your vite configuration is spelled correctly.`
1365
+ );
1366
+ }
1367
+ return {
1368
+ name: sitePath,
1369
+ path
1370
+ };
1371
+ });
1372
+ if (options.rootSite) {
1373
+ const path = resolve(options.sourceRoot, "index.html");
1374
+ if (!existsSync2(path)) {
1375
+ throw new Error(
1376
+ `Failed to find root site at ${path}. Create the missing file or set 'rootSite' to false.`
1377
+ );
1378
+ }
1379
+ sites.push({
1380
+ name: "index",
1381
+ path
1382
+ });
1383
+ }
1384
+ const entryPoints = {};
1385
+ let entryPointCount = 0;
1386
+ for (const { name, path } of [apps, sites].flat()) {
1387
+ const existingPath = entryPoints[name];
1388
+ if (existingPath) {
1389
+ throw new Error(
1390
+ `Entry point '${name}' was defined twice (paths ${existingPath} and ${path}). Remove the duplicated entry.`
1391
+ );
1392
+ }
1393
+ entryPoints[name] = path;
1394
+ ++entryPointCount;
1395
+ }
1396
+ if (entryPointCount === 0) {
1397
+ throw new Error(
1398
+ "You must configure at least one site or one app in the pioneer plugin options."
1399
+ );
1400
+ }
1401
+ const appNames = apps.map(({ name }) => name);
1402
+ return {
1403
+ entryPoints,
1404
+ appNames
1405
+ };
1406
+ }
1407
+ var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
1408
+ function findMatchingEntryPointFile(appName, prefix) {
1409
+ for (const ext of EXTENSIONS) {
1410
+ const candidate = prefix + ext;
1411
+ if (existsSync2(candidate)) {
1412
+ return candidate;
1413
+ }
1414
+ }
1415
+ const extensions = EXTENSIONS.join(", ");
1416
+ throw new Error(
1417
+ `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.`
1418
+ );
1419
+ }
1420
+
1421
+ // src/index.ts
1422
+ function pioneer(options) {
1423
+ return [mpaPlugin(options), codegenPlugin()];
1424
+ }
1425
+ export {
1426
+ pioneer
1427
+ };
86
1428
  //# sourceMappingURL=index.js.map