vite-plugin-react-server 1.1.13 → 1.1.14

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.
Files changed (159) hide show
  1. package/dist/package.json +3 -1
  2. package/dist/plugin/config/defaults.d.ts +2 -2
  3. package/dist/plugin/config/defaults.d.ts.map +1 -1
  4. package/dist/plugin/config/defaults.js +2 -2
  5. package/dist/plugin/config/defaults.js.map +1 -1
  6. package/dist/plugin/config/resolveOptions.d.ts.map +1 -1
  7. package/dist/plugin/config/resolveOptions.js +98 -61
  8. package/dist/plugin/config/resolveOptions.js.map +1 -1
  9. package/dist/plugin/error/toError.d.ts.map +1 -1
  10. package/dist/plugin/error/toError.js +0 -1
  11. package/dist/plugin/error/toError.js.map +1 -1
  12. package/dist/plugin/helpers/collectManifestCss.d.ts +1 -2
  13. package/dist/plugin/helpers/collectManifestCss.d.ts.map +1 -1
  14. package/dist/plugin/helpers/collectManifestCss.js +3 -5
  15. package/dist/plugin/helpers/collectManifestCss.js.map +1 -1
  16. package/dist/plugin/helpers/collectViteModuleGraphCss.d.ts +1 -1
  17. package/dist/plugin/helpers/collectViteModuleGraphCss.d.ts.map +1 -1
  18. package/dist/plugin/helpers/collectViteModuleGraphCss.js +6 -2
  19. package/dist/plugin/helpers/collectViteModuleGraphCss.js.map +1 -1
  20. package/dist/plugin/helpers/createCssProps.d.ts +1 -1
  21. package/dist/plugin/helpers/createCssProps.d.ts.map +1 -1
  22. package/dist/plugin/helpers/createCssProps.js +11 -32
  23. package/dist/plugin/helpers/createCssProps.js.map +1 -1
  24. package/dist/plugin/helpers/createRscStream.d.ts.map +1 -1
  25. package/dist/plugin/helpers/createRscStream.js +1 -0
  26. package/dist/plugin/helpers/createRscStream.js.map +1 -1
  27. package/dist/plugin/loader/createDefaultLoader.d.ts.map +1 -1
  28. package/dist/plugin/loader/createDefaultLoader.js +68 -4
  29. package/dist/plugin/loader/css-loader.development.d.ts +2 -15
  30. package/dist/plugin/loader/css-loader.development.d.ts.map +1 -1
  31. package/dist/plugin/loader/css-loader.development.js +16 -15
  32. package/dist/plugin/loader/css-loader.development.js.map +1 -1
  33. package/dist/plugin/loader/css-loader.production.d.ts +1 -1
  34. package/dist/plugin/loader/css-loader.production.d.ts.map +1 -1
  35. package/dist/plugin/loader/css-loader.production.js +1 -1
  36. package/dist/plugin/loader/css-loader.production.js.map +1 -1
  37. package/dist/plugin/loader/env-loader.development.d.ts +1 -0
  38. package/dist/plugin/loader/env-loader.development.d.ts.map +1 -1
  39. package/dist/plugin/loader/env-loader.development.js +17 -9
  40. package/dist/plugin/loader/handleExports.d.ts +1 -0
  41. package/dist/plugin/loader/handleExports.d.ts.map +1 -1
  42. package/dist/plugin/loader/handleExports.js +27 -8
  43. package/dist/plugin/loader/handleExports.js.map +1 -1
  44. package/dist/plugin/loader/react-loader.server.d.ts +2 -2
  45. package/dist/plugin/loader/react-loader.server.d.ts.map +1 -1
  46. package/dist/plugin/loader/react-loader.server.js +88 -26
  47. package/dist/plugin/loader/transformModuleIfNeeded.d.ts.map +1 -1
  48. package/dist/plugin/loader/transformModuleIfNeeded.js +1 -1
  49. package/dist/plugin/loader/transformModuleIfNeeded.js.map +1 -1
  50. package/dist/plugin/loader/transformModuleWithPreservedFunctions.d.ts.map +1 -1
  51. package/dist/plugin/loader/transformModuleWithPreservedFunctions.js +86 -13
  52. package/dist/plugin/loader/transformModuleWithPreservedFunctions.js.map +1 -1
  53. package/dist/plugin/plugin.client.d.ts.map +1 -1
  54. package/dist/plugin/plugin.client.js +0 -1
  55. package/dist/plugin/plugin.client.js.map +1 -1
  56. package/dist/plugin/react-client/configureWorkerRequestHandler.d.ts.map +1 -1
  57. package/dist/plugin/react-client/configureWorkerRequestHandler.js +85 -6
  58. package/dist/plugin/react-client/configureWorkerRequestHandler.js.map +1 -1
  59. package/dist/plugin/react-client/createMessageHandlers.d.ts.map +1 -1
  60. package/dist/plugin/react-client/createMessageHandlers.js +3 -0
  61. package/dist/plugin/react-client/createMessageHandlers.js.map +1 -1
  62. package/dist/plugin/react-client/createWorkerStream.d.ts +2 -2
  63. package/dist/plugin/react-client/createWorkerStream.d.ts.map +1 -1
  64. package/dist/plugin/react-client/createWorkerStream.js +13 -2
  65. package/dist/plugin/react-client/createWorkerStream.js.map +1 -1
  66. package/dist/plugin/react-client/handleWorkerRscStream.d.ts.map +1 -1
  67. package/dist/plugin/react-client/handleWorkerRscStream.js +10 -3
  68. package/dist/plugin/react-client/handleWorkerRscStream.js.map +1 -1
  69. package/dist/plugin/react-client/restartWorker.d.ts.map +1 -1
  70. package/dist/plugin/react-client/restartWorker.js +2 -1
  71. package/dist/plugin/react-client/restartWorker.js.map +1 -1
  72. package/dist/plugin/react-server/configureReactServer.d.ts.map +1 -1
  73. package/dist/plugin/react-server/configureReactServer.js +1 -2
  74. package/dist/plugin/react-server/configureReactServer.js.map +1 -1
  75. package/dist/plugin/react-server/handleServerAction.d.ts.map +1 -1
  76. package/dist/plugin/react-server/handleServerAction.js +0 -16
  77. package/dist/plugin/react-server/handleServerAction.js.map +1 -1
  78. package/dist/plugin/react-static/createBuildLoader.d.ts.map +1 -0
  79. package/dist/plugin/react-static/createBuildLoader.js.map +1 -0
  80. package/dist/plugin/react-static/plugin.d.ts.map +1 -1
  81. package/dist/plugin/react-static/plugin.js +9 -12
  82. package/dist/plugin/react-static/plugin.js.map +1 -1
  83. package/dist/plugin/react-static/temporaryReferences.d.ts.map +1 -0
  84. package/dist/plugin/react-static/temporaryReferences.js.map +1 -0
  85. package/dist/plugin/transformer/plugin.server.js +2 -2
  86. package/dist/plugin/transformer/plugin.server.js.map +1 -1
  87. package/dist/plugin/types.d.ts +14 -3
  88. package/dist/plugin/types.d.ts.map +1 -1
  89. package/dist/plugin/worker/rsc/handleRender.d.ts.map +1 -1
  90. package/dist/plugin/worker/rsc/handleRender.js +1 -0
  91. package/dist/plugin/worker/rsc/handleRender.js.map +1 -1
  92. package/dist/plugin/worker/rsc/handlers.d.ts +3 -0
  93. package/dist/plugin/worker/rsc/handlers.d.ts.map +1 -0
  94. package/dist/plugin/worker/rsc/handlers.js +223 -0
  95. package/dist/plugin/worker/rsc/handlers.js.map +1 -0
  96. package/dist/plugin/worker/rsc/messageHandler.d.ts.map +1 -1
  97. package/dist/plugin/worker/rsc/messageHandler.js +5 -110
  98. package/dist/plugin/worker/rsc/messageHandler.js.map +1 -1
  99. package/dist/plugin/worker/rsc/rsc-worker.development.js +13 -16
  100. package/dist/plugin/worker/rsc/rsc-worker.development.js.map +1 -1
  101. package/dist/plugin/worker/rsc/state.d.ts +1 -2
  102. package/dist/plugin/worker/rsc/state.d.ts.map +1 -1
  103. package/dist/plugin/worker/rsc/state.js +1 -2
  104. package/dist/plugin/worker/rsc/state.js.map +1 -1
  105. package/dist/plugin/worker/rsc/userOptions.d.ts +2 -0
  106. package/dist/plugin/worker/rsc/userOptions.d.ts.map +1 -0
  107. package/dist/plugin/worker/rsc/userOptions.js +17 -0
  108. package/dist/plugin/worker/rsc/userOptions.js.map +1 -0
  109. package/dist/plugin/worker/types.d.ts +2 -1
  110. package/dist/plugin/worker/types.d.ts.map +1 -1
  111. package/dist/tsconfig.tsbuildinfo +1 -1
  112. package/package.json +5 -1
  113. package/plugin/config/defaults.tsx +5 -2
  114. package/plugin/config/resolveOptions.ts +101 -67
  115. package/plugin/error/toError.ts +0 -2
  116. package/plugin/helpers/collectManifestCss.ts +2 -6
  117. package/plugin/helpers/collectViteModuleGraphCss.ts +6 -0
  118. package/plugin/helpers/createCssProps.tsx +17 -46
  119. package/plugin/helpers/createRscStream.tsx +1 -0
  120. package/plugin/loader/createDefaultLoader.ts +80 -4
  121. package/plugin/loader/css-loader.development.ts +17 -34
  122. package/plugin/loader/css-loader.production.ts +2 -4
  123. package/plugin/loader/env-loader.development.ts +38 -15
  124. package/plugin/loader/handleExports.ts +36 -13
  125. package/plugin/loader/react-loader.server.ts +110 -32
  126. package/plugin/loader/transformModuleIfNeeded.ts +2 -2
  127. package/plugin/loader/transformModuleWithPreservedFunctions.ts +128 -21
  128. package/plugin/plugin.client.ts +0 -2
  129. package/plugin/react-client/configureWorkerRequestHandler.ts +107 -4
  130. package/plugin/react-client/createMessageHandlers.ts +3 -0
  131. package/plugin/react-client/createWorkerStream.ts +15 -1
  132. package/plugin/react-client/handleWorkerRscStream.ts +12 -3
  133. package/plugin/react-client/restartWorker.ts +1 -0
  134. package/plugin/react-server/configureReactServer.ts +1 -2
  135. package/plugin/react-server/handleServerAction.ts +1 -19
  136. package/plugin/react-static/plugin.ts +9 -12
  137. package/plugin/transformer/plugin.server.ts +2 -2
  138. package/plugin/types.ts +25 -2
  139. package/plugin/worker/rsc/handleRender.ts +1 -0
  140. package/plugin/worker/rsc/handlers.ts +243 -0
  141. package/plugin/worker/rsc/messageHandler.tsx +4 -118
  142. package/plugin/worker/rsc/rsc-worker.development.ts +17 -20
  143. package/plugin/worker/rsc/state.ts +2 -6
  144. package/plugin/worker/rsc/userOptions.ts +8 -0
  145. package/plugin/worker/types.ts +2 -0
  146. package/dist/plugin/loader/createBuildLoader.d.ts.map +0 -1
  147. package/dist/plugin/loader/createBuildLoader.js.map +0 -1
  148. package/dist/plugin/loader/plugin.d.ts +0 -22
  149. package/dist/plugin/loader/plugin.d.ts.map +0 -1
  150. package/dist/plugin/loader/plugin.js +0 -27
  151. package/dist/plugin/loader/temporaryReferences.d.ts.map +0 -1
  152. package/dist/plugin/loader/temporaryReferences.js.map +0 -1
  153. package/plugin/loader/plugin.ts +0 -33
  154. /package/dist/plugin/{loader → react-static}/createBuildLoader.d.ts +0 -0
  155. /package/dist/plugin/{loader → react-static}/createBuildLoader.js +0 -0
  156. /package/dist/plugin/{loader → react-static}/temporaryReferences.d.ts +0 -0
  157. /package/dist/plugin/{loader → react-static}/temporaryReferences.js +0 -0
  158. /package/plugin/{loader → react-static}/createBuildLoader.ts +0 -0
  159. /package/plugin/{loader → react-static}/temporaryReferences.ts +0 -0
