@adamhl8/configs 3.1.1 → 3.2.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.
Files changed (40) hide show
  1. package/README.md +307 -73
  2. package/dist/configs/bunfig.base.toml +2 -2
  3. package/dist/configs/knip.base.d.ts +1 -1
  4. package/dist/configs/knip.base.d.ts.map +1 -1
  5. package/dist/configs/knip.base.js +5 -1
  6. package/dist/configs/knip.base.js.map +1 -1
  7. package/dist/test-utils/fixture.d.ts +17 -0
  8. package/dist/test-utils/fixture.d.ts.map +1 -0
  9. package/dist/test-utils/fixture.js +20 -0
  10. package/dist/test-utils/fixture.js.map +1 -0
  11. package/dist/test-utils/index.d.ts +7 -0
  12. package/dist/test-utils/index.js +6 -0
  13. package/dist/test-utils/pack.d.ts +3 -0
  14. package/dist/test-utils/pack.d.ts.map +1 -0
  15. package/dist/test-utils/pack.js +16 -0
  16. package/dist/test-utils/pack.js.map +1 -0
  17. package/dist/test-utils/preload.d.ts +1 -0
  18. package/dist/test-utils/preload.js +7 -0
  19. package/dist/test-utils/preload.js.map +1 -0
  20. package/dist/test-utils/shell/bin-dirs.js +19 -0
  21. package/dist/test-utils/shell/bin-dirs.js.map +1 -0
  22. package/dist/test-utils/shell/command.d.ts +18 -0
  23. package/dist/test-utils/shell/command.d.ts.map +1 -0
  24. package/dist/test-utils/shell/command.js +63 -0
  25. package/dist/test-utils/shell/command.js.map +1 -0
  26. package/dist/test-utils/shell/env.d.ts +4 -0
  27. package/dist/test-utils/shell/env.d.ts.map +1 -0
  28. package/dist/test-utils/shell/env.js +11 -0
  29. package/dist/test-utils/shell/env.js.map +1 -0
  30. package/dist/test-utils/shell/node-shim.js +18 -0
  31. package/dist/test-utils/shell/node-shim.js.map +1 -0
  32. package/dist/test-utils/shell/shell.d.ts +42 -0
  33. package/dist/test-utils/shell/shell.d.ts.map +1 -0
  34. package/dist/test-utils/shell/shell.js +24 -0
  35. package/dist/test-utils/shell/shell.js.map +1 -0
  36. package/dist/test-utils/temp-dir.d.ts +3 -0
  37. package/dist/test-utils/temp-dir.d.ts.map +1 -0
  38. package/dist/test-utils/temp-dir.js +21 -0
  39. package/dist/test-utils/temp-dir.js.map +1 -0
  40. package/package.json +9 -1
package/README.md CHANGED
@@ -1,11 +1,90 @@
1
1
  # configs
2
2
 
