dinou 9.0.3 → 9.2.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.
@@ -1,253 +1,253 @@
1
- import path from "path";
2
- import fs from "node:fs/promises";
3
- import parseExports from "../../core/parse-exports.js";
4
- import { useServerRegex } from "../../constants.js";
5
- import { extractServerFunctions, hasServerFunctions } from "../../core/transform-server-functions.js";
6
-
7
- export default function serverFunctionsPlugin({
8
- manifestData = {},
9
- serverFiles = null,
10
- } = {}) {
11
- const normalizeNormPath = (p) => {
12
- let s = path.resolve(p).replace(/\\/g, "/");
13
- if (process.platform === "win32") {
14
- s = s.replace(/^([a-zA-Z]):/, (_, d) => d.toLowerCase() + ":");
15
- }
16
- return s;
17
- };
18
- const serverFilesSet = serverFiles
19
- ? new Set(Array.from(serverFiles).map((f) => normalizeNormPath(f)))
20
- : null;
21
-
22
- return {
23
- name: "server-functions-proxy",
24
- setup(build) {
25
- if (serverFilesSet && serverFilesSet.size === 0) {
26
- return;
27
- }
28
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
- const sfFilter = serverFilesSet && serverFilesSet.size > 0
30
- ? new RegExp(Array.from(serverFilesSet).map((f) => escapeRegExp(path.basename(f))).join("|"))
31
- : /\.[jt]sx?$/;
32
- const root = process.cwd();
33
- const serverFunctions = new Map(); // Collect server functions here: Map<relativePath, Set<exports>>
34
- const sfCache = new Map(); // Cache by path: { mtimeMs, isServer, relativePath, exportsSet, proxyCode }
35
- let sfTime = 0;
36
- let sfCount = 0;
37
-
38
- build.onStart(() => {
39
- sfTime = 0;
40
- sfCount = 0;
41
- });
42
-
43
- // 1. TRANSFORM FILES DURING BUILD
44
- build.onLoad({ filter: sfFilter }, async (args) => {
45
- const normPath = args.path.replace(/\\/g, "/");
46
- if (normPath.includes("/node_modules/") || normPath.includes("/.dinou/")) return null;
47
-
48
- if (serverFilesSet) {
49
- const absNorm = normalizeNormPath(args.path);
50
- if (!serverFilesSet.has(absNorm)) {
51
- return null;
52
- }
53
- }
54
-
55
- const t0 = Date.now();
56
- try {
57
- let stat;
58
- try {
59
- stat = await fs.stat(args.path);
60
- } catch (e) {
61
- return null;
62
- }
63
-
64
- const cached = sfCache.get(args.path);
65
- if (cached && cached.mtimeMs === stat.mtimeMs && (!cached.isServer || cached.proxyCode)) {
66
- if (!cached.isServer) return null;
67
- serverFunctions.set(cached.relativePath, cached.exportsSet);
68
- return { contents: cached.proxyCode, loader: "js", watchFiles: [args.path] };
69
- }
70
-
71
- const code = await fs.readFile(args.path, "utf8");
72
- const isModuleLevel = useServerRegex.test(code.trim());
73
-
74
- if (!isModuleLevel && !hasServerFunctions(code)) {
75
- sfCache.set(args.path, { mtimeMs: stat.mtimeMs, isServer: false });
76
- return null;
77
- }
78
-
79
- const exports = isModuleLevel
80
- ? parseExports(code)
81
- : extractServerFunctions(code, args.path);
82
- if (!exports || exports.length === 0) {
83
- sfCache.set(args.path, { mtimeMs: stat.mtimeMs, isServer: false });
84
- return null;
85
- }
86
-
87
- const relativePath = path.relative(root, args.path).replace(/\\/g, "/");
88
- const exportsSet = new Set(exports);
89
- serverFunctions.set(relativePath, exportsSet); // Save exports as a Set to guarantee uniqueness
90
-
91
- const fileUrl = `file:///${relativePath}`;
92
-
93
- // Generate proxy code that forwards calls to the server instead of executing the actual code
94
- let proxyCode = `
95
- import { createServerFunctionProxy } from "/__SERVER_FUNCTION_PROXY__";
96
- `;
97
-
98
- for (const exp of exports) {
99
- const key =
100
- exp === "default" ? `${fileUrl}#default` : `${fileUrl}#${exp}`;
101
-
102
- if (exp === "default") {
103
- proxyCode += `export default createServerFunctionProxy(${JSON.stringify(
104
- key
105
- )});\n`;
106
- } else {
107
- proxyCode += `export const ${exp} = createServerFunctionProxy(${JSON.stringify(
108
- key
109
- )});\n`;
110
- }
111
- }
112
-
113
- sfCache.set(args.path, {
114
- mtimeMs: stat.mtimeMs,
115
- isServer: true,
116
- relativePath,
117
- exportsSet,
118
- proxyCode,
119
- });
120
-
121
- return {
122
- contents: proxyCode,
123
- loader: "js",
124
- watchFiles: [args.path],
125
- };
126
- } finally {
127
- sfTime += Date.now() - t0;
128
- sfCount++;
129
- globalThis.__DINOU_SF_TIME__ = sfTime;
130
- globalThis.__DINOU_SF_COUNT__ = sfCount;
131
- }
132
- });
133
-
134
- // 2. REPLACE PLACEHOLDER AND GENERATE MANIFEST AFTER BUILD
135
- build.onEnd(async (result) => {
136
- const tEnd0 = Date.now();
137
- try {
138
- if (serverFilesSet && serverFilesSet.size > 0) {
139
- for (const filePath of serverFilesSet) {
140
- const rel = path.relative(root, filePath).replace(/\\/g, "/");
141
- try {
142
- const stat = await fs.stat(filePath);
143
- const cached = sfCache.get(filePath);
144
- if (cached && cached.mtimeMs === stat.mtimeMs) {
145
- if (cached.isServer && cached.exportsSet) {
146
- serverFunctions.set(rel, cached.exportsSet);
147
- } else {
148
- serverFunctions.delete(rel);
149
- }
150
- continue;
151
- }
152
-
153
- const code = await fs.readFile(filePath, "utf8");
154
- let exports = null;
155
- if (useServerRegex.test(code.trim())) {
156
- exports = parseExports(code);
157
- } else if (hasServerFunctions(code)) {
158
- exports = extractServerFunctions(code, filePath);
159
- }
160
-
161
- if (exports && exports.length > 0) {
162
- const exportsSet = new Set(exports);
163
- serverFunctions.set(rel, exportsSet);
164
- sfCache.set(filePath, {
165
- mtimeMs: stat.mtimeMs,
166
- isServer: true,
167
- relativePath: rel,
168
- exportsSet,
169
- proxyCode: cached?.proxyCode || "",
170
- });
171
- } else {
172
- serverFunctions.delete(rel);
173
- sfCache.set(filePath, {
174
- mtimeMs: stat.mtimeMs,
175
- isServer: false,
176
- });
177
- }
178
- } catch (e) {
179
- serverFunctions.delete(rel);
180
- }
181
- }
182
- }
183
-
184
- if (serverFunctions.size === 0) {
185
- if (typeof globalThis !== "undefined") {
186
- globalThis.__DINOU_RAW_SERVER_FUNCTIONS_MANIFEST__ = {};
187
- }
188
- return;
189
- }
190
- const isProd = process.env.NODE_ENV === "production";
191
- const proxyName = manifestData["serverFunctionProxy.js"];
192
- if (isProd && !proxyName) {
193
- throw new Error(
194
- "[Dinou] serverFunctionsPlugin: could not find hashed 'serverFunctionProxy.js' in manifestData during production build."
195
- );
196
- }
197
- const hashedProxy = "/" + (proxyName || "serverFunctionProxy.js");
198
-
199
- const serverFnNormalized = new Set();
200
- for (const relPath of serverFunctions.keys()) {
201
- serverFnNormalized.add(path.resolve(root, relPath).replace(/\\/g, "/").toLowerCase());
202
- }
203
-
204
- let targetOutputFiles = Object.values(result.outputFiles || {});
205
-
206
- for (const outputFile of targetOutputFiles) {
207
- const fileCode = new TextDecoder().decode(outputFile.contents);
208
-
209
- if (!fileCode) continue;
210
- if (fileCode.includes("/__SERVER_FUNCTION_PROXY__") || (proxyName && fileCode.includes("/serverFunctionProxy.js"))) {
211
- let newCode = fileCode.replace(
212
- /\/__SERVER_FUNCTION_PROXY__/g,
213
- hashedProxy
214
- );
215
- if (proxyName && proxyName !== "serverFunctionProxy.js") {
216
- newCode = newCode.replace(
217
- /\/serverFunctionProxy\.js/g,
218
- hashedProxy
219
- );
220
- }
221
- outputFile.contents = new TextEncoder().encode(newCode);
222
- }
223
- }
224
-
225
- // Generate the final manifest by converting the Map to a plain object
226
- const manifestObj = {};
227
- for (const [path, exportsSet] of serverFunctions.entries()) {
228
- manifestObj[path] = Array.from(exportsSet);
229
- }
230
-
231
- if (typeof globalThis !== "undefined") {
232
- globalThis.__DINOU_RAW_SERVER_FUNCTIONS_MANIFEST__ = manifestObj;
233
- }
234
-
235
- const isDev = process.env.DINOU_DEV === "true" || process.env.NODE_ENV === "development";
236
- const shouldWriteToDisk = process.env.DINOU_WRITE_TO_DISK === "false" ? false : (process.env.DINOU_WRITE_TO_DISK === "true" || !isDev);
237
-
238
- if (shouldWriteToDisk) {
239
- // Write the server functions manifest JSON file to the output directory
240
- const manifestPath = path.join(
241
- ".dinou/server_functions_manifest",
242
- "server-functions-manifest.json"
243
- );
244
- await fs.mkdir(path.dirname(manifestPath), { recursive: true });
245
- await fs.writeFile(manifestPath, JSON.stringify(manifestObj, null, 2));
246
- }
247
- } finally {
248
- globalThis.__DINOU_SF_END_TIME__ = Date.now() - tEnd0;
249
- }
250
- });
251
- },
252
- };
253
- }
1
+ import path from "path";
2
+ import fs from "node:fs/promises";
3
+ import parseExports from "../../core/parse-exports.js";
4
+ import { useServerRegex } from "../../constants.js";
5
+ import { extractServerFunctions, hasServerFunctions } from "../../core/transform-server-functions.js";
6
+
7
+ export default function serverFunctionsPlugin({
8
+ manifestData = {},
9
+ serverFiles = null,
10
+ } = {}) {
11
+ const normalizeNormPath = (p) => {
12
+ let s = path.resolve(p).replace(/\\/g, "/");
13
+ if (process.platform === "win32") {
14
+ s = s.replace(/^([a-zA-Z]):/, (_, d) => d.toLowerCase() + ":");
15
+ }
16
+ return s;
17
+ };
18
+ const serverFilesSet = serverFiles
19
+ ? new Set(Array.from(serverFiles).map((f) => normalizeNormPath(f)))
20
+ : null;
21
+
22
+ return {
23
+ name: "server-functions-proxy",
24
+ setup(build) {
25
+ if (serverFilesSet && serverFilesSet.size === 0) {
26
+ return;
27
+ }
28
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29
+ const sfFilter = serverFilesSet && serverFilesSet.size > 0
30
+ ? new RegExp(Array.from(serverFilesSet).map((f) => escapeRegExp(path.basename(f))).join("|"))
31
+ : /\.[jt]sx?$/;
32
+ const root = process.cwd();
33
+ const serverFunctions = new Map(); // Collect server functions here: Map<relativePath, Set<exports>>
34
+ const sfCache = new Map(); // Cache by path: { mtimeMs, isServer, relativePath, exportsSet, proxyCode }
35
+ let sfTime = 0;
36
+ let sfCount = 0;
37
+
38
+ build.onStart(() => {
39
+ sfTime = 0;
40
+ sfCount = 0;
41
+ });
42
+
43
+ // 1. TRANSFORM FILES DURING BUILD
44
+ build.onLoad({ filter: sfFilter }, async (args) => {
45
+ const normPath = args.path.replace(/\\/g, "/");
46
+ if (normPath.includes("/node_modules/") || normPath.includes("/.dinou/")) return null;
47
+
48
+ if (serverFilesSet) {
49
+ const absNorm = normalizeNormPath(args.path);
50
+ if (!serverFilesSet.has(absNorm)) {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ const t0 = Date.now();
56
+ try {
57
+ let stat;
58
+ try {
59
+ stat = await fs.stat(args.path);
60
+ } catch (e) {
61
+ return null;
62
+ }
63
+
64
+ const cached = sfCache.get(args.path);
65
+ if (cached && cached.mtimeMs === stat.mtimeMs && (!cached.isServer || cached.proxyCode)) {
66
+ if (!cached.isServer) return null;
67
+ serverFunctions.set(cached.relativePath, cached.exportsSet);
68
+ return { contents: cached.proxyCode, loader: "js", watchFiles: [args.path] };
69
+ }
70
+
71
+ const code = await fs.readFile(args.path, "utf8");
72
+ const isModuleLevel = useServerRegex.test(code.trim());
73
+
74
+ if (!isModuleLevel && !hasServerFunctions(code)) {
75
+ sfCache.set(args.path, { mtimeMs: stat.mtimeMs, isServer: false });
76
+ return null;
77
+ }
78
+
79
+ const exports = isModuleLevel
80
+ ? parseExports(code)
81
+ : extractServerFunctions(code, args.path);
82
+ if (!exports || exports.length === 0) {
83
+ sfCache.set(args.path, { mtimeMs: stat.mtimeMs, isServer: false });
84
+ return null;
85
+ }
86
+
87
+ const relativePath = path.relative(root, args.path).replace(/\\/g, "/");
88
+ const exportsSet = new Set(exports);
89
+ serverFunctions.set(relativePath, exportsSet); // Save exports as a Set to guarantee uniqueness
90
+
91
+ const fileUrl = `file:///${relativePath}`;
92
+
93
+ // Generate proxy code that forwards calls to the server instead of executing the actual code
94
+ let proxyCode = `
95
+ import { createServerFunctionProxy } from "/__SERVER_FUNCTION_PROXY__";
96
+ `;
97
+
98
+ for (const exp of exports) {
99
+ const key =
100
+ exp === "default" ? `${fileUrl}#default` : `${fileUrl}#${exp}`;
101
+
102
+ if (exp === "default") {
103
+ proxyCode += `export default createServerFunctionProxy(${JSON.stringify(
104
+ key
105
+ )});\n`;
106
+ } else {
107
+ proxyCode += `export const ${exp} = createServerFunctionProxy(${JSON.stringify(
108
+ key
109
+ )});\n`;
110
+ }
111
+ }
112
+
113
+ sfCache.set(args.path, {
114
+ mtimeMs: stat.mtimeMs,
115
+ isServer: true,
116
+ relativePath,
117
+ exportsSet,
118
+ proxyCode,
119
+ });
120
+
121
+ return {
122
+ contents: proxyCode,
123
+ loader: "js",
124
+ watchFiles: [args.path],
125
+ };
126
+ } finally {
127
+ sfTime += Date.now() - t0;
128
+ sfCount++;
129
+ globalThis.__DINOU_SF_TIME__ = sfTime;
130
+ globalThis.__DINOU_SF_COUNT__ = sfCount;
131
+ }
132
+ });
133
+
134
+ // 2. REPLACE PLACEHOLDER AND GENERATE MANIFEST AFTER BUILD
135
+ build.onEnd(async (result) => {
136
+ const tEnd0 = Date.now();
137
+ try {
138
+ if (serverFilesSet && serverFilesSet.size > 0) {
139
+ for (const filePath of serverFilesSet) {
140
+ const rel = path.relative(root, filePath).replace(/\\/g, "/");
141
+ try {
142
+ const stat = await fs.stat(filePath);
143
+ const cached = sfCache.get(filePath);
144
+ if (cached && cached.mtimeMs === stat.mtimeMs) {
145
+ if (cached.isServer && cached.exportsSet) {
146
+ serverFunctions.set(rel, cached.exportsSet);
147
+ } else {
148
+ serverFunctions.delete(rel);
149
+ }
150
+ continue;
151
+ }
152
+
153
+ const code = await fs.readFile(filePath, "utf8");
154
+ let exports = null;
155
+ if (useServerRegex.test(code.trim())) {
156
+ exports = parseExports(code);
157
+ } else if (hasServerFunctions(code)) {
158
+ exports = extractServerFunctions(code, filePath);
159
+ }
160
+
161
+ if (exports && exports.length > 0) {
162
+ const exportsSet = new Set(exports);
163
+ serverFunctions.set(rel, exportsSet);
164
+ sfCache.set(filePath, {
165
+ mtimeMs: stat.mtimeMs,
166
+ isServer: true,
167
+ relativePath: rel,
168
+ exportsSet,
169
+ proxyCode: cached?.proxyCode || "",
170
+ });
171
+ } else {
172
+ serverFunctions.delete(rel);
173
+ sfCache.set(filePath, {
174
+ mtimeMs: stat.mtimeMs,
175
+ isServer: false,
176
+ });
177
+ }
178
+ } catch (e) {
179
+ serverFunctions.delete(rel);
180
+ }
181
+ }
182
+ }
183
+
184
+ if (serverFunctions.size === 0) {
185
+ if (typeof globalThis !== "undefined") {
186
+ globalThis.__DINOU_RAW_SERVER_FUNCTIONS_MANIFEST__ = {};
187
+ }
188
+ return;
189
+ }
190
+ const isProd = process.env.NODE_ENV === "production";
191
+ const proxyName = manifestData["serverFunctionProxy.js"];
192
+ if (isProd && !proxyName) {
193
+ throw new Error(
194
+ "[Dinou] serverFunctionsPlugin: could not find hashed 'serverFunctionProxy.js' in manifestData during production build."
195
+ );
196
+ }
197
+ const hashedProxy = "/" + (proxyName || "serverFunctionProxy.js");
198
+
199
+ const serverFnNormalized = new Set();
200
+ for (const relPath of serverFunctions.keys()) {
201
+ serverFnNormalized.add(path.resolve(root, relPath).replace(/\\/g, "/").toLowerCase());
202
+ }
203
+
204
+ let targetOutputFiles = Object.values(result.outputFiles || {});
205
+
206
+ for (const outputFile of targetOutputFiles) {
207
+ const fileCode = new TextDecoder().decode(outputFile.contents);
208
+
209
+ if (!fileCode) continue;
210
+ if (fileCode.includes("/__SERVER_FUNCTION_PROXY__") || (proxyName && fileCode.includes("/serverFunctionProxy.js"))) {
211
+ let newCode = fileCode.replace(
212
+ /\/__SERVER_FUNCTION_PROXY__/g,
213
+ hashedProxy
214
+ );
215
+ if (proxyName && proxyName !== "serverFunctionProxy.js") {
216
+ newCode = newCode.replace(
217
+ /\/serverFunctionProxy\.js/g,
218
+ hashedProxy
219
+ );
220
+ }
221
+ outputFile.contents = new TextEncoder().encode(newCode);
222
+ }
223
+ }
224
+
225
+ // Generate the final manifest by converting the Map to a plain object
226
+ const manifestObj = {};
227
+ for (const [path, exportsSet] of serverFunctions.entries()) {
228
+ manifestObj[path] = Array.from(exportsSet);
229
+ }
230
+
231
+ if (typeof globalThis !== "undefined") {
232
+ globalThis.__DINOU_RAW_SERVER_FUNCTIONS_MANIFEST__ = manifestObj;
233
+ }
234
+
235
+ const isDev = process.env.DINOU_DEV === "true" || process.env.NODE_ENV === "development";
236
+ const shouldWriteToDisk = process.env.DINOU_WRITE_TO_DISK === "false" ? false : (process.env.DINOU_WRITE_TO_DISK === "true" || !isDev);
237
+
238
+ if (shouldWriteToDisk) {
239
+ // Write the server functions manifest JSON file to the output directory
240
+ const manifestPath = path.join(
241
+ ".dinou/server_functions_manifest",
242
+ "server-functions-manifest.json"
243
+ );
244
+ await fs.mkdir(path.dirname(manifestPath), { recursive: true });
245
+ await fs.writeFile(manifestPath, JSON.stringify(manifestObj, null, 2));
246
+ }
247
+ } finally {
248
+ globalThis.__DINOU_SF_END_TIME__ = Date.now() - tEnd0;
249
+ }
250
+ });
251
+ },
252
+ };
253
+ }