@adamhl8/bask 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +29 -3
  2. package/dist/bask-file/bask-file.d.ts +3 -0
  3. package/dist/bask-file/bask-file.js +59 -0
  4. package/dist/bask-file/bask-file.js.map +1 -0
  5. package/dist/bask-file/list.d.ts +4 -0
  6. package/dist/bask-file/list.js +32 -0
  7. package/dist/bask-file/list.js.map +1 -0
  8. package/dist/bask-file/loaded.js +18 -0
  9. package/dist/bask-file/loaded.js.map +1 -0
  10. package/dist/bask-file/task-index.d.ts +2 -0
  11. package/dist/bask-file/task-index.js +69 -0
  12. package/dist/bask-file/task-index.js.map +1 -0
  13. package/dist/cli.js +15 -83
  14. package/dist/cli.js.map +1 -1
  15. package/dist/config.d.ts +46 -0
  16. package/dist/config.js +26 -0
  17. package/dist/config.js.map +1 -0
  18. package/dist/index.d.ts +3 -2
  19. package/dist/index.js +4 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/run-bask.js +47 -0
  22. package/dist/run-bask.js.map +1 -0
  23. package/dist/shell/bin-dirs.js +15 -0
  24. package/dist/shell/bin-dirs.js.map +1 -0
  25. package/dist/shell/command.d.ts +57 -0
  26. package/dist/shell/command.js +159 -0
  27. package/dist/shell/command.js.map +1 -0
  28. package/dist/shell/node-shim.js +47 -0
  29. package/dist/shell/node-shim.js.map +1 -0
  30. package/dist/shell/shell.d.ts +41 -0
  31. package/dist/shell/shell.js +55 -0
  32. package/dist/shell/shell.js.map +1 -0
  33. package/dist/task.d.ts +1 -3
  34. package/dist/task.js +15 -11
  35. package/dist/task.js.map +1 -1
  36. package/dist/utils.js +1 -2
  37. package/package.json +18 -13
  38. package/dist/registry.d.ts +0 -5
  39. package/dist/registry.d.ts.map +0 -1
  40. package/dist/registry.js +0 -96
  41. package/dist/registry.js.map +0 -1
  42. package/dist/shell.d.ts +0 -57
  43. package/dist/shell.d.ts.map +0 -1
  44. package/dist/shell.js +0 -142
  45. package/dist/shell.js.map +0 -1
  46. package/dist/task.d.ts.map +0 -1