@@ -1,13 +1,14 @@
1
1
  import { type MessagePort } from "node:worker_threads";
2
2
  import type { LoadHookContext } from "node:module";
3
- import type { LoaderContext, SerializedUserConfig } from "../types.js";
3
+ import type { LoaderContext, ResolvedUserOptions, SerializedUserConfig, SerializedUserOptions } from "../types.js";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { preprocessCSS } from "vite";
6
6
  import type { ResolvedConfig } from "vite";
7
7
  import { readFile } from "node:fs/promises";
8
- import { join } from "node:path";
9
8
  import { env } from "../utils/env.js";
10
9
  import type { InitializedCssLoaderMessage } from "../worker/types.js";
10
+ import { resolveOptions } from "../config/resolveOptions.js";
11
+ import { hydrateUserOptions } from "../helpers/index.js";
11
12
 
12
13
  /**
13
14
  * Global port for communication between the main thread and the CSS loader.
@@ -15,15 +16,8 @@ import type { InitializedCssLoaderMessage } from "../worker/types.js";
15
16
  */
16
17
  export let loaderPort: MessagePort | undefined;
17
18
 
18
- /**
19
- * Tracks CSS files used by each page.
20
- * Maps page URLs to sets of CSS file paths that are used by that page.
21
- */
22
- const cssFilesByPage = new Map<string, Set<string>>();
23
-
24
- let currentPage: string | null = null;
25
19
  let resolvedConfig: ResolvedConfig | undefined;
