@byronbroughten/code-style 0.0.0-stage → 0.1.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/README.md +27 -2
- package/docLint.js +451 -0
- package/docs/code-style/class-shape.md +63 -0
- package/docs/code-style/comments.md +15 -0
- package/docs/code-style/error-handling.md +11 -0
- package/docs/code-style/file-organization.md +20 -0
- package/docs/code-style/idioms.md +30 -0
- package/docs/code-style/naming.md +82 -0
- package/docs/code-style/tests.md +33 -0
- package/docs/code-style/type-modeling.md +26 -0
- package/docs/code-style.md +117 -0
- package/eslint/noCrossPackageImport.js +62 -0
- package/eslint/privateHelperUsesThis.js +58 -0
- package/eslint.js +111 -0
- package/lintDocs.js +60 -0
- package/package.json +68 -4
- package/prettier.json +4 -0
- package/tsconfig.base.json +16 -0
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Naming
|
|
2
|
+
|
|
3
|
+
Style fragment. The one-line rules live in [`docs/code-style.md`](../code-style.md); this file holds the reasoning and the worked examples.
|
|
4
|
+
|
|
5
|
+
The first heading is Class shape's collaborator-naming rule; the rest follow docs/code-style.md's Naming section in order, and the destructure rule's two sequels, hoisting one argument and grouping fields, have headings of their own. Grep `^## ` for the rule you're applying and read that section.
|
|
6
|
+
|
|
7
|
+
## A collaborator is `<Subject><Role>`
|
|
8
|
+
|
|
9
|
+
**A collaborator is named `<Subject><Role>`, plus the tier suffix where the codebase has tiers.** The subject is a word from the glossary of the code it serves, saying which part of the work it handles; the role is an agent noun saying what it does there (`TicketLander`, `HaltRaiser`), or a plain descriptive noun where no verb fits (`RunLoop`). It takes no coordinator prefix, since the subfolder named after the coordinator already groups them. A codebase with tiers ends the name on the tier word, as its own naming doc says; the runner has no tiers, so its collaborators stop at the role. A role can't reuse another glossary term's word: `SpecRun`'s split has no `Implementer`, the implement agent's name as a fixer, and nothing ending in `Runner`, the glossary's word for the whole tool (#344).
|
|
10
|
+
|
|
11
|
+
## Prefer TS/JS vocabulary over a made-up adjective
|
|
12
|
+
|
|
13
|
+
**Prefer a term from TS/JS's own vocabulary over a made-up adjective, once one fits.** `PureValue` named the `string | number | boolean` family after a vague "pure" adjective; renamed to `PrimitiveValue` once it was clear that's exactly what the set is — no invented term needed when the language already has one.
|
|
14
|
+
|
|
15
|
+
## Name a value after the domain type it holds
|
|
16
|
+
|
|
17
|
+
**Name a value after the domain type it holds, not a generic container word.** `entries`, `results`, `data` describe the shape (a container) but not what's in it; prefer the name that matches the actual type/concept, especially when that type already has a name elsewhere in the codebase. `rowEntries()` → `newRowConfigs()` (returns what becomes `rowConfigs.ts`), its local `entries` → `rowConfigs`, and the per-table `tableEntries` → `tableRowConfigs` (matching the `TableRowConfigs` type each value actually is).
|
|
18
|
+
|
|
19
|
+
## A boolean is a third-person statement
|
|
20
|
+
|
|
21
|
+
**A boolean is named as a third-person statement about its subject, never a bare adjective.** `is` and `has` are the usual verbs — `isActive`, `isFormula`, `hasValue`, `hasIdColumn` — but they're the common case, not the rule; reach for whatever verb states the thing plainly. `isRunOnUncheck` names a property of the flag rather than a behaviour of its subject, and is wrong for that reason. Such a flag defaults to `false`, so its absence means the ordinary behaviour and it only ever appears where it's doing something.
|
|
22
|
+
|
|
23
|
+
### A config-literal flag is an imperative directive
|
|
24
|
+
|
|
25
|
+
**An optional flag in a config literal is the exception: it is an imperative directive to whatever reads the literal, not a statement about the thing it sits on.** A handler entry's flags are `retainSelection`, `requireOneRow`, `runOnUncheck` — retain the selection, require one row, run on uncheck. They read as third-person statements first (`retainsSelection`, `runsOnUncheck`), which was defensible one flag at a time and stopped being so once a flag arrived — `requireOneRow` — that commands something the runtime does rather than describing something the entry is. Mixing the two moods in one literal makes a reader work out which flags command and which describe, so the whole set takes the imperative.
|
|
26
|
+
|
|
27
|
+
## A plural method name promises more of the same
|
|
28
|
+
|
|
29
|
+
**A plural method name promises more of the same return, not a different container.** `rowByValue` finds one row by a value, so `rowsByValue` could only mean every row matching a value. When the plural would change the shape rather than the count, it needs its own name.
|
|
30
|
+
|
|
31
|
+
## Trim a method name to what its return type doesn't say
|
|
32
|
+
|
|
33
|
+
**Trim a method name to what the return type doesn't already say.** `generateConfigFilesSources` became `generateConfigFiles`: the return type already says they are sources.
|
|
34
|
+
|
|
35
|
+
## A name reads to a newcomer
|
|
36
|
+
|
|
37
|
+
**A name has to read to someone who has never opened this codebase.** A flag named after the mechanism that sets it becomes jargon at every call site that isn't that mechanism. Prefer the word a newcomer would guess: a row held even though it looks empty is `isReserved`, not `claimed`.
|
|
38
|
+
|
|
39
|
+
## Constants are camelCase and grouped
|
|
40
|
+
|
|
41
|
+
**A constant is camelCase, and two or more in one file that serve one purpose become one `as const` object named for that purpose.** SCREAMING constants spent the shout on values that need no warning, so the name of a destructive bulk delete stopped standing out; camelCase leaves the shout to that one method. Grouping names the purpose once instead of repeating it as a suffix on every sibling: `USER_FIELDS`, `ORDER_FIELDS` and the rest became `fieldMasks.user` and friends, and a summary's four widths and caps became `layoutLimits`. A constant with no sibling stays a plain `const` (`apiBase`). An external API's enum strings (`"CUSTOM_FORMULA"`, `"NUMBER_EQ"`) are values, not names, and keep the API's spelling. `@typescript-eslint/naming-convention` holds variables to camelCase or PascalCase and rejects an all-caps word, and leaves method names free so a deliberately shouted method still passes.
|
|
42
|
+
|
|
43
|
+
## Our own properties are camelCase
|
|
44
|
+
|
|
45
|
+
**A property of a record or schema we define is camelCase; one mirroring an external wire shape keeps that API's spelling.** The runner's types for Claude's stream (`input_tokens`, `session_id`) and GitHub's API (`sub_issues_summary`) copy names another system chose, so they keep them. The implement record is our own contract, yet it first landed as `closing_comment` and `files_to_open` because a spec's sketch spelled it that way, and the runner had to map each field back to camelCase until the record was renamed. Lint's `naming-convention` covers variables only, so this rule rests on the spec and on review.
|
|
46
|
+
|
|
47
|
+
## Parens mean expensive
|
|
48
|
+
|
|
49
|
+
**Getters are for no-arg, side-effect-free derived values that might need re-deriving from updated state** (`get schema`, `get client` — each rebuilds from `this.props`, which can reflect state mutated since construction). Anything that takes an argument or has a side effect is a method, never a getter. And a value that's genuinely fixed for the object's whole lifetime (e.g. a file path built once from `import.meta.url`) is a plain field computed once, not a getter recomputed on every read.
|
|
50
|
+
|
|
51
|
+
**Such a value is a getter unless computing it is expensive: a round trip (Sheets, Apps Script, fetch, Drive) or a nested loop over a whole sheet's rows.** Loops and branches don't make it expensive. `TableBaseIdentified.get knownTableId()` branches on the Table's address and `TableIdentified.get blankTestColumnIds()` filters the column ids, and both stay getters. `GoogleSheetsAPI.fetchTimeZone()` reads the spreadsheet over the API, so it keeps its `()`. The parens are the reader's signal that this access costs something worth not repeating.
|
|
52
|
+
|
|
53
|
+
**A collaborator, an instance of one of this codebase's classes, is always a getter, never a cached field.** Building one is a cheap `new`, so caching saves nothing, and whether a cached one goes stale depends on its constructor, not on what you pass it. `TableBaseIdentified.rawTable` was briefly a field built from the Table's address alone, but `TableBaseRaw`'s constructor looks up `sheetGid` from state, so the cached copy would keep an old lookup.
|
|
54
|
+
|
|
55
|
+
## The `_` prefix: narrow-purpose, not general API
|
|
56
|
+
|
|
57
|
+
**`_` prefix means "narrow-purpose, not general API," and shows up in two shapes:**
|
|
58
|
+
1. A true private helper, decomposing a public method — pair it with the `private` keyword.
|
|
59
|
+
2. A method that a coordinating/encapsulating class must call as one step of a specific flow, but that isn't meant as general-purpose API on its own class. It *can't* be marked `private` (TS blocks cross-class access even from a coordinator), so the leading `_` is the only signal a future caller gets that this isn't for general use. Example: `TableMeta._gatherPrerequisites` is called by `Workbook.fetchAll` as one step sandwiched between two ordinary public methods (`gatherInputs`, `finalizeResults`) — it's underscored precisely because it only makes sense inside that one flow.
|
|
60
|
+
|
|
61
|
+
This case-2 underscore is about the method's *concept* being orchestration-only, not about how many callers it happens to have today. A method that instead reads as ordinary domain vocabulary for the class it's on — because it matches an existing naming family already used for sibling members — stays unprefixed even with exactly one current caller. `ColumnMeta.activeTitle()` is called from several emitters, but it's a plain public method, not `_activeTitle` — it fits the same `active*` family as `activeHeader`/`activeIsFormula` on the same class, so it reads as a legitimate query on the column itself rather than a glue step of someone else's flow.
|
|
62
|
+
|
|
63
|
+
## Destructure params or stay positional
|
|
64
|
+
|
|
65
|
+
**Param style: destructure into a named type when the params already justify grouping; otherwise stay positional.** Destructure + a type (existing or newly introduced) when there are 3+ params, or 2+ params of the same type, or a named type for the bag already exists elsewhere. Otherwise keep params positional. Example (`Workbook._prepFetch` and the module function `prepRow` below it):
|
|
66
|
+
```ts
|
|
67
|
+
private _prepFetch({ rowSpecifier, columnNames }: FetchProps): void
|
|
68
|
+
```
|
|
69
|
+
destructures because `FetchProps` already exists as a named type — the method just unpacks an existing concept. Compare a case that stays positional because nothing ties the params together as one concept — three unrelated single-use values, no shared type:
|
|
70
|
+
```ts
|
|
71
|
+
function prepRow(table: Table, rowSpecifier: RowSpecifier, columnId: string): void
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**A symmetric comparator stays positional though its two params share a type.** The rule guards against swapped arguments, and swapping `isSame(a, b)`'s changes nothing, so a bag would add a type name and protect against nothing; the runner's `issueRef.isSame`, `workspaceKey.isSame` and `leaseHolder.isSame` are such comparators. One whose order matters is not exempt: `issueRef.outside` returns a different set when its two lists swap, so it takes `{ issues, excluded }: IssueExclusion` (#654).
|
|
75
|
+
|
|
76
|
+
## Hoist the argument every implementation uses
|
|
77
|
+
|
|
78
|
+
**The one argument every implementation will use is hoisted out of the bag and passed first, positionally.** The grouping rule above is about params that travel together; it doesn't apply to a collaborator that essentially every implementation of a signature needs. A handler's action takes the workbook first and its remaining inputs as a second destructured object, because every action needs the workbook and only some need the rest — burying it in the bag would make every implementation destructure to reach the thing it always wants.
|
|
79
|
+
|
|
80
|
+
## Group paired fields the same way
|
|
81
|
+
|
|
82
|
+
**The same grouping judgment applies to fields, not just method params.** Two or more naturally-paired values (e.g. a pair of output file paths) get grouped into one object property rather than kept as separate top-level members. A generator groups its three output paths as `path: { tables, columns, values }` rather than three separate `tablesPath`/`columnsPath`/`valuesPath` members.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Test code style
|
|
2
|
+
|
|
3
|
+
Disclosed from [`docs/code-style.md`](../code-style.md).
|
|
4
|
+
|
|
5
|
+
All of docs/code-style.md applies to test code as-is.
|
|
6
|
+
|
|
7
|
+
## Outcomes over calls
|
|
8
|
+
|
|
9
|
+
The settled rule in `docs/code-style.md` asks a test to assert what a caller can observe: a return value, the state a fake is left in, a message shown. A test that asserts which calls were made, how many, or with what arguments is coupled to the route the code takes, so it breaks when an internal refactor keeps the behaviour and passes when the calls are right but the outcome is wrong. A call count is the contract only when the count is what a caller pays for, such as round trips to a rate-limited API, and such a test says so in its name ("costs one read").
|
|
10
|
+
|
|
11
|
+
## A test pins the tunable default it depends on
|
|
12
|
+
|
|
13
|
+
A default such as a limit threshold gets tuned without touching any test. A test that leans on the default's current value, by reading 0.95 as "past the pause", breaks once the default moves above 0.95, even though the behaviour under test is unchanged. Pinning the setting in the test's fixture keeps the test's reading and the threshold it's measured against in one place, so a printed figure such as "95%" can stay a literal. A test whose subject is the default itself, such as "holds a step at the default 5-hour pause", reads the default instead of copying its number, so it follows each retune.
|
|
14
|
+
|
|
15
|
+
## Test speed
|
|
16
|
+
|
|
17
|
+
A package's tests run before any change to it, or to a package it depends on, is called done, so a cost in one test is paid on every such run, and a suite gets slow one reasonable-looking test at a time.
|
|
18
|
+
|
|
19
|
+
### A test starts a process only when that process is what it tests
|
|
20
|
+
|
|
21
|
+
Spawning a process costs far more than a function call, and most of a test's behaviour doesn't depend on it.
|
|
22
|
+
|
|
23
|
+
### A fixture costing more than a few milliseconds is built once per file and copied or reset for each test
|
|
24
|
+
|
|
25
|
+
Each test still starts from a clean fixture, and only the first pays to build it.
|
|
26
|
+
|
|
27
|
+
### A test never really waits: time goes through an injected clock or fake timers
|
|
28
|
+
|
|
29
|
+
A real wait costs its full length on every run, and one tuned to pass on a quiet machine flakes on a loaded one.
|
|
30
|
+
|
|
31
|
+
### A test reaches no network and opens no real port
|
|
32
|
+
|
|
33
|
+
Either one makes the result depend on what is outside the test, and a port also collides with the tests running beside it.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Type modeling: reasoning and examples
|
|
2
|
+
|
|
3
|
+
Disclosed from [`docs/code-style.md`](../code-style.md), "Type modeling". The rules are there, one line each; this file holds the why.
|
|
4
|
+
|
|
5
|
+
## `interface` or `type`
|
|
6
|
+
|
|
7
|
+
Unions, `keyof`, mapped types and utility types are `type`s. A plain object shape is an `interface`, which lint enforces, so props and state bags can chain through `extends`.
|
|
8
|
+
|
|
9
|
+
## Two-letter generic params
|
|
10
|
+
|
|
11
|
+
Each abbreviation is usually constrained with `extends <DomainType>`. Bare `T`/`K`/`V`/`O` belong to domain-free utilities.
|
|
12
|
+
|
|
13
|
+
Two letters, not one, even where one would be unambiguous: a lone `F` or `I` reads as a bare letter rather than an abbreviation.
|
|
14
|
+
|
|
15
|
+
## Specificity over branded fallbacks
|
|
16
|
+
|
|
17
|
+
A fallback value that explains the empty case still lets the case arise, and every reader of the value has to handle it; a type narrowed until the case can't arise makes the compiler rule it out. A branded fallback string also stops working, without any error, in constraint position: the intersection that satisfies the parent's constraint collapses it back to `never`.
|
|
18
|
+
|
|
19
|
+
## Lookup tables are keyed by the producer's union
|
|
20
|
+
|
|
21
|
+
A formatter once dispatched on a `switch` over the keys of an external `Request` type, whose every member is optional, ending in a `default` that printed raw JSON. The builders returned that same wide type, so nothing tied the kinds they produced to the cases the switch handled: a new kind compiled and silently rendered as JSON. The fix names the kinds on the producer side (a `RequestVerb` union next to the builders), types the builders to return only the modeled request, and annotates the formatter table with a mapped type over that union, so a missing or mistyped formatter fails `tsc`. The `default` survives only for requests the project doesn't build. Let the type, not the reader, carry the list of keys. The general hazard: a `default` over an optional-keyed type like `Request` compiles with any case missing.
|
|
22
|
+
|
|
23
|
+
## Use the named type that already exists
|
|
24
|
+
|
|
25
|
+
A field, return type or param bag that matches a named type uses it: `TableIdentity`, not `{ tableId: string; name: string }`.
|
|
26
|
+
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Coding style
|
|
2
|
+
|
|
3
|
+
Distilled from the author's own refactors of AI-generated code, plus a survey of a codebase for consistent, repeated patterns. This file covers general TypeScript code _shape_; a project's own rules layer on it.
|
|
4
|
+
|
|
5
|
+
One line per rule. The reasoning and worked examples are one file away. Open a reasoning file only when you're changing the rule, or the rule's line doesn't decide your case.
|
|
6
|
+
|
|
7
|
+
## Reasoning files
|
|
8
|
+
|
|
9
|
+
| When | File |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Placing a member, a helper or a class | [`docs/code-style/class-shape.md`](./code-style/class-shape.md) |
|
|
12
|
+
| Naming a value, method, flag, getter or param bag | [`docs/code-style/naming.md`](./code-style/naming.md) |
|
|
13
|
+
| A type-level choice, a lookup table, a named type | [`docs/code-style/type-modeling.md`](./code-style/type-modeling.md) |
|
|
14
|
+
| A shared message phrase, a skip-and-log | [`docs/code-style/error-handling.md`](./code-style/error-handling.md) |
|
|
15
|
+
| Writing or changing a test | [`docs/code-style/tests.md`](./code-style/tests.md) |
|
|
16
|
+
| A comment, or a file-level navigation block | [`docs/code-style/comments.md`](./code-style/comments.md) |
|
|
17
|
+
| A loop, `reduce`, a chaining mutator, a combined option, a ternary, a named state flag | [`docs/code-style/idioms.md`](./code-style/idioms.md) |
|
|
18
|
+
| Imports, barrels, file names | [`docs/code-style/file-organization.md`](./code-style/file-organization.md) |
|
|
19
|
+
|
|
20
|
+
## Class shape
|
|
21
|
+
|
|
22
|
+
- **Extract the shared piece once its second caller is in the code or an open ticket**, without waiting for it to arrive.
|
|
23
|
+
- **A class extends a Base for its identity and shared state, and gets its behaviour from collaborators it builds** ([why](./code-style/class-shape.md#inherit-identity-and-state-compose-behaviour)).
|
|
24
|
+
- **Member order:** `static init()`, then collaborator getters, then public behavior methods, then `_`-prefixed private helpers — a single-caller helper sits right after its caller.
|
|
25
|
+
- **A private helper that never reads `this` is an unexported module function below the class, not a `_` method**, ordered by first use. A helper that reads `this` only to reach a collaborator stays a method. Lint backs it for `private` and `#` methods.
|
|
26
|
+
- **A helper whose arguments are one collaborator and its state belongs on that collaborator.** A public method that doesn't read `this` stays put; a helper that only renames a function in scope is deleted.
|
|
27
|
+
- **Helpers sharing a subject and passing nothing between them become an object bundle.**
|
|
28
|
+
- **Helpers passing one value around become a helper class** in its own file.
|
|
29
|
+
- **Delete dead scaffolding in a file you touch**, but **ask before deleting commented-out code.** Zero callers is a list of candidates, not a verdict.
|
|
30
|
+
- **A "why" comment carries over verbatim across a restructure.**
|
|
31
|
+
- **One class per file, custom `Error` subclasses included.** Lint backs it.
|
|
32
|
+
- **Split a class into collaborators when its private helpers fall into groups that share nothing with each other**, not when it passes a method or line count ([why](./code-style/class-shape.md#split-a-class-when-its-helpers-fall-into-groups-that-share-nothing)).
|
|
33
|
+
- **The split class keeps its public methods as one-line delegations**, and its collaborators go in a subfolder named after it.
|
|
34
|
+
- **A Base class holds the coordinator's props and builds, in lazy getters, the helper classes more than one collaborator uses**; the coordinator and each collaborator extend it, and the helper classes don't ([why](./code-style/class-shape.md#a-split-class-shares-a-base-and-layers-its-collaborators)).
|
|
35
|
+
- **Collaborators layer without cycles: each builds the ones below it in lazy getters, and the Base never imports a collaborator**; a getter back to a coordinator that holds shared state is the one upward reference ([why](./code-style/class-shape.md#a-split-class-shares-a-base-and-layers-its-collaborators)).
|
|
36
|
+
- **A collaborator is named `<Subject><Role>`, plus the tier suffix where the codebase has tiers**: the role is an agent noun, or a plain descriptive noun where no verb fits ([why](./code-style/naming.md#a-collaborator-is-subjectrole)).
|
|
37
|
+
|
|
38
|
+
## Naming
|
|
39
|
+
|
|
40
|
+
- **Prefer a term from TS/JS's own vocabulary over a made-up adjective.**
|
|
41
|
+
- **Name a value after the domain type it holds, not a generic container word.**
|
|
42
|
+
- **A boolean is a third-person statement about its subject, never a bare adjective.** It defaults to `false`, so it appears only where it changes something.
|
|
43
|
+
- **A flag in a config literal is the exception: it is an imperative directive to whatever reads the literal**, one mood per literal.
|
|
44
|
+
- **A plural method name promises more of the same return, not a different container.**
|
|
45
|
+
- **Trim a method name to what the return type doesn't already say.**
|
|
46
|
+
- **A name has to read to someone who has never opened this codebase** — never jargon named after the mechanism that sets it.
|
|
47
|
+
- **A constant is camelCase; two or more in one file that serve one purpose become one `as const` object named for that purpose.** Lint backs the camelCase half.
|
|
48
|
+
- **A property of a record or schema we define is camelCase; one mirroring an external wire shape keeps that API's spelling.** Lint doesn't check properties.
|
|
49
|
+
- **A no-arg, side-effect-free member is a getter unless it costs a round trip or a nested loop over a whole sheet's rows**; a value fixed for the object's lifetime is a plain field ([why](./code-style/naming.md#parens-mean-expensive)).
|
|
50
|
+
- **`_` prefix means "narrow-purpose, not general API"**: a true `private` helper, or a step a coordinating class must call that TS won't let you mark `private`.
|
|
51
|
+
- **Destructure params into a named type at 3+ params, 2+ params of one type, or when a named type for the bag already exists**, except a symmetric comparator, whose arguments can swap; otherwise stay positional ([why](./code-style/naming.md#destructure-params-or-stay-positional)).
|
|
52
|
+
|
|
53
|
+
## Comments
|
|
54
|
+
|
|
55
|
+
- **Default to no comments.** When a block would need a comment saying _what_ it does, pull it into a small private method whose name says it.
|
|
56
|
+
- **A comment is one line explaining a "why not the obvious thing"**; a longer why goes in the doc that line links to, or isn't written.
|
|
57
|
+
- **The one multi-line exception is a file-level navigation block**, 5–10 lines above the exported class stating the file's job and where neighbouring work lives.
|
|
58
|
+
|
|
59
|
+
## Error handling & validation
|
|
60
|
+
|
|
61
|
+
- **A phrase that names the same thing in several messages or labels comes from one function.**
|
|
62
|
+
- **Default to a plain `throw new Error("specific message")`.** Mint a custom `Error` subclass only when callers need to catch the failure _category_ by type.
|
|
63
|
+
- **Guard-clause throws, never nested conditionals.** The one accepted exception is an exhaustiveness check, which ends in a trailing `else { throw new Error(...) }`.
|
|
64
|
+
- **Trace whether a "shouldn't happen" condition is actually reachable before defaulting to skip-and-log**; if upstream already guarantees it can't happen, throw.
|
|
65
|
+
|
|
66
|
+
## Type modeling
|
|
67
|
+
|
|
68
|
+
- **`type` for everything computed from other types.** A plain object shape is an `interface`; lint enforces it.
|
|
69
|
+
- **Generic params get two-letter domain abbreviations with a constraint**; bare `T`/`K`/`V`/`O` are only for domain-free utilities and tests; lint checks the two letters, not the constraint.
|
|
70
|
+
- **`undefined` is the one "absent" value; `null` appears only where an external API's types or JSON carry it.**
|
|
71
|
+
- **Narrow a type until the empty case can't arise, rather than a branded-string fallback.**
|
|
72
|
+
- **A per-kind lookup table is keyed by the finite union its producer returns, never a `switch` with a `default` over a wider type.**
|
|
73
|
+
- **An optional parameter that switches a function to a second job means it should be a second function.** Don't add an overload to loosen a constraint for one caller.
|
|
74
|
+
- **Use the named type that already exists instead of an inline shape**, for a field or return type as well as a param bag.
|
|
75
|
+
|
|
76
|
+
## Functional vs. imperative idioms
|
|
77
|
+
|
|
78
|
+
- **`map` only for pure transforms; a loop for side effects is `for…of`, never `forEach`** ([why](./code-style/idioms.md#forof-over-foreach)).
|
|
79
|
+
- **`for…in` only in a project's structural utilities.**
|
|
80
|
+
- **`reduce` is fully accepted** for building a new object/record, rather than a manual loop with a declared accumulator: seed a fresh `{}`, `new Map()` or `[]`, mutate it and return it.
|
|
81
|
+
- **`flatMap` returning `[]` or `[x]` filters and maps in one pass** when the map needs the narrowed value.
|
|
82
|
+
- **Mutator methods return `this` for chaining.**
|
|
83
|
+
- **A helper returns what it produces; no output parameters.**
|
|
84
|
+
- **Standalone units are `function`/`export function` declarations.** Arrow functions appear only as inline callbacks; lint backs it outside tests.
|
|
85
|
+
- **An option that combines other options is built from them, not from copies of their bodies.**
|
|
86
|
+
- **`if`/`else` over a ternary for anything beyond a single trivial value pick** ([when a ternary stays](./code-style/idioms.md#ifelse-over-a-ternary)).
|
|
87
|
+
- **Encode state as a named variable and an explicit `if`, not a wrapper object or a compact operator**; `??=` fills in a default, never tracks "computed yet?".
|
|
88
|
+
- **`&&` or `||` produces a value only when every falsy value its left side can hold should count as missing.** Where a `0`, `""` or `false` is real data, use `??`, `?.` or an explicit check.
|
|
89
|
+
|
|
90
|
+
## Smells
|
|
91
|
+
|
|
92
|
+
- **Whether a smell is fixed or kept, and its approved exceptions: the byro-repo root's `docs/agents/verdicts.md`.**
|
|
93
|
+
|
|
94
|
+
## Tests
|
|
95
|
+
|
|
96
|
+
- **A test sits beside what it tests (`Foo.test.ts`).**
|
|
97
|
+
- **A test file splits by subject when its top-level `describe` blocks share nothing but setup, and the shared setup moves to a sibling fixture module**, as a class splits ([why](./code-style/class-shape.md#split-a-class-when-its-helpers-fall-into-groups-that-share-nothing)).
|
|
98
|
+
- **Assert the outcome a caller can observe, not the calls made to reach it.** A call count stands only where the count is itself the contract.
|
|
99
|
+
- **A test needing a value on one side of a tunable default pins that setting in its fixture**; only a test of the default itself reads it ([why](./code-style/tests.md#a-test-pins-the-tunable-default-it-depends-on)).
|
|
100
|
+
- **A test starts a process only when that process is what it tests.**
|
|
101
|
+
- **A fixture costing more than a few milliseconds is built once per file and copied or reset for each test.**
|
|
102
|
+
- **A test never really waits: time goes through an injected clock or fake timers.**
|
|
103
|
+
- **A test reaches no network and opens no real port.**
|
|
104
|
+
|
|
105
|
+
## Tooling
|
|
106
|
+
|
|
107
|
+
- **Hooks, scripts and tool configs follow this file too.**
|
|
108
|
+
|
|
109
|
+
## Imports & file organization
|
|
110
|
+
|
|
111
|
+
- **No barrel/index files: no file exists only to re-export others**, apart from a package's declared public entries.
|
|
112
|
+
- **A file may re-assemble the pieces in its own same-named subfolder, taking each piece's export whole**, never a hand-picked subset of its members ([why](./code-style/file-organization.md#re-assembling-a-subfolder-isnt-a-barrel)).
|
|
113
|
+
- **File naming:**
|
|
114
|
+
- PascalCase mirroring the exported class name.
|
|
115
|
+
- A short PascalCase abbreviation for a file exporting one static-bundle object of related functions. A fat bundle's pieces split into a same-named subfolder.
|
|
116
|
+
- camelCase for plain data/config or entry-point files.
|
|
117
|
+
- A module whose helpers fall into groups that share nothing splits by subject into a same-named subfolder of camelCase files, each exporting camelCase bundles written with method shorthand.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
/** @typedef {import("estree").ImportDeclaration | import("estree").ExportNamedDeclaration | import("estree").ExportAllDeclaration | import("estree").ImportExpression} ModuleReference */
|
|
5
|
+
|
|
6
|
+
// A package's dependencies are read from its package.json, so a relative import into another package is one nothing declares.
|
|
7
|
+
/** @type {import("eslint").Rule.RuleModule} */
|
|
8
|
+
export const noCrossPackageImport = {
|
|
9
|
+
meta: {
|
|
10
|
+
type: "problem",
|
|
11
|
+
messages: {
|
|
12
|
+
crossPackage:
|
|
13
|
+
"{{source}} leaves this file's package: import the other package by its name.",
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
create(context) {
|
|
17
|
+
const ownFolder = dirname(context.filename);
|
|
18
|
+
const ownRoot = packageRootOf(ownFolder);
|
|
19
|
+
/** @param {ModuleReference} node */
|
|
20
|
+
function check(node) {
|
|
21
|
+
const { source } = node;
|
|
22
|
+
if (source?.type !== "Literal" || typeof source.value !== "string") {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (!source.value.startsWith(".")) return;
|
|
26
|
+
if (packageRootOf(resolve(ownFolder, source.value)) !== ownRoot) {
|
|
27
|
+
context.report({
|
|
28
|
+
node: source,
|
|
29
|
+
messageId: "crossPackage",
|
|
30
|
+
data: { source: source.value },
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
ImportDeclaration: check,
|
|
36
|
+
ExportNamedDeclaration: check,
|
|
37
|
+
ExportAllDeclaration: check,
|
|
38
|
+
ImportExpression: check,
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** @type {Map<string, string | undefined>} */
|
|
44
|
+
const packageRoots = new Map();
|
|
45
|
+
|
|
46
|
+
// An import's target may not exist, so this walks folders rather than asking the resolver.
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} path
|
|
49
|
+
* @returns {string | undefined}
|
|
50
|
+
*/
|
|
51
|
+
function packageRootOf(path) {
|
|
52
|
+
if (packageRoots.has(path)) return packageRoots.get(path);
|
|
53
|
+
const parent = dirname(path);
|
|
54
|
+
let root;
|
|
55
|
+
if (existsSync(join(path, "package.json"))) {
|
|
56
|
+
root = path;
|
|
57
|
+
} else if (parent !== path) {
|
|
58
|
+
root = packageRootOf(parent);
|
|
59
|
+
}
|
|
60
|
+
packageRoots.set(path, root);
|
|
61
|
+
return root;
|
|
62
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// A `private` or `#` method that never reads `this` belongs below the class as a module function.
|
|
2
|
+
/** @type {import("eslint").Rule.RuleModule} */
|
|
3
|
+
export const privateHelperUsesThis = {
|
|
4
|
+
meta: {
|
|
5
|
+
type: "suggestion",
|
|
6
|
+
messages: {
|
|
7
|
+
noThis:
|
|
8
|
+
"{{name}} never reads `this`: make it an unexported module function below the class.",
|
|
9
|
+
},
|
|
10
|
+
},
|
|
11
|
+
create(context) {
|
|
12
|
+
/** @type {{ helper: PrivateHelper | undefined, usesThis: boolean }[]} */
|
|
13
|
+
const frames = [];
|
|
14
|
+
/** @param {import("eslint").Rule.Node} node */
|
|
15
|
+
function enter(node) {
|
|
16
|
+
frames.push({ helper: privateHelperOf(node), usesThis: false });
|
|
17
|
+
}
|
|
18
|
+
function exit() {
|
|
19
|
+
const frame = frames.pop();
|
|
20
|
+
if (frame?.helper && !frame.usesThis) {
|
|
21
|
+
context.report({
|
|
22
|
+
node: frame.helper.key,
|
|
23
|
+
messageId: "noThis",
|
|
24
|
+
data: { name: frame.helper.name },
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function markThis() {
|
|
29
|
+
const frame = frames.at(-1);
|
|
30
|
+
if (frame) frame.usesThis = true;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
FunctionDeclaration: enter,
|
|
34
|
+
"FunctionDeclaration:exit": exit,
|
|
35
|
+
FunctionExpression: enter,
|
|
36
|
+
"FunctionExpression:exit": exit,
|
|
37
|
+
ThisExpression: markThis,
|
|
38
|
+
Super: markThis,
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** @typedef {{ key: import("estree").Node, name: string }} PrivateHelper */
|
|
44
|
+
|
|
45
|
+
/** @param {import("eslint").Rule.Node} node */
|
|
46
|
+
function privateHelperOf(node) {
|
|
47
|
+
const method = node.parent;
|
|
48
|
+
if (method?.type !== "MethodDefinition" || method.value !== node) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
const { key } = method;
|
|
52
|
+
if (key.type === "PrivateIdentifier") return { key, name: `#${key.name}` };
|
|
53
|
+
const isPrivate =
|
|
54
|
+
"accessibility" in method && method.accessibility === "private";
|
|
55
|
+
return isPrivate && key.type === "Identifier"
|
|
56
|
+
? { key, name: key.name }
|
|
57
|
+
: undefined;
|
|
58
|
+
}
|
package/eslint.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import eslint from "@eslint/js";
|
|
2
|
+
import nodePlugin from "eslint-plugin-n";
|
|
3
|
+
import simpleImportSort from "eslint-plugin-simple-import-sort";
|
|
4
|
+
import tseslint from "typescript-eslint";
|
|
5
|
+
|
|
6
|
+
import { noCrossPackageImport } from "./eslint/noCrossPackageImport.js";
|
|
7
|
+
import { privateHelperUsesThis } from "./eslint/privateHelperUsesThis.js";
|
|
8
|
+
|
|
9
|
+
export const variableNaming = {
|
|
10
|
+
selector: "variable",
|
|
11
|
+
format: ["camelCase", "PascalCase"],
|
|
12
|
+
leadingUnderscore: "allow",
|
|
13
|
+
custom: { regex: "^[A-Z][A-Z0-9]+$", match: false },
|
|
14
|
+
};
|
|
15
|
+
// Generic params are two-letter domain abbreviations; the domain-free utilities keep bare T, K and V.
|
|
16
|
+
const typeParameterNaming = {
|
|
17
|
+
selector: "typeParameter",
|
|
18
|
+
format: null,
|
|
19
|
+
custom: { regex: "^[A-Z]{2}$", match: true },
|
|
20
|
+
};
|
|
21
|
+
export const styleSyntax = [
|
|
22
|
+
{
|
|
23
|
+
selector: "TSEnumDeclaration",
|
|
24
|
+
message:
|
|
25
|
+
"A fixed set is an `as const` object or a union of string literals, not an enum.",
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
selector: "ExportDefaultDeclaration",
|
|
29
|
+
message: "Exports are named, so every import spells the name it wants.",
|
|
30
|
+
},
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
export const eslintPreset = [
|
|
34
|
+
{ ignores: ["**/dist/**", "**/coverage/**"] },
|
|
35
|
+
eslint.configs.recommended,
|
|
36
|
+
tseslint.configs.recommended,
|
|
37
|
+
{
|
|
38
|
+
plugins: {
|
|
39
|
+
n: nodePlugin,
|
|
40
|
+
"simple-import-sort": simpleImportSort,
|
|
41
|
+
style: {
|
|
42
|
+
rules: {
|
|
43
|
+
"no-cross-package-import": noCrossPackageImport,
|
|
44
|
+
"private-helper-uses-this": privateHelperUsesThis,
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
rules: {
|
|
49
|
+
"simple-import-sort/imports": "error",
|
|
50
|
+
// Each package declares what it imports, so it installs alone.
|
|
51
|
+
"n/no-extraneous-import": "error",
|
|
52
|
+
"style/no-cross-package-import": "error",
|
|
53
|
+
"style/private-helper-uses-this": "error",
|
|
54
|
+
"@typescript-eslint/consistent-type-imports": [
|
|
55
|
+
"error",
|
|
56
|
+
{ fixStyle: "inline-type-imports" },
|
|
57
|
+
],
|
|
58
|
+
// A module's value and type imports share one line.
|
|
59
|
+
"no-duplicate-imports": ["error", { allowSeparateTypeImports: false }],
|
|
60
|
+
// No setting limits an unbraced body to an exit; multi-line is the nearest, so a one-line non-exiting body also passes.
|
|
61
|
+
curly: ["error", "multi-line"],
|
|
62
|
+
"@typescript-eslint/no-explicit-any": "error",
|
|
63
|
+
"@typescript-eslint/explicit-function-return-type": [
|
|
64
|
+
"error",
|
|
65
|
+
{ allowExpressions: true },
|
|
66
|
+
],
|
|
67
|
+
"@typescript-eslint/no-non-null-assertion": "error",
|
|
68
|
+
"@typescript-eslint/consistent-type-definitions": ["error", "interface"],
|
|
69
|
+
"func-style": ["error", "declaration"],
|
|
70
|
+
"prefer-template": "error",
|
|
71
|
+
"no-restricted-syntax": ["error", ...styleSyntax],
|
|
72
|
+
"max-classes-per-file": ["error", 1],
|
|
73
|
+
// `_` marks a parameter kept for its signature; a rest sibling is dropped on purpose.
|
|
74
|
+
"@typescript-eslint/no-unused-vars": [
|
|
75
|
+
"error",
|
|
76
|
+
{ argsIgnorePattern: "^_", ignoreRestSiblings: true },
|
|
77
|
+
],
|
|
78
|
+
// Props bags chain as interfaces, so an empty one can name a tier.
|
|
79
|
+
"@typescript-eslint/no-empty-object-type": [
|
|
80
|
+
"error",
|
|
81
|
+
{ allowInterfaces: "with-single-extends" },
|
|
82
|
+
],
|
|
83
|
+
// Constants are camelCase too; methods stay free, so SHOUTING multi-row deletes pass.
|
|
84
|
+
"@typescript-eslint/naming-convention": [
|
|
85
|
+
"error",
|
|
86
|
+
variableNaming,
|
|
87
|
+
typeParameterNaming,
|
|
88
|
+
],
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
// Tool configs are default exports by their tools' contract.
|
|
92
|
+
{
|
|
93
|
+
files: ["**/*.config.{mjs,ts}"],
|
|
94
|
+
rules: {
|
|
95
|
+
"no-restricted-syntax": [
|
|
96
|
+
"error",
|
|
97
|
+
...styleSyntax.filter(
|
|
98
|
+
({ selector }) => selector !== "ExportDefaultDeclaration",
|
|
99
|
+
),
|
|
100
|
+
],
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
// Test helpers and plain-JS files are out of the return-type and function-style rules' scope (#153).
|
|
104
|
+
{
|
|
105
|
+
files: ["**/*.test.ts", "**/*.{js,mjs}"],
|
|
106
|
+
rules: {
|
|
107
|
+
"@typescript-eslint/explicit-function-return-type": "off",
|
|
108
|
+
"func-style": "off",
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
];
|
package/lintDocs.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// `lint-docs [--published <dir>]...`: runs the doc checker against the tracked and new files of the git repo it is invoked in, exiting non-zero on a violation.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { posix } from "node:path";
|
|
7
|
+
import { parseArgs } from "node:util";
|
|
8
|
+
|
|
9
|
+
import { checkDocs } from "./docLint.js";
|
|
10
|
+
|
|
11
|
+
const { values } = parseArgs({
|
|
12
|
+
options: { published: { type: "string", multiple: true } },
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/** @param {string[]} args */
|
|
16
|
+
function git(args) {
|
|
17
|
+
return execFileSync("git", args, { encoding: "utf8" }).trim();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const root = git(["rev-parse", "--show-toplevel"]);
|
|
21
|
+
const files = git([
|
|
22
|
+
"-C",
|
|
23
|
+
root,
|
|
24
|
+
"ls-files",
|
|
25
|
+
"--cached",
|
|
26
|
+
"--others",
|
|
27
|
+
"--exclude-standard",
|
|
28
|
+
])
|
|
29
|
+
.split("\n")
|
|
30
|
+
.filter(
|
|
31
|
+
(file) => file && !file.endsWith("/") && existsSync(posix.join(root, file)),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
const docs = Object.fromEntries(
|
|
35
|
+
files
|
|
36
|
+
.filter((file) => file.endsWith(".md"))
|
|
37
|
+
.map((file) => [file, readFileSync(posix.join(root, file), "utf8")]),
|
|
38
|
+
);
|
|
39
|
+
const folders = files.flatMap((file) => {
|
|
40
|
+
const parents = [];
|
|
41
|
+
for (let dir = posix.dirname(file); dir !== "."; dir = posix.dirname(dir)) {
|
|
42
|
+
parents.push(dir);
|
|
43
|
+
}
|
|
44
|
+
return parents;
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
const violations = checkDocs({
|
|
48
|
+
docs,
|
|
49
|
+
paths: [...files, ...new Set(folders)],
|
|
50
|
+
published: values.published,
|
|
51
|
+
});
|
|
52
|
+
for (const { path, line, message } of violations) {
|
|
53
|
+
console.error(`${path}:${line} ${message}`);
|
|
54
|
+
}
|
|
55
|
+
if (violations.length > 0) {
|
|
56
|
+
console.error(
|
|
57
|
+
`lint-docs: ${violations.length} problem(s). What it checks: the @byronbroughten/code-style README.`,
|
|
58
|
+
);
|
|
59
|
+
process.exit(1);
|
|
60
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@byronbroughten/code-style",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "General tooling for TypeScript projects: an ESLint flat-config preset, the prettier config, a base tsconfig, a doc linter and the general style docs.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "ISC",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/byronbroughten/code-style.git"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
|
13
|
+
},
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
"./eslint": "./eslint.js",
|
|
19
|
+
"./prettier": "./prettier.json",
|
|
20
|
+
"./tsconfig.base.json": "./tsconfig.base.json"
|
|
21
|
+
},
|
|
22
|
+
"bin": {
|
|
23
|
+
"lint-docs": "./lintDocs.js"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"eslint.js",
|
|
27
|
+
"eslint",
|
|
28
|
+
"prettier.json",
|
|
29
|
+
"tsconfig.base.json",
|
|
30
|
+
"docLint.js",
|
|
31
|
+
"lintDocs.js",
|
|
32
|
+
"docs"
|
|
33
|
+
],
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@eslint/js": "^9.35.0",
|
|
36
|
+
"eslint-plugin-n": "^17.24.0",
|
|
37
|
+
"eslint-plugin-simple-import-sort": "^14.0.0",
|
|
38
|
+
"typescript-eslint": "^8.43.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/node": "^22.20.4",
|
|
42
|
+
"eslint": "^9.35.0",
|
|
43
|
+
"prettier": "3.9.6",
|
|
44
|
+
"typescript": "^5.9.2",
|
|
45
|
+
"vitest": "^4.1.11"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"eslint": "^9.35.0",
|
|
49
|
+
"prettier": "^3.9.6",
|
|
50
|
+
"typescript": "^5.9.2"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"eslint": {
|
|
54
|
+
"optional": true
|
|
55
|
+
},
|
|
56
|
+
"prettier": {
|
|
57
|
+
"optional": true
|
|
58
|
+
},
|
|
59
|
+
"typescript": {
|
|
60
|
+
"optional": true
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"scripts": {
|
|
64
|
+
"tsc": "tsc -p .",
|
|
65
|
+
"test": "vitest run",
|
|
66
|
+
"lint": "eslint . && node lintDocs.js --published . && prettier --check .",
|
|
67
|
+
"lint:docs": "node lintDocs.js --published ."
|
|
68
|
+
},
|
|
69
|
+
"prettier": "./prettier.json"
|
|
70
|
+
}
|
package/prettier.json
ADDED