@hyperfrontend/ workspace§
Runs the tasks of a TypeScript monorepo and releases its packages from a graph of what reaches what.
What is @hyperfrontend/workspace?
@hyperfrontend/workspace 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.jsonGenerators 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/linterYour own executors and generators
a TypeScript function and a schema, found through a manifest, run with the same command
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
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 for the test and e2e executors, @hyperfrontend/linter 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:
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 where the repository has no such remote branch, unless --base names another revision. The commands and writing an executor or generator are each one page.
API Overview
| Entry | What it is |
|---|---|
@hyperfrontend/workspace | The contract: the types an executor or generator of your own is written against |
/cli | The command line as a function |
/runner | Executors and generators by name; one task, many in order, the affected run |
/graph | The workspace graph, its persisted state and the affected analysis |
/hooks | Loads a workspace's TypeScript from source, for scripts of your own |
/lint | The projects rule family and the readers a rule of your own shares with it |
/generators | The helpers a local generator composes the packaged ones with; one entry per generator beneath it |
/executors/build 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
Runs on
- Node.js>=24.0.0supported
- Browsersnot supported
- Web Workersnot supported
- Linuxsupported
- macOSsupported
- Windowssupported
Ships as
- ESMTree-shakeable
- CJSNode and older bundlers
- CLIhf
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 covers the graph, the runner and how the entries are loaded by name.
API Reference§
Module Structure
20 modules · 413 total exports
The contract executors and generators are written against: the context an executor runs in, the tree a generator edits, and the configuration both read.
◈ Interfaces
Properties
projects:Record< string, ProjectConfiguration>Every project's configuration by name, targets resolved.Properties
Properties
executors.json.Properties
Properties
generators.json.Properties
lint target the workspace infers for its projects.Properties
Properties
project.json and the targetDefaults of hf.json write it.Properties
Properties
Methods
listChanges( ): TreeChange[ ]read( path: string): Buffer< ArrayBufferLike>Parameters
| Name | Type | Description |
|---|---|---|
§path | string |
write( path: string, content: string | Buffer< ArrayBufferLike>): voidParameters
| Name | Type | Description |
|---|---|---|
§path | string | |
§content | string | Buffer< |
Properties
hf.json writes it.Properties
targetDefaults?:Record< string, TargetConfiguration>The defaults of each target, by executor or by target name.◆ Types
type Executor = ( options: Options, context: ExecutorContext) => Promise< ExecutorResult> | ExecutorResulttype Generator = ( tree: Tree, options: Options) => unknownThe workspace's command line as a function: what the `hf` executable runs, and what another command line hands its arguments to.
ƒ Functions
@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< number>Example
Letting the other command line answer a command this one does not own
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 runParameters
| Name | Type | Description |
|---|---|---|
§word | string | The first argument |
Returns
booleanrun and every command of the tableExample
Deciding which command line answers
isOwnCommand('run-many') // true
isOwnCommand('pack') // false: the features command line is asked, when it is installedParameters
| Name | Type | Description |
|---|---|---|
§entry | string | The package entry that holds the command line(default: FEATURES_CLI) |
Returns
HandoverHostExample
Resolving the features command line from where the command was run
const host = processHost()
host.resolve('/repo/apps/shell') // => '/repo/node_modules/@hyperfrontend/features/cli/index.js', or null when the package is not installedgraph command.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after graph |
§root | string | The workspace root, absolute |
§output | GraphOutput | Where the command writes |
Returns
numberverify finds a difference, 0 otherwiseExamples
The tasks a change selects, explained
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`Checking the persisted graph state in CI
runGraph(['verify'], root, output) // => 1 when a cold build disagrees with the state on diskhf 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< number>Examples
The command line as a function
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 otherwiseAnother `hf` command line passing a command on
const code = await runWorkspaceCli({ argv, cwd, stdout, stderr, handedOver: true })
// => the exit code; an unknown command is reported here rather than passed back◈ Interfaces
Properties
readonly runFeaturesCli:( invocation: Invocation) => Promise< number>Runs the features command line and resolves to its exit code.Properties
Properties
readonly resolve:( cwd: string) => stringThe file of the features command line as a directory resolves it, or null when the package is not installed.Properties
readonly handedOver?:booleanSet by the command line that passed this run on, so it is not passed back.◆ Types
type WorkspaceCliOptions = Invocation● Variables
The `build` executor: builds a library into a publishable package with the builder, treating the workspace's own packages as first-party.
ƒ Functions
Parameters
Returns
AssetSpec[ ]fundingExample
A missing file is skipped, the funding file is conditional
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
BuildConfig from @hyperfrontend/builder/models minus what the executor decides for every workspace (isWorkspacePackage, filterWorkspaceDepsFromOutput, inheritFieldsFrom, thirdPartyLicenses, memoryMonitor).Properties
outputPath?:stringOutput directory, relative to the workspace root. Defaults to dist/<project root>.tsConfig?:stringPath to tsconfig, relative to the workspace root. Defaults to <project root>/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.clean?:booleanEmpty the output directory before emitting. Defaults to enabled; only an empty directory or a previous build of this package is removed.● Variables
Example
A `build` target writing ESM, CommonJS and a browser bundle
{
"targets": {
"build": {
"executor": "@hyperfrontend/workspace:build",
"options": {
"esm": { "bundleWorkspaceDeps": true },
"cjs": { "bundleWorkspaceDeps": true },
"umd": { "entry": ".", "globalName": "AcmeCore" },
"rootAssets": ["LICENSE", "FUNDING.md"]
}
}
}
}
```
Run with `npx hf run lib-core:build`; the package lands in `dist/libs/core` unless `outputPath` says otherwise.funding.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( options: E2eExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
Workflow:
- Run
npm packin the dist directory to create a tarball - Install the tarball in the E2E test project
- Run each configured format's suites on the node test runner (cjs, esm, browser, and the suites the project declares)
- 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< ExecutorResult>Example
An e2e project's target, the library found through `implicitDependencies`
{
"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.Parameters
Returns
FormatRunExample
A built-in format and a declared suite
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( projects: Readonly< Record< string, ProjectConfiguration>>, project: ProjectConfiguration): ProjectConfiguration
Parameters
| Name | Type | Description |
|---|---|---|
§projects | Readonly< | Every project's configuration by name |
§project | ProjectConfiguration | The e2e project |
Returns
ProjectConfigurationExample
The implicit dependency that builds names the library
libraryUnderTest(context.projects, context.projects['e2e-core'])
// => context.projects['lib-core'] when e2e-core lists implicitDependencies: ['lib-core'] and lib-core has a build targetnode_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< string, unknown>Example
Only the runtime's aliases survive
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
Properties
Properties
◆ Types
type E2eFormat = "cjs" | "esm" | "browser" | E2eFormatEntryThe `publish` executor: publishes a library's build output to the npm registry, skipping a version already there.
ƒ Functions
publishExecutor( options: PublishExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
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< ExecutorResult>Example
A `publish` target run after the build
{
"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
Properties
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
Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The workspace root, the project root, the coverage directory and the configuration module |
Returns
Promise< number>testExecutor( options: TestExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
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< ExecutorResult>Example
A `test` target reading the project's `test.config.ts`
{
"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
Properties
● Variables
The `typecheck` executor: runs the TypeScript compiler over a project's library and spec configurations without emitting files.
ƒ Functions
typecheckExecutor( options: TypecheckExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
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< ExecutorResult>Example
A `typecheck` target with the default configurations
{
"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
Properties
tsConfig?:stringPath to the library TypeScript configuration file, relative to the workspace root. Defaults to {projectRoot}/tsconfig.lib.json.specTsConfig?:stringPath to the spec TypeScript configuration file, relative to the workspace root. Defaults to {projectRoot}/tsconfig.spec.json, checked when that file exists.The `version` executor: versions a project from its conventional commits, pins its dependents to the new version, and commits the bump.
ƒ Functions
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< RunVersionResult>Examples
Versioning a project without committing
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(', ')}`)
}Carrying a follow-up's files into the version commit
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 bumpversionExecutor( options: VersionExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
@hyperfrontend/versioning. Key behaviors:
- Uses npm registry as source of truth (not git tags)
- Tags as OUTPUT (created after publish), not INPUT
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< ExecutorResult>Example
A `version` target attributing commits by scope and by file
{
"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
Properties
Properties
projects:Readonly< Record< string, ProjectConfiguration>>Every project of the workspace by name: the ones that pin the package are brought to the new versionmaxCommitFallback?:numberUpper bound on the commit window the flow analyzes for bumps and changelogsfollowUps?:unknownCalled after the bump and before the commit, each answering the files the commit must also carryProperties
Properties
version target configures: the bump, the commit and the tag, and how commits are attributed to the project.Properties
scopeFiltering?:ScopeFilteringConfigScope 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 includeexcludeScopes: Scopes to exclude even if files matchtrackDependencyChanges: Include dependency commits as indirectinfrastructure: Infrastructure path and scope tracking
maxCommitFallback?:numberUpper 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).followUps?:unknownCalled 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
type FollowUp = ( bump: VersionBump, run: FollowUpRun) => unknownThe `version-batch` executor: versions every library a change makes due a release, and records the bumps in one commit.
ƒ Functions
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
Returns
string[ ]Example
The branch behind a remote-tracking base
baseBranches('origin/main', ['origin']) // ['origin/main', 'main']versionBatchExecutor( options: VersionBatchExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
This executor:
- Detects affected libraries programmatically
- Runs versioning for each affected library
- Creates a single batch commit
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< ExecutorResult>Examples
A root project's `version-batch` target
{
"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.Forcing a bump the commits would not have made
npx hf run workspace:version-batch --releaseAs=patch --libraries=lib-core,lib-utils◈ Interfaces
The executor detects affected libraries, versions each one, and creates a single batch commit.
Properties
scopeFiltering?:ScopeFilteringConfigCommit 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?:numberUpper 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?:unknownCalled 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.Properties
The `version-check` executor: compares a project's manifest and changelog with what its commits call for, without writing anything.
ƒ Functions
versionCheckExecutor( options: VersionCheckExecutorOptions, context: ExecutorContext): Promise< ExecutorResult>
This executor is designed for CI validation to verify that:
- The expected version bump (based on conventional commits) has been applied
- The package.json version matches the expected version
- The CHANGELOG.md contains the correct entry for the version
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< ExecutorResult>Example
A `version-check` target sharing the `version` target's attribution
{
"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
version-check target configures: how commits are attributed to the project, and whether the check stands down on a version commit.Properties
scopeFiltering?:ScopeFilteringConfigScope 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 includeexcludeScopes: Scopes to exclude even if files matchtrackDependencyChanges: Include dependency commits as indirectinfrastructure: Infrastructure path and scope tracking
maxCommitFallback?:numberUpper bound on the commit window the flow analyzes for bumps and changelogs.repository?:RepositoryConfig | "inferred" | "disabled" | RepositoryResolutionRepository 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
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
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
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 sortedblockBounds( lines: unknown, opens: ( line: string) => boolean, closes: ( line: string) => boolean, what: string): BlockBounds
Parameters
Returns
BlockBoundsExample
Locating the rules block of a lint configuration
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 foundParameters
| Name | Type | Description |
|---|---|---|
§version | string | A version such as 22.18.0 |
Returns
string.0 segments dropped, 22.18Example
Dropping the trailing zero segments
compactVersion('18.0.0') // '18'
compactVersion('20.10.5') // '20.10.5'.gitignore.Parameters
Returns
IgnoreRule[ ]Example
How the lines of a `.gitignore` are read
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: '' },
// ]Parameters
Returns
numberExample
The search starts where told
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) // => -1Parameters
Returns
Promise< void>Example
The last step of a generator
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( tree: Tree, source: string, target: string, substitutions: Substitutions, options: GenerateFilesOptions): void
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
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 thereParameters
Returns
stringExample
Telling a package from a bare project
getPackageNameFromProject(tree, 'libs/core') // => '@acme/core'
getPackageNameFromProject(tree, 'apps/docs') // => nullReturns
Map< string, ProjectConfiguration>Example
A project the same run created is already there
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@scope/my-lib giving ScopeMyLib.Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
stringExample
The scope becomes part of the global
globalNameOf('@acme/data-utils') // => 'AcmeDataUtils'
globalNameOf('data-utils') // => 'DataUtils'Parameters
| Name | Type | Description |
|---|---|---|
§line | string | One line of the file |
Returns
stringExample
Matching the indentation of a neighbouring line
indentOf(' rules: {') // => ' '
indentOf('\tcommand: "hf-lint .",') // => '\t'
indentOf('export default [') // => ''Parameters
Returns
booleanExample
The last matching rule decides
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 aloneReturns
stringExample
Editing a line and writing the file back byte for byte
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 endingsParameters
| Name | Type | Description |
|---|---|---|
§...fragments | unknown | The parts of the path |
Returns
stringExample
A path fit for a configuration file, whatever the platform
joinPathFragments('libs', 'utils\\data', './package.json') // => 'libs/utils/data/package.json'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
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']Parameters
| Name | Type | Description |
|---|---|---|
§name | string | Any spelling, such as my-lib, myLib or MY_LIB |
Returns
NamesExample
The forms a template reads
names('data-utils')
// => { name: 'data-utils', className: 'DataUtils', propertyName: 'dataUtils', constantName: 'DATA_UTILS', fileName: 'data-utils' }
names('DataUtils').fileName // => 'data-utils'Parameters
| Name | Type | Description |
|---|---|---|
§range | string | An engines range such as >=22.18.0 |
Returns
string22.18.0Example
Reading the floor of an engines range
nodeFloorOf('>=18.0.0') // '18.0.0'
nodeFloorOf('^20.10 || >=22') // '20.10'../ 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 segmentExample
Pointing a project's tsconfig at the base one
`${offsetFromRoot('libs/utils/data')}tsconfig.base.json` // => '../../../tsconfig.base.json'
offsetFromRoot('.') // => './'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
PrettierExample
Formatting a text with the workspace's prettier and configuration
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"Parameters
| Name | Type | Description |
|---|---|---|
§value | string | The text |
Returns
stringExample
Writing a path into TypeScript source
quote('@acme/core') // => "'@acme/core'"
quote("it's") // => "'it\\'s'"
quote('C:\\repo') // => "'C:\\\\repo'"Parameters
Returns
ValueExample
Reading a manifest the tree holds
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.jsonParameters
Returns
PackageJsonInfoExample
A project with and without a manifest
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.jsonReturns
ProjectConfigurationExample
The root a generator writes under
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')package.json of the tree, or nothing when the tree has none.Returns
RootManifestExample
What a new package inherits
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'@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
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.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
stringExample
Dotted paths and the one call a template may make
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<%= expression %> rendered.Parameters
| Name | Type | Description |
|---|---|---|
§template | string | The template text |
§substitutions | Substitutions | The values |
Returns
stringExample
Rendering one template text
renderTemplate('export class <%= names.className %> {}\n', { names: names('data-utils') })
// => 'export class DataUtils {}\n'replaceDescriptionPackageName( json: JsonWithDescription, currentPackageName: string, newPackageName: string): void
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
import type { NamedJson } from '@hyperfrontend/workspace/generators'
import { replaceDescriptionPackageName, updateJson } from '@hyperfrontend/workspace/generators'
updateJson<NamedJson>(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( tree: Tree, written: string, options: Record< string, unknown>, importModule: ImportModule): Promise< void>
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, <name> or <package>:<name> |
§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< void>Example
A workspace generator composing the packaged `library` generator
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 featureLibraryParameters
Returns
string@scope/name, or the name aloneExample
Renaming a package under its current scope
scopedName(scopeOf('@acme/core'), 'kernel') // => '@acme/kernel'
scopedName(undefined, 'kernel') // => 'kernel'Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
string@, or undefined for an unscoped nameExample
Scoped and unscoped names
scopeOf('@acme/core') // => '@acme'
scopeOf('lodash') // => undefinedReturns
Record< string, string[ ]>Example
A stable order for the alias map
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'] }Parameters
| Name | Type | Description |
|---|---|---|
§content | string | The text to split |
Returns
TextLinesExample
The ending is remembered, not normalised
splitLines('a\r\nb\r\n') // => { lines: ['a', 'b', ''], eol: '\r\n' }
splitLines('a\nb') // => { lines: ['a', 'b'], eol: '\n' }Parameters
| Name | Type | Description |
|---|---|---|
§packageName | string | A package name, scoped or not |
Returns
stringExample
The name a directory takes
unscopedName('@acme/core') // => 'core'
unscopedName('lodash') // => 'lodash'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
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/kernelParameters
Example
Adding a target to an existing project
import type { ProjectConfiguration } from '@hyperfrontend/workspace/generators'
import { updateJson } from '@hyperfrontend/workspace/generators'
updateJson<ProjectConfiguration>(tree, 'libs/core/project.json', (json) => {
json.targets = { ...json.targets, docs: { command: 'typedoc' } }
return json
})@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
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 stayimplicitDependencies 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
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 untouchedParameters
| 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
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 aloneParameters
Example
Rewriting every source file of a project
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 visitedParameters
Example
A new project's manifest
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
Properties
Properties
.gitignore, read.Properties
Properties
Properties
Properties
Methods
project.json a generator reads, with the project's name and root settled.Properties
Properties
Properties
package.json as far as the generators read it: what every package of the workspace inherits from it.Properties
Properties
Properties
Methods
listChanges( ): TreeChange[ ]read( path: string): Buffer< ArrayBufferLike>Parameters
| Name | Type | Description |
|---|---|---|
§path | string |
write( path: string, content: string | Buffer< ArrayBufferLike>): voidParameters
| Name | Type | Description |
|---|---|---|
§path | string | |
§content | string | Buffer< |
Properties
Properties
Properties
◆ Types
type Generator = ( tree: Tree, options: Options) => unknown● Variables
The `library` generator: creates a TypeScript library of the workspace, and hands a publishable one to `make-publishable`.
ƒ Functions
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< void>Examples
An internal library
npx hf generate library my-lib --tags=type:utilA publishable library under a chosen directory
npx hf generate library my-utils --directory=libs/utils --publishable --formats=esm,cjs,iife,umdFrom a workspace's own generator, formatting once at the end
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)Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree, whose root manifest gives the default scope |
§options | LibraryGeneratorOptions | The options as given |
Returns
LibraryPlanExample
The names a spelling and the root manifest's scope settle to
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
library generator takes.Properties
scope?:stringThe npm scope of the package, with or without its @; the scope of the root manifest's name when unsetProperties
The `make-publishable` generator: gives a library the targets, manifest fields, README and e2e project a published package needs.
ƒ Functions
makePublishableGenerator( tree: Tree, options: MakePublishableGeneratorOptions): Promise< void>
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< void>Examples
A package in ESM and CommonJS
npx hf generate make-publishable my-libA package with browser bundles under a chosen global
npx hf generate make-publishable my-lib --formats=esm,cjs,iife,umd --globalName=MyLibRe-running on a published library changes nothing it already has
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 keptParameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree the project lives in |
§options | MakePublishableGeneratorOptions | The options as given |
Returns
PublishablePlanExample
The formats fall into the build's order and the e2e names follow the package's
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
make-publishable generator takes.Properties
nodeEngine:stringThe Node.js range chosen, or undefined to keep the package's own or inherit the root's◆ Types
type BundleFormat = "esm" | "cjs" | "iife" | "umd"The `move` generator: relocates a project under another directory and brings its names, aliases and references along.
ƒ Functions
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< void>Examples
Move a library under another directory
npx hf generate move my-utils libs/utilsMove and rename it
npx hf generate move my-utils libs/utils --newName=dataMove it without changing its names
npx hf generate move my-utils libs/utils --updateName=falseParameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree the project lives in |
§options | MoveGeneratorOptions | The options as given |
Returns
MovePlan◈ Interfaces
move generator takes.Properties
projectName?:stringThe project's new name, when the names are updated; the directory's name when unsetpackageName?:stringThe package's new name, when the names are updated; the directory's name under the package's current scope when unsetupdateName?:booleanWhether the project's and the package's names follow the new location; true when unsetProperties
The `rename` generator: renames a project and carries the new name into everything that refers to it.
ƒ Functions
Parameters
| Name | Type | Description |
|---|---|---|
§tree | Tree | The tree the project lives in |
§options | RenameGeneratorOptions | The options as given |
Returns
RenamePlanExample
The package keeps its scope
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',
// }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< void>Examples
Renaming a project from the command line
npx hf generate rename my-utils better-utilsChoosing the package name rather than deriving it
import renameGenerator from '@hyperfrontend/workspace/generators/rename'
await renameGenerator(tree, { project: 'my-utils', newName: 'better-utils', packageName: '@acme/utils' })◈ Interfaces
rename generator takes.Properties
Properties
The `workspace` generator: writes the root configuration the engine reads into a repository that has none.
ƒ Functions
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< void>Examples
Starting a workspace in a repository that has none
npx hf generate workspaceFrom a setup script, over a tree of the repository
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
workspace generator takes.Properties
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
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
stringParameters
Returns
Map< string, string>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
WorkspaceGraphExamples
Building from a file list and imports the caller already holds
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/...'] }, ...]A fresh graph each call, unlike `workspaceGraph`
buildGraph(root) === buildGraph(root) // => falseParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§options | BuildStateOptions | Whether to build cold(default: {}) |
Returns
BuiltStateExamples
An incremental build after one file changed
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 // => 42Forcing a cold build
buildState(root, { force: true }).outcome.plan.mode // => 'cold'Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | Any JSON value |
Returns
stringExample
Key order and whitespace are normalised, array order is kept
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.hfignore leaves out.Parameters
Returns
ChangeSetExamples
The working tree against `main`, untracked files included
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 }, ...]Two commits, as CI frames a pull request
changeSet(root, 'origin/main', 'HEAD').head // => 'HEAD'closureOf( graph: WorkspaceGraph, seeds: Iterable< string>, kinds: ReadonlySet< EdgeKind>): Closure
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
ClosureExamples
What a change can reach from a library's entry
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 wholeType-only edges left out, as a `test` target sees the graph
const kinds = relevantKinds('test')
closureOf(graph, seeds, kinds).files.size <= closureOf(graph, seeds, ALL_KINDS).files.size // => trueReturns
numberExample
Checking that a list of edges is already canonical
const canonical = graph.records.every((edge, index) => index === 0 || compareEdges(graph.records[index - 1]!, edge) <= 0)
// => trueReturns
numberExample
Code-unit order, not locale order
['b', 'B', 'a', 'A'].sort(compareText) // => ['A', 'B', 'a', 'b']
['b', 'B', 'a', 'A'].sort((left, right) => left.localeCompare(right)) // => ['a', 'A', 'b', 'B']Parameters
| Name | Type | Description |
|---|---|---|
§path | string | The path, workspace-relative |
§project | ProjectRecord | The project owning it |
Returns
ConfigurationKindExample
Configuration sits at the project root; a nested tsconfig is a source like any other
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) // => nullParameters
Returns
GraphMetaReturns
string[ ]Example
A reason with and without a path
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']Parameters
| Name | Type | Description |
|---|---|---|
§body | unknown | Any JSON value |
Returns
stringExample
Two writers agree on a digest whatever order they built the body in
digestOf({ files: [{ path: 'a', hash: '1' }], meta: {} }) === digestOf({ meta: {}, files: [{ hash: '1', path: 'a' }] }) // => trueproject.json, and one per directory holding a package.json alone, named by the configuration or the manifest.Parameters
Returns
Map< string, ProjectRecord>Examples
A file belongs to the deepest project above it
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 noneA directory with a `package.json` alone is a project named by the manifest
// libs/vendored/package.json: { "name": "@scope/vendored" }, no project.json
discoverProjects(root, listFiles(root)).get('@scope/vendored')?.configuration // => nullentriesBody( graph: WorkspaceGraph, hashes: ReadonlyMap< string, string>): Record< string, EntryClosure>
Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph whose entries are closed over |
§hashes | ReadonlyMap< | The hash of each file |
Returns
Record< string, EntryClosure>entriesOfProject( project: ProjectRecord, aliases: ReadonlyMap< string, unknown>, files: ReadonlySet< string>): EntryNode[ ]
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[ ]Example
The alias wins where it and `exports` name the same entry
// 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 itParameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph whose entries are closed over |
Example
Which entries a file's change can reach
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']Parameters
| Name | Type | Description |
|---|---|---|
§body | unknown | The body to wrap |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root |
§project | ProjectRecord | The project whose named inputs apply |
§inputs | unknown | The inputs to expand |
Returns
string[ ]{projectRoot} still unreplacedExamples
A name no definition knows is kept as a pattern
// hf.json: { namedInputs: { production: ['default', '!{projectRoot}/**/*.spec.ts'] } }
expandInputs(root, project, ['production', '{workspaceRoot}/tsconfig.base.json'])
// => ['{projectRoot}/**/*', '!{projectRoot}/**/*.spec.ts', '{workspaceRoot}/tsconfig.base.json']A named input that names itself expands once
// hf.json: { namedInputs: { default: ['default', '{workspaceRoot}/hf.json'] } }
expandInputs(root, project, ['default']) // => ['{workspaceRoot}/hf.json']Parameters
| Name | Type | Description |
|---|---|---|
§value | unknown | The value of one exports key |
Returns
stringExample
Conditions are searched in order, nested ones included
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) // => nullproduction 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
Returns
FileFilterExamples
Positive and negative patterns, placed on the project
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 srcAn extended glob the compiler cannot read excludes nothing
fileFilterOf(['{projectRoot}/**/*', '!{projectRoot}/**/+(a|b).ts'], 'libs/features')('libs/features/a.ts', 'production') // => trueParameters
| Name | Type | Description |
|---|---|---|
§files | ReadonlySet< | The workspace's files |
§path | string | The workspace-relative path, POSIX |
Returns
stringExample
An emitted `.js` name finds the TypeScript source behind it
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') // => nullParameters
| Name | Type | Description |
|---|---|---|
§set | AffectedSet | The decisions of one target |
§mode | ExplainMode | The selected ids alone, or the explanation |
Returns
string[ ]Examples
The task ids alone, ready for a runner
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']The full explanation
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-nexusParameters
| Name | Type | Description |
|---|---|---|
§set | AffectedSet | The affected set |
§task | string | The task id, <project>:<target> |
Returns
string[ ]Example
Why one task was skipped
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']Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph serialised |
Returns
GraphBodyParameters
| Name | Type | Description |
|---|---|---|
§records | unknown | The file records |
Returns
Map< string, string>Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectRecord | The project whose targets are read |
§target | string | The target's name |
Returns
booleanExample
Selecting the projects a target can run on
const graph = workspaceGraph(root)
const buildable = [...graph.projects.values()].filter((project) => hasTarget(project, 'build'))Parameters
Returns
HopExample
A file of a collapsed project is reached through the project's hop
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.hfignore lists, compiled.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root |
Returns
Glob[ ]Example
Applying the workspace's ignores to a path of your own
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') // => falseimportsBody( imports: ImportTable, hashes: ReadonlyMap< string, string>): Record< string, ImportRecord>
Parameters
| Name | Type | Description |
|---|---|---|
§imports | ImportTable | The imports by path |
§hashes | ReadonlyMap< | The hash of each file |
Returns
Record< string, ImportRecord>Parameters
Returns
Map< string, unknown>Example
Only code files appear, and a parse failure is recorded as null
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 parseParameters
Returns
FileImport[ ]Examples
Each form an import can take
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 },
// ]A file that does not parse
importsOfText('import {', 'src/broken.ts') // => nullinferLintTargets( root: string, projects: ReadonlyMap< string, ProjectRecord>): Map< string, ProjectRecord>
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< string, ProjectRecord>Example
The target a project gets when it declares none
// 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 oneParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
InstalledPackagesExample
A package installed twice at different versions
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 versionParameters
| Name | Type | Description |
|---|---|---|
§path | string | The workspace-relative path |
Returns
booleanExample
Declaration files count, vendored packages do not
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') // => falserun-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
booleanExample
Two `run-commands` targets are the same target only when they run the same command
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) // => trueParameters
| Name | Type | Description |
|---|---|---|
§path | string | The path, workspace-relative |
Returns
booleanhf.json, the root manifest, the lock file and the base tsconfigExample
Only the root's own files count
isGlobalConfig('package-lock.json') // => true
isGlobalConfig('libs/features/package.json') // => falseParameters
Returns
booleanParameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The graph the projects belong to |
§project | ProjectRecord | A project with an e2e target |
Returns
ProjectRecordExample
The library an e2e project packs
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 buildslint target inferred for a project.Parameters
Returns
stringExample
The workspace root token becomes the way back up from the project
lintCommand('libs/features', 'node {workspaceRoot}/tools/lint/bin/lint.ts .')
// => 'node ../../tools/lint/bin/lint.ts .'
lintCommand('libs/features', 'hf-lint .') // => 'hf-lint .'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
FileRecord[ ]Example
The hash follows the working tree, not the index
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 callParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
string[ ]Example
Untracked files count, ignored and `.hfignore`d ones do not
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/**`Parameters
Returns
string[ ]config:<file>; empty when they agreeExample
Why a build goes cold
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 incrementalReturns
string<kind>:<identity>Example
One id per kind
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'Parameters
| Name | Type | Description |
|---|---|---|
§specifier | string | The bare specifier |
Returns
stringExample
Scoped and unscoped subpaths
packageNameOf('@hyperfrontend/features/host') // => '@hyperfrontend/features'
packageNameOf('typescript/lib/tsserverlibrary') // => 'typescript'packagesOf( workspaces: unknown, projects: ReadonlyMap< string, ProjectRecord>): Map< string, ProjectRecord>
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< string, ProjectRecord>Example
Only projects under a declared workspace glob are importable by package name
import { compileGlob } from '@hyperfrontend/linter/helpers'
const { projects } = workspaceGraph(root)
packagesOf([compileGlob('libs/*')], projects).has('@hyperfrontend/features') // => true
packagesOf([], projects).size // => 0git 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[ ]Example
A rename carries two paths, a copy counts as an addition
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 },
// ]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
UpdatePlanprerequisitesOf( graph: WorkspaceGraph, project: ProjectRecord, target: string): Prerequisite[ ]
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[ ]Examples
The three forms, read against the graph
// 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' },
// ]An object entry is refused rather than skipped
// 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:targetParameters
Returns
WorkspaceGraphExample
Built only when a path was deleted or renamed
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 })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
Returns
WorkspaceFileExample
Read only when the file changed
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 })Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectRecord | The project whose fields are printed |
Returns
PrintableProjectParameters
| Name | Type | Description |
|---|---|---|
§projects | ReadonlyMap< | The projects by name |
§file | string | The workspace-relative path |
Returns
ProjectRecordExample
The deepest root wins, the workspace itself catches the rest
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 // => '.'tsconfig.base.json.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
Map< string, unknown>Example
Every target of an alias is kept, not only the first
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') // => undefinedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
stringExample
The two forms a version takes
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 importsParameters
Returns
FileImport[ ]Example
Bypassing the cache for one file
readImports(root, 'libs/features/src/index.ts')?.map((item) => item.specifier)
// => ['@hyperfrontend/nexus', './host/open', ...]Parameters
| Name | Type | Description |
|---|---|---|
§path | string | The file's absolute path |
Returns
ValueExample
A missing or malformed file reads as null rather than throwing
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": `Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
PersistedStateExample
All five files or nothing
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 nullParameters
| Name | Type | Description |
|---|---|---|
§path | string | The file, absolute |
Returns
Bodyhf.json of a root, read once.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
WorkspaceFileExamples
Reading the defaults of a target
const { targetDefaults, namedInputs } = readWorkspaceFile(root)
targetDefaults?.['build']?.inputs // => ['production', '^production']
namedInputs?.['production'] // => ['default', '!{projectRoot}/**/*.spec.ts', ...]A workspace without an `hf.json`
readWorkspaceFile('/tmp/empty') // => {}type for a target that runs under type stripping.Parameters
| Name | Type | Description |
|---|---|---|
§target | string | The target's name |
Returns
ReadonlySet< EdgeKind>Example
A type-only import never selects a test or lint task
relevantKinds('build').has('type') // => true
relevantKinds('test').has('type') // => false
relevantKinds('lint').has('value') // => trueParameters
Returns
ResolutionExamples
The four kinds a specifier resolves to
const graph = workspaceGraph(root)
const from = 'libs/features/src/index.ts'
resolveSpecifier(graph, from, './host/open') // => { kind: 'project', project: <lib-features>, file: 'libs/features/src/host/open.ts', path: 'libs/features/src/host/open' }
resolveSpecifier(graph, from, '@hyperfrontend/nexus') // => { kind: 'project', project: <lib-nexus>, 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 pathA relative path to a file that does not exist still names its project
const resolution = resolveSpecifier(graph, from, './missing')
if (resolution.kind === 'project') resolution.file // => null, the project is lib-features all the sameproduction exclusions, which leave specs and test and lint configuration out.Parameters
| Name | Type | Description |
|---|---|---|
§patterns | unknown | The expanded patterns |
Returns
RoleFilterExample
The `production` exclusions are read by role, not by pattern
const production = roleFilterOf(expandInputs(root, project, ['production']))
production('production') // => true
production('spec') // => false
production('docs') // => true
roleFilterOf(['{projectRoot}/**/*'])('spec') // => trueParameters
Returns
RoleExample
The roles, as the `production` named input draws the line
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 itParameters
Returns
HopExample
Telling a precise reach from a conservative one
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 preciselyParameters
| Name | Type | Description |
|---|---|---|
§options | SelectOptions | The graph, the changes, the targets and the previous graph |
Returns
Map< string, AffectedSet>Examples
Deciding the tests to run for the working tree against `main`
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 safeA depended-on target is decided as well
// hf.json: { targetDefaults: { test: { dependsOn: ['^build'] } } }
[...selectAffected({ graph, changes, targets: ['test'] }).keys()] // => ['test', 'build']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[ ]{projectRoot} still unreplacedExample
Only the project's own side of the inputs is kept
// inputs: ['production', '^production', { input: 'default', dependencies: true }]
selfInputs(root, project, 'build')
// => ['{projectRoot}/**/*', '!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)', ...]Parameters
| Name | Type | Description |
|---|---|---|
§content | string | Buffer< | What to hash |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§edges | unknown | The edges in any order |
Returns
Edge[ ]Example
One order whatever order the edges arrived in
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 placeParameters
| Name | Type | Description |
|---|---|---|
§directory | string | The directory, absolute |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
string<root>/.hf/graphExample
Locating one state file
join(stateDirectory(root), STATE_FILES.meta) // => '/repo/.hf/graph/meta.json'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
StateStatusExample
What a build would do, without doing it
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': '...', ... }*, standing for a value taken literally.Parameters
Returns
stringExample
Filling the alias target for a wildcard alias
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'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
TargetDefaultsExample
Defaults that name another executor do not apply
// 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 namedependsOn, 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
unknownExample
The project's own `dependsOn` replaces the defaults rather than adding to them
// hf.json: { targetDefaults: { build: { dependsOn: ['^build'] } } }
// project.json: { targets: { build: { dependsOn: ['lint'] } } }
targetDependsOn(root, project, 'build') // => ['lint']
targetDependsOn(root, project, 'test') // => []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< string>Example
Finding which file to edit to change a target's executor
const executor = targetExecutor(root, project, 'build')
// => { value: '@hyperfrontend/package:build', from: 'defaults' }
const file = executor?.from === 'project' ? `${project.root}/project.json` : 'hf.json'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< unknown>Examples
A target configured without inputs falls back to Nx's implicit pair
const graph = workspaceGraph(root)
const project = graph.projects.get('lib-features')!
targetInputs(root, project, 'typecheck')
// => { value: ['default', '^default'], from: 'implicit' }Telling the project's own inputs from the workspace defaults
const { from } = targetInputs(root, project, 'build')
if (from === 'defaults') console.log('build inputs come from hf.json')Returns
string<project>:<target>Example
Matching a decision's task against a ref
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 selectedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§project | ProjectRecord | The project whose task is read |
§target | string | The target's name |
Returns
TaskInputsExamples
What a build reads of itself and of its dependencies
// 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') // => trueA task that reads no dependency input
// inputs: ['default']
taskInputs(root, project, 'lint').dependencies // => nullThe lint configuration starts the lint closure alone
// 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 itParameters
Returns
string[ ]Example
The path an explanation prints
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 reachedParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
VerificationExample
A CI check that the committed state matches a cold build
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 = 1Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | The state directory, created when absent |
§work | ( | The work run while the lock is held |
§options | LockOptions | The staleness bound, the wait and the poll interval(default: {}) |
Returns
ResultExample
Writing under the lock, with a short wait for a tool that must not block
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 onceParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
WorkspaceGraphExample
Asking the graph what a file imports and who owns it
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: <lib-nexus>, 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 rootReturns
boolean◈ Interfaces
Properties
readonly fallbacks:unknownThe fallback rules that fired while the closures were followed: unresolved loads, dangling imports, parse failures, cycles.Properties
readonly imports?:ImportTableThe imports of the code files, in place of reading them through the import cache.Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
readonly from:SettingSourceThe project's configuration, the workspace defaults, or Nx's implicit default.Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
Properties
readonly specifier:stringThe specifier as written, or the expression's text for an unresolved load.readonly dynamic:booleanWhether Nx counts it as dynamic: an import(), a require under braces, an import type opening a type alias.readonly typeOnly:booleanWhether the statement brings in types alone, so erasing it leaves the runtime unchanged.readonly names:unknownThe names imported or re-exported: default, * for a namespace, the exported names; empty when unknown or none.Properties
Properties
Properties
Properties
Properties
readonly algorithm:stringThe algorithm that wrote the state: a hash of the graph sources, or installed:<version> of the installed engine.Properties
Properties
Properties
Properties
Properties
Properties
package.json, as far as the graph reads it.Properties
readonly engines?:Readonly< Record< string, string>>The engines the package declares, node among them.readonly executors?:stringThe executors manifest, relative to the package, for a package that implements executors.readonly generators?:stringThe generators manifest, relative to the package, for a package that implements generators.Properties
Properties
project.json, as far as the graph reads it.Properties
Properties
readonly type:"dynamic" | "static" | "implicit"static for an import, dynamic for a dynamic import, implicit for a declaration.Properties
Properties
ProjectNode.Properties
Properties
readonly file:stringThe file within it, or null when the specifier names a package without a matching entry or a missing file.Properties
readonly path:unknownThe edges followed from the file to the task's project, as source → target ids.Properties
readonly aliases:ReadonlyMap< string, unknown>The path aliases, from tsconfig.base.json, each to its targets.Properties
readonly previous?:WorkspaceGraphThe graph at the base of the change, which lets a deleted or renamed module name the tasks it reached.readonly previousWorkspace?:WorkspaceFileThe hf.json at the base of the change, which lets a change to it select only the tasks that resolve differently afterwards.readonly ignoredInputs?:unknownNamed 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.status reports.Properties
Properties
run-commands target runs.Properties
Properties
Properties
Properties
readonly reach:FileFilterWhether 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:OwnerFilterWhich files of the project's dependencies count, given a dependency's root, or null when the task reads no dependency input.Properties
Properties
readonly id:stringThe executor or command as the target names it, for example @hyperfrontend/package:build.Properties
Properties
readonly reasons:unknownWhy: the missing state, the meta keys that differ, or the counts of changed files.Properties
hf.json, as far as the targets are read.Properties
Properties
readonly aliases:ReadonlyMap< string, unknown>The path aliases, from tsconfig.base.json, each to its targets.readonly edges:ReadonlyMap< string, unknown>The edges by source project, then by target project and type, as Nx draws them.readonly imports:ImportTableThe imports of each code file, null for a file the parser could not read.readonly groups:ReadonlyMap< string, unknown>The qualified edges between a project and each node outside it, grouped by kind and role, by source project.readonly resolve:( from: string, specifier: string) => ResolutionWhat a specifier names, seen from a file.◆ Types
type ConfigurationKind = Readonly< { Configuration: "configuration"; Manifest: "manifest" }>type ConfigurationKind = indexedAccesstarget, ^target, or the object form.type DependsOn = string | DependsOnObjecttype EdgeEvidence = SourceEvidence | ConfigurationEvidencetype FileFilter = ( path: string, role: Role) => booleantype GraphNode = ProjectNode | FileNode | EntryNode | ExternalNode | ToolNode | ConfigNode | TaskReftype ImportTable = ReadonlyMap< string, unknown | null>hf.json and project.json write it.type InputDefinition = string | InputObjecttype PrintableProject = Omit< ProjectRecord, "manifest" | "configuration">type Resolution = ProjectResolution | NpmResolution | BuiltinResolution | UnknownResolutiontype SettingSource = "project" | "defaults" | "implicit"● Variables
unresolved for a load whose specifier is not a literal.lint target where hf.json names none: the linter's own executable, on the project.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.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
Parameters
| Name | Type | Description |
|---|---|---|
§sources | WorkspaceSources | The workspace whose aliases are read |
§specifier | string | An import specifier |
Returns
string.ts or .tsx appended, or the directory's index.ts.Parameters
Returns
stringExample
The three completions, and the cases the hook leaves to Node
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 relativeReturns
stringmodule-typescript for workspace sources, null otherwiseParameters
| Name | Type | Description |
|---|---|---|
§directory | string | The directory of the module, absolute |
Returns
stringParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Examples
Running a workspace's TypeScript from source
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.Lending a script the aliases of another workspace
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.jsonParameters
| Name | Type | Description |
|---|---|---|
§directory | string | Where to look from, absolute |
Example
Installing for the workspace a file belongs to
installFrom(dirname(fileURLToPath(import.meta.url))) // finds the nearest hf.json above this file
installFrom('/tmp') // does nothing: no workspace aboveReturns
boolean.ts and .tsx files inside the workspace and outside node_modulesParameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
Returns
WorkspaceSourcesParameters
| 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
stringExample
An alias resolves from anywhere, a relative import only from workspace 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 itParameters
| Name | Type | Description |
|---|---|---|
§directory | string | Where to start, absolute |
Returns
stringThe `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
tsconfig.base.json.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | Where to start |
Returns
stringExample
Finding the workspace from the file a rule is checking
baseConfigRootOf('/repo/libs/features/src/host') // => '/repo'
baseConfigRootOf('/tmp') // => nullParameters
Returns
stringExample
The default selector against a rule's `include` option
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'Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The absolute directory of the project |
Returns
booleannode: moduleExample
A spec's `node:` import does not make a browser library a Node project
isNodeProject('/repo/libs/workspace') // => true
isNodeProject('/repo/libs/features') // => false, even with `import { tmpdir } from 'node:os'` in a *.spec.tsParameters
| Name | Type | Description |
|---|---|---|
§directory | string | The absolute directory that would hold project.json |
Returns
booleanbuild and publish targetsExample
Gating a rule to publishable libraries
const root = projectRootOf(dirname(context.file.path))
if (root === null || !isPublishableLibrary(root)) return {}build and publish targets.Parameters
| Name | Type | Description |
|---|---|---|
§project | ProjectFile | The parsed file |
Returns
booleanExample
A library needs both targets
isPublishableProject({ projectType: 'library', targets: { build: {}, publish: {} } }) // => true
isPublishableProject({ projectType: 'library', targets: { build: {} } }) // => false
isPublishableProject({ projectType: 'application', targets: { build: {}, publish: {} } }) // => false
isPublishableProject(null) // => falseParameters
| Name | Type | Description |
|---|---|---|
§file | string | The absolute path |
Returns
unknownExample
A name exported through a list is marked exported
// 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 }]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
unknownExample
Following a re-export to the file that declares the name
// 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: <FunctionDeclaration>, 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-exportParameters
| Name | Type | Description |
|---|---|---|
§file | string | The absolute path |
Returns
NodeExample
The same program on every call
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') // => nullParameters
| Name | Type | Description |
|---|---|---|
§workspaceRoot | string | The directory holding tsconfig.base.json |
Returns
unknownExample
The first target of each alias, made absolute
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': [] }
// ]project.json, or a manifest that looks like a project's.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | Where to start |
Returns
stringExample
The project, not the workspace, that holds a file
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 projectpackage.json.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | The absolute directory |
Returns
PackageFileExample
The fields are untyped until checked
const manifest = readPackageFile('/repo/libs/features')
const name = typeof manifest?.name === 'string' ? manifest.name : null // => '@hyperfrontend/features'project.json.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | The absolute directory |
Returns
ProjectFileExample
Reading a target's existence from a rule
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.jsonParameters
Returns
stringExample
An emitted extension finds its source first
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 herehf.json, else a manifest declaring workspaces, else the nearest manifest.Parameters
| Name | Type | Description |
|---|---|---|
§directory | string | Where to start |
Returns
stringExample
Making a checked file's path workspace-relative
const root = workspaceRootOf(dirname(context.file.path)) // => '/repo'
relative(root!, context.file.path) // => 'libs/features/src/index.ts'
workspaceRootOf('/tmp') // => null◈ Interfaces
Properties
readonly include?:unknownThe project files checked; replaces the default of every publishable library.Properties
Properties
Properties
Properties
Properties
package.json the rules read from disk.Properties
Properties
project.json the rules read.Properties
Properties
◆ Types
type DeclarationKind = "function" | "class" | "interface" | "type" | "enum" | "variable" | "namespace" | "unknown"● Variables
projects in a configuration: { families: { projects: PROJECTS_FAMILY } }.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
<package>:<name>.Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The workspace's projects by name |
Returns
string[ ]Example
Listing what `npx hf generate` can run
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( source: ExecutorSource, importModule: ImportModule, executor: string): Promise< ExecutorFunction>
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< ExecutorFunction>Example
Calling an executor outside a task
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 passedloadGenerator( source: GeneratorSource, importModule: ImportModule, written: string): Promise< Generator>
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 |
Example
Loading a generator the runner located
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( root: string, projects: ReadonlyMap< string, ProjectRecord>, executor: string): ExecutorSource
Parameters
| Name | Type | Description |
|---|---|---|
§root | string | The workspace root, absolute |
§projects | ReadonlyMap< | The workspace's projects by name |
§executor | string | The executor, <package>:<name> |
Returns
ExecutorSourceExamples
Finding a packaged executor
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' }, ... } } }A workspace project stands in front of the installed package of the same name
locateExecutor(root, projects, '@acme/tooling:lint')
// => { file: '/repo/tools/tooling/src/executors/lint/index.ts', schema: { ... } } while tools/tooling carries @acme/toolinglocateGenerator( root: string, projects: ReadonlyMap< string, ProjectRecord>, written: string): GeneratorSource
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, <name> or <package>:<name> |
Returns
GeneratorSourceExamples
A bare name prefers the workspace's own generator
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: { ... } }Naming the package settles it
locateGenerator(root, projects, '@hyperfrontend/workspace:library')
// => the engine's own, whatever the workspace lists under that nameParameters
Returns
Promise< number>Example
Reporting a refusal instead of throwing
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"Parameters
| Name | Type | Description |
|---|---|---|
§outcomes | unknown | How each task ended |
Returns
string[ ]Example
The lines a run ends with
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']affected.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after affected |
Returns
AffectedRequestExample
The working tree against `origin/main` unless told otherwise
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: [] }run-many.Parameters
| Name | Type | Description |
|---|---|---|
§argv | unknown | The arguments after run-many |
Returns
ManyRequestExample
Everything after the selection reaches the tasks
parseManyArgs(['-t', 'build,test', '-p', 'lib-*', '--verbose'])
// => { targets: ['build', 'test'], projects: ['lib-*'], args: ['--verbose'] }
parseManyArgs(['-t', 'build', '--all'])
// => { targets: ['build'], projects: null, args: [] }Parameters
| Name | Type | Description |
|---|---|---|
§graph | WorkspaceGraph | The workspace graph |
§request | ManyRequest | The targets and projects asked for |
Returns
PlannedTask[ ]Example
The prerequisites come first, unrequested
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'] },
// ]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[ ]Example
Planning tasks chosen some other way than by name
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'] },
// ]runGenerator( tree: Tree, written: string, options: Record< string, unknown>, importModule: ImportModule): Promise< void>
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, <name> or <package>:<name> |
§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< void>Example
A workspace generator composing the packaged `library` generator
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 featureLibraryParameters
Returns
Promise< TaskOutcome[ ]>Example
Running the plan in children of this command line
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 }]Parameters
Returns
Promise< boolean>Example
Running one task in this process
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 firstParameters
Returns
string[ ]Example
Starting a task in a child the way this process was started
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( options: Readonly< Record< string, unknown>>, schema: ExecutorSchema): Record< string, unknown>
Parameters
| Name | Type | Description |
|---|---|---|
§options | Readonly< | The options of the target and the command line |
§schema | ExecutorSchema | The executor's options schema |
Returns
Record< string, unknown>Example
Filling the options a target left unset
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
Properties
Properties
projects:Record< string, ProjectConfiguration>Every project's configuration by name, targets resolved.Properties
Properties
Properties
executors.json.Properties
Properties
Properties
generators.json.Properties
Properties
lint target the workspace infers for its projects.Properties
Properties
Properties
Properties
Properties
Properties
readonly write:( line: string) => voidWrites a line of the runner's own: the command about to run, or why one failed.Properties
Properties
project.json and the targetDefaults of hf.json write it.Properties
Properties
Properties
Methods
listChanges( ): TreeChange[ ]read( path: string): Buffer< ArrayBufferLike>Parameters
| Name | Type | Description |
|---|---|---|
§path | string |
write( path: string, content: string | Buffer< ArrayBufferLike>): voidParameters
| Name | Type | Description |
|---|---|---|
§path | string | |
§content | string | Buffer< |
Properties
hf.json writes it.Properties
targetDefaults?:Record< string, TargetConfiguration>The defaults of each target, by executor or by target name.◆ Types
type Executor = ( options: Options, context: ExecutorContext) => Promise< ExecutorResult> | ExecutorResulttype ExecutorFunction = ( options: Record< string, unknown>, context: ExecutorContext) => unknowntype Generator = ( tree: Tree, options: Options) => unknowntype ImportModule = ( file: string) => Promise< ExecutorModule>● Variables
Related reading§
- Architecture
Architecture
How @hyperfrontend/workspace is put together, and why.
- How-to
How to add your own executor and generator to a workspace
A workspace needs checks and scaffolding particular to its own repository, and wants them run with the same command as the packaged targets rather than as loose scripts.
- How-to
How to release libraries from their commits
Versions and changelogs written by hand drift from what the commits changed, and nothing stops a push whose versions are wrong.
- Tutorial
Set up a monorepo and test only what changed
A repository of several TypeScript libraries runs every test on every change, because nothing knows which libraries a change actually reaches.
- Getting started
Getting Started
Set HyperFrontend up and embed a first feature.
- Architecture
Architecture Guide
How the packages fit together.

