@mionjs/devtools 0.8.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/build/eslint/cjs/index.cjs +41 -0
- package/build/eslint/cjs/index.cjs.map +1 -0
- package/build/eslint/cjs/package.json +1 -0
- package/build/eslint/cjs/src/eslint/index.cjs +13 -0
- package/build/eslint/cjs/src/eslint/index.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/index.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/enforce-type-imports.cjs +121 -0
- package/build/eslint/cjs/src/eslint/rules/enforce-type-imports.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/enforce-type-imports.d.ts +7 -0
- package/build/eslint/cjs/src/eslint/rules/formatTypeNames.cjs +71 -0
- package/build/eslint/cjs/src/eslint/rules/formatTypeNames.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/formatTypeNames.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/no-mixed-union-properties.cjs +220 -0
- package/build/eslint/cjs/src/eslint/rules/no-mixed-union-properties.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/no-mixed-union-properties.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/no-type-imports.cjs +251 -0
- package/build/eslint/cjs/src/eslint/rules/no-type-imports.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/no-type-imports.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/no-typeof-runtype.cjs +72 -0
- package/build/eslint/cjs/src/eslint/rules/no-typeof-runtype.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/no-typeof-runtype.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/no-unreachable-union-types.cjs +220 -0
- package/build/eslint/cjs/src/eslint/rules/no-unreachable-union-types.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/no-unreachable-union-types.d.ts +3 -0
- package/build/eslint/cjs/src/eslint/rules/no-vite-client.cjs +71 -0
- package/build/eslint/cjs/src/eslint/rules/no-vite-client.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/no-vite-client.d.ts +4 -0
- package/build/eslint/cjs/src/eslint/rules/pure-functions.cjs +346 -0
- package/build/eslint/cjs/src/eslint/rules/pure-functions.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/pure-functions.d.ts +4 -0
- package/build/eslint/cjs/src/eslint/rules/strong-typed-routes.cjs +328 -0
- package/build/eslint/cjs/src/eslint/rules/strong-typed-routes.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/strong-typed-routes.d.ts +4 -0
- package/build/eslint/cjs/src/eslint/rules/type-formats-imports.cjs +52 -0
- package/build/eslint/cjs/src/eslint/rules/type-formats-imports.cjs.map +1 -0
- package/build/eslint/cjs/src/eslint/rules/type-formats-imports.d.ts +3 -0
- package/build/eslint/cjs/src/pureFns/purityRules.cjs +67 -0
- package/build/eslint/cjs/src/pureFns/purityRules.cjs.map +1 -0
- package/build/eslint/cjs/src/pureFns/purityRules.d.ts +4 -0
- package/build/eslint/esm/index.js +42 -0
- package/build/eslint/esm/index.js.map +1 -0
- package/build/eslint/esm/src/eslint/index.d.ts +3 -0
- package/build/eslint/esm/src/eslint/index.js +14 -0
- package/build/eslint/esm/src/eslint/index.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/enforce-type-imports.d.ts +7 -0
- package/build/eslint/esm/src/eslint/rules/enforce-type-imports.js +122 -0
- package/build/eslint/esm/src/eslint/rules/enforce-type-imports.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/formatTypeNames.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/formatTypeNames.js +71 -0
- package/build/eslint/esm/src/eslint/rules/formatTypeNames.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/no-mixed-union-properties.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/no-mixed-union-properties.js +221 -0
- package/build/eslint/esm/src/eslint/rules/no-mixed-union-properties.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/no-type-imports.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/no-type-imports.js +252 -0
- package/build/eslint/esm/src/eslint/rules/no-type-imports.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/no-typeof-runtype.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/no-typeof-runtype.js +73 -0
- package/build/eslint/esm/src/eslint/rules/no-typeof-runtype.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/no-unreachable-union-types.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/no-unreachable-union-types.js +221 -0
- package/build/eslint/esm/src/eslint/rules/no-unreachable-union-types.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/no-vite-client.d.ts +4 -0
- package/build/eslint/esm/src/eslint/rules/no-vite-client.js +72 -0
- package/build/eslint/esm/src/eslint/rules/no-vite-client.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/pure-functions.d.ts +4 -0
- package/build/eslint/esm/src/eslint/rules/pure-functions.js +347 -0
- package/build/eslint/esm/src/eslint/rules/pure-functions.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/strong-typed-routes.d.ts +4 -0
- package/build/eslint/esm/src/eslint/rules/strong-typed-routes.js +329 -0
- package/build/eslint/esm/src/eslint/rules/strong-typed-routes.js.map +1 -0
- package/build/eslint/esm/src/eslint/rules/type-formats-imports.d.ts +3 -0
- package/build/eslint/esm/src/eslint/rules/type-formats-imports.js +53 -0
- package/build/eslint/esm/src/eslint/rules/type-formats-imports.js.map +1 -0
- package/build/eslint/esm/src/pureFns/purityRules.d.ts +4 -0
- package/build/eslint/esm/src/pureFns/purityRules.js +67 -0
- package/build/eslint/esm/src/pureFns/purityRules.js.map +1 -0
- package/build/vite-plugin/cjs/index.cjs +14 -0
- package/build/vite-plugin/cjs/index.cjs.map +1 -0
- package/build/vite-plugin/cjs/package.json +1 -0
- package/build/vite-plugin/cjs/src/pureFns/purityRules.cjs +65 -0
- package/build/vite-plugin/cjs/src/pureFns/purityRules.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/pureFns/purityRules.d.ts +4 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotCacheGenerator.cjs +235 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotCacheGenerator.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotCacheGenerator.d.ts +23 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotDiskCache.cjs +134 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotDiskCache.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/aotDiskCache.d.ts +6 -0
- package/build/vite-plugin/cjs/src/vite-plugin/cjsPackageJsonPlugin.cjs +15 -0
- package/build/vite-plugin/cjs/src/vite-plugin/cjsPackageJsonPlugin.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/cjsPackageJsonPlugin.d.ts +2 -0
- package/build/vite-plugin/cjs/src/vite-plugin/constants.cjs +25 -0
- package/build/vite-plugin/cjs/src/vite-plugin/constants.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/constants.d.ts +10 -0
- package/build/vite-plugin/cjs/src/vite-plugin/extractPureFn.cjs +628 -0
- package/build/vite-plugin/cjs/src/vite-plugin/extractPureFn.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/extractPureFn.d.ts +13 -0
- package/build/vite-plugin/cjs/src/vite-plugin/index.cjs +14 -0
- package/build/vite-plugin/cjs/src/vite-plugin/index.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/index.d.ts +5 -0
- package/build/vite-plugin/cjs/src/vite-plugin/mionVitePlugin.cjs +404 -0
- package/build/vite-plugin/cjs/src/vite-plugin/mionVitePlugin.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/mionVitePlugin.d.ts +36 -0
- package/build/vite-plugin/cjs/src/vite-plugin/resolveModule.cjs +55 -0
- package/build/vite-plugin/cjs/src/vite-plugin/resolveModule.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/resolveModule.d.ts +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/transformers.cjs +165 -0
- package/build/vite-plugin/cjs/src/vite-plugin/transformers.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/transformers.d.ts +10 -0
- package/build/vite-plugin/cjs/src/vite-plugin/types.cjs +2 -0
- package/build/vite-plugin/cjs/src/vite-plugin/types.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/types.d.ts +57 -0
- package/build/vite-plugin/cjs/src/vite-plugin/virtual-modules.d.cjs +2 -0
- package/build/vite-plugin/cjs/src/vite-plugin/virtual-modules.d.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/virtualModule.cjs +68 -0
- package/build/vite-plugin/cjs/src/vite-plugin/virtualModule.cjs.map +1 -0
- package/build/vite-plugin/cjs/src/vite-plugin/virtualModule.d.ts +2 -0
- package/build/vite-plugin/esm/index.js +14 -0
- package/build/vite-plugin/esm/index.js.map +1 -0
- package/build/vite-plugin/esm/src/pureFns/purityRules.d.ts +4 -0
- package/build/vite-plugin/esm/src/pureFns/purityRules.js +65 -0
- package/build/vite-plugin/esm/src/pureFns/purityRules.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotCacheGenerator.d.ts +23 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotCacheGenerator.js +235 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotCacheGenerator.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotDiskCache.d.ts +6 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotDiskCache.js +133 -0
- package/build/vite-plugin/esm/src/vite-plugin/aotDiskCache.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/cjsPackageJsonPlugin.d.ts +2 -0
- package/build/vite-plugin/esm/src/vite-plugin/cjsPackageJsonPlugin.js +15 -0
- package/build/vite-plugin/esm/src/vite-plugin/cjsPackageJsonPlugin.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/constants.d.ts +10 -0
- package/build/vite-plugin/esm/src/vite-plugin/constants.js +25 -0
- package/build/vite-plugin/esm/src/vite-plugin/constants.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/extractPureFn.d.ts +13 -0
- package/build/vite-plugin/esm/src/vite-plugin/extractPureFn.js +611 -0
- package/build/vite-plugin/esm/src/vite-plugin/extractPureFn.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/index.d.ts +5 -0
- package/build/vite-plugin/esm/src/vite-plugin/index.js +14 -0
- package/build/vite-plugin/esm/src/vite-plugin/index.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/mionVitePlugin.d.ts +36 -0
- package/build/vite-plugin/esm/src/vite-plugin/mionVitePlugin.js +387 -0
- package/build/vite-plugin/esm/src/vite-plugin/mionVitePlugin.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/resolveModule.d.ts +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/resolveModule.js +33 -0
- package/build/vite-plugin/esm/src/vite-plugin/resolveModule.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/transformers.d.ts +10 -0
- package/build/vite-plugin/esm/src/vite-plugin/transformers.js +148 -0
- package/build/vite-plugin/esm/src/vite-plugin/transformers.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/types.d.ts +57 -0
- package/build/vite-plugin/esm/src/vite-plugin/types.js +2 -0
- package/build/vite-plugin/esm/src/vite-plugin/types.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/virtual-modules.d.js +2 -0
- package/build/vite-plugin/esm/src/vite-plugin/virtual-modules.d.js.map +1 -0
- package/build/vite-plugin/esm/src/vite-plugin/virtualModule.d.ts +2 -0
- package/build/vite-plugin/esm/src/vite-plugin/virtualModule.js +68 -0
- package/build/vite-plugin/esm/src/vite-plugin/virtualModule.js.map +1 -0
- package/package.json +94 -0
- package/src/vite-plugin/virtual-modules.d.ts +48 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mionVitePlugin.cjs","sources":["../../../../../src/vite-plugin/mionVitePlugin.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {resolve} from 'path';\nimport * as ts from 'typescript';\nimport {ChildProcess} from 'child_process';\nimport {createDeepkitConfig, DeepkitConfig, createPureFnTransformerFactory} from './transformers.ts';\nimport {ServerPureFunctionsOptions, ExtractedPureFn, DeepkitTypeOptions, AOTCacheOptions, MionServerConfig} from './types.ts';\nimport {scanClientSource} from './extractPureFn.ts';\nimport {generateServerPureFnsVirtualModule} from './virtualModule.ts';\nimport {VIRTUAL_SERVER_PURE_FNS, REFLECTION_MODULES, VIRTUAL_STUB_PREFIX, resolveVirtualId} from './constants.ts';\nimport {\n generateAOTCaches,\n loadSSRRouterAndGenerateAOTCaches,\n killPersistentChild,\n logAOTCaches,\n waitForServer,\n generateJitFnsModule,\n generatePureFnsModule,\n generateRouterCacheModule,\n generateCombinedCachesModule,\n generateNoopModule,\n generateNoopCombinedModule,\n AOTCacheData,\n} from './aotCacheGenerator.ts';\nimport {getOrGenerateAOTCaches, updateDiskCache, resolveCacheDir} from './aotDiskCache.ts';\n\nexport interface MionPluginOptions {\n /** Options for pure function extraction - omit to disable */\n serverPureFunctions?: ServerPureFunctionsOptions;\n /** Options for deepkit type transformation - omit to disable */\n runTypes?: DeepkitTypeOptions;\n /** Options for AOT cache generation - omit to disable */\n aotCaches?: AOTCacheOptions | true;\n /** Server configuration - controls how the server process is managed */\n server?: MionServerConfig;\n}\n\n/** Whether the current process is a child spawned by the mion plugin */\nfunction isRunningAsChild(): boolean {\n return process.env.MION_COMPILE === 'onlyAOT' || process.env.MION_COMPILE === 'serve';\n}\n\n/**\n * Creates the unified mion Vite plugin.\n * This plugin combines pure function extraction, type compiler transformations,\n * and AOT cache generation in a single plugin with correct execution order.\n *\n * Execution order:\n * 1. Extract pure functions from original TypeScript source\n * 2. Apply type metadata transformations to the code\n *\n * This ensures pure function extraction happens on clean, untransformed TypeScript.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import {mionPlugin} from '@mionjs/devtools/vite-plugin';\n *\n * export default defineConfig({\n * plugins: [\n * mionPlugin({\n * runTypes: {\n * tsConfig: './tsconfig.json',\n * },\n * server: {\n * startServerScript: '../server/src/init.ts',\n * mode: 'onlyAOT',\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport function mionVitePlugin(options: MionPluginOptions) {\n let extractedFns: ExtractedPureFn[] | null = null;\n const pureFnOptions = options.serverPureFunctions;\n const runTypesOptions = options.runTypes;\n const aotOptions: AOTCacheOptions | undefined = options.aotCaches === true ? {} : options.aotCaches;\n const serverConfig = options.server;\n const deepkitConfig: DeepkitConfig | null = runTypesOptions ? createDeepkitConfig(runTypesOptions) : null;\n\n // Default compiler options for when deepkit is disabled\n const defaultCompilerOptions: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n };\n\n // Pure function injection counters — accumulated during transform, logged in buildEnd\n let pureServerFnCount = 0;\n let registerPureFnFactoryCount = 0;\n let pureFnFilesCount = 0;\n\n // AOT cache data - populated during buildStart (IPC) or configureServer (in-process)\n let aotData: AOTCacheData | null = null;\n let aotGenerationPromise: Promise<AOTCacheData> | null = null;\n\n // Resolved cache directory from Vite's config — set in configResolved\n let aotCacheDir = '';\n\n // SSR AOT: module loader (set in configureServer when SSR mode is active)\n let ssrLoadModule: ((url: string) => Promise<Record<string, any>>) | null = null;\n /** Whether SSR mode is active — resolved from server config */\n const ssrEnabled = serverConfig?.mode === 'viteSSR';\n /** SSR init promise: AOT generation + router/platform module loading */\n let ssrInitPromise: Promise<void> | null = null;\n\n // Persistent child process for IPC mode\n let persistentChild: ChildProcess | null = null;\n let cleanupRegistered = false;\n\n const {aotVirtualModules, aotResolvedIds} = buildAOTVirtualModuleMaps(aotOptions?.customVirtualModuleId);\n\n /** Kill persistent child process and clear reference */\n async function cleanupChild() {\n if (persistentChild) {\n await killPersistentChild(persistentChild);\n persistentChild = null;\n }\n }\n\n /** Register process exit handlers (once) */\n function registerCleanupHandlers() {\n if (cleanupRegistered) return;\n cleanupRegistered = true;\n const onExit = () => {\n if (persistentChild && !persistentChild.killed) {\n persistentChild.kill('SIGTERM');\n persistentChild = null;\n }\n };\n process.on('exit', onExit);\n process.on('SIGINT', onExit);\n process.on('SIGTERM', onExit);\n }\n\n return {\n name: 'mion',\n enforce: 'pre' as const, // literal type required: inferred 'string' is not assignable to Vite's 'pre' | 'post'\n\n config(config) {\n // Strip reflection module aliases in bundle build mode so our resolveId can stub them.\n // Vite's alias plugin runs before our resolveId, so we remove aliases here to prevent\n // them from transforming bare package names into file paths before we can intercept.\n if (aotOptions?.excludeReflection && !isRunningAsChild()) {\n const aliases = config.resolve?.alias;\n if (aliases && !Array.isArray(aliases)) {\n for (const mod of REFLECTION_MODULES) {\n delete (aliases as Record<string, string>)[mod];\n }\n }\n }\n },\n\n configResolved(config) {\n if (aotOptions) {\n aotCacheDir = resolveCacheDir(aotOptions, config.cacheDir);\n }\n },\n\n async buildStart() {\n // Generate AOT caches if server is configured\n // Skip when already running as a child process to prevent infinite recursion\n // Skip when SSR mode — configureServer will handle it\n if (serverConfig && !isRunningAsChild() && !ssrEnabled) {\n // Set port env before spawning child so the server uses the correct port\n if (serverConfig.port) process.env.MION_TEST_PORT = String(serverConfig.port);\n try {\n console.log('[mion] Generating AOT caches...');\n const resultPromise = getOrGenerateAOTCaches(serverConfig, aotOptions, aotCacheDir);\n aotGenerationPromise = resultPromise.then((r) => r.data);\n const result = await resultPromise;\n aotData = result.data;\n console.log('[mion] AOT caches generated successfully');\n logAOTCaches(aotData);\n\n // Store persistent child for IPC mode\n if (result.childProcess) {\n persistentChild = result.childProcess;\n registerCleanupHandlers();\n console.log(`[mion] Server process persisted (pid: ${persistentChild.pid})`);\n }\n\n // Non-blocking: poll server port and resolve serverReady promise (IPC mode)\n if (serverConfig.port && serverConfig.mode === 'IPC') {\n const timeout = serverConfig.waitTimeout ?? 30000;\n console.log(`[mion] Waiting for server on port ${serverConfig.port}...`);\n waitForServer(serverConfig.port, timeout)\n .then(() => {\n console.log(`[mion] Server ready on port ${serverConfig.port}`);\n onServerReady();\n })\n .catch((err) => {\n console.error(`[mion] ${err instanceof Error ? err.message : String(err)}`);\n });\n } else {\n // onlyAOT mode: no persistent server, resolve immediately\n onServerReady();\n }\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`[mion] Failed to generate AOT caches: ${message}`);\n }\n }\n },\n\n configureServer(server) {\n if (!ssrEnabled || !serverConfig) return;\n // SSR mode: use ssrLoadModule to load the server in the same Vite process.\n // ssrLoadModule uses Vite's internal transform pipeline (not HTTP),\n ssrLoadModule = (url: string) => server.ssrLoadModule(url);\n const startServerScript = resolve(serverConfig.startServerScript);\n // Single init chain: generate AOT caches → load router + platform modules\n let nodeRequestHandler: ((req: any, res: any) => void) | null = null;\n let basePath: string | null = null;\n let initFailed = false;\n\n console.log('[mion] Generating SSR AOT caches...');\n ssrInitPromise = loadSSRRouterAndGenerateAOTCaches(ssrLoadModule, startServerScript)\n .then(async (data) => {\n aotData = data;\n aotGenerationPromise = Promise.resolve(data);\n console.log('[mion] SSR AOT caches generated successfully');\n logAOTCaches(data);\n // Invalidate virtual modules so they reload with real data\n for (const resolvedId of aotResolvedIds.keys()) {\n const mod = server.moduleGraph.getModuleById(resolvedId);\n if (mod) server.moduleGraph.invalidateModule(mod);\n }\n // Load router and platform modules now that caches are ready\n const routerModule = await server.ssrLoadModule('@mionjs/router');\n const opts = routerModule.getRouterOptions();\n basePath = '/' + (opts.basePath || '').replace(/^\\//, '');\n const platformNode = await server.ssrLoadModule('@mionjs/platform-node');\n nodeRequestHandler = platformNode.httpRequestHandler;\n console.log('[mion] Dev server proxy initialized');\n onServerReady();\n })\n .catch((err) => {\n initFailed = true;\n const message = err instanceof Error ? err.message : String(err);\n console.error(`[mion] Failed to initialize SSR: ${message}`);\n });\n\n // Dev server proxy: route matching requests to mion's httpRequestHandler\n server.middlewares.use(async (req: any, res: any, next: () => void) => {\n try {\n if (!basePath && !initFailed) await ssrInitPromise;\n if (!basePath || !req.url?.startsWith(basePath)) return next();\n if (nodeRequestHandler) {\n nodeRequestHandler(req, res);\n } else {\n res.statusCode = 503;\n res.end('mion API failed to initialize');\n }\n } catch (err) {\n console.error('[mion] Dev server proxy error:', err);\n if (!res.writableEnded) {\n res.statusCode = 500;\n res.end('Internal Server Error');\n }\n }\n });\n },\n\n resolveId(id) {\n // Pure functions virtual module — always resolve, returns empty cache if not configured\n if (id === VIRTUAL_SERVER_PURE_FNS) return resolveVirtualId(id);\n // AOT virtual modules (default + custom prefix both resolve)\n if (aotVirtualModules.has(id)) return resolveVirtualId(id);\n // Stub out reflection modules in the bundle build (not needed at runtime in AOT mode)\n if (aotOptions?.excludeReflection && !isRunningAsChild() && REFLECTION_MODULES.includes(id)) {\n return resolveVirtualId(VIRTUAL_STUB_PREFIX + id);\n }\n return null;\n },\n\n async load(id) {\n // Pure functions virtual module\n if (id === resolveVirtualId(VIRTUAL_SERVER_PURE_FNS)) {\n // No serverPureFunctions configured — return empty cache\n if (!pureFnOptions) return generateServerPureFnsVirtualModule([]);\n // Lazily scan client source on first load\n if (!extractedFns) extractedFns = scanClientSource(pureFnOptions);\n return generateServerPureFnsVirtualModule(extractedFns);\n }\n\n // AOT virtual modules — check resolved ID against the map\n const aotType = aotResolvedIds.get(id);\n if (aotType) {\n const initPromise = ssrInitPromise || aotGenerationPromise;\n if (!aotData && initPromise) await initPromise;\n\n switch (aotType) {\n case 'jit-fns': {\n if (!aotData) return generateNoopModule('No-op: AOT JIT caches not generated');\n return generateJitFnsModule(aotData.jitFnsCode);\n }\n case 'pure-fns': {\n if (!aotData) return generateNoopModule('No-op: AOT pure fns not generated');\n return generatePureFnsModule(aotData.pureFnsCode);\n }\n case 'router-cache': {\n if (!aotData) return generateNoopModule('No-op: AOT router cache not generated');\n return generateRouterCacheModule(aotData.routerCacheCode);\n }\n case 'caches': {\n if (!aotData) return generateNoopCombinedModule();\n return generateCombinedCachesModule();\n }\n }\n }\n\n // Reflection module stubs (empty modules — all reflection is pre-compiled in AOT caches)\n // syntheticNamedExports tells Rollup to derive named exports from the default export,\n // so any `import {foo} from '...'` resolves to undefined without build errors.\n for (const mod of REFLECTION_MODULES) {\n if (id === resolveVirtualId(VIRTUAL_STUB_PREFIX + mod)) {\n return {code: 'export default {}', syntheticNamedExports: true};\n }\n }\n\n return null;\n },\n\n transform(code: string, fileName: string) {\n // For Vue SFC virtual modules, resolve the base path and lang for downstream tools\n const vueInfo = parseVueModuleId(fileName);\n // Strip any query params (e.g. ?macro=true from Nuxt) to get the real file path\n const basePath = fileName.includes('?') ? fileName.slice(0, fileName.indexOf('?')) : fileName;\n const filterPath = vueInfo ? vueInfo.basePath : basePath;\n\n // Skip .vue files unless they are Vue script virtual modules (?vue&type=script).\n // Bare .vue files and other .vue queries (e.g. ?macro=true from Nuxt) contain raw\n // SFC content — wait for the Vue plugin to extract the <script> block first.\n if (basePath.endsWith('.vue') && !vueInfo) return null;\n\n const lang = vueInfo?.lang || 'ts';\n const tsFileName = vueInfo ? `${vueInfo.basePath}.${lang}` : fileName;\n const isTsx = tsFileName.endsWith('.tsx') || tsFileName.endsWith('.jsx');\n\n const hasPureFns =\n code.includes('pureServerFn') || code.includes('registerPureFnFactory') || code.includes('mapFrom');\n const needsDeepkit = deepkitConfig ? deepkitConfig.filter(filterPath) : false;\n\n if (!hasPureFns && !needsDeepkit) return null;\n\n const before: ts.CustomTransformerFactory[] = [];\n const after: ts.CustomTransformerFactory[] = [];\n\n // Pure function transformer (runs first — sees clean AST)\n const collected: ExtractedPureFn[] | undefined = hasPureFns ? [] : undefined;\n if (hasPureFns) {\n before.push(createPureFnTransformerFactory(code, tsFileName, collected, pureFnOptions?.noViteClient));\n }\n\n // Deepkit has two functions: type metadata emission (follows include/exclude filters)\n // and import restoration (always runs globally for all ts.transpileModule calls).\n // afterTransformers (including requireToImport) must always be included to convert\n // deepkit's CJS require() back to ESM imports in the restored import statements.\n if (deepkitConfig) after.push(...deepkitConfig.afterTransformers);\n if (needsDeepkit) before.push(...deepkitConfig!.beforeTransformers);\n\n const baseCompilerOptions = deepkitConfig?.compilerOptions ?? defaultCompilerOptions;\n const compilerOptions = isTsx ? {...baseCompilerOptions, jsx: ts.JsxEmit.ReactJSX} : baseCompilerOptions;\n\n const result = ts.transpileModule(code, {\n compilerOptions,\n fileName: tsFileName,\n transformers: {before, after},\n });\n\n // Count injected pure functions (collector is populated synchronously by transpileModule)\n if (collected && collected.length > 0) {\n pureFnFilesCount++;\n for (const fn of collected) {\n if (fn.isFactory) registerPureFnFactoryCount++;\n else pureServerFnCount++;\n }\n }\n\n return {code: result.outputText, map: result.sourceMapText};\n },\n\n buildEnd() {\n if (pureServerFnCount > 0 || registerPureFnFactoryCount > 0) {\n const total = pureServerFnCount + registerPureFnFactoryCount;\n const parts = [\n pureServerFnCount > 0 ? `${pureServerFnCount} pureServerFn` : '',\n registerPureFnFactoryCount > 0 ? `${registerPureFnFactoryCount} registerPureFnFactory` : '',\n ].filter(Boolean);\n console.log(`[mion] Injected ${total} pure functions across ${pureFnFilesCount} files (${parts.join(', ')})`);\n }\n },\n\n async closeBundle() {\n await cleanupChild();\n },\n\n handleHotUpdate({file, server}) {\n // In dev mode, re-scan when client source changes (for pure functions)\n if (pureFnOptions) {\n const clientSrcPath = resolve(pureFnOptions.clientSrcPath);\n if (file.startsWith(clientSrcPath)) {\n const include = pureFnOptions.include || ['**/*.ts', '**/*.tsx', '**/*.vue'];\n const exclude = pureFnOptions.exclude || ['../node_modules/**', '**/.dist/**', '**/dist/**'];\n if (isIncluded(file, include, exclude)) {\n // Clear cache and invalidate virtual module\n extractedFns = null;\n const mod = server.moduleGraph.getModuleById(resolveVirtualId(VIRTUAL_SERVER_PURE_FNS));\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n return [mod];\n }\n }\n }\n }\n\n // In dev mode, regenerate AOT caches when server source changes\n // Skip when running as a child process\n if (serverConfig && !isRunningAsChild()) {\n const serverDir = resolve(serverConfig.startServerScript, '..');\n\n if (file.startsWith(serverDir)) {\n // Kill existing persistent child before regenerating\n const killPromise = cleanupChild();\n\n const regeneratePromise =\n ssrEnabled && ssrLoadModule\n ? // SSR mode: reset router and re-init via ssrLoadModule\n (async () => {\n const routerModule = await ssrLoadModule!('@mionjs/router');\n routerModule.resetRouter();\n return loadSSRRouterAndGenerateAOTCaches(\n ssrLoadModule!,\n resolve(serverConfig.startServerScript)\n );\n })()\n : // IPC mode: wait for old child to die, then spawn new\n killPromise.then(() => generateAOTCaches(serverConfig));\n\n aotGenerationPromise = regeneratePromise.then((r) => ('data' in r ? r.data : r));\n regeneratePromise\n .then((result) => {\n const data = 'data' in result ? result.data : result;\n aotData = data;\n logAOTCaches(data);\n\n // Store new persistent child if IPC mode\n if ('childProcess' in result && result.childProcess) {\n persistentChild = result.childProcess;\n console.log(`[mion] Server process re-persisted (pid: ${persistentChild!.pid})`);\n }\n\n // Non-blocking: poll restarted server and resolve serverReady promise\n if (serverConfig.port && serverConfig.mode === 'IPC') {\n const timeout = serverConfig.waitTimeout ?? 30000;\n console.log(`[mion] Waiting for restarted server on port ${serverConfig.port}...`);\n waitForServer(serverConfig.port, timeout)\n .then(() => {\n console.log(`[mion] Restarted server ready on port ${serverConfig.port}`);\n onServerReady();\n })\n .catch((err) => {\n console.error(`[mion] ${err instanceof Error ? err.message : String(err)}`);\n });\n }\n\n if (!ssrEnabled) updateDiskCache(serverConfig, aotOptions, data, aotCacheDir);\n // Invalidate all AOT virtual modules\n let invalidatedCount = 0;\n for (const resolvedId of aotResolvedIds.keys()) {\n const mod = server.moduleGraph.getModuleById(resolvedId);\n if (mod) {\n server.moduleGraph.invalidateModule(mod);\n invalidatedCount++;\n }\n }\n if (invalidatedCount > 0) {\n console.log('[mion] AOT caches regenerated, invalidating virtual modules');\n }\n })\n .catch((err) => {\n console.error('[mion] Failed to regenerate AOT caches:', err.message);\n });\n }\n }\n\n return undefined;\n },\n };\n}\n\n/** Extracts the base file path and lang from a Vue SFC virtual module ID (e.g. Component.vue?vue&type=script&lang=ts) */\nexport function parseVueModuleId(id: string): {basePath: string; lang: string | null} | null {\n const qIdx = id.indexOf('?');\n if (qIdx === -1) return null;\n const basePath = id.slice(0, qIdx);\n if (!basePath.endsWith('.vue')) return null;\n const params = new URLSearchParams(id.slice(qIdx));\n if (!params.has('vue') || params.get('type') !== 'script') return null;\n return {basePath, lang: params.get('lang')};\n}\n\n/** Checks if a file path matches the include/exclude patterns */\nexport function isIncluded(filePath: string, include: string[], exclude: string[]): boolean {\n // For Vue virtual module IDs, use the base .vue path for matching\n const vueInfo = parseVueModuleId(filePath);\n const effectivePath = vueInfo ? vueInfo.basePath : filePath;\n\n const isTs = /\\.(ts|tsx|js|jsx)$/.test(effectivePath);\n const isVue = effectivePath.endsWith('.vue');\n const isDir = effectivePath.endsWith('/');\n if (!isTs && !isVue && !isDir) return false;\n\n // Check exclude patterns\n for (const pattern of exclude) {\n if (matchGlob(effectivePath, pattern)) return false;\n }\n\n return true;\n}\n\n/** Simple glob matching for common patterns */\nfunction matchGlob(filePath: string, pattern: string): boolean {\n // Handle **/ prefix\n if (pattern.startsWith('**/')) {\n const suffix = pattern.slice(3);\n return filePath.includes(suffix.replace(/\\*/g, ''));\n }\n // Handle simple wildcard\n const regex = new RegExp('^' + pattern.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*') + '$');\n return regex.test(filePath);\n}\n\n/** AOT virtual module types — each maps to a different cache export */\nconst AOT_MODULE_TYPES = ['jit-fns', 'pure-fns', 'router-cache', 'caches'] as const;\ntype AOTModuleType = (typeof AOT_MODULE_TYPES)[number];\n\n/** Builds maps from virtual module names → AOT type for resolveId and load hooks.\n * Default 'virtual:mion-aot/*' is always registered. If customVirtualModuleId is set,\n * 'virtual:${custom}/*' is also registered — both map to the same cache data. */\nfunction buildAOTVirtualModuleMaps(customVirtualModuleId?: string) {\n const aotVirtualModules = new Map<string, AOTModuleType>();\n const aotResolvedIds = new Map<string, AOTModuleType>();\n for (const type of AOT_MODULE_TYPES) {\n const defaultId = `virtual:mion-aot/${type}`;\n aotVirtualModules.set(defaultId, type);\n aotResolvedIds.set(resolveVirtualId(defaultId), type);\n if (customVirtualModuleId) {\n const customId = `virtual:${customVirtualModuleId}/${type}`;\n aotVirtualModules.set(customId, type);\n aotResolvedIds.set(resolveVirtualId(customId), type);\n }\n }\n return {aotVirtualModules, aotResolvedIds};\n}\n\n// #################### SERVER READY ####################\n\n// Uses globalThis with Symbol.for because vitest loads vitest.config.ts and globalSetup.ts\n// in separate module contexts — without globalThis they'd get different promise instances.\nconst READY_KEY = Symbol.for('mion.serverReady');\nfunction getOrCreateServerReady(): {promise: Promise<void>; resolve: () => void} {\n if (!(globalThis as any)[READY_KEY]) {\n let _resolve: () => void;\n (globalThis as any)[READY_KEY] = {\n promise: new Promise<void>((r) => {\n _resolve = r;\n }),\n resolve: () => _resolve(),\n };\n }\n return (globalThis as any)[READY_KEY];\n}\n\n/** Promise that resolves when the server is ready. Await this in vitest globalSetup. */\nexport const serverReady: Promise<void> = getOrCreateServerReady().promise;\nconst onServerReady: () => void = getOrCreateServerReady().resolve;\n"],"names":["createDeepkitConfig","ts","killPersistentChild","REFLECTION_MODULES","resolveCacheDir","getOrGenerateAOTCaches","logAOTCaches","waitForServer","resolve","loadSSRRouterAndGenerateAOTCaches","VIRTUAL_SERVER_PURE_FNS","resolveVirtualId","VIRTUAL_STUB_PREFIX","generateServerPureFnsVirtualModule","scanClientSource","generateNoopModule","generateJitFnsModule","generatePureFnsModule","generateRouterCacheModule","generateNoopCombinedModule","generateCombinedCachesModule","createPureFnTransformerFactory","generateAOTCaches","updateDiskCache"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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AmB,SAAS,GAAG;AACjC,QAAI;AACH,eAAmB,SAAS,IAAI;AAAA,MAC7B,SAAS,IAAI,QAAc,CAAC,MAAM;AAC9B,mBAAW;AAAA,MACf,CAAC;AAAA,MACD,SAAS,MAAM,SAAA;AAAA,IAAS;AAAA,EAEhC;AACA,SAAQ,WAAmB,SAAS;AACxC;AAGO,MAAM,cAA6B,yBAAyB;AACnE,MAAM,gBAA4B,yBAAyB;;;;;"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ServerPureFunctionsOptions, DeepkitTypeOptions, AOTCacheOptions, MionServerConfig } from './types.ts';
|
|
2
|
+
export interface MionPluginOptions {
|
|
3
|
+
serverPureFunctions?: ServerPureFunctionsOptions;
|
|
4
|
+
runTypes?: DeepkitTypeOptions;
|
|
5
|
+
aotCaches?: AOTCacheOptions | true;
|
|
6
|
+
server?: MionServerConfig;
|
|
7
|
+
}
|
|
8
|
+
export declare function mionVitePlugin(options: MionPluginOptions): {
|
|
9
|
+
name: string;
|
|
10
|
+
enforce: "pre";
|
|
11
|
+
config(config: any): void;
|
|
12
|
+
configResolved(config: any): void;
|
|
13
|
+
buildStart(): Promise<void>;
|
|
14
|
+
configureServer(server: any): void;
|
|
15
|
+
resolveId(id: any): string | null;
|
|
16
|
+
load(id: any): Promise<string | {
|
|
17
|
+
code: string;
|
|
18
|
+
syntheticNamedExports: boolean;
|
|
19
|
+
} | null>;
|
|
20
|
+
transform(code: string, fileName: string): {
|
|
21
|
+
code: string;
|
|
22
|
+
map: string | undefined;
|
|
23
|
+
} | null;
|
|
24
|
+
buildEnd(): void;
|
|
25
|
+
closeBundle(): Promise<void>;
|
|
26
|
+
handleHotUpdate({ file, server }: {
|
|
27
|
+
file: any;
|
|
28
|
+
server: any;
|
|
29
|
+
}): any[] | undefined;
|
|
30
|
+
};
|
|
31
|
+
export declare function parseVueModuleId(id: string): {
|
|
32
|
+
basePath: string;
|
|
33
|
+
lang: string | null;
|
|
34
|
+
} | null;
|
|
35
|
+
export declare function isIncluded(filePath: string, include: string[], exclude: string[]): boolean;
|
|
36
|
+
export declare const serverReady: Promise<void>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
10
|
+
for (let key of __getOwnPropNames(from))
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
12
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
13
|
+
}
|
|
14
|
+
return to;
|
|
15
|
+
};
|
|
16
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
17
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
18
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
19
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
20
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
21
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
22
|
+
mod
|
|
23
|
+
));
|
|
24
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
25
|
+
const posix = require("path/posix");
|
|
26
|
+
const url = require("url");
|
|
27
|
+
async function resolveModule(moduleName, callerDir) {
|
|
28
|
+
const resolvedPath = moduleName.startsWith(".") && callerDir ? posix.resolve(callerDir, moduleName) : moduleName;
|
|
29
|
+
const metaResolve = getImportMetaResolve();
|
|
30
|
+
if (metaResolve) {
|
|
31
|
+
const resolved = await metaResolve(resolvedPath);
|
|
32
|
+
if (resolved) return resolved.startsWith("file:") ? url.fileURLToPath(resolved) : resolved;
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
if (typeof require !== "undefined" && typeof require.resolve === "function") return require.resolve(resolvedPath);
|
|
36
|
+
} catch {
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const { createRequire } = await import("module");
|
|
40
|
+
const basePath = callerDir ? posix.resolve(callerDir, "noop.js") : posix.resolve(process.cwd(), "noop.js");
|
|
41
|
+
const requireFn = createRequire(basePath);
|
|
42
|
+
return requireFn.resolve(resolvedPath);
|
|
43
|
+
} catch (err) {
|
|
44
|
+
throw new Error(`Failed to resolve module "${moduleName}": ${err instanceof Error ? err.message : String(err)}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function getImportMetaResolve() {
|
|
48
|
+
try {
|
|
49
|
+
return new Function("specifier", "return import.meta.resolve?.(specifier);");
|
|
50
|
+
} catch {
|
|
51
|
+
return void 0;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.resolveModule = resolveModule;
|
|
55
|
+
//# sourceMappingURL=resolveModule.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveModule.cjs","sources":["../../../../../src/vite-plugin/resolveModule.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/**\n * Inlined from @mionjs/core/src/utils.ts to avoid the vite plugin depending on core.\n * Keep in sync with the original implementation.\n */\n\nimport {resolve} from 'path/posix';\nimport {fileURLToPath} from 'url';\n\n/** Resolves a module path in both CJS and ESM environments. */\nexport async function resolveModule(moduleName: string, callerDir?: string): Promise<string> {\n const resolvedPath = moduleName.startsWith('.') && callerDir ? resolve(callerDir, moduleName) : moduleName;\n const metaResolve = getImportMetaResolve();\n if (metaResolve) {\n const resolved = await metaResolve(resolvedPath);\n if (resolved) return resolved.startsWith('file:') ? fileURLToPath(resolved) : resolved;\n }\n\n try {\n if (typeof require !== 'undefined' && typeof require.resolve === 'function') return require.resolve(resolvedPath);\n } catch {\n // Ignore and fall back to createRequire\n }\n\n try {\n const {createRequire} = await import('module');\n const basePath = callerDir ? resolve(callerDir, 'noop.js') : resolve(process.cwd(), 'noop.js');\n const requireFn = createRequire(basePath);\n return requireFn.resolve(resolvedPath);\n } catch (err) {\n throw new Error(`Failed to resolve module \"${moduleName}\": ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction getImportMetaResolve(): ((specifier: string) => string | Promise<string> | undefined) | undefined {\n try {\n // eslint-disable-next-line no-new-func\n return new Function('specifier', 'return import.meta.resolve?.(specifier);') as (\n specifier: string\n ) => string | Promise<string> | undefined;\n } catch {\n return undefined;\n }\n}\n"],"names":["resolve","fileURLToPath"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,eAAsB,cAAc,YAAoB,WAAqC;AACzF,QAAM,eAAe,WAAW,WAAW,GAAG,KAAK,YAAYA,cAAQ,WAAW,UAAU,IAAI;AAChG,QAAM,cAAc,qBAAA;AACpB,MAAI,aAAa;AACb,UAAM,WAAW,MAAM,YAAY,YAAY;AAC/C,QAAI,iBAAiB,SAAS,WAAW,OAAO,IAAIC,IAAAA,cAAc,QAAQ,IAAI;AAAA,EAClF;AAEA,MAAI;AACA,QAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,YAAY,WAAY,QAAO,QAAQ,QAAQ,YAAY;AAAA,EACpH,QAAQ;AAAA,EAER;AAEA,MAAI;AACA,UAAM,EAAC,cAAA,IAAiB,MAAM,OAAO,QAAQ;AAC7C,UAAM,WAAW,YAAYD,MAAAA,QAAQ,WAAW,SAAS,IAAIA,MAAAA,QAAQ,QAAQ,IAAA,GAAO,SAAS;AAC7F,UAAM,YAAY,cAAc,QAAQ;AACxC,WAAO,UAAU,QAAQ,YAAY;AAAA,EACzC,SAAS,KAAK;AACV,UAAM,IAAI,MAAM,6BAA6B,UAAU,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAAA,EACnH;AACJ;AAEA,SAAS,uBAAkG;AACvG,MAAI;AAEA,WAAO,IAAI,SAAS,aAAa,0CAA0C;AAAA,EAG/E,QAAQ;AACJ,WAAO;AAAA,EACX;AACJ;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function resolveModule(moduleName: string, callerDir?: string): Promise<string>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const pluginutils = require("@rollup/pluginutils");
|
|
4
|
+
const ts = require("typescript");
|
|
5
|
+
const typeCompiler = require("@deepkit/type-compiler");
|
|
6
|
+
const src_vitePlugin_extractPureFn = require("./extractPureFn.cjs");
|
|
7
|
+
function _interopNamespaceDefault(e) {
|
|
8
|
+
const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
|
|
9
|
+
if (e) {
|
|
10
|
+
for (const k in e) {
|
|
11
|
+
if (k !== "default") {
|
|
12
|
+
const d = Object.getOwnPropertyDescriptor(e, k);
|
|
13
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
get: () => e[k]
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
n.default = e;
|
|
21
|
+
return Object.freeze(n);
|
|
22
|
+
}
|
|
23
|
+
const ts__namespace = /* @__PURE__ */ _interopNamespaceDefault(ts);
|
|
24
|
+
const requireToImport = (context) => ({
|
|
25
|
+
transformSourceFile(sf) {
|
|
26
|
+
const newStatements = [];
|
|
27
|
+
let changed = false;
|
|
28
|
+
for (const stmt of sf.statements) {
|
|
29
|
+
const converted = tryConvertRequireToImport(context.factory, stmt);
|
|
30
|
+
if (converted) {
|
|
31
|
+
newStatements.push(converted);
|
|
32
|
+
changed = true;
|
|
33
|
+
} else {
|
|
34
|
+
newStatements.push(stmt);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return changed ? context.factory.updateSourceFile(sf, newStatements) : sf;
|
|
38
|
+
},
|
|
39
|
+
transformBundle(b) {
|
|
40
|
+
return b;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
function tryConvertRequireToImport(f, stmt) {
|
|
44
|
+
if (!ts__namespace.isVariableStatement(stmt)) return void 0;
|
|
45
|
+
const decls = stmt.declarationList.declarations;
|
|
46
|
+
if (decls.length !== 1) return void 0;
|
|
47
|
+
const decl = decls[0];
|
|
48
|
+
if (!decl.initializer || !ts__namespace.isCallExpression(decl.initializer)) return void 0;
|
|
49
|
+
const callee = decl.initializer.expression;
|
|
50
|
+
if (!ts__namespace.isIdentifier(callee) || callee.text !== "require") return void 0;
|
|
51
|
+
if (decl.initializer.arguments.length !== 1) return void 0;
|
|
52
|
+
const specArg = decl.initializer.arguments[0];
|
|
53
|
+
if (!ts__namespace.isStringLiteral(specArg)) return void 0;
|
|
54
|
+
if (ts__namespace.isObjectBindingPattern(decl.name)) {
|
|
55
|
+
const specifiers = decl.name.elements.map(
|
|
56
|
+
(el) => f.createImportSpecifier(false, void 0, f.createIdentifier(el.name.text))
|
|
57
|
+
);
|
|
58
|
+
return f.createImportDeclaration(
|
|
59
|
+
void 0,
|
|
60
|
+
f.createImportClause(false, void 0, f.createNamedImports(specifiers)),
|
|
61
|
+
f.createStringLiteral(specArg.text)
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
if (ts__namespace.isIdentifier(decl.name)) {
|
|
65
|
+
return f.createImportDeclaration(
|
|
66
|
+
void 0,
|
|
67
|
+
f.createImportClause(false, f.createIdentifier(decl.name.text), void 0),
|
|
68
|
+
f.createStringLiteral(specArg.text)
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return void 0;
|
|
72
|
+
}
|
|
73
|
+
function createDeepkitConfig(options = {}) {
|
|
74
|
+
const filter = pluginutils.createFilter(options.include ?? ["**/*.tsx", "**/*.ts"], options.exclude ?? "node_modules/**");
|
|
75
|
+
return {
|
|
76
|
+
filter: (fileName) => filter(fileName),
|
|
77
|
+
compilerOptions: {
|
|
78
|
+
target: ts__namespace.ScriptTarget.ESNext,
|
|
79
|
+
module: ts__namespace.ModuleKind.ESNext,
|
|
80
|
+
configFilePath: options.tsConfig || process.cwd() + "/tsconfig.json",
|
|
81
|
+
...options.compilerOptions || {}
|
|
82
|
+
},
|
|
83
|
+
beforeTransformers: [typeCompiler.transformer],
|
|
84
|
+
afterTransformers: [typeCompiler.declarationTransformer, requireToImport]
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function createPureFnTransformerFactory(originalSource, filePath, collector, noViteClient = false) {
|
|
88
|
+
const hasPureServerFn = originalSource.includes("pureServerFn");
|
|
89
|
+
const hasFactory = originalSource.includes("registerPureFnFactory");
|
|
90
|
+
const hasMapFrom = originalSource.includes("mapFrom");
|
|
91
|
+
const pureServerFns = hasPureServerFn ? src_vitePlugin_extractPureFn.extractPureFnsFromSource(originalSource, filePath, "pureServerFn", noViteClient) : [];
|
|
92
|
+
const factoryFns = hasFactory ? src_vitePlugin_extractPureFn.extractPureFnsFromSource(originalSource, filePath, "registerPureFnFactory") : [];
|
|
93
|
+
const mapFromFns = hasMapFrom ? src_vitePlugin_extractPureFn.extractPureFnsFromSource(originalSource, filePath, "mapFrom", noViteClient) : [];
|
|
94
|
+
return (context) => {
|
|
95
|
+
let pureIdx = 0;
|
|
96
|
+
let factoryIdx = 0;
|
|
97
|
+
let mapFromIdx = 0;
|
|
98
|
+
function visitor(node) {
|
|
99
|
+
if (ts__namespace.isCallExpression(node)) {
|
|
100
|
+
const callee = node.expression;
|
|
101
|
+
if (ts__namespace.isIdentifier(callee)) {
|
|
102
|
+
if (callee.text === "pureServerFn" && pureIdx < pureServerFns.length) {
|
|
103
|
+
if (node.arguments.length >= 2) {
|
|
104
|
+
pureIdx++;
|
|
105
|
+
return ts__namespace.visitEachChild(node, visitor, context);
|
|
106
|
+
}
|
|
107
|
+
const data = pureServerFns[pureIdx++];
|
|
108
|
+
collector?.push(data);
|
|
109
|
+
return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [
|
|
110
|
+
...node.arguments,
|
|
111
|
+
context.factory.createStringLiteral(data.bodyHash)
|
|
112
|
+
]);
|
|
113
|
+
}
|
|
114
|
+
if (callee.text === "registerPureFnFactory" && factoryIdx < factoryFns.length) {
|
|
115
|
+
if (node.arguments.length >= 4) {
|
|
116
|
+
factoryIdx++;
|
|
117
|
+
return ts__namespace.visitEachChild(node, visitor, context);
|
|
118
|
+
}
|
|
119
|
+
const data = factoryFns[factoryIdx++];
|
|
120
|
+
collector?.push(data);
|
|
121
|
+
return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [
|
|
122
|
+
...node.arguments,
|
|
123
|
+
createParsedFactoryFnNode(context.factory, data)
|
|
124
|
+
]);
|
|
125
|
+
}
|
|
126
|
+
if (callee.text === "mapFrom" && mapFromIdx < mapFromFns.length) {
|
|
127
|
+
if (node.arguments.length >= 3) {
|
|
128
|
+
mapFromIdx++;
|
|
129
|
+
return ts__namespace.visitEachChild(node, visitor, context);
|
|
130
|
+
}
|
|
131
|
+
const data = mapFromFns[mapFromIdx++];
|
|
132
|
+
collector?.push(data);
|
|
133
|
+
return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [
|
|
134
|
+
...node.arguments,
|
|
135
|
+
context.factory.createStringLiteral(data.bodyHash)
|
|
136
|
+
]);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return ts__namespace.visitEachChild(node, visitor, context);
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
transformSourceFile(sourceFile) {
|
|
144
|
+
if (pureServerFns.length === 0 && factoryFns.length === 0 && mapFromFns.length === 0) return sourceFile;
|
|
145
|
+
return ts__namespace.visitNode(sourceFile, visitor);
|
|
146
|
+
},
|
|
147
|
+
transformBundle(bundle) {
|
|
148
|
+
return bundle;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function createParsedFactoryFnNode(factory, data) {
|
|
154
|
+
return factory.createObjectLiteralExpression([
|
|
155
|
+
factory.createPropertyAssignment("bodyHash", factory.createStringLiteral(data.bodyHash)),
|
|
156
|
+
factory.createPropertyAssignment(
|
|
157
|
+
"paramNames",
|
|
158
|
+
factory.createArrayLiteralExpression(data.paramNames.map((n) => factory.createStringLiteral(n)))
|
|
159
|
+
),
|
|
160
|
+
factory.createPropertyAssignment("code", factory.createStringLiteral(data.fnBody))
|
|
161
|
+
]);
|
|
162
|
+
}
|
|
163
|
+
exports.createDeepkitConfig = createDeepkitConfig;
|
|
164
|
+
exports.createPureFnTransformerFactory = createPureFnTransformerFactory;
|
|
165
|
+
//# sourceMappingURL=transformers.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformers.cjs","sources":["../../../../../src/vite-plugin/transformers.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n// based on https://github.com/marcj/deepkit/blob/e7da3b48c50115d6e59e233eb9f018513d4d68ce/packages/vite/src/plugin.ts\n\nimport {createFilter} from '@rollup/pluginutils';\nimport * as ts from 'typescript';\nimport {transformer, declarationTransformer} from '@deepkit/type-compiler';\nimport {DeepkitTypeOptions, ExtractedPureFn} from './types.ts';\nimport {extractPureFnsFromSource} from './extractPureFn.ts';\n\n// ── Deepkit ─────────────────────────────────────────────────────────\n\n/** Deepkit configuration components for integration into the unified transform pipeline */\nexport interface DeepkitConfig {\n filter: (fileName: string) => boolean;\n compilerOptions: ts.CompilerOptions;\n beforeTransformers: ts.CustomTransformerFactory[];\n afterTransformers: ts.CustomTransformerFactory[];\n}\n\n/**\n * Post-deepkit transformer that converts require() calls back to import declarations.\n * Deepkit's getModuleType() reads tsconfig's module:NodeNext and falls back to 'cjs'\n * because ts.transpileModule doesn't set sourceFile.impliedNodeFormat. This causes\n * deepkit to emit `var {__ΩFoo} = require(\"./bar.ts\")` instead of ESM imports.\n * This transformer converts those back to `import {__ΩFoo} from \"./bar.ts\"` so Rollup\n * can properly resolve and rewrite the module specifiers.\n */\nconst requireToImport: ts.CustomTransformerFactory = (context: ts.TransformationContext): ts.CustomTransformer => ({\n transformSourceFile(sf: ts.SourceFile): ts.SourceFile {\n const newStatements: ts.Statement[] = [];\n let changed = false;\n for (const stmt of sf.statements) {\n const converted = tryConvertRequireToImport(context.factory, stmt);\n if (converted) {\n newStatements.push(converted);\n changed = true;\n } else {\n newStatements.push(stmt);\n }\n }\n return changed ? context.factory.updateSourceFile(sf, newStatements) : sf;\n },\n transformBundle(b: ts.Bundle): ts.Bundle {\n return b;\n },\n});\n\n/**\n * Converts CJS require patterns to ESM import declarations:\n * - `var {a, b} = require(\"./path\")` → `import {a, b} from \"./path\"`\n * - `var mod = require(\"./path\")` → `import mod from \"./path\"`\n */\nfunction tryConvertRequireToImport(f: ts.NodeFactory, stmt: ts.Statement): ts.ImportDeclaration | undefined {\n if (!ts.isVariableStatement(stmt)) return undefined;\n const decls = stmt.declarationList.declarations;\n if (decls.length !== 1) return undefined;\n const decl = decls[0];\n if (!decl.initializer || !ts.isCallExpression(decl.initializer)) return undefined;\n const callee = decl.initializer.expression;\n if (!ts.isIdentifier(callee) || callee.text !== 'require') return undefined;\n if (decl.initializer.arguments.length !== 1) return undefined;\n const specArg = decl.initializer.arguments[0];\n if (!ts.isStringLiteral(specArg)) return undefined;\n\n // var {a, b} = require(\"./path\") → import {a, b} from \"./path\"\n if (ts.isObjectBindingPattern(decl.name)) {\n const specifiers = decl.name.elements.map((el) =>\n f.createImportSpecifier(false, undefined, f.createIdentifier((el.name as ts.Identifier).text))\n );\n return f.createImportDeclaration(\n undefined,\n f.createImportClause(false, undefined, f.createNamedImports(specifiers)),\n f.createStringLiteral(specArg.text)\n );\n }\n\n // var mod = require(\"./path\") → import mod from \"./path\"\n if (ts.isIdentifier(decl.name)) {\n return f.createImportDeclaration(\n undefined,\n f.createImportClause(false, f.createIdentifier(decl.name.text), undefined),\n f.createStringLiteral(specArg.text)\n );\n }\n\n return undefined;\n}\n\n/** Creates deepkit config components that can be integrated into a unified ts.transpileModule call */\nexport function createDeepkitConfig(options: DeepkitTypeOptions = {}): DeepkitConfig {\n const filter = createFilter(options.include ?? ['**/*.tsx', '**/*.ts'], options.exclude ?? 'node_modules/**');\n return {\n filter: (fileName: string) => filter(fileName),\n compilerOptions: {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n configFilePath: options.tsConfig || process.cwd() + '/tsconfig.json',\n ...(options.compilerOptions || {}),\n },\n beforeTransformers: [transformer],\n afterTransformers: [declarationTransformer, requireToImport],\n };\n}\n\n// ── Pure function transformer ───────────────────────────────────────\n\n/**\n * Creates a TypeScript CustomTransformerFactory that injects build-time data into pure function calls.\n * For pureServerFn(def): injects bodyHash as 2nd argument.\n * For registerPureFnFactory(ns, id, fn): injects ParsedFactoryFn as 4th argument.\n *\n * Pre-extracts data using existing extractPureFnsFromSource to ensure hash consistency\n * with the virtual module cache (same whole-file esbuild strip + JS AST path).\n */\nexport function createPureFnTransformerFactory(\n originalSource: string,\n filePath: string,\n collector?: ExtractedPureFn[],\n noViteClient = false\n): ts.CustomTransformerFactory {\n const hasPureServerFn = originalSource.includes('pureServerFn');\n const hasFactory = originalSource.includes('registerPureFnFactory');\n const hasMapFrom = originalSource.includes('mapFrom');\n\n const pureServerFns = hasPureServerFn ? extractPureFnsFromSource(originalSource, filePath, 'pureServerFn', noViteClient) : [];\n const factoryFns = hasFactory ? extractPureFnsFromSource(originalSource, filePath, 'registerPureFnFactory') : [];\n const mapFromFns = hasMapFrom ? extractPureFnsFromSource(originalSource, filePath, 'mapFrom', noViteClient) : [];\n\n return (context: ts.TransformationContext): ts.CustomTransformer => {\n let pureIdx = 0;\n let factoryIdx = 0;\n let mapFromIdx = 0;\n\n function visitor(node: ts.Node): ts.Node {\n if (ts.isCallExpression(node)) {\n const callee = node.expression;\n if (ts.isIdentifier(callee)) {\n if (callee.text === 'pureServerFn' && pureIdx < pureServerFns.length) {\n if (node.arguments.length >= 2) {\n pureIdx++;\n return ts.visitEachChild(node, visitor, context);\n }\n const data = pureServerFns[pureIdx++];\n collector?.push(data);\n return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [\n ...node.arguments,\n context.factory.createStringLiteral(data.bodyHash),\n ]);\n }\n if (callee.text === 'registerPureFnFactory' && factoryIdx < factoryFns.length) {\n if (node.arguments.length >= 4) {\n factoryIdx++;\n return ts.visitEachChild(node, visitor, context);\n }\n const data = factoryFns[factoryIdx++];\n collector?.push(data);\n return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [\n ...node.arguments,\n createParsedFactoryFnNode(context.factory, data),\n ]);\n }\n if (callee.text === 'mapFrom' && mapFromIdx < mapFromFns.length) {\n // mapFrom(source, mapper) -> mapFrom(source, mapper, 'bodyHash')\n if (node.arguments.length >= 3) {\n mapFromIdx++;\n return ts.visitEachChild(node, visitor, context);\n }\n const data = mapFromFns[mapFromIdx++];\n collector?.push(data);\n return context.factory.updateCallExpression(node, node.expression, node.typeArguments, [\n ...node.arguments,\n context.factory.createStringLiteral(data.bodyHash),\n ]);\n }\n }\n }\n return ts.visitEachChild(node, visitor, context);\n }\n\n return {\n transformSourceFile(sourceFile: ts.SourceFile): ts.SourceFile {\n if (pureServerFns.length === 0 && factoryFns.length === 0 && mapFromFns.length === 0) return sourceFile;\n return ts.visitNode(sourceFile, visitor) as ts.SourceFile;\n },\n transformBundle(bundle: ts.Bundle): ts.Bundle {\n return bundle;\n },\n };\n };\n}\n\n/** Creates an AST node for {bodyHash: '...', paramNames: [...], code: '...'} */\nfunction createParsedFactoryFnNode(factory: ts.NodeFactory, data: ExtractedPureFn): ts.ObjectLiteralExpression {\n return factory.createObjectLiteralExpression([\n factory.createPropertyAssignment('bodyHash', factory.createStringLiteral(data.bodyHash)),\n factory.createPropertyAssignment(\n 'paramNames',\n factory.createArrayLiteralExpression(data.paramNames.map((n) => factory.createStringLiteral(n)))\n ),\n factory.createPropertyAssignment('code', factory.createStringLiteral(data.fnBody)),\n ]);\n}\n"],"names":["ts","createFilter","transformer","declarationTransformer","extractPureFnsFromSource"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAM,kBAA+C,CAAC,aAA6D;AAAA,EAC/G,oBAAoB,IAAkC;AAClD,UAAM,gBAAgC,CAAA;AACtC,QAAI,UAAU;AACd,eAAW,QAAQ,GAAG,YAAY;AAC9B,YAAM,YAAY,0BAA0B,QAAQ,SAAS,IAAI;AACjE,UAAI,WAAW;AACX,sBAAc,KAAK,SAAS;AAC5B,kBAAU;AAAA,MACd,OAAO;AACH,sBAAc,KAAK,IAAI;AAAA,MAC3B;AAAA,IACJ;AACA,WAAO,UAAU,QAAQ,QAAQ,iBAAiB,IAAI,aAAa,IAAI;AAAA,EAC3E;AAAA,EACA,gBAAgB,GAAyB;AACrC,WAAO;AAAA,EACX;AACJ;AAOA,SAAS,0BAA0B,GAAmB,MAAsD;AACxG,MAAI,CAACA,cAAG,oBAAoB,IAAI,EAAG,QAAO;AAC1C,QAAM,QAAQ,KAAK,gBAAgB;AACnC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,OAAO,MAAM,CAAC;AACpB,MAAI,CAAC,KAAK,eAAe,CAACA,cAAG,iBAAiB,KAAK,WAAW,EAAG,QAAO;AACxE,QAAM,SAAS,KAAK,YAAY;AAChC,MAAI,CAACA,cAAG,aAAa,MAAM,KAAK,OAAO,SAAS,UAAW,QAAO;AAClE,MAAI,KAAK,YAAY,UAAU,WAAW,EAAG,QAAO;AACpD,QAAM,UAAU,KAAK,YAAY,UAAU,CAAC;AAC5C,MAAI,CAACA,cAAG,gBAAgB,OAAO,EAAG,QAAO;AAGzC,MAAIA,cAAG,uBA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,qBAAOA,cAAG,eAAe,MAAM,SAAS,OAAO;AAAA,YACnD;AACA,kBAAM,OAAO,WAAW,YAAY;AACpC,uBAAW,KAAK,IAAI;AACpB,mBAAO,QAAQ,QAAQ,qBAAqB,MAAM,KAAK,YAAY,KAAK,eAAe;AAAA,cACnF,GAAG,KAAK;AAAA,cACR,QAAQ,QAAQ,oBAAoB,KAAK,QAAQ;AAAA,YAAA,CACpD;AAAA,UACL;AAAA,QACJ;AAAA,MACJ;AACA,aAAOA,cAAG,eAAe,MAAM,SAAS,OAAO;AAAA,IACnD;AAEA,WAAO;AAAA,MACH,oBAAoB,YAA0C;AAC1D,YAAI,cAAc,WAAW,KAAK,WAAW,WAAW,KAAK,WAAW,WAAW,EAAG,QAAO;AAC7F,eAAOA,cAAG,UAAU,YAAY,OAAO;AAAA,MAC3C;AAAA,MACA,gBAAgB,QAA8B;AAC1C,eAAO;AAAA,MACX;AAAA,IAAA;AAAA,EAER;AACJ;AAGA,SAAS,0BAA0B,SAAyB,MAAmD;AAC3G,SAAO,QAAQ,8BAA8B;AAAA,IACzC,QAAQ,yBAAyB,YAAY,QAAQ,oBAAoB,KAAK,QAAQ,CAAC;AAAA,IACvF,QAAQ;AAAA,MACJ;AAAA,MACA,QAAQ,6BAA6B,KAAK,WAAW,IAAI,CAAC,MAAM,QAAQ,oBAAoB,CAAC,CAAC,CAAC;AAAA,IAAA;AAAA,IAEnG,QAAQ,yBAAyB,QAAQ,QAAQ,oBAAoB,KAAK,MAAM,CAAC;AAAA,EAAA,CACpF;AACL;;;"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { DeepkitTypeOptions, ExtractedPureFn } from './types.ts';
|
|
2
|
+
import * as ts from 'typescript';
|
|
3
|
+
export interface DeepkitConfig {
|
|
4
|
+
filter: (fileName: string) => boolean;
|
|
5
|
+
compilerOptions: ts.CompilerOptions;
|
|
6
|
+
beforeTransformers: ts.CustomTransformerFactory[];
|
|
7
|
+
afterTransformers: ts.CustomTransformerFactory[];
|
|
8
|
+
}
|
|
9
|
+
export declare function createDeepkitConfig(options?: DeepkitTypeOptions): DeepkitConfig;
|
|
10
|
+
export declare function createPureFnTransformerFactory(originalSource: string, filePath: string, collector?: ExtractedPureFn[], noViteClient?: boolean): ts.CustomTransformerFactory;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { CompilerOptions } from 'typescript';
|
|
2
|
+
export interface AOTCacheOptions {
|
|
3
|
+
excludedFns?: string[];
|
|
4
|
+
excludedPureFns?: string[];
|
|
5
|
+
cache?: boolean | string;
|
|
6
|
+
excludeReflection?: boolean;
|
|
7
|
+
customVirtualModuleId?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface MionServerConfig {
|
|
10
|
+
startServerScript: string;
|
|
11
|
+
serverViteConfig?: string;
|
|
12
|
+
mode: 'onlyAOT' | 'IPC' | 'viteSSR';
|
|
13
|
+
port?: number;
|
|
14
|
+
waitTimeout?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface PureServerFnRegistryEntry {
|
|
17
|
+
readonly namespace: string;
|
|
18
|
+
readonly fnName: string;
|
|
19
|
+
readonly paramNames: string[];
|
|
20
|
+
readonly code: string;
|
|
21
|
+
readonly bodyHash: string;
|
|
22
|
+
readonly dependencies: Set<string>;
|
|
23
|
+
readonly isFactory: boolean;
|
|
24
|
+
}
|
|
25
|
+
export interface PureServerFnRegistry {
|
|
26
|
+
readonly version: string;
|
|
27
|
+
readonly entries: Record<string, PureServerFnRegistryEntry>;
|
|
28
|
+
}
|
|
29
|
+
export interface ServerPureFunctionsOptions {
|
|
30
|
+
clientSrcPath: string;
|
|
31
|
+
include?: string[];
|
|
32
|
+
exclude?: string[];
|
|
33
|
+
noViteClient?: boolean;
|
|
34
|
+
}
|
|
35
|
+
export interface ExtractedPureFn {
|
|
36
|
+
namespace: string;
|
|
37
|
+
fnName: string;
|
|
38
|
+
paramNames: string[];
|
|
39
|
+
fnBody: string;
|
|
40
|
+
bodyHash: string;
|
|
41
|
+
dependencies: Set<string>;
|
|
42
|
+
sourceFile: string;
|
|
43
|
+
isFactory: boolean;
|
|
44
|
+
}
|
|
45
|
+
export interface ParsedFactoryFn {
|
|
46
|
+
readonly bodyHash: string;
|
|
47
|
+
readonly paramNames: string[];
|
|
48
|
+
readonly code: string;
|
|
49
|
+
}
|
|
50
|
+
export type ReflectionMode = 'default' | 'explicit' | 'never';
|
|
51
|
+
export interface DeepkitTypeOptions {
|
|
52
|
+
include?: string | string[];
|
|
53
|
+
exclude?: string | string[];
|
|
54
|
+
tsConfig?: string;
|
|
55
|
+
reflection?: ReflectionMode;
|
|
56
|
+
compilerOptions?: CompilerOptions;
|
|
57
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"virtual-modules.d.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
function generateServerPureFnsVirtualModule(extractedFns) {
|
|
4
|
+
const byNamespace = /* @__PURE__ */ new Map();
|
|
5
|
+
for (const fn of extractedFns) {
|
|
6
|
+
const list = byNamespace.get(fn.namespace) || [];
|
|
7
|
+
list.push(fn);
|
|
8
|
+
byNamespace.set(fn.namespace, list);
|
|
9
|
+
}
|
|
10
|
+
const namespaceEntries = [];
|
|
11
|
+
for (const [namespace, fns] of byNamespace) {
|
|
12
|
+
const fnEntries = fns.map((fn) => generateEntryCode(fn));
|
|
13
|
+
namespaceEntries.push(` ${JSON.stringify(namespace)}: {
|
|
14
|
+
${fnEntries.join(",\n")}
|
|
15
|
+
}`);
|
|
16
|
+
}
|
|
17
|
+
return `// Auto-generated by @mionjs/server-pure-functions
|
|
18
|
+
// Do not edit manually
|
|
19
|
+
|
|
20
|
+
export const serverPureFnsCache = {
|
|
21
|
+
${namespaceEntries.join(",\n")}
|
|
22
|
+
};
|
|
23
|
+
`;
|
|
24
|
+
}
|
|
25
|
+
function generateEntryCode(fn) {
|
|
26
|
+
const paramsArray = fn.paramNames.map((p) => JSON.stringify(p)).join(", ");
|
|
27
|
+
const depsArray = [...fn.dependencies].map((d) => {
|
|
28
|
+
const parts = d.split("::");
|
|
29
|
+
return JSON.stringify(parts.length === 2 ? parts[1] : d);
|
|
30
|
+
});
|
|
31
|
+
const fnCode = fn.isFactory ? generateFactoryFn(fn) : generateDirectFn(fn);
|
|
32
|
+
return ` ${JSON.stringify(fn.fnName)}: {
|
|
33
|
+
namespace: ${JSON.stringify(fn.namespace)},
|
|
34
|
+
fnName: ${JSON.stringify(fn.fnName)},
|
|
35
|
+
paramNames: [${paramsArray}],
|
|
36
|
+
code: ${JSON.stringify(fn.fnBody)},
|
|
37
|
+
bodyHash: ${JSON.stringify(fn.bodyHash)},
|
|
38
|
+
pureFnDependencies: [${depsArray.join(", ")}],
|
|
39
|
+
isFactory: ${fn.isFactory},
|
|
40
|
+
${fnCode}
|
|
41
|
+
}`;
|
|
42
|
+
}
|
|
43
|
+
function generateDirectFn(fn) {
|
|
44
|
+
const params = fn.paramNames.join(", ");
|
|
45
|
+
const safeName = makeSafeFunctionName(fn.fnName);
|
|
46
|
+
return ` fn: function ${safeName}(${params}) {
|
|
47
|
+
${fn.fnBody}
|
|
48
|
+
},`;
|
|
49
|
+
}
|
|
50
|
+
function generateFactoryFn(fn) {
|
|
51
|
+
const params = fn.paramNames.join(", ");
|
|
52
|
+
const safeName = makeSafeFunctionName(fn.fnName);
|
|
53
|
+
return ` fn: undefined,
|
|
54
|
+
createFn: function ${safeName}(jitUtils) {
|
|
55
|
+
return (function factory(${params}) {
|
|
56
|
+
${fn.fnBody}
|
|
57
|
+
})(jitUtils);
|
|
58
|
+
},`;
|
|
59
|
+
}
|
|
60
|
+
function makeSafeFunctionName(name) {
|
|
61
|
+
const safe = name.replace(/[^a-zA-Z0-9_$]/g, "_");
|
|
62
|
+
if (/^[0-9]/.test(safe)) {
|
|
63
|
+
return "_" + safe;
|
|
64
|
+
}
|
|
65
|
+
return safe || "anonymous";
|
|
66
|
+
}
|
|
67
|
+
exports.generateServerPureFnsVirtualModule = generateServerPureFnsVirtualModule;
|
|
68
|
+
//# sourceMappingURL=virtualModule.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"virtualModule.cjs","sources":["../../../../../src/vite-plugin/virtualModule.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {ExtractedPureFn} from './types.ts';\n\n/** Generates the virtual module source code from extracted server pure functions */\nexport function generateServerPureFnsVirtualModule(extractedFns: ExtractedPureFn[]): string {\n // Group functions by namespace\n const byNamespace = new Map<string, ExtractedPureFn[]>();\n for (const fn of extractedFns) {\n const list = byNamespace.get(fn.namespace) || [];\n list.push(fn);\n byNamespace.set(fn.namespace, list);\n }\n\n // Generate nested namespace entries\n const namespaceEntries: string[] = [];\n for (const [namespace, fns] of byNamespace) {\n const fnEntries = fns.map((fn) => generateEntryCode(fn));\n namespaceEntries.push(` ${JSON.stringify(namespace)}: {\\n${fnEntries.join(',\\n')}\\n }`);\n }\n\n return `// Auto-generated by @mionjs/server-pure-functions\n// Do not edit manually\n\nexport const serverPureFnsCache = {\n${namespaceEntries.join(',\\n')}\n};\n`;\n}\n\n/** Generates the code for a single server pure function entry */\nfunction generateEntryCode(fn: ExtractedPureFn): string {\n const paramsArray = fn.paramNames.map((p) => JSON.stringify(p)).join(', ');\n\n // Convert dependencies from \"namespace::fnName\" to just \"fnName\" (same-namespace resolution)\n const depsArray = [...fn.dependencies].map((d) => {\n const parts = d.split('::');\n return JSON.stringify(parts.length === 2 ? parts[1] : d);\n });\n\n // Generate the function code\n const fnCode = fn.isFactory ? generateFactoryFn(fn) : generateDirectFn(fn);\n\n return ` ${JSON.stringify(fn.fnName)}: {\n namespace: ${JSON.stringify(fn.namespace)},\n fnName: ${JSON.stringify(fn.fnName)},\n paramNames: [${paramsArray}],\n code: ${JSON.stringify(fn.fnBody)},\n bodyHash: ${JSON.stringify(fn.bodyHash)},\n pureFnDependencies: [${depsArray.join(', ')}],\n isFactory: ${fn.isFactory},\n${fnCode}\n }`;\n}\n\n/** Generates a direct fn property for a regular pure function */\nfunction generateDirectFn(fn: ExtractedPureFn): string {\n const params = fn.paramNames.join(', ');\n const safeName = makeSafeFunctionName(fn.fnName);\n\n return ` fn: function ${safeName}(${params}) {\n ${fn.fnBody}\n },`;\n}\n\n/** Generates createFn + fn: undefined for a factory function */\nfunction generateFactoryFn(fn: ExtractedPureFn): string {\n const params = fn.paramNames.join(', ');\n const safeName = makeSafeFunctionName(fn.fnName);\n\n return ` fn: undefined,\n createFn: function ${safeName}(jitUtils) {\n return (function factory(${params}) {\n ${fn.fnBody}\n })(jitUtils);\n },`;\n}\n\n/** Makes a function name safe for use as a JavaScript identifier */\nfunction makeSafeFunctionName(name: string): string {\n // Replace any non-alphanumeric characters with underscores\n const safe = name.replace(/[^a-zA-Z0-9_$]/g, '_');\n // Ensure it starts with a letter or underscore\n if (/^[0-9]/.test(safe)) {\n return '_' + safe;\n }\n return safe || 'anonymous';\n}\n"],"names":[],"mappings":";;AAUO,SAAS,mCAAmC,cAAyC;AAExF,QAAM,kCAAkB,IAAA;AACxB,aAAW,MAAM,cAAc;AAC3B,UAAM,OAAO,YAAY,IAAI,GAAG,SAAS,KAAK,CAAA;AAC9C,SAAK,KAAK,EAAE;AACZ,gBAAY,IAAI,GAAG,WAAW,IAAI;AAAA,EACtC;AAGA,QAAM,mBAA6B,CAAA;AACnC,aAAW,CAAC,WAAW,GAAG,KAAK,aAAa;AACxC,UAAM,YAAY,IAAI,IAAI,CAAC,OAAO,kBAAkB,EAAE,CAAC;AACvD,qBAAiB,KAAK,OAAO,KAAK,UAAU,SAAS,CAAC;AAAA,EAAQ,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A;AAG/B;AAGA,SAAS,qBAAqB,MAAsB;AAEhD,QAAM,OAAO,KAAK,QAAQ,mBAAmB,GAAG;AAEhD,MAAI,SAAS,KAAK,IAAI,GAAG;AACrB,WAAO,MAAM;AAAA,EACjB;AACA,SAAO,QAAQ;AACnB;;"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { mionVitePlugin, mionVitePlugin as mionVitePlugin2, serverReady } from "./src/vite-plugin/mionVitePlugin.js";
|
|
2
|
+
import { cjsPackageJsonPlugin } from "./src/vite-plugin/cjsPackageJsonPlugin.js";
|
|
3
|
+
import { VIRTUAL_AOT_JIT_FNS, VIRTUAL_AOT_PURE_FNS, VIRTUAL_AOT_ROUTER_CACHE, VIRTUAL_SERVER_PURE_FNS } from "./src/vite-plugin/constants.js";
|
|
4
|
+
export {
|
|
5
|
+
VIRTUAL_AOT_JIT_FNS,
|
|
6
|
+
VIRTUAL_AOT_PURE_FNS,
|
|
7
|
+
VIRTUAL_AOT_ROUTER_CACHE,
|
|
8
|
+
VIRTUAL_SERVER_PURE_FNS as VIRTUAL_PURE_FUNCTIONS,
|
|
9
|
+
cjsPackageJsonPlugin,
|
|
10
|
+
mionVitePlugin as mionPlugin,
|
|
11
|
+
mionVitePlugin2 as mionVitePlugin,
|
|
12
|
+
serverReady
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare const ALLOWED_GLOBALS: Set<string>;
|
|
2
|
+
export declare const FORBIDDEN_IDENTIFIERS: Set<string>;
|
|
3
|
+
export declare const PURE_FN_CALL_NAMES: readonly ["pureServerFn", "registerPureFnFactory", "mapFrom"];
|
|
4
|
+
export declare const PURE_FN_SOURCE_PACKAGES: readonly ["@mionjs/core", "@mionjs/client"];
|