postcss-verify-variables 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ # The MIT License (MIT)
2
+
3
+ Permission is hereby granted, free of charge, to any person
4
+ obtaining a copy of this software and associated documentation
5
+ files (the “Software”), to deal in the Software without
6
+ restriction, including without limitation the rights to use,
7
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the
9
+ Software is furnished to do so, subject to the following
10
+ conditions:
11
+
12
+ The above copyright notice and this permission notice shall be
13
+ included in all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
16
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,87 @@
1
1
  # postcss-verify-variables
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ A PostCSS plugin that detects missing or misspelled CSS custom property references during a build.
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ ## Installation
6
6
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
7
+ Install the plugin and PostCSS in your project:
8
8
 
9
- ## Purpose
9
+ ```sh
10
+ npm install --save-dev postcss-verify-variables postcss
11
+ ```
10
12
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `postcss-verify-variables`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
13
+ ## Usage
15
14
 
16
- ## What is OIDC Trusted Publishing?
15
+ Add the plugin to a PostCSS pipeline:
17
16
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
17
+ ```js
18
+ import postcss from "postcss";
19
+ import { verifyVars } from "postcss-verify-variables";
19
20
 
20
- ## Setup Instructions
21
+ const css = `
22
+ :root {
23
+ --brand-color: #005ea8;
24
+ }
21
25
 
22
- To properly configure OIDC trusted publishing for this package:
26
+ .button {
27
+ color: var(--brand-color);
28
+ }
29
+ `;
23
30
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
31
+ const result = await postcss([verifyVars()]).process(css, {
32
+ from: "src/styles.css",
33
+ });
28
34
 
29
- ## DO NOT USE THIS PACKAGE
35
+ console.log(result.css);
36
+ ```
30
37
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
38
+ An undefined reference causes PostCSS processing to fail with an error identifying the variable and declaration. For example, `color: var(--missing)` fails unless `--missing` is declared or ignored.
36
39
 
37
- ## More Information
40
+ ### Vite
38
41
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
+ Vite runs PostCSS on CSS modules separately, so the PostCSS plugin may report variables declared in another module as missing. Use the Vite plugin to check the combined CSS output instead. For Vite, add it to your configuration:
42
43
 
