@adamhl8/bask 0.7.0 → 0.8.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 +54 -3
- package/dist/bask-file/task-index.d.ts +1 -1
- package/dist/bask-file/task-index.js.map +1 -1
- package/dist/cli/list.d.ts +2 -1
- package/dist/cli/run-bask.js +1 -1
- package/dist/cli/run-bask.js.map +1 -1
- package/dist/cli/run-task.js +1 -1
- package/dist/cli/run-task.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js.map +1 -1
- package/dist/task/command-line-args.js +12 -0
- package/dist/task/command-line-args.js.map +1 -0
- package/dist/task/cycles.js +42 -0
- package/dist/task/cycles.js.map +1 -0
- package/dist/task/failed-task.js +11 -0
- package/dist/task/failed-task.js.map +1 -0
- package/dist/task/types.d.ts +46 -0
- package/dist/task.d.ts +2 -31
- package/dist/task.js +75 -34
- package/dist/task.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,6 +16,7 @@ A task runner where your tasks are TypeScript functions.
|
|
|
16
16
|
- [Task arguments](#task-arguments)
|
|
17
17
|
- [Task dependencies](#task-dependencies)
|
|
18
18
|
- [Task hooks](#task-hooks)
|
|
19
|
+
- [Wrapping tasks](#wrapping-tasks)
|
|
19
20
|
- [Running commands](#running-commands)
|
|
20
21
|
- [Shell settings](#shell-settings)
|
|
21
22
|
- [Extending/sharing tasks](#extendingsharing-tasks)
|
|
@@ -232,7 +233,7 @@ Args also show next to the task in the task list:
|
|
|
232
233
|
|
|
233
234
|
### Task dependencies
|
|
234
235
|
|
|
235
|
-
To depend on another task, call it. Each task runs at most once per invocation, however many tasks call it. If two tasks call it at the same time, they both wait on the same run.
|
|
236
|
+
To depend on another task, call it. Each task runs at most once per invocation, however many tasks call it. If two tasks call it at the same time, they both wait on the same run. A task that calls itself, directly or through other tasks, will throw an error.
|
|
236
237
|
|
|
237
238
|
```ts
|
|
238
239
|
export const check = task(async () => {
|
|
@@ -270,7 +271,7 @@ build.after(async ({ sh }) => {
|
|
|
270
271
|
```
|
|
271
272
|
|
|
272
273
|
- Hooks take tasks or plain functions
|
|
273
|
-
- Hooks run in the order they were added
|
|
274
|
+
- Hooks run in the order they were added (see [Wrapping tasks](#wrapping-tasks) for how they combine with wraps)
|
|
274
275
|
- Hooks run once per invocation, along with their task
|
|
275
276
|
- This includes when another task calls the task
|
|
276
277
|
- Each hook gets its own `sh`, separate from the task's
|
|
@@ -297,6 +298,56 @@ list.after(() => {
|
|
|
297
298
|
})
|
|
298
299
|
```
|
|
299
300
|
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
### Wrapping tasks
|
|
304
|
+
|
|
305
|
+
> [!IMPORTANT]
|
|
306
|
+
> Like hooks, you'll generally only need `wrap` when [extending tasks](#extendingsharing-tasks) from another bask file.
|
|
307
|
+
|
|
308
|
+
Use `wrap` to change what a task does, or to add args to it. The function you pass wraps the task as it stands, including the hooks added so far, and `original()` runs what it wrapped:
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
import { build } from "./shared-tasks.ts"
|
|
312
|
+
|
|
313
|
+
export * from "./shared-tasks.ts"
|
|
314
|
+
|
|
315
|
+
// Add the `-r` flag which the original build task doesn't have.
|
|
316
|
+
build.wrap({ args: { release: { short: "r", desc: "Build for release" } } }, async ({ sh, args, original }) => {
|
|
317
|
+
await original()
|
|
318
|
+
if (args.release) await sh`bun run sign`
|
|
319
|
+
})
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
```sh
|
|
323
|
+
bask build -r
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
- `wrap` changes the task in place, so everything that calls it, including other shared tasks, runs the wrapped version
|
|
327
|
+
- The wrap function gets `sh`, `args`, and `positionals`, like the task, plus `original`
|
|
328
|
+
- Call `original()` to run the wrapped task, or leave it out if you want to replace the task entirely
|
|
329
|
+
- `original()` runs the entire task as it was when it was wrapped, before and after hooks included
|
|
330
|
+
- `original` runs with the same `args` and `positionals`, and is given a fresh instance of `sh`
|
|
331
|
+
- Call `original()`, never the task itself, because a task that calls itself throws an error
|
|
332
|
+
- `args` are added to the task's args, as if the task had declared them
|
|
333
|
+
- They're parsed from the command line, and they show in `bask -h <task>` and the task list
|
|
334
|
+
- An arg name the task already has throws an error
|
|
335
|
+
- Hooks added before the wrap run inside it, as part of `original()`
|
|
336
|
+
- Hooks added after the wrap run around it
|
|
337
|
+
- Wrapping a task that has already started throws an error
|
|
338
|
+
|
|
339
|
+
For example:
|
|
340
|
+
|
|
341
|
+
```ts
|
|
342
|
+
build.before(clean) // clean, build
|
|
343
|
+
build.before(lint) // clean, lint, build
|
|
344
|
+
build.wrap(async ({ original }) => {
|
|
345
|
+
console.log("start")
|
|
346
|
+
await original()
|
|
347
|
+
}) // start, clean, lint, build
|
|
348
|
+
build.before(check) // check, start, clean, lint, build
|
|
349
|
+
```
|
|
350
|
+
|
|
300
351
|
## Running commands
|
|
301
352
|
|
|
302
353
|
Every task gets a shell, `sh`, which works like Bun's `$`. One difference is that `sh` prints each command before running it:
|
|
@@ -440,7 +491,7 @@ bask build
|
|
|
440
491
|
# runs astroSync -> lint -> build -> astroBuild
|
|
441
492
|
```
|
|
442
493
|
|
|
443
|
-
This way, each project extends the shared tasks without copying or replacing them.
|
|
494
|
+
This way, each project extends the shared tasks without copying or replacing them. To change what a shared task does, or to add args to it, [wrap](#wrapping-tasks) it.
|
|
444
495
|
|
|
445
496
|
## CLI Reference
|
|
446
497
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import "./bask-file.js";
|
|
2
|
-
import "../task.js";
|
|
2
|
+
import "../task/types.js";
|
|
@@ -1 +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\"\nimport { toCamelCase, toKebabCase } from \"#utils.ts\"\n\nexport interface 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\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":";;;;;AAyBA,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"}
|
|
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/types.ts\"\nimport { toCamelCase, toKebabCase } from \"#utils.ts\"\n\nexport interface 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\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 (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tC,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/list.d.ts
CHANGED
package/dist/cli/run-bask.js
CHANGED
|
@@ -6,7 +6,7 @@ import { parseWithOptique } from "./optique.js";
|
|
|
6
6
|
import { runTask } from "./run-task.js";
|
|
7
7
|
import { splitArgs } from "./split-args.js";
|
|
8
8
|
import { checkAllTaskArgs, toTaskParser } from "./task-parser.js";
|
|
9
|
-
import { runWithArgs } from "../task.js";
|
|
9
|
+
import { runWithArgs } from "../task/command-line-args.js";
|
|
10
10
|
import { isErr } from "ts-explicit-errors";
|
|
11
11
|
// src/cli/run-bask.ts
|
|
12
12
|
const ARGS_ERROR_EXIT_CODE = 2;
|
package/dist/cli/run-bask.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-bask.js","names":[],"sources":["../../src/cli/run-bask.ts"],"sourcesContent":["import type { Result } from \"ts-explicit-errors\"\nimport { isErr } from \"ts-explicit-errors\"\n\nimport { loadBaskFile } from \"#bask-file/bask-file.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { anyTaskName, toBaskParser, toTaskNameParser } from \"#cli/bask-parser.ts\"\nimport { printBaskHelp, printTaskHelp } from \"#cli/help.ts\"\nimport { formatTaskList, list } from \"#cli/list.ts\"\nimport { parseWithOptique } from \"#cli/optique.ts\"\nimport { runTask } from \"#cli/run-task.ts\"\nimport { splitArgs } from \"#cli/split-args.ts\"\nimport { checkAllTaskArgs, toTaskParser } from \"#cli/task-parser.ts\"\nimport { runWithArgs } from \"#task.ts\"\n\nconst ARGS_ERROR_EXIT_CODE = 2\n\n/** Loads bask.ts and checks its tasks' arg declarations. */\nconst loadTasks = async (baskPath: string): Promise<Result<TaskIndex>> => {\n const baskFile = await loadBaskFile(baskPath)\n if (isErr(baskFile)) return baskFile\n\n const checkResult = checkAllTaskArgs(baskFile.tasks)\n if (isErr(checkResult)) return checkResult\n\n return baskFile.tasks\n}\n\n/**\n * Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. Returns the exit code, which is\n * 2 when Optique has already reported invalid args. An error is one of bask's own problems.\n */\nexport const runBask = async (args: string[], baskPath: string): Promise<Result<number>> => {\n const { baskArgs, taskName, taskArgs } = splitArgs(args)\n const baskInput = taskName === undefined ? baskArgs : [...baskArgs, taskName]\n\n // Check bask's flags before loading bask.ts, so they work without one and before its top-level code runs.\n const baskParser = toBaskParser(anyTaskName)\n const baskFlags = parseWithOptique(baskParser, \"bask\", baskInput)\n if (!baskFlags) return ARGS_ERROR_EXIT_CODE\n\n if (baskFlags.help && taskName === undefined) {\n printBaskHelp(baskParser)\n const listedTasks = await loadTasks(baskPath)\n if (isErr(listedTasks)) return listedTasks\n process.stdout.write(`\\n${formatTaskList(listedTasks)}\\n`)\n return 0\n }\n\n const tasks = await loadTasks(baskPath)\n if (isErr(tasks)) return tasks\n\n // Check the task name now that bask.ts has loaded, so an unknown task gets Optique's error.\n const isUnknownTask =\n taskName !== undefined && !parseWithOptique(toBaskParser(toTaskNameParser(tasks)), \"bask\", baskInput)\n if (isUnknownTask) return ARGS_ERROR_EXIT_CODE\n\n const selectedTaskEntry = tasks.byName.get(taskName ?? \"default\")\n\n if (baskFlags.help && selectedTaskEntry) {\n printTaskHelp(selectedTaskEntry)\n return 0\n }\n\n // List the tasks when asked, or when no task is named and there's no default to run.\n if (baskFlags.list || !selectedTaskEntry) {\n const listResult = await runTask(tasks, \"list\", async () => list())\n if (isErr(listResult)) return listResult\n return 0\n }\n\n const { name, task } = selectedTaskEntry\n const parsedTaskArgs = parseWithOptique(toTaskParser(task.options), `bask ${name}`, taskArgs)\n if (!parsedTaskArgs) return ARGS_ERROR_EXIT_CODE\n\n const runResult = await runTask(tasks, name, async () => runWithArgs(task, parsedTaskArgs))\n if (isErr(runResult)) return runResult\n return 0\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAM,uBAAuB;;AAG7B,MAAM,YAAY,OAAO,aAAiD;CACxE,MAAM,WAAW,MAAM,aAAa,QAAQ;CAC5C,IAAI,MAAM,QAAQ,GAAG,OAAO;CAE5B,MAAM,cAAc,iBAAiB,SAAS,KAAK;CACnD,IAAI,MAAM,WAAW,GAAG,OAAO;CAE/B,OAAO,SAAS;AAClB;;;;;AAMA,MAAa,UAAU,OAAO,MAAgB,aAA8C;CAC1F,MAAM,EAAE,UAAU,UAAU,aAAa,UAAU,IAAI;CACvD,MAAM,YAAY,aAAa,KAAA,IAAY,WAAW,CAAC,GAAG,UAAU,QAAQ;CAG5E,MAAM,aAAa,aAAa,WAAW;CAC3C,MAAM,YAAY,iBAAiB,YAAY,QAAQ,SAAS;CAChE,IAAI,CAAC,WAAW,OAAO;CAEvB,IAAI,UAAU,QAAQ,aAAa,KAAA,GAAW;EAC5C,cAAc,UAAU;EACxB,MAAM,cAAc,MAAM,UAAU,QAAQ;EAC5C,IAAI,MAAM,WAAW,GAAG,OAAO;EAC/B,QAAQ,OAAO,MAAM,KAAK,eAAe,WAAW,EAAE,GAAG;EACzD,OAAO;CACT;CAEA,MAAM,QAAQ,MAAM,UAAU,QAAQ;CACtC,IAAI,MAAM,KAAK,GAAG,OAAO;CAKzB,IADE,aAAa,KAAA,KAAa,CAAC,iBAAiB,aAAa,iBAAiB,KAAK,CAAC,GAAG,QAAQ,SAAS,GACnF,OAAO;CAE1B,MAAM,oBAAoB,MAAM,OAAO,IAAI,YAAY,SAAS;CAEhE,IAAI,UAAU,QAAQ,mBAAmB;EACvC,cAAc,iBAAiB;EAC/B,OAAO;CACT;CAGA,IAAI,UAAU,QAAQ,CAAC,mBAAmB;EACxC,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,YAAY,KAAK,CAAC;EAClE,IAAI,MAAM,UAAU,GAAG,OAAO;EAC9B,OAAO;CACT;CAEA,MAAM,EAAE,MAAM,SAAS;CACvB,MAAM,iBAAiB,iBAAiB,aAAa,KAAK,OAAO,GAAG,QAAQ,QAAQ,QAAQ;CAC5F,IAAI,CAAC,gBAAgB,OAAO;CAE5B,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,YAAY,MAAM,cAAc,CAAC;CAC1F,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"run-bask.js","names":[],"sources":["../../src/cli/run-bask.ts"],"sourcesContent":["import type { Result } from \"ts-explicit-errors\"\nimport { isErr } from \"ts-explicit-errors\"\n\nimport { loadBaskFile } from \"#bask-file/bask-file.ts\"\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { anyTaskName, toBaskParser, toTaskNameParser } from \"#cli/bask-parser.ts\"\nimport { printBaskHelp, printTaskHelp } from \"#cli/help.ts\"\nimport { formatTaskList, list } from \"#cli/list.ts\"\nimport { parseWithOptique } from \"#cli/optique.ts\"\nimport { runTask } from \"#cli/run-task.ts\"\nimport { splitArgs } from \"#cli/split-args.ts\"\nimport { checkAllTaskArgs, toTaskParser } from \"#cli/task-parser.ts\"\nimport { runWithArgs } from \"#task/command-line-args.ts\"\n\nconst ARGS_ERROR_EXIT_CODE = 2\n\n/** Loads bask.ts and checks its tasks' arg declarations. */\nconst loadTasks = async (baskPath: string): Promise<Result<TaskIndex>> => {\n const baskFile = await loadBaskFile(baskPath)\n if (isErr(baskFile)) return baskFile\n\n const checkResult = checkAllTaskArgs(baskFile.tasks)\n if (isErr(checkResult)) return checkResult\n\n return baskFile.tasks\n}\n\n/**\n * Runs the task that `args` names from the bask file at `baskPath`, or lists the tasks. Returns the exit code, which is\n * 2 when Optique has already reported invalid args. An error is one of bask's own problems.\n */\nexport const runBask = async (args: string[], baskPath: string): Promise<Result<number>> => {\n const { baskArgs, taskName, taskArgs } = splitArgs(args)\n const baskInput = taskName === undefined ? baskArgs : [...baskArgs, taskName]\n\n // Check bask's flags before loading bask.ts, so they work without one and before its top-level code runs.\n const baskParser = toBaskParser(anyTaskName)\n const baskFlags = parseWithOptique(baskParser, \"bask\", baskInput)\n if (!baskFlags) return ARGS_ERROR_EXIT_CODE\n\n if (baskFlags.help && taskName === undefined) {\n printBaskHelp(baskParser)\n const listedTasks = await loadTasks(baskPath)\n if (isErr(listedTasks)) return listedTasks\n process.stdout.write(`\\n${formatTaskList(listedTasks)}\\n`)\n return 0\n }\n\n const tasks = await loadTasks(baskPath)\n if (isErr(tasks)) return tasks\n\n // Check the task name now that bask.ts has loaded, so an unknown task gets Optique's error.\n const isUnknownTask =\n taskName !== undefined && !parseWithOptique(toBaskParser(toTaskNameParser(tasks)), \"bask\", baskInput)\n if (isUnknownTask) return ARGS_ERROR_EXIT_CODE\n\n const selectedTaskEntry = tasks.byName.get(taskName ?? \"default\")\n\n if (baskFlags.help && selectedTaskEntry) {\n printTaskHelp(selectedTaskEntry)\n return 0\n }\n\n // List the tasks when asked, or when no task is named and there's no default to run.\n if (baskFlags.list || !selectedTaskEntry) {\n const listResult = await runTask(tasks, \"list\", async () => list())\n if (isErr(listResult)) return listResult\n return 0\n }\n\n const { name, task } = selectedTaskEntry\n const parsedTaskArgs = parseWithOptique(toTaskParser(task.options), `bask ${name}`, taskArgs)\n if (!parsedTaskArgs) return ARGS_ERROR_EXIT_CODE\n\n const runResult = await runTask(tasks, name, async () => runWithArgs(task, parsedTaskArgs))\n if (isErr(runResult)) return runResult\n return 0\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAM,uBAAuB;;AAG7B,MAAM,YAAY,OAAO,aAAiD;CACxE,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,gBAAgB,OAAO;CAE5B,MAAM,YAAY,MAAM,QAAQ,OAAO,MAAM,YAAY,YAAY,MAAM,cAAc,CAAC;CAC1F,IAAI,MAAM,SAAS,GAAG,OAAO;CAC7B,OAAO;AACT"}
|
package/dist/cli/run-task.js
CHANGED
package/dist/cli/run-task.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-task.js","names":[],"sources":["../../src/cli/run-task.ts"],"sourcesContent":["import bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err } from \"ts-explicit-errors\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { hasHiddenOutput } from \"#shell/command.ts\"\nimport { getFailedTask } from \"#task.ts\"\n\n/** Runs a task and returns a failed command as an error that names the innermost task that failed. */\nexport const runTask = async (tasks: TaskIndex, taskName: string, run: () => Promise<void>): Promise<Result> => {\n const error = await attempt(run)\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"],"mappings":";;;;;;AASA,MAAa,UAAU,OAAO,OAAkB,UAAkB,QAA8C;CAC9G,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,IAAI,CAAC,OAAO;CAEZ,IAAI,EAAE,iBAAiB,IAAI,EAAE,aAAa,MAAM;CAGhD,IAAI,gBAAgB,KAAK,GAAG;EAC1B,QAAQ,OAAO,MAAM,MAAM,MAAM;EACjC,QAAQ,OAAO,MAAM,MAAM,MAAM;CACnC;CAEA,MAAM,aAAa,cAAc,KAAK;CAGtC,MAAM,cAFc,cAAc,MAAM,OAAO,IAAI,UAAU,EAAA,EAE7B,QAAQ;CACxC,OAAO,IAAI,SAAS,WAAW,0BAA0B,MAAM,YAAY,KAAA,GAAW,EAAE,UAAU,MAAM,SAAS,CAAC;AACpH"}
|
|
1
|
+
{"version":3,"file":"run-task.js","names":[],"sources":["../../src/cli/run-task.ts"],"sourcesContent":["import bun from \"bun\"\nimport type { Result } from \"ts-explicit-errors\"\nimport { attempt, err } from \"ts-explicit-errors\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport { hasHiddenOutput } from \"#shell/command.ts\"\nimport { getFailedTask } from \"#task/failed-task.ts\"\n\n/** Runs a task and returns a failed command as an error that names the innermost task that failed. */\nexport const runTask = async (tasks: TaskIndex, taskName: string, run: () => Promise<void>): Promise<Result> => {\n const error = await attempt(run)\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"],"mappings":";;;;;;AASA,MAAa,UAAU,OAAO,OAAkB,UAAkB,QAA8C;CAC9G,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,IAAI,CAAC,OAAO;CAEZ,IAAI,EAAE,iBAAiB,IAAI,EAAE,aAAa,MAAM;CAGhD,IAAI,gBAAgB,KAAK,GAAG;EAC1B,QAAQ,OAAO,MAAM,MAAM,MAAM;EACjC,QAAQ,OAAO,MAAM,MAAM,MAAM;CACnC;CAEA,MAAM,aAAa,cAAc,KAAK;CAGtC,MAAM,cAFc,cAAc,MAAM,OAAO,IAAI,UAAU,EAAA,EAE7B,QAAQ;CACxC,OAAO,IAAI,SAAS,WAAW,0BAA0B,MAAM,YAAY,KAAA,GAAW,EAAE,UAAU,MAAM,SAAS,CAAC;AACpH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { BaskConfigInput, defineConfig } from "./config.js";
|
|
2
2
|
import { list } from "./cli/list.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
3
|
+
import { isTask, task } from "./task.js";
|
|
4
|
+
import { Task } from "./task/types.js";
|
|
5
|
+
import { NoArgs } from "./task/args.js";
|
|
6
|
+
export { type BaskConfigInput, type NoArgs, type Task, defineConfig, isTask, list, task };
|
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 \"#cli/print-error.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 \"#cli/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"}
|
|
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 \"#cli/print-error.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 \"#cli/list.ts\"\nexport { isTask, task } from \"#task.ts\"\nexport type { Task } from \"#task/types.ts\"\nexport type { NoArgs } from \"#task/args.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,12 @@
|
|
|
1
|
+
// src/task/command-line-args.ts
|
|
2
|
+
const commandLineArgs = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
/** Runs the task the command line named, with the args parsed from it. */
|
|
4
|
+
const runWithArgs = async (taskToRun, taskArgs) => {
|
|
5
|
+
commandLineArgs.set(taskToRun, taskArgs);
|
|
6
|
+
await taskToRun();
|
|
7
|
+
};
|
|
8
|
+
/** Returns the args the command line gave `calledTask`, or `undefined` when it isn't the task the command line named. */
|
|
9
|
+
const getCommandLineArgs = (calledTask) => commandLineArgs.get(calledTask);
|
|
10
|
+
export { getCommandLineArgs, runWithArgs };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=command-line-args.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"command-line-args.js","names":[],"sources":["../../src/task/command-line-args.ts"],"sourcesContent":["import type { ParsedTaskArgs } from \"#task/args.ts\"\nimport type { Task } from \"#task/types.ts\"\n\n// Hold the command line's args for the task it named, because tasks are called without args.\nconst commandLineArgs = new WeakMap<Task, ParsedTaskArgs>()\n\n/** Runs the task the command line named, with the args parsed from it. */\nexport const runWithArgs = async (taskToRun: Task, taskArgs: ParsedTaskArgs) => {\n commandLineArgs.set(taskToRun, taskArgs)\n await taskToRun()\n}\n\n/** Returns the args the command line gave `calledTask`, or `undefined` when it isn't the task the command line named. */\nexport const getCommandLineArgs = (calledTask: Task) => commandLineArgs.get(calledTask)\n"],"mappings":";AAIA,MAAM,kCAAkB,IAAI,QAA8B;;AAG1D,MAAa,cAAc,OAAO,WAAiB,aAA6B;CAC9E,gBAAgB,IAAI,WAAW,QAAQ;CACvC,MAAM,UAAU;AAClB;;AAGA,MAAa,sBAAsB,eAAqB,gBAAgB,IAAI,UAAU"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
// src/task/cycles.ts
|
|
3
|
+
const runningTasks = new AsyncLocalStorage();
|
|
4
|
+
const waitingOn = /* @__PURE__ */ new Map();
|
|
5
|
+
const UNNAMED_TASK = "(unnamed)";
|
|
6
|
+
/** Returns the chain of tasks whose run the current code is inside. */
|
|
7
|
+
const getRunningChain = () => runningTasks.getStore() ?? [];
|
|
8
|
+
/** Runs `run` inside `chain` with `runningTask` added, so the calls it makes can see the chain. */
|
|
9
|
+
const runInChain = async (chain, runningTask, run) => runningTasks.run([...chain, runningTask], run);
|
|
10
|
+
/** Follows what `from` is waiting on, and returns the path to the first task it reaches in `chain`. */
|
|
11
|
+
const findWaitPath = (from, chain, seen = /* @__PURE__ */ new Set()) => {
|
|
12
|
+
if (chain.includes(from)) return [from];
|
|
13
|
+
if (seen.has(from)) return;
|
|
14
|
+
seen.add(from);
|
|
15
|
+
const waitPath = Array.from(waitingOn.get(from) ?? [], (next) => findWaitPath(next, chain, seen)).find((nextWaitPath) => nextWaitPath !== void 0);
|
|
16
|
+
return waitPath && [from, ...waitPath];
|
|
17
|
+
};
|
|
18
|
+
/** Returns the cycle that calling `calledTask` from inside `chain` would close, or `undefined` if there's none. */
|
|
19
|
+
const findCycle = (calledTask, chain) => {
|
|
20
|
+
const waitPath = findWaitPath(calledTask, chain);
|
|
21
|
+
if (!waitPath) return;
|
|
22
|
+
const cycleStart = chain.indexOf(waitPath.at(-1) ?? calledTask);
|
|
23
|
+
return [...chain.slice(cycleStart), ...waitPath];
|
|
24
|
+
};
|
|
25
|
+
/** Formats a cycle as an error message, naming each task the way the CLI does. */
|
|
26
|
+
const formatCycleMessage = (cycle, tasks) => {
|
|
27
|
+
const names = cycle.map((cycleTask) => tasks.byTask.get(cycleTask)?.name ?? UNNAMED_TASK);
|
|
28
|
+
return `Task '${names[0] ?? UNNAMED_TASK}' calls itself: ${names.join(" -> ")}`;
|
|
29
|
+
};
|
|
30
|
+
/** Records that `caller` is waiting on `calledTask` until `calledRun` settles. */
|
|
31
|
+
const waitOn = async (caller, calledTask, calledRun) => {
|
|
32
|
+
const calledTasks = waitingOn.get(caller) ?? /* @__PURE__ */ new Set();
|
|
33
|
+
waitingOn.set(caller, calledTasks.add(calledTask));
|
|
34
|
+
try {
|
|
35
|
+
await calledRun;
|
|
36
|
+
} finally {
|
|
37
|
+
calledTasks.delete(calledTask);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
export { findCycle, formatCycleMessage, getRunningChain, runInChain, waitOn };
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=cycles.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cycles.js","names":[],"sources":["../../src/task/cycles.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\"\n\nimport type { TaskIndex } from \"#bask-file/task-index.ts\"\nimport type { Task } from \"#task/types.ts\"\n\n// Track the chain of tasks whose run the current code is inside, so a task that calls itself throws instead of hanging.\nconst runningTasks = new AsyncLocalStorage<Task[]>()\n\n// Track which tasks each running task is waiting on, so a cycle between tasks that started separately still throws.\nconst waitingOn = new Map<Task, Set<Task>>()\n\nconst UNNAMED_TASK = \"(unnamed)\"\n\n/** Returns the chain of tasks whose run the current code is inside. */\nexport const getRunningChain = () => runningTasks.getStore() ?? []\n\n/** Runs `run` inside `chain` with `runningTask` added, so the calls it makes can see the chain. */\nexport const runInChain = async (chain: Task[], runningTask: Task, run: () => Promise<void>) =>\n runningTasks.run([...chain, runningTask], run)\n\n/** Follows what `from` is waiting on, and returns the path to the first task it reaches in `chain`. */\nconst findWaitPath = (from: Task, chain: Task[], seen = new Set<Task>()): Task[] | undefined => {\n if (chain.includes(from)) return [from]\n if (seen.has(from)) return\n seen.add(from)\n const nextWaitPaths = Array.from(waitingOn.get(from) ?? [], (next) => findWaitPath(next, chain, seen))\n const waitPath = nextWaitPaths.find((nextWaitPath) => nextWaitPath !== undefined)\n return waitPath && [from, ...waitPath]\n}\n\n/** Returns the cycle that calling `calledTask` from inside `chain` would close, or `undefined` if there's none. */\nexport const findCycle = (calledTask: Task, chain: Task[]) => {\n const waitPath = findWaitPath(calledTask, chain)\n if (!waitPath) return\n const cycleStart = chain.indexOf(waitPath.at(-1) ?? calledTask)\n return [...chain.slice(cycleStart), ...waitPath]\n}\n\n/** Formats a cycle as an error message, naming each task the way the CLI does. */\nexport const formatCycleMessage = (cycle: Task[], tasks: TaskIndex) => {\n const names = cycle.map((cycleTask) => tasks.byTask.get(cycleTask)?.name ?? UNNAMED_TASK)\n return `Task '${names[0] ?? UNNAMED_TASK}' calls itself: ${names.join(\" -> \")}`\n}\n\n/** Records that `caller` is waiting on `calledTask` until `calledRun` settles. */\nexport const waitOn = async (caller: Task, calledTask: Task, calledRun: Promise<void>) => {\n const calledTasks = waitingOn.get(caller) ?? new Set()\n waitingOn.set(caller, calledTasks.add(calledTask))\n try {\n await calledRun\n } finally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CACR,UAAU;EACR,YAAY,OAAO,UAAU;CAC/B;AACF"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// src/task/failed-task.ts
|
|
2
|
+
const failedTasks = /* @__PURE__ */ new WeakMap();
|
|
3
|
+
/** Records `failedTask` as the task that `error` failed, unless a task inside it already did. */
|
|
4
|
+
const recordFailedTask = (error, failedTask) => {
|
|
5
|
+
if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, failedTask);
|
|
6
|
+
};
|
|
7
|
+
/** Returns the innermost task that the error failed, so the CLI can name it. */
|
|
8
|
+
const getFailedTask = (error) => failedTasks.get(error);
|
|
9
|
+
export { getFailedTask, recordFailedTask };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=failed-task.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"failed-task.js","names":[],"sources":["../../src/task/failed-task.ts"],"sourcesContent":["import type { Task } from \"#task/types.ts\"\n\nconst failedTasks = new WeakMap<Error, Task>()\n\n/** Records `failedTask` as the task that `error` failed, unless a task inside it already did. */\nexport const recordFailedTask = (error: unknown, failedTask: Task) => {\n // Record this task only if no task has yet, because the innermost task's catch runs first.\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, failedTask)\n}\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"],"mappings":";AAEA,MAAM,8BAAc,IAAI,QAAqB;;AAG7C,MAAa,oBAAoB,OAAgB,eAAqB;CAEpE,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,UAAU;AAC1F;;AAGA,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Shell } from "../shell/shell.js";
|
|
2
|
+
import { ArgValues, NoArgs, TaskArgs } from "./args.js";
|
|
3
|
+
export interface Task<A extends TaskArgs = NoArgs> {
|
|
4
|
+
(): Promise<void>;
|
|
5
|
+
options: TaskOptions<A>;
|
|
6
|
+
before: (...fns: Hook<A>[]) => void;
|
|
7
|
+
after: (...fns: Hook<A>[]) => void;
|
|
8
|
+
/** Replaces the task's function in place. The new function can run the one it replaced with `original()`. */
|
|
9
|
+
wrap: {
|
|
10
|
+
(fn: WrapFn<A>): Task<A>;
|
|
11
|
+
<const B extends TaskArgs = NoArgs>(options: WrapOptions<B>, fn: WrapFn<A & B>): Task<A & B>;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface TaskOptions<A extends TaskArgs = NoArgs> {
|
|
15
|
+
desc?: string;
|
|
16
|
+
/** Keeps the task runnable but leaves it out of the task list. */
|
|
17
|
+
hidden?: boolean;
|
|
18
|
+
/** Additional names to run the task. */
|
|
19
|
+
alias?: string | string[];
|
|
20
|
+
/** Args the task takes from the command line, by name. */
|
|
21
|
+
args?: A;
|
|
22
|
+
/** Lets the task take positionals, including everything after `--`. */
|
|
23
|
+
positionals?: boolean;
|
|
24
|
+
}
|
|
25
|
+
export interface TaskContext<A extends TaskArgs = NoArgs> {
|
|
26
|
+
sh: Shell;
|
|
27
|
+
args: ArgValues<A>;
|
|
28
|
+
positionals: string[];
|
|
29
|
+
}
|
|
30
|
+
type AsyncOrSyncReturn = Promise<void> | void;
|
|
31
|
+
export type TaskFn<A extends TaskArgs = NoArgs> = (ctx: TaskContext<A>) => AsyncOrSyncReturn;
|
|
32
|
+
/** A task used as a hook. It leaves out the call signature so TypeScript still infers an inline hook's parameter. */
|
|
33
|
+
type HookTask = Pick<Task, "options">;
|
|
34
|
+
/** A hook added with `before` or `after`: a function that gets the task's context, or another task. */
|
|
35
|
+
export type Hook<A extends TaskArgs = NoArgs> = TaskFn<A> | HookTask;
|
|
36
|
+
interface WrapContext<A extends TaskArgs = NoArgs> extends TaskContext<A> {
|
|
37
|
+
/** Runs the function this wrap replaced. */
|
|
38
|
+
original: () => Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
export type WrapFn<A extends TaskArgs = NoArgs> = (ctx: WrapContext<A>) => AsyncOrSyncReturn;
|
|
41
|
+
export interface WrapOptions<B extends TaskArgs> {
|
|
42
|
+
/** Args to add to the task's args. */
|
|
43
|
+
args?: B;
|
|
44
|
+
}
|
|
45
|
+
export {};
|
|
46
|
+
//# sourceMappingURL=types.d.ts.map
|
package/dist/task.d.ts
CHANGED
|
@@ -1,36 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
type AsyncOrSyncReturn = Promise<void> | void;
|
|
4
|
-
interface TaskOptions<A extends TaskArgs = NoArgs> {
|
|
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
|
-
/** Args the task takes from the command line, by name. */
|
|
11
|
-
args?: A;
|
|
12
|
-
/** Lets the task take positionals, including everything after `--`. */
|
|
13
|
-
positionals?: boolean;
|
|
14
|
-
}
|
|
15
|
-
interface TaskContext<A extends TaskArgs = NoArgs> {
|
|
16
|
-
sh: Shell;
|
|
17
|
-
args: ArgValues<A>;
|
|
18
|
-
positionals: string[];
|
|
19
|
-
}
|
|
20
|
-
type TaskFn<A extends TaskArgs = NoArgs> = (ctx: TaskContext<A>) => AsyncOrSyncReturn;
|
|
21
|
-
/** A task used as a hook. It leaves out the call signature so TypeScript still infers an inline hook's parameter. */
|
|
22
|
-
type HookTask = Pick<Task, "options">;
|
|
23
|
-
/** A hook added with `before` or `after`: a function that gets the task's context, or another task. */
|
|
24
|
-
type Hook<A extends TaskArgs = NoArgs> = TaskFn<A> | HookTask;
|
|
25
|
-
export interface Task<A extends TaskArgs = NoArgs> {
|
|
26
|
-
(): Promise<void>;
|
|
27
|
-
options: TaskOptions<A>;
|
|
28
|
-
before: (...fns: Hook<A>[]) => void;
|
|
29
|
-
after: (...fns: Hook<A>[]) => void;
|
|
30
|
-
}
|
|
1
|
+
import { NoArgs, TaskArgs } from "./task/args.js";
|
|
2
|
+
import { Task, TaskFn, TaskOptions } from "./task/types.js";
|
|
31
3
|
export declare const isTask: (value: unknown) => value is Task;
|
|
32
4
|
/** Registers a task that runs at most once per bask invocation, however many times it's called. */
|
|
33
5
|
export declare function task(fn: TaskFn): Task;
|
|
34
6
|
export declare function task<const A extends TaskArgs = NoArgs>(options: TaskOptions<A>, fn: TaskFn<A>): Task<A>;
|
|
35
|
-
export {};
|
|
36
7
|
//# sourceMappingURL=task.d.ts.map
|
package/dist/task.js
CHANGED
|
@@ -1,74 +1,115 @@
|
|
|
1
1
|
import { getLoadedBaskFile } from "./loaded-bask-file.js";
|
|
2
2
|
import { createShell } from "./shell/shell.js";
|
|
3
3
|
import { toEmptyArgs } from "./task/args.js";
|
|
4
|
+
import { getCommandLineArgs } from "./task/command-line-args.js";
|
|
5
|
+
import { findCycle, formatCycleMessage, getRunningChain, runInChain, waitOn } from "./task/cycles.js";
|
|
6
|
+
import { recordFailedTask } from "./task/failed-task.js";
|
|
4
7
|
// src/task.ts
|
|
8
|
+
const HOOK_AFTER_START = "Can't add a hook to a task that has already started";
|
|
9
|
+
const WRAP_AFTER_START = "Can't wrap a task that has already started";
|
|
5
10
|
const createdByTask = /* @__PURE__ */ new WeakSet();
|
|
6
11
|
const isTask = (value) => typeof value === "function" && createdByTask.has(value);
|
|
7
|
-
const failedTasks = /* @__PURE__ */ new WeakMap();
|
|
8
|
-
/** Returns the innermost task that the error failed, so the CLI can name it. */
|
|
9
|
-
const getFailedTask = (error) => failedTasks.get(error);
|
|
10
|
-
const commandLineArgs = /* @__PURE__ */ new WeakMap();
|
|
11
|
-
/** Runs the task the command line named, with the args parsed from it. */
|
|
12
|
-
const runWithArgs = async (taskToRun, taskArgs) => {
|
|
13
|
-
commandLineArgs.set(taskToRun, taskArgs);
|
|
14
|
-
await taskToRun();
|
|
15
|
-
};
|
|
16
12
|
function task(optionsOrFn, maybeFn) {
|
|
17
|
-
const [
|
|
13
|
+
const [passedOptions, fn] = typeof optionsOrFn === "function" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn];
|
|
14
|
+
const options = { ...passedOptions };
|
|
18
15
|
if (!fn) throw new Error("task() needs a callback");
|
|
19
|
-
|
|
20
|
-
|
|
16
|
+
let beforeFns = [];
|
|
17
|
+
let afterFns = [];
|
|
18
|
+
const taskOptions = options;
|
|
21
19
|
let runPromise;
|
|
22
20
|
let hasStarted = false;
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
let hasFinished = false;
|
|
22
|
+
const assertNotStarted = (message) => {
|
|
23
|
+
if (hasStarted) throw new Error(message);
|
|
25
24
|
};
|
|
26
25
|
const before = (...fns) => {
|
|
27
|
-
assertNotStarted();
|
|
26
|
+
assertNotStarted(HOOK_AFTER_START);
|
|
28
27
|
beforeFns.push(...fns);
|
|
29
28
|
};
|
|
30
29
|
const after = (...fns) => {
|
|
31
|
-
assertNotStarted();
|
|
30
|
+
assertNotStarted(HOOK_AFTER_START);
|
|
32
31
|
afterFns.push(...fns);
|
|
33
32
|
};
|
|
34
|
-
const
|
|
35
|
-
|
|
33
|
+
const toContext = (shellConfig, taskArgs) => {
|
|
34
|
+
const args = taskArgs.args;
|
|
35
|
+
return {
|
|
36
|
+
sh: createShell(shellConfig),
|
|
37
|
+
args,
|
|
38
|
+
positionals: [...taskArgs.positionals]
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
let currentFn = async (shellConfig, taskArgs) => {
|
|
42
|
+
await fn(toContext(shellConfig, taskArgs));
|
|
43
|
+
};
|
|
44
|
+
const toLayerFn = (layerFn, layerBeforeFns, layerAfterFns) => async (shellConfig, taskArgs) => {
|
|
36
45
|
const runHook = async (hook) => {
|
|
37
46
|
if (isTask(hook)) return hook();
|
|
38
|
-
if (typeof hook
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
47
|
+
if (typeof hook === "function") return hook(toContext(shellConfig, taskArgs));
|
|
48
|
+
};
|
|
49
|
+
for (const beforeFn of layerBeforeFns) await runHook(beforeFn);
|
|
50
|
+
await layerFn(shellConfig, taskArgs);
|
|
51
|
+
for (const afterFn of layerAfterFns) await runHook(afterFn);
|
|
52
|
+
};
|
|
53
|
+
const wrap = (wrapOptionsOrFn, maybeWrapFn) => {
|
|
54
|
+
assertNotStarted(WRAP_AFTER_START);
|
|
55
|
+
const [wrapOptions, wrapFn] = typeof wrapOptionsOrFn === "function" ? [{}, wrapOptionsOrFn] : [wrapOptionsOrFn, maybeWrapFn];
|
|
56
|
+
if (!wrapFn) throw new Error("wrap() needs a callback");
|
|
57
|
+
const wrapArgs = wrapOptions.args ?? {};
|
|
58
|
+
const duplicateArg = Object.keys(wrapArgs).find((argName) => Object.hasOwn(taskOptions.args ?? {}, argName));
|
|
59
|
+
if (duplicateArg !== void 0) throw new Error(`Can't add arg '${duplicateArg}' with wrap() because the task already has it`);
|
|
60
|
+
taskOptions.args = {
|
|
61
|
+
...taskOptions.args,
|
|
62
|
+
...wrapArgs
|
|
63
|
+
};
|
|
64
|
+
const replacedFn = toLayerFn(currentFn, beforeFns, afterFns);
|
|
65
|
+
beforeFns = [];
|
|
66
|
+
afterFns = [];
|
|
67
|
+
currentFn = async (shellConfig, taskArgs) => {
|
|
68
|
+
const original = async () => replacedFn(shellConfig, taskArgs);
|
|
69
|
+
await wrapFn({
|
|
70
|
+
...toContext(shellConfig, taskArgs),
|
|
71
|
+
original
|
|
44
72
|
});
|
|
45
73
|
};
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
74
|
+
return newTask;
|
|
75
|
+
};
|
|
76
|
+
const runAll = async (shellConfig, taskArgs) => {
|
|
77
|
+
hasStarted = true;
|
|
78
|
+
try {
|
|
79
|
+
await toLayerFn(currentFn, beforeFns, afterFns)(shellConfig, taskArgs);
|
|
80
|
+
} finally {
|
|
81
|
+
hasFinished = true;
|
|
82
|
+
}
|
|
49
83
|
};
|
|
50
|
-
const runOnce = async (shellConfig, taskArgs) => {
|
|
51
|
-
runPromise ??= runAll(shellConfig, taskArgs);
|
|
84
|
+
const runOnce = async (shellConfig, taskArgs, chain) => {
|
|
85
|
+
runPromise ??= runInChain(chain, newTask, async () => runAll(shellConfig, taskArgs));
|
|
52
86
|
try {
|
|
53
87
|
await runPromise;
|
|
54
88
|
} catch (error) {
|
|
55
|
-
|
|
89
|
+
recordFailedTask(error, newTask);
|
|
56
90
|
throw error;
|
|
57
91
|
}
|
|
58
92
|
};
|
|
59
93
|
const run = () => {
|
|
60
94
|
const baskFile = getLoadedBaskFile();
|
|
61
|
-
const
|
|
62
|
-
|
|
95
|
+
const chain = getRunningChain();
|
|
96
|
+
const cycle = hasFinished ? void 0 : findCycle(newTask, chain);
|
|
97
|
+
if (cycle) throw new Error(formatCycleMessage(cycle, baskFile.tasks));
|
|
98
|
+
const taskArgs = getCommandLineArgs(newTask) ?? toEmptyArgs(options);
|
|
99
|
+
const calledRun = runOnce(baskFile.config.shell, taskArgs, chain);
|
|
100
|
+
const caller = chain.at(-1);
|
|
101
|
+
if (!caller) return calledRun;
|
|
102
|
+
return waitOn(caller, newTask, calledRun);
|
|
63
103
|
};
|
|
64
104
|
const newTask = Object.assign(run, {
|
|
65
105
|
options,
|
|
66
106
|
before,
|
|
67
|
-
after
|
|
107
|
+
after,
|
|
108
|
+
wrap
|
|
68
109
|
});
|
|
69
110
|
createdByTask.add(newTask);
|
|
70
111
|
return newTask;
|
|
71
112
|
}
|
|
72
|
-
export {
|
|
113
|
+
export { isTask, task };
|
|
73
114
|
|
|
74
115
|
//# sourceMappingURL=task.js.map
|
package/dist/task.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import type { ShellConfig } from \"#config.ts\"\nimport { getLoadedBaskFile } from \"#loaded-bask-file.ts\"\nimport { createShell } from \"#shell/shell.ts\"\nimport type { Shell } from \"#shell/shell.ts\"\nimport { toEmptyArgs } from \"#task/args.ts\"\nimport type { ArgValues, NoArgs, ParsedTaskArgs, TaskArgs } from \"#task/args.ts\"\n\ntype AsyncOrSyncReturn = Promise<void> | void\n\ninterface TaskOptions<A extends TaskArgs = NoArgs> {\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 /** Args the task takes from the command line, by name. */\n args?: A\n /** Lets the task take positionals, including everything after `--`. */\n positionals?: boolean\n}\n\ninterface TaskContext<A extends TaskArgs = NoArgs> {\n sh: Shell\n args: ArgValues<A>\n positionals: string[]\n}\n\ntype TaskFn<A extends TaskArgs = NoArgs> = (ctx: TaskContext<A>) => AsyncOrSyncReturn\n\n/** A task used as a hook. It leaves out the call signature so TypeScript still infers an inline hook's parameter. */\ntype HookTask = Pick<Task, \"options\">\n\n/** A hook added with `before` or `after`: a function that gets the task's context, or another task. */\ntype Hook<A extends TaskArgs = NoArgs> = TaskFn<A> | HookTask\n\nexport interface Task<A extends TaskArgs = NoArgs> {\n (): Promise<void>\n options: TaskOptions<A>\n before: (...fns: Hook<A>[]) => void\n after: (...fns: Hook<A>[]) => void\n}\n\nconst createdByTask = new WeakSet<object>()\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && createdByTask.has(value)\n\nconst failedTasks = new WeakMap<Error, Task>()\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// Hold the command line's args for the task it named, because tasks are called without args.\nconst commandLineArgs = new WeakMap<Task, ParsedTaskArgs>()\n\n/** Runs the task the command line named, with the args parsed from it. */\nexport const runWithArgs = async (taskToRun: Task, taskArgs: ParsedTaskArgs) => {\n commandLineArgs.set(taskToRun, taskArgs)\n await taskToRun()\n}\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<const A extends TaskArgs = NoArgs>(options: TaskOptions<A>, fn: TaskFn<A>): Task<A>\nexport function task<A extends TaskArgs>(optionsOrFn: TaskOptions<A> | TaskFn<A>, maybeFn?: TaskFn<A>): Task<A> {\n const [options, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n if (!fn) throw new Error(\"task() needs a callback\")\n\n const beforeFns: Hook<A>[] = []\n const afterFns: Hook<A>[] = []\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n // Track the start separately because `runAll` calls the task before `runPromise` is assigned.\n let hasStarted = false\n\n const assertNotStarted = () => {\n if (hasStarted) throw new Error(\"Can't add a hook to a task that has already started\")\n }\n\n const before = (...fns: Hook<A>[]) => {\n assertNotStarted()\n beforeFns.push(...fns)\n }\n\n const after = (...fns: Hook<A>[]) => {\n assertNotStarted()\n afterFns.push(...fns)\n }\n\n const runAll = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => {\n hasStarted = true\n // Give each hook and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n // Call a task used as a hook bare, because this task's args aren't its args.\n const runHook = async (hook: Hook<A>) => {\n if (isTask(hook)) return hook()\n if (typeof hook !== \"function\") return\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - `taskArgs` was parsed from this task's own `args` declaration\n const args = taskArgs.args as ArgValues<A>\n return hook({ sh: createShell(shellConfig), args, positionals: [...taskArgs.positionals] })\n }\n\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of beforeFns) await runHook(beforeFn)\n await runHook(fn)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of afterFns) await runHook(afterFn)\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const runOnce = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => {\n runPromise ??= runAll(shellConfig, taskArgs)\n try {\n await runPromise\n } catch (error) {\n // Record this task only if no task has yet, because the innermost task's catch runs first.\n // oxlint-disable-next-line no-use-before-define - `runOnce` only runs after `newTask` is assigned\n if (error instanceof Error && !failedTasks.has(error)) failedTasks.set(error, newTask)\n throw error\n }\n }\n\n // oxlint-disable-next-line typescript/promise-function-async - an async function would turn the throw into a rejection\n const run = () => {\n const baskFile = getLoadedBaskFile()\n // oxlint-disable-next-line no-use-before-define - `run` only runs after `newTask` is assigned\n const taskArgs = commandLineArgs.get(newTask) ?? toEmptyArgs(options)\n return runOnce(baskFile.config.shell, taskArgs)\n }\n\n const newTask: Task<A> = Object.assign(run, { options, before, after })\n createdByTask.add(newTask)\n return newTask\n}\n"],"mappings":";;;;AA0CA,MAAM,gCAAgB,IAAI,QAAgB;AAC1C,MAAa,UAAU,UAAkC,OAAO,UAAU,cAAc,cAAc,IAAI,KAAK;AAE/G,MAAM,8BAAc,IAAI,QAAqB;;AAE7C,MAAa,iBAAiB,UAAiB,YAAY,IAAI,KAAK;AAGpE,MAAM,kCAAkB,IAAI,QAA8B;;AAG1D,MAAa,cAAc,OAAO,WAAiB,aAA6B;CAC9E,gBAAgB,IAAI,WAAW,QAAQ;CACvC,MAAM,UAAU;AAClB;AAKA,SAAgB,KAAyB,aAAyC,SAA8B;CAC9G,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,YAAuB,CAAC;CAC9B,MAAM,WAAsB,CAAC;CAG7B,IAAI;CAEJ,IAAI,aAAa;CAEjB,MAAM,yBAAyB;EAC7B,IAAI,YAAY,MAAM,IAAI,MAAM,qDAAqD;CACvF;CAEA,MAAM,UAAU,GAAG,QAAmB;EACpC,iBAAiB;EACjB,UAAU,KAAK,GAAG,GAAG;CACvB;CAEA,MAAM,SAAS,GAAG,QAAmB;EACnC,iBAAiB;EACjB,SAAS,KAAK,GAAG,GAAG;CACtB;CAEA,MAAM,SAAS,OAAO,aAA0B,aAA6B;EAC3E,aAAa;EAGb,MAAM,UAAU,OAAO,SAAkB;GACvC,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK;GAC9B,IAAI,OAAO,SAAS,YAAY;GAEhC,MAAM,OAAO,SAAS;GACtB,OAAO,KAAK;IAAE,IAAI,YAAY,WAAW;IAAG;IAAM,aAAa,CAAC,GAAG,SAAS,WAAW;GAAE,CAAC;EAC5F;EAGA,KAAK,MAAM,YAAY,WAAW,MAAM,QAAQ,QAAQ;EACxD,MAAM,QAAQ,EAAE;EAEhB,KAAK,MAAM,WAAW,UAAU,MAAM,QAAQ,OAAO;CACvD;CAGA,MAAM,UAAU,OAAO,aAA0B,aAA6B;EAC5E,eAAe,OAAO,aAAa,QAAQ;EAC3C,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GAGd,IAAI,iBAAiB,SAAS,CAAC,YAAY,IAAI,KAAK,GAAG,YAAY,IAAI,OAAO,OAAO;GACrF,MAAM;EACR;CACF;CAGA,MAAM,YAAY;EAChB,MAAM,WAAW,kBAAkB;EAEnC,MAAM,WAAW,gBAAgB,IAAI,OAAO,KAAK,YAAY,OAAO;EACpE,OAAO,QAAQ,SAAS,OAAO,OAAO,QAAQ;CAChD;CAEA,MAAM,UAAmB,OAAO,OAAO,KAAK;EAAE;EAAS;EAAQ;CAAM,CAAC;CACtE,cAAc,IAAI,OAAO;CACzB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"task.js","names":[],"sources":["../src/task.ts"],"sourcesContent":["import type { ShellConfig } from \"#config.ts\"\nimport { getLoadedBaskFile } from \"#loaded-bask-file.ts\"\nimport { createShell } from \"#shell/shell.ts\"\nimport { toEmptyArgs } from \"#task/args.ts\"\nimport type { ArgValues, NoArgs, ParsedTaskArgs, TaskArgs } from \"#task/args.ts\"\nimport { getCommandLineArgs } from \"#task/command-line-args.ts\"\nimport { findCycle, formatCycleMessage, getRunningChain, runInChain, waitOn } from \"#task/cycles.ts\"\nimport { recordFailedTask } from \"#task/failed-task.ts\"\nimport type { Hook, Task, TaskContext, TaskFn, TaskOptions, WrapFn, WrapOptions } from \"#task/types.ts\"\n\nconst HOOK_AFTER_START = \"Can't add a hook to a task that has already started\"\nconst WRAP_AFTER_START = \"Can't wrap a task that has already started\"\n\nconst createdByTask = new WeakSet<object>()\nexport const isTask = (value: unknown): value is Task => typeof value === \"function\" && createdByTask.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<const A extends TaskArgs = NoArgs>(options: TaskOptions<A>, fn: TaskFn<A>): Task<A>\nexport function task<A extends TaskArgs>(optionsOrFn: TaskOptions<A> | TaskFn<A>, maybeFn?: TaskFn<A>): Task<A> {\n const [passedOptions, fn] = typeof optionsOrFn === \"function\" ? [{}, optionsOrFn] : [optionsOrFn, maybeFn]\n // Copy the options because `wrap` adds args to them, and tasks can share the object they were given.\n const options: TaskOptions<A> = { ...passedOptions }\n if (!fn) throw new Error(\"task() needs a callback\")\n\n // Hold the hooks of the current layer, which each `wrap` folds into the function it replaces.\n let beforeFns: Hook<A>[] = []\n let afterFns: Hook<A>[] = []\n // Widen the options so `wrap` can add args to the object `task.options` exposes.\n const taskOptions: TaskOptions<TaskArgs> = options\n\n // Store the first call's promise so overlapping and later calls share it instead of rerunning the task.\n let runPromise: Promise<void> | undefined\n // Track the start separately because `runAll` calls the task before `runPromise` is assigned.\n let hasStarted = false\n let hasFinished = false\n\n const assertNotStarted = (message: string) => {\n if (hasStarted) throw new Error(message)\n }\n\n const before = (...fns: Hook<A>[]) => {\n assertNotStarted(HOOK_AFTER_START)\n beforeFns.push(...fns)\n }\n\n const after = (...fns: Hook<A>[]) => {\n assertNotStarted(HOOK_AFTER_START)\n afterFns.push(...fns)\n }\n\n // Give each hook, wrap, and the task its own shell so settings like `sh.cwd()` stay inside the function that made them.\n const toContext = (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs): TaskContext<A> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion - `taskArgs` was parsed from this task's own `args` declaration\n const args = taskArgs.args as ArgValues<A>\n return { sh: createShell(shellConfig), args, positionals: [...taskArgs.positionals] }\n }\n\n type LayerFn = (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => Promise<void>\n\n // Hold the task's current function, which each `wrap` replaces.\n let currentFn: LayerFn = async (shellConfig, taskArgs) => {\n await fn(toContext(shellConfig, taskArgs))\n }\n\n // Run the current layer: its before hooks, its function, then its after hooks.\n const toLayerFn =\n (layerFn: LayerFn, layerBeforeFns: Hook<A>[], layerAfterFns: Hook<A>[]): LayerFn =>\n async (shellConfig, taskArgs) => {\n // Call a task used as a hook bare, because this task's args aren't its args.\n const runHook = async (hook: Hook<A>) => {\n if (isTask(hook)) return hook()\n if (typeof hook === \"function\") return hook(toContext(shellConfig, taskArgs))\n }\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const beforeFn of layerBeforeFns) await runHook(beforeFn)\n await layerFn(shellConfig, taskArgs)\n // oxlint-disable-next-line no-await-in-loop - hooks run in order\n for (const afterFn of layerAfterFns) await runHook(afterFn)\n }\n\n const wrap = (wrapOptionsOrFn: WrapOptions<TaskArgs> | WrapFn<A>, maybeWrapFn?: WrapFn<A>) => {\n assertNotStarted(WRAP_AFTER_START)\n const [wrapOptions, wrapFn] =\n typeof wrapOptionsOrFn === \"function\" ? [{}, wrapOptionsOrFn] : [wrapOptionsOrFn, maybeWrapFn]\n if (!wrapFn) throw new Error(\"wrap() needs a callback\")\n\n const wrapArgs: TaskArgs = wrapOptions.args ?? {}\n const duplicateArg = Object.keys(wrapArgs).find((argName) => Object.hasOwn(taskOptions.args ?? {}, argName))\n if (duplicateArg !== undefined)\n throw new Error(`Can't add arg '${duplicateArg}' with wrap() because the task already has it`)\n taskOptions.args = { ...taskOptions.args, ...wrapArgs }\n\n // Wrap the task as it stands, hooks included, and start a new layer for hooks added after this.\n const replacedFn = toLayerFn(currentFn, beforeFns, afterFns)\n beforeFns = []\n afterFns = []\n currentFn = async (shellConfig, taskArgs) => {\n const original = async () => replacedFn(shellConfig, taskArgs)\n await wrapFn({ ...toContext(shellConfig, taskArgs), original })\n }\n // oxlint-disable-next-line no-use-before-define - `wrap` only runs after `newTask` is assigned\n return newTask\n }\n\n const runAll = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs) => {\n hasStarted = true\n try {\n await toLayerFn(currentFn, beforeFns, afterFns)(shellConfig, taskArgs)\n } finally {\n hasFinished = true\n }\n }\n\n // Assign `runPromise` before any await so a concurrent call can't start a second run.\n const runOnce = async (shellConfig: ShellConfig, taskArgs: ParsedTaskArgs, chain: Task[]) => {\n // oxlint-disable-next-line no-use-before-define - `runOnce` only runs after `newTask` is assigned\n runPromise ??= runInChain(chain, newTask, async () => runAll(shellConfig, taskArgs))\n try {\n await runPromise\n } catch (error) {\n // oxlint-disable-next-line no-use-before-define - `runOnce` only runs after `newTask` is assigned\n recordFailedTask(error, newTask)\n throw error\n }\n }\n\n // oxlint-disable-next-line typescript/promise-function-async - an async function would turn the throw into a rejection\n const run = () => {\n const baskFile = getLoadedBaskFile()\n\n const chain = getRunningChain()\n // Skip the check once the task has finished, because a call then only gets the finished run and can't wait on itself.\n // oxlint-disable-next-line no-use-before-define - `run` only runs after `newTask` is assigned\n const cycle = hasFinished ? undefined : findCycle(newTask, chain)\n if (cycle) throw new Error(formatCycleMessage(cycle, baskFile.tasks))\n\n // oxlint-disable-next-line no-use-before-define - `run` only runs after `newTask` is assigned\n const taskArgs = getCommandLineArgs(newTask) ?? toEmptyArgs(options)\n const calledRun = runOnce(baskFile.config.shell, taskArgs, chain)\n const caller = chain.at(-1)\n if (!caller) return calledRun\n // oxlint-disable-next-line no-use-before-define - `run` only runs after `newTask` is assigned\n return waitOn(caller, newTask, calledRun)\n }\n\n const newTask: Task<A> = Object.assign(run, { options, before, after, wrap })\n createdByTask.add(newTask)\n return newTask\n}\n"],"mappings":";;;;;;;AAUA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAEzB,MAAM,gCAAgB,IAAI,QAAgB;AAC1C,MAAa,UAAU,UAAk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