package/README.md CHANGED
@@ -236,6 +236,8 @@ export const lint = task(async ({ sh }) => {
236
236
 
237
237
  > [!TIP]
238
238
  > Like a `package.json` script, `sh` finds installed bins in `node_modules/.bin`, so `oxlint` and `bun oxlint` both work.
239
+ >
240
+ > By default, `sh` runs `node_modules` bins and other `node` commands under Bun, like Bun's `--bun` flag. To use the real Node, see `.bun()` in [Shell settings](#shell-settings).
239
241
 
240
242
  To run a command without printing it, use `.echo(false)`:
241
243
 
@@ -250,15 +252,21 @@ See the [Bun Shell docs](https://bun.sh/docs/runtime/shell) for the full API.
250
252
 
251
253
  ### Shell settings
252
254
 
253
- The following methods can be used on the `sh` instance _or_ on each command.
255
+ The following methods can be used on the `sh` instance _or_ on each command. To set them for every shell, see [Project-wide shell settings](#project-wide-shell-settings).
254
256
 
255
257
  - `.cwd()` - Changes the working directory
256
258
  - Relative paths resolve from the directory you ran `bask` in, not from the `sh` instance's cwd
257
- - `.env()` - Sets the environment variables
258
- - This replaces the whole environment, so spread `process.env` to keep it: `.env({ ...process.env, DEBUG: "1" })`
259
+ - `.env()` - Adds environment variables on top of `process.env`: `.env({ DEBUG: "1" })`
260
+ - Set a variable to `undefined` to remove it: `.env({ DEBUG: undefined })`
261
+ - Commands use `process.env` as it was when `bask.ts` finished loading, so later changes to it don't reach them
262
+ - Pass later changes through with `.env(process.env)`. This also brings back variables removed earlier, so put removals after it: `.env({ ...process.env, DEBUG: undefined })`
263
+ - `.quiet()` - Hides the command's output instead of writing it to the terminal
264
+ - If a quiet command fails and the error isn't caught, bask prints its output along with the error
259
265
  - `.nothrow()` - Doesn't throw an error when a command exits with a non-zero exit code
260
266
  - `.throws()` - Sets whether a non-zero exit code throws an error
261
267
  - `.echo()` - Sets whether the command is printed before it runs
268
+ - `.bun()` - Sets whether `node_modules` bins and other `node` commands run under Bun (on by default)
269
+ - Turn it off for a tool that doesn't work on Bun: ``sh`some-tool`.bun(false)``
262
270
 
263
271
  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.
264
272
 
@@ -272,6 +280,24 @@ export const buildWeb = task(async ({ sh }) => {
272
280
  })
273
281
  ```
274
282
 
283
+ #### Project-wide shell settings
284
+
285
+ To change the defaults for every shell, including the ones in task hooks, export `baskConfig` from `bask.ts`:
286
+
287
+ ```ts
288
+ import { defineConfig } from "@adamhl8/bask"
289
+
290
+ export const baskConfig = defineConfig({
291
+ shell: { echo: false, bun: false },
292
+ })
293
+ ```
294
+
295
+ `shell` takes `cwd`, `env`, `quiet`, `throws`, `echo`, and `bun`, which work like the methods above. A setting on `sh` overrides `baskConfig`, and a setting on a command overrides both.
296
+
297
+ - `env` adds to `process.env` as it was when `bask.ts` finished loading, and the `env` of `sh` and of each command add to that
298
+ - `sh.cwd()` and `sh.env()` with no argument go back to the `baskConfig` value
299
+ - A `baskConfig` re-exported with `export *` applies, but a `baskConfig` in `bask.ts` replaces it entirely
300
+
275
301
  ## Extending/sharing tasks
276
302
 
277
303
  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.
@@ -0,0 +1,3 @@
1
+ import "./task-index.js";
2
+ import "../config.js";
3
+ import "ts-explicit-errors";
@@ -0,0 +1,59 @@
1
+ import { setLoadedBaskFile } from "./loaded.js";
2
+ import { indexTasks } from "./task-index.js";
3
+ import { isBaskConfig, resolveShellConfig } from "../config.js";
4
+ import { addBinDirsToPath } from "../shell/bin-dirs.js";
5
+ import { isTask } from "../task.js";
6
+ import path from "node:path";
7
+ import bun from "bun";
8
+ import { attempt, err, getContext, isErr, messageChain } from "ts-explicit-errors";
9
+ // src/bask-file/bask-file.ts
10
+ /** Returns a single error as is, or joins several into one error under a count with one per line. */
11
+ const joinBaskFileErrors = (baskFileErrors) => {
12
+ const [onlyError] = baskFileErrors;
13
+ if (onlyError && baskFileErrors.length === 1) return onlyError;
14
+ const lines = baskFileErrors.map((error) => ` ${messageChain(error)}`);
15
+ return err([`bask.ts has ${baskFileErrors.length} problems:`, ...lines].join("\n"), void 0);
16
+ };
17
+ /** Imports `bask.ts`, and returns an error that marks it invalid instead of throwing it. */
18
+ const importBaskFile = async (baskPath) => {
19
+ const baskFileExports = await attempt(async () => import(baskPath));
20
+ if (isErr(baskFileExports) && getContext(baskFileExports, "invalidBaskFile")) return baskFileExports;
21
+ if (isErr(baskFileExports)) throw baskFileExports;
22
+ return baskFileExports;
23
+ };
24
+ /** Validates the exports of `bask.ts` and indexes its tasks. */
25
+ const resolveBaskFileExports = (baskFileExports) => {
26
+ const baskFileErrors = [];
27
+ const { default: defaultExport, baskConfig } = baskFileExports;
28
+ if (defaultExport !== void 0 && !isTask(defaultExport)) baskFileErrors.push(err("the default export isn't a task. Wrap it in task().", void 0));
29
+ let config = {};
30
+ if (isBaskConfig(baskConfig)) config = baskConfig;
31
+ else if (baskConfig !== void 0) baskFileErrors.push(err("baskConfig isn't a config. Wrap it in defineConfig().", void 0));
32
+ const { tasks, errors: taskErrors } = indexTasks(baskFileExports);
33
+ baskFileErrors.push(...taskErrors);
34
+ if (baskFileErrors.length > 0) return joinBaskFileErrors(baskFileErrors);
35
+ return {
36
+ tasks,
37
+ config
38
+ };
39
+ };
40
+ /** Imports and validates `bask.ts`, then stores it for tasks to read when they run. */
41
+ const loadBaskFile = async (baskPath) => {
42
+ const baskDir = path.dirname(baskPath);
43
+ if (!await bun.file(baskPath).exists()) return err(`no bask.ts in ${baskDir}`, void 0);
44
+ addBinDirsToPath(baskDir);
45
+ const baskFileExports = await importBaskFile(baskPath);
46
+ if (isErr(baskFileExports)) return baskFileExports;
47
+ const resolvedExports = resolveBaskFileExports(baskFileExports);
48
+ if (isErr(resolvedExports)) return resolvedExports;
49
+ const { tasks, config } = resolvedExports;
50
+ const baskFile = {
51
+ tasks,
52
+ config: { shell: resolveShellConfig(config.shell ?? {}, process.env) }
53
+ };
54
+ setLoadedBaskFile(baskFile);
55
+ return baskFile;
56
+ };
57
+ export { loadBaskFile };
58
+
59
+ //# sourceMappingURL=bask-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bask-file.js","names":[],"sources":["../../src/bask-file/bask-file.ts"],"sourcesContent":["import path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { setLoadedBaskFile } from \"#bask-file/loaded.ts\"\nimport { indexTasks } from \"#bask-file/task-index.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { isBaskConfig, resolveShellConfig } from \"#config.ts\"\nimport type { BaskConfig, BaskConfigInput } from \"#config.ts\"\nimport { addBinDirsToPath } from \"#shell/bin-dirs.ts\"\nimport { isTask } from \"#task.ts\"\n\n/** The exports of `bask.ts`, before bask checks them. */\nexport interface BaskFileExports {\n default?: unknown\n baskConfig?: unknown\n [exportName: string]: unknown\n}\n\nexport interface BaskFile {\n tasks: TaskIndex\n /** The `baskConfig` export with its defaults filled in, and `shell.env` holding the whole starting environment. */\n config: BaskConfig\n}\n\n/** Returns a single error as is, or joins several into one error under a count with one per line. */\nconst joinBaskFileErrors = (baskFileErrors: Error[]) => {\n const [onlyError] = baskFileErrors\n if (onlyError && baskFileErrors.length === 1) return onlyError\n const lines = baskFileErrors.map((error) => ` ${messageChain(error)}`)\n return err([`bask.ts has ${baskFileErrors.length} problems:`, ...lines].join(\"\\n\"), undefined)\n}\n\n/** Imports `bask.ts`, and returns an error that marks it invalid instead of throwing it. */\nconst importBaskFile = async (baskPath: string): Promise<Result<BaskFileExports>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - a module namespace is always an object, and `resolveBaskFileExports` checks each export\n const baskFileExports = await attempt(async () => import(baskPath) as Promise<BaskFileExports>)\n if (isErr(baskFileExports) && getContext(baskFileExports, \"invalidBaskFile\")) return baskFileExports\n\n // Rethrow any other error, because a bug in `bask.ts` needs its stack trace.\n if (isErr(baskFileExports)) throw baskFileExports\n\n return baskFileExports\n}\n\n/** Validates the exports of `bask.ts` and indexes its tasks. */\nconst resolveBaskFileExports = (\n baskFileExports: BaskFileExports,\n): Result<{ tasks: TaskIndex; config: BaskConfigInput }> => {\n // Collect every error before returning, so one run reports all of them.\n const baskFileErrors: Error[] = []\n\n const { default: defaultExport, baskConfig } = baskFileExports\n\n // Reject a non-task default because bask runs it when no task is named, so it's always a mistake.\n if (defaultExport !== undefined && !isTask(defaultExport))\n baskFileErrors.push(err(\"the default export isn't a task. Wrap it in task().\", undefined))\n\n let config: BaskConfigInput = {}\n if (isBaskConfig(baskConfig)) config = baskConfig\n else if (baskConfig !== undefined)\n baskFileErrors.push(err(\"baskConfig isn't a config. Wrap it in defineConfig().\", undefined))\n\n const { tasks, errors: taskErrors } = indexTasks(baskFileExports)\n baskFileErrors.push(...taskErrors)\n\n if (baskFileErrors.length > 0) return joinBaskFileErrors(baskFileErrors)\n\n return { tasks, config }\n}\n\n/** Imports and validates `bask.ts`, then stores it for tasks to read when they run. */\nexport const loadBaskFile = async (baskPath: string): Promise<Result<BaskFile>> => {\n const baskDir = path.dirname(baskPath)\n if (!(await bun.file(baskPath).exists())) return err(`no bask.ts in ${baskDir}`, undefined)\n\n // Add the bin dirs before the import because loading copies `process.env` for every shell.\n addBinDirsToPath(baskDir)\n const baskFileExports = await importBaskFile(baskPath)\n if (isErr(baskFileExports)) return baskFileExports\n\n const resolvedExports = resolveBaskFileExports(baskFileExports)\n if (isErr(resolvedExports)) return resolvedExports\n\n const { tasks, config } = resolvedExports\n // Copy `process.env` once `bask.ts` has loaded, so later changes to it don't reach commands.\n const resolvedShellConfig = resolveShellConfig(config.shell ?? {}, process.env)\n const baskFile: BaskFile = { tasks, config: { shell: resolvedShellConfig } }\n setLoadedBaskFile(baskFile)\n\n return baskFile\n}\n"],"mappings":";;;;;;;;;;AA4BA,MAAM,sBAAsB,mBAA4B;CACtD,MAAM,CA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uBAAuB,eAAe;CAC9D,IAAI,MAAM,eAAe,GAAG,OAAO;CAEnC,MAAM,EAAE,OAAO,WAAW;CAG1B,MAAM,WAAqB;EAAE;EAAO,QAAQ,EAAE,OADlB,mBAAmB,OAAO,SAAS,CAAC,GAAG,QAAQ,GACJ,EAAE;CAAE;CAC3E,kBAAkB,QAAQ;CAE1B,OAAO;AACT"}
@@ -0,0 +1,4 @@
1
+ import { Task } from "../task.js";
2
+ import "./task-index.js";
3
+ export declare const list: Task;
4
+ //# sourceMappingURL=list.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { getLoadedBaskFile } from "./loaded.js";
2
+ import { task } from "../task.js";
3
+ // src/bask-file/list.ts
4
+ const collator = new Intl.Collator();
5
+ const formatAliases = (aliases) => {
6
+ if (aliases.length === 0) return;
7
+ return `[${aliases.length === 1 ? "alias" : "aliases"}: ${aliases.join(", ")}]`;
8
+ };
9
+ const formatTaskList = (tasks) => {
10
+ const defaultEntry = tasks.byName.get("default");
11
+ const rows = [...tasks.byTask.values()].filter((entry) => !entry.task.options.hidden).map((entry) => {
12
+ const defaultMarker = entry === defaultEntry && entry.name !== "default" ? "[default]" : void 0;
13
+ const comment = [
14
+ entry.task.options.desc,
15
+ defaultMarker,
16
+ formatAliases(entry.aliases)
17
+ ].filter(Boolean).join(" ");
18
+ return {
19
+ name: entry.name,
20
+ comment
21
+ };
22
+ }).toSorted((a, b) => collator.compare(a.name, b.name));
23
+ const nameWidth = Math.max(...rows.map((row) => row.name.length));
24
+ return ["Available tasks:", ...rows.map(({ name, comment }) => comment ? ` ${name.padEnd(nameWidth)} # ${comment}` : ` ${name}`)].join("\n");
25
+ };
26
+ const list = task(() => {
27
+ const { tasks } = getLoadedBaskFile();
28
+ console.log(formatTaskList(tasks));
29
+ });
30
+ export { formatTaskList, list };
31
+
32
+ //# sourceMappingURL=list.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"list.js","names":[],"sources":["../../src/bask-file/list.ts"],"sourcesContent":["import { getLoadedBaskFile } from \"#bask-file/loaded.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { task } from \"#task.ts\"\n\nconst collator = new Intl.Collator()\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 = (tasks: TaskIndex) => {\n const defaultEntry = tasks.byName.get(\"default\")\n\n const rows = [...tasks.byTask.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) => collator.compare(a.name, 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 const { tasks } = getLoadedBaskFile()\n console.log(formatTaskList(tasks))\n})\n"],"mappings":";;;AAIA,MAAM,WAAW,IAAI,KAAK,SAAS;AAEnC,MAAM,iBAAiB,YAAsB;CAC3C,IAAI,QAAQ,WAAW,GAAG;CAC1B,OAAO,IAAI,QAAQ,WAAW,IAAI,UAAU,UAAU,IAAI,QAAQ,KAAK,IAAI,EAAE;AAC/E;AAEA,MAAa,kBAAkB,UAAqB;CAClD,MAAM,eAAe,MAAM,OAAO,IAAI,SAAS;CAE/C,MAAM,OAAO,CAAC,GAAG,MAAM,OAAO,OAAO,CAAC,CAAC,CACpC,QAAQ,UAAU,CAAC,MAAM,KAAK,QAAQ,MAAM,CAAC,CAC7C,KAAK,UAAU;EACd,MAAM,gBAAgB,UAAU,gBAAgB,MAAM,SAAS,YAAY,cAAc,KAAA;EACzF,MAAM,UAAU;GAAC,MAAM,KAAK,QAAQ;GAAM;GAAe,cAAc,MAAM,OAAO;EAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;EAC/G,OAAO;GAAE,MAAM,MAAM;GAAM;EAAQ;CACrC,CAAC,CAAC,CACD,UAAU,GAAG,MAAM,SAAS,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC;CAEtD,MAAM,YAAY,KAAK,IAAI,GAAG,KAAK,KAAK,QAAQ,IAAI,KAAK,MAAM,CAAC;CAIhE,OAAO,CAAC,oBAAoB,GAHd,KAAK,KAAK,EAAE,MAAM,cAC9B,UAAU,OAAO,KAAK,OAAO,SAAS,EAAE,KAAK,YAAY,OAAO,MAE/B,CAAC,CAAC,CAAC,KAAK,IAAI;AACjD;AAEA,MAAa,OAAO,WAAW;CAC7B,MAAM,EAAE,UAAU,kBAAkB;CACpC,QAAQ,IAAI,eAAe,KAAK,CAAC;AACnC,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { err } from "ts-explicit-errors";
2
+ // src/bask-file/loaded.ts
3
+ let loadedBaskFile;
4
+ /** Stores the validated `bask.ts` for tasks to read when they run. */
5
+ const setLoadedBaskFile = (baskFile) => {
6
+ loadedBaskFile = baskFile;
7
+ };
8
+ /**
9
+ * Returns the loaded `bask.ts`. Throws until the CLI has loaded it, because only a task called at the top level of
10
+ * `bask.ts` gets here that early.
11
+ */
12
+ const getLoadedBaskFile = () => {
13
+ if (loadedBaskFile) return loadedBaskFile;
14
+ throw err("a task ran while bask.ts was loading. Call tasks from inside other tasks, not at the top level.", void 0, { invalidBaskFile: true });
15
+ };
16
+ export { getLoadedBaskFile, setLoadedBaskFile };
17
+
18
+ //# sourceMappingURL=loaded.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaded.js","names":[],"sources":["../../src/bask-file/loaded.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFile } from \"#bask-file/bask-file.ts\"\n\nlet loadedBaskFile: BaskFile | undefined\n\n/** Stores the validated `bask.ts` for tasks to read when they run. */\nexport const setLoadedBaskFile = (baskFile: BaskFile) => {\n loadedBaskFile = baskFile\n}\n\n/**\n * Returns the loaded `bask.ts`. Throws until the CLI has loaded it, because only a task called at the top level of\n * `bask.ts` gets here that early.\n */\nexport const getLoadedBaskFile = () => {\n if (loadedBaskFile) return loadedBaskFile\n throw err(\n \"a task ran while bask.ts was loading. Call tasks from inside other tasks, not at the top level.\",\n undefined,\n { invalidBaskFile: true },\n )\n}\n"],"mappings":";;AAIA,IAAI;;AAGJ,MAAa,qBAAqB,aAAuB;CACvD,iBAAiB;AACnB;;;;;AAMA,MAAa,0BAA0B;CACrC,IAAI,gBAAgB,OAAO;CAC3B,MAAM,IACJ,mGACA,KAAA,GACA,EAAE,iBAAiB,KAAK,CAC1B;AACF"}
@@ -0,0 +1,2 @@
1
+ import "./bask-file.js";
2
+ import "../task.js";
@@ -0,0 +1,69 @@
1
+ import { isTask } from "../task.js";
2
+ import { err } from "ts-explicit-errors";
3
+ // src/bask-file/task-index.ts
4
+ const toKebabCase = (name) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`);
5
+ const toCamelCase = (name) => name.replaceAll(/-[\da-z]/gv, (match) => match.slice(1).toUpperCase());
6
+ /** Indexes the bask file's tasks under both spellings of their export names and aliases, collecting any errors. */
7
+ const indexTasks = (baskFileExports) => {
8
+ const errors = [];
9
+ const { default: defaultExport, ...namedExports } = baskFileExports;
10
+ const exportEntries = Object.entries(namedExports);
11
+ if (defaultExport !== void 0) exportEntries.push(["default", defaultExport]);
12
+ const byName = /* @__PURE__ */ new Map();
13
+ const byTask = /* @__PURE__ */ new Map();
14
+ for (const [exportName, exportedTask] of exportEntries) {
15
+ if (!isTask(exportedTask)) continue;
16
+ const existingEntry = byTask.get(exportedTask);
17
+ if (existingEntry && exportName === "default") {
18
+ byName.set("default", existingEntry);
19
+ continue;
20
+ }
21
+ if (existingEntry) {
22
+ errors.push(err(`task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`, void 0));
23
+ continue;
24
+ }
25
+ const kebabName = toKebabCase(exportName);
26
+ const entry = {
27
+ exportName,
28
+ name: kebabName,
29
+ aliases: [],
30
+ task: exportedTask
31
+ };
32
+ byTask.set(exportedTask, entry);
33
+ byName.set(exportName, entry);
34
+ byName.set(kebabName, entry);
35
+ }
36
+ for (const entry of byTask.values()) {
37
+ const aliases = [entry.task.options.alias ?? []].flat();
38
+ for (const alias of aliases) {
39
+ const kebabAlias = toKebabCase(alias);
40
+ const camelAlias = toCamelCase(alias);
41
+ if (kebabAlias === "default") {
42
+ errors.push(err(`task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`, void 0));
43
+ continue;
44
+ }
45
+ if (byName.get(kebabAlias) === entry) continue;
46
+ const keys = [
47
+ alias,
48
+ kebabAlias,
49
+ camelAlias
50
+ ];
51
+ const owner = keys.map((key) => byName.get(key)).find(Boolean);
52
+ if (owner) errors.push(err(`task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`, void 0));
53
+ else {
54
+ entry.aliases.push(kebabAlias);
55
+ for (const key of keys) byName.set(key, entry);
56
+ }
57
+ }
58
+ }
59
+ return {
60
+ tasks: {
61
+ byName,
62
+ byTask
63
+ },
64
+ errors
65
+ };
66
+ };
67
+ export { indexTasks };
68
+
69
+ //# sourceMappingURL=task-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task-index.js","names":[],"sources":["../../src/bask-file/task-index.ts"],"sourcesContent":["import { err } from \"ts-explicit-errors\"\n\nimport type { BaskFileExports } from \"#bask-file/bask-file.ts\"\nimport { isTask } 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\nexport interface TaskIndex {\n /** Each entry under every name and alias that runs it. */\n byName: Map<string, TaskEntry>\n /** Each entry once, under its task, in export order. */\n byTask: Map<Task, TaskEntry>\n}\n\nconst toKebabCase = (name: string) => name.replaceAll(/[A-Z]/gv, (match) => `-${match.toLowerCase()}`)\nconst toCamelCase = (name: string) => name.replaceAll(/-[\\da-z]/gv, (match) => match.slice(1).toUpperCase())\n\n/** Indexes the bask file's tasks under both spellings of their export names and aliases, collecting any errors. */\nexport const indexTasks = (baskFileExports: BaskFileExports) => {\n const errors: Error[] = []\n\n // Put the default last so a task that's also exported by name keeps that name.\n const { default: defaultExport, ...namedExports } = baskFileExports\n const exportEntries = Object.entries(namedExports)\n if (defaultExport !== undefined) exportEntries.push([\"default\", defaultExport])\n\n // Index each task under its export name and kebab-case name, collecting tasks exported more than once.\n const byName: TaskIndex[\"byName\"] = new Map()\n const byTask: TaskIndex[\"byTask\"] = new Map()\n for (const [exportName, exportedTask] of exportEntries) {\n if (!isTask(exportedTask)) continue\n\n const existingEntry = byTask.get(exportedTask)\n // Point `default` at the existing entry, because exporting a named task as the default isn't a duplicate.\n if (existingEntry && exportName === \"default\") {\n byName.set(\"default\", existingEntry)\n continue\n }\n if (existingEntry) {\n errors.push(\n err(\n `task '${exportName}' is also exported as '${existingEntry.exportName}'. Use the alias option instead.`,\n undefined,\n ),\n )\n continue\n }\n\n const kebabName = toKebabCase(exportName)\n const entry: TaskEntry = { exportName, name: kebabName, aliases: [], task: exportedTask }\n byTask.set(exportedTask, entry)\n byName.set(exportName, entry)\n byName.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 for (const entry of byTask.values()) {\n const aliases = [entry.task.options.alias ?? []].flat()\n\n for (const alias of aliases) {\n const kebabAlias = toKebabCase(alias)\n const camelAlias = toCamelCase(alias)\n\n if (kebabAlias === \"default\") {\n errors.push(\n err(\n `task '${entry.exportName}' can't use 'default' as an alias. Export it as the default instead.`,\n undefined,\n ),\n )\n continue\n }\n\n // Skip an alias that repeats the task's own name or another of its aliases.\n if (byName.get(kebabAlias) === entry) continue\n\n const keys = [alias, kebabAlias, camelAlias]\n const owner = keys.map((key) => byName.get(key)).find(Boolean)\n if (owner) {\n errors.push(\n err(\n `task '${entry.exportName}' has alias '${alias}', which task '${owner.exportName}' already uses`,\n undefined,\n ),\n )\n } else {\n entry.aliases.push(kebabAlias)\n for (const key of keys) byName.set(key, entry)\n }\n }\n }\n\n const tasks: TaskIndex = { byName, byTask }\n return { tasks, errors }\n}\n"],"mappings":";;;AAuBA,MAAM,eAAe,SAAiB,KAAK,WAAW,YAAY,UAAU,IAAI,MAAM,YAAY,GAAG;AACrG,MAAM,eAAe,SAAiB,KAAK,WAAW,eAAe,UAAU,MAAM,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC;;AAG3G,MAAa,cAAc,oBAAqC;CAC9D,MAAM,SAAkB,CAAC;CAGzB,MAAM,EAAE,SAAS,eAAe,GAAG,iBAAiB;CACpD,MAAM,gBAAgB,OAAO,QAAQ,YAAY;CACjD,IAAI,kBAAkB,KAAA,GAAW,cAAc,KAAK,CAAC,WAAW,aAAa,CAAC;CAG9E,MAAM,yBAA8B,IAAI,IAAI;CAC5C,MAAM,yBAA8B,IAAI,IAAI;CAC5C,KAAK,MAAM,CAAC,YAAY,iBAAiB,eAAe;EACtD,IAAI,CAAC,OAAO,YAAY,GAAG;EAE3B,MAAM,gBAAgB,OAAO,IAAI,YAAY;EAE7C,IAAI,iBAAiB,eAAe,WAAW;GAC7C,OAAO,IAAI,WAAW,aAAa;GACnC;EACF;EACA,IAAI,eAAe;GACjB,OAAO,KACL,IACE,SAAS,WAAW,yBAAyB,cAAc,WAAW,mCACtE,KAAA,CACF,CACF;GACA;EACF;EAEA,MAAM,YAAY,YAAY,UAAU;EACxC,MAAM,QAAmB;GAAE;GAAY,MAAM;GAAW,SAAS,CAAC;GAAG,MAAM;EAAa;EACxF,OAAO,IAAI,cAAc,KAAK;EAC9B,OAAO,IAAI,YAAY,KAAK;EAC5B,OAAO,IAAI,WAAW,KAAK;CAC7B;CAIA,KAAK,MAAM,SAAS,OAAO,OAAO,GAAG;EACnC,MAAM,UAAU,CAAC,MAAM,KAAK,QAAQ,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK;EAEtD,KAAK,MAAM,SAAS,SAAS;GAC3B,MAAM,aAAa,YAAY,KAAK;GACpC,MAAM,aAAa,YAAY,KAAK;GAEpC,IAAI,eAAe,WAAW;IAC5B,OAAO,KACL,IACE,SAAS,MAAM,WAAW,uEAC1B,KAAA,CACF,CACF;IACA;GACF;GAGA,IAAI,OAAO,IAAI,UAAU,MAAM,OAAO;GAEtC,MAAM,OAAO;IAAC;IAAO;IAAY;GAAU;GAC3C,MAAM,QAAQ,KAAK,KAAK,QAAQ,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,OAAO;GAC7D,IAAI,OACF,OAAO,KACL,IACE,SAAS,MAAM,WAAW,eAAe,MAAM,iBAAiB,MAAM,WAAW,iBACjF,KAAA,CACF,CACF;QACK;IACL,MAAM,QAAQ,KAAK,UAAU;IAC7B,KAAK,MAAM,OAAO,MAAM,OAAO,IAAI,KAAK,KAAK;GAC/C;EACF;CACF;CAGA,OAAO;EAAE,OAAA;GADkB;GAAQ;EACtB;EAAG;CAAO;AACzB"}
package/dist/cli.js CHANGED
@@ -1,102 +1,34 @@
1
1
  #!/usr/bin/env bun
