@hyperfrontend/builder/package/json

json

package.json synthesis primitives — read, inherit, filter, generate exports, resolve CDN paths, synthesize the dist manifest, and write it to disk.

The subdomain ships as small, single-purpose primitives so wrappers can compose only the steps they need: readProjectPackageJson, inheritFields for selective field copy, filterWorkspaceDepsFromOutput to strip workspace-internal entries, generateExportsFromFormats to align the published exports map with the bundle-phase outputs, getCdnPaths for unpkg/jsdelivr resolution, and writeOutputPackageJson for the final emit. synthesizePackageJson is the facade that wires all of them together.

API Reference

ƒ Functions

§function

filterBundledDepsFromOutput(pkg: PackageJson, bundledDeps: string[]): PackageJson

Returns a new PackageJson with bundled-dep entries stripped from dependencies.
When the dist contains pre-passed copies under _dependencies/<dep>/, those packages are no longer transitive runtime requirements — consumers get them inside the tarball. Removing them from the published dependencies field keeps the manifest honest.
If filtering empties the dependencies map, the field is removed entirely.

Parameters

NameTypeDescription
§pkg
PackageJson
Source PackageJson to filter.
§bundledDeps
string[]
Bundled-dep package names (typically BuildContext.bundledDeps).

Returns

PackageJson
Filtered PackageJson clone.

Example

Stripping bundled deps from the published dependencies map

const filtered = filterBundledDepsFromOutput(srcPkg, ['rollup', 'postject'])
§function

filterWorkspaceDepsFromOutput(pkg: PackageJson, isWorkspacePackage: IsWorkspacePackagePredicate): PackageJson

Returns a new PackageJson with workspace-internal entries stripped from dependencies. peerDependencies and optionalDependencies are preserved verbatim so consumers retain optional integrations.
If filtering empties the dependencies map, the field is removed from the returned object instead of left as {}.

Parameters

NameTypeDescription
§pkg
PackageJson
Source PackageJson to filter.
§isWorkspacePackage
IsWorkspacePackagePredicate
Predicate returning true for workspace-internal packages.

Returns

PackageJson
Filtered PackageJson clone.

Example

Stripping `@hyperfrontend/*` deps before publishing

const filtered = filterWorkspaceDepsFromOutput(srcPkg, byPrefix('@hyperfrontend/'))
§function

generateExportsFromFormats(discovery: EntryPointDiscovery, formatOutputs: FormatOutputs, srcPkg?: PackageJson): Record<string, ExportValue>

Generates the published exports field by aligning the source package.json declaration with the actual format outputs the bundle phase produced.
Strategy is source-exports first: every key declared on srcPkg.exports is mapped to a conditional export entry built from the formats that actually landed for the matching subpath. Internal modules that were built but not advertised in the source exports map are intentionally omitted from the published output.
If srcPkg has no exports field, falls back to a single root-entry export synthesized from discovery.hasRootEntry.
IIFE / UMD CDN bundles are not advertised in exports; they are reached solely through the unpkg/jsdelivr fields (see getCdnPaths).

Parameters

NameTypeDescription
§discovery
EntryPointDiscovery
Entry-point discovery result produced earlier in the pipeline.
§formatOutputs
FormatOutputs
Aggregated outputs collected by the bundle phase.
§srcPkg?
PackageJson
Source package.json whose exports map drives advertised subpaths.

Returns

Record<string, ExportValue>
A new exports map suitable for the published package.json.

Example

Generating exports honoring source aliases

const exports = generateExportsFromFormats(discovery, formatOutputs, srcPkg)
§function

getCdnPaths(formatOutputs: FormatOutputs, opts?: CdnPathOverrides): CdnPaths

Computes the CDN entry paths advertised on the published package.json.
Priority order:
  1. Explicit opts.unpkg / opts.jsdelivr overrides win for their respective field.
  2. The first UMD bundle, when one was emitted, supplies the default path.
  3. The first IIFE bundle is used when no UMD bundle exists.
  4. When no UMD or IIFE bundles were produced, returns undefined so callers can
skip emitting the fields entirely.

Parameters

NameTypeDescription
§formatOutputs
FormatOutputs
Aggregated bundle-phase output.
§opts?
CdnPathOverrides
Optional explicit overrides for either CDN field.

Returns

CdnPaths
Resolved CDN paths or undefined when no CDN-eligible bundle was produced.

Example

Resolving CDN paths from a UMD-only build

const cdn = getCdnPaths(formatOutputs)
// → { unpkg: './bundle/index.umd.min.js', jsdelivr: './bundle/index.umd.min.js' }
§function

inheritFields(target: PackageJson, spec?: InheritFromSpec): PackageJson

Returns a new PackageJson with the requested top-level fields copied from the source described by spec onto target.
The merge is intentionally shallow: only fields named in spec.fields are considered, and the original target value wins when the source field is missing or undefined. The function is a no-op (returns target unchanged) when spec is omitted, and silently returns target when the source file does not exist on disk.

Parameters

NameTypeDescription
§target
PackageJson
Package.json being assembled for the published artifact.
§spec?
InheritFromSpec
Optional inheritance specification: source path + field names to copy.

Returns

PackageJson
A new PackageJson with inherited fields applied.

Example

Inheriting `repository`, `bugs`, and `author` from the workspace root

const merged = inheritFields(srcPkg, {
  from: '/abs/repo/package.json',
  fields: ['repository', 'bugs', 'author'],
})
§function

