@adamhl8/bask 0.2.0 → 0.4.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 CHANGED
@@ -1,28 +1,49 @@
1
- # bask
1
+ <h1 align="center"><img align="top" style="color:#36BCF7; width:38px; height:38px;" src="https://raw.githubusercontent.com/adamhl8/bask/refs/heads/main/assets/logo.svg"> bask</h1>
2
2
 
3
- A task runner for Bun where tasks are TypeScript functions.
3
+ A task runner where your tasks are TypeScript functions.
4
4
 
5
- ## Requirements
5
+ ---
6
6
 
7
- - [Bun](https://bun.sh), because tasks run on Bun and shell out with Bun's `$`
7
+ <!-- toc -->
8
8
 
9
- ## Install
9
+ - [Installation](#installation)
10
+ - [Usage](#usage)
11
+ - [Tasks](#tasks)
12
+ - [Defining tasks](#defining-tasks)
13
+ - [Task options](#task-options)
14
+ - [Task naming](#task-naming)
15
+ - [The default task](#the-default-task)
16
+ - [Task dependencies](#task-dependencies)
17
+ - [Task hooks](#task-hooks)
18
+ - [Running commands](#running-commands)
19
+ - [Shell settings](#shell-settings)
20
+ - [Extending/sharing tasks](#extendingsharing-tasks)
21
+ - [CLI Reference](#cli-reference)
10
22
 
11
- ```sh
12
- bun add --dev @adamhl8/bask
13
- ```
23
+ <!-- tocstop -->
24
+
25
+ ## Installation
14
26
 
15
- To run tasks with a plain `bask` instead of `bunx bask`, also install it globally:
27
+ bask requires [Bun](https://bun.sh) to be installed. Tasks are built on top of Bun's `$` shell.
28
+
29
+ - Your project does _not_ need to be Bun-based. You can use bask with any runtime (Node) or package manager (npm, yarn, pnpm, etc.).
16
30
 
17
31
  ```sh
18
- bun add --global @adamhl8/bask
32
+ bun add --dev @adamhl8/bask
19
33
  ```
20
34
 
21
- The global `bask` hands off to the project's copy when there is one, so each project still runs the version it pins.
35
+ > [!TIP]
36
+ > To run tasks with a plain `bask` instead of `bunx bask`, also install it globally:
37
+ >
38
+ > ```sh
39
+ > bun add --global @adamhl8/bask
40
+ > ```
41
+ >
42
+ > The global `bask` hands off to the project's copy when there is one, so each project will use its installed version of bask.
22
43
 
23
44
  ## Usage
24
45
 
25
- Export tasks from a `bask.ts` in your project root. Calling a task from another task makes it a dependency, and each task runs at most once per invocation.
46
+ Create a `bask.ts` in your project root and export some tasks:
26
47
 
27
48
  ```ts
28
49
  import { task } from "@adamhl8/bask"
@@ -32,7 +53,7 @@ export const lint = task(async ({ sh }) => {
32
53
  })
33
54
 
34
55
  export const build = task({ desc: "Lint, then build" }, async ({ sh }) => {
35
- await lint()
56
+ await lint() // calling a task makes it a dependency
36
57
  await sh`tsdown`
37
58
  })
38
59
 
@@ -43,18 +64,23 @@ export const bumpDeps = task(async ({ sh }) => {
43
64
  export default build
44
65
  ```
45
66
 
46
- Run a task with `bask` if you installed it globally, or with `bunx bask` otherwise. Use `bunx` rather than `bun`, because `bun bask` runs your `bask.ts` instead of the `bask` bin. Task names are the export names in kebab-case, so `bump-deps` runs `bumpDeps`.
67
+ Run a task by its export name:
47
68
 
48
69
  ```sh
49
70
  bask build
50
- bask bump-deps
71
+ bask bump-deps # runs `bumpDeps`
51
72
  ```
52
73
 
53
- Scripts and CI should use `bunx bask`, because they can't count on a global install.
74
+ > [!TIP]
75
+ > In scripts or CI, use `bunx bask` so you don't have to install bask globally.
54
76
 
55
- ### The default task and the task list
77
+ Run `bask` with no task name to run the default export (`build` above).
56
78
 
57
- `bask` with no task name runs the default export. If `bask.ts` has no default export, it lists your tasks instead, the same as `bask --list` (or `-l`):
79
+ ```sh
80
+ bask # runs `build`
81
+ ```
82
+
83
+ Run `bask --list` to list available tasks:
58
84
 
59
85
  ```
60
86
  Available tasks:
@@ -63,13 +89,30 @@ Available tasks:
63
89
  lint
64
90
  ```
65
91
 
66
- `export * from` never re-exports a default, so a default from a shared tasks module only applies if you re-export it by name.
92
+ ## Tasks
93
+
94
+ ### Defining tasks
95
+
96
+ `task` takes a function, and optionally an [options](#task-options) object first. The function receives `sh`, a [shell](#running-commands) for running commands, and it can be async or sync:
97
+
98
+ ```ts
99
+ export const build = task({ desc: "Build the project" }, async ({ sh }) => {
100
+ await sh`tsdown`
101
+ })
102
+
103
+ export const hello = task(() => {
104
+ console.log("hello")
105
+ })
106
+ ```
107
+
108
+ ---
67
109
 
68
110
  ### Task options
69
111
 
70
- - `desc`: shown next to the task in the list.
71
- - `hidden`: keeps the task runnable but leaves it out of the list.
72
- - `alias`: other names the task runs under, as a string or an array. Write them in kebab-case or camelCase, and either spelling runs the task.
112
+ - `desc`: Shown next to the task in the task list
113
+ - `hidden`: Keeps the task runnable but leaves it out of the task list
114
+ - `alias`: Other names the task runs under, as a string or an array
115
+ - Write them in kebab-case or camelCase, and either spelling runs the task
73
116
 
74
117
  ```ts
75
118
  export const releaseRun = task({ desc: "Run from CI", hidden: true }, async ({ sh }) => {
@@ -81,56 +124,196 @@ export const bumpDeps = task({ alias: ["up", "update-deps"] }, async ({ sh }) =>
81
124
  })
82
125
  ```
83
126
 
84
- Aliases show next to the task in the list:
127
+ Aliases show next to the task in the task list:
85
128
 
86
129
  ```
87
130
  bump-deps # [aliases: up, update-deps]
88
131
  ```
89
132
 
90
- Use `alias` rather than exporting the same task under a second name. bask can't tell which export is the original, so exporting a task twice is an error. `export default` is the exception.
133
+ ---
91
134
 
92
- ### Running commands
135
+ ### Task naming
93
136
 
94
- `sh` prints each command before running it with Bun's `$`. To run a command without printing it, use Bun's `$` directly.
137
+ A task exported with a camelCase name can be run by using its equivalent kebab-case name.
95
138
 
96
139
  ```ts
97
- import { $ } from "bun"
140
+ export const bumpDeps = task(async ({ sh }) => {
141
+ // ...
142
+ })
143
+ ```
98
144
 
99
- export const release = task(async ({ sh }) => {
100
- const branch = await $`git branch --show-current`.text()
101
- if (branch.trim() === "main") await sh`gh workflow run release.yml`
145
+ These will both run `bumpDeps`:
146
+
147
+ ```sh
148
+ bask bumpDeps
149
+ bask bump-deps
150
+ ```
151
+
152
+ ---
153
+
154
+ ### The default task
155
+
156
+ Running `bask` on its own runs the default export. If `bask.ts` has no default export, it lists your tasks instead (the same as `bask --list`).
157
+
158
+ ```ts
159
+ import { task } from "@adamhl8/bask"
160
+
161
+ export const build = task(async ({ sh }) => {
162
+ await sh`tsdown`
163
+ })
164
+
165
+ export default build
166
+ ```
167
+
168
+ ---
169
+
170
+ ### Task dependencies
171
+
172
+ To depend on another task, call it. Each task runs at most once per invocation, however many tasks call it. If two tasks call it at the same time, they both wait on the same run.
173
+
174
+ ```ts
175
+ export const check = task(async () => {
176
+ await Promise.all([lint(), build()])
177
+ })
178
+
179
+ export const ci = task(async () => {
180
+ await check()
181
+ await lint() // already ran, so this does nothing
182
+ })
183
+ ```
184
+
185
+ ---
186
+
187
+ ### Task hooks
188
+
189
+ > [!IMPORTANT]
190
+ > You'll generally only need hooks when [extending tasks](#extendingsharing-tasks) from another bask file. For tasks in your own `bask.ts`, it's simpler to call them directly from the task.
191
+
192
+ On tasks, use `before` and `after` to add hooks:
193
+
194
+ ```ts
195
+ export const clean = task(async ({ sh }) => {
196
+ await sh`rm -rf dist`
197
+ })
198
+
199
+ export const build = task(async ({ sh }) => {
200
+ await sh`tsdown`
201
+ })
202
+
203
+ build.before(clean)
204
+ build.after(async ({ sh }) => {
205
+ await sh`du -sh dist`
102
206
  })
103
207
  ```
104
208
 
105
- Bun's `$` pipes each command's output, so commands can't tell they're printing to a terminal and usually turn color off. When bask's output goes to a terminal, `sh` sets `FORCE_COLOR=1` on the commands whose output you see. Commands you capture with `.text()`, `.json()`, `.lines()`, `.blob()`, or `.arrayBuffer()` don't get it, and neither do `.quiet()` commands, so captured output is plain text. A `FORCE_COLOR` or `NO_COLOR` in your environment or in `.env()` takes precedence.
209
+ - Hooks take tasks or plain functions
210
+ - Hooks run in the order they were added
211
+ - Hooks run once per invocation, along with their task
212
+ - This includes when another task calls the task
213
+ - Each hook gets its own `sh`, separate from the task's
214
+ - Adding a hook to a task that has already started throws an error
106
215
 
107
- The `stdout` and `stderr` of an awaited `sh` command hold exactly what it printed, colors included.
216
+ The built-in `list` task, which prints the task list, takes hooks too:
217
+
218
+ ```ts
219
+ import { list } from "@adamhl8/bask"
220
+
221
+ list.after(() => {
222
+ console.log("\nRun `bask <task>` to run a task.")
223
+ })
224
+ ```
225
+
226
+ ## Running commands
108
227
 
109
- When a command fails, bask stops and names the task it failed in, then exits with the command's exit code:
228
+ Every task gets a shell, `sh`, which works like Bun's `$`. One difference is that `sh` prints each command before running it:
110
229
 
230
+ ```ts
231
+ export const lint = task(async ({ sh }) => {
232
+ await sh`oxlint --fix`
233
+ // prints "oxlint --fix", then runs it
234
+ })
111
235
  ```
112
- error: task 'lint' failed with exit code 2
236
+
237
+ To run a command without printing it, use `.echo(false)`:
238
+
239
+ ```ts
240
+ export const release = task(async ({ sh }) => {
241
+ const branch = await sh`git branch --show-current`.echo(false).text()
242
+ if (branch.trim() === "main") await sh`gh workflow run release.yml`
243
+ })
113
244
  ```
114
245
 
115
- Any other error thrown in a task still shows its stack trace.
246
+ See the [Bun Shell docs](https://bun.sh/docs/runtime/shell) for the full API.
247
+
248
+ ### Shell settings
116
249
 
117
- `sh` takes the same settings as Bun's global `$`: `sh.cwd()`, `sh.env()`, `sh.nothrow()`, and `sh.throws()`. They apply to the commands the task runs after the call, and a command's own `.cwd()` or `.env()` overrides them for that command.
250
+ The following methods can be used on the `sh` instance _or_ on each command.
251
+
252
+ - `.cwd()` - Changes the working directory
253
+ - Relative paths resolve from the directory you ran `bask` in, not from the `sh` instance's cwd
254
+ - `.env()` - Sets the environment variables
255
+ - This replaces the whole environment, so spread `process.env` to keep it: `.env({ ...process.env, DEBUG: "1" })`
256
+ - `.nothrow()` - Doesn't throw an error when a command exits with a non-zero exit code
257
+ - `.throws()` - Sets whether a non-zero exit code throws an error
258
+ - `.echo()` - Sets whether the command is printed before it runs
259
+
260
+ Each task gets its own fresh instance of `sh`, so changes to `sh` do not affect other tasks' `sh`. Using the above methods on `sh` will apply to every command after the call in the task.
118
261
 
119
262
  ```ts
120
263
  export const buildWeb = task(async ({ sh }) => {
121
264
  sh.cwd("packages/web")
122
265
  await sh`bun install`
123
266
  await sh`bun run build`
267
+ // Override `cwd` for just this command
268
+ await sh`cp -r packages/web/dist packages/server/public`.cwd(".")
124
269
  })
125
270
  ```
126
271
 
127
- Each task and each of its hooks gets its own `sh`, so these settings never reach another task or hook. Settings on Bun's global `$` don't apply to `sh`.
272
+ ## Extending/sharing tasks
128
273
 
129
- ### Extending tasks
274
+ Tasks don't have to live in `bask.ts`. They can live in any other file or package, so many projects can use the same tasks.
275
+
276
+ ```ts
277
+ // shared-tasks.ts
278
+ import { task } from "@adamhl8/bask"
130
279
 
131
- `before` and `after` add hooks that run around a task. A hook added in your `bask.ts` also runs when another task calls that task, including tasks you imported. This lets a project extend shared tasks without replacing them.
280
+ export const lint = task(async ({ sh }) => {
281
+ await sh`oxlint`
282
+ })
283
+
284
+ export const build = task(async ({ sh }) => {
285
+ await lint()
286
+ await sh`tsdown`
287
+ })
288
+ ```
289
+
290
+ To make them runnable, re-export them from your `bask.ts`:
291
+
292
+ ```ts
293
+ // bask.ts
294
+ import { task } from "@adamhl8/bask"
295
+
296
+ export * from "./shared-tasks.ts"
297
+
298
+ export const deploy = task(async ({ sh }) => {
299
+ // ...
300
+ })
301
+ ```
302
+
303
+ The `lint`, `build`, and `deploy` tasks will all be available.
304
+
305
+ > [!IMPORTANT]
306
+ > `export * from` never re-exports a default. If a shared tasks module has a default export, re-export it by name for it to apply:
307
+ >
308
+ > ```ts
309
+ > export * from "./shared-tasks.ts"
310
+ > export { default } from "./shared-tasks.ts"
311
+ > ```
312
+
313
+ If a project needs to do something before or after a shared task, use [hooks](#task-hooks). A hook you add to an imported task also runs when the shared tasks call it. For example:
132
314
 
133
315
  ```ts
316
+ // bask.ts
134
317
  import { task } from "@adamhl8/bask"
135
318
 
136
319
  import { build, lint } from "./shared-tasks.ts"
@@ -141,20 +324,33 @@ export const astroSync = task(async ({ sh }) => {
141
324
  await sh`bun astro sync`
142
325
  })
143
326
 
144
- lint.before(astroSync)
145
- build.after(async ({ sh }) => {
327
+ export const astroBuild = task(async ({ sh }) => {
146
328
  await sh`bun astro build`
147
329
  })
330
+
331
+ lint.before(astroSync)
332
+ build.after(astroBuild)
148
333
  ```
149
334
 
150
- Hooks take tasks or plain functions, run in the order they were added, and run once per invocation along with their task. Adding a hook to a task that has already started throws.
335
+ ```sh
336
+ bask build
337
+ # runs astroSync -> lint -> build -> astroBuild
338
+ ```
151
339
 
152
- The built-in `list` task, which prints the task list, takes hooks too:
340
+ This way, each project extends the shared tasks without copying or replacing them.
153
341
 
154
- ```ts
155
- import { list } from "@adamhl8/bask"
342
+ ## CLI Reference
156
343
 
157
- list.after(() => {
158
- console.log("\nRun `bask <task>` to run a task.")
159
- })
160
- ```
344
+ `bask [options] [task]`
345
+
346
+ - `task`: The task to run, by its kebab-case name, camelCase name, or an alias (default: the default export)
347
+ - `-l`, `--list`: List the available tasks
348
+
349
+ If the task doesn't exist, bask prints an error followed by the task list.
350
+
351
+ **Exit codes:**
352
+
353
+ - `0`: The task succeeded
354
+ - `1`: There's no `bask.ts`, it has a problem (e.g. a task exported twice), or the task doesn't exist
355
+ - `2`: The arguments are invalid
356
+ - Otherwise, the exit code of the command that failed
package/dist/cli.js CHANGED
@@ -1,14 +1,12 @@
1
1
  #!/usr/bin/env bun
2
+ import { printError } from "./utils.js";
2
3
  import { getFailedTask } from "./task.js";
3
4
  import { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from "./registry.js";
4
- import { parseArgs, styleText } from "node:util";
5
- import bun from "bun";
6
5
  import path from "node:path";
6
+ import bun from "bun";
7
+ import { parseArgs } from "node:util";
7
8
  //#region src/cli.ts
8
9
  const isModule = (value) => typeof value === "object" && Boolean(value);
9
- const printError = (message) => {
10
- process.stderr.write(`${styleText(["bold", "red"], "error:", { stream: process.stderr })} ${message}\n`);
11
- };
12
10
  const isParseArgsError = (error) => error instanceof TypeError && "code" in error && typeof error.code === "string" && error.code.startsWith("ERR_PARSE_ARGS_");
13
11
  /** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */
14
12
  const resolveLocalCli = () => {
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\nimport { parseArgs, styleText } from \"node:util\"\n\nimport bun from \"bun\"\n\nimport { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from \"#registry.ts\"\nimport { getFailedTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\nconst isModule = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && Boolean(value)\n\n// Write to `process.stderr` directly because Bun colors all `console.error` output red in a terminal.\nconst printError = (message: string) => {\n process.stderr.write(`${styleText([\"bold\", \"red\"], \"error:\", { stream: process.stderr })} ${message}\\n`)\n}\n\nconst isParseArgsError = (error: unknown): error is TypeError & { code: string } =>\n error instanceof TypeError &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code.startsWith(\"ERR_PARSE_ARGS_\")\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n try {\n return bun.resolveSync(\"@adamhl8/bask/cli\", process.cwd())\n } catch {\n return\n }\n}\n\nconst parseCliArgs = () => {\n try {\n return parseArgs({ options: { list: { type: \"boolean\", short: \"l\" } }, allowPositionals: true })\n } catch (error) {\n if (!isParseArgsError(error)) throw error\n printError(error.message)\n process.exitCode = 2\n return\n }\n}\n\n/** Runs a task and reports a failed command in one line, naming the innermost task that failed. */\nconst runTask = async (taskToRun: Task, taskName: string) => {\n try {\n await taskToRun()\n } catch (error) {\n // Rethrow anything else, because a bug in a task file needs its stack trace.\n if (!(error instanceof bun.$.ShellError)) throw error\n\n const failedTask = getFailedTask(error)\n const failedEntry = getTaskIndex()\n .values()\n .find((entry) => entry.task === failedTask)\n // Fall back to the task you ran, because a task that isn't exported has no name.\n const failedName = failedEntry?.name ?? taskName\n printError(`task '${failedName}' failed with exit code ${error.exitCode}`)\n process.exitCode = error.exitCode\n }\n}\n\nconst main = async () => {\n // Import the local CLI and stop, because it runs its own `main` when loaded.\n // The local copy resolves to its own path, so it skips this and runs normally.\n const localCli = resolveLocalCli()\n if (localCli && localCli !== import.meta.path) {\n await import(localCli)\n return\n }\n\n const args = parseCliArgs()\n if (!args) return\n const { values, positionals } = args\n\n const baskPath = path.resolve(\"bask.ts\")\n if (!(await bun.file(baskPath).exists())) {\n printError(`no bask.ts in ${process.cwd()}`)\n process.exitCode = 1\n return\n }\n\n const baskModule: unknown = await import(baskPath)\n if (!isModule(baskModule)) throw new Error(\"failed to import bask.ts\")\n try {\n setBaskModule(baskModule)\n } catch (error) {\n if (!(error instanceof BaskFileError)) throw error\n printError(error.message)\n process.exitCode = 1\n return\n }\n\n const [taskName] = positionals\n\n if (values.list || (taskName === undefined && !getTaskIndex().has(\"default\"))) {\n await runTask(list, \"list\")\n return\n }\n\n const selectedEntry = getTaskIndex().get(taskName ?? \"default\")\n\n if (!selectedEntry) {\n printError(`unknown task '${taskName ?? \"default\"}'`)\n process.stderr.write(`\\n${formatTaskList()}\\n`)\n process.exitCode = 1\n return\n }\n\n await runTask(selectedEntry.task, selectedEntry.name)\n}\n\nawait main()\n"],"mappings":";;;;;;;AAWA,MAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,QAAQ,KAAK;AAGjH,MAAM,cAAc,YAAoB;CACtC,QAAQ,OAAO,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,GAAG,UAAU,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG,QAAQ,GAAG;AACzG;AAEA,MAAM,oBAAoB,UACxB,iBAAiB,aACjB,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,MAAM,KAAK,WAAW,iBAAiB;;AAGzC,MAAM,wBAAwB;CAC5B,IAAI;EACF,OAAO,IAAI,YAAY,qBAAqB,QAAQ,IAAI,CAAC;CAC3D,QAAQ;EACN;CACF;AACF;AA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M,CAAC,YAAY;CAEnB,IAAI,OAAO,QAAS,aAAa,KAAA,KAAa,CAAC,aAAa,CAAC,CAAC,IAAI,SAAS,GAAI;EAC7E,MAAM,QAAQ,MAAM,MAAM;EAC1B;CACF;CAEA,MAAM,gBAAgB,aAAa,CAAC,CAAC,IAAI,YAAY,SAAS;CAE9D,IAAI,CAAC,eAAe;EAClB,WAAW,iBAAiB,YAAY,UAAU,EAAE;EACpD,QAAQ,OAAO,MAAM,KAAK,eAAe,EAAE,GAAG;EAC9C,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,QAAQ,cAAc,MAAM,cAAc,IAAI;AACtD;AAEA,MAAM,KAAK"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\nimport { parseArgs } from \"node:util\"\n\nimport bun from \"bun\"\n\nimport { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from \"#registry.ts\"\nimport { getFailedTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\nimport { printError } from \"#utils.ts\"\n\nconst isModule = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && Boolean(value)\n\nconst isParseArgsError = (error: unknown): error is TypeError & { code: string } =>\n error instanceof TypeError &&\n \"code\" in error &&\n typeof error.code === \"string\" &&\n error.code.startsWith(\"ERR_PARSE_ARGS_\")\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n try {\n return bun.resolveSync(\"@adamhl8/bask/cli\", process.cwd())\n } catch {\n return\n }\n}\n\nconst parseCliArgs = () => {\n try {\n return parseArgs({ options: { list: { type: \"boolean\", short: \"l\" } }, allowPositionals: true })\n } catch (error) {\n if (!isParseArgsError(error)) throw error\n printError(error.message)\n process.exitCode = 2\n return\n }\n}\n\n/** Runs a task and reports a failed command in one line, naming the innermost task that failed. */\nconst runTask = async (taskToRun: Task, taskName: string) => {\n try {\n await taskToRun()\n } catch (error) {\n // Rethrow anything else, because a bug in a task file needs its stack trace.\n if (!(error instanceof bun.$.ShellError)) throw error\n\n const failedTask = getFailedTask(error)\n const failedEntry = getTaskIndex()\n .values()\n .find((entry) => entry.task === failedTask)\n // Fall back to the task you ran, because a task that isn't exported has no name.\n const failedName = failedEntry?.name ?? taskName\n printError(`task '${failedName}' failed with exit code ${error.exitCode}`)\n process.exitCode = error.exitCode\n }\n}\n\nconst main = async () => {\n // Import the local CLI and stop, because it runs its own `main` when loaded.\n // The local copy resolves to its own path, so it skips this and runs normally.\n const localCli = resolveLocalCli()\n if (localCli && localCli !== import.meta.path) {\n await import(localCli)\n return\n }\n\n const args = parseCliArgs()\n if (!args) return\n const { values, positionals } = args\n\n const baskPath = path.resolve(\"bask.ts\")\n if (!(await bun.file(baskPath).exists())) {\n printError(`no bask.ts in ${process.cwd()}`)\n process.exitCode = 1\n return\n }\n\n const baskModule: unknown = await import(baskPath)\n if (!isModule(baskModule)) throw new Error(\"failed to import bask.ts\")\n try {\n setBaskModule(baskModule)\n } catch (error) {\n if (!(error instanceof BaskFileError)) throw error\n printError(error.message)\n process.exitCode = 1\n return\n }\n\n const [taskName] = positionals\n\n if (values.list || (taskName === undefined && !getTaskIndex().has(\"default\"))) {\n await runTask(list, \"list\")\n return\n }\n\n const selectedEntry = getTaskIndex().get(taskName ?? \"default\")\n\n if (!selectedEntry) {\n printError(`unknown task '${taskName ?? \"default\"}'`)\n process.stderr.write(`\\n${formatTaskList()}\\n`)\n process.exitCode = 1\n return\n }\n\n await runTask(selectedEntry.task, selectedEntry.name)\n}\n\nawait main()\n"],"mappings":";;;;;;;;AAYA,MAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,QAAQ,KAAK;AAEjH,MAAM,oBAAoB,UACxB,iBAAiB,aACjB,UAAU,SACV,OAAO,MAAM,SAAS,YACtB,MAAM,KAAK,WAAW,iBAAiB;;AAGzC,MAAM,wBAAwB;CAC5B,IAAI;EACF,OAAO,IAAI,YAAY,qBAAqB,QAAQ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OAAO;EACxB,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,CAAC,YAAY;CAEnB,IAAI,OAAO,QAAS,aAAa,KAAA,KAAa,CAAC,aAAa,CAAC,CAAC,IAAI,SAAS,GAAI;EAC7E,MAAM,QAAQ,MAAM,MAAM;EAC1B;CACF;CAEA,MAAM,gBAAgB,aAAa,CAAC,CAAC,IAAI,YAAY,SAAS;CAE9D,IAAI,CAAC,eAAe;EAClB,WAAW,iBAAiB,YAAY,UAAU,EAAE;EACpD,QAAQ,OAAO,MAAM,KAAK,eAAe,EAAE,GAAG;EAC9C,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,QAAQ,cAAc,MAAM,cAAc,IAAI;AACtD;AAEA,MAAM,KAAK"}
package/dist/index.js CHANGED
@@ -1,3 +1,15 @@
1
+ import { printError } from "./utils.js";
1
2
  import { isTask, task } from "./task.js";
2
3
  import { list } from "./registry.js";
4
+ import path from "node:path";
5
+ import bun from "bun";
6
+ //#region src/index.ts
7
+ if (path.basename(bun.main) === "bask.ts") {
8
+ const command = ["bask", ...process.argv.slice(2)].join(" ");
9
+ printError(`bask.ts can't be run directly. Use \`bunx\` instead of \`bun\`.\nEither run \`bunx ${command}\` or run \`${command}\` directly (if installed globally).`);
10
+ process.exit(1);
11
+ }
12
+ //#endregion
3
13
  export { isTask, list, task };
14
+
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\n\nimport { printError } from \"#utils.ts\"\n\n// Stop a `bun bask` run because Bun runs bask.ts itself instead of the bask CLI.\nif (path.basename(bun.main) === \"bask.ts\") {\n const command = [\"bask\", ...process.argv.slice(2)].join(\" \")\n printError(\n `bask.ts can't be run directly. Use \\`bunx\\` instead of \\`bun\\`.\\nEither run \\`bunx ${command}\\` or run \\`${command}\\` directly (if installed globally).`,\n )\n process.exit(1)\n}\n\nexport { list } from \"#registry.ts\"\nexport { isTask, task } from \"#task.ts\"\nexport type { Task } from \"#task.ts\"\n"],"mappings":";;;;;;AAOA,IAAI,KAAK,SAAS,IAAI,IAAI,MAAM,WAAW;CACzC,MAAM,UAAU,CAAC,QAAQ,GAAG,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CAC3D,WACE,sFAAsF,QAAQ,cAAc,QAAQ,qCACtH;CACA,QAAQ,KAAK,CAAC;AAChB"}
package/dist/shell.d.ts CHANGED
@@ -1,30 +1,52 @@
1
1
  import { $, ShellExpression } from "bun";
2
2
  //#region src/shell.d.ts
3
3
  type ShellEnv = Parameters<$.ShellPromise["env"]>[0];
4
- /** Changes each method of `T` that returns `From` to return `To`, keeping Bun's docs on it. */
5
- type Rechain<T, From, To> = { [K in keyof T]: T[K] extends ((...args: infer Args) => From) ? (...args: Args) => To : T[K]; };
6
- type BunCommandMethods = Omit<$.ShellPromise, keyof Promise<$.ShellOutput> | "stdin">;
7
- type ShellSettingKey = Exclude<keyof $, "braces" | "escape" | "Shell" | "ShellError" | "ShellPromise">;
8
4
  /** Runs commands like Bun's `$`, with settings that apply to every later command from the same shell. */
9
- export interface Shell extends Rechain<Pick<$, ShellSettingKey>, $, Shell> {
5
+ export interface Shell {
10
6
  (strings: TemplateStringsArray, ...expressions: ShellExpression[]): ShellCommand;
7
+ /** Change the default working directory for commands run by this shell. */
8
+ cwd: (newCwd?: string) => Shell;
9
+ /** Change the default environment variables for commands run by this shell. */
10
+ env: (newEnv?: ShellEnv) => Shell;
11
+ /** Configure the shell to not throw an exception on non-zero exit codes. */
12
+ nothrow: () => Shell;
13
+ /** Configure whether the shell should throw an exception on non-zero exit codes. */
14
+ throws: (shouldThrow: boolean) => Shell;
15
+ /** Configure whether the shell prints each command before running it. */
16
+ echo: (shouldEcho: boolean) => Shell;
11
17
  }
12
18
  /**
13
19
  * Wraps Bun's `ShellPromise` to set `FORCE_COLOR` only on commands whose output is shown. Bun's pipes hide the terminal
14
20
  * from commands, so they turn color off unless forced.
15
21
  */
16
- declare class ShellCommand implements PromiseLike<$.ShellOutput>, Rechain<BunCommandMethods, $.ShellPromise, ShellCommand> {
22
+ declare class ShellCommand implements PromiseLike<$.ShellOutput> {
17
23
  #private;
18
- constructor(promise: $.ShellPromise, env: ShellEnv);
24
+ constructor(promise: $.ShellPromise, { command, env, shouldEcho }: {
25
+ command: string;
26
+ env: ShellEnv;
27
+ shouldEcho: boolean;
28
+ });
29
+ /** Change the current working directory of the shell. */
19
30
  cwd(newCwd: string): this;
31
+ /** Set environment variables for the shell. */
20
32
  env(newEnv: ShellEnv): this;
33
+ /** Configure the shell to only buffer the output instead of also writing it to stdout and stderr. */
21
34
  quiet(isQuiet?: boolean): this;
35
+ /** Configure the shell to not throw an exception on non-zero exit codes. */
22
36
  nothrow(): this;
37
+ /** Configure whether the shell should throw an exception on non-zero exit codes. */
23
38
  throws(shouldThrow: boolean): this;
39
+ /** Configure whether the shell prints the command before running it. */
40
+ echo(shouldEcho: boolean): this;
41
+ /** Read from stdout as a string. Automatically calls {@link quiet}. */
24
42
  text(encoding?: BufferEncoding): Promise<string>;
43
+ /** Read from stdout as a JSON object. Automatically calls {@link quiet}. */
25
44
  json(): Promise<any>;
45
+ /** Read from stdout as a string, line by line. Automatically calls {@link quiet}. */
26
46
  lines(): AsyncIterable<string>;
47
+ /** Read from stdout as an ArrayBuffer. Automatically calls {@link quiet}. */
27
48
  arrayBuffer(): Promise<ArrayBuffer>;
49
+ /** Read from stdout as a Blob. Automatically calls {@link quiet}. */
28
50
  blob(): Promise<Blob>;
29
51
  then<TResult1 = $.ShellOutput, TResult2 = never>(onfulfilled?: ((value: $.ShellOutput) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
30
52
  catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<TResult | $.ShellOutput>;
@@ -1 +1 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,IAAI,QAAQ;;EAMZ,MAAM;;EAON;;EAMA,OAAO;;EAMP,KAAK;;EAMC,KAAK,WAAW,iBAAc;;EAK9B,QAAI;;EAMV,SAAK;;EAKC,eAAW,QAAA;;EAKX,QAAI,QAAA;EAKJ,KAAK,WAAWA,EAAS,aAAa,kBACjD,gBAAgB,OAAOA,EAAS,gBAAgB,WAAW,YAAY,mBACvE,eAAe,oBAAoB,WAAW,YAAY,oBAAiB,QAAA,WAAA;EAKhE,MAAM,iBAAiB,eAAe,oBAAoB,UAAU,YAAY,mBAAgB,QAAA,UAAAA,EAAA;EAIhG,QAAQ,kCAA+B,QAAAA,EAAA"}
package/dist/shell.js CHANGED
@@ -1,5 +1,5 @@
1
- import { styleText } from "node:util";
2
1
  import bun from "bun";
2
+ import { styleText } from "node:util";
3
3
  //#region src/shell.ts
4
4
  /** Formats an interpolated value the way Bun's shell escapes it. */
5
5
  const formatExpression = (expression) => {
@@ -15,46 +15,65 @@ const shouldForceColor = (env) => process.stdout.isTTY && process.stderr.isTTY &
15
15
  */
16
16
  var ShellCommand = class {
17
17
  #promise;
18
+ #command;
18
19
  #env;
20
+ #shouldEcho;
19
21
  #isQuiet = false;
20
22
  #isPrepared = false;
21
- constructor(promise, env) {
23
+ constructor(promise, { command, env, shouldEcho }) {
22
24
  this.#promise = promise;
25
+ this.#command = command;
23
26
  this.#env = env;
27
+ this.#shouldEcho = shouldEcho;
24
28
  }
29
+ /** Change the current working directory of the shell. */
25
30
  cwd(newCwd) {
26
31
  this.#promise.cwd(newCwd);
27
32
  return this;
28
33
  }
34
+ /** Set environment variables for the shell. */
29
35
  env(newEnv) {
30
36
  this.#env = newEnv;
31
37
  return this;
32
38
  }
39
+ /** Configure the shell to only buffer the output instead of also writing it to stdout and stderr. */
33
40
  quiet(isQuiet = true) {
34
41
  this.#promise.quiet(isQuiet);
35
42
  this.#isQuiet = isQuiet;
36
43
  return this;
37
44
  }
45
+ /** Configure the shell to not throw an exception on non-zero exit codes. */
38
46
  nothrow() {
39
47
  this.#promise.nothrow();
40
48
  return this;
41
49
  }
50
+ /** Configure whether the shell should throw an exception on non-zero exit codes. */
42
51
  throws(shouldThrow) {
43
52
  this.#promise.throws(shouldThrow);
44
53
  return this;
45
54
  }
55
+ /** Configure whether the shell prints the command before running it. */
56
+ echo(shouldEcho) {
57
+ this.#shouldEcho = shouldEcho;
58
+ return this;
59
+ }
60
+ /** Read from stdout as a string. Automatically calls {@link quiet}. */
46
61
  async text(encoding) {
47
62
  return this.#prepare(false).text(encoding);
48
63
  }
64
+ /** Read from stdout as a JSON object. Automatically calls {@link quiet}. */
49
65
  async json() {
50
66
  return this.#prepare(false).json();
51
67
  }
68
+ /** Read from stdout as a string, line by line. Automatically calls {@link quiet}. */
52
69
  lines() {
53
70
  return this.#prepare(false).lines();
54
71
  }
72
+ /** Read from stdout as an ArrayBuffer. Automatically calls {@link quiet}. */
55
73
  async arrayBuffer() {
56
74
  return this.#prepare(false).arrayBuffer();
57
75
  }
76
+ /** Read from stdout as a Blob. Automatically calls {@link quiet}. */
58
77
  async blob() {
59
78
  return this.#prepare(false).blob();
60
79
  }
@@ -67,10 +86,11 @@ var ShellCommand = class {
67
86
  async finally(onfinally) {
68
87
  return this.#prepare(!this.#isQuiet).finally(onfinally);
69
88
  }
70
- /** Sets the command's environment once, before Bun starts the command. */
89
+ /** Prints the command and sets its environment once, before Bun starts the command. */
71
90
  #prepare(isShown) {
72
91
  if (this.#isPrepared) return this.#promise;
73
92
  this.#isPrepared = true;
93
+ if (this.#shouldEcho) process.stderr.write(`${styleText("bold", this.#command, { stream: process.stderr })}\n`);
74
94
  const env = this.#env ?? process.env;
75
95
  this.#promise.env(isShown && shouldForceColor(env) ? {
76
96
  ...env,
@@ -83,10 +103,14 @@ var ShellCommand = class {
83
103
  const createShell = () => {
84
104
  const bunShell = new bun.$.Shell();
85
105
  let shellEnv;
106
+ let shouldEcho = true;
86
107
  const run = (strings, ...expressions) => {
87
- const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression));
88
- process.stderr.write(`${styleText("bold", command.trim(), { stream: process.stderr })}\n`);
89
- return new ShellCommand(bunShell(strings, ...expressions), shellEnv);
108
+ const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression)).trim();
109
+ return new ShellCommand(bunShell(strings, ...expressions), {
110
+ command,
111
+ env: shellEnv,
112
+ shouldEcho
113
+ });
90
114
  };
91
115
  const shell = Object.assign(run, {
92
116
  cwd: (newCwd) => {
@@ -104,6 +128,10 @@ const createShell = () => {
104
128
  throws: (shouldThrow) => {
105
129
  bunShell.throws(shouldThrow);
106
130
  return shell;
131
+ },
132
+ echo: (newShouldEcho) => {
133
+ shouldEcho = newShouldEcho;
134
+ return shell;
107
135
  }
108
136
  });
109
137
  return shell;
package/dist/shell.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\nimport bun from \"bun\"\nimport type { $ as BunShell, ShellExpression } from \"bun\"\n\ntype ShellEnv = Parameters<BunShell.ShellPromise[\"env\"]>[0]\n\n/** Changes each method of `T` that returns `From` to return `To`, keeping Bun's docs on it. */\ntype Rechain<T, From, To> = {\n [K in keyof T]: T[K] extends (...args: infer Args) => From ? (...args: Args) => To : T[K]\n}\n\n// Leave out `stdin` because Bun's types declare it but the runtime doesn't have it.\ntype BunCommandMethods = Omit<BunShell.ShellPromise, keyof Promise<BunShell.ShellOutput> | \"stdin\">\n\n// Treat every other member of Bun's `$` as a setting, so a new one fails to compile until `createShell` handles it.\ntype ShellSettingKey = Exclude<keyof BunShell, \"braces\" | \"escape\" | \"Shell\" | \"ShellError\" | \"ShellPromise\">\n\n/** Runs commands like Bun's `$`, with settings that apply to every later command from the same shell. */\nexport interface Shell extends Rechain<Pick<BunShell, ShellSettingKey>, BunShell, Shell> {\n (strings: TemplateStringsArray, ...expressions: ShellExpression[]): ShellCommand\n}\n\n/** Formats an interpolated value the way Bun's shell escapes it. */\nconst formatExpression = (expression: ShellExpression): string => {\n if (Array.isArray(expression)) return expression.map(formatExpression).join(\" \")\n if (typeof expression === \"object\" && expression !== null && \"raw\" in expression) return expression.raw\n // Print streams, files, and subprocesses as their default string because they have no command text.\n // oxlint-disable-next-line typescript/no-base-to-string\n return bun.$.escape(String(expression))\n}\n\n/** Checks whether bask should turn on color for a command whose output goes to the terminal. */\nconst shouldForceColor = (env: NonNullable<ShellEnv>) =>\n process.stdout.isTTY &&\n process.stderr.isTTY &&\n // oxlint-disable-next-line node/no-process-env - check the user's own color settings\n [process.env, env].every((vars) => vars[\"FORCE_COLOR\"] === undefined && vars[\"NO_COLOR\"] === undefined)\n\n/**\n * Wraps Bun's `ShellPromise` to set `FORCE_COLOR` only on commands whose output is shown. Bun's pipes hide the terminal\n * from commands, so they turn color off unless forced.\n */\nclass ShellCommand\n implements PromiseLike<BunShell.ShellOutput>, Rechain<BunCommandMethods, BunShell.ShellPromise, ShellCommand>\n{\n readonly #promise: BunShell.ShellPromise\n #env: ShellEnv\n #isQuiet = false\n #isPrepared = false\n\n public constructor(promise: BunShell.ShellPromise, env: ShellEnv) {\n this.#promise = promise\n this.#env = env\n }\n\n public cwd(newCwd: string) {\n void this.#promise.cwd(newCwd)\n return this\n }\n\n public env(newEnv: ShellEnv) {\n this.#env = newEnv\n return this\n }\n\n public quiet(isQuiet = true) {\n void this.#promise.quiet(isQuiet)\n this.#isQuiet = isQuiet\n return this\n }\n\n public nothrow() {\n void this.#promise.nothrow()\n return this\n }\n\n public throws(shouldThrow: boolean) {\n void this.#promise.throws(shouldThrow)\n return this\n }\n\n public async text(encoding?: BufferEncoding) {\n return this.#prepare(false).text(encoding)\n }\n\n public async json() {\n // oxlint-disable-next-line typescript/no-unsafe-return - match Bun's `json()`, which returns `any`\n return this.#prepare(false).json()\n }\n\n public lines() {\n return this.#prepare(false).lines()\n }\n\n public async arrayBuffer() {\n return this.#prepare(false).arrayBuffer()\n }\n\n public async blob() {\n return this.#prepare(false).blob()\n }\n\n // oxlint-disable-next-line unicorn/no-thenable - awaiting a command runs it, like Bun's `ShellPromise`\n public async then<TResult1 = BunShell.ShellOutput, TResult2 = never>(\n onfulfilled?: ((value: BunShell.ShellOutput) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ) {\n return this.#prepare(!this.#isQuiet).then(onfulfilled, onrejected)\n }\n\n public async catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null) {\n return this.then(undefined, onrejected)\n }\n\n public async finally(onfinally?: (() => void) | null) {\n return this.#prepare(!this.#isQuiet).finally(onfinally)\n }\n\n /** Sets the command's environment once, before Bun starts the command. */\n // oxlint-disable-next-line typescript/promise-function-async - an async function would await the command and start it\n #prepare(isShown: boolean) {\n // Skip a command that already started, because Bun rejects `env` on it.\n if (this.#isPrepared) return this.#promise\n this.#isPrepared = true\n\n // Pass `process.env` even without color because Bun copies it when the command is created, not when it runs.\n // oxlint-disable-next-line node/no-process-env - read the environment as it is when the command runs\n const env = this.#env ?? process.env\n void this.#promise.env(isShown && shouldForceColor(env) ? { ...env, FORCE_COLOR: \"1\" } : env)\n return this.#promise\n }\n}\n\n/** Creates a shell that prints each command to stderr before running it. */\nexport const createShell = () => {\n // Use a separate instance so settings on Bun's global `$` or another shell don't apply here.\n const bunShell = new bun.$.Shell()\n // Keep `env` here instead of on `bunShell` because `ShellCommand` passes it when each command runs.\n let shellEnv: ShellEnv\n\n const run = (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => {\n // Use `String.raw` because Bun's `$` also reads the raw template strings.\n const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression))\n // Write to `process.stderr` directly because Bun colors `console.error` output red in a terminal.\n process.stderr.write(`${styleText(\"bold\", command.trim(), { stream: process.stderr })}\\n`)\n return new ShellCommand(bunShell(strings, ...expressions), shellEnv)\n }\n\n const shell: Shell = Object.assign(run, {\n cwd: (newCwd?: string) => {\n bunShell.cwd(newCwd)\n return shell\n },\n env: (newEnv?: ShellEnv) => {\n shellEnv = newEnv\n return shell\n },\n nothrow: () => {\n bunShell.nothrow()\n return shell\n },\n throws: (shouldThrow: boolean) => {\n bunShell.throws(shouldThrow)\n return shell\n },\n })\n\n return shell\n}\n"],"mappings":";;;;AAwBA,MAAM,oBAAoB,eAAwC;CAChE,IAAI,MAAM,QAAQ,UAAU,GAAG,OAAO,WAAW,IAAI,gBAAgB,CAAC,CAAC,KAAK,GAAG;CAC/E,IAAI,OAAO,eAAe,YAAY,eAAe,QAAQ,SAAS,YAAY,OAAO,WAAW;CAGpG,OAAO,IAAI,EAAE,OAAO,OAAO,UAAU,CAAC;AACxC;;AAGA,MAAM,oBAAoB,QACxB,QAAQ,OAAO,SACf,QAAQ,OAAO,SAEf,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,OAAO,SAAS,KAAK,mBAAmB,KAAA,KAAa,KAAK,gBAAgB,KAAA,CAAS;;;;;AAMxG,IAAM,eAAN,MAEA;CACE;CACA;CACA,WAAW;CACX,cAAc;CAEd,YAAmB,SAAgC,KAAe;EAChE,KAAK,WAAW;EAChB,KAAK,OAAO;CACd;CAEA,IAAW,QAAgB;EACzB,KAAU,SAAS,IAAI,MAAM;EAC7B,OAAO;CACT;CAEA,IAAW,QAAkB;EAC3B,KAAK,OAAO;EACZ,OAAO;CACT;CAEA,MAAa,UAAU,MAAM;EAC3B,KAAU,SAAS,MAAM,OAAO;EAChC,KAAK,WAAW;EAChB,OAAO;CACT;CAEA,UAAiB;EACf,KAAU,SAAS,QAAQ;EAC3B,OAAO;CACT;CAEA,OAAc,aAAsB;EAClC,KAAU,SAAS,OAAO,WAAW;EACrC,OAAO;CACT;CAEA,MAAa,KAAK,UAA2B;EAC3C,OAAO,KAAK,SAAS,KAAK,CAAC,CAAC,KAAK,QAAQ;CAC3C;CAEA,MAAa,OAAO;EAElB,OAAO,KAAK,SAAS,KAAK,CAAC,CAAC,KAAK;CACnC;CAEA,QAAe;EAC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ACX,OAAO;EACT;EACA,eAAe;GACb,SAAS,QAAQ;GACjB,OAAO;EACT;EACA,SAAS,gBAAyB;GAChC,SAAS,OAAO,WAAW;GAC3B,OAAO;EACT;CACF,CAAC;CAED,OAAO;AACT"}
1
+ {"version":3,"file":"shell.js","names":[],"sources":["../src/shell.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\nimport bun from \"bun\"\nimport type { $ as BunShell, ShellExpression } from \"bun\"\n\ntype ShellEnv = Parameters<BunShell.ShellPromise[\"env\"]>[0]\n\n/** Runs commands like Bun's `$`, with settings that apply to every later command from the same shell. */\nexport interface Shell {\n (strings: TemplateStringsArray, ...expressions: ShellExpression[]): ShellCommand\n /** Change the default working directory for commands run by this shell. */\n cwd: (newCwd?: string) => Shell\n /** Change the default environment variables for commands run by this shell. */\n env: (newEnv?: ShellEnv) => Shell\n /** Configure the shell to not throw an exception on non-zero exit codes. */\n nothrow: () => Shell\n /** Configure whether the shell should throw an exception on non-zero exit codes. */\n throws: (shouldThrow: boolean) => Shell\n /** Configure whether the shell prints each command before running it. */\n echo: (shouldEcho: boolean) => Shell\n}\n\n/** Formats an interpolated value the way Bun's shell escapes it. */\nconst formatExpression = (expression: ShellExpression): string => {\n if (Array.isArray(expression)) return expression.map(formatExpression).join(\" \")\n if (typeof expression === \"object\" && expression !== null && \"raw\" in expression) return expression.raw\n // Print streams, files, and subprocesses as their default string because they have no command text.\n // oxlint-disable-next-line typescript/no-base-to-string\n return bun.$.escape(String(expression))\n}\n\n/** Checks whether bask should turn on color for a command whose output goes to the terminal. */\nconst shouldForceColor = (env: NonNullable<ShellEnv>) =>\n process.stdout.isTTY &&\n process.stderr.isTTY &&\n // oxlint-disable-next-line node/no-process-env - check the user's own color settings\n [process.env, env].every((vars) => vars[\"FORCE_COLOR\"] === undefined && vars[\"NO_COLOR\"] === undefined)\n\n/**\n * Wraps Bun's `ShellPromise` to set `FORCE_COLOR` only on commands whose output is shown. Bun's pipes hide the terminal\n * from commands, so they turn color off unless forced.\n */\nclass ShellCommand implements PromiseLike<BunShell.ShellOutput> {\n readonly #promise: BunShell.ShellPromise\n readonly #command: string\n #env: ShellEnv\n #shouldEcho: boolean\n #isQuiet = false\n #isPrepared = false\n\n public constructor(\n promise: BunShell.ShellPromise,\n { command, env, shouldEcho }: { command: string; env: ShellEnv; shouldEcho: boolean },\n ) {\n this.#promise = promise\n this.#command = command\n this.#env = env\n this.#shouldEcho = shouldEcho\n }\n\n /** Change the current working directory of the shell. */\n public cwd(newCwd: string) {\n void this.#promise.cwd(newCwd)\n return this\n }\n\n /** Set environment variables for the shell. */\n public env(newEnv: ShellEnv) {\n this.#env = newEnv\n return this\n }\n\n /** Configure the shell to only buffer the output instead of also writing it to stdout and stderr. */\n public quiet(isQuiet = true) {\n void this.#promise.quiet(isQuiet)\n this.#isQuiet = isQuiet\n return this\n }\n\n /** Configure the shell to not throw an exception on non-zero exit codes. */\n public nothrow() {\n void this.#promise.nothrow()\n return this\n }\n\n /** Configure whether the shell should throw an exception on non-zero exit codes. */\n public throws(shouldThrow: boolean) {\n void this.#promise.throws(shouldThrow)\n return this\n }\n\n /** Configure whether the shell prints the command before running it. */\n public echo(shouldEcho: boolean) {\n this.#shouldEcho = shouldEcho\n return this\n }\n\n /** Read from stdout as a string. Automatically calls {@link quiet}. */\n public async text(encoding?: BufferEncoding) {\n return this.#prepare(false).text(encoding)\n }\n\n /** Read from stdout as a JSON object. Automatically calls {@link quiet}. */\n public async json() {\n // oxlint-disable-next-line typescript/no-unsafe-return - match Bun's `json()`, which returns `any`\n return this.#prepare(false).json()\n }\n\n /** Read from stdout as a string, line by line. Automatically calls {@link quiet}. */\n public lines() {\n return this.#prepare(false).lines()\n }\n\n /** Read from stdout as an ArrayBuffer. Automatically calls {@link quiet}. */\n public async arrayBuffer() {\n return this.#prepare(false).arrayBuffer()\n }\n\n /** Read from stdout as a Blob. Automatically calls {@link quiet}. */\n public async blob() {\n return this.#prepare(false).blob()\n }\n\n // oxlint-disable-next-line unicorn/no-thenable - awaiting a command runs it, like Bun's `ShellPromise`\n public async then<TResult1 = BunShell.ShellOutput, TResult2 = never>(\n onfulfilled?: ((value: BunShell.ShellOutput) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ) {\n return this.#prepare(!this.#isQuiet).then(onfulfilled, onrejected)\n }\n\n public async catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null) {\n return this.then(undefined, onrejected)\n }\n\n public async finally(onfinally?: (() => void) | null) {\n return this.#prepare(!this.#isQuiet).finally(onfinally)\n }\n\n /** Prints the command and sets its environment once, before Bun starts the command. */\n // oxlint-disable-next-line typescript/promise-function-async - an async function would await the command and start it\n #prepare(isShown: boolean) {\n // Skip a command that already started, because Bun rejects `env` on it.\n if (this.#isPrepared) return this.#promise\n this.#isPrepared = true\n\n // Write to `process.stderr` directly because Bun colors `console.error` output red in a terminal.\n if (this.#shouldEcho) process.stderr.write(`${styleText(\"bold\", this.#command, { stream: process.stderr })}\\n`)\n\n // Pass `process.env` even without color because Bun copies it when the command is created, not when it runs.\n // oxlint-disable-next-line node/no-process-env - read the environment as it is when the command runs\n const env = this.#env ?? process.env\n void this.#promise.env(isShown && shouldForceColor(env) ? { ...env, FORCE_COLOR: \"1\" } : env)\n return this.#promise\n }\n}\n\n/** Creates a shell that prints each command to stderr before running it. */\nexport const createShell = () => {\n // Use a separate instance so settings on Bun's global `$` or another shell don't apply here.\n const bunShell = new bun.$.Shell()\n // Keep `env` here instead of on `bunShell` because `ShellCommand` passes it when each command runs.\n let shellEnv: ShellEnv\n let shouldEcho = true\n\n const run = (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => {\n // Use `String.raw` because Bun's `$` also reads the raw template strings.\n const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression)).trim()\n return new ShellCommand(bunShell(strings, ...expressions), { command, env: shellEnv, shouldEcho })\n }\n\n const shell: Shell = Object.assign(run, {\n cwd: (newCwd?: string) => {\n bunShell.cwd(newCwd)\n return shell\n },\n env: (newEnv?: ShellEnv) => {\n shellEnv = newEnv\n return shell\n },\n nothrow: () => {\n bunShell.nothrow()\n return shell\n },\n throws: (shouldThrow: boolean) => {\n bunShell.throws(shouldThrow)\n return shell\n },\n echo: (newShouldEcho: boolean) => {\n shouldEcho = newShouldEcho\n return shell\n },\n })\n\n return shell\n}\n"],"mappings":";;;;AAuBA,MAAM,oBAAoB,eAAwC;CAChE,IAAI,MAAM,QAAQ,UAAU,GAAG,OAAO,WAAW,IAAI,gBAAgB,CAAC,CAAC,KAAK,GAAG;CAC/E,IAAI,OAAO,eAAe,YAAY,eAAe,QAAQ,SAAS,YAAY,OAAO,WAAW;CAGpG,OAAO,IAAI,EAAE,OAAO,OAAO,UAAU,CAAC;AACxC;;AAGA,MAAM,oBAAoB,QACxB,QAAQ,OAAO,SACf,QAAQ,OAAO,SAEf,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,OAAO,SAAS,KAAK,mBAAmB,KAAA,KAAa,KAAK,gBAAgB,KAAA,CAAS;;;;;AAMxG,IAAM,eAAN,MAAgE;CAC9D;CACA;CACA;CACA;CACA,WAAW;CACX,cAAc;CAEd,YACE,SACA,EAAE,SAAS,KAAK,cAChB;EACA,KAAK,WAAW;EAChB,KAAK,WAAW;EAChB,KAAK,OAAO;EACZ,KAAK,cAAc;CACrB;;CAGA,IAAW,QAAgB;EACzB,KAAU,SAAS,IAAI,MAAM;EAC7B,OAAO;CACT;;CAGA,IAAW,QAAkB;EAC3B,KAAK,OAAO;EACZ,OAAO;CACT;;CAGA,MAAa,UAAU,MAAM;EAC3B,KAAU,SAAS,MAAM,OAAO;EAChC,KAAK,WAAW;EAChB,OAAO;CACT;;CAGA,UAAiB;EACf,KAAU,SAAS,QAAQ;EAC3B,OAAO;CACT;;CAGA,OAAc,aAAsB;EAClC,KAAU,SAAS,OAAO,WAAW;EACrC,OAAO;CACT;;CAGA,KAAY,YAAqB;EAC/B,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,IAAI,GAAG,GAAG,YAAY,IAAI,gBAAgB,CAAC,CAAC,CAAC,KAAK;EAC5F,OAAO,IAAI,aAAa,SAAS,SAAS,GAAG,WAAW,GAAG;GAAE;GAAS,KAAK;GAAU;EAAW,CAAC;CACnG;CAEA,MAAM,QAAe,OAAO,OAAO,KAAK;EACtC,MAAM,WAAoB;GACxB,SAAS,IAAI,MAAM;GACnB,OAAO;EACT;EACA,MAAM,WAAsB;GAC1B,WAAW;GACX,OAAO;EACT;EACA,eAAe;GACb,SAAS,QAAQ;GACjB,OAAO;EACT;EACA,SAAS,gBAAyB;GAChC,SAAS,OAAO,WAAW;GAC3B,OAAO;EACT;EACA,OAAO,kBAA2B;GAChC,aAAa;GACb,OAAO;EACT;CACF,CAAC;CAED,OAAO;AACT"}
package/dist/task.js CHANGED
@@ -11,8 +11,9 @@ function task(optionsOrFn, maybeFn) {
11
11
  const beforeFns = [];
12
12
  const afterFns = [];
13
13
  let runPromise;
14
+ let hasStarted = false;
14
15
  const assertNotStarted = () => {
15
- if (runPromise) throw new Error("Can't add a hook to a task that has already started");
16
+ if (hasStarted) throw new Error("Can't add a hook to a task that has already started");
16
17
  };
17
18
  const before = (...fns) => {
18
19
  assertNotStarted();
@@ -24,6 +25,7 @@ function task(optionsOrFn, maybeFn) {
24
25
  };
25
26
  const runWithShell = async (taskFn) => taskFn({ sh: createShell() });
26
27
  const runAll = async () => {
28
+ hasStarted = true;
27
29
  for (const beforeFn of beforeFns) await runWithShell(beforeFn);
28
30
  await runWithShell(fn);
29
31
  for (const afterFn of afterFns) await runWithShell(afterFn);
package/dist/task.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import { createShell } from \"#shell.ts\"\nimport type { Shell } from \"#shell.ts\"\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ninterface TaskOptions {\n desc?: string\n /** Keeps the task runnable but leaves it out of the task list. */\n hidden?: boolean\n /** Additional names to run the task. */\n alias?: string | string[]\n}\n\ninterface TaskContext {\n sh: Shell\n}\n\ntype TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn\n\nexport interface Task {\n (): Promise<void>\n options: TaskOptions\n before: (...fns: TaskFn[]) => void\n after: (...fns: TaskFn[]) => void\n}\n\nconst tasks = new WeakSet<object>()\n\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && tasks.has(value)\n\nconst failedTasks = new WeakMap<Error, object>()\n\n/** Returns the innermost task that the error failed, so the CLI can name it. */\nexport const getFailedTask = (error: Error) => failedTasks.get(error)\n\n/** Registers a task that runs at most once per bask invocation, however many times it's called. */\nexport function task(fn: TaskFn): Task\nexport function task(options: TaskOptions, fn: TaskFn): Task\nexport function task(optionsOrFn: TaskOptions | TaskFn, maybeFn?: TaskFn): Task {\n const [options, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n if (!fn) throw new Error(\"task() needs a callback\")\n\n const beforeFns: TaskFn[] = []\n const afterFns: TaskFn[] = []\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n\n const assertNotStarted = () => {\n if (runPromise) throw new Error(\"Can't add a hook to a task that has already started\")\n }\n\n const before = (...fns: TaskFn[]) => {\n assertNotStarted()\n beforeFns.push(...fns)\n }\n\n const after = (...fns: TaskFn[]) => {\n assertNotStarted()\n afterFns.push(...fns)\n }\n\n // Give each hook and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n const runWithShell = async (taskFn: TaskFn) => taskFn({ sh: createShell() })\n\n const runAll = async () => {\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await runWithShell(beforeFn)\n await runWithShell(fn)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await runWithShell(afterFn)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const run = async () => {\n runPromise ??= runAll()\n try {\n await runPromise\n } catch (error) {\n // Record `run` only if no task has yet, because the innermost task's catch runs first.\n // `run` is the same object as the returned task.\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, run)\n throw error\n }\n }\n\n const newTask: Task = Object.assign(run, { options, before, after })\n tasks.add(newTask)\n return newTask\n}\n"],"mappings":";;AA0BA,MAAM,wBAAQ,IAAI,QAAgB;AAElC,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,MAAM,IAAI,KAAK;AAEvG,MAAM,8BAAc,IAAI,QAAuB;;AAG/C,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK;AAKpE,SAAgB,KAAK,aAAmC,SAAwB;CAC9E,MAAM,CAAC,SAAS,MAAM,OAAO,gBAAgB,aAAa,CAAC,CAAC,GAAG,WAAW,IAAI,CAAC,aAAa,OAAO;CACnG,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,yBAAyB;CAElD,MAAM,YAAsB,CAAC;CAC7B,MAAM,WAAqB,CAAC;CAG5B,IAAI;CAEJ,MAAM,yBAAyB;EAC7B,IAAI,YAAY,MAAM,IAAI,MAAM,qDAAqD;CACvF;CAEA,MAAM,UAAU,GAAG,QAAkB;EACnC,iBAAiB;EACjB,UAAU,KAAK,GAAG,GAAG;CACvB;CAEA,MAAM,SAAS,GAAG,QAAkB;EAClC,iBAAiB;EACjB,SAAS,KAAK,GAAG,GAAG;CACtB;CAGA,MAAM,eAAe,OAAO,WAAmB,OAAO,EAAE,IAAI,YAAY,EAAE,CAAC;CAE3E,MAAM,SAAS,YAAY;EAEzB,KAAK,MAAM,YAAY,WAAW,MAAM,aAAa,QAAQ;EAC7D,MAAM,aAAa,EAAE;EAErB,KAAK,MAAM,WAAW,UAAU,MAAM,aAAa,OAAO;CAC5D;CAGA,MAAM,MAAM,YAAY;EACtB,eAAe,OAAO;EACtB,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,GAAG;GACjF,MAAM;EACR;CACF;CAEA,MAAM,UAAgB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACnE,MAAM,IAAI,OAAO;CACjB,OAAO;AACT"}
1
+ {"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import { createShell } from \"#shell.ts\"\nimport type { Shell } from \"#shell.ts\"\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ninterface TaskOptions {\n desc?: string\n /** Keeps the task runnable but leaves it out of the task list. */\n hidden?: boolean\n /** Additional names to run the task. */\n alias?: string | string[]\n}\n\ninterface TaskContext {\n sh: Shell\n}\n\ntype TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn\n\nexport interface Task {\n (): Promise<void>\n options: TaskOptions\n before: (...fns: TaskFn[]) => void\n after: (...fns: TaskFn[]) => void\n}\n\nconst tasks = new WeakSet<object>()\n\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && tasks.has(value)\n\nconst failedTasks = new WeakMap<Error, object>()\n\n/** Returns the innermost task that the error failed, so the CLI can name it. */\nexport const getFailedTask = (error: Error) => failedTasks.get(error)\n\n/** Registers a task that runs at most once per bask invocation, however many times it's called. */\nexport function task(fn: TaskFn): Task\nexport function task(options: TaskOptions, fn: TaskFn): Task\nexport function task(optionsOrFn: TaskOptions | TaskFn, maybeFn?: TaskFn): Task {\n const [options, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n if (!fn) throw new Error(\"task() needs a callback\")\n\n const beforeFns: TaskFn[] = []\n const afterFns: TaskFn[] = []\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n // Track the start separately because `runAll` calls the task before `runPromise` is assigned.\n let hasStarted = false\n\n const assertNotStarted = () => {\n if (hasStarted) throw new Error(\"Can't add a hook to a task that has already started\")\n }\n\n const before = (...fns: TaskFn[]) => {\n assertNotStarted()\n beforeFns.push(...fns)\n }\n\n const after = (...fns: TaskFn[]) => {\n assertNotStarted()\n afterFns.push(...fns)\n }\n\n // Give each hook and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n const runWithShell = async (taskFn: TaskFn) => taskFn({ sh: createShell() })\n\n const runAll = async () => {\n hasStarted = true\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await runWithShell(beforeFn)\n await runWithShell(fn)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await runWithShell(afterFn)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const run = async () => {\n runPromise ??= runAll()\n try {\n await runPromise\n } catch (error) {\n // Record `run` only if no task has yet, because the innermost task's catch runs first.\n // `run` is the same object as the returned task.\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, run)\n throw error\n }\n }\n\n const newTask: Task = Object.assign(run, { options, before, after })\n tasks.add(newTask)\n return newTask\n}\n"],"mappings":";;AA0BA,MAAM,wBAAQ,IAAI,QAAgB;AAElC,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,MAAM,IAAI,KAAK;AAEvG,MAAM,8BAAc,IAAI,QAAuB;;AAG/C,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK;AAKpE,SAAgB,KAAK,aAAmC,SAAwB;CAC9E,MAAM,CAAC,SAAS,MAAM,OAAO,gBAAgB,aAAa,CAAC,CAAC,GAAG,WAAW,IAAI,CAAC,aAAa,OAAO;CACnG,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,yBAAyB;CAElD,MAAM,YAAsB,CAAC;CAC7B,MAAM,WAAqB,CAAC;CAG5B,IAAI;CAEJ,IAAI,aAAa;CAEjB,MAAM,yBAAyB;EAC7B,IAAI,YAAY,MAAM,IAAI,MAAM,qDAAqD;CACvF;CAEA,MAAM,UAAU,GAAG,QAAkB;EACnC,iBAAiB;EACjB,UAAU,KAAK,GAAG,GAAG;CACvB;CAEA,MAAM,SAAS,GAAG,QAAkB;EAClC,iBAAiB;EACjB,SAAS,KAAK,GAAG,GAAG;CACtB;CAGA,MAAM,eAAe,OAAO,WAAmB,OAAO,EAAE,IAAI,YAAY,EAAE,CAAC;CAE3E,MAAM,SAAS,YAAY;EACzB,aAAa;EAEb,KAAK,MAAM,YAAY,WAAW,MAAM,aAAa,QAAQ;EAC7D,MAAM,aAAa,EAAE;EAErB,KAAK,MAAM,WAAW,UAAU,MAAM,aAAa,OAAO;CAC5D;CAGA,MAAM,MAAM,YAAY;EACtB,eAAe,OAAO;EACtB,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,GAAG;GACjF,MAAM;EACR;CACF;CAEA,MAAM,UAAgB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACnE,MAAM,IAAI,OAAO;CACjB,OAAO;AACT"}
package/dist/utils.js ADDED
@@ -0,0 +1,9 @@
1
+ import { styleText } from "node:util";
2
+ //#region src/utils.ts
3
+ const printError = (message) => {
4
+ process.stderr.write(`${styleText(["bold", "red"], "error:", { stream: process.stderr })} ${message}\n`);
5
+ };
6
+ //#endregion
7
+ export { printError };
8
+
9
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import { styleText } from \"node:util\"\n\n// Write to `process.stderr` directly because Bun colors all `console.error` output red in a terminal.\nexport const printError = (message: string) => {\n process.stderr.write(`${styleText([\"bold\", \"red\"], \"error:\", { stream: process.stderr })} ${message}\\n`)\n}\n"],"mappings":";;AAGA,MAAa,cAAc,YAAoB;CAC7C,QAAQ,OAAO,MAAM,GAAG,UAAU,CAAC,QAAQ,KAAK,GAAG,UAAU,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG,QAAQ,GAAG;AACzG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamhl8/bask",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Write your tasks in TypeScript",
5
5
  "keywords": [
6
6
  "build-tool",
@@ -48,16 +48,17 @@
48
48
  "access": "public"
49
49
  },
50
50
  "scripts": {
51
- "prepare": "bun tsdown && bun install --ignore-scripts --no-summary && bunx bask prepare"
51
+ "prepare": "tsdown && bun install --ignore-scripts --no-summary && bunx bask prepare"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@adamhl8/bask": "file:.",
55
- "@adamhl8/configs": "^3.0.1",
55
+ "@adamhl8/configs": "^3.0.3",
56
56
  "@arethetypeswrong/core": "^0.18.5",
57
- "@commitlint/cli": "^21.2.3",
58
- "@commitlint/config-conventional": "^21.2.3",
57
+ "@commitlint/cli": "^21.2.4",
58
+ "@commitlint/config-conventional": "^21.2.4",
59
59
  "@types/bun": "^1.4.3",
60
- "knip": "^6.41.0",
60
+ "execa": "^10.2.0",
61
+ "knip": "^6.42.0",
61
62
  "markdown-toc": "^1.2.0",
62
63
  "oxfmt": "^0.73.0",
63
64
  "oxlint": "^1.88.0",