2
+ import { runBask } from "./run-bask.js";
2
3
  import { printError } from "./utils.js";
3
- import { getFailedTask } from "./task.js";
4
- import { BaskFileError, formatTaskList, getTaskIndex, list, setBaskModule } from "./registry.js";
5
4
  import path from "node:path";
6
5
  import bun from "bun";
7
- import { parseArgs } from "node:util";
8
- //#region src/cli.ts
6
+ import { attempt, getContext, isErr, messageChain } from "ts-explicit-errors";
7
+ // src/cli.ts
9
8
  const cwd = process.cwd();
10
- const isModule = (value) => typeof value === "object" && Boolean(value);
11
- const isParseArgsError = (error) => error instanceof TypeError && "code" in error && typeof error.code === "string" && error.code.startsWith("ERR_PARSE_ARGS_");
12
9
  /** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */
13
10
  const resolveLocalCli = () => {
14
- try {
15
- return bun.resolveSync("@adamhl8/bask/cli", cwd);
16
- } catch {
17
- return;
18
- }
19
- };
20
- /** Lists `node_modules/.bin` for `dir` and each of its parents, nearest first. */
21
- const getBinDirs = (dir) => {
22
- const binDir = path.join(dir, "node_modules", ".bin");
23
- const parent = path.dirname(dir);
24
- return parent === dir ? [binDir] : [binDir, ...getBinDirs(parent)];
25
- };
26
- /** Prepends the project's `.bin` folders to `PATH`, like `bun run` does, so tasks can run installed bins by name. */
27
- const addBinDirsToPath = () => {
28
- process.env["PATH"] = [...getBinDirs(cwd), process.env["PATH"]].filter(Boolean).join(path.delimiter);
29
- };
30
- const parseCliArgs = () => {
31
- try {
32
- return parseArgs({
33
- options: { list: {
34
- type: "boolean",
35
- short: "l"
36
- } },
37
- allowPositionals: true
38
- });
39
- } catch (error) {
40
- if (!isParseArgsError(error)) throw error;
41
- printError(error.message);
42
- process.exitCode = 2;
43
- return;
44
- }
11
+ const localCli = attempt(() => bun.resolveSync("@adamhl8/bask/cli", cwd));
12
+ if (isErr(localCli)) return;
13
+ return localCli;
45
14
  };
