@rpcbase/vite 0.158.0 → 0.159.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,751 +2,812 @@ import fs, { existsSync, readFileSync } from "node:fs";
2
2
  import path from "path";
3
3
  import dotenv from "dotenv";
4
4
  import { expand } from "dotenv-expand";
5
- import babel, { defineRolldownBabelPreset } from "@rolldown/plugin-babel";
6
- import { createServer as createServer$1, loadEnv, mergeConfig } from "vite";
5
+ import { createServer as createServer$1, mergeConfig, loadEnv } from "vite";
7
6
  import { viteSingleFile } from "vite-plugin-singlefile";
8
- import react, { reactCompilerPreset } from "@vitejs/plugin-react";
7
+ import react from "@vitejs/plugin-react";
8
+ import { createHtmlPlugin } from "vite-plugin-html";
9
9
  import { analyzer } from "vite-bundle-analyzer";
10
10
  import { createRequire } from "node:module";
11
- import ejs from "ejs";
12
11
  import { spawn } from "node:child_process";
13
12
  import path$1 from "node:path";
14
13
  import { fileURLToPath } from "node:url";
15
14
  import MagicString from "magic-string";
16
15
  import * as ts from "typescript";
17
16
  import { globSync } from "glob";
18
- //#region src/dotEnvExpand.ts
19
- var envFilePath = path.resolve(process.cwd(), ".env");
17
+ const envFilePath = path.resolve(process.cwd(), ".env");
20
18
  if (fs.existsSync(envFilePath)) {
21
- const expanded = expand({ parsed: dotenv.parse(fs.readFileSync(envFilePath)) }).parsed || {};
22
- Object.assign(process.env, expanded);
19
+ const parsedFile = dotenv.parse(fs.readFileSync(envFilePath));
20
+ const expanded = expand({
21
+ parsed: parsedFile
22
+ }).parsed || {};
23
+ Object.assign(process.env, expanded);
23
24
  }
