@adamhl8/bask 0.0.1 → 0.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.
package/README.md CHANGED
@@ -12,27 +12,149 @@ A task runner for Bun where tasks are TypeScript functions.
12
12
  bun add --dev @adamhl8/bask
13
13
  ```
14
14
 
15
+ To run tasks with a plain `bask` instead of `bunx bask`, also install it globally:
16
+
17
+ ```sh
18
+ bun add --global @adamhl8/bask
19
+ ```
20
+
21
+ The global `bask` hands off to the project's copy when there is one, so each project still runs the version it pins.
22
+
15
23
  ## Usage
16
24
 
17
- Export tasks from a `bask.ts` in your project root. The default export is the task that runs when you don't name one. Calling a task from another task makes it a dependency, and each task runs at most once per invocation.
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.
18
26
 
19
27
  ```ts
20
28
  import { task } from "@adamhl8/bask"
21
29
 
22
- export const lint = task(async ({ $ }) => {
23
- await $`oxlint`
30
+ export const lint = task(async ({ sh }) => {
31
+ await sh`oxlint`
24
32
  })
25
33
 
26
- export const build = task({ desc: "Lint, then build" }, async ({ $ }) => {
34
+ export const build = task({ desc: "Lint, then build" }, async ({ sh }) => {
27
35
  await lint()
28
- await $`tsdown`
36
+ await sh`tsdown`
37
+ })
38
+
39
+ export const bumpDeps = task(async ({ sh }) => {
40
+ await sh`bunx npm-check-updates --upgrade`
29
41
  })
30
42
 
31
43
  export default build
32
44
  ```
33
45
 
34
- Run a task with `bunx`, because `bun bask` runs your `bask.ts` instead of the `bask` bin. Each command is printed before it runs.
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`.
35
47
 
36
48
  ```sh
37
- bunx bask build
49
+ bask build
50
+ bask bump-deps
51
+ ```
52
+
53
+ Scripts and CI should use `bunx bask`, because they can't count on a global install.
54
+
55
+ ### The default task and the task list
56
+
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`):
58
+
59
+ ```
60
+ Available tasks:
61
+ build # Lint, then build [default]
62
+ bump-deps
63
+ lint
64
+ ```
65
+
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.
67
+
68
+ ### Task options
69
+
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.
73
+
74
+ ```ts
75
+ export const releaseRun = task({ desc: "Run from CI", hidden: true }, async ({ sh }) => {
76
+ await sh`bun release-it --ci`
77
+ })
78
+
79
+ export const bumpDeps = task({ alias: ["up", "update-deps"] }, async ({ sh }) => {
80
+ await sh`bunx npm-check-updates --upgrade`
81
+ })
82
+ ```
83
+
84
+ Aliases show next to the task in the list:
85
+
86
+ ```
87
+ bump-deps # [aliases: up, update-deps]
88
+ ```
89
+
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.
91
+
92
+ ### Running commands
93
+
94
+ `sh` prints each command before running it with Bun's `$`. To run a command without printing it, use Bun's `$` directly.
95
+
96
+ ```ts
97
+ import { $ } from "bun"
98
+
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`
102
+ })
103
+ ```
104
+
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.
106
+
107
+ The `stdout` and `stderr` of an awaited `sh` command hold exactly what it printed, colors included.
108
+
109
+ When a command fails, bask stops and names the task it failed in, then exits with the command's exit code:
110
+
111
+ ```
112
+ error: task 'lint' failed with exit code 2
113
+ ```
114
+
115
+ Any other error thrown in a task still shows its stack trace.
116
+
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.
118
+
119
+ ```ts
120
+ export const buildWeb = task(async ({ sh }) => {
121
+ sh.cwd("packages/web")
122
+ await sh`bun install`
123
+ await sh`bun run build`
124
+ })
125
+ ```
126
+
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`.
128
+
129
+ ### Extending tasks
130
+
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.
132
+
133
+ ```ts
134
+ import { task } from "@adamhl8/bask"
135
+
136
+ import { build, lint } from "./shared-tasks.ts"
137
+
138
+ export * from "./shared-tasks.ts"
139
+
140
+ export const astroSync = task(async ({ sh }) => {
141
+ await sh`bun astro sync`
142
+ })
143
+
144
+ lint.before(astroSync)
145
+ build.after(async ({ sh }) => {
146
+ await sh`bun astro build`
147
+ })
148
+ ```
149
+
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.
151
+
152
+ The built-in `list` task, which prints the task list, takes hooks too:
153
+
154
+ ```ts
155
+ import { list } from "@adamhl8/bask"
156
+
157
+ list.after(() => {
158
+ console.log("\nRun `bask <task>` to run a task.")
159
+ })
38
160
  ```
package/dist/cli.js CHANGED
@@ -1,20 +1,89 @@
1
1
  #!/usr/bin/env bun
2
- import { isTask } from "./index.js";
2
+ import { getFailedTask } from "./task.js";
3
+ import { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from "./registry.js";
4
+ import { parseArgs, styleText } from "node:util";
5
+ import bun from "bun";
3
6
  import path from "node:path";
4
7
  //#region src/cli.ts
5
8
  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
+ const isParseArgsError = (error) => error instanceof TypeError && "code" in error && typeof error.code === "string" && error.code.startsWith("ERR_PARSE_ARGS_");
13
+ /** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */
14
+ const resolveLocalCli = () => {
15
+ try {
16
+ return bun.resolveSync("@adamhl8/bask/cli", process.cwd());
17
+ } catch {
18
+ return;
19
+ }
20
+ };
21
+ const parseCliArgs = () => {
22
+ try {
23
+ return parseArgs({
24
+ options: { list: {
25
+ type: "boolean",
26
+ short: "l"
27
+ } },
28
+ allowPositionals: true
29
+ });
30
+ } catch (error) {
31
+ if (!isParseArgsError(error)) throw error;
32
+ printError(error.message);
33
+ process.exitCode = 2;
34
+ return;
35
+ }
36
+ };
37
+ /** Runs a task and reports a failed command in one line, naming the innermost task that failed. */
38
+ const runTask = async (taskToRun, taskName) => {
39
+ try {
40
+ await taskToRun();
41
+ } catch (error) {
42
+ if (!(error instanceof bun.$.ShellError)) throw error;
43
+ const failedTask = getFailedTask(error);
44
+ const failedName = getTaskIndex().values().find((entry) => entry.task === failedTask)?.name ?? taskName;
45
+ printError(`task '${failedName}' failed with exit code ${error.exitCode}`);
46
+ process.exitCode = error.exitCode;
47
+ }
48
+ };
6
49
  const main = async () => {
7
- const taskName = process.argv[2] ?? "default";
8
- const baskModule = await import(path.resolve("bask.ts"));
50
+ const localCli = resolveLocalCli();
51
+ if (localCli && localCli !== import.meta.path) {
52
+ await import(localCli);
53
+ return;
54
+ }
55
+ const args = parseCliArgs();
56
+ if (!args) return;
57
+ const { values, positionals } = args;
58
+ const baskPath = path.resolve("bask.ts");
59
+ if (!await bun.file(baskPath).exists()) {
60
+ printError(`no bask.ts in ${process.cwd()}`);
61
+ process.exitCode = 1;
62
+ return;
63
+ }
64
+ const baskModule = await import(baskPath);
9
65
  if (!isModule(baskModule)) throw new Error("failed to import bask.ts");
10
- const selectedTask = baskModule[taskName];
11
- if (!isTask(selectedTask)) {
12
- const taskNames = Object.entries(baskModule).filter(([, value]) => isTask(value)).map(([name]) => name);
13
- console.error(`Unknown task "${taskName}". Available tasks: ${taskNames.join(", ")}`);
66
+ try {
67
+ setBaskModule(baskModule);
68
+ } catch (error) {
69
+ if (!(error instanceof BaskFileError)) throw error;
70
+ printError(error.message);
71
+ process.exitCode = 1;
72
+ return;
73
+ }
74
+ const [taskName] = positionals;
75
+ if (values.list || taskName === void 0 && !getTaskIndex().has("default")) {
76
+ await runTask(list, "list");
77
+ return;
78
+ }
79
+ const selectedEntry = getTaskIndex().get(taskName ?? "default");
80
+ if (!selectedEntry) {
81
+ printError(`unknown task '${taskName ?? "default"}'`);
82
+ process.stderr.write(`\n${formatTaskList()}\n`);
14
83
  process.exitCode = 1;
15
84
  return;
16
85
  }
17
- await selectedTask();
86
+ await runTask(selectedEntry.task, selectedEntry.name);
18
87
  };
19
88
  await main();
20
89
  //#endregion
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\"\n\nimport { isTask } from \"#index.ts\"\n\nconst isModule = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && Boolean(value)\n\nconst main = async () => {\n const taskName = process.argv[2] ?? \"default\"\n\n const baskModule: unknown = await import(path.resolve(\"bask.ts\"))\n if (!isModule(baskModule)) throw new Error(\"failed to import bask.ts\")\n\n const selectedTask = baskModule[taskName]\n\n if (!isTask(selectedTask)) {\n const baskExports = Object.entries(baskModule)\n const taskExports = baskExports.filter(([, value]) => isTask(value))\n const taskNames = taskExports.map(([name]) => name)\n\n console.error(`Unknown task \"${taskName}\". Available tasks: ${taskNames.join(\", \")}`)\n process.exitCode = 1\n return\n }\n\n await selectedTask()\n}\n\nawait main()\n"],"mappings":";;;;AAMA,MAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,QAAQ,KAAK;AAEjH,MAAM,OAAO,YAAY;CACvB,MAAM,WAAW,QAAQ,KAAK,MAAM;CAEpC,MAAM,aAAsB,MAAM,OAAO,KAAK,QAAQ,SAAS;CAC/D,IAAI,CAAC,SAAS,UAAU,GAAG,MAAM,IAAI,MAAM,0BAA0B;CAErE,MAAM,eAAe,WAAW;CAEhC,IAAI,CAAC,OAAO,YAAY,GAAG;EAGzB,MAAM,YAFc,OAAO,QAAQ,UACL,CAAC,CAAC,QAAQ,GAAG,WAAW,OAAO,KAAK,CACtC,CAAC,CAAC,KAAK,CAAC,UAAU,IAAI;EAElD,QAAQ,MAAM,iBAAiB,SAAS,sBAAsB,UAAU,KAAK,IAAI,GAAG;EACpF,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,aAAa;AACrB;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, 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;AAEA,MAAM,qBAAqB;CACzB,IAAI;EACF,OAAO,UAAU;GAAE,SAAS,EAAE,MAAM;IAAE,MAAM;IAAW,OAAO;GAAI,EAAE;GAAG,kBAAkB;EAAK,CAAC;CACjG,SAAS,OAAO;EACd,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM;EACpC,WAAW,MAAM,OAAO;EACxB,QAAQ,WAAW;EACnB;CACF;AACF;;AAGA,MAAM,UAAU,OAAO,WAAiB,aAAqB;CAC3D,IAAI;EACF,MAAM,UAAU;CAClB,SAAS,OAAO;EAEd,IAAI,EAAE,iBAAiB,IAAI,EAAE,aAAa,MAAM;EAEhD,MAAM,aAAa,cAAc,KAAK;EAKtC,MAAM,aAJc,aAAa,CAAC,CAC/B,OAAO,CAAC,CACR,MAAM,UAAU,MAAM,SAAS,UAEL,CAAC,EAAE,QAAQ;EACxC,WAAW,SAAS,WAAW,0BAA0B,MAAM,UAAU;EACzE,QAAQ,WAAW,MAAM;CAC3B;AACF;AAEA,MAAM,OAAO,YAAY;CAGvB,MAAM,WAAW,gBAAgB;CACjC,IAAI,YAAY,aAAa,YAAY,MAAM;EAC7C,MAAM,OAAO;EACb;CACF;CAEA,MAAM,OAAO,aAAa;CAC1B,IAAI,CAAC,MAAM;CACX,MAAM,EAAE,QAAQ,gBAAgB;CAEhC,MAAM,WAAW,KAAK,QAAQ,SAAS;CACvC,IAAI,CAAE,MAAM,IAAI,KAAK,QAAQ,CAAC,CAAC,OAAO,GAAI;EACxC,WAAW,iBAAiB,QAAQ,IAAI,GAAG;EAC3C,QAAQ,WAAW;EACnB;CACF;CAEA,MAAM,aAAsB,MAAM,OAAO;CACzC,IAAI,CAAC,SAAS,UAAU,GAAG,MAAM,IAAI,MAAM,0BAA0B;CACrE,IAAI;EACF,cAAc,UAAU;CAC1B,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,gBAAgB,MAAM;EAC7C,WAAW,MAAM,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.d.ts CHANGED
@@ -1,21 +1,3 @@
1
- import { ShellWrapper } from "./shell.js";
2
- //#region src/index.d.ts
3
- interface TaskOptions {
4
- desc?: string;
5
- }
6
- interface TaskContext {
7
- $: typeof ShellWrapper;
8
- }
9
- type AsyncOrSyncReturn = Promise<void> | void;
10
- type TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn;
11
- export interface Task {
12
- (): Promise<void>;
13
- options: TaskOptions;
14
- }
15
- export declare const isTask: (value: unknown) => value is Task;
16
- /** Registers a task that runs at most once per bask invocation, however many times it's called. */
17
- export declare function task(fn: TaskFn): Task;
18
- export declare function task(options: TaskOptions, fn: TaskFn): Task;
19
- //#endregion
20
- export {};
21
- //# sourceMappingURL=index.d.ts.map
1
+ import { Task, isTask, task } from "./task.js";
2
+ import { list } from "./registry.js";
3
+ export { type Task, isTask, list, task };
package/dist/index.js CHANGED
@@ -1,22 +1,3 @@
1
- import { ShellWrapper } from "./shell.js";
2
- //#region src/index.ts
3
- const tasks = /* @__PURE__ */ new WeakSet();
4
- const isTask = (value) => typeof value === "function" && tasks.has(value);
5
- function task(optionsOrFn, maybeFn) {
6
- const [options, fn] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn];
7
- if (!fn) throw new Error("task() needs a callback");
8
- const runFn = async () => fn({ $: ShellWrapper });
9
- let taskFnPromise;
10
- const run = async () => {
11
- if (taskFnPromise) return taskFnPromise;
12
- taskFnPromise = runFn();
13
- return taskFnPromise;
14
- };
15
- const newTask = Object.assign(run, { options });
16
- tasks.add(newTask);
17
- return newTask;
18
- }
19
- //#endregion
20
- export { isTask, task };
21
-
22
- //# sourceMappingURL=index.js.map
1
+ import { isTask, task } from "./task.js";
2
+ import { list } from "./registry.js";
3
+ export { isTask, list, task };
@@ -0,0 +1,5 @@
1
+ import { Task } from "./task.js";
2
+ //#region src/registry.d.ts
3
+ export declare const list: Task;
4
+ //#endregion
5
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","names":[],"sources":["../src/registry.ts"],"mappings":";;qBAgIa,MAAI"}
@@ -0,0 +1,96 @@
1
+ import { isTask, task } from "./task.js";
2
+ //#region src/registry.ts
3
+ /** Reports a mistake in `bask.ts` that the CLI prints without a stack trace. */
4
+ var BaskFileError = class extends Error {
5
+ name = "BaskFileError";
6
+ };
7
+ let taskIndex;
8
+ const toKebabCase = (name) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`);
9
+ const toCamelCase = (name) => name.replaceAll(/-[a-z\d]/gv, (match) => match.slice(1).toUpperCase());
10
+ /** Formats one problem as a single line, or several under a count with one per line. */
11
+ const formatProblems = (problems) => {
12
+ if (problems.length === 1) return problems.join("\n");
13
+ return [`bask.ts has ${problems.length} problems:`, ...problems.map((problem) => ` ${problem}`)].join("\n");
14
+ };
15
+ /** Indexes the loaded `bask.ts` module's tasks under both spellings of their export names and aliases. */
16
+ const setBaskModule = (baskModule) => {
17
+ const defaultTask = baskModule["default"];
18
+ const problems = [];
19
+ if ("default" in baskModule && !isTask(defaultTask)) problems.push("the default export isn't a task. Wrap it in task().");
20
+ const taskExports = Object.entries(baskModule).filter((entry) => entry[0] !== "default" && isTask(entry[1]));
21
+ const defaultHasName = taskExports.some(([, exportedTask]) => exportedTask === defaultTask);
22
+ if (isTask(defaultTask) && !defaultHasName) taskExports.push(["default", defaultTask]);
23
+ const index = /* @__PURE__ */ new Map();
24
+ for (const [exportName, exportedTask] of taskExports) {
25
+ const existingEntry = index.values().find((entry) => entry.task === exportedTask);
26
+ if (existingEntry) {
27
+ problems.push(`task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`);
28
+ continue;
29
+ }
30
+ const kebabName = toKebabCase(exportName);
31
+ const entry = {
32
+ exportName,
33
+ name: kebabName,
34
+ aliases: [],
35
+ task: exportedTask
36
+ };
37
+ index.set(exportName, entry);
38
+ index.set(kebabName, entry);
39
+ }
40
+ for (const entry of new Set(index.values())) {
41
+ const aliases = [entry.task.options.alias ?? []].flat();
42
+ for (const alias of aliases) {
43
+ const kebabAlias = toKebabCase(alias);
44
+ if (index.get(kebabAlias) === entry) continue;
45
+ const keys = [
46
+ alias,
47
+ kebabAlias,
48
+ toCamelCase(alias)
49
+ ];
50
+ const owner = keys.map((key) => index.get(key)).find(Boolean);
51
+ if (kebabAlias === "default") problems.push(`task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`);
52
+ else if (owner) problems.push(`task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`);
53
+ else {
54
+ entry.aliases.push(kebabAlias);
55
+ for (const key of keys) index.set(key, entry);
56
+ }
57
+ }
58
+ }
59
+ if (problems.length > 0) throw new BaskFileError(formatProblems(problems));
60
+ const defaultEntry = index.values().find((entry) => entry.task === defaultTask);
61
+ if (defaultEntry) index.set("default", defaultEntry);
62
+ taskIndex = index;
63
+ };
64
+ const getTaskIndex = () => {
65
+ if (!taskIndex) throw new Error("Tasks were read before the CLI loaded bask.ts");
66
+ return taskIndex;
67
+ };
68
+ const formatAliases = (aliases) => {
69
+ if (aliases.length === 0) return;
70
+ return `[${aliases.length === 1 ? "alias" : "aliases"}: ${aliases.join(", ")}]`;
71
+ };
72
+ const formatTaskList = () => {
73
+ const index = getTaskIndex();
74
+ const defaultEntry = index.get("default");
75
+ const rows = [...new Set(index.values())].filter((entry) => !entry.task.options.hidden).map((entry) => {
76
+ const defaultMarker = entry === defaultEntry && entry.name !== "default" ? "[default]" : void 0;
77
+ const comment = [
78
+ entry.task.options.desc,
79
+ defaultMarker,
80
+ formatAliases(entry.aliases)
81
+ ].filter(Boolean).join(" ");
82
+ return {
83
+ name: entry.name,
84
+ comment
85
+ };
86
+ }).toSorted((a, b) => a.name.localeCompare(b.name));
87
+ const nameWidth = Math.max(...rows.map((row) => row.name.length));
88
+ return ["Available tasks:", ...rows.map(({ name, comment }) => comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`)].join("\n");
89
+ };
90
+ const list = task(() => {
91
+ console.log(formatTaskList());
92
+ });
93
+ //#endregion
94
+ export { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule };
95
+
96
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../src/registry.ts"],"sourcesContent":["import { isTask, task } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\ninterface TaskEntry {\n /** Export name as written in `bask.ts`, for error messages. */\n exportName: string\n /** Kebab-case export name, or `default` for a task that's only the default export. */\n name: string\n /** Kebab-case aliases from the task's `alias` option. */\n aliases: string[]\n task: Task\n}\n\ntype TaskIndex = Map<string, TaskEntry>\n\n/** Reports a mistake in `bask.ts` that the CLI prints without a stack trace. */\nexport class BaskFileError extends Error {\n public override name = \"BaskFileError\"\n}\n\nlet taskIndex: TaskIndex | undefined\n\nconst toKebabCase = (name: string) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`)\nconst toCamelCase = (name: string) => name.replaceAll(/-[a-z\\d]/gv, (match) => match.slice(1).toUpperCase())\n\n/** Formats one problem as a single line, or several under a count with one per line. */\nconst formatProblems = (problems: string[]) => {\n if (problems.length === 1) return problems.join(\"\\n\")\n return [`bask.ts has ${problems.length} problems:`, ...problems.map((problem) => ` ${problem}`)].join(\"\\n\")\n}\n\n/** Indexes the loaded `bask.ts` module's tasks under both spellings of their export names and aliases. */\nexport const setBaskModule = (baskModule: Record<string, unknown>) => {\n const defaultTask = baskModule[\"default\"]\n // Collect every problem before throwing, so one run reports all of them.\n const problems: string[] = []\n\n // Reject a non-task default because bask runs it when no task is named, so it's always a mistake.\n if (\"default\" in baskModule && !isTask(defaultTask))\n problems.push(\"the default export isn't a task. Wrap it in task().\")\n\n // Collect named task exports, then add the default under `default` only when it has no other name.\n const taskExports = Object.entries(baskModule).filter(\n (entry): entry is [string, Task] => entry[0] !== \"default\" && isTask(entry[1]),\n )\n const defaultHasName = taskExports.some(([, exportedTask]) => exportedTask === defaultTask)\n if (isTask(defaultTask) && !defaultHasName) taskExports.push([\"default\", defaultTask])\n\n // Index each task under its export name and kebab-case name, collecting tasks exported more than once.\n const index: TaskIndex = new Map()\n for (const [exportName, exportedTask] of taskExports) {\n const existingEntry = index.values().find((entry) => entry.task === exportedTask)\n if (existingEntry) {\n problems.push(\n `task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`,\n )\n continue\n }\n\n const kebabName = toKebabCase(exportName)\n const entry: TaskEntry = { exportName, name: kebabName, aliases: [], task: exportedTask }\n index.set(exportName, entry)\n index.set(kebabName, entry)\n }\n\n // Index each alias under every spelling, collecting aliases that are `default` or already taken.\n // Every export name is already indexed, so a clash with a name is reported against the alias.\n // Collect the entries into a `Set` first because the loop adds alias keys to `index`.\n for (const entry of new Set(index.values())) {\n const aliases = [entry.task.options.alias ?? []].flat()\n\n for (const alias of aliases) {\n const kebabAlias = toKebabCase(alias)\n // Skip an alias that repeats the task's own name or another of its aliases.\n if (index.get(kebabAlias) === entry) continue\n\n const keys = [alias, kebabAlias, toCamelCase(alias)]\n const owner = keys.map((key) => index.get(key)).find(Boolean)\n if (kebabAlias === \"default\")\n problems.push(`task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`)\n else if (owner)\n problems.push(`task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`)\n else {\n entry.aliases.push(kebabAlias)\n for (const key of keys) index.set(key, entry)\n }\n }\n }\n\n if (problems.length > 0) throw new BaskFileError(formatProblems(problems))\n\n const defaultEntry = index.values().find((entry) => entry.task === defaultTask)\n if (defaultEntry) index.set(\"default\", defaultEntry)\n\n taskIndex = index\n}\n\nexport const getTaskIndex = () => {\n if (!taskIndex) throw new Error(\"Tasks were read before the CLI loaded bask.ts\")\n return taskIndex\n}\n\nconst formatAliases = (aliases: string[]) => {\n if (aliases.length === 0) return\n return `[${aliases.length === 1 ? \"alias\" : \"aliases\"}: ${aliases.join(\", \")}]`\n}\n\nexport const formatTaskList = () => {\n const index = getTaskIndex()\n const defaultEntry = index.get(\"default\")\n\n // Collect the entries into a `Set` because every name of a task shares one entry.\n const rows = [...new Set(index.values())]\n .filter((entry) => !entry.task.options.hidden)\n .map((entry) => {\n const defaultMarker = entry === defaultEntry && entry.name !== \"default\" ? \"[default]\" : undefined\n const comment = [entry.task.options.desc, defaultMarker, formatAliases(entry.aliases)].filter(Boolean).join(\" \")\n return { name: entry.name, comment }\n })\n .toSorted((a, b) => a.name.localeCompare(b.name))\n\n const nameWidth = Math.max(...rows.map((row) => row.name.length))\n const lines = rows.map(({ name, comment }) =>\n comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`,\n )\n return [\"Available tasks:\", ...lines].join(\"\\n\")\n}\n\nexport const list = task(() => {\n console.log(formatTaskList())\n})\n"],"mappings":"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"}
package/dist/shell.d.ts CHANGED
@@ -1,6 +1,35 @@
1
1
  import { $, ShellExpression } from "bun";
