@syntopica/quality-config 0.11.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) BusiRocket
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PUBLIC_API.md ADDED
@@ -0,0 +1,93 @@
1
+ # Public API (`@syntopica/quality-config`)
2
+
3
+ Semver applies to **export subpaths** listed below. Import paths not listed here
4
+ are **private** and may change without a major bump.
5
+
6
+ ## Stable exports (semver)
7
+
8
+ | Export subpath | Purpose |
9
+ | ---------------------------------------------- | ----------------------------------------------------------- |
10
+ | `@syntopica/quality-config` | Barrel re-exporting every factory and constant below |
11
+ | `@syntopica/quality-config/knip` | `createKnipConfig` — unused files/exports/deps gate |
12
+ | `@syntopica/quality-config/dependency-cruiser` | `createDepCruiserConfig` — module boundary and cycle gate |
13
+ | `@syntopica/quality-config/type-coverage` | `TYPE_COVERAGE_THRESHOLD` — minimum non-`any` type coverage |
14
+ | `@syntopica/quality-config/lefthook` | `createLefthookConfig` — shared git hook pipeline |
15
+ | `@syntopica/quality-config/jscpd` | `jscpd.json` — cross-file duplication gate config |
16
+
17
+ ### `createDepCruiserConfig(options)`
18
+
19
+ Every option is optional and every default is project-agnostic: the factory
20
+ encodes no directory name belonging to any particular repository.
21
+
22
+ | Option | Effect |
23
+ | ------------------ | ---------------------------------------------------------------------------------------------------------- |
24
+ | `scope` | `'repo'` (default) emits every rule. `'workspace'` emits only `no-orphans`, for a single-workspace cruise. |
25
+ | `tsConfigPath` | tsconfig used to resolve path aliases. |
26
+ | `orphanExemptions` | Extra `no-orphans` path patterns, on top of the framework-convention ones built in. |
27
+
28
+ **`tsConfigPath` resolves relative `paths` against the current working
29
+ directory**, not against the config file that declares them - a
30
+ dependency-cruiser behavior, not a choice made here. A tsconfig that lives
31
+ somewhere other than the directory you cruise from (a framework-generated one,
32
+ say) therefore mis-resolves every alias. Cruise from the directory its paths are
33
+ written against, or pass a config whose paths are rebased to it.
34
+
35
+ Use `orphanExemptions` for directories a repo-wide cruise cannot judge - most
36
+ often a workspace whose aliases only resolve under its own tsconfig, which you
37
+ then cruise separately with `scope: 'workspace'`.
38
+
39
+ ## Stable executables (semver)
40
+
41
+ | Binary | Purpose |
42
+ | ------------------- | ---------------------------------------------------------- |
43
+ | `baseline-env-init` | Seed a gitignored `.env` from the committed `.env.example` |
44
+ | `baseline-dupes` | Run jscpd against this package's canonical `jscpd.json` |
45
+
46
+ `baseline-env-init` takes no arguments and always exits 0. It copies
47
+ `.env.example` to `.env` in the current working directory, does nothing when
48
+ `.env` already exists, and does nothing when there is no `.env.example`. Wire it
49
+ into `prepare` so a freshly cloned project boots with the documented example
50
+ values instead of failing its startup env validation.
51
+
52
+ `baseline-dupes` takes the paths to scan (a bare call scans `.`) and forwards
53
+ every other argument to jscpd, where it wins over the config file. jscpd 5.x is
54
+ a Rust binary with no JS config loader, which is why this gate ships as a JSON
55
+ file plus a runner rather than as a factory: the config is read in place, never
56
+ copied into the consuming repo.
57
+
58
+ `baseline-type-coverage` takes the directories to search and `--at-least <n>`, a
59
+ repo-local floor for a project still climbing toward the shared threshold. It
60
+ refuses a value above that threshold, so it can only lower the bar where one is
61
+ needed, never raise or restate it.
62
+
63
+ `--also-ignore <patterns>` adds ignore patterns **on top of** the shared list.
64
+ jscpd's own `--ignore` replaces that list instead, so without this a project
65
+ with one generated directory to exclude would have to restate every shared
66
+ pattern in its own script.
67
+
68
+ Every export entry except `./jscpd` resolves to **TypeScript source** (`*.ts`)
69
+ published in the package, loaded with **ESM** and a TypeScript-aware runner (for
70
+ example `jiti` or your bundler) as shown in the package README. `./jscpd`
71
+ resolves to the JSON file jscpd itself reads.
72
+
73
+ ## Implementation detail
74
+
75
+ Internal modules under `src/` that are not re-exported through the table above
76
+ are **not** public API.
77
+
78
+ ## `publint`/`attw` findings that are expected, not defects
79
+
80
+ `publish:check` (`publint --strict && attw --pack . --profile node16`) ignores
81
+ two `attw` rules for this package: `cjs-resolves-to-esm` and
82
+ `internal-resolution-error`. Both are consequences of the no-build design above,
83
+ not resolution bugs:
84
+
85
+ - **`cjs-resolves-to-esm`** — every export subpath resolves to raw `.ts` ESM
86
+ source; there is no CommonJS build to satisfy a `require()` caller. Consumers
87
+ load these factories with ESM and a TypeScript-aware runtime (`jiti`), never
88
+ `require`.
89
+ - **`internal-resolution-error`** — `./knip` and `./dependency-cruiser` import
90
+ `knip`/`dependency-cruiser`, declared as **optional peer dependencies**.
91
+ `attw`'s sandbox only contains this package's own tarball, so it cannot see
92
+ peers a real consumer installs, and flags those imports as unresolved. This is
93
+ the intended shape of an optional peer, not a broken `exports` entry.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @syntopica/quality-config
2
+
3
+ Shared configuration factories for cross-file quality gates: unused
4
+ files/exports/dependencies (knip), module boundaries and dependency cycles
5
+ (dependency-cruiser), type coverage, and the shared git hook pipeline
6
+ (lefthook).
7
+
8
+ - **Public API (semver):** see [PUBLIC_API.md](./PUBLIC_API.md).
9
+ - **Platform decisions:**
10
+ [engineering-baseline/docs/platform-decisions.md](https://github.com/BusiRocket/engineering-baseline/blob/main/docs/platform-decisions.md).
11
+
12
+ ## Requirements
13
+
14
+ - Node.js 22+
15
+ - TypeScript 5.4+
16
+ - `knip` and `dependency-cruiser` as needed per gate (optional peers, listed in
17
+ `package.json`)
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pnpm add -D @syntopica/quality-config@^0.1.0 typescript
23
+ ```
24
+
25
+ Add `knip` and/or `dependency-cruiser` for the gates you use.
26
+
27
+ ## Usage
28
+
29
+ | Import subpath | Use case |
30
+ | ---------------------------------------------- | ----------------------------------------- |
31
+ | `@syntopica/quality-config` | All factories and constants, re-exported |
32
+ | `@syntopica/quality-config/knip` | Unused files/exports/dependencies gate |
33
+ | `@syntopica/quality-config/dependency-cruiser` | Module boundary and dependency-cycle gate |
34
+ | `@syntopica/quality-config/type-coverage` | Minimum non-`any` type coverage threshold |
35
+ | `@syntopica/quality-config/lefthook` | Shared git hook pipeline |
36
+
37
+ ### `baseline-env-init`
38
+
39
+ Seeds a gitignored `.env` from the committed `.env.example`, so a freshly cloned
40
+ project boots on the documented example values instead of failing its startup
41
+ env validation. Bundlers inline `VITE_*`/`NEXT_PUBLIC_*` values at build time,
42
+ so without this a project with no `.env` builds a bundle that throws before it
43
+ renders and reports a blank page rather than a useful error.
44
+
45
+ ```json
46
+ {
47
+ "scripts": {
48
+ "prepare": "lefthook install && baseline-env-init"
49
+ }
50
+ }
51
+ ```
52
+
53
+ Idempotent: an existing `.env` is never overwritten, and a project with no
54
+ `.env.example` is a no-op. It never writes a value into version control - `.env`
55
+ stays gitignored, `.env.example` stays the only committed copy.
56
+
57
+ ### `baseline-dupes`
58
+
59
+ Runs the cross-file duplication gate against this package's canonical
60
+ `jscpd.json`, so no project has to commit a copy of it.
61
+
62
+ ```json
63
+ {
64
+ "scripts": {
65
+ "dupes": "baseline-dupes ."
66
+ }
67
+ }
68
+ ```
69
+
70
+ Takes the paths to scan (a bare `baseline-dupes` scans `.`); every other
71
+ argument is forwarded to jscpd in the order given and wins over the config file,
72
+ so `baseline-dupes . --min-tokens 120` works. Pass the path explicitly when you
73
+ pass flags - the runner does not try to tell a path from a flag's value.
74
+
75
+ To keep the shared ignores and add your own, use `--also-ignore`:
76
+
77
+ ```json
78
+ {
79
+ "scripts": {
80
+ "dupes": "baseline-dupes . --also-ignore \"**/src/types/supabase/**\""
81
+ }
82
+ }
83
+ ```
84
+
85
+ jscpd's own `--ignore` **replaces** the config's list rather than merging into
86
+ it (measured: a config that also ignored `**/cargo-baseline/**` scanned 61 files
87
+ and found 1 clone; adding an unrelated `--ignore` took it to 109 files and 4
88
+ clones). Without `--also-ignore`, a project with one generated directory to
89
+ exclude would have to restate every shared pattern in its own script, which is
90
+ the duplication this runner exists to remove. `--also-ignore` merges through a
91
+ generated config that is deleted again on the way out; it extends your own
92
+ `--config` when you pass one. jscpd 5.x is a Rust binary that reads JSON only -
93
+ it has no JS config loader - which is why this gate ships as a config file plus
94
+ a runner rather than as a factory like `createKnipConfig`. Point another tool at
95
+ the same file through `@syntopica/quality-config/jscpd`.
96
+
97
+ `jscpd` itself stays a devDependency of the consuming project: the runner
98
+ invokes it, it does not vendor it.
99
+
100
+ ## Related
101
+
102
+ - **Lint / TS configs:** `@syntopica/eslint-config`, `@syntopica/tsconfig`.
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ // `pnpm audit` with an allowlist that expires.
3
+ //
4
+ // Usage:
5
+ // baseline-audit [--level low|moderate|high|critical] [--file <path>]
6
+ //
7
+ // The problem this replaces: two advisories in this repository sat below the
8
+ // `--audit-level=high` line and were documented as prose in TODO.md. Nothing
9
+ // re-checked them, nothing expired them, and the only way to raise the audit
10
+ // level was to accept the noise of findings that had already been judged.
11
+ //
12
+ // An allowlist entry is a decision with a date on it. `reason` is required and
13
+ // `expires` is required, so a waiver comes back on its own and has to be
14
+ // re-argued rather than inherited. That is what makes it safe to gate at
15
+ // `moderate` instead of `high`: the known exceptions stop being noise.
16
+ //
17
+ // Allowlist file (`.baseline-advisories.json`), keyed by GitHub advisory ID:
18
+ //
19
+ // {
20
+ // "GHSA-w5hq-g745-h8pq": {
21
+ // "reason": "via @lhci/cli > uuid, resolved at 8.3.2; no consumer release past 0.15.1",
22
+ // "expires": "2026-12-31"
23
+ // }
24
+ // }
25
+ import { spawnSync } from 'node:child_process'
26
+ import { readFile } from 'node:fs/promises'
27
+ import { resolve } from 'node:path'
28
+ import { argv, cwd, exit } from 'node:process'
29
+
30
+ const LEVELS = ['info', 'low', 'moderate', 'high', 'critical']
31
+ const DEFAULT_FILE = '.baseline-advisories.json'
32
+
33
+ const flag = (name, fallback) => {
34
+ const index = argv.indexOf(`--${name}`)
35
+ return index === -1 ? fallback : (argv[index + 1] ?? fallback)
36
+ }
37
+
38
+ const level = flag('level', 'moderate')
39
+ if (!LEVELS.includes(level)) {
40
+ console.error(`baseline-audit: --level must be one of ${LEVELS.join(', ')}.`)
41
+ exit(2)
42
+ }
43
+ const minimum = LEVELS.indexOf(level)
44
+ const today = new Date().toISOString().slice(0, 10)
45
+ const root = cwd()
46
+
47
+ const allowlist = await readAllowlist(resolve(root, flag('file', DEFAULT_FILE)))
48
+
49
+ // `pnpm audit` exits non-zero when it finds anything, which is the whole
50
+ // point, so its status is not an error condition here - the JSON is.
51
+ const result = spawnSync('pnpm', ['audit', '--json'], {
52
+ encoding: 'utf8',
53
+ maxBuffer: 64 * 1024 * 1024,
54
+ })
55
+ if (result.error) {
56
+ console.error(
57
+ `baseline-audit: could not run pnpm audit: ${result.error.message}`,
58
+ )
59
+ exit(2)
60
+ }
61
+
62
+ let report
63
+ try {
64
+ report = JSON.parse(result.stdout)
65
+ } catch {
66
+ console.error('baseline-audit: pnpm audit did not return JSON.')
67
+ console.error(result.stdout.slice(0, 2000))
68
+ exit(2)
69
+ }
70
+
71
+ const advisories = Object.values(report.advisories ?? {})
72
+ const failures = []
73
+ const waived = []
74
+ const stale = []
75
+
76
+ for (const advisory of advisories) {
77
+ if (LEVELS.indexOf(advisory.severity) < minimum) continue
78
+
79
+ const entry =
80
+ allowlist[advisory.github_advisory_id] ?? allowlist[String(advisory.id)]
81
+ if (!entry) {
82
+ failures.push(advisory)
83
+ continue
84
+ }
85
+ if (entry.expires < today) {
86
+ stale.push({ advisory, entry })
87
+ continue
88
+ }
89
+ waived.push({ advisory, entry })
90
+ }
91
+
92
+ for (const { advisory, entry } of waived) {
93
+ console.log(
94
+ `waived ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
95
+ `${advisory.module_name} (expires ${entry.expires})\n ${entry.reason}`,
96
+ )
97
+ }
98
+
99
+ for (const { advisory, entry } of stale) {
100
+ console.error(
101
+ `EXPIRED ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
102
+ `${advisory.module_name} (expired ${entry.expires})\n ${entry.reason}\n` +
103
+ ' Re-check it, then renew the entry or remove it.',
104
+ )
105
+ }
106
+
107
+ for (const advisory of failures) {
108
+ console.error(
109
+ `FAIL ${advisory.severity.padEnd(8)} ${advisory.github_advisory_id} ` +
110
+ `${advisory.module_name} ${advisory.vulnerable_versions}\n` +
111
+ ` patched in ${advisory.patched_versions} - ${advisory.url}\n` +
112
+ ` via ${(advisory.findings?.[0]?.paths ?? []).slice(0, 2).join(', ')}`,
113
+ )
114
+ }
115
+
116
+ const failed = failures.length + stale.length
117
+ console.log(
118
+ `\nbaseline-audit: ${advisories.length} advisories, gate at ${level}: ` +
119
+ `${failures.length} unwaived, ${stale.length} expired, ${waived.length} waived.`,
120
+ )
121
+ if (failed) exit(1)
122
+
123
+ async function readAllowlist(path) {
124
+ let raw
125
+ try {
126
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
127
+ raw = await readFile(path, 'utf8')
128
+ } catch {
129
+ return {}
130
+ }
131
+
132
+ const parsed = JSON.parse(raw)
133
+ for (const [id, entry] of Object.entries(parsed)) {
134
+ // Both fields are required, and the check is here rather than at use: an
135
+ // entry missing one is a waiver nobody can audit, and treating it as
136
+ // absent would hide the mistake behind a passing gate.
137
+ if (!entry?.reason || !entry?.expires) {
138
+ console.error(
139
+ `baseline-audit: allowlist entry ${id} needs both \`reason\` and \`expires\`.`,
140
+ )
141
+ exit(2)
142
+ }
143
+ }
144
+ return parsed
145
+ }
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ // Runs dependency-cruiser once per workspace, each with its own tsconfig.
3
+ //
4
+ // A single repo-wide cruise takes one `tsConfig`, so in a monorepo where each
5
+ // workspace maps `@/*` through its own config it can resolve at most one of
6
+ // them. Every alias in every other workspace comes back `couldNotResolve`, and
7
+ // `no-orphans` then reports whatever it could not follow. Cruising per
8
+ // workspace gives each one the config that actually describes it.
9
+ //
10
+ // Usage:
11
+ // baseline-deps-graph # src, app, server, lib
12
+ // baseline-deps-graph src app # only these
13
+ // baseline-deps-graph --config path.cjs src
14
+ import { spawnSync } from 'node:child_process'
15
+ import { existsSync, readdirSync } from 'node:fs'
16
+ import { relative, resolve } from 'node:path'
17
+ import { argv, cwd, exit } from 'node:process'
18
+
19
+ const DEFAULT_SOURCES = ['src', 'app', 'server', 'lib']
20
+ const SKIPPED_DIRECTORIES = new Set([
21
+ 'node_modules',
22
+ 'dist',
23
+ 'build',
24
+ 'coverage',
25
+ 'target',
26
+ '.git',
27
+ '.next',
28
+ '.nuxt',
29
+ '.output',
30
+ '.astro',
31
+ ])
32
+ const MAX_DEPTH = 3
33
+
34
+ const args = argv.slice(2)
35
+ const configIndex = args.indexOf('--config')
36
+ const configPath = resolve(
37
+ cwd(),
38
+ configIndex === -1
39
+ ? '.dependency-cruiser.cjs'
40
+ : (args[configIndex + 1] ?? ''),
41
+ )
42
+ const sources = (
43
+ configIndex === -1
44
+ ? args
45
+ : [...args.slice(0, configIndex), ...args.slice(configIndex + 2)]
46
+ ).filter(Boolean)
47
+ const sourceDirectories = sources.length ? sources : DEFAULT_SOURCES
48
+
49
+ // Every path below is derived from the invoking project's own tree, which is
50
+ // the point of this tool - not untrusted input.
51
+ /* eslint-disable security/detect-non-literal-fs-filename */
52
+ if (!existsSync(configPath)) {
53
+ console.error(
54
+ `baseline-deps-graph: no dependency-cruiser config at ${relative(cwd(), configPath)}. ` +
55
+ 'Pass one with --config.',
56
+ )
57
+ exit(1)
58
+ }
59
+
60
+ function findWorkspaces(root, depth = 0) {
61
+ const found = []
62
+ if (existsSync(resolve(root, 'tsconfig.json'))) found.push(root)
63
+ if (depth >= MAX_DEPTH) return found
64
+
65
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
66
+ if (!entry.isDirectory() || SKIPPED_DIRECTORIES.has(entry.name)) continue
67
+ found.push(...findWorkspaces(resolve(root, entry.name), depth + 1))
68
+ }
69
+ return found
70
+ }
71
+
72
+ const failed = []
73
+ for (const workspace of findWorkspaces(cwd())) {
74
+ const present = sourceDirectories.filter((directory) =>
75
+ existsSync(resolve(workspace, directory)),
76
+ )
77
+ if (!present.length) continue
78
+
79
+ const label = relative(cwd(), workspace) || '.'
80
+ console.log(`deps-graph: cruising ${label} (${present.join(', ')})`)
81
+ const result = spawnSync(
82
+ 'pnpm',
83
+ [
84
+ 'exec',
85
+ 'depcruise',
86
+ ...present,
87
+ '--config',
88
+ configPath,
89
+ '--ts-config',
90
+ 'tsconfig.json',
91
+ ],
92
+ { cwd: workspace, stdio: 'inherit' },
93
+ )
94
+ if (result.status !== 0) failed.push(label)
95
+ }
96
+ /* eslint-enable security/detect-non-literal-fs-filename */
97
+
98
+ if (failed.length) {
99
+ console.error(`deps-graph: failed for ${failed.join(', ')}`)
100
+ exit(1)
101
+ }
102
+ console.log('deps-graph: no violations found.')
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ // Runs jscpd against this package's canonical `jscpd.json`.
3
+ //
4
+ // jscpd 5.x is a Rust binary that reads JSON only - it has no JS config
5
+ // loader - so this gate cannot ship as a factory the way knip,
6
+ // dependency-cruiser and lefthook do. It ships as the config file plus this
7
+ // runner instead: one file, read in place, never copied into the consuming
8
+ // repo. Before this, `.jscpd.json` was duplicated byte for byte in the repo
9
+ // root and all eight templates, and every adopter had to copy it too.
10
+ //
11
+ // Usage:
12
+ // baseline-dupes scan the current directory
13
+ // baseline-dupes packages scripts scan only these paths
14
+ // baseline-dupes . --min-tokens 120 any jscpd flag, passed through
15
+ // baseline-dupes . --also-ignore "**/gen/**" keep the shared ignores, add these
16
+ //
17
+ // Arguments are forwarded to jscpd in the order given, untouched apart from
18
+ // `--also-ignore`. This runner deliberately does not try to tell a path from a
19
+ // flag's value: `--min-tokens 120` and `--config x.json` carry a value that
20
+ // looks like neither, and a runner that guesses turns `120` into a scan path.
21
+ // The only argument it adds is `--config`, and only when the caller did not
22
+ // pass one. Pass an explicit path when you pass flags; a bare
23
+ // `baseline-dupes` scans `.`.
24
+ //
25
+ // `--also-ignore` exists because jscpd's own `--ignore` REPLACES the config's
26
+ // list rather than merging into it. Measured on this repo: a config that also
27
+ // ignored `**/cargo-baseline/**` scanned 61 files and found 1 clone; adding an
28
+ // unrelated `--ignore` took it to 109 files and 4 clones, the shared patterns
29
+ // gone. So an adopter with one generated directory to exclude (committed
30
+ // Supabase types, a migrations folder, a cpanel build - five of nine repos
31
+ // surveyed) had no way to say so without restating every shared pattern in
32
+ // their own package.json, which is the duplication this runner exists to
33
+ // remove. This flag merges instead, through a generated config deleted again
34
+ // on the way out.
35
+ import { spawnSync } from 'node:child_process'
36
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
37
+ import { tmpdir } from 'node:os'
38
+ import { join } from 'node:path'
39
+ import { argv, exit } from 'node:process'
40
+ import { fileURLToPath } from 'node:url'
41
+
42
+ const PACKAGED_CONFIG = fileURLToPath(new URL('../jscpd.json', import.meta.url))
43
+
44
+ // Splits `--also-ignore a,b` and `--also-ignore=a,b` out, leaving every other
45
+ // argument in its original position.
46
+ function takeAlsoIgnore(args) {
47
+ const patterns = []
48
+ const rest = []
49
+ for (let index = 0; index < args.length; index += 1) {
50
+ const arg = args[index]
51
+ if (arg === '--also-ignore') {
52
+ index += 1
53
+ patterns.push(...String(args[index] ?? '').split(','))
54
+ continue
55
+ }
56
+ if (arg.startsWith('--also-ignore=')) {
57
+ patterns.push(...arg.slice('--also-ignore='.length).split(','))
58
+ continue
59
+ }
60
+ rest.push(arg)
61
+ }
62
+ return { patterns: patterns.map((p) => p.trim()).filter(Boolean), rest }
63
+ }
64
+
65
+ // Where the caller's own `--config` sits, if they passed one. `value` is the
66
+ // index of the path argument; `inline` is the index of a `--config=x` form.
67
+ function findConfig(args) {
68
+ for (let index = 0; index < args.length; index += 1) {
69
+ if (args[index] === '-c' || args[index] === '--config')
70
+ return { value: index + 1, inline: -1 }
71
+ if (args[index].startsWith('--config=')) return { value: -1, inline: index }
72
+ }
73
+ return { value: -1, inline: -1 }
74
+ }
75
+
76
+ const { patterns, rest } = takeAlsoIgnore(argv.slice(2))
77
+ const args = rest.length ? [...rest] : ['.']
78
+ const found = findConfig(args)
79
+ const sourceConfig =
80
+ found.value !== -1
81
+ ? args[found.value]
82
+ : found.inline !== -1
83
+ ? args[found.inline].slice('--config='.length)
84
+ : PACKAGED_CONFIG
85
+
86
+ let config = sourceConfig
87
+ let scratch
88
+ if (patterns.length) {
89
+ let parsed
90
+ try {
91
+ // The config is this package's own file, or a path the caller chose.
92
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
93
+ parsed = JSON.parse(readFileSync(sourceConfig, 'utf8'))
94
+ } catch (error) {
95
+ console.error(
96
+ `baseline-dupes: could not read ${sourceConfig} - ${error.message}`,
97
+ )
98
+ exit(1)
99
+ }
100
+ parsed.ignore = [...(parsed.ignore ?? []), ...patterns]
101
+ scratch = mkdtempSync(join(tmpdir(), 'baseline-dupes-'))
102
+ config = join(scratch, 'jscpd.json')
103
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
104
+ writeFileSync(config, JSON.stringify(parsed))
105
+ }
106
+
107
+ if (found.value !== -1) args[found.value] = config
108
+ else if (found.inline !== -1) args[found.inline] = `--config=${config}`
109
+ else args.push('--config', config)
110
+
111
+ const result = spawnSync('pnpm', ['exec', 'jscpd', ...args], {
112
+ stdio: 'inherit',
113
+ })
114
+
115
+ if (scratch) rmSync(scratch, { recursive: true, force: true })
116
+
117
+ if (result.error) {
118
+ console.error(`baseline-dupes: could not run jscpd - ${result.error.message}`)
119
+ exit(1)
120
+ }
121
+ exit(result.status ?? 1)
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ // Bootstraps a project's gitignored `.env` from its committed `.env.example`.
3
+ //
4
+ // Templates validate `import.meta.env` / `process.env` against a Zod schema at
5
+ // startup and fail fast when a required variable is missing. Bundlers inline
6
+ // those values at build time, so a freshly cloned project with no `.env` builds
7
+ // an artifact that throws before it renders anything - a blank page rather than
8
+ // an obvious error. Copying the documented example values on install gives the
9
+ // project a working default without ever committing a `.env`.
10
+ //
11
+ // Idempotent: an existing `.env` is never overwritten, and a project without an
12
+ // `.env.example` is a no-op.
13
+ import { access, copyFile } from 'node:fs/promises'
14
+ import { resolve } from 'node:path'
15
+ import { cwd } from 'node:process'
16
+
17
+ // Both paths are derived from the invoking project's own working directory,
18
+ // which is the whole point of this tool - not untrusted input.
19
+ const examplePath = resolve(cwd(), '.env.example')
20
+ const targetPath = resolve(cwd(), '.env')
21
+
22
+ const hasTarget = await access(targetPath).then(
23
+ () => true,
24
+ () => false,
25
+ )
26
+ const hasExample = await access(examplePath).then(
27
+ () => true,
28
+ () => false,
29
+ )
30
+
31
+ if (hasTarget) {
32
+ console.log('baseline-env-init: .env already exists, left untouched.')
33
+ } else if (!hasExample) {
34
+ console.log('baseline-env-init: no .env.example found, nothing to do.')
35
+ } else {
36
+ await copyFile(examplePath, targetPath)
37
+ console.log('baseline-env-init: created .env from .env.example.')
38
+ }