@hamur/css 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,39 @@
1
+ import type { StyleData } from "./types.ts";
2
+ export interface Compiled {
3
+ code: string;
4
+ /** The files the compiler read besides the one compiled. */
5
+ dependencies: string[];
6
+ }
7
+ export interface CompilerSetup {
8
+ rootDir: string;
9
+ options: {
10
+ additionalData?: StyleData;
11
+ loadPaths?: string[];
12
+ };
13
+ /** Imports a package from the app root, `undefined` when it is not installed. */
14
+ load?: (name: string) => Promise<unknown>;
15
+ }
16
+ export declare function importFromRoot(name: string, rootDir: string): Promise<unknown>;
17
+ export declare const missingCompiler: (name: string) => string;
18
+ export declare function shownPath(rootDir: string, file: string): string;
19
+ export declare const lines: (text: string) => string[];
20
+ /** `file:line:column: message`, then the source line and a caret under the column. */
21
+ export declare function frame(place: string, line: number, column: number, message: string, text: string | undefined): string;
22
+ /** Where a compiler said its error is: 1-based line and column, in the text it was given, in `at` when it is another file. */
23
+ export interface Position {
24
+ message: string;
25
+ line: number;
26
+ column: number;
27
+ at?: string;
28
+ }
29
+ /** The error of `position`: in an imported file at its own line, in `additionalData` named as such, else at the file's line with the data's lines subtracted. */
30
+ export declare function located(rootDir: string, language: string, file: string, source: string, data: string, position: Position, cause: unknown): Promise<Error>;
31
+ export declare const dataOf: (additionalData: StyleData | undefined, source: string, file: string) => Promise<string>;
32
+ export declare const withData: (data: string, source: string) => string;
33
+ /** A `#…` specifier through the `imports` of the app's `package.json`: the exact key, else the `*` key with the longest prefix, to a `./` target. */
34
+ export declare function fromImports(rootDir: string, spec: string): string | undefined;
35
+ /** A result kept per file and text with the hash of `additionalData` and of each file the compile read, so a compile whose inputs did not change returns it without the compiler. */
36
+ export declare function createMemo(): {
37
+ get(file: string, source: string, data: string): Promise<Compiled | undefined>;
38
+ set(file: string, source: string, data: string, code: string, read: string[]): Promise<Compiled>;
39
+ };
@@ -0,0 +1,9 @@
1
+ import { type Compiled, type CompilerSetup } from "./shared.ts";
2
+ export type StylusSetup = CompilerSetup;
3
+ export declare const MISSING_STYLUS: string;
4
+ /** Stylus through the app's own `stylus`, loaded on the first compile; kept and located as Sass's are. */
5
+ export declare function createStylus({ rootDir, options, load }: StylusSetup): {
6
+ /** Compiles `source`, the text of `file` (a `.styl` file, or the component a style block is in). */
7
+ compile(file: string, source: string): Promise<Compiled>;
8
+ };
9
+ export type StylusCompiler = ReturnType<typeof createStylus>;
@@ -0,0 +1,26 @@
1
+ /** Prepended to each file of the language; a function gets the file's text and absolute path. */
2
+ export type StyleData = string | ((source: string, file: string) => string | Promise<string>);
3
+ /** The `cssCompilers` config key. */
4
+ export interface CssCompilers {
5
+ sass?: {
6
+ additionalData?: StyleData;
7
+ loadPaths?: string[];
8
+ };
9
+ less?: {
10
+ additionalData?: StyleData;
11
+ loadPaths?: string[];
12
+ };
13
+ stylus?: {
14
+ additionalData?: StyleData;
15
+ loadPaths?: string[];
16
+ };
17
+ postcss?: boolean | {
18
+ config?: string;
19
+ plugins?: unknown[];
20
+ };
21
+ }
22
+ declare module "hamur" {
23
+ interface HamurModuleOptions {
24
+ cssCompilers?: CssCompilers;
25
+ }
26
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@hamur/css",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/productdevbook/hamur.git",
9
+ "directory": "packages/css"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/types/src/index.d.ts",
14
+ "bun": "./src/index.ts",
15
+ "hamur-source": "./src/index.ts",
16
+ "node": "./dist/src/index.js",
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "src"
24
+ ],
25
+ "dependencies": {},
26
+ "peerDependencies": {
27
+ "hamur": "^0.0.2",
28
+ "sass": "^1.71.0",
29
+ "sass-embedded": "^1.71.0",
30
+ "less": "^4.2.0",
31
+ "stylus": "^0.64.0",
32
+ "postcss": "^8.4.0"
33
+ },
34
+ "peerDependenciesMeta": {
35
+ "sass": {
36
+ "optional": true
37
+ },
38
+ "sass-embedded": {
39
+ "optional": true
40
+ },
41
+ "less": {
42
+ "optional": true
43
+ },
44
+ "stylus": {
45
+ "optional": true
46
+ },
47
+ "postcss": {
48
+ "optional": true
49
+ }
50
+ }
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { default } from "./module.ts"
2
+ export type { CssCompilers, StyleData } from "./types.ts"
package/src/less.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { resolve } from "node:path"
2
+ import {
3
+ fromImports,
4
+ createMemo,
5
+ dataOf,
6
+ importFromRoot,
7
+ located,
8
+ missingCompiler,
9
+ withData,
10
+ type Compiled,
11
+ type CompilerSetup,
12
+ } from "./shared.ts"
13
+ import { DiagnosticError } from "hamur/kit"
14
+
15
+ export type LessSetup = CompilerSetup
16
+
17
+ interface FileManager {
18
+ supports(filename: string, currentDirectory: string): boolean
19
+ loadFile(filename: string, currentDirectory: string, options: unknown, environment: unknown): Promise<unknown>
20
+ }
21
+
22
+ /** The part of the API of `less` that the module calls. */
23
+ interface LessApi {
24
+ FileManager: new () => FileManager
25
+ render(
26
+ source: string,
27
+ options: { filename: string; paths: string[]; plugins: object[] },
28
+ ): Promise<{ css: string; imports: string[] }>
29
+ }
30
+
31
+ interface LessError {
32
+ message: string
33
+ line: number
34
+ column: number
35
+ filename?: string
36
+ }
37
+
38
+ export const MISSING_LESS = missingCompiler("less")
39
+
40
+ const apiOf = (loaded: unknown): LessApi => {
41
+ const module = loaded as LessApi & { default?: LessApi }
42
+ return typeof module.render === "function" ? module : module.default!
43
+ }
44
+
45
+ const isLessError = (error: unknown): error is LessError =>
46
+ typeof (error as LessError | undefined)?.message === "string" &&
47
+ typeof (error as LessError).line === "number" &&
48
+ typeof (error as LessError).column === "number"
49
+
50
+ /** Less through the app's own `less`, loaded on the first compile; kept and located as Sass's are. */
51
+ export function createLess({ rootDir, options, load = (name) => importFromRoot(name, rootDir) }: LessSetup) {
52
+ let api: Promise<LessApi> | undefined
53
+ const compiler = () =>
54
+ (api ??= (async () => {
55
+ const loaded = await load("less")
56
+ if (!loaded) throw new DiagnosticError("HAMUR_E5409", MISSING_LESS)
57
+ return apiOf(loaded)
58
+ })())
59
+ const paths = (options.loadPaths ?? []).map((path) => resolve(rootDir, path))
60
+ const importsPlugin = {
61
+ install(less: LessApi, plugins: { addFileManager(manager: FileManager): void }) {
62
+ class ImportsFileManager extends less.FileManager {
63
+ override supports(filename: string): boolean {
64
+ return fromImports(rootDir, filename) !== undefined
65
+ }
66
+ override loadFile(filename: string, currentDirectory: string, loadOptions: unknown, environment: unknown) {
67
+ return super.loadFile(fromImports(rootDir, filename) ?? filename, currentDirectory, loadOptions, environment)
68
+ }
69
+ }
70
+ plugins.addFileManager(new ImportsFileManager())
71
+ },
72
+ }
73
+ const memo = createMemo()
74
+
75
+ return {
76
+ /** Compiles `source`, the text of `file` (a `.less` file, or the component a style block is in). */
77
+ async compile(file: string, source: string): Promise<Compiled> {
78
+ const data = await dataOf(options.additionalData, source, file)
79
+ const kept = await memo.get(file, source, data)
80
+ if (kept) return kept
81
+ const less = await compiler()
82
+ let output: { css: string; imports: string[] }
83
+ try {
84
+ output = await less.render(withData(data, source), { filename: file, paths, plugins: [importsPlugin] })
85
+ } catch (error) {
86
+ if (!isLessError(error)) throw error
87
+ const position = { message: error.message, line: error.line, column: error.column + 1, at: error.filename }
88
+ throw await located(rootDir, "less", file, source, data, position, error)
89
+ }
90
+ return memo.set(file, source, data, output.css, output.imports)
91
+ },
92
+ }
93
+ }
94
+
95
+ export type LessCompiler = ReturnType<typeof createLess>
package/src/module.ts ADDED
@@ -0,0 +1,189 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { extname, isAbsolute, relative, resolve, sep } from "node:path"
3
+ import type { BunPlugin } from "bun"
4
+ import { addBunPlugin, addTransform, addWatchFile, defineModule, setStylePreprocessor, useLogger } from "hamur/kit"
5
+ import { createLess, type LessCompiler } from "./less.ts"
6
+ import { createPostcss } from "./postcss.ts"
7
+ import { createSass, type SassCompiler } from "./sass.ts"
8
+ import { createStylus, type StylusCompiler } from "./stylus.ts"
9
+ import type { CssCompilers } from "./types.ts"
10
+ import { DiagnosticError } from "hamur/kit"
11
+
12
+ const COMPILERS = ["sass", "less", "stylus", "postcss"]
13
+ const LANGUAGES = ["sass", "less", "stylus"] as const
14
+
15
+ const shown = (value: unknown): string =>
16
+ typeof value === "function" ? "a function" : (JSON.stringify(value) ?? String(value))
17
+ const isObject = (value: unknown): value is Record<string, unknown> =>
18
+ typeof value === "object" && value !== null && !Array.isArray(value)
19
+
20
+ export function checkOptions(options: CssCompilers): CssCompilers {
21
+ const input = options as Record<string, unknown>
22
+ for (const key of Object.keys(input)) {
23
+ if (!COMPILERS.includes(key))
24
+ throw new DiagnosticError(
25
+ "HAMUR_E5401",
26
+ `cssCompilers.${key} is not a compiler; use sass, less, stylus or postcss`,
27
+ )
28
+ }
29
+ for (const name of LANGUAGES) {
30
+ const given = input[name]
31
+ if (given === undefined) continue
32
+ if (!isObject(given))
33
+ throw new DiagnosticError(
34
+ "HAMUR_E5402",
35
+ `cssCompilers.${name} must be { additionalData?, loadPaths? } (got ${shown(given)})`,
36
+ )
37
+ const { additionalData, loadPaths } = given
38
+ if (additionalData !== undefined && typeof additionalData !== "string" && typeof additionalData !== "function") {
39
+ throw new DiagnosticError(
40
+ "HAMUR_E5403",
41
+ `cssCompilers.${name}.additionalData must be a string or a function (got ${shown(additionalData)})`,
42
+ )
43
+ }
44
+ if (loadPaths !== undefined && (!Array.isArray(loadPaths) || loadPaths.some((path) => typeof path !== "string"))) {
45
+ throw new DiagnosticError(
46
+ "HAMUR_E5404",
47
+ `cssCompilers.${name}.loadPaths must be an array of strings (got ${shown(loadPaths)})`,
48
+ )
49
+ }
50
+ }
51
+ const { postcss } = input
52
+ if (postcss !== undefined && typeof postcss !== "boolean" && !isObject(postcss))
53
+ throw new DiagnosticError(
54
+ "HAMUR_E5405",
55
+ `cssCompilers.postcss must be a boolean or { config?, plugins? } (got ${shown(postcss)})`,
56
+ )
57
+ if (isObject(postcss)) {
58
+ if (postcss.config !== undefined && typeof postcss.config !== "string")
59
+ throw new DiagnosticError(
60
+ "HAMUR_E5406",
61
+ `cssCompilers.postcss.config must be a string (got ${shown(postcss.config)})`,
62
+ )
63
+ if (postcss.plugins !== undefined && !Array.isArray(postcss.plugins))
64
+ throw new DiagnosticError(
65
+ "HAMUR_E5407",
66
+ `cssCompilers.postcss.plugins must be an array (got ${shown(postcss.plugins)})`,
67
+ )
68
+ }
69
+ return options
70
+ }
71
+
72
+ const SCRIPT_IMPORTS = new Set(["import-statement", "dynamic-import", "require-call"])
73
+ const LANGUAGE = "s[ac]ss|less|styl"
74
+ const MAPPED = new RegExp(`\\.(?:${LANGUAGE})(?:\\.module)?\\.css$`)
75
+
76
+ /** The dev client path of a style file: Bun's dev HTML bundler links a stylesheet only when its path ends `.css`, and a CSS module only when it ends `.module.css`. */
77
+ export const cssPath = (file: string): string =>
78
+ `${file}${new RegExp(`\\.module\\.(?:${LANGUAGE})$`).test(file) ? ".module.css" : ".css"}`
79
+ export const stylePath = (path: string): string =>
80
+ new RegExp(`\\.module\\.(?:${LANGUAGE})\\.module\\.css$`).test(path)
81
+ ? path.slice(0, -".module.css".length)
82
+ : MAPPED.test(path)
83
+ ? path.slice(0, -".css".length)
84
+ : path
85
+
86
+ export interface StyleCompilers {
87
+ sass: SassCompiler
88
+ less: LessCompiler
89
+ stylus: StylusCompiler
90
+ }
91
+
92
+ const compile = (compilers: StyleCompilers, file: string, text: string) => {
93
+ switch (extname(file)) {
94
+ case ".less":
95
+ return compilers.less.compile(file, text)
96
+ case ".styl":
97
+ return compilers.stylus.compile(file, text)
98
+ default:
99
+ return compilers.sass.compile(file, text, file.endsWith(".sass") ? "indented" : "scss")
100
+ }
101
+ }
102
+
103
+ const LOCATED = /^[^\s:][^\n]*?:\d+:\d+: /
104
+
105
+ /** A dev-mapped load names the real file, as Bun's prefix of the real path does in a production build; a compiler error already names its own. */
106
+ export function named(error: unknown, file: string, rootDir: string): unknown {
107
+ if (!(error instanceof Error) || LOCATED.test(error.message)) return error
108
+ const path = relative(rootDir, file)
109
+ const shown = path === "" || path.startsWith("..") || isAbsolute(path) ? file : path.split(sep).join("/")
110
+ return Object.assign(new Error(`${shown}: ${error.message}`), { cause: error })
111
+ }
112
+
113
+ /** An import of a Sass, Less or Stylus file: CSS for Bun's CSS bundler in the client builds and in dev, an empty module on the server, as `.css` is there. */
114
+ export function cssPlugin(compilers: StyleCompilers, { rootDir, dev }: { rootDir: string; dev: boolean }): BunPlugin {
115
+ const target = (path: string, resolveDir: string) => {
116
+ try {
117
+ return Bun.resolveSync(path, resolveDir || rootDir)
118
+ } catch {
119
+ return isAbsolute(path) ? path : resolve(resolveDir || rootDir, path)
120
+ }
121
+ }
122
+ return {
123
+ name: "hamur-css",
124
+ setup(build) {
125
+ // A Workers or edge server build has Bun's `browser` target; every Hamur build defines `import.meta.server`.
126
+ const server = build.config?.define?.["import.meta.server"] === "true"
127
+ // A production build keeps the real path, which its errors name.
128
+ if (dev && !server) {
129
+ build.onResolve({ filter: new RegExp(`\\.(?:${LANGUAGE})$`) }, ({ path, resolveDir, kind, namespace }) => {
130
+ if (namespace !== "file" || !SCRIPT_IMPORTS.has(kind)) return undefined
131
+ return { path: cssPath(target(path, resolveDir)), namespace: "file" }
132
+ })
133
+ }
134
+ build.onLoad(
135
+ { filter: new RegExp(`\\.(?:${LANGUAGE})(?:(?:\\.module)?\\.css)?$`), namespace: "file" },
136
+ async ({ path }) => {
137
+ if (server) return { contents: "", loader: "js" }
138
+ const file = stylePath(path)
139
+ try {
140
+ const { code } = await compile(compilers, file, await readFile(file, "utf8"))
141
+ return { contents: code, loader: "css" }
142
+ } catch (error) {
143
+ throw file === path ? error : named(error, file, rootDir)
144
+ }
145
+ },
146
+ )
147
+ },
148
+ }
149
+ }
150
+
151
+ export default defineModule<CssCompilers>({
152
+ meta: { name: "css", configKey: "cssCompilers" },
153
+ setup(input, hamur) {
154
+ const options = checkOptions(input)
155
+ const common = { rootDir: hamur.options.rootDir }
156
+ const compilers = {
157
+ sass: createSass({ ...common, options: options.sass ?? {} }),
158
+ less: createLess({ ...common, options: options.less ?? {} }),
159
+ stylus: createStylus({ ...common, options: options.stylus ?? {} }),
160
+ }
161
+ const postcss = createPostcss({
162
+ rootDir: hamur.options.rootDir,
163
+ srcDirs: [hamur.options.srcDir, ...hamur.options.layers.map((layer) => layer.srcDir)],
164
+ options: options.postcss,
165
+ warn: (message) => useLogger("hamur").warn(message),
166
+ })
167
+ if (postcss.on) {
168
+ if (postcss.config) addWatchFile(postcss.config)
169
+ addTransform({
170
+ name: "@hamur/css:postcss",
171
+ filter: { id: /\.(css|scss|sass|less|styl)$|^hamur-(vue|svelte)-style:/ },
172
+ target: "client",
173
+ enforce: "pre",
174
+ async transform(code, { id, loader }) {
175
+ if (loader !== "css" || !postcss.sees(id)) return undefined
176
+ return postcss.process(code, id)
177
+ },
178
+ })
179
+ }
180
+ addBunPlugin(cssPlugin(compilers, { ...common, dev: hamur.options.dev }), { client: true, server: true })
181
+ setStylePreprocessor(async ({ lang, code, file }) => {
182
+ if (lang === "scss" || lang === "sass")
183
+ return compilers.sass.compile(file, code, lang === "sass" ? "indented" : "scss")
184
+ if (lang === "less") return compilers.less.compile(file, code)
185
+ if (lang === "styl" || lang === "stylus") return compilers.stylus.compile(file, code)
186
+ throw new Error(`@hamur/css compiles scss, sass, less, styl and stylus style blocks (got lang "${lang}")`)
187
+ })
188
+ },
189
+ })
package/src/postcss.ts ADDED
@@ -0,0 +1,163 @@
1
+ import { existsSync, realpathSync } from "node:fs"
2
+ import { isAbsolute, join, resolve, sep } from "node:path"
3
+ import { pathToFileURL } from "node:url"
4
+ import { frame, importFromRoot, lines, missingCompiler, shownPath } from "./shared.ts"
5
+ import { DiagnosticError, diagnostic } from "hamur/kit"
6
+
7
+ export const MISSING_POSTCSS = missingCompiler("postcss")
8
+ export const NO_PLUGINS =
9
+ "cssCompilers.postcss is on and has no plugins: add postcss.config.mjs or cssCompilers.postcss.plugins"
10
+ export const notNeeded = (name: string): string =>
11
+ `postcss plugin "${name}" is not needed: Bun's CSS bundler already prefixes`
12
+
13
+ const CONFIG_FILES = ["postcss.config.js", "postcss.config.mjs", "postcss.config.ts"]
14
+ const COVERED = new Set(["autoprefixer", "postcss-nesting", "postcss-preset-env", "postcss-import"])
15
+ const STYLE_ID = /^hamur-(?:vue|svelte)-style:/
16
+
17
+ /** Bun reports a file by its real path (`/private/tmp/…` for `/tmp/…` on macOS), so a directory matches under both spellings. */
18
+ function withRealPaths(dirs: string[]): string[] {
19
+ return [
20
+ ...new Set(
21
+ dirs.flatMap((dir) => {
22
+ try {
23
+ return [dir, realpathSync(dir)]
24
+ } catch {
25
+ return [dir]
26
+ }
27
+ }),
28
+ ),
29
+ ]
30
+ }
31
+
32
+ export interface PostcssSetup {
33
+ rootDir: string
34
+ srcDirs: string[]
35
+ /** `cssCompilers.postcss`; `undefined` turns the pass on when `rootDir` has a config file. */
36
+ options: boolean | { config?: string; plugins?: unknown[] } | undefined
37
+ /** Imports a package from the app root, `undefined` when it is not installed. */
38
+ load?: (name: string) => Promise<unknown>
39
+ warn: (message: string) => void
40
+ }
41
+
42
+ interface PostcssApi {
43
+ (plugins: unknown[]): { process(css: string, options: { from: string; map: false }): Promise<{ css: string }> }
44
+ }
45
+
46
+ interface PostcssError {
47
+ name: string
48
+ reason: string
49
+ line?: number
50
+ column?: number
51
+ }
52
+
53
+ const isPostcssError = (error: unknown): error is PostcssError =>
54
+ (error as PostcssError | undefined)?.name === "CssSyntaxError" && typeof (error as PostcssError).reason === "string"
55
+
56
+ const pluginName = (plugin: unknown): string | undefined => {
57
+ const named = plugin as { postcssPlugin?: unknown; name?: unknown } | null
58
+ const name = named?.postcssPlugin ?? (typeof plugin === "function" ? named?.name : undefined)
59
+ return typeof name === "string" && name ? name : undefined
60
+ }
61
+
62
+ /** The config file the pass reads: `cssCompilers.postcss.config`, else the first `postcss.config.{js,mjs,ts}` of `rootDir`. */
63
+ export function configFile(rootDir: string, options: PostcssSetup["options"]): string | undefined {
64
+ if (options === false) return undefined
65
+ if (typeof options === "object" && options.config !== undefined) return resolve(rootDir, options.config)
66
+ return CONFIG_FILES.map((name) => join(rootDir, name)).find(existsSync)
67
+ }
68
+
69
+ /** PostCSS through the app's own `postcss`, loaded on the first style. */
70
+ export function createPostcss({
71
+ rootDir,
72
+ srcDirs,
73
+ options,
74
+ load = (name) => importFromRoot(name, rootDir),
75
+ warn,
76
+ }: PostcssSetup) {
77
+ const config = configFile(rootDir, options)
78
+ const given = typeof options === "object" ? options.plugins : undefined
79
+ const on = options !== false && (options !== undefined || config !== undefined)
80
+ const seen = withRealPaths(srcDirs)
81
+ if (on && config && !given && !existsSync(config))
82
+ throw new DiagnosticError("HAMUR_E5408", "cannot find the PostCSS config file", { at: shownPath(rootDir, config) })
83
+ if (on && (config || given?.length)) {
84
+ try {
85
+ Bun.resolveSync("postcss", rootDir)
86
+ } catch {
87
+ throw new DiagnosticError(
88
+ "HAMUR_E5409",
89
+ MISSING_POSTCSS,
90
+ config && !given ? { at: shownPath(rootDir, config) } : undefined,
91
+ )
92
+ }
93
+ }
94
+
95
+ let ready: Promise<{ run: PostcssApi; plugins: unknown[] } | undefined> | undefined
96
+ const pluginsOf = async (): Promise<unknown[]> => {
97
+ if (given) return given
98
+ if (!config) return []
99
+ const exported = ((await import(pathToFileURL(config).href)) as { default?: unknown }).default
100
+ const resolved =
101
+ typeof exported === "function"
102
+ ? await (exported as (context: object) => unknown)({ env: process.env.NODE_ENV ?? "development" })
103
+ : exported
104
+ const plugins = (resolved as { plugins?: unknown } | null | undefined)?.plugins
105
+ if (Array.isArray(plugins)) return plugins
106
+ if (!plugins || typeof plugins !== "object") return []
107
+ const list: unknown[] = []
108
+ for (const [name, settings] of Object.entries(plugins)) {
109
+ if (settings === false) continue
110
+ const loaded = (await load(name)) as { default?: unknown } | undefined
111
+ if (!loaded)
112
+ throw new DiagnosticError("HAMUR_E5410", `plugin "${name}" is not installed in the app`, {
113
+ at: shownPath(rootDir, config),
114
+ })
115
+ const factory = (loaded.default ?? loaded) as (settings: unknown) => unknown
116
+ list.push(typeof factory === "function" ? factory(settings === true ? undefined : settings) : factory)
117
+ }
118
+ return list
119
+ }
120
+ const prepare = () =>
121
+ (ready ??= (async () => {
122
+ const plugins = await pluginsOf()
123
+ if (!plugins.length) {
124
+ warn(diagnostic("HAMUR_W5411", NO_PLUGINS))
125
+ return undefined
126
+ }
127
+ for (const name of new Set(plugins.map(pluginName)))
128
+ if (name && COVERED.has(name)) warn(diagnostic("HAMUR_W5412", notNeeded(name)))
129
+ const loaded = (await load("postcss")) as { default?: PostcssApi } | undefined
130
+ if (!loaded?.default) throw new DiagnosticError("HAMUR_E5409", MISSING_POSTCSS)
131
+ return { run: loaded.default, plugins }
132
+ })())
133
+
134
+ return {
135
+ on,
136
+ config: given ? undefined : config,
137
+ /** Whether the pass runs on the module `id`: an app or layer source file, not a dependency. */
138
+ sees(id: string): boolean {
139
+ const path = id.replace(STYLE_ID, "")
140
+ if (!isAbsolute(path) || path.includes(`${sep}node_modules${sep}`) || path.includes("/node_modules/"))
141
+ return false
142
+ return seen.some((dir) => path.startsWith(dir.endsWith(sep) ? dir : dir + sep))
143
+ },
144
+ /** `undefined` when the app has no plugins to run. */
145
+ async process(code: string, id: string): Promise<string | undefined> {
146
+ const setup = await prepare()
147
+ if (!setup) return undefined
148
+ const file = id.replace(STYLE_ID, "")
149
+ try {
150
+ return (await setup.run(setup.plugins).process(code, { from: file, map: false })).css
151
+ } catch (error) {
152
+ if (!isPostcssError(error) || error.line === undefined) throw error
153
+ const column = error.column ?? 1
154
+ throw new Error(
155
+ frame(shownPath(rootDir, file), error.line, column, error.reason, lines(code)[error.line - 1]),
156
+ { cause: error },
157
+ )
158
+ }
159
+ },
160
+ }
161
+ }
162
+
163
+ export type PostcssPass = ReturnType<typeof createPostcss>