2
2
  //#region src/shell.d.ts
3
- /** Prints each command to stderr, then runs it with Bun's `$`. */
4
- export declare const ShellWrapper: (strings: TemplateStringsArray, ...expressions: ShellExpression[]) => $.ShellPromise;
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
+ /** 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> {
10
+ (strings: TemplateStringsArray, ...expressions: ShellExpression[]): ShellCommand;
11
+ }
12
+ /**
13
+ * Wraps Bun's `ShellPromise` to set `FORCE_COLOR` only on commands whose output is shown. Bun's pipes hide the terminal
14
+ * from commands, so they turn color off unless forced.
15
+ */
16
+ declare class ShellCommand implements PromiseLike<$.ShellOutput>, Rechain<BunCommandMethods, $.ShellPromise, ShellCommand> {
17
+ #private;
18
+ constructor(promise: $.ShellPromise, env: ShellEnv);
19
+ cwd(newCwd: string): this;
20
+ env(newEnv: ShellEnv): this;
21
+ quiet(isQuiet?: boolean): this;
22
+ nothrow(): this;
23
+ throws(shouldThrow: boolean): this;
24
+ text(encoding?: BufferEncoding): Promise<string>;
25
+ json(): Promise<any>;
26
+ lines(): AsyncIterable<string>;
27
+ arrayBuffer(): Promise<ArrayBuffer>;
28
+ blob(): Promise<Blob>;
29
+ then<TResult1 = $.ShellOutput, TResult2 = never>(onfulfilled?: ((value: $.ShellOutput) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
30
+ catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<TResult | $.ShellOutput>;
31
+ finally(onfinally?: (() => void) | null): Promise<$.ShellOutput>;
32
+ }
5
33
  //#endregion
34
+ export {};
6
35
  //# sourceMappingURL=shell.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"shell.d.ts","names":["BunShell"],"sources":["../src/shell.ts"],"mappings":";;;qBAgBa,eAAY,SACd,yBAAoB,aACb,sBACfA,EAAS"}
1
+ {"version":3,"file":"shell.d.ts","names":["BunShell"],"sources":["../src/shell.ts"],"mappings":";;KAKK,WAAW,WAAWA,EAAS;;KAG/B,QAAQ,GAAG,MAAM,SACnB,WAAW,IAAI,EAAE,gBAAe,YAAY,SAAS,YAAW,MAAM,SAAS,KAAK,EAAE;KAIpF,oBAAoB,KAAKA,EAAS,oBAAoB,QAAQA,EAAS;KAGvE,kBAAkB,cAAcA;;iBAGpB,cAAc,QAAQ,KAAKA,GAAU,kBAAkBA,GAAU;GAC/E,SAAS,yBAAyB,aAAa,oBAAoB;;;;;;cAuBhE,wBACO,YAAYA,EAAS,cAAc,QAAQ,mBAAmBA,EAAS,cAAc;;EAOhG,YAAmB,SAASA,EAAS,cAAc,KAAK;EAKjD,IAAI;EAKJ,IAAI,QAAQ;EAKZ,MAAM;EAMN;EAKA,OAAO;EAKD,KAAK,WAAW,iBAAc;EAI9B,QAAI;EAKV,SAAK;EAIC,eAAW,QAAA;EAIX,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
@@ -7,13 +7,108 @@ const formatExpression = (expression) => {
7
7
  if (typeof expression === "object" && expression !== null && "raw" in expression) return expression.raw;
8
8
  return bun.$.escape(String(expression));
9
9
  };
10
- /** Prints each command to stderr, then runs it with Bun's `$`. */
11
- const ShellWrapper = (strings, ...expressions) => {
12
- const command = String.raw({ raw: strings.raw }, ...expressions.map(formatExpression));
13
- process.stderr.write(`${styleText("bold", command.trim(), { stream: process.stderr })}\n`);
14
- return bun.$(strings, ...expressions);
10
+ /** Checks whether bask should turn on color for a command whose output goes to the terminal. */
11
+ const shouldForceColor = (env) => process.stdout.isTTY && process.stderr.isTTY && [process.env, env].every((vars) => vars["FORCE_COLOR"] === void 0 && vars["NO_COLOR"] === void 0);
12
+ /**
13
+ * Wraps Bun's `ShellPromise` to set `FORCE_COLOR` only on commands whose output is shown. Bun's pipes hide the terminal
14
+ * from commands, so they turn color off unless forced.
15
+ */
16
+ var ShellCommand = class {
17
+ #promise;
18
+ #env;
19
+ #isQuiet = false;
20
+ #isPrepared = false;
21
+ constructor(promise, env) {
22
+ this.#promise = promise;
23
+ this.#env = env;
24
+ }
25
+ cwd(newCwd) {
26
+ this.#promise.cwd(newCwd);
27
+ return this;
28
+ }
29
+ env(newEnv) {
30
+ this.#env = newEnv;
31
+ return this;
32
+ }
33
+ quiet(isQuiet = true) {
34
+ this.#promise.quiet(isQuiet);
35
+ this.#isQuiet = isQuiet;
36
+ return this;
37
+ }
38
+ nothrow() {
39
+ this.#promise.nothrow();
40
+ return this;
41
+ }
42
+ throws(shouldThrow) {
43
+ this.#promise.throws(shouldThrow);
44
+ return this;
45
+ }
46
+ async text(encoding) {
47
+ return this.#prepare(false).text(encoding);
48
+ }
49
+ async json() {
50
+ return this.#prepare(false).json();
51
+ }
52
+ lines() {
53
+ return this.#prepare(false).lines();
54
+ }
55
+ async arrayBuffer() {
56
+ return this.#prepare(false).arrayBuffer();
57
+ }
58
+ async blob() {
59
+ return this.#prepare(false).blob();
60
+ }
61
+ async then(onfulfilled, onrejected) {
62
+ return this.#prepare(!this.#isQuiet).then(onfulfilled, onrejected);
63
+ }
64
+ async catch(onrejected) {
65
+ return this.then(void 0, onrejected);
66
+ }
67
+ async finally(onfinally) {
68
+ return this.#prepare(!this.#isQuiet).finally(onfinally);
69
+ }
70
+ /** Sets the command's environment once, before Bun starts the command. */
71
+ #prepare(isShown) {
72
+ if (this.#isPrepared) return this.#promise;
73
+ this.#isPrepared = true;
74
+ const env = this.#env ?? process.env;
75
+ this.#promise.env(isShown && shouldForceColor(env) ? {
76
+ ...env,
77
+ FORCE_COLOR: "1"
78
+ } : env);
79
+ return this.#promise;
80
+ }
81
+ };
82
+ /** Creates a shell that prints each command to stderr before running it. */
83
+ const createShell = () => {
84
+ const bunShell = new bun.$.Shell();
85
+ let shellEnv;
86
+ 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);
90
+ };
91
+ const shell = Object.assign(run, {
92
+ cwd: (newCwd) => {
93
+ bunShell.cwd(newCwd);
94
+ return shell;
95
+ },
96
+ env: (newEnv) => {
97
+ shellEnv = newEnv;
98
+ return shell;
99
+ },
100
+ nothrow: () => {
101
+ bunShell.nothrow();
102
+ return shell;
103
+ },
104
+ throws: (shouldThrow) => {
105
+ bunShell.throws(shouldThrow);
106
+ return shell;
107
+ }
108
+ });
109
+ return shell;
15
110
  };