24
- //#endregion
25
- //#region src/resolveIntegratedPackagePath.ts
26
- var require = createRequire(import.meta.url);
27
- var splitPackageSpecifier = (specifier) => {
28
- if (!specifier) return {
29
- pkgName: specifier,
30
- subpath: ""
31
- };
32
- if (specifier.startsWith("@")) {
33
- const segments = specifier.split("/");
34
- if (segments.length < 2) return {
35
- pkgName: specifier,
36
- subpath: ""
37
- };
38
- return {
39
- pkgName: `${segments[0]}/${segments[1]}`,
40
- subpath: segments.slice(2).join("/")
41
- };
42
- }
43
- const [pkgName, ...rest] = specifier.split("/");
44
- return {
45
- pkgName,
46
- subpath: rest.join("/")
47
- };
25
+ const require$1 = createRequire(import.meta.url);
26
+ const splitPackageSpecifier = (specifier) => {
27
+ if (!specifier) return {
28
+ pkgName: specifier,
29
+ subpath: ""
30
+ };
31
+ if (specifier.startsWith("@")) {
32
+ const segments = specifier.split("/");
33
+ if (segments.length < 2) return {
34
+ pkgName: specifier,
35
+ subpath: ""
36
+ };
37
+ return {
38
+ pkgName: `${segments[0]}/${segments[1]}`,
39
+ subpath: segments.slice(2).join("/")
40
+ };
41
+ }
42
+ const [pkgName, ...rest] = specifier.split("/");
43
+ return {
44
+ pkgName,
45
+ subpath: rest.join("/")
46
+ };
48
47
  };
49
- var withTrailingSep = (p) => p.endsWith(path.sep) ? p : p + path.sep;
50
- var resolvePackageRoot = (pkg) => {
51
- const { pkgName } = splitPackageSpecifier(pkg);
52
- if (!pkgName) return pkg;
53
- try {
54
- const pkgJson = require.resolve(`${pkgName}/package.json`);
55
- return path.dirname(pkgJson);
56
- } catch (err) {
57
- const entry = require.resolve(pkgName);
58
- let dir = path.dirname(entry);
59
- while (true) {
60
- const pkgJsonPath = path.join(dir, "package.json");
61
- if (existsSync(pkgJsonPath)) try {
62
- const json = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
63
- if (json && json.name === pkgName) return dir;
64
- } catch {}
65
- const parent = path.dirname(dir);
66
- if (parent === dir) break;
67
- dir = parent;
68
- }
69
- const nmMarker = `${path.sep}node_modules${path.sep}`;
70
- const idx = entry.lastIndexOf(nmMarker);
71
- if (idx !== -1) {
72
- const nmRoot = entry.slice(0, idx + nmMarker.length);
73
- return path.join(nmRoot, pkgName);
74
- }
75
- throw err;
76
- }
48
+ const withTrailingSep = (p) => p.endsWith(path.sep) ? p : p + path.sep;
49
+ const resolvePackageRoot = (pkg) => {
50
+ const {
51
+ pkgName
52
+ } = splitPackageSpecifier(pkg);
53
+ if (!pkgName) return pkg;
54
+ try {
55
+ const pkgJson = require$1.resolve(`${pkgName}/package.json`);
56
+ return path.dirname(pkgJson);
57
+ } catch (err) {
58
+ const entry = require$1.resolve(pkgName);
59
+ let dir = path.dirname(entry);
60
+ while (true) {
61
+ const pkgJsonPath = path.join(dir, "package.json");
62
+ if (existsSync(pkgJsonPath)) {
63
+ try {
64
+ const json = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
65
+ if (json && json.name === pkgName) return dir;
66
+ } catch {
67
+ }
68
+ }
69
+ const parent = path.dirname(dir);
70
+ if (parent === dir) break;
71
+ dir = parent;
72
+ }
73
+ const nmMarker = `${path.sep}node_modules${path.sep}`;
74
+ const idx = entry.lastIndexOf(nmMarker);
75
+ if (idx !== -1) {
76
+ const nmRoot = entry.slice(0, idx + nmMarker.length);
77
+ return path.join(nmRoot, pkgName);
78
+ }
79
+ throw err;
80
+ }
77
81
  };
78
- var resolveIntegratedPackagePath = (specifier) => {
79
- const { pkgName, subpath } = splitPackageSpecifier(specifier);
80
- if (!pkgName) return specifier;
81
- const root = resolvePackageRoot(pkgName);
82
- if (!subpath) return withTrailingSep(root);
83
- const subDir = path.join(root, subpath);
84
- const pkgJsonPath = path.join(subDir, "package.json");
85
- if (existsSync(pkgJsonPath)) try {
86
- const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
87
- const entry = pkgJson.module || pkgJson.main;
88
- if (entry) return path.join(subDir, entry);
89
- } catch {}
90
- try {
91
- return require.resolve(specifier);
92
- } catch {
93
- return withTrailingSep(subDir);
94
- }
82
+ const resolveIntegratedPackagePath = (specifier) => {
83
+ const {
84
+ pkgName,
85
+ subpath
86
+ } = splitPackageSpecifier(specifier);
87
+ if (!pkgName) return specifier;
88
+ const root = resolvePackageRoot(pkgName);
89
+ if (!subpath) {
90
+ return withTrailingSep(root);
91
+ }
92
+ const subDir = path.join(root, subpath);
93
+ const pkgJsonPath = path.join(subDir, "package.json");
94
+ if (existsSync(pkgJsonPath)) {
95
+ try {
96
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
97
+ const entry = pkgJson.module || pkgJson.main;
98
+ if (entry) {
99
+ return path.join(subDir, entry);
100
+ }
101
+ } catch {
102
+ }
103
+ }
104
+ try {
105
+ return require$1.resolve(specifier);
106
+ } catch {
107
+ return withTrailingSep(subDir);
108
+ }
95
109
  };
96
- //#endregion
97
- //#region src/plugins/html-template/index.ts
98
- var renderHtmlTemplate = (template, locals) => {
99
- return ejs.render(template, locals, { async: false });
100
- };
101
- var createTemplateLocals = (locals) => {
102
- const env = Object.fromEntries(Object.entries(locals).map(([key, value]) => [key, String(value)]));
103
- return {
104
- ...locals,
105
- ...env,
106
- process: { env: {
107
- ...process.env,
108
- ...env
109
- } }
110
- };
111
- };
112
- var htmlTemplatePlugin = (locals) => {
113
- return {
114
- name: "rb-html-template",
115
- transformIndexHtml: {
116
- order: "pre",
117
- handler(html) {
118
- if (!html.includes("<%")) return html;
119
- return renderHtmlTemplate(html, createTemplateLocals(locals));
120
- }
121
- }
122
- };
123
- };
124
- //#endregion
125
- //#region src/plugins/posthog-sourcemaps/index.ts
126
- var __dirname = path$1.dirname(fileURLToPath(import.meta.url));
110
+ const __dirname$1 = path$1.dirname(fileURLToPath(import.meta.url));
127
111
  function run(bin, args) {
128
- return new Promise((resolve, reject) => {
129
- spawn(bin, args, { stdio: "inherit" }).on("close", (code) => code === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`posthog-cli exited ${code}`)));
130
- });
112
+ return new Promise((resolve, reject) => {
113
+ const p = spawn(bin, args, {
114
+ stdio: "inherit"
115
+ });
116
+ p.on("close", (code) => code === 0 ? resolve() : reject(new Error(`posthog-cli exited ${code}`)));
117
+ });
131
118
  }
132
119
  function resolvePosthogCliBin() {
133
- const binName = "posthog-cli";
134
- const fromCwd = path$1.join(process.cwd(), "node_modules", ".bin", binName);
135
- if (fs.existsSync(fromCwd)) return fromCwd;
136
- let dir = __dirname;
137
- while (true) {
138
- const candidate = path$1.join(dir, "node_modules", ".bin", binName);
139
- if (fs.existsSync(candidate)) return candidate;
140
- const parent = path$1.dirname(dir);
141
- if (parent === dir) break;
142
- dir = parent;
143
- }
144
- return binName;
120
+ const binName = "posthog-cli";
121
+ const fromCwd = path$1.join(process.cwd(), "node_modules", ".bin", binName);
122
+ if (fs.existsSync(fromCwd)) return fromCwd;
123
+ let dir = __dirname$1;
124
+ while (true) {
125
+ const candidate = path$1.join(dir, "node_modules", ".bin", binName);
126
+ if (fs.existsSync(candidate)) return candidate;
127
+ const parent = path$1.dirname(dir);
128
+ if (parent === dir) break;
129
+ dir = parent;
130
+ }
131
+ return binName;
145
132
  }
146
133
  function posthogSourcemapsPlugin(opts = {}) {
147
- const { directory = "build/dist", version, host = process.env.RB_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com", deleteAfterUpload = true } = opts;
148
- const bin = resolvePosthogCliBin();
149
- const globalArgs = ["--host", host];
150
- return {
151
- name: "posthog-sourcemaps",
152
- apply: "build",
153
- closeBundle: async () => {
154
- const orange = "\x1B[38;5;208m";
155
- const reset = "\x1B[0m";
156
- const envId = process.env.POSTHOG_CLI_ENV_ID;
157
- const token = process.env.POSTHOG_CLI_TOKEN;
158
- if (!envId || !token) {
159
- console.warn(`${orange}posthog-sourcemaps: plugin is enabled but no env vars for auth configured (POSTHOG_CLI_ENV_ID/POSTHOG_CLI_TOKEN). Skipping without failing.${reset}`);
160
- return;
161
- }
162
- const injectArgs = [
163
- "sourcemap",
164
- "inject",
165
- "--directory",
166
- directory
167
- ];
168
- if (version) injectArgs.push("--version", version);
169
- const uploadArgs = [
170
- "sourcemap",
171
- "upload",
172
- "--directory",
173
- directory
174
- ];
175
- if (deleteAfterUpload) uploadArgs.push("--delete-after");
176
- await run(bin, [...globalArgs, ...injectArgs]);
177
- await run(bin, [...globalArgs, ...uploadArgs]);
178
- }
179
- };
134
+ const {
135
+ directory = "build/dist",
136
+ version,
137
+ host = process.env.RB_PUBLIC_POSTHOG_HOST || "https://eu.posthog.com",
138
+ deleteAfterUpload = true
139
+ } = opts;
140
+ const bin = resolvePosthogCliBin();
141
+ const globalArgs = ["--host", host];
142
+ return {
143
+ name: "posthog-sourcemaps",
144
+ apply: "build",
145
+ closeBundle: async () => {
146
+ const orange = "\x1B[38;5;208m";
147
+ const reset = "\x1B[0m";
148
+ const envId = process.env.POSTHOG_CLI_ENV_ID;
149
+ const token = process.env.POSTHOG_CLI_TOKEN;
150
+ if (!envId || !token) {
151
+ console.warn(`${orange}posthog-sourcemaps: plugin is enabled but no env vars for auth configured (POSTHOG_CLI_ENV_ID/POSTHOG_CLI_TOKEN). Skipping without failing.${reset}`);
152
+ return;
153
+ }
154
+ const injectArgs = ["sourcemap", "inject", "--directory", directory];
155
+ if (version) injectArgs.push("--version", version);
156
+ const uploadArgs = ["sourcemap", "upload", "--directory", directory];
157
+ if (deleteAfterUpload) uploadArgs.push("--delete-after");
158
+ await run(bin, [...globalArgs, ...injectArgs]);
159
+ await run(bin, [...globalArgs, ...uploadArgs]);
160
+ }
161
+ };
180
162
  }
181
- //#endregion
182
- //#region src/plugins/prune-models-for-client/transformSource.ts
183
163
  function isForbiddenModuleSource(source) {
184
- if (source === "mongoose") return true;
185
- if (source.startsWith("node:")) return true;
186
- if (source.endsWith("/extendMongooseSchema") || source.endsWith("./extendMongooseSchema") || source.endsWith("extendMongooseSchema")) return true;
187
- return false;
164
+ if (source === "mongoose") return true;
165
+ if (source.startsWith("node:")) return true;
166
+ if (source.endsWith("/extendMongooseSchema") || source.endsWith("./extendMongooseSchema") || source.endsWith("extendMongooseSchema")) {
167
+ return true;
168
+ }
169
+ return false;
188
170
  }
189
171
  function getModuleSpecifierValue(importDeclaration) {
190
- const moduleSpecifier = importDeclaration.moduleSpecifier;
191
- if (!ts.isStringLiteralLike(moduleSpecifier)) return null;
192
- return moduleSpecifier.text;
172
+ const moduleSpecifier = importDeclaration.moduleSpecifier;
173
+ if (!ts.isStringLiteralLike(moduleSpecifier)) return null;
174
+ return moduleSpecifier.text;
193
175
  }
194
176
  function isTypeOnlyImport(importDeclaration) {
195
- const importClause = importDeclaration.importClause;
196
- if (!importClause) return false;
197
- return importClause.isTypeOnly === true;
177
+ const importClause = importDeclaration.importClause;
178
+ if (!importClause) return false;
179
+ return importClause.isTypeOnly === true;
198
180
  }
199
181
  function getImportValueLocals(importDeclaration) {
200
- if (isTypeOnlyImport(importDeclaration)) return [];
201
- const importClause = importDeclaration.importClause;
202
- if (!importClause) return [];
203
- const locals = [];
204
- if (importClause.name) locals.push(importClause.name.text);
205
- const namedBindings = importClause.namedBindings;
206
- if (namedBindings) {
207
- if (ts.isNamespaceImport(namedBindings)) locals.push(namedBindings.name.text);
208
- else if (ts.isNamedImports(namedBindings)) for (const specifier of namedBindings.elements) {
209
- if (specifier.isTypeOnly) continue;
210
- locals.push(specifier.name.text);
211
- }
212
- }
213
- return locals;
182
+ if (isTypeOnlyImport(importDeclaration)) return [];
183
+ const importClause = importDeclaration.importClause;
184
+ if (!importClause) return [];
185
+ const locals = [];
186
+ if (importClause.name) locals.push(importClause.name.text);
187
+ const namedBindings = importClause.namedBindings;
188
+ if (namedBindings) {
189
+ if (ts.isNamespaceImport(namedBindings)) {
190
+ locals.push(namedBindings.name.text);
191
+ } else if (ts.isNamedImports(namedBindings)) {
192
+ for (const specifier of namedBindings.elements) {
193
+ if (specifier.isTypeOnly) continue;
194
+ locals.push(specifier.name.text);
195
+ }
196
+ }
197
+ }
198
+ return locals;
214
199
  }
215
200
  function getNamedImportSpecifiers(importDeclaration) {
216
- const importClause = importDeclaration.importClause;
217
- if (!importClause) return null;
218
- if (!importClause.namedBindings) return null;
219
- if (!ts.isNamedImports(importClause.namedBindings)) return null;
220
- return importClause.namedBindings.elements;
201
+ const importClause = importDeclaration.importClause;
202
+ if (!importClause) return null;
203
+ if (!importClause.namedBindings) return null;
204
+ if (!ts.isNamedImports(importClause.namedBindings)) return null;
205
+ return importClause.namedBindings.elements;
221
206
  }
222
207
  function rewriteRpcbaseDbImport(importDeclaration, forbiddenIdentifiers) {
223
- const valueLocals = getImportValueLocals(importDeclaration);
224
- const zLocals = /* @__PURE__ */ new Set();
225
- const namedImports = getNamedImportSpecifiers(importDeclaration);
226
- if (namedImports && !isTypeOnlyImport(importDeclaration)) for (const specifier of namedImports) {
227
- if (specifier.isTypeOnly) continue;
228
- if ((specifier.propertyName?.text ?? specifier.name.text) !== "z") continue;
229
- zLocals.add(specifier.name.text);
230
- }
231
- for (const local of valueLocals) if (!zLocals.has(local)) forbiddenIdentifiers.add(local);
232
- if (zLocals.size === 0) return {
233
- rewriteText: null,
234
- remainingValueLocals: []
235
- };
236
- return {
237
- rewriteText: `import { ${Array.from(zLocals).map((local) => local === "z" ? "z" : `z as ${local}`).join(", ")} } from "@rpcbase/db"`,
238
- remainingValueLocals: Array.from(zLocals)
239
- };
208
+ const valueLocals = getImportValueLocals(importDeclaration);
209
+ const zLocals = /* @__PURE__ */ new Set();
210
+ const namedImports = getNamedImportSpecifiers(importDeclaration);
211
+ if (namedImports && !isTypeOnlyImport(importDeclaration)) {
212
+ for (const specifier of namedImports) {
213
+ if (specifier.isTypeOnly) continue;
214
+ const imported = specifier.propertyName?.text ?? specifier.name.text;
215
+ if (imported !== "z") continue;
216
+ zLocals.add(specifier.name.text);
217
+ }
218
+ }
219
+ for (const local of valueLocals) {
220
+ if (!zLocals.has(local)) forbiddenIdentifiers.add(local);
221
+ }
222
+ if (zLocals.size === 0) {
223
+ return {
224
+ rewriteText: null,
225
+ remainingValueLocals: []
226
+ };
227
+ }
228
+ const specifierText = Array.from(zLocals).map((local) => local === "z" ? "z" : `z as ${local}`).join(", ");
229
+ return {
230
+ rewriteText: `import { ${specifierText} } from "@rpcbase/db"`,
231
+ remainingValueLocals: Array.from(zLocals)
232
+ };
240
233
  }
241
234
  function collectBindingNames(name, out) {
242
- if (ts.isIdentifier(name)) {
243
- out.push(name.text);
244
- return;
245
- }
246
- for (const element of name.elements) {
247
- if (ts.isOmittedExpression(element)) continue;
248
- collectBindingNames(element.name, out);
249
- }
235
+ if (ts.isIdentifier(name)) {
236
+ out.push(name.text);
237
+ return;
238
+ }
239
+ for (const element of name.elements) {
240
+ if (ts.isOmittedExpression(element)) continue;
241
+ collectBindingNames(element.name, out);
242
+ }
250
243
  }
251
244
  function getTopLevelBindings(statement) {
252
- if (ts.isVariableStatement(statement)) {
253
- const names = [];
254
- for (const decl of statement.declarationList.declarations) collectBindingNames(decl.name, names);
255
- return names;
256
- }
257
- if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) return statement.name ? [statement.name.text] : [];
258
- return [];
245
+ if (ts.isVariableStatement(statement)) {
246
+ const names = [];
247
+ for (const decl of statement.declarationList.declarations) {
248
+ collectBindingNames(decl.name, names);
249
+ }
250
+ return names;
251
+ }
252
+ if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) {
253
+ return statement.name ? [statement.name.text] : [];
254
+ }
255
+ return [];
259
256
  }
