ng-packagr 22.2.0-next.5 → 22.2.0-next.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ng-packagr",
3
- "version": "22.2.0-next.5",
3
+ "version": "22.2.0-next.6",
4
4
  "description": "Compile and package Angular libraries in Angular Package Format (APF)",
5
5
  "keywords": [
6
6
  "apf",
@@ -99,6 +99,7 @@ class ComponentStylesheetBundler {
99
99
  if (!this.incremental) {
100
100
  return;
101
101
  }
102
+ (0, sass_language_1.resetSassWorkerPoolCaches)();
102
103
  const normalizedFiles = new Set();
103
104
  for (const file of files) {
104
105
  const normalized = (0, path_1.ensureUnixPath)(file);
@@ -1 +1 @@
1
- {"version":3,"file":"component-stylesheets.js","sourceRoot":"","sources":["../../../../src/lib/styles/component-stylesheets.ts"],"names":[],"mappings":";;;;;;AACA,6CAAyC;AACzC,0DAA6B;AAC7B,wCAA+C;AAC/C,uDAA6F;AAC7F,mCAAsC;AACtC,2DAA4D;AAC5D,iEAAsG;AACtG,+DAAqE;AAWrE;;;;GAIG;AACH,MAAa,0BAA0B;IAWlB;IACA;IACA;IAZV,aAAa,GAAG,IAAI,mBAAW,EAAkB,CAAC;IAClD,eAAe,GAAG,IAAI,mBAAW,EAAkB,CAAC;IACpD,UAAU,GAAG,IAAI,yCAAqB,EAAE,CAAC;IAElD;;;;OAIG;IACH,YACmB,OAAgC,EAChC,qBAA6B,EAC7B,WAAoB;QAFpB,YAAO,GAAP,OAAO,CAAyB;QAChC,0BAAqB,GAArB,qBAAqB,CAAQ;QAC7B,gBAAW,GAAX,WAAW,CAAS;IACpC,CAAC;IAEJ,KAAK,CAAC,UAAU,CAAC,KAAa;QAC5B,KAAK,GAAG,IAAA,qBAAc,EAAC,KAAK,CAAC,CAAC;QAE9B,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,WAAW,CAAC,KAAK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nF,4GAA4G;oBAE5G,wGAAwG;oBACxG,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,EAAE,CAAC;oBAE5C,oFAAoF;oBACpF,wHAAwH;oBACxH,wEAAwE;oBACxE,8CAA8C;oBAC9C,gBAAgB,CAAC,IAAI,GAAG,mBAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;oBAE/E,WAAW,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;gBACrC,CAAC;qBAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;oBACrC,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC;gBAC7B,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,KAAK,CACb,kCAAkC,QAAQ,qDAAqD,CAChG,CAAC;gBACJ,CAAC;YACH,CAAC;YAED,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,QAAQ;YACR,WAAW;YACX,QAAQ;YACR,eAAe;SAChB,CAAC;IACJ,CAAC;CACF;AArMD,gEAqMC","sourcesContent":["import { Message, Metafile, OutputFile } from 'esbuild';\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport { ensureUnixPath } from '../utils/path';\nimport { BuildOutputFileType, BundleContextResult, BundlerContext } from './bundler-context';\nimport { MemoryCache } from './cache';\nimport { MemoryLoadResultCache } from './load-result-cache';\nimport { BundleStylesheetOptions, createStylesheetBundleOptions } from './stylesheets/bundle-options';\nimport { shutdownSassWorkerPool } from './stylesheets/sass-language';\n\nexport interface ComponentStylesheetResult {\n errors: Message[] | undefined;\n warnings: Message[];\n contents: string;\n outputFiles: OutputFile[];\n metafile: Metafile | undefined;\n referencedFiles: Set<string> | undefined;\n}\n\n/**\n * Bundles component stylesheets. A stylesheet can be either an inline stylesheet that\n * is contained within the Component's metadata definition or an external file referenced\n * from the Component's metadata definition.\n */\nexport class ComponentStylesheetBundler {\n readonly #fileContexts = new MemoryCache<BundlerContext>();\n readonly #inlineContexts = new MemoryCache<BundlerContext>();\n readonly #loadCache = new MemoryLoadResultCache();\n\n /**\n * @param options An object containing the stylesheet bundling options.\n * @param defaultInlineLanguage The default language to use for inline component styles.\n * @param incremental True if incremental watch mode is enabled.\n */\n constructor(\n private readonly options: BundleStylesheetOptions,\n private readonly defaultInlineLanguage: string,\n private readonly incremental: boolean,\n ) {}\n\n async bundleFile(entry: string): Promise<ComponentStylesheetResult> {\n entry = ensureUnixPath(entry);\n\n const bundlerContext = await this.#fileContexts.getOrCreate(entry, () => {\n return new BundlerContext(\n this.options.workspaceRoot,\n this.incremental,\n loadCache => {\n const buildOptions = createStylesheetBundleOptions(this.options, loadCache);\n\n buildOptions.entryPoints = [entry];\n\n return buildOptions;\n },\n /* useContext */ false,\n /* initialFilter */ undefined,\n this.#loadCache,\n );\n });\n\n return this.extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles);\n }\n\n async bundleInline(\n data: string,\n filename: string,\n language: string = this.defaultInlineLanguage,\n ): Promise<ComponentStylesheetResult> {\n filename = ensureUnixPath(filename);\n\n // Use a hash of the inline stylesheet content to ensure a consistent identifier. External stylesheets will resolve\n // to the actual stylesheet file path.\n // TODO: Consider xxhash instead for hashing\n const id = createHash('sha256').update(data).digest('hex');\n const entry = [language, id, filename].join(';');\n\n const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => {\n const namespace = 'angular:styles/component';\n\n return new BundlerContext(\n this.options.workspaceRoot,\n this.incremental,\n loadCache => {\n const buildOptions = createStylesheetBundleOptions(this.options, loadCache, {\n [entry]: data,\n });\n buildOptions.entryPoints = [`${namespace};${entry}`];\n\n buildOptions.plugins.push({\n name: 'angular-component-styles',\n setup(build) {\n build.onResolve({ filter: /^angular:styles\\/component;/ }, args => {\n if (args.kind !== 'entry-point') {\n return null;\n }\n\n return {\n path: entry,\n namespace,\n };\n });\n build.onLoad({ filter: /^css;/, namespace }, () => {\n return {\n contents: data,\n loader: 'css',\n resolveDir: path.dirname(filename),\n };\n });\n },\n });\n\n return buildOptions;\n },\n /* useContext */ false,\n /* initialFilter */ undefined,\n this.#loadCache,\n );\n });\n\n // Extract the result of the bundling from the output files\n return this.extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles);\n }\n\n /**\n * Invalidates both file and inline based component style bundling state for a set of modified files.\n * @param files The group of files that have been modified\n * @returns An array of file based stylesheet entries if any were invalidated; otherwise, undefined.\n */\n invalidate(files: Iterable<string> | ReadonlySet<string>): string[] | undefined {\n if (!this.incremental) {\n return;\n }\n\n const normalizedFiles = new Set<string>();\n for (const file of files) {\n const normalized = ensureUnixPath(file);\n normalizedFiles.add(normalized);\n if (!path.isAbsolute(normalized)) {\n normalizedFiles.add(ensureUnixPath(path.join(this.options.workspaceRoot, normalized)));\n }\n }\n\n let entries: string[] | undefined;\n\n for (const [entry, bundler] of this.#fileContexts.entries()) {\n if (bundler.invalidate(normalizedFiles)) {\n entries ??= [];\n entries.push(entry);\n }\n }\n for (const [entry, bundler] of this.#inlineContexts.entries()) {\n // Entry is format: [language, id, filename].join(';')\n const firstSemi = entry.indexOf(';');\n const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1;\n const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : '';\n if (filename && normalizedFiles.has(ensureUnixPath(filename))) {\n this.#inlineContexts.delete(entry);\n void bundler.dispose();\n } else {\n bundler.invalidate(normalizedFiles);\n }\n }\n\n return entries;\n }\n\n async dispose(): Promise<void> {\n const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()];\n this.#fileContexts.clear();\n this.#inlineContexts.clear();\n this.#loadCache.clear();\n\n await Promise.allSettled([shutdownSassWorkerPool(), ...contexts.map(context => context.dispose())]);\n }\n\n private extractResult(\n result: BundleContextResult,\n referencedFiles: Set<string> | undefined,\n ): ComponentStylesheetResult {\n let contents = '';\n let metafile;\n const outputFiles: OutputFile[] = [];\n\n if ('outputFiles' in result) {\n for (const outputFile of result.outputFiles) {\n const filename = path.basename(outputFile.path);\n\n if (outputFile.type === BuildOutputFileType.Media || filename.endsWith('.css.map')) {\n // The output files could also contain resources (images/fonts/etc.) that were referenced and the map files.\n\n // Clone the output file to avoid amending the original path which would causes problems during rebuild.\n const clonedOutputFile = outputFile.clone();\n\n // Needed for Bazel as otherwise the files will not be written in the correct place,\n // this is because esbuild will resolve the output file from the outdir which is currently set to `workspaceRoot` twice,\n // once in the stylesheet and the other in the application code bundler.\n // Ex: `../../../../../app.component.css.map`.\n clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path);\n\n outputFiles.push(clonedOutputFile);\n } else if (filename.endsWith('.css')) {\n contents = outputFile.text;\n } else {\n throw new Error(\n `Unexpected non CSS/Media file \"${filename}\" outputted during component stylesheet processing.`,\n );\n }\n }\n\n metafile = result.metafile;\n }\n\n return {\n errors: result.errors,\n warnings: result.warnings,\n contents,\n outputFiles,\n metafile,\n referencedFiles,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"component-stylesheets.js","sourceRoot":"","sources":["../../../../src/lib/styles/component-stylesheets.ts"],"names":[],"mappings":";;;;;;AACA,6CAAyC;AACzC,0DAA6B;AAC7B,wCAA+C;AAC/C,uDAA6F;AAC7F,mCAAsC;AACtC,2DAA4D;AAC5D,iEAAsG;AACtG,+DAAgG;AAWhG;;;;GAIG;AACH,MAAa,0BAA0B;IAWlB;IACA;IACA;IAZV,aAAa,GAAG,IAAI,mBAAW,EAAkB,CAAC;IAClD,eAAe,GAAG,IAAI,mBAAW,EAAkB,CAAC;IACpD,UAAU,GAAG,IAAI,yCAAqB,EAAE,CAAC;IAElD;;;;OAIG;IACH,YACmB,OAAgC,EAChC,qBAA6B,EAC7B,WAAoB;QAFpB,YAAO,GAAP,OAAO,CAAyB;QAChC,0BAAqB,GAArB,qBAAqB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,MAAM,UAAU,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;gBAC5C,MAAM,QAAQ,GAAG,mBAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBAEhD,IAAI,UAAU,CAAC,IAAI,KAAK,qCAAmB,CAAC,KAAK,IAAI,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;oBACnF,4GAA4G;oBAE5G,wGAAwG;oBACxG,MAAM,gBAAgB,GAAG,UAAU,CAAC,KAAK,EAAE,CAAC;oBAE5C,oFAAoF;oBACpF,wHAAwH;oBACxH,wEAAwE;oBACxE,8CAA8C;oBAC9C,gBAAgB,CAAC,IAAI,GAAG,mBAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;oBAE/E,WAAW,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;gBACrC,CAAC;qBAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;oBACrC,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC;gBAC7B,CAAC;qBAAM,CAAC;oBACN,MAAM,IAAI,KAAK,CACb,kCAAkC,QAAQ,qDAAqD,CAChG,CAAC;gBACJ,CAAC;YACH,CAAC;YAED,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAC7B,CAAC;QAED,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,QAAQ;YACR,WAAW;YACX,QAAQ;YACR,eAAe;SAChB,CAAC;IACJ,CAAC;CACF;AAvMD,gEAuMC","sourcesContent":["import { Message, Metafile, OutputFile } from 'esbuild';\nimport { createHash } from 'node:crypto';\nimport path from 'node:path';\nimport { ensureUnixPath } from '../utils/path';\nimport { BuildOutputFileType, BundleContextResult, BundlerContext } from './bundler-context';\nimport { MemoryCache } from './cache';\nimport { MemoryLoadResultCache } from './load-result-cache';\nimport { BundleStylesheetOptions, createStylesheetBundleOptions } from './stylesheets/bundle-options';\nimport { resetSassWorkerPoolCaches, shutdownSassWorkerPool } from './stylesheets/sass-language';\n\nexport interface ComponentStylesheetResult {\n errors: Message[] | undefined;\n warnings: Message[];\n contents: string;\n outputFiles: OutputFile[];\n metafile: Metafile | undefined;\n referencedFiles: Set<string> | undefined;\n}\n\n/**\n * Bundles component stylesheets. A stylesheet can be either an inline stylesheet that\n * is contained within the Component's metadata definition or an external file referenced\n * from the Component's metadata definition.\n */\nexport class ComponentStylesheetBundler {\n readonly #fileContexts = new MemoryCache<BundlerContext>();\n readonly #inlineContexts = new MemoryCache<BundlerContext>();\n readonly #loadCache = new MemoryLoadResultCache();\n\n /**\n * @param options An object containing the stylesheet bundling options.\n * @param defaultInlineLanguage The default language to use for inline component styles.\n * @param incremental True if incremental watch mode is enabled.\n */\n constructor(\n private readonly options: BundleStylesheetOptions,\n private readonly defaultInlineLanguage: string,\n private readonly incremental: boolean,\n ) {}\n\n async bundleFile(entry: string): Promise<ComponentStylesheetResult> {\n entry = ensureUnixPath(entry);\n\n const bundlerContext = await this.#fileContexts.getOrCreate(entry, () => {\n return new BundlerContext(\n this.options.workspaceRoot,\n this.incremental,\n loadCache => {\n const buildOptions = createStylesheetBundleOptions(this.options, loadCache);\n\n buildOptions.entryPoints = [entry];\n\n return buildOptions;\n },\n /* useContext */ false,\n /* initialFilter */ undefined,\n this.#loadCache,\n );\n });\n\n return this.extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles);\n }\n\n async bundleInline(\n data: string,\n filename: string,\n language: string = this.defaultInlineLanguage,\n ): Promise<ComponentStylesheetResult> {\n filename = ensureUnixPath(filename);\n\n // Use a hash of the inline stylesheet content to ensure a consistent identifier. External stylesheets will resolve\n // to the actual stylesheet file path.\n // TODO: Consider xxhash instead for hashing\n const id = createHash('sha256').update(data).digest('hex');\n const entry = [language, id, filename].join(';');\n\n const bundlerContext = await this.#inlineContexts.getOrCreate(entry, () => {\n const namespace = 'angular:styles/component';\n\n return new BundlerContext(\n this.options.workspaceRoot,\n this.incremental,\n loadCache => {\n const buildOptions = createStylesheetBundleOptions(this.options, loadCache, {\n [entry]: data,\n });\n buildOptions.entryPoints = [`${namespace};${entry}`];\n\n buildOptions.plugins.push({\n name: 'angular-component-styles',\n setup(build) {\n build.onResolve({ filter: /^angular:styles\\/component;/ }, args => {\n if (args.kind !== 'entry-point') {\n return null;\n }\n\n return {\n path: entry,\n namespace,\n };\n });\n build.onLoad({ filter: /^css;/, namespace }, () => {\n return {\n contents: data,\n loader: 'css',\n resolveDir: path.dirname(filename),\n };\n });\n },\n });\n\n return buildOptions;\n },\n /* useContext */ false,\n /* initialFilter */ undefined,\n this.#loadCache,\n );\n });\n\n // Extract the result of the bundling from the output files\n return this.extractResult(await bundlerContext.bundle(), bundlerContext.watchFiles);\n }\n\n /**\n * Invalidates both file and inline based component style bundling state for a set of modified files.\n * @param files The group of files that have been modified\n * @returns An array of file based stylesheet entries if any were invalidated; otherwise, undefined.\n */\n invalidate(files: Iterable<string> | ReadonlySet<string>): string[] | undefined {\n if (!this.incremental) {\n return;\n }\n\n resetSassWorkerPoolCaches();\n\n const normalizedFiles = new Set<string>();\n for (const file of files) {\n const normalized = ensureUnixPath(file);\n normalizedFiles.add(normalized);\n if (!path.isAbsolute(normalized)) {\n normalizedFiles.add(ensureUnixPath(path.join(this.options.workspaceRoot, normalized)));\n }\n }\n\n let entries: string[] | undefined;\n\n for (const [entry, bundler] of this.#fileContexts.entries()) {\n if (bundler.invalidate(normalizedFiles)) {\n entries ??= [];\n entries.push(entry);\n }\n }\n for (const [entry, bundler] of this.#inlineContexts.entries()) {\n // Entry is format: [language, id, filename].join(';')\n const firstSemi = entry.indexOf(';');\n const secondSemi = firstSemi !== -1 ? entry.indexOf(';', firstSemi + 1) : -1;\n const filename = secondSemi !== -1 ? entry.slice(secondSemi + 1) : '';\n if (filename && normalizedFiles.has(ensureUnixPath(filename))) {\n this.#inlineContexts.delete(entry);\n void bundler.dispose();\n } else {\n bundler.invalidate(normalizedFiles);\n }\n }\n\n return entries;\n }\n\n async dispose(): Promise<void> {\n const contexts = [...this.#fileContexts.values(), ...this.#inlineContexts.values()];\n this.#fileContexts.clear();\n this.#inlineContexts.clear();\n this.#loadCache.clear();\n\n await Promise.allSettled([shutdownSassWorkerPool(), ...contexts.map(context => context.dispose())]);\n }\n\n private extractResult(\n result: BundleContextResult,\n referencedFiles: Set<string> | undefined,\n ): ComponentStylesheetResult {\n let contents = '';\n let metafile;\n const outputFiles: OutputFile[] = [];\n\n if ('outputFiles' in result) {\n for (const outputFile of result.outputFiles) {\n const filename = path.basename(outputFile.path);\n\n if (outputFile.type === BuildOutputFileType.Media || filename.endsWith('.css.map')) {\n // The output files could also contain resources (images/fonts/etc.) that were referenced and the map files.\n\n // Clone the output file to avoid amending the original path which would causes problems during rebuild.\n const clonedOutputFile = outputFile.clone();\n\n // Needed for Bazel as otherwise the files will not be written in the correct place,\n // this is because esbuild will resolve the output file from the outdir which is currently set to `workspaceRoot` twice,\n // once in the stylesheet and the other in the application code bundler.\n // Ex: `../../../../../app.component.css.map`.\n clonedOutputFile.path = path.join(this.options.workspaceRoot, outputFile.path);\n\n outputFiles.push(clonedOutputFile);\n } else if (filename.endsWith('.css')) {\n contents = outputFile.text;\n } else {\n throw new Error(\n `Unexpected non CSS/Media file \"${filename}\" outputted during component stylesheet processing.`,\n );\n }\n }\n\n metafile = result.metafile;\n }\n\n return {\n errors: result.errors,\n warnings: result.warnings,\n contents,\n outputFiles,\n metafile,\n referencedFiles,\n };\n }\n}\n"]}
@@ -31,6 +31,10 @@ export declare class SassCompiler {
31
31
  * @param options The `sass` / `sass-embedded` options to use when rendering the stylesheet.
32
32
  */
33
33
  compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult>;
34
+ /**
35
+ * Clear the directory cache.
36
+ */
37
+ clearCache(): void;
34
38
  /**
35
39
  * Shutdown the Sass compiler.
36
40
  * @returns A void promise that resolves when closing is complete.
@@ -69,6 +69,7 @@ class SassCompiler {
69
69
  rebase;
70
70
  #asyncCompiler;
71
71
  #asyncCompilerPromise;
72
+ #directoryCache = new Map();
72
73
  constructor(rebase = false) {
73
74
  this.rebase = rebase;
74
75
  }
@@ -126,7 +127,7 @@ class SassCompiler {
126
127
  let finalImporters;
127
128
  let loadPaths = options.loadPaths;
128
129
  const entryDirectory = url ? (0, node_path_1.dirname)((0, node_url_1.fileURLToPath)(url)) : process.cwd();
129
- const directoryCache = new Map();
130
+ const directoryCache = this.#directoryCache;
130
131
  const rebaseSourceMaps = options.sourceMap ? new Map() : undefined;
131
132
  if (importers?.length) {
132
133
  if (importers.some(i => !isFileImporter(i))) {
@@ -163,11 +164,18 @@ class SassCompiler {
163
164
  }
164
165
  return result;
165
166
  }
167
+ /**
168
+ * Clear the directory cache.
169
+ */
170
+ clearCache() {
171
+ this.#directoryCache.clear();
172
+ }
166
173
  /**
167
174
  * Shutdown the Sass compiler.
168
175
  * @returns A void promise that resolves when closing is complete.
169
176
  */
170
177
  async close() {
178
+ this.clearCache();
171
179
  if (this.#asyncCompilerPromise !== undefined) {
172
180
  try {
173
181
  await this.#ensureAsyncCompiler();
@@ -1 +1 @@
1
- {"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sEAA2E;AAC3E,yCAAoC;AACpC,uCAAyC;AAUzC,2DAK6B;AAK7B,SAAS,cAAc,CAAC,KAAgB;IACtC,OAAO,aAAa,IAAI,KAAK,CAAC;AAChC,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,OAAO,EAAE,CAAC;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K,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;YAC7C,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACP,sDAAsD;YACxD,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC;YACrC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;YAChC,MAAM,QAAQ,CAAC,OAAO,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;CACF;AAhJD,oCAgJC","sourcesContent":["import mergeSourceMaps, { type RawSourceMap } from '@ampproject/remapping';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type {\n AsyncCompiler,\n CanonicalizeContext,\n CompileResult,\n FileImporter,\n Importer,\n NodePackageImporter,\n StringOptions,\n} from 'sass-embedded';\nimport {\n AsyncModuleUrlRebasingImporter,\n DirectoryEntry,\n LoadPathsUrlRebasingImporter,\n RelativeUrlRebasingImporter,\n} from './rebasing-importer';\n\ntype Importers =\n Importer<'sync'> | Importer<'async'> | FileImporter<'sync'> | FileImporter<'async'> | NodePackageImporter;\n\nfunction isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n}\n\nfunction parseTristate(value: unknown): boolean | undefined {\n if (value === '1' || value === 'true') {\n return true;\n }\n if (value === '0' || value === 'false') {\n return false;\n }\n\n return undefined;\n}\n\n/**\n * When `NG_BUILD_SASS_EMBEDDED` is set to `0` or `false`, or when running within a\n * WebContainer environment, the native embedded Sass compiler is disabled\n * and the pure-JavaScript Sass compiler is used instead.\n */\nexport const useSassEmbedded =\n !(process.versions as Record<string, string | undefined>)['webcontainer'] &&\n parseTristate(process.env['NG_BUILD_SASS_EMBEDDED']) !== false;\n\n/**\n * A Sass renderer implementation that uses the persistent Dart Sass embedded compiler\n * daemon (`sass-embedded`) communicating over standard input/output with protocol buffers,\n * or falls back to the pure-JS Dart Sass async compiler (`sass.initAsyncCompiler()`).\n */\nexport class SassCompiler {\n #asyncCompiler: AsyncCompiler | undefined;\n #asyncCompilerPromise: Promise<AsyncCompiler> | undefined;\n\n constructor(private readonly rebase = false) {}\n\n async #createAsyncCompiler(): Promise<AsyncCompiler> {\n if (useSassEmbedded) {\n const { initAsyncCompiler } = await import('sass-embedded');\n\n return initAsyncCompiler();\n }\n\n const { initAsyncCompiler } = await import('sass');\n\n return initAsyncCompiler() as unknown as Promise<AsyncCompiler>;\n }\n\n async #ensureAsyncCompiler(): Promise<AsyncCompiler> {\n if (this.#asyncCompiler) {\n return this.#asyncCompiler;\n }\n\n this.#asyncCompilerPromise ??= this.#createAsyncCompiler();\n\n try {\n this.#asyncCompiler = await this.#asyncCompilerPromise;\n } finally {\n this.#asyncCompilerPromise = undefined;\n }\n\n return this.#asyncCompiler;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `sass-embedded` or `sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return useSassEmbedded ? 'sass-embedded\\tasync-compiler' : 'dart-sass\\tasync-compiler';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be rendered using the native embedded compiler\n * or the pure-JS async compiler fallback.\n *\n * @param source The contents to compile.\n * @param options The `sass` / `sass-embedded` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (options.functions && Object.keys(options.functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n const compiler = await this.#ensureAsyncCompiler();\n\n if (!this.rebase) {\n return compiler.compileStringAsync(source, options);\n }\n\n const { functions, importers, importer, url, logger, ...serializableOptions } = options;\n\n let finalImporters: (Importer<'async'> | FileImporter<'async'> | NodePackageImporter)[] | undefined;\n let loadPaths = options.loadPaths;\n const entryDirectory = url ? dirname(fileURLToPath(url)) : process.cwd();\n const directoryCache = new Map<string, DirectoryEntry>();\n const rebaseSourceMaps = options.sourceMap ? new Map<string, RawSourceMap>() : undefined;\n\n if (importers?.length) {\n if (importers.some(i => !isFileImporter(i))) {\n throw new Error('Only File Importers are supported.');\n }\n\n finalImporters = [\n new AsyncModuleUrlRebasingImporter(\n entryDirectory,\n directoryCache,\n async (specifier: string, options: CanonicalizeContext): Promise<URL | null> => {\n for (const importer of importers) {\n const result = await (importer as FileImporter<'async'>).findFileUrl(specifier, options);\n if (result) {\n return result;\n }\n }\n\n return null;\n },\n ),\n ];\n }\n\n if (loadPaths?.length) {\n finalImporters ??= [];\n finalImporters.push(new LoadPathsUrlRebasingImporter(entryDirectory, directoryCache, loadPaths));\n loadPaths = undefined;\n }\n\n const relativeImporter = new RelativeUrlRebasingImporter(entryDirectory, directoryCache);\n\n const result = await compiler.compileStringAsync(source, {\n ...serializableOptions,\n url,\n loadPaths,\n importers: finalImporters,\n importer: relativeImporter,\n logger,\n });\n\n if (result.sourceMap && rebaseSourceMaps?.size) {\n result.sourceMap = mergeSourceMaps(result.sourceMap as unknown as RawSourceMap, (file, context) =>\n file !== context.importer ? rebaseSourceMaps.get(file) : null,\n ) as unknown as typeof result.sourceMap;\n }\n\n return result;\n }\n\n /**\n * Shutdown the Sass compiler.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n if (this.#asyncCompilerPromise !== undefined) {\n try {\n await this.#ensureAsyncCompiler();\n } catch {\n // Ignore compiler initialization failures on shutdown\n }\n }\n\n if (this.#asyncCompiler) {\n const compiler = this.#asyncCompiler;\n this.#asyncCompiler = undefined;\n await compiler.dispose();\n }\n }\n}\n"]}
1
+ {"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,CAAC;QAEH,IAAI,MAAM,CAAC,SAAS,IAAI,gBAAgB,EAAE,IAAI,EAAE,CAAC;YAC/C,MAAM,CAAC,SAAS,GAAG,IAAA,mBAAe,EAAC,MAAM,CAAC,SAAoC,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CAChG,IAAI,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACxB,CAAC;QAC1C,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;IAC/B,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,KAAK;QACT,IAAI,CAAC,UAAU,EAAE,CAAC;QAElB,IAAI,IAAI,CAAC,qBAAqB,KAAK,SAAS,EAAE,CAAC;YAC7C,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACP,sDAAsD;YACxD,CAAC;QACH,CAAC;QAED,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC;YACrC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;YAChC,MAAM,QAAQ,CAAC,OAAO,EAAE,CAAC;QAC3B,CAAC;IACH,CAAC;CACF;AA1JD,oCA0JC","sourcesContent":["import mergeSourceMaps, { type RawSourceMap } from '@ampproject/remapping';\nimport { dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type {\n AsyncCompiler,\n CanonicalizeContext,\n CompileResult,\n FileImporter,\n Importer,\n NodePackageImporter,\n StringOptions,\n} from 'sass-embedded';\nimport {\n AsyncModuleUrlRebasingImporter,\n DirectoryEntry,\n LoadPathsUrlRebasingImporter,\n RelativeUrlRebasingImporter,\n} from './rebasing-importer';\n\ntype Importers =\n Importer<'sync'> | Importer<'async'> | FileImporter<'sync'> | FileImporter<'async'> | NodePackageImporter;\n\nfunction isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n}\n\nfunction parseTristate(value: unknown): boolean | undefined {\n if (value === '1' || value === 'true') {\n return true;\n }\n if (value === '0' || value === 'false') {\n return false;\n }\n\n return undefined;\n}\n\n/**\n * When `NG_BUILD_SASS_EMBEDDED` is set to `0` or `false`, or when running within a\n * WebContainer environment, the native embedded Sass compiler is disabled\n * and the pure-JavaScript Sass compiler is used instead.\n */\nexport const useSassEmbedded =\n !(process.versions as Record<string, string | undefined>)['webcontainer'] &&\n parseTristate(process.env['NG_BUILD_SASS_EMBEDDED']) !== false;\n\n/**\n * A Sass renderer implementation that uses the persistent Dart Sass embedded compiler\n * daemon (`sass-embedded`) communicating over standard input/output with protocol buffers,\n * or falls back to the pure-JS Dart Sass async compiler (`sass.initAsyncCompiler()`).\n */\nexport class SassCompiler {\n #asyncCompiler: AsyncCompiler | undefined;\n #asyncCompilerPromise: Promise<AsyncCompiler> | undefined;\n readonly #directoryCache = new Map<string, DirectoryEntry>();\n\n constructor(private readonly rebase = false) {}\n\n async #createAsyncCompiler(): Promise<AsyncCompiler> {\n if (useSassEmbedded) {\n const { initAsyncCompiler } = await import('sass-embedded');\n\n return initAsyncCompiler();\n }\n\n const { initAsyncCompiler } = await import('sass');\n\n return initAsyncCompiler() as unknown as Promise<AsyncCompiler>;\n }\n\n async #ensureAsyncCompiler(): Promise<AsyncCompiler> {\n if (this.#asyncCompiler) {\n return this.#asyncCompiler;\n }\n\n this.#asyncCompilerPromise ??= this.#createAsyncCompiler();\n\n try {\n this.#asyncCompiler = await this.#asyncCompilerPromise;\n } finally {\n this.#asyncCompilerPromise = undefined;\n }\n\n return this.#asyncCompiler;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `sass-embedded` or `sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return useSassEmbedded ? 'sass-embedded\\tasync-compiler' : 'dart-sass\\tasync-compiler';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be rendered using the native embedded compiler\n * or the pure-JS async compiler fallback.\n *\n * @param source The contents to compile.\n * @param options The `sass` / `sass-embedded` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (options.functions && Object.keys(options.functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n const compiler = await this.#ensureAsyncCompiler();\n\n if (!this.rebase) {\n return compiler.compileStringAsync(source, options);\n }\n\n const { functions, importers, importer, url, logger, ...serializableOptions } = options;\n\n let finalImporters: (Importer<'async'> | FileImporter<'async'> | NodePackageImporter)[] | undefined;\n let loadPaths = options.loadPaths;\n const entryDirectory = url ? dirname(fileURLToPath(url)) : process.cwd();\n const directoryCache = this.#directoryCache;\n const rebaseSourceMaps = options.sourceMap ? new Map<string, RawSourceMap>() : undefined;\n\n if (importers?.length) {\n if (importers.some(i => !isFileImporter(i))) {\n throw new Error('Only File Importers are supported.');\n }\n\n finalImporters = [\n new AsyncModuleUrlRebasingImporter(\n entryDirectory,\n directoryCache,\n async (specifier: string, options: CanonicalizeContext): Promise<URL | null> => {\n for (const importer of importers) {\n const result = await (importer as FileImporter<'async'>).findFileUrl(specifier, options);\n if (result) {\n return result;\n }\n }\n\n return null;\n },\n ),\n ];\n }\n\n if (loadPaths?.length) {\n finalImporters ??= [];\n finalImporters.push(new LoadPathsUrlRebasingImporter(entryDirectory, directoryCache, loadPaths));\n loadPaths = undefined;\n }\n\n const relativeImporter = new RelativeUrlRebasingImporter(entryDirectory, directoryCache);\n\n const result = await compiler.compileStringAsync(source, {\n ...serializableOptions,\n url,\n loadPaths,\n importers: finalImporters,\n importer: relativeImporter,\n logger,\n });\n\n if (result.sourceMap && rebaseSourceMaps?.size) {\n result.sourceMap = mergeSourceMaps(result.sourceMap as unknown as RawSourceMap, (file, context) =>\n file !== context.importer ? rebaseSourceMaps.get(file) : null,\n ) as unknown as typeof result.sourceMap;\n }\n\n return result;\n }\n\n /**\n * Clear the directory cache.\n */\n clearCache(): void {\n this.#directoryCache.clear();\n }\n\n /**\n * Shutdown the Sass compiler.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n this.clearCache();\n\n if (this.#asyncCompilerPromise !== undefined) {\n try {\n await this.#ensureAsyncCompiler();\n } catch {\n // Ignore compiler initialization failures on shutdown\n }\n }\n\n if (this.#asyncCompiler) {\n const compiler = this.#asyncCompiler;\n this.#asyncCompiler = undefined;\n await compiler.dispose();\n }\n }\n}\n"]}
@@ -1,3 +1,4 @@
1
1
  import { StylesheetLanguage } from './stylesheet-plugin-factory';
2
+ export declare function resetSassWorkerPoolCaches(): void;
2
3
  export declare function shutdownSassWorkerPool(): void;
3
4
  export declare const SassStylesheetLanguage: Readonly<StylesheetLanguage>;
@@ -34,16 +34,30 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.SassStylesheetLanguage = void 0;
37
+ exports.resetSassWorkerPoolCaches = resetSassWorkerPoolCaches;
37
38
  exports.shutdownSassWorkerPool = shutdownSassWorkerPool;
38
39
  const node_path_1 = require("node:path");
39
40
  const node_url_1 = require("node:url");
40
41
  const cache_1 = require("../cache");
41
42
  let sassService;
42
43
  let sassServicePromise;
44
+ let resolutionCache;
45
+ let packageRootCache;
43
46
  function isSassException(error) {
44
47
  return !!error && typeof error === 'object' && 'sassMessage' in error;
45
48
  }
49
+ function resetSassWorkerPoolCaches() {
50
+ resolutionCache?.clear();
51
+ packageRootCache?.clear();
52
+ if (sassService) {
53
+ sassService.clearCache();
54
+ }
55
+ else if (sassServicePromise !== undefined) {
56
+ void sassServicePromise.then(service => service.clearCache());
57
+ }
58
+ }
46
59
  function shutdownSassWorkerPool() {
60
+ resetSassWorkerPoolCaches();
47
61
  if (sassService) {
48
62
  void sassService.close();
49
63
  sassService = undefined;
@@ -99,14 +113,15 @@ async function compileString(data, filePath, syntax, options, resolveUrl) {
99
113
  sassServicePromise = undefined;
100
114
  }
101
115
  }
102
- // Cache is currently local to individual compile requests.
103
- // Caching follows Sass behavior where a given url will always resolve to the same value
104
- // regardless of its importer's path.
116
+ // Caching follows Sass behavior where a given package url will always resolve to the same value
117
+ // regardless of its importer's path. Relative paths are qualified with the containing URL.
105
118
  // A null value indicates that the cached resolution attempt failed to find a location and
106
119
  // later stage resolution should be attempted. This avoids potentially expensive repeat
107
120
  // failing resolution attempts.
108
- const resolutionCache = new cache_1.MemoryCache();
109
- const packageRootCache = new cache_1.MemoryCache();
121
+ resolutionCache ??= new cache_1.MemoryCache();
122
+ packageRootCache ??= new cache_1.MemoryCache();
123
+ const currentResolutionCache = resolutionCache;
124
+ const currentPackageRootCache = packageRootCache;
110
125
  const warnings = [];
111
126
  const { silenceDeprecations, futureDeprecations, fatalDeprecations } = options.sass ?? {};
112
127
  try {
@@ -123,30 +138,34 @@ async function compileString(data, filePath, syntax, options, resolveUrl) {
123
138
  quietDeps: true,
124
139
  importers: [
125
140
  {
126
- findFileUrl: (url, options) => resolutionCache.getOrCreate(url, async () => {
127
- const result = await resolveUrl(url, options);
128
- if (result.path) {
129
- return (0, node_url_1.pathToFileURL)(result.path);
130
- }
131
- // Check for package deep imports
132
- const { packageName, pathSegments } = parsePackageName(url);
133
- // Caching package root locations is particularly beneficial for `@material/*` packages
134
- // which extensively use deep imports.
135
- const packageRoot = await packageRootCache.getOrCreate(packageName, async () => {
136
- // Use the required presence of a package root `package.json` file to resolve the location
137
- const packageResult = await resolveUrl(packageName + '/package.json', options);
138
- return packageResult.path ? (0, node_path_1.dirname)(packageResult.path) : null;
141
+ findFileUrl: (url, options) => {
142
+ const cacheKey = url.startsWith('pkg:') ? url : `${options.containingUrl?.href ?? ''}:${url}`;
143
+ return currentResolutionCache.getOrCreate(cacheKey, async () => {
144
+ const result = await resolveUrl(url, options);
145
+ if (result.path) {
146
+ return (0, node_url_1.pathToFileURL)(result.path);
147
+ }
148
+ // Check for package deep imports
149
+ const { packageName, pathSegments } = parsePackageName(url);
150
+ // Caching package root locations is particularly beneficial for `@material/*` packages
151
+ // which extensively use deep imports.
152
+ const packageRootKey = `${options.containingUrl?.href ?? ''}:${packageName}`;
153
+ const packageRoot = await currentPackageRootCache.getOrCreate(packageRootKey, async () => {
154
+ // Use the required presence of a package root `package.json` file to resolve the location
155
+ const packageResult = await resolveUrl(packageName + '/package.json', options);
156
+ return packageResult.path ? (0, node_path_1.dirname)(packageResult.path) : null;
157
+ });
158
+ // Package not found could be because of an error or the specifier is intended to be found
159
+ // via a later stage of the resolution process (`loadPaths`, etc.).
160
+ // Errors are reported after the full completion of the resolution process. Exceptions for
161
+ // not found packages should not be raised here.
162
+ if (packageRoot) {
163
+ return (0, node_url_1.pathToFileURL)((0, node_path_1.join)(packageRoot, ...pathSegments));
164
+ }
165
+ // Not found
166
+ return null;
139
167
  });
140
- // Package not found could be because of an error or the specifier is intended to be found
141
- // via a later stage of the resolution process (`loadPaths`, etc.).
142
- // Errors are reported after the full completion of the resolution process. Exceptions for
143
- // not found packages should not be raised here.
144
- if (packageRoot) {
145
- return (0, node_url_1.pathToFileURL)((0, node_path_1.join)(packageRoot, ...pathSegments));
146
- }
147
- // Not found
148
- return null;
149
- }),
168
+ },
150
169
  },
151
170
  ],
152
171
  logger: {
@@ -1 +1 @@
1
- {"version":3,"file":"sass-language.js","sourceRoot":"","sources":["../../../../../src/lib/styles/stylesheets/sass-language.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,wDAQC;AAtBD,yCAAoD;AACpD,uCAAwD;AAExD,oCAAuC;AAIvC,IAAI,WAAqC,CAAC;AAC1C,IAAI,kBAAqD,CAAC;AAE1D,SAAS,eAAe,CAAC,KAAc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ACH,CAAC;AACH,CAAC","sourcesContent":["import type { OnLoadResult, PartialMessage, PartialNote, ResolveResult } from 'esbuild';\nimport { dirname, join, relative } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { CanonicalizeContext, CompileResult, Exception, Syntax } from 'sass-embedded';\nimport { MemoryCache } from '../cache';\nimport type { SassCompiler } from '../sass/sass-service';\nimport { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory';\n\nlet sassService: SassCompiler | undefined;\nlet sassServicePromise: Promise<SassCompiler> | undefined;\n\nfunction isSassException(error: unknown): error is Exception {\n return !!error && typeof error === 'object' && 'sassMessage' in error;\n}\n\nexport function shutdownSassWorkerPool(): void {\n if (sassService) {\n void sassService.close();\n sassService = undefined;\n } else if (sassServicePromise !== undefined) {\n void sassServicePromise.then(shutdownSassWorkerPool);\n }\n sassServicePromise = undefined;\n}\n\nexport const SassStylesheetLanguage = Object.freeze<StylesheetLanguage>({\n name: 'sass',\n componentFilter: /^s[ac]ss;/,\n fileFilter: /\\.s[ac]ss$/,\n process(data, file, format, options, build) {\n const syntax = format === 'sass' ? 'indented' : 'scss';\n const resolveUrl = async (url: string, options: CanonicalizeContext) => {\n let resolveDir = build.initialOptions.absWorkingDir;\n if (options.containingUrl) {\n resolveDir = dirname(fileURLToPath(options.containingUrl));\n }\n\n const path = url.startsWith('pkg:') ? url.slice(4) : url;\n const result = await build.resolve(path, {\n kind: 'import-rule',\n resolveDir,\n });\n\n return result;\n };\n\n return compileString(data, file, syntax, options, resolveUrl);\n },\n});\n\nfunction parsePackageName(url: string): { packageName: string; readonly pathSegments: string[] } {\n const parts = (url.startsWith('pkg:') ? url.slice(4) : url).split('/');\n const hasScope = parts.length >= 2 && parts[0][0] === '@';\n const [nameOrScope, nameOrFirstPath, ...pathPart] = parts;\n const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope;\n\n return {\n packageName,\n get pathSegments() {\n return !hasScope && nameOrFirstPath ? [nameOrFirstPath, ...pathPart] : pathPart;\n },\n };\n}\n\nasync function compileString(\n data: string,\n filePath: string,\n syntax: Syntax,\n options: StylesheetPluginOptions,\n resolveUrl: (url: string, options: CanonicalizeContext) => Promise<ResolveResult>,\n): Promise<OnLoadResult> {\n // Lazily load Sass when a Sass file is found\n if (sassService === undefined) {\n if (sassServicePromise === undefined) {\n sassServicePromise = import('../sass/sass-service').then(sassService => new sassService.SassCompiler(true));\n }\n try {\n sassService = await sassServicePromise;\n } finally {\n sassServicePromise = undefined;\n }\n }\n\n // Cache is currently local to individual compile requests.\n // Caching follows Sass behavior where a given url will always resolve to the same value\n // regardless of its importer's path.\n // A null value indicates that the cached resolution attempt failed to find a location and\n // later stage resolution should be attempted. This avoids potentially expensive repeat\n // failing resolution attempts.\n const resolutionCache = new MemoryCache<URL | null>();\n const packageRootCache = new MemoryCache<string | null>();\n const warnings: PartialMessage[] = [];\n const { silenceDeprecations, futureDeprecations, fatalDeprecations } = options.sass ?? {};\n\n try {\n const { css, sourceMap, loadedUrls } = await sassService.compileStringAsync(data, {\n url: pathToFileURL(filePath),\n style: 'expanded',\n syntax,\n loadPaths: options.includePaths,\n sourceMap: options.sourcemap,\n sourceMapIncludeSources: options.sourcemap,\n silenceDeprecations,\n fatalDeprecations,\n futureDeprecations,\n quietDeps: true,\n importers: [\n {\n findFileUrl: (url, options) =>\n resolutionCache.getOrCreate(url, async () => {\n const result = await resolveUrl(url, options);\n if (result.path) {\n return pathToFileURL(result.path);\n }\n\n // Check for package deep imports\n const { packageName, pathSegments } = parsePackageName(url);\n\n // Caching package root locations is particularly beneficial for `@material/*` packages\n // which extensively use deep imports.\n const packageRoot = await packageRootCache.getOrCreate(packageName, async () => {\n // Use the required presence of a package root `package.json` file to resolve the location\n const packageResult = await resolveUrl(packageName + '/package.json', options);\n\n return packageResult.path ? dirname(packageResult.path) : null;\n });\n\n // Package not found could be because of an error or the specifier is intended to be found\n // via a later stage of the resolution process (`loadPaths`, etc.).\n // Errors are reported after the full completion of the resolution process. Exceptions for\n // not found packages should not be raised here.\n if (packageRoot) {\n return pathToFileURL(join(packageRoot, ...pathSegments));\n }\n\n // Not found\n return null;\n }),\n },\n ],\n logger: {\n warn: (text, { deprecation, stack, span }) => {\n const notes: PartialNote[] = [];\n if (deprecation) {\n notes.push({ text });\n }\n if (stack && !span) {\n notes.push({ text: stack });\n }\n\n warnings.push({\n text: deprecation ? 'Deprecation' : text,\n location: span && {\n file: span.url && fileURLToPath(span.url),\n lineText: span.context,\n // Sass line numbers are 0-based while esbuild's are 1-based\n line: span.start.line + 1,\n column: span.start.column,\n },\n notes,\n });\n },\n },\n });\n\n return {\n loader: 'css',\n contents: sourceMap ? `${css}\\n${sourceMapToUrlComment(sourceMap, dirname(filePath))}` : css,\n watchFiles: loadedUrls.map(url => fileURLToPath(url)),\n warnings,\n };\n } catch (error) {\n if (isSassException(error)) {\n const fileWithError = error.span.url ? fileURLToPath(error.span.url) : undefined;\n\n const watchFiles = [filePath, ...extractFilesFromStack(error.sassStack)];\n if (fileWithError) {\n watchFiles.push(fileWithError);\n }\n\n return {\n loader: 'css',\n errors: [\n {\n text: error.message,\n },\n ],\n warnings,\n watchFiles,\n };\n }\n\n throw error;\n }\n}\n\nfunction sourceMapToUrlComment(sourceMap: Exclude<CompileResult['sourceMap'], undefined>, root: string): string {\n // Remove `file` protocol from all sourcemap sources and adjust to be relative to the input file.\n // This allows esbuild to correctly process the paths.\n sourceMap.sources = sourceMap.sources.map(source => relative(root, fileURLToPath(source)));\n\n const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64');\n\n return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`;\n}\n\nfunction* extractFilesFromStack(stack: string): Iterable<string> {\n const lines = stack.split('\\n');\n const cwd = process.cwd();\n\n // Stack line has format of \"<file> <location> <identifier>\"\n for (const line of lines) {\n const segments = line.split(' ');\n if (segments.length < 3) {\n break;\n }\n\n // Extract path from stack line.\n // Paths may contain spaces. All segments before location are part of the file path.\n let path = '';\n let index = 0;\n while (!segments[index].match(/\\d+:\\d+/)) {\n path += segments[index++];\n }\n\n if (path) {\n // Stack paths from sass are relative to the current working directory (not input file or workspace root)\n yield join(cwd, path);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"sass-language.js","sourceRoot":"","sources":["../../../../../src/lib/styles/stylesheets/sass-language.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,8DAQC;AAED,wDASC;AAnCD,yCAAoD;AACpD,uCAAwD;AAExD,oCAAuC;AAIvC,IAAI,WAAqC,CAAC;AAC1C,IAAI,kBAAqD,CAAC;AAC1D,IAAI,eAAoD,CAAC;AACzD,IAAI,gBAAwD,CAAC;AAE7D,SAAS,eAAe,CAAC,KAAc;IACrC,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,aAAa,IAAI,KAAK,CAAC;AACxE,CAAC;AAED,SAAgB,yBAAyB;IACvC,eAAe,EAAE,KAAK,EAAE,CAAC;IACzB,gBAAgB,EAAE,KAAK,EAAE,CAAC;IAC1B,IAAI,WAAW,EAAE,CAAC;QAChB,WAAW,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;SAAM,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;QAC5C,KAAK,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;IAChE,CAAC;AACH,CAAC;AAED,SAAgB,sBAAsB;IACpC,yBAAyB,EAAE,CAAC;IAC5B,IAAI,WAAW,EAAE,CAAC;QAChB,KAAK,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,WAAW,GAAG,SAAS,CAAC;IAC1B,CAAC;SAAM,IAAI,kBAAkB,KAAK,SAAS,EAAE,CAAC;QAC5C,KAAK,kBAAkB,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACvD,CAAC;IACD,k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AC;AACH,CAAC","sourcesContent":["import type { OnLoadResult, PartialMessage, PartialNote, ResolveResult } from 'esbuild';\nimport { dirname, join, relative } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport type { CanonicalizeContext, CompileResult, Exception, Syntax } from 'sass-embedded';\nimport { MemoryCache } from '../cache';\nimport type { SassCompiler } from '../sass/sass-service';\nimport { StylesheetLanguage, StylesheetPluginOptions } from './stylesheet-plugin-factory';\n\nlet sassService: SassCompiler | undefined;\nlet sassServicePromise: Promise<SassCompiler> | undefined;\nlet resolutionCache: MemoryCache<URL | null> | undefined;\nlet packageRootCache: MemoryCache<string | null> | undefined;\n\nfunction isSassException(error: unknown): error is Exception {\n return !!error && typeof error === 'object' && 'sassMessage' in error;\n}\n\nexport function resetSassWorkerPoolCaches(): void {\n resolutionCache?.clear();\n packageRootCache?.clear();\n if (sassService) {\n sassService.clearCache();\n } else if (sassServicePromise !== undefined) {\n void sassServicePromise.then(service => service.clearCache());\n }\n}\n\nexport function shutdownSassWorkerPool(): void {\n resetSassWorkerPoolCaches();\n if (sassService) {\n void sassService.close();\n sassService = undefined;\n } else if (sassServicePromise !== undefined) {\n void sassServicePromise.then(shutdownSassWorkerPool);\n }\n sassServicePromise = undefined;\n}\n\nexport const SassStylesheetLanguage = Object.freeze<StylesheetLanguage>({\n name: 'sass',\n componentFilter: /^s[ac]ss;/,\n fileFilter: /\\.s[ac]ss$/,\n process(data, file, format, options, build) {\n const syntax = format === 'sass' ? 'indented' : 'scss';\n const resolveUrl = async (url: string, options: CanonicalizeContext) => {\n let resolveDir = build.initialOptions.absWorkingDir;\n if (options.containingUrl) {\n resolveDir = dirname(fileURLToPath(options.containingUrl));\n }\n\n const path = url.startsWith('pkg:') ? url.slice(4) : url;\n const result = await build.resolve(path, {\n kind: 'import-rule',\n resolveDir,\n });\n\n return result;\n };\n\n return compileString(data, file, syntax, options, resolveUrl);\n },\n});\n\nfunction parsePackageName(url: string): { packageName: string; readonly pathSegments: string[] } {\n const parts = (url.startsWith('pkg:') ? url.slice(4) : url).split('/');\n const hasScope = parts.length >= 2 && parts[0][0] === '@';\n const [nameOrScope, nameOrFirstPath, ...pathPart] = parts;\n const packageName = hasScope ? `${nameOrScope}/${nameOrFirstPath}` : nameOrScope;\n\n return {\n packageName,\n get pathSegments() {\n return !hasScope && nameOrFirstPath ? [nameOrFirstPath, ...pathPart] : pathPart;\n },\n };\n}\n\nasync function compileString(\n data: string,\n filePath: string,\n syntax: Syntax,\n options: StylesheetPluginOptions,\n resolveUrl: (url: string, options: CanonicalizeContext) => Promise<ResolveResult>,\n): Promise<OnLoadResult> {\n // Lazily load Sass when a Sass file is found\n if (sassService === undefined) {\n if (sassServicePromise === undefined) {\n sassServicePromise = import('../sass/sass-service').then(sassService => new sassService.SassCompiler(true));\n }\n try {\n sassService = await sassServicePromise;\n } finally {\n sassServicePromise = undefined;\n }\n }\n\n // Caching follows Sass behavior where a given package url will always resolve to the same value\n // regardless of its importer's path. Relative paths are qualified with the containing URL.\n // A null value indicates that the cached resolution attempt failed to find a location and\n // later stage resolution should be attempted. This avoids potentially expensive repeat\n // failing resolution attempts.\n resolutionCache ??= new MemoryCache<URL | null>();\n packageRootCache ??= new MemoryCache<string | null>();\n const currentResolutionCache = resolutionCache;\n const currentPackageRootCache = packageRootCache;\n const warnings: PartialMessage[] = [];\n const { silenceDeprecations, futureDeprecations, fatalDeprecations } = options.sass ?? {};\n\n try {\n const { css, sourceMap, loadedUrls } = await sassService.compileStringAsync(data, {\n url: pathToFileURL(filePath),\n style: 'expanded',\n syntax,\n loadPaths: options.includePaths,\n sourceMap: options.sourcemap,\n sourceMapIncludeSources: options.sourcemap,\n silenceDeprecations,\n fatalDeprecations,\n futureDeprecations,\n quietDeps: true,\n importers: [\n {\n findFileUrl: (url, options) => {\n const cacheKey = url.startsWith('pkg:') ? url : `${options.containingUrl?.href ?? ''}:${url}`;\n\n return currentResolutionCache.getOrCreate(cacheKey, async () => {\n const result = await resolveUrl(url, options);\n if (result.path) {\n return pathToFileURL(result.path);\n }\n\n // Check for package deep imports\n const { packageName, pathSegments } = parsePackageName(url);\n\n // Caching package root locations is particularly beneficial for `@material/*` packages\n // which extensively use deep imports.\n const packageRootKey = `${options.containingUrl?.href ?? ''}:${packageName}`;\n const packageRoot = await currentPackageRootCache.getOrCreate(packageRootKey, async () => {\n // Use the required presence of a package root `package.json` file to resolve the location\n const packageResult = await resolveUrl(packageName + '/package.json', options);\n\n return packageResult.path ? dirname(packageResult.path) : null;\n });\n\n // Package not found could be because of an error or the specifier is intended to be found\n // via a later stage of the resolution process (`loadPaths`, etc.).\n // Errors are reported after the full completion of the resolution process. Exceptions for\n // not found packages should not be raised here.\n if (packageRoot) {\n return pathToFileURL(join(packageRoot, ...pathSegments));\n }\n\n // Not found\n return null;\n });\n },\n },\n ],\n logger: {\n warn: (text, { deprecation, stack, span }) => {\n const notes: PartialNote[] = [];\n if (deprecation) {\n notes.push({ text });\n }\n if (stack && !span) {\n notes.push({ text: stack });\n }\n\n warnings.push({\n text: deprecation ? 'Deprecation' : text,\n location: span && {\n file: span.url && fileURLToPath(span.url),\n lineText: span.context,\n // Sass line numbers are 0-based while esbuild's are 1-based\n line: span.start.line + 1,\n column: span.start.column,\n },\n notes,\n });\n },\n },\n });\n\n return {\n loader: 'css',\n contents: sourceMap ? `${css}\\n${sourceMapToUrlComment(sourceMap, dirname(filePath))}` : css,\n watchFiles: loadedUrls.map(url => fileURLToPath(url)),\n warnings,\n };\n } catch (error) {\n if (isSassException(error)) {\n const fileWithError = error.span.url ? fileURLToPath(error.span.url) : undefined;\n\n const watchFiles = [filePath, ...extractFilesFromStack(error.sassStack)];\n if (fileWithError) {\n watchFiles.push(fileWithError);\n }\n\n return {\n loader: 'css',\n errors: [\n {\n text: error.message,\n },\n ],\n warnings,\n watchFiles,\n };\n }\n\n throw error;\n }\n}\n\nfunction sourceMapToUrlComment(sourceMap: Exclude<CompileResult['sourceMap'], undefined>, root: string): string {\n // Remove `file` protocol from all sourcemap sources and adjust to be relative to the input file.\n // This allows esbuild to correctly process the paths.\n sourceMap.sources = sourceMap.sources.map(source => relative(root, fileURLToPath(source)));\n\n const urlSourceMap = Buffer.from(JSON.stringify(sourceMap), 'utf-8').toString('base64');\n\n return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${urlSourceMap} */`;\n}\n\nfunction* extractFilesFromStack(stack: string): Iterable<string> {\n const lines = stack.split('\\n');\n const cwd = process.cwd();\n\n // Stack line has format of \"<file> <location> <identifier>\"\n for (const line of lines) {\n const segments = line.split(' ');\n if (segments.length < 3) {\n break;\n }\n\n // Extract path from stack line.\n // Paths may contain spaces. All segments before location are part of the file path.\n let path = '';\n let index = 0;\n while (!segments[index].match(/\\d+:\\d+/)) {\n path += segments[index++];\n }\n\n if (path) {\n // Stack paths from sass are relative to the current working directory (not input file or workspace root)\n yield join(cwd, path);\n }\n }\n}\n"]}