@_linked/cli 1.28.0 → 1.28.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.
- package/CHANGELOG.md +6 -0
- package/lib/esm/app-release/build-backend.d.ts +4 -1
- package/lib/esm/app-release/build-backend.d.ts.map +1 -1
- package/lib/esm/app-release/build-backend.js +5 -2
- package/lib/esm/app-release/build-backend.js.map +1 -1
- package/lib/esm/vite-config.d.ts.map +1 -1
- package/lib/esm/vite-config.js +10 -1
- package/lib/esm/vite-config.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.28.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#161](https://github.com/linked-fw/cli/pull/161) [`a43b13a`](https://github.com/linked-fw/cli/commit/a43b13ae1d965309f1d783e8570537b4524bdbb1) Thanks [@flyon](https://github.com/flyon)! - A release backend build no longer compiles a private copy of `@_linked/server-utils` and `@_linked/react` into `lib/`. That copy made every provider the app exports fail `LinkedServer`'s `instanceof ShapeProvider` check, so all but one were dropped ("exports two generic backend providers"). `build-app` now also fails if an installed `@_linked/*` package ends up inlined.
|
|
8
|
+
|
|
3
9
|
## 1.28.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
|
@@ -28,7 +28,10 @@ export declare const workspacePackagesToExternalize: (appRoot: string, discover?
|
|
|
28
28
|
}[]>) => Promise<string[]>;
|
|
29
29
|
/**
|
|
30
30
|
* A relative import from `lib/` into `packages/` means a workspace package was
|
|
31
|
-
* compiled in after all.
|
|
31
|
+
* compiled in after all. One into `node_modules/@_linked/` means an installed
|
|
32
|
+
* framework package was: `lib/node_modules/@_linked/server-utils` is a second
|
|
33
|
+
* `ShapeProvider` class, so the server's `instanceof` check rejects every
|
|
34
|
+
* provider the app exports.
|
|
32
35
|
*
|
|
33
36
|
* Worth failing the build over rather than leaving to be discovered: the
|
|
34
37
|
* output is perfectly valid JavaScript, and the symptom is the app refusing to
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-backend.d.ts","sourceRoot":"","sources":["../../../src/app-release/build-backend.ts"],"names":[],"mappings":"AA+BA,eAAO,MAAM,qBAAqB,GAChC,SAAS,MAAM,EACf,SAAQ,CAAC,CAAC,EAAE,MAAM,KAAK,OAAuB,KAC7C,MAAM,CAAC,MAAM,EAAE,MAAM,CAWvB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,8BAA8B,GACzC,SAAS,MAAM,EACf,WAAU,CACR,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,KACR,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAC,EAAE,CAG5B,KACA,OAAO,CAAC,MAAM,EAAE,CAGlB,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"build-backend.d.ts","sourceRoot":"","sources":["../../../src/app-release/build-backend.ts"],"names":[],"mappings":"AA+BA,eAAO,MAAM,qBAAqB,GAChC,SAAS,MAAM,EACf,SAAQ,CAAC,CAAC,EAAE,MAAM,KAAK,OAAuB,KAC7C,MAAM,CAAC,MAAM,EAAE,MAAM,CAWvB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,8BAA8B,GACzC,SAAS,MAAM,EACf,WAAU,CACR,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,EAAE,MAAM,KACR,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAC,EAAE,CAG5B,KACA,OAAO,CAAC,MAAM,EAAE,CAGlB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,2BAA2B,GAAI,QAAQ,MAAM,KAAG,MAAM,EAQlE,CAAC;AAEF,eAAO,MAAM,yBAAyB,GACpC,SAAS,MAAM,EACf,WAAU,CAAC,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAiC,KACvE,OAAO,CAAC,IAAI,CAwBd,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,gCAAgC,GAC3C,SAAS,MAAM,EACf,oBAAoB,MAAM,EAAE,KAC3B,MAAM,GAAG,IAgBX,CAAC;AAqBF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,oBAAoB,GAC/B,UAAS;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAM,EAChC,eAAc;IAAC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;CAAM,KACjE,OAAO,CAAC,IAAI,CAqFd,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GACjC,SAAS,MAAM,EACf,cAAc,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,KAC/C,OAAO,CAAC,MAAM,CAYhB,CAAC"}
|
|
@@ -88,7 +88,10 @@ export const workspacePackagesToExternalize = (appRoot_1, ...args_1) => __awaite
|
|
|
88
88
|
});
|
|
89
89
|
/**
|
|
90
90
|
* A relative import from `lib/` into `packages/` means a workspace package was
|
|
91
|
-
* compiled in after all.
|
|
91
|
+
* compiled in after all. One into `node_modules/@_linked/` means an installed
|
|
92
|
+
* framework package was: `lib/node_modules/@_linked/server-utils` is a second
|
|
93
|
+
* `ShapeProvider` class, so the server's `instanceof` check rejects every
|
|
94
|
+
* provider the app exports.
|
|
92
95
|
*
|
|
93
96
|
* Worth failing the build over rather than leaving to be discovered: the
|
|
94
97
|
* output is perfectly valid JavaScript, and the symptom is the app refusing to
|
|
@@ -98,7 +101,7 @@ export const findInlinedWorkspaceImports = (source) => {
|
|
|
98
101
|
// Both static `from "…"` and dynamic `import("…")`: a lazily imported page
|
|
99
102
|
// can drag a workspace package in on its own, and only the second form
|
|
100
103
|
// appears in the output for it.
|
|
101
|
-
const matches = source.matchAll(/(?:from|import)\s*\(?\s*["'](\.[^"']*\/packages\/[^"']+)["']/g);
|
|
104
|
+
const matches = source.matchAll(/(?:from|import)\s*\(?\s*["'](\.[^"']*\/(?:packages|node_modules\/@_linked)\/[^"']+)["']/g);
|
|
102
105
|
return [...new Set([...matches].map((m) => m[1]))].sort();
|
|
103
106
|
};
|
|
104
107
|
export const assertNoInlinedWorkspaces = (appRoot_1, ...args_1) => __awaiter(void 0, [appRoot_1, ...args_1], void 0, function* (appRoot, readFile = (p) => fs.readFile(p, 'utf8')) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-backend.js","sourceRoot":"","sources":["../../../src/app-release/build-backend.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAC,cAAc,EAAC,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,MAAM,UAAU,CAAC;AAC1B,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;GAMG;AACH,MAAM,eAAe,GAA6B;IAChD,OAAO,EAAE,CAAC,gBAAgB,EAAE,iBAAiB,CAAC;IAC9C,GAAG,EAAE,CAAC,aAAa,EAAE,YAAY,CAAC;IAClC,MAAM,EAAE,CAAC,gBAAgB,EAAE,eAAe,CAAC;CAC5C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,iBAAiB,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AAE7C,wDAAwD;AACxD,MAAM,aAAa,GAAG;IACpB,GAAG,cAAc;IACjB,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,IAAI,EAAE,CAAC;CAChD,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,OAAe,EACf,SAAiC,EAAE,CAAC,UAAU,EACtB,EAAE;IAC1B,MAAM,OAAO,GAA2B,EAAE,CAAC;IAC3C,KAAK,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI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,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;QACxC,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACvC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,QAAQ,CAAC,MAAM,CAAC;AACzB,CAAC,CAAA,CAAC","sourcesContent":["import {builtinModules} from 'module';\nimport fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * The backend entry points a compiled app is started from.\n *\n * `serve-app` requires all three on disk and `startServer` imports `lib/App.js`\n * and `lib/routes.js` by those exact paths, so the names are a contract, not a\n * convention.\n */\nconst BACKEND_ENTRIES: Record<string, string[]> = {\n backend: ['src/backend.ts', 'src/backend.tsx'],\n App: ['src/App.tsx', 'src/App.ts'],\n routes: ['src/routes.tsx', 'src/routes.ts'],\n};\n\n/**\n * Vite's default server conditions minus the `development|production` token.\n *\n * See the note at the `resolve` option below: dropping the token is what stops\n * a workspace package resolving to its TypeScript source.\n */\nconst SERVER_CONDITIONS = ['module', 'node'];\n\n/** Both spellings, because a backend may use either. */\nconst NODE_BUILTINS = [\n ...builtinModules,\n ...builtinModules.map((name) => `node:${name}`),\n];\n\nexport const resolveBackendEntries = (\n appRoot: string,\n exists: (p: string) => boolean = fs.existsSync\n): Record<string, string> => {\n const entries: Record<string, string> = {};\n for (const [name, candidates] of Object.entries(BACKEND_ENTRIES)) {\n const found = candidates.find((candidate) =>\n exists(path.join(appRoot, candidate))\n );\n if (found) {\n entries[name] = path.join(appRoot, found);\n }\n }\n return entries;\n};\n\n/**\n * Workspace package names to list as `ssr.external`.\n *\n * Vite will not externalise these on its own, and the reason is worth\n * recording because it is entirely non-obvious. `node_modules/@_linked/core`\n * is a symlink into `packages/core`; Vite resolves package data with\n * `preserveSymlinks: false`, so the resolved id realpaths *out* of\n * `node_modules`; and Vite refuses to externalise anything that does not look\n * like it lives there:\n *\n * if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;\n *\n * So every workspace package got compiled into `lib/`. That is not merely\n * wasteful — `linked.backend.storage.js` is loaded from the APP ROOT by a raw\n * Node `import()` and resolves `@_linked/core` through node_modules, so the\n * storage config configured one copy of `LinkedStorage` while the compiled\n * backend queried another. `LinkedStorage`'s routing state is a per-copy\n * static, so the app's single-instance guard refuses to boot. The old `tsc`\n * build never hit this: it emitted bare specifiers and Node converged on one\n * copy. Naming the packages here restores that.\n *\n * `configuredAsExternal` is the one thing that overrides the symlink rule, and\n * it is keyed on exact package names — no regexes.\n */\nexport const workspacePackagesToExternalize = async (\n appRoot: string,\n discover: (\n globs: string[],\n cwd: string\n ) => Promise<{name: string}[]> = async (globs, cwd) => {\n const {discoverWorkspaces} = await import('../vite-config.js');\n return discoverWorkspaces(globs, cwd);\n }\n): Promise<string[]> => {\n const workspaces = await discover([], appRoot);\n return [...new Set(workspaces.map((w) => w.name))].sort();\n};\n\n/**\n * A relative import from `lib/` into `packages/` means a workspace package was\n * compiled in after all.\n *\n * Worth failing the build over rather than leaving to be discovered: the\n * output is perfectly valid JavaScript, and the symptom is the app refusing to\n * boot with a message about storage routing that points nowhere near here.\n */\nexport const findInlinedWorkspaceImports = (source: string): string[] => {\n // Both static `from \"…\"` and dynamic `import(\"…\")`: a lazily imported page\n // can drag a workspace package in on its own, and only the second form\n // appears in the output for it.\n const matches = source.matchAll(\n /(?:from|import)\\s*\\(?\\s*[\"'](\\.[^\"']*\\/packages\\/[^\"']+)[\"']/g\n );\n return [...new Set([...matches].map((m) => m[1]))].sort();\n};\n\nexport const assertNoInlinedWorkspaces = async (\n appRoot: string,\n readFile: (p: string) => Promise<string> = (p) => fs.readFile(p, 'utf8')\n): Promise<void> => {\n // Every entry, not just the backend: `App.js` and `routes.js` reach code the\n // backend never imports, so a package can be inlined through either of them.\n const inlined = new Set<string>();\n for (const name of Object.keys(BACKEND_ENTRIES)) {\n const entryPath = path.join(appRoot, 'lib', `${name}.js`);\n if (!fs.existsSync(entryPath)) continue;\n for (const found of findInlinedWorkspaceImports(await readFile(entryPath))) {\n inlined.add(found);\n }\n }\n if (inlined.size === 0) return;\n\n const named = [...inlined].sort();\n throw new Error(\n 'The compiled backend inlined workspace packages instead of importing ' +\n 'them: ' +\n named.slice(0, 3).join(', ') +\n (named.length > 3 ? `, and ${named.length - 3} more` : '') +\n '. Each one is a second copy of that package, and a second copy of ' +\n '@_linked/core splits LinkedStorage\\'s routing state from the one the ' +\n 'storage config configures. Check that the package is discoverable as a ' +\n 'workspace, so it can be named in ssr.external.'\n );\n};\n\n/**\n * Turn Rollup's unresolved-import error into one that names the actual cause.\n *\n * Externalizing a workspace package means the build now resolves it through\n * its published `exports` — its `lib/`, not its `src/`. A package whose `lib/`\n * is stale therefore fails here, on a file that plainly exists in source.\n * Rollup's own message (\"failed to resolve import X\") sends you looking at the\n * import, which is fine.\n */\nexport const explainUnresolvedWorkspaceImport = (\n message: string,\n externalWorkspaces: string[]\n): string | null => {\n const match = message.match(/failed to resolve import \"([^\"]+)\"/i);\n if (!match) return null;\n const specifier = match[1];\n const pkg = externalWorkspaces.find(\n (name) => specifier === name || specifier.startsWith(`${name}/`)\n );\n if (!pkg) return null;\n return (\n `${message}\\n\\n` +\n `\"${pkg}\" is a workspace package, so a release build resolves it through its ` +\n `published exports — its lib/, not its src/. If this file exists in ` +\n `${pkg}/src but not in its build output, that package's lib/ is stale. ` +\n `Build it first (\\`linked build\\` in the package, or \\`linked build-workspace\\`) ` +\n `and run build-app again.`\n );\n};\n\n/**\n * Strip the client build's `manualChunks` from the SSR output options.\n *\n * Rollup refuses `manualChunks` together with `preserveModules`, and passing\n * `undefined` in the inline config does not remove it — Vite's config merge\n * keeps the app's value. So it is cleared in the output hook instead, after\n * the merge. Chunk grouping is a client concern; the backend wants one output\n * file per source file.\n */\nconst dropManualChunks = () => ({\n name: 'linked:backend-no-manual-chunks',\n enforce: 'post' as const,\n outputOptions(options: Record<string, unknown>) {\n if (!options.manualChunks) return null;\n const {manualChunks: _dropped, ...rest} = options;\n return rest;\n },\n});\n\n/**\n * Compile the app's backend to `lib/`.\n *\n * This runs Vite in SSR mode against the app's own `vite.config`, which is the\n * point: `linked start` already loads `src/backend.ts`, `src/App.tsx` and\n * `src/routes.tsx` through `vite.ssrLoadModule`, so a production build that\n * used anything else was resolving the same source differently from dev. The\n * workspace resolver, the decorator transform and extensionless relative\n * imports all come along for free.\n *\n * `preserveModules` keeps `src/`'s file layout in `lib/`, so the entry paths\n * stay where `serve-app` and `startServer` look for them and lazily imported\n * pages keep their own files. `manualChunks` is cleared because Rollup refuses\n * to run it alongside `preserveModules` — and it is a client-side concern\n * anyway.\n *\n * Workspace packages are named as `ssr.external` explicitly; see\n * `workspacePackagesToExternalize` for why Vite does not do it on its own.\n * Node's built-ins are listed by hand for a related reason: Vite externalises\n * them for SSR only when it recognises the specifier, and a bare `crypto` —\n * which a backend written for Node may perfectly well import — resolved\n * instead to the abandoned `crypto` shim package sitting in node_modules, and\n * failed the build.\n *\n * `copyPublicDir` is off because `public/` is the client build's output, not\n * the backend's. Left on, it copied 38MB of already-built bundles into `lib/`.\n */\nexport const buildBackendWithVite = async (\n options: {appRoot?: string} = {},\n dependencies: {viteBuild?: (config: any) => Promise<unknown>} = {}\n): Promise<void> => {\n const appRoot = options.appRoot || process.cwd();\n const entries = resolveBackendEntries(appRoot);\n\n if (!entries.backend) {\n throw new Error(\n 'No backend entry found: expected src/backend.ts in ' + appRoot\n );\n }\n\n const viteBuild =\n dependencies.viteBuild ||\n (async (config: any) => {\n const {build} = await import('vite');\n return build(config);\n });\n\n const externalWorkspaces = await workspacePackagesToExternalize(appRoot);\n\n try {\n await viteBuild({\n root: appRoot,\n mode: 'production',\n isProduction: true,\n // The client build sets `base` to the release URL. The backend emits no\n // asset URLs of its own, so it must not inherit one.\n base: '/',\n // Never resolve a `development` export condition in a release build.\n //\n // The workspace-source convention is\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // and Vite expands its `development|production` token from NODE_ENV —\n // which during a release build is whatever the app's `.env` says,\n // routinely `development`. The package then resolves to TypeScript, which\n // cannot be externalised because Node could not load it, so it is\n // compiled in regardless of what `ssr.external` says.\n //\n // Dropping the token (rather than pinning it to `production`) leaves\n // `import` — which Vite always appends last — to win. Same treatment\n // `createViteConfig` already applies to a standalone install, for the\n // mirror-image reason.\n //\n // All three lists have to say it: `ssr.resolve.conditions` does not\n // inherit from `resolve.conditions` here, and `externalConditions`\n // governs the packages that end up external.\n resolve: {conditions: SERVER_CONDITIONS},\n ssr: {\n // Merged with the app's own ssr.external rather than replacing it.\n external: externalWorkspaces,\n resolve: {\n conditions: SERVER_CONDITIONS,\n externalConditions: SERVER_CONDITIONS,\n },\n },\n plugins: [dropManualChunks()],\n build: {\n ssr: true,\n outDir: 'lib',\n emptyOutDir: true,\n copyPublicDir: false,\n manifest: false,\n sourcemap: true,\n rollupOptions: {\n input: entries,\n external: NODE_BUILTINS,\n output: {\n format: 'es',\n preserveModules: true,\n preserveModulesRoot: path.join(appRoot, 'src'),\n entryFileNames: '[name].js',\n chunkFileNames: '[name].js',\n },\n },\n },\n });\n } catch (err) {\n const explained = explainUnresolvedWorkspaceImport(\n err instanceof Error ? err.message : String(err),\n externalWorkspaces\n );\n if (!explained) throw err;\n throw new Error(explained);\n }\n\n await assertNoInlinedWorkspaces(appRoot);\n};\n\n/**\n * Copy `src`'s CSS next to the compiled backend.\n *\n * The server reads stylesheets like `lib/css/theme.css` off disk by path, so\n * they have to exist as files whether or not any module imported them.\n */\nexport const copyBackendStylesheets = async (\n appRoot: string,\n listCssFiles: (dir: string) => Promise<string[]>\n): Promise<number> => {\n const sourceFolder = path.join(appRoot, 'src');\n const targetFolder = path.join(appRoot, 'lib');\n const cssFiles = await listCssFiles(sourceFolder);\n await Promise.all(\n cssFiles.map((file) => {\n const targetFile = file.replace(sourceFolder, targetFolder);\n fs.mkdirpSync(path.dirname(targetFile));\n return fs.copyFile(file, targetFile);\n })\n );\n return cssFiles.length;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"build-backend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E,CAAC;QACb,MAAM,SAAS,GAAG,gCAAgC,CAChD,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAChD,kBAAkB,CACnB,CAAC;QACF,IAAI,CAAC,SAAS;YAAE,MAAM,GAAG,CAAC;QAC1B,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC;IAED,MAAM,yBAAyB,CAAC,OAAO,CAAC,CAAC;AAC3C,CAAC,CAAA,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,CACpC,OAAe,EACf,YAAgD,EAC/B,EAAE;IACnB,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC/C,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC/C,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,YAAY,CAAC,CAAC;IAClD,MAAM,OAAO,CAAC,GAAG,CACf,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACpB,MAAM,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;QAC5D,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;QACxC,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACvC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,QAAQ,CAAC,MAAM,CAAC;AACzB,CAAC,CAAA,CAAC","sourcesContent":["import {builtinModules} from 'module';\nimport fs from 'fs-extra';\nimport path from 'path';\n\n/**\n * The backend entry points a compiled app is started from.\n *\n * `serve-app` requires all three on disk and `startServer` imports `lib/App.js`\n * and `lib/routes.js` by those exact paths, so the names are a contract, not a\n * convention.\n */\nconst BACKEND_ENTRIES: Record<string, string[]> = {\n backend: ['src/backend.ts', 'src/backend.tsx'],\n App: ['src/App.tsx', 'src/App.ts'],\n routes: ['src/routes.tsx', 'src/routes.ts'],\n};\n\n/**\n * Vite's default server conditions minus the `development|production` token.\n *\n * See the note at the `resolve` option below: dropping the token is what stops\n * a workspace package resolving to its TypeScript source.\n */\nconst SERVER_CONDITIONS = ['module', 'node'];\n\n/** Both spellings, because a backend may use either. */\nconst NODE_BUILTINS = [\n ...builtinModules,\n ...builtinModules.map((name) => `node:${name}`),\n];\n\nexport const resolveBackendEntries = (\n appRoot: string,\n exists: (p: string) => boolean = fs.existsSync\n): Record<string, string> => {\n const entries: Record<string, string> = {};\n for (const [name, candidates] of Object.entries(BACKEND_ENTRIES)) {\n const found = candidates.find((candidate) =>\n exists(path.join(appRoot, candidate))\n );\n if (found) {\n entries[name] = path.join(appRoot, found);\n }\n }\n return entries;\n};\n\n/**\n * Workspace package names to list as `ssr.external`.\n *\n * Vite will not externalise these on its own, and the reason is worth\n * recording because it is entirely non-obvious. `node_modules/@_linked/core`\n * is a symlink into `packages/core`; Vite resolves package data with\n * `preserveSymlinks: false`, so the resolved id realpaths *out* of\n * `node_modules`; and Vite refuses to externalise anything that does not look\n * like it lives there:\n *\n * if (!configuredAsExternal && !isInNodeModules(resolved.id)) return false;\n *\n * So every workspace package got compiled into `lib/`. That is not merely\n * wasteful — `linked.backend.storage.js` is loaded from the APP ROOT by a raw\n * Node `import()` and resolves `@_linked/core` through node_modules, so the\n * storage config configured one copy of `LinkedStorage` while the compiled\n * backend queried another. `LinkedStorage`'s routing state is a per-copy\n * static, so the app's single-instance guard refuses to boot. The old `tsc`\n * build never hit this: it emitted bare specifiers and Node converged on one\n * copy. Naming the packages here restores that.\n *\n * `configuredAsExternal` is the one thing that overrides the symlink rule, and\n * it is keyed on exact package names — no regexes.\n */\nexport const workspacePackagesToExternalize = async (\n appRoot: string,\n discover: (\n globs: string[],\n cwd: string\n ) => Promise<{name: string}[]> = async (globs, cwd) => {\n const {discoverWorkspaces} = await import('../vite-config.js');\n return discoverWorkspaces(globs, cwd);\n }\n): Promise<string[]> => {\n const workspaces = await discover([], appRoot);\n return [...new Set(workspaces.map((w) => w.name))].sort();\n};\n\n/**\n * A relative import from `lib/` into `packages/` means a workspace package was\n * compiled in after all. One into `node_modules/@_linked/` means an installed\n * framework package was: `lib/node_modules/@_linked/server-utils` is a second\n * `ShapeProvider` class, so the server's `instanceof` check rejects every\n * provider the app exports.\n *\n * Worth failing the build over rather than leaving to be discovered: the\n * output is perfectly valid JavaScript, and the symptom is the app refusing to\n * boot with a message about storage routing that points nowhere near here.\n */\nexport const findInlinedWorkspaceImports = (source: string): string[] => {\n // Both static `from \"…\"` and dynamic `import(\"…\")`: a lazily imported page\n // can drag a workspace package in on its own, and only the second form\n // appears in the output for it.\n const matches = source.matchAll(\n /(?:from|import)\\s*\\(?\\s*[\"'](\\.[^\"']*\\/(?:packages|node_modules\\/@_linked)\\/[^\"']+)[\"']/g\n );\n return [...new Set([...matches].map((m) => m[1]))].sort();\n};\n\nexport const assertNoInlinedWorkspaces = async (\n appRoot: string,\n readFile: (p: string) => Promise<string> = (p) => fs.readFile(p, 'utf8')\n): Promise<void> => {\n // Every entry, not just the backend: `App.js` and `routes.js` reach code the\n // backend never imports, so a package can be inlined through either of them.\n const inlined = new Set<string>();\n for (const name of Object.keys(BACKEND_ENTRIES)) {\n const entryPath = path.join(appRoot, 'lib', `${name}.js`);\n if (!fs.existsSync(entryPath)) continue;\n for (const found of findInlinedWorkspaceImports(await readFile(entryPath))) {\n inlined.add(found);\n }\n }\n if (inlined.size === 0) return;\n\n const named = [...inlined].sort();\n throw new Error(\n 'The compiled backend inlined workspace packages instead of importing ' +\n 'them: ' +\n named.slice(0, 3).join(', ') +\n (named.length > 3 ? `, and ${named.length - 3} more` : '') +\n '. Each one is a second copy of that package, and a second copy of ' +\n '@_linked/core splits LinkedStorage\\'s routing state from the one the ' +\n 'storage config configures. Check that the package is discoverable as a ' +\n 'workspace, so it can be named in ssr.external.'\n );\n};\n\n/**\n * Turn Rollup's unresolved-import error into one that names the actual cause.\n *\n * Externalizing a workspace package means the build now resolves it through\n * its published `exports` — its `lib/`, not its `src/`. A package whose `lib/`\n * is stale therefore fails here, on a file that plainly exists in source.\n * Rollup's own message (\"failed to resolve import X\") sends you looking at the\n * import, which is fine.\n */\nexport const explainUnresolvedWorkspaceImport = (\n message: string,\n externalWorkspaces: string[]\n): string | null => {\n const match = message.match(/failed to resolve import \"([^\"]+)\"/i);\n if (!match) return null;\n const specifier = match[1];\n const pkg = externalWorkspaces.find(\n (name) => specifier === name || specifier.startsWith(`${name}/`)\n );\n if (!pkg) return null;\n return (\n `${message}\\n\\n` +\n `\"${pkg}\" is a workspace package, so a release build resolves it through its ` +\n `published exports — its lib/, not its src/. If this file exists in ` +\n `${pkg}/src but not in its build output, that package's lib/ is stale. ` +\n `Build it first (\\`linked build\\` in the package, or \\`linked build-workspace\\`) ` +\n `and run build-app again.`\n );\n};\n\n/**\n * Strip the client build's `manualChunks` from the SSR output options.\n *\n * Rollup refuses `manualChunks` together with `preserveModules`, and passing\n * `undefined` in the inline config does not remove it — Vite's config merge\n * keeps the app's value. So it is cleared in the output hook instead, after\n * the merge. Chunk grouping is a client concern; the backend wants one output\n * file per source file.\n */\nconst dropManualChunks = () => ({\n name: 'linked:backend-no-manual-chunks',\n enforce: 'post' as const,\n outputOptions(options: Record<string, unknown>) {\n if (!options.manualChunks) return null;\n const {manualChunks: _dropped, ...rest} = options;\n return rest;\n },\n});\n\n/**\n * Compile the app's backend to `lib/`.\n *\n * This runs Vite in SSR mode against the app's own `vite.config`, which is the\n * point: `linked start` already loads `src/backend.ts`, `src/App.tsx` and\n * `src/routes.tsx` through `vite.ssrLoadModule`, so a production build that\n * used anything else was resolving the same source differently from dev. The\n * workspace resolver, the decorator transform and extensionless relative\n * imports all come along for free.\n *\n * `preserveModules` keeps `src/`'s file layout in `lib/`, so the entry paths\n * stay where `serve-app` and `startServer` look for them and lazily imported\n * pages keep their own files. `manualChunks` is cleared because Rollup refuses\n * to run it alongside `preserveModules` — and it is a client-side concern\n * anyway.\n *\n * Workspace packages are named as `ssr.external` explicitly; see\n * `workspacePackagesToExternalize` for why Vite does not do it on its own.\n * Node's built-ins are listed by hand for a related reason: Vite externalises\n * them for SSR only when it recognises the specifier, and a bare `crypto` —\n * which a backend written for Node may perfectly well import — resolved\n * instead to the abandoned `crypto` shim package sitting in node_modules, and\n * failed the build.\n *\n * `copyPublicDir` is off because `public/` is the client build's output, not\n * the backend's. Left on, it copied 38MB of already-built bundles into `lib/`.\n */\nexport const buildBackendWithVite = async (\n options: {appRoot?: string} = {},\n dependencies: {viteBuild?: (config: any) => Promise<unknown>} = {}\n): Promise<void> => {\n const appRoot = options.appRoot || process.cwd();\n const entries = resolveBackendEntries(appRoot);\n\n if (!entries.backend) {\n throw new Error(\n 'No backend entry found: expected src/backend.ts in ' + appRoot\n );\n }\n\n const viteBuild =\n dependencies.viteBuild ||\n (async (config: any) => {\n const {build} = await import('vite');\n return build(config);\n });\n\n const externalWorkspaces = await workspacePackagesToExternalize(appRoot);\n\n try {\n await viteBuild({\n root: appRoot,\n mode: 'production',\n isProduction: true,\n // The client build sets `base` to the release URL. The backend emits no\n // asset URLs of its own, so it must not inherit one.\n base: '/',\n // Never resolve a `development` export condition in a release build.\n //\n // The workspace-source convention is\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // and Vite expands its `development|production` token from NODE_ENV —\n // which during a release build is whatever the app's `.env` says,\n // routinely `development`. The package then resolves to TypeScript, which\n // cannot be externalised because Node could not load it, so it is\n // compiled in regardless of what `ssr.external` says.\n //\n // Dropping the token (rather than pinning it to `production`) leaves\n // `import` — which Vite always appends last — to win. Same treatment\n // `createViteConfig` already applies to a standalone install, for the\n // mirror-image reason.\n //\n // All three lists have to say it: `ssr.resolve.conditions` does not\n // inherit from `resolve.conditions` here, and `externalConditions`\n // governs the packages that end up external.\n resolve: {conditions: SERVER_CONDITIONS},\n ssr: {\n // Merged with the app's own ssr.external rather than replacing it.\n external: externalWorkspaces,\n resolve: {\n conditions: SERVER_CONDITIONS,\n externalConditions: SERVER_CONDITIONS,\n },\n },\n plugins: [dropManualChunks()],\n build: {\n ssr: true,\n outDir: 'lib',\n emptyOutDir: true,\n copyPublicDir: false,\n manifest: false,\n sourcemap: true,\n rollupOptions: {\n input: entries,\n external: NODE_BUILTINS,\n output: {\n format: 'es',\n preserveModules: true,\n preserveModulesRoot: path.join(appRoot, 'src'),\n entryFileNames: '[name].js',\n chunkFileNames: '[name].js',\n },\n },\n },\n });\n } catch (err) {\n const explained = explainUnresolvedWorkspaceImport(\n err instanceof Error ? err.message : String(err),\n externalWorkspaces\n );\n if (!explained) throw err;\n throw new Error(explained);\n }\n\n await assertNoInlinedWorkspaces(appRoot);\n};\n\n/**\n * Copy `src`'s CSS next to the compiled backend.\n *\n * The server reads stylesheets like `lib/css/theme.css` off disk by path, so\n * they have to exist as files whether or not any module imported them.\n */\nexport const copyBackendStylesheets = async (\n appRoot: string,\n listCssFiles: (dir: string) => Promise<string[]>\n): Promise<number> => {\n const sourceFolder = path.join(appRoot, 'src');\n const targetFolder = path.join(appRoot, 'lib');\n const cssFiles = await listCssFiles(sourceFolder);\n await Promise.all(\n cssFiles.map((file) => {\n const targetFile = file.replace(sourceFolder, targetFolder);\n fs.mkdirpSync(path.dirname(targetFile));\n return fs.copyFile(file, targetFile);\n })\n );\n return cssFiles.length;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-config.d.ts","sourceRoot":"","sources":["../../src/vite-config.ts"],"names":[],"mappings":"AAWA,OAAO,EAAC,YAAY,EAAC,MAAM,MAAM,CAAC;AAMlC,OAAO,KAAK,EAAC,MAAM,EAAa,MAAM,MAAM,CAAC;AAuB7C;;;;;;;;;;;;;;;GAeG;AACH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB,GAAI,IAAI,MA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c,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED,UAAU,cAAc;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAwCD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,mBAAmB,CACvC,UAAU,EAAE;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAC,EAAE,EAC7C,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,MAAM,EAAE,CAAC,CAsEnB;AAoBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,gCAAgC,CACpD,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,cAAc,EAAE,CAAC,CAmC3B;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CACtC,UAAU,GAAE,MAAM,EAAO,EACzB,GAAG,GAAE,MAAsB,GAC1B,OAAO,CAAC,cAAc,EAAE,CAAC,CAyD3B;AAwCD;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC3B,UAAU,EAAE;IAAC,IAAI,EAAE,MAAM,CAAA;CAAC,EAAE,EAC5B,UAAU,GAAE,MAAM,EAAO,GACxB,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAGrB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAC1B,IAAI,GAAE,IAAI,CAAC,uBAAuB,EAAE,QAAQ,GAAG,MAAM,CAAM,GAC1D,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAED,wBAAgB,gBAAgB,CAAC,IAAI,GAAE,uBAA4B,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CA8WpG"}
|
package/lib/esm/vite-config.js
CHANGED
|
@@ -731,7 +731,16 @@ export function createViteConfig(opts = {}) {
|
|
|
731
731
|
// a SECOND Node-loaded core and split the shape registry. Installed packages
|
|
732
732
|
// that depend on a workspace (e.g. published fuseki when core itself is a
|
|
733
733
|
// workspace) are bundled too, so they import the Vite-loaded workspace.
|
|
734
|
-
|
|
734
|
+
//
|
|
735
|
+
// NOT DEV (a release build of the backend): nothing is force-bundled. The
|
|
736
|
+
// compiled backend is loaded by Node next to the installed
|
|
737
|
+
// `@_linked/server`, so every framework package has to stay a bare import
|
|
738
|
+
// that resolves to that same node_modules copy. `workspaces` is always
|
|
739
|
+
// empty here, and handing that to `ssrNoExternal` used to select the
|
|
740
|
+
// standalone list — which compiled a private `server-utils` into `lib/`,
|
|
741
|
+
// so no app provider was `instanceof` the server's `ShapeProvider` and
|
|
742
|
+
// `LinkedServer` dropped them all ("exports two generic backend providers").
|
|
743
|
+
noExternal: isDev ? ssrNoExternal(workspaces, yield workspaceDependents(workspaces)) : [] }, (isStandalone
|
|
735
744
|
? { resolve: { conditions: ['module', 'node'] } }
|
|
736
745
|
: {})),
|
|
737
746
|
// Client-only, deliberately: these go on the `client` environment, not the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite-config.js","sourceRoot":"","sources":["../../src/vite-config.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oEAAoE;AACpE,EAAE;AACF,+CAA+C;AAC/C,EAAE;AACF,wDAAwD;AACxD,wEAAwE;AACxE,EAAE;AACF,mEAAmE;AACnE,qEAAqE;AACrE,uEAAuE;AACvE,qEAAqE;AACrE,OAAO,EAAC,YAAY,EAAC,MAAM,MAAM,CAAC;AAClC,OAAO,KAAK,MAAM,sBAAsB,CAAC;AACzC,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAC,kBAAkB,EAAC,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAC,sBAAsB,EAAE,sBAAsB,EAAC,MAAM,sBAAsB,CAAC;AAGpF;;;;;;;;;GASG;AACH,MAAM,sBAAsB,GAAa,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;AACpE,MAAM,cAAc,GAAG,CAAC,IAAY,EAAW,EAA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MAAM,cAAc,GAAG,MAAA,QAAQ,CAAC,OAAO,mCAAI,QAAQ,CAAC;gBACnD,MAAM,CAAC,OAAoB,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,CAAC;YACtD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,IAAI,CACV,4DAA4D;oBAC1D,gEAAgE;oBAChE,sDAAsD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Vite config helper for linked apps. The one dev + build pipeline.\n//\n// Apps use this from their own vite.config.ts:\n//\n// import {createViteConfig} from '@_linked/cli/vite';\n// export default createViteConfig({port: 4040, cssMode: 'tailwind'});\n//\n// The helper preserves the dev-mode `generateScopedName` (readable\n// `_packageName_filename_className`) so CSS module class names match\n// what the previous bundler chain produced for trace/debug. Production\n// uses Vite's default scoping (content-hash, equivalent uniqueness).\nimport {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fsExtra from 'fs-extra';\nimport path from 'node:path';\nimport {generateScopedName} from './utils.js';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from './workspace-globs.js';\nimport type {Plugin, UserConfig} from 'vite';\n\n/**\n * Framework packages that MUST be single-instance per runtime — they hold\n * module-level state (`@_linked/core`'s shape registry, `LinkedStorage`, the query\n * context) or register shapes into it. Two copies in one runtime split that state\n * and mangle shape identity (`Person`→`Person2`). This ONE list is the single source\n * of truth for the standalone `optimizeDeps.exclude` (`linkedDeps`). In workspace mode\n * `ssr.noExternal` is keyed on the discovered source workspaces instead (see\n * `ssrNoExternal`), so published framework packages stay external and single-instance\n * under Node.\n */\nconst FRAMEWORK_PKG_PATTERNS: RegExp[] = [/^@_linked\\//, /^lincd-/];\nconst isFrameworkPkg = (name: string): boolean =>\n FRAMEWORK_PKG_PATTERNS.some((re) => re.test(name));\n\n/** Default dev server port, and Vite's default HMR websocket port. */\nconst DEFAULT_DEV_PORT = 4040;\nconst DEFAULT_HMR_PORT = 24678;\n/** Vite may not bind below 1024 without privileges; 65535 is the TCP ceiling. */\nconst MIN_HMR_PORT = 1024;\nconst MAX_HMR_PORT = 65535;\n\n/**\n * Derive an app's HMR websocket port from its dev port.\n *\n * Every `createViteConfig` app used to fall back to Vite's shared default\n * 24678, so any two dev servers running at once collided (\"Port 24678 is\n * already in use\") and HMR silently broke for the loser. Offsetting the HMR\n * port by the same amount the dev port is offset from its default keeps the\n * derivation trivial and means apps that already run on distinct dev ports get\n * distinct HMR ports for free.\n *\n * The input is untrusted (`process.env.PORT` is an arbitrary string), so\n * anything that is not a whole port number — `PORT=abc` yielding `NaN`, a\n * negative or out-of-range value — falls back to the dev port default. The\n * result is then clamped into the bindable range, since a far-out dev port\n * would otherwise derive an HMR port past 65535.\n */\n/**\n * Which manual chunk a module belongs in.\n *\n * Split large/common deps so route chunks don't all carry their own copy AND\n * the main entry doesn't end up at 5MB+. Each chunk becomes its own\n * `assets/<name>-<hash>.js` the browser caches independently — incremental\n * dev builds and cache wins on prod deploys both improve.\n *\n * Exported so the grouping can be asserted directly: getting it wrong does not\n * fail the build, it produces a bundle that throws on load in the browser.\n */\nexport const chunkForModuleId = (id: string): string | undefined => {\n if (!id.includes('node_modules')) {\n // Linked workspaces ship as @_linked/* / lincd-* — group all\n // linked-framework code into a single chunk.\n if (\n id.includes('/packages/core/') ||\n id.includes('/packages/react/') ||\n id.includes('/packages/server-utils/') ||\n id.includes('/packages/primitives/') ||\n id.includes('/packages/css/') ||\n /\\/packages\\/(auth|org|schema|fuseki|owl|xsd|dcat|dcmi|s3|sentry|ui)\\//.test(id)\n ) {\n return 'linked';\n }\n return undefined;\n }\n // Framework code installed from the registry rather than resolved to a\n // workspace. An app can hold both at once — a published `@_linked/server`\n // in node_modules next to workspace `@_linked/core` — and the two import\n // each other. Split across `linked` and `vendor` that is a cycle, and\n // Rollup's chosen order left a binding in its temporal dead zone:\n // `Cannot access 'Wo' before initialization` before the app rendered.\n // Same chunk, no cycle.\n if (/[\\\\/]node_modules[\\\\/](@_linked[\\\\/]|lincd-)/.test(id)) {\n return 'linked';\n }\n // React + React-DOM in their own chunk — every route uses them.\n //\n // react-router and @remix-run/router belong here too. Left in `vendor` they\n // made the two chunks import each other: react-router-dom re-exports\n // react-router, so react-vendor imported vendor, while vendor's own\n // top-level `React.createContext(...)` calls imported react-vendor. Rollup\n // has to pick an order for a cycle, and it ran vendor first — every\n // production build died on load with \"Cannot read properties of undefined\n // (reading 'createContext')\".\n if (\n /[\\\\/]node_modules[\\\\/](react|react-dom|react-router-dom|react-router|@remix-run[\\\\/]router|scheduler)[\\\\/]/.test(\n id\n )\n ) {\n return 'react-vendor';\n }\n // Heavy editor deps — only loaded on pages that need them, but worth\n // isolating so they don't get pulled into main.\n if (/[\\\\/]node_modules[\\\\/]@monaco-editor[\\\\/]/.test(id)) {\n return 'monaco';\n }\n // Charting/visualization\n if (/[\\\\/]node_modules[\\\\/](recharts|react-flow|@xyflow|d3-)[\\\\/]/.test(id)) {\n return 'viz';\n }\n // Animation\n if (/[\\\\/]node_modules[\\\\/]framer-motion[\\\\/]/.test(id)) {\n return 'motion';\n }\n // Catch-all for other node_modules in a vendor chunk\n return 'vendor';\n};\n\nexport function hmrPortFor(devPort: unknown): number {\n const parsed = Number(devPort);\n const validDevPort =\n Number.isFinite(parsed) && Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535\n ? parsed\n : DEFAULT_DEV_PORT;\n const derived = DEFAULT_HMR_PORT + (validDevPort - DEFAULT_DEV_PORT);\n return Math.min(MAX_HMR_PORT, Math.max(MIN_HMR_PORT, derived));\n}\n\nexport interface LinkedViteConfigOptions {\n /** Dev server port. Default 4040. */\n port?: number;\n /** Output dir for `vite build`. Default `public/bundles`. */\n outDir?: string;\n /** CSS pipeline mode. */\n cssMode?: 'tailwind' | 'css-modules-only';\n /** Entry file for the client bundle. Default `src/index.tsx`. */\n entry?: string;\n /** Extra Vite plugins. */\n plugins?: Plugin[];\n /** Extra PostCSS plugins (e.g. `postcss-media-to-container`). */\n postcssPlugins?: unknown[];\n /**\n * Extra `define` entries for the CLIENT environment only (used to bridge\n * `process.env.X` refs into the browser). Never applied server-side.\n */\n define?: Record<string, string>;\n /**\n * Extra workspace globs (trailing `/*`, or a direct package dir) resolved\n * RELATIVE TO the app's cwd, in ADDITION to the app's own `workspaces` field.\n *\n * For apps whose linked-package sources live OUTSIDE their own workspace tree\n * — e.g. an app consumes `packages/lincd.org/modules/*`, which sit one level\n * up (`../lincd.org/modules/*`) when the app runs inside the CN monorepo, and under\n * `packages/lincd.org/modules/*` when the app runs from its own root. Pass BOTH\n * candidate layouts; only globs whose parent dir actually exists are scanned,\n * so the same config works in either checkout. Each glob's packages are\n * registered as source workspaces (resolved to `src/` for HMR + single-instance),\n * exactly like the app's own `workspaces` field.\n */\n workspaceGlobs?: string[];\n}\n\ninterface WorkspaceEntry {\n name: string;\n srcDir: string;\n}\n\n// Resolve a dependency name to its installed package.json the way Node does:\n// look in `<dir>/node_modules/<name>`, then each parent directory's\n// node_modules, starting from the requiring package's directory. This finds\n// deps that npm/yarn workspaces HOISTED to the monorepo root (an app under\n// `services/api` whose dep lives in `<root>/node_modules`). The walk stops\n// after the nearest directory whose package.json declares `workspaces` (the\n// workspace root), or at the filesystem root. Returns null when the package\n// isn't installed (e.g. an optional dep) — we skip rather than throw.\nasync function isWorkspaceRoot(dir: string): Promise<boolean> {\n try {\n const json = await fsExtra.readJson(path.join(dir, 'package.json'));\n return !!json.workspaces;\n } catch {\n return false;\n }\n}\n\nasync function readInstalledPkg(\n name: string,\n fromDir: string,\n): Promise<{root: string; json: any} | null> {\n let dir = path.resolve(fromDir);\n while (true) {\n const root = path.join(dir, 'node_modules', name);\n const pkgJson = path.join(root, 'package.json');\n if (await fsExtra.pathExists(pkgJson)) {\n try {\n return {root, json: await fsExtra.readJson(pkgJson)};\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir || (await isWorkspaceRoot(dir))) return null;\n dir = parent;\n }\n}\n\n/**\n * Names of installed packages that depend, directly or transitively (via\n * `dependencies` / `peerDependencies`), on a discovered source workspace. Such a\n * package must also go through Vite SSR: if Node loaded it natively, it would\n * import its own Node-loaded copy of the workspace (e.g. published\n * `@_linked/fuseki` importing a workspace `@_linked/core`), splitting module\n * state. Vite rewrites the dynamic `import()` in code it transforms, so bundling\n * the dependents keeps one instance.\n *\n * Only the dependency closure of the app's `package.json` (dependencies +\n * devDependencies) and of the workspaces themselves is scanned. Packages are\n * resolved Node-style, keyed by real path, and unresolvable ones are ignored.\n * Workspace names are not included in the result.\n */\nexport async function workspaceDependents(\n workspaces: {name: string; srcDir?: string}[],\n cwd: string = process.cwd(),\n): Promise<string[]> {\n if (workspaces.length === 0) return [];\n const fs = await import('node:fs/promises');\n const wsNames = new Set(workspaces.map((w) => w.name));\n // realRoot -> {name, deps (realRoots)}\n const nodes = new Map<string, {name: string; deps: Set<string>}>();\n const realpath = async (p: string): Promise<string> => {\n try {\n return await fs.realpath(p);\n } catch {\n return path.resolve(p);\n }\n };\n\n const visit = async (root: string, json: any): Promise<string> => {\n const real = await realpath(root);\n if (nodes.has(real)) return real;\n const node = {name: json.name as string, deps: new Set<string>()};\n nodes.set(real, node);\n const names = new Set([\n ...Object.keys(json.dependencies ?? {}),\n ...Object.keys(json.peerDependencies ?? {}),\n ]);\n for (const dep of names) {\n const resolved = await readInstalledPkg(dep, real);\n if (resolved) node.deps.add(await visit(resolved.root, resolved.json));\n }\n return real;\n };\n\n // Seed: the app's direct deps, plus each workspace package's own deps.\n try {\n const appPkg = await fsExtra.readJson(path.join(cwd, 'package.json'));\n for (const dep of Object.keys({...appPkg.dependencies, ...appPkg.devDependencies})) {\n const resolved = await readInstalledPkg(dep, cwd);\n if (resolved) await visit(resolved.root, resolved.json);\n }\n } catch {}\n for (const ws of workspaces) {\n if (!ws.srcDir) continue;\n const root = path.dirname(ws.srcDir);\n try {\n await visit(root, await fsExtra.readJson(path.join(root, 'package.json')));\n } catch {}\n }\n\n // Walk reverse edges from every workspace node: everything reached depends on one.\n const dependentsOf = new Map<string, string[]>();\n for (const [key, node] of nodes) {\n for (const dep of node.deps) {\n if (!dependentsOf.has(dep)) dependentsOf.set(dep, []);\n dependentsOf.get(dep)!.push(key);\n }\n }\n const queue = [...nodes].filter(([, n]) => wsNames.has(n.name)).map(([k]) => k);\n const marked = new Set(queue);\n while (queue.length) {\n for (const parent of dependentsOf.get(queue.pop()!) ?? []) {\n if (!marked.has(parent)) {\n marked.add(parent);\n queue.push(parent);\n }\n }\n }\n const out = new Set<string>();\n for (const key of marked) {\n const name = nodes.get(key)!.name;\n if (name && !wsNames.has(name)) out.add(name);\n }\n return [...out].sort();\n}\n\n/**\n * Read a package root as a SOURCE install: `{name, srcDir}` iff it has a\n * package.json with a name and ships a `src/` dir. Published packages have only\n * `lib/` and are skipped — they resolve via their exports.\n */\nasync function readSourcePackage(root: string): Promise<WorkspaceEntry | null> {\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return null;\n const srcDir = path.join(root, 'src');\n if (!(await fsExtra.pathExists(srcDir))) return null;\n try {\n const json = await fsExtra.readJson(pkgPath);\n return json.name ? {name: json.name, srcDir} : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Linked packages installed as SOURCE, found by walking the app's\n * `dependencies` + `devDependencies` (and recursing through the `dependencies`\n * of each linked package found), keeping those marked `\"linkedPackage\": true`\n * — the same marker the CLI keys on (see cli-methods.ts) — and registering the\n * ones that ship `src/`.\n *\n * A dep ships `src/` when it is a symlinked workspace clone, a `link:`/`portal:`\n * dev install, or a LOCALIZED checkout (`packages-local/<pkg>`, in no workspace\n * glob). That's what lets a STANDALONE app (not itself a workspace root — e.g. a\n * per-branch clone under /apps) resolve a linked package's `.tsx` sources with\n * extension probing, instead of falling through to the package's\n * `development → ./src/*.ts` export (which misses `.tsx` like LinkedServer). A\n * prod/ejected app installs PUBLISHED packages (no `src/`) → not registered,\n * resolved via each package's `lib`.\n *\n * The marker — NOT the npm scope — drives discovery, so a user's own\n * custom-scope published linked package (e.g. `@acme/foo` with\n * `linkedPackage:true`) is picked up too, and linked packages present in\n * node_modules but not depended upon are ignored.\n *\n * Every root is REALPATHED before it is registered: `readInstalledPkg` returns\n * the `node_modules/<name>` symlink spelling, and Vite's resolver realpaths\n * every id it produces, so registering the symlink would give one file two\n * module ids — two instances of the same module.\n *\n * Shared by the Vite resolver table (`discoverWorkspaces`) and the `linked start`\n * HMR watch set, so the two cannot disagree about what is source.\n */\nexport async function discoverLinkedSourceDependencies(\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const pkgPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return [];\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n const walk = async (\n deps: Record<string, string> | undefined,\n fromDir: string,\n ): Promise<void> => {\n for (const name of Object.keys(deps ?? {})) {\n if (visited.has(name)) continue;\n visited.add(name);\n const resolved = await readInstalledPkg(name, fromDir);\n if (!resolved) continue;\n if (resolved.json.linkedPackage !== true) continue;\n let realRoot = resolved.root;\n try {\n realRoot = await fs.realpath(resolved.root);\n } catch {}\n const entry = await readSourcePackage(realRoot);\n if (entry && !seen.has(entry.name)) {\n seen.add(entry.name);\n out.push(entry);\n }\n // Recurse from the real location, so a symlinked clone resolves its own\n // dependencies from its source dir.\n await walk(resolved.json.dependencies, realRoot);\n }\n };\n const appPkg = await fsExtra.readJson(pkgPath);\n await walk(appPkg.dependencies, cwd);\n await walk(appPkg.devDependencies, cwd);\n return out;\n}\n\n/**\n * Walk the app's package.json `workspaces` field to build a lookup table\n * from npm name → absolute src/ directory. Used by the resolver plugin\n * to map bare specifiers like `@_linked/foo/bar` directly to source.\n *\n * Positive patterns are expanded by directory listing, so only a trailing `/*`\n * is honoured. NEGATED patterns (`\"!packages/core\"`) are honoured in full, with\n * npm's semantics — see ./workspace-globs.js. Skipping them would resolve a\n * package to an excluded directory that the package manager never installed\n * dependencies for.\n */\nexport async function discoverWorkspaces(\n extraGlobs: string[] = [],\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n // Register a package root iff it ships a `src/` dir (source install).\n const addFromRoot = async (root: string): Promise<void> => {\n const entry = await readSourcePackage(root);\n if (!entry || seen.has(entry.name)) return;\n seen.add(entry.name);\n out.push(entry);\n };\n\n // 1. The app's own `workspaces` globs — the monorepo-root case (CN, or any app\n // that is itself a workspace root). Only trailing `/*` patterns.\n const pkgPath = path.join(cwd, 'package.json');\n if (await fsExtra.pathExists(pkgPath)) {\n const pkg = await fsExtra.readJson(pkgPath);\n // Merge the app's own `workspaces` globs with any caller-supplied\n // `workspaceGlobs` (e.g. `../lincd.org/modules/*`). Non-existent parents\n // are skipped below, so passing both nested + standalone layouts is safe.\n // Either list may carry negations, so they are parsed together.\n const {patterns, negatedPatterns} = parseWorkspacePatterns([\n ...(Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? []),\n ...extraGlobs,\n ]);\n const addUnlessNegated = async (root: string): Promise<void> => {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) return;\n await addFromRoot(root);\n };\n for (const pattern of patterns) {\n const m = pattern.match(/^(.+?)\\/\\*$/);\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n for (const ent of await fs.readdir(parent, {withFileTypes: true})) {\n if (ent.isDirectory() || ent.isSymbolicLink()) {\n await addUnlessNegated(path.join(parent, ent.name));\n }\n }\n }\n } else {\n await addUnlessNegated(path.join(cwd, pattern));\n }\n }\n }\n\n // 2. Linked deps installed as source — including a localized checkout that is\n // in no workspace glob. Shared with the `linked start` watch set; see\n // discoverLinkedSourceDependencies above. Glob entries win on a name clash.\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (seen.has(entry.name)) continue;\n seen.add(entry.name);\n out.push(entry);\n }\n\n return out;\n}\n\n/**\n * Resolve a bare specifier like `@_linked/foo/bar`, `lincd-rdfs/Foo`, or\n * `pkg/utils/Bar.js` against the workspace lookup. Tries extensions in\n * order: .ts, .tsx, then the literal id (for files that already include\n * an extension or for non-TS assets). Returns null when the specifier\n * doesn't match any workspace package or no candidate exists on disk.\n */\nasync function resolveWorkspaceSpecifier(\n specifier: string,\n workspaces: WorkspaceEntry[],\n): Promise<string | null> {\n for (const ws of workspaces) {\n if (specifier === ws.name) {\n for (const ext of ['index.ts', 'index.tsx']) {\n const p = path.join(ws.srcDir, ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n return null;\n }\n if (specifier.startsWith(ws.name + '/')) {\n const subpath = specifier.slice(ws.name.length + 1);\n // Strip .js/.jsx suffix — workspace src uses TS published-output\n // convention (./Sibling.js) but we want the TS source.\n const base = subpath.replace(/\\.jsx?$/, '');\n for (const ext of ['.tsx', '.ts']) {\n const p = path.join(ws.srcDir, base + ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n // Files that already include an extension Vite handles (.css, .json,\n // .svg, etc.) — return the literal path under src.\n const literal = path.join(ws.srcDir, subpath);\n if (await fsExtra.pathExists(literal)) return literal;\n return null;\n }\n }\n return null;\n}\n\n/**\n * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those\n * package names are bundled by Vite; everything else in node_modules (including\n * published `@_linked/*`) is externalized to Node. Vite matches these entries\n * against the bare package name, so subpath imports (`pkg/shapes/Foo`) match too.\n * Installed packages that depend on a workspace (`dependents`, from\n * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.\n * Standalone (no workspaces): the context-holding framework packages are bundled.\n */\nexport function ssrNoExternal(\n workspaces: {name: string}[],\n dependents: string[] = [],\n): (string | RegExp)[] {\n if (workspaces.length === 0) return [/^@_linked\\/server-utils$/, /^@_linked\\/react$/];\n return [...new Set([...workspaces.map((w) => w.name), ...dependents])];\n}\n\n/**\n * The `process.env.*` values inlined into the browser bundle — and only there.\n * See the `environments.client.define` note in `createViteConfig` for why the\n * server environment must not receive them.\n */\nexport function clientDefine(\n opts: Pick<LinkedViteConfigOptions, 'define' | 'port'> = {},\n): Record<string, string> {\n return {\n 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),\n 'process.env.SITE_ROOT': JSON.stringify(\n process.env.SITE_ROOT ?? `http://localhost:${process.env.PORT ?? opts.port ?? 4040}`,\n ),\n // The app's display name, so client components (e.g. the header) can read it\n // like the SSR <title> does (server-utils Html reads process.env.APP_NAME). The\n // browser has no `process`, so inline it; falls back to a generic label when\n // unset so a bare checkout never renders `undefined`.\n 'process.env.APP_NAME': JSON.stringify(process.env.APP_NAME ?? 'Linked App'),\n ...(opts.define ?? {}),\n };\n}\n\nexport function createViteConfig(opts: LinkedViteConfigOptions = {}): ReturnType<typeof defineConfig> {\n return defineConfig(async ({mode}) => {\n const isDev = mode === 'development';\n const workspaces = isDev ? await discoverWorkspaces(opts.workspaceGlobs) : [];\n // STANDALONE = dev mode with no source-shipping workspaces discovered\n // (an app installed from npm outside the monorepo — its `@_linked/*` /\n // `lincd-*` deps are lib-only). discoverWorkspaces() only registers\n // packages that ship `src/` on disk, so `length === 0` is the exact\n // standalone signal used elsewhere in this file. In WORKSPACE mode\n // (CN monorepo or its workspace-member clones) this is false and none\n // of the standalone-gated branches below apply.\n const isStandalone = isDev && workspaces.length === 0;\n\n // The app's published framework deps — excluded from Vite's dep-optimizer below\n // (`optimizeDeps.exclude`) so the browser's native ESM graph loads ONE copy of each.\n // Without the exclude, esbuild inlines a duplicate `@_linked/core` into each\n // per-subpath chunk (`@_linked_schema_shapes_Person.js`,\n // `@_linked_core_utils_LinkedStorage.js`, …), duplicating framework classes\n // (`Person` → `Person2`/`3`), so their shapes register under mangled URIs that no\n // longer match the backend's (one clean copy via Node). These packages are ESM with\n // no bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // native-ESM serving needs no interop shim.\n const linkedDeps: string[] = [];\n if (isStandalone) {\n try {\n const appPkg = await fsExtra.readJson(path.join(process.cwd(), 'package.json'));\n const allDeps = {...appPkg.dependencies, ...appPkg.devDependencies};\n for (const name of Object.keys(allDeps)) {\n if (isFrameworkPkg(name)) linkedDeps.push(name);\n }\n } catch {\n /* best-effort — no package.json is fine */\n }\n }\n const config: UserConfig = {\n server: {\n port: opts.port ?? 4040,\n middlewareMode: true,\n // Unique HMR websocket port per app/worktree (PORT env override wins,\n // else opts.port) — see `hmrPortFor`. Apps can still override this with\n // their own `server.hmr` in mergeConfig.\n hmr: {port: hmrPortFor(process.env.PORT ?? opts.port)},\n },\n build: {\n outDir: opts.outDir ?? 'public/bundles',\n manifest: true,\n // Bump chunk-size warning so it doesn't fire on every build for\n // the linked vendor bundle. Real chunking happens via\n // manualChunks below.\n chunkSizeWarningLimit: 1000,\n rollupOptions: {\n input: opts.entry ?? 'src/index.tsx',\n output: {\n entryFileNames: 'assets/[name]-[hash].js',\n chunkFileNames: 'assets/[name]-[hash].js',\n assetFileNames: 'assets/[name]-[hash][extname]',\n manualChunks: chunkForModuleId,\n },\n },\n sourcemap: true,\n },\n plugins: [\n // Direct workspace specifier resolver.\n //\n // The package.json `\"./*\": { \"development\": \"./src/*.ts\" }` wildcard\n // can't express \"try .ts, fall back to .tsx\" (Node's exports spec\n // resolves to a single literal path). For React-heavy packages like\n // @_linked/primitives, @_linked/server-utils, and @_linked/auth,\n // most files are .tsx — the wildcard fails before any Vite plugin\n // gets a chance to fix it up.\n //\n // This plugin intercepts BARE workspace specifiers like\n // `@_linked/foo/bar` and `pkg-name/utils/Baz.js` BEFORE Vite's\n // package.json resolver runs, mapping them straight to source with\n // proper extension fallback (.tsx → .ts → literal). It also covers\n // the `./Sibling.js` published-output convention for imports made\n // from within workspace `src/` trees.\n isDev\n ? ({\n name: 'linked:resolve-workspace-ts',\n enforce: 'pre',\n async resolveId(id, importer) {\n if (id.startsWith('\\0')) return null;\n\n // Workspace-internal `./Sibling.js` → `.tsx` / `.ts` rewrite.\n if (\n importer &&\n importer.includes(`${path.sep}packages${path.sep}`) &&\n /\\.(jsx?)$/.test(id) &&\n (id.startsWith('.') || id.startsWith('/'))\n ) {\n const importerDir = path.dirname(importer);\n const base = path.resolve(importerDir, id);\n for (const ext of ['.tsx', '.ts']) {\n const candidate = base.replace(/\\.jsx?$/, ext);\n if (await fsExtra.pathExists(candidate)) return candidate;\n }\n }\n\n // Bare workspace specifier — resolve directly to src/.\n if (\n !id.startsWith('.') &&\n !id.startsWith('/') &&\n workspaces.length > 0\n ) {\n const resolved = await resolveWorkspaceSpecifier(id, workspaces);\n if (resolved) return resolved;\n }\n\n // STANDALONE (no workspaces): the linked packages are installed\n // from npm as lib-only (no `src`). We DON'T intercept them here —\n // instead the standalone `resolve.conditions` / `ssr.resolve.conditions`\n // (set on the config below, dropping Vite's `development` token)\n // let Vite's normal resolver pick each package's `import → lib/esm`\n // export. Bundling those lib files through the SSR runner works\n // (they're plain ESM); marking them external instead would leave a\n // bare specifier that `vite.ssrLoadModule` can't load\n // (\"Failed to load url @_linked/server/shapes/LinkedServer\").\n\n return null;\n },\n } as Plugin)\n : null,\n react({\n babel: {\n parserOpts: {\n plugins: ['decorators-legacy', 'classProperties'],\n },\n },\n }),\n // Dev-only: log every file the watcher sees change. Without this,\n // backend edits look silent (no JS rebuild step, no Node restart)\n // and it's hard to tell whether\n // Vite picked up the change at all.\n isDev\n ? ({\n name: 'linked:reload-log',\n configureServer(server) {\n server.watcher.on('change', (file) => {\n const rel = file.replace(process.cwd() + '/', '');\n console.log(`[linked] reloaded ${rel}`);\n });\n },\n } as Plugin)\n : null,\n ...(opts.plugins ?? []),\n ].filter(Boolean) as Plugin[],\n css: {\n modules: {\n generateScopedName: isDev ? generateScopedName : undefined,\n },\n postcss: opts.postcssPlugins\n ? {plugins: opts.postcssPlugins as any}\n : undefined,\n },\n esbuild: {\n tsconfigRaw: {\n compilerOptions: {\n experimentalDecorators: true,\n },\n },\n jsx: 'automatic',\n // A shape's IRI is built from its class name —\n // `getNodeShapeUri(packageName, constructor.name)` — so a minifier that\n // renames the class changes the shape's identity. In a production build\n // the client would ask the server for\n // `https://linked.cm/shape/server/za` while the server had registered\n // `.../BackendAPIStore`, and every Server.call on that shape 501'd.\n // The same mangling made registration report `Shape undefined does not\n // extend base class`.\n keepNames: true,\n },\n // STANDALONE resolve conditions.\n //\n // The published `@_linked/*` / `lincd-*` packages export\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // In dev, Vite expands its special `development|production` condition\n // token to `development`, so it resolves these to `./src/*.ts` — which\n // doesn't exist in a lib-only npm install → boot crash\n // (\"Failed to load @_linked/server/shapes/LinkedServer\").\n //\n // Dropping the dev/prod token from the condition list means Vite never\n // adds `development`; `import` (always appended last by Vite) wins, so\n // these packages resolve to `./lib/esm/*.js`. We start from Vite's\n // default SERVER conditions (`module`, `node`, `development|production`)\n // minus the dev/prod token. This governs BOTH the plugin pipeline\n // (`resolve.conditions`) and the SSR module runner used by\n // `ssrLoadModule('@_linked/server/shapes/LinkedServer')` in\n // commands/start.ts (`ssr.resolve.conditions`).\n //\n // WORKSPACE-GATED: only applied standalone. In monorepo dev the packages\n // ship `src`, and we WANT `development → src` for HMR — so we leave\n // conditions at Vite's defaults there (undefined = untouched), keeping\n // CN dev byte-for-byte unchanged.\n ...(isStandalone\n ? {\n resolve: {\n conditions: ['module', 'node'],\n // Dedupe the context-holding packages so the two `ssrLoadModule` loads\n // (LinkedServer + the app graph) resolve to ONE `server-utils`/`react`\n // instance — otherwise their `AppContext` objects differ and\n // `useAppContext()` returns null. Pairs with `ssr.noExternal` below.\n dedupe: ['@_linked/server-utils', '@_linked/react'],\n },\n }\n : {}),\n // `ssr.external` is a minimal allowlist of\n // npm deps that genuinely can't (or shouldn't) go through Vite's\n // SSR transform. Workspace packages (`@_linked/*`, `lincd-*`) are\n // DELIBERATELY removed so Vite resolves them via each package's\n // `development → ./src/*.ts` conditional export and HMR works on\n // source changes.\n //\n // \"Multiple LINCD\" warnings may resurface during the interim until\n // LINCD eradication completes (accepted).\n ssr: {\n // NOTE: Vite's `ssr.external` only accepts exact package-name strings\n // (not regex). Standalone `@_linked/*` / `lincd-*` are NOT force-listed\n // here — they auto-externalize (or bundle) and resolve via the\n // standalone `import → lib/esm` conditions set below.\n external: [\n 'react',\n 'react-dom',\n 'react-dom/server',\n 'react-router-dom',\n 'scheduler',\n 'express',\n ],\n // Vite 7 auto-externalizes node_modules packages for SSR (loading them\n // via Node → the `import`→`lib/esm` condition), which would bypass the\n // `linked:resolve-workspace-ts` resolver and create a SECOND module\n // instance of each workspace package (breaking the single-`src`-instance\n // invariant — `LinkedStorage` state set on one instance, read on the\n // other → \"No query dispatch configured\"). Force the workspace packages\n // to be BUNDLED so they resolve via each package's `development → src`.\n //\n // WORKSPACE-GATED: only force-bundle when workspaces are actually\n // present (the monorepo / CN + CN's workspace-member clones, where the\n // `@_linked/*` packages have `src` on disk). A STANDALONE app (CLI-\n // created, no workspaces) installs `@_linked/*` from npm as lib-only —\n // those have NO `src`, so bundling them via the `development → src`\n // condition fails (\"Failed to load @_linked/server/shapes/LinkedServer\").\n // Leaving them EXTERNAL lets Node resolve `import → lib/esm`. Single-\n // instance is not a concern standalone (one node_modules copy each) and\n // core's query dispatch is global-backed regardless.\n // STANDALONE: force-bundle the framework packages that hold React context /\n // shared singletons the SSR tree must agree on — `server-utils` (`AppContext`,\n // read by `AppRoot`) and `react`. If left external, LinkedServer's\n // `AppContextProvider` and the app's `AppRoot` (`useAppContext`) can resolve to\n // DIFFERENT module instances → two `AppContext` objects → `useAppContext()` sees\n // no provider (null) → \"Cannot destructure 'isNativeApp'\" and a blank \"SSR timed\n // out\". Bundling makes them one instance in Vite's SSR module graph (matching how\n // workspace mode bundles everything). Native-dep packages (`server`/`fuseki`) stay\n // external so their prebuilt binaries load via Node.\n //\n // WORKSPACE: bundle ONLY the discovered source workspaces (they resolve to `src/`\n // for HMR). Published framework packages installed under node_modules (lib-only)\n // stay EXTERNAL, so Vite-loaded source and Node-native `import()` share Node's\n // single instance of them. Force-bundling every `@_linked/*` here made Vite\n // evaluate its own `@_linked/core` while `loadStores` (core) loaded a store such\n // as `@_linked/fuseki/shapes/FusekiStore` through native `import()`, which pulled\n // a SECOND Node-loaded core and split the shape registry. Installed packages\n // that depend on a workspace (e.g. published fuseki when core itself is a\n // workspace) are bundled too, so they import the Vite-loaded workspace.\n noExternal: ssrNoExternal(workspaces, await workspaceDependents(workspaces)),\n // STANDALONE: the SSR module runner (`vite.ssrLoadModule`, used to\n // load LinkedServer + the app graph in commands/start.ts) has its OWN\n // condition list, defaulting to `resolve.conditions`. Set it\n // explicitly so `development` is excluded there too and the lib-only\n // packages resolve via `import → lib/esm`. Omitted (defaults kept) in\n // workspace mode so monorepo SSR still resolves `development → src`.\n ...(isStandalone\n ? {resolve: {conditions: ['module', 'node']}}\n : {}),\n },\n // Client-only, deliberately: these go on the `client` environment, not the\n // top-level `define`, because a top-level `define` is inherited by the SSR\n // environment too.\n //\n // The browser needs them. `@_linked/server-utils`'s `Server.ts` reads\n // `process.env.SITE_ROOT` to target the backend; the browser has no\n // `process`, and Vite (unlike a bundler's EnvironmentPlugin) doesn't\n // auto-inline `process.env.X`, so SITE_ROOT is defined here — always the\n // app's own origin, defaulted to `http://localhost:<port>` (an explicit\n // `SITE_ROOT` env, e.g. from `.env-cmdrc`, still wins). NODE_ENV is a\n // common client guard, so it is defined too.\n //\n // The server must NOT get them, for two reasons:\n // - it reads `process.env` at runtime, so an inlined build-time value is\n // wrong there (a release backend would carry the build machine's\n // SITE_ROOT rather than the deployment's);\n // - worse, every `define` key is a trigger. Vite's `vite:define` plugin\n // runs `esbuild.transform` — without `keepNames` — over any SSR module\n // whose text contains a key. esbuild renames the inner binding of a\n // tsc-emitted decorated class (`let LinkedServer = class LinkedServer`\n // becomes `class LinkedServer2`), and a shape's IRI is built from its\n // class name, so `@_linked/server`'s `LinkedServer` and `LincdAPI`\n // registered as `LinkedServer2` / `LincdAPI2` in dev. Without user keys\n // the SSR environment has none of its own (`keepProcessEnv` is on for\n // it), so nothing server-side is rewritten.\n //\n // Only these SPECIFIC tokens, never a whole-object `process.env`\n // replacement: in a client build Vite already maps any other\n // `process.env.X` to `{}.X` (undefined), which is what client code expects.\n //\n // Apps expose their OWN frontend env vars through the `define` option,\n // which lands here too:\n // createViteConfig({ define: {\n // 'process.env.MY_PUBLIC_KEY': JSON.stringify(process.env.MY_PUBLIC_KEY),\n // }})\n // (only reference PUBLIC vars in client code — a defined secret would be\n // inlined into the browser bundle). An app that puts a top-level `define`\n // in its own config reintroduces both problems for the server; use\n // `environments.client.define` there as well.\n environments: {\n client: {\n define: clientDefine(opts),\n },\n },\n // WORKSPACE mode: exclude the source-shipping workspace packages (@_linked/*,\n // lincd-*) from esbuild's dep pre-bundler. They resolve to `src/` via the\n // `linked:resolve-workspace-ts` plugin; in a workspace-member CLONE they'd\n // otherwise resolve via `node_modules` SYMLINKS and esbuild fails on their\n // subpath `exports` (\"No known conditions for ./shapes/SHACL …\").\n // STANDALONE mode: exclude the published `@_linked/*` / `lincd-*` deps from\n // esbuild's pre-bundler so the browser's native ESM graph loads ONE copy of\n // `@_linked/core` (no per-subpath duplication → stable class names → shape URIs\n // match the backend — see `linkedDeps` above). These packages are ESM with no\n // bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // serving them as native ESM needs no `optimizeDeps.include` interop shim.\n ...(workspaces.length > 0\n ? {optimizeDeps: {exclude: workspaces.map((w) => w.name)}}\n : isStandalone && linkedDeps.length > 0\n ? {optimizeDeps: {exclude: linkedDeps}}\n : {}),\n };\n\n // Tailwind plugin (only if explicitly enabled — adds a heavy plugin).\n if (opts.cssMode === 'tailwind') {\n // Try ESM dynamic import first (works when @tailwindcss/vite is\n // installed in the app or hoisted). Surface a CLEAR warning when\n // it's not — the app needs the dep for theme variables to load.\n try {\n const tailwind: any = await import('@tailwindcss/vite' as any);\n const tailwindPlugin = tailwind.default ?? tailwind;\n (config.plugins as Plugin[]).push(tailwindPlugin());\n } catch (err) {\n console.warn(\n '[createViteConfig] cssMode=tailwind but @tailwindcss/vite ' +\n 'could not be loaded. Theme variables won\\'t apply at runtime. ' +\n 'Add `@tailwindcss/vite` to your app\\'s package.json.',\n );\n }\n }\n\n return config;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"vite-config.js","sourceRoot":"","sources":["../../src/vite-config.ts"],"names":[],"mappings":";;;;;;;;;AAAA,oEAAoE;AACpE,EAAE;AACF,+CAA+C;AAC/C,EAAE;AACF,wDAAwD;AACxD,wEAAwE;AACxE,EAAE;AACF,mEAAmE;AACnE,qEAAqE;AACrE,uEAAuE;AACvE,qEAAqE;AACrE,OAAO,EAAC,YAAY,EAAC,MAAM,MAAM,CAAC;AAClC,OAAO,KAAK,MAAM,sBAAsB,CAAC;AACzC,OAAO,OAAO,MAAM,UAAU,CAAC;AAC/B,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAC,kBAAkB,EAAC,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAC,sBAAsB,EAAE,sBAAsB,EAAC,MAAM,sBAAsB,CAAC;AAGpF;;;;;;;;;GASG;AACH,MAAM,sBAAsB,GAAa,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;AACpE,MAAM,cAAc,GAAG,CAAC,IAAY,EAAW,EAAE,CAC/C,sBAAsB,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;AAErD,sEAAsE;AACtE,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAC9B,MAAM,gBAAgB,GAAG,KAAK,CAAC;AAC/B,iFAAiF;AACjF,MAAM,YAAY,GAAG,IAAI,CAAC;AAC1B,MAAM,YAAY,GAAG,KAAK,CAAC;AAE3B;;;;;;;;;;;;;;;GAeG;AACH;;;;;;;;;;GAU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,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,IAAI,CACV,4DAA4D;oBAC1D,gEAAgE;oBAChE,sDAAsD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC,CAAA,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Vite config helper for linked apps. The one dev + build pipeline.\n//\n// Apps use this from their own vite.config.ts:\n//\n// import {createViteConfig} from '@_linked/cli/vite';\n// export default createViteConfig({port: 4040, cssMode: 'tailwind'});\n//\n// The helper preserves the dev-mode `generateScopedName` (readable\n// `_packageName_filename_className`) so CSS module class names match\n// what the previous bundler chain produced for trace/debug. Production\n// uses Vite's default scoping (content-hash, equivalent uniqueness).\nimport {defineConfig} from 'vite';\nimport react from '@vitejs/plugin-react';\nimport fsExtra from 'fs-extra';\nimport path from 'node:path';\nimport {generateScopedName} from './utils.js';\nimport {parseWorkspacePatterns, isWorkspacePathNegated} from './workspace-globs.js';\nimport type {Plugin, UserConfig} from 'vite';\n\n/**\n * Framework packages that MUST be single-instance per runtime — they hold\n * module-level state (`@_linked/core`'s shape registry, `LinkedStorage`, the query\n * context) or register shapes into it. Two copies in one runtime split that state\n * and mangle shape identity (`Person`→`Person2`). This ONE list is the single source\n * of truth for the standalone `optimizeDeps.exclude` (`linkedDeps`). In workspace mode\n * `ssr.noExternal` is keyed on the discovered source workspaces instead (see\n * `ssrNoExternal`), so published framework packages stay external and single-instance\n * under Node.\n */\nconst FRAMEWORK_PKG_PATTERNS: RegExp[] = [/^@_linked\\//, /^lincd-/];\nconst isFrameworkPkg = (name: string): boolean =>\n FRAMEWORK_PKG_PATTERNS.some((re) => re.test(name));\n\n/** Default dev server port, and Vite's default HMR websocket port. */\nconst DEFAULT_DEV_PORT = 4040;\nconst DEFAULT_HMR_PORT = 24678;\n/** Vite may not bind below 1024 without privileges; 65535 is the TCP ceiling. */\nconst MIN_HMR_PORT = 1024;\nconst MAX_HMR_PORT = 65535;\n\n/**\n * Derive an app's HMR websocket port from its dev port.\n *\n * Every `createViteConfig` app used to fall back to Vite's shared default\n * 24678, so any two dev servers running at once collided (\"Port 24678 is\n * already in use\") and HMR silently broke for the loser. Offsetting the HMR\n * port by the same amount the dev port is offset from its default keeps the\n * derivation trivial and means apps that already run on distinct dev ports get\n * distinct HMR ports for free.\n *\n * The input is untrusted (`process.env.PORT` is an arbitrary string), so\n * anything that is not a whole port number — `PORT=abc` yielding `NaN`, a\n * negative or out-of-range value — falls back to the dev port default. The\n * result is then clamped into the bindable range, since a far-out dev port\n * would otherwise derive an HMR port past 65535.\n */\n/**\n * Which manual chunk a module belongs in.\n *\n * Split large/common deps so route chunks don't all carry their own copy AND\n * the main entry doesn't end up at 5MB+. Each chunk becomes its own\n * `assets/<name>-<hash>.js` the browser caches independently — incremental\n * dev builds and cache wins on prod deploys both improve.\n *\n * Exported so the grouping can be asserted directly: getting it wrong does not\n * fail the build, it produces a bundle that throws on load in the browser.\n */\nexport const chunkForModuleId = (id: string): string | undefined => {\n if (!id.includes('node_modules')) {\n // Linked workspaces ship as @_linked/* / lincd-* — group all\n // linked-framework code into a single chunk.\n if (\n id.includes('/packages/core/') ||\n id.includes('/packages/react/') ||\n id.includes('/packages/server-utils/') ||\n id.includes('/packages/primitives/') ||\n id.includes('/packages/css/') ||\n /\\/packages\\/(auth|org|schema|fuseki|owl|xsd|dcat|dcmi|s3|sentry|ui)\\//.test(id)\n ) {\n return 'linked';\n }\n return undefined;\n }\n // Framework code installed from the registry rather than resolved to a\n // workspace. An app can hold both at once — a published `@_linked/server`\n // in node_modules next to workspace `@_linked/core` — and the two import\n // each other. Split across `linked` and `vendor` that is a cycle, and\n // Rollup's chosen order left a binding in its temporal dead zone:\n // `Cannot access 'Wo' before initialization` before the app rendered.\n // Same chunk, no cycle.\n if (/[\\\\/]node_modules[\\\\/](@_linked[\\\\/]|lincd-)/.test(id)) {\n return 'linked';\n }\n // React + React-DOM in their own chunk — every route uses them.\n //\n // react-router and @remix-run/router belong here too. Left in `vendor` they\n // made the two chunks import each other: react-router-dom re-exports\n // react-router, so react-vendor imported vendor, while vendor's own\n // top-level `React.createContext(...)` calls imported react-vendor. Rollup\n // has to pick an order for a cycle, and it ran vendor first — every\n // production build died on load with \"Cannot read properties of undefined\n // (reading 'createContext')\".\n if (\n /[\\\\/]node_modules[\\\\/](react|react-dom|react-router-dom|react-router|@remix-run[\\\\/]router|scheduler)[\\\\/]/.test(\n id\n )\n ) {\n return 'react-vendor';\n }\n // Heavy editor deps — only loaded on pages that need them, but worth\n // isolating so they don't get pulled into main.\n if (/[\\\\/]node_modules[\\\\/]@monaco-editor[\\\\/]/.test(id)) {\n return 'monaco';\n }\n // Charting/visualization\n if (/[\\\\/]node_modules[\\\\/](recharts|react-flow|@xyflow|d3-)[\\\\/]/.test(id)) {\n return 'viz';\n }\n // Animation\n if (/[\\\\/]node_modules[\\\\/]framer-motion[\\\\/]/.test(id)) {\n return 'motion';\n }\n // Catch-all for other node_modules in a vendor chunk\n return 'vendor';\n};\n\nexport function hmrPortFor(devPort: unknown): number {\n const parsed = Number(devPort);\n const validDevPort =\n Number.isFinite(parsed) && Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535\n ? parsed\n : DEFAULT_DEV_PORT;\n const derived = DEFAULT_HMR_PORT + (validDevPort - DEFAULT_DEV_PORT);\n return Math.min(MAX_HMR_PORT, Math.max(MIN_HMR_PORT, derived));\n}\n\nexport interface LinkedViteConfigOptions {\n /** Dev server port. Default 4040. */\n port?: number;\n /** Output dir for `vite build`. Default `public/bundles`. */\n outDir?: string;\n /** CSS pipeline mode. */\n cssMode?: 'tailwind' | 'css-modules-only';\n /** Entry file for the client bundle. Default `src/index.tsx`. */\n entry?: string;\n /** Extra Vite plugins. */\n plugins?: Plugin[];\n /** Extra PostCSS plugins (e.g. `postcss-media-to-container`). */\n postcssPlugins?: unknown[];\n /**\n * Extra `define` entries for the CLIENT environment only (used to bridge\n * `process.env.X` refs into the browser). Never applied server-side.\n */\n define?: Record<string, string>;\n /**\n * Extra workspace globs (trailing `/*`, or a direct package dir) resolved\n * RELATIVE TO the app's cwd, in ADDITION to the app's own `workspaces` field.\n *\n * For apps whose linked-package sources live OUTSIDE their own workspace tree\n * — e.g. an app consumes `packages/lincd.org/modules/*`, which sit one level\n * up (`../lincd.org/modules/*`) when the app runs inside the CN monorepo, and under\n * `packages/lincd.org/modules/*` when the app runs from its own root. Pass BOTH\n * candidate layouts; only globs whose parent dir actually exists are scanned,\n * so the same config works in either checkout. Each glob's packages are\n * registered as source workspaces (resolved to `src/` for HMR + single-instance),\n * exactly like the app's own `workspaces` field.\n */\n workspaceGlobs?: string[];\n}\n\ninterface WorkspaceEntry {\n name: string;\n srcDir: string;\n}\n\n// Resolve a dependency name to its installed package.json the way Node does:\n// look in `<dir>/node_modules/<name>`, then each parent directory's\n// node_modules, starting from the requiring package's directory. This finds\n// deps that npm/yarn workspaces HOISTED to the monorepo root (an app under\n// `services/api` whose dep lives in `<root>/node_modules`). The walk stops\n// after the nearest directory whose package.json declares `workspaces` (the\n// workspace root), or at the filesystem root. Returns null when the package\n// isn't installed (e.g. an optional dep) — we skip rather than throw.\nasync function isWorkspaceRoot(dir: string): Promise<boolean> {\n try {\n const json = await fsExtra.readJson(path.join(dir, 'package.json'));\n return !!json.workspaces;\n } catch {\n return false;\n }\n}\n\nasync function readInstalledPkg(\n name: string,\n fromDir: string,\n): Promise<{root: string; json: any} | null> {\n let dir = path.resolve(fromDir);\n while (true) {\n const root = path.join(dir, 'node_modules', name);\n const pkgJson = path.join(root, 'package.json');\n if (await fsExtra.pathExists(pkgJson)) {\n try {\n return {root, json: await fsExtra.readJson(pkgJson)};\n } catch {\n return null;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir || (await isWorkspaceRoot(dir))) return null;\n dir = parent;\n }\n}\n\n/**\n * Names of installed packages that depend, directly or transitively (via\n * `dependencies` / `peerDependencies`), on a discovered source workspace. Such a\n * package must also go through Vite SSR: if Node loaded it natively, it would\n * import its own Node-loaded copy of the workspace (e.g. published\n * `@_linked/fuseki` importing a workspace `@_linked/core`), splitting module\n * state. Vite rewrites the dynamic `import()` in code it transforms, so bundling\n * the dependents keeps one instance.\n *\n * Only the dependency closure of the app's `package.json` (dependencies +\n * devDependencies) and of the workspaces themselves is scanned. Packages are\n * resolved Node-style, keyed by real path, and unresolvable ones are ignored.\n * Workspace names are not included in the result.\n */\nexport async function workspaceDependents(\n workspaces: {name: string; srcDir?: string}[],\n cwd: string = process.cwd(),\n): Promise<string[]> {\n if (workspaces.length === 0) return [];\n const fs = await import('node:fs/promises');\n const wsNames = new Set(workspaces.map((w) => w.name));\n // realRoot -> {name, deps (realRoots)}\n const nodes = new Map<string, {name: string; deps: Set<string>}>();\n const realpath = async (p: string): Promise<string> => {\n try {\n return await fs.realpath(p);\n } catch {\n return path.resolve(p);\n }\n };\n\n const visit = async (root: string, json: any): Promise<string> => {\n const real = await realpath(root);\n if (nodes.has(real)) return real;\n const node = {name: json.name as string, deps: new Set<string>()};\n nodes.set(real, node);\n const names = new Set([\n ...Object.keys(json.dependencies ?? {}),\n ...Object.keys(json.peerDependencies ?? {}),\n ]);\n for (const dep of names) {\n const resolved = await readInstalledPkg(dep, real);\n if (resolved) node.deps.add(await visit(resolved.root, resolved.json));\n }\n return real;\n };\n\n // Seed: the app's direct deps, plus each workspace package's own deps.\n try {\n const appPkg = await fsExtra.readJson(path.join(cwd, 'package.json'));\n for (const dep of Object.keys({...appPkg.dependencies, ...appPkg.devDependencies})) {\n const resolved = await readInstalledPkg(dep, cwd);\n if (resolved) await visit(resolved.root, resolved.json);\n }\n } catch {}\n for (const ws of workspaces) {\n if (!ws.srcDir) continue;\n const root = path.dirname(ws.srcDir);\n try {\n await visit(root, await fsExtra.readJson(path.join(root, 'package.json')));\n } catch {}\n }\n\n // Walk reverse edges from every workspace node: everything reached depends on one.\n const dependentsOf = new Map<string, string[]>();\n for (const [key, node] of nodes) {\n for (const dep of node.deps) {\n if (!dependentsOf.has(dep)) dependentsOf.set(dep, []);\n dependentsOf.get(dep)!.push(key);\n }\n }\n const queue = [...nodes].filter(([, n]) => wsNames.has(n.name)).map(([k]) => k);\n const marked = new Set(queue);\n while (queue.length) {\n for (const parent of dependentsOf.get(queue.pop()!) ?? []) {\n if (!marked.has(parent)) {\n marked.add(parent);\n queue.push(parent);\n }\n }\n }\n const out = new Set<string>();\n for (const key of marked) {\n const name = nodes.get(key)!.name;\n if (name && !wsNames.has(name)) out.add(name);\n }\n return [...out].sort();\n}\n\n/**\n * Read a package root as a SOURCE install: `{name, srcDir}` iff it has a\n * package.json with a name and ships a `src/` dir. Published packages have only\n * `lib/` and are skipped — they resolve via their exports.\n */\nasync function readSourcePackage(root: string): Promise<WorkspaceEntry | null> {\n const pkgPath = path.join(root, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return null;\n const srcDir = path.join(root, 'src');\n if (!(await fsExtra.pathExists(srcDir))) return null;\n try {\n const json = await fsExtra.readJson(pkgPath);\n return json.name ? {name: json.name, srcDir} : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Linked packages installed as SOURCE, found by walking the app's\n * `dependencies` + `devDependencies` (and recursing through the `dependencies`\n * of each linked package found), keeping those marked `\"linkedPackage\": true`\n * — the same marker the CLI keys on (see cli-methods.ts) — and registering the\n * ones that ship `src/`.\n *\n * A dep ships `src/` when it is a symlinked workspace clone, a `link:`/`portal:`\n * dev install, or a LOCALIZED checkout (`packages-local/<pkg>`, in no workspace\n * glob). That's what lets a STANDALONE app (not itself a workspace root — e.g. a\n * per-branch clone under /apps) resolve a linked package's `.tsx` sources with\n * extension probing, instead of falling through to the package's\n * `development → ./src/*.ts` export (which misses `.tsx` like LinkedServer). A\n * prod/ejected app installs PUBLISHED packages (no `src/`) → not registered,\n * resolved via each package's `lib`.\n *\n * The marker — NOT the npm scope — drives discovery, so a user's own\n * custom-scope published linked package (e.g. `@acme/foo` with\n * `linkedPackage:true`) is picked up too, and linked packages present in\n * node_modules but not depended upon are ignored.\n *\n * Every root is REALPATHED before it is registered: `readInstalledPkg` returns\n * the `node_modules/<name>` symlink spelling, and Vite's resolver realpaths\n * every id it produces, so registering the symlink would give one file two\n * module ids — two instances of the same module.\n *\n * Shared by the Vite resolver table (`discoverWorkspaces`) and the `linked start`\n * HMR watch set, so the two cannot disagree about what is source.\n */\nexport async function discoverLinkedSourceDependencies(\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const pkgPath = path.join(cwd, 'package.json');\n if (!(await fsExtra.pathExists(pkgPath))) return [];\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n const visited = new Set<string>();\n const walk = async (\n deps: Record<string, string> | undefined,\n fromDir: string,\n ): Promise<void> => {\n for (const name of Object.keys(deps ?? {})) {\n if (visited.has(name)) continue;\n visited.add(name);\n const resolved = await readInstalledPkg(name, fromDir);\n if (!resolved) continue;\n if (resolved.json.linkedPackage !== true) continue;\n let realRoot = resolved.root;\n try {\n realRoot = await fs.realpath(resolved.root);\n } catch {}\n const entry = await readSourcePackage(realRoot);\n if (entry && !seen.has(entry.name)) {\n seen.add(entry.name);\n out.push(entry);\n }\n // Recurse from the real location, so a symlinked clone resolves its own\n // dependencies from its source dir.\n await walk(resolved.json.dependencies, realRoot);\n }\n };\n const appPkg = await fsExtra.readJson(pkgPath);\n await walk(appPkg.dependencies, cwd);\n await walk(appPkg.devDependencies, cwd);\n return out;\n}\n\n/**\n * Walk the app's package.json `workspaces` field to build a lookup table\n * from npm name → absolute src/ directory. Used by the resolver plugin\n * to map bare specifiers like `@_linked/foo/bar` directly to source.\n *\n * Positive patterns are expanded by directory listing, so only a trailing `/*`\n * is honoured. NEGATED patterns (`\"!packages/core\"`) are honoured in full, with\n * npm's semantics — see ./workspace-globs.js. Skipping them would resolve a\n * package to an excluded directory that the package manager never installed\n * dependencies for.\n */\nexport async function discoverWorkspaces(\n extraGlobs: string[] = [],\n cwd: string = process.cwd(),\n): Promise<WorkspaceEntry[]> {\n const fs = await import('node:fs/promises');\n const out: WorkspaceEntry[] = [];\n const seen = new Set<string>();\n // Register a package root iff it ships a `src/` dir (source install).\n const addFromRoot = async (root: string): Promise<void> => {\n const entry = await readSourcePackage(root);\n if (!entry || seen.has(entry.name)) return;\n seen.add(entry.name);\n out.push(entry);\n };\n\n // 1. The app's own `workspaces` globs — the monorepo-root case (CN, or any app\n // that is itself a workspace root). Only trailing `/*` patterns.\n const pkgPath = path.join(cwd, 'package.json');\n if (await fsExtra.pathExists(pkgPath)) {\n const pkg = await fsExtra.readJson(pkgPath);\n // Merge the app's own `workspaces` globs with any caller-supplied\n // `workspaceGlobs` (e.g. `../lincd.org/modules/*`). Non-existent parents\n // are skipped below, so passing both nested + standalone layouts is safe.\n // Either list may carry negations, so they are parsed together.\n const {patterns, negatedPatterns} = parseWorkspacePatterns([\n ...(Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? []),\n ...extraGlobs,\n ]);\n const addUnlessNegated = async (root: string): Promise<void> => {\n const rel = path.relative(cwd, root).split(path.sep).join('/');\n if (isWorkspacePathNegated(rel, negatedPatterns)) return;\n await addFromRoot(root);\n };\n for (const pattern of patterns) {\n const m = pattern.match(/^(.+?)\\/\\*$/);\n if (m) {\n const parent = path.join(cwd, m[1]);\n if (await fsExtra.pathExists(parent)) {\n for (const ent of await fs.readdir(parent, {withFileTypes: true})) {\n if (ent.isDirectory() || ent.isSymbolicLink()) {\n await addUnlessNegated(path.join(parent, ent.name));\n }\n }\n }\n } else {\n await addUnlessNegated(path.join(cwd, pattern));\n }\n }\n }\n\n // 2. Linked deps installed as source — including a localized checkout that is\n // in no workspace glob. Shared with the `linked start` watch set; see\n // discoverLinkedSourceDependencies above. Glob entries win on a name clash.\n for (const entry of await discoverLinkedSourceDependencies(cwd)) {\n if (seen.has(entry.name)) continue;\n seen.add(entry.name);\n out.push(entry);\n }\n\n return out;\n}\n\n/**\n * Resolve a bare specifier like `@_linked/foo/bar`, `lincd-rdfs/Foo`, or\n * `pkg/utils/Bar.js` against the workspace lookup. Tries extensions in\n * order: .ts, .tsx, then the literal id (for files that already include\n * an extension or for non-TS assets). Returns null when the specifier\n * doesn't match any workspace package or no candidate exists on disk.\n */\nasync function resolveWorkspaceSpecifier(\n specifier: string,\n workspaces: WorkspaceEntry[],\n): Promise<string | null> {\n for (const ws of workspaces) {\n if (specifier === ws.name) {\n for (const ext of ['index.ts', 'index.tsx']) {\n const p = path.join(ws.srcDir, ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n return null;\n }\n if (specifier.startsWith(ws.name + '/')) {\n const subpath = specifier.slice(ws.name.length + 1);\n // Strip .js/.jsx suffix — workspace src uses TS published-output\n // convention (./Sibling.js) but we want the TS source.\n const base = subpath.replace(/\\.jsx?$/, '');\n for (const ext of ['.tsx', '.ts']) {\n const p = path.join(ws.srcDir, base + ext);\n if (await fsExtra.pathExists(p)) return p;\n }\n // Files that already include an extension Vite handles (.css, .json,\n // .svg, etc.) — return the literal path under src.\n const literal = path.join(ws.srcDir, subpath);\n if (await fsExtra.pathExists(literal)) return literal;\n return null;\n }\n }\n return null;\n}\n\n/**\n * `ssr.noExternal` for the dev SSR runner. With source workspaces, only those\n * package names are bundled by Vite; everything else in node_modules (including\n * published `@_linked/*`) is externalized to Node. Vite matches these entries\n * against the bare package name, so subpath imports (`pkg/shapes/Foo`) match too.\n * Installed packages that depend on a workspace (`dependents`, from\n * `workspaceDependents`) are bundled too, so they share the Vite-loaded workspace.\n * Standalone (no workspaces): the context-holding framework packages are bundled.\n */\nexport function ssrNoExternal(\n workspaces: {name: string}[],\n dependents: string[] = [],\n): (string | RegExp)[] {\n if (workspaces.length === 0) return [/^@_linked\\/server-utils$/, /^@_linked\\/react$/];\n return [...new Set([...workspaces.map((w) => w.name), ...dependents])];\n}\n\n/**\n * The `process.env.*` values inlined into the browser bundle — and only there.\n * See the `environments.client.define` note in `createViteConfig` for why the\n * server environment must not receive them.\n */\nexport function clientDefine(\n opts: Pick<LinkedViteConfigOptions, 'define' | 'port'> = {},\n): Record<string, string> {\n return {\n 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),\n 'process.env.SITE_ROOT': JSON.stringify(\n process.env.SITE_ROOT ?? `http://localhost:${process.env.PORT ?? opts.port ?? 4040}`,\n ),\n // The app's display name, so client components (e.g. the header) can read it\n // like the SSR <title> does (server-utils Html reads process.env.APP_NAME). The\n // browser has no `process`, so inline it; falls back to a generic label when\n // unset so a bare checkout never renders `undefined`.\n 'process.env.APP_NAME': JSON.stringify(process.env.APP_NAME ?? 'Linked App'),\n ...(opts.define ?? {}),\n };\n}\n\nexport function createViteConfig(opts: LinkedViteConfigOptions = {}): ReturnType<typeof defineConfig> {\n return defineConfig(async ({mode}) => {\n const isDev = mode === 'development';\n const workspaces = isDev ? await discoverWorkspaces(opts.workspaceGlobs) : [];\n // STANDALONE = dev mode with no source-shipping workspaces discovered\n // (an app installed from npm outside the monorepo — its `@_linked/*` /\n // `lincd-*` deps are lib-only). discoverWorkspaces() only registers\n // packages that ship `src/` on disk, so `length === 0` is the exact\n // standalone signal used elsewhere in this file. In WORKSPACE mode\n // (CN monorepo or its workspace-member clones) this is false and none\n // of the standalone-gated branches below apply.\n const isStandalone = isDev && workspaces.length === 0;\n\n // The app's published framework deps — excluded from Vite's dep-optimizer below\n // (`optimizeDeps.exclude`) so the browser's native ESM graph loads ONE copy of each.\n // Without the exclude, esbuild inlines a duplicate `@_linked/core` into each\n // per-subpath chunk (`@_linked_schema_shapes_Person.js`,\n // `@_linked_core_utils_LinkedStorage.js`, …), duplicating framework classes\n // (`Person` → `Person2`/`3`), so their shapes register under mangled URIs that no\n // longer match the backend's (one clean copy via Node). These packages are ESM with\n // no bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // native-ESM serving needs no interop shim.\n const linkedDeps: string[] = [];\n if (isStandalone) {\n try {\n const appPkg = await fsExtra.readJson(path.join(process.cwd(), 'package.json'));\n const allDeps = {...appPkg.dependencies, ...appPkg.devDependencies};\n for (const name of Object.keys(allDeps)) {\n if (isFrameworkPkg(name)) linkedDeps.push(name);\n }\n } catch {\n /* best-effort — no package.json is fine */\n }\n }\n const config: UserConfig = {\n server: {\n port: opts.port ?? 4040,\n middlewareMode: true,\n // Unique HMR websocket port per app/worktree (PORT env override wins,\n // else opts.port) — see `hmrPortFor`. Apps can still override this with\n // their own `server.hmr` in mergeConfig.\n hmr: {port: hmrPortFor(process.env.PORT ?? opts.port)},\n },\n build: {\n outDir: opts.outDir ?? 'public/bundles',\n manifest: true,\n // Bump chunk-size warning so it doesn't fire on every build for\n // the linked vendor bundle. Real chunking happens via\n // manualChunks below.\n chunkSizeWarningLimit: 1000,\n rollupOptions: {\n input: opts.entry ?? 'src/index.tsx',\n output: {\n entryFileNames: 'assets/[name]-[hash].js',\n chunkFileNames: 'assets/[name]-[hash].js',\n assetFileNames: 'assets/[name]-[hash][extname]',\n manualChunks: chunkForModuleId,\n },\n },\n sourcemap: true,\n },\n plugins: [\n // Direct workspace specifier resolver.\n //\n // The package.json `\"./*\": { \"development\": \"./src/*.ts\" }` wildcard\n // can't express \"try .ts, fall back to .tsx\" (Node's exports spec\n // resolves to a single literal path). For React-heavy packages like\n // @_linked/primitives, @_linked/server-utils, and @_linked/auth,\n // most files are .tsx — the wildcard fails before any Vite plugin\n // gets a chance to fix it up.\n //\n // This plugin intercepts BARE workspace specifiers like\n // `@_linked/foo/bar` and `pkg-name/utils/Baz.js` BEFORE Vite's\n // package.json resolver runs, mapping them straight to source with\n // proper extension fallback (.tsx → .ts → literal). It also covers\n // the `./Sibling.js` published-output convention for imports made\n // from within workspace `src/` trees.\n isDev\n ? ({\n name: 'linked:resolve-workspace-ts',\n enforce: 'pre',\n async resolveId(id, importer) {\n if (id.startsWith('\\0')) return null;\n\n // Workspace-internal `./Sibling.js` → `.tsx` / `.ts` rewrite.\n if (\n importer &&\n importer.includes(`${path.sep}packages${path.sep}`) &&\n /\\.(jsx?)$/.test(id) &&\n (id.startsWith('.') || id.startsWith('/'))\n ) {\n const importerDir = path.dirname(importer);\n const base = path.resolve(importerDir, id);\n for (const ext of ['.tsx', '.ts']) {\n const candidate = base.replace(/\\.jsx?$/, ext);\n if (await fsExtra.pathExists(candidate)) return candidate;\n }\n }\n\n // Bare workspace specifier — resolve directly to src/.\n if (\n !id.startsWith('.') &&\n !id.startsWith('/') &&\n workspaces.length > 0\n ) {\n const resolved = await resolveWorkspaceSpecifier(id, workspaces);\n if (resolved) return resolved;\n }\n\n // STANDALONE (no workspaces): the linked packages are installed\n // from npm as lib-only (no `src`). We DON'T intercept them here —\n // instead the standalone `resolve.conditions` / `ssr.resolve.conditions`\n // (set on the config below, dropping Vite's `development` token)\n // let Vite's normal resolver pick each package's `import → lib/esm`\n // export. Bundling those lib files through the SSR runner works\n // (they're plain ESM); marking them external instead would leave a\n // bare specifier that `vite.ssrLoadModule` can't load\n // (\"Failed to load url @_linked/server/shapes/LinkedServer\").\n\n return null;\n },\n } as Plugin)\n : null,\n react({\n babel: {\n parserOpts: {\n plugins: ['decorators-legacy', 'classProperties'],\n },\n },\n }),\n // Dev-only: log every file the watcher sees change. Without this,\n // backend edits look silent (no JS rebuild step, no Node restart)\n // and it's hard to tell whether\n // Vite picked up the change at all.\n isDev\n ? ({\n name: 'linked:reload-log',\n configureServer(server) {\n server.watcher.on('change', (file) => {\n const rel = file.replace(process.cwd() + '/', '');\n console.log(`[linked] reloaded ${rel}`);\n });\n },\n } as Plugin)\n : null,\n ...(opts.plugins ?? []),\n ].filter(Boolean) as Plugin[],\n css: {\n modules: {\n generateScopedName: isDev ? generateScopedName : undefined,\n },\n postcss: opts.postcssPlugins\n ? {plugins: opts.postcssPlugins as any}\n : undefined,\n },\n esbuild: {\n tsconfigRaw: {\n compilerOptions: {\n experimentalDecorators: true,\n },\n },\n jsx: 'automatic',\n // A shape's IRI is built from its class name —\n // `getNodeShapeUri(packageName, constructor.name)` — so a minifier that\n // renames the class changes the shape's identity. In a production build\n // the client would ask the server for\n // `https://linked.cm/shape/server/za` while the server had registered\n // `.../BackendAPIStore`, and every Server.call on that shape 501'd.\n // The same mangling made registration report `Shape undefined does not\n // extend base class`.\n keepNames: true,\n },\n // STANDALONE resolve conditions.\n //\n // The published `@_linked/*` / `lincd-*` packages export\n // \"development\": \"./src/*.ts\", \"import\": \"./lib/esm/*.js\"\n // In dev, Vite expands its special `development|production` condition\n // token to `development`, so it resolves these to `./src/*.ts` — which\n // doesn't exist in a lib-only npm install → boot crash\n // (\"Failed to load @_linked/server/shapes/LinkedServer\").\n //\n // Dropping the dev/prod token from the condition list means Vite never\n // adds `development`; `import` (always appended last by Vite) wins, so\n // these packages resolve to `./lib/esm/*.js`. We start from Vite's\n // default SERVER conditions (`module`, `node`, `development|production`)\n // minus the dev/prod token. This governs BOTH the plugin pipeline\n // (`resolve.conditions`) and the SSR module runner used by\n // `ssrLoadModule('@_linked/server/shapes/LinkedServer')` in\n // commands/start.ts (`ssr.resolve.conditions`).\n //\n // WORKSPACE-GATED: only applied standalone. In monorepo dev the packages\n // ship `src`, and we WANT `development → src` for HMR — so we leave\n // conditions at Vite's defaults there (undefined = untouched), keeping\n // CN dev byte-for-byte unchanged.\n ...(isStandalone\n ? {\n resolve: {\n conditions: ['module', 'node'],\n // Dedupe the context-holding packages so the two `ssrLoadModule` loads\n // (LinkedServer + the app graph) resolve to ONE `server-utils`/`react`\n // instance — otherwise their `AppContext` objects differ and\n // `useAppContext()` returns null. Pairs with `ssr.noExternal` below.\n dedupe: ['@_linked/server-utils', '@_linked/react'],\n },\n }\n : {}),\n // `ssr.external` is a minimal allowlist of\n // npm deps that genuinely can't (or shouldn't) go through Vite's\n // SSR transform. Workspace packages (`@_linked/*`, `lincd-*`) are\n // DELIBERATELY removed so Vite resolves them via each package's\n // `development → ./src/*.ts` conditional export and HMR works on\n // source changes.\n //\n // \"Multiple LINCD\" warnings may resurface during the interim until\n // LINCD eradication completes (accepted).\n ssr: {\n // NOTE: Vite's `ssr.external` only accepts exact package-name strings\n // (not regex). Standalone `@_linked/*` / `lincd-*` are NOT force-listed\n // here — they auto-externalize (or bundle) and resolve via the\n // standalone `import → lib/esm` conditions set below.\n external: [\n 'react',\n 'react-dom',\n 'react-dom/server',\n 'react-router-dom',\n 'scheduler',\n 'express',\n ],\n // Vite 7 auto-externalizes node_modules packages for SSR (loading them\n // via Node → the `import`→`lib/esm` condition), which would bypass the\n // `linked:resolve-workspace-ts` resolver and create a SECOND module\n // instance of each workspace package (breaking the single-`src`-instance\n // invariant — `LinkedStorage` state set on one instance, read on the\n // other → \"No query dispatch configured\"). Force the workspace packages\n // to be BUNDLED so they resolve via each package's `development → src`.\n //\n // WORKSPACE-GATED: only force-bundle when workspaces are actually\n // present (the monorepo / CN + CN's workspace-member clones, where the\n // `@_linked/*` packages have `src` on disk). A STANDALONE app (CLI-\n // created, no workspaces) installs `@_linked/*` from npm as lib-only —\n // those have NO `src`, so bundling them via the `development → src`\n // condition fails (\"Failed to load @_linked/server/shapes/LinkedServer\").\n // Leaving them EXTERNAL lets Node resolve `import → lib/esm`. Single-\n // instance is not a concern standalone (one node_modules copy each) and\n // core's query dispatch is global-backed regardless.\n // STANDALONE: force-bundle the framework packages that hold React context /\n // shared singletons the SSR tree must agree on — `server-utils` (`AppContext`,\n // read by `AppRoot`) and `react`. If left external, LinkedServer's\n // `AppContextProvider` and the app's `AppRoot` (`useAppContext`) can resolve to\n // DIFFERENT module instances → two `AppContext` objects → `useAppContext()` sees\n // no provider (null) → \"Cannot destructure 'isNativeApp'\" and a blank \"SSR timed\n // out\". Bundling makes them one instance in Vite's SSR module graph (matching how\n // workspace mode bundles everything). Native-dep packages (`server`/`fuseki`) stay\n // external so their prebuilt binaries load via Node.\n //\n // WORKSPACE: bundle ONLY the discovered source workspaces (they resolve to `src/`\n // for HMR). Published framework packages installed under node_modules (lib-only)\n // stay EXTERNAL, so Vite-loaded source and Node-native `import()` share Node's\n // single instance of them. Force-bundling every `@_linked/*` here made Vite\n // evaluate its own `@_linked/core` while `loadStores` (core) loaded a store such\n // as `@_linked/fuseki/shapes/FusekiStore` through native `import()`, which pulled\n // a SECOND Node-loaded core and split the shape registry. Installed packages\n // that depend on a workspace (e.g. published fuseki when core itself is a\n // workspace) are bundled too, so they import the Vite-loaded workspace.\n //\n // NOT DEV (a release build of the backend): nothing is force-bundled. The\n // compiled backend is loaded by Node next to the installed\n // `@_linked/server`, so every framework package has to stay a bare import\n // that resolves to that same node_modules copy. `workspaces` is always\n // empty here, and handing that to `ssrNoExternal` used to select the\n // standalone list — which compiled a private `server-utils` into `lib/`,\n // so no app provider was `instanceof` the server's `ShapeProvider` and\n // `LinkedServer` dropped them all (\"exports two generic backend providers\").\n noExternal: isDev ? ssrNoExternal(workspaces, await workspaceDependents(workspaces)) : [],\n // STANDALONE: the SSR module runner (`vite.ssrLoadModule`, used to\n // load LinkedServer + the app graph in commands/start.ts) has its OWN\n // condition list, defaulting to `resolve.conditions`. Set it\n // explicitly so `development` is excluded there too and the lib-only\n // packages resolve via `import → lib/esm`. Omitted (defaults kept) in\n // workspace mode so monorepo SSR still resolves `development → src`.\n ...(isStandalone\n ? {resolve: {conditions: ['module', 'node']}}\n : {}),\n },\n // Client-only, deliberately: these go on the `client` environment, not the\n // top-level `define`, because a top-level `define` is inherited by the SSR\n // environment too.\n //\n // The browser needs them. `@_linked/server-utils`'s `Server.ts` reads\n // `process.env.SITE_ROOT` to target the backend; the browser has no\n // `process`, and Vite (unlike a bundler's EnvironmentPlugin) doesn't\n // auto-inline `process.env.X`, so SITE_ROOT is defined here — always the\n // app's own origin, defaulted to `http://localhost:<port>` (an explicit\n // `SITE_ROOT` env, e.g. from `.env-cmdrc`, still wins). NODE_ENV is a\n // common client guard, so it is defined too.\n //\n // The server must NOT get them, for two reasons:\n // - it reads `process.env` at runtime, so an inlined build-time value is\n // wrong there (a release backend would carry the build machine's\n // SITE_ROOT rather than the deployment's);\n // - worse, every `define` key is a trigger. Vite's `vite:define` plugin\n // runs `esbuild.transform` — without `keepNames` — over any SSR module\n // whose text contains a key. esbuild renames the inner binding of a\n // tsc-emitted decorated class (`let LinkedServer = class LinkedServer`\n // becomes `class LinkedServer2`), and a shape's IRI is built from its\n // class name, so `@_linked/server`'s `LinkedServer` and `LincdAPI`\n // registered as `LinkedServer2` / `LincdAPI2` in dev. Without user keys\n // the SSR environment has none of its own (`keepProcessEnv` is on for\n // it), so nothing server-side is rewritten.\n //\n // Only these SPECIFIC tokens, never a whole-object `process.env`\n // replacement: in a client build Vite already maps any other\n // `process.env.X` to `{}.X` (undefined), which is what client code expects.\n //\n // Apps expose their OWN frontend env vars through the `define` option,\n // which lands here too:\n // createViteConfig({ define: {\n // 'process.env.MY_PUBLIC_KEY': JSON.stringify(process.env.MY_PUBLIC_KEY),\n // }})\n // (only reference PUBLIC vars in client code — a defined secret would be\n // inlined into the browser bundle). An app that puts a top-level `define`\n // in its own config reintroduces both problems for the server; use\n // `environments.client.define` there as well.\n environments: {\n client: {\n define: clientDefine(opts),\n },\n },\n // WORKSPACE mode: exclude the source-shipping workspace packages (@_linked/*,\n // lincd-*) from esbuild's dep pre-bundler. They resolve to `src/` via the\n // `linked:resolve-workspace-ts` plugin; in a workspace-member CLONE they'd\n // otherwise resolve via `node_modules` SYMLINKS and esbuild fails on their\n // subpath `exports` (\"No known conditions for ./shapes/SHACL …\").\n // STANDALONE mode: exclude the published `@_linked/*` / `lincd-*` deps from\n // esbuild's pre-bundler so the browser's native ESM graph loads ONE copy of\n // `@_linked/core` (no per-subpath duplication → stable class names → shape URIs\n // match the backend — see `linkedDeps` above). These packages are ESM with no\n // bare CJS runtime deps (e.g. `classnames` is inlined in `@_linked/react`), so\n // serving them as native ESM needs no `optimizeDeps.include` interop shim.\n ...(workspaces.length > 0\n ? {optimizeDeps: {exclude: workspaces.map((w) => w.name)}}\n : isStandalone && linkedDeps.length > 0\n ? {optimizeDeps: {exclude: linkedDeps}}\n : {}),\n };\n\n // Tailwind plugin (only if explicitly enabled — adds a heavy plugin).\n if (opts.cssMode === 'tailwind') {\n // Try ESM dynamic import first (works when @tailwindcss/vite is\n // installed in the app or hoisted). Surface a CLEAR warning when\n // it's not — the app needs the dep for theme variables to load.\n try {\n const tailwind: any = await import('@tailwindcss/vite' as any);\n const tailwindPlugin = tailwind.default ?? tailwind;\n (config.plugins as Plugin[]).push(tailwindPlugin());\n } catch (err) {\n console.warn(\n '[createViteConfig] cssMode=tailwind but @tailwindcss/vite ' +\n 'could not be loaded. Theme variables won\\'t apply at runtime. ' +\n 'Add `@tailwindcss/vite` to your app\\'s package.json.',\n );\n }\n }\n\n return config;\n });\n}\n"]}
|