vite-plugin-ssr-config 1.0.3

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 ADDED
@@ -0,0 +1,489 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ default: () => index_default,
34
+ ssr: () => ssr,
35
+ ssrConfig: () => ssrConfig
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+ var import_path5 = __toESM(require("path"), 1);
39
+
40
+ // src/model.ts
41
+ var assertSSRConfig = (ssrOpts = {}) => {
42
+ let {
43
+ root = process.cwd(),
44
+ disableBuild = false,
45
+ //Main Entry
46
+ entryClient = ".ssr/entryClient.jsx",
47
+ entryRender = ".ssr/entryRender.jsx",
48
+ rootDocument = ".ssr/root.jsx",
49
+ //Server
50
+ server = ".ssr/server.js",
51
+ handler = ".ssr/handler.js",
52
+ //SSR
53
+ pageServer = ".ssr/pageServer.jsx",
54
+ pageBrowser = ".ssr/pageBrowser.jsx",
55
+ rootRoutes = ".ssr/rootRoutes.jsx",
56
+ errorBoundary = ".ssr/errorBoundary.jsx",
57
+ //Scripts
58
+ liveReload = ".ssr/liveReload.jsx",
59
+ viteScripts = ".ssr/viteScripts.jsx",
60
+ //Out directories
61
+ serverOutDir = "dist/",
62
+ serverMinify = false,
63
+ serverBuild = (config) => config,
64
+ clientOutDir = "dist/client",
65
+ clientMinify = true,
66
+ clientBuild = (config) => config
67
+ } = ssrOpts;
68
+ return {
69
+ root,
70
+ disableBuild,
71
+ entryClient,
72
+ entryRender,
73
+ rootDocument,
74
+ server,
75
+ handler,
76
+ pageServer,
77
+ pageBrowser,
78
+ rootRoutes,
79
+ errorBoundary,
80
+ liveReload,
81
+ viteScripts,
82
+ serverOutDir,
83
+ serverMinify,
84
+ serverBuild,
85
+ clientOutDir,
86
+ clientMinify,
87
+ clientBuild
88
+ };
89
+ };
90
+
91
+ // src/utils.ts
92
+ var import_fs_extra = __toESM(require("fs-extra"), 1);
93
+ var import_path = __toESM(require("path"), 1);
94
+ var import_url = require("url");
95
+ var import_meta = {};
96
+ var finalUrl = (base, name) => {
97
+ return import_path.default.join(base, name).replaceAll("\\", "/");
98
+ };
99
+ var getPluginDirectory = () => {
100
+ if (typeof __dirname === "undefined") {
101
+ const filename = (0, import_url.fileURLToPath)(import_meta.url);
102
+ return import_path.default.dirname(filename);
103
+ } else {
104
+ return __dirname;
105
+ }
106
+ };
107
+ var findDirPlugin = (dirname, max = 5) => {
108
+ const basedir = getPluginDirectory();
109
+ let relative = "/";
110
+ let dirPath = "";
111
+ for (var i = 0; i < max; i++) {
112
+ dirPath = import_path.default.join(basedir, relative, dirname);
113
+ if (import_fs_extra.default.existsSync(dirPath)) {
114
+ return dirPath;
115
+ }
116
+ relative += "../";
117
+ }
118
+ throw Error(`Not found: ${dirPath}`);
119
+ };
120
+ var cleanDirectory = (target) => {
121
+ if (import_fs_extra.default.existsSync(target)) {
122
+ import_fs_extra.default.rmSync(target, { recursive: true, force: true });
123
+ }
124
+ import_fs_extra.default.mkdirSync(target, { recursive: true });
125
+ };
126
+ var copyFilesDirectory = (origin, target, {
127
+ files = [],
128
+ oldId = "",
129
+ newId = ""
130
+ }) => {
131
+ files.forEach((file) => {
132
+ const sourceFilePath = import_path.default.join(origin, file);
133
+ const targetFilePath = import_path.default.join(target, file);
134
+ if (oldId !== newId) {
135
+ let fileContent = import_fs_extra.default.readFileSync(sourceFilePath, "utf-8");
136
+ fileContent = fileContent.replace(new RegExp(oldId, "g"), newId);
137
+ import_fs_extra.default.writeFileSync(targetFilePath, fileContent, "utf-8");
138
+ } else {
139
+ import_fs_extra.default.copySync(sourceFilePath, targetFilePath, { overwrite: true });
140
+ }
141
+ });
142
+ };
143
+
144
+ // src/plugin-build/build.ts
145
+ var import_fs_extra2 = __toESM(require("fs-extra"), 1);
146
+ var import_path2 = __toESM(require("path"), 1);
147
+ var import_vite = require("vite");
148
+ var doBuildServer = async (ssrConfig2, viteConfig) => {
149
+ const {
150
+ root,
151
+ serverMinify,
152
+ serverOutDir,
153
+ entryClient,
154
+ clientOutDir,
155
+ server,
156
+ handler,
157
+ serverBuild,
158
+ rootDocument,
159
+ entryRender,
160
+ pageServer,
161
+ pageBrowser,
162
+ rootRoutes,
163
+ errorBoundary,
164
+ liveReload,
165
+ viteScripts
166
+ } = ssrConfig2;
167
+ const { base = "/" } = viteConfig;
168
+ const ssrServerFile = import_path2.default.resolve(root, server);
169
+ const ssrPublicDir = import_path2.default.relative(serverOutDir, clientOutDir);
170
+ const manifestFile = import_path2.default.resolve(`${clientOutDir}/manifest.json`);
171
+ const manifestContent = import_fs_extra2.default.readFileSync(manifestFile, "utf-8");
172
+ const manifest = JSON.parse(manifestContent);
173
+ const manifestOut = manifest[entryClient].file;
174
+ const ssrEntryClientURL = finalUrl(base, manifestOut);
175
+ const ssrFiles = [
176
+ handler,
177
+ rootDocument,
178
+ entryClient,
179
+ entryRender,
180
+ pageServer,
181
+ pageBrowser,
182
+ rootRoutes,
183
+ errorBoundary,
184
+ liveReload,
185
+ viteScripts
186
+ ];
187
+ const baseConfig = {
188
+ appType: "custom",
189
+ base,
190
+ root,
191
+ publicDir: "private",
192
+ define: {
193
+ "process.env.SSR_BASENAME": JSON.stringify(base),
194
+ "process.env.SSR_PUBLIC_DIR": JSON.stringify(ssrPublicDir),
195
+ "process.env.SSR_ENTRY_CLIENT": JSON.stringify(ssrEntryClientURL),
196
+ "process.env.SSR": JSON.stringify(true)
197
+ },
198
+ ssr: {
199
+ noExternal: []
200
+ },
201
+ build: {
202
+ outDir: serverOutDir,
203
+ ssr: ssrServerFile,
204
+ write: true,
205
+ minify: serverMinify,
206
+ target: "esnext",
207
+ emptyOutDir: false,
208
+ rollupOptions: {
209
+ external: viteConfig.build?.rollupOptions?.external,
210
+ output: {
211
+ format: "es",
212
+ entryFileNames: "app.js",
213
+ chunkFileNames: "bin/[name]-[hash].js",
214
+ assetFileNames: "assets/[name]-[hash].[ext]",
215
+ manualChunks: (id) => {
216
+ const isSsr = ssrFiles.find(
217
+ (it) => id.startsWith(it) || id.endsWith(it)
218
+ );
219
+ if (isSsr) {
220
+ return "ssr";
221
+ }
222
+ if (id.startsWith("virtual")) {
223
+ return "virtual";
224
+ }
225
+ }
226
+ },
227
+ onwarn: (warning, handler2) => {
228
+ if (warning.code === "UNUSED_EXTERNAL_IMPORT" && warning.ids.some((id) => id.includes("node_modules"))) {
229
+ return;
230
+ }
231
+ handler2(warning);
232
+ }
233
+ }
234
+ }
235
+ };
236
+ const customConfig = await serverBuild(baseConfig);
237
+ const finalConfig = (0, import_vite.mergeConfig)(baseConfig, customConfig);
238
+ await (0, import_vite.build)(finalConfig);
239
+ };
240
+ var doBuildClient = async (ssrConfig2, viteConfig) => {
241
+ const { base = "/" } = viteConfig;
242
+ const { root, clientMinify, clientOutDir, entryClient, clientBuild } = ssrConfig2;
243
+ const preloadFiles = [
244
+ "modulepreload",
245
+ "commonjsHelpers",
246
+ "vite/",
247
+ "installHook"
248
+ ];
249
+ const baseConfig = {
250
+ root,
251
+ appType: "custom",
252
+ base,
253
+ define: {
254
+ "process.env.SSR_BASENAME": JSON.stringify(base),
255
+ "process.env.SSR": JSON.stringify(false)
256
+ },
257
+ build: {
258
+ write: true,
259
+ manifest: true,
260
+ minify: clientMinify,
261
+ target: "modules",
262
+ emptyOutDir: false,
263
+ outDir: clientOutDir,
264
+ rollupOptions: {
265
+ external: viteConfig.build?.rollupOptions?.external,
266
+ input: {
267
+ main: import_path2.default.resolve(root, entryClient)
268
+ },
269
+ output: {
270
+ format: "es",
271
+ entryFileNames: `assets/[name]-[hash].js`,
272
+ chunkFileNames: `chunks/[name]-[hash].js`,
273
+ assetFileNames: `assets/[name]-[hash].[ext]`,
274
+ manualChunks: (id) => {
275
+ const isInternal = preloadFiles.find((it) => id.includes(it));
276
+ if (isInternal) {
277
+ return "preload";
278
+ }
279
+ if (id.includes("node_modules")) {
280
+ return "vendor";
281
+ }
282
+ }
283
+ }
284
+ }
285
+ }
286
+ };
287
+ const customConfig = await clientBuild(baseConfig);
288
+ const finalConfig = (0, import_vite.mergeConfig)(baseConfig, customConfig);
289
+ await (0, import_vite.build)(finalConfig);
290
+ };
291
+
292
+ // src/plugin-build/index.ts
293
+ var pluginBuildSkip = () => {
294
+ const ENTRY_NONE = "____.html";
295
+ return {
296
+ name: "vite-plugin-ssr-config:skip",
297
+ enforce: "pre",
298
+ apply: "build",
299
+ config: () => {
300
+ if (process.env.IS_SSR_KIT_BUILD) return {};
301
+ return {
302
+ build: {
303
+ emptyOutDir: true,
304
+ copyPublicDir: false,
305
+ write: false,
306
+ rollupOptions: {
307
+ input: {
308
+ main: ENTRY_NONE
309
+ }
310
+ }
311
+ }
312
+ };
313
+ },
314
+ resolveId: (id) => {
315
+ if (id === ENTRY_NONE) {
316
+ return id;
317
+ }
318
+ return null;
319
+ },
320
+ load: (id) => {
321
+ if (id === ENTRY_NONE) {
322
+ return "";
323
+ }
324
+ return null;
325
+ }
326
+ };
327
+ };
328
+ var pluginBuildSSR = (ssrConfig2) => {
329
+ let viteConfig = {};
330
+ return {
331
+ name: "vite-plugin-ssr-config:build",
332
+ enforce: "pre",
333
+ apply: "build",
334
+ configResolved: (config) => {
335
+ viteConfig = config;
336
+ },
337
+ buildStart: async () => {
338
+ if (process.env.IS_SSR_KIT_BUILD) return;
339
+ process.env.IS_SSR_KIT_BUILD = "true";
340
+ cleanDirectory(ssrConfig2.clientOutDir);
341
+ cleanDirectory(ssrConfig2.serverOutDir);
342
+ viteConfig.logger.info("");
343
+ viteConfig.logger.info("\x1B[1m\x1B[31mCLIENT BUILD\x1B[0m");
344
+ await doBuildClient(ssrConfig2, viteConfig);
345
+ viteConfig.logger.info("");
346
+ viteConfig.logger.info("\x1B[1m\x1B[31mSERVER BUILD\x1B[0m");
347
+ await doBuildServer(ssrConfig2, viteConfig);
348
+ viteConfig.logger.info("");
349
+ }
350
+ };
351
+ };
352
+ var pluginBuild = (ssrConfig2) => {
353
+ if (ssrConfig2.disableBuild) {
354
+ return null;
355
+ }
356
+ return [pluginBuildSkip(), pluginBuildSSR(ssrConfig2)];
357
+ };
358
+
359
+ // src/plugin-resolve/index.ts
360
+ var import_path3 = __toESM(require("path"), 1);
361
+ var pluginResolve = (ssrConfig2) => {
362
+ let {
363
+ root,
364
+ server,
365
+ handler,
366
+ rootDocument,
367
+ entryClient,
368
+ entryRender,
369
+ pageServer,
370
+ pageBrowser,
371
+ rootRoutes,
372
+ errorBoundary,
373
+ liveReload,
374
+ viteScripts
375
+ } = ssrConfig2;
376
+ const absoluteFile = (name) => {
377
+ return import_path3.default.join(root, name);
378
+ };
379
+ return {
380
+ name: "vite-plugin-ssr-config:resolve",
381
+ enforce: "pre",
382
+ config: () => {
383
+ return {
384
+ resolve: {
385
+ alias: {
386
+ "@ssr/server.js": absoluteFile(server),
387
+ "@ssr/handler.js": absoluteFile(handler),
388
+ "@ssr/root.jsx": absoluteFile(rootDocument),
389
+ "@ssr/entryClient.jsx": absoluteFile(entryClient),
390
+ "@ssr/entryRender.jsx": absoluteFile(entryRender),
391
+ "@ssr/pageServer.jsx": absoluteFile(pageServer),
392
+ "@ssr/pageBrowser.jsx": absoluteFile(pageBrowser),
393
+ "@ssr/rootRoutes.jsx": absoluteFile(rootRoutes),
394
+ "@ssr/errorBoundary.jsx": absoluteFile(errorBoundary),
395
+ "@ssr/liveReload.jsx": absoluteFile(liveReload),
396
+ "@ssr/viteScripts.jsx": absoluteFile(viteScripts)
397
+ }
398
+ }
399
+ };
400
+ }
401
+ };
402
+ };
403
+
404
+ // src/plugin-serve/index.ts
405
+ var import_fs_extra3 = __toESM(require("fs-extra"), 1);
406
+ var import_path4 = __toESM(require("path"), 1);
407
+ var pluginServe = (ssrConfig2) => {
408
+ const { entryClient, root } = ssrConfig2;
409
+ return {
410
+ name: "vite-plugin-ssr-config:serve",
411
+ enforce: "post",
412
+ apply: "serve",
413
+ config: ({ base = "/" }) => {
414
+ const ssrClientEntry = finalUrl(base, entryClient);
415
+ return {
416
+ appType: "custom",
417
+ define: {
418
+ "process.env.SSR_BASENAME": JSON.stringify(base),
419
+ "process.env.SSR_ENTRY_CLIENT": JSON.stringify(ssrClientEntry)
420
+ }
421
+ };
422
+ },
423
+ configureServer: async (devServer) => {
424
+ return async () => {
425
+ devServer.middlewares.use(async (req, res, next) => {
426
+ const indexHtmlPath = import_path4.default.join(root, req.url, "index.html");
427
+ if (import_fs_extra3.default.existsSync(indexHtmlPath)) {
428
+ return devServer.transformIndexHtml(
429
+ req.url,
430
+ import_fs_extra3.default.readFileSync(indexHtmlPath, "utf-8")
431
+ ).then((html) => {
432
+ res.setHeader("Content-Type", "text/html");
433
+ res.setHeader("Pragma", "no-cache");
434
+ res.setHeader("Expires", "0");
435
+ res.end(html);
436
+ });
437
+ }
438
+ next();
439
+ });
440
+ devServer.middlewares.use(async (req, res, next) => {
441
+ try {
442
+ process.env.SSR = true;
443
+ const mod = await devServer.ssrLoadModule("@ssr/handler.js", {
444
+ fixStacktrace: true
445
+ });
446
+ await mod.handler(req, res, next);
447
+ } catch (error) {
448
+ next(error);
449
+ }
450
+ });
451
+ };
452
+ }
453
+ };
454
+ };
455
+
456
+ // src/index.ts
457
+ var ssrConfig = (opts = {}) => {
458
+ const ssrConfig2 = assertSSRConfig(opts);
459
+ const cacheOrigin = findDirPlugin("ssr");
460
+ const cacheTarget = import_path5.default.join(ssrConfig2.root, ".ssr");
461
+ cleanDirectory(cacheTarget);
462
+ copyFilesDirectory(cacheOrigin, cacheTarget, {
463
+ files: [
464
+ "entryClient.jsx",
465
+ "entryRender.jsx",
466
+ "errorBoundary.jsx",
467
+ "handler.js",
468
+ "liveReload.jsx",
469
+ "pageBrowser.jsx",
470
+ "pageServer.jsx",
471
+ "root.jsx",
472
+ "rootRoutes.jsx",
473
+ "server.js",
474
+ "viteScripts.jsx"
475
+ ]
476
+ });
477
+ return [
478
+ pluginResolve(ssrConfig2),
479
+ pluginServe(ssrConfig2),
480
+ pluginBuild(ssrConfig2)
481
+ ];
482
+ };
483
+ var ssr = ssrConfig;
484
+ var index_default = ssrConfig;
485
+ // Annotate the CommonJS export names for ESM import in node:
486
+ 0 && (module.exports = {
487
+ ssr,
488
+ ssrConfig
489
+ });
@@ -0,0 +1,29 @@
1
+ import { UserConfig, PluginOption } from 'vite';
2
+
3
+ type SSRConfig = {
4
+ root: string;
5
+ entryClient: string;
6
+ entryRender: string;
7
+ server: string;
8
+ handler: string;
9
+ rootDocument: string;
10
+ pageServer: string;
11
+ pageBrowser: string;
12
+ rootRoutes: string;
13
+ errorBoundary: string;
14
+ liveReload: string;
15
+ viteScripts: string;
16
+ clientOutDir: string;
17
+ clientMinify: boolean | "terser" | "esbuild";
18
+ clientBuild: (config: UserConfig) => UserConfig;
19
+ serverOutDir: string;
20
+ serverMinify: boolean | "terser" | "esbuild";
21
+ serverBuild: (config: UserConfig) => UserConfig;
22
+ disableBuild: boolean;
23
+ };
24
+ type SSROpts = Partial<SSRConfig>;
25
+
26
+ declare const ssrConfig: (opts?: SSROpts) => PluginOption;
27
+ declare const ssr: (opts?: SSROpts) => PluginOption;
28
+
29
+ export { ssrConfig as default, ssr, ssrConfig };
@@ -0,0 +1,29 @@
1
+ import { UserConfig, PluginOption } from 'vite';
2
+
3
+ type SSRConfig = {
4
+ root: string;
5
+ entryClient: string;
6
+ entryRender: string;
7
+ server: string;
8
+ handler: string;
9
+ rootDocument: string;
10
+ pageServer: string;
11
+ pageBrowser: string;
12
+ rootRoutes: string;
13
+ errorBoundary: string;
14
+ liveReload: string;
15
+ viteScripts: string;
16
+ clientOutDir: string;
17
+ clientMinify: boolean | "terser" | "esbuild";
18
+ clientBuild: (config: UserConfig) => UserConfig;
19
+ serverOutDir: string;
20
+ serverMinify: boolean | "terser" | "esbuild";
21
+ serverBuild: (config: UserConfig) => UserConfig;
22
+ disableBuild: boolean;
23
+ };
24
+ type SSROpts = Partial<SSRConfig>;
25
+
26
+ declare const ssrConfig: (opts?: SSROpts) => PluginOption;
27
+ declare const ssr: (opts?: SSROpts) => PluginOption;
28
+
29
+ export { ssrConfig as default, ssr, ssrConfig };