@eightshift/frontend-libs-tailwind 3.4.0 → 3.5.1

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.
@@ -1 +1 @@
1
- @infinum/wordpress-team
1
+ * @infinum/wordpress-team
package/CHANGELOG.md CHANGED
@@ -6,6 +6,28 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
6
6
 
7
7
  ---
8
8
 
9
+ ## [3.5.1]
10
+
11
+ ### Fixed
12
+
13
+ - Fixed stylelint false positives on Tailwind `@apply`: `at-rule-prelude-no-invalid` now ignores `@apply`, as the CSS Mixins spec `@apply` syntax only accepts dashed idents.
14
+ - Fixed stylelint false positives on `&` inside `@utility` and `@custom-variant` (`nesting-selector-no-missing-scoping-root`).
15
+ - Fixed stylelint false positives on declarations in at-rules nested inside `@utility`, such as `@supports` (`no-invalid-position-declaration`).
16
+
17
+ ### Updated
18
+
19
+ - Updated dependencies (`@wordpress/dependency-extraction-webpack-plugin` 7, `@wordpress/api-fetch` 8, `stylelint`, `eslint`, `oxlint`, `webpack`, `webpack-cli`, `@swc/core`, `eslint-plugin-better-tailwindcss`, `prettier`, `lint-staged`).
20
+ - `@wordpress/dependency-extraction-webpack-plugin` 7 requires Node.js 22.13 or newer.
21
+
22
+ ## [3.5.0]
23
+
24
+ ### Added
25
+
26
+ - `tw-sweep` CLI (`bunx tw-sweep`, also `lint:tw`): checks Tailwind classes in block manifests and PHP against the project's Tailwind entry and reports unknown and non-canonical classes. `--write` rewrites non-canonical ones. PHP sources: `class="…"` attributes, string arguments of `tailwindClasses`/`getTwPart` (after the part name), `getTwClasses`, `clsx` and `classnames`, and non-key string literals between `// tw-sweep-classes-start.` and `// tw-sweep-classes-end.` (the full stop keeps PHPCS happy; the markers match without it too).
27
+ - `linters/oxlint.config.mjs`: `createOxlintConfig({ entryPoint })` for oxlint with `eslint-plugin-better-tailwindcss`.
28
+ - `tw-ignore.json`: one unknown-class ignore list (JSON array of regex strings) read by both `tw-sweep` and `createOxlintConfig`. Invalid patterns fail loudly.
29
+ - lint-staged does not run commands through a shell, so chain tools as an array: `"*.js": ["bun lintJs", "bun lintJs:oxlint"]`.
30
+
9
31
  ## [3.4.0]
10
32
 
11
33
  ### Added
@@ -383,7 +405,8 @@ Co-authored with @piqusy
383
405
 
384
406
  - Initial release.
385
407
 
