Debian Codegraph @

node/esbuild-sass-plugin/src/render.ts

raw
1 import {dirname, isAbsolute, parse, relative, resolve, sep} from 'path'
2 import fs, {readFileSync} from 'fs'
3 import {createResolver, fileSyntax, sourceMappingURL, DEFAULT_FILTER} from './utils'
4 import {PartialMessage} from 'esbuild'
5 import {fileURLToPath, pathToFileURL} from 'url'
6 import {SassPluginOptions} from './index'
7 import {ImporterResult} from 'sass'
8 import {StringOptions} from 'sass/types/options'
9 import {CompileResult} from 'sass/types/compile'
10
11 export type RenderSass = (path: string) => Promise<RenderResult>
12
13 export type RenderResult = {
14 cssText: string
15 watchFiles: string[]
16 warnings?: PartialMessage[]
17 }
18
19 export type Compiler = (source: string, options?: StringOptions<any>) => CompileResult | Promise<CompileResult>
20
21 async function createCompiler(embedded:boolean|undefined, onDispose: (callback: () => void) => void): Promise<Compiler> {
22 if (embedded) {
23 const {initAsyncCompiler} = await import('sass-embedded')
24 const compiler = await initAsyncCompiler();
25 onDispose(compiler.dispose.bind(compiler))
26 return compiler.compileStringAsync.bind(compiler) as Compiler
27 } else {
28 const {compileString} = await import('sass')
29 return compileString
30 }
31 }
32
33 export async function createRenderer(
34 options: SassPluginOptions = {},
35 sourcemap: boolean,
36 onDispose: (callback: () => void) => void
37 ): Promise<RenderSass> {
38
39 const loadPaths = options.loadPaths!
40 const resolveModule = createResolver(options, loadPaths)
41
42 /**
43 * NOTE: we're deliberately ignoring sass recommendation to avoid sacrificing speed here!
44 * - we prefer fragment attempt over syntax attempt
45 * - we prefer .scss and .css over .sass
46 * - we don't throw exceptions if the URL is ambiguous
47 */
48 function resolveImport(pathname: string, ext?: string): string | null {
49 if (ext) {
50 let filename = pathname + ext
51 if (fs.existsSync(filename)) {
52 return filename
53 }
54 const index = filename.lastIndexOf(sep)
55 filename = index >= 0 ? filename.slice(0, index) + sep + '_' + filename.slice(index + 1) : '_' + filename
56 if (fs.existsSync(filename)) {
57 return filename
58 }
59 return null
60 } else {
61 if (!fs.existsSync(dirname(pathname))) {
62 return null
63 }
64 return resolveImport(pathname, '.scss')
65 || resolveImport(pathname, '.css')
66 || resolveImport(pathname, '.sass')
67 || resolveImport(pathname + sep + 'index')
68 }
69 }
70
71 function resolveRelativeImport(loadPath: string, filename: string): string | null {
72 const absolute = resolve(loadPath, filename)
73 const pathParts = parse(absolute)
74 if (DEFAULT_FILTER.test(pathParts.ext)) {
75 return resolveImport(pathParts.dir + sep + pathParts.name, pathParts.ext)
76 } else {
77 return resolveImport(absolute)
78 }
79 }
80
81 const sepTilde = `${sep}~`
82
83 const compileString = await createCompiler(options.embedded, onDispose)
84
85 /**
86 * renderAsync
87 */
88 return async function (path: string): Promise<RenderResult> {
89
90 const basedir = dirname(path)
91
92 let source = fs.readFileSync(path, 'utf-8')
93 if (options.precompile) {
94 source = options.precompile(source, path, true)
95 }
96
97 const syntax = fileSyntax(path)
98 if (syntax === 'css') {
99 return {cssText: readFileSync(path, 'utf-8'), watchFiles: [path]}
100 }
101
102 if (options.quietDeps) {
103 options.url = pathToFileURL(path)
104 }
105
106 const warnings: PartialMessage[] = []
107 const logger = options.logger ?? {
108 warn: function (message, opts) {
109 if (!opts.span) {
110 warnings.push({text: `sass warning: ${message}`})
111 } else {
112 const filename = opts.span.url?.pathname ?? path
113 const esbuildMsg = {
114 text: message,
115 location: {
116 file: filename,
117 line: opts.span.start.line,
118 column: opts.span.start.column,
119 lineText: opts.span.text
120 },
121 detail: {
122 deprecation: opts.deprecation,
123 stack: opts.stack
124 }
125 }
126
127 warnings.push(esbuildMsg)
128 }
129 }
130 }
131
132 const {
133 css,
134 loadedUrls,
135 sourceMap
136 } = await compileString(source, {
137 sourceMapIncludeSources: true,
138 ...options,
139 logger,
140 syntax,
141 importer: {
142 load(canonicalUrl: URL): ImporterResult | null {
143 const pathname = fileURLToPath(canonicalUrl)
144 let contents = fs.readFileSync(pathname, 'utf8')
145 if (options.precompile) {
146 contents = options.precompile(contents, pathname, false)
147 }
148 return {
149 contents,
150 syntax: fileSyntax(pathname),
151 sourceMapUrl: sourcemap ? canonicalUrl : undefined
152 }
153 },
154 canonicalize(url: string): URL | null {
155 let filename: string
156 if (url.startsWith('~')) {
157 filename = resolveModule(decodeURI(url.slice(1)), basedir)
158 } else if (url.startsWith('file://')) {
159 filename = fileURLToPath(url)
160 // ================================================ patch for: https://github.com/sass/dart-sass/issues/1581
161 let joint = filename.lastIndexOf(sepTilde)
162 if (joint >= 0) {
163 filename = resolveModule(filename.slice(joint + 2), filename.slice(0, joint))
164 }
165 // =========================================================================================================
166 } else {
167 filename = decodeURI(url)
168 }
169 if (options.importMapper) {
170 filename = options.importMapper(filename)
171 }
172 let resolved = resolveRelativeImport(basedir, filename)
173 if (resolved) {
174 return pathToFileURL(resolved)
175 }
176 for (const loadPath of loadPaths) {
177 resolved = resolveRelativeImport(loadPath, filename)
178 if (resolved) {
179 return pathToFileURL(resolved)
180 }
181 }
182 // For bare module specifiers, fall back to require.resolve which honours package.json "exports"
183 if (!filename.startsWith('.') && !isAbsolute(filename)) {
184 const moduleResolved = resolveModule(filename, basedir)
185 if (moduleResolved !== filename && fs.existsSync(moduleResolved)) {
186 return pathToFileURL(moduleResolved)
187 }
188 }
189 return null
190 }
191 },
192 sourceMap: sourcemap
193 })
194
195 let cssText = css.toString()
196
197 if (sourceMap) {
198 delete sourceMap.sourceRoot
199 sourceMap.sources = sourceMap.sources.map(source => {
200 return relative(basedir, source.startsWith('data:') ? path : fileURLToPath(source))
201 })
202 cssText += '\n' + sourceMappingURL(sourceMap)
203 }
204
205 return {
206 cssText,
207 warnings: warnings,
208 watchFiles: [path, ...loadedUrls.map(fileURLToPath as (url:URL)=>string)]
209 }
210 }
211 }