260
257
  function isRuntimeReferenceIdentifier(identifier) {
261
- const parent = identifier.parent;
262
- if (!parent) return true;
263
- if (ts.isVariableDeclaration(parent) && parent.name === identifier) return false;
264
- if (ts.isParameter(parent) && parent.name === identifier) return false;
265
- if ((ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent)) && parent.name === identifier) return false;
266
- if ((ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) && parent.name === identifier) return false;
267
- if (ts.isEnumDeclaration(parent) && parent.name === identifier) return false;
268
- if (ts.isTypeAliasDeclaration(parent) && parent.name === identifier) return false;
269
- if (ts.isInterfaceDeclaration(parent) && parent.name === identifier) return false;
270
- if (ts.isModuleDeclaration(parent) && parent.name === identifier) return false;
271
- if (ts.isTypeParameterDeclaration(parent) && parent.name === identifier) return false;
272
- if (ts.isImportClause(parent) && parent.name === identifier) return false;
273
- if (ts.isNamespaceImport(parent) && parent.name === identifier) return false;
274
- if (ts.isImportSpecifier(parent) && parent.name === identifier) return false;
275
- if (ts.isImportEqualsDeclaration(parent) && parent.name === identifier) return false;
276
- if (ts.isBindingElement(parent)) {
277
- if (parent.name === identifier) return false;
278
- if (parent.propertyName === identifier) return false;
279
- }
280
- if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) return false;
281
- if (ts.isQualifiedName(parent)) return false;
282
- if (ts.isPropertyAssignment(parent) && parent.name === identifier) return false;
283
- if (ts.isPropertyDeclaration(parent) && parent.name === identifier) return false;
284
- if (ts.isPropertySignature(parent) && parent.name === identifier) return false;
285
- if (ts.isMethodDeclaration(parent) && parent.name === identifier) return false;
286
- if (ts.isMethodSignature(parent) && parent.name === identifier) return false;
287
- if (ts.isGetAccessorDeclaration(parent) && parent.name === identifier) return false;
288
- if (ts.isSetAccessorDeclaration(parent) && parent.name === identifier) return false;
289
- if (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) return true;
290
- if (ts.isExportSpecifier(parent)) return identifier === (parent.propertyName ?? parent.name);
291
- if (ts.isLabeledStatement(parent) && parent.label === identifier) return false;
292
- if ((ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === identifier) return false;
293
- return true;
258
+ const parent = identifier.parent;
259
+ if (!parent) return true;
260
+ if (ts.isVariableDeclaration(parent) && parent.name === identifier) return false;
261
+ if (ts.isParameter(parent) && parent.name === identifier) return false;
262
+ if ((ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent)) && parent.name === identifier) return false;
263
+ if ((ts.isClassDeclaration(parent) || ts.isClassExpression(parent)) && parent.name === identifier) return false;
264
+ if (ts.isEnumDeclaration(parent) && parent.name === identifier) return false;
265
+ if (ts.isTypeAliasDeclaration(parent) && parent.name === identifier) return false;
266
+ if (ts.isInterfaceDeclaration(parent) && parent.name === identifier) return false;
267
+ if (ts.isModuleDeclaration(parent) && parent.name === identifier) return false;
268
+ if (ts.isTypeParameterDeclaration(parent) && parent.name === identifier) return false;
269
+ if (ts.isImportClause(parent) && parent.name === identifier) return false;
270
+ if (ts.isNamespaceImport(parent) && parent.name === identifier) return false;
271
+ if (ts.isImportSpecifier(parent) && parent.name === identifier) return false;
272
+ if (ts.isImportEqualsDeclaration(parent) && parent.name === identifier) return false;
273
+ if (ts.isBindingElement(parent)) {
274
+ if (parent.name === identifier) return false;
275
+ if (parent.propertyName === identifier) return false;
276
+ }
277
+ if (ts.isPropertyAccessExpression(parent) && parent.name === identifier) return false;
278
+ if (ts.isQualifiedName(parent)) return false;
279
+ if (ts.isPropertyAssignment(parent) && parent.name === identifier) return false;
280
+ if (ts.isPropertyDeclaration(parent) && parent.name === identifier) return false;
281
+ if (ts.isPropertySignature(parent) && parent.name === identifier) return false;
282
+ if (ts.isMethodDeclaration(parent) && parent.name === identifier) return false;
283
+ if (ts.isMethodSignature(parent) && parent.name === identifier) return false;
284
+ if (ts.isGetAccessorDeclaration(parent) && parent.name === identifier) return false;
285
+ if (ts.isSetAccessorDeclaration(parent) && parent.name === identifier) return false;
286
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === identifier) return true;
287
+ if (ts.isExportSpecifier(parent)) {
288
+ const local = parent.propertyName ?? parent.name;
289
+ return identifier === local;
290
+ }
291
+ if (ts.isLabeledStatement(parent) && parent.label === identifier) return false;
292
+ if ((ts.isBreakStatement(parent) || ts.isContinueStatement(parent)) && parent.label === identifier) return false;
293
+ return true;
294
294
  }