46
- /** Runs a task and reports a failed command in one line, naming the innermost task that failed. */
47
- const runTask = async (taskToRun, taskName) => {
48
- try {
49
- await taskToRun();
50
- } catch (error) {
51
- if (!(error instanceof bun.$.ShellError)) throw error;
52
- const failedTask = getFailedTask(error);
53
- const failedName = getTaskIndex().values().find((entry) => entry.task === failedTask)?.name ?? taskName;
54
- printError(`task '${failedName}' failed with exit code ${error.exitCode}`);
55
- process.exitCode = error.exitCode;
56
- }
57
- };
58
- const main = async () => {
15
+ /** Hands off to the project's own bask CLI, or runs bask from this one. */
16
+ const bask = async () => {
59
17
  const localCli = resolveLocalCli();
60
18
  if (localCli && localCli !== import.meta.path) {
61
19
  await import(localCli);
62
20
  return;
63
21
  }
64
- const args = parseCliArgs();
65
- if (!args) return;
66
- const { values, positionals } = args;
67
- const baskPath = path.join(cwd, "bask.ts");
68
- if (!await bun.file(baskPath).exists()) {
69
- printError(`no bask.ts in ${cwd}`);
70
- process.exitCode = 1;
71
- return;
72
- }
73
- addBinDirsToPath();
74
- const baskModule = await import(baskPath);
75
- if (!isModule(baskModule)) throw new Error("failed to import bask.ts");
76
- try {
77
- setBaskModule(baskModule);
78
- } catch (error) {
79
- if (!(error instanceof BaskFileError)) throw error;
80
- printError(error.message);
81
- process.exitCode = 1;
82
- return;
83
- }
84
- const [taskName] = positionals;
85
- if (values.list || taskName === void 0 && !getTaskIndex().has("default")) {
86
- await runTask(list, "list");
87
- return;
88
- }
89
- const selectedEntry = getTaskIndex().get(taskName ?? "default");
90
- if (!selectedEntry) {
91
- printError(`unknown task '${taskName ?? "default"}'`);
92
- process.stderr.write(`\n${formatTaskList()}\n`);
93
- process.exitCode = 1;
94
- return;
22
+ return runBask(process.argv.slice(2), path.join(cwd, "bask.ts"));
23
+ };
24
+ const main = async () => {
25
+ const result = await bask();
26
+ if (isErr(result)) {
27
+ printError(messageChain(result));
28
+ process.exitCode = getContext(result, "exitCode") ?? 1;
95
29
  }
96
- await runTask(selectedEntry.task, selectedEntry.name);
97
30
  };
98
31
  await main();
99
- //#endregion
100
32
  export {};
101
33
 
102
34
  //# sourceMappingURL=cli.js.map
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 } 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 cwd = process.cwd()\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\", cwd)\n } catch {\n return\n }\n}\n\n/** Lists `node_modules/.bin` for `dir` and each of its parents, nearest first. */\nconst getBinDirs = (dir: string): string[] => {\n const binDir = path.join(dir, \"node_modules\", \".bin\")\n const parent = path.dirname(dir)\n return parent === dir ? [binDir] : [binDir, ...getBinDirs(parent)]\n}\n\n/** Prepends the project's `.bin` folders to `PATH`, like `bun run` does, so tasks can run installed bins by name. */\nconst addBinDirsToPath = () => {\n // oxlint-disable-next-line node/no-process-env - commands in `sh` look up bins on this `PATH`\n process.env[\"PATH\"] = [...getBinDirs(cwd), process.env[\"PATH\"]].filter(Boolean).join(path.delimiter)\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.join(cwd, \"bask.ts\")\n if (!(await bun.file(baskPath).exists())) {\n printError(`no bask.ts in ${cwd}`)\n process.exitCode = 1\n return\n }\n\n addBinDirsToPath()\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,MAAM,QAAQ,IAAI;AAExB,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,GAAG;CACjD,QAAQ;EACN;CACF;AACF;;AAGA,MAAM,cAAc,QAA0B;CAC5C,MAAM,SAAS,KAAK,KAAK,KAAK,gBAAgB,MAAM;CACpD,MAAM,SAAS,KAAK,QAAQ,GAAG;CAC/B,OAAO,WAAW,MAAM,CAAC,MAAM,IAAI,CAAC,QAAQ,GAAG,WAAW,MAAM,CAAC;AACnE;;AAGA,MAAM,yBAAyB;CAE7B,QAAQ,IAAI,UAAU,CAAC,GAAG,WAAW,GAAG,GAAG,QAAQ,IAAI,OAAO,CAAC,CAAC,OAAO,OA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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"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env bun\n\nimport path from \"node:path\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, getContext, isErr, messageChain } from \"ts-explicit-errors\"\n\nimport { runBask } from \"#run-bask.ts\"\nimport { printError } from \"#utils.ts\"\n\nconst cwd = process.cwd()\n\n/** Finds the project's own bask CLI, so a global `bask` runs the version the project pins. */\nconst resolveLocalCli = () => {\n const localCli = attempt(() => bun.resolveSync(\"@adamhl8/bask/cli\", cwd))\n if (isErr(localCli)) return\n return localCli\n}\n\n/** Hands off to the project's own bask CLI, or runs bask from this one. */\nconst bask = async (): Promise<Result> => {\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 return runBask(process.argv.slice(2), path.join(cwd, \"bask.ts\"))\n}\n\nconst main = async () => {\n const result = await bask()\n if (isErr(result)) {\n printError(messageChain(result))\n // Set the exit code only on an error, because the local CLI sets its own.\n process.exitCode = getContext<number>(result, \"exitCode\") ?? 1\n }\n}\n\nawait main()\n"],"mappings":";;;;;;;AAWA,MAAM,MAAM,QAAQ,IAAI;;AAGxB,MAAM,wBAAwB;CAC5B,MAAM,WAAW,cAAc,IAAI,YAAY,qBAAqB,GAAG,CAAC;CACxE,IAAI,MAAM,QAAQ,GAAG;CACrB,OAAO;AACT;;AAGA,MAAM,OAAO,YAA6B;CAGxC,MAAM,WAAW,gBAAgB;CACjC,IAAI,YAAY,aAAa,YAAY,MAAM;EAC7C,MAAM,OAAO;EACb;CACF;CAEA,OAAO,QAAQ,QAAQ,KAAK,MAAM,CAAC,GAAG,KAAK,KAAK,KAAK,SAAS,CAAC;AACjE;AAEA,MAAM,OAAO,YAAY;CACvB,MAAM,SAAS,MAAM,KAAK;CAC1B,IAAI,MAAM,MAAM,GAAG;EACjB,WAAW,aAAa,MAAM,CAAC;EAE/B,QAAQ,WAAW,WAAmB,QAAQ,UAAU,KAAK;CAC/D;AACF;AAEA,MAAM,KAAK"}
@@ -0,0 +1,46 @@
1
+ import { ShellEnv } from "./shell/command.js";
2
+ /** Settings for every shell, set by the `baskConfig` export in `bask.ts`. */
3
+ export interface ShellConfig {
4
+ /**
5
+ * The default working directory for commands run by every shell.
6
+ *
7
+ * @default process.cwd()
8
+ */
9
+ cwd: string | undefined;
10
+ /**
11
+ * Environment variables for commands run by every shell, on top of `process.env` as it was when `bask.ts` loaded. Set
12
+ * one to `undefined` to remove it.
13
+ */
14
+ env: ShellEnv;
15
+ /**
16
+ * Whether commands run by every shell only buffer their output instead of also writing it to stdout and stderr.
17
+ *
18
+ * @default false
19
+ */
20
+ quiet: boolean;
21
+ /**
22
+ * Whether commands run by every shell throw an exception on non-zero exit codes.
23
+ *
24
+ * @default true
25
+ */
26
+ throws: boolean;
27
+ /**
28
+ * Whether every shell prints each command before running it.
29
+ *
30
+ * @default true
31
+ */
32
+ echo: boolean;
33
+ /**
34
+ * Whether every shell runs `node_modules` bins and `node` under Bun (like Bun's `--bun` flag).
35
+ *
36
+ * @default true
37
+ */
38
+ bun: boolean;
39
+ }
40
+ /** The `baskConfig` that `defineConfig` accepts, where every setting is optional. */
41
+ export interface BaskConfigInput {
42
+ shell?: Partial<ShellConfig>;
43
+ }
44
+ /** Marks a config for bask to read from the `baskConfig` export in `bask.ts`. */
45
+ export declare const defineConfig: (config: BaskConfigInput) => BaskConfigInput;
46
+ //# sourceMappingURL=config.d.ts.map
package/dist/config.js ADDED
@@ -0,0 +1,26 @@
1
+ // src/config.ts
2
+ /**
3
+ * Fills in the default for each shell setting that `shellConfig` leaves out. The resolved `env` holds the whole
4
+ * environment, with `shellConfig.env` on top of `baseEnv`.
5
+ */
6
+ const resolveShellConfig = (shellConfig, baseEnv) => ({
7
+ cwd: shellConfig.cwd,
8
+ env: {
9
+ ...baseEnv,
10
+ ...shellConfig.env
11
+ },
12
+ quiet: shellConfig.quiet ?? false,
13
+ throws: shellConfig.throws ?? true,
14
+ echo: shellConfig.echo ?? true,
15
+ bun: shellConfig.bun ?? true
16
+ });
17
+ const configs = /* @__PURE__ */ new WeakSet();
18
+ const isBaskConfig = (value) => typeof value === "object" && value !== null && configs.has(value);
19
+ /** Marks a config for bask to read from the `baskConfig` export in `bask.ts`. */
20
+ const defineConfig = (config) => {
21
+ configs.add(config);
22
+ return config;
23
+ };
24
+ export { defineConfig, isBaskConfig, resolveShellConfig };
25
+
26
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import type { ShellEnv } from \"#shell/command.ts\"\n\n/** Settings for every shell, set by the `baskConfig` export in `bask.ts`. */\nexport interface ShellConfig {\n /**\n * The default working directory for commands run by every shell.\n *\n * @default process.cwd()\n */\n cwd: string | undefined\n /**\n * Environment variables for commands run by every shell, on top of `process.env` as it was when `bask.ts` loaded. Set\n * one to `undefined` to remove it.\n */\n env: ShellEnv\n /**\n * Whether commands run by every shell only buffer their output instead of also writing it to stdout and stderr.\n *\n * @default false\n */\n quiet: boolean\n /**\n * Whether commands run by every shell throw an exception on non-zero exit codes.\n *\n * @default true\n */\n throws: boolean\n /**\n * Whether every shell prints each command before running it.\n *\n * @default true\n */\n echo: boolean\n /**\n * Whether every shell runs `node_modules` bins and `node` under Bun (like Bun's `--bun` flag).\n *\n * @default true\n */\n bun: boolean\n}\n\n/** Project-wide settings, set by the `baskConfig` export in `bask.ts`. */\nexport interface BaskConfig {\n /** Default settings for every shell. `sh` and each command can override them. */\n shell: ShellConfig\n}\n\n/** The `baskConfig` that `defineConfig` accepts, where every setting is optional. */\nexport interface BaskConfigInput {\n shell?: Partial<ShellConfig>\n}\n\n/**\n * Fills in the default for each shell setting that `shellConfig` leaves out. The resolved `env` holds the whole\n * environment, with `shellConfig.env` on top of `baseEnv`.\n */\nexport const resolveShellConfig = (shellConfig: Partial<ShellConfig>, baseEnv: ShellEnv): ShellConfig => ({\n cwd: shellConfig.cwd,\n env: { ...baseEnv, ...shellConfig.env },\n quiet: shellConfig.quiet ?? false,\n throws: shellConfig.throws ?? true,\n echo: shellConfig.echo ?? true,\n bun: shellConfig.bun ?? true,\n})\n\nconst configs = new WeakSet<object>()\nexport const isBaskConfig = (value: unknown): value is BaskConfigInput =>\n typeof value === \"object\" && value !== null && configs.has(value)\n\n/** Marks a config for bask to read from the `baskConfig` export in `bask.ts`. */\nexport const defineConfig = (config: BaskConfigInput) => {\n configs.add(config)\n return config\n}\n"],"mappings":";;;;;AAwDA,MAAa,sBAAsB,aAAmC,aAAoC;CACxG,KAAK,YAAY;CACjB,KAAK;EAAE,GAAG;EAAS,GAAG,YAAY;CAAI;CACtC,OAAO,YAAY,SAAS;CAC5B,QAAQ,YAAY,UAAU;CAC9B,MAAM,YAAY,QAAQ;CAC1B,KAAK,YAAY,OAAO;AAC1B;AAEA,MAAM,0BAAU,IAAI,QAAgB;AACpC,MAAa,gBAAgB,UAC3B,OAAO,UAAU,YAAY,UAAU,QAAQ,QAAQ,IAAI,KAAK;;AAGlE,MAAa,gBAAgB,WAA4B;CACvD,QAAQ,IAAI,MAAM;CAClB,OAAO;AACT"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { BaskConfigInput, defineConfig } from "./config.js";
2
+ import { list } from "./bask-file/list.js";
1
3
  import { Task, isTask, task } from "./task.js";