readProjectPackageJson(projectRoot: string): PackageJson

Reads and parses the project's package.json from the given project root.
The file is required to exist; missing files surface as the standard FS_NOT_FOUND filesystem error from project-scope.

Parameters

NameTypeDescription
§projectRoot
string
Absolute path to the project root containing package.json.

Returns

PackageJson
Parsed package.json contents typed as PackageJson.

Example

Reading the source package.json before synthesizing the dist version

const srcPkg = readProjectPackageJson('/abs/libs/foo')
console.log(srcPkg.name)
§function

reflectFilesAllowlist(outputPath: string): string[]

Reflects a materialized publishable output tree into a package.json#files allowlist.
Derives files from what the build actually emitted: the two index globs cover every entrypoint index./index.d.ts at any depth, and every surviving non-index file is named explicitly by its package-root-relative POSIX path (no <dir>/ buckets). Run after every emit phase and the orphan-prune so the walk sees exactly the tree that ships; the allowlist is then correct by construction.
The root package.json is skipped (npm always includes it) and index.
files are skipped (covered by the glob); metadata files (README, LICENSE, THIRD_PARTY_LICENSES, …) are picked up by the walk only when present.
The sorted positive entries are followed by JS_MAP_EXCLUDE_GLOB — a trailing negation that subtracts any JS sourcemap the index glob would otherwise ship. It must come last (npm resolves files last-match-wins), so it is appended after the sort rather than folded into the sorted set.

Parameters

NameTypeDescription
§outputPath
string
Absolute path to the materialized publishable output root.

Returns

string[]
Sorted, deduped positive allowlist entries, then the trailing JS-map exclusion, for package.json#files.

Example

Reflecting a built library's output tree

const files = reflectFilesAllowlist(ctx.outputPath)
// => the two index globs, then 'README.md', 'models.d.ts', 'bin/hf-build.js', …, '!**/*.js.map'
§function

synthesizePackageJson(srcPkg: PackageJson, ctx: BuildContext, formatOutputs: FormatOutputs, opts?: SynthesizePackageJsonOptions): PackageJson

Composes the published package.json from the source manifest, the bundle-phase outputs, and caller-supplied options.
Pipeline order is: filter workspace deps → apply inherited fields → assemble the new manifest with sideEffects: false, the regenerated exports map, and resolved main / module / types pointers; CDN fields are appended only when a UMD or IIFE bundle was emitted; the bin field is synthesized from the supplied bin declarations using deterministic naming rules; the files allowlist is forwarded verbatim when supplied.
Root-pointers (main, module, types) are removed entirely when the library has no root entry, so consumers cannot resolve a non-existent default.

Parameters

NameTypeDescription
§srcPkg
PackageJson
Source package.json parsed from the project root.
§ctx
BuildContext
Resolved build context (used for the entry-point discovery shape).
§formatOutputs
FormatOutputs
Aggregated outputs collected by the bundle phase.
§opts?
SynthesizePackageJsonOptions
Inheritance / filter / CDN-override / bin / files toggles.

Returns

PackageJson
The fully assembled PackageJson ready to be written to the dist root.

Example

Synthesizing the dist package.json for a library with workspace inlining

const distPkg = synthesizePackageJson(srcPkg, ctx, formatOutputs, {
  inheritFieldsFrom: { from: '/abs/repo/package.json', fields: ['repository', 'bugs'] },
  filterWorkspaceDepsFromOutput: true,
  isWorkspacePackage: (n) => n.startsWith('@hyperfrontend/'),
  bins: [{ name: 'hf-build', format: ['cjs'] }],
  files: ['_dependencies/', 'bin/', 'index.*'],
})
§function

writeOutputPackageJson(outputPath: string, packageJson: PackageJson): void

Writes the synthesized package.json to the build output directory.
The file is emitted with two-space indentation (project-scope's default) and a trailing newline so the published artifact diffs cleanly against formatter-managed source files.

Parameters

NameTypeDescription
§outputPath
string
Absolute path to the output directory (the dist root).
§packageJson
PackageJson
Fully assembled PackageJson to serialize.

Example

Writing the dist package.json

writeOutputPackageJson(ctx.outputPath, distPkg)

Interfaces

§interface

CdnPathOverrides

Optional overrides accepted by getCdnPaths.

Properties

§jsdelivr?:string
Explicit path for the jsdelivr field.
§unpkg?:string
Explicit path for the unpkg field.
§interface

CdnPaths

Resolved CDN paths for unpkg and jsdelivr package.json fields.

Properties

§jsdelivr:string
Path advertised on the jsdelivr field.
§unpkg:string
Path advertised on the unpkg field.
§interface

SynthesizePackageJsonOptions

Options consumed by synthesizePackageJson.

Properties

§bins?:BinConfig[]
Bin declarations from the build config; drives package.json#bin synthesis.
§files?:string[]
Allowlist for package.json#files; emitted verbatim when non-empty.
§filterWorkspaceDepsFromOutput?:boolean
Strip workspace-internal entries from the output dependencies map.
§inheritFieldsFrom?:InheritFromSpec
Selectively copy fields from another package.json onto the output.
§isWorkspacePackage?:IsWorkspacePackagePredicate
Predicate identifying workspace-internal packages; required when filtering is enabled.
§jsdelivr?:string
Override path for the jsdelivr field.
§unpkg?:string
Override path for the unpkg field.