@shardev/vite-plugin-modular 1.1.1 → 1.2.1

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.cjs CHANGED
@@ -39,56 +39,65 @@ module.exports = __toCommonJS(index_exports);
39
39
  var import_fs = __toESM(require("fs"), 1);
40
40
  var import_path = __toESM(require("path"), 1);
41
41
  function laravelModule(options) {
42
+ const {
43
+ name,
44
+ vendor = "shardevcom",
45
+ srcDir = "resources/react/src",
46
+ input,
47
+ inputs,
48
+ buildDir = `build/${vendor}/${name}`,
49
+ publishedDir = `resources/react/${vendor}/${name}`
50
+ } = options;
51
+ const root = process.cwd();
52
+ const moduleRoot = import_path.default.resolve(root, "packages", vendor, name);
53
+ const relative = import_path.default.relative(moduleRoot, root);
54
+ const isModuleRoot = !relative || relative === "." || !relative.startsWith("..");
55
+ let normalizedInput = {};
56
+ if (input && Object.keys(input).length > 0) {
57
+ for (const [key, file] of Object.entries(input)) {
58
+ normalizedInput[key] = import_path.default.resolve(moduleRoot, file);
59
+ }
60
+ } else {
61
+ const legacyInputs = inputs ?? ["main.tsx"];
62
+ legacyInputs.forEach((file) => {
63
+ const key = import_path.default.parse(file).name;
64
+ normalizedInput[key] = import_path.default.resolve(moduleRoot, srcDir, file);
65
+ });
66
+ }
67
+ const publishedPath = import_path.default.resolve(root, publishedDir);
68
+ const isPublished = import_fs.default.existsSync(publishedPath);
69
+ const aliasPath = isPublished ? publishedPath : import_path.default.resolve(moduleRoot, srcDir);
70
+ const meta = {
71
+ name,
72
+ input: normalizedInput,
73
+ buildDir,
74
+ alias: {
75
+ [`@${vendor}/${name}`]: aliasPath
76
+ },
77
+ usePublished: isPublished
78
+ };
42
79
  return {
43
- name: `vite-plugin-laravel-module:${options.name}`,
44
- config: () => {
45
- const {
46
- name,
47
- vendor = "shardevcom",
48
- srcDir = "resources/react/src",
49
- inputs = ["main.tsx"],
50
- buildDir = `build/${vendor}/${name}`,
51
- publishedDir = `resources/react/${name}`
52
- } = options;
53
- const moduleRoot = import_path.default.resolve(`packages/${vendor}/${name}`);
54
- const isModuleRoot = process.cwd() === moduleRoot;
55
- const inputPaths = {};
56
- inputs.forEach((file) => {
57
- const key = import_path.default.parse(file).name;
58
- inputPaths[key] = import_path.default.resolve(moduleRoot, srcDir, file);
59
- });
60
- const publishedPath = import_path.default.resolve(publishedDir);
61
- const isPublished = import_fs.default.existsSync(publishedPath);
80
+ name: `vite-plugin-laravel-module:${name}`,
81
+ // 🔥 Metadata consumida por laravelModules()
82
+ shardevMeta: meta,
83
+ config() {
62
84
  if (isModuleRoot) {
63
85
  return {
64
86
  build: {
65
87
  outDir: buildDir,
66
88
  emptyOutDir: true,
67
89
  rollupOptions: {
68
- input: inputPaths
90
+ input: normalizedInput
69
91
  }
70
92
  },
71
93
  resolve: {
72
- alias: {
73
- [`@${vendor}/${name}`]: import_path.default.resolve(srcDir)
74
- }
94
+ alias: meta.alias
75
95
  }
76
96
  };
77
97
  }
78
98
  return {
79
- shardevModule: JSON.stringify({
80
- ...options,
81
- srcDir,
82
- input: isPublished ? void 0 : inputPaths,
83
- usePublished: isPublished,
84
- alias: {
85
- [`@${vendor}/${name}`]: isPublished ? publishedPath : import_path.default.resolve(moduleRoot, srcDir)
86
- }
87
- }),
88
99
  resolve: {
89
- alias: {
90
- [`@${vendor}/${name}`]: isPublished ? publishedPath : import_path.default.resolve(moduleRoot, srcDir)
91
- }
100
+ alias: meta.alias
92
101
  }
93
102
  };
94
103
  }
@@ -100,224 +109,132 @@ var import_vite = require("vite");
100
109
  var import_path2 = __toESM(require("path"), 1);
101
110
  var import_fs2 = __toESM(require("fs"), 1);
102
111
  function laravelModules(options = {}) {
103
- const { modulesDir = "packages", statusesFile = "modules.json" } = options;
104
- const modulesPath = import_path2.default.resolve(process.cwd(), modulesDir);
105
- const statusesPath = import_path2.default.resolve(process.cwd(), statusesFile);
112
+ const {
113
+ modulesDir = "packages",
114
+ statusesFile = "modules.json",
115
+ debug = false,
116
+ useMetaCache = true
117
+ } = options;
106
118
  const root = process.cwd();
107
- const findLaravelPlugin = (plugins) => {
108
- const flattenPlugins = (plugins2) => {
109
- return plugins2.flatMap((plugin) => {
110
- if (Array.isArray(plugin)) {
111
- return flattenPlugins(plugin);
112
- }
113
- return plugin && typeof plugin === "object" && "name" in plugin ? [plugin] : [];
114
- });
115
- };
116
- const flatPlugins = flattenPlugins(plugins);
117
- return flatPlugins.find((plugin) => plugin?.name === "laravel") ?? null;
118
- };
119
- const normalizePath = (id) => {
120
- let cleanPath = id.replace(/^[\/\\]+/, "").split("?")[0].split("#")[0];
121
- cleanPath = cleanPath.replace(/\\/g, "/");
122
- const normalizedRoot = root.replace(/\\/g, "/");
123
- if (cleanPath.startsWith(normalizedRoot)) {
124
- cleanPath = cleanPath.slice(normalizedRoot.length).replace(/^\/+/, "");
125
- }
126
- return cleanPath;
127
- };
128
- const parseNamespace = (id) => {
129
- const cleanPath = normalizePath(id);
130
- const patterns = [
131
- /^([\w.-]+):([\w.-]+)::(.+)$/,
132
- // vendor:pkg::file
133
- /^packages\/([^/]+)\/([^/]+)\/resources\/react\/src\/(.+)$/,
134
- // packages/vendor/pkg/resources/react/src/file
135
- /^resources\/react\/([^/]+)\/([^/]+)\/src\/(.+)$/
136
- // resources/react/vendor/pkg/src/file
137
- ];
138
- for (const pattern of patterns) {
139
- const match = cleanPath.match(pattern);
140
- if (match) {
141
- return { vendor: match[1], pkg: match[2], file: match[3] };
142
- }
143
- }
144
- return null;
119
+ const modulesPath = import_path2.default.resolve(root, modulesDir);
120
+ const statusesPath = import_path2.default.resolve(root, statusesFile);
121
+ let cachedMetas = [];
122
+ let metaCacheLoaded = false;
123
+ const log = (...args) => {
124
+ if (debug) console.log("[laravel-modules]", ...args);
145
125
  };
146
- const resolveNamespacedToFs = (vendor, pkg, file) => {
147
- const paths = [
148
- import_path2.default.join(root, "resources", "react", vendor, pkg, "src", file),
149
- // Published path
150
- import_path2.default.join(root, "packages", vendor, pkg, "resources", "react", "src", file)
151
- // Workspace path
152
- ];
153
- return paths.find(import_fs2.default.existsSync) || null;
154
- };
155
- const loadModuleStatuses = () => {
126
+ const loadStatuses = () => {
127
+ if (!import_fs2.default.existsSync(statusesPath)) return {};
156
128
  try {
157
- if (import_fs2.default.existsSync(statusesPath)) {
158
- return JSON.parse(import_fs2.default.readFileSync(statusesPath, "utf-8"));
159
- }
160
- } catch (error) {
161
- console.warn("[laravel-modules] Failed to load module statuses:", error);
129
+ return JSON.parse(import_fs2.default.readFileSync(statusesPath, "utf-8"));
130
+ } catch {
131
+ return {};
162
132
  }
163
- return {};
164
133
  };
165
- const getInputArray = (input) => {
166
- return Array.isArray(input) ? input : Object.values(input || {});
134
+ const validateMeta = (meta) => {
135
+ if (!meta.name) throw new Error("Module meta missing name");
136
+ if (!meta.srcDir) throw new Error(`Module ${meta.name} missing srcDir`);
137
+ if (!meta.input) throw new Error(`Module ${meta.name} missing input`);
167
138
  };
168
- const discoverModules = async (statuses) => {
139
+ const discoverModules = async () => {
140
+ if (useMetaCache && metaCacheLoaded) {
141
+ log("Using cached module metas");
142
+ return cachedMetas;
143
+ }
169
144
  if (!import_fs2.default.existsSync(modulesPath)) return [];
170
- const plugins = [];
171
- const vendors = import_fs2.default.readdirSync(modulesPath, { withFileTypes: true }).filter((dirent) => dirent.isDirectory());
145
+ const statuses = loadStatuses();
146
+ const metas = [];
147
+ const vendors = import_fs2.default.readdirSync(modulesPath, { withFileTypes: true }).filter((d) => d.isDirectory());
172
148
  for (const vendor of vendors) {
173
149
  const vendorPath = import_path2.default.join(modulesPath, vendor.name);
174
- const packages = import_fs2.default.readdirSync(vendorPath, { withFileTypes: true }).filter((dirent) => dirent.isDirectory() && statuses[dirent.name] !== false);
150
+ const packages = import_fs2.default.readdirSync(vendorPath, { withFileTypes: true }).filter((d) => d.isDirectory() && statuses[d.name] !== false);
175
151
  for (const pkg of packages) {
176
152
  const pkgPath = import_path2.default.join(vendorPath, pkg.name);
177
153
  const viteConfigPath = import_path2.default.join(pkgPath, "vite.config.ts");
178
154
  if (!import_fs2.default.existsSync(viteConfigPath)) continue;
179
- try {
180
- const server = await (0, import_vite.createServer)({
181
- configFile: viteConfigPath,
182
- logLevel: "silent"
183
- });
184
- plugins.push(...server.config.plugins);
185
- await server.close();
186
- } catch (error) {
187
- console.warn(`[laravel-modules] Error loading ${viteConfigPath}:`, error);
155
+ const server = await (0, import_vite.createServer)({
156
+ configFile: viteConfigPath,
157
+ logLevel: "silent"
158
+ });
159
+ const plugins = server.config.plugins || [];
160
+ for (const plugin of plugins) {
161
+ if (plugin?.name?.startsWith("vite-plugin-laravel-module:")) {
162
+ const meta = plugin.shardevMeta;
163
+ if (meta) {
164
+ validateMeta(meta);
165
+ metas.push(meta);
166
+ }
167
+ }
188
168
  }
169
+ await server.close();
189
170
  }
190
171
  }
191
- return plugins;
172
+ cachedMetas = metas;
173
+ metaCacheLoaded = true;
174
+ log("Discovered modules:", metas.map((m) => m.name));
175
+ return metas;
192
176
  };
193
- const extractModuleMetadata = (plugins) => {
194
- const aliases = {};
195
- const moduleConfigs = [];
196
- plugins.forEach((plugin) => {
197
- if (!plugin?.name?.startsWith("vite-plugin-laravel-module:")) {
198
- return;
199
- }
200
- let resolvedConfig;
201
- if (typeof plugin.config === "function") {
202
- const fn = plugin.config;
203
- resolvedConfig = fn({});
204
- }
205
- if (!resolvedConfig?.shardevModule) return;
206
- try {
207
- const meta = JSON.parse(resolvedConfig?.shardevModule);
208
- if (meta.alias) Object.assign(aliases, meta.alias);
209
- if (!meta.usePublished && meta.input) moduleConfigs.push(meta);
210
- } catch (error) {
211
- console.warn("[laravel-modules] Failed to parse module metadata:", error);
212
- }
213
- });
214
- return { aliases, moduleConfigs };
215
- };
216
- const generateRollupInputs = (moduleConfigs) => {
177
+ const generateInputs = (metas) => {
217
178
  const inputs = {};
218
- moduleConfigs.forEach((mod) => {
219
- const modInputs = getInputArray(mod.input);
220
- modInputs.forEach((inputPath, idx) => {
221
- const name = modInputs.length > 1 ? `${mod.name}-${idx}` : mod.name;
222
- inputs[name] = inputPath;
179
+ metas.forEach((meta) => {
180
+ Object.entries(meta.input).forEach(([key, value]) => {
181
+ inputs[`${meta.name}-${key}`] = value;
223
182
  });
224
183
  });
225
184
  return inputs;
226
185
  };
227
- function getLaravelResolvedConfig(plugin, config, env) {
228
- if (!plugin.config || typeof plugin.config !== "function") return null;
229
- try {
230
- const fn = plugin.config;
231
- const result = fn(config, env);
232
- return result && typeof result === "object" ? result : null;
233
- } catch (error) {
234
- console.warn("[laravel-modules] Failed to get Laravel config:", error);
235
- return null;
236
- }
237
- }
238
- function extractAliases(config) {
239
- const alias = config?.resolve?.alias;
240
- if (!alias) return {};
241
- if (Array.isArray(alias)) {
242
- return alias.reduce((acc, item) => {
243
- if (item && typeof item.find === "string" && typeof item.replacement === "string") {
244
- acc[item.find] = item.replacement;
245
- }
246
- return acc;
247
- }, {});
248
- }
249
- if (typeof alias === "object") {
250
- return { ...alias };
251
- }
252
- return {};
253
- }
186
+ const resolveWatchPath = (meta) => {
187
+ const base = meta.usePublished && meta.publishedDir ? meta.publishedDir : meta.srcDir;
188
+ if (!base) return null;
189
+ return import_path2.default.isAbsolute(base) ? base : import_path2.default.resolve(root, base);
190
+ };
191
+ const handleHMR = (server, file) => {
192
+ const module2 = server.moduleGraph.getModuleById(file);
193
+ if (!module2) return;
194
+ log("HMR update:", file);
195
+ const updates = [{
196
+ type: "js-update",
197
+ path: module2.url,
198
+ acceptedPath: module2.url,
199
+ timestamp: Date.now()
200
+ }];
201
+ server.moduleGraph.invalidateModule(module2);
202
+ server.ws.send({
203
+ type: "update",
204
+ updates
205
+ });
206
+ };
254
207
  return {
255
208
  name: "laravel-modules",
256
209
  async config(config, env) {
257
- const statuses = loadModuleStatuses();
258
- const modules = await discoverModules(statuses);
210
+ const metas = await discoverModules();
259
211
  const aliases = {};
260
- const moduleConfigs = [];
261
- const laravelPlugin = findLaravelPlugin(config.plugins || []);
262
- if (laravelPlugin && laravelPlugin?.config) {
263
- try {
264
- const laravelConfig = getLaravelResolvedConfig(laravelPlugin, config, env);
265
- if (!laravelConfig) throw new Error("Invalid Laravel config");
266
- moduleConfigs.push({
267
- name: "main",
268
- input: getInputArray(laravelConfig?.build?.rollupOptions?.input || []),
269
- buildDir: laravelConfig?.build?.buildDir || "build",
270
- alias: extractAliases(laravelConfig)
271
- });
272
- } catch (error) {
273
- console.warn("[laravel-modules] Failed to extract Laravel plugin config:", error);
274
- }
275
- }
276
- const { aliases: moduleAliases, moduleConfigs: extractedConfigs } = extractModuleMetadata(modules);
277
- Object.assign(aliases, moduleAliases);
278
- moduleConfigs.push(...extractedConfigs);
279
- const rollupInputs = generateRollupInputs(moduleConfigs);
212
+ metas.forEach((meta) => Object.assign(aliases, meta.alias));
213
+ const rollupInputs = generateInputs(metas);
280
214
  return (0, import_vite.mergeConfig)(config, {
281
- resolve: {
282
- alias: aliases
283
- },
215
+ resolve: { alias: aliases },
284
216
  build: {
285
- rollupOptions: {
286
- input: rollupInputs
287
- }
217
+ rollupOptions: { input: rollupInputs }
288
218
  }
289
219
  });
290
220
  },
291
- resolveId(source) {
292
- const ns = parseNamespace(source);
293
- if (!ns) return null;
294
- const resolved = resolveNamespacedToFs(ns.vendor, ns.pkg, ns.file);
295
- if (resolved) return resolved;
296
- return null;
297
- },
298
- writeBundle(_, bundle) {
299
- const manifestFile = Object.keys(bundle).find((f) => f === "manifest.json");
300
- if (!manifestFile) return;
301
- const asset = bundle[manifestFile];
302
- if (asset?.type !== "asset" || typeof asset.source !== "string") return;
303
- try {
304
- const manifest = JSON.parse(asset.source);
305
- const rewritten = { ...manifest };
306
- for (const [src, data] of Object.entries(manifest)) {
307
- const ns = parseNamespace(src);
308
- if (ns) {
309
- const aliasKey = `${ns.vendor}:${ns.pkg}::${ns.file}`;
310
- rewritten[aliasKey] = data;
311
- }
221
+ async configureServer(server) {
222
+ const metas = await discoverModules();
223
+ for (const meta of metas) {
224
+ const watchPath = resolveWatchPath(meta);
225
+ if (watchPath && import_fs2.default.existsSync(watchPath)) {
226
+ server.watcher.add(watchPath);
227
+ log("Watching:", watchPath);
312
228
  }
313
- asset.source = JSON.stringify(rewritten, null, 2);
314
- const outDir = _.dir || import_path2.default.dirname(_.file || "");
315
- const outPath = import_path2.default.join(outDir, manifestFile);
316
- import_fs2.default.writeFileSync(outPath, asset.source, "utf-8");
317
- console.log("[laravel-modules] Manifest namespaced keys injected");
318
- } catch (error) {
319
- console.warn("[laravel-modules] Failed to process manifest:", error);
320
229
  }
230
+ server.watcher.on("change", (file) => {
231
+ const matched = metas.some((meta) => {
232
+ const watchPath = resolveWatchPath(meta);
233
+ return watchPath && file.startsWith(watchPath);
234
+ });
235
+ if (!matched) return;
236
+ handleHMR(server, file);
237
+ });
321
238
  }
322
239
  };
323
240
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/laravelModule.ts","../src/laravelModules.ts"],"sourcesContent":["export { default as laravelModule } from './laravelModule';\r\nexport { default as laravelModules } from './laravelModules';","import fs from 'fs';\nimport path from 'path';\nimport type { PluginOption } from 'vite';\n\ninterface ModuleOptions {\n name: string;\n vendor?: string;\n srcDir?: string;\n inputs?: string[];\n buildDir?: string;\n publishedDir?: string;\n}\n\nexport default function laravelModule(options: ModuleOptions): PluginOption {\n return {\n name: `vite-plugin-laravel-module:${options.name}`,\n config: () => {\n const {\n name,\n vendor = 'shardevcom',\n srcDir = 'resources/react/src',\n inputs = ['main.tsx'],\n buildDir = `build/${vendor}/${name}`,\n publishedDir = `resources/react/${name}`\n } = options;\n\n const moduleRoot = path.resolve(`packages/${vendor}/${name}`);\n const isModuleRoot = process.cwd() === moduleRoot;\n\n const inputPaths: Record<string, string> = {};\n inputs.forEach((file) => {\n const key = path.parse(file).name;\n inputPaths[key] = path.resolve(moduleRoot, srcDir, file);\n });\n\n const publishedPath = path.resolve(publishedDir);\n const isPublished = fs.existsSync(publishedPath);\n\n if (isModuleRoot) {\n return {\n build: {\n outDir: buildDir,\n emptyOutDir: true,\n rollupOptions: {\n input: inputPaths\n }\n },\n resolve: {\n alias: {\n [`@${vendor}/${name}`]: path.resolve(srcDir)\n }\n }\n };\n }\n\n return {\n shardevModule: JSON.stringify({\n ...options,\n srcDir,\n input: isPublished ? undefined : inputPaths,\n usePublished: isPublished,\n alias: {\n [`@${vendor}/${name}`]: isPublished ? publishedPath : path.resolve(moduleRoot, srcDir)\n }\n }),\n resolve: {\n alias: {\n [`@${vendor}/${name}`]: isPublished ? publishedPath : path.resolve(moduleRoot, srcDir)\n }\n }\n };\n }\n };\n}\n","import type { Plugin, UserConfig, PluginOption, ConfigEnv } from 'vite';\nimport { mergeConfig, createServer } from 'vite';\nimport path from 'path';\nimport fs from 'fs';\n\ninterface LaravelModulesOptions {\n modulesDir?: string;\n statusesFile?: string;\n}\n\ninterface ModuleConfigMeta {\n name: string;\n input: string[];\n buildDir: string;\n alias?: Record<string, string>;\n usePublished?: boolean;\n}\n\ninterface ParsedNamespace {\n vendor: string;\n pkg: string;\n file: string;\n}\n\nexport interface ShardevUserConfig extends UserConfig {\n shardevModule?: string; // JSON.stringify(ModuleConfigMeta)\n}\n\ninterface LaravelResolvedConfig {\n build?: {\n rollupOptions?: {\n input?: string[] | Record<string, string>;\n };\n buildDir?: string;\n };\n resolve?: {\n alias?: Record<string, string> | Array<{ find: string | RegExp, replacement: string }>;\n };\n}\n\ninterface ModuleDiscoveryResult {\n aliases: Record<string, string>;\n moduleConfigs: ModuleConfigMeta[];\n}\n\n/**\n * Laravel Modules Plugin for Vite\n *\n * This plugin enables Vite to work with Laravel modules by:\n * 1. Discovering and loading module configurations\n * 2. Resolving module-specific aliases\n * 3. Handling namespace resolution for modules\n * 4. Processing manifest files for proper asset handling\n */\nexport default function laravelModules(options: LaravelModulesOptions = {}): Plugin {\n const { modulesDir = 'packages', statusesFile = 'modules.json' } = options;\n const modulesPath = path.resolve(process.cwd(), modulesDir);\n const statusesPath = path.resolve(process.cwd(), statusesFile);\n const root = process.cwd();\n\n /**\n * Finds the Laravel plugin instance within the main Vite config\n */\n const findLaravelPlugin = (plugins: PluginOption[]): Plugin | null => {\n const flattenPlugins = (plugins: PluginOption[]): Plugin[] => {\n return plugins.flatMap(plugin => {\n if (Array.isArray(plugin)) {\n return flattenPlugins(plugin);\n }\n return plugin && typeof plugin === 'object' && 'name' in plugin ? [plugin] : [];\n });\n };\n\n const flatPlugins = flattenPlugins(plugins);\n return flatPlugins.find(plugin => plugin?.name === 'laravel') ?? null;\n };\n\n /**\n * Normalizes path by removing query/hash and standardizing separators\n */\n const normalizePath = (id: string): string => {\n // Remove query/hash and leading slashes\n let cleanPath = id.replace(/^[\\/\\\\]+/, '').split('?')[0].split('#')[0];\n\n // Normalize separators to forward slashes\n cleanPath = cleanPath.replace(/\\\\/g, '/');\n\n // Remove root prefix if present\n const normalizedRoot = root.replace(/\\\\/g, '/');\n if (cleanPath.startsWith(normalizedRoot)) {\n cleanPath = cleanPath.slice(normalizedRoot.length).replace(/^\\/+/, '');\n }\n\n return cleanPath;\n };\n\n /**\n * Parses namespace from path using multiple patterns\n */\n const parseNamespace = (id: string): ParsedNamespace | null => {\n const cleanPath = normalizePath(id);\n\n const patterns = [\n /^([\\w.-]+):([\\w.-]+)::(.+)$/, // vendor:pkg::file\n /^packages\\/([^/]+)\\/([^/]+)\\/resources\\/react\\/src\\/(.+)$/, // packages/vendor/pkg/resources/react/src/file\n /^resources\\/react\\/([^/]+)\\/([^/]+)\\/src\\/(.+)$/ // resources/react/vendor/pkg/src/file\n ];\n\n for (const pattern of patterns) {\n const match = cleanPath.match(pattern);\n if (match) {\n return { vendor: match[1], pkg: match[2], file: match[3] };\n }\n }\n\n return null;\n };\n\n /**\n * Resolves namespace to filesystem path\n */\n const resolveNamespacedToFs = (vendor: string, pkg: string, file: string): string | null => {\n const paths = [\n path.join(root, 'resources', 'react', vendor, pkg, 'src', file), // Published path\n path.join(root, 'packages', vendor, pkg, 'resources', 'react', 'src', file) // Workspace path\n ];\n\n return paths.find(fs.existsSync) || null;\n };\n\n /**\n * Loads module activation statuses from JSON file\n */\n const loadModuleStatuses = (): Record<string, boolean> => {\n try {\n if (fs.existsSync(statusesPath)) {\n return JSON.parse(fs.readFileSync(statusesPath, 'utf-8'));\n }\n } catch (error) {\n console.warn('[laravel-modules] Failed to load module statuses:', error);\n }\n\n return {};\n };\n\n /**\n * Extracts input array from various input formats\n */\n const getInputArray = (input: string[] | Record<string, string>): string[] => {\n return Array.isArray(input) ? input : Object.values(input || {});\n };\n\n /**\n * Discovers all active modules with a vite.config.* file\n */\n const discoverModules = async (statuses: Record<string, boolean>): Promise<Plugin[]> => {\n if (!fs.existsSync(modulesPath)) return [];\n\n const plugins: Plugin[] = [];\n const vendors = fs.readdirSync(modulesPath, { withFileTypes: true })\n .filter(dirent => dirent.isDirectory());\n\n for (const vendor of vendors) {\n const vendorPath = path.join(modulesPath, vendor.name);\n const packages = fs.readdirSync(vendorPath, { withFileTypes: true })\n .filter(dirent => dirent.isDirectory() && (statuses[dirent.name] !== false));\n\n for (const pkg of packages) {\n const pkgPath = path.join(vendorPath, pkg.name);\n const viteConfigPath = path.join(pkgPath, 'vite.config.ts');\n\n if (!fs.existsSync(viteConfigPath)) continue;\n\n try {\n const server = await createServer({\n configFile: viteConfigPath,\n logLevel: 'silent'\n });\n\n // 🚨 Aquí capturamos los plugins del módulo\n plugins.push(...(server.config.plugins as Plugin[]));\n await server.close();\n } catch (error) {\n console.warn(`[laravel-modules] Error loading ${viteConfigPath}:`, error);\n }\n }\n }\n\n return plugins;\n };\n\n\n /**\n * Extracts module metadata from plugins\n */\n const extractModuleMetadata = (plugins: Plugin[]): ModuleDiscoveryResult => {\n const aliases: Record<string, string> = {};\n const moduleConfigs: ModuleConfigMeta[] = [];\n\n plugins.forEach(plugin => {\n\n if (!plugin?.name?.startsWith(\"vite-plugin-laravel-module:\")) {\n return;\n }\n\n let resolvedConfig: ShardevUserConfig | undefined;\n if (typeof plugin.config === \"function\") {\n const fn = plugin.config as (config: ShardevUserConfig, env?: ConfigEnv) => ShardevUserConfig;\n resolvedConfig = fn({}) as ShardevUserConfig;\n }\n\n if (!resolvedConfig?.shardevModule) return;\n\n try {\n const meta: ModuleConfigMeta = JSON.parse(resolvedConfig?.shardevModule);\n if (meta.alias) Object.assign(aliases, meta.alias);\n if (!meta.usePublished && meta.input) moduleConfigs.push(meta);\n } catch (error) {\n console.warn('[laravel-modules] Failed to parse module metadata:', error);\n }\n });\n\n return { aliases, moduleConfigs };\n };\n\n /**\n * Generates rollup inputs from module configurations\n */\n const generateRollupInputs = (moduleConfigs: ModuleConfigMeta[]): Record<string, string> => {\n const inputs: Record<string, string> = {};\n\n moduleConfigs.forEach(mod => {\n const modInputs = getInputArray(mod.input);\n modInputs.forEach((inputPath, idx) => {\n const name = modInputs.length > 1 ? `${mod.name}-${idx}` : mod.name;\n inputs[name] = inputPath;\n });\n });\n\n return inputs;\n };\n\n /**\n * Retrieves resolved Laravel configuration from the plugin\n */\n function getLaravelResolvedConfig(plugin: Plugin, config: UserConfig, env: ConfigEnv) {\n if (!plugin.config || typeof plugin.config !== 'function') return null;\n\n try {\n const fn = plugin.config as (config: UserConfig, env?: ConfigEnv) => LaravelResolvedConfig;\n const result = fn(config, env) as LaravelResolvedConfig;\n return result && typeof result === 'object' ? result : null;\n } catch (error) {\n console.warn('[laravel-modules] Failed to get Laravel config:', error);\n return null;\n }\n }\n\n /**\n * Extracts aliases from Laravel config\n */\n function extractAliases(config: LaravelResolvedConfig): Record<string, string> {\n const alias = config?.resolve?.alias;\n\n if (!alias) return {};\n\n if (Array.isArray(alias)) {\n // Convertir array format [{ find: 'foo', replacement: 'bar' }] to object { foo: 'bar' }\n return alias.reduce((acc, item) => {\n if (item && typeof item.find === 'string' && typeof item.replacement === 'string') {\n acc[item.find] = item.replacement;\n }\n return acc;\n }, {} as Record<string, string>);\n }\n\n if (typeof alias === 'object') {\n return { ...alias };\n }\n\n return {};\n }\n\n\n return {\n name: 'laravel-modules',\n\n async config(config: UserConfig, env) {\n const statuses = loadModuleStatuses();\n const modules = await discoverModules(statuses);\n\n const aliases: Record<string, string> = {};\n const moduleConfigs: ModuleConfigMeta[] = [];\n\n // Extract main Laravel config\n const laravelPlugin = findLaravelPlugin(config.plugins || []);\n if (laravelPlugin && laravelPlugin?.config) {\n try {\n const laravelConfig = getLaravelResolvedConfig(laravelPlugin, config, env);\n if (!laravelConfig) throw new Error('Invalid Laravel config');\n moduleConfigs.push({\n name: 'main',\n input: getInputArray(laravelConfig?.build?.rollupOptions?.input || []),\n buildDir: laravelConfig?.build?.buildDir || 'build',\n alias: extractAliases(laravelConfig)\n });\n } catch (error) {\n console.warn('[laravel-modules] Failed to extract Laravel plugin config:', error);\n }\n }\n\n // Extract module metadata\n const { aliases: moduleAliases, moduleConfigs: extractedConfigs } = extractModuleMetadata(modules);\n Object.assign(aliases, moduleAliases);\n moduleConfigs.push(...extractedConfigs);\n\n // Generate rollup inputs\n const rollupInputs = generateRollupInputs(moduleConfigs);\n\n // Merge with main config\n return mergeConfig(config, {\n resolve: {\n alias: aliases\n },\n build: {\n rollupOptions: {\n input: rollupInputs\n }\n }\n });\n },\n\n resolveId(source: string) {\n const ns = parseNamespace(source);\n if (!ns) return null;\n\n const resolved = resolveNamespacedToFs(ns.vendor, ns.pkg, ns.file);\n if (resolved) return resolved;\n\n //this.warn(`[laravel-modules] Not found: ${ns.vendor}:${ns.pkg}::${ns.file}`);\n return null;\n },\n\n writeBundle(_, bundle) {\n const manifestFile = Object.keys(bundle).find(f => f === 'manifest.json');\n if (!manifestFile) return;\n\n const asset = bundle[manifestFile];\n if (asset?.type !== 'asset' || typeof asset.source !== 'string') return;\n\n try {\n const manifest = JSON.parse(asset.source);\n const rewritten: Record<string, unknown> = { ...manifest };\n\n // Add namespaced entries\n for (const [src, data] of Object.entries<unknown>(manifest)) {\n const ns = parseNamespace(src);\n if (ns) {\n const aliasKey = `${ns.vendor}:${ns.pkg}::${ns.file}`;\n rewritten[aliasKey] = data;\n }\n }\n\n\n // Write updated manifest\n asset.source = JSON.stringify(rewritten, null, 2);\n const outDir = _.dir || path.dirname(_.file || '');\n const outPath = path.join(outDir, manifestFile);\n\n fs.writeFileSync(outPath, asset.source, 'utf-8');\n console.log('[laravel-modules] Manifest namespaced keys injected');\n } catch (error) {\n console.warn('[laravel-modules] Failed to process manifest:', error);\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAAe;AACf,kBAAiB;AAYF,SAAR,cAA+B,SAAsC;AACxE,SAAO;AAAA,IACH,MAAM,8BAA8B,QAAQ,IAAI;AAAA,IAChD,QAAQ,MAAM;AACV,YAAM;AAAA,QACF;AAAA,QACA,SAAS;AAAA,QACT,SAAS;AAAA,QACT,SAAS,CAAC,UAAU;AAAA,QACpB,WAAW,SAAS,MAAM,IAAI,IAAI;AAAA,QAClC,eAAe,mBAAmB,IAAI;AAAA,MAC1C,IAAI;AAEJ,YAAM,aAAa,YAAAA,QAAK,QAAQ,YAAY,MAAM,IAAI,IAAI,EAAE;AAC5D,YAAM,eAAe,QAAQ,IAAI,MAAM;AAEvC,YAAM,aAAqC,CAAC;AAC5C,aAAO,QAAQ,CAAC,SAAS;AACrB,cAAM,MAAM,YAAAA,QAAK,MAAM,IAAI,EAAE;AAC7B,mBAAW,GAAG,IAAI,YAAAA,QAAK,QAAQ,YAAY,QAAQ,IAAI;AAAA,MAC3D,CAAC;AAED,YAAM,gBAAgB,YAAAA,QAAK,QAAQ,YAAY;AAC/C,YAAM,cAAc,UAAAC,QAAG,WAAW,aAAa;AAE/C,UAAI,cAAc;AACd,eAAO;AAAA,UACH,OAAO;AAAA,YACH,QAAQ;AAAA,YACR,aAAa;AAAA,YACb,eAAe;AAAA,cACX,OAAO;AAAA,YACX;AAAA,UACJ;AAAA,UACA,SAAS;AAAA,YACL,OAAO;AAAA,cACH,CAAC,IAAI,MAAM,IAAI,IAAI,EAAE,GAAG,YAAAD,QA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fs","path","plugins","fs"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/laravelModule.ts","../src/laravelModules.ts"],"sourcesContent":["export { laravelModule } from './laravelModule'\r\nexport { laravelModules } from './laravelModules'","import fs from 'fs'\nimport path from 'path'\nimport type { PluginOption } from 'vite'\n\nexport interface ModuleOptions {\n name: string\n vendor?: string\n srcDir?: string\n\n // ✅ Nuevo formato recomendado\n input?: Record<string, string>\n\n // ⚠ Backward compatibility\n inputs?: string[]\n\n buildDir?: string\n publishedDir?: string\n}\n\nexport interface ShardevModuleMeta {\n name: string\n input: Record<string, string>\n buildDir: string\n alias: Record<string, string>\n usePublished: boolean\n}\n\nexport function laravelModule(options: ModuleOptions): PluginOption {\n\n const {\n name,\n vendor = 'shardevcom',\n srcDir = 'resources/react/src',\n input,\n inputs,\n buildDir = `build/${vendor}/${name}`,\n publishedDir = `resources/react/${vendor}/${name}`\n } = options\n\n const root = process.cwd()\n const moduleRoot = path.resolve(root, 'packages', vendor, name)\n\n const relative = path.relative(moduleRoot, root)\n const isModuleRoot =\n !relative || relative === '.' || !relative.startsWith('..')\n\n // ---------------------------------------------------\n // 🔥 Normalización inteligente de inputs\n // ---------------------------------------------------\n\n let normalizedInput: Record<string, string> = {}\n\n if (input && Object.keys(input).length > 0) {\n // Nuevo formato recomendado\n for (const [key, file] of Object.entries(input)) {\n normalizedInput[key] = path.resolve(moduleRoot, file)\n }\n } else {\n // Backward compatibility con inputs: []\n const legacyInputs = inputs ?? ['main.tsx']\n\n legacyInputs.forEach(file => {\n const key = path.parse(file).name\n normalizedInput[key] = path.resolve(moduleRoot, srcDir, file)\n })\n }\n\n // ---------------------------------------------------\n // Published detection\n // ---------------------------------------------------\n\n const publishedPath = path.resolve(root, publishedDir)\n const isPublished = fs.existsSync(publishedPath)\n\n const aliasPath = isPublished\n ? publishedPath\n : path.resolve(moduleRoot, srcDir)\n\n const meta: ShardevModuleMeta = {\n name,\n input: normalizedInput,\n buildDir,\n alias: {\n [`@${vendor}/${name}`]: aliasPath\n },\n usePublished: isPublished\n }\n\n return {\n name: `vite-plugin-laravel-module:${name}`,\n\n // 🔥 Metadata consumida por laravelModules()\n shardevMeta: meta,\n\n config() {\n\n // 🔹 Standalone build\n if (isModuleRoot) {\n return {\n build: {\n outDir: buildDir,\n emptyOutDir: true,\n rollupOptions: {\n input: normalizedInput\n }\n },\n resolve: {\n alias: meta.alias\n }\n }\n }\n\n // 🔹 Integrated mode\n return {\n resolve: {\n alias: meta.alias\n }\n }\n }\n\n } as PluginOption\n}","import type { Plugin, UserConfig, ConfigEnv, ViteDevServer, ModuleNode } from 'vite'\nimport { mergeConfig, createServer } from 'vite'\nimport path from 'path'\nimport fs from 'fs'\n\ninterface LaravelModulesOptions {\n modulesDir?: string\n statusesFile?: string\n debug?: boolean\n useMetaCache?: boolean\n}\n\ninterface ShardevModuleMeta {\n name: string\n input: Record<string, string>\n buildDir: string\n alias: Record<string, string>\n usePublished: boolean\n srcDir: string\n publishedDir?: string\n}\n\nexport function laravelModules(\n options: LaravelModulesOptions = {}\n): Plugin {\n\n const {\n modulesDir = 'packages',\n statusesFile = 'modules.json',\n debug = false,\n useMetaCache = true\n } = options\n\n const root = process.cwd()\n const modulesPath = path.resolve(root, modulesDir)\n const statusesPath = path.resolve(root, statusesFile)\n\n let cachedMetas: ShardevModuleMeta[] = []\n let metaCacheLoaded = false\n\n const log = (...args: any[]) => {\n if (debug) console.log('[laravel-modules]', ...args)\n }\n\n const loadStatuses = (): Record<string, boolean> => {\n if (!fs.existsSync(statusesPath)) return {}\n try {\n return JSON.parse(fs.readFileSync(statusesPath, 'utf-8'))\n } catch {\n return {}\n }\n }\n\n const validateMeta = (meta: ShardevModuleMeta) => {\n if (!meta.name) throw new Error('Module meta missing name')\n if (!meta.srcDir) throw new Error(`Module ${meta.name} missing srcDir`)\n if (!meta.input) throw new Error(`Module ${meta.name} missing input`)\n }\n\n const discoverModules = async (): Promise<ShardevModuleMeta[]> => {\n\n if (useMetaCache && metaCacheLoaded) {\n log('Using cached module metas')\n return cachedMetas\n }\n\n if (!fs.existsSync(modulesPath)) return []\n\n const statuses = loadStatuses()\n const metas: ShardevModuleMeta[] = []\n\n const vendors = fs.readdirSync(modulesPath, { withFileTypes: true })\n .filter(d => d.isDirectory())\n\n for (const vendor of vendors) {\n const vendorPath = path.join(modulesPath, vendor.name)\n\n const packages = fs.readdirSync(vendorPath, { withFileTypes: true })\n .filter(d => d.isDirectory() && statuses[d.name] !== false)\n\n for (const pkg of packages) {\n\n const pkgPath = path.join(vendorPath, pkg.name)\n const viteConfigPath = path.join(pkgPath, 'vite.config.ts')\n\n if (!fs.existsSync(viteConfigPath)) continue\n\n const server = await createServer({\n configFile: viteConfigPath,\n logLevel: 'silent'\n })\n\n const plugins = (server.config.plugins || []) as Plugin[]\n\n for (const plugin of plugins) {\n if (plugin?.name?.startsWith('vite-plugin-laravel-module:')) {\n const meta = (plugin as any).shardevMeta as ShardevModuleMeta\n if (meta) {\n validateMeta(meta)\n metas.push(meta)\n }\n }\n }\n\n await server.close()\n }\n }\n\n cachedMetas = metas\n metaCacheLoaded = true\n\n log('Discovered modules:', metas.map(m => m.name))\n\n return metas\n }\n\n const generateInputs = (metas: ShardevModuleMeta[]) => {\n const inputs: Record<string, string> = {}\n metas.forEach(meta => {\n Object.entries(meta.input).forEach(([key, value]) => {\n inputs[`${meta.name}-${key}`] = value\n })\n })\n return inputs\n }\n\n const resolveWatchPath = (meta: ShardevModuleMeta): string | null => {\n const base = meta.usePublished && meta.publishedDir\n ? meta.publishedDir\n : meta.srcDir\n\n if (!base) return null\n\n return path.isAbsolute(base)\n ? base\n : path.resolve(root, base)\n }\n\n const handleHMR = (\n server: ViteDevServer,\n file: string\n ) => {\n\n const module = server.moduleGraph.getModuleById(file)\n\n if (!module) return\n\n log('HMR update:', file)\n\n const updates = [{\n type: 'js-update',\n path: module.url,\n acceptedPath: module.url,\n timestamp: Date.now()\n }]\n\n server.moduleGraph.invalidateModule(module)\n\n server.ws.send({\n type: 'update',\n updates\n })\n }\n\n return {\n name: 'laravel-modules',\n\n async config(config: UserConfig, env: ConfigEnv) {\n\n const metas = await discoverModules()\n\n const aliases: Record<string, string> = {}\n metas.forEach(meta => Object.assign(aliases, meta.alias))\n\n const rollupInputs = generateInputs(metas)\n\n return mergeConfig(config, {\n resolve: { alias: aliases },\n build: {\n rollupOptions: { input: rollupInputs }\n }\n })\n },\n\n async configureServer(server: ViteDevServer) {\n\n const metas = await discoverModules()\n\n for (const meta of metas) {\n const watchPath = resolveWatchPath(meta)\n if (watchPath && fs.existsSync(watchPath)) {\n server.watcher.add(watchPath)\n log('Watching:', watchPath)\n }\n }\n\n server.watcher.on('change', (file) => {\n\n const matched = metas.some(meta => {\n const watchPath = resolveWatchPath(meta)\n return watchPath && file.startsWith(watchPath)\n })\n\n if (!matched) return\n\n handleHMR(server, file)\n })\n }\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAAe;AACf,kBAAiB;AA0BV,SAAS,cAAc,SAAsC;AAEhE,QAAM;AAAA,IACF;AAAA,IACA,SAAS;AAAA,IACT,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA,WAAW,SAAS,MAAM,IAAI,IAAI;AAAA,IAClC,eAAe,mBAAmB,MAAM,IAAI,IAAI;AAAA,EACpD,IAAI;AAEJ,QAAM,OAAO,QAAQ,IAAI;AACzB,QAAM,aAAa,YAAAA,QAAK,QAAQ,MAAM,YAAY,QAAQ,IAAI;AAE9D,QAAM,WAAW,YAAAA,QAAK,SAAS,YAAY,IAAI;AAC/C,QAAM,eACF,CAAC,YAAY,aAAa,OAAO,CAAC,SAAS,WAAW,IAAI;AAM9D,MAAI,kBAA0C,CAAC;AAE/C,MAAI,SAAS,OAAO,KAAK,KAAK,EAAE,SAAS,GAAG;AAExC,eAAW,CAAC,KAAK,IAAI,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC7C,sBAAgB,GAAG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AA,IACL;AAAA,EACJ;AACJ;","names":["path","fs","import_path","import_fs","path","fs","module"]}
package/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ interface ModuleOptions {
4
4
  name: string;
5
5
  vendor?: string;
6
6
  srcDir?: string;
7
+ input?: Record<string, string>;
7
8
  inputs?: string[];
8
9
  buildDir?: string;
9
10
  publishedDir?: string;
@@ -13,16 +14,9 @@ declare function laravelModule(options: ModuleOptions): PluginOption;
13
14
  interface LaravelModulesOptions {
14
15
  modulesDir?: string;
15
16
  statusesFile?: string;
17
+ debug?: boolean;
18
+ useMetaCache?: boolean;
16
19
  }
17
- /**
18
- * Laravel Modules Plugin for Vite
19
- *
20
- * This plugin enables Vite to work with Laravel modules by:
21
- * 1. Discovering and loading module configurations
22
- * 2. Resolving module-specific aliases
23
- * 3. Handling namespace resolution for modules
24
- * 4. Processing manifest files for proper asset handling
25
- */
26
20
  declare function laravelModules(options?: LaravelModulesOptions): Plugin;
27
21
 
28
22
  export { laravelModule, laravelModules };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ interface ModuleOptions {
4
4
  name: string;
5
5
  vendor?: string;
6
6
  srcDir?: string;
7
+ input?: Record<string, string>;
7
8
  inputs?: string[];
8
9
  buildDir?: string;
9
10
  publishedDir?: string;
@@ -13,16 +14,9 @@ declare function laravelModule(options: ModuleOptions): PluginOption;
13
14
  interface LaravelModulesOptions {
14
15
  modulesDir?: string;
15
16
  statusesFile?: string;
17
+ debug?: boolean;
18
+ useMetaCache?: boolean;
16
19
  }
17
- /**
18
- * Laravel Modules Plugin for Vite
19
- *
20
- * This plugin enables Vite to work with Laravel modules by:
21
- * 1. Discovering and loading module configurations
22
- * 2. Resolving module-specific aliases
23
- * 3. Handling namespace resolution for modules
24
- * 4. Processing manifest files for proper asset handling
25
- */
26
20
  declare function laravelModules(options?: LaravelModulesOptions): Plugin;
27
21
 
28
22
  export { laravelModule, laravelModules };