@lark-apaas/coding-template-nestjs-react-fullstack 0.1.27-alpha.20260824122815 → 0.1.27

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.
@@ -1,420 +0,0 @@
1
- import fs from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import path from 'node:path';
4
- import { pathToFileURL } from 'node:url';
5
- import { defineConfig, mergeConfig } from 'vite';
6
- import workspaceConfig from '../vite.config.ts';
7
-
8
- const projectRoot = path.resolve(
9
- process.env.MIAODA_WORKSPACE_ROOT || process.cwd()
10
- );
11
- const rawCacheEnabled = process.env.MIAODA_VITE_DEPS_CACHE_ENABLED || 'true';
12
- if (rawCacheEnabled !== 'true' && rawCacheEnabled !== 'false') {
13
- throw new Error(`MIAODA_VITE_DEPS_CACHE_ENABLED_INVALID: ${rawCacheEnabled}`);
14
- }
15
- const cacheEnabled = rawCacheEnabled === 'true';
16
- const vite8RuntimeEnabled = process.env.MIAODA_VITE8_RUNTIME_ENABLED === 'true';
17
- const devBundleEnabled = process.env.MIAODA_VITE_DEV_BUNDLE_ENABLED === 'true';
18
- const persistentCacheDir = path.resolve(
19
- process.env.MIAODA_VITE_PERSISTENT_CACHE_DIR ||
20
- path.join(projectRoot, 'node_modules', '.vite')
21
- );
22
- const ephemeralCacheDir = path.resolve(
23
- process.env.MIAODA_VITE_EPHEMERAL_CACHE_DIR ||
24
- '/tmp/miaoda-vite-deps-ephemeral'
25
- );
26
- const platformVitePresetEntry = path.resolve(
27
- process.env.MIAODA_PLATFORM_VITE_PRESET_ENTRY ||
28
- '/opt/miaoda/preview-runtime/node_modules/@lark-apaas/fullstack-vite-preset/lib/index.js'
29
- );
30
- const platformReactPluginEntry = path.resolve(
31
- process.env.MIAODA_PLATFORM_REACT_PLUGIN_ENTRY ||
32
- '/opt/miaoda/preview-runtime/node_modules/@vitejs/plugin-react/dist/index.js'
33
- );
34
- const bundledDevOutputFile = path.join(
35
- projectRoot,
36
- 'dist',
37
- 'client',
38
- 'index.html'
39
- );
40
- const forbiddenBundledDevEntries = [
41
- '/@vite/client',
42
- '/@react-refresh',
43
- '/client/src/index.tsx',
44
- '/client/src/main.tsx',
45
- '/src/index.tsx',
46
- '/src/main.tsx',
47
- '/@runtime.js',
48
- ];
49
- const platformRuntimePluginNames = new Set([
50
- 'fullstack-runtime-injection',
51
- 'fullstack-error-overlay',
52
- 'fullstack-ws-watchdog',
53
- ]);
54
-
55
- function resolveHtmlInput(config) {
56
- const input = config.build.rollupOptions?.input;
57
- if (typeof input === 'string') return input;
58
- if (Array.isArray(input)) return input.find(file => file.endsWith('.html'));
59
- if (input && typeof input === 'object') {
60
- return Object.values(input).find(file => file.endsWith('.html'));
61
- }
62
- return path.join(config.root, 'index.html');
63
- }
64
-
65
- function documentPathFor(config, htmlInput) {
66
- const relativeInput = path
67
- .relative(config.root, htmlInput)
68
- .split(path.sep)
69
- .join('/');
70
- const base = config.base.endsWith('/') ? config.base : `${config.base}/`;
71
- return `${base}${relativeInput}`.replace(/\/+/g, '/');
72
- }
73
-
74
- function externalScriptSources(html) {
75
- return Array.from(
76
- html.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["']/gi),
77
- match => match[1]
78
- );
79
- }
80
-
81
- async function waitForServerAddress(server) {
82
- const deadline = Date.now() + 60_000;
83
- while (Date.now() < deadline) {
84
- const address = server.httpServer?.address();
85
- if (address && typeof address === 'object') return address;
86
- await new Promise(resolve => setTimeout(resolve, 20));
87
- }
88
- throw new Error('MIAODA_VITE_BUNDLED_DEV_SERVER_ADDRESS_TIMEOUT');
89
- }
90
-
91
- function bundledDevMaterializationPlugin() {
92
- let config;
93
- return {
94
- name: 'miaoda-vite-bundled-dev-materialization',
95
- apply: 'serve',
96
- configResolved(resolvedConfig) {
97
- config = resolvedConfig;
98
- },
99
- configureServer(server) {
100
- if (!devBundleEnabled) return;
101
- void (async () => {
102
- const address = await waitForServerAddress(server);
103
- const bundledDev = server.environments?.client?.bundledDev;
104
- if (typeof bundledDev?.waitForInitialBuildFinish !== 'function') {
105
- throw new Error('MIAODA_VITE_BUNDLED_DEV_RUNTIME_UNAVAILABLE');
106
- }
107
- await bundledDev.waitForInitialBuildFinish();
108
- const htmlInput = resolveHtmlInput(config);
109
- if (!htmlInput || !fs.existsSync(htmlInput)) {
110
- throw new Error(
111
- `MIAODA_VITE_BUNDLED_DEV_HTML_INPUT_MISSING: ${htmlInput}`
112
- );
113
- }
114
- const documentPath = documentPathFor(config, htmlInput);
115
- const response = await fetch(
116
- `http://127.0.0.1:${address.port}${documentPath}`,
117
- { headers: { 'sec-fetch-dest': 'document' } }
118
- );
119
- if (!response.ok) {
120
- throw new Error(
121
- `MIAODA_VITE_BUNDLED_DEV_DOCUMENT_UNAVAILABLE: ${documentPath} status=${response.status}`
122
- );
123
- }
124
- const html = await response.text();
125
- const scriptSources = externalScriptSources(html);
126
- const forbiddenSources = scriptSources.filter(source =>
127
- forbiddenBundledDevEntries.some(entry => source.includes(entry))
128
- );
129
- if (forbiddenSources.length > 0) {
130
- throw new Error(
131
- `MIAODA_VITE_BUNDLED_DEV_DOCUMENT_NOT_BUNDLED: ${forbiddenSources.join(',')}`
132
- );
133
- }
134
- fs.mkdirSync(path.dirname(bundledDevOutputFile), { recursive: true });
135
- const temporaryOutput = `${bundledDevOutputFile}.${process.pid}.tmp`;
136
- fs.writeFileSync(temporaryOutput, html);
137
- fs.renameSync(temporaryOutput, bundledDevOutputFile);
138
- process.stdout.write(
139
- `${JSON.stringify({
140
- event: 'miaoda_vite_bundled_dev_materialized',
141
- documentPath,
142
- outputFile: bundledDevOutputFile,
143
- htmlBytes: Buffer.byteLength(html),
144
- externalScriptSources: scriptSources,
145
- })}\n`
146
- );
147
- })().catch(error => {
148
- process.stderr.write(
149
- `${JSON.stringify({
150
- event: 'miaoda_vite_bundled_dev_materialization_failed',
151
- message: error instanceof Error ? error.message : String(error),
152
- })}\n`
153
- );
154
- });
155
- },
156
- };
157
- }
158
-
159
- async function usePlatformBundledDevCompatibility(plugins) {
160
- if (!devBundleEnabled) return plugins;
161
- if (!fs.existsSync(platformVitePresetEntry)) {
162
- throw new Error(
163
- `MIAODA_PLATFORM_VITE_PRESET_ENTRY_MISSING: ${platformVitePresetEntry}`
164
- );
165
- }
166
- if (!fs.existsSync(platformReactPluginEntry)) {
167
- throw new Error(
168
- `MIAODA_PLATFORM_REACT_PLUGIN_ENTRY_MISSING: ${platformReactPluginEntry}`
169
- );
170
- }
171
- const platformPreset = await import(
172
- pathToFileURL(platformVitePresetEntry).href
173
- );
174
- const platformReact = await import(
175
- pathToFileURL(platformReactPluginEntry).href
176
- );
177
- if (typeof platformPreset.runtimeInjectionPlugin !== 'function') {
178
- throw new Error('MIAODA_PLATFORM_RUNTIME_INJECTION_PLUGIN_MISSING');
179
- }
180
- if (typeof platformPreset.errorOverlayPlugin !== 'function') {
181
- throw new Error('MIAODA_PLATFORM_ERROR_OVERLAY_PLUGIN_MISSING');
182
- }
183
- if (typeof platformPreset.createWsWatchdogPlugin !== 'function') {
184
- throw new Error('MIAODA_PLATFORM_WS_WATCHDOG_PLUGIN_MISSING');
185
- }
186
- if (typeof platformReact.default !== 'function') {
187
- throw new Error('MIAODA_PLATFORM_REACT_PLUGIN_MISSING');
188
- }
189
- const presetPackageFile = path.resolve(
190
- platformVitePresetEntry,
191
- '..',
192
- '..',
193
- 'package.json'
194
- );
195
- const reactPackageFile = path.resolve(
196
- platformReactPluginEntry,
197
- '..',
198
- '..',
199
- 'package.json'
200
- );
201
- const presetVersion = JSON.parse(
202
- fs.readFileSync(presetPackageFile, 'utf8')
203
- ).version;
204
- const reactPluginVersion = JSON.parse(
205
- fs.readFileSync(reactPackageFile, 'utf8')
206
- ).version;
207
- const flattenedPlugins = plugins.flat(Infinity).filter(Boolean);
208
- const clientBasePath = (process.env.CLIENT_BASE_PATH || '').replace(
209
- /\/+$/,
210
- ''
211
- );
212
- const platformRequire = createRequire(platformVitePresetEntry);
213
- let MagicString;
214
- try {
215
- const platformMagicString = platformRequire('magic-string');
216
- MagicString = platformMagicString.default || platformMagicString;
217
- } catch (error) {
218
- throw new Error(
219
- `MIAODA_PLATFORM_MAGIC_STRING_MISSING: ${error instanceof Error ? error.message : String(error)}`
220
- );
221
- }
222
- if (typeof MagicString !== 'function') {
223
- throw new Error('MIAODA_PLATFORM_MAGIC_STRING_INVALID');
224
- }
225
- const bundledDevLazyBasePlugin = {
226
- name: 'miaoda-vite-bundled-dev-lazy-base',
227
- renderChunk(code, chunk) {
228
- const lazyEndpointLiteral = '`/@vite/lazy?';
229
- const rewrittenLazyEndpointLiteral = `\`${clientBasePath}/@vite/lazy?`;
230
- const replacementOffsets = [];
231
- let searchOffset = 0;
232
- while (searchOffset < code.length) {
233
- const replacementOffset = code.indexOf(
234
- lazyEndpointLiteral,
235
- searchOffset
236
- );
237
- if (replacementOffset < 0) break;
238
- replacementOffsets.push(replacementOffset);
239
- searchOffset = replacementOffset + lazyEndpointLiteral.length;
240
- }
241
- if (replacementOffsets.length === 0) return null;
242
- const rewritten = new MagicString(code);
243
- for (const replacementOffset of replacementOffsets) {
244
- rewritten.overwrite(
245
- replacementOffset,
246
- replacementOffset + lazyEndpointLiteral.length,
247
- rewrittenLazyEndpointLiteral
248
- );
249
- }
250
- process.stdout.write(
251
- `${JSON.stringify({
252
- event: 'miaoda_vite_bundled_dev_lazy_base_rewritten',
253
- chunkFileName: chunk.fileName,
254
- clientBasePath,
255
- replacementCount: replacementOffsets.length,
256
- })}\n`
257
- );
258
- return {
259
- code: rewritten.toString(),
260
- map: rewritten.generateMap({
261
- source: chunk.fileName,
262
- includeContent: true,
263
- hires: true,
264
- }),
265
- };
266
- },
267
- };
268
- const platformRuntimePlugins = new Map([
269
- [
270
- 'fullstack-runtime-injection',
271
- platformPreset.runtimeInjectionPlugin({ clientBasePath }),
272
- ],
273
- [
274
- 'fullstack-error-overlay',
275
- platformPreset.errorOverlayPlugin({ clientBasePath }),
276
- ],
277
- [
278
- 'fullstack-ws-watchdog',
279
- platformPreset.createWsWatchdogPlugin({ clientBasePath }),
280
- ],
281
- ]);
282
- const workspaceRuntimePluginNamesReplaced = [];
283
- const installedPlatformRuntimePluginNames = new Set();
284
- const withPlatformRuntime = [];
285
- for (const plugin of flattenedPlugins) {
286
- const pluginName = plugin?.name;
287
- if (!platformRuntimePluginNames.has(pluginName)) {
288
- withPlatformRuntime.push(plugin);
289
- continue;
290
- }
291
- workspaceRuntimePluginNamesReplaced.push(pluginName);
292
- if (installedPlatformRuntimePluginNames.has(pluginName)) continue;
293
- withPlatformRuntime.push(platformRuntimePlugins.get(pluginName));
294
- installedPlatformRuntimePluginNames.add(pluginName);
295
- }
296
- for (const pluginName of platformRuntimePluginNames) {
297
- if (installedPlatformRuntimePluginNames.has(pluginName)) continue;
298
- withPlatformRuntime.push(platformRuntimePlugins.get(pluginName));
299
- }
300
- const firstReactIndex = withPlatformRuntime.findIndex(plugin =>
301
- plugin?.name?.startsWith('vite:react')
302
- );
303
- const workspaceReactPluginNames = withPlatformRuntime
304
- .filter(plugin => plugin?.name?.startsWith('vite:react'))
305
- .map(plugin => plugin.name);
306
- const retainedPlugins = withPlatformRuntime.filter(
307
- plugin => !plugin?.name?.startsWith('vite:react')
308
- );
309
- const styledJsxPlugin =
310
- process.env.FORCE_FRAMEWORK_BUILD_LOOSE_MODE === 'true'
311
- ? '@lark-apaas/styled-jsx/babel'
312
- : 'styled-jsx/babel';
313
- const platformReactPlugins = platformReact.default({
314
- jsxRuntime: 'automatic',
315
- babel: { plugins: [[styledJsxPlugin]] },
316
- });
317
- const reactInsertionIndex =
318
- firstReactIndex < 0
319
- ? retainedPlugins.length
320
- : Math.min(firstReactIndex, retainedPlugins.length);
321
- retainedPlugins.splice(reactInsertionIndex, 0, ...platformReactPlugins);
322
- retainedPlugins.push(bundledDevLazyBasePlugin);
323
- process.stdout.write(
324
- `${JSON.stringify({
325
- event: 'miaoda_vite_runtime_injection_policy',
326
- mode: 'bundled-entry',
327
- source: 'platform-image',
328
- presetVersion,
329
- presetEntry: platformVitePresetEntry,
330
- workspaceRuntimePluginNamesReplaced: [
331
- ...new Set(workspaceRuntimePluginNamesReplaced),
332
- ],
333
- })}\n`
334
- );
335
- process.stdout.write(
336
- `${JSON.stringify({
337
- event: 'miaoda_vite_react_compatibility_policy',
338
- mode: 'bundled-entry',
339
- source: 'platform-image',
340
- reactPluginVersion,
341
- reactPluginEntry: platformReactPluginEntry,
342
- styledJsxPlugin,
343
- workspaceReactPluginNamesRemoved: workspaceReactPluginNames,
344
- })}\n`
345
- );
346
- return retainedPlugins;
347
- }
348
-
349
- async function resolveWorkspaceConfig(configEnv) {
350
- const candidate =
351
- typeof workspaceConfig === 'function'
352
- ? workspaceConfig(configEnv)
353
- : workspaceConfig;
354
- return (await candidate) || {};
355
- }
356
-
357
- function cachePolicyEvidencePlugin() {
358
- return {
359
- name: 'miaoda-vite-deps-cache-policy-evidence',
360
- configResolved(config) {
361
- const metadataFile = path.join(config.cacheDir, 'deps', '_metadata.json');
362
- let metadataSize = 0;
363
- let metadataMtimeMs = 0;
364
- try {
365
- const stat = fs.statSync(metadataFile);
366
- metadataSize = stat.size;
367
- metadataMtimeMs = stat.mtimeMs;
368
- } catch {}
369
- process.stdout.write(
370
- `${JSON.stringify({
371
- event: 'miaoda_vite_deps_cache_policy',
372
- enabled: cacheEnabled,
373
- cacheDir: config.cacheDir,
374
- force: config.optimizeDeps.force === true,
375
- metadataFile,
376
- metadataExistsAtConfigResolved: metadataSize > 0,
377
- metadataSize,
378
- metadataMtimeMs,
379
- })}\n`
380
- );
381
- },
382
- };
383
- }
384
-
385
- function runtimePolicyEvidencePlugin() {
386
- return {
387
- name: 'miaoda-vite-runtime-policy-evidence',
388
- configResolved(config) {
389
- process.stdout.write(
390
- `${JSON.stringify({
391
- event: 'miaoda_vite_runtime_policy',
392
- vite8RuntimeEnabled,
393
- devBundleEnabled,
394
- bundledDevResolved: config.experimental?.bundledDev === true,
395
- })}\n`
396
- );
397
- },
398
- };
399
- }
400
-
401
- export default defineConfig(async configEnv => {
402
- const userConfig = await resolveWorkspaceConfig(configEnv);
403
- const cachePolicy = cacheEnabled
404
- ? {
405
- cacheDir: persistentCacheDir,
406
- optimizeDeps: { force: false },
407
- }
408
- : {
409
- cacheDir: ephemeralCacheDir,
410
- optimizeDeps: { force: true },
411
- };
412
- const resolved = mergeConfig(userConfig, cachePolicy);
413
- resolved.plugins = [
414
- ...(await usePlatformBundledDevCompatibility(resolved.plugins || [])),
415
- bundledDevMaterializationPlugin(),
416
- cachePolicyEvidencePlugin(),
417
- runtimePolicyEvidencePlugin(),
418
- ];
419
- return resolved;
420
- });