16
111
  //#endregion
17
- export { ShellWrapper };
112
+ export { createShell };
18
113
 
19
114
  //# sourceMappingURL=shell.js.map
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\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/** Prints each command to stderr, then runs it with Bun's `$`. */\n// oxlint-disable-next-line typescript/promise-function-async - return Bun's `ShellPromise` as is, because an async function would wrap it and drop `.quiet()` and `.text()`.\nexport const ShellWrapper = (\n strings: TemplateStringsArray,\n ...expressions: ShellExpression[]\n): BunShell.ShellPromise => {\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 bun.$(strings, ...expressions)\n}\n"],"mappings":";;;;AAMA,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;;AAIA,MAAa,gBACX,SACA,GAAG,gBACuB;CAE1B,MAAM,UAAU,OAAO,IAAI,EAAE,KAAK,QAAQ,IAAI,GAAG,GAAG,YAAY,IAAI,gBAAgB,CAAC;CAErF,QAAQ,OAAO,MAAM,GAAG,UAAU,QAAQ,QAAQ,KAAK,GAAG,EAAE,QAAQ,QAAQ,OAAO,CAAC,EAAE,GAAG;CACzF,OAAO,IAAI,EAAE,SAAS,GAAG,WAAW;AACtC"}
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":"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"}
package/dist/task.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { Shell } from "./shell.js";
2
+ //#region src/task.d.ts
3
+ type AsyncOrSyncReturn = Promise<void> | void;
4
+ interface TaskOptions {
5
+ desc?: string;
6
+ /** Keeps the task runnable but leaves it out of the task list. */
7
+ hidden?: boolean;
8
+ /** Additional names to run the task. */
9
+ alias?: string | string[];
10
+ }
11
+ interface TaskContext {
12
+ sh: Shell;
13
+ }
14
+ type TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn;
15
+ export interface Task {
16
+ (): Promise<void>;
17
+ options: TaskOptions;
18
+ before: (...fns: TaskFn[]) => void;
19
+ after: (...fns: TaskFn[]) => void;
20
+ }
21
+ export declare const isTask: (value: unknown) => value is Task;
22
+ /** Registers a task that runs at most once per bask invocation, however many times it's called. */
23
+ export declare function task(fn: TaskFn): Task;
24
+ export declare function task(options: TaskOptions, fn: TaskFn): Task;
25
+ //#endregion
26
+ export {};
27
+ //# sourceMappingURL=task.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task.d.ts","names":[],"sources":["../src/task.ts"],"mappings":";;KAGK,oBAAoB;UAEf;EACR;;EAEA;;EAEA;;UAGQ;EACR,IAAI;;KAGD,UAAU,KAAK,gBAAgB;iBAEnB;MACX;EACJ,SAAS;EACT,YAAY,KAAK;EACjB,WAAW,KAAK;;qBAKL,SAAM,mBAAqB,SAAS;;wBAQjC,KAAK,IAAI,SAAS;wBAClB,KAAK,SAAS,aAAa,IAAI,SAAS"}
package/dist/task.js ADDED
@@ -0,0 +1,51 @@
1
+ import { createShell } from "./shell.js";
2
+ //#region src/task.ts
3
+ const tasks = /* @__PURE__ */ new WeakSet();
4
+ const isTask = (value) => typeof value === "function" && tasks.has(value);
5
+ const failedTasks = /* @__PURE__ */ new WeakMap();
6
+ /** Returns the innermost task that the error failed, so the CLI can name it. */
7
+ const getFailedTask = (error) => failedTasks.get(error);
8
+ function task(optionsOrFn, maybeFn) {
9
+ const [options, fn] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn];
10
+ if (!fn) throw new Error("task() needs a callback");
11
+ const beforeFns = [];
12
+ const afterFns = [];
13
+ let runPromise;
14
+ const assertNotStarted = () => {
15
+ if (runPromise) throw new Error("Can't add a hook to a task that has already started");
16
+ };
17
+ const before = (...fns) => {
18
+ assertNotStarted();
19
+ beforeFns.push(...fns);
20
+ };
21
+ const after = (...fns) => {
22
+ assertNotStarted();
23
+ afterFns.push(...fns);
24
+ };
25
+ const runWithShell = async (taskFn) => taskFn({ sh: createShell() });
26
+ const runAll = async () => {
27
+ for (const beforeFn of beforeFns) await runWithShell(beforeFn);
28
+ await runWithShell(fn);
29
+ for (const afterFn of afterFns) await runWithShell(afterFn);
30
+ };
31
+ const run = async () => {
32
+ runPromise ??= runAll();
33
+ try {
34
+ await runPromise;
35
+ } catch (error) {
36
+ if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, run);
37
+ throw error;
38
+ }
39
+ };
40
+ const newTask = Object.assign(run, {
41
+ options,
42
+ before,
43
+ after
44
+ });
45
+ tasks.add(newTask);
46
+ return newTask;
47
+ }
48
+ //#endregion
49
+ export { getFailedTask, isTask, task };
50
+
51
+ //# sourceMappingURL=task.js.map
@@ -0,0 +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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamhl8/bask",
3
- "version": "0.0.1",
3
+ "version": "0.2.0",
4
4
  "description": "Write your tasks in TypeScript",
