@moostjs/vite 0.5.21 → 0.5.22

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.mjs CHANGED
@@ -1,350 +1,365 @@
1
- import { mergeConfig } from 'vite';
2
- import { Moost, EventLogger, getMoostInfact, getMoostMate, clearGlobalWooks } from 'moost';
3
- import { readFileSync } from 'node:fs';
4
- import { builtinModules } from 'node:module';
1
+ import { EventLogger, Moost, clearGlobalWooks, getMoostInfact, getMoostMate } from "moost";
2
+ import { readFileSync } from "node:fs";
3
+ import { builtinModules } from "node:module";
5
4
 
5
+ //#region packages/vite/src/adapter-detector.ts
6
6
  function createAdapterDetector(adapter, onInit) {
7
- return {
8
- detected: false,
9
- regex: new RegExp(`from\\s+["'](@moostjs\\/event-${adapter})["']`),
10
- constructor: null,
11
- async init() {
12
- this.detected = true;
13
- const module = await import(`@moostjs/event-${adapter}`);
14
- this.constructor = module[`Moost${adapter.charAt(0).toUpperCase() + adapter.slice(1)}`];
15
- if (onInit) {
16
- onInit(this.constructor);
17
- }
18
- },
19
- compare(c) {
20
- if (this.detected && this.constructor) {
21
- return (this.constructor === c ||
22
- c instanceof this.constructor ||
23
- c.prototype instanceof this.constructor);
24
- }
25
- return false;
26
- },
27
- };
7
+ return {
8
+ detected: false,
9
+ regex: new RegExp(`from\\s+["'](@moostjs\\/event-${adapter})["']`),
10
+ constructor: null,
11
+ async init() {
12
+ this.detected = true;
13
+ const module = await import(`@moostjs/event-${adapter}`);
14
+ this.constructor = module[`Moost${adapter.charAt(0).toUpperCase() + adapter.slice(1)}`];
15
+ if (onInit) onInit(this.constructor);
16
+ },
17
+ compare(c) {
18
+ if (this.detected && this.constructor) return this.constructor === c || c instanceof this.constructor || c.prototype instanceof this.constructor;
19
+ return false;
20
+ }
21
+ };
28
22
  }
29
23
 