3
- Configs (`tsconfig`, `oxfmt`, `oxlint`, etc.) I use across my projects.
3
+ Configs, tasks, and workflows I use across my TS projects.
4
+
5
+ - Base configs for `tsconfig`, `oxfmt`, `oxlint`, `knip`, `tsdown`, `commitlint`, `release-it`, and `lefthook`, each extended through a typed merge function
6
+ - Shared [bask](https://github.com/adamhl8/bask) tasks for linting, building, testing, and releasing
7
+ - `bunfig.toml` and `.gitignore` entries synced into each project
8
+ - Reusable GitHub Actions workflows for CI, dependency updates, and releases
9
+ - An OpenTofu module for each repo's GitHub settings and Actions secrets
10
+ - Utilities for validated env vars and integration tests
11
+
12
+ ---
13
+
14
+ <!-- toc -->
15
+
16
+ - [Installation](#installation)
17
+ - [Setup](#setup)
18
+ - [Configs](#configs)
19
+ - [Config merging](#config-merging)
20
+ - [tsconfig](#tsconfig)
21
+ - [oxfmt](#oxfmt)
22
+ - [oxlint](#oxlint)
23
+ - [knip](#knip)
24
+ - [tsdown](#tsdown)
25
+ - [commitlint](#commitlint)
26
+ - [release-it](#release-it)
27
+ - [lefthook](#lefthook)
28
+ - [bask tasks](#bask-tasks)
29
+ - [Synced files](#synced-files)
30
+ - [bunfig](#bunfig)
31
+ - [gitignore](#gitignore)
32
+ - [Utilities](#utilities)
33
+ - [env](#env)
34
+ - [test](#test)
35
+ - [GitHub Actions](#github-actions)
36
+ - [CI](#ci)
37
+ - [Update dependencies](#update-dependencies)
38
+ - [Release](#release)
39
+ - [Secrets](#secrets)
40
+ - [GitHub repo settings](#github-repo-settings)
41
+ - [Developing this repo](#developing-this-repo)
42
+
43
+ <!-- tocstop -->
44
+
45
+ ---
46
+
47
+ ## Installation
4
48
 
5
49
  ```sh
6
50
  bun add -D @adamhl8/configs
7
51
  ```
8
52
 
53
+ The tasks run each tool's bin from the project, so install the tools directly too. With bun's `isolated` linker, a bin that's only a dependency of `@adamhl8/configs` isn't on the project's `PATH`.
54
+
55
+ ```sh
56
+ bun add -D @adamhl8/bask @commitlint/cli @commitlint/config-conventional @types/bun knip markdown-toc oxfmt oxlint oxlint-tsgolint typescript
57
+ ```
58
+
59
+ Some tools are only needed by some projects:
60
+
61
+ - Published packages: `tsdown publint @arethetypeswrong/core`
62
+ - Releases: `release-it release-it-git-cliff` (see [release-it](#release-it))
63
+ - Astro projects that use Tailwind: `tailwint @tailwindcss/language-server` (see [bask tasks](#bask-tasks))
64
+
65
+ ## Setup
66
+
67
+ A project using everything here has these files:
68
+
69
+ | File | Section |
70
+ | ------------------------- | --------------------------------------------- |
71
+ | `bask.ts` | [bask tasks](#bask-tasks) |
72
+ | `package.json` `prepare` | [bask tasks](#bask-tasks) |
73
+ | `tsconfig.json` | [tsconfig](#tsconfig) |
74
+ | `oxfmt.config.ts` | [oxfmt](#oxfmt) |
75
+ | `oxlint.config.ts` | [oxlint](#oxlint) |
76
+ | `knip.ts` | [knip](#knip) |
77
+ | `tsdown.config.ts` | [tsdown](#tsdown) |
78
+ | `commitlint.config.ts` | [commitlint](#commitlint) |
79
+ | `.release-it.ts` | [release-it](#release-it) |
80
+ | `lefthook.yaml` | [lefthook](#lefthook) |
81
+ | `.github/workflows/*.yml` | [GitHub Actions](#github-actions) |
82
+ | `github.tofu` | [GitHub repo settings](#github-repo-settings) |
83
+
84
+ `bunfig.toml` and `.gitignore` are kept up to date by the [synced files](#synced-files).
85
+
86
+ ## Configs
87
+
9
88
  ### Config merging
10
89
 
11
90
  Each `fooConfig({ ... })` function deep merges your config into the base config. Arrays are appended to the base array by default. To use arrays as-is instead, put them in a second config object, which is merged the same way except its arrays replace the base array:
@@ -25,67 +104,23 @@ const config = oxlintConfig(
25
104
  )
26
105
  ```
27
106
 
28
- The second config works at any depth: only the arrays you provide are replaced, sibling keys still merge normally, and a key in both objects gets the second object's value. Required keys (e.g. `platform` for `tsdownConfig`) must be provided in the first object.
29
-
30
- ### bask
31
-
32
- Tasks live in a shared [bask](https://github.com/adamhl8/bask) tasks module instead of being copied into every project's `package.json`. Install `@adamhl8/bask` as a dev dependency, then re-export the tasks from your `bask.ts`:
33
-
34
- ```ts
35
- export * from "@adamhl8/configs/bask"
36
- ```
37
-
38
- It provides `lint`, `build`, `test`, `bump-deps`, `release`, `release-run` (hidden, run by the release workflow), `tofu-check`, `commit-types`, and `prepare`. Run `bunx bask` to list them along with the allowed commit types. The tasks degrade gracefully so projects can use them as-is: `build` only runs `tsdown` if the project has a `tsdown.config.ts`, `test` (`bun test`) passes when there are no tests, and `tofu-check` (a `tofu plan` drift check, which `build` also runs) skips itself unless run locally in a project with `.tofu` files.
39
-
40
- In projects that depend on `tailwindcss`, `lint` also runs [tailwint](https://github.com/peterwangsc/tailwint) on `.astro` files, because oxlint can't see Astro markup. It only checks and never fixes, because tailwint resolves a class conflict by deleting a class by position, not by which one wins. Projects with `.astro` files install it:
41
-
42
- ```sh
43
- bun add -D tailwint @tailwindcss/language-server
44
- ```
45
-
46
- Both are optional peer dependencies. bask runs `bun tailwint` from the project, so with bun's `isolated` linker the bin has to be installed by the project, not just by `@adamhl8/configs`.
47
-
48
- To customize a task, add hooks to it from your `bask.ts`. A hook also runs when another base task calls that task, so extending `lint` extends `build` too:
49
-
50
- ```ts
51
- import { task } from "@adamhl8/bask"
52
- import { bumpDeps, lint } from "@adamhl8/configs/bask"
53
-
54
- export * from "@adamhl8/configs/bask"
55
-
56
- export const astroSync = task(async ({ sh }) => {
57
- await sh`astro sync`
58
- })
59
-
60
- lint.before(astroSync)
61
- bumpDeps.after(async ({ sh }) => {
62
- await sh`prisma generate`
63
- })
64
- ```
65
-
66
- The only script left in `package.json` is `prepare`, which hands off to bask:
67
-
68
- ```json
69
- "scripts": {
70
- "prepare": "bask prepare"
71
- }
72
- ```
73
-
74
- The `prepare` script and task `sh` calls run local bins by their bare name, because `bun run` and bask both put `node_modules/.bin` on `PATH`. Git hooks and the workflows run `bunx bask` rather than `bun bask`, because `bun bask` runs `bask.ts` instead of the bask bin.
107
+ The second config works at any depth: only the arrays you provide are replaced, sibling keys still merge normally, and a key in both objects gets the second object's value. Required keys (e.g. `platform` for `tsdownConfig`) must be provided in the first object. A function with no required keys can be called with no arguments to get the base config as-is.
75
108
 
76
109
  ### tsconfig
77
110
 
78
111
  ```json
112
+ // tsconfig.json
79
113
  {
80
114
  "extends": "@adamhl8/configs/tsconfig"
81
115
  }
82
116
  ```
83
117
 
84
- The base tsconfig sets `types: ["bun"]`, so the project needs `@types/bun` installed.
118
+ The base tsconfig adds stricter checks like `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes`, with no emit and bundler module resolution. It sets `types: ["bun"]`, so the project needs `@types/bun` installed.
85
119
 
86
120
  ### oxfmt
87
121
 
88
122
  ```ts
123
+ // oxfmt.config.ts
89
124
  import { oxfmtConfig } from "@adamhl8/configs"
90
125
  import { defineConfig } from "oxfmt"
91
126
 
@@ -94,11 +129,14 @@ const config = oxfmtConfig({ ... })
94
129
  export default defineConfig(config)
95
130
  ```
96
131
 
132
+ The base uses a 120 character line width and no semicolons, and sorts imports, `package.json`, and Tailwind classes.
133
+
97
134
  In projects that depend on `tailwindcss`, Tailwind classes are sorted against the project's Tailwind stylesheet, so classes from plugins and `@theme` sort correctly. The stylesheet is found the same way the Tailwind language server finds it: the first CSS file, in sorted order, that does `@import "tailwindcss"`. oxfmt has to run from the project root for this to find the file. If it picks the wrong file, set `sortTailwindcss: { stylesheet: "path/to/global.css" }`.
98
135
 
99
136
  ### oxlint
100
137
 
101
138
  ```ts
139
+ // oxlint.config.ts
102
140
  import { oxlintConfig } from "@adamhl8/configs"
103
141
  import { defineConfig } from "oxlint"
104
142
 
@@ -107,55 +145,75 @@ const config = oxlintConfig({ ... })
107
145
  export default defineConfig(config)
108
146
  ```
109
147
 
110
- When the project depends on `tailwindcss`, the config enables [oxlint-tailwindcss](https://github.com/sergioazoc/oxlint-tailwindcss) with every rule except `enforce-sort-order` and `enforce-consistent-line-wrapping` (oxfmt handles these), `enforce-logical` (it conflicts with `enforce-physical`), and `max-class-count`. The plugin reads the design system from the same stylesheet oxfmt sorts against. If that's the wrong file, set `settings: { tailwindcss: { entryPoint: "path/to/global.css" } }`, alongside the oxfmt `sortTailwindcss` override.
148
+ The base turns on every rule category as an error, with type-aware linting and type checking, then turns off the rules that don't fit. It also loads these JS plugins with every rule on, except the rules a native rule already covers:
149
+
150
+ - Always: [bunisms](https://github.com/himynameisdave/eslint-plugin-bunisms), [clean-modules](https://github.com/adamhl8/eslint-plugin-clean-modules), [directive-comments](https://github.com/tunderadev/oxlint-plugin-directive-comments), [e18e](https://github.com/e18e/eslint-plugin), and [regexp](https://github.com/ota-meshi/eslint-plugin-regexp)
151
+ - When the project depends on `hono`: [hono](https://github.com/ouka-lab/eslint-plugin-hono)
152
+ - When the project depends on `react`: [react-web-api](https://github.com/Rel1cx/eslint-react) and [react-you-might-not-need-an-effect](https://github.com/nickjvandyke/eslint-plugin-react-you-might-not-need-an-effect)
153
+ - When the project has a Tailwind stylesheet: [oxlint-tailwindcss](https://github.com/sergioazoc/oxlint-tailwindcss)
154
+
155
+ The plugins are loaded from `@adamhl8/configs`'s own dependencies, so the project doesn't install them. In a project whose `package.json` has `engines.node`, the bunisms rules are off in `src/` (except in tests), because that code runs on Node.
156
+
157
+ oxlint-tailwindcss runs every rule except `enforce-sort-order` and `enforce-consistent-line-wrapping` (oxfmt handles these), `enforce-logical` (it conflicts with `enforce-physical`), and `max-class-count`. It reads the design system from the same stylesheet oxfmt sorts against. If that's the wrong file, set `settings: { tailwindcss: { entryPoint: "path/to/global.css" } }`, alongside the oxfmt `sortTailwindcss` override.
111
158
 
112
159
  ### knip
113
160
 
114
161
  ```ts
162
+ // knip.ts
115
163
  import { knipConfig } from "@adamhl8/configs"
116
164
 
117
165
  export default knipConfig({ ... })
118
166
  ```
119
167
 
168
+ The base leaves `fixtures` and `fixture` dirs out of the analysis, at any depth. It adds `**/*.test.ts` and `bask.ts` to the bun plugin's entries rather than the top-level `entry`, so a project's own `entry` doesn't replace knip's default entries. knip doesn't see commands run through bask's `sh`, so a dependency that's only run there goes in `ignoreDependencies`.
169
+
120
170
  ### tsdown
121
171
 
122
172
  ```ts
173
+ // tsdown.config.ts
123
174
  import { tsdownConfig } from "@adamhl8/configs"
124
175
  import { defineConfig } from "tsdown"
125
176
 
126
- const config = tsdownConfig({ ... })
177
+ const config = tsdownConfig({ platform: "node" })
127
178
 
128
179
  export default defineConfig(config)
129
180
  ```
130
181
 
182
+ The base builds `src/index.ts` as an unbundled ESM library with sourcemaps and type declarations, and checks the package with `attw` and `publint`. Any warning fails the build. `platform` is required.
183
+
131
184
  `tsdownBundleConfig` is also exported for single-file bundles that aren't published libraries: everything is bundled, with no type declarations or publish checks. `tsdownBinConfig` builds `package.json` bin executables: the same bundle for node, with an extensionless output file.
132
185
 
133
186
  ### commitlint
134
187
 
135
188
  ```ts
189
+ // commitlint.config.ts
136
190
  import { commitlintConfig } from "@adamhl8/configs"
137
191
 
138
192
  export default commitlintConfig({ ... })
139
193
  ```
140
194
 
141
- #### Notes
195
+ The allowed commit types are the conventional types without `test`, `style`, and `build`, plus `improve` and `release`. `bunx bask commit-types` prints them.
142
196
 
143
- `@commitlint/config-conventional` is both a dependency and a peer dependency:
197
+ <details>
198
+ <summary><i>Why is <code>@commitlint/config-conventional</code> both a dependency and a peer dependency?</i></summary>
144
199
 
145
200
  - Dependency: `commitlint.base.ts` imports it to read the conventional commit types.
146
201
  - Peer dependency: `commitlint.base.ts` also sets `extends: ["@commitlint/config-conventional"]`. commitlint resolves that string from the consumer's project root, not from `@adamhl8/configs`.
147
202
 
148
203
  With bun's `isolated` linker, our copy lives only in `@adamhl8/configs`'s own `node_modules` and is never hoisted to the consumer's root. So commitlint can't find it unless the consumer installs it directly, which the peer dependency asks them to do.
149
204
 
205
+ </details>
206
+
150
207
  ### release-it
151
208
 
152
209
  ```ts
210
+ // .release-it.ts
153
211
  import { releaseItConfig } from "@adamhl8/configs"
154
212
 
155
213
  export default releaseItConfig({ ... })
156
214
  ```
157
215
 
158
- The release config registers the [`release-it-git-cliff`](https://github.com/adamhl8/release-it-git-cliff) plugin with the bundled git-cliff config (`cliff.base.toml`), so there is no per-project `cliff.toml` to write. git-cliff picks the next version from the commits, and the plugin writes `CHANGELOG.md` (formatted with `oxfmt`) and sets the release notes. Tags are named `v${version}`. It publishes with `bun publish`.
216
+ The release config registers the [`release-it-git-cliff`](https://github.com/adamhl8/release-it-git-cliff) plugin with the bundled git-cliff config (`cliff.base.toml`), so there is no per-project `cliff.toml` to write. git-cliff picks the next version from the commits, and the plugin writes `CHANGELOG.md` (formatted with `oxfmt`) and sets the release notes. A release starts by running `bunx bask build`. The release commit is `release: v${version}`, and the tag is `v${version}`. It publishes with `bun publish --ignore-scripts`.
159
217
 
160
218
  git-cliff must be on `PATH`, and the project needs `release-it-git-cliff` installed directly:
161
219
 
@@ -163,15 +221,18 @@ git-cliff must be on `PATH`, and the project needs `release-it-git-cliff` instal
163
221
  bun add -D release-it release-it-git-cliff
164
222
  ```
165
223
 
166
- #### Notes
224
+ Preview the next version or the unreleased changelog section with `release-it --release-version` or `release-it --changelog`.
225
+
226
+ <details>
227
+ <summary><i>Why does the project install <code>release-it-git-cliff</code>?</i></summary>
167
228
 
168
229
  `release-it-git-cliff` is an optional peer dependency. release-it resolves plugins from its own location or the working directory, so with bun's `isolated` linker it can't find a plugin that's only a dependency of `@adamhl8/configs`.
169
230
 
170
- Preview the next version or the unreleased changelog section with `release-it --release-version` or `release-it --changelog`.
231
+ </details>
171
232
 
172
233
  ### lefthook
173
234
 
174
- `lefthook.base.yaml` runs `bunx bask build` on pre-commit and `commitlint` on commit-msg. Extend it from your `lefthook.yaml`:
235
+ `lefthook.base.yaml` runs `bunx bask build` on pre-commit and `commitlint` on commit-msg. The pre-commit hook fails when the build changes any files, so you can stage the lint fixes and formatting and commit again. Extend it from your `lefthook.yaml`:
175
236
 
176
237
  ```yaml
177
238
  # lefthook.yaml
@@ -179,19 +240,97 @@ extends:
179
240
  - node_modules/@adamhl8/configs/dist/configs/lefthook.base.yaml
180
241
  ```
181
242
 
182
- `lefthook install` (the base `prepare` task runs it) sets up the hooks. `prepare` skips it in CI (when `CI` is set), so commits made by the workflows don't run the hooks.
243
+ `lefthook install` (the `prepare` task runs it) sets up the hooks.
244
+
245
+ ## bask tasks
246
+
247
+ Tasks live in a shared [bask](https://github.com/adamhl8/bask) tasks module instead of being copied into every project's `package.json`. Re-export them from your `bask.ts`:
248
+
249
+ ```ts
250
+ // bask.ts
251
+ export * from "@adamhl8/configs/bask"
252
+ ```
253
+
254
+ Run `bunx bask` to list them along with the allowed commit types.
255
+
256
+ | Task | What it does |
257
+ | -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
258
+ | `lint` | Updates the README's table of contents, runs oxlint (with fixes), oxfmt, tailwint, `tofu fmt`, knip, and actionlint, then `test` |
259
+ | `build` | Runs `lint`, `tsdown`, and `tofu-check`. In CI, it fails when lint fixes or formatting changed any files |
260
+ | `test` | Runs `bun test`, which passes when there are no tests |
261
+ | `bump-deps` | Updates every dependency to its latest version, then reinstalls without the lockfile, `node_modules`, or bun's cache |
262
+ | `release` | Starts the [release workflow](#release) (`gh workflow run release.yml`) |
263
+ | `release-run` | Runs `release-it --ci`. It's hidden because only the release workflow runs it |
264
+ | `tofu-check` | Runs `tofu plan` to check the [GitHub repo settings](#github-repo-settings) for drift |
265
+ | `commit-types` | Prints the allowed commit types |
266
+ | `prepare` | Runs `lefthook install`, the [synced files](#synced-files), and `tofu init -upgrade` |
267
+
268
+ The tasks skip the steps a project doesn't need, so projects can use them as-is:
269
+
270
+ - `lint` runs tailwint only when the project has a Tailwind stylesheet and `.astro` files, `tofu fmt` only when it has tofu files, and actionlint only when it has `.github/workflows`. The table of contents only changes in a README with [markdown-toc](https://github.com/jonschlinkert/markdown-toc)'s `toc` and `tocstop` comment markers.
271
+ - `build` runs `tsdown` only when the project has a `tsdown.config.ts`.
272
+ - `tofu-check` and `tofu init` run only outside CI, in a project with a root `.tofu` file, on a machine with the `adamhl8` AWS profile.
273
+ - `prepare` skips `lefthook install` in CI, so commits made by the workflows don't run the hooks.
274
+
275
+ tailwint runs on `.astro` files because oxlint can't see Astro markup. It only checks and never fixes, because tailwint resolves a class conflict by deleting a class by position, not by which one wins. Projects with `.astro` files install it:
276
+
277
+ ```sh
278
+ bun add -D tailwint @tailwindcss/language-server
279
+ ```
280
+
281
+ Both are optional peer dependencies. bask runs `bun tailwint` from the project, so with bun's `isolated` linker the bin has to be installed by the project, not just by `@adamhl8/configs`.
282
+
283
+ To customize a task, add hooks to it from your `bask.ts`. A hook also runs when another base task calls that task, so extending `lint` extends `build` too:
284
+
285
+ ```ts
286
+ // bask.ts
287
+ import { task } from "@adamhl8/bask"
288
+ import { bumpDeps, lint } from "@adamhl8/configs/bask"
289
+
290
+ export * from "@adamhl8/configs/bask"
291
+
292
+ export const astroSync = task(async ({ sh }) => {
293
+ await sh`astro sync`
294
+ })
295
+
296
+ lint.before(astroSync)
297
+ bumpDeps.after(async ({ sh }) => {
298
+ await sh`prisma generate`
299
+ })
300
+ ```
301
+
302
+ The only script left in `package.json` is `prepare`, which hands off to bask:
303
+
304
+ ```json
305
+ "scripts": {
306
+ "prepare": "bask prepare"
307
+ }
308
+ ```
309
+
310
+ The `prepare` script and task `sh` calls run local bins by their bare name, because `bun run` and bask both put `node_modules/.bin` on `PATH`. Git hooks and the workflows run `bunx bask` rather than `bun bask`, because `bun bask` runs `bask.ts` instead of the bask bin.
311
+
312
+ ## Synced files
183
313
 
184
314
  ### bunfig
185
315
 
186
- bun has no extends mechanism for `bunfig.toml`, so shared settings are synced into the project's `bunfig.toml`. The base `prepare` task runs the `adamhl8-bunfig` bin, which merges the shared base config (`bunfig.base.toml`) with the project's `bunfig.toml` and writes the result back. The project's values win over the base's, and a project without a `bunfig.toml` gets the base config as-is.
316
+ bun has no extends mechanism for `bunfig.toml`, so shared settings are synced into the project's `bunfig.toml`. The `prepare` task runs the `adamhl8-bunfig` bin, which merges the shared base config (`bunfig.base.toml`) with the project's `bunfig.toml` and writes the result back. `prepare` then formats it with oxfmt. The project's values win over the base's, arrays merge by index, and a project without a `bunfig.toml` gets the base config as-is.
317
+
318
+ The base config:
319
+
320
+ - turns on coverage for `bun test`, leaving out test files and `__tests__` dirs
321
+ - only prints failing tests
322
+ - runs `**/*.test.ts` files concurrently
323
+ - skips `fixtures` and `fixture` dirs at any depth
324
+ - uses the isolated install linker
325
+ - makes `bun run` run scripts with bun instead of node
187
326
 
188
- The base config turns on coverage for `bun test` (showing only failures), runs `**/*.test.ts` files concurrently, ignores `fixtures/` directories, uses the isolated install linker, and makes `bun run` run scripts with bun instead of node.
327
+ Because the merged result is written back, a change to a base value doesn't reach a project that already has that key. Delete the key from the project's `bunfig.toml` and run the sync again to pick it up.
189
328
 
190
329
  Since the file is regenerated from the merged config, comments in `bunfig.toml` don't survive the sync. The sync can also be run manually by running `adamhl8-bunfig`.
191
330
 
192
331
  ### gitignore
193
332
 
194
- git has no include mechanism for `.gitignore`, so shared entries are synced into the project's `.gitignore`. The base `prepare` task runs the `adamhl8-gitignore` bin, which keeps the shared list at the top of the file above a marker line: the first run prepends it, later runs replace everything above the marker with the current shared list, so changes propagate on package updates:
333
+ git has no include mechanism for `.gitignore`, so shared entries are synced into the project's `.gitignore`. The `prepare` task runs the `adamhl8-gitignore` bin, which keeps the shared list at the top of the file above a marker line: the first run prepends it, later runs replace everything above the marker with the current shared list, so changes propagate on package updates:
195
334
 
196
335
  ```gitignore
197
336
  node_modules/
@@ -204,6 +343,8 @@ dist/
204
343
 
205
344
  Everything below the marker is left untouched. The sync can also be run manually by running `adamhl8-gitignore`.
206
345
 
346
+ ## Utilities
347
+
207
348
  ### env
208
349
 
209
350
  Utilities for validated environment variables, exported from the `/env` subpath:
@@ -222,11 +363,55 @@ export const env = parseEnv({
222
363
 
223
364
  `parseEnv` is `arkenv` with friendlier failures: invalid env prints the validation message and exits instead of throwing. `requireWhen` makes a var required while its condition is true and optional otherwise. An optional third argument supplies a fallback for when the var is unset (the fallback is exempt from validation, a set value never is).
224
365
 
366
+ ### test
367
+
368
+ Helpers for integration tests that run real commands in temp dirs, exported from the `/test` subpath. They're built on Bun's shell, as a replacement for `execa`:
369
+
370
+ ```ts
371
+ import { copyFixture, minimalEnv, packPackage } from "@adamhl8/configs/test"
372
+
373
+ const tarball = await packPackage(ROOT) // once per run, like in a preload's `beforeAll`
374
+ const { dir, run } = await copyFixture(FIXTURE, { shell: { env: minimalEnv() } })
375
+ await run`bun add -d ${tarball}`
376
+
377
+ const { stdout, stderr, exitCode } = await run`my-cli --version`
378
+ // Like Bun's `$`, a command's own settings chain before it's awaited and don't change the shell.
379
+ const { exitCode: failedCode } = await run`my-cli --bad-flag`.nothrow()
380
+ ```
381
+
382
+ - `createShell(options)` returns a shell that runs commands quietly. Awaiting a command returns its `stdout` and `stderr` (with one trailing newline stripped) plus its `exitCode`.
383
+ - `cwd` defaults to `process.cwd()`.
384
+ - `env` replaces `process.env` instead of merging into it. It defaults to `process.env` without `FORCE_COLOR`, which `bask` sets in a terminal.
385
+ - `localBins` (default `true`) puts `node_modules/.bin` of the cwd and each of its parents first on `PATH`.
386
+ - `throws` (default `true`) makes a non-zero exit code throw Bun's `ShellError`, which `bun test` prints with its `exitCode`, `stdout`, and `stderr`.
387
+ - Each command can chain `.cwd()`, `.env()` (merged over the shell's), `.localBins()`, and `.nothrow()`.
388
+ - The `node` shims from `bask` and `bun run --bun` are taken off `PATH`, so `node` is always the real Node.
389
+ - Commands read the test runner's stdin, so add `< /dev/null` to a command that might prompt.
390
+ - `copyFixture(fixture, { prefix, shell })` copies a fixture dir into a temp dir and returns the `dir` plus a `run` shell bound to it. `shell` takes the `createShell` options except `cwd`.
391
+ - `packPackage(root)` runs `bun tsdown` when `root` has a `tsdown.config.ts`, then packs it with `bun pm pack --ignore-scripts` into a temp dir, and returns the tarball path.
392
+ - `minimalEnv(extra)` returns just `PATH` and `HOME`, plus `extra`.
393
+ - `makeTempDir(prefix)` makes a temp dir that's removed after the test run. `copyFixture` and `packPackage` use it.
394
+
395
+ The temp dirs are removed by a preload, which each project adds to its `bunfig.toml`:
396
+
397
+ ```toml
398
+ [test]
399
+ preload = ["@adamhl8/configs/test/preload"]
400
+ ```
401
+
402
+ A project with its own preload imports it at the top of that file instead, so all of its test setup stays in one place:
403
+
404
+ ```ts
405
+ import "@adamhl8/configs/test/preload"
406
+ ```
407
+
408
+ It isn't in the shared bunfig base because `adamhl8-bunfig` merges arrays by index, so a project's own `preload` would replace it.
409
+
225
410
  ## GitHub Actions
226
411
 
227
- This repo hosts three reusable workflows you can call from other projects instead of copy/pasting them. The calling project must use `bun`, have a `bask.ts` that re-exports the base tasks (see [bask](#bask)), and have a commitlint config (e.g. via these configs). The workflows set up bun themselves.
412
+ This repo hosts three reusable workflows you can call from other projects instead of copy/pasting them. The calling project must use `bun`, have a `bask.ts` that re-exports the base tasks (see [bask tasks](#bask-tasks)), and have a commitlint config (e.g. via these configs). The workflows set up bun, actionlint, and OpenTofu themselves.
228
413
 
229
- - `ci.yml`: runs `build` (build + lint) on pushes/PRs and lints commit messages with commitlint
414
+ - `ci.yml`: runs `build` on pushes and PRs, and lints the commit message on pushes and the PR title on PRs
230
415
  - `update-deps.yml`: weekly `bump-deps` run that opens a dependency-update PR
231
416
  - `release.yml`: manually dispatched release where git-cliff sets the version, then publishes to npm and cuts a GitHub release (commit and tag signed)
232
417
 
@@ -241,11 +426,14 @@ on:
241
426
  push:
242
427
  branches: [main]
243
428
  pull_request:
429
+ types: [opened, edited, synchronize, reopened]
244
430
  jobs:
245
431
  ci:
246
432
  uses: adamhl8/configs/.github/workflows/ci.yml@main
247
433
  ```
248
434
 
435
+ On a PR, CI lints the PR title instead of the PR's commits, because squash merges (the only merge type the [GitHub repo settings](#github-repo-settings) allow) use the title as the commit message. The `edited` type reruns the title check when the title changes. An edit skips the build, because it only changes the title or body.
436
+
249
437
  The `bunx bask build` step runs with `GITHUB_TOKEN` set, for builds that call the GitHub API. It comes from the optional `GH_TOKEN` secret (see [Secrets](#secrets)): the names differ because Actions secrets can't be named `GITHUB_*`, so a build reading `GITHUB_TOKEN` can't be fed by a secret of the same name.
250
438
 
251
439
  When the secret is unset it falls back to the workflow's auto-provisioned token, so fork PRs (which receive no secrets) still build. To supply your own token, pass it. Prefer naming it over `secrets: inherit` here: CI runs on every PR, so it shouldn't be handed the release and deploy secrets it never uses.
@@ -279,7 +467,7 @@ jobs:
279
467
 
280
468
  Manually dispatched. `release-it` uses git-cliff (via `release-it-git-cliff`, see [release-it](#release-it)) to compute the next version from the commits, then bumps `package.json`, regenerates the changelog, commits and tags (both SSH-signed), publishes to npm, and cuts a GitHub release. There is no automatic trigger, so run it when a release is ready (the `release` task just does `gh workflow run release.yml`). A dispatch with no releasable commits fails fast because the plugin finds nothing to release.
281
469
 
282
- Needs the `NPM_CI_TOKEN` and `CI_SIGNING_KEY` secrets (see [Secrets](#secrets)). The workflow installs git-cliff and runs the base `release-run` task: `release-it --ci`.
470
+ Needs the `CI_SIGNING_KEY` secret, and `NPM_CI_TOKEN` to publish to npm (see [Secrets](#secrets)). The workflow installs git-cliff and runs the `release-run` task: `release-it --ci`.
283
471
 
284
472
  ```yaml
285
473
  # .github/workflows/release.yml
@@ -294,6 +482,21 @@ jobs:
294
482
  secrets: inherit
295
483
  ```
296
484
 
485
+ Pass `before-release` to run shell commands after the install, just before the release, such as installing system tools the build needs:
486
+
487
+ ```yaml
488
+ jobs:
489
+ release:
490
+ permissions:
491
+ contents: write
492
+ uses: adamhl8/configs/.github/workflows/release.yml@main
493
+ with:
494
+ before-release: |
495
+ sudo apt update
496
+ sudo apt install -y fontforge
497
+ secrets: inherit
498
+ ```
499
+
297
500
  #### Docker
298
501
 
299
502
  Pass `docker-image` to build the repo's `Dockerfile` and push it to `ghcr.io/<owner>/<docker-image>:latest` once the release lands. The image name is separate from the repo name, since they often differ. Omit the input and no image is built.
@@ -318,19 +521,50 @@ jobs:
318
521
 
319
522
  ### Secrets
320
523
 
321
- Configure these on each repo that uses the workflows (Settings -> Secrets and variables -> Actions):
524
+ The [GitHub repo settings](#github-repo-settings) module sets these on each repo that uses the workflows. To set them by hand, use Settings -> Secrets and variables -> Actions.
322
525
 
323
- | Secret | Used by | What it is |
324
- | ---------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
325
- | `CI_TOKEN` | `update-deps.yml` | PAT with `contents` and `pull-requests` write, so the opened PR triggers CI |
326
- | `GH_TOKEN` | `ci.yml`, `release.yml` | Optional. PAT for a build that calls the GitHub API. Reaches a `ci.yml` build as `GITHUB_TOKEN`, and a `release.yml` docker build as the `GH_TOKEN` BuildKit secret. Unset, the `ci.yml` build falls back to the automatic token. |
327
- | `NPM_CI_TOKEN` | `release.yml` | npm automation token with publish access |
328
- | `CI_SIGNING_KEY` | `release.yml` | Private SSH key that signs the release commit and tag. Add the matching public key to your GitHub account as a Signing Key so the signature verifies as you. Use a dedicated, passphrase-less key, not your personal auth key. |
526
+ | Secret | Used by | What it is |
527
+ | ---------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
528
+ | `CI_TOKEN` | `update-deps.yml`, `release.yml` | PAT with `contents` and `pull-requests` write, so the opened PR triggers CI. `release.yml` passes it to the release step as `CI_TOKEN`, for release hooks that need it. |
529
+ | `GH_TOKEN` | `ci.yml`, `release.yml` | Optional. PAT for a build that calls the GitHub API. Reaches a `ci.yml` build as `GITHUB_TOKEN`, and a `release.yml` docker build as the `GH_TOKEN` BuildKit secret. Unset, the `ci.yml` build falls back to the automatic token. |
530
+ | `NPM_CI_TOKEN` | `release.yml` | npm automation token with publish access |
531
+ | `CI_SIGNING_KEY` | `release.yml` | Private SSH key that signs the release commit and tag. Add the matching public key to your GitHub account as a Signing Key so the signature verifies as you. Use a dedicated, passphrase-less key, not your personal auth key. |
329
532
 
330
533
  `GITHUB_TOKEN` is provided automatically. The release wrapper grants it `contents: write` to push the release commit and tag and to create the GitHub release.
331
534
 
332
- ## Notes
535
+ ## GitHub repo settings
536
+
537
+ The `github` OpenTofu module manages a repo's GitHub settings and its Actions [secrets](#secrets). Use it from the project's `github.tofu`:
538
+
539
+ ```hcl
540
+ # github.tofu
541
+ terraform {
542
+ backend "s3" {
543
+ profile = "adamhl8"
544
+ bucket = "<state-bucket>"
545
+ key = "adamhl8/<repo>.tfstate"
546
+ region = "<region>"
547
+ }
548
+ }
549
+
550
+ module "github" {
551
+ source = "./node_modules/@adamhl8/configs/dist/tofu/github"
552
+ repo_name = "<repo>"
553
+ actions_secrets = {
554
+ NPM_CI_TOKEN = true
555
+ }
556
+ repo_settings = {
557
+ visibility = "public"
558
+ }
559
+ }
560
+ ```
561
+
562
+ The repo's description, homepage, and topics come from the `description`, `homepage`, and `keywords` in `package.json`. A homepage that points at the repo itself is left out. The repo only allows squash merges, which use the PR title as the commit message, and deletes branches once they're merged. Secret scanning, push protection, and vulnerability alerts are on.
563
+
564
+ `actions_secrets` picks the secrets to set. `CI_SIGNING_KEY` and `CI_TOKEN` are on by default, and `NPM_CI_TOKEN` and `GH_TOKEN` are off. `additional_secrets` adds other secrets by name. Each value is read from `~/homelab/secrets/credentials.yaml` (a sops file) under the secret's lowercased name. A plan fails when the repo has a secret the module doesn't manage.
565
+
566
+ The `prepare` task runs `tofu init -upgrade`, and the `tofu-check` task (which `build` runs) checks for drift with `tofu plan`. See [bask tasks](#bask-tasks) for when they run.
333
567
 
334
- The `prepare` script is `"prepare": "bask prepare"`, which runs the base `prepare` task (`lefthook install` outside CI, the `.gitignore` sync, and the `bunfig.toml` sync).
568
+ ## Developing this repo
335
569
 
336
570
  bun links a dependency's `package.json` bin executables into the local `node_modules/.bin`, but not the bins of the package being developed itself. This repo depends on itself (`"@adamhl8/configs": "file:."`) so that its own bins can be run directly, e.g. `adamhl8-bunfig` instead of `src/adamhl8-bunfig/index.ts`. That's also why this repo's `bask.ts` runs `tsdown` before the `prepare` task: the bins point at `dist/`, so those builds need to be available.
@@ -1,8 +1,8 @@
1
1
  [test]
2
- pathIgnorePatterns = ["fixtures/**", "fixture/**"]
2
+ pathIgnorePatterns = ["**/fixtures/**", "**/fixture/**"]
3
3
  coverage = true
4
4
  coverageSkipTestFiles = true
5
- coveragePathIgnorePatterns = ["src/test-setup.ts"]
5
+ coveragePathIgnorePatterns = ["**/__tests__/**"]
6
6
  concurrentTestGlob = "**/*.test.ts"
7
7
  onlyFailures = true
8
8
 
@@ -1,7 +1,7 @@
1
1
  import { OptionalMergeConfigFn } from "../merge-config/merge-config.js";
2
2
  import { KnipConfig } from "knip";
3
3
  export declare const knipConfig: OptionalMergeConfigFn<KnipConfig, {
4
- readonly project: ["**/*"];
4
+ readonly project: ["**/*", "!**/fixtures/**", "!**/fixture/**"];
5
5
  readonly bun: {
6
6
  readonly entry: ["**/*.test.ts", "bask.ts"];
7
7
  };
@@ -1 +1 @@
1
- {"version":3,"file":"knip.base.d.ts","names":["_$_merge_config_merge_config_ts0.OptionalMergeConfigFn"],"sources":["../../src/configs/knip.base.ts"],"mappings":";;qBAaa,YAAUA,sBAAA;;;aAJnB"}
1
+ {"version":3,"file":"knip.base.d.ts","names":["_$_merge_config_merge_config_ts0.OptionalMergeConfigFn"],"sources":["../../src/configs/knip.base.ts"],"mappings":";;qBAca,YAAUA,sBAAA;;;aAJnB"}
@@ -1,6 +1,10 @@
1
1
  import { createMergeConfigFn } from "../merge-config/merge-config.js";
2
2
  const knipConfig = createMergeConfigFn({
3
- project: ["**/*"],
3
+ project: [
4
+ "**/*",
5
+ "!**/fixtures/**",
6
+ "!**/fixture/**"
7
+ ],
4
8
  bun: { entry: ["**/*.test.ts", "bask.ts"] }
5
9
  });
6
10
  export { knipConfig };
@@ -1 +1 @@
1
- {"version":3,"file":"knip.base.js","names":[],"sources":["../../src/configs/knip.base.ts"],"sourcesContent":["import type { KnipConfig } from \"knip\"\n\nimport { createMergeConfigFn } from \"#merge-config/merge-config.ts\"\n\nconst baseConfig = {\n project: [\"**/*\"],\n bun: {\n // List `bask.ts` because bask loads it by path and nothing imports it.\n // Add it here because a top-level `entry` replaces knip's default entries.\n entry: [\"**/*.test.ts\", \"bask.ts\"],\n },\n} as const satisfies KnipConfig\n\nexport const knipConfig = createMergeConfigFn<KnipConfig, typeof baseConfig>(baseConfig)\n"],"mappings":";AAaA,MAAa,aAAa,oBAAmD;CAR3E,SAAS,CAAC,MAAM;CAChB,KAAK,EAGH,OAAO,CAAC,gBAAgB,SAAS,EACnC;AAG2E,CAAU"}
1
+ {"version":3,"file":"knip.base.js","names":[],"sources":["../../src/configs/knip.base.ts"],"sourcesContent":["import type { KnipConfig } from \"knip\"\n\nimport { createMergeConfigFn } from \"#merge-config/merge-config.ts\"\n\nconst baseConfig = {\n // Exclude fixtures with negated `project` globs because knip hints to remove an `ignore` glob that hides nothing.\n project: [\"**/*\", \"!**/fixtures/**\", \"!**/fixture/**\"],\n bun: {\n // List `bask.ts` because bask loads it by path and nothing imports it.\n // Add it here because a top-level `entry` replaces knip's default entries.\n entry: [\"**/*.test.ts\", \"bask.ts\"],\n },\n} as const satisfies KnipConfig\n\nexport const knipConfig = createMergeConfigFn<KnipConfig, typeof baseConfig>(baseConfig)\n"],"mappings":";AAcA,MAAa,aAAa,oBAAmD;CAR3E,SAAS;EAAC;EAAQ;EAAmB;CAAgB;CACrD,KAAK,EAGH,OAAO,CAAC,gBAAgB,SAAS,EACnC;AAG2E,CAAU"}
@@ -0,0 +1,17 @@
1
+ import { Shell, ShellOptions } from "./shell/shell.js";
2
+ export interface CopyFixtureOptions {
3
+ /**
4
+ * The start of the temp dir's name.
5
+ *
6
+ * @default `${path.basename(fixture)}-`
7
+ */
8
+ prefix?: string;
9
+ /** Options for the returned shell, which always runs in the copy. */
10
+ shell?: Omit<ShellOptions, "cwd">;
11
+ }
12
+ /** Copies `fixture` into a new temp dir, and returns the dir and a shell that runs there. */
13
+ export declare const copyFixture: (fixture: string, { prefix, shell }?: CopyFixtureOptions) => Promise<{
14
+ dir: string;
15
+ run: Shell;
16
+ }>;
17
+ //# sourceMappingURL=fixture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixture.d.ts","names":["_$_test_utils_shell_shell_ts0.Shell"],"sources":["../../src/test-utils/fixture.ts"],"mappings":";iBAOiB;;;;;;EAMf;;EAEA,QAAQ,KAAK;;;qBAIF,cAAW,mBAAyB,QAAA,UAAqB,uBAAkB;;E,KAAlBA"}
@@ -0,0 +1,20 @@
1
+ import { createShell } from "./shell/shell.js";
2
+ import { makeTempDir } from "./temp-dir.js";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ // src/test-utils/fixture.ts
6
+ /** Copies `fixture` into a new temp dir, and returns the dir and a shell that runs there. */
7
+ const copyFixture = async (fixture, { prefix, shell } = {}) => {
8
+ const dir = await makeTempDir(prefix ?? `${path.basename(fixture)}-`);
9
+ await fs.cp(fixture, dir, { recursive: true });
10
+ return {
11
+ dir,
12
+ run: createShell({
13
+ ...shell,
14
+ cwd: dir
15
+ })
16
+ };
17
+ };
18
+ export { copyFixture };
19
+
20
+ //# sourceMappingURL=fixture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixture.js","names":[],"sources":["../../src/test-utils/fixture.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport path from \"node:path\"\n\nimport { createShell } from \"#test-utils/shell/shell.ts\"\nimport type { ShellOptions } from \"#test-utils/shell/shell.ts\"\nimport { makeTempDir } from \"#test-utils/temp-dir.ts\"\n\nexport interface CopyFixtureOptions {\n /**\n * The start of the temp dir's name.\n *\n * @default `${path.basename(fixture)}-`\n */\n prefix?: string\n /** Options for the returned shell, which always runs in the copy. */\n shell?: Omit<ShellOptions, \"cwd\">\n}\n\n/** Copies `fixture` into a new temp dir, and returns the dir and a shell that runs there. */\nexport const copyFixture = async (fixture: string, { prefix, shell }: CopyFixtureOptions = {}) => {\n const dir = await makeTempDir(prefix ?? `${path.basename(fixture)}-`)\n await fs.cp(fixture, dir, { recursive: true })\n const run = createShell({ ...shell, cwd: dir })\n return { dir, run }\n}\n"],"mappings":";;;;;;AAmBA,MAAa,cAAc,OAAO,SAAiB,EAAE,QAAQ,UAA8B,CAAC,MAAM;CAChG,MAAM,MAAM,MAAM,YAAY,UAAU,GAAG,KAAK,SAAS,OAAO,EAAE,EAAE;CACpE,MAAM,GAAG,GAAG,SAAS,KAAK,EAAE,WAAW,KAAK,CAAC;CAE7C,OAAO;EAAE;EAAK,KADF,YAAY;GAAE,GAAG;GAAO,KAAK;EAAI,CAC7B;CAAE;AACpB"}
@@ -0,0 +1,7 @@
1
+ import { ShellCommand } from "./shell/command.js";
2
+ import { Shell, ShellEnv, ShellOptions, ShellResult, createShell } from "./shell/shell.js";
3
+ import { minimalEnv } from "./shell/env.js";
4
+ import { CopyFixtureOptions, copyFixture } from "./fixture.js";
5
+ import { packPackage } from "./pack.js";
6
+ import { makeTempDir } from "./temp-dir.js";
7
+ export { type CopyFixtureOptions, type Shell, type ShellCommand, type ShellEnv, type ShellOptions, type ShellResult, copyFixture, createShell, makeTempDir, minimalEnv, packPackage };
@@ -0,0 +1,6 @@
1
+ import { minimalEnv } from "./shell/env.js";
2
+ import { createShell } from "./shell/shell.js";
3
+ import { makeTempDir } from "./temp-dir.js";
4
+ import { copyFixture } from "./fixture.js";
5
+ import { packPackage } from "./pack.js";
6
+ export { copyFixture, createShell, makeTempDir, minimalEnv, packPackage };
@@ -0,0 +1,3 @@
1
+ /** Builds the package at `root` when it has a tsdown config, packs it into a temp dir, and returns the tarball path. */
2
+ export declare const packPackage: (root: string) => Promise<string>;
3
+ //# sourceMappingURL=pack.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pack.d.ts","names":[],"sources":["../../src/test-utils/pack.ts"],"mappings":";qBAQa,cAAW,iBAAsB"}
@@ -0,0 +1,16 @@
1
+ import { createShell } from "./shell/shell.js";
2
+ import { makeTempDir } from "./temp-dir.js";
3
+ import path from "node:path";
4
+ import bun from "bun";
5
+ // src/test-utils/pack.ts
6
+ /** Builds the package at `root` when it has a tsdown config, packs it into a temp dir, and returns the tarball path. */
7
+ const packPackage = async (root) => {
8
+ const run = createShell({ cwd: root });
9
+ if (await bun.file(path.join(root, "tsdown.config.ts")).exists()) await run`bun tsdown`;
10
+ const destination = await makeTempDir(`${path.basename(root)}-pack-`);
11
+ const { stdout } = await run`bun pm pack --ignore-scripts --quiet --destination ${destination}`;
12
+ return path.resolve(destination, stdout);
13
+ };
14
+ export { packPackage };
15
+
16
+ //# sourceMappingURL=pack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pack.js","names":[],"sources":["../../src/test-utils/pack.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\n\nimport { createShell } from \"#test-utils/shell/shell.ts\"\nimport { makeTempDir } from \"#test-utils/temp-dir.ts\"\n\n/** Builds the package at `root` when it has a tsdown config, packs it into a temp dir, and returns the tarball path. */\nexport const packPackage = async (root: string) => {\n const run = createShell({ cwd: root })\n if (await bun.file(path.join(root, \"tsdown.config.ts\")).exists()) await run`bun tsdown`\n\n const destination = await makeTempDir(`${path.basename(root)}-pack-`)\n // Skip lifecycle scripts because a `prepare` script would rebuild and run the package's own tasks.\n const { stdout } = await run`bun pm pack --ignore-scripts --quiet --destination ${destination}`\n return path.resolve(destination, stdout)\n}\n"],"mappings":";;;;;;AAQA,MAAa,cAAc,OAAO,SAAiB;CACjD,MAAM,MAAM,YAAY,EAAE,KAAK,KAAK,CAAC;CACrC,IAAI,MAAM,IAAI,KAAK,KAAK,KAAK,MAAM,kBAAkB,CAAC,CAAC,CAAC,OAAO,GAAG,MAAM,GAAG;CAE3E,MAAM,cAAc,MAAM,YAAY,GAAG,KAAK,SAAS,IAAI,EAAE,OAAO;CAEpE,MAAM,EAAE,WAAW,MAAM,GAAG,sDAAsD;CAClF,OAAO,KAAK,QAAQ,aAAa,MAAM;AACzC"}
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,7 @@
1
+ import { removeTempDirs } from "./temp-dir.js";
2
+ import { afterAll } from "bun:test";
3
+ // src/test-utils/preload.ts
4
+ afterAll(removeTempDirs);
5
+ export {};
6
+
7
+ //# sourceMappingURL=preload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preload.js","names":[],"sources":["../../src/test-utils/preload.ts"],"sourcesContent":["import { afterAll } from \"bun:test\"\n\nimport { removeTempDirs } from \"#test-utils/temp-dir.ts\"\n\nafterAll(removeTempDirs)\n"],"mappings":";;;AAIA,SAAS,cAAc"}
@@ -0,0 +1,19 @@
1
+ import path from "node:path";
2
+ // src/test-utils/shell/bin-dirs.ts
3
+ /** Lists `node_modules/.bin` for `dir` and each of its parents, nearest first. */
4
+ const getBinDirs = (dir) => {
5
+ const binDir = path.join(dir, "node_modules", ".bin");
6
+ const parent = path.dirname(dir);
7
+ return parent === dir ? [binDir] : [binDir, ...getBinDirs(parent)];
8
+ };
9
+ /** Puts `node_modules/.bin` of `cwd` and each of its parents first on `PATH`. */
10
+ const addBinDirs = (cwd, env) => {
11
+ const PATH = [...getBinDirs(cwd), env["PATH"]].filter(Boolean).join(path.delimiter);
12
+ return {
13
+ ...env,
14
+ PATH
15
+ };
16
+ };
17
+ export { addBinDirs };
18
+
19
+ //# sourceMappingURL=bin-dirs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin-dirs.js","names":[],"sources":["../../../src/test-utils/shell/bin-dirs.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport type { ShellEnv } from \"#test-utils/shell/shell.ts\"\n\n/** Lists `node_modules/.bin` for `dir` and each of its parents, nearest first. */\nconst getBinDirs = (dir: string): string[] => {\n const binDir = path.join(dir, \"node_modules\", \".bin\")\n const parent = path.dirname(dir)\n return parent === dir ? [binDir] : [binDir, ...getBinDirs(parent)]\n}\n\n/** Puts `node_modules/.bin` of `cwd` and each of its parents first on `PATH`. */\nexport const addBinDirs = (cwd: string, env: ShellEnv): ShellEnv => {\n // Drop an empty `PATH` because the shell reads a trailing empty entry as the cwd.\n const PATH = [...getBinDirs(cwd), env[\"PATH\"]].filter(Boolean).join(path.delimiter)\n\n return { ...env, PATH }\n}\n"],"mappings":";;;AAKA,MAAM,cAAc,QAA0B;CAC5C,MAAM,SAAS,KAAK,KAAK,KAAK,gBAAgB,MAAM;CACpD,MAAM,SAAS,KAAK,QAAQ,GAAG;CAC/B,OAAO,WAAW,MAAM,CAAC,MAAM,IAAI,CAAC,QAAQ,GAAG,WAAW,MAAM,CAAC;AACnE;;AAGA,MAAa,cAAc,KAAa,QAA4B;CAElE,MAAM,OAAO,CAAC,GAAG,WAAW,GAAG,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,KAAK,SAAS;CAElF,OAAO;EAAE,GAAG;EAAK;CAAK;AACxB"}
@@ -0,0 +1,18 @@
1
+ import { ShellEnv, ShellOptions, ShellResult } from "./shell.js";
2
+ import { $ } from "bun";
3
+ /** Wraps Bun's `ShellPromise` to apply its settings when it runs and return its output as strings. */
4
+ export declare class ShellCommand implements PromiseLike<ShellResult> {
5
+ #private;
6
+ /** Starts from the shell's settings, which the command's own methods can then override. */
7
+ constructor(shellPromise: $.ShellPromise, settings: Required<ShellOptions>);
8
+ /** Change the working directory for the command. Relative paths resolve against `process.cwd()`. */
9
+ cwd(newCwd: string): this;
10
+ /** Add environment variables for the command, on top of the shell's. Set one to `undefined` to remove it. */
11
+ env(newEnv: ShellEnv): this;
12
+ /** Configure whether the command puts `node_modules/.bin` of its cwd and each of its parents first on `PATH`. */
13
+ localBins(useLocalBins: boolean): this;
14
+ /** Configure the command to not throw an exception on a non-zero exit code. */
15
+ nothrow(): this;
16
+ then<TResult1 = ShellResult, TResult2 = never>(onfulfilled?: ((value: ShellResult) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
17
+ }
18
+ //# sourceMappingURL=command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.d.ts","names":["BunShell"],"sources":["../../../src/test-utils/shell/command.ts"],"mappings":";;;qBAca,wBAAwB,YAAY;;;EAM/C,YAAmB,cAAcA,EAAS,cAAc,UAAU,SAAS;;EAOpE,IAAI;;EAMJ,IAAI,QAAQ;;EAMZ,UAAU;;EAMV;EAMM,KAAK,WAAW,aAAa,kBACxC,gBAAgB,OAAO,gBAAgB,WAAW,YAAY,mBAC9D,eAAe,oBAAoB,WAAW,YAAY,oBAAiB,QAAA,WAAA"}
@@ -0,0 +1,63 @@
1
+ import { addBinDirs } from "./bin-dirs.js";
2
+ import { removeNodeShims } from "./node-shim.js";
3
+ import path from "node:path";
4
+ import bun from "bun";
5
+ // src/test-utils/shell/command.ts
6
+ const FINAL_NEWLINE = /\r?\n$/v;
7
+ const stripFinalNewline = (output) => output.toString().replace(FINAL_NEWLINE, "");
8
+ /** Wraps Bun's `ShellPromise` to apply its settings when it runs and return its output as strings. */
9
+ var ShellCommand = class {
10
+ #shellPromise;
11
+ #settings;
12
+ #result;
13
+ /** Starts from the shell's settings, which the command's own methods can then override. */
14
+ constructor(shellPromise, settings) {
15
+ this.#shellPromise = shellPromise;
16
+ this.#settings = { ...settings };
17
+ }
18
+ /** Change the working directory for the command. Relative paths resolve against `process.cwd()`. */
19
+ cwd(newCwd) {
20
+ this.#settings.cwd = newCwd;
21
+ return this;
22
+ }
23
+ /** Add environment variables for the command, on top of the shell's. Set one to `undefined` to remove it. */
24
+ env(newEnv) {
25
+ this.#settings.env = {
26
+ ...this.#settings.env,
27
+ ...newEnv
28
+ };
29
+ return this;
30
+ }
31
+ /** Configure whether the command puts `node_modules/.bin` of its cwd and each of its parents first on `PATH`. */
32
+ localBins(useLocalBins) {
33
+ this.#settings.localBins = useLocalBins;
34
+ return this;
35
+ }
36
+ /** Configure the command to not throw an exception on a non-zero exit code. */
37
+ nothrow() {
38
+ this.#settings.throws = false;
39
+ return this;
40
+ }
41
+ async then(onfulfilled, onrejected) {
42
+ this.#result ??= this.#run();
43
+ return this.#result.then(onfulfilled, onrejected);
44
+ }
45
+ async #run() {
46
+ const { env, localBins, throws } = this.#settings;
47
+ const cwd = path.resolve(this.#settings.cwd);
48
+ const envWithBins = localBins ? addBinDirs(cwd, env) : env;
49
+ const finalEnv = removeNodeShims(envWithBins);
50
+ const output = await this.#shellPromise.cwd(cwd).env(finalEnv).quiet().throws(throws).catch((error) => {
51
+ if (error instanceof bun.$.ShellError) throw error;
52
+ throw new Error(`Command failed to start (cwd: ${cwd})`, { cause: error });
53
+ });
54
+ return {
55
+ stdout: stripFinalNewline(output.stdout),
56
+ stderr: stripFinalNewline(output.stderr),
57
+ exitCode: output.exitCode
58
+ };
59
+ }
60
+ };
61
+ export { ShellCommand };
62
+
63
+ //# sourceMappingURL=command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command.js","names":[],"sources":["../../../src/test-utils/shell/command.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { $ as BunShell } from \"bun\"\n\nimport { addBinDirs } from \"#test-utils/shell/bin-dirs.ts\"\nimport { removeNodeShims } from \"#test-utils/shell/node-shim.ts\"\nimport type { ShellEnv, ShellOptions, ShellResult } from \"#test-utils/shell/shell.ts\"\n\nconst FINAL_NEWLINE = /\\r?\\n$/v\n\nconst stripFinalNewline = (output: Buffer) => output.toString().replace(FINAL_NEWLINE, \"\")\n\n/** Wraps Bun's `ShellPromise` to apply its settings when it runs and return its output as strings. */\nexport class ShellCommand implements PromiseLike<ShellResult> {\n readonly #shellPromise: BunShell.ShellPromise\n readonly #settings: Required<ShellOptions>\n #result: Promise<ShellResult> | undefined\n\n /** Starts from the shell's settings, which the command's own methods can then override. */\n public constructor(shellPromise: BunShell.ShellPromise, settings: Required<ShellOptions>) {\n this.#shellPromise = shellPromise\n // Copy `settings` so this command's changes don't reach the shell.\n this.#settings = { ...settings }\n }\n\n /** Change the working directory for the command. Relative paths resolve against `process.cwd()`. */\n public cwd(newCwd: string) {\n this.#settings.cwd = newCwd\n return this\n }\n\n /** Add environment variables for the command, on top of the shell's. Set one to `undefined` to remove it. */\n public env(newEnv: ShellEnv) {\n this.#settings.env = { ...this.#settings.env, ...newEnv }\n return this\n }\n\n /** Configure whether the command puts `node_modules/.bin` of its cwd and each of its parents first on `PATH`. */\n public localBins(useLocalBins: boolean) {\n this.#settings.localBins = useLocalBins\n return this\n }\n\n /** Configure the command to not throw an exception on a non-zero exit code. */\n public nothrow() {\n this.#settings.throws = false\n return this\n }\n\n // oxlint-disable-next-line unicorn/no-thenable - awaiting a command runs it, like Bun's `ShellPromise`\n public async then<TResult1 = ShellResult, TResult2 = never>(\n onfulfilled?: ((value: ShellResult) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ) {\n // Keep the first run because Bun rejects settings on a command that already started.\n this.#result ??= this.#run()\n return this.#result.then(onfulfilled, onrejected)\n }\n\n async #run(): Promise<ShellResult> {\n const { env, localBins, throws } = this.#settings\n const cwd = path.resolve(this.#settings.cwd)\n const envWithBins = localBins ? addBinDirs(cwd, env) : env\n const finalEnv = removeNodeShims(envWithBins)\n\n const output = await this.#shellPromise\n .cwd(cwd)\n .env(finalEnv)\n .quiet()\n .throws(throws)\n .catch((error: unknown) => {\n if (error instanceof bun.$.ShellError) throw error\n // Name the cwd because Bun's start errors (like a missing cwd) don't.\n throw new Error(`Command failed to start (cwd: ${cwd})`, { cause: error })\n })\n\n return {\n stdout: stripFinalNewline(output.stdout),\n stderr: stripFinalNewline(output.stderr),\n exitCode: output.exitCode,\n }\n }\n}\n"],"mappings":";;;;;AASA,MAAM,gBAAgB;AAEtB,MAAM,qBAAqB,WAAmB,OAAO,SAAS,CAAC,CAAC,QAAQ,eAAe,EAAE;;AAGzF,IAAa,eAAb,MAA8D;CAC5D;CACA;CACA;;CAGA,YAAmB,cAAqC,UAAkC;EACxF,KAAK,gBAAgB;EAErB,KAAK,YAAY,EAAE,GAAG,SAAS;CACjC;;CAGA,IAAW,QAAgB;EACzB,KAAK,UAAU,MAAM;EACrB,OAAO;CACT;;CAGA,IAAW,QAAkB;EAC3B,KAAK,UAAU,MAAM;GAAE,GAAG,KAAK,UAAU;GAAK,GAAG;EAAO;EACxD,OAAO;CACT;;CAGA,UAAiB,cAAuB;EACtC,KAAK,UAAU,YAAY;EAC3B,OAAO;CACT;;CAGA,UAAiB;EACf,KAAK,UAAU,SAAS;EACxB,OAAO;CACT;CAGA,MAAa,KACX,aACA,YACA;EAEA,KAAK,YAAY,KAAK,KAAK;EAC3B,OAAO,KAAK,QAAQ,KAAK,aAAa,UAAU;CAClD;CAEA,MAAM,OAA6B;EACjC,MAAM,EAAE,KAAK,WAAW,WAAW,KAAK;EACxC,MAAM,MAAM,KAAK,QAAQ,KAAK,UAAU,GAAG;EAC3C,MAAM,cAAc,YAAY,WAAW,KAAK,GAAG,IAAI;EACvD,MAAM,WAAW,gBAAgB,WAAW;EAE5C,MAAM,SAAS,MAAM,KAAK,cACvB,IAAI,GAAG,CAAC,CACR,IAAI,QAAQ,CAAC,CACb,MAAM,CAAC,CACP,OAAO,MAAM,CAAC,CACd,OAAO,UAAmB;GACzB,IAAI,iBAAiB,IAAI,EAAE,YAAY,MAAM;GAE7C,MAAM,IAAI,MAAM,iCAAiC,IAAI,IAAI,EAAE,OAAO,MAAM,CAAC;EAC3E,CAAC;EAEH,OAAO;GACL,QAAQ,kBAAkB,OAAO,MAAM;GACvC,QAAQ,kBAAkB,OAAO,MAAM;GACvC,UAAU,OAAO;EACnB;CACF;AACF"}
@@ -0,0 +1,4 @@
1
+ import { ShellEnv } from "./shell.js";
2
+ /** Returns `PATH` and `HOME` from `process.env`, merged with `extra`. */
3
+ export declare const minimalEnv: (extra?: ShellEnv) => ShellEnv;
4
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","names":[],"sources":["../../../src/test-utils/shell/env.ts"],"mappings":";;qBAKa,aAAU,QAAW,aAAgB"}
@@ -0,0 +1,11 @@
1
+ import process from "node:process";
2
+ // src/test-utils/shell/env.ts
3
+ /** Returns `PATH` and `HOME` from `process.env`, merged with `extra`. */
4
+ const minimalEnv = (extra = {}) => ({
5
+ PATH: process.env["PATH"],
6
+ HOME: process.env["HOME"],
7
+ ...extra
8
+ });
9
+ export { minimalEnv };
10
+
11
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":[],"sources":["../../../src/test-utils/shell/env.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport type { ShellEnv } from \"#test-utils/shell/shell.ts\"\n\n/** Returns `PATH` and `HOME` from `process.env`, merged with `extra`. */\nexport const minimalEnv = (extra: ShellEnv = {}): ShellEnv => ({\n PATH: process.env[\"PATH\"],\n HOME: process.env[\"HOME\"],\n ...extra,\n})\n"],"mappings":";;;AAKA,MAAa,cAAc,QAAkB,CAAC,OAAiB;CAC7D,MAAM,QAAQ,IAAI;CAClB,MAAM,QAAQ,IAAI;CAClB,GAAG;AACL"}
@@ -0,0 +1,18 @@
1
+ import path from "node:path";
2
+ // src/test-utils/shell/node-shim.ts
3
+ const NODE_SHIM_DIR = /^(?:bask|bun)-node-/v;
4
+ /** Checks for a folder that `bask` or `bun run --bun` puts on `PATH` so `node` runs Bun. */
5
+ const isNodeShimDir = (dir) => NODE_SHIM_DIR.test(path.basename(dir));
6
+ /** Takes every `node` shim off `PATH` so `node` is the real Node however the tests started. */
7
+ const removeNodeShims = (env) => {
8
+ const currentPath = env["PATH"];
9
+ if (currentPath === void 0) return env;
10
+ const PATH = currentPath.split(path.delimiter).filter((dir) => !isNodeShimDir(dir)).join(path.delimiter);
11
+ return {
12
+ ...env,
13
+ PATH
14
+ };
15
+ };
16
+ export { removeNodeShims };
17
+
18
+ //# sourceMappingURL=node-shim.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-shim.js","names":[],"sources":["../../../src/test-utils/shell/node-shim.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport type { ShellEnv } from \"#test-utils/shell/shell.ts\"\n\nconst NODE_SHIM_DIR = /^(?:bask|bun)-node-/v\n\n/** Checks for a folder that `bask` or `bun run --bun` puts on `PATH` so `node` runs Bun. */\nconst isNodeShimDir = (dir: string) => NODE_SHIM_DIR.test(path.basename(dir))\n\n/** Takes every `node` shim off `PATH` so `node` is the real Node however the tests started. */\nexport const removeNodeShims = (env: ShellEnv): ShellEnv => {\n const currentPath = env[\"PATH\"]\n if (currentPath === undefined) return env\n\n const pathDirs = currentPath.split(path.delimiter)\n const PATH = pathDirs.filter((dir) => !isNodeShimDir(dir)).join(path.delimiter)\n\n return { ...env, PATH }\n}\n"],"mappings":";;AAIA,MAAM,gBAAgB;;AAGtB,MAAM,iBAAiB,QAAgB,cAAc,KAAK,KAAK,SAAS,GAAG,CAAC;;AAG5E,MAAa,mBAAmB,QAA4B;CAC1D,MAAM,cAAc,IAAI;CACxB,IAAI,gBAAgB,KAAA,GAAW,OAAO;CAGtC,MAAM,OADW,YAAY,MAAM,KAAK,SACpB,CAAC,CAAC,QAAQ,QAAQ,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC,KAAK,KAAK,SAAS;CAE9E,OAAO;EAAE,GAAG;EAAK;CAAK;AACxB"}
@@ -0,0 +1,42 @@
1
+ import { ShellCommand } from "./command.js";
2
+ import { ShellExpression } from "bun";
3
+ export type ShellEnv = Record<string, string | undefined>;
4
+ export interface ShellOptions {
5
+ /**
6
+ * The working directory for commands. Relative paths resolve against `process.cwd()`.
7
+ *
8
+ * @default process.cwd()
9
+ */
10
+ cwd?: string;
11
+ /**
12
+ * The environment for commands. Replaces `process.env`.
13
+ *
14
+ * @default process.env without `FORCE_COLOR`
15
+ */
16
+ env?: ShellEnv;
17
+ /**
18
+ * Put `node_modules/.bin` of the cwd and each of its parents first on `PATH`.
19
+ *
20
+ * @default true
21
+ */
22
+ localBins?: boolean;
23
+ /**
24
+ * Throw Bun's `ShellError` on a non-zero exit code.
25
+ *
26
+ * @default true
27
+ */
28
+ throws?: boolean;
29
+ }
30
+ export interface ShellResult {
31
+ stdout: string;
32
+ stderr: string;
33
+ exitCode: number;
34
+ }
35
+ /** Runs commands like Bun's `$`, quietly, starting from the shell's options. */
36
+ export type Shell = (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => ShellCommand;
37
+ /**
38
+ * Creates a shell that runs each command quietly and returns its output with one trailing newline stripped. Commands
39
+ * read the test runner's stdin, so add `< /dev/null` to a command that might prompt.
40
+ */
41
+ export declare const createShell: (options?: ShellOptions) => Shell;
42
+ //# sourceMappingURL=shell.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell.d.ts","names":[],"sources":["../../../src/test-utils/shell/shell.ts"],"mappings":";;YAOY,WAAW;iBAEN;;;;;;EAMf;;;;;;EAMA,MAAM;;;;;;EAMN;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;;;YAIU,SAAS,SAAS,yBAAyB,aAAa,sBAAsB;;;;;qBAM7E,cAAW,UAAa,iBAAoB"}
@@ -0,0 +1,24 @@
1
+ import { ShellCommand } from "./command.js";
2
+ import process from "node:process";
3
+ import bun from "bun";
4
+ // src/test-utils/shell/shell.ts
5
+ /**
6
+ * Creates a shell that runs each command quietly and returns its output with one trailing newline stripped. Commands
7
+ * read the test runner's stdin, so add `< /dev/null` to a command that might prompt.
8
+ */
9
+ const createShell = (options = {}) => {
10
+ const bunShell = new bun.$.Shell();
11
+ const settings = {
12
+ cwd: options.cwd ?? process.cwd(),
13
+ env: options.env ?? {
14
+ ...process.env,
15
+ FORCE_COLOR: void 0
16
+ },
17
+ localBins: options.localBins ?? true,
18
+ throws: options.throws ?? true
19
+ };
20
+ return (strings, ...expressions) => new ShellCommand(bunShell(strings, ...expressions), settings);
21
+ };
22
+ export { createShell };
23
+
24
+ //# sourceMappingURL=shell.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell.js","names":[],"sources":["../../../src/test-utils/shell/shell.ts"],"sourcesContent":["import process from \"node:process\"\n\nimport bun from \"bun\"\nimport type { ShellExpression } from \"bun\"\n\nimport { ShellCommand } from \"#test-utils/shell/command.ts\"\n\nexport type ShellEnv = Record<string, string | undefined>\n\nexport interface ShellOptions {\n /**\n * The working directory for commands. Relative paths resolve against `process.cwd()`.\n *\n * @default process.cwd()\n */\n cwd?: string\n /**\n * The environment for commands. Replaces `process.env`.\n *\n * @default process.env without `FORCE_COLOR`\n */\n env?: ShellEnv\n /**\n * Put `node_modules/.bin` of the cwd and each of its parents first on `PATH`.\n *\n * @default true\n */\n localBins?: boolean\n /**\n * Throw Bun's `ShellError` on a non-zero exit code.\n *\n * @default true\n */\n throws?: boolean\n}\n\nexport interface ShellResult {\n stdout: string\n stderr: string\n exitCode: number\n}\n\n/** Runs commands like Bun's `$`, quietly, starting from the shell's options. */\nexport type Shell = (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => ShellCommand\n\n/**\n * Creates a shell that runs each command quietly and returns its output with one trailing newline stripped. Commands\n * read the test runner's stdin, so add `< /dev/null` to a command that might prompt.\n */\nexport const createShell = (options: ShellOptions = {}): Shell => {\n // Use a separate instance so settings on Bun's global `$` don't apply here.\n const bunShell = new bun.$.Shell()\n const settings: Required<ShellOptions> = {\n cwd: options.cwd ?? process.cwd(),\n // Drop `FORCE_COLOR` because `bask` sets it when the tests run in a terminal and CI does not.\n env: options.env ?? { ...process.env, FORCE_COLOR: undefined },\n localBins: options.localBins ?? true,\n throws: options.throws ?? true,\n }\n\n return (strings, ...expressions) => new ShellCommand(bunShell(strings, ...expressions), settings)\n}\n"],"mappings":";;;;;;;;AAiDA,MAAa,eAAe,UAAwB,CAAC,MAAa;CAEhE,MAAM,WAAW,IAAI,IAAI,EAAE,MAAM;CACjC,MAAM,WAAmC;EACvC,KAAK,QAAQ,OAAO,QAAQ,IAAI;EAEhC,KAAK,QAAQ,OAAO;GAAE,GAAG,QAAQ;GAAK,aAAa,KAAA;EAAU;EAC7D,WAAW,QAAQ,aAAa;EAChC,QAAQ,QAAQ,UAAU;CAC5B;CAEA,QAAQ,SAAS,GAAG,gBAAgB,IAAI,aAAa,SAAS,SAAS,GAAG,WAAW,GAAG,QAAQ;AAClG"}
@@ -0,0 +1,3 @@
1
+ /** Makes a temp dir whose name starts with `prefix`, and records it for `removeTempDirs`. */
2
+ export declare const makeTempDir: (prefix: string) => Promise<string>;
3
+ //# sourceMappingURL=temp-dir.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"temp-dir.d.ts","names":[],"sources":["../../src/test-utils/temp-dir.ts"],"mappings":";qBAOa,cAAW,mBAAwB"}
@@ -0,0 +1,21 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ // src/test-utils/temp-dir.ts
5
+ const tempDirs = [];
6
+ /** Makes a temp dir whose name starts with `prefix`, and records it for `removeTempDirs`. */
7
+ const makeTempDir = async (prefix) => {
8
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
9
+ tempDirs.push(dir);
10
+ return dir;
11
+ };
12
+ /** Removes every dir made by `makeTempDir`. */
13
+ const removeTempDirs = async () => {
14
+ await Promise.all(tempDirs.map(async (dir) => fs.rm(dir, {
15
+ recursive: true,
16
+ force: true
17
+ })));
18
+ };
19
+ export { makeTempDir, removeTempDirs };
20
+
21
+ //# sourceMappingURL=temp-dir.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"temp-dir.js","names":[],"sources":["../../src/test-utils/temp-dir.ts"],"sourcesContent":["import fs from \"node:fs/promises\"\nimport os from \"node:os\"\nimport path from \"node:path\"\n\nconst tempDirs: string[] = []\n\n/** Makes a temp dir whose name starts with `prefix`, and records it for `removeTempDirs`. */\nexport const makeTempDir = async (prefix: string) => {\n const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix))\n tempDirs.push(dir)\n return dir\n}\n\n/** Removes every dir made by `makeTempDir`. */\nexport const removeTempDirs = async () => {\n await Promise.all(tempDirs.map(async (dir) => fs.rm(dir, { recursive: true, force: true })))\n}\n"],"mappings":";;;;AAIA,MAAM,WAAqB,CAAC;;AAG5B,MAAa,cAAc,OAAO,WAAmB;CACnD,MAAM,MAAM,MAAM,GAAG,QAAQ,KAAK,KAAK,GAAG,OAAO,GAAG,MAAM,CAAC;CAC3D,SAAS,KAAK,GAAG;CACjB,OAAO;AACT;;AAGA,MAAa,iBAAiB,YAAY;CACxC,MAAM,QAAQ,IAAI,SAAS,IAAI,OAAO,QAAQ,GAAG,GAAG,KAAK;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC,CAAC,CAAC;AAC7F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamhl8/configs",
3
- "version": "3.1.1",
3
+ "version": "3.2.0",
4
4
  "description": "My shared configs for TS projects",
5
5
  "homepage": "https://github.com/adamhl8/configs",
6
6
  "bugs": {
@@ -40,6 +40,14 @@
40
40
  "./bask": {
41
41
  "types": "./dist/configs/bask.base.d.ts",
42
42
  "import": "./dist/configs/bask.base.js"
43
+ },
44
+ "./test": {
45
+ "types": "./dist/test-utils/index.d.ts",
46
+ "import": "./dist/test-utils/index.js"
47
+ },
48
+ "./test/preload": {
49
+ "types": "./dist/test-utils/preload.d.ts",
50
+ "import": "./dist/test-utils/preload.js"
43
51
  }
44
52
  },
45
53
  "publishConfig": {