43
- ---
44
+ ```js
45
+ import { defineConfig } from "vite";
46
+ import { verifyVarsVite } from "postcss-verify-variables/vite";
44
47
 
45
- **Maintained for OIDC setup purposes only**
48
+ export default defineConfig({
49
+ plugins: [verifyVarsVite()],
50
+ });
51
+ ```
52
+
53
+ ## What is checked
54
+
55
+ The plugin checks `var(--name)` references in declaration values against custom properties declared anywhere in the processed PostCSS root or in the [`global`](#global-compiled-css) option. Variables listed in [`ignore`](#ignoring-variables) are also allowed.
56
+
57
+ This is a presence check, not a cascade or scope analysis. A declaration counts regardless of its selector or position, even if it would not apply to the element using the variable.
58
+
59
+ References in fallbacks are checked too. For example, `var(--primary, var(--fallback))` requires both variables to be declared or ignored, even if `--primary` is declared.
60
+
61
+ References are detected with a regular expression, not a CSS value parser. It recognizes ASCII letters, digits, underscores, and hyphens in names; escaped or non-ASCII names may be missed or matched only partially. Text resembling a reference inside a string may also be checked.
62
+
63
+ To check variables across files, place this plugin after plugins that import or combine CSS into the same PostCSS root.
64
+
65
+ ## Ignoring variables
66
+
67
+ Use `ignore` for variables supplied at runtime or by CSS outside the processed root. Provide exact names, including the `--` prefix:
68
+
69
+ ```diff
70
+ verifyVars({
71
+ + ignore: ["--runtime-color", "--host-theme"],
72
+ })
73
+ ```
74
+
75
+ `ignore` is optional and defaults to an empty list.
76
+
77
+ ## Global compiled CSS
78
+
79
+ Use `global` to provide compiled CSS whose variables will be available in the final build:
80
+
81
+ ```diff
82
+ verifyVars({
83
+ + global: ":root { --runtime-color: black; --host-theme: white; }",
84
+ }),
85
+ ```
86
+
87
+ `global` is optional and defaults to an empty string. It must contain valid CSS. Its custom property declarations count as defined, but text in comments or strings does not. References inside `global` itself are not checked.
@@ -0,0 +1,2 @@
1
+ import { n as verifyVars } from "./verify-vars-CDU6o_xB.mjs";
2
+ export { verifyVars };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ export { n as verifyVars } from "./verify-vars-Dngt_e-5.mjs";
@@ -0,0 +1,27 @@
1
+ import { Plugin } from "postcss";
2
+ /**
3
+ * Configuration options for postcss-verify-variables-vars.
4
+ */
5
+ interface VerifyOptions {
6
+ /**
7
+ * Variable names that are allowed without being defined in the processed CSS.
8
+ * Specify each name exactly, including the `--` prefix.
9
+ *
10
+ * @defaultValue `[]`
11
+ */
12
+ ignore?: string[];
13
+ /**
14
+ * Already compiled global CSS containing variables that are provided at the
15
+ * final build stage. Variables declared in this string are allowed in the
16
+ * processed CSS even if they are not declared in the PostCSS root.
17
+ * The string must be valid CSS.
18
+ *
19
+ * @defaultValue `""`
20
+ */
21
+ global?: string;
22
+ }
23
+ declare function verifyVars(opts?: VerifyOptions): Plugin;
24
+ declare namespace verifyVars {
25
+ var postcss: boolean;
26
+ }
27
+ export { verifyVars as n, VerifyOptions as t };
@@ -0,0 +1,35 @@
1
+ import { parse } from "postcss";
2
+ // src/verify-vars.ts
3
+ const VERIFY_VARS_PLUGIN_NAME = "postcss-verify-variables-vars";
4
+ function collectDefinedVars(root, definedVars) {
5
+ root.walkDecls((decl) => {
6
+ if (decl.prop.startsWith("--")) definedVars.add(decl.prop);
7
+ });
8
+ }
9
+ function verifyVars(opts = {}) {
10
+ const ignore = new Set(opts.ignore || []);
11
+ const globalDefinedVars = /* @__PURE__ */ new Set();
12
+ if (opts.global !== void 0) collectDefinedVars(parse(opts.global, { from: void 0 }), globalDefinedVars);
13
+ return {
14
+ postcssPlugin: VERIFY_VARS_PLUGIN_NAME,
15
+ Once(root) {
16
+ const definedVars = new Set(globalDefinedVars);
17
+ collectDefinedVars(root, definedVars);
18
+ root.walkDecls((decl) => {
19
+ if (!decl.value.toLowerCase().includes("var(")) return;
20
+ const matches = decl.value.matchAll(/var\(\s*(--[\w-]+)/gi);
21
+ for (const match of matches) {
22
+ const varName = match[1];
23
+ if (!definedVars.has(varName) && !ignore.has(varName)) throw decl.error([
24
+ `CSS variable "${varName}" referenced in "${decl.prop}" could not be verified.`,
25
+ "It is not declared in the processed CSS or \"global\" and is not listed in \"ignore\".",
26
+ "Declare the variable in the processed CSS.",
27
+ "If it is defined elsewhere, provide its CSS via \"global\" or add its name to \"ignore\"."
28
+ ].join("\n"), { word: varName });
29
+ }
30
+ });
31
+ }
32
+ };
33
+ }
34
+ verifyVars.postcss = true;
35
+ export { verifyVars as n, VERIFY_VARS_PLUGIN_NAME as t };
@@ -0,0 +1,6 @@
1
+ import { t as VerifyOptions } from "./verify-vars-CDU6o_xB.mjs";
2
+ import { Plugin } from "vite";
3
+ /**
4
+ * Verify all generated Vite CSS assets together.
5
+ */
6
+ export declare function verifyVarsVite(options?: VerifyOptions): Plugin[];
package/dist/vite.mjs ADDED
@@ -0,0 +1,174 @@
1
+ import { n as verifyVars } from "./verify-vars-Dngt_e-5.mjs";
2
+ import postcss, { CssSyntaxError, parse, root } from "postcss";
3
+ import { normalizePath } from "vite";
4
+ // src/vite/verify-styles.ts
5
+ /**
6
+ * Verify stylesheets together as one root. Each stylesheet is parsed with its
7
+ * own file name so that errors point at the right file, line and column.
8
+ */
9
+ async function verifyStyles(processor, sources) {
10
+ const root$1 = root();
11
+ for (const [file, code] of sources) root$1.append(parse(code, { from: file }).nodes);
12
+ await processor.process(root$1, { from: void 0 });
13
+ }
14
+ // src/vite/dev.ts
15
+ const STYLE_FILE = /\.(?:css|pcss|postcss|sass|scss|less|styl|stylus)$/i;
16
+ const PREPROCESSED_FILE = /\.(?:sass|scss|less|styl|stylus)$/i;
17
+ const NON_CSS_QUERY = /[?&](?:worker|sharedworker|raw|url)\b/;
18
+ const VERIFICATION_DELAY_MS = 75;
19
+ function toError(error) {
20
+ return error instanceof Error ? error : new Error(String(error));
21
+ }
22
+ function createErrorPayload(error) {
23
+ const syntaxError = error instanceof CssSyntaxError ? error : void 0;
24
+ const location = syntaxError?.file !== void 0 && syntaxError.line !== void 0 ? {
25
+ file: syntaxError.file,
26
+ line: syntaxError.line,
27
+ column: syntaxError.column ?? 1
28
+ } : void 0;
29
+ const preprocessed = location?.file !== void 0 && PREPROCESSED_FILE.test(location.file);
30
+ let message = error.message;
31
+ if (syntaxError && location) {
32
+ const position = `${location.line}:${location.column}`;
33
+ message = `${preprocessed ? `${location.file} (processed CSS:${position})` : `${location.file}:${position}`}: ${syntaxError.reason}`;
34
+ }
35
+ return {
36
+ type: "error",
37
+ err: {
38
+ message,
39
+ stack: "",
40
+ plugin: "verify-variables:development",
41
+ id: location?.file,
42
+ loc: preprocessed ? void 0 : location
43
+ }
44
+ };
45
+ }
46
+ function createStyleVerifier(server, options) {
47
+ let processor;
48
+ try {
49
+ processor = postcss([verifyVars(options)]);
50
+ } catch (error) {
51
+ server.config.logger.warn(toError(error).message);
52
+ return;
53
+ }
54
+ const styles = /* @__PURE__ */ new Map();
55
+ let timer;
56
+ let activeError;
57
+ function clearActiveError() {
58
+ if (!activeError) return;
59
+ activeError = void 0;
60
+ if (server.ws.clients.size > 0) server.ws.send({ type: "full-reload" });
61
+ }
62
+ async function verifyLoadedStyles() {
63
+ timer = void 0;
64
+ if (styles.size === 0) {
65
+ clearActiveError();
66
+ return;
67
+ }
68
+ try {
69
+ await verifyStyles(processor, styles);
70
+ clearActiveError();
71
+ } catch (error) {
72
+ const payload = createErrorPayload(toError(error));
73
+ if (payload.err.message === activeError?.err.message) return;
74
+ server.config.logger.warn(payload.err.message);
75
+ activeError = payload;
76
+ if (server.ws.clients.size > 0) server.ws.send(payload);
77
+ }
78
+ }
79
+ function schedule() {
80
+ clearTimeout(timer);
81
+ timer = setTimeout(() => {
82
+ verifyLoadedStyles();
83
+ }, VERIFICATION_DELAY_MS);
84
+ }
85
+ server.ws.on("vite:client:connect", (_data, client) => {
86
+ if (activeError) client.send(activeError);
87
+ });
88
+ return {
89
+ update(id, code) {
90
+ if (styles.get(id) === code) return;
91
+ styles.set(id, code);
92
+ schedule();
93
+ },
94
+ remove(matches) {
95
+ const removed = styles.keys().filter(matches).toArray();
96
+ for (const id of removed) styles.delete(id);
97
+ if (removed.length > 0) schedule();
98
+ },
99
+ dispose() {
100
+ clearTimeout(timer);
101
+ }
102
+ };
103
+ }
104
+ function verifyDevelopment(options) {
105
+ let verifier;
106
+ return {
107
+ name: "verify-variables:development",
108
+ apply: "serve",
109
+ configureServer(server) {
110
+ const current = createStyleVerifier(server, options);
111
+ if (!current) return;
112
+ verifier = current;
113
+ server.watcher.on("unlink", (file) => {
114
+ const normalized = normalizePath(file);
115
+ current.remove((id) => id === normalized);
116
+ });
117
+ server.watcher.on("unlinkDir", (directory) => {
118
+ const normalized = normalizePath(directory);
119
+ current.remove((id) => id.startsWith(`${normalized}/`));
120
+ });
121
+ server.httpServer?.once("close", () => {
122
+ current.dispose();
123
+ verifier = void 0;
124
+ });
125
+ },
126
+ transform(code, id) {
127
+ const cssId = normalizePath(id.split("?", 1)[0]);
128
+ if (!STYLE_FILE.test(cssId) || NON_CSS_QUERY.test(id)) return;
129
+ verifier?.update(cssId, code);
130
+ }
131
+ };
132
+ }
133
+ // src/vite/output.ts
134
+ const decoder = new TextDecoder();
135
+ function isCssAsset(chunk) {
136
+ return chunk.type === "asset" && chunk.fileName.endsWith(".css");
137
+ }
138
+ function readSource(asset) {
139
+ return typeof asset.source === "string" ? asset.source : decoder.decode(asset.source);
140
+ }
141
+ function verifyOutput(options) {
142
+ return {
143
+ name: "verify-variables:output",
144
+ apply: "build",
145
+ enforce: "post",
146
+ configResolved(config) {
147
+ const output = config.build.rolldownOptions.output;
148
+ if (Array.isArray(output) && output.length > 1) throw new Error("verifyVarsVite does not support builds with multiple output configurations.");
149
+ },
150
+ generateBundle: {
151
+ order: "post",
152
+ async handler(_outputOptions, bundle) {
153
+ const sources = Object.values(bundle).filter(isCssAsset).map((asset) => [asset.fileName, readSource(asset)]);
154
+ try {
155
+ await verifyStyles(postcss([verifyVars(options)]), sources);
156
+ } catch (error) {
157
+ if (!(error instanceof CssSyntaxError) || error.plugin !== "postcss-verify-variables-vars") throw error;
158
+ this.error({
159
+ message: error.message,
160
+ stack: ""
161
+ });
162
+ }
163
+ }
164
+ }
165
+ };
166
+ }
167
+ // src/vite.ts
168
+ /**
169
+ * Verify all generated Vite CSS assets together.
170
+ */
171
+ function verifyVarsVite(options = {}) {
172
+ return [verifyOutput(options), verifyDevelopment(options)];
173
+ }
174
+ export { verifyVarsVite };
package/package.json CHANGED
@@ -1,10 +1,93 @@
1
1
  {
2
2
  "name": "postcss-verify-variables",
3
- "version": "0.0.0",
4
- "description": "OIDC trusted publishing setup package for postcss-verify-variables",
3
+ "version": "1.0.0",
4
+ "description": "Verify CSS custom property references with PostCSS",
5
5
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
6
+ "Utility"
7
+ ],
8
+ "homepage": "https://github.com/OlofFredriksson/postcss-verify-variables",
9
+ "bugs": "https://github.com/OlofFredriksson/postcss-verify-variables/issues",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/OlofFredriksson/postcss-verify-variables.git"
13
+ },
14
+ "license": "MIT",
15
+ "author": "Olof",
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.mts",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./vite": {
23
+ "types": "./dist/vite.d.mts",
24
+ "default": "./dist/vite.mjs"
25
+ }
26
+ },
27
+ "types": "./dist/index.d.mts",
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "workspaces": [
32
+ "vite-sandbox"
33
+ ],
34
+ "scripts": {
35
+ "build": "npm run build:plugin && npm run build --workspace vite-sandbox",
36
+ "prebuild:plugin": "tsc",
37
+ "build:plugin": "node build.mjs",
38
+ "eslint": "eslint --cache .",
39
+ "eslint:fix": "eslint --fix .",
40
+ "integration-test": "vitest run --mode integration",
41
+ "lint": "npm run eslint && npm run prettier:check",
42
+ "lint:fix": "npm run eslint:fix && npm run prettier:write",
43
+ "prepare": "commitlint-config",
44
+ "prettier:check": "prettier --check .",
45
+ "prettier:write": "prettier --write .",
46
+ "pretest": "npm run lint",
47
+ "test": "vitest run"
48
+ },
49
+ "allowScripts": {
50
+ "@parcel/watcher": false,
51
+ "cypress": false,
52
+ "puppeteer": true,
53
+ "unrs-resolver": true
54
+ },
55
+ "commitlint": {
56
+ "extends": "@forsakringskassan/commitlint-config/no-jira"
57
+ },
58
+ "prettier": "@forsakringskassan/prettier-config",
59
+ "release": {
60
+ "extends": "@forsakringskassan/semantic-release-config"
61
+ },
62
+ "devDependencies": {
63
+ "@forsakringskassan/commitlint-config": "4.2.8",
64
+ "@forsakringskassan/eslint-config": "15.14.0",
65
+ "@forsakringskassan/eslint-config-typescript": "15.14.0",
66
+ "@forsakringskassan/eslint-config-vue": "15.14.0",
67
+ "@forsakringskassan/prettier-config": "3.7.15",
68
+ "@tsconfig/node22": "22.0.7",
69
+ "@types/node": "22.20.6",
70
+ "@typescript/native": "npm:typescript@7.0.2",
71
+ "npm-pkg-lint": "5.5.0",
72
+ "postcss": "^8.5.33",
73
+ "puppeteer": "25.18.1",
74
+ "sass": "1.108.2",
75
+ "tsdown": "0.23.7",
76
+ "typescript": "npm:@typescript/typescript6@6.0.2",
77
+ "vite": "8.3.8",
78
+ "vitest": "5.1.1"
79
+ },
80
+ "peerDependencies": {
81
+ "postcss": "^8.5.0",
82
+ "vite": "^8.0.0"
83
+ },
84
+ "peerDependenciesMeta": {
85
+ "vite": {
86
+ "optional": true
87
+ }
88
+ },
89
+ "engines": {
90
+ "node": "^22.16 || >= 24.15",
91
+ "npm": ">=11.0.0"
92
+ }
10
93
  }