30
- function flattenItem(item) {
31
- return `${item.eventName}||${item.classConstructor.name}||${item.method}`;
24
+ //#endregion
25
+ //#region packages/vite/src/moost-logging.ts
26
+ function _define_property(obj, key, value) {
27
+ if (key in obj) Object.defineProperty(obj, key, {
28
+ value,
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true
32
+ });
33
+ else obj[key] = value;
34
+ return obj;
32
35
  }
33
- class LogsStorage {
34
- constructor() {
35
- this.oldMap = new Map();
36
- this.newItems = [];
37
- this.isFirstRun = true;
38
- }
39
- startRecording() {
40
- this.newItems = [];
41
- }
42
- record(item) {
43
- const flat = flattenItem(item);
44
- this.newItems.push(item);
45
- return !this.oldMap.has(flat);
46
- }
47
- endRecording(logRemovedItem) {
48
- const newMap = new Map();
49
- for (const item of this.newItems) {
50
- const flat = flattenItem(item);
51
- newMap.set(flat, item);
52
- }
53
- for (const [flat, item] of this.oldMap.entries()) {
54
- if (!newMap.has(flat)) {
55
- logRemovedItem(item);
56
- }
57
- }
58
- this.oldMap = newMap;
59
- this.newItems = [];
60
- this.isFirstRun = false;
61
- }
36
+ /**
37
+ * Converts a TItem into a flattened string to uniquely identify it.
38
+ * @param {TItem} item - The handler registration item to flatten.
39
+ * @returns {string} A unique string key for the item.
40
+ */ function flattenItem(item) {
41
+ return `${item.eventName}||${item.classConstructor.name}||${item.method}`;
62
42
  }
63
- let logsStorage;
43
+ /**
44
+ * A storage mechanism to track old and new handler registrations
45
+ * across multiple initialization cycles. During each init:
46
+ * 1. Start recording newly encountered handlers.
47
+ * 2. Compare them against previously recorded handlers to detect
48
+ * which are newly added vs. removed.
49
+ * 3. Store the new state as the old map for the next cycle.
50
+ */ let LogsStorage = class LogsStorage$1 {
51
+ /**
52
+ * Called at the start of an init cycle to
53
+ * clear out the list of new items.
54
+ */ startRecording() {
55
+ this.newItems = [];
56
+ }
57
+ /**
58
+ * Records a newly encountered handler (via logMappedHandler).
59
+ *
60
+ * @param {TItem} item - The handler registration item to record.
61
+ * @returns {boolean} True if this item is newly added (not in oldMap),
62
+ * false if it existed already.
63
+ */ record(item) {
64
+ const flat = flattenItem(item);
65
+ this.newItems.push(item);
66
+ return !this.oldMap.has(flat);
67
+ }
68
+ /**
69
+ * Called at the end of an init cycle.
70
+ * 1. Builds a newMap of all newly encountered handlers.
71
+ * 2. Logs/strokes out any handlers that have disappeared compared
72
+ * to the previous cycle.
73
+ * 3. Updates oldMap so it becomes the baseline for the next cycle.
74
+ *
75
+ * @param {(item: TItem) => void} logRemovedItem - A callback that logs
76
+ * removed items (presumably by striking them out).
77
+ */ endRecording(logRemovedItem) {
78
+ const newMap = new Map();
79
+ for (const item of this.newItems) {
80
+ const flat = flattenItem(item);
81
+ newMap.set(flat, item);
82
+ }
83
+ for (const [flat, item] of this.oldMap.entries()) if (!newMap.has(flat)) logRemovedItem(item);
84
+ this.oldMap = newMap;
85
+ this.newItems = [];
86
+ this.isFirstRun = false;
87
+ }
88
+ constructor() {
89
+ /**
90
+ * A map of flattenItem() => TItem
91
+ * representing the previous cycle's known handlers.
92
+ */ _define_property(this, "oldMap", new Map());
93
+ /**
94
+ * The handlers discovered in the current cycle,
95
+ * awaiting finalization.
96
+ */ _define_property(this, "newItems", []);
97
+ _define_property(this, "isFirstRun", true);
98
+ }
99
+ };
100
+ /**
101
+ * A reference to a shared LogsStorage instance that persists
102
+ * across init cycles in dev mode.
103
+ */ let logsStorage;
64
104
  function patchMoostHandlerLogging() {
65
- const origInit = Moost.prototype.init;
66
- Moost.prototype.init = async function init() {
67
- if (!logsStorage) {
68
- logsStorage = new LogsStorage();
69
- }
70
- logsStorage.startRecording();
71
- await origInit.call(this);
72
- logsStorage.endRecording((item) => {
73
- origLogMappedHandler.call(this, item.eventName, item.classConstructor, item.method, true, '❌ ');
74
- });
75
- };
76
- const origLogMappedHandler = Moost.prototype.logMappedHandler;
77
- Moost.prototype.logMappedHandler = function logMappedHandler(eventName, classConstructor, method) {
78
- if (logsStorage.record({ eventName, classConstructor, method })) {
79
- origLogMappedHandler.call(this, eventName, classConstructor, method, false, logsStorage.isFirstRun ? '' : '✅ ');
80
- }
81
- };
105
+ const origInit = Moost.prototype.init;
106
+ /**
107
+ * Monkey-patch Moost.init:
108
+ * 1. Start a new recording cycle in LogsStorage.
109
+ * 2. Call the real .init().
110
+ * 3. End the recording, logging any removed handlers.
111
+ */ Moost.prototype.init = async function init() {
112
+ if (!logsStorage) logsStorage = new LogsStorage();
113
+ logsStorage.startRecording();
114
+ await origInit.call(this);
115
+ logsStorage.endRecording((item) => {
116
+ origLogMappedHandler.call(this, item.eventName, item.classConstructor, item.method, true, "❌ ");
117
+ });
118
+ };
119
+ const origLogMappedHandler = Moost.prototype.logMappedHandler;
120
+ /**
121
+ * Monkey-patch Moost.logMappedHandler:
122
+ * If we haven’t seen this particular route+class+method combination
123
+ * in a previous cycle, call the original logger. Otherwise, skip it
124
+ * to avoid duplicate logs.
125
+ */ Moost.prototype.logMappedHandler = function logMappedHandler(eventName, classConstructor, method) {
126
+ if (logsStorage.record({
127
+ eventName,
128
+ classConstructor,
129
+ method
130
+ })) origLogMappedHandler.call(this, eventName, classConstructor, method, false, logsStorage.isFirstRun ? "" : "✅ ");
131
+ };
82
132
  }
83
133
 
84
- const PLUGIN_NAME = 'moost-vite';
134
+ //#endregion
135
+ //#region packages/vite/src/utils.ts
136
+ const PLUGIN_NAME = "moost-vite";
85
137
  function gatherAllImporters(moduleNode, visited = new Set()) {
86
- if (!moduleNode) {
87
- return visited;
88
- }
89
- if (visited.has(moduleNode)) {
90
- return visited;
91
- }
92
- visited.add(moduleNode);
93
- if (moduleNode.importers) {
94
- for (const importer of moduleNode.importers) {
95
- gatherAllImporters(importer, visited);
96
- }
97
- }
98
- return visited;
138
+ if (!moduleNode) return visited;
139
+ if (visited.has(moduleNode)) return visited;
140
+ visited.add(moduleNode);
141
+ if (moduleNode.importers) for (const importer of moduleNode.importers) gatherAllImporters(importer, visited);
142
+ return visited;
99
143
  }
100
- const logger = new EventLogger('', { level: 99 }).createTopic('' + '' + PLUGIN_NAME);
144
+ const logger = new EventLogger("", { level: 99 }).createTopic("\x1B[2m\x1B[36m" + PLUGIN_NAME);
101
145
  function getLogger() {
102
- return logger;
146
+ return logger;
103
147
  }
104
148
  function getExternals({ node, workspace }) {
105
- const pkg = JSON.parse(readFileSync('package.json', 'utf8').toString());
106
- const externals = workspace
107
- ? Object.keys(pkg.dependencies || {})
108
- : Object.entries(pkg.dependencies || {})
109
- .filter(([key, ver]) => !ver.startsWith('workspace:'))
110
- .map(i => i[0]);
111
- if (node) {
112
- externals.push(...builtinModules, ...builtinModules.map(m => `node:${m}`));
113
- }
114
- return externals;
149
+ const pkg = JSON.parse(readFileSync("package.json", "utf8").toString());
150
+ const externals = workspace ? Object.keys(pkg.dependencies || {}) : Object.entries(pkg.dependencies || {}).filter(([key, ver]) => !ver.startsWith("workspace:")).map((i) => i[0]);
151
+ if (node) externals.push(...builtinModules, ...builtinModules.map((m) => `node:${m}`));
152
+ return externals;
115
153
  }
116
154
 
155
+ //#endregion
156
+ //#region packages/vite/src/restart-cleanup.ts
117
157
  function moostRestartCleanup(adapters, onEject, cleanupInstances) {
118
- const logger = getLogger();
119
- const infact = getMoostInfact();
120
- const { registry, scopes } = infact;
121
- const registries = [registry, ...Object.values(scopes)];
122
- infact._cleanup();
123
- const mate = getMoostMate();
124
- if (cleanupInstances) {
125
- for (const reg of registries) {
126
- for (const key of Object.getOwnPropertySymbols(reg)) {
127
- const instance = reg[key];
128
- const viteId = mate.read(instance)?.__vite_id;
129
- if (viteId && cleanupInstances.has(viteId)) {
130
- logger.debug(`🔃 Replacing "${constructorName(instance)}"`);
131
- delete reg[key];
132
- }
133
- }
134
- for (const key of Object.getOwnPropertySymbols(reg)) {
135
- const instance = reg[key];
136
- scanParams(instance, (type) => {
137
- if ((type === Moost || type instanceof Moost || type.prototype instanceof Moost) &&
138
- (!onEject || onEject(instance, type))) {
139
- delete reg[key];
140
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "Moost")`);
141
- return true;
142
- }
143
- for (const adapter of adapters) {
144
- if (adapter.compare(type) && (!onEject || onEject(instance, type))) {
145
- delete reg[key];
146
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "${adapter.constructor.name}")`);
147
- return true;
148
- }
149
- }
150
- });
151
- }
152
- clearDependantRegistry(reg, onEject);
153
- }
154
- infact.registry = registry;
155
- infact.scopes = scopes;
156
- }
157
- getMoostMate()._cleanup();
158
- clearGlobalWooks();
158
+ const logger$1 = getLogger();
159
+ const infact = getMoostInfact();
160
+ const { registry, scopes } = infact;
161
+ const registries = [registry, ...Object.values(scopes)];
162
+ infact._cleanup();
163
+ const mate = getMoostMate();
164
+ if (cleanupInstances) {
165
+ for (const reg of registries) {
166
+ for (const key of Object.getOwnPropertySymbols(reg)) {
167
+ const instance = reg[key];
168
+ const viteId = mate.read(instance)?.__vite_id;
169
+ if (viteId && cleanupInstances.has(viteId)) {
170
+ logger$1.debug(`🔃 Replacing "${constructorName(instance)}"`);
171
+ delete reg[key];
172
+ }
173
+ }
174
+ for (const key of Object.getOwnPropertySymbols(reg)) {
175
+ const instance = reg[key];
176
+ scanParams(instance, (type) => {
177
+ if ((type === Moost || type instanceof Moost || type.prototype instanceof Moost) && (!onEject || onEject(instance, type))) {
178
+ delete reg[key];
179
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "Moost")`);
180
+ return true;
181
+ }
182
+ for (const adapter of adapters) if (adapter.compare(type) && (!onEject || onEject(instance, type))) {
183
+ delete reg[key];
184
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "${adapter.constructor.name}")`);
185
+ return true;
186
+ }
187
+ });
188
+ }
189
+ clearDependantRegistry(reg, onEject);
190
+ }
191
+ infact.registry = registry;
192
+ infact.scopes = scopes;
193
+ }
194
+ getMoostMate()._cleanup();
195
+ clearGlobalWooks();
159
196
  }