2
- import { list } from "./registry.js";
3
- export { type Task, isTask, list, task };
4
+ export { type BaskConfigInput, type Task, defineConfig, isTask, list, task };
package/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  import { printError } from "./utils.js";
2
+ import { defineConfig } from "./config.js";
3
+ import { list } from "./bask-file/list.js";
2
4
  import { isTask, task } from "./task.js";
3
- import { list } from "./registry.js";
4
5
  import path from "node:path";
5
6
  import bun from "bun";
6
- //#region src/index.ts
7
+ // src/index.ts
7
8
  if (path.basename(bun.main) === "bask.ts") {
8
9
  const command = ["bask", ...process.argv.slice(2)].join(" ");
9
10
  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
11
  process.exit(1);
11
12
  }
12
- //#endregion
13
- export { isTask, list, task };
13
+ export { defineConfig, isTask, list, task };
14
14
 
15
15
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +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"}
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 { defineConfig } from \"#config.ts\"\nexport type { BaskConfigInput } from \"#config.ts\"\nexport { list } from \"#bask-file/list.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"}
@@ -0,0 +1,47 @@
1
+ import { loadBaskFile } from "./bask-file/bask-file.js";
2
+ import { formatTaskList, list } from "./bask-file/list.js";
3
+ import { hasHiddenOutput } from "./shell/command.js";
4
+ import { getFailedTask } from "./task.js";
5
+ import bun from "bun";
6
+ import { parseArgs } from "node:util";
7
+ import { attempt, err, isErr } from "ts-explicit-errors";
8
+ // src/run-bask.ts
9
+ /** Runs a task and returns a failed command as an error that names the innermost task that failed. */
10
+ const runTask = async (tasks, taskToRun, taskName) => {
11
+ const error = await attempt(async () => taskToRun());
12
+ if (!error) return;
13
+ if (!(error instanceof bun.$.ShellError)) throw error;
14
+ if (hasHiddenOutput(error)) {
15
+ process.stdout.write(error.stdout);
16
+ process.stderr.write(error.stderr);
17
+ }
18
+ const failedTask = getFailedTask(error);
19
+ const failedName = (failedTask && tasks.byTask.get(failedTask))?.name ?? taskName;
20
+ return err(`task '${failedName}' failed with exit code ${error.exitCode}`, void 0, { exitCode: error.exitCode });
21
+ };
22
+ /** Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. */
23
+ const runBask = async (args, baskPath) => {
24
+ const parsedArgs = attempt(() => parseArgs({
25
+ args,
26
+ options: { list: {
27
+ type: "boolean",
28
+ short: "l"
29
+ } },
30
+ allowPositionals: true
31
+ }));
32
+ if (isErr(parsedArgs)) return err(parsedArgs.message, void 0, { exitCode: 2 });
33
+ const { values: flags, positionals } = parsedArgs;
34
+ const baskFile = await loadBaskFile(baskPath);
35
+ if (isErr(baskFile)) return baskFile;
36
+ const { tasks } = baskFile;
37
+ const [taskName] = positionals;
38
+ const resolvedTaskName = taskName ?? "default";
39
+ const selectedTaskEntry = tasks.byName.get(resolvedTaskName);
40
+ if (flags.list || taskName === void 0 && !selectedTaskEntry) return runTask(tasks, list, "list");
41
+ if (!selectedTaskEntry) return err(`unknown task '${resolvedTaskName}'\n\n${formatTaskList(tasks)}`, void 0);
42
+ const { task, name } = selectedTaskEntry;
43
+ return runTask(tasks, task, name);
44
+ };
45
+ export { runBask };
46
+
47
+ //# sourceMappingURL=run-bask.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-bask.js","names":[],"sources":["../src/run-bask.ts"],"sourcesContent":["import { parseArgs } from \"node:util\"\n\nimport bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err, isErr } from \"ts-explicit-errors\"\n\nimport { loadBaskFile } from \"#bask-file/bask-file.ts\"\nimport { formatTaskList, list } from \"#bask-file/list.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { hasHiddenOutput } from \"#shell/command.ts\"\nimport { getFailedTask } from \"#task.ts\"\nimport type { Task } from \"#task.ts\"\n\n/** Runs a task and returns a failed command as an error that names the innermost task that failed. */\nconst runTask = async (tasks: TaskIndex, taskToRun: Task, taskName: string): Promise<Result> => {\n const error = await attempt(async () => taskToRun())\n if (!error) return\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 // Print the output of a command that hid it, because it usually explains the failure.\n if (hasHiddenOutput(error)) {\n process.stdout.write(error.stdout)\n process.stderr.write(error.stderr)\n }\n\n const failedTask = getFailedTask(error)\n const failedEntry = failedTask && tasks.byTask.get(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 return err(`task '${failedName}' failed with exit code ${error.exitCode}`, undefined, { exitCode: error.exitCode })\n}\n\n/** Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. */\nexport const runBask = async (args: string[], baskPath: string): Promise<Result> => {\n const parsedArgs = attempt(() =>\n parseArgs({ args, options: { list: { type: \"boolean\", short: \"l\" } }, allowPositionals: true }),\n )\n // Copy the message to leave out the `TypeError` name, which `messageChain` prints.\n if (isErr(parsedArgs)) return err(parsedArgs.message, undefined, { exitCode: 2 })\n const { values: flags, positionals } = parsedArgs\n\n const baskFile = await loadBaskFile(baskPath)\n if (isErr(baskFile)) return baskFile\n const { tasks } = baskFile\n\n const [taskName] = positionals\n const resolvedTaskName = taskName ?? \"default\"\n const selectedTaskEntry = tasks.byName.get(resolvedTaskName)\n\n // List the tasks when asked, or when no task is named and there's no default to run.\n if (flags.list || (taskName === undefined && !selectedTaskEntry)) return runTask(tasks, list, \"list\")\n\n if (!selectedTaskEntry) return err(`unknown task '${resolvedTaskName}'\\n\\n${formatTaskList(tasks)}`, undefined)\n\n const { task, name } = selectedTaskEntry\n return runTask(tasks, task, name)\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,UAAU,OAAO,OAAkB,WAAiB,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