295
295
  function referencesForbiddenRuntime(statement, forbidden) {
296
- if (forbidden.size === 0) return false;
297
- if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) return false;
298
- let found = false;
299
- const visit = (node) => {
300
- if (found) return;
301
- if (ts.isTypeNode(node)) return;
302
- if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
303
- if (ts.isIdentifier(node)) {
304
- if (forbidden.has(node.text) && isRuntimeReferenceIdentifier(node)) {
305
- found = true;
306
- return;
307
- }
308
- }
309
- ts.forEachChild(node, visit);
310
- };
311
- visit(statement);
312
- return found;
296
+ if (forbidden.size === 0) return false;
297
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement)) return false;
298
+ let found = false;
299
+ const visit = (node) => {
300
+ if (found) return;
301
+ if (ts.isTypeNode(node)) return;
302
+ if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
303
+ if (ts.isIdentifier(node)) {
304
+ if (forbidden.has(node.text) && isRuntimeReferenceIdentifier(node)) {
305
+ found = true;
306
+ return;
307
+ }
308
+ }
309
+ ts.forEachChild(node, visit);
310
+ };
311
+ visit(statement);
312
+ return found;
313
313
  }
314
314
  function scriptKindFromFilePath(filePath) {
315
- if (path$1.extname(filePath).toLowerCase() === ".tsx") return ts.ScriptKind.TSX;
316
- return ts.ScriptKind.TS;
315
+ const ext = path$1.extname(filePath).toLowerCase();
316
+ if (ext === ".tsx") return ts.ScriptKind.TSX;
317
+ return ts.ScriptKind.TS;
317
318
  }
318
319
  function collectRuntimeIdentifierReferences(statement, out) {
319
- const visit = (node) => {
320
- if (ts.isTypeNode(node)) return;
321
- if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
322
- if (ts.isIdentifier(node) && isRuntimeReferenceIdentifier(node)) out.add(node.text);
323
- ts.forEachChild(node, visit);
324
- };
325
- visit(statement);
320
+ const visit = (node) => {
321
+ if (ts.isTypeNode(node)) return;
322
+ if (ts.isHeritageClause(node) && node.token === ts.SyntaxKind.ImplementsKeyword) return;
323
+ if (ts.isIdentifier(node) && isRuntimeReferenceIdentifier(node)) {
324
+ out.add(node.text);
325
+ }
326
+ ts.forEachChild(node, visit);
327
+ };
328
+ visit(statement);
326
329
  }
327
330
  function createTransformSource() {
328
- return ({ code, filePath }) => {
329
- const forbiddenIdentifiers = /* @__PURE__ */ new Set();
330
- const scriptKind = scriptKindFromFilePath(filePath);
331
- const sourceFile = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true, scriptKind);
332
- const importActions = /* @__PURE__ */ new Map();
333
- for (const statement of sourceFile.statements) {
334
- if (!ts.isImportDeclaration(statement)) continue;
335
- const source = getModuleSpecifierValue(statement);
336
- if (!source) continue;
337
- if (source === "@rpcbase/db") {
338
- const { rewriteText, remainingValueLocals } = rewriteRpcbaseDbImport(statement, forbiddenIdentifiers);
339
- if (!rewriteText) importActions.set(statement, { type: "remove" });
340
- else importActions.set(statement, {
341
- type: "overwrite",
342
- text: rewriteText,
343
- remainingValueLocals
344
- });
345
- continue;
346
- }
347
- if (!isForbiddenModuleSource(source)) continue;
348
- getImportValueLocals(statement).forEach((local) => forbiddenIdentifiers.add(local));
349
- importActions.set(statement, { type: "remove" });
350
- }
351
- let changed = true;
352
- const statementsToRemove = /* @__PURE__ */ new Set();
353
- while (changed) {
354
- changed = false;
355
- for (const statement of sourceFile.statements) {
356
- if (ts.isImportDeclaration(statement)) continue;
357
- if (statementsToRemove.has(statement)) continue;
358
- if (!referencesForbiddenRuntime(statement, forbiddenIdentifiers)) continue;
359
- getTopLevelBindings(statement).forEach((name) => forbiddenIdentifiers.add(name));
360
- statementsToRemove.add(statement);
361
- changed = true;
362
- }
363
- }
364
- const usedRuntimeIdentifiers = /* @__PURE__ */ new Set();
365
- for (const statement of sourceFile.statements) {
366
- if (ts.isImportDeclaration(statement)) continue;
367
- if (statementsToRemove.has(statement)) continue;
368
- collectRuntimeIdentifierReferences(statement, usedRuntimeIdentifiers);
369
- }
370
- for (const statement of sourceFile.statements) {
371
- if (!ts.isImportDeclaration(statement)) continue;
372
- const currentAction = importActions.get(statement);
373
- if (currentAction?.type === "remove") continue;
374
- const remainingValueLocals = currentAction?.type === "overwrite" ? currentAction.remainingValueLocals : getImportValueLocals(statement);
375
- if (remainingValueLocals.length === 0) continue;
376
- if (remainingValueLocals.some((local) => usedRuntimeIdentifiers.has(local))) continue;
377
- importActions.set(statement, { type: "remove" });
378
- }
379
- const s = new MagicString(code);
380
- for (const [importDeclaration, action] of importActions) {
381
- if (action.type === "remove") {
382
- s.remove(importDeclaration.pos, importDeclaration.end);
383
- continue;
384
- }
385
- const start = importDeclaration.getStart(sourceFile);
386
- s.overwrite(start, importDeclaration.end, action.text);
387
- }
388
- for (const statement of statementsToRemove) s.remove(statement.pos, statement.end);
389
- if (!s.hasChanged()) return null;
390
- const map = JSON.parse(s.generateMap({
391
- hires: true,
392
- includeContent: true,
393
- source: filePath,
394
- file: filePath
395
- }).toString());
396
- map.file = filePath;
397
- map.sources = [filePath];
398
- return {
399
- code: s.toString(),
400
- map: JSON.stringify(map)
401
- };
402
- };
331
+ return ({
332
+ code,
333
+ filePath
334
+ }) => {
335
+ const forbiddenIdentifiers = /* @__PURE__ */ new Set();
336
+ const scriptKind = scriptKindFromFilePath(filePath);
337
+ const sourceFile = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true, scriptKind);
338
+ const importActions = /* @__PURE__ */ new Map();
339
+ for (const statement of sourceFile.statements) {
340
+ if (!ts.isImportDeclaration(statement)) continue;
341
+ const source = getModuleSpecifierValue(statement);
342
+ if (!source) continue;
343
+ if (source === "@rpcbase/db") {
344
+ const {
345
+ rewriteText,
346
+ remainingValueLocals
347
+ } = rewriteRpcbaseDbImport(statement, forbiddenIdentifiers);
348
+ if (!rewriteText) importActions.set(statement, {
349
+ type: "remove"
350
+ });
351
+ else importActions.set(statement, {
352
+ type: "overwrite",
353
+ text: rewriteText,
354
+ remainingValueLocals
355
+ });
356
+ continue;
357
+ }
358
+ if (!isForbiddenModuleSource(source)) continue;
359
+ getImportValueLocals(statement).forEach((local) => forbiddenIdentifiers.add(local));
360
+ importActions.set(statement, {
361
+ type: "remove"
362
+ });
363
+ }
364
+ let changed = true;
365
+ const statementsToRemove = /* @__PURE__ */ new Set();
366
+ while (changed) {
367
+ changed = false;
368
+ for (const statement of sourceFile.statements) {
369
+ if (ts.isImportDeclaration(statement)) continue;
370
+ if (statementsToRemove.has(statement)) continue;
371
+ if (!referencesForbiddenRuntime(statement, forbiddenIdentifiers)) continue;
372
+ getTopLevelBindings(statement).forEach((name) => forbiddenIdentifiers.add(name));
373
+ statementsToRemove.add(statement);
374
+ changed = true;
375
+ }
376
+ }
377
+ const usedRuntimeIdentifiers = /* @__PURE__ */ new Set();
378
+ for (const statement of sourceFile.statements) {
379
+ if (ts.isImportDeclaration(statement)) continue;
380
+ if (statementsToRemove.has(statement)) continue;
381
+ collectRuntimeIdentifierReferences(statement, usedRuntimeIdentifiers);
382
+ }
383
+ for (const statement of sourceFile.statements) {
384
+ if (!ts.isImportDeclaration(statement)) continue;
385
+ const currentAction = importActions.get(statement);
386
+ if (currentAction?.type === "remove") continue;
387
+ const remainingValueLocals = currentAction?.type === "overwrite" ? currentAction.remainingValueLocals : getImportValueLocals(statement);
388
+ if (remainingValueLocals.length === 0) continue;
389
+ if (remainingValueLocals.some((local) => usedRuntimeIdentifiers.has(local))) continue;
390
+ importActions.set(statement, {
391
+ type: "remove"
392
+ });
393
+ }
394
+ const s = new MagicString(code);
395
+ for (const [importDeclaration, action] of importActions) {
396
+ if (action.type === "remove") {
397
+ s.remove(importDeclaration.pos, importDeclaration.end);
398
+ continue;
399
+ }
400
+ const start = importDeclaration.getStart(sourceFile);
401
+ s.overwrite(start, importDeclaration.end, action.text);
402
+ }
403
+ for (const statement of statementsToRemove) {
404
+ s.remove(statement.pos, statement.end);
405
+ }
406
+ if (!s.hasChanged()) return null;
407
+ const map = JSON.parse(s.generateMap({
408
+ hires: true,
409
+ includeContent: true,
410
+ source: filePath,
411
+ file: filePath
412
+ }).toString());
413
+ map.file = filePath;
414
+ map.sources = [filePath];
415
+ return {
416
+ code: s.toString(),
417
+ map: JSON.stringify(map)
418
+ };
419
+ };
403
420
  }
