# @hyperfrontend/workspace

Five project tiles joined by the edges of their imports, each with its test task, under the command hf affected -t test. A file in core changes and the change travels every import that leaves core: it arrives at api through a value import and at cli through an import a spec makes, and both tasks light; it fades along the dashed type-only import to types, whose task stays dark; it carries on from api to web. A caption under the graph names the rule at each step, and the count beside selectAffected ends at 3 of 5

Runs the tasks of a TypeScript monorepo and releases its packages from a graph of what reaches what. ## What is @hyperfrontend/workspace? [`@hyperfrontend/workspace`](https://www.hyperfrontend.dev/docs/libraries/workspace.md) is the `hf` command line for a TypeScript monorepo: it runs a project's tasks, runs only the tasks a change affects, scaffolds libraries and makes them publishable, and versions and publishes them from their commits. A workspace adds executors and generators of its own in TypeScript, listed in a manifest beside the project, with no build step. It is one small tool a team can read end to end. It keeps no task cache and loads no plugins. ### Key Features - **Affected analysis that explains itself** - every task a change selects or skips carries the rule and the file behind the decision - **The package lifecycle as targets** - typecheck, test, build, e2e, publish, version-check and version, named once in `hf.json` - **Generators that compose** - workspace, library, make-publishable, rename and move, callable by name from a generator of your own - **Releases from commits** - the version flow reads conventional commits, pins dependents, writes the changelog and commits the bump - **Lint rules on the graph** - module boundaries, dependency checks and shell command lines, for [`@hyperfrontend/linter`](https://www.hyperfrontend.dev/docs/libraries/linter.md) - **Your own executors and generators** - a TypeScript function and a schema, found through a manifest, run with the same command ### Architecture Highlights The graph records each import with its kind and the role of the file that drew it, so a spec's import reaches the test target and not the build, a type-only import reaches neither test nor lint, and what cannot be followed precisely is counted whole and reported as such. The [architecture guide](https://www.hyperfrontend.dev/docs/libraries/workspace/architecture.md) covers the graph, the runner and how the entries are loaded by name. ## Why Use @hyperfrontend/workspace? ### Decisions you can read A CI run that skipped a task says why, by rule and by file, and a lint rule that refuses an import names the constraint. When a selection is wrong, the output names the rule to revisit. ### Scaffold to publish in one tool Generate a library, make it publishable with an e2e project that installs the packed tarball, type check and test it, version it from its commits and publish it, all through targets named once in `hf.json`. ### Extend it in TypeScript A local executor is a function of its options and the task's context; a local generator is a function of a tree, and composes the packaged generators by name. Both load from source, without a compile step. ## Installation ```bash npm install --save-dev @hyperfrontend/workspace ``` Requires Node.js 24 or later. The peers are optional, so install the ones the workspace uses: [`@hyperfrontend/testing`](https://www.hyperfrontend.dev/docs/libraries/testing.md) for the test and e2e executors, [`@hyperfrontend/linter`](https://www.hyperfrontend.dev/docs/libraries/linter.md) for the inferred lint target, prettier for the format command and the generators, and jsdom for the browser e2e suites. The type check and the build run on the TypeScript the package itself depends on, so the root may carry whatever TypeScript the editor wants, or none. ## Quick Start In a repository with a root `package.json`: ```bash npx hf generate workspace npm install npx hf generate library my-utils --publishable npx hf run my-utils:test npx hf affected -t test ``` The first command writes `hf.json` and the base configurations and settles the root manifest (an ES module package, with `@types/node` among its development dependencies), which the second installs; the third writes a library with its project, manifest, configurations and e2e project; the rest run its tasks. The affected run compares with `origin/main`, or with [`main`](https://www.hyperfrontend.dev/docs/libraries/workspace/runner/#api-main) where the repository has no such remote branch, unless `--base` names another revision. [The commands](https://www.hyperfrontend.dev/docs/libraries/workspace/cli.md) and [writing an executor or generator](https://www.hyperfrontend.dev/docs/libraries/workspace/runner.md) are each one page. ## API Overview | Entry | What it is | | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | [`@hyperfrontend/workspace`](https://www.hyperfrontend.dev/docs/libraries/workspace.md) | The contract: the types an executor or generator of your own is written against | | [`/cli`](https://www.hyperfrontend.dev/docs/libraries/workspace/cli.md) | The command line as a function | | [`/runner`](https://www.hyperfrontend.dev/docs/libraries/workspace/runner.md) | Executors and generators by name; one task, many in order, the affected run | | [`/graph`](https://www.hyperfrontend.dev/docs/libraries/workspace/graph.md) | The workspace graph, its persisted state and the affected analysis | | [`/hooks`](https://www.hyperfrontend.dev/docs/libraries/workspace/hooks.md) | Loads a workspace's TypeScript from source, for scripts of your own | | [`/lint`](https://www.hyperfrontend.dev/docs/libraries/workspace/lint.md) | The projects rule family and the readers a rule of your own shares with it | | [`/generators`](https://www.hyperfrontend.dev/docs/libraries/workspace/generators.md) | The helpers a local generator composes the packaged ones with; one entry per generator beneath it | | [`/executors/build`](https://www.hyperfrontend.dev/docs/libraries/workspace/executors/build.md) and siblings | One entry per executor, each with its schema | | `hf` | The command line | ## Limitations - No task cache, local or remote: a task runs every time it is asked for. - Target configurations (`--configuration`) are refused; a target has one shape. - The graph reads TypeScript and JavaScript imports; a dependency carried only through another language is counted whole, as a fallback, and reported as such. - The affected analysis of a historical range is exact only when the working tree is that range's head. ## Compatibility Requires Node.js 24 or later. There is no browser build. | Environment | Supported | | --------------- | :-------: | | Node.js >= 24 | ✅ | | Modern Browsers | ❌ | | Web Workers | ❌ | | Operating System | Supported | | ---------------- | :-------: | | Linux | ✅ | | macOS | ✅ | | Windows | ✅ | ### Output Formats | Format | File | Tree-Shakeable | | ------ | ------------ | :------------: | | ESM | `index.mjs` | ✅ | | CJS | `index.cjs` | ❌ | | Bin | `bin/hf.mjs` | ❌ | ## Part of hyperfrontend This library is part of the [hyperfrontend](https://github.com/AndrewRedican/hyperfrontend) monorepo. **📖 [Full documentation](https://www.hyperfrontend.dev/docs/libraries/workspace.md)** ## License [MIT](https://github.com/AndrewRedican/hyperfrontend/blob/main/LICENSE.md) ## API Reference Grouped by entry point. A declaration exported from several entry points is documented once, under the most specific one, and listed by name under the others. ### @hyperfrontend/workspace The contract executors and generators are written against: the context an executor runs in, the tree a generator edits, and the configuration both read. Also exported here, documented under the entry point that owns each: - `@hyperfrontend/workspace/generators`: `Tree`, `TreeChange`, `Generator` - `@hyperfrontend/workspace/runner`: `ExecutorContext`, `ExecutorEntry`, `ExecutorResult`, `ExecutorsManifest`, `GeneratorEntry`, `GeneratorsManifest`, `LintSettings`, `ProjectConfiguration`, `TargetConfiguration`, `WorkspaceConfiguration`, `Executor` ### @hyperfrontend/workspace/cli The workspace's command line as a function: what the `hf` executable runs, and what another command line hands its arguments to. #### Functions ##### handOver ```typescript function handOver(invocation: Invocation, host: HandoverHost): Promise ``` Passes a run on to the features command line, when `@hyperfrontend/features` is installed where the command was run. **Parameters** | Name | Type | Description | | --- | --- | --- | | `invocation` | `Invocation` | The run, passed on as it was received | | `host` | `HandoverHost` | How the features command line is found and loaded | **Returns** `Promise`: The exit code of the features command line, or null when the package is not installed **Example: Letting the other command line answer a command this one does not own** ```typescript import { handOver, processHost } from '@hyperfrontend/workspace/cli' const code = await handOver({ argv: ['pack', '.'], cwd: process.cwd(), stdout: process.stdout, stderr: process.stderr }, processHost()) // => the features exit code, or null when @hyperfrontend/features is not installed where the command was run ``` ##### isOwnCommand ```typescript function isOwnCommand(word: string): boolean ``` Whether a word is a command this command line owns. **Parameters** | Name | Type | Description | | --- | --- | --- | | `word` | `string` | The first argument | **Returns** `boolean`: True for `run` and every command of the table **Example: Deciding which command line answers** ```typescript isOwnCommand('run-many') // true isOwnCommand('pack') // false: the features command line is asked, when it is installed ``` ##### processHost ```typescript function processHost(entry: string): HandoverHost ``` The handover host of the running process: the features command line is resolved from the directory the command was run in, the way Node resolves any installed package. **Parameters** | Name | Type | Description | | --- | --- | --- | | `entry` | `string` | The package entry that holds the command line (default: `FEATURES_CLI`) | **Returns** `HandoverHost`: How this process resolves and loads that entry **Example: Resolving the features command line from where the command was run** ```typescript const host = processHost() host.resolve('/repo/apps/shell') // => '/repo/node_modules/@hyperfrontend/features/cli/index.js', or null when the package is not installed ``` ##### runGraph ```typescript function runGraph(argv: unknown, root: string, output: GraphOutput): number ``` Runs the `graph` command. **Parameters** | Name | Type | Description | | --- | --- | --- | | `argv` | `unknown` | The arguments after `graph` | | `root` | `string` | The workspace root, absolute | | `output` | `GraphOutput` | Where the command writes | **Returns** `number`: The exit code: 1 when `verify` finds a difference, 0 otherwise **Example: The tasks a change selects, explained** ```typescript import { runGraph } from '@hyperfrontend/workspace/cli' const output = { say: (line: string) => process.stdout.write(`${line}\n`), note: (line: string) => process.stderr.write(`${line}\n`) } runGraph(['affected', '--target', 'build', '--base', 'origin/main', '--explain'], root, output) // => 0; each selected build and the file that selected it went to `say`, the state build report to `note` ``` **Example: Checking the persisted graph state in CI** ```typescript runGraph(['verify'], root, output) // => 1 when a cold build disagrees with the state on disk ``` ##### runWorkspaceCli ```typescript function runWorkspaceCli(options: Invocation, host: HandoverHost): Promise ``` Runs the workspace's command line. The `hf` name is shared with `@hyperfrontend/features`: where that package is installed, a command this one does not own is passed on to its command line, and the usage is followed by its usage. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `Invocation` | The arguments, the starting directory and where to write | | `host` | `HandoverHost` | How the features command line is found and loaded (default: `...`) | **Returns** `Promise`: The exit code: 0 when the command succeeded, 1 otherwise **Example: The command line as a function** ```typescript import { runWorkspaceCli } from '@hyperfrontend/workspace/cli' const code = await runWorkspaceCli({ argv: ['run-many', '-t', 'build', '-p', 'lib-*'], cwd: process.cwd(), stdout: process.stdout, stderr: process.stderr, }) // => 0 when every task succeeded, 1 otherwise ``` **Example: Another `hf` command line passing a command on** ```typescript const code = await runWorkspaceCli({ argv, cwd, stdout, stderr, handedOver: true }) // => the exit code; an unknown command is reported here rather than passed back ``` #### Interfaces ##### FeaturesCli The features package's command line, as far as this one calls it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly runFeaturesCli` | `(invocation: Invocation) => Promise` | Runs the features command line and resolves to its exit code. | ##### GraphOutput Where the command writes. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly say` | `(line: string) => void` | Writes a line of the result, to standard output. | | `readonly note` | `(line: string) => void` | Writes a line about what the command did on the way, to standard error. | ##### HandoverHost How the other command line is found and loaded. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly resolve` | `(cwd: string) => string` | The file of the features command line as a directory resolves it, or null when the package is not installed. | | `readonly load` | `(file: string) => Promise` | Loads the features command line from its file. | ##### Invocation One run of a command line, as both packages take it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly argv` | `unknown` | The arguments after the executable's name. | | `readonly cwd` | `string` | The directory the command line was started in. | | `readonly stdout` | `TextSink` | Where results go. | | `readonly stderr` | `TextSink` | Where the command line's own lines go. | | `readonly handedOver?` | `boolean` | Set by the command line that passed this run on, so it is not passed back. | ##### TextSink Somewhere text is written. ###### write ```typescript write(text: string): unknown ``` Writes text. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `string` | | #### Types ##### WorkspaceCliOptions What a run of the command line is given. ```typescript type WorkspaceCliOptions = Invocation ``` #### Variables ##### FEATURES_CLI The entry of the features package that runs its command line. ```typescript const FEATURES_CLI: "@hyperfrontend/features/cli" ``` **Value** `'@hyperfrontend/features/cli'` ##### GRAPH_USAGE What the command expects. ```typescript const GRAPH_USAGE: "usage: hf graph projects [--json] | graph [--json] | explain | build [--force] | verify | status [--json] | affected --target [--base ] [--head ] [--json|--explain]" ``` **Value** `'usage: hf graph projects [--json] | graph [--json] | explain | build [--force] | verify | status [--json] | affected --target [--base ] [--head ] [--json|--explain]'` ##### USAGE What the command line prints about itself. ```typescript const USAGE: "@hyperfrontend/workspace: run the tasks of a workspace, see what a change affects, and generate code Usage: hf [options] Commands: run : [--name=value ...] Run one task, nothing it depends on first run-many -t [-p | --all] Run tasks and what they depend on affected -t [--base=] [--head=] Run the tasks a change selects format --check|--write [--all | --files=] Run prettier over changed, named or all files generate [...] [--dry-run] Run a generator of the workspace or of an installed package show projects [--with-target=] [--json] List the projects graph Print and explain the workspace graph " ``` **Value** `...` ##### WORKSPACE_FILE The file that marks a workspace root. ```typescript const WORKSPACE_FILE: "hf.json" ``` **Value** `'hf.json'` ### @hyperfrontend/workspace/executors/build The `build` executor: builds a library into a publishable package with the builder, treating the workspace's own packages as first-party. #### Functions ##### rootAssetSpecs ```typescript function rootAssetSpecs(root: string, names: unknown): AssetSpec[] ``` The assets copied from the workspace root. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `names` | `unknown` | The files, relative to the root | **Returns** `AssetSpec[]`: One asset spec per file that exists, the funding file conditional on the package declaring `funding` **Example: A missing file is skipped, the funding file is conditional** ```typescript rootAssetSpecs('/repo', ['LICENSE', 'FUNDING.md', 'NOTICE']) // => [ // { from: '/repo', files: ['LICENSE'] }, // { from: '/repo', files: ['FUNDING.md'], condition: (manifest) => Boolean(manifest.funding) }, // ] when /repo has no NOTICE ``` #### Interfaces ##### BuildExecutorOptions Schema-validated executor options. Mirrors `BuildConfig` from `@hyperfrontend/builder/models` minus what the executor decides for every workspace (`isWorkspacePackage`, `filterWorkspaceDepsFromOutput`, `inheritFieldsFrom`, `thirdPartyLicenses`, `memoryMonitor`). **Properties** | Name | Type | Description | | --- | --- | --- | | `outputPath?` | `string` | Output directory, relative to the workspace root. Defaults to `dist/`. | | `tsConfig?` | `string` | Path to tsconfig, relative to the workspace root. Defaults to `/tsconfig.lib.json`. | | `rootAssets?` | `string[]` | Files at the workspace root copied into the package when they exist, such as a licence. `FUNDING.md` is copied only into a package that declares `funding`. | | `assets?` | `AssetSpec[]` | Additional asset specs to copy in addition to the project's README and changelog and the root assets. | | `external?` | `string[]` | Global externals applied to every format. | | `esm?` | `EsmConfig \| EsmConfig[]` | ESM output configuration. Omit to skip. | | `cjs?` | `CjsConfig \| CjsConfig[]` | CommonJS output configuration. Omit to skip. | | `iife?` | `IifeConfig \| IifeConfig[]` | IIFE bundle configuration. Omit to skip. | | `umd?` | `UmdConfig \| UmdConfig[]` | UMD bundle configuration. Omit to skip. | | `unpkg?` | `string` | Override path for the unpkg field. Defaults to the first UMD bundle path. | | `jsdelivr?` | `string` | Override path for the jsdelivr field. Defaults to the first UMD bundle path. | | `bin?` | `BinConfig[]` | Bin declarations to synthesize alongside the library. | | `dedupeSharedInternals?` | `boolean` | Hoist first-party modules shared across entry bundles into `_shared/` chunks. Defaults to enabled. | | `verbose?` | `boolean` | Enable verbose / debug logging. | | `clean?` | `boolean` | Empty the output directory before emitting. Defaults to enabled; only an empty directory or a previous build of this package is removed. | #### Variables ##### buildExecutor Builds a library into a publishable package. ```typescript const buildExecutor: Executor ``` **Value** `...` ##### FUNDING_ASSET The root asset that travels only with a package that declares `funding`. ```typescript const FUNDING_ASSET: "FUNDING.md" ``` **Value** `'FUNDING.md'` ### @hyperfrontend/workspace/executors/e2e The `e2e` executor: packs a library's build, installs the tarball into the e2e project that tests it, and runs that project's suites. #### Functions ##### e2eExecutor ```typescript function e2eExecutor(options: E2eExecutorOptions, context: ExecutorContext): Promise ``` E2E executor for testing package build outputs. Workflow: 1. Run `npm pack` in the dist directory to create a tarball 2. Install the tarball in the E2E test project 3. Run each configured format's suites on the node test runner (cjs, esm, browser, and the suites the project declares) 4. Optionally cleanup the tarball **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `E2eExecutorOptions` | Configuration for test directory, formats, and cleanup behavior | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: A promise resolving to an object indicating success or failure **Example: An e2e project's target, the library found through `implicitDependencies`** ```json { "name": "e2e-core", "implicitDependencies": ["lib-core"], "targets": { "e2e": { "executor": "@hyperfrontend/workspace:e2e", "dependsOn": ["^build"], "options": { "formats": ["cjs", "esm", { "name": "consumer", "specs": ["src/consumer.spec.ts"], "timeoutMs": 120000 }] } } } } ``` `npx hf run e2e-core:e2e` packs `dist/libs/core`, installs the tarball into `e2e/core`, and runs the three suites. ##### formatRun ```typescript function formatRun(format: E2eFormat, platform: string): FormatRun ``` How a format of the target's options runs. **Parameters** | Name | Type | Description | | --- | --- | --- | | `format` | `E2eFormat` | A built-in format's name, or a suite the project declares itself | | `platform` | `string` | The platform the run happens on | **Returns** `FormatRun`: The run, or undefined for a name that is no built-in format **Example: A built-in format and a declared suite** ```typescript formatRun('browser', 'linux') // => { name: 'browser', candidates: ['src/iife.spec.ts', 'src/umd.spec.ts'], dom: true, timeoutMs: 30000, serial: false } formatRun({ name: 'consumer', specs: ['src/consumer.spec.ts'], timeoutMs: 120000, serialOn: ['win32'] }, 'win32') // => { name: 'consumer', candidates: ['src/consumer.spec.ts'], dom: false, timeoutMs: 120000, serial: true } ``` ##### libraryUnderTest ```typescript function libraryUnderTest(projects: Readonly>, project: ProjectConfiguration): ProjectConfiguration ``` The library an e2e project tests: the first project it implicitly depends on that builds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `projects` | `Readonly>` | Every project's configuration by name | | `project` | `ProjectConfiguration` | The e2e project | **Returns** `ProjectConfiguration`: The library's configuration, or undefined when the project depends on none that builds **Example: The implicit dependency that builds names the library** ```typescript libraryUnderTest(context.projects, context.projects['e2e-core']) // => context.projects['lib-core'] when e2e-core lists implicitDependencies: ['lib-core'] and lib-core has a build target ``` ##### testingAliases ```typescript function testingAliases(workspaceRoot: string): Record ``` The path aliases of the test runtime, as the workspace declares them. A run that replaces the workspace aliases outright, so a packed tarball resolves from a test project's `node_modules`, still has to reach the runtime by name where the workspace serves it from source. **Parameters** | Name | Type | Description | | --- | --- | --- | | `workspaceRoot` | `string` | The workspace root, absolute | **Returns** `Record`: The runtime's aliases and nothing else; none in a workspace that installs the runtime **Example: Only the runtime's aliases survive** ```typescript testingAliases(root) // => { '@hyperfrontend/testing': ['libs/testing/src/index.ts'], '@hyperfrontend/testing/*': ['libs/testing/src/*'] } in the workspace that develops the runtime // => {} in a workspace that installs it ``` #### Interfaces ##### E2eExecutorOptions Options for the e2e executor. **Properties** | Name | Type | Description | | --- | --- | --- | | `packageDir?` | `string` | Path to built package directory relative to workspace root | | `testDir?` | `string` | Path to E2E test project directory relative to workspace root | | `formats?` | `E2eFormat[]` | Output formats to test | | `skipInstall?` | `boolean` | Skip npm pack and install step | | `cleanupTarball?` | `boolean` | Remove tarball after installation | ##### E2eFormatEntry A suite of an e2e project that the built-in formats do not name. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The name the run is reported under | | `specs` | `string[]` | The spec files it runs, relative to the test project | | `timeoutMs?` | `number` | Per-test timeout in milliseconds; 30000 when unset | | `dom?` | `boolean` | Whether the run needs the DOM preload | | `serialOn?` | `string[]` | The platforms (`process.platform` values) on which the suites run one at a time | #### Types ##### E2eFormat A format of the e2e target: a built-in name or a suite the project declares. ```typescript type E2eFormat = "cjs" | "esm" | "browser" | E2eFormatEntry ``` ### @hyperfrontend/workspace/executors/publish The `publish` executor: publishes a library's build output to the npm registry, skipping a version already there. #### Functions ##### publishExecutor ```typescript function publishExecutor(options: PublishExecutorOptions, context: ExecutorContext): Promise ``` Publish executor for the libraries of a workspace. Publishes a library's build output, wherever its `build` target writes it, to the npm registry with support for: - Dry-run mode to preview what would be published - Custom registry URL - NPM dist-tags - Scope access control - 2FA OTP support **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `PublishExecutorOptions` | Options for the publish executor | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: Success status **Example: A `publish` target run after the build** ```json { "targets": { "publish": { "executor": "@hyperfrontend/workspace:publish", "dependsOn": ["build"], "options": { "access": "public", "tag": "latest", "provenance": true } } } } ``` `npx hf run lib-core:publish --dryRun` previews the npm command; a version the registry already has is skipped with success. #### Interfaces ##### PublishExecutorOptions Options for the publish executor. **Properties** | Name | Type | Description | | --- | --- | --- | | `dryRun?` | `boolean` | Run in dry-run mode without actually publishing | | `registry?` | `string` | Custom npm registry URL | | `tag?` | `string` | NPM dist-tag to publish with | | `access?` | `"public" \| "restricted"` | Publish access level for scoped packages | | `otp?` | `string` | One-time password for npm 2FA | | `provenance?` | `boolean` | Attach a provenance statement signed with the CI identity token | ### @hyperfrontend/workspace/executors/test The `test` executor: runs a project's suites on Node's built-in test runner, in a process of its own that this entry also serves. #### Functions ##### runTestsCli ```typescript function runTestsCli(argv: unknown): Promise ``` Loads a project's test configuration and runs its suites. **Parameters** | Name | Type | Description | | --- | --- | --- | | `argv` | `unknown` | The workspace root, the project root, the coverage directory and the configuration module | **Returns** `Promise`: The exit code: 0 when every suite passed and the coverage thresholds held, 1 otherwise ##### testExecutor ```typescript function testExecutor(options: TestExecutorOptions, context: ExecutorContext): Promise ``` Test executor for workspace projects. Runs the project's suites on Node's built-in test runner. The runner is started as its own process so the project's `test.config.ts` is evaluated by the same runtime that executes the tests, rather than by whatever TypeScript loader the calling process has installed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `TestExecutorOptions` | Executor options naming the test configuration and coverage directory | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: An object indicating success or failure of the test run **Example: A `test` target reading the project's `test.config.ts`** ```json { "targets": { "test": { "executor": "@hyperfrontend/workspace:test", "options": { "coverageDirectory": "coverage/libs/core" } } } } ``` `npx hf run lib-core:test` starts a Node.js process with `@hyperfrontend/testing/hooks` preloaded; coverage lands in `coverage/libs/core`, the default for a project at `libs/core`. #### Interfaces ##### TestExecutorOptions Schema types for the test executor. **Properties** | Name | Type | Description | | --- | --- | --- | | `testConfig?` | `string` | Path to the project's test configuration. Defaults to {projectRoot}/test.config.ts. | | `coverageDirectory?` | `string` | Where coverage reports are written. Defaults to {workspaceRoot}/coverage/{projectRoot}. | #### Variables ##### RUNNER_ENTRY The entry of this package that holds the runner the executor starts in a process of its own. ```typescript const RUNNER_ENTRY: "@hyperfrontend/workspace/executors/test" ``` **Value** `'@hyperfrontend/workspace/executors/test'` ##### TESTING_PACKAGE The package every project's suites run on. ```typescript const TESTING_PACKAGE: "@hyperfrontend/testing" ``` **Value** `'@hyperfrontend/testing'` ### @hyperfrontend/workspace/executors/typecheck The `typecheck` executor: runs the TypeScript compiler over a project's library and spec configurations without emitting files. #### Functions ##### typecheckExecutor ```typescript function typecheckExecutor(options: TypecheckExecutorOptions, context: ExecutorContext): Promise ``` Typecheck executor for the projects of a workspace. Runs the TypeScript compiler in --noEmit mode over the library config and, when the project has one, the spec config. Specs run with their types stripped, so this is the only step that type checks them. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `TypecheckExecutorOptions` | Executor options including the tsconfig paths | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: An object indicating success or failure of the type check **Example: A `typecheck` target with the default configurations** ```json { "targets": { "typecheck": { "executor": "@hyperfrontend/workspace:typecheck" } } } ``` `npx hf run lib-core:typecheck` checks `libs/core/tsconfig.lib.json`, then `libs/core/tsconfig.spec.json` when that file exists; `--tsConfig=libs/core/tsconfig.json` names another. #### Interfaces ##### TypecheckExecutorOptions Schema types for the typecheck executor. **Properties** | Name | Type | Description | | --- | --- | --- | | `tsConfig?` | `string` | Path to the library TypeScript configuration file, relative to the workspace root. Defaults to {projectRoot}/tsconfig.lib.json. | | `specTsConfig?` | `string` | Path to the spec TypeScript configuration file, relative to the workspace root. Defaults to {projectRoot}/tsconfig.spec.json, checked when that file exists. | ### @hyperfrontend/workspace/executors/version The `version` executor: versions a project from its conventional commits, pins its dependents to the new version, and commits the bump. #### Functions ##### runVersion ```typescript function runVersion(options: RunVersionOptions): Promise ``` Runs versioning logic for a single project. This function contains the core versioning logic extracted from the executor, allowing it to be called directly by the version-batch executor without going through the executor interface. Key behaviors: - Uses npm registry as source of truth (not git tags) - Performs safety checks (version commit detection, unstable git state) - Executes the versioning flow via `@hyperfrontend/versioning` - Updates dependent package versions - Tracks all modified files **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `RunVersionOptions` | Configuration options for versioning | **Returns** `Promise`: Result containing success status, version info, and modified files **Example: Versioning a project without committing** ```typescript const result = await runVersion({ projectName: 'my-lib', workspaceRoot: '/path/to/workspace', projectRoot: 'libs/my-lib', projects: context.projects, skipCommit: true, skipTag: true, }) if (result.bumped) { console.log(`Bumped from ${result.previousVersion} to ${result.newVersion}`) console.log(`Modified files: ${result.modifiedFiles.join(', ')}`) } ``` **Example: Carrying a follow-up's files into the version commit** ```typescript import { writeFileSync } from 'node:fs' import { join } from 'node:path' const result = await runVersion({ projectName: 'my-lib', workspaceRoot: '/path/to/workspace', projectRoot: 'libs/my-lib', projects: context.projects, followUps: [ (bump, run) => { if (!run.dryRun) writeFileSync(join(run.workspaceRoot, 'docs/versions.md'), `${bump.packageName} ${bump.newVersion}\n`) return ['docs/versions.md'] }, ], }) // => result.modifiedFiles ends with 'docs/versions.md', amended into the commit that records the bump ``` ##### versionExecutor ```typescript function versionExecutor(options: VersionExecutorOptions, context: ExecutorContext): Promise ``` Versions a project using `@hyperfrontend/versioning`. Key behaviors: - Uses npm registry as source of truth (not git tags) - Tags as OUTPUT (created after publish), not INPUT This executor delegates to `runVersion()` for the core versioning logic, allowing the same logic to be reused by the `version-batch` executor. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `VersionExecutorOptions` | Configuration options for the version executor | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: Success status **Example: A `version` target attributing commits by scope and by file** ```json { "targets": { "version": { "executor": "@hyperfrontend/workspace:version", "options": { "tagPrefix": "lib-core@", "scopeFiltering": { "strategy": "hybrid", "excludeScopes": ["ci", "docs-site"] } } } } } ``` `npx hf run lib-core:version --dryRun` says what would be bumped; without the flag the bump, the changelog entry and the pins of the dependents are committed, and no tag is made until `--skipTag=false`. #### Interfaces ##### FollowUpRun The run a follow-up is called from. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly workspaceRoot` | `string` | Absolute path to the workspace root | | `readonly dryRun` | `boolean` | Whether the run writes nothing; a follow-up then writes nothing either | ##### RunVersionOptions Options for running version logic on a single project. **Properties** | Name | Type | Description | | --- | --- | --- | | `projectName` | `string` | Name of the project to version | | `workspaceRoot` | `string` | Absolute path to workspace root | | `projectRoot` | `string` | Project root relative to workspace root | | `projects` | `Readonly>` | Every project of the workspace by name: the ones that pin the package are brought to the new version | | `skipCommit?` | `boolean` | Skip creating a git commit | | `skipTag?` | `boolean` | Skip creating a git tag | | `dryRun?` | `boolean` | Preview changes without applying | | `verbose?` | `boolean` | Enable verbose logging | | `quiet?` | `boolean` | Suppress non-error output | | `releaseAs?` | `"major" \| "minor" \| "patch"` | Force a specific bump type | | `tagPrefix?` | `string` | Version tag prefix | | `scopeFiltering?` | `ScopeFilteringConfig` | Scope filtering configuration | | `maxCommitFallback?` | `number` | Upper bound on the commit window the flow analyzes for bumps and changelogs | | `followUps?` | `unknown` | Called after the bump and before the commit, each answering the files the commit must also carry | ##### RunVersionResult Result of running version logic on a single project. **Properties** | Name | Type | Description | | --- | --- | --- | | `success` | `boolean` | Whether the operation completed successfully | | `bumped` | `boolean` | Whether a version bump actually occurred | | `previousVersion` | `string` | Previous version (null if first release or skipped) | | `newVersion` | `string` | New version (null if skipped) | | `modifiedFiles` | `string[]` | All files modified during the operation | | `error?` | `string` | Error message if operation failed | | `flowResult?` | `FlowResult` | The underlying flow result for advanced use cases | ##### VersionBump What a version run did to a project, as a follow-up reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly projectName` | `string` | The project's name | | `readonly projectRoot` | `string` | The project's root, workspace-relative | | `readonly packageName` | `string` | The name of the package the project carries | | `readonly previousVersion` | `string` | The version before the bump, or null for a first release | | `readonly newVersion` | `string` | The version the bump wrote | ##### VersionExecutorOptions What a `version` target configures: the bump, the commit and the tag, and how commits are attributed to the project. **Properties** | Name | Type | Description | | --- | --- | --- | | `dryRun?` | `boolean` | See what commands would be run, without committing to git or updating files. | | `scopeFiltering?` | `ScopeFilteringConfig` | Scope filtering configuration for commit classification and changelog generation. Controls how commits are filtered and classified for this project: - `strategy`: Filtering strategy ('hybrid', 'scope-only', 'file-only', 'inferred') - `includeScopes`: Additional scopes to always include - `excludeScopes`: Scopes to exclude even if files match - `trackDependencyChanges`: Include dependency commits as indirect - `infrastructure`: Infrastructure path and scope tracking | | `maxCommitFallback?` | `number` | Upper bound on the commit window the flow analyzes for bumps and changelogs. | | `releaseAs?` | `"major" \| "minor" \| "patch"` | Manually increment the version by that keyword (major, minor, patch). | | `tagPrefix?` | `string` | Version tag prefix. Default is '{projectName}@' in independent mode. | | `skipCommit?` | `boolean` | Allows to skip making a commit when bumping a version. | | `skipTag?` | `boolean` | Allows to skip tagging the release. Default: true (tags created after publish). | | `verbose?` | `boolean` | Enable verbose output for debugging. Shows additional details about each step. | | `quiet?` | `boolean` | Suppress all non-error output. | | `followUps?` | `unknown` | Called after the bump and before the commit that records it, each answering the files the commit must also carry. No configuration sets this; an executor that wraps this one passes it. | #### Types ##### FollowUp Called after a project is bumped and before the commit that records the bump. It answers the workspace-relative files it changed, and the commit carries them with the bump. ```typescript type FollowUp = (bump: VersionBump, run: FollowUpRun) => unknown ``` ### @hyperfrontend/workspace/executors/version-batch The `version-batch` executor: versions every library a change makes due a release, and records the bumps in one commit. #### Functions ##### baseBranches ```typescript function baseBranches(base: string, remotes: unknown): string[] ``` The branch names a base revision may be read as: the revision as written, without a `refs/heads/` or `refs/remotes/` prefix, and the branch behind a remote-tracking name such as `origin/main` for each remote the repository knows. **Parameters** | Name | Type | Description | | --- | --- | --- | | `base` | `string` | The base revision, as the batch was given it | | `remotes` | `unknown` | The names of the repository's remotes | **Returns** `string[]`: The branch names, each once **Example: The branch behind a remote-tracking base** ```typescript baseBranches('origin/main', ['origin']) // ['origin/main', 'main'] ``` ##### versionBatchExecutor ```typescript function versionBatchExecutor(options: VersionBatchExecutorOptions, context: ExecutorContext): Promise ``` Versions every library a change makes due a release and records the bumps in one commit. This executor: 1. Detects affected libraries programmatically 2. Runs versioning for each affected library 3. Creates a single batch commit It stands down on the base branch itself: the releases of that branch are made from the branches merged into it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `VersionBatchExecutorOptions` | Executor options from schema | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: Executor result with success status **Example: A root project's `version-batch` target** ```json { "name": "workspace", "root": ".", "targets": { "version-batch": { "executor": "@hyperfrontend/workspace:version-batch", "options": { "base": "origin/main" } } } } ``` `npx hf run workspace:version-batch` versions every library the change since `origin/main` makes due a release and commits the bumps as `chore: update versions for lib-core, lib-utils`; on `main` itself it stands down. **Example: Forcing a bump the commits would not have made** ```bash npx hf run workspace:version-batch --releaseAs=patch --libraries=lib-core,lib-utils ``` #### Interfaces ##### VersionBatchExecutorOptions Options of the version-batch executor. The executor detects affected libraries, versions each one, and creates a single batch commit. **Properties** | Name | Type | Description | | --- | --- | --- | | `base?` | `string` | Base git ref for affected detection. | | `head?` | `string` | Head git ref for affected detection. | | `dryRun?` | `boolean` | Preview changes without making them. | | `verbose?` | `boolean` | Enable verbose logging. | | `scopeFiltering?` | `ScopeFilteringConfig` | Commit scope filtering applied when attributing commits to a project. Defaults to whatever the `version` target declares, so the batch that writes versions attributes commits exactly as the single-project run and `version-check` do. | | `maxCommitFallback?` | `number` | Upper bound on the commit window the flow analyzes for bumps and changelogs. | | `releaseAs?` | `"major" \| "minor" \| "patch"` | Force this bump on the libraries named by `libraries`, calculated from each one's published version, for a release whose change is in the package artifact rather than its code. | | `libraries?` | `string[]` | Project names to version instead of the affected set. Required with `releaseAs`, and only meaningful with it. | | `followUps?` | `unknown` | Called after each bump and before the batch commit, each answering the files the commit must also carry. No configuration sets this; an executor that wraps this one passes it. | ##### VersionBatchResult Result of version-batch executor. **Properties** | Name | Type | Description | | --- | --- | --- | | `success` | `boolean` | Whether the batch versioning operation succeeded | | `bumpedLibraries` | `string[]` | Libraries that were actually bumped | | `commitHash?` | `string` | Commit hash if a batch commit was created | | `error?` | `string` | Error message if operation failed | ### @hyperfrontend/workspace/executors/version-check The `version-check` executor: compares a project's manifest and changelog with what its commits call for, without writing anything. #### Functions ##### versionCheckExecutor ```typescript function versionCheckExecutor(options: VersionCheckExecutorOptions, context: ExecutorContext): Promise ``` Validates version state without making changes. This executor is designed for CI validation to verify that: 1. The expected version bump (based on conventional commits) has been applied 2. The package.json version matches the expected version 3. The CHANGELOG.md contains the correct entry for the version Unlike the version executor, this makes NO changes to the repository. It's a read-only check that provides clear failure messages for remediation. Use cases: - CI pipeline validation - Local verification that a version run did what the commits call for - Debugging version discrepancies **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `VersionCheckExecutorOptions` | Configuration options for the version-check executor | | `context` | `ExecutorContext` | The workspace, the project and the target the task runs on | **Returns** `Promise`: Success status **Example: A `version-check` target sharing the `version` target's attribution** ```json { "targets": { "version-check": { "executor": "@hyperfrontend/workspace:version-check", "options": { "scopeFiltering": { "strategy": "hybrid", "excludeScopes": ["ci"] } } } } } ``` `npx hf run lib-core:version-check` fails when `libs/core/package.json` or its changelog lag behind what the commits call for, naming the `npx hf run lib-core:version` run that puts them right; it passes without a look on a version commit for the project. #### Interfaces ##### VersionCheckExecutorOptions What a `version-check` target configures: how commits are attributed to the project, and whether the check stands down on a version commit. **Properties** | Name | Type | Description | | --- | --- | --- | | `scopeFiltering?` | `ScopeFilteringConfig` | Scope filtering configuration for commit classification and changelog generation. Controls how commits are filtered and classified for this project: - `strategy`: Filtering strategy ('hybrid', 'scope-only', 'file-only', 'inferred') - `includeScopes`: Additional scopes to always include - `excludeScopes`: Scopes to exclude even if files match - `trackDependencyChanges`: Include dependency commits as indirect - `infrastructure`: Infrastructure path and scope tracking | | `maxCommitFallback?` | `number` | Upper bound on the commit window the flow analyzes for bumps and changelogs. | | `skipIfVersionCommit?` | `boolean` | Skip validation if the current commit is a version/release commit. | | `verbose?` | `boolean` | Enable verbose output for debugging. Shows additional details about validation. | | `quiet?` | `boolean` | Suppress all non-error output. | | `repository?` | `RepositoryConfig \| "inferred" \| "disabled" \| RepositoryResolution` | Repository resolution for changelog compare URLs. - `'disabled'`: No compare URLs generated - `'inferred'`: Auto-detect from package.json or git remote (default) - Object: Fine-grained control with mode and options | ### @hyperfrontend/workspace/generators What the generators are built from, so a workspace's own generators compose the packaged ones on the same tree: JSON, project and template helpers, names and paths, and running by name. #### Functions ##### addTsConfigPath ```typescript function addTsConfigPath(tree: Tree, options: AddPathOptions): void ``` Add a new path mapping to tsconfig.base.json. Maintains alphabetical sorting. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `AddPathOptions` | Options containing package name and project root | **Example: Registering a new library's alias** ```typescript import { addTsConfigPath } from '@hyperfrontend/workspace/generators' addTsConfigPath(tree, { packageName: '@acme/data-utils', projectRoot: 'libs/utils/data' }) // tsconfig.base.json compilerOptions.paths gains '@acme/data-utils': ['libs/utils/data/src/index.ts'], keys sorted ``` ##### blockBounds ```typescript function blockBounds(lines: unknown, opens: (line: string) => boolean, closes: (line: string) => boolean, what: string): BlockBounds ``` Locate a block by the line that opens it and the first later line that closes it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `lines` | `unknown` | The lines to search | | `opens` | `(line: string) => boolean` | Recognises the opening line | | `closes` | `(line: string) => boolean` | Recognises the closing line | | `what` | `string` | Names the block in the error raised when it is not there | **Returns** `BlockBounds`: The indices of the opening and closing lines **Example: Locating the rules block of a lint configuration** ```typescript const lines = ['export default [', ' {', ' rules: {', " 'a': 'error',", ' },', ' },', ']'] blockBounds(lines, (line) => line.trim() === 'rules: {', (line) => line.trim() === '},', 'the rules block') // => { open: 2, close: 4 } blockBounds(lines, (line) => line.trim() === 'ignores: [', (line) => line.trim() === '],', 'the ignores block') // throws: the ignores block: the block that opens it was not found ``` ##### compactVersion ```typescript function compactVersion(version: string): string ``` A version without the trailing zero segments a reader does not need. **Parameters** | Name | Type | Description | | --- | --- | --- | | `version` | `string` | A version such as `22.18.0` | **Returns** `string`: The version with trailing `.0` segments dropped, `22.18` **Example: Dropping the trailing zero segments** ```typescript compactVersion('18.0.0') // '18' compactVersion('20.10.5') // '20.10.5' ``` ##### compileIgnoreRules ```typescript function compileIgnoreRules(text: string, base: string): IgnoreRule[] ``` The rules of one `.gitignore`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `string` | The file's text | | `base` | `string` | The directory the file sits in, relative to the root, or an empty string | **Returns** `IgnoreRule[]`: The rules in order; comments and blank lines dropped **Example: How the lines of a `.gitignore` are read** ```typescript compileIgnoreRules('# build output\ndist/\n!dist/keep.txt\n', '') // => [ // { negated: false, directoryOnly: true, anchored: false, glob: 'dist', base: '' }, // { negated: true, directoryOnly: false, anchored: true, glob: 'dist/keep.txt', base: '' }, // ] ``` ##### findLine ```typescript function findLine(lines: unknown, matches: (line: string) => boolean, from: number): number ``` Find the first line a predicate accepts. **Parameters** | Name | Type | Description | | --- | --- | --- | | `lines` | `unknown` | The lines to search | | `matches` | `(line: string) => boolean` | The predicate | | `from` | `number` | The index to start searching at | **Returns** `number`: The index of the first matching line, or -1 when none matches **Example: The search starts where told** ```typescript const lines = ['import a from "a"', '', 'export default [', ' a,', ']'] findLine(lines, (line) => line.startsWith('export default'), 0) // => 2 findLine(lines, (line) => line === ']', 3) // => 4 findLine(lines, (line) => line.startsWith('import'), 1) // => -1 ``` ##### formatFiles ```typescript function formatFiles(tree: Tree, prettier: Prettier): Promise ``` Formats every created or updated file of the tree in place. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree whose changes are formatted | | `prettier` | `Prettier` | The prettier to format with; the workspace's own when omitted (default: `...`) | **Returns** `Promise`: Resolves when every file is written back **Example: The last step of a generator** ```typescript import type { Generator } from '@hyperfrontend/workspace/generators' import { formatFiles, writeJson } from '@hyperfrontend/workspace/generators' const addConfig: Generator<{ project: string; skipFormat?: boolean }> = async (tree, options) => { writeJson(tree, `libs/${options.project}/custom.json`, { enabled: true }) if (!options.skipFormat) await formatFiles(tree) } ``` ##### generateFiles ```typescript function generateFiles(tree: Tree, source: string, target: string, substitutions: Substitutions, options: GenerateFilesOptions): void ``` Writes every file of a template directory under a target directory of the tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree written to | | `source` | `string` | The template directory, absolute | | `target` | `string` | The directory the files land under, relative to the tree's root | | `substitutions` | `Substitutions` | The values the templates name | | `options` | `GenerateFilesOptions` | Whether files already there are kept (default: `{}`) | **Example: A generator's `files` directory written under the project** ```typescript import { join } from 'node:path' import { generateFiles, names } from '@hyperfrontend/workspace/generators' // files/src/index.ts.template holds: export const <%= names.propertyName %> = '<%= names.name %>' generateFiles(tree, join(import.meta.dirname, 'files'), 'libs/data-utils', { names: names('data-utils') }, { keepExisting: true }) // writes libs/data-utils/src/index.ts holding "export const dataUtils = 'data-utils'", unless the file is already there ``` ##### getPackageNameFromProject ```typescript function getPackageNameFromProject(tree: Tree, projectRoot: string): string ``` Get package name from a project's package.json file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `projectRoot` | `string` | The project root path | **Returns** `string`: The package name or null if not found **Example: Telling a package from a bare project** ```typescript getPackageNameFromProject(tree, 'libs/core') // => '@acme/core' getPackageNameFromProject(tree, 'apps/docs') // => null ``` ##### getProjects ```typescript function getProjects(tree: Tree): Map ``` Every project of the tree, by name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree read | **Returns** `Map`: The projects, in path order **Example: A project the same run created is already there** ```typescript import { getProjects, writeJson } from '@hyperfrontend/workspace/generators' writeJson(tree, 'libs/data/project.json', { projectType: 'library' }) getProjects(tree).get('data') // => { name: 'data', root: 'libs/data', projectType: 'library' }, named after its directory ``` ##### globalNameOf ```typescript function globalNameOf(packageName: string): string ``` The global a browser bundle of a package registers under: the scope and the name as one class name, `@scope/my-lib` giving `ScopeMyLib`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The identifier a browser attaches the bundle under **Example: The scope becomes part of the global** ```typescript globalNameOf('@acme/data-utils') // => 'AcmeDataUtils' globalNameOf('data-utils') // => 'DataUtils' ``` ##### indentOf ```typescript function indentOf(line: string): string ``` The leading whitespace of a line. **Parameters** | Name | Type | Description | | --- | --- | --- | | `line` | `string` | One line of the file | **Returns** `string`: Its indentation, empty for a line that starts at the margin **Example: Matching the indentation of a neighbouring line** ```typescript indentOf(' rules: {') // => ' ' indentOf('\tcommand: "hf-lint .",') // => '\t' indentOf('export default [') // => '' ``` ##### isIgnored ```typescript function isIgnored(path: string, isDirectory: boolean, rules: unknown): boolean ``` Whether git would ignore a path under the rules in force. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path relative to the root | | `isDirectory` | `boolean` | Whether the path names a directory | | `rules` | `unknown` | The rules in order, the deepest `.gitignore` last | **Returns** `boolean`: True when the last matching rule ignores it **Example: The last matching rule decides** ```typescript const rules = compileIgnoreRules('dist/\n!dist/keep.txt\n', '') isIgnored('libs/core/dist', true, rules) // => true isIgnored('dist/keep.txt', false, rules) // => false isIgnored('dist', false, rules) // => false: the rule names directories alone ``` ##### joinLines ```typescript function joinLines(text: TextLines): string ``` Join lines back into a text with the ending they were split from. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `TextLines` | The lines and their ending | **Returns** `string`: The text **Example: Editing a line and writing the file back byte for byte** ```typescript const text = splitLines(tree.read('lint.base.config.ts', 'utf-8') ?? '') text.lines.splice(3, 0, " '@acme/lint-rules',") tree.write('lint.base.config.ts', joinLines(text)) // the file keeps its CRLF or LF endings ``` ##### joinPathFragments ```typescript function joinPathFragments(...fragments: unknown): string ``` Fragments joined and normalised as a POSIX path; a native path among them is made portable first. **Parameters** | Name | Type | Description | | --- | --- | --- | | `...fragments` | `unknown` | The parts of the path | **Returns** `string`: The joined path with forward slashes **Example: A path fit for a configuration file, whatever the platform** ```typescript joinPathFragments('libs', 'utils\\data', './package.json') // => 'libs/utils/data/package.json' ``` ##### moveTsConfigPaths ```typescript function moveTsConfigPaths(tree: Tree, options: MovePathOptions): void ``` Update path mappings for a moved project in tsconfig.base.json. Updates both the key (package name) and value (file path). Maintains alphabetical sorting. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `MovePathOptions` | Options with current/new roots and package names | **Example: Moving the aliases with the directory, keeping the name** ```typescript moveTsConfigPaths(tree, { currentProjectRoot: 'libs/core', newProjectRoot: 'packages/core', currentPackageName: '@acme/core', newPackageName: '@acme/core', updateName: false, }) // '@acme/core': ['libs/core/src/index.ts'] became '@acme/core': ['packages/core/src/index.ts'] ``` ##### names ```typescript function names(name: string): Names ``` The forms of a name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | Any spelling, such as `my-lib`, `myLib` or `MY_LIB` | **Returns** `Names`: The class, property, constant and file forms **Example: The forms a template reads** ```typescript names('data-utils') // => { name: 'data-utils', className: 'DataUtils', propertyName: 'dataUtils', constantName: 'DATA_UTILS', fileName: 'data-utils' } names('DataUtils').fileName // => 'data-utils' ``` ##### nodeFloorOf ```typescript function nodeFloorOf(range: string): string ``` The lowest version an engines range names: the first version number in it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `range` | `string` | An engines range such as `>=22.18.0` | **Returns** `string`: The version, `22.18.0` **Example: Reading the floor of an engines range** ```typescript nodeFloorOf('>=18.0.0') // '18.0.0' nodeFloorOf('^20.10 || >=22') // '20.10' ``` ##### offsetFromRoot ```typescript function offsetFromRoot(directory: string): string ``` The relative path from a directory back to the root it is under: one `../` per segment. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | A directory relative to the root, such as `libs/utils/data` | **Returns** `string`: `./` for the root itself, else `../` repeated once per segment **Example: Pointing a project's tsconfig at the base one** ```typescript `${offsetFromRoot('libs/utils/data')}tsconfig.base.json` // => '../../../tsconfig.base.json' offsetFromRoot('.') // => './' ``` ##### prettierOf ```typescript function prettierOf(root: string): Prettier ``` The prettier a workspace installs, resolved from its root the way any module of the workspace resolves it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Prettier`: Its API **Example: Formatting a text with the workspace's prettier and configuration** ```typescript const prettier = prettierOf(tree.root) const options = { ...(await prettier.resolveConfig(`${tree.root}/libs/core/src/index.ts`, { editorconfig: true })), filepath: 'index.ts' } await prettier.format('export const a={b:1}', options) // => "export const a = { b: 1 }\n" ``` ##### quote ```typescript function quote(value: string): string ``` Write a value as a single-quoted TypeScript string literal. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `string` | The text | **Returns** `string`: The literal, with backslashes and quotes escaped **Example: Writing a path into TypeScript source** ```typescript quote('@acme/core') // => "'@acme/core'" quote("it's") // => "'it\\'s'" quote('C:\\repo') // => "'C:\\\\repo'" ``` ##### readJson ```typescript function readJson(tree: Tree, path: string): Value ``` The value of a JSON file of the tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file is read from | | `path` | `string` | The file, relative to the root | **Returns** `Value`: The parsed value **Example: Reading a manifest the tree holds** ```typescript import { readJson } from '@hyperfrontend/workspace/generators' readJson<{ name: string; version: string }>(tree, 'libs/core/package.json') // => { name: '@acme/core', version: '1.0.0' } readJson(tree, 'libs/core/missing.json') // throws: Cannot find libs/core/missing.json ``` ##### readPackageJsonInfo ```typescript function readPackageJsonInfo(tree: Tree, projectRoot: string): PackageJsonInfo ``` Read package name, description and keywords from a project's package.json. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `projectRoot` | `string` | The project root path | **Returns** `PackageJsonInfo`: Package name and description **Example: A project with and without a manifest** ```typescript readPackageJsonInfo(tree, 'libs/core') // => { name: '@acme/core', description: 'Core library.', keywords: ['core', 'acme'] } readPackageJsonInfo(tree, 'apps/docs') // => { name: null, description: '', keywords: [] } when apps/docs has no package.json ``` ##### readProjectConfiguration ```typescript function readProjectConfiguration(tree: Tree, name: string): ProjectConfiguration ``` One project of the tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the project is read from | | `name` | `string` | Which project | **Returns** `ProjectConfiguration`: Its configuration **Example: The root a generator writes under** ```typescript const project = readProjectConfiguration(tree, 'lib-core') // => { name: 'lib-core', root: 'libs/core', projectType: 'library', targets: { build: { ... } } } tree.write(`${project.root}/src/generated.ts`, 'export const generated = true\n') ``` ##### readRootManifest ```typescript function readRootManifest(tree: Tree): RootManifest ``` The root `package.json` of the tree, or nothing when the tree has none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree whose root is looked at | **Returns** `RootManifest`: The manifest's fields the generators inherit from **Example: What a new package inherits** ```typescript import { readRootManifest, scopeOf } from '@hyperfrontend/workspace/generators' const root = readRootManifest(tree) // => { name: '@acme/workspace', license: 'MIT', repository: { type: 'git', url: 'https://github.com/acme/workspace.git' } } scopeOf(root.name ?? '') // => '@acme' ``` ##### renameTsConfigPaths ```typescript function renameTsConfigPaths(tree: Tree, options: RenamePathOptions): void ``` Rename path mappings in tsconfig.base.json. Handles both exact matches and prefixed paths (e.g., `@pkg/sub`). Maintains alphabetical sorting. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `RenamePathOptions` | Options with current and new package names | **Example: The entry points of a package are renamed with it** ```typescript renameTsConfigPaths(tree, { currentPackageName: '@acme/core', newPackageName: '@acme/kernel' }) // '@acme/core' and '@acme/core/testing' became '@acme/kernel' and '@acme/kernel/testing'; '@acme/core-ui' is untouched ``` ##### renderExpression ```typescript function renderExpression(expression: string, substitutions: Substitutions): string ``` The text an expression renders as: the value a dotted path names, optionally with one `.replace("search", "replacement")` applied; a missing member renders as nothing. **Parameters** | Name | Type | Description | | --- | --- | --- | | `expression` | `string` | The text between `<%=` and `%>` | | `substitutions` | `Substitutions` | The values | **Returns** `string`: The text **Example: Dotted paths and the one call a template may make** ```typescript const substitutions = { names: names('data-utils'), packageName: '@acme/data-utils' } renderExpression('names.className', substitutions) // => 'DataUtils' renderExpression('packageName.replace("@", "")', substitutions) // => 'acme/data-utils' renderExpression('names.missing', substitutions) // => '' renderExpression('other', substitutions) // throws: other is not defined for the template ``` ##### renderTemplate ```typescript function renderTemplate(template: string, substitutions: Substitutions): string ``` A template with every `<%= expression %>` rendered. **Parameters** | Name | Type | Description | | --- | --- | --- | | `template` | `string` | The template text | | `substitutions` | `Substitutions` | The values | **Returns** `string`: The rendered text **Example: Rendering one template text** ```typescript renderTemplate('export class <%= names.className %> {}\n', { names: names('data-utils') }) // => 'export class DataUtils {}\n' ``` ##### replaceDescriptionPackageName ```typescript function replaceDescriptionPackageName(json: JsonWithDescription, currentPackageName: string, newPackageName: string): void ``` Update description field by replacing package name references. Mutates the json object in place for use inside updateJson callbacks. **Parameters** | Name | Type | Description | | --- | --- | --- | | `json` | `JsonWithDescription` | The JSON object to update | | `currentPackageName` | `string` | Package name to replace | | `newPackageName` | `string` | Replacement package name | **Example: Inside an `updateJson` updater** ```typescript import type { NamedJson } from '@hyperfrontend/workspace/generators' import { replaceDescriptionPackageName, updateJson } from '@hyperfrontend/workspace/generators' updateJson(tree, 'e2e/core/project.json', (json) => { replaceDescriptionPackageName(json, '@acme/core', '@acme/kernel') return json // description "E2E tests for @acme/core" now reads "E2E tests for @acme/kernel" }) ``` ##### runGenerator ```typescript function runGenerator(tree: Tree, written: string, options: Record, importModule: ImportModule): Promise ``` Runs the generator a name means over a tree, so a generator composes another by name: a workspace's own generator of that name, else the engine's. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the generator edits, rooted at the workspace | | `written` | `string` | The generator as the command line names it, `` or `:` | | `options` | `Record` | The options the generator is called with | | `importModule` | `ImportModule` | Imports a module from its absolute path; the process's own import when omitted (default: `...`) | **Returns** `Promise`: Resolves when the generator has run **Example: A workspace generator composing the packaged `library` generator** ```typescript import type { Generator } from '@hyperfrontend/workspace/generators' import { runGenerator } from '@hyperfrontend/workspace/generators' const featureLibrary: Generator<{ name: string }> = async (tree, options) => { await runGenerator(tree, 'library', { name: options.name, tags: ['type:feature'], skipFormat: true }) tree.write(`libs/${options.name}/src/feature.ts`, 'export const feature = true\n') } export default featureLibrary ``` ##### scopedName ```typescript function scopedName(scope: string, name: string): string ``` The package name a scope and a name make. **Parameters** | Name | Type | Description | | --- | --- | --- | | `scope` | `string` | The scope with its `@`, or undefined for no scope | | `name` | `string` | The name under the scope | **Returns** `string`: `@scope/name`, or the name alone **Example: Renaming a package under its current scope** ```typescript scopedName(scopeOf('@acme/core'), 'kernel') // => '@acme/kernel' scopedName(undefined, 'kernel') // => 'kernel' ``` ##### scopeOf ```typescript function scopeOf(packageName: string): string ``` The scope of a package name. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The scope with its `@`, or undefined for an unscoped name **Example: Scoped and unscoped names** ```typescript scopeOf('@acme/core') // => '@acme' scopeOf('lodash') // => undefined ``` ##### sortPaths ```typescript function sortPaths(paths: Record): Record ``` Sort paths object alphabetically by key. **Parameters** | Name | Type | Description | | --- | --- | --- | | `paths` | `Record` | The paths object to sort | **Returns** `Record`: Sorted paths object **Example: A stable order for the alias map** ```typescript sortPaths({ '@acme/utils': ['libs/utils/src/index.ts'], '@acme/core': ['libs/core/src/index.ts'] }) // => { '@acme/core': ['libs/core/src/index.ts'], '@acme/utils': ['libs/utils/src/index.ts'] } ``` ##### splitLines ```typescript function splitLines(content: string): TextLines ``` Split a text into lines, keeping the line ending it uses. **Parameters** | Name | Type | Description | | --- | --- | --- | | `content` | `string` | The text to split | **Returns** `TextLines`: The lines and their ending **Example: The ending is remembered, not normalised** ```typescript splitLines('a\r\nb\r\n') // => { lines: ['a', 'b', ''], eol: '\r\n' } splitLines('a\nb') // => { lines: ['a', 'b'], eol: '\n' } ``` ##### unscopedName ```typescript function unscopedName(packageName: string): string ``` A package name without its scope. **Parameters** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | A package name, scoped or not | **Returns** `string`: The part after the scope's slash, or the name as given **Example: The name a directory takes** ```typescript unscopedName('@acme/core') // => 'core' unscopedName('lodash') // => 'lodash' ``` ##### updateContentReferences ```typescript function updateContentReferences(tree: Tree, options: UpdateContentOptions): void ``` Update all content references (README + JSDoc). Convenience function combining updateReadmeReferences and updateModuleJSDoc. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `UpdateContentOptions` | Options containing project root and package names | **Example: Carrying a package's new name into its prose** ```typescript import { updateContentReferences } from '@hyperfrontend/workspace/generators' updateContentReferences(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' }) // libs/core/README.md and the @module header of libs/core/src/index.ts now say @acme/kernel ``` ##### updateJson ```typescript function updateJson(tree: Tree, path: string, updater: (value: Value) => Value): void ``` Rewrites a JSON file through an updater. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file lives in | | `path` | `string` | The file, relative to the root | | `updater` | `(value: Value) => Value` | Maps the current value to the one written | **Example: Adding a target to an existing project** ```typescript import type { ProjectConfiguration } from '@hyperfrontend/workspace/generators' import { updateJson } from '@hyperfrontend/workspace/generators' updateJson(tree, 'libs/core/project.json', (json) => { json.targets = { ...json.targets, docs: { command: 'typedoc' } } return json }) ``` ##### updateModuleJSDoc ```typescript function updateModuleJSDoc(tree: Tree, options: UpdateContentOptions): void ``` Update `@module` JSDoc tags in source files. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `UpdateContentOptions` | Options containing project root and package names | **Example: Only the entry's `@module` tag is rewritten** ```typescript updateModuleJSDoc(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' }) // "@module @acme/core" in libs/core/src/index.ts now reads "@module @acme/kernel"; other mentions of the name stay ``` ##### updateProjectReferences ```typescript function updateProjectReferences(tree: Tree, options: UpdateReferencesOptions): void ``` Renames a project in every other project's `implicitDependencies` and `dependsOn` entries. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the configurations live in | | `options` | `UpdateReferencesOptions` | The current and new names, and the roots to skip | **Example: The projects that depend on a renamed one follow it** ```typescript updateProjectReferences(tree, { currentProjectName: 'lib-core', newProjectName: 'lib-kernel' }) // e2e/core/project.json: implicitDependencies ['lib-core'] became ['lib-kernel'] // apps/shell/project.json: a target's dependsOn ['lib-core'] became ['lib-kernel']; '^build' entries are untouched ``` ##### updateReadmeReferences ```typescript function updateReadmeReferences(tree: Tree, options: UpdateContentOptions): void ``` Update README.md with new package name references. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The virtual file system tree | | `options` | `UpdateContentOptions` | Options containing project root and package names | **Example: Every mention in the README follows the package** ```typescript updateReadmeReferences(tree, { projectRoot: 'libs/core', currentPackageName: '@acme/core', newPackageName: '@acme/kernel' }) // "npm install @acme/core" in libs/core/README.md now reads "npm install @acme/kernel"; a project without a README is left alone ``` ##### visitNotIgnoredFiles ```typescript function visitNotIgnoredFiles(tree: Tree, directory: string, visitor: (path: string) => void): void ``` Visits every file under a directory of the tree that git would not ignore. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree walked | | `directory` | `string` | Where to start, relative to the root; an empty string or `.` for the root | | `visitor` | `(path: string) => void` | Called with each file's path relative to the root | **Example: Rewriting every source file of a project** ```typescript import { visitNotIgnoredFiles } from '@hyperfrontend/workspace/generators' visitNotIgnoredFiles(tree, 'libs/core', (path) => { if (!path.endsWith('.ts')) return const content = tree.read(path, 'utf-8') ?? '' tree.write(path, content.replaceAll('@acme/core', '@acme/kernel')) }) // libs/core/node_modules and anything libs/core/.gitignore lists are never visited ``` ##### writeJson ```typescript function writeJson(tree: Tree, path: string, value: unknown): void ``` Writes a value as two-space JSON with a trailing newline. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the file is written to | | `path` | `string` | The file, relative to the root | | `value` | `unknown` | What to write | **Example: A new project's manifest** ```typescript writeJson(tree, 'libs/core/project.json', { name: 'lib-core', projectType: 'library', targets: { build: {} } }) tree.read('libs/core/project.json', 'utf-8') // => '{\n "name": "lib-core",\n "projectType": "library",\n "targets": {\n "build": {}\n }\n}\n' ``` #### Interfaces ##### AddPathOptions Options for adding a new path mapping. **Properties** | Name | Type | Description | | --- | --- | --- | | `packageName` | `string` | npm package name (e.g., '@hyperfrontend/data-utils') | | `projectRoot` | `string` | Project root path (e.g., 'libs/utils/data') | ##### BlockBounds The first and last line of a bracketed block. **Properties** | Name | Type | Description | | --- | --- | --- | | `open` | `number` | Index of the line that opens the block | | `close` | `number` | Index of the line that closes the block | ##### Funding Where sponsorship of a package goes. **Properties** | Name | Type | Description | | --- | --- | --- | | `type?` | `string` | The platform | | `url?` | `string` | The page | ##### IgnoreRule One line of a `.gitignore`, read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly negated` | `boolean` | Whether a match re-includes the path. | | `readonly directoryOnly` | `boolean` | Whether the rule matches directories alone. | | `readonly anchored` | `boolean` | Whether the pattern names a path under the ignore file's directory rather than a name at any depth. | | `readonly glob` | `string` | The glob, without its anchors. | | `readonly base` | `string` | The directory the ignore file sits in, relative to the root, or an empty string. | ##### JsonWithDescription JSON object with an optional description field. **Properties** | Name | Type | Description | | --- | --- | --- | | `description?` | `unknown` | Optional description text | ##### MovePathOptions Options for moving path mappings. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentProjectRoot` | `string` | Current project root path | | `newProjectRoot` | `string` | New project root path | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | | `updateName` | `boolean` | Whether the name is being updated | ##### NamedJson A project or package manifest as far as a rename reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `description?` | `unknown` | Optional description text | | `name?` | `string` | The project or package name | ##### Names The forms of a name. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The name as given. | | `readonly className` | `string` | UpperCamelCase. | | `readonly propertyName` | `string` | lowerCamelCase. | | `readonly constantName` | `string` | CONSTANT_CASE. | | `readonly fileName` | `string` | lower-hyphenated. | ##### PackageJsonInfo Result of reading package.json metadata. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | Package name or null if not found | | `description` | `string` | Package description or empty string | | `keywords` | `string[]` | npm keywords, empty when the package declares none | ##### Prettier The part of prettier's API that formatting the tree uses. ###### format ```typescript format(source: string, options: Record): Promise ``` Formats a text with options. **Parameters** | Name | Type | Description | | --- | --- | --- | | `source` | `string` | | | `options` | `Record` | | ###### getFileInfo ```typescript getFileInfo(file: string, options: FileInfoOptions): Promise ``` Whether a file is ignored and which parser handles it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | | | `options` | `FileInfoOptions` | | ###### resolveConfig ```typescript resolveConfig(file: string, options: ResolveConfigOptions): Promise> ``` The configuration that applies to a file, or null when none does. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | | | `options` | `ResolveConfigOptions` | | ##### ProjectConfiguration The parts of a `project.json` a generator reads, with the project's name and root settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The project's name: the file's, or its directory's. | | `root` | `string` | The project's directory, relative to the root. | | `sourceRoot?` | `string` | Where its sources live. | | `description?` | `string` | What the project is for. | | `projectType?` | `string` | The kind of project. | | `tags?` | `string[]` | The tags the module boundaries read. | | `implicitDependencies?` | `string[]` | Projects depended on without an import. | | `targets?` | `Record` | The targets, by name. | | `metadata?` | `Record` | Free-form metadata. | ##### RenamePathOptions Options for renaming path mappings. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | ##### Repository Where a repository's packages are kept, as the root manifest states it. **Properties** | Name | Type | Description | | --- | --- | --- | | `type?` | `string` | The kind of repository, such as `git` | | `url?` | `string` | Its URL | | `directory?` | `string` | The directory of one package within it | ##### RootManifest The root `package.json` as far as the generators read it: what every package of the workspace inherits from it. **Properties** | Name | Type | Description | | --- | --- | --- | | `name?` | `string` | The workspace's own name, whose scope its packages take | | `license?` | `string` | The licence its packages are under | | `repository?` | `string \| Repository` | The repository its packages are kept in | | `funding?` | `string \| Funding` | Where sponsorship goes | | `engines?` | `Record` | The engines its packages run on | ##### TextLines A text split into lines, remembering the line ending it was written with so it can be joined back without changing a single byte it did not mean to. **Properties** | Name | Type | Description | | --- | --- | --- | | `lines` | `string[]` | The lines, without their endings | | `eol` | `string` | The ending every line was separated by | ##### Tree A virtual file tree: reads fall through to the files, writes are recorded until committed. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | The directory every path is relative to, absolute. | ###### children ```typescript children(path: string): string[] ``` The names directly under a directory. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ###### delete ```typescript delete(path: string): void ``` Records a file's deletion. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ###### exists ```typescript exists(path: string): boolean ``` Whether a file or directory is there. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ###### isFile ```typescript isFile(path: string): boolean ``` Whether the path names a file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ###### listChanges ```typescript listChanges(): TreeChange[] ``` Every change recorded so far. ###### read ```typescript read(path: string): Buffer ``` The content of a file, or null when there is none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | ```typescript read(path: string, encoding: "utf-8"): string ``` The text of a file, or null when there is none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | | `encoding` | `"utf-8"` | | ###### write ```typescript write(path: string, content: string | Buffer): void ``` Records a file's content. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | | | `content` | `string \| Buffer` | | ##### TreeChange One change a tree has recorded since it was opened. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly path` | `string` | The path, relative to the tree's root, POSIX. | | `readonly type` | `"CREATE" \| "UPDATE" \| "DELETE"` | What happened to the file. | | `readonly content?` | `Buffer` | The content written, or nothing for a deletion. | ##### UpdateContentOptions Options for updating content references. **Properties** | Name | Type | Description | | --- | --- | --- | | `projectRoot` | `string` | Project root path | | `currentPackageName` | `string` | Current npm package name | | `newPackageName` | `string` | New npm package name | ##### UpdateReferencesOptions How a project is renamed in the configurations that refer to it. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentProjectName` | `string` | The project's current name | | `newProjectName` | `string` | The project's new name | | `excludeRoots?` | `string[]` | The roots of projects whose configuration is left alone, such as the moved project's old and new roots | #### Types ##### Generator A generator: the default export of the module a generators manifest names. ```typescript type Generator = (tree: Tree, options: Options) => unknown ``` ##### Substitutions The values a template may name. ```typescript type Substitutions = Readonly> ``` #### Variables ##### DEFAULT_NODE_ENGINE The Node.js range a package declares when it declares none of its own. ```typescript const DEFAULT_NODE_ENGINE: ">=18.0.0" ``` **Value** `'>=18.0.0'` ##### DEFAULT_NPM_ENGINE The npm range a package declares when it declares none of its own. ```typescript const DEFAULT_NPM_ENGINE: ">=8.0.0" ``` **Value** `'>=8.0.0'` ##### PRINT_WIDTH The line width the workspace's formatter wraps at. A transform that writes a line longer than this would be rewritten by the next format pass, so the transforms break such a line themselves and running them twice changes nothing. ```typescript const PRINT_WIDTH: 140 ``` **Value** `140` ### @hyperfrontend/workspace/generators/library The `library` generator: creates a TypeScript library of the workspace, and hands a publishable one to `make-publishable`. #### Functions ##### libraryGenerator ```typescript function libraryGenerator(tree: Tree, options: LibraryGeneratorOptions): Promise ``` Creates a library: its manifests, the files of its templates, and its alias in `tsconfig.base.json`; then, for a publishable one, runs the generator named `make-publishable` on it, the workspace's own where it provides one. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, rooted at the workspace | | `options` | `LibraryGeneratorOptions` | What to create | **Returns** `Promise`: Resolves when the library is written **Example: An internal library** ```bash npx hf generate library my-lib --tags=type:util ``` **Example: A publishable library under a chosen directory** ```bash npx hf generate library my-utils --directory=libs/utils --publishable --formats=esm,cjs,iife,umd ``` **Example: From a workspace's own generator, formatting once at the end** ```typescript import libraryGenerator from '@hyperfrontend/workspace/generators/library' import { formatFiles } from '@hyperfrontend/workspace/generators' await libraryGenerator(tree, { name: 'data-utils', tags: ['type:util'], skipFormat: true }) tree.write('libs/data-utils/src/index.ts', 'export * from "./data"\n') await formatFiles(tree) ``` ##### planLibrary ```typescript function planLibrary(tree: Tree, options: LibraryGeneratorOptions): LibraryPlan ``` Settles the options: the names, the directory and the defaults the root manifest gives. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, whose root manifest gives the default scope | | `options` | `LibraryGeneratorOptions` | The options as given | **Returns** `LibraryPlan`: The names, the root and the description the generator writes from **Example: The names a spelling and the root manifest's scope settle to** ```typescript planLibrary(tree, { name: 'DataUtils', directory: 'libs/utils' }) // => { // name: 'data-utils', // projectName: 'data-utils', // packageName: '@acme/data-utils', // projectRoot: 'libs/utils/data-utils', // description: 'DataUtils library.', // tags: [], // offsetFromRoot: '../../../', // } when the root package.json is named @acme/workspace ``` #### Interfaces ##### LibraryGeneratorOptions What the `library` generator takes. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The name of the library, which names its directory and, with the scope, its package | | `directory?` | `string` | The directory the library is created under; `libs` when unset | | `scope?` | `string` | The npm scope of the package, with or without its `@`; the scope of the root manifest's name when unset | | `projectName?` | `string` | The project's name, as tasks address it; the library's name when unset | | `packageName?` | `string` | The package's name; the library's name under the scope when unset | | `description?` | `string` | A description of the library | | `tags?` | `string[]` | The tags the module boundaries read | | `publishable?` | `boolean` | Whether the generator named `make-publishable` runs on the library next | | `keywords?` | `string[]` | npm keywords for the package, handed to `make-publishable` | | `formats?` | `string[]` | The bundle formats the package builds, handed to `make-publishable` | | `skipFormat?` | `boolean` | Skip formatting the generated files | ##### LibraryPlan The options settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `name` | `string` | The library's name, as a file name | | `projectName` | `string` | The project's name | | `packageName` | `string` | The package's name | | `projectRoot` | `string` | The project's directory, relative to the root | | `description` | `string` | The description | | `tags` | `string[]` | The tags | | `offsetFromRoot` | `string` | The path from the project to the root | ### @hyperfrontend/workspace/generators/make-publishable The `make-publishable` generator: gives a library the targets, manifest fields, README and e2e project a published package needs. #### Functions ##### makePublishableGenerator ```typescript function makePublishableGenerator(tree: Tree, options: MakePublishableGeneratorOptions): Promise ``` Makes a library publishable: the targets a package runs, the manifest fields a registry asks for, a README when the project has none, and the project that tests the package. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, rooted at the workspace | | `options` | `MakePublishableGeneratorOptions` | Which project, and how it is built and tested | **Returns** `Promise`: Resolves when the project is written **Example: A package in ESM and CommonJS** ```bash npx hf generate make-publishable my-lib ``` **Example: A package with browser bundles under a chosen global** ```bash npx hf generate make-publishable my-lib --formats=esm,cjs,iife,umd --globalName=MyLib ``` **Example: Re-running on a published library changes nothing it already has** ```typescript import makePublishableGenerator from '@hyperfrontend/workspace/generators/make-publishable' await makePublishableGenerator(tree, { project: 'my-lib', formats: ['esm', 'cjs', 'umd'] }) // the build target gains its umd options; the existing targets, keywords, README and e2e suites are kept ``` ##### planPublishable ```typescript function planPublishable(tree: Tree, options: MakePublishableGeneratorOptions): PublishablePlan ``` Settles the options: the project, its package, the formats and the e2e project's names. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the project lives in | | `options` | `MakePublishableGeneratorOptions` | The options as given | **Returns** `PublishablePlan`: The names, the formats and the e2e project the generator writes from **Example: The formats fall into the build's order and the e2e names follow the package's** ```typescript planPublishable(tree, { project: 'data-utils', formats: ['umd', 'esm'] }) // => { // projectName: 'data-utils', // projectRoot: 'libs/data-utils', // packageName: '@acme/data-utils', // formats: ['esm', 'umd'], // globalName: 'AcmeDataUtils', // bundleEntry: '.', // keywords: ['data-utils', 'acme', 'typescript'], // buildExecutor: '@hyperfrontend/workspace:build', // e2eProjectName: 'e2e-data-utils', // e2ePackageName: '@acme/e2e-data-utils', // e2eProjectRoot: 'e2e/data-utils', // createE2e: true, // republishing: false, // e2eExists: false, // ... // } ``` #### Interfaces ##### MakePublishableGeneratorOptions What the `make-publishable` generator takes. **Properties** | Name | Type | Description | | --- | --- | --- | | `project` | `string` | The project made publishable | | `formats?` | `string[]` | The bundle formats the package builds; `esm` and `cjs` when unset | | `globalName?` | `string` | The global an `iife` or `umd` bundle registers under; derived from the package name when unset | | `bundleEntry?` | `string` | The entry the `iife` and `umd` bundles are built from; `.` when unset | | `keywords?` | `string[]` | npm keywords; the package's own, else its name, its scope and `typescript`, when unset | | `nodeEngine?` | `string` | The Node.js range the package declares; its own, else `>=18.0.0`, when unset | | `buildExecutor?` | `string` | The executor of the `build` target; `@hyperfrontend/workspace:build` when unset | | `e2eDirectory?` | `string` | The directory the e2e project is created under; `e2e` when unset | | `skipE2E?` | `boolean` | Skip creating the e2e project | | `skipFormat?` | `boolean` | Skip formatting the generated files | ##### PublishablePlan The options settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `projectName` | `string` | The project's name | | `projectRoot` | `string` | The project's directory, relative to the root | | `packageName` | `string` | The package's name | | `description` | `string` | The package's description | | `formats` | `unknown` | The bundle formats | | `globalName` | `string` | The global of the browser bundles | | `bundleEntry` | `string` | The entry of the browser bundles | | `keywords` | `string[]` | The npm keywords | | `nodeEngine` | `string` | The Node.js range chosen, or undefined to keep the package's own or inherit the root's | | `buildExecutor` | `string` | The executor of the `build` target | | `e2eProjectName` | `string` | The e2e project's name | | `e2ePackageName` | `string` | The e2e package's name | | `e2eProjectRoot` | `string` | The e2e project's directory, relative to the root | | `createE2e` | `boolean` | Whether the e2e project is created | | `republishing` | `boolean` | Whether the project already publishes, so what it has is kept | | `e2eExists` | `boolean` | Whether the e2e project already exists, so every file it has is kept | #### Types ##### BundleFormat A bundle format the build writes. ```typescript type BundleFormat = "esm" | "cjs" | "iife" | "umd" ``` ### @hyperfrontend/workspace/generators/move The `move` generator: relocates a project under another directory and brings its names, aliases and references along. #### Functions ##### moveGenerator ```typescript function moveGenerator(tree: Tree, options: MoveGeneratorOptions): Promise ``` Moves a project: copies its files under the destination, rewrites its manifests and the configuration files that point back at the root, moves its aliases, renames it in the projects that refer to it and in the project that tests it, and deletes the old directory. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, rooted at the workspace | | `options` | `MoveGeneratorOptions` | Which project, where to, and whether its names follow | **Returns** `Promise`: Resolves when the move is written **Example: Move a library under another directory** ```bash npx hf generate move my-utils libs/utils ``` **Example: Move and rename it** ```bash npx hf generate move my-utils libs/utils --newName=data ``` **Example: Move it without changing its names** ```bash npx hf generate move my-utils libs/utils --updateName=false ``` ##### planMove ```typescript function planMove(tree: Tree, options: MoveGeneratorOptions): MovePlan ``` Settles the options: where the project goes and what it and its package are called there. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the project lives in | | `options` | `MoveGeneratorOptions` | The options as given | **Returns** `MovePlan`: The roots, the names and the offset the move writes from #### Interfaces ##### MoveGeneratorOptions What the `move` generator takes. **Properties** | Name | Type | Description | | --- | --- | --- | | `project` | `string` | The project moved | | `destination` | `string` | The directory the project's directory moves under, relative to the root | | `newName?` | `string` | The new name of the project's directory; the current one when unset | | `projectName?` | `string` | The project's new name, when the names are updated; the directory's name when unset | | `packageName?` | `string` | The package's new name, when the names are updated; the directory's name under the package's current scope when unset | | `updateName?` | `boolean` | Whether the project's and the package's names follow the new location; true when unset | | `skipFormat?` | `boolean` | Skip formatting the generated files | ##### MovePlan The options settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `projectName` | `string` | The project's current name | | `currentProjectRoot` | `string` | The project's current directory, relative to the root | | `newProjectRoot` | `string` | The project's new directory, relative to the root | | `newProjectName` | `string` | The project's new name; its current one when the names are kept | | `currentPackageName` | `string` | The package's current name, or undefined for a project with no package | | `newPackageName` | `string` | The package's new name, or undefined for a project with no package | | `updateName` | `boolean` | Whether the names follow the new location | | `newOffsetFromRoot` | `string` | The path from the new project root to the workspace root | ### @hyperfrontend/workspace/generators/rename The `rename` generator: renames a project and carries the new name into everything that refers to it. #### Functions ##### planRename ```typescript function planRename(tree: Tree, options: RenameGeneratorOptions): RenamePlan ``` Settles the options: the project's root and its package's names. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree the project lives in | | `options` | `RenameGeneratorOptions` | The options as given | **Returns** `RenamePlan`: The root and the names the rename writes from **Example: The package keeps its scope** ```typescript planRename(tree, { project: 'my-utils', newName: 'better-utils' }) // => { // currentProjectName: 'my-utils', // projectRoot: 'libs/my-utils', // newProjectName: 'better-utils', // currentPackageName: '@acme/my-utils', // newPackageName: '@acme/better-utils', // } ``` ##### renameGenerator ```typescript function renameGenerator(tree: Tree, options: RenameGeneratorOptions): Promise ``` Renames a project: its `project.json` and `package.json`, its aliases in `tsconfig.base.json`, the `implicitDependencies` and `dependsOn` entries that name it, the package name its README and module header mention, and the project that tests it. The directory stays where it is; the `move` generator relocates it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, rooted at the workspace | | `options` | `RenameGeneratorOptions` | Which project, and its new names | **Returns** `Promise`: Resolves when the rename is written **Example: Renaming a project from the command line** ```bash npx hf generate rename my-utils better-utils ``` **Example: Choosing the package name rather than deriving it** ```typescript import renameGenerator from '@hyperfrontend/workspace/generators/rename' await renameGenerator(tree, { project: 'my-utils', newName: 'better-utils', packageName: '@acme/utils' }) ``` #### Interfaces ##### RenameGeneratorOptions What the `rename` generator takes. **Properties** | Name | Type | Description | | --- | --- | --- | | `project` | `string` | The project renamed | | `newName` | `string` | The project's new name | | `packageName?` | `string` | The package's new name; the new name under the package's current scope when unset | | `skipFormat?` | `boolean` | Skip formatting the generated files | ##### RenamePlan The options settled. **Properties** | Name | Type | Description | | --- | --- | --- | | `currentProjectName` | `string` | The project's current name | | `projectRoot` | `string` | The project's directory, relative to the root | | `newProjectName` | `string` | The project's new name | | `currentPackageName` | `string` | The package's current name, or undefined for a project with no package | | `newPackageName` | `string` | The package's new name, or undefined for a project with no package | ### @hyperfrontend/workspace/generators/workspace The `workspace` generator: writes the root configuration the engine reads into a repository that has none. #### Functions ##### workspaceGenerator ```typescript function workspaceGenerator(tree: Tree, options: WorkspaceGeneratorOptions): Promise ``` Writes the root configuration of a workspace: `hf.json` with the target defaults of the packaged executors, `tsconfig.base.json` with an empty alias map, a base lint configuration registering the `projects` rule family, `.hfignore`, and a `.gitignore` when there is none. The root manifest, where there is one, becomes an ES module package, since the configurations written are modules, and gains the Node.js type declarations the configurations name, on the major of the running Node.js, for the next `npm install` to fetch. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tree` | `Tree` | The tree, rooted at the repository | | `options` | `WorkspaceGeneratorOptions` | Whether to format (default: `{}`) | **Returns** `Promise`: Resolves when the files are written **Example: Starting a workspace in a repository that has none** ```bash npx hf generate workspace ``` **Example: From a setup script, over a tree of the repository** ```typescript import { commitChanges, createFsTree } from '@hyperfrontend/project-scope/vfs' import workspaceGenerator from '@hyperfrontend/workspace/generators/workspace' const tree = createFsTree(process.cwd()) await workspaceGenerator(tree, { skipFormat: true }) commitChanges(tree) // writes hf.json, tsconfig.base.json, lint.base.config.ts, .hfignore and, when missing, .gitignore; settles package.json ``` #### Interfaces ##### WorkspaceGeneratorOptions What the `workspace` generator takes. **Properties** | Name | Type | Description | | --- | --- | --- | | `skipFormat?` | `boolean` | Skip formatting the generated files | ### @hyperfrontend/workspace/graph The owned workspace graph: the projects, files, entries and installed packages a workspace holds, the qualified edges between them, and the project edges Nx would draw. #### Functions ##### algorithmVersion ```typescript function algorithmVersion(root: string): string ``` The algorithm that builds the graph for a workspace: a hash of the graph sources where the workspace aliases the graph package to its source, else `installed:` and the version of the installed engine, so a state one version wrote is rebuilt by the next. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string`: The algorithm's name ##### blobHashes ```typescript function blobHashes(root: string, paths: unknown): Map ``` The blob ids git would store for files of the working tree, with the checkout's filters applied, so a file hashed here agrees with the index entry of the same content. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `paths` | `unknown` | The files, workspace-relative and POSIX | **Returns** `Map`: Each path to its blob id ##### buildGraph ```typescript function buildGraph(root: string, options: BuildOptions): WorkspaceGraph ``` Builds the graph of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `options` | `BuildOptions` | The files and imports to build from, where the caller has them (default: `{}`) | **Returns** `WorkspaceGraph`: The graph of projects, edges, npm uses, aliases and versions **Example: Building from a file list and imports the caller already holds** ```typescript const files = listFiles(root) const imports = importsOfFiles(root, files) const graph = buildGraph(root, { files, imports }) graph.npmUses.get('lib-workspace') // => [{ name: '@hyperfrontend/linter', files: ['libs/workspace/src/...'] }, ...] ``` **Example: A fresh graph each call, unlike `workspaceGraph`** ```typescript buildGraph(root) === buildGraph(root) // => false ``` ##### buildState ```typescript function buildState(root: string, options: BuildStateOptions): BuiltState ``` Builds the state of a workspace under its lock: reads what is persisted, redoes what the plan says, writes the files whose bytes changed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `options` | `BuildStateOptions` | Whether to build cold (default: `{}`) | **Returns** `BuiltState`: The graph, the state and what the build did **Example: An incremental build after one file changed** ```typescript const { graph, outcome } = buildState(root) outcome.plan.mode // => 'incremental' outcome.plan.reasons // => ['0 added', '1 changed', '0 deleted'] outcome.plan.reparse // => ['libs/features/src/index.ts'] outcome.written // => ['files.json', 'imports.json', 'entries.json'], graph.json held the same bytes graph.projects.size // => 42 ``` **Example: Forcing a cold build** ```typescript buildState(root, { force: true }).outcome.plan.mode // => 'cold' ``` ##### canonicalJson ```typescript function canonicalJson(value: unknown): string ``` The canonical JSON text of a value: keys sorted at every depth, no whitespace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | Any JSON value | **Returns** `string`: The text **Example: Key order and whitespace are normalised, array order is kept** ```typescript canonicalJson({ b: [{ z: 1, a: 2 }], a: 'x' }) // => '{"a":"x","b":[{"a":2,"z":1}]}' canonicalJson({ a: 1, b: 2 }) === canonicalJson({ b: 2, a: 1 }) // => true ``` ##### changeSet ```typescript function changeSet(root: string, base: string, head: string): ChangeSet ``` The files that changed from the merge base of two revisions to the head, or to the working tree when the head is null, less what `.hfignore` leaves out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `base` | `string` | The base revision | | `head` | `string` | The head revision, or null for the working tree | **Returns** `ChangeSet`: The change set, sorted by path **Example: The working tree against `main`, untracked files included** ```typescript const changes = changeSet(root, 'main', null) changes.base // => 'a1b2c3...', the merge base rather than main's tip changes.head // => null changes.changes // => [{ status: 'added', path: 'libs/features/src/new.ts', previousPath: null }, ...] ``` **Example: Two commits, as CI frames a pull request** ```typescript changeSet(root, 'origin/main', 'HEAD').head // => 'HEAD' ``` ##### closureOf ```typescript function closureOf(graph: WorkspaceGraph, seeds: Iterable, kinds: ReadonlySet): Closure ``` Everything a set of files reaches through edges of the given kinds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph whose edges are followed | | `seeds` | `Iterable` | The files to start from, workspace-relative | | `kinds` | `ReadonlySet` | The edge kinds to follow; unresolved and side-effect edges are always honoured | **Returns** `Closure`: The reachable files and projects, with how each was reached **Example: What a change can reach from a library's entry** ```typescript const graph = workspaceGraph(root) const closure = closureOf(graph, ['libs/features/src/index.ts'], ALL_KINDS) closure.files.has('libs/nexus/src/core/registry.ts') // => true when the entry imports it, however indirectly closure.files.get('libs/features/src/index.ts') // => { from: null, edge: null, rule: null }, a seed closure.touched // => Set { 'lib-features', 'lib-nexus', ... } closure.projects // => Map {}, unless a fallback collapsed a project to whole ``` **Example: Type-only edges left out, as a `test` target sees the graph** ```typescript const kinds = relevantKinds('test') closureOf(graph, seeds, kinds).files.size <= closureOf(graph, seeds, ALL_KINDS).files.size // => true ``` ##### compareEdges ```typescript function compareEdges(left: Edge, right: Edge): number ``` Orders two edges deterministically: by source, target, kind, role, specifier, then evidence. **Parameters** | Name | Type | Description | | --- | --- | --- | | `left` | `Edge` | One edge | | `right` | `Edge` | Another | **Returns** `number`: Negative, zero or positive as a comparator does **Example: Checking that a list of edges is already canonical** ```typescript const canonical = graph.records.every((edge, index) => index === 0 || compareEdges(graph.records[index - 1]!, edge) <= 0) // => true ``` ##### compareText ```typescript function compareText(left: string, right: string): number ``` Orders two strings by code unit, the way every serialisation of the graph is ordered. **Parameters** | Name | Type | Description | | --- | --- | --- | | `left` | `string` | One string | | `right` | `string` | Another | **Returns** `number`: Negative, zero or positive as a comparator does **Example: Code-unit order, not locale order** ```typescript ['b', 'B', 'a', 'A'].sort(compareText) // => ['A', 'B', 'a', 'b'] ['b', 'B', 'a', 'A'].sort((left, right) => left.localeCompare(right)) // => ['a', 'A', 'b', 'B'] ``` ##### configurationKind ```typescript function configurationKind(path: string, project: ProjectRecord): ConfigurationKind ``` What kind of configuration of its project a file is, if any. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path, workspace-relative | | `project` | `ProjectRecord` | The project owning it | **Returns** `ConfigurationKind`: The kind, or null for a source, asset or documentation file **Example: Configuration sits at the project root; a nested tsconfig is a source like any other** ```typescript const project = graph.projects.get('lib-features')! // root 'libs/features' configurationKind('libs/features/package.json', project) // => 'manifest' configurationKind('libs/features/tsconfig.lib.json', project) // => 'configuration' configurationKind('libs/features/lint.config.ts', project) // => 'configuration' configurationKind('libs/features/e2e/tsconfig.json', project) // => null configurationKind('libs/features/src/index.ts', project) // => null ``` ##### currentMeta ```typescript function currentMeta(root: string, files: unknown): GraphMeta ``` The meta of a state written now from the given files. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace's files with their hashes | **Returns** `GraphMeta`: What a state written now is written by and from ##### describeReason ```typescript function describeReason(item: Reason): string[] ``` The lines describing one reason: the rule, the file and the sentence, then the path followed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `item` | `Reason` | The reason described | **Returns** `string[]`: One or two lines **Example: A reason with and without a path** ```typescript describeReason({ rule: 'changed-input', file: 'libs/a/src/x.ts', path: [], message: 'libs/a/src/x.ts is an input of lib-a:build (production file of lib-a)' }) // => ['changed-input libs/a/src/x.ts: libs/a/src/x.ts is an input of lib-a:build (production file of lib-a)'] describeReason({ rule: 'dependent-task', file: null, path: ['task:lib-a:build'], message: 'lib-a:test runs after lib-a:build, which is selected' }) // => ['dependent-task: lib-a:test runs after lib-a:build, which is selected', ' via task:lib-a:build'] ``` ##### digestOf ```typescript function digestOf(body: unknown): string ``` The digest of a JSON body: the sha256 of its canonical text. **Parameters** | Name | Type | Description | | --- | --- | --- | | `body` | `unknown` | Any JSON value | **Returns** `string`: The hex digest **Example: Two writers agree on a digest whatever order they built the body in** ```typescript digestOf({ files: [{ path: 'a', hash: '1' }], meta: {} }) === digestOf({ meta: {}, files: [{ hash: '1', path: 'a' }] }) // => true ``` ##### discoverProjects ```typescript function discoverProjects(root: string, files: unknown): Map ``` The projects of a workspace: one per directory holding a `project.json`, and one per directory holding a `package.json` alone, named by the configuration or the manifest. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace's files | **Returns** `Map`: The projects by name, with their files assigned to the deepest owning root **Example: A file belongs to the deepest project above it** ```typescript const projects = discoverProjects(root, listFiles(root)) const workspace = [...projects.values()].find((project) => project.root === '.')! workspace.files.includes('libs/features/src/index.ts') // => false, lib-features owns it projects.get('lib-features')?.type // => 'lib', inferred from the location when project.json names none ``` **Example: A directory with a `package.json` alone is a project named by the manifest** ```typescript // libs/vendored/package.json: { "name": "@scope/vendored" }, no project.json discoverProjects(root, listFiles(root)).get('@scope/vendored')?.configuration // => null ``` ##### entriesBody ```typescript function entriesBody(graph: WorkspaceGraph, hashes: ReadonlyMap): Record ``` The entries body: each entry's closure and the digest of the content it reaches. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph whose entries are closed over | | `hashes` | `ReadonlyMap` | The hash of each file | **Returns** `Record`: The closures by entry id ##### entriesOfProject ```typescript function entriesOfProject(project: ProjectRecord, aliases: ReadonlyMap, files: ReadonlySet): EntryNode[] ``` The entries of a project: its export subpaths, then the aliases naming its package, each to the source file it resolves to. A subpath or alias naming no file in the project is left out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectRecord` | The project whose entries are read | | `aliases` | `ReadonlyMap` | The workspace's path aliases, each to its targets | | `files` | `ReadonlySet` | The workspace's files | **Returns** `EntryNode[]`: The entries, in the order found **Example: The alias wins where it and `exports` name the same entry** ```typescript // package.json: { name: '@hyperfrontend/features', exports: { '.': './dist/index.js', './host': './dist/host.js' } } // tsconfig.base.json paths: { '@hyperfrontend/features': ['libs/features/src/index.ts'] } const files = new Set(listFiles(root)) entriesOfProject(project, readAliases(root), files) // => [{ kind: 'entry', id: '@hyperfrontend/features', project: 'lib-features', file: 'libs/features/src/index.ts' }] // './host' is left out: dist/host.js is not among the files, and no alias names it ``` ##### entryClosures ```typescript function entryClosures(graph: WorkspaceGraph): Map ``` The closure of every entry, following every edge kind. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph whose entries are closed over | **Returns** `Map`: Each entry id to what its file reaches **Example: Which entries a file's change can reach** ```typescript const changed = 'libs/nexus/src/core/registry.ts' const reaching = [...entryClosures(graph)].filter(([, closure]) => closure.files.has(changed)).map(([id]) => id) // => ['@hyperfrontend/nexus', '@hyperfrontend/features', '@hyperfrontend/features/host'] ``` ##### envelopeText ```typescript function envelopeText(body: unknown): string ``` The text of a state file holding a body: the canonical JSON of its envelope, with the body canonicalised once and digested as written. **Parameters** | Name | Type | Description | | --- | --- | --- | | `body` | `unknown` | The body to wrap | **Returns** `string`: The text, with a trailing newline ##### expandInputs ```typescript function expandInputs(root: string, project: ProjectRecord, inputs: unknown): string[] ``` The file patterns a list of inputs stands for, named inputs expanded through the workspace's and the project's definitions. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root | | `project` | `ProjectRecord` | The project whose named inputs apply | | `inputs` | `unknown` | The inputs to expand | **Returns** `string[]`: The patterns, `{projectRoot}` still unreplaced **Example: A name no definition knows is kept as a pattern** ```typescript // hf.json: { namedInputs: { production: ['default', '!{projectRoot}/**/*.spec.ts'] } } expandInputs(root, project, ['production', '{workspaceRoot}/tsconfig.base.json']) // => ['{projectRoot}/**/*', '!{projectRoot}/**/*.spec.ts', '{workspaceRoot}/tsconfig.base.json'] ``` **Example: A named input that names itself expands once** ```typescript // hf.json: { namedInputs: { default: ['default', '{workspaceRoot}/hf.json'] } } expandInputs(root, project, ['default']) // => ['{workspaceRoot}/hf.json'] ``` ##### exportTarget ```typescript function exportTarget(value: unknown): string ``` The file an export value names: a string, or the first string found among the conditions of an object, conditions nested in conditions included. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The value of one `exports` key | **Returns** `string`: The path as the manifest writes it, or null when the value names no file **Example: Conditions are searched in order, nested ones included** ```typescript exportTarget('./src/index.ts') // => './src/index.ts' exportTarget({ types: './dist/index.d.ts', import: './dist/index.js' }) // => './dist/index.js', import before types exportTarget({ node: { import: './dist/node.js' }, default: './dist/index.js' }) // => './dist/index.js' exportTarget({ import: { default: './dist/index.js' } }) // => './dist/index.js' exportTarget(null) // => null ``` ##### fileFilterOf ```typescript function fileFilterOf(patterns: unknown, projectRoot: string): FileFilter ``` Whether a file is an input under a list of patterns: it matches a positive pattern and no negative one, where the `production` exclusions are read by role and any other extended glob is left unapplied, so a file is never excluded by a pattern the compiler cannot read. **Parameters** | Name | Type | Description | | --- | --- | --- | | `patterns` | `unknown` | The expanded patterns, `{projectRoot}` unreplaced | | `projectRoot` | `string` | The root `{projectRoot}` stands for | **Returns** `FileFilter`: Whether a file of a role is an input **Example: Positive and negative patterns, placed on the project** ```typescript const inputs = fileFilterOf(['{projectRoot}/src/**/*', '!{projectRoot}/src/**/*.md'], 'libs/features') inputs('libs/features/src/index.ts', 'production') // => true inputs('libs/features/src/README.md', 'docs') // => false inputs('libs/features/package.json', 'build-config') // => false, not under src ``` **Example: An extended glob the compiler cannot read excludes nothing** ```typescript fileFilterOf(['{projectRoot}/**/*', '!{projectRoot}/**/+(a|b).ts'], 'libs/features')('libs/features/a.ts', 'production') // => true ``` ##### fileOf ```typescript function fileOf(files: ReadonlySet, path: string): string ``` The file a path names, with an extension or an index file supplied when the path has none. **Parameters** | Name | Type | Description | | --- | --- | --- | | `files` | `ReadonlySet` | The workspace's files | | `path` | `string` | The workspace-relative path, POSIX | **Returns** `string`: The file, or null when none matches **Example: An emitted `.js` name finds the TypeScript source behind it** ```typescript const files = new Set(['libs/features/src/index.ts', 'libs/features/src/host/open.tsx']) fileOf(files, 'libs/features/src/index.js') // => 'libs/features/src/index.ts' fileOf(files, 'libs/features/src') // => 'libs/features/src/index.ts' fileOf(files, 'libs/features/src/host/open') // => 'libs/features/src/host/open.tsx' fileOf(files, 'libs/features/src/missing') // => null ``` ##### formatAffected ```typescript function formatAffected(set: AffectedSet, mode: ExplainMode): string[] ``` The lines an affected set prints as. **Parameters** | Name | Type | Description | | --- | --- | --- | | `set` | `AffectedSet` | The decisions of one target | | `mode` | `ExplainMode` | The selected ids alone, or the explanation | **Returns** `string[]`: The lines **Example: The task ids alone, ready for a runner** ```typescript const graph = workspaceGraph(root) const changes = changeSet(root, 'main', null) const sets = selectAffected({ graph, changes, targets: ['test'], previous: previousGraph(root, changes) }) formatAffected(sets.get('test')!, 'tasks') // => ['lib-features:test', 'lib-nexus:test'] ``` **Example: The full explanation** ```typescript formatAffected(sets.get('test')!, 'explain').join('\n') // test: 2 of 14 tasks selected, 3 changed files, a1b2c3d4e5f6 → working tree // lib-nexus:test // changed-input libs/nexus/src/core/registry.ts: libs/nexus/src/core/registry.ts is an input of lib-nexus:test (production file of lib-nexus) // ... // skipped 12 tasks // lib-builder:test // unreachable libs/nexus/src/core/registry.ts: ... lib-builder does not depend on lib-nexus ``` ##### formatTask ```typescript function formatTask(set: AffectedSet, task: string): string[] ``` The lines explaining one task of an affected set. **Parameters** | Name | Type | Description | | --- | --- | --- | | `set` | `AffectedSet` | The affected set | | `task` | `string` | The task id, `:` | **Returns** `string[]`: The decision with its reasons, or one line saying the target has no such task **Example: Why one task was skipped** ```typescript formatTask(sets.get('test')!, 'lib-builder:test') // => ['lib-builder:test is skipped', ' unreachable libs/nexus/src/core/registry.ts: ...'] formatTask(sets.get('test')!, 'docs-site:test') // => ['docs-site:test is not a task of test'] ``` ##### graphBody ```typescript function graphBody(graph: WorkspaceGraph): GraphBody ``` The graph body of a graph. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph serialised | **Returns** `GraphBody`: The projects, nodes, records and edges in canonical order ##### hashesByPath ```typescript function hashesByPath(records: unknown): Map ``` Indexes the records for lookup. **Parameters** | Name | Type | Description | | --- | --- | --- | | `records` | `unknown` | The file records | **Returns** `Map`: Each path to its hash ##### hasTarget ```typescript function hasTarget(project: ProjectRecord, target: string): boolean ``` Whether a project declares a target. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectRecord` | The project whose targets are read | | `target` | `string` | The target's name | **Returns** `boolean`: True when the project's configuration declares it **Example: Selecting the projects a target can run on** ```typescript const graph = workspaceGraph(root) const buildable = [...graph.projects.values()].filter((project) => hasTarget(project, 'build')) ``` ##### hopTo ```typescript function hopTo(closure: Closure, path: string, project: string): Hop ``` The hop through which a file entered the closure, for a reached file or a file of a collapsed project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure asked about | | `path` | `string` | The file asked about | | `project` | `string` | The project owning it, or null | **Returns** `Hop`: The hop, or null when the closure does not reach the file **Example: A file of a collapsed project is reached through the project's hop** ```typescript hopTo(closure, 'libs/nexus/src/core/registry.ts', 'lib-nexus') // => the hop that reached the file, or the one that collapsed lib-nexus hopTo(closure, 'README.md', null) // => null ``` ##### ignoredPatterns ```typescript function ignoredPatterns(root: string): Glob[] ``` The patterns `.hfignore` lists, compiled. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root | **Returns** `Glob[]`: The globs, none when the file is absent **Example: Applying the workspace's ignores to a path of your own** ```typescript import { matchesAny } from '@hyperfrontend/linter/helpers' const ignores = ignoredPatterns(root) // from a .hfignore holding `# build output` and `dist/**` matchesAny(ignores, 'dist/libs/features/index.js') // => true matchesAny(ignores, 'libs/features/src/index.ts') // => false ``` ##### importsBody ```typescript function importsBody(imports: ImportTable, hashes: ReadonlyMap): Record ``` The imports body: one record per code file among the given, with the hash it was read from. **Parameters** | Name | Type | Description | | --- | --- | --- | | `imports` | `ImportTable` | The imports by path | | `hashes` | `ReadonlyMap` | The hash of each file | **Returns** `Record`: The records by path ##### importsOfFiles ```typescript function importsOfFiles(root: string, files: unknown): Map ``` The imports of every code file among the given, from the cache where the file is unchanged and from the parser otherwise; the cache is rewritten only when an entry changed. A file that no longer exists is left out, and one that does not parse is recorded as null and is not remembered, so a parser that learns to read it reads it next time. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `files` | `unknown` | The workspace-relative paths | **Returns** `Map`: The imports by path, for the code files only **Example: Only code files appear, and a parse failure is recorded as null** ```typescript const imports = importsOfFiles(root, listFiles(root)) imports.has('README.md') // => false imports.get('libs/features/src/index.ts')?.length // => 7 imports.get('libs/broken/src/index.ts') // => null, when the file does not parse ``` ##### importsOfText ```typescript function importsOfText(text: string, file: string): FileImport[] ``` The imports of a text. **Parameters** | Name | Type | Description | | --- | --- | --- | | `text` | `string` | The file's text | | `file` | `string` | Its path, whose extension decides the dialect | **Returns** `FileImport[]`: The imports, in source order, or null when the text does not parse **Example: Each form an import can take** ```typescript importsOfText( [ "import type { Node } from '@hyperfrontend/linter'", "import './polyfill'", "export * from './host'", "const mod = await import(`./locale/${lang}`)", ].join('\n'), 'src/index.ts' ) // => [ // { specifier: '@hyperfrontend/linter', dynamic: false, kind: 'type', typeOnly: true, names: ['Node'], line: 1, column: 1 }, // { specifier: './polyfill', dynamic: false, kind: 'side-effect', typeOnly: false, names: [], line: 2, column: 1 }, // { specifier: './host', dynamic: false, kind: 're-export-all', typeOnly: false, names: ['*'], line: 3, column: 1 }, // { specifier: '`./locale/${lang}`', dynamic: true, kind: 'unresolved', typeOnly: false, names: [], line: 4, column: 19 }, // ] ``` **Example: A file that does not parse** ```typescript importsOfText('import {', 'src/broken.ts') // => null ``` ##### inferLintTargets ```typescript function inferLintTargets(root: string, projects: ReadonlyMap): Map ``` Gives every project but the workspace root a `lint` target where it declares none, leaving out the projects whose project files `hf.json` lists under `lint.exclude` and the projects the linter would find no `lint.config.ts` for, in their root or above it. The target runs the command `hf.json` names under `lint.command`, or the linter's own executable. A project with an `install` target lints after it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `projects` | `ReadonlyMap` | The projects, by name | **Returns** `Map`: The same projects, the inferred target added to their configuration **Example: The target a project gets when it declares none** ```typescript // hf.json: { lint: { command: 'node {workspaceRoot}/tools/lint/bin/lint.ts .', exclude: ['libs/vendored/**'] } } const inferred = inferLintTargets(root, projects) inferred.get('lib-features')?.configuration?.targets?.['lint'] // => { executor: '@hyperfrontend/workspace:run-commands', // options: { command: 'node ../../tools/lint/bin/lint.ts .', cwd: 'libs/features' } } hasTarget(inferred.get('@scope/vendored')!, 'lint') // => false, excluded hasTarget(inferred.get('tool-local')!, 'lint') // => false, no lint.config.ts in tools/local or above it hasTarget(inferred.get('hyperfrontend')!, 'lint') // => false, the workspace root never gets one ``` ##### installedPackages ```typescript function installedPackages(root: string): InstalledPackages ``` The installed versions of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `InstalledPackages`: The top-level versions and the nested ones; empty without a lock file **Example: A package installed twice at different versions** ```typescript const { hoisted, nested } = installedPackages(root) hoisted.get('minimatch') // => '10.0.1', from node_modules/minimatch nested.has('minimatch@3.1.2') // => true, from node_modules/typedoc/node_modules/minimatch hoisted.get('@hyperfrontend/features') // => undefined, workspace links carry no version ``` ##### isCodeFile ```typescript function isCodeFile(path: string): boolean ``` Whether a file's imports count: a code file outside any node_modules. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The workspace-relative path | **Returns** `boolean`: Whether to read it **Example: Declaration files count, vendored packages do not** ```typescript isCodeFile('libs/features/src/index.ts') // => true isCodeFile('libs/features/src/types.d.ts') // => true isCodeFile('libs/features/node_modules/left-pad/index.js') // => false isCodeFile('libs/features/README.md') // => false ``` ##### isCompatibleTarget ```typescript function isCompatibleTarget(own: TargetRecord, defaults: TargetDefaults): boolean ``` Whether the workspace defaults of a target apply to a project's target, as Nx decides it: they do unless the two name different executors, or both name `run-commands` with different commands. **Parameters** | Name | Type | Description | | --- | --- | --- | | `own` | `TargetRecord` | The target as the project writes it, or undefined for a target the defaults alone define | | `defaults` | `TargetDefaults` | The defaults for the target's name | **Returns** `boolean`: True when Nx would merge the defaults into the target **Example: Two `run-commands` targets are the same target only when they run the same command** ```typescript const shell = '@hyperfrontend/workspace:run-commands' const defaults = { executor: shell, options: { command: 'hf-lint .' }, inputs: ['default'] } isCompatibleTarget({ executor: shell, options: { command: 'hf-lint .' } }, defaults) // => true isCompatibleTarget({ executor: shell, options: { command: 'tsc -p .' } }, defaults) // => false isCompatibleTarget({ executor: '@hyperfrontend/package:build' }, defaults) // => false isCompatibleTarget(undefined, defaults) // => true ``` ##### isGlobalConfig ```typescript function isGlobalConfig(path: string): boolean ``` Whether a file is one whose change invalidates the whole workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The path, workspace-relative | **Returns** `boolean`: True for `hf.json`, the root manifest, the lock file and the base tsconfig **Example: Only the root's own files count** ```typescript isGlobalConfig('package-lock.json') // => true isGlobalConfig('libs/features/package.json') // => false ``` ##### isStaleLock ```typescript function isStaleLock(path: string, staleMs: number): boolean ``` Whether a lock file no longer protects anything: it is gone, older than the bound, or held by a process that is not running. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The lock file | | `staleMs` | `number` | The bound on its age, in milliseconds | **Returns** `boolean`: True when the lock may be removed ##### libraryOfE2e ```typescript function libraryOfE2e(graph: WorkspaceGraph, project: ProjectRecord): ProjectRecord ``` The library an e2e project tests. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph the projects belong to | | `project` | `ProjectRecord` | A project with an e2e target | **Returns** `ProjectRecord`: The first implicit dependency with a build target, or null **Example: The library an e2e project packs** ```typescript const graph = workspaceGraph(root) libraryOfE2e(graph, graph.projects.get('e2e-lib-features')!)?.name // => 'lib-features' libraryOfE2e(graph, graph.projects.get('lib-features')!) // => null, no implicit dependency builds ``` ##### lintCommand ```typescript function lintCommand(root: string, command: string): string ``` The command of the `lint` target inferred for a project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The project root, workspace-relative and POSIX | | `command` | `string` | The command as `hf.json` writes it | **Returns** `string`: The command as it runs from the project's root **Example: The workspace root token becomes the way back up from the project** ```typescript lintCommand('libs/features', 'node {workspaceRoot}/tools/lint/bin/lint.ts .') // => 'node ../../tools/lint/bin/lint.ts .' lintCommand('libs/features', 'hf-lint .') // => 'hf-lint .' ``` ##### listFileRecords ```typescript function listFileRecords(root: string): FileRecord[] ``` The files of a workspace with their hashes: those git tracks or could track, less the ignored and less the tracked files the working tree no longer holds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `FileRecord[]`: The records, sorted by path **Example: The hash follows the working tree, not the index** ```typescript const records = listFileRecords(root) records[0] // => { path: '.hfignore', hash: '3b18e512dba79e4c8300dd08aeb37f8e728b8dad' } records.some((record) => record.path.startsWith('.hf/')) // => false, the state never describes itself // edit a tracked file without staging it: its hash changes on the next call ``` ##### listFiles ```typescript function listFiles(root: string): string[] ``` The files of a workspace: those git tracks or could track, less the ignored, as workspace-relative POSIX paths. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string[]`: The paths, in git's order **Example: Untracked files count, ignored and `.hfignore`d ones do not** ```typescript const files = listFiles(root) files.includes('libs/workspace/src/new-file.ts') // => true, before it is ever added files.includes('node_modules/typescript/package.json') // => false, with or without a .gitignore files.includes('apps/docs-site/.next/cache') // => false when .hfignore lists `apps/docs-site/.next/**` ``` ##### metaDifferences ```typescript function metaDifferences(previous: GraphMeta, current: GraphMeta): string[] ``` What differs between the meta of a persisted state and the current one. **Parameters** | Name | Type | Description | | --- | --- | --- | | `previous` | `GraphMeta` | The persisted meta | | `current` | `GraphMeta` | The meta a build would write now | **Returns** `string[]`: The differing keys, configuration files as `config:`; empty when they agree **Example: Why a build goes cold** ```typescript const persisted = readState(root)!.meta metaDifferences(persisted, currentMeta(root, listFileRecords(root))) // => ['node', 'config:package-lock.json'] after a Node upgrade and an install // => [] when the next build may be warm or incremental ``` ##### nodeId ```typescript function nodeId(node: GraphNode): string ``` The id of a node, unique across kinds. **Parameters** | Name | Type | Description | | --- | --- | --- | | `node` | `GraphNode` | The node to identify | **Returns** `string`: `:` **Example: One id per kind** ```typescript nodeId({ kind: 'project', name: 'lib-features', root: 'libs/features' }) // => 'project:lib-features' nodeId({ kind: 'file', path: 'libs/features/src/index.ts', project: 'lib-features', role: 'production' }) // => 'file:libs/features/src/index.ts' nodeId({ kind: 'entry', id: '@hyperfrontend/features/host', project: 'lib-features', file: 'libs/features/src/host.ts' }) // => 'entry:@hyperfrontend/features/host' nodeId({ kind: 'external', name: 'typescript', version: '5.9.2' }) // => 'external:typescript@5.9.2' nodeId({ kind: 'external', name: 'typescript', version: null }) // => 'external:typescript@*' nodeId({ kind: 'task', project: 'lib-features', target: 'build' }) // => 'task:lib-features:build' ``` ##### packageNameOf ```typescript function packageNameOf(specifier: string): string ``` The package a specifier names: its first segment, or its first two for a scoped package. **Parameters** | Name | Type | Description | | --- | --- | --- | | `specifier` | `string` | The bare specifier | **Returns** `string`: The package name, scope included **Example: Scoped and unscoped subpaths** ```typescript packageNameOf('@hyperfrontend/features/host') // => '@hyperfrontend/features' packageNameOf('typescript/lib/tsserverlibrary') // => 'typescript' ``` ##### packagesOf ```typescript function packagesOf(workspaces: unknown, projects: ReadonlyMap): Map ``` The projects importable by their package names: those the root manifest's `workspaces` globs cover, since Nx resolves a package name to a workspace project only for a package-manager workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `workspaces` | `unknown` | The globs of the root manifest's `workspaces`, compiled | | `projects` | `ReadonlyMap` | The projects by name | **Returns** `Map`: The map, empty when the root declares no workspaces **Example: Only projects under a declared workspace glob are importable by package name** ```typescript import { compileGlob } from '@hyperfrontend/linter/helpers' const { projects } = workspaceGraph(root) packagesOf([compileGlob('libs/*')], projects).has('@hyperfrontend/features') // => true packagesOf([], projects).size // => 0 ``` ##### parseNameStatus ```typescript function parseNameStatus(output: string): FileChange[] ``` The changes `git diff --name-status -z` lists: a status, then one path, or two for a rename or copy. **Parameters** | Name | Type | Description | | --- | --- | --- | | `output` | `string` | The NUL-separated output | **Returns** `FileChange[]`: The changes, in git's order **Example: A rename carries two paths, a copy counts as an addition** ```typescript parseNameStatus('M\0libs/a.ts\0R100\0libs/old.ts\0libs/new.ts\0C75\0libs/x.ts\0libs/y.ts\0') // => [ // { status: 'modified', path: 'libs/a.ts', previousPath: null }, // { status: 'renamed', path: 'libs/new.ts', previousPath: 'libs/old.ts' }, // { status: 'added', path: 'libs/y.ts', previousPath: null }, // ] ``` ##### planUpdate ```typescript function planUpdate(previous: PersistedState, meta: GraphMeta, files: unknown): UpdatePlan ``` Plans a build. **Parameters** | Name | Type | Description | | --- | --- | --- | | `previous` | `PersistedState` | The persisted state, or null when there is none to build on | | `meta` | `GraphMeta` | The meta a build would write now | | `files` | `unknown` | The workspace's files with their hashes | **Returns** `UpdatePlan`: What to reparse, what to reuse and why ##### prerequisitesOf ```typescript function prerequisitesOf(graph: WorkspaceGraph, project: ProjectRecord, target: string): Prerequisite[] ``` The tasks a project's target runs after that exist: the target of each project an entry names, when that project has it; each once, in the order the entries name them, and never the task itself. The entries are the project's own `dependsOn`, else the workspace defaults. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The graph the projects belong to | | `project` | `ProjectRecord` | The depending project | | `target` | `string` | The depending target | **Returns** `Prerequisite[]`: The tasks that must succeed before the target runs **Example: The three forms, read against the graph** ```typescript // project.json of lib-features: { targets: { build: { dependsOn: ['lint', '^build', 'lib-builder:build'] } } } const graph = workspaceGraph(root) prerequisitesOf(graph, graph.projects.get('lib-features')!, 'build') // => [ // { id: 'lib-features:lint', project: 'lib-features', target: 'lint' }, // { id: 'lib-nexus:build', project: 'lib-nexus', target: 'build' }, // each project lib-features has an edge to // { id: 'lib-builder:build', project: 'lib-builder', target: 'build' }, // ] ``` **Example: An object entry is refused rather than skipped** ```typescript // dependsOn: [{ target: 'build', projects: 'dependencies' }] prerequisitesOf(graph, project, 'build') // throws: lib-features:build depends on {"target":"build","projects":"dependencies"}, which is not one of the forms read: target, ^target or project:target ``` ##### previousGraph ```typescript function previousGraph(root: string, changes: ChangeSet): WorkspaceGraph ``` The graph at the base of a change set, when the selection needs it: only a deleted or renamed path asks what read it before the change. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `changes` | `ChangeSet` | The change set, or null for a selection of everything | **Returns** `WorkspaceGraph`: The graph at the change set's base, or undefined when no change removed a path **Example: Built only when a path was deleted or renamed** ```typescript const changes = changeSet(root, 'main', null) const previous = previousGraph(root, changes) // => undefined for edits and additions alone selectAffected({ graph: workspaceGraph(root), changes, targets: ['test'], previous }) ``` ##### previousWorkspaceFile ```typescript function previousWorkspaceFile(root: string, changes: ChangeSet): WorkspaceFile ``` The `hf.json` as it stood at the base of a change set, when the selection needs it: only a change to the file asks what each task resolved to before. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `changes` | `ChangeSet` | The change set, or null for a selection of everything | **Returns** `WorkspaceFile`: The file's content at the base, empty where the base had none, or undefined when the change set leaves the file alone **Example: Read only when the file changed** ```typescript const changes = changeSet(root, 'main', null) const previousWorkspace = previousWorkspaceFile(root, changes) // => undefined unless hf.json is among the changes selectAffected({ graph: workspaceGraph(root), changes, targets: ['test'], previousWorkspace }) ``` ##### printableProject ```typescript function printableProject(project: ProjectRecord): PrintableProject ``` A project as the state prints it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectRecord` | The project whose fields are printed | **Returns** `PrintableProject`: The record without its manifest and configuration ##### projectOfFile ```typescript function projectOfFile(projects: ReadonlyMap, file: string): ProjectRecord ``` The project owning a file: the one with the deepest root above it, the workspace itself last. **Parameters** | Name | Type | Description | | --- | --- | --- | | `projects` | `ReadonlyMap` | The projects by name | | `file` | `string` | The workspace-relative path | **Returns** `ProjectRecord`: The project, or null when the workspace has no root project **Example: The deepest root wins, the workspace itself catches the rest** ```typescript const { projects } = workspaceGraph(root) projectOfFile(projects, 'libs/features/e2e/src/open.spec.ts')?.name // => 'e2e-lib-features' projectOfFile(projects, 'libs/features/src/index.ts')?.name // => 'lib-features' projectOfFile(projects, 'tsconfig.base.json')?.root // => '.' ``` ##### readAliases ```typescript function readAliases(root: string): Map ``` The path aliases of a workspace, from its `tsconfig.base.json`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Map`: Each alias to its targets, none when the file or its paths are absent **Example: Every target of an alias is kept, not only the first** ```typescript const aliases = readAliases(root) aliases.get('@hyperfrontend/workspace/graph') // => ['libs/workspace/src/graph/index.ts'] aliases.get('@hyperfrontend/features/*') // => ['libs/features/src/*', 'libs/features/src/*.ts'] aliases.get('left-pad') // => undefined ``` ##### readerVersion ```typescript function readerVersion(root: string): string ``` The version of the reader for a workspace: the cache format, then a hash of the parser's sources where the workspace aliases the parser package to its source, else the version of the installed engine, which carries its own copy of the parser. A cache another version wrote is discarded. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string`: The version string **Example: The two forms a version takes** ```typescript readerVersion(root) // => '3:4f2a...' where the workspace aliases @hyperfrontend/linter to its sources readerVersion(root) // => '3:0.11.2' where the installed engine's parser reads the imports ``` ##### readImports ```typescript function readImports(root: string, file: string): FileImport[] ``` The imports of one code file, read and parsed now. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `file` | `string` | The workspace-relative path | **Returns** `FileImport[]`: The imports, or null when the file does not parse **Example: Bypassing the cache for one file** ```typescript readImports(root, 'libs/features/src/index.ts')?.map((item) => item.specifier) // => ['@hyperfrontend/nexus', './host/open', ...] ``` ##### readJson ```typescript function readJson(path: string): Value ``` Reads a JSON file, or nothing when it does not exist or does not parse. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file's absolute path | **Returns** `Value`: The value, or null **Example: A missing or malformed file reads as null rather than throwing** ```typescript readJson<{ name?: string }>(join(root, 'package.json'))?.name // => 'hyperfrontend' readJson(join(root, 'absent.json')) // => null readJson(join(root, 'broken.json')) // => null, for a file holding `{ "name": ` ``` ##### readState ```typescript function readState(root: string): PersistedState ``` The persisted state of a workspace, or nothing when any of its files is missing or invalid. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `PersistedState`: The state, or null **Example: All five files or nothing** ```typescript const state = readState(root) state?.meta.schema // => 'hf-graph/1' state?.graph.projects.map((project) => project.name) // => ['docs-site', 'lib-features', ...] // delete or hand-edit any one of the files and the whole state reads as null ``` ##### readStateFile ```typescript function readStateFile(path: string): Body ``` The body of a state file, or nothing when the file is absent, does not parse, follows another schema, is not laid out as written, or does not match its own digest. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file, absolute | **Returns** `Body`: The body, or null ##### readWorkspaceFile ```typescript function readWorkspaceFile(root: string): WorkspaceFile ``` The `hf.json` of a root, read once. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `WorkspaceFile`: The file's content, empty where there is none **Example: Reading the defaults of a target** ```typescript const { targetDefaults, namedInputs } = readWorkspaceFile(root) targetDefaults?.['build']?.inputs // => ['production', '^production'] namedInputs?.['production'] // => ['default', '!{projectRoot}/**/*.spec.ts', ...] ``` **Example: A workspace without an `hf.json`** ```typescript readWorkspaceFile('/tmp/empty') // => {} ``` ##### relevantKinds ```typescript function relevantKinds(target: string): ReadonlySet ``` The edge kinds that carry a change to a target: every kind, less `type` for a target that runs under type stripping. **Parameters** | Name | Type | Description | | --- | --- | --- | | `target` | `string` | The target's name | **Returns** `ReadonlySet`: The kinds that carry a change to it **Example: A type-only import never selects a test or lint task** ```typescript relevantKinds('build').has('type') // => true relevantKinds('test').has('type') // => false relevantKinds('lint').has('value') // => true ``` ##### resolveSpecifier ```typescript function resolveSpecifier(resolver: Resolver, from: string, specifier: string): Resolution ``` Resolves a specifier seen from a file as Nx does: a relative path or an alias target names the project whose root holds it, whether or not the file exists; an alias that names no project falls through to the package lookup, where a package name resolves to the file of the entry it names. **Parameters** | Name | Type | Description | | --- | --- | --- | | `resolver` | `Resolver` | What is known of the workspace | | `from` | `string` | The importing file, workspace-relative | | `specifier` | `string` | The specifier as written | **Returns** `Resolution`: What it names **Example: The four kinds a specifier resolves to** ```typescript const graph = workspaceGraph(root) const from = 'libs/features/src/index.ts' resolveSpecifier(graph, from, './host/open') // => { kind: 'project', project: , file: 'libs/features/src/host/open.ts', path: 'libs/features/src/host/open' } resolveSpecifier(graph, from, '@hyperfrontend/nexus') // => { kind: 'project', project: , file: 'libs/nexus/src/index.ts', path: null } resolveSpecifier(graph, from, 'node:path') // => { kind: 'builtin' } resolveSpecifier(graph, from, 'typescript/lib/tsserverlibrary') // => { kind: 'npm', name: 'typescript' } // 'unknown' is answered only where no project, the workspace root included, holds the path ``` **Example: A relative path to a file that does not exist still names its project** ```typescript const resolution = resolveSpecifier(graph, from, './missing') if (resolution.kind === 'project') resolution.file // => null, the project is lib-features all the same ``` ##### roleFilterOf ```typescript function roleFilterOf(patterns: unknown): RoleFilter ``` Whether the files of a role count under a list of input patterns: every role, unless the patterns carry the `production` exclusions, which leave specs and test and lint configuration out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `patterns` | `unknown` | The expanded patterns | **Returns** `RoleFilter`: Whether files of a role count **Example: The `production` exclusions are read by role, not by pattern** ```typescript const production = roleFilterOf(expandInputs(root, project, ['production'])) production('production') // => true production('spec') // => false production('docs') // => true roleFilterOf(['{projectRoot}/**/*'])('spec') // => true ``` ##### roleOf ```typescript function roleOf(file: string, projectRoot: string): Role ``` The role of a file within its project. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | The path to classify, workspace-relative and POSIX | | `projectRoot` | `string` | The owning project's root, workspace-relative and POSIX; `.` for the workspace itself | **Returns** `Role`: Which role the file plays **Example: The roles, as the `production` named input draws the line** ```typescript roleOf('libs/features/src/index.ts', 'libs/features') // => 'production' roleOf('libs/features/src/index.spec.ts', 'libs/features') // => 'spec' roleOf('libs/features/src/__test-utils__/host.ts', 'libs/features') // => 'spec' roleOf('libs/features/lint.config.ts', 'libs/features') // => 'lint-config' roleOf('libs/features/tsconfig.lib.json', 'libs/features') // => 'build-config' roleOf('libs/features/scripts/release.ts', 'libs/features') // => 'script' roleOf('libs/features/README.md', 'libs/features') // => 'docs' roleOf('libs/features/assets/logo.svg', 'libs/features') // => 'asset' roleOf('tools/lint/bin/lint.ts', '.') // => 'production', the workspace root owns it ``` ##### ruleHop ```typescript function ruleHop(closure: Closure, path: string): Hop ``` The hop that brought a file into the closure under a fallback rule, if any: the nearest collapse along the chain that reached it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure the file was reached in | | `path` | `string` | The reached file | **Returns** `Hop`: The hop carrying the rule, or null when ordinary edges reached the file **Example: Telling a precise reach from a conservative one** ```typescript const hop = ruleHop(closure, 'libs/nexus/src/core/registry.ts') hop?.rule // => 'unresolved-import' when a file on the chain loads an expression, null when every edge was followed precisely ``` ##### selectAffected ```typescript function selectAffected(options: SelectOptions): Map ``` Decides the tasks of the requested targets. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `SelectOptions` | The graph, the changes, the targets and the previous graph | **Returns** `Map`: The affected set of each requested target, and of each target one of them depends on **Example: Deciding the tests to run for the working tree against `main`** ```typescript import { changeSet, previousGraph, selectAffected, workspaceGraph } from '@hyperfrontend/workspace/graph' const graph = workspaceGraph(root) const changes = changeSet(root, 'main', null) const sets = selectAffected({ graph, changes, targets: ['test'], previous: previousGraph(root, changes) }) const tests = sets.get('test')! tests.selected.map((decision) => decision.task) // => ['lib-features:test', 'lib-nexus:test'] tests.selected[0]!.reasons[0]!.rule // => 'changed-input' tests.skipped[0]!.reasons[0]!.rule // => 'unreachable', every skip names the rule that makes it safe ``` **Example: A depended-on target is decided as well** ```typescript // hf.json: { targetDefaults: { test: { dependsOn: ['^build'] } } } [...selectAffected({ graph, changes, targets: ['test'] }).keys()] // => ['test', 'build'] ``` ##### selfInputs ```typescript function selfInputs(root: string, project: ProjectRecord, target: string): string[] ``` The file patterns of a target's own inputs, named inputs expanded, the dependencies' left out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root | | `project` | `ProjectRecord` | The project whose target is read | | `target` | `string` | The target's name | **Returns** `string[]`: The patterns, `{projectRoot}` still unreplaced **Example: Only the project's own side of the inputs is kept** ```typescript // inputs: ['production', '^production', { input: 'default', dependencies: true }] selfInputs(root, project, 'build') // => ['{projectRoot}/**/*', '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)', ...] ``` ##### sha256 ```typescript function sha256(content: string | Buffer): string ``` The sha256 of a text or buffer, as hex. **Parameters** | Name | Type | Description | | --- | --- | --- | | `content` | `string \| Buffer` | What to hash | **Returns** `string`: The hex digest ##### sortEdges ```typescript function sortEdges(edges: unknown): Edge[] ``` The edges in their canonical order, so two graphs built from the same inputs serialise to the same bytes whatever order their edges were found in. **Parameters** | Name | Type | Description | | --- | --- | --- | | `edges` | `unknown` | The edges in any order | **Returns** `Edge[]`: A sorted copy **Example: One order whatever order the edges arrived in** ```typescript const forward = sortEdges(edges) const backward = sortEdges([...edges].reverse()) JSON.stringify(forward) === JSON.stringify(backward) // => true forward === edges // => false, the input is never sorted in place ``` ##### sourcesHash ```typescript function sourcesHash(directory: string): string ``` A hash of the TypeScript sources under a directory, specs and test utilities left out, so the algorithm that wrote a state is named by the code that implements it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The directory, absolute | **Returns** `string`: The hex digest of every source's content, in path order ##### stateDirectory ```typescript function stateDirectory(root: string): string ``` The state directory of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `string`: `/.hf/graph` **Example: Locating one state file** ```typescript join(stateDirectory(root), STATE_FILES.meta) // => '/repo/.hf/graph/meta.json' ``` ##### stateStatus ```typescript function stateStatus(root: string): StateStatus ``` What is persisted and what a build would do, without building. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `StateStatus`: Whether a state is persisted, its meta and digests, and the plan **Example: What a build would do, without doing it** ```typescript const status = stateStatus(root) status.present // => true status.plan // => { mode: 'incremental', reasons: ['2 added', '0 changed', '0 deleted'], added: [...], changed: [], deleted: [], reparse: 2 } status.digests // => { 'files.json': '9f86d0...', 'imports.json': '...', ... } ``` ##### substituteWildcard ```typescript function substituteWildcard(pattern: string, value: string): string ``` A path pattern with its wildcard, the first `*`, standing for a value taken literally. **Parameters** | Name | Type | Description | | --- | --- | --- | | `pattern` | `string` | The pattern, as a tsconfig path alias or target writes it | | `value` | `string` | What the wildcard stands for | **Returns** `string`: The pattern with the value in place of its wildcard, or as is when it has none **Example: Filling the alias target for a wildcard alias** ```typescript substituteWildcard('libs/features/src/*.ts', 'host/open') // => 'libs/features/src/host/open.ts' substituteWildcard('libs/features/src/index.ts', 'host/open') // => 'libs/features/src/index.ts' ``` ##### targetDefaultsFor ```typescript function targetDefaultsFor(root: string, project: ProjectRecord, target: string): TargetDefaults ``` The workspace defaults that apply to a project's target: the entry under the target's name in `hf.json`, when the target is compatible with it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose target is read | | `target` | `string` | The target's name | **Returns** `TargetDefaults`: The defaults, or null when there are none or they do not apply **Example: Defaults that name another executor do not apply** ```typescript // hf.json: { targetDefaults: { build: { executor: '@hyperfrontend/package:build', inputs: ['production'] } } } // project.json: { targets: { build: { executor: '@hyperfrontend/workspace:run-commands', ... } } } targetDefaultsFor(root, project, 'build') // => null targetDefaultsFor(root, project, 'publish') // => null, no entry under that name ``` ##### targetDependsOn ```typescript function targetDependsOn(root: string, project: ProjectRecord, target: string): unknown ``` The tasks a target runs after: the project's own `dependsOn`, else the workspace defaults. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose target is read | | `target` | `string` | The target's name | **Returns** `unknown`: The dependencies as written, none when neither configures any **Example: The project's own `dependsOn` replaces the defaults rather than adding to them** ```typescript // hf.json: { targetDefaults: { build: { dependsOn: ['^build'] } } } // project.json: { targets: { build: { dependsOn: ['lint'] } } } targetDependsOn(root, project, 'build') // => ['lint'] targetDependsOn(root, project, 'test') // => [] ``` ##### targetExecutor ```typescript function targetExecutor(root: string, project: ProjectRecord, target: string): Configured ``` The executor of a target: the project's own, else the workspace defaults. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose target is read | | `target` | `string` | The target's name | **Returns** `Configured`: The executor and where it comes from, or null when neither names one **Example: Finding which file to edit to change a target's executor** ```typescript const executor = targetExecutor(root, project, 'build') // => { value: '@hyperfrontend/package:build', from: 'defaults' } const file = executor?.from === 'project' ? `${project.root}/project.json` : 'hf.json' ``` ##### targetInputs ```typescript function targetInputs(root: string, project: ProjectRecord, target: string): Configured ``` The inputs of a target: the project's own, else the workspace defaults, else Nx's implicit `default` and `^default`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose target is read | | `target` | `string` | The target's name | **Returns** `Configured`: The inputs and where they come from **Example: A target configured without inputs falls back to Nx's implicit pair** ```typescript const graph = workspaceGraph(root) const project = graph.projects.get('lib-features')! targetInputs(root, project, 'typecheck') // => { value: ['default', '^default'], from: 'implicit' } ``` **Example: Telling the project's own inputs from the workspace defaults** ```typescript const { from } = targetInputs(root, project, 'build') if (from === 'defaults') console.log('build inputs come from hf.json') ``` ##### taskId ```typescript function taskId(task: TaskRef): string ``` The id of a task as Nx writes it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `task` | `TaskRef` | The task to identify | **Returns** `string`: `:` **Example: Matching a decision's task against a ref** ```typescript const ref = { kind: 'task', project: 'lib-features', target: 'build' } as const sets.get('build')?.selected.some((decision) => decision.task === taskId(ref)) // => true when lib-features:build is selected ``` ##### taskInputs ```typescript function taskInputs(root: string, project: ProjectRecord, target: string): TaskInputs ``` What a task reads. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `project` | `ProjectRecord` | The project whose task is read | | `target` | `string` | The target's name | **Returns** `TaskInputs`: The own-file filter, the dependency filter, the named projects and the relevant kinds **Example: What a build reads of itself and of its dependencies** ```typescript // inputs: ['production', '^production'] const inputs = taskInputs(root, graph.projects.get('lib-features')!, 'build') inputs.self('libs/features/src/index.spec.ts', 'spec') // => false inputs.reach('libs/features/src/index.ts', 'production') // => true inputs.dependencies?.('libs/nexus')('libs/nexus/src/index.ts', 'production') // => true inputs.kinds.has('type') // => true ``` **Example: A task that reads no dependency input** ```typescript // inputs: ['default'] taskInputs(root, project, 'lint').dependencies // => null ``` **Example: The lint configuration starts the lint closure alone** ```typescript // inputs: ['default', '^production'] for test; lint.config.ts imports the base config, which imports the rules taskInputs(root, project, 'lint').reach('libs/features/lint.config.ts', 'lint-config') // => true taskInputs(root, project, 'test').reach('libs/features/lint.config.ts', 'lint-config') // => false, a test never loads it ``` ##### traceOf ```typescript function traceOf(closure: Closure, path: string): string[] ``` The chain of node ids from a seed of the closure to a file: each file visited, with the entry an edge went through where it did. **Parameters** | Name | Type | Description | | --- | --- | --- | | `closure` | `Closure` | The closure the file was reached in | | `path` | `string` | The reached file | **Returns** `string[]`: The ids, the seed first and the file last **Example: The path an explanation prints** ```typescript const closure = closureOf(graph, ['libs/features/src/index.ts'], ALL_KINDS) traceOf(closure, 'libs/nexus/src/core/registry.ts') // => ['file:libs/features/src/index.ts', 'entry:@hyperfrontend/nexus', 'file:libs/nexus/src/index.ts', 'file:libs/nexus/src/core/registry.ts'] traceOf(closure, 'libs/unrelated/src/index.ts') // => ['file:libs/unrelated/src/index.ts'], a file the closure never reached ``` ##### verifyState ```typescript function verifyState(root: string): Verification ``` Verifies the persisted state against a cold build of the working tree. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `Verification`: Whether every state file agrees, and which do not **Example: A CI check that the committed state matches a cold build** ```typescript const { ok, differences } = verifyState(root) // => { ok: false, differences: ['imports.json'] } when an import changed since the state was written // => { ok: false, differences: ['no persisted state'] } when there is nothing to compare if (!ok) process.exitCode = 1 ``` ##### withLock ```typescript function withLock(directory: string, work: () => Result, options: LockOptions): Result ``` Runs work while holding the directory's lock, taken over from a stale holder and waited for from a live one; the lock is released whether the work returns or throws. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The state directory, created when absent | | `work` | `() => Result` | The work run while the lock is held | | `options` | `LockOptions` | The staleness bound, the wait and the poll interval (default: `{}`) | **Returns** `Result`: What the work returned **Example: Writing under the lock, with a short wait for a tool that must not block** ```typescript const outcome = withLock(stateDirectory(root), () => buildState(root), { timeoutMs: 5_000 }) // throws after 5 s while another live process holds the lock: // the graph state at /repo/.hf/graph is locked by another process // a lock left by a process that died is taken over at once ``` ##### workspaceGraph ```typescript function workspaceGraph(root: string): WorkspaceGraph ``` The graph of a workspace, built on first request. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `WorkspaceGraph`: The graph, the same object on every later request **Example: Asking the graph what a file imports and who owns it** ```typescript import { workspaceGraph } from '@hyperfrontend/workspace/graph' const graph = workspaceGraph(root) graph.projectOf('libs/features/src/index.ts')?.name // => 'lib-features' graph.resolve('libs/features/src/index.ts', '@hyperfrontend/nexus') // => { kind: 'project', project: , file: 'libs/nexus/src/index.ts', path: null } graph.edges.get('lib-features') // => [{ source: 'lib-features', target: 'lib-nexus', type: 'static', files: [...] }] workspaceGraph(root) === graph // => true, built once per root ``` ##### writeStateFile ```typescript function writeStateFile(path: string, text: string): boolean ``` Writes a state file unless it already holds the same text; a process writes its own temporary file and renames it into place, so a reader never sees half a file. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file, absolute | | `text` | `string` | What it should hold | **Returns** `boolean`: True when the file was written, false when it already agreed #### Interfaces ##### AffectedSet The tasks of one target an analysis selected and skipped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly target` | `string` | The target analysed. | | `readonly changes` | `ChangeSet` | The change set analysed. | | `readonly selected` | `unknown` | The tasks selected, sorted by id. | | `readonly skipped` | `unknown` | The tasks skipped, sorted by id, each with the reason it was safe to skip. | | `readonly fallbacks` | `unknown` | The fallback rules that fired while the closures were followed: unresolved loads, dangling imports, parse failures, cycles. | ##### BuildOptions What a build may be given instead of reading it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files?` | `unknown` | The workspace's files, in place of asking git. | | `readonly imports?` | `ImportTable` | The imports of the code files, in place of reading them through the import cache. | ##### BuildOutcome What a build did. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly plan` | `UpdatePlan` | The plan the build followed. | | `readonly written` | `unknown` | The state files whose bytes changed. | | `readonly durationMs` | `number` | How long the build took, in milliseconds. | ##### BuildStateOptions How a build runs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly force?` | `boolean` | Whether to ignore the persisted state and build cold. | ##### BuiltinResolution A specifier naming a Node built-in. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"builtin"` | The resolution's kind. | ##### BuiltState A built state with the graph it describes. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly graph` | `WorkspaceGraph` | The graph. | | `readonly state` | `PersistedState` | The state as written. | | `readonly outcome` | `BuildOutcome` | What the build did. | ##### ChangeSet The files that changed between two revisions. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly base` | `string` | The base revision. | | `readonly head` | `string` | The head revision; the working tree when null. | | `readonly changes` | `unknown` | The changes, sorted by path. | ##### Closure What a set of files reaches. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `ReadonlyMap` | Every reachable file, with how it was reached first. | | `readonly projects` | `ReadonlyMap` | Every project collapsed to project level, with why. | | `readonly touched` | `ReadonlySet` | Every project any file of which is reachable. | | `readonly fallbacks` | `unknown` | The fallbacks that fired. | ##### ConfigNode A configuration file a target reads. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"config"` | The node's kind. | | `readonly path` | `string` | The file, workspace-relative and POSIX. | ##### Configured A target setting with its origin. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly value` | `Value` | The value in force. | | `readonly from` | `SettingSource` | The project's configuration, the workspace defaults, or Nx's implicit default. | ##### DependsOnObject A task dependency written as an object. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly target?` | `string` | The target depended on. | | `readonly projects?` | `string \| unknown` | Whose target: the project's dependencies, named projects, or the project itself when absent. | | `readonly dependencies?` | `boolean` | Whether the dependencies' target is meant. | ##### Edge One edge between two nodes. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending node's id, as `nodeId` writes it. | | `readonly target` | `string` | The depended-on node's id. | | `readonly kind` | `EdgeKind` | What produced the edge. | | `readonly role` | `Role` | The role of the importing or declaring file. | | `readonly path` | `EdgePath` | The specifier and its resolution, or null for an edge no specifier drew. | | `readonly targets` | `unknown` | The targets the edge is relevant to; empty means every target. | | `readonly evidence` | `EdgeEvidence` | Where the edge was drawn. | ##### EdgeGroup The edges between two projects of one kind and one role, grouped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending project. | | `readonly target` | `string` | The project depended on. | | `readonly kind` | `EdgeKind` | What produced the edges. | | `readonly role` | `Role` | The role of the files that drew them. | | `readonly files` | `unknown` | The files of the source that draw the edges, in listing order. | ##### EdgePath The specifier an edge was written with and what it resolved to. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly specifier` | `string` | The specifier as written in the source or configuration. | | `readonly resolved` | `string` | The resolved file, workspace-relative and POSIX, or the package name; null when unresolved. | ##### EntriesBody What the entries state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly entries` | `Readonly>` | Each entry's closure, by entry id. | ##### EntryClosure One entry's reach. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly file` | `string` | The file the entry resolves to. | | `readonly project` | `string` | The project owning the entry. | | `readonly files` | `unknown` | Every file a change of which can reach the entry, sorted. | | `readonly digest` | `string` | The sha256 of the sorted `path hash` lines of those files. | ##### EntryNode An entry point a project exposes: a package name or a package subpath. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"entry"` | The node's kind. | | `readonly id` | `string` | `` or `/`, as consumers import it. | | `readonly project` | `string` | The project that owns the entry. | | `readonly file` | `string` | The file the entry resolves to, workspace-relative and POSIX. | ##### Envelope A state file's content. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly body` | `Body` | The body. | | `readonly digest` | `string` | The sha256 of the body's canonical text. | | `readonly schema` | `string` | The schema the file follows. | ##### ExternalNode An installed npm package. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"external"` | The node's kind. | | `readonly name` | `string` | The package name, scope included. | | `readonly version` | `string` | The installed version, or null when the lock file records none. | ##### Fallback A fallback that fired while the closure was followed. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly edge` | `Edge` | The edge that could not be followed precisely. | | `readonly rule` | `ReasonRule` | The rule that fired. | | `readonly project` | `string` | The project collapsed to project level. | ##### FileChange One changed file. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly status` | `ChangeStatus` | What happened to it. | | `readonly path` | `string` | The path at the head revision, or the deleted path. | | `readonly previousPath` | `string` | The path at the base revision for a rename, else null. | ##### FileImport One import of a file. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly specifier` | `string` | The specifier as written, or the expression's text for an `unresolved` load. | | `readonly dynamic` | `boolean` | Whether Nx counts it as dynamic: an `import()`, a `require` under braces, an import type opening a type alias. | | `readonly kind` | `ImportKind` | The form of the statement. | | `readonly typeOnly` | `boolean` | Whether the statement brings in types alone, so erasing it leaves the runtime unchanged. | | `readonly names` | `unknown` | The names imported or re-exported: `default`, `*` for a namespace, the exported names; empty when unknown or none. | | `readonly line` | `number` | The one-based line of the statement. | | `readonly column` | `number` | The one-based column of the statement. | ##### FileNode A file the workspace tracks. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"file"` | The node's kind. | | `readonly path` | `string` | The path, workspace-relative and POSIX. | | `readonly project` | `string` | The owning project, or null when no project root contains the file. | | `readonly role` | `Role` | The role the file plays in its project. | ##### FileRecord One file and the hash of its content. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly path` | `string` | The path, workspace-relative and POSIX. | | `readonly hash` | `string` | The blob id of the content. | ##### FilesBody What the files state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `unknown` | Every file with its hash, sorted by path. | ##### GraphBody What the graph state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly projects` | `unknown` | The projects, sorted by name. | | `readonly nodes` | `unknown` | Every node, sorted by id. | | `readonly records` | `unknown` | Every qualified edge, in canonical order. | | `readonly edges` | `Readonly>` | The project edges as Nx draws them, by project. | ##### GraphMeta What a state was written by and from. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly schema` | `string` | The schema of the state files. | | `readonly algorithm` | `string` | The algorithm that wrote the state: a hash of the graph sources, or `installed:` of the installed engine. | | `readonly reader` | `string` | The import reader, as `readerVersion` names it. | | `readonly node` | `string` | The Node major the state was written on, kept because the parser can differ. | | `readonly config` | `Readonly>` | The hash of each global configuration file, null for one the workspace lacks. | ##### Hop How a file or project entered the closure. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly from` | `string` | The file whose edge or collapse brought it in, or null for a seed. | | `readonly edge` | `Edge` | The edge followed, or null for a seed or a collapse without one. | | `readonly rule` | `ReasonRule` | The fallback rule that brought it in, or null for an ordinary edge. | ##### ImportRecord What is remembered of one code file's imports. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly hash` | `string` | The hash of the content the imports were read from. | | `readonly imports` | `unknown` | The imports, or null for a file the parser could not read. | ##### ImportsBody What the imports state file holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `Readonly>` | The import record of each code file, by path. | ##### InputObject An input written as an object. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly fileset?` | `string` | A file pattern. | | `readonly input?` | `string` | A named input. | | `readonly dependencies?` | `boolean` | Whether the input is the dependencies' rather than the project's. | | `readonly projects?` | `string \| unknown` | Whose input it is: `self`, `dependencies` or a list of projects. | ##### LockOptions How a lock is taken. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly staleMs?` | `number` | After how many milliseconds a lock counts as stale whatever its holder, 60 s by default. | | `readonly timeoutMs?` | `number` | How long to wait for a live lock before giving up, 60 s by default. | | `readonly pollMs?` | `number` | How long to pause between attempts, 50 ms by default. | ##### NpmResolution A specifier naming an npm package. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"npm"` | The resolution's kind. | | `readonly name` | `string` | The package name, scope included. | ##### NpmUse The npm packages a project's files import. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The package name. | | `readonly files` | `unknown` | The files importing it. | ##### PackageManifest A project's `package.json`, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `string` | The package name. | | `readonly version?` | `string` | The version. | | `readonly private?` | `boolean` | Whether the package is private. | | `readonly keywords?` | `unknown` | The keywords, which become tags. | | `readonly dependencies?` | `Readonly>` | The runtime dependencies. | | `readonly devDependencies?` | `Readonly>` | The development dependencies. | | `readonly peerDependencies?` | `Readonly>` | The peer dependencies. | | `readonly optionalDependencies?` | `Readonly>` | The optional dependencies. | | `readonly exports?` | `unknown` | The exports map. | | `readonly engines?` | `Readonly>` | The engines the package declares, `node` among them. | | `readonly executors?` | `string` | The executors manifest, relative to the package, for a package that implements executors. | | `readonly generators?` | `string` | The generators manifest, relative to the package, for a package that implements generators. | ##### PersistedState The whole persisted state. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `FilesBody` | The files and their hashes. | | `readonly imports` | `ImportsBody` | The imports by path. | | `readonly graph` | `GraphBody` | The graph. | | `readonly entries` | `EntriesBody` | The entry closures. | | `readonly meta` | `GraphMeta` | What wrote the state and from what. | ##### Prerequisite A task another task runs after. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly id` | `string` | `:`. | | `readonly project` | `string` | The project. | | `readonly target` | `string` | The target. | ##### ProjectConfiguration A project's `project.json`, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `string` | The project's name. | | `readonly projectType?` | `string` | `application` or `library`. | | `readonly tags?` | `unknown` | The tags. | | `readonly implicitDependencies?` | `unknown` | The projects this one depends on without importing them. | | `readonly targets?` | `Readonly>` | The targets by name. | | `readonly metadata?` | `Readonly>` | The metadata. | | `readonly sourceRoot?` | `string` | The source root. | | `readonly namedInputs?` | `Readonly>` | The named inputs the project defines for its targets. | ##### ProjectEdge An edge between projects, as Nx draws it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly source` | `string` | The depending project. | | `readonly target` | `string` | The project depended on. | | `readonly type` | `"dynamic" \| "static" \| "implicit"` | `static` for an import, `dynamic` for a dynamic import, `implicit` for a declaration. | | `readonly files` | `unknown` | The files of the source that draw the edge, for an import. | ##### ProjectInput Another project whose files a task names as inputs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly project` | `string` | The project. | | `readonly input` | `string` | The named input evaluated on that project's files. | | `readonly files` | `OwnerFilter` | Which of its files count, given its root. | ##### ProjectNode A project, named as Nx names it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"project"` | The node's kind. | | `readonly name` | `string` | The project's name. | | `readonly root` | `string` | The root, workspace-relative and POSIX; `.` for the workspace itself. | ##### ProjectRecord One project: the data behind a `ProjectNode`. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The name Nx knows it by. | | `readonly root` | `string` | The root, workspace-relative and POSIX; `.` for the workspace itself. | | `readonly type` | `"app" \| "lib"` | `app` or `lib`. | | `readonly tags` | `unknown` | The tags: the manifest's visibility and keywords, then the configuration's. | | `readonly implicitDependencies` | `unknown` | The projects it depends on by declaration. | | `readonly files` | `unknown` | The files it owns, workspace-relative and POSIX, in listing order. | | `readonly manifest` | `PackageManifest` | The manifest, or null when the project has none. | | `readonly configuration` | `ProjectConfiguration` | The configuration, or null when the project has none. | ##### ProjectResolution A specifier naming a workspace project. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"project"` | The resolution's kind. | | `readonly project` | `ProjectRecord` | The project the specifier names. | | `readonly file` | `string` | The file within it, or null when the specifier names a package without a matching entry or a missing file. | | `readonly path` | `string` | The workspace-relative path the specifier named, or null for a package name. | ##### Reason Why a task was selected or skipped. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly rule` | `ReasonRule` | The rule that fired. | | `readonly file` | `string` | The changed file the reason starts from, or null for a reason no file started. | | `readonly path` | `unknown` | The edges followed from the file to the task's project, as `source → target` ids. | | `readonly message` | `string` | One sentence for a reader. | ##### Resolver What the resolver knows of the workspace. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | The workspace root, absolute. | | `readonly files` | `ReadonlySet` | The files, workspace-relative. | | `readonly projects` | `ReadonlyMap` | The projects by name. | | `readonly aliases` | `ReadonlyMap` | The path aliases, from `tsconfig.base.json`, each to its targets. | | `readonly packages` | `ReadonlyMap` | The projects by package name. | | `readonly entries` | `ReadonlyMap` | The entries every project exposes, by id. | ##### SelectOptions What an analysis needs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly graph` | `WorkspaceGraph` | The graph at the head of the change. | | `readonly changes` | `ChangeSet` | The change set. | | `readonly targets` | `unknown` | The targets to decide; a target another depends on is decided as well. | | `readonly previous?` | `WorkspaceGraph` | The graph at the base of the change, which lets a deleted or renamed module name the tasks it reached. | | `readonly previousWorkspace?` | `WorkspaceFile` | The `hf.json` at the base of the change, which lets a change to it select only the tasks that resolve differently afterwards. | | `readonly ignoredInputs?` | `unknown` | Named inputs whose files do not count, by name: the release flow leaves out the engine, which changes what a task does and never what a build emits. An ignored input still names its project, so it still bounds what a tool implemented there reaches. | ##### StateStatus What `status` reports. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly present` | `boolean` | Whether a valid state is persisted. | | `readonly meta` | `GraphMeta` | The persisted meta, or null. | | `readonly digests` | `Readonly>` | The digest of each persisted state file's body, or null. | | `readonly plan` | `StatusPlan` | What a build would do now. | ##### TargetDefaults A target's defaults, as far as they are read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly inputs?` | `unknown` | The inputs. | | `readonly executor?` | `string` | The executor. | | `readonly options?` | `TargetOptions` | The options, as far as they identify a `run-commands` target. | | `readonly dependsOn?` | `unknown` | The tasks the target runs after. | ##### TargetOptions The options that identify what a `run-commands` target runs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly command?` | `string` | The one command of a `run-commands` target. | | `readonly cwd?` | `string` | The directory a `run-commands` target runs from. | | `readonly commands?` | `unknown` | The commands of a `run-commands` target. | ##### TargetRecord A target of a project, as far as the graph reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly executor?` | `string` | The executor, `:`. | | `readonly options?` | `TargetOptions` | The options, as far as they identify a `run-commands` target. | | `readonly inputs?` | `unknown` | The inputs, as `project.json` writes them. | | `readonly dependsOn?` | `unknown` | The tasks this target runs after, as `project.json` writes them. | ##### TaskDecision One task's decision with its reasons. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly task` | `string` | The task's id, `:`. | | `readonly reasons` | `unknown` | The reasons, in the order the rules fired. | ##### TaskInputs What a task reads. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly self` | `FileFilter` | Whether one of the project's own files is an input. | | `readonly reach` | `FileFilter` | Whether one of the project's own files is a start of the task's dependency closure: the inputs, less the lint configuration for a target other than lint. | | `readonly dependencies` | `OwnerFilter` | Which files of the project's dependencies count, given a dependency's root, or null when the task reads no dependency input. | | `readonly projects` | `unknown` | The other projects whose files the task names. | | `readonly kinds` | `ReadonlySet` | The edge kinds that carry a change to the task. | | `readonly key` | `string` | A key identifying the start set, shared by tasks reading the same own files. | ##### TaskRef A task: one target of one project. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"task"` | The node's kind. | | `readonly project` | `string` | The project. | | `readonly target` | `string` | The target. | ##### ToolNode An executor or command a target runs, resolved to the project implementing it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"tool"` | The node's kind. | | `readonly id` | `string` | The executor or command as the target names it, for example `@hyperfrontend/package:build`. | | `readonly project` | `string` | The workspace project implementing it, or null for an installed tool. | | `readonly entry` | `string` | The entry of that project the tool loads, or null when none is known. | ##### UnknownResolution A specifier naming a path no project holds. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly kind` | `"unknown"` | The resolution's kind. | | `readonly path` | `string` | The workspace-relative path the specifier named. | ##### UpdatePlan What a build will do. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly mode` | `UpdateMode` | How much is redone. | | `readonly reasons` | `unknown` | Why: the missing state, the meta keys that differ, or the counts of changed files. | | `readonly added` | `unknown` | The files added since the state was written. | | `readonly changed` | `unknown` | The files whose content changed. | | `readonly deleted` | `unknown` | The files no longer present. | | `readonly reparse` | `unknown` | The code files to parse. | | `readonly reuse` | `ReadonlyMap` | The import records to reuse, by path. | ##### Verification A verification's result. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly ok` | `boolean` | Whether the persisted state equals a cold build. | | `readonly differences` | `unknown` | The state files that differ, or why the comparison could not run. | ##### WorkspaceFile The root `hf.json`, as far as the targets are read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly namedInputs?` | `Readonly>` | The named inputs. | | `readonly targetDefaults?` | `Readonly>` | The defaults of each target. | ##### WorkspaceGraph A workspace's graph. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly files` | `ReadonlySet` | The files, workspace-relative. | | `readonly projects` | `ReadonlyMap` | The projects by name. | | `readonly aliases` | `ReadonlyMap` | The path aliases, from `tsconfig.base.json`, each to its targets. | | `readonly root` | `string` | The workspace root, absolute. | | `readonly edges` | `ReadonlyMap` | The edges by source project, then by target project and type, as Nx draws them. | | `readonly packages` | `ReadonlyMap` | The projects by package name. | | `readonly entries` | `ReadonlyMap` | The entries every project exposes, by id. | | `readonly npmUses` | `ReadonlyMap` | The npm packages each project's files import. | | `readonly versions` | `ReadonlyMap` | The installed version of each top-level package. | | `readonly nested` | `ReadonlySet` | Each `name@version` installed below another package. | | `readonly imports` | `ImportTable` | The imports of each code file, null for a file the parser could not read. | | `readonly nodes` | `ReadonlyMap` | Every node, by id. | | `readonly records` | `unknown` | Every qualified edge, in canonical order. | | `readonly groups` | `ReadonlyMap` | The qualified edges between a project and each node outside it, grouped by kind and role, by source project. | | `readonly projectOf` | `(file: string) => ProjectRecord` | The project owning a file. | | `readonly resolve` | `(from: string, specifier: string) => Resolution` | What a specifier names, seen from a file. | #### Types ##### ChangeStatus One of the change statuses. ```typescript type ChangeStatus = indexedAccess ``` ##### ConfigurationKind What kind of configuration a changed file is. ```typescript type ConfigurationKind = Readonly<{ Configuration: "configuration"; Manifest: "manifest" }> ``` ##### ConfigurationKind One of the configuration kinds. ```typescript type ConfigurationKind = indexedAccess ``` ##### DependsOn A task dependency: `target`, `^target`, or the object form. ```typescript type DependsOn = string | DependsOnObject ``` ##### EdgeEvidence What an edge rests on. ```typescript type EdgeEvidence = SourceEvidence | ConfigurationEvidence ``` ##### EdgeKind One of the edge kinds. ```typescript type EdgeKind = indexedAccess ``` ##### ExplainMode How an affected set is printed. ```typescript type ExplainMode = "tasks" | "explain" ``` ##### FileFilter Whether a file of a given role is an input. ```typescript type FileFilter = (path: string, role: Role) => boolean ``` ##### GraphNode Any node of the graph. ```typescript type GraphNode = ProjectNode | FileNode | EntryNode | ExternalNode | ToolNode | ConfigNode | TaskRef ``` ##### ImportKind One of the import forms. ```typescript type ImportKind = indexedAccess ``` ##### ImportTable The imports of each code file: the list read, or null for a file the parser could not read. ```typescript type ImportTable = ReadonlyMap ``` ##### InputDefinition An input of a target, as `hf.json` and `project.json` write it. ```typescript type InputDefinition = string | InputObject ``` ##### NodeKind One of the node kinds. ```typescript type NodeKind = indexedAccess ``` ##### PrintableProject A project as the state prints it: the record without its manifest and configuration. ```typescript type PrintableProject = Omit ``` ##### ReasonRule One of the reason rules. ```typescript type ReasonRule = indexedAccess ``` ##### Resolution What a specifier names. ```typescript type Resolution = ProjectResolution | NpmResolution | BuiltinResolution | UnknownResolution ``` ##### Role One of the roles. ```typescript type Role = indexedAccess ``` ##### RoleFilter Whether files of a role count. ```typescript type RoleFilter = (role: Role) => boolean ``` ##### SettingSource Where a target setting was configured. ```typescript type SettingSource = "project" | "defaults" | "implicit" ``` ##### StateKey A key of the state. ```typescript type StateKey = unknown ``` ##### UpdateMode One of the update modes. ```typescript type UpdateMode = indexedAccess ``` #### Variables ##### ALL_KINDS Every edge kind. ```typescript const ALL_KINDS: ReadonlySet ``` **Value** `...` ##### ChangeStatus What happened to one file between two revisions. ```typescript const ChangeStatus: Readonly<{ Added: "added"; Deleted: "deleted"; Modified: "modified"; Renamed: "renamed" }> ``` **Value** `...` ##### EdgeKind The kinds of edge, by what produces them. ```typescript const EdgeKind: Readonly<{ Config: "config"; Declared: "declared"; Dynamic: "dynamic"; Manifest: "manifest"; ReExportAll: "re-export-all"; SideEffect: "side-effect"; Tool: "tool"; Type: "type"; Unresolved: "unresolved"; Value: "value" }> ``` **Value** `...` ##### ENGINE_INPUT The named input the workspace file gives the code that runs every task: the runner, the loader hooks and the command line of the engine. A target naming it among its inputs runs when that code changes; the release flow leaves it out, since the engine changes what a task does and never what a build emits. ```typescript const ENGINE_INPUT: "engine" ``` **Value** `'engine'` ##### EXECUTOR_SHARED_INPUT The named input the workspace file gives the helpers every executor of the engine shares: the JSON reader, the logger, and where the workspace resolves a package or writes a build. A task running an executor runs when they change; the release flow leaves them out, since they find tools and read manifests and never shape what a build emits. ```typescript const EXECUTOR_SHARED_INPUT: "executorShared" ``` **Value** `'executorShared'` ##### GLOBAL_CONFIG The files whose change invalidates the whole graph: aliases, externals, inputs. ```typescript const GLOBAL_CONFIG: unknown ``` **Value** `...` ##### ImportKind The forms an import takes, by what the statement brings in; `unresolved` for a load whose specifier is not a literal. ```typescript const ImportKind: Readonly<{ Dynamic: "dynamic"; ReExportAll: "re-export-all"; SideEffect: "side-effect"; Type: "type"; Unresolved: "unresolved"; Value: "value" }> ``` **Value** `...` ##### LINT_COMMAND The command of the inferred `lint` target where `hf.json` names none: the linter's own executable, on the project. ```typescript const LINT_COMMAND: "hf-lint ." ``` **Value** `'hf-lint .'` ##### LOCK_FILE The lock file's name within the state directory. ```typescript const LOCK_FILE: ".lock" ``` **Value** `'.lock'` ##### NodeKind The kinds of node. ```typescript const NodeKind: Readonly<{ Config: "config"; Entry: "entry"; External: "external"; File: "file"; Project: "project"; Task: "task"; Tool: "tool" }> ``` **Value** `...` ##### PRODUCTION_EXCLUSIONS The exclusions of the `production` named input this module implements, written as `hf.json` writes them. A spec compares the list with the workspace's `hf.json`, so an exclusion added there without a matching rule here is noticed rather than silently treated as production. ```typescript const PRODUCTION_EXCLUSIONS: unknown ``` **Value** `...` ##### ReasonRule The closed set of rules an affected decision can rest on. ```typescript const ReasonRule: Readonly<{ ChangedInput: "changed-input"; Cycle: "cycle"; DeclaredDependency: "declared-dependency"; DeletedModule: "deleted-module"; DependencyManifest: "dependency-manifest"; DependentTask: "dependent-task"; ExternalReExport: "external-re-export"; GlobalConfig: "global-config"; KindIrrelevant: "kind-irrelevant"; ParseFailure: "parse-failure"; ProjectConfiguration: "project-configuration"; ReachableFromEntry: "reachable-from-entry"; RenamedModule: "renamed-module"; RoleIrrelevant: "role-irrelevant"; SameResolution: "same-resolution"; SideEffectImport: "side-effect-import"; StateInvalidated: "state-invalidated"; ToolChanged: "tool-changed"; Unreachable: "unreachable"; UnresolvedImport: "unresolved-import" }> ``` **Value** `...` ##### Role The roles a file can play. ```typescript const Role: Readonly<{ Asset: "asset"; BuildConfig: "build-config"; Docs: "docs"; LintConfig: "lint-config"; Production: "production"; Script: "script"; Spec: "spec"; TestConfig: "test-config" }> ``` **Value** `...` ##### RUN_COMMANDS The executor of a target that runs shell commands. The engine runs it itself, so no project implements it. ```typescript const RUN_COMMANDS: "@hyperfrontend/workspace:run-commands" ``` **Value** `'@hyperfrontend/workspace:run-commands'` ##### SCHEMA The shape of the state files; raised when any body's shape changes. ```typescript const SCHEMA: "hf-graph/1" ``` **Value** `'hf-graph/1'` ##### STATE_FILES The state files, by the key of the state they hold. ```typescript const STATE_FILES: Readonly<{ entries: "entries.json"; files: "files.json"; graph: "graph.json"; imports: "imports.json"; meta: "meta.json" }> ``` **Value** `...` ##### TYPE_BLIND_TARGETS The targets that strip types before running, so a type-only import does not reach them. ```typescript const TYPE_BLIND_TARGETS: unknown ``` **Value** `...` ##### UpdateMode How much of a build is redone. ```typescript const UpdateMode: Readonly<{ Cold: "cold"; Incremental: "incremental"; Warm: "warm" }> ``` **Value** `...` ### @hyperfrontend/workspace/hooks The resolution hook that loads a workspace's TypeScript from source: the path aliases of `tsconfig.base.json`, and extensionless relative imports completed the way the compiler does. #### Functions ##### aliasTarget ```typescript function aliasTarget(sources: WorkspaceSources, specifier: string): string ``` The file an alias names. **Parameters** | Name | Type | Description | | --- | --- | --- | | `sources` | `WorkspaceSources` | The workspace whose aliases are read | | `specifier` | `string` | An import specifier | **Returns** `string`: The absolute file the alias maps to, or null when the specifier is no alias ##### completeRelative ```typescript function completeRelative(specifier: string, parentFile: string): string ``` Completes an extensionless relative import the way the compiler does: the file with `.ts` or `.tsx` appended, or the directory's `index.ts`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `specifier` | `string` | The import specifier | | `parentFile` | `string` | The absolute path of the importing file | **Returns** `string`: The completed absolute path, or null when the specifier is not relative, names a file as written, or completes to nothing **Example: The three completions, and the cases the hook leaves to Node** ```typescript const parent = '/repo/libs/features/src/index.ts' completeRelative('./host/open', parent) // => '/repo/libs/features/src/host/open.ts' completeRelative('./host', parent) // => '/repo/libs/features/src/host/index.ts', when host/ is a directory completeRelative('./host/open.ts', parent) // => null, the file exists as written completeRelative('@hyperfrontend/nexus', parent) // => null, not relative ``` ##### formatOf ```typescript function formatOf(root: string, url: string): string ``` The module format of a URL, when this module knows it: workspace TypeScript is always an ES module, which saves Node from parsing each file twice to find out. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `url` | `string` | The module's URL | **Returns** `string`: `module-typescript` for workspace sources, null otherwise ##### homeOf ```typescript function homeOf(directory: string): string ``` The workspace a module of this package lives in as source: the one above its directory, unless the package is installed, when it belongs to no workspace's sources. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The directory of the module, absolute | **Returns** `string`: The workspace root, or null for an installed package or a directory with no workspace above it ##### installAliases ```typescript function installAliases(root: string): void ``` Installs the hooks for a workspace. A workspace installed twice is resolved once, and one installed after another is asked after it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Example: Running a workspace's TypeScript from source** ```bash node --import @hyperfrontend/workspace/hooks tools/scripts/report.ts ``` Importing the module installs the hooks for the workspace above the working directory; call `installAliases` only for a second workspace, which is asked after the first. **Example: Lending a script the aliases of another workspace** ```typescript import { installAliases } from '@hyperfrontend/workspace/hooks' installAliases('/repos/other-workspace') installAliases('/repos/other-workspace') // a second call for the same root changes nothing const { buildGraph } = await import('@other/graph') // an alias of the other workspace's tsconfig.base.json ``` ##### installFrom ```typescript function installFrom(directory: string): void ``` Installs the hooks for the workspace above a directory, when there is one. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | Where to look from, absolute | **Example: Installing for the workspace a file belongs to** ```typescript installFrom(dirname(fileURLToPath(import.meta.url))) // finds the nearest hf.json above this file installFrom('/tmp') // does nothing: no workspace above ``` ##### isWorkspaceSource ```typescript function isWorkspaceSource(root: string, file: string): boolean ``` Whether a file is workspace TypeScript whose relative imports are completed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `file` | `string` | An absolute path | **Returns** `boolean`: True for `.ts` and `.tsx` files inside the workspace and outside `node_modules` ##### readSources ```typescript function readSources(root: string): WorkspaceSources ``` The sources of a workspace. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | **Returns** `WorkspaceSources`: The root with the path aliases of its base tsconfig, none when it has no such file or the file declares none ##### resolveWorkspace ```typescript function resolveWorkspace(sources: WorkspaceSources, specifier: string, parentURL: string): string ``` Resolves one specifier the way the hook does. **Parameters** | Name | Type | Description | | --- | --- | --- | | `sources` | `WorkspaceSources` | The workspace whose sources are resolved | | `specifier` | `string` | The import specifier | | `parentURL` | `string` | The importing module's URL, when there is one | **Returns** `string`: The file URL to load, or null when the hook has nothing to say **Example: An alias resolves from anywhere, a relative import only from workspace TypeScript** ```typescript const sources = readSources('/repo') resolveWorkspace(sources, '@hyperfrontend/nexus', undefined) // => 'file:///repo/libs/nexus/src/index.ts' resolveWorkspace(sources, './host', 'file:///repo/libs/features/src/index.ts') // => 'file:///repo/libs/features/src/host/index.ts' resolveWorkspace(sources, './host', 'file:///repo/node_modules/pkg/index.js') // => null resolveWorkspace(sources, 'typescript', 'file:///repo/libs/features/src/index.ts') // => null, Node resolves it ``` ##### workspaceRootFrom ```typescript function workspaceRootFrom(directory: string): string ``` The workspace root above a directory. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | Where to start, absolute | **Returns** `string`: The nearest directory at or above it that holds the workspace file, or null when none does #### Interfaces ##### WorkspaceSources The sources of one workspace, as the hook resolves them. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | The workspace root, absolute. | | `readonly aliases` | `Readonly>` | The path aliases, each mapped to the source files it names, workspace-relative. | ### @hyperfrontend/workspace/lint The `projects` rule family: lint rules that read the workspace graph, and the readers of a workspace's aliases, project files and module exports that the rules and a workspace's own rules share. #### Functions ##### baseConfigRootOf ```typescript function baseConfigRootOf(directory: string): string ``` The nearest directory at or above another that holds a `tsconfig.base.json`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | Where to start | **Returns** `string`: That directory, or null when none holds the file **Example: Finding the workspace from the file a rule is checking** ```typescript baseConfigRootOf('/repo/libs/features/src/host') // => '/repo' baseConfigRootOf('/tmp') // => null ``` ##### checkedProject ```typescript function checkedProject(path: string, include: unknown): string ``` The project root of a file the rule checks. **Parameters** | Name | Type | Description | | --- | --- | --- | | `path` | `string` | The file's absolute path | | `include` | `unknown` | The selectors of the files checked | **Returns** `string`: The root of the project owning the file, or null when the file is not checked **Example: The default selector against a rule's `include` option** ```typescript checkedProject('/repo/libs/features/project.json', [{ publishableLibraries: true }]) // => '/repo/libs/features' checkedProject('/repo/apps/docs-site/project.json', [{ publishableLibraries: true }]) // => null checkedProject('/repo/apps/docs-site/project.json', [{ files: ['apps/**/project.json'] }]) // => '/repo/apps/docs-site' ``` ##### isNodeProject ```typescript function isNodeProject(root: string): boolean ``` Whether a project runs on Node. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The absolute directory of the project | **Returns** `boolean`: Whether a runtime source of it imports a `node:` module **Example: A spec's `node:` import does not make a browser library a Node project** ```typescript isNodeProject('/repo/libs/workspace') // => true isNodeProject('/repo/libs/features') // => false, even with `import { tmpdir } from 'node:os'` in a *.spec.ts ``` ##### isPublishableLibrary ```typescript function isPublishableLibrary(directory: string): boolean ``` Whether a directory holds a publishable library. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The absolute directory that would hold `project.json` | **Returns** `boolean`: True when the project is a library with `build` and `publish` targets **Example: Gating a rule to publishable libraries** ```typescript const root = projectRootOf(dirname(context.file.path)) if (root === null || !isPublishableLibrary(root)) return {} ``` ##### isPublishableProject ```typescript function isPublishableProject(project: ProjectFile): boolean ``` Whether a project file describes a publishable library: a library with `build` and `publish` targets. **Parameters** | Name | Type | Description | | --- | --- | --- | | `project` | `ProjectFile` | The parsed file | **Returns** `boolean`: True for a publishable library **Example: A library needs both targets** ```typescript isPublishableProject({ projectType: 'library', targets: { build: {}, publish: {} } }) // => true isPublishableProject({ projectType: 'library', targets: { build: {} } }) // => false isPublishableProject({ projectType: 'application', targets: { build: {}, publish: {} } }) // => false isPublishableProject(null) // => false ``` ##### moduleDeclarations ```typescript function moduleDeclarations(file: string): unknown ``` The top-level declarations of a module, in source order; a name exported through a list is marked exported. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | The absolute path | **Returns** `unknown`: The declarations, none when the file is missing or does not parse **Example: A name exported through a list is marked exported** ```typescript // const helper = () => 1 // export const { a, b } = pair // export { helper } moduleDeclarations('/repo/libs/features/src/util.ts').map(({ name, kind, exported }) => ({ name, kind, exported })) // => [{ name: 'helper', kind: 'variable', exported: true }, { name: 'a', kind: 'variable', exported: true }, { name: 'b', kind: 'variable', exported: true }] ``` ##### moduleExports ```typescript function moduleExports(file: string): unknown ``` The names a module exports, with the declaration behind each; `export *` and `export { x } from` are followed, a cycle is cut, and an exported name whose declaration is not found is kept with an unknown kind. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | The absolute path | **Returns** `unknown`: The exports, in the order the module lists them **Example: Following a re-export to the file that declares the name** ```typescript // libs/features/src/index.ts: export { open as openHost } from './host/open' // export * from './types' const exports = moduleExports('/repo/libs/features/src/index.ts') exports.find((item) => item.name === 'openHost') // => { name: 'openHost', kind: 'function', node: , file: '/repo/libs/features/src/host/open.ts' } exports.some((item) => item.name === 'open') // => false, the local name is not exported exports.find((item) => item.name === 'HostOptions')?.kind // => 'interface', brought in by the star re-export ``` ##### parsedModule ```typescript function parsedModule(file: string): Node ``` The program of a source file, parsed once. **Parameters** | Name | Type | Description | | --- | --- | --- | | `file` | `string` | The absolute path | **Returns** `Node`: The program, or null when the file is missing or does not parse **Example: The same program on every call** ```typescript const program = parsedModule('/repo/libs/features/src/index.ts') program?.kind // => 'Program' parsedModule('/repo/libs/features/src/index.ts') === program // => true parsedModule('/repo/libs/features/src/missing.ts') // => null ``` ##### pathAliases ```typescript function pathAliases(workspaceRoot: string): unknown ``` The aliases a workspace's base configuration declares, in declaration order. **Parameters** | Name | Type | Description | | --- | --- | --- | | `workspaceRoot` | `string` | The directory holding `tsconfig.base.json` | **Returns** `unknown`: The aliases, none when the file is missing, unreadable or declares no paths **Example: The first target of each alias, made absolute** ```typescript pathAliases('/repo') // => [ // { alias: '@hyperfrontend/features', source: '/repo/libs/features/src/index.ts' }, // { alias: '@hyperfrontend/features/*', source: '/repo/libs/features/src/*' }, // { alias: '@scope/empty', source: null }, // paths: { '@scope/empty': [] } // ] ``` ##### projectRootOf ```typescript function projectRootOf(directory: string): string ``` The root of the project that owns a directory, as project-scope finds it: the nearest directory with a `project.json`, or a manifest that looks like a project's. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | Where to start | **Returns** `string`: The root, or null **Example: The project, not the workspace, that holds a file** ```typescript projectRootOf('/repo/libs/features/src/host') // => '/repo/libs/features' projectRootOf('/repo/libs/features/e2e/src') // => '/repo/libs/features/e2e', the nearest project.json projectRootOf('/repo/tools') // => '/repo', the workspace is its own project ``` ##### readPackageFile ```typescript function readPackageFile(directory: string): PackageFile ``` Reads a directory's `package.json`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The absolute directory | **Returns** `PackageFile`: The parsed manifest, or null when there is none or it is not an object **Example: The fields are untyped until checked** ```typescript const manifest = readPackageFile('/repo/libs/features') const name = typeof manifest?.name === 'string' ? manifest.name : null // => '@hyperfrontend/features' ``` ##### readProjectFile ```typescript function readProjectFile(directory: string): ProjectFile ``` Reads a directory's `project.json`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | The absolute directory | **Returns** `ProjectFile`: The parsed file, or null when there is none or it is not an object **Example: Reading a target's existence from a rule** ```typescript const project = readProjectFile('/repo/libs/features') project?.name // => 'lib-features' project?.targets?.['publish'] !== undefined // => true readProjectFile('/repo/libs/vendored') // => null, a package.json alone has no project.json ``` ##### resolveModule ```typescript function resolveModule(from: string, specifier: string): string ``` The file a relative specifier names from a module: the written path, the source file of an emitted extension, then the extensions and the index files tried in order. **Parameters** | Name | Type | Description | | --- | --- | --- | | `from` | `string` | The absolute path of the importing module | | `specifier` | `string` | The specifier as written | **Returns** `string`: The absolute path of the file, or null for a bare specifier or a missing file **Example: An emitted extension finds its source first** ```typescript const from = '/repo/libs/features/src/index.ts' resolveModule(from, './host/open.js') // => '/repo/libs/features/src/host/open.ts' resolveModule(from, './host') // => '/repo/libs/features/src/host/index.ts' resolveModule(from, '@hyperfrontend/nexus') // => null, bare specifiers are not resolved here ``` ##### workspaceRootOf ```typescript function workspaceRootOf(directory: string): string ``` The workspace root above a directory, as project-scope finds it: a workspace marker such as `hf.json`, else a manifest declaring workspaces, else the nearest manifest. **Parameters** | Name | Type | Description | | --- | --- | --- | | `directory` | `string` | Where to start | **Returns** `string`: The root, or null **Example: Making a checked file's path workspace-relative** ```typescript const root = workspaceRootOf(dirname(context.file.path)) // => '/repo' relative(root!, context.file.path) // => 'libs/features/src/index.ts' workspaceRootOf('/tmp') // => null ``` #### Interfaces ##### CommandLinesOptions The rule's options. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly include?` | `unknown` | The project files checked; replaces the default of every publishable library. | ##### Declaration A top-level declaration of a module. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The declared name. | | `readonly kind` | `DeclarationKind` | What kind of thing it declares. | | `readonly node` | `Node` | The declaring node, or null when the name is only known to exist. | | `readonly file` | `string` | The absolute path of the file holding the declaration. | | `readonly exported` | `boolean` | Whether the file exports it under that name. | ##### DependencyChecksOptions The rule's options. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly ignoredDependencies?` | `unknown` | Packages never reported. | | `readonly ignoredFiles?` | `unknown` | File patterns whose imports are not counted, `{projectRoot}` standing for the project's root. | ##### DependencyConstraint A tag constraint. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly sourceTag` | `string` | The tag of the projects the constraint governs. | | `readonly onlyDependOnLibsWithTags?` | `unknown` | The tags at least one of which every imported project must carry; none means no tagged project. | ##### ModuleBoundariesOptions The rule's options. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly allow?` | `unknown` | Imports never checked: `prefix/**`, `prefix/*`, `prefix/** /suffix` or a regular expression. | | `readonly depConstraints?` | `unknown` | The tag constraints projects must respect. | | `readonly enforceBuildableLibDependency?` | `boolean` | Whether a buildable library may import only buildable libraries. | ##### ModuleExport A name a module exports, with the declaration behind it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The exported name. | | `readonly kind` | `DeclarationKind` | What kind of thing it is. | | `readonly node` | `Node` | The declaring node, or null when the declaration was not found. | | `readonly file` | `string` | The absolute path of the file holding the declaration, or the re-exporting file when unknown. | ##### PackageFile The fields of `package.json` the rules read from disk. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `unknown` | The package name. | | `readonly engines?` | `Readonly>` | The engines the package declares. | | `readonly exports?` | `unknown` | The exports map. | | `readonly description?` | `unknown` | The description. | ##### PathAlias One alias of the base configuration. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly alias` | `string` | The alias as imports write it, such as `@scope/pkg/sub`. | | `readonly source` | `string` | The absolute path of the first file the alias maps to, or null when it maps to none. | ##### ProjectFile The fields of `project.json` the rules read. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name?` | `unknown` | The Nx project name. | | `readonly projectType?` | `unknown` | `library` or `application`. | | `readonly targets?` | `Readonly>` | The targets by name. | | `readonly metadata?` | `Readonly>` | Free-form metadata: compatibility, deploy, lifecycle. | ##### Selector One way a file is selected. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly publishableLibraries?` | `boolean` | Selects every file of a publishable library. | | `readonly files?` | `unknown` | Selects every file matching one of these workspace-relative globs. | #### Types ##### DeclarationKind What kind of thing a declaration is. ```typescript type DeclarationKind = "function" | "class" | "interface" | "type" | "enum" | "variable" | "namespace" | "unknown" ``` #### Variables ##### BASE_CONFIG The file that holds the aliases. ```typescript const BASE_CONFIG: "tsconfig.base.json" ``` **Value** `'tsconfig.base.json'` ##### PROJECTS_FAMILY The rules of the family by name, registered under the prefix `projects` in a configuration: `{ families: { projects: PROJECTS_FAMILY } }`. ```typescript const PROJECTS_FAMILY: RuleFamily ``` **Value** `...` ### @hyperfrontend/workspace/runner The task runner as a library: run one task, plan and run many with their prerequisites, and find the executor or generator a name means. #### Functions ##### generatorNames ```typescript function generatorNames(root: string, projects: ReadonlyMap): string[] ``` Every generator a name could mean, as `:`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `projects` | `ReadonlyMap` | The workspace's projects by name | **Returns** `string[]`: The generators of the workspace's projects, then the engine's own **Example: Listing what `npx hf generate` can run** ```typescript import { discoverProjects, listFiles } from '@hyperfrontend/workspace/graph' import { generatorNames } from '@hyperfrontend/workspace/runner' generatorNames(root, discoverProjects(root, listFiles(root))) // => ['@acme/tooling:component', '@hyperfrontend/workspace:workspace', '@hyperfrontend/workspace:library', ...] ``` ##### loadExecutor ```typescript function loadExecutor(source: ExecutorSource, importModule: ImportModule, executor: string): Promise ``` Imports the module implementing an executor and finds its default export. **Parameters** | Name | Type | Description | | --- | --- | --- | | `source` | `ExecutorSource` | Where the executor lives | | `importModule` | `ImportModule` | Imports a module from its path | | `executor` | `string` | The executor, for the error | **Returns** `Promise`: The executor function **Example: Calling an executor outside a task** ```typescript import { pathToFileURL } from 'node:url' import { loadExecutor, locateExecutor, withDefaults } from '@hyperfrontend/workspace/runner' const source = locateExecutor(root, projects, '@acme/tooling:lint') const lint = await loadExecutor(source, (file) => import(pathToFileURL(file).href), '@acme/tooling:lint') const result = await lint(withDefaults({ fix: true }, source.schema), context) // => whatever the executor answers, { success: true } when it passed ``` ##### loadGenerator ```typescript function loadGenerator(source: GeneratorSource, importModule: ImportModule, written: string): Promise ``` The generator a located module implements. **Parameters** | Name | Type | Description | | --- | --- | --- | | `source` | `GeneratorSource` | Where the generator lives | | `importModule` | `ImportModule` | Imports a module from its absolute path | | `written` | `string` | The generator as the command line names it, for the refusal | **Returns** `Promise`: The module's default export **Example: Loading a generator the runner located** ```typescript import { pathToFileURL } from 'node:url' import { loadGenerator, locateGenerator } from '@hyperfrontend/workspace/runner' const generate = await loadGenerator(locateGenerator(root, projects, 'library'), (file) => import(pathToFileURL(file).href), 'library') await generate(tree, { name: 'data-utils' }) ``` ##### locateExecutor ```typescript function locateExecutor(root: string, projects: ReadonlyMap, executor: string): ExecutorSource ``` Where the executor a target names lives. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `projects` | `ReadonlyMap` | The workspace's projects by name | | `executor` | `string` | The executor, `:` | **Returns** `ExecutorSource`: The module and the options schema **Example: Finding a packaged executor** ```typescript import { discoverProjects, listFiles } from '@hyperfrontend/workspace/graph' import { locateExecutor } from '@hyperfrontend/workspace/runner' const projects = discoverProjects(root, listFiles(root)) locateExecutor(root, projects, '@hyperfrontend/workspace:typecheck') // => { file: '/repo/node_modules/@hyperfrontend/workspace/executors/typecheck/index.js', schema: { properties: { tsConfig: { type: 'string' }, ... } } } ``` **Example: A workspace project stands in front of the installed package of the same name** ```typescript locateExecutor(root, projects, '@acme/tooling:lint') // => { file: '/repo/tools/tooling/src/executors/lint/index.ts', schema: { ... } } while tools/tooling carries @acme/tooling ``` ##### locateGenerator ```typescript function locateGenerator(root: string, projects: ReadonlyMap, written: string): GeneratorSource ``` Where the generator a name means lives. **Parameters** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute | | `projects` | `ReadonlyMap` | The workspace's projects by name | | `written` | `string` | The generator as the command line names it, `` or `:` | **Returns** `GeneratorSource`: The module and the options schema **Example: A bare name prefers the workspace's own generator** ```typescript locateGenerator(root, projects, 'library') // => the library generator of a workspace project that lists one, else { file: '/repo/node_modules/@hyperfrontend/workspace/generators/library/index.js', schema: { ... } } ``` **Example: Naming the package settles it** ```typescript locateGenerator(root, projects, '@hyperfrontend/workspace:library') // => the engine's own, whatever the workspace lists under that name ``` ##### main ```typescript function main(argv: unknown, host: RunHost): Promise ``` The command line: runs the task it names and reports why it could not, when it could not. **Parameters** | Name | Type | Description | | --- | --- | --- | | `argv` | `unknown` | The arguments after the entry, `run : [--name=value ...]` | | `host` | `RunHost` | Where the task runs and what it runs with | **Returns** `Promise`: The exit code: 0 when the task succeeded, 1 otherwise **Example: Reporting a refusal instead of throwing** ```typescript await main(['run', 'lib-core:build:production'], host) // => 1, after writing "hf run lib-core:build:production: lib-core:build:production names the configuration production; targets run without configurations" ``` ##### manySummary ```typescript function manySummary(outcomes: unknown): string[] ``` The summary of a run: one line per task and a count of each ending. **Parameters** | Name | Type | Description | | --- | --- | --- | | `outcomes` | `unknown` | How each task ended | **Returns** `string[]`: The lines **Example: The lines a run ends with** ```typescript manySummary([ { id: 'lib-core:build', status: 'succeeded', durationMs: 1840 }, { id: 'app-shell:build', status: 'skipped', durationMs: 0 }, ]) // => [' succeeded lib-core:build (1.8 s)', ' skipped app-shell:build (0.0 s)', '1 succeeded, 0 failed, 1 skipped'] ``` ##### parseAffectedArgs ```typescript function parseAffectedArgs(argv: unknown): AffectedRequest ``` Reads the command line of `affected`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `argv` | `unknown` | The arguments after `affected` | **Returns** `AffectedRequest`: The request **Example: The working tree against `origin/main` unless told otherwise** ```typescript parseAffectedArgs(['-t', 'test']) // => { targets: ['test'], base: 'origin/main', head: null, args: [] } parseAffectedArgs(['-t', 'test', '--base=v1.2.0', '--head', 'HEAD']) // => { targets: ['test'], base: 'v1.2.0', head: 'HEAD', args: [] } ``` ##### parseManyArgs ```typescript function parseManyArgs(argv: unknown): ManyRequest ``` Reads the command line of `run-many`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `argv` | `unknown` | The arguments after `run-many` | **Returns** `ManyRequest`: The request **Example: Everything after the selection reaches the tasks** ```typescript parseManyArgs(['-t', 'build,test', '-p', 'lib-*', '--verbose']) // => { targets: ['build', 'test'], projects: ['lib-*'], args: ['--verbose'] } parseManyArgs(['-t', 'build', '--all']) // => { targets: ['build'], projects: null, args: [] } ``` ##### planMany ```typescript function planMany(graph: WorkspaceGraph, request: ManyRequest): PlannedTask[] ``` Every task to run for a request, each after its prerequisites; a cycle is refused with its path. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The workspace graph | | `request` | `ManyRequest` | The targets and projects asked for | **Returns** `PlannedTask[]`: The tasks in the order they run **Example: The prerequisites come first, unrequested** ```typescript import { workspaceGraph } from '@hyperfrontend/workspace/graph' import { planMany } from '@hyperfrontend/workspace/runner' planMany(workspaceGraph(root), { targets: ['build'], projects: ['app-shell'], args: [] }) // => [ // { id: 'lib-core:build', requested: false, after: [] }, // { id: 'app-shell:build', requested: true, after: ['lib-core:build'] }, // ] ``` ##### planTasks ```typescript function planTasks(graph: WorkspaceGraph, tasks: unknown): PlannedTask[] ``` The given tasks and every task their `dependsOn` reaches, each after its prerequisites, in the order given otherwise; a cycle is refused with its path. **Parameters** | Name | Type | Description | | --- | --- | --- | | `graph` | `WorkspaceGraph` | The workspace graph | | `tasks` | `unknown` | The tasks asked for, each of a project of the graph | **Returns** `PlannedTask[]`: The tasks in the order they run **Example: Planning tasks chosen some other way than by name** ```typescript planTasks(graph, [{ project: 'app-shell', target: 'e2e' }]) // => [ // { id: 'lib-core:build', requested: false, after: [] }, // { id: 'app-shell:build', requested: false, after: ['lib-core:build'] }, // { id: 'app-shell:e2e', requested: true, after: ['app-shell:build'] }, // ] ``` ##### runPlanned ```typescript function runPlanned(tasks: unknown, args: unknown, host: ManyHost): Promise ``` Runs planned tasks one at a time, skipping any whose prerequisite did not succeed. **Parameters** | Name | Type | Description | | --- | --- | --- | | `tasks` | `unknown` | The tasks in order | | `args` | `unknown` | The arguments every requested task receives | | `host` | `ManyHost` | How a task runs, the clock and the output | **Returns** `Promise`: How each task ended, in order **Example: Running the plan in children of this command line** ```typescript import { spawn } from 'node:child_process' import { runPlanned, selfCommand } from '@hyperfrontend/workspace/runner' const outcomes = await runPlanned(tasks, ['--verbose'], { runChild: (id, args) => new Promise((resolve) => { const command = selfCommand(process, ['run', id, ...args]) spawn(command[0] as string, command.slice(1), { stdio: 'inherit' }).on('close', (code) => resolve(code ?? 1)) }), now: Date.now, write: (line) => process.stderr.write(`${line}\n`), }) // => [{ id: 'lib-core:build', status: 'failed', durationMs: 1840 }, { id: 'app-shell:build', status: 'skipped', durationMs: 0 }] ``` ##### runTask ```typescript function runTask(id: string, args: unknown, host: RunHost): Promise ``` Runs one task. **Parameters** | Name | Type | Description | | --- | --- | --- | | `id` | `string` | The task, `:` | | `args` | `unknown` | The arguments after the task, `--name=value` or `--name` | | `host` | `RunHost` | Where the task runs and what it runs with | **Returns** `Promise`: True when the task succeeded **Example: Running one task in this process** ```typescript import { spawn } from 'node:child_process' import { pathToFileURL } from 'node:url' import { runTask } from '@hyperfrontend/workspace/runner' const succeeded = await runTask('lib-core:build', ['--clean=false'], { root, cwd: process.cwd(), env: process.env, platform: process.platform, execPath: process.execPath, spawn: (line, options) => spawn(line, options), write: (line) => process.stderr.write(`${line}\n`), importModule: (file) => import(pathToFileURL(file).href), }) // => true when the build executor answered { success: true }; lib-core's dependsOn did not run first ``` ##### selfCommand ```typescript function selfCommand(started: StartedAs, args: unknown): string[] ``` The argument vector that starts this command line again with other arguments. **Parameters** | Name | Type | Description | | --- | --- | --- | | `started` | `StartedAs` | The running process | | `args` | `unknown` | The arguments of the new run | **Returns** `string[]`: The executable, its flags, the entry module and the arguments **Example: Starting a task in a child the way this process was started** ```typescript import { spawn } from 'node:child_process' import { selfCommand } from '@hyperfrontend/workspace/runner' const [program, ...args] = selfCommand(process, ['run', 'lib-core:build']) // => ['/usr/bin/node', '--import=tsx', '/repo/node_modules/@hyperfrontend/workspace/bin/hf.mjs', 'run', 'lib-core:build'] spawn(program as string, args, { stdio: 'inherit' }) ``` ##### withDefaults ```typescript function withDefaults(options: Readonly>, schema: ExecutorSchema): Record ``` Options with the defaults of their schema filled in where they are unset. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `Readonly>` | The options of the target and the command line | | `schema` | `ExecutorSchema` | The executor's options schema | **Returns** `Record`: A copy of the options with the defaults applied **Example: Filling the options a target left unset** ```typescript withDefaults({ tsConfig: 'libs/core/tsconfig.lib.json' }, { properties: { tsConfig: { type: 'string' }, strict: { type: 'boolean', default: true } } }) // => { tsConfig: 'libs/core/tsconfig.lib.json', strict: true } ``` #### Interfaces ##### AffectedRequest The targets asked for over a change, and the arguments every requested task receives. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly targets` | `unknown` | The targets. | | `readonly base` | `string` | The base revision, `origin/main` when none is named. | | `readonly head` | `string` | The head revision, or null for the working tree. | | `readonly args` | `unknown` | The arguments after the selection, passed to each requested task. | ##### ExecutorContext What an executor is called with besides its options. **Properties** | Name | Type | Description | | --- | --- | --- | | `root` | `string` | The workspace root, absolute. | | `cwd` | `string` | The directory the command line started in. | | `projectName` | `string` | The project the task runs on. | | `targetName` | `string` | The target the task runs. | | `target` | `TargetConfiguration` | The target, merged with its defaults and its tokens replaced. | | `projects` | `Record` | Every project's configuration by name, targets resolved. | | `configuration` | `WorkspaceConfiguration` | The workspace configuration. | ##### ExecutorEntry One executor of an executors manifest. **Properties** | Name | Type | Description | | --- | --- | --- | | `implementation` | `string` | The module whose default export implements it, relative to the manifest. | | `schema` | `string` | The schema of its options, relative to the manifest. | | `description?` | `string` | What it does. | ##### ExecutorResult What an executor answers. **Properties** | Name | Type | Description | | --- | --- | --- | | `success` | `boolean` | Whether the task succeeded. | ##### ExecutorSchema An executor's options schema, as far as the runner reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly properties?` | `Readonly>` | The options. | | `readonly required?` | `unknown` | The options a run must give, from the target or the command line. | ##### ExecutorsManifest A package's `executors.json`. **Properties** | Name | Type | Description | | --- | --- | --- | | `executors?` | `Record` | The executors by name. | ##### ExecutorSource Where an executor lives. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly file` | `string` | The module implementing it, absolute. | | `readonly schema` | `ExecutorSchema` | The schema of its options. | ##### GeneratorEntry One generator of a generators manifest. **Properties** | Name | Type | Description | | --- | --- | --- | | `factory` | `string` | The module whose default export implements it, relative to the manifest. | | `schema` | `string` | The schema of its options, relative to the manifest. | | `description?` | `string` | What it does. | ##### GeneratorsManifest A package's `generators.json`. **Properties** | Name | Type | Description | | --- | --- | --- | | `generators?` | `Record` | The generators by name. | ##### GeneratorSource Where a generator lives. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly file` | `string` | The module implementing it, absolute. | | `readonly schema` | `GeneratorSchema` | The schema of its options. | ##### LintSettings The settings of the `lint` target the workspace infers for its projects. **Properties** | Name | Type | Description | | --- | --- | --- | | `command?` | `string` | The command the inferred target runs from a project's root; `{workspaceRoot}` in it is the path from there to the workspace root. Defaults to `hf-lint .`. | | `exclude?` | `string[]` | The project files whose projects get no inferred target, as globs. | ##### ManyHost What running the tasks needs. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly runChild` | `(id: string, args: unknown) => Promise` | Runs one task in a child, with the arguments after it; resolves to the exit code. | | `readonly now` | `() => number` | The current time in milliseconds. | | `readonly write` | `(line: string) => void` | Writes a line to standard error. | ##### ManyRequest The tasks asked for and the arguments every requested task receives. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly targets` | `unknown` | The targets. | | `readonly projects` | `unknown` | The project names and globs, or null for every project. | | `readonly args` | `unknown` | The arguments after the selection, passed to each requested task. | ##### PlannedTask One task to run, in order. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly id` | `string` | `:`. | | `readonly requested` | `boolean` | Whether the task was asked for, rather than reached through `dependsOn`. | | `readonly after` | `unknown` | The tasks it runs after. | ##### ProjectConfiguration A project's configuration, as an executor reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `name?` | `string` | The project's name. | | `root` | `string` | The project's root, workspace-relative and POSIX. | | `sourceRoot?` | `string` | The source root. | | `projectType?` | `"application" \| "library"` | `application` or `library`. | | `tags?` | `string[]` | The tags. | | `implicitDependencies?` | `string[]` | The projects this one depends on without importing them. | | `targets?` | `Record` | The targets by name. | | `metadata?` | `Readonly>` | Free-form metadata. | ##### RunHost Where a task runs and what it runs with. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly cwd` | `string` | The directory the command line started in. | | `readonly importModule` | `ImportModule` | Imports an executor's module. | | `readonly root` | `string` | The workspace root, absolute. | | `readonly env` | `Environment` | The environment the commands start from. | | `readonly platform` | `string` | The platform, which decides how the search path is written. | | `readonly execPath` | `string` | The running Node.js executable, whose directory joins the search path. | | `readonly spawn` | `ShellSpawn` | Starts a command. | | `readonly write` | `(line: string) => void` | Writes a line of the runner's own: the command about to run, or why one failed. | ##### SchemaProperty One option of an executor's schema, as far as the runner reads it. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly type?` | `string` | The JSON type. | | `readonly default?` | `unknown` | The value the option takes when a run leaves it unset. | ##### StartedAs What of a running process names the command line it was started as. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly execPath` | `string` | The Node.js executable. | | `readonly execArgv` | `unknown` | The flags Node.js itself was given. | | `readonly argv` | `unknown` | The argument vector: the executable, the entry module, then the arguments. | ##### TargetConfiguration A target, as `project.json` and the `targetDefaults` of `hf.json` write it. **Properties** | Name | Type | Description | | --- | --- | --- | | `executor?` | `string` | The executor, `:`. | | `command?` | `string` | A shell command, the short form of a `run-commands` target. | | `options?` | `Options` | The options the executor is called with. | | `inputs?` | `unknown` | The inputs whose change selects the target. | | `dependsOn?` | `unknown` | The tasks the target runs after. | | `metadata?` | `Readonly>` | Free-form metadata. | ##### TaskOutcome How one task ended. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly id` | `string` | `:`. | | `readonly status` | `"succeeded" \| "failed" \| "skipped"` | Whether it ran and succeeded, ran and failed, or was skipped after a failed prerequisite. | | `readonly durationMs` | `number` | How long it ran, in milliseconds; 0 when skipped. | ##### TaskRef A task named by its project and target. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly project` | `string` | The project's name. | | `readonly target` | `string` | The target. | ##### WorkspaceConfiguration The workspace configuration, as `hf.json` writes it. **Properties** | Name | Type | Description | | --- | --- | --- | | `targetDefaults?` | `Record` | The defaults of each target, by executor or by target name. | | `namedInputs?` | `Record` | The named inputs. | | `lint?` | `LintSettings` | The inferred `lint` target's settings. | #### Types ##### Executor An executor: the default export of the module an executors manifest names. ```typescript type Executor = (options: Options, context: ExecutorContext) => Promise | ExecutorResult ``` ##### ExecutorFunction An executor: called with the options and the context, it answers a promise of its result. ```typescript type ExecutorFunction = (options: Record, context: ExecutorContext) => unknown ``` ##### ExecutorModule A module as the runner reads it: its exports by name. ```typescript type ExecutorModule = Readonly> ``` ##### ImportModule Imports a module from its absolute path. ```typescript type ImportModule = (file: string) => Promise ``` #### Variables ##### ENGINE_PACKAGE The package whose generators answer to a bare name when no workspace project offers it. ```typescript const ENGINE_PACKAGE: "@hyperfrontend/workspace" ``` **Value** `'@hyperfrontend/workspace'` Also exported here, documented under the entry point that owns each: - `@hyperfrontend/workspace/generators`: `Generator`, `runGenerator`, `Tree`, `TreeChange` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/workspace/ This file: https://www.hyperfrontend.dev/docs/libraries/workspace.md Documentation index: https://www.hyperfrontend.dev/llms.txt