160
197
  function clearDependantRegistry(registry, onEject) {
161
- const logger = getLogger();
162
- const objSet = new Set();
163
- let somethingIsDeleted = true;
164
- while (somethingIsDeleted) {
165
- somethingIsDeleted = false;
166
- for (const key of Object.getOwnPropertySymbols(registry)) {
167
- const instance = registry[key];
168
- objSet.add(Object.getPrototypeOf(instance).constructor);
169
- }
170
- for (const key of Object.getOwnPropertySymbols(registry)) {
171
- const instance = registry[key];
172
- scanParams(instance, (type) => {
173
- if (!objSet.has(type) && (!onEject || onEject(instance, type))) {
174
- delete registry[key];
175
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on "${type.name}" which is not in registry)`);
176
- somethingIsDeleted = true;
177
- return true;
178
- }
179
- });
180
- }
181
- }
198
+ const logger$1 = getLogger();
199
+ const objSet = new Set();
200
+ let somethingIsDeleted = true;
201
+ while (somethingIsDeleted) {
202
+ somethingIsDeleted = false;
203
+ for (const key of Object.getOwnPropertySymbols(registry)) {
204
+ const instance = registry[key];
205
+ objSet.add(Object.getPrototypeOf(instance).constructor);
206
+ }
207
+ for (const key of Object.getOwnPropertySymbols(registry)) {
208
+ const instance = registry[key];
209
+ scanParams(instance, (type) => {
210
+ if (!objSet.has(type) && (!onEject || onEject(instance, type))) {
211
+ delete registry[key];
212
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on "${type.name}" which is not in registry)`);
213
+ somethingIsDeleted = true;
214
+ return true;
215
+ }
216
+ });
217
+ }
218
+ }
182
219
  }