404
- //#endregion
405
- //#region src/plugins/prune-models-for-client/index.ts
406
421
  function inferIsSsrTransform(transformOptions) {
407
- if (typeof transformOptions === "boolean") return transformOptions;
408
- if (!transformOptions || typeof transformOptions !== "object") return false;
409
- return transformOptions.ssr === true;
422
+ if (typeof transformOptions === "boolean") return transformOptions;
423
+ if (!transformOptions || typeof transformOptions !== "object") return false;
424
+ return transformOptions.ssr === true;
410
425
  }
411
426
  function isPrunableModelsFilePath(filePath) {
412
- const normalized = filePath.replaceAll("\\", "/");
413
- const parts = normalized.split("/");
414
- if (parts.includes("node_modules")) return false;
415
- if (parts.length < 2) return false;
416
- if (!parts.some((part, index) => part === "models" && index < parts.length - 1)) return false;
417
- if (normalized.endsWith(".d.ts")) return false;
418
- const ext = path$1.posix.extname(normalized);
419
- return ext === ".ts" || ext === ".tsx";
427
+ const normalized = filePath.replaceAll("\\", "/");
428
+ const parts = normalized.split("/");
429
+ if (parts.includes("node_modules")) return false;
430
+ if (parts.length < 2) return false;
431
+ if (!parts.some((part, index) => part === "models" && index < parts.length - 1)) return false;
432
+ if (normalized.endsWith(".d.ts")) return false;
433
+ const ext = path$1.posix.extname(normalized);
434
+ return ext === ".ts" || ext === ".tsx";
420
435
  }
421
436
  function pruneModelsForClientPlugin() {
422
- const prune = createTransformSource();
423
- return {
424
- name: "lz-models-prune-for-browser",
425
- enforce: "pre",
426
- transform(code, id, transformOptions) {
427
- if (inferIsSsrTransform(transformOptions)) return;
428
- const filePath = id.split("?", 1)[0] ?? id;
429
- if (!isPrunableModelsFilePath(filePath)) return;
430
- const result = prune({
431
- code,
432
- filePath
433
- });
434
- if (!result) return;
435
- return result;
436
- }
437
- };
437
+ const prune = createTransformSource();
438
+ return {
439
+ name: "lz-models-prune-for-browser",
440
+ enforce: "pre",
441
+ transform(code, id, transformOptions) {
442
+ if (inferIsSsrTransform(transformOptions)) return;
443
+ const filePath = id.split("?", 1)[0] ?? id;
444
+ if (!isPrunableModelsFilePath(filePath)) return;
445
+ const result = prune({
446
+ code,
447
+ filePath
448
+ });
449
+ if (!result) return;
450
+ return result;
451
+ }
452
+ };
438
453
  }