26
-
20
+ let userOptions: ResolvedUserOptions | undefined;
27
21
 
28
22
  /**
29
23
  * Initializes the CSS loader with the necessary communication channels.
@@ -32,31 +26,18 @@ let resolvedConfig: ResolvedConfig | undefined;
32
26
  * @param data - Configuration data for the CSS loader
33
27
  * @param data.port - The message port for communication
34
28
  */
35
- export async function initialize(data: { id: string, port: MessagePort, resolvedConfig: SerializedUserConfig }) {
29
+ export async function initialize(data: { id: string, port: MessagePort, resolvedConfig: SerializedUserConfig, userOptions: SerializedUserOptions }) {
36
30
  loaderPort = data.port;
37
31
  resolvedConfig = data.resolvedConfig;
32
+ const resolvedUserOptions = resolveOptions(hydrateUserOptions(data.userOptions));
33
+ if(resolvedUserOptions.type === "error") {
34
+ throw new Error(resolvedUserOptions.error.message);
35
+ }
36
+ userOptions = resolvedUserOptions.userOptions;
38
37
  data.port.postMessage({ type: "INITIALIZED_CSS_LOADER", id: data.id } satisfies InitializedCssLoaderMessage);
39
38
  }
40
39
 
41
- /**
42
- * Sets the current page being processed.
43
- * Used to track which CSS files are associated with which pages.
44
- *
45
- * @param page - The URL of the current page, or null if no page is active
46
- */
47
- export function setCurrentPage(page: string | null) {
48
- currentPage = page;
49
- }
50
40
 
51
- /**
52
- * Retrieves all CSS files associated with a specific page.
53
- *
54
- * @param page - The URL of the page
55
- * @returns An array of CSS file paths used by the page
56
- */
57
- export function getCssFilesForPage(page: string): string[] {
58
- return Array.from(cssFilesByPage.get(page) || []);
59
- }
60
41
 
61
42
  /**
62
43
  * Processes a CSS file request.
@@ -79,6 +60,11 @@ async function processCssFile(
79
60
 
80
61
  // Process CSS using Vite's preprocessCSS
81
62
  const source = await readFile(path, "utf-8");
63
+ let moduleID = path;
64
+ if(userOptions?.normalizer) {
65
+ let [,value] = userOptions.normalizer(path);
66
+ moduleID = userOptions.moduleID(value || path);
67
+ }
82
68
  const processed = await preprocessCSS(source, path, {
83
69
  ...config,
84
70
  env: env
@@ -88,11 +74,8 @@ async function processCssFile(
88
74
  if (loaderPort) {
89
75
  loaderPort.postMessage({
90
76
  type: "CSS_FILE",
91
- id: currentPage ? join(path, "?page=" + currentPage) : path,
92
- path: path,
93
- content: processed.code,
94
- modules: processed.modules || {},
95
- inline,
77
+ id: moduleID,
78
+ content: processed.code
96
79
  });
97
80
  }
98
81
 
@@ -18,11 +18,10 @@ let stashedCssFiles = new Map();
18
18
  *
19
19
  * @param data - Configuration data for the CSS loader
20
20
  * @param data.port - The message port for communication
21
- * @param data.server - The Vite dev server instance
22
21
  */
23
- export async function initialize(data: { port: MessagePort }) {
22
+ export async function initialize(data: { id: string, port: MessagePort }) {
24
23
  loaderPort = data.port;
25
- data.port.postMessage({ type: "INITIALIZED_CSS_LOADER" });
24
+ data.port.postMessage({ type: "INITIALIZED_CSS_LOADER", id: data.id });
26
25
  }
27
26
 
28
27
  /**
@@ -30,7 +29,6 @@ export async function initialize(data: { port: MessagePort }) {
30
29
  * Sends a request to the main thread and waits for the processed CSS.
31
30
  *
32
31
  * @param filePath - The file system path of the CSS file
33
- * @param config - The Vite config
34
32
  * @returns A promise that resolves to the processed CSS content
35
33
  */
36
34
  async function processCssFile(
@@ -2,15 +2,24 @@ import type { LoadHookContext } from "node:module";
2
2
  import type { LoaderContext } from "../types.js";
3
3
  import type { MessagePort } from "node:worker_threads";
4
4
  import type { ResolvedConfig } from "vite";
5
+ import type { RscWorkerInputMessage } from "../worker/types.js";
5
6
 
6
7
  export let loaderPort: MessagePort | undefined;
7
8
  let resolvedConfig: ResolvedConfig | undefined;
8
9
 
9
10
  // Initialize hook
10
- export async function initialize(data: { port: MessagePort, resolvedConfig: ResolvedConfig }) {
11
+ export async function initialize(data: {
12
+ id: string;
13
+ port: MessagePort;
14
+ resolvedConfig: ResolvedConfig;
15
+ }) {
11
16
  loaderPort = data.port;
12
17
  resolvedConfig = data.resolvedConfig;
13
- data.port.postMessage({ type: "INITIALIZED_ENV_LOADER" });
18
+ data.port.postMessage({
19
+ type: "INITIALIZED_ENV_LOADER",
20
+ id: data.id,
21
+ env: {},
22
+ } satisfies RscWorkerInputMessage);
14
23
  }
15
24
 
16
25
  // Load hook
@@ -27,7 +36,7 @@ export async function load(
27
36
  }
28
37
 
29
38
  // Skip node internals and hidden files
30
- if (url.startsWith('node:') || url.includes('/.')) {
39
+ if (url.startsWith("node:") || url.includes("/.")) {
31
40
  return result;
32
41
  }
33
42
 
@@ -35,10 +44,15 @@ export async function load(
35
44
  let sourceStr: string;
36
45
  if (typeof result.source === "string") {
37
46
  sourceStr = result.source;
38
- } else if (result.source instanceof Uint8Array || Buffer.isBuffer(result.source)) {
47
+ } else if (
48
+ result.source instanceof Uint8Array ||
49
+ Buffer.isBuffer(result.source)
50
+ ) {
39
51
  sourceStr = result.source.toString("utf-8");
40
52
  } else {
41
- console.warn(`[env-loader] Unexpected source type: ${typeof result.source}`);
53
+ console.warn(
54
+ `[env-loader] Unexpected source type: ${typeof result.source}`
55
+ );
42
56
  return result;
43
57
  }
44
58
 
@@ -47,29 +61,34 @@ export async function load(
47
61
 
48
62
  // Create the env object with Vite's default environment variables
49
63
  const envObject = {
50
- MODE: resolvedConfig?.mode || 'development',
51
- BASE_URL: resolvedConfig?.base || '/',
64
+ MODE: resolvedConfig?.mode || "development",
65
+ BASE_URL: resolvedConfig?.base || "/",
52
66
  PROD: resolvedConfig?.isProduction ? true : false,
53
67
  DEV: resolvedConfig?.isProduction ? false : true,
54
68
  SSR: true,
55
69
  ...Object.fromEntries(
56
70
  Object.entries(define)
57
- .filter(([key]) => key.startsWith('import.meta.env.'))
58
- .map(([key, value]) => [key.replace('import.meta.env.', ''), JSON.parse(value as string)])
59
- )
71
+ .filter(([key]) => key.startsWith("import.meta.env."))
72
+ .map(([key, value]) => [
73
+ key.replace("import.meta.env.", ""),
74
+ JSON.parse(value as string),
75
+ ])
76
+ ),
60
77
  };
61
78
 
62
79
  // Replace environment variable references in the source
63
80
  let newSource = sourceStr;
64
-
81
+
65
82
  // Check if we need to handle import.meta.env
66
- if (newSource.includes('import.meta.env')) {
67
- newSource = `Object.defineProperty(import.meta, "env", { value: ${JSON.stringify(envObject)}, writable: false, configurable: false });\n${newSource}`;
83
+ if (newSource.includes("import.meta.env")) {
84
+ newSource = `Object.defineProperty(import.meta, "env", { value: ${JSON.stringify(
85
+ envObject
86
+ )}, writable: false, configurable: false });\n${newSource}`;
68
87
  }
69
88
 
70
89
  return {
71
90
  ...result,
72
- source: newSource
91
+ source: newSource,
73
92
  };
74
93
  }
75
94
 
@@ -79,6 +98,10 @@ export async function transformSource(
79
98
  context: any,
80
99
  defaultTransformSource: any
81
100
  ) {
82
- const transformed = await defaultTransformSource(source, context, defaultTransformSource);
101
+ const transformed = await defaultTransformSource(
102
+ source,
103
+ context,
104
+ defaultTransformSource
105
+ );
83
106
  return transformed;
84
107
  }
@@ -37,6 +37,7 @@ export function handleExports(
37
37
  before?: string[];
38
38
  after?: string[];
39
39
  isAsync?: boolean;
40
+ isServerAction?: boolean;
40
41
  }
41
42
  >;
42
43
  } {
@@ -53,6 +54,7 @@ export function handleExports(
53
54
  before?: string[];
54
55
  after?: string[];
55
56
  isAsync?: boolean;
57
+ isServerAction?: boolean;
56
58
  }
57
59
  >();
58
60
 
@@ -71,7 +73,28 @@ export function handleExports(
71
73
  }
72
74
 
73
75
  if (node.type === "ImportDeclaration") {
76
+ const importSource = node.source.value as string;
77
+ const isServerImport = importSource.includes(".server.");
74
78
  imports.push(source.slice(node.start, node.end));
79
+
80
+ // If this is a server import, mark all imported functions as server actions
81
+ if (isServerImport) {
82
+ for (const spec of node.specifiers) {
83
+ if (spec.type === "ImportSpecifier") {
84
+ const localName = spec.local.type === "Identifier" ? spec.local.name : "";
85
+ const importedName = spec.imported.type === "Identifier" ? spec.imported.name : "";
86
+ if (localName && importedName) {
87
+ exports.set(localName, {
88
+ type: "function",
89
+ localName,
90
+ isServerAction: true,
91
+ before: [...currentBefore],
92
+ });
93
+ exportNames.push(localName);
94
+ }
95
+ }
96
+ }
97
+ }
75
98
  } else if (node.type === "ExportAllDeclaration") {
76
99
  // For export * from './other', just add the * export
77
100
  exports.set("*", {
@@ -95,11 +118,12 @@ export function handleExports(
95
118
  exports.set(name, {
96
119
  type: "function",
97
120
  declaration: source.slice(node.declaration.start, node.declaration.end),
98
- before: [...currentBefore], // Copy the current before array
121
+ before: [...currentBefore],
99
122
  isAsync: node.declaration.async,
123
+ isServerAction: isServerFunction === true,
100
124
  });
101
125
  exportNames.push(name);
102
- currentBefore = []; // Reset for next export
126
+ currentBefore = [];
103
127
  } else if (
104
128
  node.declaration.type === "ClassDeclaration" &&
105
129
  node.declaration.id
@@ -108,22 +132,19 @@ export function handleExports(
108
132
  exports.set(name, {
109
133
  type: "class",
110
134
  declaration: source.slice(node.declaration.start, node.declaration.end),
111
- before: [...currentBefore], // Copy the current before array
135
+ before: [...currentBefore],
112
136
  });
113
137
  exportNames.push(name);
114
- currentBefore = []; // Reset for next export
138
+ currentBefore = [];
115
139
  } else if (node.declaration.type === "VariableDeclaration") {
116
140
  for (const decl of node.declaration.declarations) {
117
141
  if (decl.id && decl.id.type === "Identifier") {
118
142
  const name = decl.id.name;
119
- // Check if the declaration is a function expression or arrow function
120
143
  const init = decl.init;
121
144
  const isFunction = init && (
122
145
  init.type === "FunctionExpression" ||
123
146
  init.type === "ArrowFunctionExpression"
124
147
  );
125
- // For function expressions and arrow functions, we want to mark them as async
126
- // if they are explicitly marked as async
127
148
  const isAsync = isFunction && (
128
149
  (init.type === "FunctionExpression" && init.async === true) ||
129
150
  (init.type === "ArrowFunctionExpression" && init.async === true)
@@ -131,11 +152,12 @@ export function handleExports(
131
152
  exports.set(name, {
132
153
  type: isFunction ? "function" : "variable",
133
154
  declaration: source.slice(decl.start, decl.end),
134
- before: [...currentBefore], // Copy the current before array
135
- isAsync: isAsync || false
155
+ before: [...currentBefore],
156
+ isAsync: isAsync || false,
157
+ isServerAction: isFunction != null && isServerFunction === true,
136
158
  });
137
159
  exportNames.push(name);
138
- currentBefore = []; // Reset for next export
160
+ currentBefore = [];
139
161
  }
140
162
  }
141
163
  }
@@ -159,7 +181,8 @@ export function handleExports(
159
181
  localName,
160
182
  declaration: source.slice(functionDecl.start, functionDecl.end),
161
183
  before: [...currentBefore],
162
- isAsync: functionDecl.async
184
+ isAsync: functionDecl.async,
185
+ isServerAction: isServerFunction === true,
163
186
  });
164
187
  exportNames.push(exportedName);
165
188
  } else {
@@ -189,7 +212,8 @@ export function handleExports(
189
212
  localName,
190
213
  declaration: source.slice(decl.start, decl.end),
191
214
  before: [...currentBefore],
192
- isAsync
215
+ isAsync,
216
+ isServerAction: isServerFunction === true,
193
217
  });
194
218
  exportNames.push(exportedName);
195
219
  }
@@ -205,7 +229,6 @@ export function handleExports(
205
229
  }
206
230
  }
207
231
  }
208
- currentBefore = []; // Reset for next export
209
232
  }
210
233
  } else if (node.type === "ExportDefaultDeclaration") {
211
234
  if (node.declaration && node.declaration.type === "FunctionDeclaration" && node.declaration.id) {
@@ -1,12 +1,19 @@
1
- import type { LoaderContext, ResolvedUserOptions } from "../types.js";
1
+ import type {
2
+ LoaderContext,
3
+ ResolvedUserOptions,
4
+ SerializedUserOptions,
5
+ } from "../types.js";
2
6
  import type { ModuleInfo } from "rollup";
3
7
  import { transformModuleIfNeeded } from "./transformModuleIfNeeded.js";
4
8
  import type { MessagePort } from "node:worker_threads";
5
- import type { InitializedReactLoaderMessage, ServerModuleMessage } from "../worker/types.js";
6
- import { hydrateUserOptions } from "../helpers/index.js";
7
- import { resolveOptions } from "../config/index.js";
9
+ import type {
10
+ InitializedReactLoaderMessage,
11
+ ServerModuleMessage,
12
+ } from "../worker/types.js";
8
13
  import { fileURLToPath } from "node:url";
9
14
  import { join } from "node:path";
15
+ import { resolveOptions } from "../config/resolveOptions.js";
16
+ import { hydrateUserOptions } from "../helpers/index.js";
10
17
 
11
18
  export interface LoaderOptions {
12
19
  id: string;
@@ -22,27 +29,82 @@ export type LoaderFunction = (options: LoaderOptions) => Promise<ModuleInfo>;
22
29
 
23
30
  let userOptions: ResolvedUserOptions | undefined;
24
31
  let loaderPort: MessagePort | undefined;
25
- export async function initialize(data: { id: string, port: MessagePort, userOptions: any }) {
26
- const userOptionsResult = resolveOptions(hydrateUserOptions(data.userOptions));
27
- loaderPort = data.port;
28
- loaderPort.postMessage({ type: "INITIALIZED_REACT_LOADER", id: data.id } satisfies InitializedReactLoaderMessage);
29
- if(userOptionsResult.type === "error") {
30
- throw userOptionsResult.error
32
+ export async function initialize(data: {
33
+ id: string;
34
+ port: MessagePort;
35
+ userOptions: SerializedUserOptions;
36
+ }) {
37
+ if (userOptions?.verbose) {
38
+ console.log("[react-loader] Initializing with options:", data.id);
31
39
  }
32
- userOptions = userOptionsResult.userOptions;
40
+ const resolvedUserOptions = resolveOptions(
41
+ hydrateUserOptions(data.userOptions)
42
+ );
43
+ if (resolvedUserOptions.type === "error") {
44
+ throw new Error(resolvedUserOptions.error.message);
45
+ }
46
+ userOptions = resolvedUserOptions.userOptions;
47
+ loaderPort = data.port;
48
+ loaderPort.postMessage({
49
+ type: "INITIALIZED_REACT_LOADER",
50
+ id: data.id,
51
+ } satisfies InitializedReactLoaderMessage);
33
52
  }
34
53
 
35
54
  export async function load(url: string, context: LoaderContext, nextLoad: any) {
36
- const { format } = context;
55
+ if (userOptions?.verbose) {
56
+ console.log("[react-loader] Attempting to load:", url);
57
+ console.log("[react-loader] Context:", {
58
+ format: context.format,
59
+ conditions: context.conditions,
60
+ });
61
+ }
37
62
 
38
- if (format === "module") {
63
+ const { format } = context;
64
+ if (format === "module" || format === "module-typescript") {
65
+ if (userOptions?.verbose) {
66
+ console.log("[react-loader] Loading module:", url);
67
+ }
39
68
  const result = await nextLoad(url, context);
40
- const source = typeof result.source === 'string' ? result.source :
41
- result.source instanceof Uint8Array ? new TextDecoder().decode(result.source) :
42
- String(result.source);
69
+ if (userOptions?.verbose) {
70
+ console.log("[react-loader] Next load result:", {
71
+ format: result.format,
72
+ shortCircuit: result.shortCircuit,
73
+ source: typeof result.source,
74
+ });
75
+ }
76
+
77
+ const source =
78
+ typeof result.source === "string"
79
+ ? result.source
80
+ : result.source instanceof Uint8Array
81
+ ? new TextDecoder().decode(result.source)
82
+ : String(result.source);
83
+
84
+ const isServer = userOptions?.autoDiscover?.isServerFunctionCode(source);
85
+ const isClient = userOptions?.autoDiscover?.isClientComponentCode(source);
86
+ if (userOptions?.verbose) {
87
+ console.log("[react-loader] Module analysis:", {
88
+ url,
89
+ isServer,
90
+ isClient,
91
+ sourceLength: source.length,
92
+ sourcePreview: source.slice(0, 100) + "...",
93
+ });
94
+ }
95
+
96
+ if (!isServer && !isClient) {
97
+ if (userOptions?.verbose) {
98
+ console.log("[react-loader] Skipping non-server/non-client module:", url);
99
+ }
100
+ return result;
101
+ }
43
102
 
44
103
  // Handle file URLs
45
104
  const filePath = url.startsWith("file://") ? fileURLToPath(url) : url;
105
+ if (userOptions?.verbose) {
106
+ console.log("[react-loader] File path:", filePath);
107
+ }
46
108
 
47
109
  // Normalize the URL using the same logic as plugin.server.ts
48
110
  let moduleID = filePath;
@@ -51,27 +113,30 @@ export async function load(url: string, context: LoaderContext, nextLoad: any) {
51
113
  const [, value] = userOptions.normalizer(filePath);
52
114
  moduleID = join(userOptions.moduleBasePath, value);
53
115
  finalID = userOptions.moduleID(moduleID);
54
- }
55
- if (userOptions?.verbose) {
56
- console.log("[react-loader] moduleID:", moduleID);
57
- console.log("[react-loader] finalID:", finalID);
116
+ if (userOptions?.verbose) {
117
+ console.log("[react-loader] Normalized IDs:", { moduleID, finalID });
118
+ }
58
119
  }
59
120
 
60
121
  const transformed = transformModuleIfNeeded(
61
122
  source,
62
123
  finalID,
63
- userOptions?.autoDiscover?.isServerFunction(source),
64
- userOptions?.autoDiscover?.isClientComponent(source),
65
- true, // isServerEnvironment
124
+ isServer,
125
+ isClient,
126
+ true // isServerEnvironment
66
127
  );
67
128
 
68
129
  if (userOptions?.verbose) {
69
- console.log("[react-loader] Transformed source:", transformed);
130
+ console.log("[react-loader] Transformation result:", {
131
+ originalLength: source.length,
132
+ transformedLength: transformed.length,
133
+ wasTransformed: source !== transformed,
134
+ });
70
135
  }
71
136
 
72
137
  if (loaderPort) {
73
138
  if (userOptions?.verbose) {
74
- console.log("[react-loader] Sending SERVER_MODULE message:", { id: finalID, url: filePath });
139
+ console.log("[react-loader] Sending SERVER_MODULE message");
75
140
  }
76
141
  loaderPort.postMessage({
77
142
  type: "SERVER_MODULE",
@@ -82,19 +147,24 @@ export async function load(url: string, context: LoaderContext, nextLoad: any) {
82
147
  }
83
148
 
84
149
  // If we have a source map, update it to point to the transformed source
85
- const map = result.map ? {
86
- ...result.map,
87
- sourcesContent: [transformed],
88
- mappings: result.map.mappings
89
- } : null;
150
+ const map = result.map
151
+ ? {
152
+ ...result.map,
153
+ sourcesContent: [transformed],
154
+ mappings: result.map.mappings,
155
+ }
156
+ : null;
90
157
 
91
158
  return {
92
159
  ...result,
93
160
  source: transformed,
94
- map
161
+ map,
95
162
  };
96
163
  }
97
164
 
165
+ if (userOptions?.verbose) {
166
+ console.log("[react-loader] Skipping non-module format:", format);
167
+ }
98
168
  return nextLoad(url, context);
99
169
  }
100
170
 
@@ -103,5 +173,13 @@ export async function resolve(
103
173
  context: any,
104
174
  nextResolve: any
105
175
  ) {
106
- return nextResolve(specifier, context);
176
+ if (userOptions?.verbose) {
177
+ console.log("[react-loader] Resolving:", specifier);
178
+ console.log("[react-loader] Resolve context:", context);
179
+ }
180
+ const result = await nextResolve(specifier, context);
181
+ if (userOptions?.verbose) {
182
+ console.log("[react-loader] Resolve result:", result);
183
+ }
184
+ return result;
107
185
  }
@@ -6,8 +6,8 @@ import { DEFAULT_CONFIG } from "../config/defaults.js";
6
6
  export function transformModuleIfNeeded(
7
7
  source: string,
8
8
  moduleId: string,
9
- isServerFunction: boolean | RegExpMatchArray | null = DEFAULT_CONFIG.AUTO_DISCOVER.isServerFunction(source),
10
- isClientComponent: boolean | RegExpMatchArray | null = DEFAULT_CONFIG.AUTO_DISCOVER.isClientComponent(source),
9
+ isServerFunction: boolean | RegExpMatchArray | null = DEFAULT_CONFIG.AUTO_DISCOVER.isServerFunctionCode(source, moduleId),
10
+ isClientComponent: boolean | RegExpMatchArray | null = DEFAULT_CONFIG.AUTO_DISCOVER.isClientComponentCode(source),
11
11
  isServerEnvironment = getCondition() === "react-server"
12
12
  ) {
13
13
  // Parse source and handle source maps