@kainappsinc/factory 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README.md +342 -2
- package/package.json +76 -4
- package/src/cli/args.ts +48 -0
- package/src/cli/baseline.ts +57 -0
- package/src/cli/check.ts +104 -0
- package/src/cli/factory.schema.json +96 -0
- package/src/cli/git.ts +73 -0
- package/src/cli/glob.ts +46 -0
- package/src/cli/index.ts +7 -0
- package/src/cli/io.ts +46 -0
- package/src/cli/main.ts +99 -0
- package/src/cli/manifest.ts +230 -0
- package/src/cli/ratchet.ts +522 -0
- package/src/cli/risk.ts +104 -0
- package/src/depcruise/index.cjs +85 -0
- package/src/depcruise/index.d.cts +7 -0
- package/src/eslint/ast.ts +62 -0
- package/src/eslint/config.ts +86 -0
- package/src/eslint/index.ts +26 -0
- package/src/eslint/messages.ts +43 -0
- package/src/eslint/rules/import-suffix.ts +79 -0
- package/src/eslint/rules/no-json-parse-cast.ts +46 -0
- package/src/eslint/rules/no-raw-request-json.ts +46 -0
- package/src/eslint/rules/no-untracked-todo.ts +37 -0
- package/src/eslint/tester.ts +19 -0
- package/src/packs/ts-bun/classic-typescript.ts +149 -0
- package/src/packs/ts-bun/counter-cli.ts +69 -0
- package/src/packs/ts-bun/depcruise-counts.ts +114 -0
- package/src/packs/ts-bun/eslint-counts.ts +123 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1
|
|
4
|
+
|
|
5
|
+
- `ratchet --against`: when the target's counter command fails, the message says to check whether
|
|
6
|
+
it runs a path this branch removed, and to keep a thin shim there for one merge request.
|
|
7
|
+
- `ratchet --update` names the keys it drops from a baseline (and the zero keys it adds), instead
|
|
8
|
+
of printing an empty description (`LOWERED boundaries: (written to …)`).
|
|
9
|
+
- `ratchet` notes baseline keys the count no longer produces and says `--update` drops them.
|
|
10
|
+
Pass/fail is unchanged: a missing key still counts as 0, so an orphan at 0 passes and one above
|
|
11
|
+
0 fails as stale.
|
|
12
|
+
- `@kainappsinc/factory/eslint/tester` takes its parser from `typescript-eslint`; the
|
|
13
|
+
`@typescript-eslint/parser` peer dependency is gone.
|
|
14
|
+
- `LICENSE` (MIT) ships in the package. README: migrating from a vendored copy, and why the CI
|
|
15
|
+
jobs need a real `install`.
|
|
16
|
+
|
|
17
|
+
## 0.1.0
|
|
18
|
+
|
|
19
|
+
First release: the `factory` CLI (`check`, `ratchet`, `risk`, `validate`), the ts-bun counters
|
|
20
|
+
(`factory-eslint-counts`, `factory-depcruise-counts`) and TypeScript 7 shim, the shared ESLint
|
|
21
|
+
rules and config, the dependency-cruiser rule shapes and the manifest schema.
|
|
22
|
+
|
|
23
|
+
`import-suffix` reports with the message ids `missing` (a relative import without the
|
|
24
|
+
convention's suffix) and `wrong` (with the other one); a repository overriding its messages passes
|
|
25
|
+
`messages: { missing, wrong }`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kain Apps Inc.
|
|
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/README.md
CHANGED
|
@@ -1,3 +1,343 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kainappsinc/factory
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Mechanical gates that make a repository safe for agents (and people) to change at volume: every
|
|
4
|
+
change passes the same checks, debt counts can only go down, and changes to sensitive paths are
|
|
5
|
+
flagged for a person. A repository declares all of it in `factory.yaml` at its root; this package
|
|
6
|
+
runs it.
|
|
7
|
+
|
|
8
|
+
What is in the package:
|
|
9
|
+
|
|
10
|
+
- **The `factory` CLI**: `check` (run the gates), `ratchet` (counts that may only go down),
|
|
11
|
+
`risk` (which risk zones a change touches), `validate`. Bun built-ins only.
|
|
12
|
+
- **The ts-bun pack**: the ESLint and dependency-cruiser counters a `run` ratchet calls
|
|
13
|
+
(`factory-eslint-counts`, `factory-depcruise-counts`) and the TypeScript 7 shim
|
|
14
|
+
(`classic-typescript`).
|
|
15
|
+
- **Shared ESLint rules and config** (`@kainappsinc/factory/eslint`, `…/eslint/config`): rules each
|
|
16
|
+
repository would otherwise copy, with configurable messages, and the flat-config boilerplate.
|
|
17
|
+
- **dependency-cruiser rule shapes** (`@kainappsinc/factory/depcruise`): layer ordering, no test
|
|
18
|
+
imports in production, no value-import cycles.
|
|
19
|
+
- **The manifest's JSON schema** (`@kainappsinc/factory/schema.json`), for editors.
|
|
20
|
+
|
|
21
|
+
It ships TypeScript source and runs on **Bun** (1.3 or later); there is no build step.
|
|
22
|
+
|
|
23
|
+
## Adopting it
|
|
24
|
+
|
|
25
|
+
1. Add the dependency and a script. The counters use the repository's own ESLint,
|
|
26
|
+
dependency-cruiser and TypeScript (optional peer dependencies), so install the ones your
|
|
27
|
+
ratchets and lint config use:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
bun add -d @kainappsinc/factory eslint @eslint/js typescript-eslint \
|
|
31
|
+
@eslint-community/eslint-plugin-eslint-comments dependency-cruiser
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
"scripts": { "factory": "factory", "lint": "bun --bun eslint" }
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
If the repository's `typescript` is 7.0 (no JavaScript compiler API), also add the classic
|
|
39
|
+
compiler under an alias for typescript-eslint and dependency-cruiser:
|
|
40
|
+
`"typescript-classic": "npm:typescript@~6.0.3"` (see "TypeScript 7" below). With TypeScript 6
|
|
41
|
+
or earlier it is not needed.
|
|
42
|
+
|
|
43
|
+
The CLI and the counters live in `node_modules`: without installed dependencies
|
|
44
|
+
`bun run factory` fails with "command not found" (exit 127).
|
|
45
|
+
|
|
46
|
+
2. Write `factory.yaml` at the root (format: `schema.json`; for editor completion add
|
|
47
|
+
`# yaml-language-server: $schema=node_modules/@kainappsinc/factory/src/cli/factory.schema.json`):
|
|
48
|
+
|
|
49
|
+
```yaml
|
|
50
|
+
version: 1
|
|
51
|
+
pack: ts-bun
|
|
52
|
+
cli: bun run factory # how people run it here; used in messages
|
|
53
|
+
gates:
|
|
54
|
+
- { id: ratchet, run: bun run factory ratchet, tier: fast }
|
|
55
|
+
- { id: typecheck, run: bun run typecheck, tier: fast }
|
|
56
|
+
- { id: test, run: bun test, tier: full }
|
|
57
|
+
ratchets:
|
|
58
|
+
- id: eslint
|
|
59
|
+
why: "Lint findings may only go down: fix the code the rule flags."
|
|
60
|
+
run: bun run factory-eslint-counts
|
|
61
|
+
show: bun run factory-eslint-counts --show {keys}
|
|
62
|
+
- id: boundaries
|
|
63
|
+
why: "An import crosses a module boundary; --show gives each rule's fix."
|
|
64
|
+
run: bun run factory-depcruise-counts src
|
|
65
|
+
show: bun run factory-depcruise-counts --show {keys} src
|
|
66
|
+
- id: long-files
|
|
67
|
+
why: "Files over 1000 lines are hard to review; split them."
|
|
68
|
+
max_lines: 1000
|
|
69
|
+
include: ["src/**/*.ts"]
|
|
70
|
+
exclude: ["**/__tests__/**"]
|
|
71
|
+
risk_zones:
|
|
72
|
+
factory: [factory.yaml, eslint.config.js, .dependency-cruiser.cjs, .gitlab-ci.yml]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Then seed the baselines: `bun run factory ratchet --update --allow-increase`, and commit
|
|
76
|
+
`factory/baselines/`.
|
|
77
|
+
|
|
78
|
+
3. `eslint.config.js` (runs on Bun only, since it imports TypeScript):
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
import { defineConfig, globalIgnores } from 'eslint/config';
|
|
82
|
+
import { baseConfig, testConfig } from '@kainappsinc/factory/eslint/config';
|
|
83
|
+
import factory from '@kainappsinc/factory/eslint';
|
|
84
|
+
|
|
85
|
+
const TESTS = ['**/__tests__/**', '**/*.test.ts'];
|
|
86
|
+
|
|
87
|
+
export default defineConfig([
|
|
88
|
+
globalIgnores(['dist/', '**/node_modules/']),
|
|
89
|
+
await baseConfig({
|
|
90
|
+
files: ['src/**/*.ts'],
|
|
91
|
+
plugins: { factory },
|
|
92
|
+
rules: {
|
|
93
|
+
'factory/import-suffix': ['error', { suffix: 'js' }],
|
|
94
|
+
'factory/no-json-parse-cast': 'error',
|
|
95
|
+
'factory/no-untracked-todo': 'error',
|
|
96
|
+
},
|
|
97
|
+
}),
|
|
98
|
+
testConfig({ files: TESTS, rules: { 'factory/no-json-parse-cast': 'off' } }),
|
|
99
|
+
]);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
To keep existing rule ids (and so the `eslint` ratchet's keys), register the shared rules under
|
|
103
|
+
the repository's own plugin instead, next to its own rules:
|
|
104
|
+
`plugins: { myrepo: { meta: { name: 'myrepo' }, rules: { ...ownRules, 'import-js-suffix': importSuffix, 'no-untracked-todo': noUntrackedTodo } } }`
|
|
105
|
+
(`import { importSuffix, noUntrackedTodo } from '@kainappsinc/factory/eslint'`).
|
|
106
|
+
|
|
107
|
+
4. `.dependency-cruiser.cjs`, if the repository has one, can build its rules from the shared
|
|
108
|
+
shapes (below).
|
|
109
|
+
|
|
110
|
+
5. CI (GitLab): the `kainapps/ci-templates` components run the ratchet and risk jobs with the
|
|
111
|
+
repository's `bun run factory`:
|
|
112
|
+
|
|
113
|
+
```yaml
|
|
114
|
+
include:
|
|
115
|
+
- component: $CI_SERVER_FQDN/kainapps/ci-templates/factory-gates@1.2.1
|
|
116
|
+
inputs: { stage: check, install: bun install --frozen-lockfile }
|
|
117
|
+
- component: $CI_SERVER_FQDN/kainapps/ci-templates/factory-risk@1.2.1
|
|
118
|
+
inputs: { stage: check, install: bun install --frozen-lockfile }
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
`factory:ratchet` runs `ratchet --against origin/<target branch>` on a branch and plain
|
|
122
|
+
`ratchet` on the default branch; `factory:risk` runs `risk --base origin/<target branch>` and
|
|
123
|
+
writes `factory-risk.json` and `FACTORY_RISK_ZONES`. Both need the installed package (the CLI
|
|
124
|
+
lives in `node_modules`), so each needs a real `install` (as above); with `install: ""` the job
|
|
125
|
+
fails with "command not found" (exit 127).
|
|
126
|
+
|
|
127
|
+
## Migrating from a vendored copy
|
|
128
|
+
|
|
129
|
+
A repository that copied the factory scripts in (for example `factory/packs/ts-bun/*.ts`) moves to
|
|
130
|
+
the package in two merge requests, because a merge request is judged by the **target** branch's
|
|
131
|
+
`factory.yaml` (`ratchet --against`): while the target's `eslint` or `boundaries` definition still
|
|
132
|
+
runs the vendored path, a branch without that file cannot be counted by it.
|
|
133
|
+
|
|
134
|
+
1. The merge request that adopts the package points `factory.yaml` at the package bins
|
|
135
|
+
(`bun run factory-eslint-counts`, `bun run factory-depcruise-counts`) and deletes the vendored
|
|
136
|
+
code, but leaves a thin shim at each old counter path, calling the package's `main()`:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
// factory/packs/ts-bun/eslint-counts.ts: remove once the target's factory.yaml runs the package bin.
|
|
140
|
+
import { main } from '@kainappsinc/factory/ts-bun/eslint-counts';
|
|
141
|
+
process.exit(await main(process.argv.slice(2)));
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
(`depcruise-counts.ts` the same, from `@kainappsinc/factory/ts-bun/depcruise-counts`.) The
|
|
145
|
+
changed definition is reported as `CHANGED`; the shims let the target's definition still count.
|
|
146
|
+
2. Once that has merged, a follow-up merge request deletes the shims.
|
|
147
|
+
|
|
148
|
+
## Commands
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
factory check [--tier fast|full] [--only id,...] [--json evidence.json]
|
|
152
|
+
factory ratchet [--update [--allow-increase]] [--against <git-ref>] [--only <id>]
|
|
153
|
+
factory risk --base origin/main [--head <ref>] [--json] [--fail-on-risk]
|
|
154
|
+
factory validate
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
- `check` runs the gates in order and keeps going after a failure; `--tier fast` runs only the
|
|
158
|
+
fast gates (the inner loop), the full tier runs all.
|
|
159
|
+
- `ratchet` counts each ratchet and compares it with `<baselines_dir>/<id>.json`
|
|
160
|
+
(default `factory/baselines`).
|
|
161
|
+
- `risk` lists the files a change touches by risk zone. Zones come from `factory.yaml` at the base
|
|
162
|
+
ref, so a change cannot remove itself from a zone. Without `--head` it includes uncommitted and
|
|
163
|
+
untracked files.
|
|
164
|
+
- `validate` checks the manifest and notes globs that match no file.
|
|
165
|
+
|
|
166
|
+
Exit codes: 0 ok, 1 a gate or ratchet failed, 2 usage or manifest error, 3 risk (`--fail-on-risk`).
|
|
167
|
+
|
|
168
|
+
### When a ratchet fails
|
|
169
|
+
|
|
170
|
+
- **Over** (`FAIL as-any: 6 -> 7 (+1)`): an occurrence was added. The message says why the rule
|
|
171
|
+
exists and lists the matches, changed files first. Fix the code; do not raise the baseline.
|
|
172
|
+
- **Stale** (`6 -> 5 (-1): ... the baseline is stale`): one was removed. Run
|
|
173
|
+
`ratchet --update` and commit the baseline, so the slack cannot be spent again.
|
|
174
|
+
- **Raised against the target**: a branch may not raise its own baseline, even if the count
|
|
175
|
+
matches. Restore the file from the target and bring the count down, or get an allowance first.
|
|
176
|
+
- **Removed ratchet**: put it back, or retire it on purpose under `retired:` (`id`, `why`).
|
|
177
|
+
|
|
178
|
+
Under `--against`, the target branch's definitions and baselines judge the change: a ratchet
|
|
179
|
+
whose regex or globs changed is also counted with the target's definition (`CHANGED`).
|
|
180
|
+
`--update` only ever lowers baselines; `--allow-increase` (raise or create) seeds a new ratchet,
|
|
181
|
+
or raises a baseline that an allowance covers.
|
|
182
|
+
|
|
183
|
+
### Raising a baseline (allowances)
|
|
184
|
+
|
|
185
|
+
A merge request cannot raise its own baseline, so the permission comes from the target branch, in
|
|
186
|
+
two steps:
|
|
187
|
+
|
|
188
|
+
1. A merge request that only adds an allowance to `factory.yaml` (it changes no count; keep
|
|
189
|
+
`factory.yaml` in a risk zone so a person reviews it):
|
|
190
|
+
|
|
191
|
+
```yaml
|
|
192
|
+
allowances:
|
|
193
|
+
- ratchet: eslint # a ratchet id
|
|
194
|
+
key: (suppressed) # optional; default total (pattern and max_lines ratchets have only total)
|
|
195
|
+
by: 1 # how much the baseline may rise
|
|
196
|
+
why: "src/x.ts must read process.env before config loads; see #123"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
2. After it is merged, the change that adds the occurrence runs
|
|
200
|
+
`ratchet --update --allow-increase --only <id>` and deletes the allowance in the same merge
|
|
201
|
+
request. `ratchet --against` prints `ALLOWED <id>: …` for the rise.
|
|
202
|
+
|
|
203
|
+
A rise of n on a key passes only if the target's allowances for that ratchet and key add up to at
|
|
204
|
+
least n, and the branch holds at most (that sum − n) for the key: a used allowance must be deleted
|
|
205
|
+
(or lowered by what was used), so it cannot be spent twice.
|
|
206
|
+
|
|
207
|
+
### Adding a ratchet
|
|
208
|
+
|
|
209
|
+
1. Add an entry under `ratchets:` with an `id`, a one-line `why` (printed on every failure) and
|
|
210
|
+
one counter:
|
|
211
|
+
- `pattern`: a JavaScript regex; the count is matching lines in `include` minus `exclude`.
|
|
212
|
+
- `max_lines: N`: the count is files in `include` minus `exclude` longer than N lines.
|
|
213
|
+
- `run`: a command printing `{"key": count, ...}`. Optional `show`: a command printed on
|
|
214
|
+
failure that lists the occurrences; `{keys}` in it becomes the keys that rose.
|
|
215
|
+
2. Run `factory ratchet --only <id>`: with no baseline yet it lists every match. Tighten the regex
|
|
216
|
+
until there are no false positives.
|
|
217
|
+
3. Seed it: `factory ratchet --update --allow-increase --only <id>`; commit the baseline.
|
|
218
|
+
|
|
219
|
+
Globs: `*` stays inside a path segment, `**` spans any number of segments (including none), `?`,
|
|
220
|
+
`[abc]` and `{a,b}` work, dotfiles are not special, no `!` (use `exclude`). Paths come from
|
|
221
|
+
`git ls-files` (tracked plus untracked, minus ignored), so `.gitignore` is honoured.
|
|
222
|
+
|
|
223
|
+
## The ts-bun counters
|
|
224
|
+
|
|
225
|
+
```sh
|
|
226
|
+
factory-eslint-counts [--cwd <dir>] [--config <file>] [--show <keys>] [<pattern>...]
|
|
227
|
+
factory-depcruise-counts [--config <file>] [--show <rules>] [<path>...]
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
- `factory-eslint-counts` prints every enabled rule with its count, 0 included (so a rule's first
|
|
231
|
+
violation is a rise on a known key), plus `(parse-error)`, `(unused-directive)` and
|
|
232
|
+
`(suppressed)`: an inline `eslint-disable` still counts. It uses the ESLint installed for
|
|
233
|
+
`--cwd`.
|
|
234
|
+
- `factory-depcruise-counts` prints every `forbidden` rule of `.dependency-cruiser.cjs` (or
|
|
235
|
+
`--config`) with its violation count, 0 included, plus `(unresolved)`: imports that resolve to
|
|
236
|
+
no file, so a broken alias cannot hide edges.
|
|
237
|
+
- `--show` prints the occurrences of the given keys (the ratchet's `show:` command).
|
|
238
|
+
|
|
239
|
+
Both exit 1 when the tool fails (bad config, no files), so a broken counter never reads as zero.
|
|
240
|
+
From a `factory.yaml`, call them as `bun run factory-eslint-counts …` (package bins are on the
|
|
241
|
+
path only through `bun run`).
|
|
242
|
+
|
|
243
|
+
## ESLint rules
|
|
244
|
+
|
|
245
|
+
`@kainappsinc/factory/eslint` exports the plugin (default; rules under the `factory/` prefix when
|
|
246
|
+
registered as `factory`), the `rules` record, and each rule. Every rule takes a `messages` option
|
|
247
|
+
(message id → text, `{{name}}` placeholders filled from the report) so a repository can name its
|
|
248
|
+
own replacement.
|
|
249
|
+
|
|
250
|
+
| Rule | Flags | Options |
|
|
251
|
+
|---|---|---|
|
|
252
|
+
| `import-suffix` | relative imports without the convention's suffix (`missing`), or with the other one (`wrong`) | `suffix`: `'js'` (default: `./x.js` names `x.ts`; `.js`, `.mjs`, `.cjs`, `.json` allowed) or `'ts'` (the source by its own name; `.ts`, `.tsx`, `.mjs`, `.cjs`, `.json` allowed); `messages: { missing, wrong }` (`{{spec}}` available) |
|
|
253
|
+
| `no-json-parse-cast` | `JSON.parse(s) as T`, `<T>JSON.parse(s)`, `const x: T = JSON.parse(s)` (`unknown` and `as const` pass) | `messages: { cast }` |
|
|
254
|
+
| `no-raw-request-json` | `req.json()`, `request.json()`, `ctx.req.json()`: a request body read without a bound or validation | `requestNames` (default `['req', 'request']`); `messages: { raw }` |
|
|
255
|
+
| `no-untracked-todo` | `TODO`/`FIXME`/`HACK`/`XXX` comments without `#123`, `group/repo#123` or a URL | `messages: { untracked }` (`{{marker}}` available) |
|
|
256
|
+
|
|
257
|
+
Example: `'factory/no-raw-request-json': ['error', { messages: { raw: 'Use parseBody(req, schema) from src/http.ts, which validates and answers 400.' } }]`.
|
|
258
|
+
|
|
259
|
+
`@kainappsinc/factory/eslint/config` has `baseConfig({ files, plugins, rules })` (eslint,
|
|
260
|
+
typescript-eslint and eslint-comments recommended, unused disable directives as errors,
|
|
261
|
+
`BASE_RULES`), `testConfig({ files, plugins, rules })` (`TEST_RULES`: `any`, `require`,
|
|
262
|
+
generators without `yield` and directives without a reason allowed) and `loadTypeScriptEslint()`.
|
|
263
|
+
Not type-aware: typed linting costs gigabytes of memory under Bun.
|
|
264
|
+
|
|
265
|
+
For rule authors: `@kainappsinc/factory/eslint/ast` (defensive AST accessors that see the
|
|
266
|
+
TypeScript nodes too) and `@kainappsinc/factory/eslint/tester` (a TypeScript-parsing `RuleTester`
|
|
267
|
+
wired to `bun:test`; its parser comes from `typescript-eslint`).
|
|
268
|
+
|
|
269
|
+
## dependency-cruiser rule shapes
|
|
270
|
+
|
|
271
|
+
```js
|
|
272
|
+
const { layerRules, noTestImportsInProduction, noValueCycles, TYPE_EDGES } = require('@kainappsinc/factory/depcruise');
|
|
273
|
+
const TESTS = '(^|/)__tests__/|\\.test\\.ts$';
|
|
274
|
+
const LAYERS = [ // lowest first
|
|
275
|
+
{ name: 'infra', path: '^src/infra/', fix: 'move the shared piece down, or inject it' },
|
|
276
|
+
{ name: 'domain', path: '^src/domain/', fix: 'depend on an interface and inject it' },
|
|
277
|
+
{ name: 'app', path: '^src/main\\.ts$', fix: '' },
|
|
278
|
+
];
|
|
279
|
+
module.exports = {
|
|
280
|
+
forbidden: [
|
|
281
|
+
...layerRules(LAYERS, { tests: TESTS }),
|
|
282
|
+
noTestImportsInProduction({ from: '^src/', tests: TESTS }),
|
|
283
|
+
noValueCycles({ from: '^src/', tests: TESTS }),
|
|
284
|
+
],
|
|
285
|
+
options: { tsPreCompilationDeps: true, tsConfig: { fileName: 'tsconfig.json' } },
|
|
286
|
+
};
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
- `layerRules(layers, { tests, typeImportsUpTo, doc })`: one rule `layer-<name>` per layer: no
|
|
290
|
+
import into a higher layer (or into the layer's own `to` paths). With
|
|
291
|
+
`typeImportsUpTo: '<layer>'`, `import type` may reach upward into the layers below that one.
|
|
292
|
+
`doc` (default `factory/BOUNDARIES.md`) is named in the comment.
|
|
293
|
+
- `noTestImportsInProduction({ from, tests, describe })` and `noValueCycles({ from, tests })`.
|
|
294
|
+
|
|
295
|
+
The module is plain CommonJS, so the `depcruise` CLI can load the config under Node too.
|
|
296
|
+
|
|
297
|
+
## TypeScript 7
|
|
298
|
+
|
|
299
|
+
TypeScript 7.0's npm package has no JavaScript compiler API. typescript-eslint and
|
|
300
|
+
dependency-cruiser need one, so when the installed `typescript` lacks it, the counters, the ESLint
|
|
301
|
+
config helper and the rule tester load the classic compiler from the `typescript-classic` alias
|
|
302
|
+
for their own process (`@kainappsinc/factory/ts-bun/classic-typescript`; `tsc` keeps running 7.x).
|
|
303
|
+
Under Bun a runtime plugin covers `require('typescript')` and `import 'typescript'`; not covered:
|
|
304
|
+
`typescript/lib/tsserverlibrary` (type-aware linting). With TypeScript 6 or earlier installed,
|
|
305
|
+
nothing is replaced and the alias is not needed.
|
|
306
|
+
|
|
307
|
+
## Developing
|
|
308
|
+
|
|
309
|
+
```sh
|
|
310
|
+
bun install
|
|
311
|
+
bun test # never as root: some tests rely on file modes
|
|
312
|
+
bun run typecheck
|
|
313
|
+
bun run lint
|
|
314
|
+
bun run factory check # this package gates itself (factory.yaml)
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
## Releasing
|
|
318
|
+
|
|
319
|
+
1. Bump `version` in `package.json` in a merge request; merge it.
|
|
320
|
+
2. Tag the merge commit `vX.Y.Z` (the same version) and push the tag. The `publish` job checks
|
|
321
|
+
that the tag matches `package.json` and that the version is not on npm yet, then publishes.
|
|
322
|
+
|
|
323
|
+
The job authenticates one of two ways:
|
|
324
|
+
|
|
325
|
+
- **`NPM_TOKEN`** (works today): a CI/CD variable, masked and protected, holding a granular npm
|
|
326
|
+
access token with read and write access to `@kainappsinc/factory`. Protect the `v*` tags
|
|
327
|
+
(Settings → Repository → Protected tags) so the protected variable reaches the tag pipeline.
|
|
328
|
+
No provenance is published on this path.
|
|
329
|
+
- **Trusted publishing (OIDC)**, used when `NPM_TOKEN` is unset: npm exchanges the job's
|
|
330
|
+
`NPM_ID_TOKEN` (audience `npm:registry.npmjs.org`) for a short-lived publish credential and
|
|
331
|
+
publishes provenance. npm documents this for GitLab.com shared runners only ("Self-hosted
|
|
332
|
+
runners are not currently supported"), so the `publish` job is tagged for a GitLab.com hosted
|
|
333
|
+
runner and shared runners are enabled on this project. To use it: on npmjs.com, package settings
|
|
334
|
+
→ Trusted publisher → GitLab CI/CD, namespace `kainapps`, project `factory`, top-level CI file
|
|
335
|
+
`.gitlab-ci.yml`, allow `npm publish`; publish once within two days
|
|
336
|
+
(an unused configuration expires); then delete `NPM_TOKEN` and set Publishing access to "Require
|
|
337
|
+
two-factor authentication and disallow tokens".
|
|
338
|
+
|
|
339
|
+
**The first publish** cannot use trusted publishing: a trusted publisher is configured in the
|
|
340
|
+
settings of a package that already exists. Publish 0.1.0 once by hand from a clean checkout of the
|
|
341
|
+
`v0.1.0` tag, logged in as an owner of the `@kainappsinc` scope (`npm login`, then
|
|
342
|
+
`npm publish --access public`, with the one-time password), or set `NPM_TOKEN` to a granular token
|
|
343
|
+
allowed to publish in the scope and push the tag. Later releases go through the `publish` job.
|
package/package.json
CHANGED
|
@@ -1,6 +1,78 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kainappsinc/factory",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Software factory kit: a gate runner, debt ratchets that only go down, risk zones, shared ESLint rules and the ts-bun stack pack. Runs on Bun.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://gitlab.com/kainapps/factory.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://gitlab.com/kainapps/factory#readme",
|
|
12
|
+
"bugs": "https://gitlab.com/kainapps/factory/-/issues",
|
|
13
|
+
"keywords": ["ratchet", "quality-gates", "eslint", "dependency-cruiser", "bun", "ci"],
|
|
14
|
+
"engines": {
|
|
15
|
+
"bun": ">=1.3.0"
|
|
16
|
+
},
|
|
17
|
+
"bin": {
|
|
18
|
+
"factory": "./src/cli/index.ts",
|
|
19
|
+
"factory-eslint-counts": "./src/packs/ts-bun/eslint-counts.ts",
|
|
20
|
+
"factory-depcruise-counts": "./src/packs/ts-bun/depcruise-counts.ts"
|
|
21
|
+
},
|
|
22
|
+
"exports": {
|
|
23
|
+
"./cli": "./src/cli/main.ts",
|
|
24
|
+
"./schema.json": "./src/cli/factory.schema.json",
|
|
25
|
+
"./ts-bun/classic-typescript": "./src/packs/ts-bun/classic-typescript.ts",
|
|
26
|
+
"./ts-bun/counter-cli": "./src/packs/ts-bun/counter-cli.ts",
|
|
27
|
+
"./ts-bun/eslint-counts": "./src/packs/ts-bun/eslint-counts.ts",
|
|
28
|
+
"./ts-bun/depcruise-counts": "./src/packs/ts-bun/depcruise-counts.ts",
|
|
29
|
+
"./eslint": "./src/eslint/index.ts",
|
|
30
|
+
"./eslint/config": "./src/eslint/config.ts",
|
|
31
|
+
"./eslint/ast": "./src/eslint/ast.ts",
|
|
32
|
+
"./eslint/tester": "./src/eslint/tester.ts",
|
|
33
|
+
"./depcruise": {
|
|
34
|
+
"types": "./src/depcruise/index.d.cts",
|
|
35
|
+
"default": "./src/depcruise/index.cjs"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"src/",
|
|
41
|
+
"!src/**/__tests__/",
|
|
42
|
+
"README.md",
|
|
43
|
+
"CHANGELOG.md",
|
|
44
|
+
"LICENSE"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"factory": "bun src/cli/index.ts",
|
|
48
|
+
"typecheck": "tsc --noEmit",
|
|
49
|
+
"lint": "bun --bun eslint",
|
|
50
|
+
"test": "bun test"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@eslint-community/eslint-plugin-eslint-comments": "^4.8.1",
|
|
54
|
+
"@eslint/js": "^9.39.5",
|
|
55
|
+
"dependency-cruiser": "^18.8.0",
|
|
56
|
+
"eslint": "^9.39.5",
|
|
57
|
+
"typescript": ">=5.0.0",
|
|
58
|
+
"typescript-eslint": "^8.73.0"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"@eslint-community/eslint-plugin-eslint-comments": { "optional": true },
|
|
62
|
+
"@eslint/js": { "optional": true },
|
|
63
|
+
"dependency-cruiser": { "optional": true },
|
|
64
|
+
"eslint": { "optional": true },
|
|
65
|
+
"typescript": { "optional": true },
|
|
66
|
+
"typescript-eslint": { "optional": true }
|
|
67
|
+
},
|
|
68
|
+
"devDependencies": {
|
|
69
|
+
"@eslint-community/eslint-plugin-eslint-comments": "^4.8.1",
|
|
70
|
+
"@eslint/js": "^9.39.5",
|
|
71
|
+
"@types/bun": "^1.3.11",
|
|
72
|
+
"dependency-cruiser": "^18.8.0",
|
|
73
|
+
"eslint": "^9.39.5",
|
|
74
|
+
"typescript": "7.0.2",
|
|
75
|
+
"typescript-classic": "npm:typescript@~6.0.3",
|
|
76
|
+
"typescript-eslint": "^8.73.0"
|
|
77
|
+
}
|
|
78
|
+
}
|
package/src/cli/args.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { FactoryError } from './io.js';
|
|
2
|
+
|
|
3
|
+
export type FlagSpec = Record<string, 'string' | 'boolean'>;
|
|
4
|
+
export type Flags = Record<string, string | boolean | undefined>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parses `--name value`, `--name=value` and boolean `--name`. Unknown flags and
|
|
8
|
+
* positional arguments are usage errors: a typo must not silently change what runs.
|
|
9
|
+
*/
|
|
10
|
+
export function parseFlags(command: string, argv: readonly string[], spec: FlagSpec): Flags {
|
|
11
|
+
const flags: Flags = {};
|
|
12
|
+
for (let i = 0; i < argv.length; i++) {
|
|
13
|
+
const arg = argv[i] ?? '';
|
|
14
|
+
if (!arg.startsWith('--')) {
|
|
15
|
+
throw new FactoryError(`factory ${command}: unexpected argument "${arg}" (flags start with --; see factory help)`);
|
|
16
|
+
}
|
|
17
|
+
const eq = arg.indexOf('=');
|
|
18
|
+
const name = arg.slice(2, eq === -1 ? undefined : eq);
|
|
19
|
+
const kind = spec[name];
|
|
20
|
+
if (!kind) {
|
|
21
|
+
const known = Object.keys(spec).map((k) => `--${k}`).join(', ') || 'none';
|
|
22
|
+
throw new FactoryError(`factory ${command}: unknown flag --${name} (known: ${known})`);
|
|
23
|
+
}
|
|
24
|
+
if (kind === 'boolean') {
|
|
25
|
+
if (eq !== -1) throw new FactoryError(`factory ${command}: --${name} takes no value`);
|
|
26
|
+
flags[name] = true;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
// `--name=value`, or `--name value` (which consumes the next argument)
|
|
30
|
+
const value = eq !== -1 ? arg.slice(eq + 1) : argv[++i];
|
|
31
|
+
if (value === undefined || value === '' || value.startsWith('--')) {
|
|
32
|
+
throw new FactoryError(`factory ${command}: --${name} needs a value`);
|
|
33
|
+
}
|
|
34
|
+
flags[name] = value;
|
|
35
|
+
}
|
|
36
|
+
return flags;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function stringFlag(flags: Flags, name: string): string | undefined {
|
|
40
|
+
const v = flags[name];
|
|
41
|
+
return typeof v === 'string' ? v : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** `a,b , c` -> ['a','b','c'] */
|
|
45
|
+
export function listFlag(flags: Flags, name: string): string[] | undefined {
|
|
46
|
+
const v = stringFlag(flags, name);
|
|
47
|
+
return v === undefined ? undefined : v.split(',').map((s) => s.trim()).filter(Boolean);
|
|
48
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export type Counts = Record<string, number>;
|
|
5
|
+
export interface Baseline { id: string; counts: Counts }
|
|
6
|
+
|
|
7
|
+
/** A count is a non-negative integer. */
|
|
8
|
+
export function isCount(v: unknown): v is number {
|
|
9
|
+
return typeof v === 'number' && Number.isInteger(v) && v >= 0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function baselinePath(baselinesDir: string, id: string): string {
|
|
13
|
+
return `${baselinesDir}/${id}.json`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Stable text: two-space JSON, keys sorted, trailing newline. */
|
|
17
|
+
export function formatBaseline(id: string, counts: Counts): string {
|
|
18
|
+
const sorted: Counts = {};
|
|
19
|
+
for (const k of Object.keys(counts).sort()) sorted[k] = counts[k] ?? 0;
|
|
20
|
+
return `${JSON.stringify({ id, counts: sorted }, null, 2)}\n`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Parses baseline text; returns an error string instead of throwing. */
|
|
24
|
+
export function parseBaseline(text: string, id: string, source: string): Baseline | string {
|
|
25
|
+
let raw: unknown;
|
|
26
|
+
try { raw = JSON.parse(text); } catch (e) { return `${source} is not valid JSON: ${(e as Error).message}`; }
|
|
27
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return `${source}: expected {"id": "${id}", "counts": {...}}`;
|
|
28
|
+
const obj = raw as Record<string, unknown>;
|
|
29
|
+
if (obj.id !== id) return `${source}: "id" is ${JSON.stringify(obj.id)}, expected "${id}" (the file name and the id must agree)`;
|
|
30
|
+
const counts = obj.counts;
|
|
31
|
+
if (typeof counts !== 'object' || counts === null || Array.isArray(counts)) return `${source}: "counts" must be an object of key -> count`;
|
|
32
|
+
const out: Counts = {};
|
|
33
|
+
for (const [k, v] of Object.entries(counts)) {
|
|
34
|
+
if (!isCount(v)) return `${source}: counts.${k} must be a non-negative integer, got ${JSON.stringify(v)}`;
|
|
35
|
+
out[k] = v;
|
|
36
|
+
}
|
|
37
|
+
return { id, counts: out };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function readBaseline(root: string, baselinesDir: string, id: string): Baseline | string | null {
|
|
41
|
+
const rel = baselinePath(baselinesDir, id);
|
|
42
|
+
const abs = join(root, rel);
|
|
43
|
+
if (!existsSync(abs)) return null;
|
|
44
|
+
return parseBaseline(readFileSync(abs, 'utf8'), id, rel);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function writeBaseline(root: string, baselinesDir: string, id: string, counts: Counts): void {
|
|
48
|
+
mkdirSync(join(root, baselinesDir), { recursive: true });
|
|
49
|
+
writeFileSync(join(root, baselinePath(baselinesDir, id)), formatBaseline(id, counts));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Ids of baseline files present on disk. */
|
|
53
|
+
export function baselineIds(root: string, baselinesDir: string): string[] {
|
|
54
|
+
const dir = join(root, baselinesDir);
|
|
55
|
+
if (!existsSync(dir)) return [];
|
|
56
|
+
return readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)).sort();
|
|
57
|
+
}
|