439
- //#endregion
440
- //#region src/plugins/spec-inputs/index.ts
441
- var toPosixPath = (p) => p.split(path$1.sep).join("/");
442
- var computeInputs = (args) => {
443
- const { root, pattern, specDir } = args;
444
- const specDirAbs = path$1.resolve(root, specDir);
445
- const filesAbs = globSync(pattern, {
446
- cwd: root,
447
- absolute: true,
448
- nodir: true
449
- });
450
- const inputs = {};
451
- for (const fileAbs of filesAbs) {
452
- const outputName = toPosixPath(path$1.relative(specDirAbs, fileAbs)).replace(/\.ts$/, "");
453
- inputs[outputName] = fileAbs;
454
- }
455
- return inputs;
454
+ const toPosixPath = (p) => p.split(path$1.sep).join("/");
455
+ const computeInputs = (args) => {
456
+ const {
457
+ root,
458
+ pattern,
459
+ specDir
460
+ } = args;
461
+ const specDirAbs = path$1.resolve(root, specDir);
462
+ const filesAbs = globSync(pattern, {
463
+ cwd: root,
464
+ absolute: true,
465
+ nodir: true
466
+ });
467
+ const inputs = {};
468
+ for (const fileAbs of filesAbs) {
469
+ const relFromSpec = path$1.relative(specDirAbs, fileAbs);
470
+ const outputName = toPosixPath(relFromSpec).replace(/\.ts$/, "");
471
+ inputs[outputName] = fileAbs;
472
+ }
473
+ return inputs;
456
474
  };
457
- var inputsKey = (inputs) => Object.keys(inputs).sort().join("\n");
458
- var hasRollupInput = (input) => {
459
- if (!input) return false;
460
- if (typeof input === "string") return true;
461
- if (Array.isArray(input)) return input.length > 0;
462
- if (typeof input === "object") return Object.keys(input).length > 0;
463
- return false;
475
+ const inputsKey = (inputs) => Object.keys(inputs).sort().join("\n");
476
+ const hasRollupInput = (input) => {
477
+ if (!input) return false;
478
+ if (typeof input === "string") return true;
479
+ if (Array.isArray(input)) return input.length > 0;
480
+ if (typeof input === "object") return Object.keys(input).length > 0;
481
+ return false;
464
482
  };
465
483
  function specInputsPlugin(opts = {}) {
466
- const { pattern = "spec/**/*.spec{,.desktop,.mobile}.ts", specDir = "spec" } = opts;
467
- let rootAbs;
468
- let specDirAbs;
469
- let outDirAbs;
470
- let active = false;
471
- let inputsDirty = true;
472
- let currentInputs;
473
- let lastInputsKey;
474
- return {
475
- name: "rb-spec-inputs",
476
- apply: "build",
477
- configResolved(config) {
478
- const root = config.root;
479
- rootAbs = root;
480
- specDirAbs = path$1.resolve(root, specDir);
481
- outDirAbs = path$1.resolve(root, config.build.outDir);
482
- },
483
- options(inputOptions) {
484
- if (!rootAbs) return;
485
- active = !hasRollupInput(inputOptions.input);
486
- if (!active) return;
487
- if (!currentInputs || inputsDirty) {
488
- currentInputs = computeInputs({
489
- root: rootAbs,
490
- pattern,
491
- specDir
492
- });
493
- inputsDirty = false;
494
- }
495
- inputOptions.input = currentInputs;
496
- return inputOptions;
497
- },
498
- watchChange(id, change) {
499
- if (!active) return;
500
- if (!rootAbs || !specDirAbs) return;
501
- const absId = path$1.isAbsolute(id) ? id : path$1.resolve(rootAbs, id);
502
- if (absId === specDirAbs) {
503
- inputsDirty = true;
504
- return;
505
- }
506
- if (!absId.startsWith(specDirAbs + path$1.sep)) return;
507
- if (!/\.spec(?:\.(?:desktop|mobile))?\.ts$/.test(absId)) return;
508
- if (change.event === "create" || change.event === "delete") inputsDirty = true;
509
- if (change.event === "update") {
510
- const outputName = toPosixPath(path$1.relative(specDirAbs, absId)).replace(/\.ts$/, "");
511
- if (!currentInputs || currentInputs[outputName] !== absId) inputsDirty = true;
512
- }
513
- },
514
- buildStart() {
515
- if (!active) return;
516
- if (!specDirAbs) return;
517
- this.addWatchFile(specDirAbs);
518
- if (!outDirAbs || !currentInputs) return;
519
- const key = inputsKey(currentInputs);
520
- if (lastInputsKey && lastInputsKey !== key) fs.rmSync(outDirAbs, {
521
- recursive: true,
522
- force: true
523
- });
524
- lastInputsKey = key;
525
- }
526
- };
484
+ const {
485
+ pattern = "spec/**/*.spec{,.desktop,.mobile}.ts",
486
+ specDir = "spec"
487
+ } = opts;
488
+ let rootAbs;
489
+ let specDirAbs;
490
+ let outDirAbs;
491
+ let active = false;
492
+ let inputsDirty = true;
493
+ let currentInputs;
494
+ let lastInputsKey;
495
+ return {
496
+ name: "rb-spec-inputs",
497
+ apply: "build",
498
+ configResolved(config) {
499
+ rootAbs = config.root;
500
+ specDirAbs = path$1.resolve(rootAbs, specDir);
501
+ outDirAbs = path$1.resolve(rootAbs, config.build.outDir);
502
+ },
503
+ options(inputOptions) {
504
+ if (!rootAbs) return;
505
+ active = !hasRollupInput(inputOptions.input);
506
+ if (!active) return;
507
+ if (!currentInputs || inputsDirty) {
508
+ currentInputs = computeInputs({
509
+ root: rootAbs,
510
+ pattern,
511
+ specDir
512
+ });
513
+ inputsDirty = false;
514
+ }
515
+ inputOptions.input = currentInputs;
516
+ return inputOptions;
517
+ },
518
+ watchChange(id, change) {
519
+ if (!active) return;
520
+ if (!rootAbs || !specDirAbs) return;
521
+ const absId = path$1.isAbsolute(id) ? id : path$1.resolve(rootAbs, id);
522
+ if (absId === specDirAbs) {
523
+ inputsDirty = true;
524
+ return;
525
+ }
526
+ if (!absId.startsWith(specDirAbs + path$1.sep)) return;
527
+ if (!/\.spec(?:\.(?:desktop|mobile))?\.ts$/.test(absId)) return;
528
+ if (change.event === "create" || change.event === "delete") {
529
+ inputsDirty = true;
530
+ }
531
+ if (change.event === "update") {
532
+ const relFromSpec = path$1.relative(specDirAbs, absId);
533
+ const outputName = toPosixPath(relFromSpec).replace(/\.ts$/, "");
534
+ if (!currentInputs || currentInputs[outputName] !== absId) {
535
+ inputsDirty = true;
536
+ }
537
+ }
538
+ },
539
+ buildStart() {
540
+ if (!active) return;
541
+ if (!specDirAbs) return;
542
+ this.addWatchFile(specDirAbs);
543
+ if (!outDirAbs || !currentInputs) return;
544
+ const key = inputsKey(currentInputs);
545
+ if (lastInputsKey && lastInputsKey !== key) {
546
+ fs.rmSync(outDirAbs, {
547
+ recursive: true,
548
+ force: true
549
+ });
550
+ }
551
+ lastInputsKey = key;
552
+ }
553
+ };
527
554
  }
528
- //#endregion
529
- //#region src/index.ts
530
- var shouldAnalyze = process.env.ANALYZE === "1";
531
- var isCI = [
532
- "true",
533
- "yes",
534
- "1"
535
- ].includes(process.env.CI?.trim());
536
- var isProduction = process.env.NODE_ENV === "production";
537
- var ALLOWED_ENV_PREFIXES = ["RB_PUBLIC_", ...isProduction ? [] : ["NODE_ENV", "APP_NAME"]];
538
- var resolveAliases = {
539
- "@/api": path.resolve(process.cwd(), "./src/api/"),
540
- "@/models": path.resolve(process.cwd(), "./src/models/"),
541
- "@/shared": path.resolve(process.cwd(), "./src/shared/"),
542
- "@/types": path.resolve(process.cwd(), "./src/types/"),
543
- "@": path.resolve(process.cwd(), "./src/client/")
555
+ const shouldAnalyze = process.env.ANALYZE === "1";
556
+ const ensureEnvPolyfillInjectPath = () => {
557
+ const injectDir = path.resolve(process.cwd(), "node_modules/.rpcbase");
558
+ const injectPath = path.join(injectDir, "rb-env-polyfill-inject.js");
559
+ const injectContents = 'import "@rpcbase/env/polyfill"\n';
560
+ fs.mkdirSync(injectDir, {
561
+ recursive: true
562
+ });
563
+ try {
564
+ const existing = fs.readFileSync(injectPath, "utf8");
565
+ if (existing === injectContents) {
566
+ return injectPath;
567
+ }
568
+ } catch {
569
+ }
570
+ fs.writeFileSync(injectPath, injectContents, "utf8");
571
+ return injectPath;
572
+ };
573
+ const esbuildInjectPath = ensureEnvPolyfillInjectPath();
574
+ const esbuildInject = [esbuildInjectPath];
575
+ const esbuildInjectPlugins = [{
576
+ name: "rb-env-polyfill-inject",
577
+ setup(build) {
578
+ build.onResolve({
579
+ filter: /.*/
580
+ }, (args) => {
581
+ if (args.path === esbuildInjectPath) {
582
+ return {
583
+ path: esbuildInjectPath,
584
+ namespace: "file"
585
+ };
586
+ }
587
+ return void 0;
588
+ });
589
+ }
590
+ }];
591
+ const isCI = ["true", "yes", "1"].includes(process.env.CI?.trim());
592
+ const isProduction = process.env.NODE_ENV === "production";
593
+ const ALLOWED_DEV_ENV = ["NODE_ENV", "APP_NAME"];
594
+ const ALLOWED_ENV_PREFIXES = ["RB_PUBLIC_", ...isProduction ? [] : ALLOWED_DEV_ENV];
595
+ const htmlMinifyOptions = {
596
+ collapseWhitespace: true,
597
+ keepClosingSlash: true,
598
+ removeComments: false,
599
+ removeRedundantAttributes: true,
600
+ removeScriptTypeAttributes: true,
601
+ removeStyleLinkTypeAttributes: true,
602
+ useShortDoctype: true,
603
+ minifyCSS: true
604
+ };
605
+ const resolveAliases = {
606
+ "@/api": path.resolve(process.cwd(), "./src/api/"),
607
+ "@/models": path.resolve(process.cwd(), "./src/models/"),
608
+ "@/shared": path.resolve(process.cwd(), "./src/shared/"),
609
+ "@/types": path.resolve(process.cwd(), "./src/types/"),
610
+ "@": path.resolve(process.cwd(), "./src/client/")
544
611
  };
545
- [
546
- "@hookform/resolvers",
547
- "axios",
548
- "events",
549
- "libphonenumber-js",
550
- "posthog-js",
551
- "posthog-js/react",
552
- "posthog-node",
553
- "react-router",
554
- "react-hook-form"
555
- ].forEach((pkg) => {
556
- resolveAliases[pkg] = resolveIntegratedPackagePath(pkg);
612
+ const integratedPackages = ["@hookform/resolvers", "axios", "events", "libphonenumber-js", "posthog-js", "posthog-js/react", "posthog-node", "react-router", "react-hook-form"];
613
+ integratedPackages.forEach((pkg) => {
614
+ const resolved = resolveIntegratedPackagePath(pkg);
615
+ resolveAliases[pkg] = resolved;
557
616
  });
558
617
  resolveAliases["node:events"] = resolveIntegratedPackagePath("events");
559
- var posthogReactEsm = resolveIntegratedPackagePath("posthog-js/react/dist/esm/index.js");
618
+ const posthogReactEsm = resolveIntegratedPackagePath("posthog-js/react/dist/esm/index.js");
560
619
  resolveAliases["posthog-js/react"] = posthogReactEsm;
561
620
  resolveAliases["posthog-js/react/dist/esm/index.js"] = posthogReactEsm;
562
- var rbPackagesNeedingEnvPolyfill = [
563
- "@rpcbase/auth",
564
- "@rpcbase/env",
565
- "@rpcbase/client",
566
- "@rpcbase/form",
567
- "@rpcbase/router"
621
+ const rbPackagesNeedingEnvPolyfill = [
622
+ "@rpcbase/auth",
623
+ "@rpcbase/env",
624
+ // "@rpcbase/env/polyfill",
625
+ "@rpcbase/client",
626
+ "@rpcbase/form",
627
+ "@rpcbase/router"
568
628
  ];
569
- var rbSsrNoExternalPackages = [...rbPackagesNeedingEnvPolyfill, "@rpcbase/server"];
570
- var normalizePath = (id) => id.replaceAll("\\", "/");
571
- var reactCompilerBase = reactCompilerPreset();
572
- var reactCompiler = defineRolldownBabelPreset({
573
- ...reactCompilerBase,
574
- rolldown: {
575
- ...reactCompilerBase.rolldown,
576
- filter: {
577
- ...reactCompilerBase.rolldown.filter,
578
- id: {
579
- include: [/\.[cm]?[jt]sx?$/],
580
- exclude: [/\/node_modules\//]
581
- }
582
- }
583
- }
584
- });
585
- var isRbPackageNeedingEnvPolyfillPath = (id) => {
586
- const normalizedId = normalizePath(id);
587
- return rbPackagesNeedingEnvPolyfill.some((pkg) => {
588
- const packageName = pkg.slice(9);
589
- return normalizedId.includes(`/node_modules/${pkg}/`) || normalizedId.includes(`/pkg/${packageName}/`);
590
- });
591
- };
592
- var isRbEnvPolyfillPath = (id) => {
593
- const normalizedId = normalizePath(id);
594
- return normalizedId.includes("/@rpcbase/env/polyfill") || normalizedId.includes("/pkg/env/") && /\/polyfill(?:\.node)?\.[cm]?[jt]s$/.test(normalizedId);
629
+ const rbSsrNoExternalPackages = [...rbPackagesNeedingEnvPolyfill, "@rpcbase/server"];
630
+ const rpcbaseDedupePackages = ["@rpcbase/api", "@rpcbase/auth", "@rpcbase/client", "@rpcbase/db", "@rpcbase/debug", "@rpcbase/env", "@rpcbase/form", "@rpcbase/router", "@rpcbase/server", "@rpcbase/ui", "@rpcbase/worker"];
631
+ const createRuntimeEnv = (args) => {
632
+ const {
633
+ env,
634
+ configEnv
635
+ } = args;
636
+ const {
637
+ command,
638
+ mode,
639
+ isSsrBuild
640
+ } = configEnv;
641
+ const isDevCommand = command === "serve";
642
+ const mergedEnv = {
643
+ ...env
644
+ };
645
+ return {
646
+ ...mergedEnv,
647
+ BASE_URL: mergedEnv.BASE_URL ?? "/",
648
+ MODE: mode,
649
+ DEV: isDevCommand,
650
+ PROD: !isDevCommand,
651
+ SSR: Boolean(isSsrBuild)
652
+ };
595
653
  };
596
- var rbEnvPolyfillOptimizeDepsPlugin = () => ({
597
- name: "rb-env-polyfill-optimize-deps",
598
- transform(code, id) {
599
- if (!isRbPackageNeedingEnvPolyfillPath(id)) return null;
600
- if (isRbEnvPolyfillPath(id)) return null;
601
- if (!code.includes("__rb_env__") && !code.includes("globalThis.__rb_env__")) return null;
602
- if (code.includes("\"@rpcbase/env/polyfill\"")) return null;
603
- return {
604
- code: `import "@rpcbase/env/polyfill"\n${code}`,
605
- map: null
606
- };
607
- }
608
- });
609
- var rpcbaseDedupePackages = [
610
- "@rpcbase/api",
611
- "@rpcbase/auth",
612
- "@rpcbase/client",
613
- "@rpcbase/db",
614
- "@rpcbase/debug",
615
- "@rpcbase/env",
616
- "@rpcbase/form",
617
- "@rpcbase/router",
618
- "@rpcbase/server",
619
- "@rpcbase/ui",
620
- "@rpcbase/worker"
621
- ];
622
- var createRuntimeEnv = (args) => {
623
- const { env, configEnv } = args;
624
- const { command, mode, isSsrBuild } = configEnv;
625
- const isDevCommand = command === "serve";
626
- const mergedEnv = { ...env };
627
- return {
628
- ...mergedEnv,
629
- BASE_URL: mergedEnv.BASE_URL ?? "/",
630
- MODE: mode,
631
- DEV: isDevCommand,
632
- PROD: !isDevCommand,
633
- SSR: Boolean(isSsrBuild)
634
- };
654
+ const getBaseConfig = (configEnv) => {
655
+ const {
656
+ mode
657
+ } = configEnv;
658
+ const env = loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES);
659
+ const runtimeEnv = createRuntimeEnv({
660
+ env,
661
+ configEnv
662
+ });
663
+ return {
664
+ clearScreen: false,
665
+ plugins: [pruneModelsForClientPlugin(), react({
666
+ babel: {
667
+ plugins: [["babel-plugin-react-compiler", {
668
+ target: "19"
669
+ }]]
670
+ }
671
+ }), createHtmlPlugin({
672
+ // IMPORTANT: minify removes comments by default, which are used by the app ssr
673
+ minify: htmlMinifyOptions
674
+ }), viteSingleFile({
675
+ useRecommendedBuildConfig: false,
676
+ deleteInlinedFiles: true,
677
+ inlinePattern: ["**/*.css"],
678
+ removeViteModuleLoader: false
679
+ }), isProduction && isCI && posthogSourcemapsPlugin({}), shouldAnalyze && analyzer()].filter(Boolean),
680
+ define: {
681
+ __vite_env__: runtimeEnv
682
+ },
683
+ envPrefix: ALLOWED_ENV_PREFIXES,
684
+ publicDir: path.join(process.cwd(), "./src/client/public"),
685
+ build: {
686
+ sourcemap: isProduction ? "hidden" : false,
687
+ cssCodeSplit: false,
688
+ outDir: "./build/dist/",
689
+ rollupOptions: {
690
+ input: {
691
+ app: "./src/client/index.html"
692
+ }
693
+ },
694
+ commonjsOptions: {
695
+ transformMixedEsModules: true
696
+ }
697
+ },
698
+ server: {
699
+ allowedHosts: true,
700
+ headers: {
701
+ // "X-Custom-Header": "test-custom",
702
+ },
703
+ watch: {
704
+ ignored: ["**/build/playwright/**"]
705
+ }
706
+ },
707
+ resolve: {
708
+ alias: {
709
+ ...resolveAliases
710
+ },
711
+ dedupe: ["react", "react-dom", "react-router", "react-hook-form", ...rpcbaseDedupePackages],
712
+ preserveSymlinks: true
713
+ },
714
+ ssr: {
715
+ external: [
716
+ // "react", "react-dom",
717
+ "cookie",
718
+ "mongoose",
719
+ "mongodb"
720
+ ],
721
+ noExternal: [
722
+ ...rbSsrNoExternalPackages
723
+ // "react-use",
724
+ ]
725
+ },
726
+ optimizeDeps: {
727
+ include: [
728
+ // Force RPC Base packages through esbuild so rb-env-polyfill injects before their dist code touches globalThis.__rb_env__
729
+ ...rbPackagesNeedingEnvPolyfill,
730
+ "hoist-non-react-statics"
731
+ // "react", "react-dom", "react-dom/server"
732
+ // "cookie"
733
+ ],
734
+ exclude: [
735
+ "@radix-ui/*",
736
+ "@rpcbase/ui"
737
+ // TMP only in sample app?
738
+ // "react", "react-dom/server",
739
+ // "react-hook-form",
740
+ // "react-dom"
741
+ ],
742
+ esbuildOptions: {
743
+ inject: esbuildInject,
744
+ plugins: esbuildInjectPlugins
745
+ }
746
+ }
747
+ // future: {
748
+ // removeSsrLoadModule: true
749
+ // },
750
+ };
635
751
  };
636
- var getBaseConfig = (configEnv) => {
637
- const { mode } = configEnv;
638
- const runtimeEnv = createRuntimeEnv({
639
- env: loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES),
640
- configEnv
641
- });
642
- return {
643
- clearScreen: false,
644
- plugins: [
645
- pruneModelsForClientPlugin(),
646
- react(),
647
- babel({ presets: [reactCompiler] }),
648
- htmlTemplatePlugin(runtimeEnv),
649
- viteSingleFile({
650
- useRecommendedBuildConfig: false,
651
- deleteInlinedFiles: true,
652
- inlinePattern: ["**/*.css"],
653
- removeViteModuleLoader: false
654
- }),
655
- isProduction && isCI && posthogSourcemapsPlugin({}),
656
- shouldAnalyze && analyzer()
657
- ].filter(Boolean),
658
- define: { __vite_env__: runtimeEnv },
659
- envPrefix: ALLOWED_ENV_PREFIXES,
660
- publicDir: path.join(process.cwd(), "./src/client/public"),
661
- build: {
662
- sourcemap: isProduction ? "hidden" : false,
663
- cssCodeSplit: false,
664
- outDir: "./build/dist/",
665
- rollupOptions: { input: { app: "./src/client/index.html" } },
666
- commonjsOptions: { transformMixedEsModules: true }
667
- },
668
- server: {
669
- allowedHosts: true,
670
- headers: {},
671
- watch: { ignored: ["**/build/playwright/**"] }
672
- },
673
- resolve: {
674
- alias: { ...resolveAliases },
675
- dedupe: [
676
- "react",
677
- "react-dom",
678
- "react-router",
679
- "react-hook-form",
680
- ...rpcbaseDedupePackages
681
- ],
682
- preserveSymlinks: true
683
- },
684
- ssr: {
685
- external: [
686
- "cookie",
687
- "mongoose",
688
- "mongodb"
689
- ],
690
- noExternal: [...rbSsrNoExternalPackages]
691
- },
692
- optimizeDeps: {
693
- include: [
694
- ...rbPackagesNeedingEnvPolyfill,
695
- "hoist-non-react-statics",
696
- "react/compiler-runtime"
697
- ],
698
- exclude: ["@radix-ui/*", "@rpcbase/ui"],
699
- rolldownOptions: { plugins: [rbEnvPolyfillOptimizeDepsPlugin()] }
700
- }
701
- };
752
+ const extendConfig = (userConfig) => {
753
+ return async (configEnv) => {
754
+ const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
755
+ const baseConfig = getBaseConfig(configEnv);
756
+ return mergeConfig(baseConfig, config);
757
+ };
702
758
  };
703
- var extendConfig = (userConfig) => {
704
- return async (configEnv) => {
705
- const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
706
- return mergeConfig(getBaseConfig(configEnv), config);
707
- };
759
+ const getSpecBaseConfig = (configEnv) => {
760
+ const {
761
+ mode
762
+ } = configEnv;
763
+ const env = loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES);
764
+ const runtimeEnv = createRuntimeEnv({
765
+ env,
766
+ configEnv
767
+ });
768
+ return {
769
+ clearScreen: false,
770
+ define: {
771
+ __vite_env__: runtimeEnv
772
+ },
773
+ envPrefix: ALLOWED_ENV_PREFIXES,
774
+ plugins: [specInputsPlugin()],
775
+ build: {
776
+ outDir: "./build/spec/",
777
+ ssr: true,
778
+ rollupOptions: {
779
+ input: {}
780
+ },
781
+ commonjsOptions: {
782
+ transformMixedEsModules: true
783
+ }
784
+ },
785
+ resolve: {
786
+ alias: {
787
+ ...resolveAliases
788
+ },
789
+ dedupe: ["react", "react-dom", "react-router", "react-hook-form", ...rpcbaseDedupePackages],
790
+ preserveSymlinks: true
791
+ },
792
+ ssr: {
793
+ external: ["mongoose"],
794
+ noExternal: ["@rpcbase/*"]
795
+ }
796
+ };
708
797
  };
709
- var getSpecBaseConfig = (configEnv) => {
710
- const { mode } = configEnv;
711
- return {
712
- clearScreen: false,
713
- define: { __vite_env__: createRuntimeEnv({
714
- env: loadEnv(mode, process.cwd(), ALLOWED_ENV_PREFIXES),
715
- configEnv
716
- }) },
717
- envPrefix: ALLOWED_ENV_PREFIXES,
718
- plugins: [specInputsPlugin()],
719
- build: {
720
- outDir: "./build/spec/",
721
- ssr: true,
722
- rollupOptions: { input: {} },
723
- commonjsOptions: { transformMixedEsModules: true }
724
- },
725
- resolve: {
726
- alias: { ...resolveAliases },
727
- dedupe: [
728
- "react",
729
- "react-dom",
730
- "react-router",
731
- "react-hook-form",
732
- ...rpcbaseDedupePackages
733
- ],
734
- preserveSymlinks: true
735
- },
736
- ssr: {
737
- external: ["mongoose"],
738
- noExternal: ["@rpcbase/*"]
739
- }
740
- };
798
+ const extendSpecConfig = (userConfig) => {
799
+ return async (configEnv) => {
800
+ const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
801
+ const baseConfig = getSpecBaseConfig(configEnv);
802
+ return mergeConfig(baseConfig, config);
803
+ };
741
804
  };
742
- var extendSpecConfig = (userConfig) => {
743
- return async (configEnv) => {
744
- const config = typeof userConfig === "function" ? await userConfig(configEnv) : userConfig;
745
- return mergeConfig(getSpecBaseConfig(configEnv), config);
746
- };
805
+ const createServer = createServer$1;
806
+ export {
807
+ createServer,
808
+ extendConfig,
809
+ extendSpecConfig,
810
+ pruneModelsForClientPlugin,
811
+ resolveAliases
747
812
  };
748
- var createServer = createServer$1;
749
- //#endregion
750
- export { createServer, extendConfig, extendSpecConfig, pruneModelsForClientPlugin, resolveAliases };
751
-
752
- //# sourceMappingURL=index.js.map
813
+ //# sourceMappingURL=index.js.map