@ivogt/rsc-router 0.0.0-experimental.1

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 (123) hide show
  1. package/README.md +19 -0
  2. package/package.json +131 -0
  3. package/src/__mocks__/version.ts +6 -0
  4. package/src/__tests__/route-definition.test.ts +63 -0
  5. package/src/browser/event-controller.ts +876 -0
  6. package/src/browser/index.ts +18 -0
  7. package/src/browser/link-interceptor.ts +121 -0
  8. package/src/browser/lru-cache.ts +69 -0
  9. package/src/browser/merge-segment-loaders.ts +126 -0
  10. package/src/browser/navigation-bridge.ts +891 -0
  11. package/src/browser/navigation-client.ts +155 -0
  12. package/src/browser/navigation-store.ts +823 -0
  13. package/src/browser/partial-update.ts +545 -0
  14. package/src/browser/react/Link.tsx +248 -0
  15. package/src/browser/react/NavigationProvider.tsx +228 -0
  16. package/src/browser/react/ScrollRestoration.tsx +94 -0
  17. package/src/browser/react/context.ts +53 -0
  18. package/src/browser/react/index.ts +52 -0
  19. package/src/browser/react/location-state-shared.ts +120 -0
  20. package/src/browser/react/location-state.ts +62 -0
  21. package/src/browser/react/use-action.ts +240 -0
  22. package/src/browser/react/use-client-cache.ts +56 -0
  23. package/src/browser/react/use-handle.ts +178 -0
  24. package/src/browser/react/use-link-status.ts +134 -0
  25. package/src/browser/react/use-navigation.ts +150 -0
  26. package/src/browser/react/use-segments.ts +188 -0
  27. package/src/browser/request-controller.ts +149 -0
  28. package/src/browser/rsc-router.tsx +310 -0
  29. package/src/browser/scroll-restoration.ts +324 -0
  30. package/src/browser/server-action-bridge.ts +747 -0
  31. package/src/browser/shallow.ts +35 -0
  32. package/src/browser/types.ts +443 -0
  33. package/src/cache/__tests__/memory-segment-store.test.ts +487 -0
  34. package/src/cache/__tests__/memory-store.test.ts +484 -0
  35. package/src/cache/cache-scope.ts +565 -0
  36. package/src/cache/cf/__tests__/cf-cache-store.test.ts +361 -0
  37. package/src/cache/cf/cf-cache-store.ts +274 -0
  38. package/src/cache/cf/index.ts +19 -0
  39. package/src/cache/index.ts +52 -0
  40. package/src/cache/memory-segment-store.ts +150 -0
  41. package/src/cache/memory-store.ts +253 -0
  42. package/src/cache/types.ts +366 -0
  43. package/src/client.rsc.tsx +88 -0
  44. package/src/client.tsx +609 -0
  45. package/src/components/DefaultDocument.tsx +20 -0
  46. package/src/default-error-boundary.tsx +88 -0
  47. package/src/deps/browser.ts +8 -0
  48. package/src/deps/html-stream-client.ts +2 -0
  49. package/src/deps/html-stream-server.ts +2 -0
  50. package/src/deps/rsc.ts +10 -0
  51. package/src/deps/ssr.ts +2 -0
  52. package/src/errors.ts +259 -0
  53. package/src/handle.ts +120 -0
  54. package/src/handles/MetaTags.tsx +178 -0
  55. package/src/handles/index.ts +6 -0
  56. package/src/handles/meta.ts +247 -0
  57. package/src/href-client.ts +128 -0
  58. package/src/href.ts +139 -0
  59. package/src/index.rsc.ts +69 -0
  60. package/src/index.ts +84 -0
  61. package/src/loader.rsc.ts +204 -0
  62. package/src/loader.ts +47 -0
  63. package/src/network-error-thrower.tsx +21 -0
  64. package/src/outlet-context.ts +15 -0
  65. package/src/root-error-boundary.tsx +277 -0
  66. package/src/route-content-wrapper.tsx +198 -0
  67. package/src/route-definition.ts +1333 -0
  68. package/src/route-map-builder.ts +140 -0
  69. package/src/route-types.ts +148 -0
  70. package/src/route-utils.ts +89 -0
  71. package/src/router/__tests__/match-context.test.ts +104 -0
  72. package/src/router/__tests__/match-pipelines.test.ts +537 -0
  73. package/src/router/__tests__/match-result.test.ts +566 -0
  74. package/src/router/__tests__/on-error.test.ts +935 -0
  75. package/src/router/__tests__/pattern-matching.test.ts +577 -0
  76. package/src/router/error-handling.ts +287 -0
  77. package/src/router/handler-context.ts +60 -0
  78. package/src/router/loader-resolution.ts +326 -0
  79. package/src/router/manifest.ts +116 -0
  80. package/src/router/match-context.ts +261 -0
  81. package/src/router/match-middleware/background-revalidation.ts +236 -0
  82. package/src/router/match-middleware/cache-lookup.ts +261 -0
  83. package/src/router/match-middleware/cache-store.ts +250 -0
  84. package/src/router/match-middleware/index.ts +81 -0
  85. package/src/router/match-middleware/intercept-resolution.ts +268 -0
  86. package/src/router/match-middleware/segment-resolution.ts +174 -0
  87. package/src/router/match-pipelines.ts +214 -0
  88. package/src/router/match-result.ts +212 -0
  89. package/src/router/metrics.ts +62 -0
  90. package/src/router/middleware.test.ts +1355 -0
  91. package/src/router/middleware.ts +748 -0
  92. package/src/router/pattern-matching.ts +271 -0
  93. package/src/router/revalidation.ts +190 -0
  94. package/src/router/router-context.ts +299 -0
  95. package/src/router/types.ts +96 -0
  96. package/src/router.ts +3484 -0
  97. package/src/rsc/__tests__/helpers.test.ts +175 -0
  98. package/src/rsc/handler.ts +942 -0
  99. package/src/rsc/helpers.ts +64 -0
  100. package/src/rsc/index.ts +56 -0
  101. package/src/rsc/nonce.ts +18 -0
  102. package/src/rsc/types.ts +225 -0
  103. package/src/segment-system.tsx +405 -0
  104. package/src/server/__tests__/request-context.test.ts +171 -0
  105. package/src/server/context.ts +340 -0
  106. package/src/server/handle-store.ts +230 -0
  107. package/src/server/loader-registry.ts +174 -0
  108. package/src/server/request-context.ts +470 -0
  109. package/src/server/root-layout.tsx +10 -0
  110. package/src/server/tsconfig.json +14 -0
  111. package/src/server.ts +126 -0
  112. package/src/ssr/__tests__/ssr-handler.test.tsx +188 -0
  113. package/src/ssr/index.tsx +215 -0
  114. package/src/types.ts +1473 -0
  115. package/src/use-loader.tsx +346 -0
  116. package/src/vite/__tests__/expose-loader-id.test.ts +117 -0
  117. package/src/vite/expose-action-id.ts +344 -0
  118. package/src/vite/expose-handle-id.ts +209 -0
  119. package/src/vite/expose-loader-id.ts +357 -0
  120. package/src/vite/expose-location-state-id.ts +177 -0
  121. package/src/vite/index.ts +608 -0
  122. package/src/vite/version.d.ts +12 -0
  123. package/src/vite/virtual-entries.ts +109 -0