386
- [Unreleased]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/master...HEAD
408
+ [3.5.1]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.5.0...3.5.1
409
+ [3.5.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.5.0
387
410
  [3.4.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.4.0
388
411
  [3.3.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.2.0...3.3.0
389
412
  [3.2.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.1.2...3.2.0
package/README.md CHANGED
@@ -12,6 +12,51 @@ This library is meant to bring you the modern front-end development tools to the
12
12
  ## Documentation
13
13
  **For the full documentation please check this [link](https://eightshift.com).**
14
14
 
15
+ ## Tailwind class linting
16
+
17
+ Two tools check classes against your project's own Tailwind entry: oxlint for JS, and `tw-sweep` for block manifests and PHP. Both read one ignore list.
18
+
19
+ 1. Add `oxlint` to your project's `devDependencies`. Isolated installs (pnpm, `bun --linker isolated`) do not expose this package's binaries.
20
+ 2. Create `oxlint.config.ts`:
21
+
22
+ ```ts
23
+ import { defineConfig } from 'oxlint';
24
+ import { createOxlintConfig } from '@eightshift/frontend-libs-tailwind/linters/oxlint.config.mjs';
25
+
26
+ export default defineConfig(createOxlintConfig({ entryPoint: 'tailwind.css' }));
27
+ ```
28
+
29
+ 3. Create `tw-ignore.json` for classes that are not Tailwind utilities (JS hooks, BEM selectors, other design-system prefixes). It is a JSON array of regex strings; an invalid pattern stops both tools:
30
+
31
+ ```json
32
+ ["^es:", "^js-", "^my-block__"]
33
+ ```
34
+
35
+ 4. Wire the scripts. lint-staged does not run commands through a shell, so use an array instead of `&&`:
36
+
37
+ ```json
38
+ "scripts": {
39
+ "lintJs:oxlint": "oxlint",
40
+ "lintTw": "tw-sweep",
41
+ "test": "bun run lintJs && bun run lintJs:oxlint && bun run lintTw"
42
+ },
43
+ "lint-staged": {
44
+ "*.js": ["bun lintJs", "bun lintJs:oxlint"],
45
+ "src/Blocks/**/manifest.json": "tw-sweep",
46
+ "src/**/*.php": "tw-sweep"
47
+ }
48
+ ```
49
+
50
+ `tw-sweep` reports unknown and non-canonical classes; `tw-sweep --write` rewrites the non-canonical ones. In PHP it reads static `class="…"` attributes and the string arguments of `tailwindClasses`, `getTwPart`, `getTwClasses`, `clsx` and `classnames`. For class maps that no helper wraps, such as selectors returned from a filter, mark the code:
51
+
52
+ ```php
53
+ // tw-sweep-classes-start.
54
+ $selectors['field']['parts']['label'] = ['flex items-center text-body-sm'];
55
+ // tw-sweep-classes-end.
56
+ ```
57
+
58
+ Every string literal between the markers that is not an array key is checked. Run `tw-sweep --help` for all flags.
59
+
15
60
  ## Who do I talk to?
16
61
 
17
62
  If you have any questions or problems, please [open an issue](https://github.com/infinum/eightshift-frontend-libs/issues) on GitHub and we will do our best to give you a timely answer.
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+ // bin/tw-sweep.mjs
3
+ // Project-wide Tailwind class check for sources oxlint cannot read:
4
+ // block manifests and PHP. Reports classes the design system does not know
5
+ // (unknown) and classes with a canonical spelling (non-canonical), using
6
+ // @tailwindcss/node against the project's own Tailwind entry.
7
+
8
+ import { readFile, writeFile } from 'node:fs/promises';
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
10
+ import { resolve, relative } from 'node:path';
11
+ import process from 'node:process';
12
+ import { glob } from 'glob';
13
+ import { __unstable__loadDesignSystem } from '@tailwindcss/node';
14
+ import { extractGroups, REGION_START, REGION_END } from '../linters/tw-sweep-extract.mjs';
15
+ import { loadTwIgnore, TW_IGNORE_FILE } from '../linters/tw-ignore.mjs';
16
+
17
+ const EXIT_OK = 0;
18
+ const EXIT_VIOLATIONS = 1;
19
+ const EXIT_USAGE = 2;
20
+
21
+ function parseArgs(argv) {
22
+ const opts = {
23
+ files: [],
24
+ include: null,
25
+ exclude: null,
26
+ entry: null,
27
+ ignoreFile: TW_IGNORE_FILE,
28
+ unknown: true,
29
+ write: false,
30
+ rootFontSize: 16,
31
+ help: false,
32
+ };
33
+
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const a = argv[i];
36
+
37
+ if (a === '--entry') opts.entry = argv[++i];
38
+ else if (a === '--include') opts.include = argv[++i].split(',').map((s) => s.trim());
39
+ else if (a === '--exclude') opts.exclude = argv[++i].split(',').map((s) => s.trim());
40
+ else if (a === '--ignore-file') opts.ignoreFile = argv[++i];
41
+ else if (a === '--no-unknown') opts.unknown = false;
42
+ else if (a === '--root-font-size') opts.rootFontSize = Number(argv[++i]);
43
+ else if (a === '--write') opts.write = true;
44
+ else if (a === '--check') opts.write = false;
45
+ else if (a === '-h' || a === '--help') opts.help = true;
46
+ else if (a.startsWith('--')) {
47
+ console.error(`Unknown flag: ${a}`);
48
+ process.exit(EXIT_USAGE);
49
+ } else {
50
+ opts.files.push(a);
51
+ }
52
+ }
53
+
54
+ return opts;
55
+ }
56
+
57
+ function printHelp() {
58
+ console.log(`tw-sweep — find unknown and non-canonical Tailwind classes in manifests and PHP
59
+
60
+ Usage:
61
+ tw-sweep [flags] [file...]
62
+
63
+ Flags:
64
+ --entry <path> Tailwind CSS entry. Default: the first ./tailwind.css, tailwind-frontend.css
65
+ or tailwind-editor.css that imports 'tailwindcss', searched upward,
66
+ then wp-content/themes/*. Files without that import are skipped.
67
+ --include <glob,...> Globs to scan (default: src/Blocks/**/manifest.json, src/**/*.php).
68
+ --exclude <glob,...> Extra globs to skip (always skipped: public, node_modules, vendor*).
69
+ --ignore-file <path> Unknown-class ignore list, a JSON array of regex strings
70
+ (default: ./${TW_IGNORE_FILE}; shared with the oxlint config).
71
+ --no-unknown Only report non-canonical classes.
72
+ --root-font-size <px> For canonicalization (default: 16).
73
+ --write Rewrite non-canonical classes in place. Unknown classes are
74
+ only reported.
75
+ --check Report only (default).
76
+ -h, --help This help.
77
+
78
+ Sources: manifest twClasses* strings; PHP class="…" attributes; string arguments of
79
+ tailwindClasses/getTwPart (after the part name), getTwClasses, clsx and classnames;
80
+ and every non-key string literal between // ${REGION_START}. and // ${REGION_END}.
81
+ Values that contain PHP, $ interpolation or % placeholders are skipped.
82
+
83
+ Exit codes: 0 clean, 1 violations, 2 usage error.
84
+ `);
85
+ }
86
+
87
+ // A usable entry imports Tailwind itself. Projects often keep theme tokens in a
88
+ // tailwind.css that the real (prefixed) entry imports; using that file would
89
+ // report every class as unknown.
90
+ function importsTailwind(path) {
91
+ return existsSync(path) && /@import\s+(['"])tailwindcss\1/.test(readFileSync(path, 'utf8'));
92
+ }
93
+
94
+ function findDefaultEntry(cwd) {
95
+ const candidates = ['tailwind.css', 'tailwind-frontend.css', 'tailwind-editor.css'];
96
+
97
+ for (let dir = cwd; ; dir = resolve(dir, '..')) {
98
+ for (const name of candidates) {
99
+ if (importsTailwind(resolve(dir, name))) return resolve(dir, name);
100
+ }
101
+
102
+ const wpThemes = resolve(dir, 'wp-content/themes');
103
+
104
+ if (existsSync(wpThemes)) {
105
+ for (const theme of readdirSync(wpThemes)) {
106
+ for (const name of candidates) {
107
+ if (importsTailwind(resolve(wpThemes, theme, name))) return resolve(wpThemes, theme, name);
108
+ }
109
+ }
110
+ }
111
+
112
+ if (resolve(dir, '..') === dir) return null;
113
+ }
114
+ }
115
+
116
+ function offsetToLineCol(content, offset) {
117
+ const before = content.slice(0, offset);
118
+ const line = before.split('\n').length;
119
+
120
+ return { line, col: offset - before.lastIndexOf('\n') };
121
+ }
122
+
123
+ // CSS.escape (CSSOM spec), which Tailwind also uses for class selectors.
124
+ function cssEscape(value) {
125
+ let out = '';
126
+
127
+ for (let i = 0; i < value.length; i++) {
128
+ const code = value.charCodeAt(i);
129
+ const char = value[i];
130
+
131
+ if (code === 0) {
132
+ out += '\uFFFD';
133
+ } else if ((code >= 0x1 && code <= 0x1f) || code === 0x7f || (i === 0 && code >= 0x30 && code <= 0x39) || (i === 1 && code >= 0x30 && code <= 0x39 && value.charCodeAt(0) === 0x2d)) {
134
+ out += `\\${code.toString(16)} `;
135
+ } else if (i === 0 && value.length === 1 && char === '-') {
136
+ out += `\\${char}`;
137
+ } else if (code >= 0x80 || char === '-' || char === '_' || /[0-9A-Za-z]/.test(char)) {
138
+ out += char;
139
+ } else {
140
+ out += `\\${char}`;
141
+ }
142
+ }
143
+
144
+ return out;
145
+ }
146
+
147
+ async function main() {
148
+ const args = parseArgs(process.argv.slice(2));
149
+
150
+ if (args.help) {
151
+ printHelp();
152
+ return EXIT_OK;
153
+ }
154
+
155
+ const cwd = process.cwd();
156
+ const entryPath = args.entry ? resolve(cwd, args.entry) : findDefaultEntry(cwd);
157
+
158
+ if (!entryPath || !existsSync(entryPath)) {
159
+ console.error(entryPath ? `Entry CSS not found: ${entryPath}` : "Could not locate a Tailwind CSS entry that imports 'tailwindcss'. Pass --entry <path>.");
160
+ return EXIT_USAGE;
161
+ }
162
+
163
+ let ignore;
164
+
165
+ try {
166
+ ignore = loadTwIgnore(args.ignoreFile, cwd).map((pattern) => new RegExp(pattern));
167
+ } catch (error) {
168
+ console.error(error.message);
169
+ return EXIT_USAGE;
170
+ }
171
+
172
+ let files;
173
+
174
+ if (args.files.length) {
175
+ files = args.files.map((f) => resolve(cwd, f));
176
+ } else {
177
+ const includes = args.include ?? ['src/Blocks/**/manifest.json', 'src/**/*.php'];
178
+ const excludes = ['public/**', 'node_modules/**', 'vendor/**', 'vendor-prefixed/**', ...(args.exclude ?? [])];
179
+ const found = new Set();
180
+
181
+ for (const pattern of includes) {
182
+ for (const m of await glob(pattern, { cwd, ignore: excludes, absolute: true })) found.add(m);
183
+ }
184
+
185
+ files = [...found].sort();
186
+ }
187
+
188
+ if (files.length === 0) {
189
+ process.stderr.write('No files matched.\n');
190
+ return EXIT_OK;
191
+ }
192
+
193
+ const ds = await __unstable__loadDesignSystem(await readFile(entryPath, 'utf8'), { base: resolve(entryPath, '..') });
194
+ const verdicts = new Map();
195
+
196
+ // Selectors and at-rule preludes of a class's CSS, with the class name
197
+ // replaced by a placeholder. Values may legitimately change under
198
+ // canonicalization (16px → calc(var(--spacing) * 16) with a 1px spacing
199
+ // token); selectors must not. Canonicalizing arbitrary variants can drop
200
+ // `\_` escapes or wrap the selector in :where(), which changes the result.
201
+ const selectorShape = (className) => {
202
+ const css = ds.candidatesToCss([className])[0] ?? '';
203
+
204
+ return css
205
+ .replaceAll(`.${cssEscape(className)}`, '.X')
206
+ .split('{')
207
+ .slice(0, -1)
208
+ .map((part) => part.split(/[;}]/).pop().trim())
209
+ .join(' { ');
210
+ };
211
+
212
+ // One class at a time: batches drop unknown classes and merge pairs
213
+ // (top-0 bottom-0 → inset-y-0), which would break token alignment.
214
+ const judge = (className) => {
215
+ if (!verdicts.has(className)) {
216
+ if (ignore.some((re) => re.test(className))) {
217
+ verdicts.set(className, { ok: true });
218
+ } else if (ds.candidatesToCss([className])[0] === null) {
219
+ verdicts.set(className, { unknown: true });
220
+ } else {
221
+ const [canonical] = ds.canonicalizeCandidates([className], { rem: args.rootFontSize });
222
+ const safe = canonical && canonical !== className && selectorShape(canonical) === selectorShape(className);
223
+
224
+ verdicts.set(className, safe ? { canonical } : { ok: true });
225
+ }
226
+ }
227
+
228
+ return verdicts.get(className);
229
+ };
230
+
231
+ let unknownCount = 0;
232
+ let canonicalCount = 0;
233
+
234
+ for (const file of files) {
235
+ const content = await readFile(file, 'utf8');
236
+ const rel = relative(cwd, file);
237
+ const replacements = [];
238
+
239
+ for (const group of extractGroups(content, file)) {
240
+ for (const token of group.tokens) {
241
+ const verdict = judge(token.className);
242
+ const { line, col } = offsetToLineCol(content, token.start);
243
+
244
+ if (verdict.unknown && args.unknown) {
245
+ console.log(`${rel}:${line}:${col} unknown ${token.className}`);
246
+ unknownCount++;
247
+ } else if (verdict.canonical) {
248
+ console.log(`${rel}:${line}:${col} ${token.className} → ${verdict.canonical}`);
249
+ replacements.push({ ...token, canonical: verdict.canonical });
250
+ canonicalCount++;
251
+ }
252
+ }
253
+ }
254
+
255
+ if (args.write && replacements.length) {
256
+ let next = content;
257
+
258
+ for (const r of replacements.sort((a, b) => b.start - a.start)) {
259
+ next = next.slice(0, r.start) + (r.encode ? r.encode(r.canonical) : r.canonical) + next.slice(r.end);
260
+ }
261
+
262
+ await writeFile(file, next, 'utf8');
263
+ }
264
+ }
265
+
266
+ if (unknownCount + canonicalCount === 0) {
267
+ return EXIT_OK;
268
+ }
269
+
270
+ console.error(`\n${unknownCount} unknown, ${canonicalCount} non-canonical class(es)${args.write ? ' (non-canonical rewritten)' : ''}.`);
271
+
272
+ return unknownCount > 0 || !args.write ? EXIT_VIOLATIONS : EXIT_OK;
273
+ }
274
+
275
+ main().then(
276
+ (code) => process.exit(code),
277
+ (err) => {
278
+ console.error(err && err.stack ? err.stack : String(err));
279
+ process.exit(EXIT_USAGE);
280
+ },
281
+ );
@@ -0,0 +1,65 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { getDefaultSelectors } from 'eslint-plugin-better-tailwindcss/defaults';
3
+ import { loadTwIgnore, TW_IGNORE_FILE } from './tw-ignore.mjs';
4
+
5
+ // Resolved here, not by name, so projects that depend only on this package
6
+ // load the plugin under isolated linkers (pnpm, bun --linker isolated).
7
+ const tailwindPlugin = fileURLToPath(import.meta.resolve('eslint-plugin-better-tailwindcss'));
8
+
9
+ const defaultIgnorePatterns = ['public/**', 'node_modules/**', 'vendor/**', 'vendor-prefixed/**', 'eightshift/**', 'coverage/**'];
10
+
11
+ /**
12
+ * Eightshift oxlint config with Tailwind class checks.
13
+ *
14
+ * Usage in a project's `oxlint.config.ts`:
15
+ *
16
+ * import { defineConfig } from 'oxlint';
17
+ * import { createOxlintConfig } from '@eightshift/frontend-libs-tailwind/linters/oxlint.config.mjs';
18
+ *
19
+ * export default defineConfig(createOxlintConfig({ entryPoint: 'tailwind.css' }));
20
+ *
21
+ * Unknown-class exceptions live in `tw-ignore.json` (shared with `tw-sweep`).
22
+ *
23
+ * @param {object} options
24
+ * @param {string} options.entryPoint Tailwind CSS entry, relative to the config.
25
+ * @param {string} [options.ignoreFile] Unknown-class ignore list (JSON array of regex strings).
26
+ * @param {string[]} [options.ignorePatterns] Extra paths to skip.
27
+ * @param {object} [options.rules] Rule overrides, merged last.
28
+ * @returns {object} oxlint config.
29
+ */
30
+ export function createOxlintConfig({ entryPoint, ignoreFile = TW_IGNORE_FILE, ignorePatterns = [], rules = {} }) {
31
+ if (!entryPoint) {
32
+ throw new Error('createOxlintConfig: `entryPoint` is required');
33
+ }
34
+
35
+ return {
36
+ plugins: ['eslint', 'unicorn', 'oxc', 'react'],
37
+ jsPlugins: [tailwindPlugin],
38
+ settings: {
39
+ 'better-tailwindcss': {
40
+ entryPoint,
41
+ selectors: [...getDefaultSelectors(), { kind: 'attribute', name: '^.+ClassName$', match: [{ type: 'strings' }] }],
42
+ },
43
+ },
44
+ ignorePatterns: [...defaultIgnorePatterns, ...ignorePatterns],
45
+ rules: {
46
+ 'no-array-constructor': 'error',
47
+ 'no-constant-binary-expression': 'error',
48
+ 'no-implicit-coercion': 'error',
49
+ 'no-nested-ternary': 'error',
50
+ 'no-unused-expressions': 'error',
51
+ 'no-void': 'error',
52
+ 'no-param-reassign': 'warn',
53
+ 'react/rules-of-hooks': 'error',
54
+ 'react/exhaustive-deps': 'error',
55
+ 'react/react-in-jsx-scope': 'off',
56
+ 'react/self-closing-comp': 'warn',
57
+ 'better-tailwindcss/no-duplicate-classes': 'error',
58
+ 'better-tailwindcss/no-deprecated-classes': 'error',
59
+ 'better-tailwindcss/enforce-canonical-classes': 'error',
60
+ 'better-tailwindcss/no-unknown-classes': ['error', { ignore: loadTwIgnore(ignoreFile) }],
61
+ 'better-tailwindcss/no-conflicting-classes': 'error',
62
+ ...rules,
63
+ },
64
+ };
65
+ }
@@ -145,5 +145,30 @@ module.exports = {
145
145
  ignoreAtRules: ['tailwind'],
146
146
  },
147
147
  ],
148
+
149
+ // Tailwind's `@apply` takes utility classes, but the CSS Mixins spec `@apply` in csstree's syntax data only accepts dashed idents.
150
+ // `media` is kept from stylelint-config-recommended, as setting options replaces its list.
151
+ 'at-rule-prelude-no-invalid': [
152
+ true,
153
+ {
154
+ ignoreAtRules: ['media', 'apply'],
155
+ },
156
+ ],
157
+
158
+ // In Tailwind's `@utility` and `@custom-variant`, `&` resolves to the generated utility class, so it has a scoping root.
159
+ 'nesting-selector-no-missing-scoping-root': [
160
+ true,
161
+ {
162
+ ignoreAtRules: ['utility', 'custom-variant'],
163
+ },
164
+ ],
165
+
166
+ // Tailwind's `@utility` acts as a style rule, so declarations in at-rules nested inside it (e.g. `@supports`) are valid.
167
+ 'no-invalid-position-declaration': [
168
+ true,
169
+ {
170
+ ignoreAtRules: ['utility'],
171
+ },
172
+ ],
148
173
  },
149
174
  };
@@ -0,0 +1,45 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+
4
+ export const TW_IGNORE_FILE = 'tw-ignore.json';
5
+
6
+ /**
7
+ * Loads the project's Tailwind unknown-class ignore list: a JSON array of regex
8
+ * source strings, shared by oxlint (`no-unknown-classes`) and `tw-sweep`.
9
+ *
10
+ * A missing file means "ignore nothing". An invalid file or pattern throws,
11
+ * naming the offending entry, so a typo never silently disables the check.
12
+ *
13
+ * @param {string} [file] Path to the JSON file, relative to `cwd`.
14
+ * @param {string} [cwd] Base directory.
15
+ * @returns {string[]} Regex source strings.
16
+ */
17
+ export function loadTwIgnore(file = TW_IGNORE_FILE, cwd = process.cwd()) {
18
+ const path = resolve(cwd, file);
19
+
20
+ if (!existsSync(path)) {
21
+ return [];
22
+ }
23
+
24
+ let patterns;
25
+
26
+ try {
27
+ patterns = JSON.parse(readFileSync(path, 'utf8'));
28
+ } catch (error) {
29
+ throw new Error(`${path}: invalid JSON (${error.message})`);
30
+ }
31
+
32
+ if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== 'string')) {
33
+ throw new Error(`${path}: expected a JSON array of regex strings`);
34
+ }
35
+
36
+ for (const pattern of patterns) {
37
+ try {
38
+ new RegExp(pattern);
39
+ } catch (error) {
40
+ throw new Error(`${path}: invalid pattern ${JSON.stringify(pattern)} (${error.message})`);
41
+ }
42
+ }
43
+
44
+ return patterns;
45
+ }