183
220
  function scanParams(instance, cb) {
184
- const mate = getMoostMate();
185
- const params = mate.read(instance)?.params;
186
- if (params?.length) {
187
- for (const param of params) {
188
- if (param.type === undefined ||
189
- [Array, String, Number, Boolean, Object].includes(param.type)) {
190
- continue;
191
- }
192
- if (cb(param.type)) {
193
- break;
194
- }
195
- }
196
- }
221
+ const mate = getMoostMate();
222
+ const params = mate.read(instance)?.params;
223
+ if (params?.length) for (const param of params) {
224
+ if (param.type === undefined || [
225
+ Array,
226
+ String,
227
+ Number,
228
+ Boolean,
229
+ Object
230
+ ].includes(param.type)) continue;
231
+ if (cb(param.type)) break;
232
+ }
197
233
  }
198
234
  function constructorName(i) {
199
- return Object.getPrototypeOf(i).constructor.name;
235
+ return Object.getPrototypeOf(i).constructor.name;
200
236
  }
201
237
 
202
- const REG_HAS_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/m;
238
+ //#endregion
239
+ //#region packages/vite/src/moost-vite.ts
240
+ /** Regex checks */ const REG_HAS_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/m;
203
241
  const REG_REPLACE_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/gm;
204
242
  function moostVite(options) {
205
- const isTest = process.env.NODE_ENV === 'test';
206
- const isProd = process.env.NODE_ENV === 'production';
207
- let moostMiddleware = null;
208
- const adapters = isTest
209
- ? []
210
- : [
211
- createAdapterDetector('http', MoostHttp => {
212
- MoostHttp.prototype.listen = function (...args) {
213
- moostMiddleware = this.getServerCb();
214
- setTimeout(() => {
215
- args.filter(a => typeof a === 'function').forEach(a => a());
216
- }, 1);
217
- return Promise.resolve();
218
- };
219
- }),
220
- createAdapterDetector('cli'),
221
- createAdapterDetector('wf'),
222
- ];
223
- const logger = isTest ? console : getLogger();
224
- let reloadRequired = false;
225
- patchMoostHandlerLogging();
226
- const pluginConfig = {
227
- name: PLUGIN_NAME,
228
- enforce: 'pre',
229
- config(cfg) {
230
- const entry = cfg.build?.rollupOptions?.input || options.entry;
231
- const outfile = typeof entry === 'string' ? entry.split('/').pop().replace(/\.ts$/, '.js') : undefined;
232
- const pluginConfig = {
233
- server: {
234
- port: cfg.server?.port || options.port || 3000,
235
- host: cfg.server?.host || options.host,
236
- },
237
- optimizeDeps: {
238
- noDiscovery: cfg.optimizeDeps?.noDiscovery === undefined ? true : cfg.optimizeDeps.noDiscovery,
239
- exclude: cfg.optimizeDeps?.exclude || ['@swc/core'],
240
- },
241
- build: {
242
- target: cfg.build?.target || 'node',
243
- outDir: cfg.build?.outDir || options.outDir || 'dist',
244
- ssr: cfg.build?.ssr ?? true,
245
- minify: cfg.build?.minify || false,
246
- rollupOptions: {
247
- external: isTest
248
- ? cfg.build?.rollupOptions?.external
249
- : cfg.build?.rollupOptions?.external ||
250
- (options.externals === false
251
- ? []
252
- : getExternals({
253
- node: Boolean(options.externals === true || options.externals?.node),
254
- workspace: Boolean(options.externals === true || options.externals?.workspace),
255
- })),
256
- input: entry,
257
- output: {
258
- format: options.format,
259
- sourcemap: !!(options.sourcemap ?? true),
260
- entryFileNames: outfile,
261
- ...cfg.build?.rollupOptions?.output,
262
- },
263
- },
264
- },
265
- };
266
- return mergeConfig(cfg, pluginConfig);
267
- },
268
- async transform(code, id) {
269
- if (!id.endsWith('.ts')) {
270
- return code;
271
- }
272
- for (const adapter of adapters) {
273
- if (!adapter.detected && adapter.regex.test(code)) {
274
- await adapter.init();
275
- }
276
- }
277
- if (REG_HAS_EXPORT_CLASS.test(code)) {
278
- code = code.replace(REG_REPLACE_EXPORT_CLASS, '\n@__VITE_ID(import.meta.filename)\n$1');
279
- code = `import { __VITE_ID } from 'virtual:vite-id'\n\n${code}`;
280
- }
281
- return code;
282
- },
283
- resolveId(id) {
284
- if (id === 'virtual:vite-id') {
285
- return '\0virtual:vite-id';
286
- }
287
- },
288
- load(id) {
289
- if (id === '\0virtual:vite-id') {
290
- return `
243
+ const isTest = false;
244
+ const isProd = false;
245
+ let moostMiddleware = null;
246
+ const adapters = isTest ? [] : [
247
+ createAdapterDetector("http", (MoostHttp) => {
248
+ MoostHttp.prototype.listen = function(...args) {
249
+ moostMiddleware = this.getServerCb();
250
+ setTimeout(() => {
251
+ args.filter((a) => typeof a === "function").forEach((a) => a());
252
+ }, 1);
253
+ return Promise.resolve();
254
+ };
255
+ }),
256
+ createAdapterDetector("cli"),
257
+ createAdapterDetector("wf")
258
+ ];
259
+ /** A logger instance for plugin debug output. */ const logger$1 = isTest ? console : getLogger();
260
+ let reloadRequired = false;
261
+ patchMoostHandlerLogging();
262
+ const pluginConfig = {
263
+ name: PLUGIN_NAME,
264
+ enforce: "pre",
265
+ config(cfg) {
266
+ const entry = cfg.build?.rollupOptions?.input || options.entry;
267
+ const outfile = typeof entry === "string" ? entry.split("/").pop().replace(/\.ts$/, ".js") : undefined;
268
+ return {
269
+ server: {
270
+ port: cfg.server?.port || options.port || 3e3,
271
+ host: cfg.server?.host || options.host
272
+ },
273
+ optimizeDeps: {
274
+ noDiscovery: cfg.optimizeDeps?.noDiscovery === undefined ? true : cfg.optimizeDeps.noDiscovery,
275
+ exclude: cfg.optimizeDeps?.exclude || ["@swc/core"]
276
+ },
277
+ build: {
278
+ target: cfg.build?.target || "node",
279
+ outDir: cfg.build?.outDir || options.outDir || "dist",
280
+ ssr: cfg.build?.ssr ?? true,
281
+ minify: cfg.build?.minify || false,
282
+ rollupOptions: {
283
+ external: isTest ? cfg.build?.rollupOptions?.external : cfg.build?.rollupOptions?.external || (options.externals === false ? [] : getExternals({
284
+ node: Boolean(options.externals === true || options.externals?.node),
285
+ workspace: Boolean(options.externals === true || options.externals?.workspace)
286
+ })),
287
+ input: entry,
288
+ output: {
289
+ format: options.format,
290
+ sourcemap: !!(options.sourcemap ?? true),
291
+ entryFileNames: outfile,
292
+ ...cfg.build?.rollupOptions?.output
293
+ }
294
+ }
295
+ }
296
+ };
297
+ },
298
+ async transform(code, id) {
299
+ if (!id.endsWith(".ts")) return code;
300
+ for (const adapter of adapters) if (!adapter.detected && adapter.regex.test(code)) await adapter.init();
301
+ if (REG_HAS_EXPORT_CLASS.test(code)) {
302
+ code = code.replace(REG_REPLACE_EXPORT_CLASS, "\n@__VITE_ID(import.meta.filename)\n$1");
303
+ code = `import { __VITE_ID } from 'virtual:vite-id'\n\n${code}`;
304
+ }
305
+ return code;
306
+ },
307
+ resolveId(id) {
308
+ if (id === "virtual:vite-id") return "\0virtual:vite-id";
309
+ },
310
+ load(id) {
311
+ if (id === "\0virtual:vite-id") return `
291
312
  import { getMoostMate } from "moost";
292
313
  const mate = getMoostMate();
293
314
  export function __VITE_ID(id) {
294
315
  return mate.decorate("__vite_id", id)
295
316
  }
296
317
  `;
297
- }
298
- },
299
- async configureServer(server) {
300
- moostRestartCleanup(adapters, options.onEject);
301
- await server.ssrLoadModule(options.entry);
302
- server.middlewares.use(async (req, res, next) => {
303
- if (reloadRequired) {
304
- reloadRequired = false;
305
- console.log();
306
- logger.debug('🚀 Reloading Moost App...');
307
- console.log();
308
- await server.ssrLoadModule(options.entry);
309
- await new Promise(resolve => setTimeout(resolve, 1));
310
- }
311
- if (moostMiddleware) {
312
- return moostMiddleware(req, res);
313
- }
314
- next();
315
- });
316
- },
317
- hotUpdate({ file }) {
318
- if (file.endsWith('.ts')) {
319
- const modules = this.environment.moduleGraph.getModulesByFile(file);
320
- if (modules) {
321
- logger.debug(`🔃 Hot update: ${file}`);
322
- const cleanupInstances = new Set();
323
- for (const mod of modules) {
324
- const allImporters = gatherAllImporters(mod);
325
- for (const impModule of allImporters) {
326
- if (impModule.id) {
327
- cleanupInstances.add(impModule.id);
328
- }
329
- }
330
- this.environment.moduleGraph.invalidateModule(mod);
331
- }
332
- moostMiddleware = null;
333
- moostRestartCleanup(adapters, options.onEject, cleanupInstances);
334
- reloadRequired = true;
335
- }
336
- return [];
337
- }
338
- },
339
- };
340
- if (isProd || isTest) {
341
- delete pluginConfig.configureServer;
342
- delete pluginConfig.resolveId;
343
- delete pluginConfig.load;
344
- delete pluginConfig.transform;
345
- delete pluginConfig.hotUpdate;
346
- }
347
- return pluginConfig;
318
+ },
319
+ async configureServer(server) {
320
+ moostRestartCleanup(adapters, options.onEject);
321
+ await server.ssrLoadModule(options.entry);
322
+ server.middlewares.use(async (req, res, next) => {
323
+ if (reloadRequired) {
324
+ reloadRequired = false;
325
+ console.log();
326
+ logger$1.debug("🚀 Reloading Moost App...");
327
+ console.log();
328
+ await server.ssrLoadModule(options.entry);
329
+ await new Promise((resolve) => setTimeout(resolve, 1));
330
+ }
331
+ if (moostMiddleware) return moostMiddleware(req, res);
332
+ next();
333
+ });
334
+ },
335
+ hotUpdate({ file }) {
336
+ if (file.endsWith(".ts")) {
337
+ const modules = this.environment.moduleGraph.getModulesByFile(file);
338
+ if (modules) {
339
+ logger$1.debug(`🔃 Hot update: ${file}`);
340
+ const cleanupInstances = new Set();
341
+ for (const mod of modules) {
342
+ const allImporters = gatherAllImporters(mod);
343
+ for (const impModule of allImporters) if (impModule.id) cleanupInstances.add(impModule.id);
344
+ this.environment.moduleGraph.invalidateModule(mod);
345
+ }
346
+ moostMiddleware = null;
347
+ moostRestartCleanup(adapters, options.onEject, cleanupInstances);
348
+ reloadRequired = true;
349
+ }
350
+ return [];
351
+ }
352
+ }
353
+ };
354
+ if (isProd || isTest) {
355
+ delete pluginConfig.configureServer;
356
+ delete pluginConfig.resolveId;
357
+ delete pluginConfig.load;
358
+ delete pluginConfig.transform;
359
+ delete pluginConfig.hotUpdate;
360
+ }
361
+ return pluginConfig;
348
362
  }
349
363
 
350
- export { moostVite };
364
+ //#endregion
365
+ export { moostVite };