@analogjs/vite-plugin-angular 3.0.0-beta.5 → 3.0.0-beta.51
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/migrations/migrate-setup-vitest/migrate-setup-vitest.js +2 -1
- package/migrations/migrate-setup-vitest/migrate-setup-vitest.js.map +1 -1
- package/ngp/LICENSE +21 -0
- package/ngp/api.mjs +46806 -0
- package/ngp/build.json +4 -0
- package/ngp/ng_analyze.cjs +601 -0
- package/ngp/ng_analyze_bg.wasm +0 -0
- package/package.json +4 -1
- package/src/index.d.ts +2 -0
- package/src/index.js +3 -1
- package/src/index.js.map +1 -1
- package/src/lib/analog-plugin-interop.js +1 -1
- package/src/lib/angular-build-context.d.ts +215 -0
- package/src/lib/angular-build-context.js +361 -0
- package/src/lib/angular-build-context.js.map +1 -0
- package/src/lib/angular-build-optimizer-plugin.d.ts +6 -4
- package/src/lib/angular-build-optimizer-plugin.js +24 -9
- package/src/lib/angular-build-optimizer-plugin.js.map +1 -1
- package/src/lib/angular-jit-plugin.d.ts +5 -3
- package/src/lib/angular-jit-plugin.js +14 -6
- package/src/lib/angular-jit-plugin.js.map +1 -1
- package/src/lib/angular-vite-plugin.d.ts +6 -109
- package/src/lib/angular-vite-plugin.js +8 -1249
- package/src/lib/angular-vite-plugin.js.map +1 -1
- package/src/lib/angular-vitest-plugin.d.ts +3 -2
- package/src/lib/angular-vitest-plugin.js +6 -3
- package/src/lib/angular-vitest-plugin.js.map +1 -1
- package/src/lib/companion-plugins.d.ts +7 -0
- package/src/lib/companion-plugins.js +38 -0
- package/src/lib/companion-plugins.js.map +1 -0
- package/src/lib/compilation-api/compilation-api-plugin.d.ts +11 -2
- package/src/lib/compilation-api/compilation-api-plugin.js +154 -282
- package/src/lib/compilation-api/compilation-api-plugin.js.map +1 -1
- package/src/lib/compiler/compile.d.ts +1 -1
- package/src/lib/compiler/compile.js +190 -145
- package/src/lib/compiler/compile.js.map +1 -1
- package/src/lib/compiler/defer.d.ts +2 -3
- package/src/lib/compiler/defer.js +12 -14
- package/src/lib/compiler/defer.js.map +1 -1
- package/src/lib/compiler/dts-reader.d.ts +6 -1
- package/src/lib/compiler/dts-reader.js +19 -10
- package/src/lib/compiler/dts-reader.js.map +1 -1
- package/src/lib/compiler/hmr.d.ts +4 -0
- package/src/lib/compiler/hmr.js +7 -2
- package/src/lib/compiler/hmr.js.map +1 -1
- package/src/lib/compiler/index.d.ts +2 -2
- package/src/lib/compiler/index.js +4 -4
- package/src/lib/compiler/jit-metadata.d.ts +3 -1
- package/src/lib/compiler/jit-metadata.js +10 -8
- package/src/lib/compiler/jit-metadata.js.map +1 -1
- package/src/lib/compiler/jit-transform.js +2 -2
- package/src/lib/compiler/jit-transform.js.map +1 -1
- package/src/lib/compiler/js-emitter.d.ts +0 -3
- package/src/lib/compiler/js-emitter.js +3 -21
- package/src/lib/compiler/js-emitter.js.map +1 -1
- package/src/lib/compiler/registry.d.ts +7 -1
- package/src/lib/compiler/registry.js +23 -3
- package/src/lib/compiler/registry.js.map +1 -1
- package/src/lib/compiler/resource-inliner.d.ts +8 -9
- package/src/lib/compiler/resource-inliner.js +10 -18
- package/src/lib/compiler/resource-inliner.js.map +1 -1
- package/src/lib/compiler/style-ast.d.ts +9 -1
- package/src/lib/compiler/style-ast.js +26 -5
- package/src/lib/compiler/style-ast.js.map +1 -1
- package/src/lib/compiler/type-elision.d.ts +4 -3
- package/src/lib/compiler/type-elision.js +10 -11
- package/src/lib/compiler/type-elision.js.map +1 -1
- package/src/lib/compiler/utils.d.ts +9 -7
- package/src/lib/compiler/utils.js +49 -9
- package/src/lib/compiler/utils.js.map +1 -1
- package/src/lib/component-scanner.d.ts +74 -0
- package/src/lib/component-scanner.js +178 -0
- package/src/lib/component-scanner.js.map +1 -0
- package/src/lib/component-styles-plugin.d.ts +52 -0
- package/src/lib/component-styles-plugin.js +353 -0
- package/src/lib/component-styles-plugin.js.map +1 -0
- package/src/lib/compose-angular-plugins.d.ts +12 -0
- package/src/lib/compose-angular-plugins.js +31 -0
- package/src/lib/compose-angular-plugins.js.map +1 -0
- package/src/lib/dev-server-mode-plugin.d.ts +7 -0
- package/src/lib/dev-server-mode-plugin.js +23 -0
- package/src/lib/dev-server-mode-plugin.js.map +1 -0
- package/src/lib/fast-compile-api.d.ts +62 -0
- package/src/lib/fast-compile-api.js +12 -0
- package/src/lib/fast-compile-api.js.map +1 -0
- package/src/lib/fast-compile-plugin.d.ts +6 -1
- package/src/lib/fast-compile-plugin.js +167 -107
- package/src/lib/fast-compile-plugin.js.map +1 -1
- package/src/lib/host.d.ts +3 -0
- package/src/lib/host.js +4 -2
- package/src/lib/host.js.map +1 -1
- package/src/lib/live-reload-plugin.d.ts +6 -3
- package/src/lib/live-reload-plugin.js +13 -6
- package/src/lib/live-reload-plugin.js.map +1 -1
- package/src/lib/ngp-compile-api.d.ts +55 -0
- package/src/lib/ngp-compile-api.js +12 -0
- package/src/lib/ngp-compile-api.js.map +1 -0
- package/src/lib/ngp-compile-plugin.d.ts +4 -0
- package/src/lib/ngp-compile-plugin.js +662 -0
- package/src/lib/ngp-compile-plugin.js.map +1 -0
- package/src/lib/ngtsc-compile-plugin.d.ts +23 -0
- package/src/lib/ngtsc-compile-plugin.js +778 -0
- package/src/lib/ngtsc-compile-plugin.js.map +1 -0
- package/src/lib/nx-folder-plugin.d.ts +6 -5
- package/src/lib/nx-folder-plugin.js +12 -7
- package/src/lib/nx-folder-plugin.js.map +1 -1
- package/src/lib/plugins/file-replacements.plugin.d.ts +6 -0
- package/src/lib/plugins/file-replacements.plugin.js +1 -0
- package/src/lib/plugins/file-replacements.plugin.js.map +1 -1
- package/src/lib/router-plugin.d.ts +5 -1
- package/src/lib/router-plugin.js +13 -4
- package/src/lib/router-plugin.js.map +1 -1
- package/src/lib/utils/compilation-shared.js +1 -1
- package/src/lib/utils/devkit.js +1 -1
- package/src/lib/utils/hmr-component-updates.d.ts +7 -0
- package/src/lib/utils/hmr-component-updates.js +87 -0
- package/src/lib/utils/hmr-component-updates.js.map +1 -0
- package/src/lib/utils/lsp-type-checker.d.ts +75 -0
- package/src/lib/utils/lsp-type-checker.js +531 -0
- package/src/lib/utils/lsp-type-checker.js.map +1 -0
- package/src/lib/utils/ngp-host-fs.d.ts +32 -0
- package/src/lib/utils/ngp-host-fs.js +104 -0
- package/src/lib/utils/ngp-host-fs.js.map +1 -0
- package/src/lib/utils/plugin-config.d.ts +15 -8
- package/src/lib/utils/plugin-config.js +18 -5
- package/src/lib/utils/plugin-config.js.map +1 -1
- package/src/lib/utils/stylesheet-warning.d.ts +2 -0
- package/src/lib/utils/stylesheet-warning.js +11 -0
- package/src/lib/utils/stylesheet-warning.js.map +1 -0
- package/src/lib/utils/tsconfig-resolver.js +1 -1
- package/src/lib/virtual-modules-plugin.d.ts +11 -3
- package/src/lib/virtual-modules-plugin.js +43 -12
- package/src/lib/virtual-modules-plugin.js.map +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ngtsc-compile-plugin.js","names":[],"sources":["../../../src/lib/ngtsc-compile-plugin.ts"],"sourcesContent":["import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n} from 'node:path';\nimport { union } from 'es-toolkit';\nimport * as compilerCli from '@angular/compiler-cli';\nimport type { NgtscProgram } from '@angular/compiler-cli';\nimport type * as ts from 'typescript';\nimport type * as vite from 'vite';\nimport {\n normalizePath,\n preprocessCSS,\n type ModuleNode,\n type Plugin,\n type ResolvedConfig,\n type ViteDevServer,\n} from 'vite';\n\nimport {\n createAngularBuildContext,\n isAngularBuildContext,\n type AngularBuildContext,\n type AngularBuildContextOptions,\n} from './angular-build-context.js';\nimport {\n StyleUrlsResolver,\n TemplateUrlsResolver,\n} from './component-resolvers.js';\nimport {\n findTemplateOwnerModules,\n getModulesForChangedFile,\n handleDirectComponentStyleHmr,\n isModuleForChangedResource,\n markModuleSelfAccepting,\n} from './component-styles-plugin.js';\nimport { isComponentStyleSheet } from './encapsulation-plugin.js';\nimport {\n augmentHostWithCaching,\n augmentHostWithModuleResolution,\n augmentHostWithResources,\n augmentProgramWithVersioning,\n mergeTransformers,\n} from './host.js';\nimport { createHotUpdateBatcher } from './hot-update-batch.js';\nimport type { EmitFileResult } from './models.js';\nimport type {\n FileReplacementSSR,\n FileReplacementWith,\n} from './plugins/file-replacements.plugin.js';\nimport {\n describeStylesheetContent,\n injectViteIgnoreForHmrMetadata,\n} from './utils/compilation-shared.js';\nimport { releaseCssPreprocessorWorkers } from './utils/css-preprocessor-workers.js';\nimport {\n activateDeferredDebug,\n debugCompiler,\n debugCompilerV,\n debugEmit,\n debugEmitV,\n debugHmr,\n debugHmrV,\n debugStyles,\n} from './utils/debug.js';\nimport {\n createJitResourceTransformer,\n SourceFileCache,\n} from './utils/devkit.js';\nimport { toJitInlineStyleId } from './utils/jit-inline-styles.js';\nimport {\n createDepOptimizerConfig,\n EXCLUDED_TS_EXT_REGEX,\n TS_EXT_REGEX,\n} from './utils/plugin-config.js';\nimport { getJsTransformConfigKey } from './utils/rolldown.js';\nimport { markStylePathSafe } from './utils/safe-module-paths.js';\nimport type { SourceFileCache as SourceFileCacheType } from './utils/source-file-cache.js';\nimport { toVirtualRawId } from './utils/virtual-ids.js';\nimport {\n loadAngularVirtualModule,\n resolveAngularVirtualId,\n} from './virtual-modules-plugin.js';\n\nconst require = createRequire(import.meta.url);\n\ninterface DeclarationFile {\n declarationFileDir: string;\n declarationPath: string;\n data: string;\n}\n\nexport interface FileMetadataResult {\n errors?: string[];\n warnings?: (string | ts.DiagnosticMessageChain)[];\n hmrUpdateCode?: string | null;\n hmrEligible?: boolean;\n}\n\nexport function evictDeletedFileMetadata(\n file: string,\n {\n classNamesMap,\n fileTransformMap,\n }: {\n classNamesMap: Map<string, string>;\n fileTransformMap: Map<string, string>;\n },\n): void {\n const normalizedFile = normalizePath(file.split('?')[0]);\n classNamesMap.delete(normalizedFile);\n fileTransformMap.delete(normalizedFile);\n}\n\nexport function createFsWatcherCacheInvalidator(\n invalidateFsCaches: () => void,\n invalidateTsconfigCaches: () => void,\n performCompilation: () => Promise<void>,\n): () => Promise<void> {\n return async (): Promise<void> => {\n invalidateFsCaches();\n invalidateTsconfigCaches();\n await performCompilation();\n };\n}\n\n/**\n * Compiles Angular TypeScript sources using `@angular/compiler-cli` (`NgtscProgram`).\n */\nexport function ngtscCompilePlugin(\n ctxOrOptions?: AngularBuildContext | AngularBuildContextOptions,\n): Plugin {\n const ctx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : createAngularBuildContext({\n ...ctxOrOptions,\n compilationBackend: 'ngtsc',\n });\n\n const ts = require('typescript') as typeof import('typescript');\n\n let cachedBuilder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram\n | undefined;\n let nextProgram: NgtscProgram | undefined;\n let cachedHost: ts.CompilerHost | undefined;\n let cachedHostKey: string | undefined;\n\n function invalidateFsCaches(): void {\n ctx.tsconfigResolver.invalidateIncludeCache();\n }\n\n function invalidateTsconfigCaches(): void {\n ctx.tsconfigResolver.invalidateTsconfigCaches();\n cachedHost = undefined;\n cachedHostKey = undefined;\n }\n\n const sourceFileCache: SourceFileCacheType = new SourceFileCache();\n const tsSourceFileCache = new Map<string, ts.SourceFile>();\n\n function invalidateSourceFiles(files: Set<string>): void {\n for (const file of files) {\n tsSourceFileCache.delete(normalizePath(file));\n }\n sourceFileCache.invalidate(files);\n }\n\n const { jit, isTest } = ctx.options;\n let viteServer: ViteDevServer | undefined;\n\n const styleUrlsResolver = new StyleUrlsResolver();\n const templateUrlsResolver = new TemplateUrlsResolver();\n let outputFile: ((file: string) => void) | undefined;\n const outputFiles = new Map<string, EmitFileResult>();\n\n // Vite resolves module ids through symlinks, while the TypeScript program\n // names files by the tsconfig path as given. Both sides go through\n // `toRealPath` so `/var/...` and `/private/var/...` (macOS) or a symlinked\n // workspace name the same file.\n const realPaths = new Map<string, string>();\n const toRealPath = (file: string): string => {\n const normalizedFile = normalizePath(file);\n const cachedPath = realPaths.get(normalizedFile);\n if (cachedPath !== undefined) {\n return cachedPath;\n }\n\n let realPath: string;\n try {\n realPath = normalizePath(realpathSync(normalizedFile));\n } catch {\n // Not on disk (yet): leave it as is and don't cache it.\n return normalizedFile;\n }\n realPaths.set(normalizedFile, realPath);\n return realPath;\n };\n\n const normalizeEmitterLookupId = (file: string): string => {\n const normalizedFile = normalizePath(file);\n\n if (!normalizedFile.startsWith('/@fs/')) {\n return toRealPath(normalizedFile);\n }\n\n const fsPath = normalizedFile\n .slice('/@fs'.length)\n .replace(/^\\/([A-Za-z]:\\/)/, '$1');\n\n return toRealPath(fsPath);\n };\n\n const describeEmitMarkers = (content: string) => ({\n contentLength: content.length,\n hasCmp: content.includes('ɵcmp'),\n hasFac: content.includes('ɵfac'),\n hasProv: content.includes('ɵprov'),\n hasDecorate: content.includes('__decorate'),\n hasMetadata: content.includes('__metadata'),\n });\n\n const fileEmitter = (file: string): EmitFileResult | undefined => {\n const normalizedFile = normalizeEmitterLookupId(file);\n const hadCachedEmit = outputFiles.has(normalizedFile);\n outputFile?.(normalizedFile);\n const emittedResult = outputFiles.get(normalizedFile);\n debugEmitV('fileEmitter lookup', {\n requestFile: file,\n normalizedFile,\n hadCachedEmit,\n hasOutputFileHook: !!outputFile,\n emitted: !!emittedResult,\n knownOutputCount: outputFiles.size,\n contentLength: emittedResult?.content?.length ?? 0,\n errorCount: emittedResult?.errors?.length ?? 0,\n warningCount: emittedResult?.warnings?.length ?? 0,\n });\n return emittedResult;\n };\n\n ctx.hmr.setFileEmitter((file) => fileEmitter(file));\n\n const compilerApi = {\n angularCompiler: true as const,\n getTsConfigPath: (): string => ctx.resolveTsConfigPath(),\n getSourceMap: (id: string): string | undefined =>\n outputFiles.get(normalizeEmitterLookupId(id))?.map,\n hasEmitted: (id: string): boolean =>\n outputFiles.has(normalizeEmitterLookupId(id)),\n };\n\n ctx.registerCompiler({\n name: '@analogjs/vite-plugin-angular',\n getTsConfigPath: compilerApi.getTsConfigPath,\n getSourceMap: compilerApi.getSourceMap,\n hasEmitted: compilerApi.hasEmitted,\n });\n\n let initialCompilation = false;\n let activeBuilds = 0;\n let closeRequested = false;\n const declarationFiles: DeclarationFile[] = [];\n const fileTransformMap = new Map<string, string>();\n let styleTransform: (\n code: string,\n filename: string,\n ) => Promise<vite.PreprocessCSSResult>;\n let pendingCompilation: Promise<void> | null = null;\n let compilationLock = Promise.resolve();\n const hotUpdates = createHotUpdateBatcher((ids) =>\n performCompilation(ctx.resolvedConfig!, ids),\n );\n\n function releaseCompilation(): void {\n cachedBuilder = undefined;\n nextProgram = undefined;\n cachedHost = undefined;\n cachedHostKey = undefined;\n outputFile = undefined;\n outputFiles.clear();\n fileTransformMap.clear();\n tsSourceFileCache.clear();\n sourceFileCache.clear();\n sourceFileCache.modifiedFiles.clear();\n sourceFileCache.babelFileCache?.clear();\n sourceFileCache.typeScriptFileCache?.clear();\n sourceFileCache.referencedFiles = undefined;\n ctx.tsconfigResolver.invalidateAll();\n releaseCssPreprocessorWorkers();\n ctx.styles.clear();\n }\n\n async function closeCompilation(): Promise<void> {\n closeRequested = false;\n hotUpdates.close();\n await compilationLock;\n declarationFiles.forEach(\n ({ declarationFileDir, declarationPath, data }) => {\n mkdirSync(declarationFileDir, { recursive: true });\n writeFileSync(declarationPath, data, 'utf-8');\n },\n );\n declarationFiles.length = 0;\n releaseCompilation();\n }\n\n function normalizeSourceMapSources(map: string, id: string): string {\n const sourceMap = JSON.parse(map) as {\n sources?: string[];\n sourceRoot?: string;\n };\n const sourceDirectory = dirname(id);\n const sourceRoot = sourceMap.sourceRoot ?? '';\n sourceMap.sources = sourceMap.sources?.map((source) => {\n if (isAbsolute(source) || /^[a-z][a-z\\d+.-]*:/i.test(source)) {\n return normalizePath(source);\n }\n return normalizePath(resolve(sourceDirectory, sourceRoot, source));\n });\n delete sourceMap.sourceRoot;\n return JSON.stringify(sourceMap);\n }\n\n async function performCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n let releaseLock: (() => unknown) | undefined;\n const previousLock = compilationLock;\n compilationLock = new Promise<void>((r) => {\n releaseLock = r;\n });\n try {\n await previousLock;\n await ctx.refreshIntegrations(config);\n await _doPerformCompilation(config, ids);\n } finally {\n releaseLock!();\n }\n }\n\n /**\n * This method shares mutable state and performs the actual compilation work.\n * It should not be called concurrently. Use `performCompilation` which wraps\n * this method in a lock to ensure only one compilation runs at a time.\n */\n async function _doPerformCompilation(\n config: ResolvedConfig,\n ids?: string[],\n ): Promise<void> {\n const isProd = config.mode === 'production';\n const modifiedFiles = new Set<string>(ids ?? []);\n invalidateSourceFiles(modifiedFiles);\n\n if (ids?.length) {\n for (const id of ids) {\n fileTransformMap.delete(id);\n }\n }\n\n const resolvedTsConfigPath = ctx.resolveTsConfigPath();\n const cached = ctx.tsconfigResolver.getCachedTsconfigOptions(\n resolvedTsConfigPath,\n config,\n );\n\n // Clone options before mutation (preserve cache purity)\n const tsCompilerOptions = { ...cached.options };\n let rootNames = [...cached.rootNames];\n\n if (ctx.shouldExternalizeStyles()) {\n tsCompilerOptions['externalRuntimeStyles'] = true;\n }\n\n if (ctx.shouldEnableLiveReload()) {\n tsCompilerOptions['_enableHmr'] = true;\n // Workaround for https://github.com/angular/angular/issues/59310\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n debugCompiler('tsCompilerOptions (NgtscProgram path)', {\n liveReload: ctx.options.liveReload,\n viteHmr: ctx.hasViteHmrTransport(),\n externalizeStylesRequested: ctx.externalizeStylesRequested,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n externalRuntimeStyles: !!tsCompilerOptions['externalRuntimeStyles'],\n hmrEnabled: !!tsCompilerOptions['_enableHmr'],\n });\n\n if (tsCompilerOptions['compilationMode'] === 'partial') {\n // These options can't be false in partial mode\n tsCompilerOptions['supportTestBed'] = true;\n tsCompilerOptions['supportJitMode'] = true;\n }\n\n if (!isTest && config.build?.lib) {\n tsCompilerOptions['declaration'] = true;\n tsCompilerOptions['declarationMap'] = ctx.watchMode;\n tsCompilerOptions['inlineSources'] = true;\n }\n\n if (isTest) {\n // Allow `TestBed.overrideXXX()` APIs.\n tsCompilerOptions['supportTestBed'] = true;\n }\n\n const replacements = ctx.options.fileReplacements.map((rp) =>\n join(\n ctx.options.workspaceRoot,\n (rp as FileReplacementSSR).ssr || (rp as FileReplacementWith).with,\n ),\n );\n // Merge + dedupe root names\n rootNames = [\n ...new Set(\n union(\n union(rootNames, ctx.tsconfigResolver.ensureIncludeCache()),\n replacements,\n ).map(toRealPath),\n ),\n ];\n const hostKey = JSON.stringify(tsCompilerOptions);\n let host: ts.CompilerHost;\n\n if (cachedHost && cachedHostKey === hostKey) {\n host = cachedHost;\n } else {\n host = ts.createIncrementalCompilerHost(tsCompilerOptions, {\n ...ts.sys,\n readFile(path: string, encoding?: string) {\n if (fileTransformMap.has(path)) {\n return fileTransformMap.get(path);\n }\n\n const file = ts.sys.readFile.call(null, path, encoding);\n\n if (file) {\n fileTransformMap.set(path, file);\n }\n\n return file;\n },\n });\n augmentHostWithModuleResolution(host, tsCompilerOptions);\n cachedHost = host;\n cachedHostKey = hostKey;\n\n // Only store cache if in watch mode\n if (ctx.watchMode) {\n augmentHostWithCaching(host, tsSourceFileCache);\n }\n }\n\n if (!jit) {\n const externalizeStyles = !!tsCompilerOptions['externalRuntimeStyles'];\n const stylesheetRegistry = ctx.styles.resetRegistry(externalizeStyles);\n debugStyles('stylesheet registry initialized (NgtscProgram path)', {\n externalizeStyles,\n });\n augmentHostWithResources(host, styleTransform, {\n inlineStylesExtension: ctx.options.inlineStylesExtension,\n isProd,\n stylesheetRegistry,\n sourceFileCache,\n stylePreprocessor: ctx.stylePreprocessor,\n logger: ctx.resolvedConfig?.logger,\n isBuild: ctx.resolvedConfig?.command === 'build',\n });\n }\n\n /**\n * Creates a new NgtscProgram to analyze/re-analyze\n * the source files and create a file emitter.\n * This is shared between an initial build and a hot update.\n */\n let typeScriptProgram: ts.Program;\n let angularCompiler: NgtscProgram['compiler'] | undefined;\n // Declaration changes can invalidate diagnostics in unchanged consumers.\n let builder:\n | ts.BuilderProgram\n | ts.EmitAndSemanticDiagnosticsBuilderProgram;\n const oldBuilder = ids?.some((id) => EXCLUDED_TS_EXT_REGEX.test(id))\n ? undefined\n : (cachedBuilder ?? ts.readBuilderProgram(tsCompilerOptions, host));\n\n if (!jit) {\n // Create the Angular specific program that contains the Angular compiler\n const angularProgram: NgtscProgram = new compilerCli.NgtscProgram(\n rootNames,\n tsCompilerOptions,\n host,\n nextProgram,\n );\n angularCompiler = angularProgram.compiler;\n typeScriptProgram = angularProgram.compiler.getCurrentProgram();\n augmentProgramWithVersioning(typeScriptProgram);\n\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n typeScriptProgram,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n nextProgram = angularProgram;\n } else {\n builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(\n rootNames,\n tsCompilerOptions,\n host,\n oldBuilder as ts.EmitAndSemanticDiagnosticsBuilderProgram,\n );\n\n typeScriptProgram = builder.getProgram();\n }\n\n if (!ctx.watchMode) {\n // When not in watch mode, the startup cost of the incremental analysis can be avoided by\n // using an abstract builder that only wraps a TypeScript program.\n builder = ts.createAbstractBuilder(typeScriptProgram, host, oldBuilder);\n }\n cachedBuilder = builder;\n\n if (angularCompiler) {\n await angularCompiler.analyzeAsync();\n\n if (!ctx.options.disableTypeChecking) {\n // TypeScript builds the program diagnostics lazily and records why each\n // file is in the program as an index into `referencedFiles`, which\n // includes the shim references Angular tags onto every source file.\n // `prepareEmit()` below removes those tags, so a diagnostic that\n // explains a file (e.g. TS6059 for a file outside `rootDir`) would\n // otherwise throw while it is built for the first file's diagnostics.\n typeScriptProgram.getOptionsDiagnostics();\n }\n }\n\n const beforeTransformers = jit\n ? [\n compilerCli.constructorParametersDownlevelTransform(\n builder.getProgram(),\n ),\n createJitResourceTransformer(() =>\n builder.getProgram().getTypeChecker(),\n ),\n ]\n : [];\n\n const transformers = mergeTransformers(\n { before: beforeTransformers },\n jit ? {} : angularCompiler!.prepareEmit().transformers,\n );\n\n const fileMetadata = getFileMetadata(\n builder,\n angularCompiler,\n ctx.options.liveReload,\n ctx.options.disableTypeChecking,\n ctx.hmr.classNames,\n );\n\n const writeFileCallback: ts.WriteFileCallback = (\n _filename,\n content,\n _a,\n _b,\n sourceFiles,\n ) => {\n if (!sourceFiles?.length) {\n return;\n }\n\n const filename = normalizePath(sourceFiles[0].fileName);\n\n // Skip declaration outputs and declaration source files.\n if (\n filename.includes('ngtypecheck.ts') ||\n filename.includes('.d.') ||\n _filename.endsWith('.d.ts') ||\n _filename.endsWith('.d.mts') ||\n _filename.endsWith('.d.cts')\n ) {\n return;\n }\n\n // TS emits the .js.map file separately — attach it to the entry for\n // the same source file so the transform hook can return the map and\n // coverage tools can chain maps back to the original TS. The .map can\n // arrive before or after the .js, so upsert in either order. Match\n // only `.js.map` (not `.d.ts.map`) so a future `declarationMap: true`\n // doesn't clobber the JS source map with the declaration map.\n if (/\\.[cm]?js\\.map$/.test(_filename)) {\n const existing = outputFiles.get(filename);\n outputFiles.set(filename, {\n ...(existing ?? { dependencies: [] }),\n map: content,\n });\n return;\n }\n\n const metadata = ctx.watchMode ? fileMetadata(filename) : {};\n const existing = outputFiles.get(filename);\n\n outputFiles.set(filename, {\n ...(existing ?? {}),\n content,\n dependencies: [],\n errors: metadata.errors,\n warnings: metadata.warnings,\n hmrUpdateCode: metadata.hmrUpdateCode,\n hmrEligible: metadata.hmrEligible,\n });\n debugEmitV('registered ngtsc output', {\n filename,\n ...describeEmitMarkers(content),\n errorCount: metadata.errors?.length ?? 0,\n warningCount: metadata.warnings?.length ?? 0,\n hmrEligible: !!metadata.hmrEligible,\n knownOutputCount: outputFiles.size,\n });\n };\n\n const writeOutputFile = (id: string): void => {\n const sourceFile = builder.getSourceFile(toRealPath(id));\n if (!sourceFile) {\n return;\n }\n\n let content = '';\n let map: string | undefined;\n let mapFilename: string | undefined;\n builder.emit(\n sourceFile,\n (filename, data) => {\n if (/\\.[cm]?js$/.test(filename)) {\n content = data;\n }\n\n if (/\\.[cm]?js\\.map$/.test(filename)) {\n map = data;\n mapFilename = filename;\n }\n\n if (\n !ctx.watchMode &&\n !isTest &&\n /\\.d\\.ts/.test(filename) &&\n !filename.includes('.ngtypecheck.')\n ) {\n // output to library root instead /src\n const root = toRealPath(config.root);\n const declarationPath = resolve(\n root,\n config.build.outDir,\n relative(root, filename),\n ).replace('/src/', '/');\n\n const declarationFileDir = declarationPath\n .replace(basename(filename), '')\n .replace('/src/', '/');\n\n declarationFiles.push({\n declarationFileDir,\n declarationPath,\n data,\n });\n }\n },\n undefined /* cancellationToken */,\n undefined /* emitOnlyDtsFiles */,\n transformers,\n );\n\n writeFileCallback(id, content, false, undefined, [sourceFile]);\n if (map !== undefined && mapFilename !== undefined) {\n // Use the filename TypeScript emitted (handles `.cts`/`.mts` as well\n // as `.ts`) instead of regex-replacing the source `.ts` extension.\n writeFileCallback(mapFilename, map, false, undefined, [sourceFile]);\n }\n\n if (angularCompiler) {\n angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile);\n }\n };\n\n if (ctx.watchMode) {\n if (ids && ids.length > 0) {\n ids.forEach((id) => writeOutputFile(id));\n } else if (isTest) {\n /**\n * Only block the server from starting up\n * during testing.\n */\n while (\n (\n builder as ts.EmitAndSemanticDiagnosticsBuilderProgram\n ).emitNextAffectedFile(\n writeFileCallback,\n undefined,\n undefined,\n transformers,\n )\n ) {\n /* empty */\n }\n }\n }\n\n if (!isTest) {\n /**\n * Perf: Output files on demand so the dev server\n * isn't blocked when emitting files.\n */\n outputFile = writeOutputFile;\n }\n }\n\n return {\n name: '@analogjs/vite-plugin-angular',\n api: compilerApi,\n async config(config, { command, mode }) {\n activateDeferredDebug(command);\n const resolution = ctx.initConfig(config, { command, mode });\n\n // Do a preliminary resolution for dep optimizer (before configResolved)\n const preliminaryTsConfigPath = ctx.resolveTsConfigPath();\n\n const esbuild = config.esbuild ?? false;\n const oxc = config.oxc ?? false;\n const jsTransformConfigKey = getJsTransformConfigKey();\n const jsTransformConfigValue =\n jsTransformConfigKey === 'oxc' ? oxc : esbuild;\n\n const depOptimizer = createDepOptimizerConfig({\n tsconfig: preliminaryTsConfigPath,\n isProd: resolution.isProd,\n jit: ctx.options.jit,\n watchMode: ctx.watchMode,\n isTest: ctx.options.isTest,\n isAstroIntegration: ctx.options.isAstroIntegration,\n });\n\n return {\n [jsTransformConfigKey]: jsTransformConfigValue,\n ...depOptimizer,\n };\n },\n configResolved(config) {\n ctx.setResolvedConfig(config);\n\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, config);\n }\n },\n configureServer(server) {\n viteServer = server;\n hotUpdates.configureServer(server);\n\n // Add/unlink changes the TypeScript program shape, not just file\n // contents, so we need to invalidate both include discovery and the\n // cached tsconfig root names before recompiling.\n const invalidateCompilationOnFsChange = createFsWatcherCacheInvalidator(\n invalidateFsCaches,\n invalidateTsconfigCaches,\n () => performCompilation(ctx.resolvedConfig!),\n );\n server.watcher.on('add', (file) => {\n if (EXCLUDED_TS_EXT_REGEX.test(file)) {\n invalidateSourceFiles(new Set([normalizePath(file)]));\n }\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('unlink', (file) => {\n const id = normalizePath(file);\n outputFiles.delete(id);\n tsSourceFileCache.delete(id);\n sourceFileCache.invalidate(new Set([id]));\n evictDeletedFileMetadata(file, {\n classNamesMap: ctx.hmr.classNames,\n fileTransformMap,\n });\n return invalidateCompilationOnFsChange();\n });\n server.watcher.on('change', (file) => {\n if (file.includes('tsconfig')) {\n invalidateTsconfigCaches();\n }\n });\n },\n async buildStart() {\n activeBuilds++;\n // Vite keys its CSS preprocessor worker cache by the top-level resolved\n // config object. Passing `this.environment.config` misses that cache\n // and falls back to a worker Vite never closes, which keeps Vitest\n // from exiting after AOT tests with `.scss` styleUrls. (#2556)\n if (!jit) {\n styleTransform = (code: string, filename: string) =>\n preprocessCSS(code, filename, ctx.resolvedConfig!);\n }\n\n // Browser mode also creates a server that may never transform TypeScript.\n if (!ctx.deferInitialCompilation) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as ResolvedConfig | undefined) ??\n ctx.resolvedConfig!,\n );\n await pendingCompilation;\n pendingCompilation = null;\n\n initialCompilation = true;\n }\n },\n async buildEnd(): Promise<void> {\n // Environments (e.g. client and ssr) build in parallel and share this\n // plugin's compilation state, so only reset after the last one ends.\n activeBuilds = Math.max(0, activeBuilds - 1);\n if (activeBuilds > 0) return;\n if (closeRequested) {\n await closeCompilation();\n return;\n }\n if (!ctx.watchMode) releaseCompilation();\n },\n async handleHotUpdate(hmrCtx) {\n if (ctx.hmr.isIgnoredFile(hmrCtx.file)) {\n debugHmr('ignored file change', { file: hmrCtx.file });\n return [];\n }\n\n if (TS_EXT_REGEX.test(hmrCtx.file)) {\n const [fileId] = hmrCtx.file.split('?');\n debugHmr('TS file changed', { file: hmrCtx.file, fileId });\n\n await hotUpdates.schedule(hmrCtx.file, [fileId]);\n\n if (EXCLUDED_TS_EXT_REGEX.test(fileId)) {\n // Declaration dependencies have no runtime modules for Vite to invalidate.\n hmrCtx.server.moduleGraph.invalidateAll();\n hmrCtx.server.ws.send({ type: 'full-reload', triggeredBy: fileId });\n return [];\n }\n\n let result: EmitFileResult | undefined;\n\n if (ctx.shouldEnableLiveReload()) {\n result = fileEmitter(fileId);\n debugHmr('TS file emitted', {\n fileId,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n });\n debugHmrV('ts hmr evaluation', {\n file: hmrCtx.file,\n fileId,\n hasResult: !!result,\n hmrEligible: !!result?.hmrEligible,\n hasClassName: !!ctx.hmr.classNames.get(fileId),\n className: ctx.hmr.classNames.get(fileId),\n updateCode: result?.hmrUpdateCode\n ? describeStylesheetContent(result.hmrUpdateCode)\n : undefined,\n errors: result?.errors?.length ?? 0,\n warnings: result?.warnings?.length ?? 0,\n hint: result?.hmrEligible\n ? 'A TS-side component change, including inline template edits, produced an Angular HMR payload.'\n : 'No Angular HMR payload was emitted for this TS change; the change may not affect component template state.',\n });\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n result?.hmrEligible &&\n ctx.hmr.classNames.get(fileId)\n ) {\n const relativeFileId = ctx.hmr.toComponentUpdateId(fileId);\n\n debugHmr('sending component update', { relativeFileId });\n debugHmrV('ts hmr component update payload', {\n file: hmrCtx.file,\n fileId,\n relativeFileId,\n className: ctx.hmr.classNames.get(fileId),\n });\n ctx.hmr.sendComponentUpdate(hmrCtx.server, relativeFileId);\n\n return hmrCtx.modules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n }\n\n if (/\\.(html|htm|css|less|sass|scss)$/.test(hmrCtx.file)) {\n debugHmr('resource file changed', { file: hmrCtx.file });\n fileTransformMap.delete(hmrCtx.file.split('?')[0]);\n // Angular component resources frequently enter HMR with incomplete\n // watcher context. In practice `ctx.modules` may only contain the\n // source file, only the `?direct` module, or nothing at all after a\n // TS-driven component refresh. Resolve the full live module set from\n // Vite's module graph and our stylesheet registry before deciding how\n // to hot update the resource.\n const stylesheetRegistry = ctx.styles.registry;\n const fileModules = await getModulesForChangedFile(\n hmrCtx.server,\n hmrCtx.file,\n hmrCtx.modules,\n stylesheetRegistry,\n );\n /**\n * Check to see if this was a direct request\n * for an external resource (styles, html).\n */\n const isDirect = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?direct') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n const isInline = fileModules.find(\n (mod) =>\n !!mod.id &&\n mod.id.includes('?inline') &&\n isModuleForChangedResource(mod, hmrCtx.file, stylesheetRegistry),\n );\n debugHmrV('resource direct/inline detection', {\n file: hmrCtx.file,\n hasDirect: !!isDirect,\n directId: isDirect?.id,\n hasInline: !!isInline,\n inlineId: isInline?.id,\n });\n\n if (isDirect || isInline) {\n if (ctx.shouldExternalizeStyles() && isDirect?.id && isDirect.file) {\n const isComponentStyle =\n isDirect.type === 'css' && isComponentStyleSheet(isDirect.id);\n debugHmrV('resource direct branch', {\n file: hmrCtx.file,\n directId: isDirect.id,\n directType: isDirect.type,\n shouldExternalize: ctx.shouldExternalizeStyles(),\n isComponentStyle,\n });\n if (isComponentStyle) {\n return handleDirectComponentStyleHmr({\n server: hmrCtx.server,\n file: hmrCtx.file,\n directModule: isDirect,\n fileModules,\n stylesheetRegistry,\n stylePreprocessor: ctx.stylePreprocessor,\n });\n }\n }\n return fileModules;\n }\n\n if (\n ctx.shouldEnableLiveReload() &&\n /\\.(html|htm)$/.test(hmrCtx.file) &&\n fileModules.length === 0\n ) {\n const ownerModules = findTemplateOwnerModules(\n hmrCtx.server,\n hmrCtx.file,\n );\n debugHmrV('template owner lookup', {\n file: hmrCtx.file,\n ownerCount: ownerModules.length,\n ownerIds: ownerModules.map((mod) => mod.id),\n hint:\n ownerModules.length > 0\n ? 'The external template has candidate TS owner modules that can be recompiled for HMR.'\n : 'No TS owner modules were visible for this external template change; HMR will fall through to the generic importer path.',\n });\n if (ownerModules.length > 0) {\n const ownerIds = ownerModules\n .map((mod) => mod.id)\n .filter(Boolean) as string[];\n\n ownerModules.forEach((mod) =>\n hmrCtx.server.moduleGraph.invalidateModule(mod),\n );\n\n await hotUpdates.schedule(hmrCtx.file, ownerIds);\n\n const updates = ownerIds.filter((id) => ctx.hmr.classNames.get(id));\n debugHmrV('template owner recompilation result', {\n file: hmrCtx.file,\n ownerIds,\n updates,\n updateClassNames: updates.map((id) => ({\n id,\n className: ctx.hmr.classNames.get(id),\n })),\n hint:\n updates.length > 0\n ? 'External template recompilation produced Angular component update targets.'\n : 'External template recompilation completed, but no Angular component update targets were surfaced.',\n });\n if (updates.length > 0) {\n debugHmr('template owner module invalidation', {\n file: hmrCtx.file,\n ownerIds,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return ownerModules.map((mod) => markModuleSelfAccepting(mod));\n }\n }\n }\n\n const mods: ModuleNode[] = [];\n const updates: string[] = [];\n fileModules.forEach((mod) => {\n mod.importers.forEach((imp) => {\n hmrCtx.server.moduleGraph.invalidateModule(imp);\n\n if (\n ctx.shouldExternalizeStyles() &&\n imp.id &&\n ctx.hmr.classNames.get(imp.id)\n ) {\n updates.push(imp.id);\n } else {\n mods.push(imp);\n }\n });\n });\n debugHmrV('resource importer analysis', {\n file: hmrCtx.file,\n fileModuleCount: fileModules.length,\n importerCount: fileModules.reduce(\n (count, mod) => count + mod.importers.size,\n 0,\n ),\n updates,\n mods: mods.map((mod) => mod.id),\n });\n\n if (mods.length === 0 && updates.length === 0) return mods;\n\n await hotUpdates.schedule(hmrCtx.file, [\n ...mods.map((mod) => mod.id as string),\n ...updates,\n ]);\n\n if (updates.length > 0) {\n debugHmr('resource importer component updates', {\n file: hmrCtx.file,\n updateCount: updates.length,\n });\n updates.forEach((updateId) => {\n ctx.hmr.sendComponentUpdate(\n hmrCtx.server,\n ctx.hmr.toComponentUpdateId(updateId),\n );\n });\n\n return fileModules.map((mod) => {\n if (mod.id === hmrCtx.file) {\n return markModuleSelfAccepting(mod);\n }\n\n return mod;\n });\n }\n\n return mods;\n }\n\n // clear HMR updates with a full reload\n debugHmr('full reload — unrecognized file type', { file: hmrCtx.file });\n ctx.hmr.clear();\n return hmrCtx.modules;\n },\n resolveId(id, importer) {\n const virtualId = resolveAngularVirtualId(id, importer, {\n jit,\n resolvedConfig: ctx.resolvedConfig,\n });\n if (virtualId !== undefined) {\n return virtualId;\n }\n\n return ctx.styles.resolveComponentStyleId(id);\n },\n async load(id) {\n const virtualModule = await loadAngularVirtualModule(\n this,\n id,\n ctx.resolvedConfig,\n );\n if (virtualModule !== undefined) {\n return virtualModule;\n }\n\n return ctx.styles.loadComponentStyle(id);\n },\n transform: {\n filter: {\n id: {\n include: [TS_EXT_REGEX],\n exclude: [/node_modules/, 'type=script', '@ng/component'],\n },\n },\n async handler(code, id) {\n if (ctx.transformFilter && !ctx.transformFilter(code, id)) {\n return;\n }\n\n // Encapsulation of component stylesheets is handled by the\n // separate '@analogjs/vite-plugin-angular:encapsulation' plugin\n // with enforce: 'post'. This ensures @tailwindcss/vite (enforce:\n // 'pre') fully resolves @apply directives — including those inside\n // :host {} — before Angular's ShadowCss rewrites selectors. (#2293)\n\n if (id.includes('.ts?')) {\n // Strip the query string off the ID\n // in case of a dynamically loaded file\n id = id.replace(/\\?(.*)/, '');\n }\n\n fileTransformMap.set(id, code);\n\n /**\n * Re-analyze on each transform\n * for test(Vitest)\n */\n if (isTest) {\n if (ctx.deferInitialCompilation && !initialCompilation) {\n // Do full initial compilation\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n );\n initialCompilation = true;\n }\n\n const tsMod = viteServer?.moduleGraph.getModuleById(id);\n if (tsMod) {\n const invalidated = tsMod.lastInvalidationTimestamp;\n\n if (ctx.testWatchMode && invalidated) {\n pendingCompilation = performCompilation(\n (this.environment?.config as unknown as\n | ResolvedConfig\n | undefined) ?? ctx.resolvedConfig!,\n [id],\n );\n }\n }\n }\n\n const hasComponent = code.includes('@Component');\n debugCompilerV('transform', {\n id,\n codeLength: code.length,\n hasComponent,\n });\n // Resource URLs are only consumed for watch-file registration and\n // JIT rewrites, so skip resolution entirely in prod AOT builds.\n const resolveResourceUrls = hasComponent && (ctx.watchMode || jit);\n const templateUrls = resolveResourceUrls\n ? templateUrlsResolver.resolve(code, id)\n : [];\n const styleUrls = resolveResourceUrls\n ? styleUrlsResolver.resolve(code, id)\n : [];\n\n if (resolveResourceUrls && ctx.watchMode) {\n for (const urlSet of [...templateUrls, ...styleUrls]) {\n // `urlSet` is a string where a relative path is joined with an\n // absolute path using the `|` symbol.\n // For example: `./app.component.html|/home/projects/analog/src/app/app.component.html`.\n const [, absoluteFileUrl] = urlSet.split('|');\n this.addWatchFile(absoluteFileUrl);\n }\n }\n\n if (pendingCompilation) {\n await pendingCompilation;\n pendingCompilation = null;\n }\n await hotUpdates.wait();\n\n const typescriptResult = fileEmitter(id);\n if (!typescriptResult) {\n debugCompilerV('transform skip (file not emitted by Angular)', {\n id,\n });\n // File not in the Angular program — skip and let other plugins\n // or Vite's built-in transform handle it. Warn if it looks like\n // an Angular file that should have been compiled.\n const isAngular =\n !id.includes('@ng/component') &&\n /(Component|Directive|Pipe|Injectable|NgModule)\\(/.test(code);\n debugEmit('transform emit miss', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n knownOutputCount: outputFiles.size,\n hasOutputFileHook: !!outputFile,\n isAngular,\n });\n\n if (isAngular) {\n this.warn(\n `[@analogjs/vite-plugin-angular]: \"${id}\" contains Angular decorators but is not in the TypeScript program. ` +\n `Ensure it is included in your tsconfig.`,\n );\n }\n\n return;\n }\n\n if (typescriptResult.warnings && typescriptResult.warnings.length > 0) {\n this.warn(`${typescriptResult.warnings.join('\\n')}`);\n }\n\n if (typescriptResult.errors && typescriptResult.errors.length > 0) {\n this.error(`${typescriptResult.errors.join('\\n')}`);\n }\n\n let data = typescriptResult.content ?? '';\n debugEmitV('transform emit hit', {\n id,\n normalizedId: normalizeEmitterLookupId(id),\n ...describeEmitMarkers(data),\n errorCount: typescriptResult.errors?.length ?? 0,\n warningCount: typescriptResult.warnings?.length ?? 0,\n });\n\n if (jit && data.includes('angular:jit:')) {\n // The emitted id carries the base64 of the entire stylesheet,\n // and the bundler derives chunk names from it — hash it so a\n // large inline style can't produce an over-long filename (#2459).\n data = data.replace(\n /angular:jit:style:inline;([A-Za-z0-9+/=]*)/g,\n (_match, encodedStyles) =>\n toJitInlineStyleId(encodedStyles, isTest),\n );\n\n // Templates use virtual ids (no extension) so Vite's asset/CSS\n // plugins don't interfere. (#2263)\n templateUrls.forEach((templateUrlSet) => {\n const [templateFile, resolvedTemplateUrl] =\n templateUrlSet.split('|');\n data = data.replace(\n `angular:jit:template:file;${templateFile}`,\n toVirtualRawId(resolvedTemplateUrl),\n );\n });\n\n // External styles use native ?inline imports. We mark each\n // path as safe in Vite's safeModulePaths so the Denied ID\n // security check passes, and Vite's CSS pipeline handles\n // preprocessing, test.css, and browser/node differences\n // natively. (#2263, #2310)\n styleUrls.forEach((styleUrlSet) => {\n const [styleFile, resolvedStyleUrl] = styleUrlSet.split('|');\n markStylePathSafe(ctx.resolvedConfig, resolvedStyleUrl);\n data = data.replace(\n `angular:jit:style:file;${styleFile}`,\n resolvedStyleUrl + '?inline',\n );\n });\n }\n\n // Angular's HMR initializer emits dynamic import() calls that Vite's\n // import-analysis plugin cannot statically analyze, producing SSR\n // warnings. The Angular compiler's IR includes a @vite-ignore comment\n // but it can be lost during TypeScript emit. Re-inject it here so the\n // warning is suppressed regardless of the compilation path used.\n if (data.includes('HmrLoad')) {\n const hasMetaUrl = data.includes('getReplaceMetadataURL');\n debugHmrV('vite-ignore injection', {\n id,\n dataLength: data.length,\n hasMetaUrl,\n });\n if (hasMetaUrl) {\n const patched = injectViteIgnoreForHmrMetadata(data);\n if (patched !== data && !patched.includes('@vite-ignore')) {\n debugHmrV('vite-ignore regex fallback', { id });\n }\n data = patched;\n }\n }\n if (typescriptResult.map) {\n // TS emits `//# sourceMappingURL=foo.js.map` at the end of the\n // .js content, but the .map file isn't served by Vite — we\n // return the map object directly. Strip the stale reference so\n // downstream tools don't see two sourceMappingURL comments.\n data = data.replace(/\\s*\\/\\/# sourceMappingURL=[^\\r\\n]*\\s*$/, '');\n }\n\n return {\n code: data,\n map: typescriptResult.map\n ? normalizeSourceMapSources(typescriptResult.map, id)\n : null,\n };\n },\n },\n async closeBundle(): Promise<void> {\n closeRequested = true;\n if (activeBuilds === 0) {\n await closeCompilation();\n }\n },\n };\n}\n\n/**\n * @internal\n */\nexport function getFileMetadata(\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n hmrEnabled?: boolean,\n disableTypeChecking?: boolean,\n classNamesMap: Map<string, string> = new Map(),\n): (file: string) => FileMetadataResult {\n const ts = require('typescript') as typeof import('typescript');\n return (file: string): FileMetadataResult => {\n const sourceFile = program.getSourceFile(file);\n if (!sourceFile) {\n return {};\n }\n\n const diagnostics = getDiagnosticsForSourceFile(\n sourceFile,\n !!disableTypeChecking,\n program,\n angularCompiler,\n );\n\n const errors = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Error)\n .map((d) =>\n typeof d.messageText === 'object'\n ? d.messageText.messageText\n : d.messageText,\n );\n\n const warnings = diagnostics\n .filter((d) => d.category === ts.DiagnosticCategory?.Warning)\n .map((d) => d.messageText);\n\n let hmrUpdateCode: string | null | undefined = undefined;\n\n let hmrEligible = false;\n if (hmrEnabled) {\n for (const node of sourceFile.statements) {\n if (ts.isClassDeclaration(node) && node.name != null) {\n hmrUpdateCode = angularCompiler?.emitHmrUpdateModule(node);\n if (hmrUpdateCode) {\n const className = node.name.getText();\n classNamesMap.set(file, className);\n hmrEligible = true;\n debugHmr('NgtscProgram emitHmrUpdateModule', { file, className });\n }\n }\n }\n }\n\n return { errors, warnings, hmrUpdateCode, hmrEligible };\n };\n}\n\nfunction getDiagnosticsForSourceFile(\n sourceFile: ts.SourceFile,\n disableTypeChecking: boolean,\n program: ts.BuilderProgram,\n angularCompiler?: NgtscProgram['compiler'],\n): readonly ts.Diagnostic[] {\n const syntacticDiagnostics = program.getSyntacticDiagnostics(sourceFile);\n\n if (disableTypeChecking) {\n // Syntax errors are cheap to compute and the app will not run if there are any\n // So always show these types of errors regardless if type checking is disabled\n return syntacticDiagnostics;\n }\n\n const semanticDiagnostics = program.getSemanticDiagnostics(sourceFile);\n const angularDiagnostics = angularCompiler\n ? angularCompiler.getDiagnosticsForFile(sourceFile, 1)\n : [];\n return [\n ...syntacticDiagnostics,\n ...semanticDiagnostics,\n ...angularDiagnostics,\n ];\n}\n"],"mappings":";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B,gBAAgB,sBAAsB,YAAY,CAAC,IACnD,CAAC;CACL,OAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;CACL;AACF"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { Plugin } from "vite";
|
|
1
|
+
import { type Plugin } from "vite";
|
|
2
|
+
import { type AngularBuildContext } from "./angular-build-context.js";
|
|
2
3
|
/**
|
|
3
|
-
* Ignores anything in the
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Ignores anything in the `.nx` folder from triggering HMR.
|
|
5
|
+
* When given an `AngularBuildContext`, also registers the ignore predicate
|
|
6
|
+
* into `ctx.hmr` so compiler `handleHotUpdate` hooks skip `.nx` writes.
|
|
6
7
|
*/
|
|
7
|
-
export declare function nxFolderPlugin(): Plugin;
|
|
8
|
+
export declare function nxFolderPlugin(ctx?: AngularBuildContext): Plugin;
|
|
@@ -1,17 +1,22 @@
|
|
|
1
|
+
import { isAngularBuildContext } from "./angular-build-context.js";
|
|
1
2
|
import { normalizePath } from "vite";
|
|
2
3
|
//#region packages/vite-plugin-angular/src/lib/nx-folder-plugin.ts
|
|
4
|
+
function isNxCacheFile(file) {
|
|
5
|
+
return file.includes(normalizePath("/.nx/"));
|
|
6
|
+
}
|
|
3
7
|
/**
|
|
4
|
-
* Ignores anything in the
|
|
5
|
-
*
|
|
6
|
-
*
|
|
8
|
+
* Ignores anything in the `.nx` folder from triggering HMR.
|
|
9
|
+
* When given an `AngularBuildContext`, also registers the ignore predicate
|
|
10
|
+
* into `ctx.hmr` so compiler `handleHotUpdate` hooks skip `.nx` writes.
|
|
7
11
|
*/
|
|
8
|
-
function nxFolderPlugin() {
|
|
12
|
+
function nxFolderPlugin(ctx) {
|
|
13
|
+
if (isAngularBuildContext(ctx)) ctx.hmr.addIgnoreFilter(isNxCacheFile);
|
|
9
14
|
return {
|
|
10
15
|
name: "analogjs-nx-folder-plugin",
|
|
11
16
|
apply: "serve",
|
|
12
|
-
handleHotUpdate(
|
|
13
|
-
if (
|
|
14
|
-
return
|
|
17
|
+
handleHotUpdate(hmrCtx) {
|
|
18
|
+
if (isNxCacheFile(hmrCtx.file)) return [];
|
|
19
|
+
return hmrCtx.modules;
|
|
15
20
|
}
|
|
16
21
|
};
|
|
17
22
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nx-folder-plugin.js","names":[],"sources":["../../../src/lib/nx-folder-plugin.ts"],"sourcesContent":["import { normalizePath, Plugin } from 'vite';\n\n/**\n * Ignores anything in the
|
|
1
|
+
{"version":3,"file":"nx-folder-plugin.js","names":[],"sources":["../../../src/lib/nx-folder-plugin.ts"],"sourcesContent":["import { normalizePath, type Plugin } from 'vite';\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\n\nfunction isNxCacheFile(file: string): boolean {\n return file.includes(normalizePath('/.nx/'));\n}\n\n/**\n * Ignores anything in the `.nx` folder from triggering HMR.\n * When given an `AngularBuildContext`, also registers the ignore predicate\n * into `ctx.hmr` so compiler `handleHotUpdate` hooks skip `.nx` writes.\n */\nexport function nxFolderPlugin(ctx?: AngularBuildContext): Plugin {\n if (isAngularBuildContext(ctx)) {\n ctx.hmr.addIgnoreFilter(isNxCacheFile);\n }\n\n return {\n name: 'analogjs-nx-folder-plugin',\n apply: 'serve',\n handleHotUpdate(hmrCtx) {\n if (isNxCacheFile(hmrCtx.file)) {\n return [];\n }\n\n return hmrCtx.modules;\n },\n };\n}\n"],"mappings":";;;AAMA,SAAS,cAAc,MAAuB;CAC5C,OAAO,KAAK,SAAS,cAAc,OAAO,CAAC;AAC7C;;;;;;AAOA,SAAgB,eAAe,KAAmC;CAChE,IAAI,sBAAsB,GAAG,GAC3B,IAAI,IAAI,gBAAgB,aAAa;CAGvC,OAAO;EACL,MAAM;EACN,OAAO;EACP,gBAAgB,QAAQ;GACtB,IAAI,cAAc,OAAO,IAAI,GAC3B,OAAO,CAAC;GAGV,OAAO,OAAO;EAChB;CACF;AACF"}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import { Plugin } from "vite";
|
|
2
|
+
import { type AngularBuildContext } from "../angular-build-context.js";
|
|
3
|
+
export interface FileReplacementsPluginOptions {
|
|
4
|
+
replacements?: FileReplacement[];
|
|
5
|
+
workspaceRoot?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function fileReplacementsPlugin(ctxOrOptions?: AngularBuildContext | FileReplacementsPluginOptions): Plugin | undefined;
|
|
2
8
|
export declare function replaceFiles(replacements: FileReplacement[], workspaceRoot: string): Plugin | false;
|
|
3
9
|
export type FileReplacement = FileReplacementWith | FileReplacementSSR;
|
|
4
10
|
export interface FileReplacementBase {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { debugCompiler } from "../utils/debug.js";
|
|
2
|
+
import "../angular-build-context.js";
|
|
2
3
|
import { isAbsolute, resolve } from "node:path";
|
|
3
4
|
//#region packages/vite-plugin-angular/src/lib/plugins/file-replacements.plugin.ts
|
|
4
5
|
function replaceFiles(replacements, workspaceRoot) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-replacements.plugin.js","names":[],"sources":["../../../../src/lib/plugins/file-replacements.plugin.ts"],"sourcesContent":["// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js\nimport { isAbsolute, resolve } from 'node:path';\nimport { Plugin } from 'vite';\nimport { debugCompiler } from '../utils/debug.js';\n\nexport function replaceFiles(\n replacements: FileReplacement[],\n workspaceRoot: string,\n): Plugin | false {\n if (!replacements?.length) {\n return false;\n }\n\n return {\n name: 'rollup-plugin-replace-files',\n enforce: 'pre',\n async resolveId(source, importer, options) {\n const resolved = await this.resolve(source, importer, {\n ...options,\n skipSelf: true,\n });\n /**\n * The reason we're using endsWith here is because the resolved id\n * will be the absolute path to the file. We want to check if the\n * file ends with the file we're trying to replace, which will be essentially\n * the path from the root of our workspace.\n */\n const mappedReplacements = replacements.map((fr: FileReplacement) => {\n const frSSR = fr as FileReplacementSSR;\n const frWith = fr as FileReplacementWith;\n\n return {\n ...fr,\n ssr: frSSR.ssr\n ? isAbsolute(frSSR.ssr)\n ? frSSR.ssr\n : resolve(workspaceRoot, frSSR.ssr)\n : '',\n with: frWith.with\n ? isAbsolute(frWith.with)\n ? frWith.with\n : resolve(workspaceRoot, frWith.with)\n : '',\n };\n });\n const foundReplace = mappedReplacements.find((replacement) =>\n resolved?.id?.endsWith(replacement.replace),\n );\n if (foundReplace) {\n try {\n if (this.environment.name === 'ssr' && foundReplace.ssr) {\n // return new file id for ssr\n return {\n id: foundReplace.ssr,\n };\n } else if (foundReplace.ssr) {\n return null;\n }\n\n // return new file id\n return {\n id: foundReplace.with,\n };\n } catch (err) {\n debugCompiler('file replacement error', {\n error: String(err),\n source,\n importer,\n });\n return null;\n }\n }\n return null;\n },\n };\n}\n\nexport type FileReplacement = FileReplacementWith | FileReplacementSSR;\n\nexport interface FileReplacementBase {\n replace: string;\n}\nexport interface FileReplacementWith extends FileReplacementBase {\n with: string;\n}\n\nexport interface FileReplacementSSR extends FileReplacementBase {\n ssr: string;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"file-replacements.plugin.js","names":[],"sources":["../../../../src/lib/plugins/file-replacements.plugin.ts"],"sourcesContent":["// source: https://github.com/Myrmod/vitejs-theming/blob/master/build-plugins/rollup/replace-files.js\nimport { isAbsolute, resolve } from 'node:path';\nimport { Plugin } from 'vite';\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from '../angular-build-context.js';\nimport { debugCompiler } from '../utils/debug.js';\n\nexport interface FileReplacementsPluginOptions {\n replacements?: FileReplacement[];\n workspaceRoot?: string;\n}\n\nexport function fileReplacementsPlugin(\n ctxOrOptions?: AngularBuildContext | FileReplacementsPluginOptions,\n): Plugin | undefined {\n const replacements = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions.options.fileReplacements\n : (ctxOrOptions?.replacements ?? []);\n const workspaceRoot = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions.options.workspaceRoot\n : (ctxOrOptions?.workspaceRoot ?? process.cwd());\n return replaceFiles(replacements, workspaceRoot) || undefined;\n}\n\nexport function replaceFiles(\n replacements: FileReplacement[],\n workspaceRoot: string,\n): Plugin | false {\n if (!replacements?.length) {\n return false;\n }\n\n return {\n name: 'rollup-plugin-replace-files',\n enforce: 'pre',\n async resolveId(source, importer, options) {\n const resolved = await this.resolve(source, importer, {\n ...options,\n skipSelf: true,\n });\n /**\n * The reason we're using endsWith here is because the resolved id\n * will be the absolute path to the file. We want to check if the\n * file ends with the file we're trying to replace, which will be essentially\n * the path from the root of our workspace.\n */\n const mappedReplacements = replacements.map((fr: FileReplacement) => {\n const frSSR = fr as FileReplacementSSR;\n const frWith = fr as FileReplacementWith;\n\n return {\n ...fr,\n ssr: frSSR.ssr\n ? isAbsolute(frSSR.ssr)\n ? frSSR.ssr\n : resolve(workspaceRoot, frSSR.ssr)\n : '',\n with: frWith.with\n ? isAbsolute(frWith.with)\n ? frWith.with\n : resolve(workspaceRoot, frWith.with)\n : '',\n };\n });\n const foundReplace = mappedReplacements.find((replacement) =>\n resolved?.id?.endsWith(replacement.replace),\n );\n if (foundReplace) {\n try {\n if (this.environment.name === 'ssr' && foundReplace.ssr) {\n // return new file id for ssr\n return {\n id: foundReplace.ssr,\n };\n } else if (foundReplace.ssr) {\n return null;\n }\n\n // return new file id\n return {\n id: foundReplace.with,\n };\n } catch (err) {\n debugCompiler('file replacement error', {\n error: String(err),\n source,\n importer,\n });\n return null;\n }\n }\n return null;\n },\n };\n}\n\nexport type FileReplacement = FileReplacementWith | FileReplacementSSR;\n\nexport interface FileReplacementBase {\n replace: string;\n}\nexport interface FileReplacementWith extends FileReplacementBase {\n with: string;\n}\n\nexport interface FileReplacementSSR extends FileReplacementBase {\n ssr: string;\n}\n"],"mappings":";;;;AA0BA,SAAgB,aACd,cACA,eACgB;CAChB,IAAI,CAAC,cAAc,QACjB,OAAO;CAGT,OAAO;EACL,MAAM;EACN,SAAS;EACT,MAAM,UAAU,QAAQ,UAAU,SAAS;GACzC,MAAM,WAAW,MAAM,KAAK,QAAQ,QAAQ,UAAU;IACpD,GAAG;IACH,UAAU;GACZ,CAAC;GAyBD,MAAM,eAlBqB,aAAa,KAAK,OAAwB;IACnE,MAAM,QAAQ;IACd,MAAM,SAAS;IAEf,OAAO;KACL,GAAG;KACH,KAAK,MAAM,MACP,WAAW,MAAM,GAAG,IAClB,MAAM,MACN,QAAQ,eAAe,MAAM,GAAG,IAClC;KACJ,MAAM,OAAO,OACT,WAAW,OAAO,IAAI,IACpB,OAAO,OACP,QAAQ,eAAe,OAAO,IAAI,IACpC;IACN;GACF,CACqB,CAAA,CAAmB,MAAM,gBAC5C,UAAU,IAAI,SAAS,YAAY,OAAO,CAC5C;GACA,IAAI,cACF,IAAI;IACF,IAAI,KAAK,YAAY,SAAS,SAAS,aAAa,KAElD,OAAO,EACL,IAAI,aAAa,IACnB;SACK,IAAI,aAAa,KACtB,OAAO;IAIT,OAAO,EACL,IAAI,aAAa,KACnB;GACF,SAAS,KAAK;IACZ,cAAc,0BAA0B;KACtC,OAAO,OAAO,GAAG;KACjB;KACA;IACF,CAAC;IACD,OAAO;GACT;GAEF,OAAO;EACT;CACF;AACF"}
|
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
import type { Plugin } from "vite";
|
|
2
|
-
|
|
2
|
+
import { type AngularBuildContext } from "./angular-build-context.js";
|
|
3
|
+
export interface RouterPluginOptions {
|
|
4
|
+
workspaceRoot?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function routerPlugin(ctxOrOptions?: AngularBuildContext | RouterPluginOptions): Plugin;
|
package/src/lib/router-plugin.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { JavaScriptTransformer } from "./utils/devkit.js";
|
|
2
2
|
import { createPersistentTransformCache, resolveTransformCacheDir, withMemoryLayer } from "./utils/transform-cache.js";
|
|
3
|
+
import { isAngularBuildContext } from "./angular-build-context.js";
|
|
3
4
|
//#region packages/vite-plugin-angular/src/lib/router-plugin.ts
|
|
4
|
-
function routerPlugin() {
|
|
5
|
+
function routerPlugin(ctxOrOptions) {
|
|
6
|
+
isAngularBuildContext(ctxOrOptions);
|
|
7
|
+
let configuredRoot = isAngularBuildContext(ctxOrOptions) ? ctxOrOptions.options.workspaceRoot : ctxOrOptions?.workspaceRoot;
|
|
5
8
|
const memoryCache = /* @__PURE__ */ new Map();
|
|
6
9
|
const memoryOnly = {
|
|
7
10
|
get: (key) => memoryCache.get(key),
|
|
@@ -9,18 +12,24 @@ function routerPlugin() {
|
|
|
9
12
|
memoryCache.set(key, value);
|
|
10
13
|
}
|
|
11
14
|
};
|
|
12
|
-
const persistentDir = resolveTransformCacheDir(process.cwd());
|
|
13
15
|
let javascriptTransformer;
|
|
14
16
|
function getTransformer() {
|
|
15
|
-
|
|
17
|
+
if (!javascriptTransformer) {
|
|
18
|
+
const persistentDir = resolveTransformCacheDir(configuredRoot ?? process.cwd());
|
|
19
|
+
javascriptTransformer = new JavaScriptTransformer({ jit: true }, 1, persistentDir ? withMemoryLayer(createPersistentTransformCache(persistentDir)) : memoryOnly);
|
|
20
|
+
}
|
|
21
|
+
return javascriptTransformer;
|
|
16
22
|
}
|
|
17
23
|
/**
|
|
18
|
-
* Transforms Angular packages
|
|
24
|
+
* Transforms Angular packages that didn't get picked up by Vite's pre-optimization.
|
|
19
25
|
*/
|
|
20
26
|
return {
|
|
21
27
|
name: "analogjs-router-optimization",
|
|
22
28
|
enforce: "pre",
|
|
23
29
|
apply: "serve",
|
|
30
|
+
configResolved(config) {
|
|
31
|
+
configuredRoot ??= config.root || process.cwd();
|
|
32
|
+
},
|
|
24
33
|
buildEnd() {
|
|
25
34
|
return javascriptTransformer?.close();
|
|
26
35
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-plugin.js","names":[],"sources":["../../../src/lib/router-plugin.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport { JavaScriptTransformer } from './utils/devkit.js';\nimport {\n createPersistentTransformCache,\n resolveTransformCacheDir,\n withMemoryLayer,\n type TransformCacheStore,\n} from './utils/transform-cache.js';\n\nexport function routerPlugin(): Plugin {\n const memoryCache = new Map<string, Uint8Array>();\n const memoryOnly: TransformCacheStore = {\n get: (key: string) => memoryCache.get(key),\n put: (key: string, value: Uint8Array) => {\n memoryCache.set(key, value);\n },\n };\n
|
|
1
|
+
{"version":3,"file":"router-plugin.js","names":[],"sources":["../../../src/lib/router-plugin.ts"],"sourcesContent":["import type { Plugin } from 'vite';\nimport {\n isAngularBuildContext,\n type AngularBuildContext,\n} from './angular-build-context.js';\nimport { JavaScriptTransformer } from './utils/devkit.js';\nimport {\n createPersistentTransformCache,\n resolveTransformCacheDir,\n withMemoryLayer,\n type TransformCacheStore,\n} from './utils/transform-cache.js';\n\nexport interface RouterPluginOptions {\n workspaceRoot?: string;\n}\n\nexport function routerPlugin(\n ctxOrOptions?: AngularBuildContext | RouterPluginOptions,\n): Plugin {\n const sharedCtx = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions\n : undefined;\n let configuredRoot = isAngularBuildContext(ctxOrOptions)\n ? ctxOrOptions.options.workspaceRoot\n : ctxOrOptions?.workspaceRoot;\n\n const memoryCache = new Map<string, Uint8Array>();\n const memoryOnly: TransformCacheStore = {\n get: (key: string) => memoryCache.get(key),\n put: (key: string, value: Uint8Array) => {\n memoryCache.set(key, value);\n },\n };\n let javascriptTransformer: InstanceType<typeof JavaScriptTransformer>;\n function getTransformer() {\n if (!javascriptTransformer) {\n const persistentDir = resolveTransformCacheDir(\n configuredRoot ?? process.cwd(),\n );\n javascriptTransformer = new JavaScriptTransformer(\n { jit: true },\n 1,\n persistentDir\n ? withMemoryLayer(createPersistentTransformCache(persistentDir))\n : memoryOnly,\n );\n }\n return javascriptTransformer;\n }\n\n /**\n * Transforms Angular packages that didn't get picked up by Vite's pre-optimization.\n */\n return {\n name: 'analogjs-router-optimization',\n enforce: 'pre',\n apply: 'serve',\n configResolved(config) {\n configuredRoot ??= config.root || process.cwd();\n },\n buildEnd() {\n return javascriptTransformer?.close();\n },\n transform: {\n filter: {\n id: /fesm(.*?)\\.mjs/,\n },\n async handler(_code: string, id: string) {\n const path = id.split('?')[0];\n const contents = await getTransformer().transformFile(path);\n\n return {\n code: Buffer.from(contents).toString('utf-8'),\n };\n },\n },\n };\n}\n"],"mappings":";;;;AAiBA,SAAgB,aACd,cACQ;CACU,sBAAsB,YAAY;CAGpD,IAAI,iBAAiB,sBAAsB,YAAY,IACnD,aAAa,QAAQ,gBACrB,cAAc;CAElB,MAAM,8BAAc,IAAI,IAAwB;CAChD,MAAM,aAAkC;EACtC,MAAM,QAAgB,YAAY,IAAI,GAAG;EACzC,MAAM,KAAa,UAAsB;GACvC,YAAY,IAAI,KAAK,KAAK;EAC5B;CACF;CACA,IAAI;CACJ,SAAS,iBAAiB;EACxB,IAAI,CAAC,uBAAuB;GAC1B,MAAM,gBAAgB,yBACpB,kBAAkB,QAAQ,IAAI,CAChC;GACA,wBAAwB,IAAI,sBAC1B,EAAE,KAAK,KAAK,GACZ,GACA,gBACI,gBAAgB,+BAA+B,aAAa,CAAC,IAC7D,UACN;EACF;EACA,OAAO;CACT;;;;CAKA,OAAO;EACL,MAAM;EACN,SAAS;EACT,OAAO;EACP,eAAe,QAAQ;GACrB,mBAAmB,OAAO,QAAQ,QAAQ,IAAI;EAChD;EACA,WAAW;GACT,OAAO,uBAAuB,MAAM;EACtC;EACA,WAAW;GACT,QAAQ,EACN,IAAI,iBACN;GACA,MAAM,QAAQ,OAAe,IAAY;IACvC,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,CAAC;IAC3B,MAAM,WAAW,MAAM,eAAe,CAAC,CAAC,cAAc,IAAI;IAE1D,OAAO,EACL,MAAM,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,OAAO,EAC9C;GACF;EACF;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { debugStylesV } from "./debug.js";
|
|
2
1
|
import { normalizeStylesheetDependencies } from "../style-preprocessor.js";
|
|
2
|
+
import { debugStylesV } from "./debug.js";
|
|
3
3
|
import { preprocessStylesheetResult, rewriteRelativeCssImports } from "../stylesheet-registry.js";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { existsSync, readFileSync } from "node:fs";
|
package/src/lib/utils/devkit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { dirname, join } from "node:path";
|
|
2
1
|
import { createRequire } from "node:module";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
3
|
import { VERSION } from "@angular/compiler-cli";
|
|
4
4
|
//#region packages/vite-plugin-angular/src/lib/utils/devkit.ts
|
|
5
5
|
var require = createRequire(import.meta.url);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applies the Angular CLI's HMR rule to an edited file. Returns the
|
|
3
|
+
* components whose `template`, `templateUrl`, `styles`, `styleUrl` or
|
|
4
|
+
* `stylesUrl` fields are the only changes, or `null` when the edit
|
|
5
|
+
* needs a full reload.
|
|
6
|
+
*/
|
|
7
|
+
export declare function findHmrComponentUpdates(filename: string, staleText: string, updatedText: string, components: ReadonlySet<string>): string[] | null;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { parseSync } from "oxc-parser";
|
|
2
|
+
//#region packages/vite-plugin-angular/src/lib/utils/hmr-component-updates.ts
|
|
3
|
+
var HMR_FIELDS = /* @__PURE__ */ new Set([
|
|
4
|
+
"template",
|
|
5
|
+
"templateUrl",
|
|
6
|
+
"styles",
|
|
7
|
+
"styleUrl",
|
|
8
|
+
"stylesUrl"
|
|
9
|
+
]);
|
|
10
|
+
function parse(filename, text) {
|
|
11
|
+
const { program, errors } = parseSync(filename, text);
|
|
12
|
+
return errors.length ? null : {
|
|
13
|
+
text,
|
|
14
|
+
body: program.body
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function classOf(statement) {
|
|
18
|
+
if (statement.type === "ClassDeclaration") return statement;
|
|
19
|
+
return statement.declaration?.type === "ClassDeclaration" ? statement.declaration : void 0;
|
|
20
|
+
}
|
|
21
|
+
function statementStart(statement) {
|
|
22
|
+
return Math.min(statement.start, classOf(statement)?.decorators[0]?.start ?? statement.start);
|
|
23
|
+
}
|
|
24
|
+
function statementText(source, statement) {
|
|
25
|
+
return source.text.slice(statementStart(statement), statement.end);
|
|
26
|
+
}
|
|
27
|
+
function classHeader(source, statement, cls) {
|
|
28
|
+
const [decorator] = cls.decorators;
|
|
29
|
+
return source.text.slice(statementStart(statement), decorator.start) + source.text.slice(decorator.end, cls.body.start) + source.text.slice(cls.body.end, statement.end);
|
|
30
|
+
}
|
|
31
|
+
function decoratorMetadata(source, decorator) {
|
|
32
|
+
const call = decorator.expression;
|
|
33
|
+
const metadata = call.arguments?.[0];
|
|
34
|
+
if (call.arguments?.length !== 1 || metadata.type !== "ObjectExpression") return null;
|
|
35
|
+
const fields = [];
|
|
36
|
+
for (const property of metadata.properties) {
|
|
37
|
+
if (property.type !== "Property" || property.kind !== "init" || property.computed || property.shorthand || property.method) return null;
|
|
38
|
+
fields.push([String(property.key.name ?? property.key.value), source.text.slice(property.value.start, property.value.end)]);
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
callee: source.text.slice(call.callee.start, call.callee.end),
|
|
42
|
+
fields
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function fieldsText(fields, hmr) {
|
|
46
|
+
const selected = fields.filter(([name]) => HMR_FIELDS.has(name) === hmr);
|
|
47
|
+
if (hmr) selected.sort(([a], [b]) => a.localeCompare(b));
|
|
48
|
+
return JSON.stringify(selected);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether a component changed only in its HMR fields, or `null` when
|
|
52
|
+
* anything else in the statement changed.
|
|
53
|
+
*/
|
|
54
|
+
function componentChanged(stale, staleStatement, updated, updatedStatement) {
|
|
55
|
+
const staleClass = classOf(staleStatement);
|
|
56
|
+
const updatedClass = classOf(updatedStatement);
|
|
57
|
+
if (staleStatement.type !== updatedStatement.type || staleClass?.decorators.length !== 1 || updatedClass.decorators.length !== 1 || classHeader(stale, staleStatement, staleClass) !== classHeader(updated, updatedStatement, updatedClass) || stale.text.slice(staleClass.body.start, staleClass.body.end) !== updated.text.slice(updatedClass.body.start, updatedClass.body.end)) return null;
|
|
58
|
+
const staleMeta = decoratorMetadata(stale, staleClass.decorators[0]);
|
|
59
|
+
const updatedMeta = decoratorMetadata(updated, updatedClass.decorators[0]);
|
|
60
|
+
if (!staleMeta || !updatedMeta || staleMeta.callee !== updatedMeta.callee || fieldsText(staleMeta.fields, false) !== fieldsText(updatedMeta.fields, false)) return null;
|
|
61
|
+
return fieldsText(staleMeta.fields, true) !== fieldsText(updatedMeta.fields, true);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Applies the Angular CLI's HMR rule to an edited file. Returns the
|
|
65
|
+
* components whose `template`, `templateUrl`, `styles`, `styleUrl` or
|
|
66
|
+
* `stylesUrl` fields are the only changes, or `null` when the edit
|
|
67
|
+
* needs a full reload.
|
|
68
|
+
*/
|
|
69
|
+
function findHmrComponentUpdates(filename, staleText, updatedText, components) {
|
|
70
|
+
const stale = parse(filename, staleText);
|
|
71
|
+
const updated = parse(filename, updatedText);
|
|
72
|
+
if (!stale || !updated || stale.body.length !== updated.body.length) return null;
|
|
73
|
+
const changed = [];
|
|
74
|
+
for (let i = 0; i < updated.body.length; i++) {
|
|
75
|
+
const name = classOf(updated.body[i])?.id?.name;
|
|
76
|
+
if (name && components.has(name)) {
|
|
77
|
+
const result = componentChanged(stale, stale.body[i], updated, updated.body[i]);
|
|
78
|
+
if (result === null) return null;
|
|
79
|
+
if (result) changed.push(name);
|
|
80
|
+
} else if (statementText(stale, stale.body[i]) !== statementText(updated, updated.body[i])) return null;
|
|
81
|
+
}
|
|
82
|
+
return changed.length ? changed : null;
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { findHmrComponentUpdates };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=hmr-component-updates.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hmr-component-updates.js","names":[],"sources":["../../../../src/lib/utils/hmr-component-updates.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\n\n// Component metadata fields the Angular CLI updates in place\nconst HMR_FIELDS = new Set([\n 'template',\n 'templateUrl',\n 'styles',\n 'styleUrl',\n 'stylesUrl',\n]);\n\ninterface Source {\n text: string;\n body: any[];\n}\n\ntype Fields = [name: string, value: string][];\n\nfunction parse(filename: string, text: string): Source | null {\n const { program, errors } = parseSync(filename, text);\n return errors.length ? null : { text, body: program.body };\n}\n\nfunction classOf(statement: any) {\n if (statement.type === 'ClassDeclaration') return statement;\n return statement.declaration?.type === 'ClassDeclaration'\n ? statement.declaration\n : undefined;\n}\n\n// Decorators written before `export` fall outside the statement span\nfunction statementStart(statement: any) {\n return Math.min(\n statement.start,\n classOf(statement)?.decorators[0]?.start ?? statement.start,\n );\n}\n\nfunction statementText(source: Source, statement: any) {\n return source.text.slice(statementStart(statement), statement.end);\n}\n\n// The statement without its decorator and class body\nfunction classHeader(source: Source, statement: any, cls: any) {\n const [decorator] = cls.decorators;\n return (\n source.text.slice(statementStart(statement), decorator.start) +\n source.text.slice(decorator.end, cls.body.start) +\n source.text.slice(cls.body.end, statement.end)\n );\n}\n\nfunction decoratorMetadata(source: Source, decorator: any) {\n const call = decorator.expression;\n const metadata = call.arguments?.[0];\n if (call.arguments?.length !== 1 || metadata.type !== 'ObjectExpression') {\n return null;\n }\n const fields: Fields = [];\n for (const property of metadata.properties) {\n if (\n property.type !== 'Property' ||\n property.kind !== 'init' ||\n property.computed ||\n property.shorthand ||\n property.method\n ) {\n return null;\n }\n fields.push([\n String(property.key.name ?? property.key.value),\n source.text.slice(property.value.start, property.value.end),\n ]);\n }\n return {\n callee: source.text.slice(call.callee.start, call.callee.end),\n fields,\n };\n}\n\nfunction fieldsText(fields: Fields, hmr: boolean) {\n const selected = fields.filter(([name]) => HMR_FIELDS.has(name) === hmr);\n // HMR fields can move; other fields must keep their order\n if (hmr) selected.sort(([a], [b]) => a.localeCompare(b));\n return JSON.stringify(selected);\n}\n\n/**\n * Whether a component changed only in its HMR fields, or `null` when\n * anything else in the statement changed.\n */\nfunction componentChanged(\n stale: Source,\n staleStatement: any,\n updated: Source,\n updatedStatement: any,\n): boolean | null {\n const staleClass = classOf(staleStatement);\n const updatedClass = classOf(updatedStatement);\n if (\n staleStatement.type !== updatedStatement.type ||\n staleClass?.decorators.length !== 1 ||\n updatedClass.decorators.length !== 1 ||\n classHeader(stale, staleStatement, staleClass) !==\n classHeader(updated, updatedStatement, updatedClass) ||\n stale.text.slice(staleClass.body.start, staleClass.body.end) !==\n updated.text.slice(updatedClass.body.start, updatedClass.body.end)\n ) {\n return null;\n }\n const staleMeta = decoratorMetadata(stale, staleClass.decorators[0]);\n const updatedMeta = decoratorMetadata(updated, updatedClass.decorators[0]);\n if (\n !staleMeta ||\n !updatedMeta ||\n staleMeta.callee !== updatedMeta.callee ||\n fieldsText(staleMeta.fields, false) !==\n fieldsText(updatedMeta.fields, false)\n ) {\n return null;\n }\n return (\n fieldsText(staleMeta.fields, true) !== fieldsText(updatedMeta.fields, true)\n );\n}\n\n/**\n * Applies the Angular CLI's HMR rule to an edited file. Returns the\n * components whose `template`, `templateUrl`, `styles`, `styleUrl` or\n * `stylesUrl` fields are the only changes, or `null` when the edit\n * needs a full reload.\n */\nexport function findHmrComponentUpdates(\n filename: string,\n staleText: string,\n updatedText: string,\n components: ReadonlySet<string>,\n): string[] | null {\n const stale = parse(filename, staleText);\n const updated = parse(filename, updatedText);\n if (!stale || !updated || stale.body.length !== updated.body.length) {\n return null;\n }\n const changed: string[] = [];\n for (let i = 0; i < updated.body.length; i++) {\n const name = classOf(updated.body[i])?.id?.name;\n if (name && components.has(name)) {\n const result = componentChanged(\n stale,\n stale.body[i],\n updated,\n updated.body[i],\n );\n if (result === null) return null;\n if (result) changed.push(name);\n } else if (\n statementText(stale, stale.body[i]) !==\n statementText(updated, updated.body[i])\n ) {\n return null;\n }\n }\n return changed.length ? changed : null;\n}\n"],"mappings":";;AAGA,IAAM,6BAAa,IAAI,IAAI;CACzB;CACA;CACA;CACA;CACA;AACF,CAAC;AASD,SAAS,MAAM,UAAkB,MAA6B;CAC5D,MAAM,EAAE,SAAS,WAAW,UAAU,UAAU,IAAI;CACpD,OAAO,OAAO,SAAS,OAAO;EAAE;EAAM,MAAM,QAAQ;CAAK;AAC3D;AAEA,SAAS,QAAQ,WAAgB;CAC/B,IAAI,UAAU,SAAS,oBAAoB,OAAO;CAClD,OAAO,UAAU,aAAa,SAAS,qBACnC,UAAU,cACV,KAAA;AACN;AAGA,SAAS,eAAe,WAAgB;CACtC,OAAO,KAAK,IACV,UAAU,OACV,QAAQ,SAAS,CAAC,EAAE,WAAW,EAAE,EAAE,SAAS,UAAU,KACxD;AACF;AAEA,SAAS,cAAc,QAAgB,WAAgB;CACrD,OAAO,OAAO,KAAK,MAAM,eAAe,SAAS,GAAG,UAAU,GAAG;AACnE;AAGA,SAAS,YAAY,QAAgB,WAAgB,KAAU;CAC7D,MAAM,CAAC,aAAa,IAAI;CACxB,OACE,OAAO,KAAK,MAAM,eAAe,SAAS,GAAG,UAAU,KAAK,IAC5D,OAAO,KAAK,MAAM,UAAU,KAAK,IAAI,KAAK,KAAK,IAC/C,OAAO,KAAK,MAAM,IAAI,KAAK,KAAK,UAAU,GAAG;AAEjD;AAEA,SAAS,kBAAkB,QAAgB,WAAgB;CACzD,MAAM,OAAO,UAAU;CACvB,MAAM,WAAW,KAAK,YAAY;CAClC,IAAI,KAAK,WAAW,WAAW,KAAK,SAAS,SAAS,oBACpD,OAAO;CAET,MAAM,SAAiB,CAAC;CACxB,KAAK,MAAM,YAAY,SAAS,YAAY;EAC1C,IACE,SAAS,SAAS,cAClB,SAAS,SAAS,UAClB,SAAS,YACT,SAAS,aACT,SAA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AAM,UAAU,SAAS;CACvC,MAAM,UAAU,MAAM,UAAU,WAAW;CAC3C,IAAI,CAAC,SAAS,CAAC,WAAW,MAAM,KAAK,WAAW,QAAQ,KAAK,QAC3D,OAAO;CAET,MAAM,UAAoB,CAAC;CAC3B,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,KAAK,QAAQ,KAAK;EAC5C,MAAM,OAAO,QAAQ,QAAQ,KAAK,EAAE,CAAC,EAAE,IAAI;EAC3C,IAAI,QAAQ,WAAW,IAAI,IAAI,GAAG;GAChC,MAAM,SAAS,iBACb,OACA,MAAM,KAAK,IACX,SACA,QAAQ,KAAK,EACf;GACA,IAAI,WAAW,MAAM,OAAO;GAC5B,IAAI,QAAQ,QAAQ,KAAK,IAAI;EAC/B,OAAO,IACL,cAAc,OAAO,MAAM,KAAK,EAAE,MAClC,cAAc,SAAS,QAAQ,KAAK,EAAE,GAEtC,OAAO;CAEX;CACA,OAAO,QAAQ,SAAS,UAAU;AACpC"}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export interface TcbTemplateSource {
|
|
2
|
+
templateFile?: string;
|
|
3
|
+
templateExpression?: {
|
|
4
|
+
start: number;
|
|
5
|
+
end: number;
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
type TemplateSources = Record<string, TcbTemplateSource>;
|
|
9
|
+
interface TcbLineRange {
|
|
10
|
+
startLine: number;
|
|
11
|
+
endLine: number;
|
|
12
|
+
filePath: string;
|
|
13
|
+
sourceCode: string;
|
|
14
|
+
templateSources: TemplateSources;
|
|
15
|
+
}
|
|
16
|
+
/** NGP's footer comment mapping TCB ids to the template they were generated from. */
|
|
17
|
+
export declare const TCB_TEMPLATE_SOURCES_PREFIX = "ngp-tcb-template-sources:";
|
|
18
|
+
export declare function readSpanComment(value: string): {
|
|
19
|
+
start: number;
|
|
20
|
+
end: number;
|
|
21
|
+
} | null;
|
|
22
|
+
export type TypeCheckerOption = "tsgo" | "tsrs" | {
|
|
23
|
+
command: string;
|
|
24
|
+
args?: string[];
|
|
25
|
+
};
|
|
26
|
+
interface TypeCheckerCommand {
|
|
27
|
+
command: string;
|
|
28
|
+
args: string[];
|
|
29
|
+
}
|
|
30
|
+
/** LSP `FileChangeType`: 1 created, 2 changed, 3 deleted. */
|
|
31
|
+
export type FileChangeType = 1 | 2 | 3;
|
|
32
|
+
/** A reported location, with a one-based line and character. */
|
|
33
|
+
export interface SourceLocation {
|
|
34
|
+
file: string;
|
|
35
|
+
line: number;
|
|
36
|
+
character: number;
|
|
37
|
+
}
|
|
38
|
+
/** Hooks for checking files that don't exist on disk. */
|
|
39
|
+
export interface LspTypeCheckerHost {
|
|
40
|
+
/**
|
|
41
|
+
* The text of files that exist only in memory, by normalized path. They're
|
|
42
|
+
* opened before any check, so imports of them resolve.
|
|
43
|
+
*/
|
|
44
|
+
inMemoryFiles(): ReadonlyMap<string, string>;
|
|
45
|
+
/** Maps a reported location to the source it was generated from. */
|
|
46
|
+
mapLocation(location: SourceLocation): SourceLocation;
|
|
47
|
+
}
|
|
48
|
+
export declare function resolveTypeChecker(tsconfig: string, option: TypeCheckerOption): TypeCheckerCommand;
|
|
49
|
+
export declare class LspTypeChecker {
|
|
50
|
+
private readonly host?;
|
|
51
|
+
private proc;
|
|
52
|
+
private seq;
|
|
53
|
+
private pending;
|
|
54
|
+
private versions;
|
|
55
|
+
private queued;
|
|
56
|
+
/** The text last sent for each open in-memory file. */
|
|
57
|
+
private inMemoryText;
|
|
58
|
+
private buffer;
|
|
59
|
+
private exitError;
|
|
60
|
+
readonly ready: Promise<void>;
|
|
61
|
+
constructor(tsconfig: string, option?: TypeCheckerOption, host?: LspTypeCheckerHost);
|
|
62
|
+
private onData;
|
|
63
|
+
private send;
|
|
64
|
+
private notify;
|
|
65
|
+
private request;
|
|
66
|
+
updateDocument(filePath: string, text: string);
|
|
67
|
+
checkFile(filePath: string, sourceLineCount?: number, lines?: string[], tcbRanges?: TcbLineRange[], inMemory?: boolean): Promise<string[]>;
|
|
68
|
+
private formatLocation;
|
|
69
|
+
/** Reports a change on disk; an open copy is closed so the checker rereads the file. */
|
|
70
|
+
notifyFileChanged(filePath: string, type: FileChangeType);
|
|
71
|
+
queueFile(filePath: string, sourceCode: string, tcbCode?: string | null);
|
|
72
|
+
flushQueue(watchMode?: boolean): Promise<string[]>;
|
|
73
|
+
close();
|
|
74
|
+
}
|
|
75
|
+
export {};
|