@@ -0,0 +1,357 @@
1
+ import type { Plugin, ResolvedConfig } from "vite";
2
+ import MagicString from "magic-string";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+
6
+ /**
7
+ * Normalize path to forward slashes
8
+ */
9
+ function normalizePath(p: string): string {
10
+ return p.split(path.sep).join("/");
11
+ }
12
+
13
+ /**
14
+ * Generate a short hash for a loader ID
15
+ * Uses first 8 chars of SHA-256 hash for uniqueness while keeping IDs short
16
+ * Appends export name for easier debugging in production: "abc123#CartLoader"
17
+ */
18
+ function hashLoaderId(filePath: string, exportName: string): string {
19
+ const input = `${filePath}#${exportName}`;
20
+ const hash = crypto.createHash("sha256").update(input).digest("hex");
21
+ return `${hash.slice(0, 8)}#${exportName}`;
22
+ }
23
+
24
+ /**
25
+ * Check if file imports createLoader from rsc-router
26
+ */
27
+ function hasCreateLoaderImport(code: string): boolean {
28
+ // Match: import { createLoader } from "rsc-router" or "rsc-router/server"
29
+ // Must be exact - no aliasing support
30
+ const pattern =
31
+ /import\s*\{[^}]*\bcreateLoader\b[^}]*\}\s*from\s*["']rsc-router(?:\/server)?["']/;
32
+ return pattern.test(code);
33
+ }
34
+
35
+ /**
36
+ * Count the number of arguments in a createLoader call
37
+ * Returns the count of top-level arguments (not counting nested commas)
38
+ */
39
+ function countCreateLoaderArgs(code: string, startPos: number, endPos: number): number {
40
+ let depth = 0;
41
+ let argCount = 0;
42
+ let hasContent = false;
43
+
44
+ for (let i = startPos; i < endPos; i++) {
45
+ const char = code[i];
46
+
47
+ // Track nested structures
48
+ if (char === "(" || char === "[" || char === "{") {
49
+ depth++;
50
+ hasContent = true;
51
+ } else if (char === ")" || char === "]" || char === "}") {
52
+ depth--;
53
+ } else if (char === "," && depth === 0) {
54
+ // Top-level comma means another argument
55
+ argCount++;
56
+ } else if (!/\s/.test(char)) {
57
+ hasContent = true;
58
+ }
59
+ }
60
+
61
+ // If there's content, we have at least one argument
62
+ return hasContent ? argCount + 1 : 0;
63
+ }
64
+
65
+ /**
66
+ * Find all export const X = createLoader(...) patterns and inject $$id
67
+ * In production, IDs are hashed to avoid exposing file paths.
68
+ * In dev, IDs use filePath#exportName for easier debugging.
69
+ *
70
+ * The ID is injected in two ways:
71
+ * 1. As a hidden third parameter to createLoader() for registry registration
72
+ * 2. As a property assignment X.$$id = "..." for external access
73
+ *
74
+ * IMPORTANT: The $$id must always be the THIRD parameter to createLoader.
75
+ * createLoader(fn, fetchable?, __injectedId?)
76
+ * If the user only provides fn, we inject: undefined, "id"
77
+ * If the user provides fn and fetchable, we inject: , "id"
78
+ */
79
+ function transformLoaderExports(
80
+ code: string,
81
+ filePath: string,
82
+ sourceId?: string,
83
+ isBuild: boolean = false
84
+ ): { code: string; map: ReturnType<MagicString["generateMap"]> } | null {
85
+ // Quick bail-out
86
+ if (!code.includes("createLoader")) {
87
+ return null;
88
+ }
89
+
90
+ // Must have direct import from rsc-router
91
+ if (!hasCreateLoaderImport(code)) {
92
+ return null;
93
+ }
94
+
95
+ // Match: export const X = createLoader(
96
+ // Captures the export name (X)
97
+ const pattern = /export\s+const\s+(\w+)\s*=\s*createLoader\s*\(/g;
98
+
99
+ const s = new MagicString(code);
100
+ let hasChanges = false;
101
+ let match: RegExpExecArray | null;
102
+
103
+ while ((match = pattern.exec(code)) !== null) {
104
+ const exportName = match[1];
105
+ const matchEnd = match.index + match[0].length;
106
+
107
+ // Find the end of the createLoader(...) call
108
+ // Need to count parentheses to find matching close
109
+ let parenDepth = 1;
110
+ let i = matchEnd;
111
+ while (i < code.length && parenDepth > 0) {
112
+ if (code[i] === "(") parenDepth++;
113
+ if (code[i] === ")") parenDepth--;
114
+ i++;
115
+ }
116
+
117
+ // i now points just after the closing )
118
+ const closeParenPos = i - 1;
119
+
120
+ // Count existing arguments
121
+ const argCount = countCreateLoaderArgs(code, matchEnd, closeParenPos);
122
+
123
+ // Find the semicolon or end of statement
124
+ let statementEnd = i;
125
+ while (statementEnd < code.length && /\s/.test(code[statementEnd])) {
126
+ statementEnd++;
127
+ }
128
+ if (code[statementEnd] === ";") {
129
+ statementEnd++;
130
+ }
131
+
132
+ // In production: hash ID to avoid exposing file paths
133
+ // In dev: use readable format for easier debugging
134
+ const loaderId = isBuild
135
+ ? hashLoaderId(filePath, exportName)
136
+ : `${filePath}#${exportName}`;
137
+
138
+ // Inject $$id as hidden third parameter before the closing paren
139
+ // If user only has 1 arg (fn), we need to add undefined for fetchable
140
+ // createLoader(fn) -> createLoader(fn, undefined, "id")
141
+ // createLoader(fn, true) -> createLoader(fn, true, "id")
142
+ const paramInjection = argCount === 1
143
+ ? `, undefined, "${loaderId}"`
144
+ : `, "${loaderId}"`;
145
+ s.appendLeft(closeParenPos, paramInjection);
146
+
147
+ // Also set $$id property for external access (useLoader, useFetchLoader)
148
+ const propInjection = `\n${exportName}.$$id = "${loaderId}";`;
149
+ s.appendRight(statementEnd, propInjection);
150
+ hasChanges = true;
151
+ }
152
+
153
+ if (!hasChanges) {
154
+ return null;
155
+ }
156
+
157
+ return {
158
+ code: s.toString(),
159
+ map: s.generateMap({ source: sourceId, includeContent: true }),
160
+ };
161
+ }
162
+
163
+ const VIRTUAL_LOADER_MANIFEST = "virtual:rsc-router/loader-manifest";
164
+ const RESOLVED_VIRTUAL_LOADER_MANIFEST = "\0" + VIRTUAL_LOADER_MANIFEST;
165
+
166
+ // Store for deferred manifest generation - populated during transform, used after build
167
+ let manifestGenerated = false;
168
+
169
+ /**
170
+ * Vite plugin that exposes $$id on createLoader calls and generates a loader manifest.
171
+ *
172
+ * When users create loaders with createLoader(), this plugin:
173
+ * 1. Injects a $$id property containing the file path and export name
174
+ * 2. Tracks all loaders and generates a virtual manifest module
175
+ *
176
+ * The manifest can be imported by the RSC handler to get all loaders.
177
+ *
178
+ * Requirements:
179
+ * - Must use direct import: import { createLoader } from "rsc-router"
180
+ * - No aliasing support (import { createLoader as cl } won't work)
181
+ * - Must use named export: export const MyLoader = createLoader(...)
182
+ */
183
+ export function exposeLoaderId(): Plugin {
184
+ let config: ResolvedConfig;
185
+ let isBuild = false;
186
+
187
+ // Track discovered loaders: hashedId -> { filePath, exportName }
188
+ const loaderRegistry = new Map<
189
+ string,
190
+ { filePath: string; exportName: string }
191
+ >();
192
+
193
+ // For build mode: pre-scan for loaders during buildStart
194
+ const pendingLoaderScans = new Map<string, Promise<void>>();
195
+
196
+ return {
197
+ name: "rsc-router:expose-loader-id",
198
+ enforce: "post",
199
+
200
+ configResolved(resolvedConfig) {
201
+ config = resolvedConfig;
202
+ isBuild = config.command === "build";
203
+ },
204
+
205
+ async buildStart() {
206
+ if (!isBuild) return;
207
+
208
+ // Pre-scan for loader files to populate registry before manifest is loaded
209
+ // This runs before module resolution, so manifest will have access to all loaders
210
+ const fs = await import("node:fs/promises");
211
+
212
+ async function scanDir(dir: string): Promise<string[]> {
213
+ const results: string[] = [];
214
+ try {
215
+ const entries = await fs.readdir(dir, { withFileTypes: true });
216
+ for (const entry of entries) {
217
+ const fullPath = path.join(dir, entry.name);
218
+ if (entry.isDirectory()) {
219
+ if (entry.name !== "node_modules") {
220
+ results.push(...(await scanDir(fullPath)));
221
+ }
222
+ } else if (/\.(ts|tsx|js|jsx)$/.test(entry.name)) {
223
+ results.push(fullPath);
224
+ }
225
+ }
226
+ } catch {
227
+ // Directory doesn't exist or not readable
228
+ }
229
+ return results;
230
+ }
231
+
232
+ try {
233
+ const srcDir = path.join(config.root, "src");
234
+ const files = await scanDir(srcDir);
235
+
236
+ for (const filePath of files) {
237
+ const content = await fs.readFile(filePath, "utf-8");
238
+
239
+ // Quick check for createLoader
240
+ if (!content.includes("createLoader")) continue;
241
+ if (!hasCreateLoaderImport(content)) continue;
242
+
243
+ // Extract loader exports
244
+ const pattern = /export\s+const\s+(\w+)\s*=\s*createLoader\s*\(/g;
245
+ const relativePath = normalizePath(
246
+ path.relative(config.root, filePath)
247
+ );
248
+ let match: RegExpExecArray | null;
249
+
250
+ while ((match = pattern.exec(content)) !== null) {
251
+ const exportName = match[1];
252
+ const hashedId = hashLoaderId(relativePath, exportName);
253
+ loaderRegistry.set(hashedId, {
254
+ filePath: relativePath,
255
+ exportName,
256
+ });
257
+ }
258
+ }
259
+ } catch (error) {
260
+ // Fall back to transform-time discovery
261
+ console.warn("[exposeLoaderId] Pre-scan failed:", error);
262
+ }
263
+ },
264
+
265
+ resolveId(id) {
266
+ if (id === VIRTUAL_LOADER_MANIFEST) {
267
+ return RESOLVED_VIRTUAL_LOADER_MANIFEST;
268
+ }
269
+ },
270
+
271
+ load(id) {
272
+ if (id === RESOLVED_VIRTUAL_LOADER_MANIFEST) {
273
+ // Generate a lazy import map for on-demand loader loading
274
+ // This avoids importing all loader modules at startup
275
+
276
+ if (!isBuild) {
277
+ // Dev mode: empty map - use fallback path parsing in loader registry
278
+ // IDs in dev mode are "filePath#exportName" format for easier debugging
279
+ return `import { setLoaderImports } from "rsc-router/server";
280
+
281
+ // Dev mode: empty map, loaders are resolved dynamically via path parsing
282
+ setLoaderImports({});
283
+ `;
284
+ }
285
+
286
+ // Build mode: generate lazy import map
287
+ // Each loader is only imported when first requested
288
+ // Keys are hashed IDs to avoid exposing file paths
289
+ const lazyImports: string[] = [];
290
+
291
+ for (const [hashedId, { filePath, exportName }] of loaderRegistry) {
292
+ // Create a lazy import function for each loader
293
+ lazyImports.push(
294
+ ` "${hashedId}": () => import("/${filePath}").then(m => m.${exportName})`
295
+ );
296
+ }
297
+
298
+ // If no loaders discovered, set empty map
299
+ if (lazyImports.length === 0) {
300
+ return `import { setLoaderImports } from "rsc-router/server";
301
+
302
+ // No fetchable loaders discovered during build
303
+ setLoaderImports({});
304
+ `;
305
+ }
306
+
307
+ const code = `import { setLoaderImports } from "rsc-router/server";
308
+
309
+ // Lazy import map - loaders are loaded on-demand when first requested
310
+ setLoaderImports({
311
+ ${lazyImports.join(",\n")}
312
+ });
313
+ `;
314
+ return code;
315
+ }
316
+ },
317
+
318
+ transform(code, id) {
319
+ // Skip node_modules
320
+ if (id.includes("/node_modules/")) {
321
+ return;
322
+ }
323
+
324
+ // Quick bail-out
325
+ if (!code.includes("createLoader")) {
326
+ return;
327
+ }
328
+
329
+ // Must have direct import from rsc-router
330
+ if (!hasCreateLoaderImport(code)) {
331
+ return;
332
+ }
333
+
334
+ // Check if we're in RSC environment (server-side)
335
+ const envName = this.environment?.name;
336
+ const isRscEnv = envName === "rsc";
337
+
338
+ // Get relative path for the ID
339
+ const relativePath = normalizePath(path.relative(config.root, id));
340
+
341
+ // Track loaders for manifest (only in RSC env to avoid duplicate entries)
342
+ if (isRscEnv) {
343
+ const pattern = /export\s+const\s+(\w+)\s*=\s*createLoader\s*\(/g;
344
+ let match: RegExpExecArray | null;
345
+ while ((match = pattern.exec(code)) !== null) {
346
+ const exportName = match[1];
347
+ const hashedId = hashLoaderId(relativePath, exportName);
348
+ loaderRegistry.set(hashedId, { filePath: relativePath, exportName });
349
+ }
350
+ }
351
+
352
+ // Transform: inject $$id in all environments
353
+ // In build mode, IDs are hashed; in dev mode, they're readable
354
+ return transformLoaderExports(code, relativePath, id, isBuild);
355
+ },
356
+ };
357
+ }
@@ -0,0 +1,177 @@
1
+ import type { Plugin, ResolvedConfig } from "vite";
2
+ import MagicString from "magic-string";
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+
6
+ /**
7
+ * Normalize path to forward slashes
8
+ */
9
+ function normalizePath(p: string): string {
10
+ return p.split(path.sep).join("/");
11
+ }
12
+
13
+ /**
14
+ * Generate a short hash for a location state key
15
+ * Uses first 8 chars of SHA-256 hash for uniqueness while keeping keys short
16
+ * Appends export name for easier debugging: "abc123#ProductState"
17
+ */
18
+ function hashLocationStateKey(filePath: string, exportName: string): string {
19
+ const input = `${filePath}#${exportName}`;
20
+ const hash = crypto.createHash("sha256").update(input).digest("hex");
21
+ return `${hash.slice(0, 8)}#${exportName}`;
22
+ }
23
+
24
+ /**
25
+ * Check if file imports createLocationState from rsc-router
26
+ */
27
+ function hasCreateLocationStateImport(code: string): boolean {
28
+ // Match: import { createLocationState } from "rsc-router" or "rsc-router/client"
29
+ const pattern =
30
+ /import\s*\{[^}]*\bcreateLocationState\b[^}]*\}\s*from\s*["']rsc-router(?:\/[^"']+)?["']/;
31
+ return pattern.test(code);
32
+ }
33
+
34
+ /**
35
+ * Transform export const X = createLocationState<...>() patterns to inject key
36
+ *
37
+ * The key is injected as the first parameter if not present:
38
+ * - createLocationState() -> createLocationState("id")
39
+ * - createLocationState<T>() -> createLocationState<T>("id")
40
+ */
41
+ function transformLocationStateExports(
42
+ code: string,
43
+ filePath: string,
44
+ sourceId?: string,
45
+ isBuild: boolean = false
46
+ ): { code: string; map: ReturnType<MagicString["generateMap"]> } | null {
47
+ // Quick bail-out
48
+ if (!code.includes("createLocationState")) {
49
+ return null;
50
+ }
51
+
52
+ // Must have direct import from rsc-router
53
+ if (!hasCreateLocationStateImport(code)) {
54
+ return null;
55
+ }
56
+
57
+ // Match: export const X = createLocationState<...>(
58
+ // Captures the export name (X)
59
+ const pattern = /export\s+const\s+(\w+)\s*=\s*createLocationState\s*(?:<[^>]*>)?\s*\(/g;
60
+
61
+ const s = new MagicString(code);
62
+ let hasChanges = false;
63
+ let match: RegExpExecArray | null;
64
+
65
+ while ((match = pattern.exec(code)) !== null) {
66
+ const exportName = match[1];
67
+ const matchEnd = match.index + match[0].length;
68
+
69
+ // Find the end of the createLocationState(...) call
70
+ let parenDepth = 1;
71
+ let i = matchEnd;
72
+ while (i < code.length && parenDepth > 0) {
73
+ if (code[i] === "(") parenDepth++;
74
+ if (code[i] === ")") parenDepth--;
75
+ i++;
76
+ }
77
+
78
+ // i now points just after the closing )
79
+ const closeParenPos = i - 1;
80
+
81
+ // Check if there are any arguments (content between open and close paren)
82
+ const content = code.slice(matchEnd, closeParenPos).trim();
83
+ const hasArgs = content.length > 0;
84
+
85
+ // Find the semicolon or end of statement
86
+ let statementEnd = i;
87
+ while (statementEnd < code.length && /\s/.test(code[statementEnd])) {
88
+ statementEnd++;
89
+ }
90
+ if (code[statementEnd] === ";") {
91
+ statementEnd++;
92
+ }
93
+
94
+ // Generate key: hashed in production, readable in dev
95
+ const stateKey = isBuild
96
+ ? hashLocationStateKey(filePath, exportName)
97
+ : `${filePath}#${exportName}`;
98
+
99
+ // Inject key as the first (and only) parameter
100
+ // createLocationState() -> createLocationState("id")
101
+ if (!hasArgs) {
102
+ s.appendLeft(closeParenPos, `"${stateKey}"`);
103
+ } else {
104
+ // Already has a key, skip (shouldn't happen with new API, but be safe)
105
+ continue;
106
+ }
107
+
108
+ // Also set __rsc_ls_key property for verification
109
+ const propInjection = `\n${exportName}.__rsc_ls_key = "__rsc_ls_${stateKey}";`;
110
+ s.appendRight(statementEnd, propInjection);
111
+ hasChanges = true;
112
+ }
113
+
114
+ if (!hasChanges) {
115
+ return null;
116
+ }
117
+
118
+ return {
119
+ code: s.toString(),
120
+ map: s.generateMap({ source: sourceId, includeContent: true }),
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Vite plugin that exposes location state keys on createLocationState calls.
126
+ *
127
+ * When users create location states with createLocationState(), this plugin:
128
+ * 1. Injects an auto-generated key as the first parameter
129
+ * 2. Sets __rsc_ls_key property for verification
130
+ *
131
+ * This allows location states to be created without explicit keys:
132
+ * - Before: export const ProductState = createLocationState<Product>("product")
133
+ * - After: export const ProductState = createLocationState<Product>()
134
+ *
135
+ * The key is auto-generated from file path + export name.
136
+ *
137
+ * Requirements:
138
+ * - Must use direct import: import { createLocationState } from "rsc-router"
139
+ * - Must use named export: export const MyState = createLocationState(...)
140
+ */
141
+ export function exposeLocationStateId(): Plugin {
142
+ let config: ResolvedConfig;
143
+ let isBuild = false;
144
+
145
+ return {
146
+ name: "rsc-router:expose-location-state-id",
147
+ enforce: "post",
148
+
149
+ configResolved(resolvedConfig) {
150
+ config = resolvedConfig;
151
+ isBuild = config.command === "build";
152
+ },
153
+
154
+ transform(code, id) {
155
+ // Skip node_modules
156
+ if (id.includes("/node_modules/")) {
157
+ return;
158
+ }
159
+
160
+ // Quick bail-out
161
+ if (!code.includes("createLocationState")) {
162
+ return;
163
+ }
164
+
165
+ // Must have direct import from rsc-router
166
+ if (!hasCreateLocationStateImport(code)) {
167
+ return;
168
+ }
169
+
170
+ // Get relative path for the key
171
+ const relativePath = normalizePath(path.relative(config.root, id));
172
+
173
+ // Transform: inject key
174
+ return transformLocationStateExports(code, relativePath, id, isBuild);
175
+ },
176
+ };
177
+ }