5
5
  "keywords": [
6
6
  "build-tool",
@@ -38,16 +38,21 @@
38
38
  ".": {
39
39
  "types": "./dist/index.d.ts",
40
40
  "import": "./dist/index.js"
41
+ },
42
+ "./cli": {
43
+ "types": "./dist/cli.d.ts",
44
+ "import": "./dist/cli.js"
41
45
  }
42
46
  },
43
47
  "publishConfig": {
44
48
  "access": "public"
45
49
  },
46
50
  "scripts": {
47
- "prepare": "just prepare"
51
+ "prepare": "bun tsdown && bun install --ignore-scripts --no-summary && bunx bask prepare"
48
52
  },
49
53
  "devDependencies": {
50
- "@adamhl8/configs": "^2.8.2",
54
+ "@adamhl8/bask": "file:.",
55
+ "@adamhl8/configs": "^3.0.1",
51
56
  "@arethetypeswrong/core": "^0.18.5",
52
57
  "@commitlint/cli": "^21.2.3",
53
58
  "@commitlint/config-conventional": "^21.2.3",
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;UAEU;EACR;;UAGQ;EACR,UAAU;;KAGP,oBAAoB;KAEpB,UAAU,KAAK,gBAAgB;iBAEnB;MACX;EACJ,SAAS;;qBAKE,SAAM,mBAAqB,SAAS;;wBAGjC,KAAK,IAAI,SAAS;wBAClB,KAAK,SAAS,aAAa,IAAI,SAAS"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { ShellWrapper } from \"#shell.ts\"\n\ninterface TaskOptions {\n desc?: string\n}\n\ninterface TaskContext {\n $: typeof ShellWrapper\n}\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ntype TaskFn = (ctx: TaskContext) => AsyncOrSyncReturn\n\nexport interface Task {\n (): Promise<void>\n options: TaskOptions\n}\n\nconst tasks = new WeakSet<object>()\n\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && tasks.has(value)\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 // Wrap `fn` so a sync `fn` still returns a promise.\n const runFn = async () => fn({ $: ShellWrapper })\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning `fn`.\n let taskFnPromise: Promise<void> | undefined\n\n const run = async () => {\n if (taskFnPromise) return taskFnPromise\n taskFnPromise = runFn()\n return taskFnPromise\n }\n\n const newTask: Task = Object.assign(run, { options })\n tasks.add(newTask)\n return newTask\n}\n"],"mappings":";;AAmBA,MAAM,wBAAQ,IAAI,QAAgB;AAElC,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,MAAM,IAAI,KAAK;AAKvG,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;CAGlD,MAAM,QAAQ,YAAY,GAAG,EAAE,GAAG,aAAa,CAAC;CAGhD,IAAI;CAEJ,MAAM,MAAM,YAAY;EACtB,IAAI,eAAe,OAAO;EAC1B,gBAAgB,MAAM;EACtB,OAAO;CACT;CAEA,MAAM,UAAgB,OAAO,OAAO,KAAK,EAAE,QAAQ,CAAC;CACpD,MAAM,IAAI,OAAO;CACjB,OAAO;AACT"}