Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

refactor: rebuild the domain-neutral language host

kashorindb4e545d1ea5
diff --git a/packages/validation/README.md b/packages/admission/README.md
similarity index 79%
rename from packages/validation/README.md
rename to packages/admission/README.md
index a7c45fae..6acd6b28 100644
--- a/packages/validation/README.md
+++ b/packages/admission/README.md
@@ -1,10 +1,10 @@
-# `@hypit/validation`
+# `@hypit/admission`
Host side semantic validation for package owned types.
Core checks nominal type connections. A component package may additionally register one pure
validator for an exact `TypeRef`. The compiler applies that validator to authored and provided
-values; `NodeDriver` applies it to component and endpoint results before offering them to Core.
+values; `Executor` applies it to component and endpoint results before offering them to Core.
Validators only accept or reject. They cannot rewrite a value, create graph edges, select an
endpoint, read credentials or add author intent. The registry executes trusted installed handlers
diff --git a/packages/validation/package.json b/packages/admission/package.json
similarity index 66%
rename from packages/validation/package.json
rename to packages/admission/package.json
index 7a908132..c3a843dc 100644
--- a/packages/validation/package.json
+++ b/packages/admission/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/validation",
+ "name": "@hypit/admission",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
@@ -8,8 +8,8 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/component-kit": "workspace:*",
- "@hypit/core": "workspace:*",
+ "@hypit/facet": "workspace:*",
+ "@hypit/kernel": "workspace:*",
"@hypit/protocol": "workspace:*"
}
}
diff --git a/packages/validation/src/index.ts b/packages/admission/src/index.ts
similarity index 62%
rename from packages/validation/src/index.ts
rename to packages/admission/src/index.ts
index c79b180b..7a7246ed 100644
--- a/packages/validation/src/index.ts
+++ b/packages/admission/src/index.ts
@@ -1,18 +1,66 @@
import {
resolveType,
verifyRecordStructure,
-} from "@hypit/core";
-import type {
- TypeValidatorHandler,
- TypeValidatorRegistrar,
-} from "@hypit/component-kit";
+} from "@hypit/kernel";
+import type { Facet } from "@hypit/facet";
import type { ResolvedModuleClosure, StoredValue, TypeRef, TypedRecord } from "@hypit/protocol";
function typeKey(type: TypeRef): string {
return `${type.module.name}@${type.module.version}#${type.name}`;
}
-export type { TypeValidatorContext, TypeValidatorHandler, TypeValidatorRegistrar } from "@hypit/component-kit";
+export type TypeValidatorContext = {
+ readonly type: TypeRef;
+ readonly value: StoredValue;
+};
+
+export type TypeValidatorHandler = (
+ context: TypeValidatorContext,
+) => void | Promise<void>;
+
+export interface TypeValidatorRegistrar {
+ register(type: TypeRef, handler: TypeValidatorHandler): void;
+}
+
+/** Package-owned semantic validator implementation. */
+export type TypeValidatorFacet = {
+ readonly type: TypeRef;
+ readonly handler: TypeValidatorHandler;
+};
+
+export type AdmissionPackage = {
+ readonly validators?: readonly TypeValidatorFacet[];
+};
+
+export const admissionPackageFacetAbi = "hypit.admission-package@1";
+
+export type AdmissionPackageFacet = Facet & {
+ readonly abi: typeof admissionPackageFacetAbi;
+ readonly implementation: AdmissionPackage;
+};
+
+export function createAdmissionPackageFacet(value: unknown): AdmissionPackageFacet {
+ const item = value !== null && typeof value === "object"
+ ? value as AdmissionPackage
+ : {};
+ return {
+ abi: admissionPackageFacetAbi,
+ implementation: item.validators === undefined ? {} : { validators: item.validators },
+ };
+}
+
+export function admissionPackagesFromFacets(facets: readonly Facet[]): readonly AdmissionPackage[] {
+ return facets.flatMap((facet) => facet.abi === admissionPackageFacetAbi
+ ? [(facet as AdmissionPackageFacet).implementation]
+ : []);
+}
+
+export function registerTypeValidatorFacets(
+ registry: TypeValidatorRegistrar,
+ facets: readonly TypeValidatorFacet[],
+): void {
+ for (const facet of facets) registry.register(facet.type, facet.handler);
+}
export type TypeValidatorRegistration = {
readonly handler: TypeValidatorHandler;
diff --git a/packages/artifact/src/activation.ts b/packages/artifact/src/activation.ts
deleted file mode 100644
index d39b8925..00000000
--- a/packages/artifact/src/activation.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { artifactManifest } from "./index.js";
-
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- modules: [{ manifest: artifactManifest }],
-};
-
-export default hypitPackage;
diff --git a/packages/artifact/src/index.ts b/packages/artifact/src/index.ts
deleted file mode 100644
index 36c7f966..00000000
--- a/packages/artifact/src/index.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type {
- ModuleManifest,
- TypeRef,
-} from "@hypit/protocol";
-
-export const artifactModuleRef = { name: "@hypit/artifact", version: "1" } as const;
-
-export const artifactTypes = {
- blob: { module: artifactModuleRef, name: "BlobArtifact" },
-} satisfies Record<string, TypeRef>;
-
-export const artifactManifest: ModuleManifest = {
- format: "hypit.module@1",
- name: artifactModuleRef.name,
- version: artifactModuleRef.version,
- dependencies: [],
- types: [{ name: artifactTypes.blob.name }],
- capabilities: [],
- producers: [],
-};
-
-export const artifactDependency = {
- module: artifactModuleRef,
-} as const;
diff --git a/packages/file-io-node/README.md b/packages/atomic-file/README.md
similarity index 98%
rename from packages/file-io-node/README.md
rename to packages/atomic-file/README.md
index 857fcd97..b3d63261 100644
--- a/packages/file-io-node/README.md
+++ b/packages/atomic-file/README.md
@@ -1,4 +1,4 @@
-# `@hypit/file-io-node`
+# `@hypit/atomic-file`
Node filesystem operations shared by file-backed adapters. This package has no knowledge of
credentials, Build Results, Runtime or repository formats.
diff --git a/packages/file-io-node/package.json b/packages/atomic-file/package.json
similarity index 85%
rename from packages/file-io-node/package.json
rename to packages/atomic-file/package.json
index e8f1306d..bb9af1f8 100644
--- a/packages/file-io-node/package.json
+++ b/packages/atomic-file/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/file-io-node",
+ "name": "@hypit/atomic-file",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
diff --git a/packages/file-io-node/src/index.ts b/packages/atomic-file/src/index.ts
similarity index 100%
rename from packages/file-io-node/src/index.ts
rename to packages/atomic-file/src/index.ts
diff --git a/packages/file-io-node/src/replace-file-windows.ts b/packages/atomic-file/src/replace-file-windows.ts
similarity index 100%
rename from packages/file-io-node/src/replace-file-windows.ts
rename to packages/atomic-file/src/replace-file-windows.ts
diff --git a/packages/file-io-node/src/replace-file.ts b/packages/atomic-file/src/replace-file.ts
similarity index 100%
rename from packages/file-io-node/src/replace-file.ts
rename to packages/atomic-file/src/replace-file.ts
diff --git a/packages/file-io-node/test/replace-file.test.ts b/packages/atomic-file/test/replace-file.test.ts
similarity index 100%
rename from packages/file-io-node/test/replace-file.test.ts
rename to packages/atomic-file/test/replace-file.test.ts
diff --git a/packages/author-kit/README.md b/packages/author-kit/README.md
deleted file mode 100644
index 4ad17dc9..00000000
--- a/packages/author-kit/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# `@hypit/hypit/author-kit`
-
-Small public framework API for an Author Package.
-
-It joins four stable authoring boundaries: nominal Module declarations, deterministic component
-handlers, sealed Graph Fragments and Markup Surface handlers. Domain facts still come from their
-owners—for example `@hypit/composition`, `@hypit/timeline` and `@hypit/spatial`. This package
-does not re-export the video vocabulary or turn those packages into one central object.
-
-`@hypit/hypit/author-kit` contains no registry, package search, installer, Runtime, Provider or Studio
-selection. Importing it makes no component visible. A project's Source explicitly selects an
-installed Author Package; the Host then consumes only the contribution exported by that package's
-declared activation entry.
-
-An external Author Package normally has one development dependency on the released `@hypit/hypit`
-Distribution. It imports this boundary from `@hypit/hypit/author-kit` and the relevant domain owners from
-subpaths such as `@hypit/hypit/composition`, compiles its activation to JavaScript, and publishes only its
-own built files and assets. At execution time the active Hypit Distribution supplies those exact
-public subpaths. This keeps one framework implementation in the process and prevents a component
-tarball from carrying private copies of Core.
-
-The Distribution includes the small package example at
-[`examples/minimal-author-package/packages/example-component`](../../examples/minimal-author-package/packages/example-component).
-Copy it into the video's `packages/`, give it the owner's package and Module name, and follow its
-README to select the installed Hypit release as its development dependency. It includes the Manifest,
-Surface, Fragment, Producer, activation, preview and TypeScript build configuration. It can stay in
-the project or be packed and installed in another project without changing its logical Module import.
-
-For a component that follows speech, [Ranking](../ranking/README.md) traces the complete semantic
-path from a Selection or Moment through projection, schedule and drawing to a Studio Companion.
-Its implementation illustrates those relationships; a new component owns its own visual behavior.
diff --git a/packages/author-kit/package.json b/packages/author-kit/package.json
deleted file mode 100644
index 2085337b..00000000
--- a/packages/author-kit/package.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name": "@hypit/author-kit",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/component-kit": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/markup": "workspace:*",
- "@hypit/protocol": "workspace:*"
- }
-}
diff --git a/packages/author-kit/src/index.ts b/packages/author-kit/src/index.ts
deleted file mode 100644
index 23b7455d..00000000
--- a/packages/author-kit/src/index.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Stable framework-facing author-package surface.
- *
- * Domain values stay with their owning packages; this module only joins the small set of framework
- * interfaces needed to declare a Module, lower a Surface into a Fragment and provide deterministic
- * handlers. It performs no discovery, registration, installation or execution.
- */
-export {
- canonicalize,
- isResourceId,
- sameType,
-} from "@hypit/protocol";
-export type {
- BlobRef,
- CanonicalValue,
- ModuleManifest,
- ModuleRef,
- ProducerRef,
- StoredValue,
- TypeRef,
- TypedRecord,
- ValueSchema,
-} from "@hypit/protocol";
-
-export type {
- ComponentPackage,
- ProducerFacet,
- ProducerHandler,
- ProducerHandlerContext,
- ProducerHandlerResult,
- TypeValidatorFacet,
- TypeValidatorHandler,
-} from "@hypit/component-kit";
-
-export {
- sealGraphFragment,
-} from "@hypit/elaborator";
-export type {
- FragmentOperation,
- GraphFragment,
-} from "@hypit/elaborator";
-
-export {
- assertAttributes,
- assertEmptyElement,
- assertExactAttributes,
- createMarkupSurfaceHostFacet,
- localName,
- optionalTextAttribute,
- textAttribute,
-} from "@hypit/markup";
-export type {
- MarkupSurfaceHostFacetOptions,
- StructuredElement,
- StructuredSurfaceHandler,
- SurfaceComponentDraft,
- SurfaceRecordDraft,
- SurfaceResolvedReference,
-} from "@hypit/markup";
diff --git a/packages/elaborator/README.md b/packages/author/README.md
similarity index 69%
rename from packages/elaborator/README.md
rename to packages/author/README.md
index beedadde..e0369958 100644
--- a/packages/elaborator/README.md
+++ b/packages/author/README.md
@@ -1,10 +1,10 @@
-# `@hypit/elaborator`
+# `@hypit/author`
Parser-independent author linking and static Graph Fragment elaboration outside SVML Core.
The package is the optional compilation layer between authored declarations and the domain-free
Kernel. A frontend, API or visual editor first emits one sealed `hypit.author-module@1` containing
-component calls with symbolic Record/Component-output references. The Elaborator then works in two
+component calls with symbolic Record/Component-output references. The Author linker then works in two
phases:
1. lock every referenced Fragment and predeclare every component export;
@@ -20,18 +20,17 @@ The official Markup adapter emits this exact Author Module format. Its separate
integration fixture proves the complete `source → Surface → AuthorModule → Graph → BuildPlan` path;
Markup still does not become a prerequisite for direct API or visual-editor callers.
-The package also provides the domain-neutral recursive Source Closure reference implementation.
-The Host supplies an entry SourceUnit, exact Frontend registry, immutable module closure and a
-Source resolver. Source compilation discovers dependencies before decoding, rejects cycles and
-duplicate aliases, decodes dependencies first, hygienically qualifies private Record/component
-identities and binds only declared public exports into importer namespaces. Host filesystem paths
-are excluded from Source Closure identity; source contents, Frontend digests and written import
-edges remain covered. Every source asset actually requested during decode is also covered by its
-author-written locator and exact Resource `BlobRef`; raw bytes remain a Host transfer
-concern and never enter the parser-independent AuthorModule or Core BuildState.
+The package owns the parser-independent Frontend, Author Module, Source Closure and provenance
+contracts consumed by compilation. `@hypit/compiler` owns recursive discovery and closure
+orchestration: it receives a `ResolvedSource`, exact Frontend registry, immutable module closure and
+Workspace resolver, rejects cycles and duplicate aliases, and decodes dependencies before their
+importers. The Author linker then qualifies private Record/component identities and binds only
+declared public exports into importer namespaces. Workspace paths remain outside Source Closure
+identity; source contents, Frontend digests, written import edges and requested Blob identities stay
+covered without moving raw bytes into AuthorModule or Kernel BuildState.
The same hygienic pass emits an ephemeral `hypit.author-provenance@1` sidecar. A Frontend may retain
-the structural ranges of author elements and inputs; Elaborator qualifies their Record, component,
+the structural ranges of author elements and inputs; the Author linker qualifies their Record, component,
output and endpoint identities together with the graph. This is a compiler result, not a Source
file, lock, digest inventory or editor database. It carries no domain or Studio presentation and
lets any diagnostic/editor join a graph value back to the exact author endpoint without matching a
@@ -40,23 +39,23 @@ local name after compilation.
The orchestration ABI is asynchronous even when a local Text/SVS implementation is synchronous.
This lets a browser, sandbox or remote repository provide SourceUnits without changing the
compilation contract. The Host resolver is the authority for path canonicalization, workspace
-containment, symlink policy and I/O; Elaborator receives bytes and identities but never opens files
+containment, symlink policy and I/O; the Author linker receives bytes and identities but never opens files
or grants filesystem access itself.
Asset resolution follows the same inversion of authority. The decode context exposes only an
-asynchronous `resolveAsset({ from, mediaType })` capability. Elaborator validates the returned
+asynchronous `resolveAsset({ from, mediaType })` capability. The Author linker validates the returned
identity, rejects conflicting media assignments for one written locator and folds the dependency
into Source Closure identity. It does not know whether a Host obtained the bytes from a filesystem,
browser upload, repository object or remote content store.
Frontend output passes a Host-owned Record validation hook before linking. The hook is permitted to
reject a Record but is forbidden to rewrite Record identity, Type or value.
-`@hypit/compiler-node` wires this to `@hypit/validation` by default, so authored
+`@hypit/compiler` wires this to `@hypit/admission` by default, so authored
values use the same Type-owner gate as Producer, Provider and provided Candidate values.
A `hypit.fragment@1` value may reference only declared Fragment inputs and local Operations. It
contains no JavaScript callback, ambient file lookup, credential access or Runtime endpoint. Before
-expansion the Elaborator verifies producer ports, types, cycles, reachable exports and Semantic
+expansion the Author linker verifies producer ports, types, cycles, reachable exports and Semantic
Input Envelopes.
Expansion assigns hygienic identities from `Fragment id + author instance id + local id`.
@@ -69,6 +68,6 @@ edges. The result is ordinary graph data that Core validates again before freezi
does not name an Author Logical Output. Run frontends keep Candidate declaration and the explicit
`output -> candidate` Satisfaction edge separate.
-`@hypit/elaborator` is not a public `@hypit/author` subsystem. It is a reusable graph-construction
-library. A domain normally adds its own contract and component packages; Text remains only one
+`@hypit/author` is a reusable graph-construction owner, not a universal Author SDK facade. A domain
+normally adds its own contract and component packages; Text remains only one
optional frontend capable of producing the same Author Module data.
diff --git a/packages/workspace-fs-node/package.json b/packages/author/package.json
similarity index 50%
rename from packages/workspace-fs-node/package.json
rename to packages/author/package.json
index 2e791916..e46e93b2 100644
--- a/packages/workspace-fs-node/package.json
+++ b/packages/author/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/workspace-fs-node",
+ "name": "@hypit/author",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
@@ -8,8 +8,14 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/workspace": "workspace:*",
+ "@hypit/kernel": "workspace:*",
+ "@hypit/facet": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/source": "workspace:*"
+ },
+ "devDependencies": {
+ "@hypit/composition": "workspace:*",
+ "@hypit/narrative-temporal": "workspace:*",
+ "@hypit/spatial": "workspace:*"
}
}
diff --git a/packages/elaborator/src/author.ts b/packages/author/src/author.ts
similarity index 99%
rename from packages/elaborator/src/author.ts
rename to packages/author/src/author.ts
index 78ca6ef3..55c6a602 100644
--- a/packages/elaborator/src/author.ts
+++ b/packages/author/src/author.ts
@@ -1,7 +1,7 @@
import {
sealCompiledGraph,
verifyCompiledGraph,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
CompiledGraph,
GraphValueRef,
diff --git a/packages/elaborator/src/fragment.ts b/packages/author/src/fragment.ts
similarity index 99%
rename from packages/elaborator/src/fragment.ts
rename to packages/author/src/fragment.ts
index dfa2316e..032abaa3 100644
--- a/packages/elaborator/src/fragment.ts
+++ b/packages/author/src/fragment.ts
@@ -1,6 +1,6 @@
import {
resolveProducer,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
Candidate,
Satisfaction,
diff --git a/packages/author/src/frontend-facet.ts b/packages/author/src/frontend-facet.ts
new file mode 100644
index 00000000..9072e89c
--- /dev/null
+++ b/packages/author/src/frontend-facet.ts
@@ -0,0 +1,30 @@
+import {
+ createFrontendFacet,
+ frontendsFromFacets,
+} from "@hypit/facet";
+import type {
+ FrontendFacet,
+ Facet,
+} from "@hypit/facet";
+import { sourceFrontendPackageAbi } from "@hypit/source";
+
+import type { AuthorFrontend } from "./source.js";
+
+export type AuthorFrontendFacet = FrontendFacet<"author", AuthorFrontend> & {
+ readonly abi: typeof sourceFrontendPackageAbi;
+};
+
+export function createAuthorFrontendFacet(frontend: AuthorFrontend): AuthorFrontendFacet {
+ return createFrontendFacet(sourceFrontendPackageAbi, "author", frontend) as AuthorFrontendFacet;
+}
+
+export function authorFrontendsFromFacets(facets: readonly Facet[]): readonly AuthorFrontend[] {
+ return frontendsFromFacets<"author", AuthorFrontend>(sourceFrontendPackageAbi, "author", facets);
+}
+
+export function installAuthorFrontendFacets(
+ facets: readonly Facet[],
+ registry: { register(frontend: AuthorFrontend): void },
+): void {
+ for (const frontend of authorFrontendsFromFacets(facets)) registry.register(frontend);
+}
diff --git a/packages/elaborator/src/index.ts b/packages/author/src/index.ts
similarity index 85%
rename from packages/elaborator/src/index.ts
rename to packages/author/src/index.ts
index 40562f65..b2efb823 100644
--- a/packages/elaborator/src/index.ts
+++ b/packages/author/src/index.ts
@@ -11,18 +11,16 @@ export type {
GraphFragmentResolver,
} from "./author.js";
export {
+ AuthorFrontendError,
AuthorFrontendRegistry,
- SourceClosureError,
- compileSourceClosure,
- prepareAuthorSource,
resolveCompiledSourceExport,
} from "./source.js";
export {
- authorFrontendsFromHostFacets,
- createAuthorFrontendHostFacet,
- installAuthorFrontendHostFacets,
+ authorFrontendsFromFacets,
+ createAuthorFrontendFacet,
+ installAuthorFrontendFacets,
} from "./frontend-facet.js";
-export type { AuthorFrontendHostFacet } from "./frontend-facet.js";
+export type { AuthorFrontendFacet } from "./frontend-facet.js";
export type {
AuthorFrontend,
AuthorElementProvenance,
@@ -43,7 +41,6 @@ export type {
AuthorSourceUnit,
AuthorRecordAdmitter,
Awaitable,
- CompileSourceClosureRequest,
CompiledSourceClosure,
CompiledSourceExport,
DecodedAuthorSource,
diff --git a/packages/author/src/source.ts b/packages/author/src/source.ts
new file mode 100644
index 00000000..c174e484
--- /dev/null
+++ b/packages/author/src/source.ts
@@ -0,0 +1,207 @@
+import type {
+ CompiledGraph,
+ GraphValueRef,
+ LinkedProgram,
+ ResolvedModuleClosure,
+ TypeRef,
+ TypedRecord,
+} from "@hypit/protocol";
+import type {
+ ResolvedSourceAsset,
+ SourceAssetRequest,
+ SourceAssetResolver,
+ SourceImportRequest,
+ SourceResolver,
+ SourceUnit,
+} from "@hypit/source";
+
+import type { AuthorComponent, AuthorValueRef } from "./author.js";
+import type { GraphFragment } from "./fragment.js";
+
+export type AuthorSourceUnit = SourceUnit;
+export type AuthorFrontendSourceUnit = AuthorSourceUnit;
+export type AuthorSourceImport = SourceImportRequest;
+
+export type AuthorSourceDiscovery = {
+ readonly modules: readonly string[];
+ readonly sources: readonly AuthorSourceImport[];
+};
+
+export type AuthorSourceAssetRequest = SourceAssetRequest;
+export type ResolvedAuthorSourceAsset = ResolvedSourceAsset;
+export type AuthorSourceResolver = SourceResolver;
+export type AuthorSourceAssetResolver = SourceAssetResolver;
+
+export type AuthorSourceExport = {
+ readonly name: string;
+ readonly ref: AuthorValueRef;
+ readonly type: TypeRef;
+};
+
+export type AuthorSourceIdentity = {
+ readonly namespace: TypeRef;
+ readonly id: string;
+};
+
+export type AuthorInputProvenanceDraft = {
+ readonly name: string;
+ readonly range: import("@hypit/protocol").SourceRange;
+ readonly kind: "literal" | "reference";
+ readonly ref?: AuthorValueRef;
+};
+
+export type AuthorElementProvenanceDraft = {
+ readonly range: import("@hypit/protocol").SourceRange;
+ readonly records: readonly string[];
+ readonly components: readonly string[];
+ readonly outputs: readonly { readonly component: string; readonly name: string; readonly id: string }[];
+ readonly inputs: readonly AuthorInputProvenanceDraft[];
+};
+
+export type ResolvedAuthorSourceImport = {
+ readonly request: AuthorSourceImport;
+ readonly source: string;
+ readonly exports: readonly AuthorSourceExport[];
+ readonly records: readonly TypedRecord[];
+};
+
+export type Awaitable<T> = T | Promise<T>;
+
+export type AuthorSourceDecodeContext = {
+ readonly closure: ResolvedModuleClosure;
+ readonly imports: readonly ResolvedAuthorSourceImport[];
+ readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<ResolvedAuthorSourceAsset>;
+};
+
+export type DecodedAuthorSource = {
+ readonly records: readonly TypedRecord[];
+ readonly components: readonly AuthorComponent[];
+ readonly fragments: readonly GraphFragment[];
+ readonly exports: readonly AuthorSourceExport[];
+ readonly identities?: readonly AuthorSourceIdentity[];
+ readonly provenance?: readonly AuthorElementProvenanceDraft[];
+};
+
+export type AuthorFrontend = {
+ readonly id: string;
+ discover(source: AuthorFrontendSourceUnit): Awaitable<AuthorSourceDiscovery>;
+ decode(source: AuthorFrontendSourceUnit, context: AuthorSourceDecodeContext): Awaitable<DecodedAuthorSource>;
+};
+
+export interface AuthorFrontendRegistryLike {
+ resolve(id: string): AuthorFrontend | undefined;
+}
+
+export class AuthorFrontendError extends Error {
+ readonly code: string;
+ readonly subject: string | undefined;
+
+ constructor(code: string, message: string, subject?: string) {
+ super(message);
+ this.name = "AuthorFrontendError";
+ this.code = code;
+ this.subject = subject;
+ }
+}
+
+export class AuthorFrontendRegistry implements AuthorFrontendRegistryLike {
+ readonly #frontends = new Map<string, AuthorFrontend>();
+
+ register(frontend: AuthorFrontend): void {
+ if (frontend.id.length === 0) throw new AuthorFrontendError("EMPTY_FRONTEND_ID", "Frontend id is empty");
+ if (this.#frontends.has(frontend.id)) {
+ throw new AuthorFrontendError("DUPLICATE_FRONTEND", `Frontend ${frontend.id} is already registered`, frontend.id);
+ }
+ this.#frontends.set(frontend.id, frontend);
+ }
+
+ resolve(id: string): AuthorFrontend | undefined {
+ return this.#frontends.get(id);
+ }
+}
+
+export type AuthorRecordAdmitter = (
+ closure: ResolvedModuleClosure,
+ record: TypedRecord,
+) => Awaitable<void>;
+
+export type SourceClosureUnit = {
+ readonly id: string;
+ readonly name: string;
+ readonly frontend: string;
+ readonly imports: readonly { readonly alias: string; readonly source: string }[];
+};
+
+export type AuthorInputProvenance = {
+ readonly id: string;
+ readonly name: string;
+ readonly range: import("@hypit/protocol").SourceRange;
+ readonly kind: "literal" | "reference";
+ readonly ref?: AuthorValueRef;
+};
+
+export type AuthorElementProvenance = {
+ readonly id: string;
+ readonly source: string;
+ readonly sourceName: string;
+ readonly frontend: string;
+ readonly range: import("@hypit/protocol").SourceRange;
+ readonly records: readonly { readonly local: string; readonly id: string }[];
+ readonly components: readonly { readonly local: string; readonly id: string }[];
+ readonly outputs: readonly {
+ readonly component: string;
+ readonly name: string;
+ readonly local: string;
+ readonly id: string;
+ }[];
+ readonly inputs: readonly AuthorInputProvenance[];
+};
+
+export type AuthorProvenance = {
+ readonly format: "hypit.author-provenance@1";
+ readonly elements: readonly AuthorElementProvenance[];
+};
+
+export type SourceClosure = {
+ readonly entry: string;
+ readonly units: readonly SourceClosureUnit[];
+};
+
+export type CompiledSourceExport = {
+ readonly name: string;
+ readonly type: TypeRef;
+ readonly ref: GraphValueRef;
+};
+
+/** Domain result of authoring; the Compiler owns how a Source closure is assembled. */
+export type CompiledSourceClosure = {
+ readonly closure: SourceClosure;
+ readonly program: LinkedProgram;
+ readonly graph: CompiledGraph;
+ readonly exports: readonly CompiledSourceExport[];
+ readonly provenance: AuthorProvenance;
+};
+
+function sameType(left: TypeRef, right: TypeRef): boolean {
+ return left.module.name === right.module.name
+ && left.module.version === right.module.version
+ && left.name === right.name;
+}
+
+export function resolveCompiledSourceExport(
+ compiled: CompiledSourceClosure,
+ name: string,
+ expected?: TypeRef,
+): CompiledSourceExport {
+ const item = compiled.exports.find((candidate) => candidate.name === name);
+ if (item === undefined) throw new AuthorFrontendError("UNKNOWN_SOURCE_EXPORT", `unknown source export ${name}`, name);
+ if (expected !== undefined && !sameType(item.type, expected)) {
+ const typeName = (type: TypeRef) => `${type.module.name}@${type.module.version}#${type.name}`;
+ throw new AuthorFrontendError(
+ "SOURCE_EXPORT_TYPE_MISMATCH",
+ `${name} is ${typeName(item.type)}, expected ${typeName(expected)}`,
+ name,
+ );
+ }
+ return item;
+}
diff --git a/packages/elaborator/test/author.test.ts b/packages/author/test/author.test.ts
similarity index 98%
rename from packages/elaborator/test/author.test.ts
rename to packages/author/test/author.test.ts
index 405db0da..2849ebd8 100644
--- a/packages/elaborator/test/author.test.ts
+++ b/packages/author/test/author.test.ts
@@ -7,13 +7,13 @@ import {
sealBuildRequest,
sealRecord,
start,
-} from "@hypit/core";
+} from "@hypit/kernel";
import {
AuthorGraphError,
elaborateAuthorGraph,
sealGraphFragment,
-} from "@hypit/elaborator";
-import type { AuthorComponent, GraphFragment } from "@hypit/elaborator";
+} from "@hypit/author";
+import type { AuthorComponent, GraphFragment } from "@hypit/author";
import type {
LinkedProgram,
ModuleManifest,
diff --git a/packages/elaborator/test/fragment.test.ts b/packages/author/test/fragment.test.ts
similarity index 98%
rename from packages/elaborator/test/fragment.test.ts
rename to packages/author/test/fragment.test.ts
index 29ce9b51..d5666051 100644
--- a/packages/elaborator/test/fragment.test.ts
+++ b/packages/author/test/fragment.test.ts
@@ -12,17 +12,17 @@ import {
sealCompiledGraph,
sealRecord,
start,
-} from "@hypit/core";
+} from "@hypit/kernel";
import {
bindAuthorFragment,
elaborateGraphFragment,
mergeFragmentContributions,
sealGraphFragment,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import type {
FragmentContribution,
GraphFragment,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import type {
CompiledGraph,
LinkedProgram,
diff --git a/packages/artifact/README.md b/packages/blob/README.md
similarity index 64%
rename from packages/artifact/README.md
rename to packages/blob/README.md
index 2b0403f1..75493d11 100644
--- a/packages/artifact/README.md
+++ b/packages/blob/README.md
@@ -1,10 +1,10 @@
-# `@hypit/artifact`
+# `@hypit/blob`
Domain-neutral nominal contract for one byte Artifact referenced by a Runtime Resource id.
-`BlobArtifact` wraps the Protocol `BlobRef` storage form in an owner-defined `TypeRef`, allowing any
+`Blob` wraps the Protocol `BlobRef` storage form in an owner-defined `TypeRef`, allowing any
domain to place files, model outputs or other immutable bytes on Graph edges without borrowing a
media/video type. Artifact storage and transfer remain separate Runtime ports implemented by
-packages such as `@hypit/resource-store-fs` and `@hypit/resource-store-s3`.
+the single-host Runtime's build-local Resource store.
The package has no filesystem, network, media or Provider behavior.
diff --git a/packages/artifact/package.json b/packages/blob/package.json
similarity index 90%
rename from packages/artifact/package.json
rename to packages/blob/package.json
index 17911078..1481da2c 100644
--- a/packages/artifact/package.json
+++ b/packages/blob/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/artifact",
+ "name": "@hypit/blob",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
diff --git a/packages/blob/src/activation.ts b/packages/blob/src/activation.ts
new file mode 100644
index 00000000..f752238d
--- /dev/null
+++ b/packages/blob/src/activation.ts
@@ -0,0 +1,8 @@
+import { blobManifest } from "./index.js";
+
+export const hypitPackage = {
+ format: "hypit.package@1" as const,
+ modules: [{ manifest: blobManifest }],
+};
+
+export default hypitPackage;
diff --git a/packages/blob/src/index.ts b/packages/blob/src/index.ts
new file mode 100644
index 00000000..40142eb7
--- /dev/null
+++ b/packages/blob/src/index.ts
@@ -0,0 +1,24 @@
+import type {
+ ModuleManifest,
+ TypeRef,
+} from "@hypit/protocol";
+
+export const blobModuleRef = { name: "@hypit/blob", version: "1" } as const;
+
+export const blobTypes = {
+ blob: { module: blobModuleRef, name: "Blob" },
+} satisfies Record<string, TypeRef>;
+
+export const blobManifest: ModuleManifest = {
+ format: "hypit.module@1",
+ name: blobModuleRef.name,
+ version: blobModuleRef.version,
+ dependencies: [],
+ types: [{ name: blobTypes.blob.name }],
+ capabilities: [],
+ producers: [],
+};
+
+export const blobDependency = {
+ module: blobModuleRef,
+} as const;
diff --git a/packages/build-result-fs/README.md b/packages/build-result-fs/README.md
deleted file mode 100644
index 2a305aa4..00000000
--- a/packages/build-result-fs/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# `@hypit/build-result-fs`
-
-Default project Build Result repository backed by ordinary files. The local Runtime uses
-`.hypit/results` when the project has no `hypit.results.json`, so a normal checkout needs no account or
-external service.
-
-An explicit selection can move the same repository elsewhere:
-
-```json
-{
- "format": "hypit.build-results@1",
- "use": "@hypit/build-result-fs",
- "config": { "path": ".hypit/results" }
-}
-```
-
-Relative paths are resolved from the project root. Results are grouped by the UTC date already encoded
-in their ordered Build ids. Each Build has a directory containing its `result.json`, new public
-Resource files and Composite Value Documents:
-
-```text
-.hypit/results/2026-09-03/<build-id>/
-```
-
-A Value Document keeps domain data separate from its nested Resource-path bindings. There is no
-project-wide history database. Browsing sorts the shallow date buckets and enumerates Build directories
-only inside the dates reached while filling the requested cursor page; only those Result manifests are
-opened. File reads support byte ranges. Active diagnosis checks the selected directory (or its nearest
-existing parent) for read/write access without creating a probe file.
-
-Existing resources keep their addresses, including inside nested Composite values. External Workspace
-files remain live references; reused Result files retain their original owning Build. See the shared
-[Result value and reference model](../build-result/README.md) for ownership and export behavior.
-
-## Publication
-
-Runtime execution state stays in the Runtime's store. Result synchronization publishes newly accepted
-public Outputs: it saves new Resource files and Value Documents, then replaces `result.json`.
-Internal graph progress and already published Outputs cause no Result writes. A private `.writer.json`
-holds the file assignments needed while publishing and is removed at completion. The Runtime saves
-all accepted public Outputs and the final outcome before removing active execution state, including
-when the Build fails or is cancelled.
-
-Files are written completely beside their destination before publication. POSIX systems use `rename`;
-Windows uses `SetFileInformationByHandle(FileRenameInfoEx)` with replacement and POSIX semantics through
-Koffi. Existing readers keep their old file, while subsequent opens see the new one. This platform code
-belongs to the filesystem implementation; the Result model and other repository adapters do not
-depend on it. A filesystem that rejects this operation reports the Windows error without timed retries.
-
-The Windows behavior is defined by Microsoft's
-[FileRenameInformationEx documentation](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/4217551b-d2c0-42cb-9dc1-69a716cf6d0c).
diff --git a/packages/build-result-fs/package.json b/packages/build-result-fs/package.json
deleted file mode 100644
index 58c2a6f2..00000000
--- a/packages/build-result-fs/package.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "name": "@hypit/build-result-fs",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "hypit": {
- "activation": "./src/activation.ts"
- },
- "dependencies": {
- "@hypit/build-result": "workspace:*",
- "@hypit/build-result-kit": "workspace:*"
- }
-}
diff --git a/packages/build-result-fs/src/activation.ts b/packages/build-result-fs/src/activation.ts
deleted file mode 100644
index c7a0a1de..00000000
--- a/packages/build-result-fs/src/activation.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { constants } from "node:fs";
-import { access, stat } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
-
-import { FileBuildResultRepository } from "@hypit/build-result";
-import { buildResultConfigExact, buildResultConfigObject, buildResultConfigString, createBuildResultRepositoryHostFacet } from "@hypit/build-result-kit";
-
-const filesystemBuildResultRepository = createBuildResultRepositoryHostFacet({
- use: "@hypit/build-result-fs",
- validate(context) {
- const config = buildResultConfigObject(context.config, "filesystem Build Result Repository");
- buildResultConfigExact(config, ["path"], "filesystem Build Result Repository");
- if (buildResultConfigString(config.path, "Build Result path") === undefined) {
- throw new Error("Build Result path is required");
- }
- },
- open(context) {
- const config = buildResultConfigObject(context.config, "filesystem Build Result Repository");
- const path = buildResultConfigString(config.path, "Build Result path");
- if (path === undefined) throw new Error("Build Result path is required");
- return {
- repository: new FileBuildResultRepository(resolve(context.root, path)),
- };
- },
- async doctor(context) {
- const config = buildResultConfigObject(context.config, "filesystem Build Result Repository");
- const selected = buildResultConfigString(config.path, "Build Result path");
- if (selected === undefined) return [];
- const target = resolve(context.root, selected);
- let current = target;
- try {
- while (true) {
- const found = await stat(current).catch((error: unknown) => {
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined;
- throw error;
- });
- if (found !== undefined) {
- if (!found.isDirectory()) throw new Error(`${current} is not a directory`);
- await access(current, constants.R_OK | constants.W_OK);
- return [];
- }
- const parent = dirname(current);
- if (parent === current) throw new Error(`no existing parent directory for ${target}`);
- current = parent;
- }
- } catch (error) {
- return [{
- severity: "error" as const,
- code: "RESULT_REPOSITORY_UNAVAILABLE",
- message: error instanceof Error ? error.message : String(error),
- subject: target,
- }];
- }
- },
-});
-
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- hostFacets: [filesystemBuildResultRepository],
-};
-
-export default hypitPackage;
diff --git a/packages/build-result-fs/src/index.ts b/packages/build-result-fs/src/index.ts
deleted file mode 100644
index bdc25d2d..00000000
--- a/packages/build-result-fs/src/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { FileBuildResultRepository } from "@hypit/build-result";
diff --git a/packages/build-result-kit/README.md b/packages/build-result-kit/README.md
deleted file mode 100644
index c9eb046b..00000000
--- a/packages/build-result-kit/README.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# `@hypit/build-result-kit`
-
-Host-facing package selection for project Build Result repositories. A Repository owns historical
-Build manifests, public Outputs and their Resource files. Temporary Resources and active execution
-state belong to the Runtime implementation instead.
-
-The selected repository is opened before submission and its serializable location travels with the
-active Build. A detached Worker therefore writes to the original destination even if the project's
-active Runtime Profile changes later. Repository packages implement one interface; Core and author
-components do not branch on filesystem, S3 or service type.
diff --git a/packages/build-result-kit/package.json b/packages/build-result-kit/package.json
deleted file mode 100644
index b2164961..00000000
--- a/packages/build-result-kit/package.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "name": "@hypit/build-result-kit",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/build-result": "workspace:*",
- "@hypit/host": "workspace:*",
- "@hypit/protocol": "workspace:*"
- }
-}
diff --git a/packages/build-result-kit/src/index.ts b/packages/build-result-kit/src/index.ts
deleted file mode 100644
index f2fadd3b..00000000
--- a/packages/build-result-kit/src/index.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import type { BuildResultRepository } from "@hypit/build-result";
-import type { HostFacet } from "@hypit/host";
-import type { CanonicalValue } from "@hypit/protocol";
-
-export const buildResultRepositoryHostAbi = "hypit.build-result-repository-host@1";
-
-export type BuildResultRepositorySelection = {
- readonly use: string;
- readonly config?: CanonicalValue;
-};
-
-/** Serializable address carried by a queued Build so a detached Worker can reopen its Repository. */
-export type BuildResultRepositoryLocation = {
- readonly root: string;
- readonly selection: BuildResultRepositorySelection;
-};
-
-export type BuildResultRepositoryContext = {
- /** Directory containing the configuration that selected this Repository. */
- readonly root: string;
- readonly config: CanonicalValue;
-};
-
-export type BuildResultRepositoryOpened = {
- readonly repository: BuildResultRepository;
- readonly close?: () => void | Promise<void>;
-};
-
-export type BuildResultRepositoryDiagnostic = {
- readonly severity: "error" | "warning" | "info";
- readonly code: string;
- readonly message: string;
- readonly subject?: string;
-};
-
-export type BuildResultRepositoryAdapter = {
- validate(context: BuildResultRepositoryContext): void;
- open(context: BuildResultRepositoryContext): BuildResultRepositoryOpened | Promise<BuildResultRepositoryOpened>;
- /** Active, read-only reachability/permission diagnosis for the selected backing store. */
- doctor?(context: BuildResultRepositoryContext): readonly BuildResultRepositoryDiagnostic[] | Promise<readonly BuildResultRepositoryDiagnostic[]>;
-};
-
-export type BuildResultRepositoryHostFacet = HostFacet & {
- readonly abi: typeof buildResultRepositoryHostAbi;
- readonly offers: readonly [string];
- readonly implementation: BuildResultRepositoryAdapter;
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-export function createBuildResultRepositoryHostFacet(options: {
- readonly use: string;
- readonly validate: BuildResultRepositoryAdapter["validate"];
- readonly open: BuildResultRepositoryAdapter["open"];
- readonly doctor?: BuildResultRepositoryAdapter["doctor"];
-}): BuildResultRepositoryHostFacet {
- assert(options.use.trim().length > 0, "Build Result Repository use name is empty");
- return {
- abi: buildResultRepositoryHostAbi,
- offers: [options.use],
- implementation: {
- validate: options.validate,
- open: options.open,
- ...(options.doctor === undefined ? {} : { doctor: options.doctor }),
- },
- };
-}
-
-export function isBuildResultRepositoryHostFacet(value: HostFacet): value is BuildResultRepositoryHostFacet {
- if (value.abi !== buildResultRepositoryHostAbi || value.offers?.length !== 1) return false;
- const implementation = value.implementation as Partial<BuildResultRepositoryAdapter> | null;
- return (
- implementation !== null && typeof implementation === "object"
- && typeof implementation.validate === "function"
- && typeof implementation.open === "function"
- && (implementation.doctor === undefined || typeof implementation.doctor === "function")
- );
-}
-
-export class BuildResultRepositoryRegistry {
- readonly #adapters = new Map<string, BuildResultRepositoryAdapter>();
-
- registerFacet(facet: HostFacet): void {
- assert(isBuildResultRepositoryHostFacet(facet), `Host facet ${facet.abi} is not a Build Result Repository`);
- const use = facet.offers[0];
- assert(!this.#adapters.has(use), `Build Result Repository ${use} is already registered`);
- this.#adapters.set(use, facet.implementation);
- }
-
- has(use: string): boolean {
- return this.#adapters.has(use);
- }
-
- validate(selection: BuildResultRepositorySelection, root: string): void {
- const adapter = this.#adapters.get(selection.use);
- assert(adapter !== undefined, `Build Result Repository ${selection.use} is not installed`);
- adapter.validate({ root, config: selection.config ?? {} });
- }
-
- async open(selection: BuildResultRepositorySelection, root: string): Promise<BuildResultRepositoryOpened> {
- const adapter = this.#adapters.get(selection.use);
- assert(adapter !== undefined, `Build Result Repository ${selection.use} is not installed`);
- const context = { root, config: selection.config ?? {} };
- adapter.validate(context);
- return await adapter.open(context);
- }
-
- async doctor(
- selection: BuildResultRepositorySelection,
- root: string,
- ): Promise<readonly BuildResultRepositoryDiagnostic[]> {
- const adapter = this.#adapters.get(selection.use);
- assert(adapter !== undefined, `Build Result Repository ${selection.use} is not installed`);
- const context = { root, config: selection.config ?? {} };
- adapter.validate(context);
- return await adapter.doctor?.(context) ?? [];
- }
-}
-
-export function buildResultConfigObject(value: CanonicalValue, subject: string): Record<string, CanonicalValue> {
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
- throw new Error(`${subject} config must be an object`);
- }
- return value as Record<string, CanonicalValue>;
-}
-
-export function buildResultConfigExact(value: Readonly<Record<string, CanonicalValue>>, allowed: readonly string[], subject: string): void {
- const unknown = Object.keys(value).find((key) => !allowed.includes(key));
- if (unknown !== undefined) throw new Error(`${subject} config does not accept ${unknown}`);
-}
-
-export function buildResultConfigString(value: CanonicalValue | undefined, subject: string): string | undefined {
- if (value === undefined) return undefined;
- if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${subject} must be a non-empty string`);
- return value;
-}
-
-export function buildResultConfigBoolean(value: CanonicalValue | undefined, subject: string): boolean | undefined {
- if (value === undefined) return undefined;
- if (typeof value !== "boolean") throw new Error(`${subject} must be a boolean`);
- return value;
-}
diff --git a/packages/build-result-s3/README.md b/packages/build-result-s3/README.md
deleted file mode 100644
index 942e8ffd..00000000
--- a/packages/build-result-s3/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# `@hypit/build-result-s3`
-
-Opt-in S3-compatible repository for complete project Build Results. It stores Build manifests,
-Composite Value Documents and public Resource files under one project prefix; an active Build's
-temporary Resources remain with the selected Runtime implementation.
-
-```json
-{
- "format": "hypit.build-results@1",
- "use": "@hypit/build-result-s3",
- "config": {
- "bucket": "my-video-results",
- "prefix": "projects/episode-12",
- "region": "us-east-1"
- }
-}
-```
-
-`bucket` is required. `prefix`, `expectedBucketOwner`, `region`, `endpoint` and `forcePathStyle` are
-optional. The AWS SDK uses its normal credential chain, so credentials stay outside the Profile.
-`endpoint` and `forcePathStyle` support compatible object stores.
-
-The repository exposes the same logical shape as the filesystem adapter:
-
-```text
-<prefix>/
- <build-id>/
- result.json
- files/...
- values/...
-```
-
-Filesystem and S3 use the same Record-to-Result encoder. The adapter only writes the selected
-relative document or byte path; it does not interpret domain values. A Value Document keeps canonical
-domain data separate from the paths of nested Resources.
-Nested reuse retains each Resource's original Build and path. Workspace files remain explicit external
-references rather than being uploaded merely because this repository uses S3. The shared
-[Result value and reference model](../build-result/README.md) describes ownership and external access.
-Synchronization uploads new public Outputs and then their updated manifest. Internal graph progress
-and repeated synchronization of already published Outputs produce no object writes.
-
-Physical object prefixes use a reversible descending-time form derived from the ordered Build id, so
-S3 can return a newest-first delimiter page directly. This is only adapter key layout: callers still
-address `build + output`, and no index object or global Build table exists. A reused historical Output is a
-small forward reference to the finished Result that owns its value. New references are reduced to that
-terminal address as they are written, so repeated reuse still reads the original file without uploading
-another copy or maintaining a reverse dependency index. While a Build is running, a private writer
-file records only the state needed to continue publishing completed public Outputs and is removed when
-the Result receives its outcome.
-
-Object listing uses a bounded cursor page. File reads accept normalized byte ranges, allowing Studio to
-stream remote video and audio without buffering the complete object. The adapter's active doctor uses
-one bounded prefix listing to verify credentials, bucket access and endpoint reachability; it creates
-no probe object and reads no Result manifest.
diff --git a/packages/build-result-s3/package.json b/packages/build-result-s3/package.json
deleted file mode 100644
index 665aed94..00000000
--- a/packages/build-result-s3/package.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "name": "@hypit/build-result-s3",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "hypit": {
- "activation": "./src/activation.ts"
- },
- "dependencies": {
- "@aws-sdk/client-s3": "3.1103.0",
- "@hypit/build-result": "workspace:*",
- "@hypit/build-result-kit": "workspace:*",
- "@hypit/protocol": "workspace:*"
- }
-}
diff --git a/packages/build-result-s3/src/activation.ts b/packages/build-result-s3/src/activation.ts
deleted file mode 100644
index c739ee80..00000000
--- a/packages/build-result-s3/src/activation.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import {
- buildResultConfigBoolean,
- buildResultConfigExact,
- buildResultConfigObject,
- buildResultConfigString,
- createBuildResultRepositoryHostFacet,
-} from "@hypit/build-result-kit";
-
-import { S3BuildResultRepository } from "./repository.js";
-
-function repositoryFromConfig(configValue: Parameters<typeof buildResultConfigObject>[0]): S3BuildResultRepository {
- const config = buildResultConfigObject(configValue, "S3 Build Result Repository");
- const bucket = buildResultConfigString(config.bucket, "S3 bucket");
- if (bucket === undefined) throw new Error("S3 bucket is required");
- const prefix = buildResultConfigString(config.prefix, "S3 prefix");
- const expectedBucketOwner = buildResultConfigString(config.expectedBucketOwner, "S3 expectedBucketOwner");
- const region = buildResultConfigString(config.region, "S3 region");
- const endpoint = buildResultConfigString(config.endpoint, "S3 endpoint");
- const forcePathStyle = buildResultConfigBoolean(config.forcePathStyle, "S3 forcePathStyle");
- return new S3BuildResultRepository({
- bucket,
- ...(prefix === undefined ? {} : { prefix }),
- ...(expectedBucketOwner === undefined ? {} : { expectedBucketOwner }),
- ...(region === undefined ? {} : { region }),
- ...(endpoint === undefined ? {} : { endpoint }),
- ...(forcePathStyle === undefined ? {} : { forcePathStyle }),
- });
-}
-
-const s3BuildResultRepository = createBuildResultRepositoryHostFacet({
- use: "@hypit/build-result-s3",
- validate(context) {
- const config = buildResultConfigObject(context.config, "S3 Build Result Repository");
- buildResultConfigExact(config, ["bucket", "prefix", "expectedBucketOwner", "region", "endpoint", "forcePathStyle"], "S3 Build Result Repository");
- if (buildResultConfigString(config.bucket, "S3 bucket") === undefined) throw new Error("S3 bucket is required");
- buildResultConfigString(config.prefix, "S3 prefix");
- buildResultConfigString(config.expectedBucketOwner, "S3 expectedBucketOwner");
- buildResultConfigString(config.region, "S3 region");
- buildResultConfigString(config.endpoint, "S3 endpoint");
- buildResultConfigBoolean(config.forcePathStyle, "S3 forcePathStyle");
- },
- open(context) {
- const repository = repositoryFromConfig(context.config);
- return { repository, close: async () => await repository.close() };
- },
- async doctor(context) {
- const repository = repositoryFromConfig(context.config);
- try {
- await repository.diagnose();
- return [];
- } catch (error) {
- const config = buildResultConfigObject(context.config, "S3 Build Result Repository");
- const bucket = buildResultConfigString(config.bucket, "S3 bucket") ?? "unknown";
- return [{
- severity: "error" as const,
- code: "RESULT_REPOSITORY_UNAVAILABLE",
- message: error instanceof Error ? error.message : String(error),
- subject: `s3://${bucket}`,
- }];
- } finally {
- await repository.close();
- }
- },
-});
-
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- hostFacets: [s3BuildResultRepository],
-};
-
-export default hypitPackage;
diff --git a/packages/build-result-s3/src/client.ts b/packages/build-result-s3/src/client.ts
deleted file mode 100644
index 7475d4e2..00000000
--- a/packages/build-result-s3/src/client.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import {
- AbortMultipartUploadCommand,
- CompleteMultipartUploadCommand,
- CreateMultipartUploadCommand,
- DeleteObjectCommand,
- GetObjectCommand,
- ListObjectsV2Command,
- PutObjectCommand,
- S3Client,
- UploadPartCommand,
-} from "@aws-sdk/client-s3";
-import type { S3ClientConfig } from "@aws-sdk/client-s3";
-import type { BuildResultFileRange } from "@hypit/build-result";
-
-export type BuildResultS3Client = {
- put(key: string, bytes: Uint8Array, mediaType: string): Promise<void>;
- putStream(key: string, chunks: AsyncIterable<Uint8Array>, mediaType: string): Promise<void>;
- get(key: string): Promise<Uint8Array | undefined>;
- open(key: string, range?: BuildResultFileRange): Promise<AsyncIterable<Uint8Array> | undefined>;
- list(prefix: string, options?: {
- readonly limit?: number;
- readonly after?: string;
- readonly delimiter?: string;
- }): Promise<readonly string[]>;
- delete(key: string): Promise<void>;
- close?(): void | Promise<void>;
-};
-
-function statusCode(error: unknown): number | undefined {
- if (typeof error !== "object" || error === null || !("$metadata" in error)) return undefined;
- const metadata = error.$metadata;
- if (typeof metadata !== "object" || metadata === null || !("httpStatusCode" in metadata)) return undefined;
- return typeof metadata.httpStatusCode === "number" ? metadata.httpStatusCode : undefined;
-}
-
-function absent(error: unknown): boolean {
- return statusCode(error) === 404 || (error instanceof Error && (error.name === "NoSuchKey" || error.name === "NotFound"));
-}
-
-export type AwsBuildResultS3ClientOptions = {
- readonly bucket: string;
- readonly expectedBucketOwner?: string;
- readonly partSizeBytes?: number;
- readonly region?: string;
- readonly endpoint?: string;
- readonly forcePathStyle?: boolean;
-};
-
-export class AwsBuildResultS3Client implements BuildResultS3Client {
- readonly #client: S3Client;
- readonly #bucket: string;
- readonly #expectedBucketOwner: string | undefined;
- readonly #partSizeBytes: number;
-
- constructor(options: AwsBuildResultS3ClientOptions) {
- this.#bucket = options.bucket;
- this.#expectedBucketOwner = options.expectedBucketOwner;
- this.#partSizeBytes = options.partSizeBytes ?? 16 * 1024 * 1024;
- this.#client = new S3Client({
- ...(options.region === undefined ? {} : { region: options.region }),
- ...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }),
- ...(options.forcePathStyle === undefined ? {} : { forcePathStyle: options.forcePathStyle }),
- } satisfies S3ClientConfig);
- }
-
- #owner(): { readonly ExpectedBucketOwner?: string } {
- return this.#expectedBucketOwner === undefined ? {} : { ExpectedBucketOwner: this.#expectedBucketOwner };
- }
-
- async put(key: string, bytes: Uint8Array, mediaType: string): Promise<void> {
- await this.#client.send(
- new PutObjectCommand({
- Bucket: this.#bucket,
- Key: key,
- Body: bytes,
- ContentLength: bytes.byteLength,
- ContentType: mediaType,
- ...this.#owner(),
- }),
- );
- }
-
- async putStream(key: string, chunks: AsyncIterable<Uint8Array>, mediaType: string): Promise<void> {
- const created = await this.#client.send(
- new CreateMultipartUploadCommand({
- Bucket: this.#bucket,
- Key: key,
- ContentType: mediaType,
- ...this.#owner(),
- }),
- );
- if (created.UploadId === undefined) throw new Error(`S3 did not start upload for ${key}`);
- const uploadId = created.UploadId;
- const parts: { PartNumber: number; ETag: string }[] = [];
- let pending: Uint8Array[] = [];
- let pendingBytes = 0;
- const flush = async (): Promise<void> => {
- if (pendingBytes === 0) return;
- const body = new Uint8Array(pendingBytes);
- let offset = 0;
- for (const piece of pending) {
- body.set(piece, offset);
- offset += piece.byteLength;
- }
- pending = [];
- pendingBytes = 0;
- const partNumber = parts.length + 1;
- const uploaded = await this.#client.send(
- new UploadPartCommand({
- Bucket: this.#bucket,
- Key: key,
- UploadId: uploadId,
- PartNumber: partNumber,
- Body: body,
- ContentLength: body.byteLength,
- ...this.#owner(),
- }),
- );
- if (uploaded.ETag === undefined) throw new Error(`S3 did not return part ${partNumber} for ${key}`);
- parts.push({ PartNumber: partNumber, ETag: uploaded.ETag });
- };
- try {
- for await (const value of chunks) {
- const chunk = Uint8Array.from(value);
- let offset = 0;
- while (offset < chunk.byteLength) {
- const take = Math.min(this.#partSizeBytes - pendingBytes, chunk.byteLength - offset);
- pending.push(chunk.slice(offset, offset + take));
- pendingBytes += take;
- offset += take;
- if (pendingBytes === this.#partSizeBytes) await flush();
- }
- }
- await flush();
- if (parts.length === 0) {
- await this.#client.send(
- new AbortMultipartUploadCommand({
- Bucket: this.#bucket,
- Key: key,
- UploadId: uploadId,
- ...this.#owner(),
- }),
- );
- await this.put(key, new Uint8Array(), mediaType);
- return;
- }
- await this.#client.send(
- new CompleteMultipartUploadCommand({
- Bucket: this.#bucket,
- Key: key,
- UploadId: uploadId,
- MultipartUpload: { Parts: parts },
- ...this.#owner(),
- }),
- );
- } catch (error) {
- await this.#client
- .send(
- new AbortMultipartUploadCommand({
- Bucket: this.#bucket,
- Key: key,
- UploadId: uploadId,
- ...this.#owner(),
- }),
- )
- .catch(() => undefined);
- throw error;
- }
- }
-
- async get(key: string): Promise<Uint8Array | undefined> {
- try {
- const response = await this.#client.send(
- new GetObjectCommand({
- Bucket: this.#bucket,
- Key: key,
- ...this.#owner(),
- }),
- );
- if (response.Body === undefined) throw new Error(`S3 object ${key} has no body`);
- return Uint8Array.from(await response.Body.transformToByteArray());
- } catch (error) {
- if (absent(error)) return undefined;
- throw error;
- }
- }
-
- async open(key: string, range?: BuildResultFileRange): Promise<AsyncIterable<Uint8Array> | undefined> {
- try {
- const response = await this.#client.send(
- new GetObjectCommand({
- Bucket: this.#bucket,
- Key: key,
- ...(range === undefined ? {} : { Range: `bytes=${range.start}-${range.endExclusive - 1}` }),
- ...this.#owner(),
- }),
- );
- if (response.Body === undefined) throw new Error(`S3 object ${key} has no body`);
- const body = response.Body as unknown as AsyncIterable<Uint8Array>;
- return (async function* () {
- for await (const chunk of body) yield Uint8Array.from(chunk);
- })();
- } catch (error) {
- if (absent(error)) return undefined;
- throw error;
- }
- }
-
- async list(prefix: string, options: {
- readonly limit?: number;
- readonly after?: string;
- readonly delimiter?: string;
- } = {}): Promise<readonly string[]> {
- if (options.limit !== undefined && (!Number.isSafeInteger(options.limit) || options.limit < 1)) {
- throw new Error("S3 list limit must be a positive safe integer");
- }
- const keys: string[] = [];
- let continuationToken: string | undefined;
- do {
- const response = await this.#client.send(
- new ListObjectsV2Command({
- Bucket: this.#bucket,
- Prefix: prefix,
- ...(options.after === undefined ? {} : { StartAfter: options.after }),
- ...(options.delimiter === undefined ? {} : { Delimiter: options.delimiter }),
- ...(options.limit === undefined ? {} : { MaxKeys: Math.min(1_000, options.limit - keys.length) }),
- ...(continuationToken === undefined ? {} : { ContinuationToken: continuationToken }),
- ...this.#owner(),
- }),
- );
- keys.push(
- ...(response.CommonPrefixes ?? []).flatMap((item) => item.Prefix === undefined ? [] : [item.Prefix]),
- ...(response.Contents ?? []).flatMap((item) => item.Key === undefined ? [] : [item.Key]),
- );
- if (options.limit !== undefined && keys.length >= options.limit) return keys.slice(0, options.limit);
- continuationToken = response.IsTruncated === true ? response.NextContinuationToken : undefined;
- } while (continuationToken !== undefined);
- return keys;
- }
-
- async delete(key: string): Promise<void> {
- await this.#client.send(
- new DeleteObjectCommand({
- Bucket: this.#bucket,
- Key: key,
- ...this.#owner(),
- }),
- );
- }
-
- close(): void {
- this.#client.destroy();
- }
-}
diff --git a/packages/build-result-s3/src/index.ts b/packages/build-result-s3/src/index.ts
deleted file mode 100644
index 46a1c8c2..00000000
--- a/packages/build-result-s3/src/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export { AwsBuildResultS3Client } from "./client.js";
-export type { AwsBuildResultS3ClientOptions, BuildResultS3Client } from "./client.js";
-export { S3BuildResultRepository } from "./repository.js";
-export type { S3BuildResultRepositoryOptions } from "./repository.js";
diff --git a/packages/build-result-s3/src/repository.ts b/packages/build-result-s3/src/repository.ts
deleted file mode 100644
index 17d7aa80..00000000
--- a/packages/build-result-s3/src/repository.ts
+++ /dev/null
@@ -1,379 +0,0 @@
-import { preserveExecutionLog } from "@hypit/build-result";
-import type {
- BuildResultFileRef,
- ExternalFileAccess,
- BuildResultFileRange,
- BuildResultFinish,
- BuildResultManifest,
- BuildResultPresentationUpdate,
- BuildResultRepository,
- BuildResultSeed,
- BuildResultSync,
- BuildResultWriter,
- BuildResultWriterState,
- RepositoryBuildResultOutput,
- RepositoryBuildResultOutputDescription,
-} from "@hypit/build-result";
-import {
- applyBuildResultPresentation,
- assertBuildResultSeed,
- decodeBuildResultJson,
- decodeBuildResultManifest,
- decodeBuildResultValueDocument,
- decodeBuildResultWriterState,
- encodeBuildResultManifest,
- normalizeBuildResultForwards,
- syncBuildResultOutputs,
- currentFileReference,
- localExternalFiles,
-} from "@hypit/build-result";
-import { assertOrderedBuildId, buildIdCreatedAt } from "@hypit/protocol";
-
-import { AwsBuildResultS3Client } from "./client.js";
-import type { AwsBuildResultS3ClientOptions, BuildResultS3Client } from "./client.js";
-
-export type S3BuildResultRepositoryOptions = AwsBuildResultS3ClientOptions & {
- readonly prefix?: string;
- readonly client?: BuildResultS3Client;
- readonly externalFiles?: ExternalFileAccess;
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-function normalizePrefix(value: string | undefined): string {
- if (value === undefined || value.length === 0) return "";
- const normalized = value.replace(/^\/+|\/+$/gu, "");
- assert(normalized.length > 0 && !normalized.split("/").some((part) => part === "." || part === ".."), "S3 Build Result prefix is invalid");
- return normalized;
-}
-
-function physicalBuild(build: string): string {
- assertOrderedBuildId(build);
- const createdAt = buildIdCreatedAt(build)!;
- const descendingTime = (Number.MAX_SAFE_INTEGER - createdAt).toString().padStart(16, "0");
- return `${descendingTime}-${build}`;
-}
-
-function publicBuild(physical: string): string | undefined {
- if (!/^\d{16}-bld_/u.test(physical)) return undefined;
- const build = physical.slice(17);
- return buildIdCreatedAt(build) === undefined || physicalBuild(build) !== physical ? undefined : build;
-}
-
-function safePath(path: string): string {
- assert(path.length > 0 && !path.startsWith("/") && !path.includes("\\"), "Build Result path must be relative");
- assert(!path.split("/").some((part) => part.length === 0 || part === "." || part === ".."), `Build Result path ${path} is invalid`);
- return path;
-}
-
-function encodeJson(value: unknown): Uint8Array {
- return new TextEncoder().encode(`${JSON.stringify(value, null, 2)}\n`);
-}
-
-class S3BuildResultWriter implements BuildResultWriter {
- readonly #repository: S3BuildResultRepository;
- readonly #build: string;
-
- constructor(repository: S3BuildResultRepository, build: string) {
- this.#repository = repository;
- this.#build = build;
- }
-
- async read(): Promise<BuildResultManifest> {
- const manifest = await this.#repository.read(this.#build);
- assert(manifest !== undefined, `Build Result ${this.#build} does not exist`);
- return manifest;
- }
-
- async sync(input: BuildResultSync): Promise<BuildResultManifest> {
- const manifest = await this.read();
- if (manifest.outcome !== undefined) return manifest;
- const writer = await this.#repository.readWriter(this.#build);
- assert(writer !== undefined, `Build Result ${this.#build} has no writer state`);
- const updated = await syncBuildResultOutputs({
- manifest,
- writer,
- sync: input,
- target: {
- writeResource: async (path, artifact, source) => {
- const chunks = await source.open(artifact);
- if (chunks === undefined) throw new Error(`Build resource ${artifact.resource} is unavailable`);
- await this.#repository.writeFile(this.#build, path, chunks, artifact.mediaType);
- },
- writeValue: async (path, document) => {
- await this.#repository.writeJson(this.#build, path, document);
- },
- },
- });
- if (!updated.changed) return manifest;
- await this.#repository.writeWriter(this.#build, updated.writer);
- await this.#repository.writeManifest(this.#build, updated.manifest);
- return updated.manifest;
- }
-
- async finish(input: BuildResultFinish): Promise<BuildResultManifest> {
- const manifest = await this.read();
- if (manifest.outcome !== undefined) {
- assert(manifest.outcome === input.outcome && manifest.failure === input.failure,
- `Build Result ${manifest.id} is already finished with a different outcome`);
- await this.#repository.deleteWriter(this.#build);
- return manifest;
- }
- const executionLog = await preserveExecutionLog(input.executionLog,
- async (path, chunks, mediaType) => await this.#repository.writeFile(this.#build, path, chunks, mediaType));
- const now = Date.now();
- const updated: BuildResultManifest = {
- ...manifest,
- outcome: input.outcome,
- ...(executionLog === undefined ? {} : { executionLog }),
- ...(input.operations === undefined ? {} : { operations: input.operations }),
- finishedAt: manifest.finishedAt ?? now,
- ...(input.failure === undefined ? {} : { failure: input.failure }),
- };
- await this.#repository.writeManifest(this.#build, updated);
- await this.#repository.deleteWriter(this.#build);
- return updated;
- }
-}
-
-export class S3BuildResultRepository implements BuildResultRepository {
- readonly #client: BuildResultS3Client;
- readonly #prefix: string;
- readonly #externalFiles: ExternalFileAccess;
-
- constructor(options: S3BuildResultRepositoryOptions) {
- assert(options.bucket.trim().length > 0, "S3 Build Result bucket must not be empty");
- this.#prefix = normalizePrefix(options.prefix);
- this.#externalFiles = options.externalFiles ?? localExternalFiles;
- this.#client = options.client ?? new AwsBuildResultS3Client(options);
- }
-
- #key(build: string, path: string): string {
- const relative = `${physicalBuild(build)}/${safePath(path)}`;
- return this.#prefix.length === 0 ? relative : `${this.#prefix}/${relative}`;
- }
-
- async #readJson(build: string, path: string): Promise<unknown | undefined> {
- const bytes = await this.#client.get(this.#key(build, path));
- return bytes === undefined ? undefined : decodeBuildResultJson(bytes, `${build}/${path}`);
- }
-
- async writeJson(build: string, path: string, value: unknown): Promise<void> {
- await this.#client.put(this.#key(build, path), encodeJson(value), "application/json");
- }
-
- async writeFile(build: string, path: string, chunks: AsyncIterable<Uint8Array>, mediaType: string): Promise<void> {
- await this.#client.putStream(this.#key(build, path), chunks, mediaType);
- }
-
- async writeManifest(build: string, manifest: BuildResultManifest): Promise<void> {
- await this.writeJson(build, "result.json", encodeBuildResultManifest(manifest));
- }
-
- async readWriter(build: string): Promise<BuildResultWriterState | undefined> {
- const subject = `${build}/.writer.json`;
- const value = await this.#readJson(build, ".writer.json");
- return value === undefined ? undefined : decodeBuildResultWriterState(value, subject);
- }
-
- async writeWriter(build: string, state: BuildResultWriterState): Promise<void> {
- await this.writeJson(build, ".writer.json", state);
- }
-
- async deleteWriter(build: string): Promise<void> {
- await this.#client.delete(this.#key(build, ".writer.json"));
- }
-
- async create(seed: BuildResultSeed): Promise<BuildResultWriter> {
- assertOrderedBuildId(seed.id);
- assertBuildResultSeed(seed);
- assert((await this.read(seed.id)) === undefined, `Build Result ${seed.id} already exists`);
- const forwards = await normalizeBuildResultForwards(this, seed.forwards ?? []);
- const manifest: BuildResultManifest = {
- format: "hypit.build-result@1",
- id: seed.id,
- ...(seed.title === undefined ? {} : { title: seed.title }),
- source: seed.source,
- ...(seed.run === undefined ? {} : { run: seed.run }),
- targets: [...seed.targets],
- outputs: {},
- };
- try {
- await this.writeWriter(seed.id, {
- resources: {},
- values: {},
- publishedOutputs: seed.publishedOutputs,
- ...(seed.resourceReferences === undefined ? {} : { resourceReferences: seed.resourceReferences }),
- forwards,
- });
- await this.writeManifest(seed.id, manifest);
- } catch (error) {
- await this.#client.delete(this.#key(seed.id, ".writer.json")).catch(() => undefined);
- await this.#client.delete(this.#key(seed.id, "result.json")).catch(() => undefined);
- throw error;
- }
- return new S3BuildResultWriter(this, seed.id);
- }
-
- async openWriter(build: string): Promise<BuildResultWriter | undefined> {
- return (await this.read(build)) === undefined ? undefined : new S3BuildResultWriter(this, build);
- }
-
- async removeIncomplete(build: string): Promise<void> {
- const manifest = await this.read(build);
- if (manifest === undefined) return;
- assert(manifest.outcome === undefined, `Finished Build Result ${build} cannot be removed`);
- const prefix = this.#key(build, "result.json").slice(0, -"result.json".length);
- const keys = await this.#client.list(prefix);
- await Promise.all(keys.filter((key) => key.startsWith(prefix)).map(async (key) => await this.#client.delete(key)));
- }
-
- async read(build: string): Promise<BuildResultManifest | undefined> {
- const subject = `${build}/result.json`;
- const value = await this.#readJson(build, "result.json");
- return value === undefined ? undefined : decodeBuildResultManifest(value, build, subject);
- }
-
- async updatePresentation(
- build: string,
- update: BuildResultPresentationUpdate,
- ): Promise<BuildResultManifest> {
- const manifest = await this.read(build);
- assert(manifest !== undefined, `Build Result ${build} does not exist`);
- const updated = applyBuildResultPresentation(manifest, update);
- await this.writeManifest(build, updated);
- return updated;
- }
-
- async browse(request: { readonly before?: string; readonly limit: number }) {
- assert(Number.isSafeInteger(request.limit) && request.limit > 0, "Build Result browse limit must be positive");
- if (request.before !== undefined) assertOrderedBuildId(request.before);
- const prefix = this.#prefix.length === 0 ? "" : `${this.#prefix}/`;
- const found: Array<BuildResultManifest & { readonly outcome: NonNullable<BuildResultManifest["outcome"]>; readonly finishedAt: number }> = [];
- let after = request.before === undefined ? undefined : `${prefix}${physicalBuild(request.before)}/`;
- while (found.length <= request.limit) {
- const page = await this.#client.list(prefix, {
- limit: Math.min(1_000, Math.max(32, request.limit + 1)),
- delimiter: "/",
- ...(after === undefined ? {} : { after }),
- });
- if (page.length === 0) break;
- for (const item of page) {
- after = item;
- if (!item.startsWith(prefix) || !item.endsWith("/")) continue;
- const physical = item.slice(prefix.length, -1);
- if (physical.includes("/")) continue;
- const build = publicBuild(physical);
- if (build === undefined) continue;
- const manifest = await this.read(build);
- if (manifest?.outcome === undefined || manifest.finishedAt === undefined) continue;
- found.push(manifest as typeof found[number]);
- if (found.length > request.limit) break;
- }
- if (found.length > request.limit || page.length < Math.min(1_000, Math.max(32, request.limit + 1))) break;
- }
- const results = found.slice(0, request.limit);
- return {
- results,
- ...(found.length > request.limit && results.length > 0 ? { next: results[results.length - 1]!.id } : {}),
- };
- }
-
- async describeOutput(build: string, output: string): Promise<RepositoryBuildResultOutputDescription | undefined> {
- const seen = new Set<string>();
- let currentBuild = build;
- let currentOutput = output;
- while (true) {
- const address = `${currentBuild}\u0000${currentOutput}`;
- assert(!seen.has(address), `Build Output forwarding repeats ${currentBuild} / ${currentOutput}`);
- seen.add(address);
- const manifest = await this.read(currentBuild);
- const entry = manifest?.outputs[currentOutput];
- if (entry === undefined) return undefined;
- if (entry.value.kind === "build-output") {
- currentBuild = entry.value.build;
- currentOutput = entry.value.output;
- continue;
- }
- const file = entry.value.kind === "external-file" ? await currentFileReference(entry.value, this.#externalFiles) : entry.value;
- return file.kind === "build-file" || file.kind === "external-file"
- ? { type: entry.type, kind: "resource", size: file.size, mediaType: file.mediaType }
- : entry.value.kind === "value"
- ? { type: entry.type, kind: "composite" }
- : { type: entry.type, kind: "scalar" };
- }
- }
-
- async resolve(build: string, output: string): Promise<RepositoryBuildResultOutput | undefined> {
- const seen = new Set<string>();
- let currentBuild = build;
- let currentOutput = output;
- while (true) {
- const address = `${currentBuild}\u0000${currentOutput}`;
- assert(!seen.has(address), `Build Output forwarding repeats ${currentBuild} / ${currentOutput}`);
- seen.add(address);
- const manifest = await this.read(currentBuild);
- const entry = manifest?.outputs[currentOutput];
- if (entry === undefined) return undefined;
- if (entry.value.kind === "build-output") {
- currentBuild = entry.value.build;
- currentOutput = entry.value.output;
- continue;
- }
- if (entry.value.kind === "value") {
- const rawDocument = await this.#readJson(currentBuild, entry.value.path);
- assert(rawDocument !== undefined, `Build ${currentBuild} value ${entry.value.path} is unavailable`);
- const document = decodeBuildResultValueDocument(
- rawDocument,
- `Build ${currentBuild} Output ${currentOutput}`,
- );
- return {
- build: currentBuild,
- output: currentOutput,
- type: entry.type,
- value: { ...entry.value, document },
- };
- }
- const terminalKind = (entry.value as { readonly kind?: unknown }).kind;
- assert(terminalKind === "build-file" || terminalKind === "external-file" || terminalKind === "inline",
- `Build ${currentBuild} Output ${currentOutput} has unsupported Result value kind ${String(terminalKind)}`);
- return {
- build: currentBuild,
- output: currentOutput,
- type: entry.type,
- value: entry.value.kind === "external-file" ? await currentFileReference(entry.value, this.#externalFiles) : entry.value,
- };
- }
- }
-
- async describeFile(_build: string, file: BuildResultFileRef): Promise<BuildResultFileRef> {
- return await currentFileReference(file, this.#externalFiles);
- }
-
- async openFile(
- build: string,
- file: BuildResultFileRef,
- range?: BuildResultFileRange,
- ): Promise<AsyncIterable<Uint8Array> | undefined> {
- if (file.kind === "external-file") return await this.#externalFiles.open(file.uri, range);
- if (range !== undefined) {
- assert(Number.isSafeInteger(range.start) && range.start >= 0, "Build Result file range start is invalid");
- assert(Number.isSafeInteger(range.endExclusive) && range.endExclusive > range.start,
- "Build Result file range end is invalid");
- assert(range.endExclusive <= file.size, "Build Result file range exceeds the declared file size");
- }
- return await this.#client.open(this.#key(file.build ?? build, file.path), range);
- }
-
- /** Verify that the configured bucket/prefix can be listed without loading Result history. */
- async diagnose(): Promise<void> {
- const prefix = this.#prefix.length === 0 ? "" : `${this.#prefix}/`;
- await this.#client.list(prefix, { limit: 1 });
- }
-
- async close(): Promise<void> {
- await this.#client.close?.();
- }
-}
diff --git a/packages/build-result-s3/test/repository.test.ts b/packages/build-result-s3/test/repository.test.ts
deleted file mode 100644
index ab9ec3bf..00000000
--- a/packages/build-result-s3/test/repository.test.ts
+++ /dev/null
@@ -1,531 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import { S3BuildResultRepository } from "@hypit/build-result-s3";
-import type { BuildResultS3Client } from "@hypit/build-result-s3";
-import type { BlobRef, BuildState, TypeRef } from "@hypit/protocol";
-
-const videoType: TypeRef = {
- module: { name: "example.media", version: "1" },
- name: "Video",
-};
-const compositeType: TypeRef = {
- module: { name: "example.speech", version: "1" },
- name: "CompositeValue",
-};
-
-class MemoryS3 implements BuildResultS3Client {
- readonly objects = new Map<string, Uint8Array>();
- readonly writes: string[] = [];
- readonly listRequests: {
- readonly prefix: string;
- readonly limit?: number;
- readonly after?: string;
- readonly delimiter?: string;
- }[] = [];
-
- async put(key: string, bytes: Uint8Array): Promise<void> {
- this.writes.push(key);
- this.objects.set(key, Uint8Array.from(bytes));
- }
-
- async putStream(key: string, chunks: AsyncIterable<Uint8Array>): Promise<void> {
- this.writes.push(key);
- const values: Uint8Array[] = [];
- let size = 0;
- for await (const chunk of chunks) {
- const value = Uint8Array.from(chunk);
- values.push(value);
- size += value.byteLength;
- }
- const bytes = new Uint8Array(size);
- let offset = 0;
- for (const value of values) {
- bytes.set(value, offset);
- offset += value.byteLength;
- }
- this.objects.set(key, bytes);
- }
-
- async get(key: string): Promise<Uint8Array | undefined> {
- const value = this.objects.get(key);
- return value === undefined ? undefined : Uint8Array.from(value);
- }
-
- async open(key: string, range?: { readonly start: number; readonly endExclusive: number }): Promise<AsyncIterable<Uint8Array> | undefined> {
- const value = this.objects.get(key);
- if (value === undefined) return undefined;
- const selected = range === undefined ? value : value.slice(range.start, range.endExclusive);
- return (async function* () {
- yield Uint8Array.from(selected);
- })();
- }
-
- async list(prefix: string, options: {
- readonly limit?: number;
- readonly after?: string;
- readonly delimiter?: string;
- } = {}): Promise<readonly string[]> {
- this.listRequests.push({ prefix, ...options });
- const keys = [...this.objects.keys()].filter((key) => key.startsWith(prefix)).sort();
- const items = options.delimiter === undefined
- ? keys
- : [...new Set(keys.map((key) => {
- const remainder = key.slice(prefix.length);
- const split = remainder.indexOf(options.delimiter!);
- return split < 0 ? key : `${prefix}${remainder.slice(0, split + options.delimiter!.length)}`;
- }))];
- const selected = options.after === undefined ? items : items.filter((item) => item > options.after!);
- return options.limit === undefined ? selected : selected.slice(0, options.limit);
- }
-
- async delete(key: string): Promise<void> {
- this.objects.delete(key);
- }
-}
-
-test("S3 publishes new Outputs without uploading unchanged Result documents", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });
- const writer = await repository.create({
- id: "bld_20260902T100000000Z_0000000001",
- source: { path: "/project/main.svml" }, targets: ["answer"],
- publishedOutputs: [{ name: "answer", output: "logical:answer" }],
- });
- const resources = { async open() { throw new Error("unexpected Resource read"); } };
- const count = client.writes.length;
- await writer.sync({ state: state({ records: [], bindings: [] }), resources });
- assert.equal(client.writes.length, count);
- const accepted = state({
- records: [{ id: "record:answer", type: videoType, value: { kind: "inline", value: 42 } }],
- bindings: [{ output: "logical:answer", record: "record:answer" }],
- });
- await writer.sync({ state: accepted, resources });
- const published = client.writes.length;
- assert.ok(published > count);
- assert.deepEqual((await writer.read()).outputs.answer?.value, { kind: "inline", value: 42 });
- await writer.sync({ state: accepted, resources });
- assert.equal(client.writes.length, published);
- await writer.finish({ outcome: "cancelled" });
- assert.equal((await writer.read()).outcome, "cancelled");
- assert.deepEqual((await writer.read()).outputs.answer?.value, { kind: "inline", value: 42 });
-});
-
-function state(input: {
- readonly status?: BuildState["status"];
- readonly records: BuildState["records"];
- readonly bindings: readonly { readonly output: string; readonly record: string }[];
-}): BuildState {
- return {
- status: input.status ?? "active",
- records: input.records,
- plan: {
- outputBindings: input.bindings.map((binding) => ({
- ...binding,
- type: input.records.find((record) => record.id === binding.record)!.type,
- })),
- },
- } as unknown as BuildState;
-}
-
-test("S3 keeps the same Build Result model as the filesystem repository", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({
- bucket: "unused-by-memory-client",
- prefix: "projects/episode-12",
- client,
- });
- const bytes = new TextEncoder().encode("one video");
- const video: BlobRef = {
- kind: "blob",
- resource: "res_same_build_video",
- size: bytes.byteLength,
- mediaType: "video/mp4",
- };
- const writer = await repository.create({
- id: "bld_20260902T100000000Z_0000000001",
- title: "opening variants",
- source: { path: "/project/main.svml" },
- run: { path: "/project/build.svrun" },
- targets: ["shot.video"],
- publishedOutputs: [
- { name: "shot.take", output: "logical:take" },
- { name: "shot.video", output: "logical:video" },
- ],
- });
- const storedManifestKey = [...client.objects.keys()].find((key) => key.endsWith("/result.json"));
- assert.notEqual(storedManifestKey, undefined);
- const storedManifest = JSON.parse(new TextDecoder().decode(client.objects.get(storedManifestKey!)!)) as object;
- assert.equal(Object.hasOwn(storedManifest, "id"), false);
- assert.equal((await writer.read()).id, "bld_20260902T100000000Z_0000000001");
- const manifest = await writer.sync({
- state: state({
- records: [
- { id: "record:video", type: videoType, value: video },
- {
- id: "record:take",
- type: compositeType,
- value: {
- kind: "inline",
- value: { media: { visual: { artifact: video } } },
- },
- },
- ],
- bindings: [
- {
- output: "logical:video",
- record: "record:video",
- },
- {
- output: "logical:take",
- record: "record:take",
- },
- ],
- }),
- resources: {
- async open() {
- return (async function* () {
- yield bytes;
- })();
- },
- },
- });
-
- assert.equal(manifest.title, "opening variants");
- assert.equal(manifest.outputs["shot.video"]?.value.kind, "build-file");
- assert.equal(manifest.outputs["shot.take"]?.value.kind, "value");
- assert.deepEqual(
- [...client.objects.keys()].filter((key) => key.includes("/files/")).map((key) => key.slice(key.indexOf("/files/"))),
- ["/files/file-0001.mp4"],
- );
- const resolvedTake = await repository.resolve("bld_20260902T100000000Z_0000000001", "shot.take");
- assert.equal(resolvedTake?.value.kind, "value");
- if (resolvedTake?.value.kind !== "value") throw new Error("expected Composite Result value");
- assert.deepEqual(resolvedTake.value.document, {
- format: "hypit.result-value@1",
- value: { media: { visual: { artifact: null } } },
- resources: [{
- at: ["media", "visual", "artifact"],
- file: {
- kind: "build-file",
- path: "files/file-0001.mp4",
- size: bytes.byteLength,
- mediaType: "video/mp4",
- },
- }],
- });
- assert.deepEqual(
- (await repository.browse({ limit: 20 })).results.map((item) => item.id),
- [],
- );
- await writer.finish({ outcome: "complete" });
- await writer.finish({ outcome: "complete" });
- assert.equal(client.objects.has("projects/episode-12/bld_20260902T100000000Z_0000000001/.writer.json"), false);
- await assert.rejects(
- writer.finish({ outcome: "failed", failure: "different" }),
- /already finished with a different outcome/u,
- );
- assert.deepEqual((await repository.browse({ limit: 20 })).results.map((item) => item.id), ["bld_20260902T100000000Z_0000000001"]);
- const presented = await repository.updatePresentation("bld_20260902T100000000Z_0000000001", {
- outputDisplayNames: { "shot.video": "Opening portrait" },
- title: "Episode 12 opening",
- note: "Preferred composite.",
- highlightedOutputs: ["shot.video"],
- });
- assert.equal(presented.outputs["shot.video"]?.displayName, "Opening portrait");
- assert.equal((await repository.read(presented.id))?.outputs["shot.video"]?.displayName, "Opening portrait");
- assert.equal(presented.title, "Episode 12 opening");
- assert.equal(presented.note, "Preferred composite.");
- assert.deepEqual(presented.highlightedOutputs, ["shot.video"]);
-});
-
-test("S3 opens only the requested byte range of a Result file", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "unused", client });
- const bytes = new TextEncoder().encode("0123456789");
- const build = "bld_20260902T100000010Z_0000000001";
- const physical = `${(Number.MAX_SAFE_INTEGER - Date.parse("2026-09-02T10:00:00.010Z")).toString().padStart(16, "0")}-${build}`;
- client.objects.set(`${physical}/files/video.mp4`, bytes);
- const stream = await repository.openFile(build, {
- kind: "build-file",
- path: "files/video.mp4",
- size: bytes.byteLength,
- mediaType: "video/mp4",
- }, { start: 2, endExclusive: 6 });
- assert.notEqual(stream, undefined);
- const chunks: number[] = [];
- for await (const chunk of stream!) chunks.push(...chunk);
- assert.equal(new TextDecoder().decode(Uint8Array.from(chunks)), "2345");
-});
-
-test("S3 uses the shared Result decoder before exposing a manifest", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "unused", client });
- const build = "bld_20260902T100000012Z_0000000001";
- const physical = `${(Number.MAX_SAFE_INTEGER - Date.parse("2026-09-02T10:00:00.012Z")).toString().padStart(16, "0")}-${build}`;
- client.objects.set(`${physical}/result.json`, new TextEncoder().encode(JSON.stringify({
- format: "hypit.build-result@1",
- source: { path: "main.svml" },
- targets: [],
- outputs: null,
- })));
- await assert.rejects(repository.read(build), /result\.json\.outputs must be an object/u);
-});
-
-test("S3 diagnosis performs one bounded prefix listing", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({
- bucket: "unused",
- prefix: "projects/episode-12",
- client,
- });
- await repository.diagnose();
- assert.deepEqual(client.listRequests, [{ prefix: "projects/episode-12/", limit: 1 }]);
-});
-
-test("S3 browses ordered Build ids newest first with a public cursor", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({
- bucket: "unused",
- prefix: "projects/episode-12",
- client,
- });
- const ids = [
- "bld_20260902T100000001Z_0000000001",
- "bld_20260902T100000002Z_0000000001",
- "bld_20260902T100000003Z_0000000001",
- ];
- for (const id of ids) {
- const writer = await repository.create({
- id,
- source: { path: "/project/main.svml" },
- targets: ["video"],
- publishedOutputs: [{ name: "video", output: "logical:video" }],
- });
- await writer.finish({ outcome: "failed", failure: "ordering fixture" });
- }
-
- const first = await repository.browse({ limit: 2 });
- assert.deepEqual(first.results.map((item) => item.id), [ids[2], ids[1]]);
- assert.equal(first.next, ids[1]);
- if (first.next === undefined) throw new Error("expected an older Result cursor");
- const second = await repository.browse({ limit: 2, before: first.next });
- assert.deepEqual(second.results.map((item) => item.id), [ids[0]]);
- assert.equal(second.next, undefined);
- assert.equal(client.listRequests.at(-1)?.after?.endsWith(`-${ids[1]}/`), true);
-});
-
-test("S3 reduces repeated reuse to its finished content owner without copying bytes", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "fixture", client });
- const bytes = new TextEncoder().encode("historical video");
- const original = await repository.create({
- id: "bld_20260902T100000001Z_0000000001",
- source: { path: "/project/main.svml" },
- targets: ["video"],
- publishedOutputs: [{ name: "video", output: "logical:video" }],
- });
- await original.sync({
- state: state({
- status: "complete",
- records: [
- {
- id: "record:video",
- type: videoType,
- value: {
- kind: "blob",
- resource: "res_original",
- size: bytes.byteLength,
- mediaType: "video/mp4",
- },
- },
- ],
- bindings: [
- {
- output: "logical:video",
- record: "record:video",
- },
- ],
- }),
- resources: {
- async open() {
- return (async function* () {
- yield bytes;
- })();
- },
- },
- });
- await assert.rejects(
- repository.create({
- id: "bld_20260902T100000002Z_0000000001",
- source: { path: "/project/main.svml" },
- targets: ["video"],
- publishedOutputs: [{ name: "video", output: "logical:video" }],
- forwards: [{
- output: "logical:video",
- build: "bld_20260902T100000001Z_0000000001",
- sourceOutput: "video",
- }],
- }),
- /is not a finished Result/u,
- );
- await original.finish({ outcome: "complete" });
- await assert.rejects(
- repository.removeIncomplete("bld_20260902T100000001Z_0000000001"),
- /cannot be removed/u,
- );
-
- const forward = async (id: string, fromBuild: string) => {
- const writer = await repository.create({
- id,
- source: { path: "/project/main.svml" },
- targets: ["video"],
- publishedOutputs: [{ name: "video", output: "logical:video" }],
- forwards: [{ output: "logical:video", build: fromBuild, sourceOutput: "video" }],
- });
- const manifest = await writer.sync({
- state: state({
- status: "complete",
- records: [
- {
- id: "record:reused",
- type: videoType,
- value: {
- kind: "blob",
- resource: "res_reused",
- size: bytes.byteLength,
- mediaType: "video/mp4",
- },
- },
- ],
- bindings: [
- {
- output: "logical:video",
- record: "record:reused",
- },
- ],
- }),
- resources: {
- async open() {
- throw new Error("forwarded bytes must not be copied");
- },
- },
- });
- await writer.finish({ outcome: "complete" });
- return manifest;
- };
- await forward("bld_20260902T100000002Z_0000000001", "bld_20260902T100000001Z_0000000001");
- const forwardedAgain = await forward(
- "bld_20260902T100000003Z_0000000001",
- "bld_20260902T100000002Z_0000000001",
- );
- assert.deepEqual(forwardedAgain.outputs.video?.value, {
- kind: "build-output",
- build: "bld_20260902T100000001Z_0000000001",
- output: "video",
- });
-
- const described = await repository.describeOutput("bld_20260902T100000003Z_0000000001", "video");
- assert.equal(described?.kind, "resource");
- const resolved = await repository.resolve("bld_20260902T100000003Z_0000000001", "video");
- assert.equal(resolved?.build, "bld_20260902T100000001Z_0000000001");
- assert.equal(resolved?.value.kind, "build-file");
- if (resolved?.value.kind !== "build-file") throw new Error("expected historical file");
- const opened = await repository.openFile(resolved.build, resolved.value);
- if (opened === undefined) throw new Error("expected historical file bytes");
- const chunks: Uint8Array[] = [];
- for await (const chunk of opened) chunks.push(chunk);
- assert.equal(new TextDecoder().decode(Uint8Array.from(chunks.flatMap((chunk) => [...chunk]))), "historical video");
- assert.equal([...client.objects.keys()].filter((key) => key.includes("/files/")).length, 1);
-});
-
-test("S3 Composite values retain external and prior-Result Resource references", async () => {
- const client = new MemoryS3();
- let external = new Uint8Array([1, 2, 3]);
- const repository = new S3BuildResultRepository({ bucket: "test", prefix: "project", client,
- externalFiles: {
- async size(uri) { assert.equal(uri, "asset://selected/photo"); return external.length; },
- async open(uri, range) {
- assert.equal(uri, "asset://selected/photo");
- return (async function* () { yield range === undefined ? external : external.slice(range.start, range.endExclusive); })();
- },
- },
- });
- const originalId = "bld_20260902T100000000Z_0000000001";
- const reusedId = "bld_20260902T100000001Z_0000000001";
- const video: BlobRef = { kind: "blob", resource: "res_generated", size: 2, mediaType: "video/mp4" };
- const original = await repository.create({ id: originalId, source: { path: "main.svml" },
- targets: ["video"], publishedOutputs: [{ name: "video", output: "video" }] });
- await original.sync({ state: state({ records: [{ id: "r", type: videoType, value: video }],
- bindings: [{ output: "video", record: "r" }] }),
- resources: { async open() { return (async function* () { yield new Uint8Array([8, 9]); })(); } } });
- await original.finish({ outcome: "complete" });
- const saved = (await repository.resolve(originalId, "video"))!;
- assert.equal(saved.value.kind, "build-file");
- if (saved.value.kind !== "build-file") throw new Error("expected file");
- const photo: BlobRef = { kind: "blob", resource: "res_photo", size: 3, mediaType: "image/png" };
- const writer = await repository.create({ id: reusedId, source: { path: "main.svml" }, targets: ["layout"],
- publishedOutputs: [{ name: "layout", output: "layout" }], resourceReferences: {
- [photo.resource]: { kind: "external-file", uri: "asset://selected/photo", size: 3, mediaType: "image/png" },
- [video.resource]: { ...saved.value, build: originalId },
- } });
- await writer.sync({ state: state({ records: [{ id: "r", type: compositeType,
- value: { kind: "inline", value: { layers: [{ parts: [photo, { clip: video, repeated: photo }] }] } } }],
- bindings: [{ output: "layout", record: "r" }] }),
- resources: { async open() { throw new Error("Referenced resources cannot be uploaded again"); } } });
- await writer.finish({ outcome: "complete" });
- assert.equal([...client.objects.keys()].filter((key) => key.includes("/files/")).length, 1);
- const resolved = (await repository.resolve(reusedId, "layout"))!;
- assert.equal(resolved.value.kind, "value");
- if (resolved.value.kind !== "value") throw new Error("expected composite");
- assert.equal(resolved.value.document.resources.length, 3);
- const oldVideo = resolved.value.document.resources.find((binding) => binding.file.kind === "build-file")!;
- assert.deepEqual(oldVideo.file, { ...saved.value, build: originalId });
- const chunks: Uint8Array[] = [];
- for await (const chunk of (await repository.openFile(reusedId, oldVideo.file))!) chunks.push(chunk);
- assert.deepEqual(Buffer.concat(chunks), Buffer.from([8, 9]));
- const externalRef = resolved.value.document.resources.find((binding) => binding.file.kind === "external-file")!.file;
- external = new Uint8Array([4, 5, 6, 7]);
- assert.equal((await repository.describeFile(reusedId, externalRef)).size, 4);
- const selected: Uint8Array[] = [];
- for await (const chunk of (await repository.openFile(reusedId, externalRef, { start: 1, endExclusive: 3 }))!) selected.push(chunk);
- assert.deepEqual(Buffer.concat(selected), Buffer.from([5, 6]));
-});
-
-test("S3 preserves execution evidence before terminal publication and does not repeat it on finish", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });
- const id = "bld_20260913T130000000Z_0000000001";
- const writer = await repository.create({ id, source: { path: "main.svml" }, targets: [], publishedOutputs: [] });
- const text = '{"format":"hypit.execution-log@1","message":"renderer stopped"}\n';
- const manifest = await writer.finish({ outcome: "cancelled", executionLog: (async function* () { yield Buffer.from(text); })() });
- assert.ok(manifest.executionLog);
- assert.deepEqual(manifest.outputs, {});
- assert.equal(manifest.executionLog.size, Buffer.byteLength(text));
- assert.ok(client.writes.at(-2)?.endsWith("execution.jsonl"));
- assert.ok(client.writes.at(-1)?.endsWith("result.json"));
- const reopened = await repository.read(id);
- const stream = await repository.openFile(id, reopened!.executionLog!);
- let read = "";
- for await (const chunk of stream!) read += Buffer.from(chunk).toString();
- assert.equal(read, text);
- const count = client.writes.length;
- await writer.finish({ outcome: "cancelled" });
- assert.equal(client.writes.length, count);
-});
-
-test("failed log archival keeps the Result open and finishing again performs only storage", async () => {
- const client = new MemoryS3();
- const repository = new S3BuildResultRepository({ bucket: "unused", prefix: "project", client });
- const id = "bld_20260913T130000000Z_0000000002";
- const writer = await repository.create({ id, source: { path: "main.svml" }, targets: [], publishedOutputs: [] });
- await assert.rejects(writer.finish({ outcome: "failed", failure: "render stopped", executionLog: (async function* () {
- yield Buffer.from('first record\n'); throw new Error("log read failed");
- })() }), /log read failed/);
- assert.equal((await repository.read(id))!.outcome, undefined);
- const result = await writer.finish({ outcome: "failed", failure: "render stopped", executionLog: (async function* () {
- yield Buffer.from('complete record\n');
- })() });
- assert.equal(result.outcome, "failed");
- assert.ok(result.executionLog);
-});
diff --git a/packages/compiler-markup-node/README.md b/packages/compiler-markup-node/README.md
deleted file mode 100644
index 62c910db..00000000
--- a/packages/compiler-markup-node/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# `@hypit/compiler-markup-node`
-
-Reference Node compiler assembly for the official `@hypit/markup` authoring language.
-
-The package selects the Markup Frontend ABI, installs Markup Surface Host facets from already trusted
-package contributions, and combines them with the syntax-neutral `@hypit/compiler-node`. It does not
-discover packages, grant Runtime authority or know any video component by name.
-
-Every compiled source selects Markup—or another registered Frontend—through its mandatory Source
-Header. Use `@hypit/compiler-node` directly for another Frontend assembly. Use
-`@hypit/package-loader-node` independently when a Runtime only needs locked deterministic compute
-facets and no author syntax.
diff --git a/packages/compiler-markup-node/package.json b/packages/compiler-markup-node/package.json
deleted file mode 100644
index 9f050d15..00000000
--- a/packages/compiler-markup-node/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "@hypit/compiler-markup-node",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/compiler-node": "workspace:*",
- "@hypit/component-kit": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/workspace": "workspace:*",
- "@hypit/package-loader-node": "workspace:*",
- "@hypit/markup": "workspace:*",
- "@hypit/validation": "workspace:*"
- },
- "devDependencies": {
- "@hypit/workspace-fs-node": "workspace:*"
- }
-}
diff --git a/packages/compiler-markup-node/src/index.ts b/packages/compiler-markup-node/src/index.ts
deleted file mode 100644
index 6988140f..00000000
--- a/packages/compiler-markup-node/src/index.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { registerTypeValidatorFacets } from "@hypit/component-kit";
-import {
- ModulePackageRegistry,
- NodeCompiler,
-} from "@hypit/compiler-node";
-import { AuthorFrontendRegistry, installAuthorFrontendHostFacets } from "@hypit/elaborator";
-import type { Workspace } from "@hypit/workspace";
-import {
- collectNodePackageComponents,
-} from "@hypit/package-loader-node";
-import type { NodePackageContribution } from "@hypit/package-loader-node";
-import {
- createMarkupAuthorFrontend,
- installMarkupSurfaceHostFacets,
- MarkupSurfaceRegistry,
-} from "@hypit/markup";
-import { TypeValidatorRegistry } from "@hypit/validation";
-
-export type CreateMarkupNodeCompilerOptions = {
- readonly workspace: Workspace;
-};
-
-/** Assemble the official Markup authoring environment from already trusted package facets. */
-export function createMarkupNodeCompiler(
- packages: readonly NodePackageContribution[],
- options: CreateMarkupNodeCompilerOptions,
-): NodeCompiler {
- const modules = new ModulePackageRegistry();
- const surfaces = new MarkupSurfaceRegistry();
- const frontends = new AuthorFrontendRegistry();
- const validators = new TypeValidatorRegistry();
- const components = collectNodePackageComponents(packages);
-
- for (const item of packages) {
- for (const module of item.modules ?? []) modules.register(module);
- installMarkupSurfaceHostFacets(item.hostFacets ?? [], surfaces);
- installAuthorFrontendHostFacets(item.hostFacets ?? [], frontends);
- }
-
- for (const component of components) {
- registerTypeValidatorFacets(validators, component.validators ?? []);
- }
-
- frontends.register(createMarkupAuthorFrontend({
- registry: surfaces,
- resolveModule(request) {
- const resolved = modules.resolve(request.from);
- if (resolved === undefined) throw new Error(`No selected author package satisfies ${request.from}`);
- return resolved;
- },
- }));
-
- return new NodeCompiler({
- modules,
- frontends,
- validators,
- workspace: options.workspace,
- });
-}
diff --git a/packages/compiler-markup-node/test/compiler.test.ts b/packages/compiler-markup-node/test/compiler.test.ts
deleted file mode 100644
index 8fcbb3b8..00000000
--- a/packages/compiler-markup-node/test/compiler.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import assert from "node:assert/strict";
-import {
- mkdtemp,
- rm,
- writeFile,
-} from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-
-import { createMarkupNodeCompiler } from "@hypit/compiler-markup-node";
-import type { NodePackageContribution } from "@hypit/package-loader-node";
-import { createMarkupSurfaceHostFacet } from "@hypit/markup";
-import { NodeFilesystemWorkspace } from "@hypit/workspace-fs-node";
-
-const module = { name: "example.card", version: "1" } as const;
-const resultType = { module, name: "CardResult" } as const;
-const cardSurface = {
- name: "card",
- tag: "Card",
- mode: "structured",
- outputs: [resultType],
-} as const;
-
-const installedPackage: NodePackageContribution = {
- format: "hypit.node-package@1",
- modules: [{
- manifest: {
- format: "hypit.module@1",
- name: module.name,
- version: module.version,
- dependencies: [],
- types: [{ name: resultType.name }],
- capabilities: [],
- producers: [],
- },
- specifiers: ["example.card@1"],
- }],
- hostFacets: [
- createMarkupSurfaceHostFacet({
- module,
- declaration: cardSurface,
- handler({ element }) {
- return {
- records: [{
- id: "card-result",
- type: resultType,
- value: { kind: "inline", value: "accepted" },
- range: element.range,
- }],
- components: [],
- fragments: [],
- };
- },
- }),
- {
- abi: "example.unselected-host@1",
- implementation() {
- throw new Error("an unselected Host facet executed");
- },
- },
- ],
-};
-
-test("Markup compiler alone selects Markup Surface Host facets from a generic package contribution", async () => {
- const root = await mkdtemp(join(tmpdir(), "hypit-markup-compiler-"));
- try {
- const source = join(root, "main.svml");
- await writeFile(source, `<?svml using="@hypit/markup@1"?>
- <svml>
- <import as="example" from="example.card@1"/>
- <example:Card/>
- </svml>`, "utf8");
- const compiler = createMarkupNodeCompiler([installedPackage], {
- workspace: new NodeFilesystemWorkspace({ root }),
- });
- const result = await compiler.compileFile(source);
-
- assert.deepEqual(result.program.closure.modules.map((item) => ({
- name: item.manifest.name,
- version: item.manifest.version,
- })), [module]);
- assert.equal(result.program.records[0]?.value.kind, "inline");
- assert.equal(result.graph.operations.length, 0);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-});
diff --git a/packages/compiler-node/README.md b/packages/compiler/README.md
similarity index 73%
rename from packages/compiler-node/README.md
rename to packages/compiler/README.md
index 213169c8..727a46bb 100644
--- a/packages/compiler-node/README.md
+++ b/packages/compiler/README.md
@@ -1,28 +1,30 @@
-# `@hypit/compiler-node`
+# `@hypit/compiler`
-Domain-neutral Node.js compiler host.
+Domain-neutral compilation orchestration.
This package is outside Core. It connects a replaceable definition-time `Workspace` to the already
implemented compiler IR:
```text
-Source Header + registered Frontends + registered manifests
+ResolvedSource + registered Frontends + registered manifests
-> discovered Source/Module closure
-> typed Source Closure
-> Author Module + Graph
```
-Every Author Source selects its own exact Frontend through the mandatory `@hypit/source` Header.
-The compiler has no suffix table and no entry-Frontend default. A recursively imported source may
-select another Frontend without the importer choosing on its behalf.
+Every Author Source reaches the compiler as a `ResolvedSource` with an exact Frontend. The default
+filesystem Workspace can obtain that binding through `@hypit/source/text`; another Workspace or
+package Source export can provide it directly. The compiler has no suffix table, body bootstrap or
+entry-Frontend default. A recursively imported Source may select another Frontend through its own
+resolution authority.
`ModulePackageRegistry` maps author import spellings to exact, already trusted manifests and closes
their declared Resource dependencies. It does not install npm packages or execute module code. An
embedding application must register the manifests and matching Frontend/Surface implementations it
has chosen to trust.
-`NodeCompiler` requires the host-neutral `Workspace` contract. The reference CLI explicitly selects
-`@hypit/workspace-fs-node`, where every recursive Source import is confined to the canonical root
+`Compiler` requires the host-neutral `Workspace` contract. The reference CLI explicitly selects
+`@hypit/workspace/node`, where every recursive Source import is confined to the canonical root
that owns the importing SourceUnit, symlink escapes are rejected and each edge is locked to the
first bytes read for that compilation. The Host may explicitly mount another Source root; the
Compiler sees only the resulting Workspace units and does not know whether that root came from an
@@ -32,7 +34,7 @@ Workspace without changing Frontends, Surfaces, Source Closure identity or Core.
The Workspace session owns a separate Source Asset capability. A Frontend/Surface may request an
asset and assign its exact media type, but it never receives a path, filesystem handle or ambient
read authority. The Workspace returns a `BlobRef`, the compiler binds that reference into the
-requesting SourceUnit, and the session exposes defensive generic `ArtifactAttachment`s on the Node
+requesting SourceUnit, and the session exposes defensive generic `BlobAttachment`s on the Node
compilation result. `check` and `plan` perform no ResourceStore write. `build` passes the attachments
to the selected Runtime for size-checked staging.
@@ -40,11 +42,11 @@ SourceUnit recursion and Source Asset resolution are intentionally different cap
asset cannot import syntax, and a source import does not silently make arbitrary neighboring bytes
available to package code.
-`NodeCompiler` runs a discovery pass first because Headers and imports must be known before source decoding,
+`Compiler` runs a discovery pass first because imports must be known before source decoding,
while the exact Module Closure must be known before typed Records can be verified. It then invokes
-the ordinary Elaborator Source Closure implementation.
+the Source Closure compiler and parser-independent Author linker.
-`NodeRunCompiler` is the separate dual-graph assembly. It compiles one self-described Run Source,
+`RunCompiler` is the separate dual-graph assembly. It compiles one resolved Run Source,
opens its explicitly named Author Source in the same Workspace session, resolves the complete Run
Graph, extends the execution Program Closure with Modules referenced only by selected Run
Fragments, binds Author and Run graph identities into the final immutable graph, and only then asks
diff --git a/packages/compiler-node/package.json b/packages/compiler/package.json
similarity index 59%
rename from packages/compiler-node/package.json
rename to packages/compiler/package.json
index de2a259a..af439562 100644
--- a/packages/compiler-node/package.json
+++ b/packages/compiler/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/compiler-node",
+ "name": "@hypit/compiler",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
@@ -8,18 +8,17 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/core": "workspace:*",
- "@hypit/elaborator": "workspace:*",
+ "@hypit/kernel": "workspace:*",
+ "@hypit/author": "workspace:*",
"@hypit/workspace": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/run": "workspace:*",
"@hypit/source": "workspace:*",
- "@hypit/text": "workspace:*",
- "@hypit/validation": "workspace:*"
+ "@hypit/admission": "workspace:*"
},
"devDependencies": {
- "@hypit/run-markup": "workspace:*",
"@hypit/markup": "workspace:*",
- "@hypit/workspace-fs-node": "workspace:*"
+ "@hypit/markup": "workspace:*",
+ "@hypit/workspace": "workspace:*"
}
}
diff --git a/packages/compiler-node/src/compiler.ts b/packages/compiler/src/compiler.ts
similarity index 55%
rename from packages/compiler-node/src/compiler.ts
rename to packages/compiler/src/compiler.ts
index 5ee3245a..065e2afa 100644
--- a/packages/compiler-node/src/compiler.ts
+++ b/packages/compiler/src/compiler.ts
@@ -1,30 +1,25 @@
-import { randomUUID } from "node:crypto";
-
-import {
- compileSourceClosure,
- prepareAuthorSource,
-} from "@hypit/elaborator";
-import { link } from "@hypit/core";
+import { link } from "@hypit/kernel";
import type {
AuthorFrontendRegistryLike,
AuthorSourceDiscovery,
CompiledSourceClosure,
AuthorRecordAdmitter,
-} from "@hypit/elaborator";
-import type { SourceUnit } from "@hypit/source";
-import type { ArtifactAttachment, Workspace, WorkspaceSession } from "@hypit/workspace";
+} from "@hypit/author";
+import type { ResolvedSource, SourceUnit } from "@hypit/source";
+import type { BlobAttachment, Workspace, WorkspaceSession } from "@hypit/workspace";
import type { BlobRef, LinkedProgram } from "@hypit/protocol";
import {
TypeValidatorRegistry,
createRecordAdmitter,
-} from "@hypit/validation";
-import type { TypeValidatorRegistryLike } from "@hypit/validation";
+} from "@hypit/admission";
+import type { TypeValidatorRegistryLike } from "@hypit/admission";
-import { NodeCompilerError } from "./error.js";
+import { CompilerError } from "./error.js";
import type { ModulePackageRegistryLike } from "./modules.js";
+import { compileSourceClosure } from "./source.js";
type DiscoveredUnit = {
- readonly source: SourceUnit;
+ readonly source: ResolvedSource;
readonly frontend: string;
readonly discovery: AuthorSourceDiscovery;
};
@@ -33,14 +28,14 @@ function attachmentKey(artifact: BlobRef): string {
return `${artifact.resource}\u0000${artifact.mediaType}`;
}
-export function mergeAttachments(groups: readonly (readonly ArtifactAttachment[])[]): readonly ArtifactAttachment[] {
- const merged = new Map<string, ArtifactAttachment>();
+export function mergeAttachments(groups: readonly (readonly BlobAttachment[])[]): readonly BlobAttachment[] {
+ const merged = new Map<string, BlobAttachment>();
for (const item of groups.flat()) {
const key = attachmentKey(item.artifact);
const existing = merged.get(key);
if (existing !== undefined) {
if (existing.artifact.size !== item.artifact.size) {
- throw new NodeCompilerError(
+ throw new CompilerError(
"SOURCE_ATTACHMENT_CONFLICT",
`Artifact attachment ${item.artifact.resource} carries conflicting sizes`,
item.artifact.resource,
@@ -59,28 +54,27 @@ export function mergeAttachments(groups: readonly (readonly ArtifactAttachment[]
}
async function discoverClosure(
- entry: SourceUnit,
+ entry: ResolvedSource,
frontends: AuthorFrontendRegistryLike,
workspace: WorkspaceSession,
): Promise<readonly DiscoveredUnit[]> {
const units = new Map<string, DiscoveredUnit>();
const visiting = new Set<string>();
- const visit = async (source: SourceUnit): Promise<void> => {
- const prepared = prepareAuthorSource(source);
- const selectedFrontend = prepared.header.using;
- const key = `${source.id}\u0000${selectedFrontend}`;
+ const visit = async (source: ResolvedSource): Promise<void> => {
+ const selectedFrontend = source.frontend;
+ const key = `${source.unit.id}\u0000${selectedFrontend}`;
if (units.has(key)) return;
if (visiting.has(key)) {
- throw new NodeCompilerError("SOURCE_IMPORT_CYCLE", `Source imports cycle through ${source.name}`, source.id);
+ throw new CompilerError("SOURCE_IMPORT_CYCLE", `Source imports cycle through ${source.unit.name}`, source.unit.id);
}
const frontend = frontends.resolve(selectedFrontend);
if (frontend === undefined) {
- throw new NodeCompilerError("UNKNOWN_FRONTEND", `Frontend ${selectedFrontend} is not registered`, selectedFrontend);
+ throw new CompilerError("UNKNOWN_FRONTEND", `Frontend ${selectedFrontend} is not registered`, selectedFrontend);
}
visiting.add(key);
- const discovery = await frontend.discover(prepared);
+ const discovery = await frontend.discover(source.unit);
for (const request of discovery.sources) {
- await visit(await workspace.resolveSource(source, request));
+ await visit(await workspace.resolveSource(source.unit, request));
}
visiting.delete(key);
units.set(key, { source, frontend: selectedFrontend, discovery });
@@ -89,7 +83,7 @@ async function discoverClosure(
return [...units.values()];
}
-export type NodeCompilerOptions = {
+export type CompilerOptions = {
readonly modules: ModulePackageRegistryLike;
readonly frontends: AuthorFrontendRegistryLike;
/** Explicit definition environment selected by the Host. */
@@ -98,17 +92,17 @@ export type NodeCompilerOptions = {
readonly validators?: TypeValidatorRegistryLike;
};
-export type NodeCompiledSourceClosure = CompiledSourceClosure & {
+export type CompiledAuthorSource = CompiledSourceClosure & {
/** Host-side transfer bundle; bytes are not serialized into Core BuildState. */
- readonly attachments: readonly ArtifactAttachment[];
+ readonly attachments: readonly BlobAttachment[];
};
-/** Domain-neutral Node facade from a real Author Source to a verified Source Closure and Graph. */
-export class NodeCompiler {
- readonly #options: NodeCompilerOptions;
+/** Domain-neutral compiler from a resolved Author Source to a verified Source Closure and Graph. */
+export class Compiler {
+ readonly #options: CompilerOptions;
readonly #admitRecord: AuthorRecordAdmitter;
- constructor(options: NodeCompilerOptions) {
+ constructor(options: CompilerOptions) {
this.#options = options;
this.#admitRecord = createRecordAdmitter(options.validators ?? new TypeValidatorRegistry());
}
@@ -117,19 +111,18 @@ export class NodeCompiler {
return this.#options.frontends.resolve(id) !== undefined;
}
- /** Open one read-once Workspace session so a Host can inspect the Source Header and compile it once. */
- async openFile(file: string): Promise<WorkspaceSession> {
- return await this.#options.workspace.open(file);
+ /** Open one read-once Workspace session for an explicitly selected entry locator. */
+ async openEntry(locator: string): Promise<WorkspaceSession> {
+ return await this.#options.workspace.open(locator);
}
- async compileFile(file: string): Promise<NodeCompiledSourceClosure> {
- const workspace = await this.openFile(file);
- return await this.compileSource(workspace.entry, workspace);
+ async compileEntry(locator: string): Promise<CompiledAuthorSource> {
+ const workspace = await this.openEntry(locator);
+ return await this.compileResolvedSource(workspace.entry, workspace);
}
- /** Compile an explicitly resolved self-describing SourceUnit inside one already isolated Workspace. */
- async compileSource(entry: SourceUnit, workspace: WorkspaceSession): Promise<NodeCompiledSourceClosure> {
- const embeddedAttachments = new Map<string, ArtifactAttachment>();
+ /** Compile an explicitly resolved Source inside one already isolated Workspace. */
+ async compileResolvedSource(entry: ResolvedSource, workspace: WorkspaceSession): Promise<CompiledAuthorSource> {
const discovered = await discoverClosure(
entry,
this.#options.frontends,
@@ -139,7 +132,7 @@ export class NodeCompiler {
discovered.flatMap((unit) => unit.discovery.modules),
);
const discoveries = new Map(discovered.map((unit) => [
- `${unit.source.id}\u0000${unit.frontend}`,
+ `${unit.source.unit.id}\u0000${unit.frontend}`,
unit.discovery,
]));
const compilation = await compileSourceClosure({
@@ -149,7 +142,7 @@ export class NodeCompiler {
discover(source, frontend) {
const discovery = discoveries.get(`${source.id}\u0000${frontend.id}`);
if (discovery === undefined) {
- throw new NodeCompilerError(
+ throw new CompilerError(
"SOURCE_DISCOVERY_MISSING",
`Source ${source.name} was not present in the frozen discovery closure`,
source.id,
@@ -158,35 +151,12 @@ export class NodeCompiler {
return discovery;
},
resolveSource: workspace.resolveSource,
- async resolveAsset(importer, request) {
- if (request.bytes === undefined) return await workspace.resolveAsset(importer, request);
- const bytes = Uint8Array.from(request.bytes);
- const artifact: BlobRef = {
- kind: "blob",
- resource: `res_${randomUUID()}`,
- size: bytes.byteLength,
- mediaType: request.mediaType,
- };
- const key = attachmentKey(artifact);
- const existing = embeddedAttachments.get(key);
- if (existing !== undefined && existing.artifact.size !== bytes.byteLength) {
- throw new NodeCompilerError(
- "SOURCE_ATTACHMENT_CONFLICT",
- `Embedded asset ${request.from} conflicts with ${artifact.resource}`,
- request.from,
- );
- }
- embeddedAttachments.set(key, {
- artifact,
- open: async () => (async function* () { yield Uint8Array.from(bytes); })(),
- });
- return { artifact: { ...artifact } };
- },
+ resolveAsset: workspace.resolveAsset,
admitRecord: this.#admitRecord,
});
return {
...compilation,
- attachments: mergeAttachments([await workspace.attachments(), [...embeddedAttachments.values()]]),
+ attachments: mergeAttachments([await workspace.attachments()]),
};
}
diff --git a/packages/compiler-node/src/error.ts b/packages/compiler/src/error.ts
similarity index 71%
rename from packages/compiler-node/src/error.ts
rename to packages/compiler/src/error.ts
index 66f32602..2a867079 100644
--- a/packages/compiler-node/src/error.ts
+++ b/packages/compiler/src/error.ts
@@ -1,10 +1,10 @@
-export class NodeCompilerError extends Error {
+export class CompilerError extends Error {
readonly code: string;
readonly subject: string | undefined;
constructor(code: string, message: string, subject?: string) {
super(message);
- this.name = "NodeCompilerError";
+ this.name = "CompilerError";
this.code = code;
this.subject = subject;
}
diff --git a/packages/compiler-node/src/graph-query.ts b/packages/compiler/src/graph-query.ts
similarity index 98%
rename from packages/compiler-node/src/graph-query.ts
rename to packages/compiler/src/graph-query.ts
index 4dcefc16..d0cedf36 100644
--- a/packages/compiler-node/src/graph-query.ts
+++ b/packages/compiler/src/graph-query.ts
@@ -2,7 +2,7 @@ import {
resolveCandidate,
resolveLogicalOutput,
resolveOperation,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
Candidate,
CompiledGraph,
diff --git a/packages/compiler-node/src/index.ts b/packages/compiler/src/index.ts
similarity index 51%
rename from packages/compiler-node/src/index.ts
rename to packages/compiler/src/index.ts
index f6014179..381b958f 100644
--- a/packages/compiler-node/src/index.ts
+++ b/packages/compiler/src/index.ts
@@ -1,4 +1,6 @@
-export { NodeCompilerError } from "./error.js";
+export { CompilerError } from "./error.js";
+export { compileSourceClosure, SourceClosureError } from "./source.js";
+export type { CompileSourceClosureRequest } from "./source.js";
export {
ModulePackageRegistry,
} from "./modules.js";
@@ -6,16 +8,16 @@ export type {
ModulePackageRegistryLike,
RegisteredModulePackage,
} from "./modules.js";
-export { NodeCompiler } from "./compiler.js";
-export { NodeRunCompiler } from "./run.js";
+export { Compiler } from "./compiler.js";
+export { RunCompiler } from "./run.js";
export type {
- NodeCompilerOptions,
- NodeCompiledSourceClosure,
+ CompilerOptions,
+ CompiledAuthorSource,
} from "./compiler.js";
export type {
- NodeCheckedRun,
- NodeCompiledRun,
- NodeRunCompilerOptions,
+ CheckedRun,
+ CompiledRun,
+ RunCompilerOptions,
PlannedBuild,
} from "./run.js";
export {
diff --git a/packages/compiler-node/src/modules.ts b/packages/compiler/src/modules.ts
similarity index 83%
rename from packages/compiler-node/src/modules.ts
rename to packages/compiler/src/modules.ts
index 3e3ba841..b25a60d0 100644
--- a/packages/compiler-node/src/modules.ts
+++ b/packages/compiler/src/modules.ts
@@ -1,11 +1,11 @@
-import { createResolvedClosure } from "@hypit/core";
+import { createResolvedClosure } from "@hypit/kernel";
import type {
ModuleManifest,
ModuleRef,
ResolvedModuleClosure,
} from "@hypit/protocol";
-import { NodeCompilerError } from "./error.js";
+import { CompilerError } from "./error.js";
function moduleKey(ref: ModuleRef): string {
return `${ref.name}@${ref.version}`;
@@ -42,16 +42,16 @@ export class ModulePackageRegistry implements ModulePackageRegistryLike {
const key = moduleKey(ref);
const existing = this.#manifests.get(key);
if (existing !== undefined) {
- throw new NodeCompilerError("DUPLICATE_MODULE_PACKAGE", `Module package ${key} is already registered`, key);
+ throw new CompilerError("DUPLICATE_MODULE_PACKAGE", `Module package ${key} is already registered`, key);
}
const specifiers = new Set([key, ...(value.specifiers ?? [])]);
for (const specifier of specifiers) {
if (specifier.length === 0) {
- throw new NodeCompilerError("EMPTY_MODULE_SPECIFIER", `${key} declares an empty import specifier`, key);
+ throw new CompilerError("EMPTY_MODULE_SPECIFIER", `${key} declares an empty import specifier`, key);
}
const owner = this.#specifiers.get(specifier);
if (owner !== undefined) {
- throw new NodeCompilerError(
+ throw new CompilerError(
"DUPLICATE_MODULE_SPECIFIER",
`Import ${specifier} is already bound to ${owner}`,
specifier,
@@ -74,14 +74,14 @@ export class ModulePackageRegistry implements ModulePackageRegistryLike {
if (included.has(key)) return;
const manifest = this.#manifests.get(key);
if (manifest === undefined) {
- throw new NodeCompilerError("MISSING_MODULE_DEPENDENCY", `Module dependency ${key} is not registered`, key);
+ throw new CompilerError("MISSING_MODULE_DEPENDENCY", `Module dependency ${key} is not registered`, key);
}
included.set(key, manifest);
for (const dependency of manifest.dependencies) {
const dependencyKey = moduleKey(dependency.module);
const resolved = this.#manifests.get(dependencyKey);
if (resolved === undefined) {
- throw new NodeCompilerError(
+ throw new CompilerError(
"MISSING_MODULE_DEPENDENCY",
`${key} requires unregistered module ${dependencyKey}`,
dependencyKey,
@@ -94,7 +94,7 @@ export class ModulePackageRegistry implements ModulePackageRegistryLike {
for (const request of [...new Set(requests)].sort()) {
const key = this.#specifiers.get(request);
if (key === undefined) {
- throw new NodeCompilerError("UNKNOWN_MODULE_IMPORT", `No registered module satisfies ${request}`, request);
+ throw new CompilerError("UNKNOWN_MODULE_IMPORT", `No registered module satisfies ${request}`, request);
}
visit(key);
}
diff --git a/packages/compiler-node/src/run.ts b/packages/compiler/src/run.ts
similarity index 84%
rename from packages/compiler-node/src/run.ts
rename to packages/compiler/src/run.ts
index bfdc3959..80fd33ed 100644
--- a/packages/compiler-node/src/run.ts
+++ b/packages/compiler/src/run.ts
@@ -4,10 +4,10 @@ import {
defineBuild,
materializeBuild,
planBuild,
-} from "@hypit/core";
-import type { BuildCandidateSelection } from "@hypit/core";
+} from "@hypit/kernel";
+import type { BuildCandidateSelection } from "@hypit/kernel";
import type {
- ArtifactAttachment,
+ BlobAttachment,
} from "@hypit/workspace";
import type {
BuildDefinition,
@@ -26,15 +26,15 @@ import type {
RunCompilation,
RunFragmentRegistryLike,
RunFrontendRegistryLike,
- RunSourceUnit,
} from "@hypit/run";
import type { LinkedProgram } from "@hypit/protocol";
+import type { ResolvedSource, SourceUnit } from "@hypit/source";
-import type { NodeCompiledSourceClosure } from "./compiler.js";
-import { mergeAttachments, NodeCompiler } from "./compiler.js";
+import type { CompiledAuthorSource } from "./compiler.js";
+import { mergeAttachments, Compiler } from "./compiler.js";
-export type NodeRunCompilerOptions = {
- readonly authorCompiler: NodeCompiler;
+export type RunCompilerOptions = {
+ readonly authorCompiler: Compiler;
readonly frontends: RunFrontendRegistryLike;
readonly fragments: RunFragmentRegistryLike;
readonly locateHistoricalOutput?: (
@@ -57,20 +57,20 @@ export type NodeRunCompilerOptions = {
) => Promise<{
readonly type: TypeRef;
readonly value: StoredValue;
- readonly attachments?: readonly ArtifactAttachment[];
+ readonly attachments?: readonly BlobAttachment[];
} | undefined>
| {
readonly type: TypeRef;
readonly value: StoredValue;
- readonly attachments?: readonly ArtifactAttachment[];
+ readonly attachments?: readonly BlobAttachment[];
}
| undefined;
};
-export type NodeCompiledRun = {
+export type CompiledRun = {
readonly source: string;
readonly authorSource: string;
- readonly author: NodeCompiledSourceClosure;
+ readonly author: CompiledAuthorSource;
/** Author program rebound to the union closure required by Author and selected Run code. */
readonly program: LinkedProgram;
readonly run: RunCompilation;
@@ -80,13 +80,13 @@ export type NodeCompiledRun = {
readonly output: string;
readonly type: TypeRef;
}>>;
- readonly attachments: readonly ArtifactAttachment[];
+ readonly attachments: readonly BlobAttachment[];
};
-export type NodeCheckedRun = {
+export type CheckedRun = {
readonly source: string;
readonly authorSource: string;
- readonly author: NodeCompiledSourceClosure;
+ readonly author: CompiledAuthorSource;
readonly program: LinkedProgram;
readonly document: RunCompilation["document"];
readonly unresolvedHistoricalOutputs: readonly {
@@ -94,11 +94,11 @@ export type NodeCheckedRun = {
readonly build: string;
readonly output: string;
}[];
- readonly attachments: readonly ArtifactAttachment[];
+ readonly attachments: readonly BlobAttachment[];
};
export type PlannedBuild = {
- readonly compilation: NodeCompiledRun;
+ readonly compilation: CompiledRun;
/** Compiler-only explanation of how the two graphs became the execution plan. */
readonly selections: readonly BuildCandidateSelection[];
/** Whole-Output historical sources selected by the plan; Result storage may forward them directly. */
@@ -127,7 +127,7 @@ function decodeStoredValue(bytes: Uint8Array, from: string): StoredValue {
return parsed as StoredValue;
}
-async function attachmentBytes(attachment: ArtifactAttachment): Promise<Uint8Array> {
+async function attachmentBytes(attachment: BlobAttachment): Promise<Uint8Array> {
const chunks: Uint8Array[] = [];
let size = 0;
for await (const chunk of await attachment.open()) {
@@ -145,7 +145,7 @@ async function attachmentBytes(attachment: ArtifactAttachment): Promise<Uint8Arr
async function storedValueFromWorkspace(
workspace: WorkspaceSession,
- source: RunSourceUnit,
+ source: SourceUnit,
from: string,
): Promise<StoredValue> {
const resolved = await workspace.resolveAsset(source, { from, mediaType: "application/json" });
@@ -156,18 +156,18 @@ async function storedValueFromWorkspace(
async function fileValueFromWorkspace(
workspace: WorkspaceSession,
- source: RunSourceUnit,
+ source: SourceUnit,
from: string,
mediaType: string,
): Promise<StoredValue> {
return (await workspace.resolveAsset(source, { from, mediaType })).artifact;
}
-/** Node Host for the second, mandatory source graph. It never guesses a Frontend from a suffix. */
-export class NodeRunCompiler {
- readonly #options: NodeRunCompilerOptions;
+/** Compiler for the second, mandatory source graph. It never guesses a Frontend from a suffix. */
+export class RunCompiler {
+ readonly #options: RunCompilerOptions;
- constructor(options: NodeRunCompilerOptions) {
+ constructor(options: RunCompilerOptions) {
this.#options = options;
}
@@ -175,9 +175,9 @@ export class NodeRunCompiler {
return this.#options.frontends.resolve(id) !== undefined;
}
- async compileFile(file: string): Promise<NodeCompiledRun> {
- const workspace = await this.#options.authorCompiler.openFile(file);
- return await this.compileSource(workspace.entry, workspace);
+ async compileEntry(locator: string): Promise<CompiledRun> {
+ const workspace = await this.#options.authorCompiler.openEntry(locator);
+ return await this.compileResolvedSource(workspace.entry, workspace);
}
/**
@@ -186,13 +186,13 @@ export class NodeRunCompiler {
* A future BuildRecord is valid Run intent even before that Build exists. It
* becomes executable only when plan/build resolves its exact historical Result value.
*/
- async checkSource(source: RunSourceUnit, workspace: WorkspaceSession): Promise<NodeCheckedRun> {
+ async checkResolvedSource(source: ResolvedSource, workspace: WorkspaceSession): Promise<CheckedRun> {
const decoded = await compileRunSource(source, this.#options.frontends);
- const authorSource = await workspace.resolveSource(source, {
+ const authorSource = await workspace.resolveSource(source.unit, {
from: decoded.document.author.source,
alias: "author",
});
- const author = await this.#options.authorCompiler.compileSource(authorSource, workspace);
+ const author = await this.#options.authorCompiler.compileResolvedSource(authorSource, workspace);
const program = this.#options.authorCompiler.extendExecutionProgram(
author.program,
collectRunModuleRequests(decoded.document, this.#options.fragments),
@@ -213,9 +213,9 @@ export class NodeRunCompiler {
for (const candidate of selectedLocalSources) {
const candidateSource = structuralRun.candidateSources[candidate]!;
const value = candidateSource.kind === "stored-value"
- ? await storedValueFromWorkspace(workspace, source, candidateSource.from)
+ ? await storedValueFromWorkspace(workspace, source.unit, candidateSource.from)
: candidateSource.kind === "file"
- ? await fileValueFromWorkspace(workspace, source, candidateSource.from, candidateSource.mediaType)
+ ? await fileValueFromWorkspace(workspace, source.unit, candidateSource.from, candidateSource.mediaType)
: undefined;
if (value !== undefined) resolvedValues.set(candidate, value);
}
@@ -235,8 +235,8 @@ export class NodeRunCompiler {
}),
});
const checkedPlan = planBuild(program, author.graph, checkedRunGraph);
- const admitRecord = (this.#options.authorCompiler as NodeCompiler & {
- readonly admitRecord?: NodeCompiler["admitRecord"];
+ const admitRecord = (this.#options.authorCompiler as Compiler & {
+ readonly admitRecord?: Compiler["admitRecord"];
}).admitRecord;
if (typeof admitRecord === "function") {
const localRecordIds = new Set(checkedPlan.selections
@@ -248,8 +248,8 @@ export class NodeRunCompiler {
}
}
return {
- source: source.id,
- authorSource: authorSource.id,
+ source: source.unit.id,
+ authorSource: authorSource.unit.id,
author,
program,
document: decoded.document,
@@ -261,13 +261,13 @@ export class NodeRunCompiler {
}
/** Compile both source graphs in one read-once Workspace session selected by the Host. */
- async compileSource(source: RunSourceUnit, workspace: WorkspaceSession): Promise<NodeCompiledRun> {
+ async compileResolvedSource(source: ResolvedSource, workspace: WorkspaceSession): Promise<CompiledRun> {
const decoded = await compileRunSource(source, this.#options.frontends);
- const authorSource = await workspace.resolveSource(source, {
+ const authorSource = await workspace.resolveSource(source.unit, {
from: decoded.document.author.source,
alias: "author",
});
- const author = await this.#options.authorCompiler.compileSource(authorSource, workspace);
+ const author = await this.#options.authorCompiler.compileResolvedSource(authorSource, workspace);
const program = this.#options.authorCompiler.extendExecutionProgram(
author.program,
collectRunModuleRequests(decoded.document, this.#options.fragments),
@@ -275,7 +275,7 @@ export class NodeRunCompiler {
const executionCompilation = program === author.program ? author : { ...author, program };
const locateHistoricalOutput = this.#options.locateHistoricalOutput;
const resolveHistoricalOutput = this.#options.resolveHistoricalOutput;
- const buildAttachments: ArtifactAttachment[] = [];
+ const buildAttachments: BlobAttachment[] = [];
const structuralRun = await resolveRunDocument(decoded.document, {
compilation: executionCompilation,
fragments: this.#options.fragments,
@@ -294,13 +294,13 @@ export class NodeRunCompiler {
for (const candidate of selectedSources) {
const candidateSource = structuralRun.candidateSources[candidate]!;
if (candidateSource.kind === "stored-value") {
- resolvedValues.set(candidate, await storedValueFromWorkspace(workspace, source, candidateSource.from));
+ resolvedValues.set(candidate, await storedValueFromWorkspace(workspace, source.unit, candidateSource.from));
continue;
}
if (candidateSource.kind === "file") {
resolvedValues.set(candidate, await fileValueFromWorkspace(
workspace,
- source,
+ source.unit,
candidateSource.from,
candidateSource.mediaType,
));
@@ -360,8 +360,8 @@ export class NodeRunCompiler {
...run.graph,
targets: run.graph.targets.filter((target) => !forwardOnlyOutputs.has(target.output)),
});
- const admitRecord = (this.#options.authorCompiler as NodeCompiler & {
- readonly admitRecord?: NodeCompiler["admitRecord"];
+ const admitRecord = (this.#options.authorCompiler as Compiler & {
+ readonly admitRecord?: Compiler["admitRecord"];
}).admitRecord;
if (typeof admitRecord === "function") {
for (const record of admitted.initialRecords) {
@@ -369,8 +369,8 @@ export class NodeRunCompiler {
}
}
return {
- source: source.id,
- authorSource: authorSource.id,
+ source: source.unit.id,
+ authorSource: authorSource.unit.id,
author,
program,
run,
@@ -379,7 +379,7 @@ export class NodeRunCompiler {
};
}
- planCompilation(compilation: NodeCompiledRun): PlannedBuild {
+ planCompilation(compilation: CompiledRun): PlannedBuild {
const preliminary = planBuild(compilation.program, compilation.author.graph, compilation.run.graph);
const consumedRecords = new Set(preliminary.plan.steps.flatMap((step) => Object.values(step.inputs)));
const forwardOnlyOutputs = new Set(preliminary.selections.flatMap((selection) => {
@@ -415,7 +415,7 @@ export class NodeRunCompiler {
return { compilation, selections: sliced.selections, resultForwards, definition, state };
}
- async planFile(file: string): Promise<PlannedBuild> {
- return this.planCompilation(await this.compileFile(file));
+ async planEntry(locator: string): Promise<PlannedBuild> {
+ return this.planCompilation(await this.compileEntry(locator));
}
}
diff --git a/packages/elaborator/src/source.ts b/packages/compiler/src/source.ts
similarity index 66%
rename from packages/elaborator/src/source.ts
rename to packages/compiler/src/source.ts
index 9dc70970..4b83d6bc 100644
--- a/packages/elaborator/src/source.ts
+++ b/packages/compiler/src/source.ts
@@ -1,217 +1,42 @@
-import { link } from "@hypit/core";
+import { link } from "@hypit/kernel";
import { canonicalStringify, isResourceId } from "@hypit/protocol";
import type {
- CompiledGraph,
GraphValueRef,
- LinkedProgram,
ResolvedModuleClosure,
TypeRef,
TypedRecord,
} from "@hypit/protocol";
-import {
- maskSourceHeader,
- parseSourceHeader,
-} from "@hypit/source";
import type {
- ResolvedSourceAsset,
- SourceAssetRequest,
+ ResolvedSource,
SourceAssetResolver,
- SourceHeader,
- SourceImportRequest,
SourceResolver,
- SourceUnit,
} from "@hypit/source";
-
-import {
- elaborateAuthorGraph,
-} from "./author.js";
+import { elaborateAuthorGraph } from "@hypit/author";
import type {
AuthorComponent,
+ AuthorElementProvenance,
+ AuthorFrontend,
+ AuthorFrontendRegistryLike,
+ AuthorFrontendSourceUnit,
+ AuthorRecordAdmitter,
+ AuthorSourceDiscovery,
+ AuthorSourceExport,
+ AuthorSourceIdentity,
+ AuthorSourceUnit,
AuthorValueRef,
-} from "./author.js";
-import type { GraphFragment } from "./fragment.js";
-
-export type AuthorSourceUnit = SourceUnit;
-
-/** Source presented to a Frontend after the mandatory Header has been admitted and masked. */
-export type AuthorFrontendSourceUnit = AuthorSourceUnit & {
- readonly header: SourceHeader;
-};
-
-export type AuthorSourceImport = SourceImportRequest;
-
-export type AuthorSourceDiscovery = {
- readonly modules: readonly string[];
- readonly sources: readonly AuthorSourceImport[];
-};
-
-/** A semantic source dependency requested by a Frontend or package-owned Surface. */
-export type AuthorSourceAssetRequest = SourceAssetRequest;
-
-export type ResolvedAuthorSourceAsset = ResolvedSourceAsset;
-
-export type AuthorSourceExport = {
- /** Relative public name. The importing source contributes its own alias. */
- readonly name: string;
- readonly ref: AuthorValueRef;
- readonly type: TypeRef;
-};
-
-/**
- * One author-visible identity whose uniqueness is part of a domain's public
- * contract. The Frontend only carries the declaration; the owning Surface
- * chooses the Type namespace and the Source closure enforces it generically.
- */
-export type AuthorSourceIdentity = {
- readonly namespace: TypeRef;
- readonly id: string;
-};
-
-/** One author input before Source-local graph identities are hygienized. */
-export type AuthorInputProvenanceDraft = {
- readonly name: string;
- readonly range: import("@hypit/protocol").SourceRange;
- readonly kind: "literal" | "reference";
- readonly ref?: AuthorValueRef;
-};
-
-/**
- * Structural origin retained by a Frontend while it lowers author syntax.
- * It contains no editor presentation and is never persisted beside the Source.
- */
-export type AuthorElementProvenanceDraft = {
- readonly range: import("@hypit/protocol").SourceRange;
- readonly records: readonly string[];
- readonly components: readonly string[];
- readonly outputs: readonly { readonly component: string; readonly name: string; readonly id: string }[];
- readonly inputs: readonly AuthorInputProvenanceDraft[];
-};
-
-export type ResolvedAuthorSourceImport = {
- readonly request: AuthorSourceImport;
- readonly source: string;
- readonly exports: readonly AuthorSourceExport[];
- /** Public record exports available to a package-owned Surface during author compilation. */
- readonly records: readonly TypedRecord[];
-};
-
-export type AuthorSourceDecodeContext = {
- readonly closure: ResolvedModuleClosure;
- readonly imports: readonly ResolvedAuthorSourceImport[];
- /** Host authority: Frontends declare asset dependencies but never open files themselves. */
- readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<ResolvedAuthorSourceAsset>;
-};
-
-export type DecodedAuthorSource = {
- readonly records: readonly TypedRecord[];
- readonly components: readonly AuthorComponent[];
- readonly fragments: readonly GraphFragment[];
- readonly exports: readonly AuthorSourceExport[];
- readonly identities?: readonly AuthorSourceIdentity[];
- readonly provenance?: readonly AuthorElementProvenanceDraft[];
-};
-
-export type Awaitable<T> = T | Promise<T>;
-
-export type AuthorFrontend = {
- readonly id: string;
- discover(source: AuthorFrontendSourceUnit): Awaitable<AuthorSourceDiscovery>;
- decode(source: AuthorFrontendSourceUnit, context: AuthorSourceDecodeContext): Awaitable<DecodedAuthorSource>;
-};
-
-export interface AuthorFrontendRegistryLike {
- resolve(id: string): AuthorFrontend | undefined;
-}
-
-export class AuthorFrontendRegistry implements AuthorFrontendRegistryLike {
- readonly #frontends = new Map<string, AuthorFrontend>();
-
- register(frontend: AuthorFrontend): void {
- if (frontend.id.length === 0) throw new SourceClosureError("EMPTY_FRONTEND_ID", "Frontend id is empty");
- if (this.#frontends.has(frontend.id)) {
- throw new SourceClosureError("DUPLICATE_FRONTEND", `Frontend ${frontend.id} is already registered`, frontend.id);
- }
- this.#frontends.set(frontend.id, frontend);
- }
-
- resolve(id: string): AuthorFrontend | undefined {
- return this.#frontends.get(id);
- }
-}
-
-export type AuthorSourceResolver = SourceResolver;
+ CompiledSourceClosure,
+ DecodedAuthorSource,
+ ResolvedAuthorSourceAsset,
+ ResolvedAuthorSourceImport,
+ SourceClosure,
+ SourceClosureUnit,
+} from "@hypit/author";
+import type { GraphFragment } from "@hypit/author";
-export type AuthorSourceAssetResolver = SourceAssetResolver;
-
-/** Host-owned admission gate for one already sealed authored Record. */
-export type AuthorRecordAdmitter = (
- closure: ResolvedModuleClosure,
- record: TypedRecord,
-) => Awaitable<void>;
-
-export type SourceClosureUnit = {
- readonly id: string;
- readonly name: string;
- readonly frontend: string;
- readonly imports: readonly {
- readonly alias: string;
- readonly source: string;
- }[];
-};
-
-export type AuthorInputProvenance = {
- /** Compilation-local identity; authors never write or maintain it. */
- readonly id: string;
- readonly name: string;
- readonly range: import("@hypit/protocol").SourceRange;
- readonly kind: "literal" | "reference";
- readonly ref?: AuthorValueRef;
-};
-
-export type AuthorElementProvenance = {
- readonly id: string;
- readonly source: string;
- readonly sourceName: string;
- readonly frontend: string;
- readonly range: import("@hypit/protocol").SourceRange;
- readonly records: readonly { readonly local: string; readonly id: string }[];
- readonly components: readonly { readonly local: string; readonly id: string }[];
- readonly outputs: readonly {
- readonly component: string;
- readonly name: string;
- readonly local: string;
- readonly id: string;
- }[];
- readonly inputs: readonly AuthorInputProvenance[];
-};
-
-/** Ephemeral Source-to-graph lineage emitted with one compilation. */
-export type AuthorProvenance = {
- readonly format: "hypit.author-provenance@1";
- readonly elements: readonly AuthorElementProvenance[];
-};
-
-export type SourceClosure = {
- readonly entry: string;
- readonly units: readonly SourceClosureUnit[];
-};
-
-export type CompiledSourceExport = {
- readonly name: string;
- readonly type: TypeRef;
- readonly ref: GraphValueRef;
-};
-
-export type CompiledSourceClosure = {
- readonly closure: SourceClosure;
- readonly program: LinkedProgram;
- readonly graph: CompiledGraph;
- readonly exports: readonly CompiledSourceExport[];
- readonly provenance: AuthorProvenance;
-};
+type Awaitable<T> = T | Promise<T>;
export type CompileSourceClosureRequest = {
- readonly entry: AuthorSourceUnit;
+ readonly entry: ResolvedSource;
readonly closure: ResolvedModuleClosure;
readonly frontends: AuthorFrontendRegistryLike;
/**
@@ -222,8 +47,8 @@ export type CompileSourceClosureRequest = {
source: AuthorFrontendSourceUnit,
frontend: AuthorFrontend,
) => Awaitable<AuthorSourceDiscovery>;
- readonly resolveSource: AuthorSourceResolver;
- readonly resolveAsset?: AuthorSourceAssetResolver;
+ readonly resolveSource: SourceResolver;
+ readonly resolveAsset?: SourceAssetResolver;
readonly admitRecord?: AuthorRecordAdmitter;
};
@@ -262,15 +87,6 @@ function sourceKey(source: AuthorSourceUnit, frontend: string): string {
return `${source.id}\u0000${frontend}`;
}
-export function prepareAuthorSource(source: AuthorSourceUnit): AuthorFrontendSourceUnit {
- const header = parseSourceHeader(source.name, source.text);
- return {
- ...source,
- text: maskSourceHeader(source.text, header),
- header,
- };
-}
-
type HygienicSource = {
readonly unit: SourceClosureUnit;
readonly records: readonly TypedRecord[];
@@ -433,10 +249,11 @@ export async function compileSourceClosure(
const visitingAt = new Map<string, number>();
const ordered: HygienicSource[] = [];
- const compile = async (rawSource: AuthorSourceUnit): Promise<HygienicSource> => {
+ const compile = async (resolvedSource: ResolvedSource): Promise<HygienicSource> => {
+ const rawSource = resolvedSource.unit;
assert(rawSource.id.length > 0, "EMPTY_SOURCE_ID", "SourceUnit id is empty");
- const source = prepareAuthorSource(rawSource);
- const frontendId = source.header.using;
+ const source = rawSource;
+ const frontendId = resolvedSource.frontend;
const key = sourceKey(rawSource, frontendId);
const cached = cache.get(key);
if (cached !== undefined) return cached;
@@ -586,23 +403,3 @@ export async function compileSourceClosure(
.sort((left, right) => left.name.localeCompare(right.name)),
};
}
-
-export function resolveCompiledSourceExport(
- compiled: CompiledSourceClosure,
- name: string,
- expected?: TypeRef,
-): CompiledSourceExport {
- const item = compiled.exports.find((candidate) => candidate.name === name);
- if (item === undefined) {
- throw new SourceClosureError("UNKNOWN_SOURCE_EXPORT", `unknown source export ${name}`, name);
- }
- if (expected !== undefined) {
- assert(
- sameType(item.type, expected),
- "SOURCE_EXPORT_TYPE_MISMATCH",
- `${name} is ${typeName(item.type)}, expected ${typeName(expected)}`,
- name,
- );
- }
- return item;
-}
diff --git a/packages/compiler-node/test/compiler.test.ts b/packages/compiler/test/compiler.test.ts
similarity index 86%
rename from packages/compiler-node/test/compiler.test.ts
rename to packages/compiler/test/compiler.test.ts
index 96312a6b..e8560beb 100644
--- a/packages/compiler-node/test/compiler.test.ts
+++ b/packages/compiler/test/compiler.test.ts
@@ -12,19 +12,19 @@ import test from "node:test";
import {
ModulePackageRegistry,
- NodeCompiler,
- NodeCompilerError,
- NodeRunCompiler,
-} from "@hypit/compiler-node";
+ Compiler,
+ CompilerError,
+ RunCompiler,
+} from "@hypit/compiler";
import {
AuthorFrontendRegistry,
sealGraphFragment,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import type {
AuthorSourceAssetRequest,
AuthorSourceImport,
AuthorSourceUnit,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import type {
BlobRef,
ModuleManifest,
@@ -32,19 +32,22 @@ import type {
ProducerRef,
TypeRef,
} from "@hypit/protocol";
-import { SourceHeaderError } from "@hypit/source";
+import { decodeSourceText } from "@hypit/source";
+import { resolveSelfDescribedTextSource, SourceHeaderError } from "@hypit/source/text";
import {
RunFragmentRegistry,
RunFrontendRegistry,
} from "@hypit/run";
-import { runMarkupFrontend } from "@hypit/run-markup";
-import type { ArtifactAttachment, Workspace } from "@hypit/workspace";
+import { runMarkupFrontend } from "@hypit/markup/run";
+import type { BlobAttachment, Workspace } from "@hypit/workspace";
import { WorkspaceError } from "@hypit/workspace";
import {
createMarkupAuthorFrontend,
MarkupSurfaceRegistry,
} from "@hypit/markup";
-import { NodeFilesystemWorkspace } from "@hypit/workspace-fs-node";
+import { NodeFilesystemWorkspace } from "@hypit/workspace/node";
+
+const rawSourceAdapter = (unit: import("@hypit/source").SourceUnit) => ({ unit, frontend: "test.frontend@1" });
function emptyManifest(name: string, version = "1"): ModuleManifest {
return {
@@ -84,7 +87,7 @@ test("module registration is atomic", () => {
modules.register({ manifest: first, specifiers: ["example.shared@1"] });
assert.throws(
() => modules.register({ manifest: second, specifiers: ["example.shared@1"] }),
- (error: unknown) => error instanceof NodeCompilerError && error.code === "DUPLICATE_MODULE_SPECIFIER",
+ (error: unknown) => error instanceof CompilerError && error.code === "DUPLICATE_MODULE_SPECIFIER",
);
assert.equal(modules.resolve("example.second@1"), undefined);
@@ -139,7 +142,7 @@ function compiler(
root: string,
additional: readonly ModuleManifest[] = [],
onDiscover?: () => void,
-): NodeCompiler {
+): Compiler {
const modules = new ModulePackageRegistry();
modules.register({ manifest: laboratoryManifest });
for (const manifest of additional) modules.register({ manifest });
@@ -179,7 +182,7 @@ function compiler(
return frontend.discover(source);
},
});
- return new NodeCompiler({ modules, frontends, workspace: new NodeFilesystemWorkspace({ root }) });
+ return new Compiler({ modules, frontends, workspace: new NodeFilesystemWorkspace({ root }) });
}
const previewModule = { name: "example.compiler-preview", version: "1" } as const;
@@ -231,7 +234,7 @@ const consumeFragment = sealGraphFragment({
}],
});
-function assetCompiler(environment: { readonly root: string } | { readonly workspace: Workspace }): NodeCompiler {
+function assetCompiler(environment: { readonly root: string } | { readonly workspace: Workspace }): Compiler {
const modules = new ModulePackageRegistry();
modules.register({ manifest: assetManifest });
modules.register({ manifest: laboratoryManifest });
@@ -280,7 +283,7 @@ function assetCompiler(environment: { readonly root: string } | { readonly works
return resolved;
},
}));
- return new NodeCompiler({
+ return new Compiler({
modules,
frontends,
workspace: "workspace" in environment
@@ -292,7 +295,7 @@ function assetCompiler(environment: { readonly root: string } | { readonly works
function memoryWorkspace(sourceText: string, assetBytes: Uint8Array): Workspace {
return {
async open(entryLocator) {
- const entry: AuthorSourceUnit = { id: entryLocator, name: "main.svml", text: sourceText };
+ const entry = resolveSelfDescribedTextSource({ id: entryLocator, name: "main.svml", text: sourceText });
let attachment: { readonly artifact: BlobRef; readonly open: () => AsyncIterable<Uint8Array> } | undefined;
return {
entry,
@@ -300,7 +303,7 @@ function memoryWorkspace(sourceText: string, assetBytes: Uint8Array): Workspace
throw new WorkspaceError("UNKNOWN_MEMORY_SOURCE", `No memory source satisfies ${request.from}`, request.from);
},
async resolveAsset(importer: AuthorSourceUnit, request: AuthorSourceAssetRequest) {
- if (importer !== entry || request.from !== "./reference.bin") {
+ if (importer !== entry.unit || request.from !== "./reference.bin") {
throw new WorkspaceError("UNKNOWN_MEMORY_ASSET", `No memory asset satisfies ${request.from}`, request.from);
}
const bytes = Uint8Array.from(assetBytes);
@@ -323,7 +326,7 @@ function memoryWorkspace(sourceText: string, assetBytes: Uint8Array): Workspace
};
}
-async function readAttachment(attachment: ArtifactAttachment | undefined): Promise<Uint8Array | undefined> {
+async function readAttachment(attachment: BlobAttachment | undefined): Promise<Uint8Array | undefined> {
if (attachment === undefined) return undefined;
const chunks: Uint8Array[] = [];
let size = 0;
@@ -350,14 +353,14 @@ test("Node Compiler discovers real imports and emits a named public Author Graph
</svml>`, "utf8");
let discoveries = 0;
- const compiled = await compiler(root, [], () => { discoveries += 1; }).compileFile(file);
+ const compiled = await compiler(root, [], () => { discoveries += 1; }).compileEntry(file);
assert.equal(compiled.exports[0]?.name, "hello.result");
assert.equal(compiled.graph.outputs.length, 1);
assert.equal(discoveries, 1, "the frozen Import Prologue must not execute Frontend discovery twice");
});
-test("the mandatory Source Header selects the Frontend independently of the filename suffix", async () => {
+test("the self-described text adapter requires a Header and ignores the filename suffix", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-self-described-source-"));
const text = `<?svml using="@hypit/markup@1"?>
<svml>
@@ -368,15 +371,15 @@ test("the mandatory Source Header selects the Frontend independently of the file
const arbitrary = join(root, "main.anything");
await writeFile(svml, text, "utf8");
await writeFile(arbitrary, text, "utf8");
- const first = await compiler(root).compileFile(svml);
- const second = await compiler(root).compileFile(arbitrary);
+ const first = await compiler(root).compileEntry(svml);
+ const second = await compiler(root).compileEntry(arbitrary);
assert.equal(first.exports[0]?.name, "hello.result");
assert.equal(second.exports[0]?.name, "hello.result");
const missing = join(root, "missing.svml");
await writeFile(missing, "<svml/>", "utf8");
await assert.rejects(
- compiler(root).compileFile(missing),
+ compiler(root).compileEntry(missing),
(error: unknown) => error instanceof SourceHeaderError && error.code === "SOURCE_HEADER_MISSING",
);
});
@@ -392,7 +395,7 @@ test("Run-only Fragment modules extend the execution closure without polluting t
<import as="unused" from="example.unused-video-feature@1"/>
<lab:Result id="hello"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<import from="@example/preview" as="preview"/>
@@ -406,8 +409,8 @@ test("Run-only Fragment modules extend the execution closure without polluting t
frontends.register(runMarkupFrontend);
const fragments = new RunFragmentRegistry();
fragments.register({ name: "@example/preview", fragments: { result: previewFragment } });
- const runCompiler = new NodeRunCompiler({ authorCompiler, frontends, fragments });
- const compiled = await runCompiler.compileFile(runFile);
+ const runCompiler = new RunCompiler({ authorCompiler, frontends, fragments });
+ const compiled = await runCompiler.compileEntry(runFile);
const planned = runCompiler.planCompilation(compiled);
assert.deepEqual(
@@ -438,7 +441,7 @@ test("static Run checking accepts a future BuildRecord without opening project R
<import as="lab" from="example.compiler-lab@1"/>
<lab:Result id="hello"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="hello.result"/>
@@ -448,20 +451,20 @@ test("static Run checking accepts a future BuildRecord without opening project R
const authorCompiler = compiler(root);
const frontends = new RunFrontendRegistry();
frontends.register(runMarkupFrontend);
- const runCompiler = new NodeRunCompiler({
+ const runCompiler = new RunCompiler({
authorCompiler,
frontends,
fragments: new RunFragmentRegistry(),
});
const workspace = await new NodeFilesystemWorkspace({ root }).open(runFile);
- const checked = await runCompiler.checkSource(workspace.entry, workspace);
+ const checked = await runCompiler.checkResolvedSource(workspace.entry, workspace);
assert.deepEqual(checked.unresolvedHistoricalOutputs, [{
id: "prior",
build: "future-build",
output: "hello.result",
}]);
await assert.rejects(
- runCompiler.compileSource(workspace.entry, workspace),
+ runCompiler.compileResolvedSource(workspace.entry, workspace),
/requires a project Result Store/u,
);
@@ -471,7 +474,7 @@ test("static Run checking accepts a future BuildRecord without opening project R
<lab:Result id="hello"/><lab:Result id="unused-history"/>
<lab:Result id="unused-value"/><lab:Result id="unused-file"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="hello.result"/>
@@ -483,13 +486,13 @@ test("static Run checking accepts a future BuildRecord without opening project R
<satisfy output="unused-file.result" candidate="media"/>
</svrun>`, "utf8");
const unusedWorkspace = await new NodeFilesystemWorkspace({ root }).open(runFile);
- const compiled = await runCompiler.compileSource(unusedWorkspace.entry, unusedWorkspace);
+ const compiled = await runCompiler.compileResolvedSource(unusedWorkspace.entry, unusedWorkspace);
assert.equal(runCompiler.planCompilation(compiled).state.plan.steps.length, 1,
"unreachable zero-input Candidates are never opened or substituted into the selected execution");
await writeFile(join(root, "selected-value.json"), JSON.stringify({ kind: "inline", value: "ready" }), "utf8");
await writeFile(join(root, "selected-file.mp4"), new Uint8Array([1, 2, 3]));
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="unused-value.result"/><target output="unused-file.result"/>
@@ -499,7 +502,7 @@ test("static Run checking accepts a future BuildRecord without opening project R
<satisfy output="unused-file.result" candidate="media"/>
</svrun>`, "utf8");
const selectedWorkspace = await new NodeFilesystemWorkspace({ root }).open(runFile);
- const selected = runCompiler.planCompilation(await runCompiler.compileSource(selectedWorkspace.entry, selectedWorkspace));
+ const selected = runCompiler.planCompilation(await runCompiler.compileResolvedSource(selectedWorkspace.entry, selectedWorkspace));
assert.deepEqual(selected.definition.initialRecords.map((record) => record.value.kind).sort(), ["blob", "inline"]);
});
@@ -512,7 +515,7 @@ test("a historical Output is materialized only when a selected Producer consumes
<import as="lab" from="example.compiler-lab@1"/>
<lab:Result id="source"/><lab:Result id="final"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<import from="@example/preview" as="preview"/>
@@ -532,7 +535,7 @@ test("a historical Output is materialized only when a selected Producer consumes
});
let located = 0;
let resolved = 0;
- const runCompiler = new NodeRunCompiler({
+ const runCompiler = new RunCompiler({
authorCompiler: compiler(root, [previewManifest]),
frontends,
fragments,
@@ -550,7 +553,7 @@ test("a historical Output is materialized only when a selected Producer consumes
},
});
- const planned = await runCompiler.planFile(runFile);
+ const planned = await runCompiler.planEntry(runFile);
assert.equal(located, 1, "the selected historical address is validated from its manifest");
assert.equal(resolved, 1, "a Producer dependency materializes the historical value exactly once");
assert.equal(planned.state.plan.steps.length, 1);
@@ -580,13 +583,13 @@ test("source assets become graph values and a Host transfer bundle without closu
</svml>`, "utf8");
await writeFile(asset, new Uint8Array([1, 2, 3, 4]));
- const first = await assetCompiler({ root }).compileFile(file);
+ const first = await assetCompiler({ root }).compileEntry(file);
const attachment = first.attachments[0];
assert.deepEqual(await readAttachment(attachment), new Uint8Array([1, 2, 3, 4]));
assert.equal(first.program.records[0]?.value.kind, "blob");
assert.equal(first.program.records[0]?.value.kind === "blob" ? first.program.records[0].value.resource : undefined, attachment?.artifact.resource);
await writeFile(asset, new Uint8Array([9, 8, 7]));
- const second = await assetCompiler({ root }).compileFile(file);
+ const second = await assetCompiler({ root }).compileEntry(file);
assert.notEqual(second.attachments[0]?.artifact.resource, attachment?.artifact.resource);
});
@@ -599,7 +602,7 @@ test("an installed package Surface can contribute embedded bytes without an auth
<asset:Asset id="embedded" src="package:example.asset-lab/embedded.bin"/>
</svml>`, "utf8");
- const compiled = await assetCompiler({ root }).compileFile(file);
+ const compiled = await assetCompiler({ root }).compileEntry(file);
const attachment = compiled.attachments[0];
assert.deepEqual(await readAttachment(attachment), new Uint8Array([8, 6, 7, 5, 3, 0, 9]));
assert.equal(compiled.program.records[0]?.value.kind, "blob");
@@ -619,7 +622,7 @@ test("Run compilation retains embedded Author attachments for later Runtime stag
<asset:Asset id="embedded" src="package:example.asset-lab/embedded.bin"/>
<lab:Result id="hello"/>
</svml>`, "utf8");
- await writeFile(runFile, `<?svml using="@hypit/run-markup@1"?>
+ await writeFile(runFile, `<?svml using="@hypit/markup/run@1"?>
<svrun version="1">
<author source="./main.svml"/>
<target output="hello.result"/>
@@ -628,12 +631,12 @@ test("Run compilation retains embedded Author attachments for later Runtime stag
const authorCompiler = assetCompiler({ root });
const frontends = new RunFrontendRegistry();
frontends.register(runMarkupFrontend);
- const runCompiler = new NodeRunCompiler({
+ const runCompiler = new RunCompiler({
authorCompiler,
frontends,
fragments: new RunFragmentRegistry(),
});
- const compiled = await runCompiler.compileFile(runFile);
+ const compiled = await runCompiler.compileEntry(runFile);
assert.deepEqual(compiled.attachments.map((item) => item.artifact), compiled.author.attachments.map((item) => item.artifact));
assert.deepEqual(await readAttachment(compiled.attachments[0]), new Uint8Array([8, 6, 7, 5, 3, 0, 9]));
});
@@ -650,34 +653,34 @@ test("filesystem Workspace captures source text and asset identity once", async
await writeFile(includedPath, "included-first", "utf8");
await writeFile(outsidePath, "outside", "utf8");
await writeFile(assetPath, new Uint8Array([1, 2, 3]));
- const workspace = await new NodeFilesystemWorkspace({ root }).open(entryPath);
+ const workspace = await new NodeFilesystemWorkspace({ root, sourceAdapter: rawSourceAdapter }).open(entryPath);
const entry = workspace.entry;
await writeFile(entryPath, "second", "utf8");
- assert.equal((await new NodeFilesystemWorkspace({ root }).open(entryPath)).entry.text, "second");
- assert.equal(entry.text, "first");
+ assert.equal(decodeSourceText((await new NodeFilesystemWorkspace({ root, sourceAdapter: rawSourceAdapter }).open(entryPath)).entry.unit), "second");
+ assert.equal(decodeSourceText(entry.unit), "first");
assert.equal(await readFile(entryPath, "utf8"), "second");
const sourceRequest = { from: "./included.svs", alias: "included" };
- const firstIncluded = await workspace.resolveSource(entry, sourceRequest);
+ const firstIncluded = await workspace.resolveSource(entry.unit, sourceRequest);
await writeFile(includedPath, "included-second", "utf8");
- assert.deepEqual(await workspace.resolveSource(entry, sourceRequest), firstIncluded);
- assert.equal(firstIncluded.text, "included-first");
- const firstAsset = await workspace.resolveAsset(entry, { from: "./asset.bin", mediaType: "application/octet-stream" });
+ assert.deepEqual(await workspace.resolveSource(entry.unit, sourceRequest), firstIncluded);
+ assert.equal(decodeSourceText(firstIncluded.unit), "included-first");
+ const firstAsset = await workspace.resolveAsset(entry.unit, { from: "./asset.bin", mediaType: "application/octet-stream" });
await writeFile(assetPath, new Uint8Array([4, 5, 6, 7]));
- const capturedAsset = await workspace.resolveAsset(entry, { from: "./asset.bin", mediaType: "application/octet-stream" });
+ const capturedAsset = await workspace.resolveAsset(entry.unit, { from: "./asset.bin", mediaType: "application/octet-stream" });
assert.deepEqual(capturedAsset, firstAsset, "one Workspace keeps an asset edge bound to the first bytes read");
const detached = await workspace.attachments();
assert.deepEqual(await readAttachment(detached[0]), new Uint8Array([4, 5, 6, 7]),
"attachment bytes are opened lazily; Runtime rejects them if they no longer match the captured identity");
assert.equal((await workspace.attachments())[0]?.artifact.resource, firstAsset.artifact.resource);
await assert.rejects(
- async () => await workspace.resolveSource(entry, {
+ async () => await workspace.resolveSource(entry.unit, {
from: "../outside.svs",
alias: "escaped",
}),
(error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
);
await assert.rejects(
- async () => await workspace.resolveAsset(entry, {
+ async () => await workspace.resolveAsset(entry.unit, {
from: "../outside.svs",
mediaType: "application/octet-stream",
}),
@@ -693,14 +696,14 @@ test("filesystem Workspace captures source text and asset identity once", async
return;
}
await assert.rejects(
- async () => await workspace.resolveSource(entry, {
+ async () => await workspace.resolveSource(entry.unit, {
from: "./escaped.svs",
alias: "escaped",
}),
(error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
);
await assert.rejects(
- async () => await workspace.resolveAsset(entry, {
+ async () => await workspace.resolveAsset(entry.unit, {
from: "./escaped.svs",
mediaType: "application/octet-stream",
}),
@@ -721,12 +724,12 @@ test("an asset root widens bytes without widening Source imports", async () => {
await writeFile(entryPath, "entry", "utf8");
await writeFile(assetPath, new Uint8Array([2, 7, 1, 8]));
await writeFile(sourcePath, "shared source", "utf8");
- const workspace = await new NodeFilesystemWorkspace({ root: project, assetRoots: [library] }).open(entryPath);
- assert.equal((await workspace.resolveAsset(workspace.entry, {
+ const workspace = await new NodeFilesystemWorkspace({ root: project, assetRoots: [library], sourceAdapter: rawSourceAdapter }).open(entryPath);
+ assert.equal((await workspace.resolveAsset(workspace.entry.unit, {
from: "../library/shared.bin",
mediaType: "application/octet-stream",
})).artifact.size, 4);
- await assert.rejects(async () => await workspace.resolveSource(workspace.entry, {
+ await assert.rejects(async () => await workspace.resolveSource(workspace.entry.unit, {
from: "../library/shared.svs",
alias: "shared",
}), (error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT");
@@ -748,18 +751,19 @@ test("a Host-resolved Source keeps relative imports inside its own read boundary
await writeFile(outsidePath, "outside", "utf8");
const workspace = await new NodeFilesystemWorkspace({
root: project,
+ sourceAdapter: rawSourceAdapter,
externalSourceResolver(_importer, request) {
assert.equal(request.from, "@acme/kits/example");
return { root: packageRoot, source: kitPath };
},
}).open(entryPath);
- const kit = await workspace.resolveSource(workspace.entry, {
+ const kit = await workspace.resolveSource(workspace.entry.unit, {
from: "@acme/kits/example",
alias: "kit",
});
- assert.equal((await workspace.resolveSource(kit, { from: "./child.svs", alias: "child" })).text, "child");
+ assert.equal(decodeSourceText((await workspace.resolveSource(kit.unit, { from: "./child.svs", alias: "child" })).unit), "child");
await assert.rejects(
- async () => await workspace.resolveSource(kit, { from: "../outside.svs", alias: "outside" }),
+ async () => await workspace.resolveSource(kit.unit, { from: "../outside.svs", alias: "outside" }),
(error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
);
});
@@ -776,8 +780,8 @@ test("filesystem and in-memory Workspaces load identical asset bytes", async ()
await writeFile(file, source, "utf8");
await writeFile(join(root, "reference.bin"), bytes);
- const filesystem = await assetCompiler({ root }).compileFile(file);
- const memory = await assetCompiler({ workspace: memoryWorkspace(source, bytes) }).compileFile("memory:main");
+ const filesystem = await assetCompiler({ root }).compileEntry(file);
+ const memory = await assetCompiler({ workspace: memoryWorkspace(source, bytes) }).compileEntry("memory:main");
const memoryArtifact = memory.attachments[0]?.artifact;
const filesystemArtifact = filesystem.attachments[0]?.artifact;
diff --git a/packages/elaborator/test/source.test.ts b/packages/compiler/test/source.test.ts
similarity index 87%
rename from packages/elaborator/test/source.test.ts
rename to packages/compiler/test/source.test.ts
index 2621353e..158bd43c 100644
--- a/packages/elaborator/test/source.test.ts
+++ b/packages/compiler/test/source.test.ts
@@ -1,13 +1,13 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { createResolvedClosure } from "@hypit/core";
+import { createResolvedClosure } from "@hypit/kernel";
import {
AuthorFrontendRegistry,
- SourceClosureError,
- compileSourceClosure,
-} from "@hypit/elaborator";
-import type { AuthorSourceUnit } from "@hypit/elaborator";
+} from "@hypit/author";
+import { SourceClosureError, compileSourceClosure } from "@hypit/compiler";
+import type { ResolvedSource } from "@hypit/source";
+import { resolveSelfDescribedTextSource } from "@hypit/source/text";
import type { ModuleManifest, TypeRef } from "@hypit/protocol";
const moduleRef = { name: "example.identity", version: "1" } as const;
@@ -23,8 +23,8 @@ const manifest: ModuleManifest = {
};
const frontendId = "example.identity-frontend@1";
-function source(id: string, name: string): AuthorSourceUnit {
- return { id, name, text: `<?svml using="${frontendId}"?>\nidentity` };
+function source(id: string, name: string): ResolvedSource {
+ return resolveSelfDescribedTextSource({ id, name, text: `<?svml using="${frontendId}"?>\nidentity` });
}
test("Source Closure rejects a repeated domain-declared public identity", async () => {
diff --git a/packages/elaborator/package.json b/packages/elaborator/package.json
deleted file mode 100644
index f534c958..00000000
--- a/packages/elaborator/package.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name": "@hypit/elaborator",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/core": "workspace:*",
- "@hypit/host": "workspace:*",
- "@hypit/protocol": "workspace:*",
- "@hypit/source": "workspace:*"
- }
-}
diff --git a/packages/elaborator/src/frontend-facet.ts b/packages/elaborator/src/frontend-facet.ts
deleted file mode 100644
index 79dfbae1..00000000
--- a/packages/elaborator/src/frontend-facet.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import {
- createFrontendHostFacet,
- frontendsFromHostFacets,
-} from "@hypit/host";
-import type {
- FrontendHostFacet,
- HostFacet,
-} from "@hypit/host";
-import { sourceFrontendPackageAbi } from "@hypit/source";
-
-import type { AuthorFrontend } from "./source.js";
-
-export type AuthorFrontendHostFacet = FrontendHostFacet<"author", AuthorFrontend> & {
- readonly abi: typeof sourceFrontendPackageAbi;
-};
-
-export function createAuthorFrontendHostFacet(frontend: AuthorFrontend): AuthorFrontendHostFacet {
- return createFrontendHostFacet(sourceFrontendPackageAbi, "author", frontend) as AuthorFrontendHostFacet;
-}
-
-export function authorFrontendsFromHostFacets(facets: readonly HostFacet[]): readonly AuthorFrontend[] {
- return frontendsFromHostFacets<"author", AuthorFrontend>(sourceFrontendPackageAbi, "author", facets);
-}
-
-export function installAuthorFrontendHostFacets(
- facets: readonly HostFacet[],
- registry: { register(frontend: AuthorFrontend): void },
-): void {
- for (const frontend of authorFrontendsFromHostFacets(facets)) registry.register(frontend);
-}
diff --git a/packages/driver-node/README.md b/packages/executor/README.md
similarity index 81%
rename from packages/driver-node/README.md
rename to packages/executor/README.md
index f3987ccf..051e27ce 100644
--- a/packages/driver-node/README.md
+++ b/packages/executor/README.md
@@ -1,9 +1,9 @@
-# `@hypit/driver-node`
+# `@hypit/executor`
-Node execution of commands produced by the domain neutral Core.
+Environment-neutral execution of commands produced by the domain-neutral Kernel.
`ProducerRegistry` installs deterministic component handlers. `EndpointRegistry` installs exact
-capability implementations. `NodeDriver.prepare()` regenerates the current commands from Core and
+capability implementations. `Executor.prepare()` regenerates the current commands from Core and
classifies each as runnable or blocked; it does not search the graph or choose a candidate.
Producer handlers receive immutable typed inputs. External work is represented by a declared Need
@@ -15,14 +15,14 @@ Immediate endpoints run once. Asynchronous endpoints start a task, store its han
artifacts after remote completion. Polling uses the stored Need and handle without loading its whole
Build. Credentials are resolved only for slots declared by the selected endpoint; simultaneous reads
of the same credential are coalesced. Cancellation is best effort and never rolls back completed work.
-A failed action retains its receipt and error for the Result; the Driver does not retry or reconcile it.
+A failed action retains its receipt and error for the Result; the Executor does not retry or reconcile it.
Immediate calls and asynchronous submit, poll and collect actions receive the same progress and
diagnostic callbacks. Progress reaches the caller while the action is running; changes of phase also
-enter the execution log. The Endpoint supplies the content, and the Driver forwards it with the
+enter the execution log. The Endpoint supplies the content, and the Executor forwards it with the
selected Endpoint identity without interpreting service-specific phases or treating progress as a receipt.
`acceptOperation()` validates an already received value without making a remote call. Runtime can
retain such a sibling result when another Need fails, without polling unfinished jobs to completion.
-The Driver validates returned values before offering a command result to Core. It does not load
+The Executor validates returned values before offering a command result to the Kernel. It does not load
packages, parse source files, own the active Build work set or know any video vocabulary.
diff --git a/packages/driver-node/package.json b/packages/executor/package.json
similarity index 57%
rename from packages/driver-node/package.json
rename to packages/executor/package.json
index 51006d17..641f6da5 100644
--- a/packages/driver-node/package.json
+++ b/packages/executor/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/driver-node",
+ "name": "@hypit/executor",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
@@ -8,11 +8,11 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/component-kit": "workspace:*",
- "@hypit/core": "workspace:*",
- "@hypit/endpoint-kit": "workspace:*",
+ "@hypit/producer": "workspace:*",
+ "@hypit/kernel": "workspace:*",
+ "@hypit/endpoint": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/runtime": "workspace:*",
- "@hypit/validation": "workspace:*"
+ "@hypit/admission": "workspace:*"
}
}
diff --git a/packages/driver-node/src/driver.ts b/packages/executor/src/executor.ts
similarity index 96%
rename from packages/driver-node/src/driver.ts
rename to packages/executor/src/executor.ts
index b79892d2..ccd08b96 100644
--- a/packages/driver-node/src/driver.ts
+++ b/packages/executor/src/executor.ts
@@ -1,13 +1,11 @@
-import { randomUUID } from "node:crypto";
-
-import { reduce, resolveNeedCommand, resolveProducer } from "@hypit/core";
-import type { ProducerHandlerResult } from "@hypit/component-kit";
-import type { EndpointCredential, EndpointFulfillment, EndpointOutcome } from "@hypit/endpoint-kit";
-import { endpointResourceClaims } from "@hypit/endpoint-kit";
+import { reduce, resolveNeedCommand, resolveProducer } from "@hypit/kernel";
+import type { ProducerHandlerResult } from "@hypit/producer";
+import type { EndpointCredential, EndpointFulfillment, EndpointOutcome } from "@hypit/endpoint";
+import { endpointResourceClaims } from "@hypit/endpoint";
import type {
BuildState,
CommandResult,
- CoreCommand,
+ BuildCommand,
FulfillNeedCommand,
InvokeProducerCommand,
TypedRecord,
@@ -15,8 +13,8 @@ import type {
import {
TypeValidatorRegistry,
validateValue,
-} from "@hypit/validation";
-import type { TypeValidatorRegistryLike } from "@hypit/validation";
+} from "@hypit/admission";
+import type { TypeValidatorRegistryLike } from "@hypit/admission";
import type {
ResourceStore,
CredentialStore,
@@ -42,12 +40,12 @@ import {
} from "./registry.js";
import type {
BlockedCommand,
- DriverExecutionOutcome,
- DriverRunResult,
+ ExecutorExecutionOutcome,
+ ExecutorRunResult,
EndpointRegistration,
} from "./types.js";
-export type NodeDriverOptions = {
+export type ExecutorOptions = {
readonly producers?: ProducerRegistry;
readonly endpoints?: EndpointRegistry;
readonly resources?: ResourceStore;
@@ -90,7 +88,7 @@ function failureMessage(error: unknown): string {
return [...new Set(parts)].join("; caused by: ");
}
-export class NodeDriver {
+export class Executor {
readonly producers: ProducerRegistry;
readonly endpoints: EndpointRegistry;
readonly resources: ResourceStore;
@@ -101,7 +99,7 @@ export class NodeDriver {
readonly #actions: import("@hypit/runtime").RuntimeActionExecutor | undefined;
readonly #credentialReads = new Map<string, Promise<CredentialValue | undefined>>();
- constructor(options: NodeDriverOptions = {}) {
+ constructor(options: ExecutorOptions = {}) {
this.producers = options.producers ?? new ProducerRegistry();
this.endpoints = options.endpoints ?? new EndpointRegistry();
this.resources = options.resources ?? new MemoryResourceStore();
@@ -170,7 +168,7 @@ export class NodeDriver {
#classify(
state: BuildState,
- command: CoreCommand,
+ command: BuildCommand,
indexedRecord?: (id: string) => TypedRecord | undefined,
): { readonly executable?: Executable; readonly blocked?: BlockedCommand } {
if (command.kind === "invoke-producer") {
@@ -322,7 +320,7 @@ export class NodeDriver {
throw new Error(`Operation ${operation.id} belongs to ${operation.endpoint}; its execution source cannot change`);
}
operation ??= await operations.create({
- id: `op_${randomUUID()}`, build: context.build, command: executable.command.id,
+ id: `op_${crypto.randomUUID()}`, build: context.build, command: executable.command.id,
endpoint: executable.endpointId, status: "pending", submission: "queued", createdAt: Date.now(),
request: structuredClone(executable.command),
credentials: structuredClone(executable.registration.credentials ?? {}),
@@ -385,7 +383,7 @@ export class NodeDriver {
const command = operation.request;
if (command === undefined) throw new Error(`Operation ${operation.id} has no stored request`);
const endpoint = registration.endpoint;
- const action: import("@hypit/endpoint-kit").EndpointAction = operation.remoteEnded ? "collect"
+ const action: import("@hypit/endpoint").EndpointAction = operation.remoteEnded ? "collect"
: operation.handle !== undefined ? "poll" : "submit";
if (action === "submit" && operation.submission !== "queued") {
return await operations.update(operation.id, {
@@ -399,7 +397,7 @@ export class NodeDriver {
resources: this.#resourceStore(operation.build), operation: operation.id,
credentials: await this.#endpointCredentials({ ...registration, credentials: operation.credentials ?? registration.credentials ?? {} }),
...this.#endpointObservers(operation.endpoint, runtimeContext),
- checkpoint: async (checkpoint: import("@hypit/endpoint-kit").EndpointCheckpoint) => {
+ checkpoint: async (checkpoint: import("@hypit/endpoint").EndpointCheckpoint) => {
await operations.update(operation.id, { status: "pending", ...checkpoint,
submission: "accepted", acknowledgedAt: operation.acknowledgedAt ?? Date.now(), wakeAt: Date.now(), progress: { phase: checkpoint.remoteEnded ? "collecting" : "submitted" } });
if (checkpoint.remoteEnded) await runtimeContext.releaseOperationCapacity?.();
@@ -537,7 +535,7 @@ export class NodeDriver {
#prepare(
state: BuildState,
- commands: readonly CoreCommand[],
+ commands: readonly BuildCommand[],
indexedRecord?: (id: string) => TypedRecord | undefined,
): RuntimePreparation {
if (state.status === "complete" || state.status === "failed") {
@@ -624,9 +622,9 @@ export class NodeDriver {
return await operations.update(current.id, { status: "cancelled", cancellation });
}
- async run(initial: BuildState, context?: RuntimeExecutionContext): Promise<DriverRunResult> {
+ async run(initial: BuildState, context?: RuntimeExecutionContext): Promise<ExecutorRunResult> {
let state = initial;
- const outcomes: DriverExecutionOutcome[] = [];
+ const outcomes: ExecutorExecutionOutcome[] = [];
while (true) {
if (state.status === "complete") {
@@ -661,7 +659,7 @@ export class NodeDriver {
return { status: "paused", state, outcomes, blocked: [] };
}
if (execution.status === "deferred") {
- throw new Error("direct NodeDriver execution has no Runtime capacity admission to defer");
+ throw new Error("direct Executor execution has no Runtime capacity admission to defer");
}
const event = execution.event;
state = reduce(state, event);
diff --git a/packages/driver-node/src/index.ts b/packages/executor/src/index.ts
similarity index 74%
rename from packages/driver-node/src/index.ts
rename to packages/executor/src/index.ts
index 76f48ad4..d33f8677 100644
--- a/packages/driver-node/src/index.ts
+++ b/packages/executor/src/index.ts
@@ -1,6 +1,6 @@
export { MemoryResourceStore } from "./resources.js";
-export { NodeDriver } from "./driver.js";
-export type { NodeDriverOptions } from "./driver.js";
+export { Executor } from "./executor.js";
+export type { ExecutorOptions } from "./executor.js";
export { evaluateProducerPlan } from "./planning.js";
export type { ProducerPlanEvaluation } from "./planning.js";
export {
diff --git a/packages/driver-node/src/planning.ts b/packages/executor/src/planning.ts
similarity index 89%
rename from packages/driver-node/src/planning.ts
rename to packages/executor/src/planning.ts
index b3d64a7d..bcc2e7fe 100644
--- a/packages/driver-node/src/planning.ts
+++ b/packages/executor/src/planning.ts
@@ -1,9 +1,9 @@
-import { BuildMachine } from "@hypit/core";
+import { BuildMachine } from "@hypit/kernel";
import type { BuildDefinition, BuildState } from "@hypit/protocol";
-import { TypeValidatorRegistry } from "@hypit/validation";
-import type { TypeValidatorRegistryLike } from "@hypit/validation";
+import { TypeValidatorRegistry } from "@hypit/admission";
+import type { TypeValidatorRegistryLike } from "@hypit/admission";
-import { NodeDriver } from "./driver.js";
+import { Executor } from "./executor.js";
import { EndpointRegistry, ProducerRegistry } from "./registry.js";
export type ProducerPlanEvaluation = {
@@ -25,7 +25,7 @@ export async function evaluateProducerPlan(
producers: ProducerRegistry,
validators: TypeValidatorRegistryLike = new TypeValidatorRegistry(),
): Promise<ProducerPlanEvaluation> {
- const driver = new NodeDriver({ producers, endpoints: new EndpointRegistry(), validators });
+ const driver = new Executor({ producers, endpoints: new EndpointRegistry(), validators });
const machine = new BuildMachine(definition);
const attempted = new Set<string>();
const failures = new Map<string, string>();
diff --git a/packages/driver-node/src/registry.ts b/packages/executor/src/registry.ts
similarity index 99%
rename from packages/driver-node/src/registry.ts
rename to packages/executor/src/registry.ts
index 913261e2..584b860e 100644
--- a/packages/driver-node/src/registry.ts
+++ b/packages/executor/src/registry.ts
@@ -5,10 +5,10 @@ import type {
EndpointScheduling,
ImmediateEndpointHandler,
AsyncEndpoint,
-} from "@hypit/endpoint-kit";
+} from "@hypit/endpoint";
import type {
ProducerRegistrar,
-} from "@hypit/component-kit";
+} from "@hypit/producer";
import type {
CapabilityRef,
ProducerRef,
diff --git a/packages/driver-node/src/resources.ts b/packages/executor/src/resources.ts
similarity index 93%
rename from packages/driver-node/src/resources.ts
rename to packages/executor/src/resources.ts
index aa6cb669..a6c7dff2 100644
--- a/packages/driver-node/src/resources.ts
+++ b/packages/executor/src/resources.ts
@@ -1,5 +1,3 @@
-import { randomUUID } from "node:crypto";
-
import type { BlobRef, ResourceId } from "@hypit/protocol";
import type { ResourceIOOptions, ResourceStore } from "@hypit/runtime";
@@ -9,7 +7,7 @@ export class MemoryResourceStore implements ResourceStore {
async put(bytes: Uint8Array, mediaType: string, options: ResourceIOOptions = {}): Promise<BlobRef> {
options.signal?.throwIfAborted();
const copy = Uint8Array.from(bytes);
- const resource = `res_${randomUUID()}` as ResourceId;
+ const resource = `res_${crypto.randomUUID()}` as ResourceId;
this.#values.set(resource, copy);
return { kind: "blob", resource, size: copy.byteLength, mediaType };
}
diff --git a/packages/driver-node/src/types.ts b/packages/executor/src/types.ts
similarity index 84%
rename from packages/driver-node/src/types.ts
rename to packages/executor/src/types.ts
index afd2dce8..2260bc80 100644
--- a/packages/driver-node/src/types.ts
+++ b/packages/executor/src/types.ts
@@ -1,24 +1,24 @@
import type {
BuildState,
- CoreCommand,
+ BuildCommand,
TypeRef,
CapabilityRef,
} from "@hypit/protocol";
import type {
ProducerHandler,
-} from "@hypit/component-kit";
-import type { EndpointRegistrationOptions, EndpointScheduling, ImmediateEndpointHandler, AsyncEndpoint } from "@hypit/endpoint-kit";
+} from "@hypit/producer";
+import type { EndpointRegistrationOptions, EndpointScheduling, ImmediateEndpointHandler, AsyncEndpoint } from "@hypit/endpoint";
export type {
ProducerHandler,
ProducerHandlerContext,
ProducerHandlerResult,
ProducerRegistrar,
-} from "@hypit/component-kit";
+} from "@hypit/producer";
-export type DriverExecutionOutcome = {
+export type ExecutorExecutionOutcome = {
readonly command: string;
- readonly kind: CoreCommand["kind"];
+ readonly kind: BuildCommand["kind"];
readonly status: "completed" | "pending" | "error";
readonly operation?: string;
readonly wakeAt?: number;
@@ -36,10 +36,10 @@ export type BlockedCommand = {
readonly subject: string;
};
-export type DriverRunResult = {
+export type ExecutorRunResult = {
readonly status: "complete" | "paused" | "failed";
readonly state: BuildState;
- readonly outcomes: readonly DriverExecutionOutcome[];
+ readonly outcomes: readonly ExecutorExecutionOutcome[];
readonly blocked: readonly BlockedCommand[];
};
diff --git a/packages/driver-node/test/driver.test.ts b/packages/executor/test/driver.test.ts
similarity index 93%
rename from packages/driver-node/test/driver.test.ts
rename to packages/executor/test/driver.test.ts
index 32879aee..c749b586 100644
--- a/packages/driver-node/test/driver.test.ts
+++ b/packages/executor/test/driver.test.ts
@@ -4,13 +4,13 @@ import test from "node:test";
import {
ProducerRegistry,
MemoryResourceStore,
- NodeDriver,
+ Executor,
EndpointRegistry,
-} from "@hypit/driver-node";
+} from "@hypit/executor";
import { credentialRef } from "@hypit/runtime";
import type { WritableCredentialStore } from "@hypit/runtime";
-import { capabilities, createGreetingBuild, producers as greetingProducers, types } from "../../core/test/greeting-fixture.js";
+import { capabilities, createGreetingBuild, producers as greetingProducers, types } from "../../kernel/test/greeting-fixture.js";
function inlineString(value: unknown): string {
if (typeof value !== "string") throw new Error("expected inline string");
@@ -78,7 +78,7 @@ function configuredRegistry(): {
test("Driver can continue a returned state after its missing Endpoint is installed", async () => {
const { producers, endpoints, calls } = configuredRegistry();
- const driver = new NodeDriver({ producers, endpoints });
+ const driver = new Executor({ producers, endpoints });
const paused = await driver.run(createGreetingBuild());
assert.equal(paused.status, "paused");
@@ -108,7 +108,7 @@ test("Endpoint Registry rejects an ambiguous Runtime Profile", async () => {
value: { kind: "inline", value: "Beta" },
}));
- const driver = new NodeDriver({ producers, endpoints });
+ const driver = new Executor({ producers, endpoints });
const ambiguous = await driver.run(createGreetingBuild());
assert.equal(ambiguous.status, "paused");
assert.equal(ambiguous.blocked[0]?.reason, "ambiguous-endpoint");
@@ -131,7 +131,7 @@ test("an Endpoint receives only declared credential slots and secrets never ente
},
{ credentials: { apiKey: credentialRef("test", "endpoint-key") } },
);
- const driver = new NodeDriver({
+ const driver = new Executor({
producers,
endpoints,
credentials: {
@@ -168,7 +168,7 @@ test("a writable credential gives its Endpoint authority to replace only that de
async put(_ref, value) { stored = value.secret; },
async delete() { return false; },
};
- const driver = new NodeDriver({
+ const driver = new Executor({
producers,
endpoints,
credentials: credentialStore,
@@ -194,7 +194,7 @@ test("Endpoint capabilities may narrow themselves with typed Need constraints",
},
});
- const completed = await new NodeDriver({ producers, endpoints }).run(createGreetingBuild());
+ const completed = await new Executor({ producers, endpoints }).run(createGreetingBuild());
assert.equal(completed.status, "complete");
assert.equal(completed.state.records.some((record) => record.id === "generated:root"), true);
});
@@ -213,7 +213,7 @@ test("the same return Type cannot impersonate another exact capability", async (
};
},
);
- const result = await new NodeDriver({ producers, endpoints }).run(createGreetingBuild());
+ const result = await new Executor({ producers, endpoints }).run(createGreetingBuild());
assert.equal(result.status, "paused");
assert.equal(result.blocked[0]?.reason, "missing-endpoint");
assert.equal(calls, 0);
@@ -229,10 +229,10 @@ test("an alternate Candidate is explicitly selected before execution, never by E
}),
);
- const exact = await new NodeDriver({ producers, endpoints }).run(createGreetingBuild());
+ const exact = await new Executor({ producers, endpoints }).run(createGreetingBuild());
assert.equal(exact.status, "paused");
assert.equal(exact.blocked[0]?.reason, "missing-endpoint");
- const accepted = await new NodeDriver({ producers, endpoints }).run(
+ const accepted = await new Executor({ producers, endpoints }).run(
createGreetingBuild({ generationRealization: "placeholder" }),
);
assert.equal(accepted.status, "complete");
@@ -259,7 +259,7 @@ test("Core still owns scheduling when Driver has every implementation", async ()
}));
const start = createGreetingBuild();
assert.equal(start.outstanding[0]?.kind, "invoke-producer");
- const result = await new NodeDriver({ producers, endpoints }).run(start);
+ const result = await new Executor({ producers, endpoints }).run(start);
assert.equal(result.status, "complete");
});
@@ -275,7 +275,7 @@ test("a direct Driver failure ends its state and a new attempt starts independen
};
});
- const driver = new NodeDriver({ producers, endpoints });
+ const driver = new Executor({ producers, endpoints });
const paused = await driver.run(createGreetingBuild());
assert.equal(paused.status, "failed");
assert.match(paused.outcomes.at(-1)?.message ?? "", /temporary outage/u);
diff --git a/packages/driver-node/test/scheduler.test.ts b/packages/executor/test/scheduler.test.ts
similarity index 85%
rename from packages/driver-node/test/scheduler.test.ts
rename to packages/executor/test/scheduler.test.ts
index e7d71500..da3e72b2 100644
--- a/packages/driver-node/test/scheduler.test.ts
+++ b/packages/executor/test/scheduler.test.ts
@@ -3,19 +3,19 @@ import test from "node:test";
import {
ProducerRegistry,
- NodeDriver,
+ Executor,
EndpointRegistry,
-} from "@hypit/driver-node";
-import type { AsyncEndpoint } from "@hypit/endpoint-kit";
+} from "@hypit/executor";
+import type { AsyncEndpoint } from "@hypit/endpoint";
import {
materializeBuild,
-} from "@hypit/core";
+} from "@hypit/kernel";
import {
- LocalBuildScheduler,
+ InProcessBuildScheduler,
} from "@hypit/runtime";
import type { BuildStore, OperationSnapshot, OperationStore, OperationUpdate, RuntimeCommandExecutor, RuntimeExecutionContext } from "@hypit/runtime";
-import { capabilities, createGreetingBuild, createParallelGreetingBuild, producers as greetingProducers, types } from "../../core/test/greeting-fixture.js";
-import { completeChainStep, createChainDefinition } from "../../core/test/chain-fixture.js";
+import { capabilities, createGreetingBuild, createParallelGreetingBuild, producers as greetingProducers, types } from "../../kernel/test/greeting-fixture.js";
+import { completeChainStep, createChainDefinition } from "../../kernel/test/chain-fixture.js";
function memoryOperations(): OperationStore {
const values = new Map<string, OperationSnapshot>();
@@ -85,7 +85,7 @@ test("a durable Scheduler keeps preparation and Record lookup on the indexed Bui
return { status: "completed", event: completeChainStep(descriptor.command) };
},
};
- const [result] = await new LocalBuildScheduler(executor, { buildStore: builds }).run([{
+ const [result] = await new InProcessBuildScheduler(executor, { buildStore: builds }).run([{
id: "indexed-chain",
snapshot: { build: "indexed-chain", definition, facts: [], state },
}]);
@@ -130,7 +130,7 @@ function configuredExecutor(options: {
},
},
);
- return { executor: new NodeDriver({ producers, endpoints }), endpoints, getCalls: () => calls };
+ return { executor: new Executor({ producers, endpoints }), endpoints, getCalls: () => calls };
}
function registerGreetingProducers(producers: ProducerRegistry): void {
@@ -176,7 +176,7 @@ function asyncExecutor(
},
},
);
- return new NodeDriver({ producers, endpoints, operations });
+ return new Executor({ producers, endpoints, operations });
}
test("one local Scheduler shares an Endpoint resource across multiple Builds", async () => {
@@ -188,7 +188,7 @@ test("one local Scheduler shares an Endpoint resource across multiple Builds", a
maximumActive = Math.max(maximumActive, active);
},
});
- const scheduler = new LocalBuildScheduler(executor);
+ const scheduler = new InProcessBuildScheduler(executor);
const results = await scheduler.run([
{ id: "video-a", state: createGreetingBuild() },
{ id: "video-b", state: createGreetingBuild() },
@@ -210,7 +210,7 @@ test("independent paid commands inside one Build may fill the same resource with
maximumActive = Math.max(maximumActive, active);
},
});
- const [result] = await new LocalBuildScheduler(executor).run([{
+ const [result] = await new InProcessBuildScheduler(executor).run([{
id: "two-shots",
state: createParallelGreetingBuild(),
}]);
@@ -257,7 +257,7 @@ test("a failure stops new work and preserves a result from an already running si
{ scheduling: { resources: [{ id: "pool:fixture.account", limit: 2 }] } },
);
- const [result] = await new LocalBuildScheduler(new NodeDriver({ producers, endpoints, operations })).run([{
+ const [result] = await new InProcessBuildScheduler(new Executor({ producers, endpoints, operations })).run([{
id: "parallel-failure",
state: createParallelGreetingBuild(3),
}]);
@@ -296,7 +296,7 @@ test("an asynchronous Endpoint starts once and is polled until complete", async
};
const firstExecutor = asyncExecutor(endpoint, operations);
- const [first] = await new LocalBuildScheduler(firstExecutor)
+ const [first] = await new InProcessBuildScheduler(firstExecutor)
.run([{ id: "video", state: createGreetingBuild() }]);
assert.equal(first?.status, "paused");
assert.equal(starts, 1);
@@ -307,7 +307,7 @@ test("an asynchronous Endpoint starts once and is polled until complete", async
assert.equal((await operations.read(pending.operation))?.status, "pending");
const secondExecutor = asyncExecutor(endpoint, operations);
- const [second] = await new LocalBuildScheduler(secondExecutor)
+ const [second] = await new InProcessBuildScheduler(secondExecutor)
.run([{ id: "video", state: createGreetingBuild() }]);
assert.equal(second?.status, "complete");
@@ -373,6 +373,38 @@ test("asynchronous actions expose progress before returning without treating it
})));
});
+test("a temporary collection failure keeps remote completion and retries collection", async () => {
+ const operations = memoryOperations();
+ let collections = 0;
+ const executor = asyncExecutor({
+ start: () => ({ status: "pending", handle: { job: "one" }, receipt: { id: "one" } }),
+ poll: (context) => ({ status: "ready", handle: context.handle, receipt: { id: "one" } }),
+ collect: (context) => {
+ collections += 1;
+ if (collections === 1) {
+ return { status: "pending", handle: context.handle, progress: { phase: "retrying-collection" } };
+ }
+ return { status: "completed", result: { value: { kind: "inline", value: "done" } }, receipt: { id: "one" } };
+ },
+ }, operations);
+ const [first] = await new InProcessBuildScheduler(executor).run([{ id: "video", state: createGreetingBuild() }]);
+ const operationId = first?.outcomes.find((entry) => entry.status === "pending")?.operation;
+ assert.ok(operationId);
+ const submitted = await operations.read(operationId);
+ assert.ok(submitted);
+
+ const ready = await executor.advanceOperation(submitted, { build: "video" });
+ assert.equal(ready.remoteEnded, true);
+ const retry = await executor.advanceOperation(ready, { build: "video" });
+ assert.equal(retry.status, "pending");
+ assert.equal(retry.remoteEnded, true);
+ assert.equal(retry.progress?.phase, "retrying-collection");
+ const completed = await executor.advanceOperation(retry, { build: "video" });
+ assert.equal(collections, 2);
+ assert.equal(completed.remoteEnded, true);
+ assert.deepEqual(completed.completion, { value: { kind: "inline", value: "done" } });
+});
+
test("a submission error ends its attempt and a new Build can submit normally", async () => {
const operations = memoryOperations();
let starts = 0;
@@ -384,7 +416,7 @@ test("a submission error ends its attempt and a new Build can submit normally",
},
poll() { return { status: "completed", result: { value: { kind: "inline", value: "done" } } }; },
};
- const scheduler = new LocalBuildScheduler(asyncExecutor(endpoint, operations));
+ const scheduler = new InProcessBuildScheduler(asyncExecutor(endpoint, operations));
const [failed] = await scheduler.run([{ id: "first", state: createGreetingBuild() }]);
assert.equal(failed?.status, "failed");
assert.equal((await operations.list({ build: "first" }))[0]?.status, "failed");
@@ -416,7 +448,7 @@ test("wakeAt prevents early polling and Runtime cancellation becomes a terminal
},
};
const executor = asyncExecutor(endpoint, operations);
- const scheduler = new LocalBuildScheduler(executor);
+ const scheduler = new InProcessBuildScheduler(executor);
const [first] = await scheduler.run([{ id: "cancel-video", state: createGreetingBuild() }]);
const operationId = first?.outcomes.find((item) => item.status === "pending")?.operation;
assert.ok(operationId);
@@ -445,7 +477,7 @@ test("request quantities govern concurrent admission, independent of whole-Need
active -= 4;
return { value: { kind: "inline", value: "done" } };
}, { scheduling: { resources: [{ id: "browsers", limit: 6 }], unitsForRequest: () => ({ browsers: 4 }) } });
- const results = await new LocalBuildScheduler(new NodeDriver({ producers: producerRegistry, endpoints }))
+ const results = await new InProcessBuildScheduler(new Executor({ producers: producerRegistry, endpoints }))
.run(["a", "b"].map((id) => ({ id, state: createGreetingBuild() })));
assert.ok(results.every((result) => result.status === "complete"));
assert.equal(maximum, 4, "two four-worker requests cannot fit in six slots");
@@ -458,7 +490,7 @@ test("a poll transport error fails once and retains the acknowledged receipt", a
start() { starts++; return { status: "pending", handle: { job: "one" }, receipt: { id: "one" } }; },
poll() { polls++; throw new Error("connection lost"); },
};
- const scheduler = new LocalBuildScheduler(asyncExecutor(endpoint, operations));
+ const scheduler = new InProcessBuildScheduler(asyncExecutor(endpoint, operations));
const [first] = await scheduler.run([{ id: "poll-error", state: createGreetingBuild() }]);
const [second] = await scheduler.run([{ id: "poll-error", state: first!.state }]);
const [operation] = await operations.list({ build: "poll-error" });
diff --git a/packages/driver-node/test/validation.test.ts b/packages/executor/test/validation.test.ts
similarity index 96%
rename from packages/driver-node/test/validation.test.ts
rename to packages/executor/test/validation.test.ts
index beff7fca..90a96fbf 100644
--- a/packages/driver-node/test/validation.test.ts
+++ b/packages/executor/test/validation.test.ts
@@ -9,12 +9,12 @@ import {
sealRecord,
start,
verifyRecordStructure,
-} from "@hypit/core";
+} from "@hypit/kernel";
import {
ProducerRegistry,
- NodeDriver,
+ Executor,
EndpointRegistry,
-} from "@hypit/driver-node";
+} from "@hypit/executor";
import type {
CapabilityRef,
CompiledGraph,
@@ -28,7 +28,7 @@ import {
TypeValidatorRegistry,
admitRecord,
validateValue,
-} from "@hypit/validation";
+} from "@hypit/admission";
const contractModule = { name: "example.measurement-contract", version: "1.0.0" } as const;
const sensorModule = { name: "example.sensor", version: "1.0.0" } as const;
@@ -191,7 +191,7 @@ function hosts(measured: number): ProducerRegistry {
test("three independent packages communicate through an owner-validated nominal Type", async () => {
const linked = program();
- const result = await new NodeDriver({
+ const result = await new Executor({
producers: hosts(4),
validators: registry(),
}).run(outputBuild(linked));
@@ -205,7 +205,7 @@ test("three independent packages communicate through an owner-validated nominal
test("a structurally valid but semantically invalid Producer value never enters BuildState", async () => {
const linked = program();
- const result = await new NodeDriver({
+ const result = await new Executor({
producers: hosts(3),
validators: registry(),
}).run(outputBuild(linked));
@@ -258,7 +258,7 @@ async function providerBuild(measured: number) {
value: { kind: "inline", value: { value: measured, unit: "ticks" } },
}),
);
- return await new NodeDriver({ producers: hosts, endpoints, validators: registry() }).run(start(
+ return await new Executor({ producers: hosts, endpoints, validators: registry() }).run(start(
linked,
graph,
sealBuildRequest({
diff --git a/packages/host/README.md b/packages/facet/README.md
similarity index 50%
rename from packages/host/README.md
rename to packages/facet/README.md
index b1f84be8..113927e3 100644
--- a/packages/host/README.md
+++ b/packages/facet/README.md
@@ -1,5 +1,5 @@
-# `@hypit/host`
+# `@hypit/facet`
-The minimal opaque `HostFacet` envelope: an ABI, logical offers, locked identity and inert
-implementation. Package loading can carry it without learning what it does; only the exact Host ABI
+The minimal opaque `Facet` envelope: an ABI, logical offers, locked identity and inert
+implementation. Package loading can carry it without learning what it does; only the exact consumer ABI
may interpret it. Source and asset sessions live separately in `@hypit/workspace`.
diff --git a/packages/host/package.json b/packages/facet/package.json
similarity index 85%
rename from packages/host/package.json
rename to packages/facet/package.json
index 48f6b76b..d6cc41ee 100644
--- a/packages/host/package.json
+++ b/packages/facet/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/host",
+ "name": "@hypit/facet",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
diff --git a/packages/facet/src/facet.ts b/packages/facet/src/facet.ts
new file mode 100644
index 00000000..d6fa4acb
--- /dev/null
+++ b/packages/facet/src/facet.ts
@@ -0,0 +1,6 @@
+/** One package contribution understood only by the owner of its exact ABI. */
+export type Facet = {
+ readonly abi: string;
+ readonly offers?: readonly string[];
+ readonly implementation: unknown;
+};
diff --git a/packages/host/src/frontend.ts b/packages/facet/src/frontend.ts
similarity index 64%
rename from packages/host/src/frontend.ts
rename to packages/facet/src/frontend.ts
index 06177331..550a4245 100644
--- a/packages/host/src/frontend.ts
+++ b/packages/facet/src/frontend.ts
@@ -1,13 +1,13 @@
-import type { HostFacet } from "./facet.js";
+import type { Facet } from "./facet.js";
export type FrontendImplementation = {
readonly id: string;
};
-export type FrontendHostFacet<
+export type FrontendFacet<
Kind extends string,
Frontend extends FrontendImplementation,
-> = HostFacet & {
+> = Facet & {
readonly offers: readonly [string];
readonly implementation: {
readonly kind: Kind;
@@ -15,14 +15,14 @@ export type FrontendHostFacet<
};
};
-/** Build the common inert declaration shared by every self-described Source Frontend. */
-export function createFrontendHostFacet<
+/** Build the common inert declaration shared by every contributed Source Frontend. */
+export function createFrontendFacet<
Kind extends string,
Frontend extends FrontendImplementation,
->(abi: string, kind: Kind, frontend: Frontend): FrontendHostFacet<Kind, Frontend> {
+>(abi: string, kind: Kind, frontend: Frontend): FrontendFacet<Kind, Frontend> {
if (abi.trim().length === 0 || kind.trim().length === 0
|| frontend.id.trim().length === 0) {
- throw new Error(`${kind || "Source"} Frontend Host facet has an invalid identity`);
+ throw new Error(`${kind || "Source"} Frontend facet has an invalid identity`);
}
return {
abi,
@@ -34,11 +34,11 @@ export function createFrontendHostFacet<
};
}
-/** Select and validate Frontends owned by one exact Host ABI and Frontend kind. */
-export function frontendsFromHostFacets<
+/** Select and validate Frontends owned by one exact Facet ABI and Frontend kind. */
+export function frontendsFromFacets<
Kind extends string,
Frontend extends FrontendImplementation,
->(abi: string, kind: Kind, facets: readonly HostFacet[]): readonly Frontend[] {
+>(abi: string, kind: Kind, facets: readonly Facet[]): readonly Frontend[] {
const values: Frontend[] = [];
for (const facet of facets) {
if (facet.abi !== abi || facet.implementation === null
@@ -48,7 +48,7 @@ export function frontendsFromHostFacets<
const frontend = implementation.frontend;
if (frontend === null || typeof frontend !== "object" || Array.isArray(frontend)
|| typeof (frontend as { readonly id?: unknown }).id !== "string") {
- throw new Error(`${kind} Frontend Host facet has an invalid implementation`);
+ throw new Error(`${kind} Frontend facet has an invalid implementation`);
}
values.push(frontend as Frontend);
}
diff --git a/packages/facet/src/index.ts b/packages/facet/src/index.ts
new file mode 100644
index 00000000..f1714b2a
--- /dev/null
+++ b/packages/facet/src/index.ts
@@ -0,0 +1,9 @@
+export type { Facet } from "./facet.js";
+export {
+ createFrontendFacet,
+ frontendsFromFacets,
+} from "./frontend.js";
+export type {
+ FrontendFacet,
+ FrontendImplementation,
+} from "./frontend.js";
diff --git a/packages/host/src/facet.ts b/packages/host/src/facet.ts
deleted file mode 100644
index 50abb604..00000000
--- a/packages/host/src/facet.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-/** One package contribution understood only by the Host that owns its ABI. */
-export type HostFacet = {
- readonly abi: string;
- readonly offers?: readonly string[];
- readonly implementation: unknown;
-};
diff --git a/packages/host/src/index.ts b/packages/host/src/index.ts
deleted file mode 100644
index ae97dd39..00000000
--- a/packages/host/src/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export type { HostFacet } from "./facet.js";
-export {
- createFrontendHostFacet,
- frontendsFromHostFacets,
-} from "./frontend.js";
-export type {
- FrontendHostFacet,
- FrontendImplementation,
-} from "./frontend.js";
diff --git a/packages/core/README.md b/packages/kernel/README.md
similarity index 99%
rename from packages/core/README.md
rename to packages/kernel/README.md
index 426192d6..6a0eb5be 100644
--- a/packages/core/README.md
+++ b/packages/kernel/README.md
@@ -1,4 +1,4 @@
-# `@hypit/core`
+# `@hypit/kernel`
The domain neutral graph compiler and build state machine.
diff --git a/packages/core/package.json b/packages/kernel/package.json
similarity index 88%
rename from packages/core/package.json
rename to packages/kernel/package.json
index cf1d47b5..3a38ec09 100644
--- a/packages/core/package.json
+++ b/packages/kernel/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/core",
+ "name": "@hypit/kernel",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
diff --git a/packages/core/src/error.ts b/packages/kernel/src/error.ts
similarity index 100%
rename from packages/core/src/error.ts
rename to packages/kernel/src/error.ts
diff --git a/packages/core/src/graph.ts b/packages/kernel/src/graph.ts
similarity index 100%
rename from packages/core/src/graph.ts
rename to packages/kernel/src/graph.ts
diff --git a/packages/core/src/index.ts b/packages/kernel/src/index.ts
similarity index 100%
rename from packages/core/src/index.ts
rename to packages/kernel/src/index.ts
diff --git a/packages/core/src/link.ts b/packages/kernel/src/link.ts
similarity index 100%
rename from packages/core/src/link.ts
rename to packages/kernel/src/link.ts
diff --git a/packages/core/src/machine.ts b/packages/kernel/src/machine.ts
similarity index 96%
rename from packages/core/src/machine.ts
rename to packages/kernel/src/machine.ts
index 851b7911..df81bde7 100644
--- a/packages/core/src/machine.ts
+++ b/packages/kernel/src/machine.ts
@@ -2,7 +2,7 @@ import type {
BuildDefinition,
BuildFact,
BuildState,
- CoreCommand,
+ BuildCommand,
CommandResult,
Need,
TypedRecord,
@@ -24,13 +24,13 @@ function insertDependency(dependents: Map<string, string[]>, record: string, ste
}
function mergeCommands(
- current: readonly CoreCommand[],
+ current: readonly BuildCommand[],
removed: string,
- added: readonly CoreCommand[],
-): readonly CoreCommand[] {
+ added: readonly BuildCommand[],
+): readonly BuildCommand[] {
const retained = current.filter((command) => command.id !== removed);
const additions = [...added].sort((left, right) => left.id.localeCompare(right.id));
- const merged: CoreCommand[] = [];
+ const merged: BuildCommand[] = [];
let left = 0;
let right = 0;
while (left < retained.length || right < additions.length) {
@@ -59,7 +59,7 @@ export class BuildMachine {
#proposal: BuildFact | undefined;
readonly #records = new Map<string, TypedRecord>();
readonly #needs = new Map<string, Need>();
- readonly #commands = new Map<string, CoreCommand>();
+ readonly #commands = new Map<string, BuildCommand>();
readonly #stepIndexes = new Map<string, number>();
readonly #stepStatuses = new Map<string, "pending" | "complete">();
readonly #missingInputs = new Map<string, number>();
@@ -96,7 +96,7 @@ export class BuildMachine {
return this.#state.status;
}
- commands(): readonly CoreCommand[] {
+ commands(): readonly BuildCommand[] {
return this.#state.outstanding;
}
@@ -138,7 +138,7 @@ export class BuildMachine {
let steps = this.#state.steps;
let diagnostics = this.#state.diagnostics;
let status = this.#state.status;
- const addedCommands: CoreCommand[] = [];
+ const addedCommands: BuildCommand[] = [];
if (fact.kind === "command-failed") {
status = "failed";
diff --git a/packages/core/src/plan.ts b/packages/kernel/src/plan.ts
similarity index 100%
rename from packages/core/src/plan.ts
rename to packages/kernel/src/plan.ts
diff --git a/packages/core/src/reducer.ts b/packages/kernel/src/reducer.ts
similarity index 99%
rename from packages/core/src/reducer.ts
rename to packages/kernel/src/reducer.ts
index 8debd493..2e78a37d 100644
--- a/packages/core/src/reducer.ts
+++ b/packages/kernel/src/reducer.ts
@@ -3,7 +3,7 @@ import type {
BuildFact,
BuildRequest,
BuildState,
- CoreCommand,
+ BuildCommand,
CompiledGraph,
CommandResult,
CommandId,
@@ -46,7 +46,7 @@ export function resolveNeedCommand(state: BuildState, id: CommandId): FulfillNee
return need === undefined ? undefined : buildNeedCommand(need);
}
-function withoutCommand(state: BuildState, id: string): readonly CoreCommand[] {
+function withoutCommand(state: BuildState, id: string): readonly BuildCommand[] {
return state.outstanding.filter((command) => command.id !== id);
}
@@ -216,7 +216,7 @@ function schedule(state: BuildState): BuildState {
}
const issued = new Set(state.outstanding.map((command) => command.id));
- const commands: CoreCommand[] = [...state.outstanding];
+ const commands: BuildCommand[] = [...state.outstanding];
for (const need of state.needs) {
if (records.has(need.result)) continue;
const command = buildNeedCommand(need);
@@ -314,7 +314,7 @@ function initialBuildView(definition: BuildDefinition): BuildState {
}
export type BuildAdmissionLookup = {
- readonly command: (id: CommandId) => CoreCommand | undefined;
+ readonly command: (id: CommandId) => BuildCommand | undefined;
readonly stepStatus: (id: string) => "pending" | "complete" | undefined;
readonly need: (id: string) => Need | undefined;
readonly record: (id: string) => TypedRecord | undefined;
diff --git a/packages/core/src/reference.ts b/packages/kernel/src/reference.ts
similarity index 100%
rename from packages/core/src/reference.ts
rename to packages/kernel/src/reference.ts
diff --git a/packages/core/src/slice.ts b/packages/kernel/src/slice.ts
similarity index 100%
rename from packages/core/src/slice.ts
rename to packages/kernel/src/slice.ts
diff --git a/packages/core/test/chain-fixture.ts b/packages/kernel/test/chain-fixture.ts
similarity index 98%
rename from packages/core/test/chain-fixture.ts
rename to packages/kernel/test/chain-fixture.ts
index b6aad88c..5f1d2c76 100644
--- a/packages/core/test/chain-fixture.ts
+++ b/packages/kernel/test/chain-fixture.ts
@@ -3,7 +3,7 @@ import {
defineBuild,
link,
sealRecord,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
BuildDefinition,
CommandResult,
diff --git a/packages/core/test/core.test.ts b/packages/kernel/test/core.test.ts
similarity index 99%
rename from packages/core/test/core.test.ts
rename to packages/kernel/test/core.test.ts
index f3c97349..5e29b2aa 100644
--- a/packages/core/test/core.test.ts
+++ b/packages/kernel/test/core.test.ts
@@ -7,7 +7,7 @@ import {
materializeBuild,
reduce,
resolveNeedCommand,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
CommandResult,
BuildFact,
diff --git a/packages/core/test/demand.test.ts b/packages/kernel/test/demand.test.ts
similarity index 99%
rename from packages/core/test/demand.test.ts
rename to packages/kernel/test/demand.test.ts
index 1d28f8a4..8f1649c4 100644
--- a/packages/core/test/demand.test.ts
+++ b/packages/kernel/test/demand.test.ts
@@ -11,7 +11,7 @@ import {
sealCompiledGraph,
sealRecord,
start,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
BuildRequest,
BuildState,
diff --git a/packages/core/test/greeting-fixture.ts b/packages/kernel/test/greeting-fixture.ts
similarity index 99%
rename from packages/core/test/greeting-fixture.ts
rename to packages/kernel/test/greeting-fixture.ts
index a6e2ed5d..7c1d7a4d 100644
--- a/packages/core/test/greeting-fixture.ts
+++ b/packages/kernel/test/greeting-fixture.ts
@@ -5,7 +5,7 @@ import {
sealCompiledGraph,
sealRecord,
start,
-} from "@hypit/core";
+} from "@hypit/kernel";
import type {
BuildState,
CapabilityRef,
diff --git a/packages/core/test/machine-scaling.test.ts b/packages/kernel/test/machine-scaling.test.ts
similarity index 96%
rename from packages/core/test/machine-scaling.test.ts
rename to packages/kernel/test/machine-scaling.test.ts
index b525137e..6b2000f0 100644
--- a/packages/core/test/machine-scaling.test.ts
+++ b/packages/kernel/test/machine-scaling.test.ts
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { BuildMachine } from "@hypit/core";
+import { BuildMachine } from "@hypit/kernel";
import type { BuildFact, InvokeProducerCommand } from "@hypit/protocol";
import { completeChainStep, createChainDefinition } from "./chain-fixture.js";
diff --git a/packages/package-loader-node/README.md b/packages/loader/README.md
similarity index 55%
rename from packages/package-loader-node/README.md
rename to packages/loader/README.md
index 7a1fcb80..3ebc0742 100644
--- a/packages/package-loader-node/README.md
+++ b/packages/loader/README.md
@@ -1,6 +1,13 @@
-# `@hypit/package-loader-node`
+# `@hypit/loader`
-Loads installed Hypit packages selected by source discovery or a Runtime Profile.
+Defines the package contribution value consumed by Hypit Hosts. It contains logical Modules and
+opaque Facets, but no package-manager policy or platform I/O. `verifyPackageContributions()` checks
+the selected declarations without interpreting executable Facets.
+
+## Node Host
+
+`@hypit/loader/node` loads installed Hypit packages selected by Source discovery or a Runtime
+Profile.
The user's package manager owns installation, versions and package bytes. This loader resolves only
the requested packages. An implementation package selected by Source discovery or a Runtime
@@ -13,32 +20,30 @@ The Host can resolve that one requested file without importing `hypit.activation
package executable authority. Package-internal relative Sources and assets remain confined to the
package root. Executable activation and Source-data lookup are deliberately separate operations.
+The root CLI Host similarly resolves only command-module exports named by the Distribution or
+project `package.json`. `resolveNodePackageModule` follows the exact npm export (including its
+`import` condition) without scanning dependencies; importing the resolved module is the Host's
+separate, explicitly authorized action.
+
Module dependencies declared by selected packages are loaded from ordinary installed dependencies.
-Syntax, components and Runtime facets remain inert until a matching Host ABI consumes them.
+Syntax, components and Runtime facets remain inert until a matching Facet ABI consumes them.
Physical lookup distinguishes package identity, ESM imports, package resources and npm executables.
It does not use a CommonJS root export as evidence that a package is installed: CLI-only,
-import-only and resource-only packages are valid. The active Distribution owns `@hypit/*`;
-Distribution code may use upstream dependencies from the machine npm home, while project packages
-continue to resolve their own dependencies from the project.
-
-The machine home stores `<package-name>/<exact-version>/node_modules`, with the importing package's
-ordinary `dependencies` selecting the version. Loading a second Distribution does not replace an
-existing release. ESM, resource and executable lookup use the same selection; project dependencies
-retain ordinary project ownership. There is no inventory or source-content matching.
-
-Runtime declaration discovery may use `deferExternalDependencies` to inspect capabilities and
-Managed Programs before their execution tools are prepared. Actual JavaScript imports still follow
-Node resolution and must be available. A selected Profile remains a valid package configuration;
-Endpoint scoping is not permission to execute an invalid or absent Provider implementation.
+import-only and resource-only packages are valid. The active Distribution protects the exact embedded
+packages it owns. Independently published `@hypit/*` packages and third-party dependencies remain
+ordinary npm dependencies: project packages resolve from the project, and embedded Distribution code
+resolves from the Distribution installation. The loader reports absent dependencies and never installs
+or upgrades them.
## Execution-owned module scopes
`NodePackageLoadOptions.importModule` lets the Host own module lifetime while package selection and
contribution validation stay here. The default uses ordinary process imports. The local execution
Host supplies a `NodeModuleScope` for each Build: selected project packages and their transitive
-JavaScript dependencies receive scope-local module identities. The installed `@hypit/*` Distribution
-remains shared process code. Registries and configured adapter instances are still created per Build.
+JavaScript dependencies receive scope-local module identities. Only public exports and exact packages
+physically embedded by the active Distribution remain shared process code; npm scope alone grants no
+such ownership. Registries and configured adapter instances are still created per Build.
`NodeModuleScope` uses Node resolution/loading hooks and transpiles scope-owned TypeScript/TSX. Its CommonJS
bridge has a scope-owned module cache, Node-style named-export discovery and synchronous evaluation;
@@ -51,13 +56,3 @@ This is trusted execution, not a sandbox. Builtins, native libraries and process
(including `process.cwd()` and `process.env`) remain shared. Existing module bindings do not change
under an active Build; a file or dependency first
read later uses ordinary filesystem semantics. Scoped loading does not make a project tree immutable.
-
-## Dependency installation options
-
-A Distribution package may declare `hypit.dependencyInstallEnv` in its package.json, keyed by its
-ordinary direct external dependency names. Each value is an environment-variable map passed to that
-dependency's explicit npm installation. For example, an owner can disable an SDK's automatic asset
-download and prepare that asset through its ManagedProgram instead. Options do not propagate to
-unrelated installations or the caller's process. Conflicting values from selected packages fail;
-no package wins by discovery order. They are command inputs, not a second dependency inventory,
-readiness record, or new version system. Project packages remain owned by their package manager.
diff --git a/packages/package-loader-node/package.json b/packages/loader/package.json
similarity index 62%
rename from packages/package-loader-node/package.json
rename to packages/loader/package.json
index a1888b39..11bcb92f 100644
--- a/packages/package-loader-node/package.json
+++ b/packages/loader/package.json
@@ -1,16 +1,16 @@
{
- "name": "@hypit/package-loader-node",
+ "name": "@hypit/loader",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts",
- "./module-scope": "./src/module-scope.ts"
+ "./node": "./src/node/index.ts",
+ "./node/module-scope": "./src/node/module-scope.ts"
},
"dependencies": {
- "@hypit/component-kit": "workspace:*",
- "@hypit/host": "workspace:*",
+ "@hypit/facet": "workspace:*",
"@hypit/protocol": "workspace:*",
"cjs-module-lexer": "2.2.1",
"typescript": "5.9.3"
diff --git a/packages/loader/src/contribution.ts b/packages/loader/src/contribution.ts
new file mode 100644
index 00000000..6ef0aaa1
--- /dev/null
+++ b/packages/loader/src/contribution.ts
@@ -0,0 +1,48 @@
+import type {
+ ModuleContribution,
+ PackageContribution,
+} from "./types.js";
+
+function assertPackage(value: PackageContribution): void {
+ if (value.format !== "hypit.package@1") {
+ throw new Error("Package contribution has an unsupported format");
+ }
+ for (const facet of value.facets ?? []) {
+ if (facet.abi.trim().length === 0) throw new Error("Package contribution has an empty Facet ABI");
+ const offers = facet.offers ?? [];
+ if (offers.some((item) => item.trim().length === 0)) {
+ throw new Error(`Package contribution has an empty logical name for Facet ${facet.abi}`);
+ }
+ if (new Set(offers).size !== offers.length) {
+ throw new Error(`Package contribution repeats a logical name for Facet ${facet.abi}`);
+ }
+ }
+}
+
+/** Validate declarations and logical offers without interpreting any executable Facet. */
+export function verifyPackageContributions(packages: readonly PackageContribution[]): void {
+ const manifests = new Map<string, ModuleContribution>();
+ const moduleSpecifiers = new Map<string, string>();
+ const offers = new Set<string>();
+ for (const item of packages) {
+ assertPackage(item);
+ for (const module of item.modules ?? []) {
+ const key = `${module.manifest.name}@${module.manifest.version}`;
+ if (manifests.has(key)) throw new Error(`Packages repeat Module ${key}`);
+ for (const specifier of new Set([key, ...(module.specifiers ?? [])])) {
+ if (specifier.trim().length === 0) throw new Error(`${key} declares an empty Module specifier`);
+ const owner = moduleSpecifiers.get(specifier);
+ if (owner !== undefined) throw new Error(`Module specifier ${specifier} is already bound to ${owner}`);
+ moduleSpecifiers.set(specifier, key);
+ }
+ manifests.set(key, module);
+ }
+ for (const facet of item.facets ?? []) {
+ for (const offered of facet.offers ?? []) {
+ const key = `${facet.abi}\u0000${offered}`;
+ if (offers.has(key)) throw new Error(`Packages repeat ${facet.abi} offer ${offered}`);
+ offers.add(key);
+ }
+ }
+ }
+}
diff --git a/packages/loader/src/index.ts b/packages/loader/src/index.ts
new file mode 100644
index 00000000..c69dfea3
--- /dev/null
+++ b/packages/loader/src/index.ts
@@ -0,0 +1,4 @@
+export {
+ verifyPackageContributions,
+} from "./contribution.js";
+export type * from "./types.js";
diff --git a/packages/package-loader-node/src/distribution-resolution.ts b/packages/loader/src/node/distribution-resolution.ts
similarity index 53%
rename from packages/package-loader-node/src/distribution-resolution.ts
rename to packages/loader/src/node/distribution-resolution.ts
index 50ddccee..ca98f0cb 100644
--- a/packages/package-loader-node/src/distribution-resolution.ts
+++ b/packages/loader/src/node/distribution-resolution.ts
@@ -5,13 +5,10 @@ import { pathToFileURL } from "node:url";
import {
distributionPackageDirectory,
- declaredExternalPackageRoot,
setActiveDistributionPackageRoots,
- setActiveExternalPackageRoots,
} from "./location.js";
let installed: readonly string[] = [];
-let externalInstalled: readonly string[] = [];
function packageAddress(specifier: string): { readonly name: string; readonly subpath: string } | undefined {
const parts = specifier.split("/");
@@ -22,13 +19,6 @@ function packageAddress(specifier: string): { readonly name: string; readonly su
return { name: parts[0]!, subpath: parts.slice(1).join("/") };
}
-function barePackageSpecifier(specifier: string): boolean {
- return !specifier.startsWith(".")
- && !specifier.startsWith("/")
- && !specifier.startsWith("#")
- && !specifier.includes(":");
-}
-
function distributionPackageEntry(root: string, specifier: string): string | undefined {
const address = packageAddress(specifier);
if (address === undefined) return undefined;
@@ -73,9 +63,14 @@ export function resolveDistributionPackageImport(root: string, specifier: string
return undefined;
}
+/** Whether one package import is shared host code of the active Distribution. */
+export function isActiveDistributionHostImport(specifier: string): boolean {
+ return installed.some((root) => resolveDistributionPackageImport(root, specifier) !== undefined);
+}
+
/**
- * Let external project activations import official packages from a read-only Distribution checkout.
- * The @hypit namespace belongs to the active Distribution and cannot be shadowed by project installs.
+ * Let external activations import public APIs and exact embedded packages from a read-only
+ * Distribution. Independently published @hypit packages remain ordinary project dependencies.
*/
export function installDistributionPackageResolution(roots: readonly string[]): void {
const next = roots.map((root) => resolve(root));
@@ -83,71 +78,15 @@ export function installDistributionPackageResolution(roots: readonly string[]):
if (installed.length > 0) throw new Error("Distribution package roots cannot change inside one Host process");
installed = next;
setActiveDistributionPackageRoots(installed);
- const rootUrls = installed.map((root) => pathToFileURL(`${root}/`).href);
registerHooks({
resolve(specifier, context, nextResolve) {
if (specifier.startsWith("@hypit/")) {
- // A contributor checkout may resolve through workspace links. An installed
- // monolithic Distribution resolves from its own packages/services tree.
- // Accept ordinary resolution only when its real target remains inside this
- // Distribution; a project-local package with the same spelling may not shadow it.
- try {
- const found = nextResolve(specifier, context);
- if (found.url.startsWith("file:") && rootUrls.some((root) => found.url.startsWith(root))) {
- return found;
- }
- } catch {
- // Try the explicit Distribution resolvers below.
- }
for (const root of installed) {
const entry = resolveDistributionPackageImport(root, specifier);
if (entry !== undefined) return nextResolve(pathToFileURL(entry).href, context);
}
- throw new Error(`Active Hypit Distribution does not provide ${specifier}`);
}
return nextResolve(specifier, context);
},
});
}
-
-/**
- * Fall back to the machine npm home for upstream packages that are not part of
- * the Distribution or the current project. Project resolution always wins;
- * the @hypit namespace always remains Distribution-owned.
- */
-export function installExternalPackageResolution(roots: readonly string[]): void {
- const next = roots.map((root) => resolve(root));
- if (next.every((root, index) => root === externalInstalled[index])
- && next.length === externalInstalled.length) return;
- if (externalInstalled.length > 0) {
- throw new Error("External package roots cannot change inside one Host process");
- }
- externalInstalled = next;
- setActiveExternalPackageRoots(externalInstalled);
- registerHooks({
- resolve(specifier, context, nextResolve) {
- if (specifier.startsWith("@hypit/") || !barePackageSpecifier(specifier)) {
- return nextResolve(specifier, context);
- }
- try {
- return nextResolve(specifier, context);
- } catch (original) {
- if (context.parentURL === undefined || !context.parentURL.startsWith("file:")) throw original;
- if (installed.length > 0 && !installed.some((root) =>
- context.parentURL!.startsWith(pathToFileURL(`${root}/`).href))) throw original;
- for (const root of externalInstalled) {
- try {
- const name = packageAddress(specifier)?.name;
- const selected = name === undefined ? undefined : declaredExternalPackageRoot(root, context.parentURL, name);
- if (selected === undefined) continue;
- const parentURL = pathToFileURL(join(selected, "__hypit_external__.mjs")).href;
- return nextResolve(specifier, { ...context, parentURL });
- } catch {
- // Try the next machine package root before preserving Node's error.
- }
- }
- throw original;
- }
- },
- });
-}
diff --git a/packages/package-loader-node/src/index.ts b/packages/loader/src/node/index.ts
similarity index 69%
rename from packages/package-loader-node/src/index.ts
rename to packages/loader/src/node/index.ts
index 1270b787..80cac871 100644
--- a/packages/package-loader-node/src/index.ts
+++ b/packages/loader/src/node/index.ts
@@ -1,30 +1,28 @@
-export {
- collectLoadedNodePackageComponents,
- collectNodePackageComponents,
-} from "./contribution.js";
export {
loadNodePackageSelection,
NodePackageSelectionMissingError,
physicalPackageName,
- distributionExternalPackageRequirements,
} from "./loader.js";
export {
installDistributionPackageResolution,
- installExternalPackageResolution,
resolveDistributionPackageImport,
} from "./distribution-resolution.js";
export {
locateNodePackage,
NodePackageNotFoundError,
- distributionPackageDeclaring,
- externalPackageInstallRoot,
resolveNodePackageExecutable,
+ resolveNodePackageModule,
resolveNodePackageResource,
+ resolveNodePackageResourceSpecifier,
resolveNodePackageSource,
} from "./location.js";
export type {
LocatedNodePackage,
+ LocatedNodePackageModule,
LocatedNodePackageSource,
+ LocatedNodePackageResource,
LocateNodePackageOptions,
} from "./location.js";
+export { verifyPackageContributions } from "../contribution.js";
+export type * from "../types.js";
export type * from "./types.js";
diff --git a/packages/package-loader-node/src/loader.ts b/packages/loader/src/node/loader.ts
similarity index 65%
rename from packages/package-loader-node/src/loader.ts
rename to packages/loader/src/node/loader.ts
index bc3eccf4..3646b046 100644
--- a/packages/package-loader-node/src/loader.ts
+++ b/packages/loader/src/node/loader.ts
@@ -1,4 +1,5 @@
import { readFile, realpath, stat } from "node:fs/promises";
+import { realpathSync } from "node:fs";
import { isAbsolute, join, relative, resolve, sep } from "node:path";
import { pathToFileURL } from "node:url";
@@ -7,16 +8,15 @@ import { modulePackageAbi } from "@hypit/protocol";
import type {
LoadedPackage,
LogicalPackageAddress,
- NodePackageLoadOptions,
- NodePackageContribution,
- NodePackageSelectionRequest,
-} from "./types.js";
-import { externalPackageRoots, locateNodePackage } from "./location.js";
+ PackageContribution,
+} from "../types.js";
+import type { NodePackageLoadOptions, NodePackageSelectionRequest } from "./types.js";
+import { distributionPackageDirectory, locateNodePackage } from "./location.js";
type PackageJson = {
readonly name: string;
readonly version?: string;
- readonly hypit?: { readonly activation?: string; readonly dependencyInstallEnv?: Readonly<Record<string, Readonly<Record<string, string>>>> };
+ readonly hypit?: { readonly activation?: string };
readonly dependencies: Readonly<Record<string, string>>;
};
@@ -43,18 +43,8 @@ function parsePackageJson(value: unknown, subject: string): PackageJson {
return {
name: text(item.name, `${subject}.name`),
...(item.version === undefined ? {} : { version: text(item.version, `${subject}.version`) }),
- ...(hypit === undefined ? {} : { hypit: {
- ...(hypit.activation === undefined ? {} : { activation: text(hypit.activation, `${subject}.hypit.activation`) }),
- ...(hypit.dependencyInstallEnv === undefined ? {} : { dependencyInstallEnv: Object.fromEntries(
- Object.entries(object(hypit.dependencyInstallEnv, `${subject}.hypit.dependencyInstallEnv`)).map(([name, raw]) => {
- assert(Object.hasOwn(dependencies, name) && !name.startsWith("@hypit/"), `${subject}: installation environment must name a direct external dependency: ${name}`);
- const env = object(raw, `${subject}.hypit.dependencyInstallEnv.${name}`);
- for (const [key, value] of Object.entries(env)) {
- assert(/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key) && typeof value === "string", `${subject}: invalid installation environment for ${name}`);
- }
- return [name, env as Record<string, string>];
- }),
- ) }),
+ ...(hypit?.activation === undefined ? {} : { hypit: {
+ activation: text(hypit.activation, `${subject}.hypit.activation`),
} }),
dependencies: Object.fromEntries(Object.entries(dependencies).map(([name, version]) => [
name,
@@ -75,9 +65,7 @@ async function resolvePackage(specifier: string, roots: readonly string[]): Prom
const located = locateNodePackage(specifier, {
from: join(resolve(from), "__hypit_package_loader__.mjs"),
workspaceRoots: [from],
- distributionRoots: specifier.startsWith("@hypit/") ? [from] : [],
- externalRoots: [],
- allowExternal: false,
+ distributionRoots: [],
});
return { root: located.root, json: await packageJson(located.root) };
} catch (error) {
@@ -92,9 +80,9 @@ function resolutionRoots(
projectRoots: readonly string[],
distributionRoots: readonly string[],
): readonly string[] {
- // @hypit is the active Distribution's namespace. A project dependency with
- // the same spelling must never silently replace the tool ABI it is using.
- return specifier.startsWith("@hypit/") && distributionRoots.length > 0
+ // Protect only exact packages physically embedded by the active Distribution. Its ordinary npm
+ // dependencies are independently versioned extensions, so an explicit project install wins.
+ return distributionRoots.some((root) => distributionPackageDirectory(root, specifier) !== undefined)
? distributionRoots
: [...projectRoots, ...distributionRoots];
}
@@ -109,37 +97,48 @@ function activationPath(item: ResolvedPackage): string {
return target;
}
-async function importContribution(item: ResolvedPackage, options: NodePackageLoadOptions): Promise<NodePackageContribution> {
+function embeddedByDistribution(
+ item: ResolvedPackage,
+ distributionRoots: readonly string[],
+): boolean {
+ return distributionRoots.some((root) => {
+ const directory = distributionPackageDirectory(root, item.json.name);
+ return directory !== undefined && realpathSync.native(directory) === item.root;
+ });
+}
+
+function embeddedPackageNamed(name: string, distributionRoots: readonly string[]): boolean {
+ return distributionRoots.some((root) => distributionPackageDirectory(root, name) !== undefined);
+}
+
+async function importContribution(
+ item: ResolvedPackage,
+ options: NodePackageLoadOptions,
+ distributionRoots: readonly string[],
+): Promise<PackageContribution> {
const target = activationPath(item);
assert((await stat(target)).isFile(), `${item.json.name} activation is not a file`);
const url = pathToFileURL(target).href;
- const imported = await (options.importModule !== undefined && !item.json.name.startsWith("@hypit/")
+ const imported = await (options.importModule !== undefined && !embeddedByDistribution(item, distributionRoots)
? options.importModule(url) : import(url)) as { readonly default?: unknown };
assert(imported.default !== null && typeof imported.default === "object", `${item.json.name} activation has no default package export`);
- const contribution = imported.default as Partial<NodePackageContribution>;
- assert(contribution.format === "hypit.node-package@1", `${item.json.name} activation has an unsupported package format`);
- return contribution as NodePackageContribution;
-}
-
-function within(root: string, candidate: string): boolean {
- const relation = relative(resolve(root), resolve(candidate));
- return relation === "" || (relation !== ".." && !relation.startsWith(`..${sep}`) && !isAbsolute(relation));
+ const contribution = imported.default as Partial<PackageContribution>;
+ assert(contribution.format === "hypit.package@1", `${item.json.name} activation has an unsupported package format`);
+ return contribution as PackageContribution;
}
async function assertExternalDependencies(
item: ResolvedPackage,
distributionRoots: readonly string[],
- externalRoots: readonly string[],
): Promise<void> {
- const distributionOwned = distributionRoots.some((root) => within(root, item.root));
+ const distributionOwned = embeddedByDistribution(item, distributionRoots);
for (const [name, required] of Object.entries(item.json.dependencies)) {
- if (name.startsWith("@hypit/") || required.startsWith("workspace:")) continue;
+ if (embeddedPackageNamed(name, distributionRoots) || name.startsWith("@hypit/")
+ || required.startsWith("workspace:")) continue;
try {
const resolved = locateNodePackage(name, {
from: join(item.root, "__hypit_package_dependencies__.mjs"),
distributionRoots,
- externalRoots,
- allowExternal: distributionOwned,
});
if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(required)
&& resolved.manifest.version !== required) {
@@ -147,7 +146,7 @@ async function assertExternalDependencies(
}
} catch (error) {
const repair = distributionOwned
- ? `Install it once with: hypit packages install ${name}@${required}`
+ ? "The active Distribution's npm manifest must provide it; reinstall or update that Distribution"
: `Install it with the project package manager that owns ${item.root}`;
throw new Error(`${item.json.name} requires ${name}@${required}. ${repair}`, { cause: error });
}
@@ -158,13 +157,13 @@ function addressKey(value: LogicalPackageAddress): string {
return `${value.abi}\u0000${value.name}`;
}
-function offers(value: NodePackageContribution): readonly LogicalPackageAddress[] {
+function offers(value: PackageContribution): readonly LogicalPackageAddress[] {
return [
...(value.modules ?? []).flatMap((item) => [
`${item.manifest.name}@${item.manifest.version}`,
...(item.specifiers ?? []),
].map((name) => ({ abi: modulePackageAbi, name }))),
- ...(value.hostFacets ?? []).flatMap((facet) => (facet.offers ?? []).map((name) => ({ abi: facet.abi, name }))),
+ ...(value.facets ?? []).flatMap((facet) => (facet.offers ?? []).map((name) => ({ abi: facet.abi, name }))),
];
}
@@ -187,44 +186,6 @@ export class NodePackageSelectionMissingError extends Error {
}
}
-/**
- * Resolve the ordinary upstream npm dependencies of Distribution packages.
- * Internal @hypit dependencies are followed to their manifests. Other selected
- * packages belong to their project's package manager, including their dependencies.
- */
-export async function distributionExternalPackageRequirements(
- specifiers: readonly string[],
- distributionRoot: string,
-): Promise<readonly { readonly name: string; readonly version: string; readonly specifier: string; readonly env?: Readonly<Record<string, string>> }[]> {
- const root = resolve(distributionRoot);
- const queue = [...new Set(specifiers.filter((name) => name.startsWith("@hypit/")))].sort();
- const visited = new Set<string>();
- const external = new Map<string, { readonly name: string; readonly version: string; readonly specifier: string; readonly env?: Readonly<Record<string, string>> }>();
- while (queue.length > 0) {
- const name = queue.shift()!;
- if (visited.has(name)) continue;
- visited.add(name);
- const physical = await resolvePackage(name, [root]);
- for (const [dependency, version] of Object.entries(physical.json.dependencies)) {
- if (dependency.startsWith("@hypit/")) {
- queue.push(dependency);
- continue;
- }
- const specifier = `${dependency}@${version}`;
- const requested = physical.json.hypit?.dependencyInstallEnv?.[dependency];
- const previous = external.get(specifier);
- const env = { ...previous?.env };
- for (const [key, value] of Object.entries(requested ?? {})) {
- assert(env[key] === undefined || env[key] === value, `Conflicting installation environment ${key} for ${specifier}`);
- env[key] = value;
- }
- external.set(specifier, { name: dependency, version, specifier,
- ...(Object.keys(env).length === 0 ? {} : { env }) });
- }
- }
- return [...external.values()].sort((left, right) => left.specifier.localeCompare(right.specifier));
-}
-
/**
* Load the packages explicitly named by Source discovery or a Runtime Profile.
* Node's package manager owns installed versions and bytes; Hypit validates only the
@@ -247,10 +208,9 @@ export async function loadNodePackageSelection(
const distributionRoots = (await Promise.all((options.fallbackRoots ?? []).map(async (candidate) =>
await realpath(candidate))))
.filter((candidate) => candidate !== projectRoot);
- const externalRoots = options.externalRoots ?? externalPackageRoots();
const roots = await Promise.all([...selected].sort().map(async (name) =>
await resolvePackage(name, resolutionRoots(name, projectRoots, distributionRoots))));
- type ActivatedPackage = { readonly physical: ResolvedPackage; readonly contribution: NodePackageContribution };
+ type ActivatedPackage = { readonly physical: ResolvedPackage; readonly contribution: PackageContribution };
const activated = new Map<string, ActivatedPackage>();
const providedModules = new Set<string>();
const requirements: { readonly key: string; readonly from: string }[] = [];
@@ -273,8 +233,8 @@ export async function loadNodePackageSelection(
for (const item of await Promise.all(roots.map(async (physical) => ({
physical,
contribution: await (async () => {
- if (!options.deferExternalDependencies) await assertExternalDependencies(physical, distributionRoots, externalRoots);
- return await importContribution(physical, options);
+ await assertExternalDependencies(physical, distributionRoots);
+ return await importContribution(physical, options, distributionRoots);
})(),
})))) add(item);
@@ -287,8 +247,8 @@ export async function loadNodePackageSelection(
providerPackage,
resolutionRoots(providerPackage, [requirement.from, root], distributionRoots),
);
- if (!options.deferExternalDependencies) await assertExternalDependencies(physical, distributionRoots, externalRoots);
- const provider = { physical, contribution: await importContribution(physical, options) };
+ await assertExternalDependencies(physical, distributionRoots);
+ const provider = { physical, contribution: await importContribution(physical, options, distributionRoots) };
add(provider);
assert(providedModules.has(requirement.key), `${providerPackage} does not provide the required ${requirement.key}`);
}
diff --git a/packages/package-loader-node/src/location.ts b/packages/loader/src/node/location.ts
similarity index 65%
rename from packages/package-loader-node/src/location.ts
rename to packages/loader/src/node/location.ts
index 256493d4..85d22e1f 100644
--- a/packages/package-loader-node/src/location.ts
+++ b/packages/loader/src/node/location.ts
@@ -26,6 +26,20 @@ export type LocatedNodePackageSource = {
readonly source: string;
};
+export type LocatedNodePackageModule = {
+ readonly specifier: string;
+ readonly package: string;
+ readonly root: string;
+ readonly module: string;
+};
+
+export type LocatedNodePackageResource = {
+ readonly specifier: string;
+ readonly package: string;
+ readonly root: string;
+ readonly resource: string;
+};
+
export type LocateNodePackageOptions = {
/** File or module URL whose owning package is requesting the dependency. */
readonly from: string | URL;
@@ -33,14 +47,9 @@ export type LocateNodePackageOptions = {
readonly workspaceRoots?: readonly string[];
/** Defaults to the active Hypit Distribution roots. */
readonly distributionRoots?: readonly string[];
- /** Defaults to the active machine npm package roots. */
- readonly externalRoots?: readonly string[];
- /** Defaults to true only when `from` belongs to the active Distribution. */
- readonly allowExternal?: boolean;
};
let activeDistributionRoots: readonly string[] = [];
-let activeExternalRoots: readonly string[] = [];
function normalizedRoots(roots: readonly string[]): readonly string[] {
return [...new Set(roots.map((root) => resolve(root)))];
@@ -50,19 +59,6 @@ export function setActiveDistributionPackageRoots(roots: readonly string[]): voi
activeDistributionRoots = normalizedRoots(roots);
}
-export function setActiveExternalPackageRoots(roots: readonly string[]): void {
- activeExternalRoots = normalizedRoots(roots);
-}
-
-export function externalPackageRoots(): readonly string[] {
- return activeExternalRoots;
-}
-
-function within(root: string, candidate: string): boolean {
- const relation = relative(resolve(root), resolve(candidate));
- return relation === "" || (relation !== ".." && !relation.startsWith(`..${sep}`) && !isAbsolute(relation));
-}
-
function packageName(value: string): string {
const parts = value.split("/");
const segment = (item: string): boolean => /^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(item)
@@ -74,38 +70,6 @@ function packageName(value: string): string {
return value;
}
-/** One ordinary npm installation per exact upstream release; no shared mutable node_modules. */
-export function externalPackageInstallRoot(root: string, name: string, version: string): string {
- packageName(name);
- if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(version)) {
- throw new Error(`${name}@${version} must select an exact upstream version`);
- }
- return join(resolve(root), ...name.split("/"), version);
-}
-
-/** The importing package's own manifest owns its upstream version selection. */
-export function declaredExternalPackageRoot(root: string, from: string | URL, name: string): string | undefined {
- let cursor = dirname(fromPath(from));
- while (true) {
- const manifest = join(cursor, "package.json");
- if (existsSync(manifest)) {
- const value = JSON.parse(readFileSync(manifest, "utf8")) as {
- dependencies?: Record<string, string>;
- optionalDependencies?: Record<string, string>;
- };
- // An upstream asset a package ships as optional is still selected by one exact version here.
- // `hypit packages install` places it under the machine npm root named by this selection, so
- // reading only the required map makes the documented repair unusable for every optional asset.
- // npm lets optionalDependencies override dependencies with the same name.
- const version = value.optionalDependencies?.[name] ?? value.dependencies?.[name];
- return version === undefined ? undefined : externalPackageInstallRoot(root, name, version);
- }
- const parent = dirname(cursor);
- if (parent === cursor) return undefined;
- cursor = parent;
- }
-}
-
function packageSourceAddress(value: string): { readonly name: string; readonly subpath: string } {
if (value.startsWith(".") || value.startsWith("/") || value.startsWith("#") || value.includes(":")) {
throw new Error(`${value} must be one npm package Source export`);
@@ -190,73 +154,30 @@ export function distributionPackageDirectory(root: string, name: string): string
return undefined;
}
-/**
- * The Distribution package that declares `name@version` as an external dependency, or undefined
- * when none does.
- *
- * Resolution of an external package starts from whoever requires it — the ancestor walk begins at
- * that package's directory, and the machine home is addressed by the version that package
- * declares. A caller holding only `name@version`, as `hypit packages status` does, cannot ask the
- * question the loader answers until it knows the requirer. Finding it here keeps that one answer
- * in one place instead of letting each caller approximate it.
- */
-export function distributionPackageDeclaring(
- root: string,
- name: string,
- version: string,
-): string | undefined {
- for (const directory of distributionPackageDirectories(root)) {
- const manifest = join(directory, "package.json");
- if (!existsSync(manifest)) continue;
- const value = JSON.parse(readFileSync(manifest, "utf8")) as {
- dependencies?: Record<string, string>;
- optionalDependencies?: Record<string, string>;
- };
- // npm lets optionalDependencies override dependencies of the same name, and
- // declaredExternalPackageRoot reads them in that order; match it.
- const declared = value.optionalDependencies?.[name] ?? value.dependencies?.[name];
- if (declared === version) return directory;
- }
- return undefined;
-}
-
-function* distributionPackageDirectories(root: string): Generator<string> {
- const base = resolve(root);
- for (const group of ["packages", "services"]) {
- const directory = join(base, group);
- if (!existsSync(directory)) continue;
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
- if (entry.isDirectory()) yield join(directory, entry.name);
- }
- }
-}
-
function distributionPackage(root: string, name: string): LocatedNodePackage | undefined {
const directory = distributionPackageDirectory(root, name);
return directory === undefined ? nodeModulesPackage(root, name) : readPackage(directory, name);
}
/**
- * Locate package identity without assuming it has a CommonJS/root export. Package ownership stays
- * explicit: @hypit belongs to the Distribution, project dependencies stay project-local, and only
- * Distribution code may fall back to the machine npm home.
+ * Locate package identity without assuming it has a CommonJS/root export. An exact package
+ * physically embedded by the active Distribution is protected from project shadowing. Every other
+ * package, including an independently published @hypit package, follows ordinary project-first
+ * resolution and may use a Distribution dependency only as its installed fallback.
*/
export function locateNodePackage(nameValue: string, options: LocateNodePackageOptions): LocatedNodePackage {
const name = packageName(nameValue);
const from = fromPath(options.from);
const workspaceRoots = normalizedRoots(options.workspaceRoots ?? []);
const distributionRoots = normalizedRoots(options.distributionRoots ?? activeDistributionRoots);
- const externalRoots = normalizedRoots(options.externalRoots ?? activeExternalRoots);
const nearby = ancestorPackage(name, from);
if (name.startsWith("@hypit/")) {
- if (nearby !== undefined && (distributionRoots.length === 0
- || distributionRoots.some((root) => within(root, nearby.root)))) return nearby;
for (const root of distributionRoots) {
- const found = distributionPackage(root, name);
- if (found !== undefined) return found;
+ const directory = distributionPackageDirectory(root, name);
+ const embedded = directory === undefined ? undefined : readPackage(directory, name);
+ if (embedded !== undefined) return embedded;
}
- throw new Error(`Active Hypit Distribution does not provide ${name}`);
}
if (nearby !== undefined) return nearby;
@@ -264,14 +185,9 @@ export function locateNodePackage(nameValue: string, options: LocateNodePackageO
const found = distributionPackage(root, name);
if (found !== undefined) return found;
}
- const allowExternal = options.allowExternal
- ?? distributionRoots.some((root) => within(root, dirname(from)));
- if (allowExternal) {
- for (const root of externalRoots) {
- const installation = declaredExternalPackageRoot(root, from, name);
- const found = installation === undefined ? undefined : nodeModulesPackage(installation, name);
- if (found !== undefined) return found;
- }
+ for (const root of distributionRoots) {
+ const found = distributionPackage(root, name);
+ if (found !== undefined) return found;
}
throw new NodePackageNotFoundError(name);
}
@@ -295,6 +211,15 @@ function packageFile(
return target;
}
+function importExportTarget(value: unknown): string | undefined {
+ if (typeof value === "string") return value;
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const conditions = value as Readonly<Record<string, unknown>>;
+ return typeof conditions.import === "string"
+ ? conditions.import
+ : typeof conditions.default === "string" ? conditions.default : undefined;
+}
+
/** Resolve an explicitly named package asset; package exports are module API, not a file inventory. */
export function resolveNodePackageResource(
name: string,
@@ -304,13 +229,35 @@ export function resolveNodePackageResource(
return packageFile(locateNodePackage(name, options), relativePath, `${name} resource path`);
}
+/** Resolve `package:<name>/<path>` without importing or executing the package. */
+export function resolveNodePackageResourceSpecifier(
+ specifier: string,
+ options: LocateNodePackageOptions,
+): LocatedNodePackageResource {
+ if (!specifier.startsWith("package:")) {
+ throw new Error(`${specifier} must use the package: asset scheme`);
+ }
+ const address = packageSourceAddress(specifier.slice("package:".length));
+ if (address.subpath.length === 0) {
+ throw new Error(`${specifier} must name one package-relative asset`);
+ }
+ const located = locateNodePackage(address.name, options);
+ return {
+ specifier,
+ package: address.name,
+ root: located.root,
+ resource: packageFile(located, address.subpath, `${address.name} resource path`),
+ };
+}
+
/**
* Resolve one explicitly imported Source through the owning package's standard `exports` map.
* This reads package data only; it never imports `hypit.activation` or executes package code.
*/
-export function resolveNodePackageSource(
+function resolveNodePackageExport(
specifier: string,
options: LocateNodePackageOptions,
+ kind: "Source" | "module",
): LocatedNodePackageSource {
const address = packageSourceAddress(specifier);
const located = locateNodePackage(address.name, options);
@@ -327,14 +274,36 @@ export function resolveNodePackageSource(
} else if (manifest.exports !== null && typeof manifest.exports === "object" && !Array.isArray(manifest.exports)) {
declared = (manifest.exports as Readonly<Record<string, unknown>>)[key];
}
- if (typeof declared !== "string") {
- throw new Error(`${address.name} does not export Source ${key}`);
+ const target = importExportTarget(declared);
+ if (target === undefined) {
+ throw new Error(`${address.name} does not export ${kind} ${key}`);
}
return {
specifier,
package: address.name,
root: located.root,
- source: packageFile(located, declared, `${address.name} Source export ${key}`),
+ source: packageFile(located, target, `${address.name} ${kind} export ${key}`),
+ };
+}
+
+export function resolveNodePackageSource(
+ specifier: string,
+ options: LocateNodePackageOptions,
+): LocatedNodePackageSource {
+ return resolveNodePackageExport(specifier, options, "Source");
+}
+
+/** Resolve one explicitly selected executable module through the package's exports map. */
+export function resolveNodePackageModule(
+ specifier: string,
+ options: LocateNodePackageOptions,
+): LocatedNodePackageModule {
+ const located = resolveNodePackageExport(specifier, options, "module");
+ return {
+ specifier: located.specifier,
+ package: located.package,
+ root: located.root,
+ module: located.source,
};
}
diff --git a/packages/package-loader-node/src/module-scope.ts b/packages/loader/src/node/module-scope.ts
similarity index 95%
rename from packages/package-loader-node/src/module-scope.ts
rename to packages/loader/src/node/module-scope.ts
index ca40f4bb..e29eba44 100644
--- a/packages/package-loader-node/src/module-scope.ts
+++ b/packages/loader/src/node/module-scope.ts
@@ -6,6 +6,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { compileFunction } from "node:vm";
import { initSync, parse as parseCommonJs } from "cjs-module-lexer";
import { transpileModule, ModuleKind, ScriptTarget, JsxEmit } from "typescript";
+import { isActiveDistributionHostImport } from "./distribution-resolution.js";
/** A module identity namespace, not a filesystem directory. No files are written here. */
const prefix = pathToFileURL(join(tmpdir(), ".hypit-module-scopes", String(process.pid)) + sep).href;
@@ -85,7 +86,8 @@ function install(): void {
const [scope, request, parentURL] = JSON.parse(Buffer.from(specifier.slice(requestPrefix.length), "base64url").toString("utf8")) as [string, string, string];
scopeFor(scope);
const found = nextResolve(request, { ...context, parentURL });
- return found.url.startsWith("file:") && !request.startsWith("@hypit/") ? { ...found, url: moduleUrl(scope, found.url) } : found;
+ return found.url.startsWith("file:") && !isActiveDistributionHostImport(request)
+ ? { ...found, url: moduleUrl(scope, found.url) } : found;
}
const direct = address(specifier);
const parent = address(context.parentURL);
@@ -95,7 +97,8 @@ function install(): void {
const found = nextResolve(target, parent ? { ...context, parentURL: parent.url } : context);
// The installed Distribution is process code. Its package APIs remain shared; each
// invocation still creates the Build's own registries, adapters and configuration.
- if (scope === undefined || !found.url.startsWith("file:") || specifier.startsWith("@hypit/")) return found;
+ if (scope === undefined || !found.url.startsWith("file:")
+ || isActiveDistributionHostImport(specifier)) return found;
scopeFor(scope);
return { ...found, url: moduleUrl(scope, found.url) };
},
@@ -149,7 +152,7 @@ export class NodeModuleScope {
const require = Object.assign((specifier: string): unknown => {
if (isBuiltin(specifier)) return nativeRequire(specifier);
const resolved = nativeRequire.resolve(specifier);
- if (specifier.startsWith("@hypit/") || resolved.endsWith(".node")) return nativeRequire(specifier);
+ if (isActiveDistributionHostImport(specifier) || resolved.endsWith(".node")) return nativeRequire(specifier);
if (resolved.endsWith(".json")) {
if (this.#commonJs[resolved] === undefined) {
const json = new Module(resolved, mod);
diff --git a/packages/loader/src/node/public.ts b/packages/loader/src/node/public.ts
new file mode 100644
index 00000000..424ef400
--- /dev/null
+++ b/packages/loader/src/node/public.ts
@@ -0,0 +1,29 @@
+/**
+ * Narrow public Node package-location kit for independently distributed adapters.
+ * It resolves bytes only and never executes an installed package.
+ */
+export {
+ loadNodePackageSelection,
+ NodePackageSelectionMissingError,
+ physicalPackageName,
+} from "./loader.js";
+export type {
+ NodePackageLoadOptions,
+ NodePackageSelectionRequest,
+} from "./types.js";
+export {
+ installDistributionPackageResolution,
+ resolveDistributionPackageImport,
+} from "./distribution-resolution.js";
+export {
+ locateNodePackage,
+ NodePackageNotFoundError,
+ resolveNodePackageResource,
+ resolveNodePackageResourceSpecifier,
+ resolveNodePackageSource,
+} from "./location.js";
+export type {
+ LocatedNodePackage,
+ LocatedNodePackageResource,
+ LocateNodePackageOptions,
+} from "./location.js";
diff --git a/packages/loader/src/node/types.ts b/packages/loader/src/node/types.ts
new file mode 100644
index 00000000..6eed73a6
--- /dev/null
+++ b/packages/loader/src/node/types.ts
@@ -0,0 +1,18 @@
+import type { LogicalPackageAddress } from "../types.js";
+
+export type NodePackageSelectionRequest = {
+ /** Physical packages selected by Source discovery or a Runtime Profile. */
+ readonly selected: readonly string[];
+ /** Logical capabilities that the selected packages must provide. */
+ readonly logical?: readonly LogicalPackageAddress[];
+};
+
+export type NodePackageLoadOptions = {
+ /** Host-owned module scope. Omitting this uses Node's ordinary process imports. */
+ readonly importModule?: (url: string) => Promise<unknown>;
+ /**
+ * Additional read-only Distribution roots. Exact embedded packages are protected host code;
+ * ordinary packages installed for the Distribution are fallbacks after project dependencies.
+ */
+ readonly fallbackRoots?: readonly string[];
+};
diff --git a/packages/loader/src/types.ts b/packages/loader/src/types.ts
new file mode 100644
index 00000000..1c33f936
--- /dev/null
+++ b/packages/loader/src/types.ts
@@ -0,0 +1,32 @@
+import type { Facet } from "@hypit/facet";
+import type { ModuleManifest } from "@hypit/protocol";
+
+/** Semantic Module declaration carried by one physical package. */
+export type ModuleContribution = {
+ readonly manifest: ModuleManifest;
+ /** Additional author import spellings resolved to this exact Manifest. */
+ readonly specifiers?: readonly string[];
+};
+
+/** Opaque logical address resolved to an explicitly selected installed package. */
+export type LogicalPackageAddress = {
+ readonly abi: string;
+ readonly name: string;
+};
+
+/**
+ * Executable facets exported by one installed physical package. The Host independently grants
+ * each exact Facet ABI. Runtime facets remain inert unless a Runtime Profile selects the package.
+ */
+export type PackageContribution = {
+ readonly format: "hypit.package@1";
+ readonly modules?: readonly ModuleContribution[];
+ /** Executable contributions remain inert until the owner of their exact ABI selects them. */
+ readonly facets?: readonly Facet[];
+};
+
+/** Physical owner established by the Host; executable code never self-asserts this identity. */
+export type LoadedPackage = {
+ readonly specifier: string;
+ readonly contribution: PackageContribution;
+};
diff --git a/packages/package-loader-node/test/distribution-resolution.test.ts b/packages/loader/test/distribution-resolution.test.ts
similarity index 71%
rename from packages/package-loader-node/test/distribution-resolution.test.ts
rename to packages/loader/test/distribution-resolution.test.ts
index e1e0a3d4..7c9c4fc0 100644
--- a/packages/package-loader-node/test/distribution-resolution.test.ts
+++ b/packages/loader/test/distribution-resolution.test.ts
@@ -6,23 +6,23 @@ import { resolve } from "node:path";
import {
installDistributionPackageResolution,
resolveDistributionPackageImport,
-} from "../src/distribution-resolution.js";
+} from "../src/node/distribution-resolution.js";
test("one Distribution resolves its internal and public package spellings", () => {
assert.equal(
- resolveDistributionPackageImport(process.cwd(), "@hypit/svs"),
- resolve(process.cwd(), "packages/svs/src/index.ts"),
+ resolveDistributionPackageImport(process.cwd(), "@hypit/recipe"),
+ resolve(process.cwd(), "packages/recipe/src/index.ts"),
);
assert.equal(
- resolveDistributionPackageImport(process.cwd(), "@hypit/hypit/svs"),
- resolve(process.cwd(), "packages/svs/src/index.ts"),
+ resolveDistributionPackageImport(process.cwd(), "@hypit/hypit/recipe"),
+ resolve(process.cwd(), "packages/recipe/src/index.ts"),
);
assert.equal(resolveDistributionPackageImport(process.cwd(), "example-package"), undefined);
});
test("an external Author Package imports the active Distribution public API", async () => {
installDistributionPackageResolution([process.cwd()]);
- const author = await import(String("@hypit/hypit/author-kit")) as { readonly sealGraphFragment?: unknown };
+ const author = await import(String("@hypit/hypit/author")) as { readonly sealGraphFragment?: unknown };
const composition = await import(String("@hypit/hypit/composition")) as { readonly sealVisualTrack?: unknown };
assert.equal(typeof author.sealGraphFragment, "function");
assert.equal(typeof composition.sealVisualTrack, "function");
diff --git a/packages/package-loader-node/test/loader.test.ts b/packages/loader/test/loader.test.ts
similarity index 55%
rename from packages/package-loader-node/test/loader.test.ts
rename to packages/loader/test/loader.test.ts
index d89214a3..905912a1 100644
--- a/packages/package-loader-node/test/loader.test.ts
+++ b/packages/loader/test/loader.test.ts
@@ -1,18 +1,16 @@
import assert from "node:assert/strict";
-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import {
- distributionExternalPackageRequirements,
- loadNodePackageSelection,
-} from "@hypit/package-loader-node";
+import { loadNodePackageSelection } from "@hypit/loader/node";
async function installedPackage(
root: string,
name: string,
contribution: string,
+ dependencies: Readonly<Record<string, string>> = {},
): Promise<void> {
const directory = join(root, "node_modules", name);
await mkdir(directory, { recursive: true });
@@ -22,6 +20,7 @@ async function installedPackage(
type: "module",
exports: "./activation.mjs",
hypit: { activation: "./activation.mjs" },
+ dependencies,
}), "utf8");
await writeFile(join(directory, "activation.mjs"), `export default ${contribution};\n`, "utf8");
}
@@ -48,8 +47,8 @@ test("loads an explicitly selected installed package", async () => {
const root = await mkdtemp(join(tmpdir(), "hypit-package-loader-"));
try {
await installedPackage(root, "example-cards", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.cards@1", offers: ["cards"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["cards"] }]
}`);
const loaded = await loadNodePackageSelection(["example-cards"], root);
assert.deepEqual(loaded.map((item) => item.specifier), ["example-cards"]);
@@ -58,64 +57,15 @@ test("loads an explicitly selected installed package", async () => {
}
});
-test("Distribution requirements leave project packages to npm and follow internal dependencies", async () => {
- const root = await mkdtemp(join(tmpdir(), "hypit-distribution-requirements-"));
- try {
- await projectPackage(root, "@hypit/provider-example", `{
- format: "hypit.node-package@1"
- }`, {
- "@hypit/transport-example": "workspace:*",
- "example-sdk": "2.3.4",
- });
- await projectPackage(root, "@hypit/transport-example", `{
- format: "hypit.node-package@1"
- }`, {
- "example-transport": "1.2.3",
- });
- assert.deepEqual(await distributionExternalPackageRequirements(
- ["@hypit/provider-example", "@studio/provider-art", "another-provider"], root,
- ), [
- { name: "example-sdk", version: "2.3.4", specifier: "[email protected]" },
- { name: "example-transport", version: "1.2.3", specifier: "[email protected]" },
- ]);
- assert.deepEqual(await distributionExternalPackageRequirements(["@studio/provider-art"], root), []);
- } finally {
- await rm(root, { recursive: true, force: true });
- }
-});
-
-test("selected packages own dependency install options and conflicting declarations fail", async () => {
- const root = await mkdtemp(join(tmpdir(), "hypit-package-install-options-"));
- try {
- for (const [name, option] of [["first", "yes"], ["second", "no"]]) {
- await projectPackage(root, `@hypit/${name}`, `{ format: "hypit.node-package@1" }`, { "example-sdk": "1.2.3" });
- const path = join(root, "packages", name!, "package.json");
- const manifest = JSON.parse(await readFile(path, "utf8"));
- manifest.hypit.dependencyInstallEnv = { "example-sdk": { SDK_SKIP_DOWNLOAD: option } };
- await writeFile(path, JSON.stringify(manifest));
- }
- assert.deepEqual(await distributionExternalPackageRequirements(["@hypit/first"], root), [{
- name: "example-sdk", version: "1.2.3", specifier: "[email protected]", env: { SDK_SKIP_DOWNLOAD: "yes" },
- }]);
- await assert.rejects(distributionExternalPackageRequirements(["@hypit/first", "@hypit/second"], root), /Conflicting installation environment/u);
- const path = join(root, "packages", "first", "package.json");
- const manifest = JSON.parse(await readFile(path, "utf8"));
- manifest.hypit.dependencyInstallEnv = { "unrelated-package": { SDK_SKIP_DOWNLOAD: "yes" } };
- await writeFile(path, JSON.stringify(manifest));
- await assert.rejects(distributionExternalPackageRequirements(["@hypit/first"], root), /must name a direct external dependency/u);
- } finally { await rm(root, { recursive: true, force: true }); }
-});
-
-test("a Distribution package accepts an exact CLI-only dependency from the machine npm home", async () => {
+test("an embedded Distribution package resolves a dependency installed with its Distribution", async () => {
const project = await mkdtemp(join(tmpdir(), "hypit-cli-only-project-"));
const distribution = await mkdtemp(join(tmpdir(), "hypit-cli-only-distribution-"));
- const machine = await mkdtemp(join(tmpdir(), "hypit-cli-only-machine-"));
try {
await projectPackage(distribution, "@hypit/provider-example", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.provider@1", offers: ["example"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.provider@1", offers: ["example"] }]
}`, { "cli-only": "1.2.3" });
- const cli = join(machine, "cli-only", "1.2.3", "node_modules", "cli-only");
+ const cli = join(distribution, "node_modules", "cli-only");
await mkdir(join(cli, "bin"), { recursive: true });
await writeFile(join(cli, "package.json"), JSON.stringify({
name: "cli-only",
@@ -126,13 +76,11 @@ test("a Distribution package accepts an exact CLI-only dependency from the machi
await writeFile(join(cli, "bin", "cli.mjs"), "export {};\n", "utf8");
const loaded = await loadNodePackageSelection(["@hypit/provider-example"], project, {
fallbackRoots: [distribution],
- externalRoots: [machine],
});
assert.deepEqual(loaded.map((item) => item.specifier), ["@hypit/provider-example"]);
} finally {
await rm(project, { recursive: true, force: true });
await rm(distribution, { recursive: true, force: true });
- await rm(machine, { recursive: true, force: true });
}
});
@@ -140,8 +88,8 @@ test("resolves a logical request to its conventional installed package", async (
const root = await mkdtemp(join(tmpdir(), "hypit-package-selection-"));
try {
await installedPackage(root, "example-provider", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.endpoint@1", offers: ["example-provider"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.endpoint@1", offers: ["example-provider"] }]
}`);
const loaded = await loadNodePackageSelection({
selected: [],
@@ -157,8 +105,8 @@ test("loads an explicit project package without linking it into the Distribution
const root = await mkdtemp(join(tmpdir(), "hypit-project-package-"));
try {
await projectPackage(root, "@acme/cards", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.cards@1", offers: ["cards"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["cards"] }]
}`);
const loaded = await loadNodePackageSelection(["@acme/cards"], root);
assert.deepEqual(loaded.map((item) => item.specifier), ["@acme/cards"]);
@@ -172,8 +120,8 @@ test("falls back to an explicit read-only Distribution root", async () => {
const distribution = await mkdtemp(join(tmpdir(), "hypit-distribution-root-"));
try {
await installedPackage(distribution, "@hypit/cards", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.cards@1", offers: ["cards"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["cards"] }]
}`);
const loaded = await loadNodePackageSelection(["@hypit/cards"], project, {
fallbackRoots: [distribution],
@@ -185,23 +133,70 @@ test("falls back to an explicit read-only Distribution root", async () => {
}
});
-test("the active Distribution owns the reserved @hypit namespace", async () => {
+test("a project-installed official extension wins over the Distribution fallback", async () => {
const project = await mkdtemp(join(tmpdir(), "hypit-project-root-"));
const distribution = await mkdtemp(join(tmpdir(), "hypit-distribution-root-"));
try {
await installedPackage(project, "@hypit/cards", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.cards@1", offers: ["project-shadow"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["project-shadow"] }]
}`);
await installedPackage(distribution, "@hypit/cards", `{
- format: "hypit.node-package@1",
- hostFacets: [{ abi: "example.cards@1", offers: ["distribution"] }]
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["distribution"] }]
}`);
const loaded = await loadNodePackageSelection(["@hypit/cards"], project, {
fallbackRoots: [distribution],
});
assert.deepEqual(loaded.map((item) => item.specifier), ["@hypit/cards"]);
- assert.deepEqual(loaded[0]!.contribution.hostFacets?.[0]?.offers, ["distribution"]);
+ assert.deepEqual(loaded[0]!.contribution.facets?.[0]?.offers, ["project-shadow"]);
+ } finally {
+ await rm(project, { recursive: true, force: true });
+ await rm(distribution, { recursive: true, force: true });
+ }
+});
+
+test("an exact package embedded by the active Distribution cannot be shadowed", async () => {
+ const project = await mkdtemp(join(tmpdir(), "hypit-project-root-"));
+ const distribution = await mkdtemp(join(tmpdir(), "hypit-distribution-root-"));
+ try {
+ await installedPackage(project, "@hypit/cards", `{
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["project-shadow"] }]
+ }`);
+ await projectPackage(distribution, "@hypit/cards", `{
+ format: "hypit.package@1",
+ facets: [{ abi: "example.cards@1", offers: ["embedded-host"] }]
+ }`);
+ const loaded = await loadNodePackageSelection(["@hypit/cards"], project, {
+ fallbackRoots: [distribution],
+ });
+ assert.deepEqual(loaded[0]!.contribution.facets?.[0]?.offers, ["embedded-host"]);
+ } finally {
+ await rm(project, { recursive: true, force: true });
+ await rm(distribution, { recursive: true, force: true });
+ }
+});
+
+test("official extensions use the Build module scope while embedded host packages stay shared", async () => {
+ const project = await mkdtemp(join(tmpdir(), "hypit-project-root-"));
+ const distribution = await mkdtemp(join(tmpdir(), "hypit-distribution-root-"));
+ try {
+ await installedPackage(distribution, "@hypit/cards", `{ format: "hypit.package@1" }`);
+ await projectPackage(distribution, "@hypit/facet-cards", `{ format: "hypit.package@1" }`);
+ const scoped: string[] = [];
+ const importModule = async (url: string): Promise<unknown> => {
+ scoped.push(url);
+ return await import(url);
+ };
+ await loadNodePackageSelection(["@hypit/cards"], project, {
+ fallbackRoots: [distribution], importModule,
+ });
+ assert.equal(scoped.length, 1);
+ await loadNodePackageSelection(["@hypit/facet-cards"], project, {
+ fallbackRoots: [distribution], importModule,
+ });
+ assert.equal(scoped.length, 1);
} finally {
await rm(project, { recursive: true, force: true });
await rm(distribution, { recursive: true, force: true });
diff --git a/packages/package-loader-node/test/location.test.ts b/packages/loader/test/location.test.ts
similarity index 50%
rename from packages/package-loader-node/test/location.test.ts
rename to packages/loader/test/location.test.ts
index d2bc88fe..ca5e581b 100644
--- a/packages/package-loader-node/test/location.test.ts
+++ b/packages/loader/test/location.test.ts
@@ -3,24 +3,23 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { pathToFileURL } from "node:url";
import {
- installExternalPackageResolution,
- externalPackageInstallRoot,
locateNodePackage,
resolveNodePackageExecutable,
+ resolveNodePackageModule,
resolveNodePackageResource,
+ resolveNodePackageResourceSpecifier,
resolveNodePackageSource,
-} from "@hypit/package-loader-node";
+} from "@hypit/loader/node";
-async function machinePackage(
- machine: string,
+async function installedPackage(
+ owner: string,
name: string,
manifest: Readonly<Record<string, unknown>>,
files: Readonly<Record<string, string>>,
): Promise<string> {
- const root = join(machine, "node_modules", ...name.split("/"));
+ const root = join(owner, "node_modules", ...name.split("/"));
await mkdir(root, { recursive: true });
await writeFile(join(root, "package.json"), JSON.stringify({ name, ...manifest }), "utf8");
for (const [path, contents] of Object.entries(files)) {
@@ -33,14 +32,13 @@ async function machinePackage(
test("one physical locator distinguishes CLI packages, resources and project ownership", async () => {
const distribution = await mkdtemp(join(tmpdir(), "hypit-locator-distribution-"));
const project = await mkdtemp(join(tmpdir(), "hypit-locator-project-"));
- const machine = await mkdtemp(join(tmpdir(), "hypit-locator-machine-"));
try {
- const cli = await machinePackage(externalPackageInstallRoot(machine, "cli-only", "1.2.3"), "cli-only", {
+ const cli = await installedPackage(distribution, "cli-only", {
version: "1.2.3",
type: "module",
bin: { tool: "./bin/tool.mjs" },
}, { "bin/tool.mjs": "export {};\n" });
- const resource = await machinePackage(externalPackageInstallRoot(machine, "resource-only", "2.3.4"), "resource-only", {
+ const resource = await installedPackage(distribution, "resource-only", {
version: "2.3.4",
}, { "files/value.txt": "value\n" });
const fromDistribution = join(distribution, "packages", "provider", "activation.mjs");
@@ -51,7 +49,6 @@ test("one physical locator distinguishes CLI packages, resources and project own
const options = {
from: fromDistribution,
distributionRoots: [distribution],
- externalRoots: [machine],
} as const;
const canonicalCli = await realpath(cli);
@@ -60,40 +57,18 @@ test("one physical locator distinguishes CLI packages, resources and project own
assert.equal(resolveNodePackageExecutable("cli-only", "tool", options), join(canonicalCli, "bin", "tool.mjs"));
assert.equal(resolveNodePackageResource("resource-only", "files/value.txt", options), join(canonicalResource, "files", "value.txt"));
assert.throws(() => locateNodePackage("resource-only", {
- ...options,
from: join(project, "package.mjs"),
}), /cannot locate installed package/u);
} finally {
await rm(distribution, { recursive: true, force: true });
await rm(project, { recursive: true, force: true });
- await rm(machine, { recursive: true, force: true });
}
});
-test("machine npm fallback preserves ESM conditions and each importing package's version", async () => {
- const machine = await mkdtemp(join(tmpdir(), "hypit-esm-machine-"));
- try {
- for (const [version, value] of [["1.0.0", 42], ["2.0.0", 84]] as const) {
- await machinePackage(externalPackageInstallRoot(machine, "import-only", version), "import-only", {
- version, type: "module", exports: { ".": { import: "./index.mjs" } },
- }, { "index.mjs": `export const value = ${value};\n` });
- const consumer = join(machine, `consumer-${version}`);
- await mkdir(consumer);
- await writeFile(join(consumer, "package.json"), JSON.stringify({ dependencies: { "import-only": version } }));
- await writeFile(join(consumer, "entry.mjs"), 'export { value } from "import-only";\n');
- }
- installExternalPackageResolution([machine]);
- const first = await import(pathToFileURL(join(machine, "consumer-1.0.0", "entry.mjs")).href);
- const second = await import(pathToFileURL(join(machine, "consumer-2.0.0", "entry.mjs")).href);
- assert.equal(first.value, 42);
- assert.equal(second.value, 84);
- } finally { await rm(machine, { recursive: true, force: true }); }
-});
-
test("package Source resolution reads one public export without activating package code", async () => {
const project = await mkdtemp(join(tmpdir(), "hypit-package-source-project-"));
try {
- const root = await machinePackage(project, "@acme/image-kits", {
+ const root = await installedPackage(project, "@acme/image-kits", {
version: "1.2.3",
type: "module",
exports: {
@@ -103,7 +78,7 @@ test("package Source resolution reads one public export without activating packa
hypit: { activation: "./activation-that-must-not-run.mjs" },
}, {
"activation-that-must-not-run.mjs": "throw new Error('activation ran');\n",
- "kits/phone-ugc-v1.svs": "<?svml using=\"@hypit/svs@1\"?>\n<sheet version=\"1\"/>\n",
+ "kits/phone-ugc-v1.svs": "<?svml using=\"@hypit/recipe@1\"?>\n<sheet version=\"1\"/>\n",
});
const options = { from: join(project, "main.svml") } as const;
assert.deepEqual(resolveNodePackageSource("@acme/image-kits/phone-ugc-v1", options), {
@@ -121,35 +96,56 @@ test("package Source resolution reads one public export without activating packa
}
});
-test("a machine npm fallback resolves an upstream asset the importer declares optionally", async () => {
- const distribution = await mkdtemp(join(tmpdir(), "hypit-optional-distribution-"));
- const machine = await mkdtemp(join(tmpdir(), "hypit-optional-machine-"));
+test("package module resolution follows an explicit conditional import export", async () => {
+ const project = await mkdtemp(join(tmpdir(), "hypit-package-module-project-"));
try {
- const asset = await machinePackage(
- externalPackageInstallRoot(machine, "optional-only", "3.2.1"), "optional-only",
- { version: "3.2.1" }, { "files/asset.css": "/* asset */\n" });
- const importer = join(distribution, "packages", "fonts", "surface.mjs");
- await mkdir(join(importer, ".."), { recursive: true });
- // `hypit packages install <name>@<version>` tells the author to install exactly this asset, so
- // the version selection must read the same declaration the install was addressed to.
- await writeFile(join(importer, "..", "package.json"), JSON.stringify({
- dependencies: { "optional-only": "1.0.0" },
- optionalDependencies: { "optional-only": "3.2.1" },
- }));
- const options = {
- from: importer,
- distributionRoots: [distribution],
- externalRoots: [machine],
- } as const;
+ const root = await installedPackage(project, "@acme/commands", {
+ version: "1.2.3",
+ type: "module",
+ exports: { "./cli": { types: "./cli.d.ts", import: "./cli.mjs" } },
+ }, {
+ "cli.d.ts": "export {};\n",
+ "cli.mjs": "export const cliCommandModules = [];\n",
+ });
+ const canonical = await realpath(root);
+ assert.deepEqual(resolveNodePackageModule("@acme/commands/cli", {
+ from: join(project, "package.json"),
+ }), {
+ specifier: "@acme/commands/cli",
+ package: "@acme/commands",
+ root: canonical,
+ module: join(canonical, "cli.mjs"),
+ });
+ } finally { await rm(project, { recursive: true, force: true }); }
+});
- const canonical = await realpath(asset);
- assert.equal(locateNodePackage("optional-only", options).root, canonical);
- assert.equal(
- resolveNodePackageResource("optional-only", "files/asset.css", options),
- join(canonical, "files", "asset.css"),
+test("package asset locators resolve one contained file without importing package code", async () => {
+ const project = await mkdtemp(join(tmpdir(), "hypit-package-asset-project-"));
+ try {
+ const root = await installedPackage(project, "@acme/brand-fonts", {
+ version: "1.0.0",
+ exports: ".",
+ }, {
+ "files/brand.woff2": "font bytes",
+ "index.js": "throw new Error('package code ran');\n",
+ });
+ const located = resolveNodePackageResourceSpecifier(
+ "package:@acme/brand-fonts/files/brand.woff2",
+ { from: join(project, "main.svml") },
+ );
+ assert.deepEqual(located, {
+ specifier: "package:@acme/brand-fonts/files/brand.woff2",
+ package: "@acme/brand-fonts",
+ root: await realpath(root),
+ resource: join(await realpath(root), "files", "brand.woff2"),
+ });
+ assert.throws(
+ () => resolveNodePackageResourceSpecifier("package:@acme/brand-fonts/../outside", {
+ from: join(project, "main.svml"),
+ }),
+ /invalid package Source export path/u,
);
} finally {
- await rm(distribution, { recursive: true, force: true });
- await rm(machine, { recursive: true, force: true });
+ await rm(project, { recursive: true, force: true });
}
});
diff --git a/packages/package-loader-node/test/module-scope.test.ts b/packages/loader/test/module-scope.test.ts
similarity index 79%
rename from packages/package-loader-node/test/module-scope.test.ts
rename to packages/loader/test/module-scope.test.ts
index 41ad5714..7956a0bc 100644
--- a/packages/package-loader-node/test/module-scope.test.ts
+++ b/packages/loader/test/module-scope.test.ts
@@ -4,10 +4,33 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import test from "node:test";
-import { NodeModuleScope } from "../src/module-scope.js";
+import { NodeModuleScope } from "../src/node/module-scope.js";
+import { installDistributionPackageResolution } from "../src/node/distribution-resolution.js";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
+test("an official project extension keeps Build-local module state", async () => {
+ const root = await realpath(await mkdtemp(join(tmpdir(), "hypit-official-extension-scope-")));
+ installDistributionPackageResolution([process.cwd()]);
+ const a = new NodeModuleScope(); const b = new NodeModuleScope();
+ try {
+ const extension = join(root, "node_modules", "@hypit", "fixture-state");
+ await mkdir(extension, { recursive: true });
+ await writeFile(join(extension, "package.json"), JSON.stringify({
+ name: "@hypit/fixture-state", version: "1.0.0", type: "module", exports: "./index.mjs",
+ }));
+ await writeFile(join(extension, "index.mjs"), "let count=0;export const next=()=>++count;");
+ await writeFile(join(root, "package.json"), '{"type":"module"}');
+ await writeFile(join(root, "entry.mjs"), 'export {next} from "@hypit/fixture-state";');
+ const url = pathToFileURL(join(root, "entry.mjs")).href;
+ const first = await a.import(url) as { next: () => number };
+ const second = await b.import(url) as { next: () => number };
+ assert.equal(first.next(), 1);
+ assert.equal(second.next(), 1);
+ assert.equal(first.next(), 2);
+ } finally { a.close(); b.close(); await rm(root, { recursive: true, force: true }); }
+});
+
test("Build module scopes preserve old bindings and read new ESM and CommonJS dependencies", async () => {
const root = await realpath(await mkdtemp(join(tmpdir(), "hypit-module-scope-")));
const a = new NodeModuleScope(); const b = new NodeModuleScope();
@@ -68,7 +91,7 @@ test("execution entry point keeps mixed module imports, top-level await, and cir
await writeFile(join(root, "circle.cjs"), "exports.ready=true;exports.entry=require('./entry.cjs');");
await writeFile(join(root, "entry.cjs"), "exports.value=require('./esm.mjs').value;exports.circle=require('./circle.cjs');exports.dynamic=()=>import('./async.mjs');");
await writeFile(join(root, "reexport.cjs"), "module.exports=require('./esm.mjs');");
- const loader = new URL("../src/module-scope.ts", import.meta.url).href;
+ const loader = new URL("../src/node/module-scope.ts", import.meta.url).href;
await writeFile(join(root, "check.mjs"), `
import {register} from ${JSON.stringify(import.meta.resolve("tsx/esm/api"))};
register();
diff --git a/packages/markup/README.md b/packages/markup/README.md
index e138f113..63a4c0ec 100644
--- a/packages/markup/README.md
+++ b/packages/markup/README.md
@@ -1,12 +1,13 @@
# `@hypit/markup`
Official XML-like Author Frontend normally used by `.svml` source units. The suffix has no parser
-authority; a mandatory `<?svml using="@hypit/markup@1"?>` Header selects this Frontend. It owns only the `<svml>` envelope,
+authority. Hypit's default self-described text adapter selects this Frontend with
+`<?svml using="@hypit/markup@1"?>`; another Workspace can bind it directly. Markup owns only the `<svml>` envelope,
the leading Import Prologue, namespace binding, generic structured elements and dispatch to
-package-owned Markup Surface Host facets.
+package-owned Markup Surface facets.
The package has no built-in Script, media or video vocabulary. `<script>` is accepted only when an
-imported package contributes that tag through a locked Markup Host facet. The semantic Module
+imported package contributes that tag through a locked Markup Surface facet. The semantic Module
Manifest contains no XML or parser fact. The current registry is for trusted official/in-process use; it is not a security
sandbox for third-party parser code.
@@ -50,7 +51,7 @@ Outputs.
## Frontend implementation
Decoding has two passes. `discoverMarkup` reads only the root and complete leading Import Prologue.
-After Driver supplies one immutable resolved closure, `decodeMarkup` freezes the visible Surface
+After Compiler supplies one immutable resolved closure, `decodeMarkup` freezes the visible Surface
scope and parses the body. A raw Surface receives the source cursor immediately after its opening
tag and must return the cursor after its own close; a structured Surface receives Markup's generic
element tree.
@@ -67,15 +68,15 @@ content-addressed `BlobRef`; Markup never exposes filesystem APIs or a resolved
Compiler Host, not the Surface, owns containment, read-once behavior and byte transfer. A handler
that does not request assets remains unchanged apart from being awaitable.
-Markup validates source ranges, duplicate identities, Host-facet-declared Record types and complete
+Markup validates source ranges, duplicate identities, Facet-declared Record types and complete
Fragment references. It strips diagnostic ranges before sealing one `hypit.author-module@1`, so
source reflow does not change author semantics. It does not expand Fragments while reading the
body. Surface handlers can resolve references through the scoped decoder context described above;
-after all drafts are collected, `@hypit/elaborator` resolves their graph wiring and emits the Core
+after all drafts are collected, `@hypit/author` resolves their graph wiring and emits the Core
Graph. That later graph pass does not make future authored Records available to an earlier decoder.
Direct `decodeMarkup()` calls require every source import to be supplied as an already resolved
-namespace. The reference `compileSourceClosure()` orchestration in `@hypit/elaborator` recursively
-discovers those SourceUnits. Each dependency's own Source Header selects its exact Frontend; Markup
-never chooses a dependency parser. The compiler decodes dependencies first and then calls Markup
+namespace. The reference `compileSourceClosure()` orchestration in `@hypit/compiler` recursively
+discovers those SourceUnits. Each dependency arrives with its own resolved Frontend; Markup never
+chooses a dependency parser. The compiler decodes dependencies first and then calls Markup
with their locked public exports. Markup itself never reads a file or guesses a Frontend.
diff --git a/packages/markup/package.json b/packages/markup/package.json
index ab70f9f8..0ef17aad 100644
--- a/packages/markup/package.json
+++ b/packages/markup/package.json
@@ -5,12 +5,20 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./run": "./src/run/index.ts"
+ },
+ "hypit": {
+ "activation": "./src/run/activation.ts"
},
"dependencies": {
- "@hypit/core": "workspace:*",
- "@hypit/elaborator": "workspace:*",
- "@hypit/host": "workspace:*",
- "@hypit/protocol": "workspace:*"
+ "@hypit/source": "workspace:*",
+ "@hypit/author": "workspace:*",
+ "@hypit/facet": "workspace:*",
+ "@hypit/protocol": "workspace:*",
+ "@hypit/run": "workspace:*"
+ },
+ "devDependencies": {
+ "@hypit/kernel": "workspace:*"
}
}
diff --git a/packages/markup/src/frontend.ts b/packages/markup/src/frontend.ts
index ad0fe667..b453362c 100644
--- a/packages/markup/src/frontend.ts
+++ b/packages/markup/src/frontend.ts
@@ -1,4 +1,5 @@
import { canonicalStringify } from "@hypit/protocol";
+import { decodeSourceText } from "@hypit/source";
import type {
ModuleRef,
ResolvedModule,
@@ -11,7 +12,7 @@ import type {
AuthorSourceIdentity,
AuthorValueRef,
GraphFragment,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import { MarkupFrontendError } from "./error.js";
import {
@@ -203,7 +204,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCo
name,
id,
}))),
- inputs: Object.entries(element.attributes).flatMap(([name, value]): readonly import("@hypit/elaborator").AuthorInputProvenanceDraft[] => {
+ inputs: Object.entries(element.attributes).flatMap(([name, value]): readonly import("@hypit/author").AuthorInputProvenanceDraft[] => {
const range = element.attributeValueRanges?.[name];
if (range === undefined) return [];
if (typeof value === "string") return [{ name, range: { ...range }, kind: "literal" as const }];
@@ -245,6 +246,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCo
if (opening.selfClosing) fail(source, "MARKUP_RAW_SELF_CLOSING", `Raw Surface <${opening.name}> cannot be self-closing.`, cursor);
const rawOutput = await (registered.handler as RawSurfaceHandler)({
sourceName: source.name,
+ ...(source.id === undefined ? {} : { sourceId: source.id }),
source: source.text,
tag: opening.name,
openingStart: opening.start,
@@ -267,6 +269,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCo
structuredElement = parsed.element;
output = await (registered.handler as StructuredSurfaceHandler)({
sourceName: source.name,
+ ...(source.id === undefined ? {} : { sourceId: source.id }),
element: parsed.element,
resolveReference(path) {
const imported = importedReferences.get(path);
@@ -481,7 +484,7 @@ export function createMarkupAuthorFrontend(options: MarkupAuthorFrontendOptions)
return {
id: markupAuthorFrontendId,
discover(source) {
- const discovery = discoverMarkup(source);
+ const discovery = discoverMarkup({ ...source, text: decodeSourceText(source) });
return {
modules: discovery.imports.filter((item) => item.kind === "module").map((item) => item.from),
sources: discovery.imports
@@ -495,8 +498,9 @@ export function createMarkupAuthorFrontend(options: MarkupAuthorFrontendOptions)
};
},
async decode(source, context) {
+ const text = decodeSourceText(source);
const result = await decodeMarkup(
- { name: source.name, text: source.text },
+ { id: source.id, name: source.name, text },
{
closure: context.closure,
registry: options.registry,
diff --git a/packages/markup/src/index.ts b/packages/markup/src/index.ts
index 4b6ccbcc..ceaf324d 100644
--- a/packages/markup/src/index.ts
+++ b/packages/markup/src/index.ts
@@ -10,11 +10,11 @@ export {
export { decodeMarkup, createMarkupAuthorFrontend, markupAuthorFrontendId } from "./frontend.js";
export { MarkupSurfaceRegistry } from "./registry.js";
export {
- createMarkupSurfaceHostFacet,
- installMarkupSurfaceHostFacets,
- markupSurfaceHostFacetAbi,
-} from "./host-facet.js";
-export type { MarkupSurfaceHostFacetOptions } from "./host-facet.js";
+ createMarkupSurfaceFacet,
+ installMarkupSurfaceFacets,
+ markupSurfaceFacetAbi,
+} from "./surface-facet.js";
+export type { MarkupSurfaceFacetOptions } from "./surface-facet.js";
export {
closeDocument,
discoverMarkup,
diff --git a/packages/markup/src/run/activation.ts b/packages/markup/src/run/activation.ts
new file mode 100644
index 00000000..cb6c5db4
--- /dev/null
+++ b/packages/markup/src/run/activation.ts
@@ -0,0 +1,10 @@
+import { createRunFrontendFacet } from "@hypit/run";
+
+import { runMarkupFrontend } from "./index.js";
+
+export const hypitPackage = {
+ format: "hypit.package@1" as const,
+ facets: [createRunFrontendFacet(runMarkupFrontend)],
+};
+
+export default hypitPackage;
diff --git a/packages/run-markup/src/frontend.ts b/packages/markup/src/run/frontend.ts
similarity index 52%
rename from packages/run-markup/src/frontend.ts
rename to packages/markup/src/run/frontend.ts
index 930d0ea6..53f11540 100644
--- a/packages/run-markup/src/frontend.ts
+++ b/packages/markup/src/run/frontend.ts
@@ -1,16 +1,17 @@
import type { RunFrontend } from "@hypit/run";
+import { decodeSourceText } from "@hypit/source";
import { parseRunDocument } from "./syntax.js";
-export const runMarkupFrontendId = "@hypit/run-markup@1";
+export const runMarkupFrontendId = "@hypit/markup/run@1";
export const runMarkupFrontend: RunFrontend = {
id: runMarkupFrontendId,
discover(source) {
- const document = parseRunDocument(source.name, source.text);
+ const document = parseRunDocument(source.name, decodeSourceText(source));
return { author: document.author, imports: document.imports };
},
decode(source) {
- return { document: parseRunDocument(source.name, source.text) };
+ return { document: parseRunDocument(source.name, decodeSourceText(source)) };
},
};
diff --git a/packages/run-markup/src/index.ts b/packages/markup/src/run/index.ts
similarity index 100%
rename from packages/run-markup/src/index.ts
rename to packages/markup/src/run/index.ts
diff --git a/packages/run-markup/src/syntax.ts b/packages/markup/src/run/syntax.ts
similarity index 100%
rename from packages/run-markup/src/syntax.ts
rename to packages/markup/src/run/syntax.ts
diff --git a/packages/markup/src/host-facet.ts b/packages/markup/src/surface-facet.ts
similarity index 77%
rename from packages/markup/src/host-facet.ts
rename to packages/markup/src/surface-facet.ts
index 4727ea69..ba45dc0d 100644
--- a/packages/markup/src/host-facet.ts
+++ b/packages/markup/src/surface-facet.ts
@@ -1,4 +1,4 @@
-import type { HostFacet } from "@hypit/host";
+import type { Facet } from "@hypit/facet";
import type { ModuleRef, TypeRef } from "@hypit/protocol";
import type {
@@ -11,9 +11,9 @@ import type {
StructuredSurfaceDeclaration,
} from "./types.js";
-export const markupSurfaceHostFacetAbi = "hypit.markup-surface-host@1";
+export const markupSurfaceFacetAbi = "hypit.markup-surface@1";
-type RawMarkupSurfaceHostFacetOptions =
+type RawMarkupSurfaceFacetOptions =
| {
readonly module: ModuleRef;
readonly surface: string;
@@ -29,7 +29,7 @@ type RawMarkupSurfaceHostFacetOptions =
readonly handler: RawSurfaceHandler;
};
-type StructuredMarkupSurfaceHostFacetOptions =
+type StructuredMarkupSurfaceFacetOptions =
| {
readonly module: ModuleRef;
readonly surface: string;
@@ -47,9 +47,9 @@ type StructuredMarkupSurfaceHostFacetOptions =
export type { MarkupSurfaceDeclaration } from "./types.js";
-export type MarkupSurfaceHostFacetOptions =
- | RawMarkupSurfaceHostFacetOptions
- | StructuredMarkupSurfaceHostFacetOptions;
+export type MarkupSurfaceFacetOptions =
+ | RawMarkupSurfaceFacetOptions
+ | StructuredMarkupSurfaceFacetOptions;
type MutableMarkupSurfaceRegistry = MarkupSurfaceRegistryLike & {
register(value: RegisteredSurface): void;
@@ -60,9 +60,9 @@ function assert(condition: unknown, message: string): asserts condition {
}
/** Package-owned Markup Surface declaration carried through the syntax-neutral package loader. */
-export function createMarkupSurfaceHostFacet(options: RawMarkupSurfaceHostFacetOptions): HostFacet;
-export function createMarkupSurfaceHostFacet(options: StructuredMarkupSurfaceHostFacetOptions): HostFacet;
-export function createMarkupSurfaceHostFacet(options: MarkupSurfaceHostFacetOptions): HostFacet {
+export function createMarkupSurfaceFacet(options: RawMarkupSurfaceFacetOptions): Facet;
+export function createMarkupSurfaceFacet(options: StructuredMarkupSurfaceFacetOptions): Facet;
+export function createMarkupSurfaceFacet(options: MarkupSurfaceFacetOptions): Facet {
const declaration = "declaration" in options
? {
surface: options.declaration.name,
@@ -98,18 +98,18 @@ export function createMarkupSurfaceHostFacet(options: MarkupSurfaceHostFacetOpti
handler: options.handler as StructuredSurfaceHandler,
};
return {
- abi: markupSurfaceHostFacetAbi,
+ abi: markupSurfaceFacetAbi,
implementation,
};
}
-/** Install only facets owned by the Markup Host ABI; unrelated Host facets remain inert. */
-export function installMarkupSurfaceHostFacets(
- facets: readonly HostFacet[],
+/** Install only facets owned by the Markup Surface ABI; unrelated facets remain inert. */
+export function installMarkupSurfaceFacets(
+ facets: readonly Facet[],
registry: MutableMarkupSurfaceRegistry,
): void {
for (const facet of facets) {
- if (facet.abi !== markupSurfaceHostFacetAbi) continue;
+ if (facet.abi !== markupSurfaceFacetAbi) continue;
registry.register(facet.implementation as RegisteredSurface);
}
}
diff --git a/packages/markup/src/types.ts b/packages/markup/src/types.ts
index 5f398bad..6a1fdb38 100644
--- a/packages/markup/src/types.ts
+++ b/packages/markup/src/types.ts
@@ -19,10 +19,11 @@ import type {
Awaitable,
GraphFragment,
ResolvedAuthorSourceImport,
-} from "@hypit/elaborator";
+} from "@hypit/author";
/** Decoder-local Markup text; Source identity and closure ownership stay outside the parser. */
export type MarkupSource = {
+ readonly id?: string;
readonly name: string;
readonly text: string;
};
@@ -92,12 +93,14 @@ export type SurfaceDecodeOutput = {
export type RawSurfaceInput = {
readonly sourceName: string;
+ /** Canonical identity of the declaring Source when the Host provides one. */
+ readonly sourceId?: string;
readonly source: string;
readonly tag: string;
readonly openingStart: number;
readonly contentStart: number;
readonly attributes: Readonly<Record<string, MarkupAttributeValue>>;
- readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/elaborator").ResolvedAuthorSourceAsset>;
+ readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/author").ResolvedAuthorSourceAsset>;
};
export type RawSurfaceOutput = SurfaceDecodeOutput & {
@@ -106,6 +109,8 @@ export type RawSurfaceOutput = SurfaceDecodeOutput & {
export type StructuredSurfaceInput = {
readonly sourceName: string;
+ /** Canonical identity of the declaring Source when the Host provides one. */
+ readonly sourceId?: string;
readonly element: StructuredElement;
/**
* Resolve an explicitly written author reference. Imported record values are
@@ -113,7 +118,7 @@ export type StructuredSurfaceInput = {
* A component output has a ref and Type but no compile-time Record value.
*/
readonly resolveReference: (path: string) => SurfaceResolvedReference | undefined;
- readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/elaborator").ResolvedAuthorSourceAsset>;
+ readonly resolveAsset: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/author").ResolvedAuthorSourceAsset>;
};
export type SurfaceResolvedReference = {
@@ -221,7 +226,7 @@ export type MarkupDecodeContext = {
readonly registry: MarkupSurfaceRegistryLike;
readonly resolveModule: (request: MarkupImportRequest) => ModuleRef;
readonly sourceImports?: readonly ResolvedAuthorSourceImport[];
- readonly resolveAsset?: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/elaborator").ResolvedAuthorSourceAsset>;
+ readonly resolveAsset?: (request: AuthorSourceAssetRequest) => Awaitable<import("@hypit/author").ResolvedAuthorSourceAsset>;
};
export type MarkupDecodeResult = {
diff --git a/packages/markup/test/author-integration.test.ts b/packages/markup/test/author-integration.test.ts
index 009ec489..f821c95e 100644
--- a/packages/markup/test/author-integration.test.ts
+++ b/packages/markup/test/author-integration.test.ts
@@ -6,13 +6,13 @@ import {
link,
sealBuildRequest,
start,
-} from "@hypit/core";
+} from "@hypit/kernel";
import {
AuthorGraphError,
elaborateAuthorGraph,
sealGraphFragment,
-} from "@hypit/elaborator";
-import type { GraphFragment } from "@hypit/elaborator";
+} from "@hypit/author";
+import type { GraphFragment } from "@hypit/author";
import type {
ModuleManifest,
ProducerRef,
diff --git a/packages/run-markup/test/run.test.ts b/packages/markup/test/run/run.test.ts
similarity index 91%
rename from packages/run-markup/test/run.test.ts
rename to packages/markup/test/run/run.test.ts
index d6a39551..b8f2c29d 100644
--- a/packages/run-markup/test/run.test.ts
+++ b/packages/markup/test/run/run.test.ts
@@ -9,19 +9,20 @@ import {
planBuild,
sealCompiledGraph,
sealRecord,
-} from "@hypit/core";
-import { sealGraphFragment } from "@hypit/elaborator";
-import type { CompiledSourceClosure } from "@hypit/elaborator";
+} from "@hypit/kernel";
+import { sealGraphFragment } from "@hypit/author";
+import type { CompiledSourceClosure } from "@hypit/author";
import type { BuildState, ModuleManifest, ProducerRef, TypeRef } from "@hypit/protocol";
import {
compileRunSource,
- createRunFragmentHostFacet,
- installRunFragmentHostFacets,
+ createRunFragmentFacet,
+ installRunFragmentFacets,
resolveRunDocument,
RunFragmentRegistry,
RunFrontendRegistry,
} from "@hypit/run";
-import { parseRunDocument, runMarkupFrontend } from "@hypit/run-markup";
+import { parseRunDocument, runMarkupFrontend } from "@hypit/markup/run";
+import { resolveSelfDescribedTextSource } from "@hypit/source/text";
const moduleRef = { name: "example.run", version: "1" } as const;
const promptType = { module: moduleRef, name: "Prompt" } satisfies TypeRef;
@@ -110,11 +111,11 @@ function realize(compilation: CompiledSourceClosure, run: Awaited<ReturnType<typ
async function compileDocument(body: string) {
const frontends = new RunFrontendRegistry();
frontends.register(runMarkupFrontend);
- return await compileRunSource({
+ return await compileRunSource(resolveSelfDescribedTextSource({
id: "/project/build.svrun",
name: "build.svrun",
- text: `<?svml using="@hypit/run-markup@1"?>\n${body}`,
- }, frontends);
+ text: `<?svml using="@hypit/markup/run@1"?>\n${body}`,
+ }), frontends);
}
test("Run Markup compilation consumes decode output without repeating package discovery", async () => {
@@ -125,19 +126,19 @@ test("Run Markup compilation consumes decode output without repeating package di
throw new Error("package discovery must not run during compilation");
},
});
- const compiled = await compileRunSource({
+ const compiled = await compileRunSource(resolveSelfDescribedTextSource({
id: "/project/build.svrun",
name: "build.svrun",
- text: `<?svml using="@hypit/run-markup@1"?>\n<svrun version="1"><author source="./main.svml"/><target output="left"/></svrun>`,
- }, frontends);
+ text: `<?svml using="@hypit/markup/run@1"?>\n<svrun version="1"><author source="./main.svml"/><target output="left"/></svrun>`,
+ }), frontends);
assert.equal(compiled.document.targets[0]?.output, "left");
});
test("Run Fragments enter the Host only through the selected Run facet ABI", () => {
const fragment = previewFragment();
- const facet = createRunFragmentHostFacet({ name: "@example/run-preview", fragments: { shared: fragment } });
+ const facet = createRunFragmentFacet({ name: "@example/run-preview", fragments: { shared: fragment } });
const registry = new RunFragmentRegistry();
- installRunFragmentHostFacets([facet], registry);
+ installRunFragmentFacets([facet], registry);
assert.equal(registry.resolve("@example/run-preview", "shared")?.id, fragment.id);
});
@@ -226,11 +227,11 @@ test("a Provided Value is an ordinary zero-input Candidate", async () => {
assert.equal(state.records.some((record) => record.id === "provided:run:fixed"), true);
});
-test("a source file is an ordinary BlobArtifact Candidate", async () => {
+test("a source file is an ordinary Blob Candidate", async () => {
const compiled = await compileDocument(`<svrun version="1">
<author source="./main.svml"/>
<target output="left"/>
- <file id="approved" type="@hypit/artifact@1#BlobArtifact" from="./approved.mp4" media-type="video/mp4"/>
+ <file id="approved" type="@hypit/blob@1#Blob" from="./approved.mp4" media-type="video/mp4"/>
<satisfy output="left" candidate="approved"/>
</svrun>`);
const compilation = fixture();
@@ -239,8 +240,8 @@ test("a source file is an ordinary BlobArtifact Candidate", async () => {
fragments: new RunFragmentRegistry(),
});
assert.equal(run.graph.candidates.length, 1);
- assert.equal(run.graph.candidates[0]?.type.module.name, "@hypit/artifact");
- assert.equal(run.graph.candidates[0]?.type.name, "BlobArtifact");
+ assert.equal(run.graph.candidates[0]?.type.module.name, "@hypit/blob");
+ assert.equal(run.graph.candidates[0]?.type.name, "Blob");
assert.deepEqual(run.candidateSources[run.graph.candidates[0]!.id], {
kind: "file",
from: "./approved.mp4",
diff --git a/packages/package-loader-node/src/contribution.ts b/packages/package-loader-node/src/contribution.ts
deleted file mode 100644
index 055d932f..00000000
--- a/packages/package-loader-node/src/contribution.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import type { ComponentPackage } from "@hypit/component-kit";
-
-import type {
- LoadedComponentPackage,
- LoadedPackage,
- NodeModuleContribution,
- NodePackageContribution,
-} from "./types.js";
-
-function assertPackage(value: NodePackageContribution): void {
- if (value.format !== "hypit.node-package@1") {
- throw new Error("Node package contribution has an unsupported format");
- }
- for (const facet of value.hostFacets ?? []) {
- if (facet.abi.trim().length === 0) throw new Error("Node package contribution has an empty Host facet ABI");
- const offers = facet.offers ?? [];
- if (offers.some((item) => item.trim().length === 0)) {
- throw new Error(`Node package contribution has an empty logical name for Host facet ${facet.abi}`);
- }
- if (new Set(offers).size !== offers.length) {
- throw new Error(`Node package contribution repeats a logical name for Host facet ${facet.abi}`);
- }
- }
-}
-
-function facetKey(
- ref: { readonly module: { readonly name: string; readonly version: string }; readonly name: string },
-): string {
- return `${ref.module.name}@${ref.module.version}#${ref.name}`;
-}
-
-/** Collect declarative modules and executable component implementations from loaded packages. */
-export function collectNodePackageComponents(
- packages: readonly NodePackageContribution[],
-): readonly ComponentPackage[] {
- const manifests = new Map<string, NodeModuleContribution>();
- const moduleSpecifiers = new Map<string, string>();
- const components: ComponentPackage[] = [];
- const producers = new Set<string>();
- const validators = new Set<string>();
- const declarations = new Set<string>();
- for (const item of packages) {
- assertPackage(item);
- for (const module of item.modules ?? []) {
- const key = `${module.manifest.name}@${module.manifest.version}`;
- if (manifests.has(key)) throw new Error(`Node packages repeat Module ${key}`);
- for (const specifier of new Set([key, ...(module.specifiers ?? [])])) {
- if (specifier.trim().length === 0) throw new Error(`${key} declares an empty Module specifier`);
- const owner = moduleSpecifiers.get(specifier);
- if (owner !== undefined) throw new Error(`Module specifier ${specifier} is already bound to ${owner}`);
- moduleSpecifiers.set(specifier, key);
- }
- manifests.set(key, module);
- for (const producer of module.manifest.producers) {
- declarations.add(`${key}#producer:${producer.name}`);
- }
- for (const type of module.manifest.types) {
- declarations.add(`${key}#type:${type.name}`);
- }
- }
- for (const component of item.components ?? []) {
- components.push(component);
- for (const producer of component.producers ?? []) {
- const key = facetKey(producer.producer);
- if (producers.has(key)) throw new Error(`Node packages repeat Producer facet ${key}`);
- producers.add(key);
- }
- for (const validator of component.validators ?? []) {
- const key = facetKey(validator.type);
- if (validators.has(key)) throw new Error(`Node packages repeat Type Validator facet ${key}`);
- validators.add(key);
- }
- }
- }
- for (const component of components) {
- for (const facet of component.producers ?? []) {
- const key = `${facet.producer.module.name}@${facet.producer.module.version}#producer:${facet.producer.name}`;
- if (!declarations.has(key)) throw new Error(`Module ${facet.producer.module.name} implements undeclared Producer ${facetKey(facet.producer)}`);
- }
- for (const facet of component.validators ?? []) {
- const key = `${facet.type.module.name}@${facet.type.module.version}#type:${facet.type.name}`;
- if (!declarations.has(key)) throw new Error(`Module ${facet.type.module.name} validates undeclared Type ${facetKey(facet.type)}`);
- }
- }
- return components;
-}
-
-/** Validate a loaded selection while preserving the physical owner of every Component package. */
-export function collectLoadedNodePackageComponents(
- packages: readonly LoadedPackage[],
-): readonly LoadedComponentPackage[] {
- collectNodePackageComponents(packages.map((item) => item.contribution));
- return packages.map((item) => ({
- specifier: item.specifier,
- components: item.contribution.components ?? [],
- }));
-}
diff --git a/packages/package-loader-node/src/types.ts b/packages/package-loader-node/src/types.ts
deleted file mode 100644
index c46ef42a..00000000
--- a/packages/package-loader-node/src/types.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import type { ComponentPackage } from "@hypit/component-kit";
-import type { HostFacet } from "@hypit/host";
-import type { ModuleManifest } from "@hypit/protocol";
-
-/** Semantic Module declaration carried by one physical Node package. */
-export type NodeModuleContribution = {
- readonly manifest: ModuleManifest;
- /** Additional author import spellings resolved to this exact Manifest. */
- readonly specifiers?: readonly string[];
-};
-
-/** Opaque logical address resolved to an explicitly selected installed package. */
-export type LogicalPackageAddress = {
- readonly abi: string;
- readonly name: string;
-};
-
-/**
- * Executable facets exported by one installed physical package. The Host independently grants
- * each exact Host ABI. Runtime facets remain inert unless a Runtime Profile selects the package.
- */
-export type NodePackageContribution = {
- readonly format: "hypit.node-package@1";
- readonly modules?: readonly NodeModuleContribution[];
- /** Syntax- or Host-specific executable facets, inert until their exact Host ABI selects them. */
- readonly hostFacets?: readonly HostFacet[];
- readonly components?: readonly ComponentPackage[];
-};
-
-/** Physical owner established by the Host; executable code never self-asserts this identity. */
-export type LoadedPackage = {
- readonly specifier: string;
- readonly contribution: NodePackageContribution;
-};
-
-/** Runtime Component implementations grouped by their physical package owner. */
-export type LoadedComponentPackage = {
- readonly specifier: string;
- readonly components: readonly ComponentPackage[];
-};
-
-export type NodePackageSelectionRequest = {
- /** Physical packages selected by Source discovery or a Runtime Profile. */
- readonly selected: readonly string[];
- /** Logical capabilities that the selected packages must provide. */
- readonly logical?: readonly LogicalPackageAddress[];
-};
-
-export type NodePackageLoadOptions = {
- /** Host-owned module scope. Omitting this uses Node's ordinary process imports. */
- readonly importModule?: (url: string) => Promise<unknown>;
- /**
- * Additional read-only Distribution roots. They are fallbacks for project-scoped packages;
- * the reserved @hypit namespace resolves only from these roots when they are present.
- */
- readonly fallbackRoots?: readonly string[];
- /**
- * Machine npm homes used only by Distribution-owned packages for their ordinary upstream
- * dependencies. Defaults to the roots installed by the Hypit launcher.
- */
- readonly externalRoots?: readonly string[];
- /** Runtime declarations can be read before their optional execution tools are prepared. */
- readonly deferExternalDependencies?: boolean;
-};
diff --git a/packages/component-kit/README.md b/packages/producer/README.md
similarity index 62%
rename from packages/component-kit/README.md
rename to packages/producer/README.md
index b135fec7..fc8c679c 100644
--- a/packages/component-kit/README.md
+++ b/packages/producer/README.md
@@ -1,14 +1,15 @@
-# `@hypit/component-kit`
+# `@hypit/producer`
-The minimal host-neutral SDK for trusted deterministic compute components. A package exports
-enumerable Producer and Type-owner Validator facets. Both identities are data: an exact nominal
-reference plus handler. Hosts enumerate them without running an opaque `install()` callback.
+The minimal host-neutral SDK for trusted deterministic Producers. A package exports enumerable
+Producer facets; Type-owner validation is independently owned by `@hypit/admission`. Both identities
+are data: an exact nominal reference plus handler. Hosts enumerate them without running an opaque
+`install()` callback.
Producer handlers receive only the
Core command, Producer identity and immutable typed inputs.
They receive no ResourceStore, credentials, network client, queue or Runtime infrastructure. Work that
needs those authorities must emit an explicit Need and be implemented by a separately selected
-Endpoint package. `@hypit/driver-node` implements the structural registrar but is not part of this
+Provider package's Endpoint instance. `@hypit/executor` implements the structural registrar but is not part of this
SDK.
This is dependency inversion, not a sandbox. Until components run in an isolated Worker, selected
@@ -18,24 +19,28 @@ JavaScript packages remain trusted code and may still possess ambient authority
A component normally lives in the video's `packages/` and is installed through that project's
ordinary package manager. Use the owner's scope, such as `@studio/score-strip`; the active
-Distribution reserves `@hypit/*`. A Source imports the package's logical Module ABI, for example
+Hypit project publishes under `@hypit/*`. A Source imports the package's logical Module ABI, for example
`<import as="score" from="@studio/score-strip@1"/>`. That `1` is not its npm release version.
-External Author Packages use the released Distribution's public subpaths. The small framework-facing
-surface is `@hypit/hypit/author-kit`; domain values continue to come from their own owners:
+External Author Packages use the released Distribution's narrow public subpaths. There is no central
+Author Kit; import only the owner of each responsibility:
| Owner | Interface |
| --- | --- |
-| `@hypit/hypit/author-kit` | Module declarations, deterministic handlers, sealed Fragments and Markup Surface handlers |
-| `@hypit/hypit/temporal-markup` | author-time semantic Window/Instant projection helpers |
-| `@hypit/hypit/composition`, `@hypit/hypit/visual-ir` | peer Track values and renderer-independent visual representation |
-| `@hypit/hypit/studio-adapter` (optional, in Companion code) | editor entity projection, Inspector bindings and executed temporal lineage |
+| `@hypit/hypit/protocol` | Module manifests and serializable graph identities |
+| `@hypit/hypit/producer` | deterministic Producer handlers and Producer package facets |
+| `@hypit/hypit/admission` | package-owned Type validators and Admission package facets |
+| `@hypit/hypit/author` | sealed Author Graph Fragments |
+| `@hypit/hypit/markup` | Markup Surface declarations and handlers |
+| `@hypit/hypit/temporal/markup` | author-time semantic Window/Instant projection helpers |
+| `@hypit/hypit/composition`, `@hypit/hypit/composition` | peer Track values and renderer-independent visual representation |
+| `@hypit/studio-companion` (optional, in Companion code) | editor entity projection, Inspector bindings and executed temporal lineage |
The Author Package keeps one development dependency on `@hypit/hypit`, compiles its activation to
JavaScript, and publishes only its own files. The active Distribution supplies these subpaths at
execution, so a component does not carry a second Core or choose its own framework version. This
-package remains the internal deterministic-handler owner; `@hypit/hypit/author-kit` is the deliberately
-small public composition boundary, not a facade for every video domain.
+package remains the deterministic-handler owner; the public subpaths do not create a second package
+format or a facade that claims to own every kind of author extension.
An ESM package names its activation entry in `package.json`, for example
`"hypit": { "activation": "./dist/activation.js" }`. The built files, preview assets and package
@@ -43,27 +48,32 @@ dependencies must actually be included. A TypeScript entry can be used when the
Host supports it; a compiled JavaScript entry avoids depending on a TypeScript loader.
The activation module connects the implementation pieces; this is a wiring excerpt, assuming the
-local Manifest, ComponentPackage and Surface declarations/handlers already exist:
+local Manifest, Producer/Admission packages and Surface declarations/handlers already exist:
```ts
-import { createMarkupSurfaceHostFacet } from "@hypit/hypit/author-kit";
+import { createAdmissionPackageFacet } from "@hypit/hypit/admission";
+import { createMarkupSurfaceFacet } from "@hypit/hypit/markup";
+import { createProducerPackageFacet } from "@hypit/hypit/producer";
import { manifest, moduleRef, surfaces } from "./manifest.js";
import { component } from "./component.js";
import { decodeTrack } from "./surface.js";
export const hypitPackage = {
- format: "hypit.node-package@1" as const,
+ format: "hypit.package@1" as const,
modules: [{ manifest }],
- components: [component],
- hostFacets: surfaces.map((declaration) => createMarkupSurfaceHostFacet({
- module: moduleRef, declaration, handler: decodeTrack,
- })),
+ facets: [
+ createProducerPackageFacet(component),
+ createAdmissionPackageFacet(component),
+ ...surfaces.map((declaration) => createMarkupSurfaceFacet({
+ module: moduleRef, declaration, handler: decodeTrack,
+ })),
+ ],
};
export default hypitPackage;
```
If several Surfaces have different handlers, bind each declaration to its actual handler instead of
-mapping them all to `decodeTrack`. Surface metadata is registered through the Markup Host facet;
+mapping them all to `decodeTrack`. Surface metadata is registered through the Markup Surface facet;
it does not make Markup syntax part of the semantic Module Manifest.
Structured handlers return `records`, `components`, `fragments` and optionally explicit `exports`.
@@ -87,11 +97,11 @@ Runtime.
A component can render through the ordinary Track protocol without custom editor behavior. When it
needs meaningful timeline entities or Inspector fields, put a Companion in a separate file and
-merge `createStudioTrackCompanionHostFacet(companions)` into the same activation's `hostFacets`.
+merge `createStudioTrackCompanionFacet(companions)` into the same activation's `facets`.
Retain the existing Module, Producer and Surface contributions. The selected project's package
supplies the extension; do not edit Studio's registry or add editor metadata to the domain Manifest.
-The [Studio Adapter README](../studio-adapter/README.md) owns the working declaration and activation
+The [Studio Companion README](../studio-companion/README.md) owns the working declaration and activation
example. Expose any required deterministic schedule/program values through actual Surface outputs,
and retain the real temporal input edges. The Companion describes those facts and writable Source
parameters; it neither renders the video nor performs Source filesystem writes.
diff --git a/packages/component-kit/package.json b/packages/producer/package.json
similarity index 77%
rename from packages/component-kit/package.json
rename to packages/producer/package.json
index d692c92d..f0cbc7c4 100644
--- a/packages/component-kit/package.json
+++ b/packages/producer/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/component-kit",
+ "name": "@hypit/producer",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
@@ -8,6 +8,7 @@
".": "./src/index.ts"
},
"dependencies": {
+ "@hypit/facet": "workspace:*",
"@hypit/protocol": "workspace:*"
}
}
diff --git a/packages/component-kit/src/index.ts b/packages/producer/src/index.ts
similarity index 76%
rename from packages/component-kit/src/index.ts
rename to packages/producer/src/index.ts
index 0a123d41..19350c6e 100644
--- a/packages/component-kit/src/index.ts
+++ b/packages/producer/src/index.ts
@@ -8,26 +8,10 @@ import type {
TypeRef,
TypedRecord,
} from "@hypit/protocol";
+import type { Facet } from "@hypit/facet";
export type Awaitable<T> = T | Promise<T>;
-export type TypeValidatorContext = {
- readonly type: TypeRef;
- readonly value: StoredValue;
-};
-
-export type TypeValidatorHandler = (
- context: TypeValidatorContext,
-) => void | Promise<void>;
-
-/** Minimal structural port implemented by a validation Host. */
-export interface TypeValidatorRegistrar {
- register(
- type: TypeRef,
- handler: TypeValidatorHandler,
- ): void;
-}
-
export type ProducerHandlerResult = {
readonly outputs: Readonly<Record<string, StoredValue>>;
readonly needs: Readonly<Record<string, CanonicalValue>>;
@@ -131,25 +115,37 @@ export function registerProducerFacets(
}
}
-/** Package-owned semantic validator. */
-export type TypeValidatorFacet = {
- readonly type: TypeRef;
- readonly handler: TypeValidatorHandler;
-};
-
-export function registerTypeValidatorFacets(
- registry: TypeValidatorRegistrar,
- facets: readonly TypeValidatorFacet[],
-): void {
- for (const facet of facets) {
- registry.register(facet.type, facet.handler);
- }
-}
-
-/** Trusted deterministic implementation package; it selects no Provider or Runtime infrastructure. */
-export type ComponentPackage = {
+/** Producer-owned deterministic implementations; it selects no Provider or Runtime infrastructure. */
+export type ProducerPackage = {
readonly producers?: readonly ProducerFacet[];
- readonly validators?: readonly TypeValidatorFacet[];
/** Planning knowledge owned by the package that declares the external request. */
readonly plannedNeeds?: readonly PlannedNeedFacet[];
};
+
+export const producerPackageFacetAbi = "hypit.producer-package@1";
+
+export type ProducerPackageFacet = Facet & {
+ readonly abi: typeof producerPackageFacetAbi;
+ readonly implementation: ProducerPackage;
+};
+
+/** Convert one package's Producer-owned implementations into an opaque package Facet. */
+export function createProducerPackageFacet(value: unknown): ProducerPackageFacet {
+ const item = value !== null && typeof value === "object"
+ ? value as ProducerPackage
+ : {};
+ return {
+ abi: producerPackageFacetAbi,
+ implementation: {
+ ...(item.producers === undefined ? {} : { producers: item.producers }),
+ ...(item.plannedNeeds === undefined ? {} : { plannedNeeds: item.plannedNeeds }),
+ },
+ };
+}
+
+/** Select only Producer facets; package loading itself never interprets their implementation. */
+export function producerPackagesFromFacets(facets: readonly Facet[]): readonly ProducerPackage[] {
+ return facets.flatMap((facet) => facet.abi === producerPackageFacetAbi
+ ? [(facet as ProducerPackageFacet).implementation]
+ : []);
+}
diff --git a/packages/project-context-node/src/index.ts b/packages/project-context-node/src/index.ts
deleted file mode 100644
index d08019e6..00000000
--- a/packages/project-context-node/src/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { resolveProjectRoot, resolvePackageRoot } from "./project-context.js";
-export { findRuntimeProfile, selectRuntimeProfile, clearRuntimeProfile } from "./runtime-selection.js";
-export type { RuntimeProfileSelection } from "./runtime-selection.js";
diff --git a/packages/project-context-node/src/project-context.ts b/packages/project-context-node/src/project-context.ts
deleted file mode 100644
index 9d436760..00000000
--- a/packages/project-context-node/src/project-context.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { realpath, stat } from "node:fs/promises";
-import { dirname, resolve } from "node:path";
-
-async function nearestProjectPackageRoot(start: string): Promise<string | undefined> {
- let directory = resolve(start);
- while (true) {
- const candidate = resolve(directory, "package.json");
- try {
- if ((await stat(candidate)).isFile()) return directory;
- } catch (error) {
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
- }
- const parent = dirname(directory);
- if (parent === directory) return undefined;
- directory = parent;
- }
-}
-
-/**
- * Resolve the project before any Runtime selection is considered.
- *
- * An explicit Workspace is already the boundary. Otherwise the nearest
- * package.json declares the boundary; when none exists, cwd itself is the
- * explicit shell context. Source paths and Runtime state never choose it.
- */
-export async function resolveProjectRoot(options: {
- readonly workspaceRoot?: string;
- readonly cwd?: string;
-} = {}): Promise<string> {
- const start = resolve(options.workspaceRoot ?? options.cwd ?? process.cwd());
- const selected = options.workspaceRoot !== undefined ? start : await nearestProjectPackageRoot(start) ?? start;
- // Select through the caller's directory first; following a link before discovery
- // could choose a different parent project. Source readers also return real paths.
- return await realpath(selected);
-}
-
-/** Project package discovery cannot escape an already resolved project. */
-export async function resolvePackageRoot(projectRoot: string): Promise<string> {
- return resolve(projectRoot);
-}
diff --git a/packages/project-context-node/src/runtime-selection.ts b/packages/project-context-node/src/runtime-selection.ts
deleted file mode 100644
index cc182522..00000000
--- a/packages/project-context-node/src/runtime-selection.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { mkdir, readFile, realpath, stat, unlink, writeFile } from "node:fs/promises";
-import { relative, resolve } from "node:path";
-
-const stateDirectoryName = ".hypit";
-const selectionFileName = "runtime";
-
-export type RuntimeProfileSelection = {
- readonly profile: string;
- readonly projectRoot: string;
- readonly selectionFile: string;
-};
-
-function errorCode(error: unknown): string | undefined {
- return error !== null && typeof error === "object" && "code" in error
- ? String((error as { readonly code?: unknown }).code)
- : undefined;
-}
-
-async function readSelectionFile(projectRoot: string): Promise<{
- readonly projectRoot: string;
- readonly selectionFile: string;
- readonly value: string;
-} | undefined> {
- const root = resolve(projectRoot);
- const selectionFile = resolve(root, stateDirectoryName, selectionFileName);
- try {
- if (!(await stat(selectionFile)).isFile()) {
- throw new Error(`Runtime selection must be a file: ${selectionFile}; this path is occupied by a directory. `
- + "Move that directory and update its configuration before running hypit runtime use <profile>.");
- }
- return {
- projectRoot: root,
- selectionFile,
- value: (await readFile(selectionFile, "utf8")).trim(),
- };
- } catch (error) {
- if (errorCode(error) === "ENOENT") return undefined;
- throw error;
- }
-}
-
-/**
- * Remember one Runtime Profile for a project. This is project execution context, not
- * Author Source, Run Source, package selection or Core state.
- */
-export async function selectRuntimeProfile(projectRoot: string, profile: string): Promise<RuntimeProfileSelection> {
- const root = await realpath(resolve(projectRoot));
- const selectedProfile = await realpath(resolve(profile));
- const stateDirectory = resolve(root, stateDirectoryName);
- const selectionFile = resolve(stateDirectory, selectionFileName);
- await mkdir(stateDirectory, { recursive: true });
- try {
- await writeFile(resolve(stateDirectory, ".gitignore"), "*\n", { encoding: "utf8", flag: "wx" });
- } catch (error) {
- if (errorCode(error) !== "EEXIST") throw error;
- }
- await readSelectionFile(root);
- const stored = relative(root, selectedProfile) || ".";
- await writeFile(selectionFile, `${stored}\n`, "utf8");
- return { profile: selectedProfile, projectRoot: root, selectionFile };
-}
-
-/** Read only the explicitly resolved project's Runtime selection. */
-export async function findRuntimeProfile(projectRoot: string): Promise<RuntimeProfileSelection | undefined> {
- const selected = await readSelectionFile(projectRoot);
- if (selected === undefined) return undefined;
- if (selected.value.length === 0) {
- throw new Error(`Runtime selection is empty: ${selected.selectionFile}; run hypit runtime use <profile>`);
- }
- const root = selected.projectRoot;
- const candidate = resolve(root, selected.value);
- try {
- return {
- profile: await realpath(candidate),
- projectRoot: root,
- selectionFile: selected.selectionFile,
- };
- } catch (error) {
- if (errorCode(error) === "ENOENT") {
- throw new Error(
- `Selected Runtime Profile no longer exists: ${candidate}; run hypit runtime use <profile>`,
- );
- }
- throw error;
- }
-}
-
-/** Remove only the local pointer. Runtime state, Programs and Builds are untouched. */
-export async function clearRuntimeProfile(projectRoot: string): Promise<RuntimeProfileSelection | undefined> {
- const selected = await readSelectionFile(projectRoot);
- if (selected === undefined) return undefined;
- const profile = resolve(selected.projectRoot, selected.value);
- await unlink(selected.selectionFile);
- return {
- profile,
- projectRoot: selected.projectRoot,
- selectionFile: selected.selectionFile,
- };
-}
diff --git a/packages/project-context-node/README.md b/packages/project/README.md
similarity index 71%
rename from packages/project-context-node/README.md
rename to packages/project/README.md
index 2a7abf5f..e03d4fe5 100644
--- a/packages/project-context-node/README.md
+++ b/packages/project/README.md
@@ -1,13 +1,14 @@
-# `@hypit/project-context-node`
+# `@hypit/project`
Shared project and Runtime selection for Node entrypoints: CLI, Studio and creation tools.
This package resolves locations and reads or explicitly changes the project's Runtime pointer.
It does not load Providers, install programs, inspect credentials or select services.
-1. `resolveProjectRoot({ workspaceRoot?, cwd? })` uses the explicit Workspace, otherwise the nearest
- `package.json` above cwd, otherwise cwd itself. Source and Run filenames do not choose the project.
- After selecting the existing directory, it returns its real filesystem path so project and Source
- paths use the same representation. Symlinks do not redirect the preceding parent-project search.
+1. `resolveProjectRoot({ projectRoot?, cwd? })` uses an explicit Project, otherwise the nearest
+ `package.json` above cwd whose `hypit.project` is `true`. It never turns an arbitrary npm package or
+ cwd into a Project. `findProjectRoot()` exposes the same discovery without requiring a Project.
+ Source and Run filenames do not choose the Project. After selection it returns the real filesystem
+ path; symlinks do not redirect the preceding parent-project search.
2. `findRuntimeProfile(projectRoot)` reads only that project's `.hypit/runtime` file and resolves its
path relative to the project. An entrypoint's explicit `--runtime` overrides this read for that invocation.
3. The selected Runtime implementation interprets the Profile, including `dataRoot`, Credentials,
diff --git a/packages/project-context-node/package.json b/packages/project/package.json
similarity index 78%
rename from packages/project-context-node/package.json
rename to packages/project/package.json
index a634e78c..8c638081 100644
--- a/packages/project-context-node/package.json
+++ b/packages/project/package.json
@@ -1,5 +1,5 @@
{
- "name": "@hypit/project-context-node",
+ "name": "@hypit/project",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
diff --git a/packages/project/src/index.ts b/packages/project/src/index.ts
new file mode 100644
index 00000000..1a6cfe1b
--- /dev/null
+++ b/packages/project/src/index.ts
@@ -0,0 +1 @@
+export { findProjectRoot, resolveProjectRoot } from "./project-context.js";
diff --git a/packages/project/src/project-context.ts b/packages/project/src/project-context.ts
new file mode 100644
index 00000000..c763e65d
--- /dev/null
+++ b/packages/project/src/project-context.ts
@@ -0,0 +1,54 @@
+import { readFile, realpath, stat } from "node:fs/promises";
+import { dirname, resolve } from "node:path";
+
+function isProjectManifest(value: unknown): boolean {
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
+ const hypit = (value as { readonly hypit?: unknown }).hypit;
+ return hypit !== null && typeof hypit === "object" && !Array.isArray(hypit)
+ && (hypit as { readonly project?: unknown }).project === true;
+}
+
+async function nearestProjectPackageRoot(start: string): Promise<string | undefined> {
+ let directory = resolve(start);
+ while (true) {
+ const candidate = resolve(directory, "package.json");
+ try {
+ if ((await stat(candidate)).isFile()) {
+ const manifest = JSON.parse(await readFile(candidate, "utf8")) as unknown;
+ if (isProjectManifest(manifest)) return directory;
+ }
+ } catch (error) {
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
+ }
+ const parent = dirname(directory);
+ if (parent === directory) return undefined;
+ directory = parent;
+ }
+}
+
+/** Find an explicitly marked Hypit project above cwd without inventing one. */
+export async function findProjectRoot(options: { readonly cwd?: string } = {}): Promise<string | undefined> {
+ const selected = await nearestProjectPackageRoot(options.cwd ?? process.cwd());
+ return selected === undefined ? undefined : await realpath(selected);
+}
+
+/**
+ * Resolve an explicit project or require one marked in package.json.
+ *
+ * Source paths, package manifests without `hypit.project: true`, Runtime state
+ * and the current directory alone never manufacture a project boundary.
+ */
+export async function resolveProjectRoot(options: {
+ readonly projectRoot?: string;
+ readonly cwd?: string;
+} = {}): Promise<string> {
+ const selected = options.projectRoot === undefined
+ ? await findProjectRoot(options.cwd === undefined ? {} : { cwd: options.cwd })
+ : resolve(options.cwd ?? process.cwd(), options.projectRoot);
+ if (selected === undefined) {
+ throw new Error("No Hypit project was found; run inside a package.json with hypit.project set to true, or pass --project <directory>");
+ }
+ // Select through the caller's directory first; following a link before discovery
+ // could choose a different parent project. Source readers also return real paths.
+ return await realpath(selected);
+}
diff --git a/packages/protocol/src/build.ts b/packages/protocol/src/build.ts
index f3f23461..fbe34308 100644
--- a/packages/protocol/src/build.ts
+++ b/packages/protocol/src/build.ts
@@ -180,7 +180,7 @@ export type FulfillNeedCommand = {
readonly need: Need;
};
-export type CoreCommand = InvokeProducerCommand | FulfillNeedCommand;
+export type BuildCommand = InvokeProducerCommand | FulfillNeedCommand;
export type ProducerCompletedEvent = {
readonly kind: "producer-completed";
@@ -260,6 +260,6 @@ export type BuildState = {
readonly records: readonly TypedRecord[];
readonly steps: readonly StepState[];
readonly needs: readonly Need[];
- readonly outstanding: readonly CoreCommand[];
+ readonly outstanding: readonly BuildCommand[];
readonly diagnostics: readonly BuildDiagnostic[];
};
diff --git a/packages/build-result/README.md b/packages/result/README.md
similarity index 99%
rename from packages/build-result/README.md
rename to packages/result/README.md
index 2c305c29..79641007 100644
--- a/packages/build-result/README.md
+++ b/packages/result/README.md
@@ -1,4 +1,4 @@
-# `@hypit/build-result`
+# `@hypit/result`
Build Results retain accepted public Outputs and the attempt's final outcome. Execution state belongs
to Runtime. A Result records which value satisfied each Output; a new Output record does not imply a
diff --git a/packages/build-result/package.json b/packages/result/package.json
similarity index 59%
rename from packages/build-result/package.json
rename to packages/result/package.json
index b2e385e5..bdd17914 100644
--- a/packages/build-result/package.json
+++ b/packages/result/package.json
@@ -1,14 +1,15 @@
{
- "name": "@hypit/build-result",
+ "name": "@hypit/result",
"version": "0.0.0-dev",
"license": "SEE LICENSE IN LICENSE",
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./node": "./src/node/index.ts"
},
"dependencies": {
"@hypit/protocol": "workspace:*",
- "@hypit/file-io-node": "workspace:*"
+ "@hypit/atomic-file": "workspace:*"
}
}
diff --git a/packages/build-result/src/decode.ts b/packages/result/src/decode.ts
similarity index 98%
rename from packages/build-result/src/decode.ts
rename to packages/result/src/decode.ts
index 985096ef..3c26523e 100644
--- a/packages/build-result/src/decode.ts
+++ b/packages/result/src/decode.ts
@@ -209,8 +209,8 @@ export function decodeBuildResultManifest(
...(title === undefined ? {} : { title }),
...(note === undefined ? {} : { note }),
...(highlightedOutputs === undefined ? {} : { highlightedOutputs }),
- source: { path: text(source.path, `${subject}.source.path`) },
- ...(run === undefined ? {} : { run: { path: text(run.path, `${subject}.run.path`) } }),
+ source: { id: text(source.id, `${subject}.source.id`) },
+ ...(run === undefined ? {} : { run: { id: text(run.id, `${subject}.run.id`) } }),
targets: texts(item.targets, `${subject}.targets`),
...(finishedAt === undefined ? {} : { finishedAt }),
...(outcome === undefined ? {} : { outcome }),
diff --git a/packages/build-result/src/execution-log.ts b/packages/result/src/execution-log.ts
similarity index 100%
rename from packages/build-result/src/execution-log.ts
rename to packages/result/src/execution-log.ts
diff --git a/packages/result/src/index.ts b/packages/result/src/index.ts
new file mode 100644
index 00000000..0b470865
--- /dev/null
+++ b/packages/result/src/index.ts
@@ -0,0 +1,15 @@
+export {
+ assertBuildResultValueDocument,
+ assertBuildResultSeed,
+} from "./types.js";
+export {
+ decodeBuildResultJson,
+ decodeBuildResultManifest,
+ decodeBuildResultValueDocument,
+ decodeBuildResultWriterState,
+ encodeBuildResultManifest,
+} from "./decode.js";
+export { syncBuildResultOutputs } from "./writer.js";
+export type * from "./types.js";
+export type * from "./writer.js";
+export { preserveExecutionLog } from "./execution-log.js";
diff --git a/packages/build-result/src/file-reference.ts b/packages/result/src/node/file-reference.ts
similarity index 99%
rename from packages/build-result/src/file-reference.ts
rename to packages/result/src/node/file-reference.ts
index f8bbc21a..4001ef80 100644
--- a/packages/build-result/src/file-reference.ts
+++ b/packages/result/src/node/file-reference.ts
@@ -1,7 +1,7 @@
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { fileURLToPath } from "node:url";
-import type { BuildResultFileRange, BuildResultFileRef } from "./types.js";
+import type { BuildResultFileRange, BuildResultFileRef } from "../types.js";
/** Address access belongs to the Repository adapter, not the value or domain graph. */
export type ExternalFileAccess = {
diff --git a/packages/build-result/src/index.ts b/packages/result/src/node/index.ts
similarity index 53%
rename from packages/build-result/src/index.ts
rename to packages/result/src/node/index.ts
index 40448ef0..db71f1bd 100644
--- a/packages/build-result/src/index.ts
+++ b/packages/result/src/node/index.ts
@@ -1,15 +1,4 @@
-export {
- assertBuildResultValueDocument,
- assertBuildResultSeed,
-} from "./types.js";
-export {
- decodeBuildResultJson,
- decodeBuildResultManifest,
- decodeBuildResultValueDocument,
- decodeBuildResultWriterState,
- encodeBuildResultManifest,
-} from "./decode.js";
-export { syncBuildResultOutputs } from "./writer.js";
+export * from "../index.js";
export {
FileBuildResult,
FileBuildResultRepository,
@@ -23,9 +12,5 @@ export {
readBuildResult,
resolveBuildResultOutput,
} from "./store.js";
-export type * from "./types.js";
-export type * from "./writer.js";
-
export { currentFileReference, fileReferenceIdentity, ownedFileReference, localExternalFiles } from "./file-reference.js";
export type { ExternalFileAccess } from "./file-reference.js";
-export { preserveExecutionLog } from "./execution-log.js";
diff --git a/packages/build-result/src/store.ts b/packages/result/src/node/store.ts
similarity index 98%
rename from packages/build-result/src/store.ts
rename to packages/result/src/node/store.ts
index 130aa5bf..89382a34 100644
--- a/packages/build-result/src/store.ts
+++ b/packages/result/src/node/store.ts
@@ -1,4 +1,4 @@
-import { preserveExecutionLog } from "./execution-log.js";
+import { preserveExecutionLog } from "../execution-log.js";
import { currentFileReference, localExternalFiles } from "./file-reference.js";
import type { ExternalFileAccess } from "./file-reference.js";
import { randomUUID } from "node:crypto";
@@ -34,17 +34,17 @@ import type {
RepositoryBuildResultOutputDescription,
RepositoryBuildResultOutputLocation,
FinishedBuildResultManifest,
-} from "./types.js";
-import { assertBuildResultSeed } from "./types.js";
+} from "../types.js";
+import { assertBuildResultSeed } from "../types.js";
import {
decodeBuildResultJson,
decodeBuildResultManifest,
decodeBuildResultValueDocument,
decodeBuildResultWriterState,
encodeBuildResultManifest,
-} from "./decode.js";
-import { syncBuildResultOutputs } from "./writer.js";
-import { replaceFile } from "@hypit/file-io-node";
+} from "../decode.js";
+import { syncBuildResultOutputs } from "../writer.js";
+import { replaceFile } from "@hypit/atomic-file";
const manifestName = "result.json";
const writerStateName = ".writer.json";
diff --git a/packages/build-result/src/types.ts b/packages/result/src/types.ts
similarity index 96%
rename from packages/build-result/src/types.ts
rename to packages/result/src/types.ts
index 4cd141fd..70b1cbd7 100644
--- a/packages/build-result/src/types.ts
+++ b/packages/result/src/types.ts
@@ -196,8 +196,10 @@ export type BuildResultManifest = {
readonly note?: string;
/** Human-selected public Outputs to surface first; names must exist in `outputs`. */
readonly highlightedOutputs?: readonly string[];
- readonly source: { readonly path: string };
- readonly run?: { readonly path: string };
+ /** Opaque author Source identity. A local application may choose a project-relative path. */
+ readonly source: { readonly id: string };
+ /** Opaque Run Source identity, when this Build was authored through one. */
+ readonly run?: { readonly id: string };
/** Author-facing names of the Build's actual final goals. */
readonly targets: readonly string[];
readonly finishedAt?: number;
@@ -240,8 +242,8 @@ export type RepositoryBuildResultOutputLocation = {
export type BuildResultSeed = {
readonly id: string;
readonly title?: string;
- readonly source: { readonly path: string };
- readonly run?: { readonly path: string };
+ readonly source: { readonly id: string };
+ readonly run?: { readonly id: string };
readonly targets: readonly string[];
readonly publishedOutputs: readonly BuildResultPublishedOutput[];
readonly forwards?: readonly BuildResultForward[];
@@ -251,6 +253,10 @@ export type BuildResultSeed = {
/** Validate the one-name-per-Output public Result surface before storage is touched. */
export function assertBuildResultSeed(seed: BuildResultSeed): void {
+ if (seed.source.id.trim().length === 0) throw new Error("Build Result Source identity must not be empty");
+ if (seed.run !== undefined && seed.run.id.trim().length === 0) {
+ throw new Error("Build Result Run identity must not be empty");
+ }
if (seed.title !== undefined && seed.title.trim().length === 0) {
throw new Error("Build Result title must not be empty");
}
diff --git a/packages/build-result/src/writer.ts b/packages/result/src/writer.ts
similarity index 100%
rename from packages/build-result/src/writer.ts
rename to packages/result/src/writer.ts
diff --git a/packages/build-result/test/result.test.ts b/packages/result/test/result.test.ts
similarity index 96%
rename from packages/build-result/test/result.test.ts
rename to packages/result/test/result.test.ts
index 3f4aa6cc..3421d122 100644
--- a/packages/build-result/test/result.test.ts
+++ b/packages/result/test/result.test.ts
@@ -5,7 +5,7 @@ import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import test from "node:test";
-import { buildResultDirectory, FileBuildResult, FileBuildResultRepository, syncBuildResultOutputs } from "@hypit/build-result";
+import { buildResultDirectory, FileBuildResult, FileBuildResultRepository, syncBuildResultOutputs } from "@hypit/result/node";
import type { BlobRef, BuildState, TypeRef } from "@hypit/protocol";
const videoType: TypeRef = {
@@ -39,7 +39,7 @@ test("internal progress and already published Outputs leave Result files untouch
try {
const result = await FileBuildResult.create(root, {
id: "bld_20260902T100000000Z_0000000001",
- source: { path: "/project/main.svml" }, targets: ["answer"],
+ source: { id: "/project/main.svml" }, targets: ["answer"],
publishedOutputs: [{ name: "answer", output: "logical:answer", displayName: "Answer" }],
});
const paths = ["result.json", ".writer.json"].map((name) => join(result.directory, name));
@@ -78,7 +78,7 @@ test("publishing and finishing preserve open readers of the previous Result file
try {
const result = await FileBuildResult.create(root, {
id: "bld_20260902T100000000Z_0000000001",
- source: { path: "/project/main.svml" }, targets: ["answer"],
+ source: { id: "/project/main.svml" }, targets: ["answer"],
publishedOutputs: [{ name: "answer", output: "logical:answer" }],
});
const manifestPath = join(result.directory, "result.json");
@@ -120,8 +120,8 @@ test("one same-Build resource backs a public video and a CompositeValue payload"
try {
const result = await FileBuildResult.create(root, {
id: "bld_20260902T100000000Z_0000000001",
- source: { path: "/project/main.svml" },
- run: { path: "/project/build.svrun" },
+ source: { id: "/project/main.svml" },
+ run: { id: "/project/build.svrun" },
targets: ["shot.video"],
publishedOutputs: [
{ name: "shot.video", output: "logical:shot-video" },
@@ -265,7 +265,7 @@ test("filesystem decodes Result and writer data before exposing it", async () =>
await mkdir(directory, { recursive: true });
await writeFile(join(directory, "result.json"), JSON.stringify({
format: "hypit.build-result@1",
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: ["video"],
outputs: {
video: {
@@ -279,7 +279,7 @@ test("filesystem decodes Result and writer data before exposing it", async () =>
const writer = await repository.create({
id: unfinished,
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: [],
publishedOutputs: [],
});
@@ -306,7 +306,7 @@ test("reserved-looking domain objects remain ordinary Composite data", async ()
await mkdir(join(directory, "values"), { recursive: true });
await writeFile(join(directory, "result.json"), JSON.stringify({
format: "hypit.build-result@1",
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: ["value"],
outcome: "complete",
finishedAt: 1,
@@ -336,7 +336,7 @@ test("describing a Composite Output reads only its manifest", async () => {
await mkdir(directory, { recursive: true });
await writeFile(join(directory, "result.json"), JSON.stringify({
format: "hypit.build-result@1",
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: ["take"],
outcome: "complete",
finishedAt: 1,
@@ -356,7 +356,7 @@ test("an explicitly reused public output is a forward reference and copies no by
try {
const prior = await FileBuildResult.create(root, {
id: "bld_20260902T100000001Z_0000000001",
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["opening.video"],
publishedOutputs: [{ name: "opening.video", output: "logical:opening-video" }],
});
@@ -373,7 +373,7 @@ test("an explicitly reused public output is a forward reference and copies no by
});
const reused = {
id: "bld_20260902T100000002Z_0000000002",
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["shot.video"],
publishedOutputs: [{ name: "shot.video", output: "logical:shot-video" }],
forwards: [{ output: "logical:shot-video", build: "bld_20260902T100000001Z_0000000001", sourceOutput: "opening.video" }],
@@ -422,7 +422,7 @@ test("a forward-only Composite is published from manifests without opening its m
try {
const prior = await FileBuildResult.create(root, {
id: priorId,
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["layout"],
publishedOutputs: [{ name: "layout", output: "logical:layout" }],
});
@@ -438,7 +438,7 @@ test("a forward-only Composite is published from manifests without opening its m
const forwarded = await FileBuildResult.create(root, {
id: nextId,
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["layout"],
publishedOutputs: [{ name: "layout", output: "logical:layout" }],
forwards: [{ output: "logical:layout", build: priorId, sourceOutput: "layout", type: videoType }],
@@ -461,7 +461,7 @@ test("a failed filesystem sync cannot make a later resource inherit stale bytes"
try {
const result = await FileBuildResult.create(root, {
id: "bld_20260924T100000000Z_0000000001",
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["a", "b", "z"],
publishedOutputs: ["a", "b", "z"].map((name) => ({ name, output: name })),
});
@@ -502,7 +502,7 @@ test("Result writer recovers one numeric cursor across file extensions and the 9
manifest: {
format: "hypit.build-result@1",
id: "bld_20260924T110000000Z_0000000001",
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: ["image"],
outputs: {},
},
@@ -534,11 +534,11 @@ test("Result writer bounds resource writes and drains started work before a fail
kind: "blob", resource: `res_${String(index).padStart(2, "0")}`,
size: 1, mediaType: "image/png",
}));
- const input = (target: import("@hypit/build-result").BuildResultWriteTarget) => syncBuildResultOutputs({
+ const input = (target: import("@hypit/result").BuildResultWriteTarget) => syncBuildResultOutputs({
manifest: {
format: "hypit.build-result@1" as const,
id: "bld_20260924T110000001Z_0000000001",
- source: { path: "main.svml" },
+ source: { id: "main.svml" },
targets: ["images"],
outputs: {},
},
@@ -607,7 +607,7 @@ test("filesystem Results have one public name per Output and browse newest first
try {
await assert.rejects(repository.create({
id: "bld_20260902T100000000Z_0000000001",
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["video"],
publishedOutputs: [
{ name: "video", output: "logical:video" },
@@ -618,7 +618,7 @@ test("filesystem Results have one public name per Output and browse newest first
for (const id of ids) {
const writer = await repository.create({
id,
- source: { path: "/project/main.svml" },
+ source: { id: "/project/main.svml" },
targets: ["video"],
publishedOutputs: [{ name: "video", output: "logical:video" }],
});
diff --git a/packages/run-markup/README.md b/packages/run-markup/README.md
deleted file mode 100644
index cf3ba589..00000000
--- a/packages/run-markup/README.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# `@hypit/run-markup`
-
-Official human-readable Frontend for `@hypit/run`.
-
-One Run Source is self-described and names one Author Source explicitly:
-
-```xml
-<?svml using="@hypit/run-markup@1"?>
-<svrun version="1">
- <author source="./main.svml"/>
- <target output="final.video"/>
-
- <build-record id="opening" build="prior-build-id" output="opening-take"/>
- <file id="approved" type="@hypit/artifact@1#BlobArtifact" from="./approved.mp4" media-type="video/mp4"/>
- <satisfy output="opening-take" candidate="opening"/>
-</svrun>
-```
-
-The Author Source's own Header—not this file and not its suffix—selects its Author Frontend.
-
-`<value>` declares a typed zero-input `StoredValue`; its JSON file includes the wrapper, such as
-`{"kind":"inline","value":{"enabled":true}}`, with the inner value matching the declared Type.
-`<file>` admits ordinary source
-bytes as the explicitly named blob Type; Run itself does not assume an Artifact module.
-`<build-record>` exposes one exact named Output from a prior Build Result as a zero-input Candidate. `<fragment>`
-instantiates a trusted package Fragment and may
-export several Candidates backed by shared Operations. Two declarations are two instances; one
-declaration with several exports is one instance.
-
-The `output` on `<build-record>` is the prior Result's unique public Output name. After Core plans the
-complete Author and Run graphs, the Host resolves only the selected zero-input Candidate sources;
-unreached local values, local files and historical Outputs are not opened. Core receives only the typed Candidate value,
-and the historical value receives no automatic semantic-relationship claim
-against the output it is selected to satisfy.
-
-Results are not selected automatically by repeating a Run, retaining an output name, or changing only
-its Targets. Cross-Build reuse requires an explicit Candidate selection. Removing a `satisfy` returns
-that Logical Output to its primary Candidate and can make the displaced generation route reachable
-again. Preserve unrelated selections when revising a Run.
-
-Imports form the opening prologue. They name Fragment libraries already admitted by the Host; they
-do not install packages. Provider credentials, queues, Stores, Endpoint bindings and inline
-callbacks are not Run language elements.
-
-## Fragment input references
-
-`<input name="media" from="opening-media.media"/>` names a public value of the Run's Author
-entry. A computed Author Output remains a graph dependency, with its selected Candidate applied.
-The reference is not another Run Candidate name and does not expose a nested Source namespace that
-the Author entry has not published.
-
-`<input name="duration" value="5"/>` supplies a scalar. The parser recognizes numbers, booleans
-and null; other text is a string. Typed object inputs are obtained through `from`, not by placing
-JSON in a scalar attribute. `<value>` reads a serialized typed value as a Candidate for a Logical
-Output; it does not introduce an Author binding for Fragment inputs.
-
-Fragment exports are available as `<instance-id>.<export-name>`. Optional `<export name="video"/>`
-children expose selected exports; omitting them exposes all Fragment exports. Their shared required
-operations remain one instance. Imports precede Targets and Candidate declarations, following the
-required `author` declaration.
diff --git a/packages/run-markup/package.json b/packages/run-markup/package.json
deleted file mode 100644
index 1d06e272..00000000
--- a/packages/run-markup/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "@hypit/run-markup",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "hypit": {
- "activation": "./src/activation.ts"
- },
- "dependencies": {
- "@hypit/protocol": "workspace:*",
- "@hypit/run": "workspace:*",
- "@hypit/markup": "workspace:*"
- },
- "devDependencies": {
- "@hypit/core": "workspace:*",
- "@hypit/elaborator": "workspace:*"
- }
-}
diff --git a/packages/run-markup/src/activation.ts b/packages/run-markup/src/activation.ts
deleted file mode 100644
index 66a61136..00000000
--- a/packages/run-markup/src/activation.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { createRunFrontendHostFacet } from "@hypit/run";
-
-import { runMarkupFrontend } from "./index.js";
-
-export const hypitPackage = {
- format: "hypit.node-package@1" as const,
- hostFacets: [createRunFrontendHostFacet(runMarkupFrontend)],
-};
-
-export default hypitPackage;
diff --git a/packages/run/README.md b/packages/run/README.md
index b32bb05b..c57abd75 100644
--- a/packages/run/README.md
+++ b/packages/run/README.md
@@ -3,7 +3,7 @@
Syntax-neutral Run Source and complete Run Graph compiler.
This package is outside Core and knows no XML, filename suffix, video type, Provider or Runtime
-configuration. Given a self-described source unit, a registered `RunFrontend`, an already compiled
+configuration. Given a resolved Source, a registered `RunFrontend`, an already compiled
Author Source and trusted Run Fragment registry, it produces:
```text
@@ -17,7 +17,7 @@ CLI flags.
`RunSourceClosure` separately binds original source bytes, Frontend id/implementation and decoded
semantic meaning. `RunFragmentRegistry` accepts trusted Fragment packages only through the
-`hypit.run-fragment-host@1` Host-facet installer. Package loading does not interpret Fragment code.
+`hypit.run-fragment@1` Facet installer. Package loading does not interpret Fragment code.
-The optional official XML-like syntax lives in `@hypit/run-markup`. Another trusted Frontend can emit
+The optional official XML-like syntax lives in `@hypit/markup/run`. Another trusted Frontend can emit
the same `RunDocument` without changing this package or Core.
diff --git a/packages/run/package.json b/packages/run/package.json
index 4bbdcee3..2239fb19 100644
--- a/packages/run/package.json
+++ b/packages/run/package.json
@@ -8,8 +8,8 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/elaborator": "workspace:*",
- "@hypit/host": "workspace:*",
+ "@hypit/author": "workspace:*",
+ "@hypit/facet": "workspace:*",
"@hypit/protocol": "workspace:*",
"@hypit/source": "workspace:*"
}
diff --git a/packages/run/src/facet.ts b/packages/run/src/facet.ts
index e9a79cc7..5ca125b9 100644
--- a/packages/run/src/facet.ts
+++ b/packages/run/src/facet.ts
@@ -1,14 +1,14 @@
-import type { GraphFragment } from "@hypit/elaborator";
-import type { HostFacet } from "@hypit/host";
+import type { GraphFragment } from "@hypit/author";
+import type { Facet } from "@hypit/facet";
import type {
RunFragmentPackage,
} from "./types.js";
-export const runFragmentHostAbi = "hypit.run-fragment-host@1";
+export const runFragmentFacetAbi = "hypit.run-fragment@1";
-export type RunFragmentHostFacet = HostFacet & {
- readonly abi: typeof runFragmentHostAbi;
+export type RunFragmentFacet = Facet & {
+ readonly abi: typeof runFragmentFacetAbi;
readonly offers: readonly string[];
readonly implementation: RunFragmentPackage;
};
@@ -16,42 +16,42 @@ export type RunFragmentHostFacet = HostFacet & {
function validateFragments(fragments: Readonly<Record<string, GraphFragment>>): void {
for (const [name, fragment] of Object.entries(fragments)) {
if (name.trim().length === 0 || fragment.id.trim().length === 0) {
- throw new Error("Run Fragment Host facet has an invalid export");
+ throw new Error("Run Fragment facet has an invalid export");
}
}
}
-/** Package helper: expose inert Run Fragments through the exact Run Host ABI. */
-export function createRunFragmentHostFacet(item: RunFragmentPackage): RunFragmentHostFacet {
- if (item.name.trim().length === 0) throw new Error("Run Fragment Host facet package name is empty");
+/** Package helper: expose inert Run Fragments through the exact Run Fragment ABI. */
+export function createRunFragmentFacet(item: RunFragmentPackage): RunFragmentFacet {
+ if (item.name.trim().length === 0) throw new Error("Run Fragment facet package name is empty");
validateFragments(item.fragments);
return {
- abi: runFragmentHostAbi,
+ abi: runFragmentFacetAbi,
offers: [item.name],
implementation: item,
};
}
/**
- * Install only facets addressed to this Host ABI. Package loading itself never interprets or
+ * Install only facets addressed to this Facet ABI. Package loading itself never interprets or
* activates the executable Fragment objects.
*/
-export function installRunFragmentHostFacets(
- facets: readonly HostFacet[],
+export function installRunFragmentFacets(
+ facets: readonly Facet[],
registry: { register(item: RunFragmentPackage): void },
): void {
for (const opaque of facets) {
- if (opaque.abi !== runFragmentHostAbi) continue;
+ if (opaque.abi !== runFragmentFacetAbi) continue;
if (opaque.implementation === null || typeof opaque.implementation !== "object"
|| Array.isArray(opaque.implementation)) {
- throw new Error("Run Fragment Host facet has an invalid implementation");
+ throw new Error("Run Fragment facet has an invalid implementation");
}
- const facet = opaque as RunFragmentHostFacet;
+ const facet = opaque as RunFragmentFacet;
if (typeof facet.implementation.name !== "string"
|| facet.implementation.fragments === null
|| typeof facet.implementation.fragments !== "object"
|| Array.isArray(facet.implementation.fragments)) {
- throw new Error("Run Fragment Host facet has an invalid package implementation");
+ throw new Error("Run Fragment facet has an invalid package implementation");
}
validateFragments(facet.implementation.fragments);
registry.register(facet.implementation);
diff --git a/packages/run/src/frontend-facet.ts b/packages/run/src/frontend-facet.ts
index 10d59b88..2ae6ad76 100644
--- a/packages/run/src/frontend-facet.ts
+++ b/packages/run/src/frontend-facet.ts
@@ -1,23 +1,23 @@
import {
- createFrontendHostFacet,
- frontendsFromHostFacets,
-} from "@hypit/host";
+ createFrontendFacet,
+ frontendsFromFacets,
+} from "@hypit/facet";
import type {
- FrontendHostFacet,
- HostFacet,
-} from "@hypit/host";
+ FrontendFacet,
+ Facet,
+} from "@hypit/facet";
import { sourceFrontendPackageAbi } from "@hypit/source";
import type { RunFrontend } from "./types.js";
-export type RunFrontendHostFacet = FrontendHostFacet<"run", RunFrontend> & {
+export type RunFrontendFacet = FrontendFacet<"run", RunFrontend> & {
readonly abi: typeof sourceFrontendPackageAbi;
};
-export function createRunFrontendHostFacet(frontend: RunFrontend): RunFrontendHostFacet {
- return createFrontendHostFacet(sourceFrontendPackageAbi, "run", frontend) as RunFrontendHostFacet;
+export function createRunFrontendFacet(frontend: RunFrontend): RunFrontendFacet {
+ return createFrontendFacet(sourceFrontendPackageAbi, "run", frontend) as RunFrontendFacet;
}
-export function runFrontendsFromHostFacets(facets: readonly HostFacet[]): readonly RunFrontend[] {
- return frontendsFromHostFacets<"run", RunFrontend>(sourceFrontendPackageAbi, "run", facets);
+export function runFrontendsFromFacets(facets: readonly Facet[]): readonly RunFrontend[] {
+ return frontendsFromFacets<"run", RunFrontend>(sourceFrontendPackageAbi, "run", facets);
}
diff --git a/packages/run/src/frontend.ts b/packages/run/src/frontend.ts
index 9ac96bdd..67938ef6 100644
--- a/packages/run/src/frontend.ts
+++ b/packages/run/src/frontend.ts
@@ -1,7 +1,4 @@
-import {
- maskSourceHeader,
- parseSourceHeader,
-} from "@hypit/source";
+import type { ResolvedSource } from "@hypit/source";
import type {
RunDocument,
@@ -41,22 +38,12 @@ export class RunFrontendRegistry implements RunFrontendRegistryLike {
}
}
-export function prepareRunSource(source: RunSourceUnit): RunFrontendSourceUnit {
- const header = parseSourceHeader(source.name, source.text);
- return {
- ...source,
- text: maskSourceHeader(source.text, header),
- header,
- };
-}
-
export async function compileRunSource(
- source: RunSourceUnit,
+ source: ResolvedSource,
frontends: RunFrontendRegistryLike,
): Promise<{ readonly document: RunDocument }> {
- const prepared = prepareRunSource(source);
- const frontend = frontends.resolve(prepared.header.using);
- assert(frontend !== undefined, "UNKNOWN_RUN_FRONTEND", `Run Frontend ${prepared.header.using} is not registered`, prepared.header.using);
- const decoded = await frontend.decode(prepared);
+ const frontend = frontends.resolve(source.frontend);
+ assert(frontend !== undefined, "UNKNOWN_RUN_FRONTEND", `Run Frontend ${source.frontend} is not registered`, source.frontend);
+ const decoded = await frontend.decode(source.unit);
return { document: decoded.document };
}
diff --git a/packages/run/src/index.ts b/packages/run/src/index.ts
index 8cc6c09a..f6ef13ce 100644
--- a/packages/run/src/index.ts
+++ b/packages/run/src/index.ts
@@ -6,25 +6,24 @@ export type {
ProvidedCandidateInput,
} from "./candidate.js";
export {
- createRunFragmentHostFacet,
- installRunFragmentHostFacets,
- runFragmentHostAbi,
+ createRunFragmentFacet,
+ installRunFragmentFacets,
+ runFragmentFacetAbi,
} from "./facet.js";
export type {
- RunFragmentHostFacet,
+ RunFragmentFacet,
} from "./facet.js";
export { collectRunModuleRequests, resolveRunDocument } from "./resolve.js";
export {
compileRunSource,
- prepareRunSource,
RunFrontendRegistry,
RunSourceError,
} from "./frontend.js";
export {
- createRunFrontendHostFacet,
- runFrontendsFromHostFacets,
+ createRunFrontendFacet,
+ runFrontendsFromFacets,
} from "./frontend-facet.js";
-export type { RunFrontendHostFacet } from "./frontend-facet.js";
+export type { RunFrontendFacet } from "./frontend-facet.js";
export {
RunGraphError,
sealRunGraph,
diff --git a/packages/run/src/registry.ts b/packages/run/src/registry.ts
index 9a386124..fa4f0378 100644
--- a/packages/run/src/registry.ts
+++ b/packages/run/src/registry.ts
@@ -1,4 +1,4 @@
-import type { GraphFragment } from "@hypit/elaborator";
+import type { GraphFragment } from "@hypit/author";
import type { RunFragmentPackage, RunFragmentRegistryLike } from "./types.js";
diff --git a/packages/run/src/resolve.ts b/packages/run/src/resolve.ts
index d94e0150..20b16537 100644
--- a/packages/run/src/resolve.ts
+++ b/packages/run/src/resolve.ts
@@ -2,7 +2,7 @@ import {
elaborateGraphFragment,
exportRunFragment,
resolveCompiledSourceExport,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import { canonicalize, sameType } from "@hypit/protocol";
import type {
Candidate,
diff --git a/packages/run/src/types.ts b/packages/run/src/types.ts
index 3a1c5d7b..da3a2d32 100644
--- a/packages/run/src/types.ts
+++ b/packages/run/src/types.ts
@@ -1,7 +1,7 @@
import type {
CompiledSourceClosure,
GraphFragment,
-} from "@hypit/elaborator";
+} from "@hypit/author";
import type {
Candidate,
CanonicalValue,
@@ -11,13 +11,11 @@ import type {
TypeRef,
} from "@hypit/protocol";
export type { RunGraph } from "@hypit/protocol";
-import type { SourceHeader, SourceUnit } from "@hypit/source";
+import type { SourceUnit } from "@hypit/source";
export type RunSourceUnit = SourceUnit;
-export type RunFrontendSourceUnit = RunSourceUnit & {
- readonly header: SourceHeader;
-};
+export type RunFrontendSourceUnit = RunSourceUnit;
export type RunAuthorSourceRequest = {
readonly source: string;
diff --git a/packages/runtime-kit/README.md b/packages/runtime-kit/README.md
deleted file mode 100644
index 2074770a..00000000
--- a/packages/runtime-kit/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# `@hypit/hypit/runtime-kit`
-
-Host facets for the two environmental choices a Local Runtime Profile may select:
-
-* an Endpoint implements external capabilities;
-* a Credential Store resolves explicit credential references.
-
-External packages use this public subpath from their `@hypit/hypit` development dependency. The built
-package's `hypit.activation` entry exports a default package contribution with
-`format: "hypit.node-package@1"` and the declared `hostFacets`.
-
-For a Provider, `createRuntimeEndpointAdapterFacet({ use, activate })` advertises its owner-scoped
-package name. `activate(context)` reads `instance`, `pool`, and the package's own `config`, then
-returns `{ endpoint }` from `defineEndpointPackage`; it can also return `program` and `diagnose`.
-The configuration helpers parse values and CredentialRefs. Activation describes the deployment;
-credential resolution, remote invocation, and Managed Program startup happen through their Runtime
-operations. Installing the same package in another project preserves its `use` name.
-
-```json
-{
- "endpoints": {
- "art.personal": {
- "use": "@studio/provider-art",
- "config": { "apiKey": { "store": "os", "key": "art.personal" } }
- }
- }
-}
-```
-
-This is a Profile fragment: the Provider defines its actual config fields, and the complete Profile
-selects the `os` Credential Store as well. Separate instances can use separate accounts. A binding
-names the chosen instance when several offer the same capability. The default pool identity is the
-instance; declare a shared pool only for a real shared account, deployment, or compute quota.
-
-Each adapter is addressed by its kind and `use` name. A package advertises that name through a Host
-facet; the Runtime Profile selects it explicitly. Installing a package does not activate it.
-
-Endpoint activation returns one Endpoint and may also describe a Managed Program such as a warm local
-WhisperX process. Credential adapters validate configuration before opening a store. Active Resource
-storage belongs to the Runtime implementation, while project Build Result repositories use the
-separate `@hypit/build-result-kit` boundary. Runtime Kit knows no Provider, filesystem, database or
-video package by name.
-
-`ManagedProgram.installation.prepareBeforeStart` lets a Provider reconcile its installed environment
-before a cold start, even when the installation probe already passes. The declared commands use the
-Provider's ordinary package manager. `programs prepare` runs the declared installation independently
-of process startup; `programs up` also checks its resources when the process is already healthy.
-The installation probe covers the owner's selected execution resources, while the process probe
-reports service readiness. Cold reconciliation still applies only before starting a new process.
-Runtime does not name models, inspect source files or infer implementation versions. Preparation
-may acquire resources; execution must consume already prepared resources and report what is missing.
-`ManagedProgramCommand.label` optionally names a command's purpose for progress and log headings.
-It is display text supplied by the Program owner, not a phase to persist or interpret. Runtime
-reports generic process/probe facts; the service itself owns domain-specific progress in its logs.
diff --git a/packages/runtime-kit/package.json b/packages/runtime-kit/package.json
deleted file mode 100644
index abf83c3b..00000000
--- a/packages/runtime-kit/package.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "name": "@hypit/runtime-kit",
- "version": "0.0.0-dev",
- "license": "SEE LICENSE IN LICENSE",
- "private": true,
- "type": "module",
- "exports": {
- ".": "./src/index.ts"
- },
- "dependencies": {
- "@hypit/endpoint-kit": "workspace:*",
- "@hypit/host": "workspace:*",
- "@hypit/protocol": "workspace:*",
- "@hypit/runtime": "workspace:*"
- }
-}
diff --git a/packages/runtime-kit/src/index.ts b/packages/runtime-kit/src/index.ts
deleted file mode 100644
index 267a63f1..00000000
--- a/packages/runtime-kit/src/index.ts
+++ /dev/null
@@ -1,311 +0,0 @@
-import { endpointActions } from "@hypit/endpoint-kit";
-import type { EndpointPackage } from "@hypit/endpoint-kit";
-import type { HostFacet } from "@hypit/host";
-import type { CanonicalValue } from "@hypit/protocol";
-import { credentialRef } from "@hypit/runtime";
-import type { CredentialRef, CredentialStore, CredentialValue } from "@hypit/runtime";
-
-export const runtimeEndpointAdapterHostAbi = "hypit.runtime-endpoint-adapter-host@1";
-export const runtimeCredentialStoreAdapterHostAbi = "hypit.runtime-credential-store-adapter-host@1";
-
-export type RuntimeAdapterKind = "endpoint" | "credential-store";
-
-type RuntimeAdapterAddress = {
- readonly use: string;
- readonly kind: RuntimeAdapterKind;
-};
-
-export type RuntimeAdapterFactoryContext = {
- /** Persistent machine/user state supplied by the Host, outside every author project. */
- readonly hostStateRoot: string;
- /** Runtime/Profile state belonging to this project. */
- readonly dataRoot: string;
- readonly instance: string;
- readonly pool?: string;
- readonly config: CanonicalValue;
-};
-
-export type RuntimeDoctorDiagnostic = {
- readonly severity: "error" | "warning" | "info";
- readonly code: string;
- readonly message: string;
- readonly subject?: string;
-};
-
-export type ManagedProgramCommand = {
- /** Optional human-readable purpose, supplied by the program owner. Not a lifecycle state. */
- readonly label?: string;
- readonly command: string;
- readonly args: readonly string[];
- readonly cwd?: string;
- readonly env?: Readonly<Record<string, string>>;
-};
-
-export type ManagedProgramInstallation = {
- /** Read-only inspection of the selected environment and resources; no downloads or receipts. */
- probe(): Promise<ManagedProgramState>;
- /** Reconcile an installed environment before a cold start, using its package manager's cache. */
- readonly prepareBeforeStart?: boolean;
- /** Explicit preparation commands, run for missing resources or cold reconciliation above. */
- readonly commands: readonly ManagedProgramCommand[];
-};
-
-export type ManagedProgramState =
- | { readonly state: "ready" }
- | { readonly state: "down"; readonly detail: string }
- | { readonly state: "mismatch"; readonly detail: string };
-
-export type ManagedProgram = {
- readonly id: string;
- /** Shared lifecycle files live here; absent means this Runtime owns them. */
- readonly stateRoot?: string;
- /** Installation and runtime readiness are deliberately separate states. */
- readonly installation?: ManagedProgramInstallation;
- probe(): Promise<ManagedProgramState>;
- readonly start?: ManagedProgramCommand;
-};
-
-export type RuntimeEndpointActivation = {
- readonly endpoint: EndpointPackage;
- readonly program?: ManagedProgram;
- readonly diagnose?: (context: {
- readonly credentials: Readonly<Record<string, CredentialValue>>;
- readonly capabilities?: readonly import("@hypit/protocol").CapabilityRef[];
- }) => readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;
-};
-
-export type RuntimeOpened<T> = {
- readonly value: T;
- readonly close?: () => void | Promise<void>;
-};
-
-export type RuntimeEndpointAdapterImplementation = {
- activate(context: RuntimeAdapterFactoryContext): RuntimeEndpointActivation | Promise<RuntimeEndpointActivation>;
-};
-
-type RuntimeStoreAdapterImplementation<T> = {
- validate(context: RuntimeAdapterFactoryContext): void;
- open(context: RuntimeAdapterFactoryContext): RuntimeOpened<T> | Promise<RuntimeOpened<T>>;
- doctor?(context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] | Promise<readonly RuntimeDoctorDiagnostic[]>;
-};
-
-type RuntimeAdapterImplementation =
- | RuntimeEndpointAdapterImplementation
- | RuntimeStoreAdapterImplementation<CredentialStore>;
-
-export type RuntimeAdapterHostFacet = HostFacet & {
- readonly abi:
- | typeof runtimeEndpointAdapterHostAbi
- | typeof runtimeCredentialStoreAdapterHostAbi;
- readonly implementation: RuntimeAdapterImplementation;
-};
-
-function assert(condition: unknown, message: string): asserts condition {
- if (!condition) throw new Error(message);
-}
-
-function abiFor(kind: RuntimeAdapterKind): RuntimeAdapterHostFacet["abi"] {
- if (kind === "endpoint") return runtimeEndpointAdapterHostAbi;
- return runtimeCredentialStoreAdapterHostAbi;
-}
-
-function address(facet: RuntimeAdapterHostFacet): RuntimeAdapterAddress {
- const kind = facet.abi === runtimeEndpointAdapterHostAbi
- ? "endpoint"
- : facet.abi === runtimeCredentialStoreAdapterHostAbi ? "credential-store" : undefined;
- assert(kind !== undefined, `Runtime Adapter ${facet.abi} ABI is unsupported`);
- assert(facet.offers?.length === 1 && facet.offers[0]!.trim().length > 0,
- "Runtime Adapter must offer exactly one non-empty use name");
- return { use: facet.offers[0]!, kind };
-}
-
-function verifyImplementation(value: unknown, subject: string, kind: RuntimeAdapterKind): RuntimeAdapterImplementation {
- assert(value !== null && typeof value === "object", `${subject} implementation is not an object`);
- if (kind === "endpoint") {
- assert(typeof (value as { activate?: unknown }).activate === "function", `${subject} does not implement activate()`);
- return value as RuntimeEndpointAdapterImplementation;
- }
- assert(typeof (value as { validate?: unknown }).validate === "function", `${subject} does not implement validate()`);
- assert(typeof (value as { open?: unknown }).open === "function", `${subject} does not implement open()`);
- const doctor = (value as { doctor?: unknown }).doctor;
- assert(doctor === undefined || typeof doctor === "function", `${subject}.doctor must be a function`);
- return value as RuntimeAdapterImplementation;
-}
-
-function storeFacet<T>(kind: "credential-store", options: {
- readonly use: string;
- readonly validate: RuntimeStoreAdapterImplementation<T>["validate"];
- readonly open: RuntimeStoreAdapterImplementation<T>["open"];
- readonly doctor?: RuntimeStoreAdapterImplementation<T>["doctor"];
-}): RuntimeAdapterHostFacet {
- assert(options.use.trim().length > 0, "Runtime Adapter use name is empty");
- const implementation = {
- validate: options.validate,
- open: options.open,
- ...(options.doctor === undefined ? {} : { doctor: options.doctor }),
- };
- return {
- abi: abiFor(kind),
- offers: [options.use],
- implementation: verifyImplementation(implementation, `Runtime Adapter ${options.use}`, kind),
- };
-}
-
-export function createRuntimeEndpointAdapterFacet(options: {
- readonly use: string;
- readonly activate: RuntimeEndpointAdapterImplementation["activate"];
-}): RuntimeAdapterHostFacet {
- assert(options.use.trim().length > 0, "Runtime Adapter use name is empty");
- return {
- abi: runtimeEndpointAdapterHostAbi,
- offers: [options.use],
- implementation: verifyImplementation({ activate: options.activate }, `Runtime Adapter ${options.use}`, "endpoint"),
- };
-}
-
-export function createRuntimeCredentialStoreAdapterFacet(options: {
- readonly use: string;
- readonly validate: RuntimeStoreAdapterImplementation<CredentialStore>["validate"];
- readonly open: RuntimeStoreAdapterImplementation<CredentialStore>["open"];
- readonly doctor?: RuntimeStoreAdapterImplementation<CredentialStore>["doctor"];
-}): RuntimeAdapterHostFacet {
- return storeFacet("credential-store", options);
-}
-
-export function isRuntimeAdapterHostFacet(value: HostFacet): value is RuntimeAdapterHostFacet {
- try {
- const resolved = address(value as RuntimeAdapterHostFacet);
- verifyImplementation(value.implementation, "Runtime Adapter", resolved.kind);
- return true;
- } catch {
- return false;
- }
-}
-
-export class RuntimeAdapterRegistry {
- readonly #registrations = new Map<string, RuntimeAdapterImplementation>();
-
- #key(use: string, kind: RuntimeAdapterKind): string {
- return `${kind}\u0000${use}`;
- }
-
- registerFacet(facet: HostFacet): void {
- assert(isRuntimeAdapterHostFacet(facet), `Host facet ${facet.abi} is not a valid Runtime Adapter`);
- const resolved = address(facet);
- const key = this.#key(resolved.use, resolved.kind);
- assert(!this.#registrations.has(key), `Runtime ${resolved.kind} Adapter ${resolved.use} is already registered`);
- this.#registrations.set(key, facet.implementation);
- }
-
- has(use: string, kind: RuntimeAdapterKind): boolean {
- return this.#registrations.has(this.#key(use, kind));
- }
-
- async activateEndpoint(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeEndpointActivation> {
- const implementation = this.#registrations.get(this.#key(use, "endpoint")) as RuntimeEndpointAdapterImplementation | undefined;
- assert(implementation !== undefined, `Runtime Endpoint adapter ${use} is not registered`);
- const activation = await implementation.activate(context);
- assert(activation.endpoint.instance.id === context.instance,
- `Runtime Endpoint adapter ${use} created Endpoint ${activation.endpoint.instance.id} outside configured instance ${context.instance}`);
- return activation;
- }
-
- async createEndpoint(use: string, context: RuntimeAdapterFactoryContext): Promise<EndpointPackage> {
- return (await this.activateEndpoint(use, context)).endpoint;
- }
-
- async #openStore<T>(use: string, kind: "credential-store", context: RuntimeAdapterFactoryContext): Promise<RuntimeOpened<T>> {
- const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<T> | undefined;
- assert(implementation !== undefined, `Runtime ${kind} adapter ${use} is not registered`);
- implementation.validate(context);
- const opened = await implementation.open(context);
- assert(opened.value !== null && typeof opened.value === "object", `Runtime ${kind} adapter ${use} returned no value`);
- return opened;
- }
-
- async openCredentialStore(use: string, context: RuntimeAdapterFactoryContext): Promise<RuntimeOpened<CredentialStore>> {
- return await this.#openStore(use, "credential-store", context);
- }
-
- validate(use: string, kind: Exclude<RuntimeAdapterKind, "endpoint">, context: RuntimeAdapterFactoryContext): readonly RuntimeDoctorDiagnostic[] {
- const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<unknown> | undefined;
- if (implementation === undefined) return [{
- severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use,
- }];
- implementation.validate(context);
- return [];
- }
-
- async doctor(use: string, kind: Exclude<RuntimeAdapterKind, "endpoint">, context: RuntimeAdapterFactoryContext): Promise<readonly RuntimeDoctorDiagnostic[]> {
- const implementation = this.#registrations.get(this.#key(use, kind)) as RuntimeStoreAdapterImplementation<unknown> | undefined;
- if (implementation === undefined) return [{
- severity: "error", code: "RUNTIME_ADAPTER_MISSING", message: `Runtime Adapter ${use} is not registered`, subject: use,
- }];
- return implementation.doctor === undefined ? [] : await implementation.doctor(context);
- }
-}
-
-export function runtimeConfigObject(value: CanonicalValue, subject: string): Record<string, CanonicalValue> {
- assert(value !== null && typeof value === "object" && !Array.isArray(value), `${subject} config must be an object`);
- return value as Record<string, CanonicalValue>;
-}
-
-export function runtimeConfigExact(value: Record<string, CanonicalValue>, allowed: readonly string[], subject: string): void {
- const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
- assert(unknown.length === 0, `${subject} config does not accept ${unknown[0]}`);
-}
-
-export function runtimeConfigString(value: CanonicalValue | undefined, subject: string): string | undefined {
- if (value === undefined) return undefined;
- assert(typeof value === "string" && value.trim().length > 0, `${subject} must be a non-empty string`);
- return value;
-}
-
-export function runtimeConfigPositiveInteger(value: CanonicalValue | undefined, subject: string): number | undefined {
- if (value === undefined) return undefined;
- assert(typeof value === "number" && Number.isSafeInteger(value) && value > 0, `${subject} must be a positive integer`);
- return value;
-}
-
-export function runtimeConfigBoolean(value: CanonicalValue | undefined, subject: string): boolean | undefined {
- if (value === undefined) return undefined;
- assert(typeof value === "boolean", `${subject} must be a boolean`);
- return value;
-}
-
-export function runtimeConfigCredentialRef(
- value: CanonicalValue | undefined,
- subject: string,
-): CredentialRef | undefined {
- if (value === undefined) return undefined;
- const object = runtimeConfigObject(value, subject);
- runtimeConfigExact(object, ["store", "key"], subject);
- const store = runtimeConfigString(object.store, `${subject}.store`);
- const key = runtimeConfigString(object.key, `${subject}.key`);
- assert(store !== undefined && key !== undefined, `${subject} requires store and key`);
- return credentialRef(store, key);
-}
-
-/** Common Profile representation for short action occupancy and rate budgets. */
-export function runtimeConfigActionLimits(value: CanonicalValue | undefined): import("@hypit/endpoint-kit").EndpointActionLimits | undefined {
- if (value === undefined) return undefined;
- const actions = runtimeConfigObject(value, "actionLimits");
- runtimeConfigExact(actions, endpointActions, "actionLimits");
- return Object.fromEntries(Object.entries(actions).map(([action, raw]) => {
- const limit = runtimeConfigObject(raw, `actionLimits.${action}`);
- runtimeConfigExact(limit, ["concurrency", "rate"], `actionLimits.${action}`);
- const concurrency = runtimeConfigPositiveInteger(limit.concurrency, `${action} concurrency`);
- let rate: { limit: number; periodMs: number } | undefined;
- if (limit.rate !== undefined) {
- const item = runtimeConfigObject(limit.rate, `${action} rate`);
- runtimeConfigExact(item, ["limit", "periodMs"], `${action} rate`);
- const units = runtimeConfigPositiveInteger(item.limit, `${action} rate.limit`);
- const periodMs = runtimeConfigPositiveInteger(item.periodMs, `${action} rate.periodMs`);
- if (units === undefined || periodMs === undefined) throw new Error(`${action} rate requires limit and periodMs`);
- rate = { limit: units, periodMs };
- }
- return [action, { ...(concurrency === undefined ? {} : { concurrency }), ...(rate === undefined ? {} : { rate }) }];
- }));
-}
-
-export { requestDeadline } from "./request-deadline.js";
diff --git a/packages/runtime-kit/src/request-deadline.ts b/packages/runtime-kit/src/request-deadline.ts
deleted file mode 100644
index 502ded46..00000000
--- a/packages/runtime-kit/src/request-deadline.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/** A deadline covers headers and body consumption even when a transport ignores abort. */
-export function requestDeadline(timeoutMs: number, error: () => Error = () => new Error("Request timed out")) {
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1) throw new Error("Request timeout must be a positive integer");
- const controller = new AbortController();
- let reject!: (reason: Error) => void;
- const expired = new Promise<never>((_resolve, fail) => { reject = fail; });
- const timer = setTimeout(() => {
- const reason = error();
- reject(reason);
- controller.abort(reason);
- }, timeoutMs);
- return {
- signal: controller.signal,
- wait: async <T>(work: Promise<T>): Promise<T> => await Promise.race([work, expired]),
- finish: (): void => clearTimeout(timer),
- };
-}
diff --git a/packages/runtime-kit/test/registry.test.ts b/packages/runtime-kit/test/registry.test.ts
deleted file mode 100644
index 973008c2..00000000
--- a/packages/runtime-kit/test/registry.test.ts
+++ /dev/null
@@ -1,111 +0,0 @@
-import assert from "node:assert/strict";
-import test from "node:test";
-
-import {
- createRuntimeCredentialStoreAdapterFacet,
- createRuntimeEndpointAdapterFacet,
- isRuntimeAdapterHostFacet,
- runtimeConfigBoolean,
- runtimeConfigExact,
- runtimeConfigObject,
- runtimeConfigPositiveInteger,
- runtimeConfigString,
- RuntimeAdapterRegistry,
-} from "@hypit/runtime-kit";
-import type { RuntimeAdapterFactoryContext } from "@hypit/runtime-kit";
-
-const context = { hostStateRoot: "/host", dataRoot: "/tmp", instance: "one", config: {} };
-const endpointPackage = (instance: string) => ({
- name: instance,
- manifest: { facets: [] },
- instance: { id: instance },
- offers: [],
- credentials: [],
- install() {},
-}) as never;
-const endpoint = (use: string, extra: Record<string, unknown> = {}) =>
- createRuntimeEndpointAdapterFacet({
- use,
- activate: (value: RuntimeAdapterFactoryContext) => ({ endpoint: endpointPackage(value.instance), ...extra }),
- } as never);
-
-test("Endpoint and Credential Store adapters may share one package address", () => {
- const registry = new RuntimeAdapterRegistry();
- registry.registerFacet(endpoint("example.shared"));
- registry.registerFacet(createRuntimeCredentialStoreAdapterFacet({
- use: "example.shared",
- validate() {},
- open: () => ({ value: {} as never }),
- }));
- assert.ok(registry.has("example.shared", "endpoint"));
- assert.ok(registry.has("example.shared", "credential-store"));
-});
-
-test("one kind and logical name has one adapter, so a second registration is an error", () => {
- const registry = new RuntimeAdapterRegistry();
- registry.registerFacet(endpoint("example.endpoint"));
- assert.throws(() => registry.registerFacet(endpoint("example.endpoint")), /already registered/u);
-});
-
-test("an Endpoint facet without activate() is not a facet", () => {
- assert.throws(
- () => createRuntimeEndpointAdapterFacet({ use: "x" } as never),
- /does not implement activate\(\)/u,
- );
- assert.throws(
- () => createRuntimeEndpointAdapterFacet({ use: "x", activate: 1 } as never),
- /does not implement activate\(\)/u,
- );
- assert.throws(
- () => createRuntimeEndpointAdapterFacet({ use: " ", activate: () => ({}) } as never),
- /use name is empty/u,
- );
-});
-
-test("one activation validates and declares the selected Endpoint", async () => {
- let activated = 0;
- const registry = new RuntimeAdapterRegistry();
- registry.registerFacet(createRuntimeEndpointAdapterFacet({
- use: "example.validated",
- activate(value) {
- activated += 1;
- if (value.config !== null && typeof value.config === "object" && "bad" in value.config) {
- throw new Error("bad config");
- }
- return { endpoint: endpointPackage(value.instance) };
- },
- }));
-
- await assert.rejects(
- async () => await registry.activateEndpoint("example.validated", { ...context, config: { bad: true } }),
- /bad config/u,
- );
- const activation = await registry.activateEndpoint("example.validated", context);
- assert.equal(activation.endpoint.instance.id, "one");
- assert.equal(activated, 2);
-});
-
-test("a produced facet is recognisable as a Runtime Adapter host facet", () => {
- assert.ok(isRuntimeAdapterHostFacet(endpoint("example.endpoint")));
- assert.equal(isRuntimeAdapterHostFacet({ abi: "something-else" } as never), false);
-});
-
-test("Runtime config readers accept a value or refuse it; they never guess one", () => {
- const config = runtimeConfigObject({ a: "x", n: 2, b: true }, "subject");
- assert.equal(runtimeConfigString(config.a, "a"), "x");
- assert.equal(runtimeConfigPositiveInteger(config.n, "n"), 2);
- assert.equal(runtimeConfigBoolean(config.b, "b"), true);
- // Absence is absence, not a default.
- assert.equal(runtimeConfigString(undefined, "a"), undefined);
- assert.equal(runtimeConfigPositiveInteger(undefined, "n"), undefined);
- assert.equal(runtimeConfigBoolean(undefined, "b"), undefined);
-
- assert.throws(() => runtimeConfigObject([] as never, "subject"), /must be an object/u);
- assert.throws(() => runtimeConfigString(1 as never, "a"), /a/u);
- assert.throws(() => runtimeConfigPositiveInteger(0 as never, "n"), /n/u);
- assert.throws(() => runtimeConfigPositiveInteger(1.5 as never, "n"), /n/u);
- assert.throws(() => runtimeConfigBoolean("true" as never, "b"), /b/u);
- // An unknown key is a misconfiguration, not something to ignore.
- assert.throws(() => runtimeConfigExact(config, ["a", "n"], "subject"), /does not accept b/u);
- assert.doesNotThrow(() => runtimeConfigExact(config, ["a", "n", "b"], "subject"));
-});
diff --git a/packages/runtime/README.md b/packages/runtime/README.md
index bdd130af..fd241d0b 100644
--- a/packages/runtime/README.md
+++ b/packages/runtime/README.md
@@ -6,16 +6,15 @@ The package defines the small ports used by a runtime:
* `BuildStore` keeps one active Build definition and its accepted facts until the Result is saved and active state is removed.
* `OperationStore` keeps asynchronous external work only while the owning Build is active.
-* `PendingBuildStore` owns the short submission transaction before the Build becomes active.
-* `BuildExecutionStore` owns active scheduling facts, opaque Host execution choices, a stop request, the immutable decision, attention and shared capacity reservations.
* `ResourceStore` is the transient byte gateway used during Provider execution.
* `CredentialStore` resolves secrets outside source and build state.
* `RuntimeCommandExecutor` turns the commands regenerated by Core into component or endpoint calls.
-* `LocalBuildScheduler` runs ready commands concurrently while respecting declared resource limits.
+* `InProcessBuildScheduler` runs ready commands concurrently in one process while respecting declared resource limits.
-These contracts do not define historical Build Results or choose a provider or source language. The default local
-implementation lives in `@hypit/runtime-local`; Node component and endpoint execution lives in
-`@hypit/driver-node`.
+These contracts do not define historical Build Results or choose a provider or source language. The
+default local implementation, including submission and active-execution stores, lives in
+`@hypit/runtime-local`; component and endpoint command execution lives in the environment-neutral
+`@hypit/executor`.
The scheduler never changes graph meaning. Targets and candidates are fixed before execution, and
resource limits only control when an already selected command may run.
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index 1554d91f..3f5f59ec 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -8,8 +8,7 @@
".": "./src/index.ts"
},
"dependencies": {
- "@hypit/build-result-kit": "workspace:*",
- "@hypit/core": "workspace:*",
+ "@hypit/kernel": "workspace:*",
"@hypit/protocol": "workspace:*"
}
}
diff --git a/packages/runtime/src/catalog.ts b/packages/runtime/src/catalog.ts
deleted file mode 100644
index d375efb2..00000000
--- a/packages/runtime/src/catalog.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import type {
- LogicalOutputRef,
-} from "@hypit/protocol";
-
-export type BuildPublishedOutput = {
- /** Author-provided display name; the Output identifier remains unchanged. */
- readonly displayName?: string;
- readonly name: string;
- readonly ref: LogicalOutputRef;
-};
-
-export type BuildCatalogDescriptor = {
- readonly source: {
- readonly path: string;
- };
- readonly run?: {
- readonly path: string;
- };
- /** Author-facing targets requested by the Run, including Outputs forwarded outside Core execution. */
- readonly targets?: readonly LogicalOutputRef[];
- readonly publishedOutputs: readonly BuildPublishedOutput[];
-};
-
-export type BuildCatalogEntry = BuildCatalogDescriptor & {
- readonly build: string;
-};
-
-/** Host presentation index only. It is never Build truth. */
-export type BuildCatalog = {
- record(build: string, descriptor: BuildCatalogDescriptor): Promise<BuildCatalogEntry>;
- read(build: string): Promise<BuildCatalogEntry | undefined>;
- /** Result manifests own finished presentation; Runtime Catalog covers active execution only. */
- remove?(build: string): Promise<void>;
-};
diff --git a/packages/runtime/src/credentials.ts b/packages/runtime/src/credentials.ts
index 68f9c6cc..3a29daa2 100644
--- a/packages/runtime/src/credentials.ts
+++ b/packages/runtime/src/credentials.ts
@@ -39,7 +39,7 @@ export function decodeOAuth2Credential(secret: string): OAuth2Credential | undef
return candidate as OAuth2Credential;
}
-/** Host-facing way to acquire one credential; Provider-specific values stay in its Endpoint package. */
+/** Host-facing way to acquire one credential; Provider-specific values stay in its Provider package. */
export type CredentialAcquisition = {
readonly kind: "oauth2-pkce";
readonly authorizationEndpoint: string;
diff --git a/packages/runtime/src/execution.ts b/packages/runtime/src/execution.ts
index 3569d999..854a24b8 100644
--- a/packages/runtime/src/execution.ts
+++ b/packages/runtime/src/execution.ts
@@ -1,113 +1,4 @@
-import type { BuildResultRepositoryLocation } from "@hypit/build-result-kit";
import type { CommandResult } from "@hypit/protocol";
-import type {
- CapacityAcquire,
- CapacityAcquireRequest,
- CapacityReservation,
-} from "./capacity.js";
-
-export type BuildOutcome = "complete" | "failed" | "cancelled";
-
-export type BuildExecutionRequest = {
- readonly build: string;
- /** Host-owned execution choices. Opaque to the graph and Core. */
- readonly context?: import("@hypit/protocol").CanonicalValue;
- /** Installed component packages loaded when this execution context starts. */
- readonly componentPackages: readonly string[];
- /** Exact project Result Repository selected at submission. */
- readonly result: BuildResultRepositoryLocation;
-};
-
-export type BuildExecutionDecision = {
- readonly outcome: BuildOutcome;
- readonly reason?: string;
-};
-
-/** A durable instruction to stop launching work, independent of remote Operation termination. */
-export type BuildExecutionStop = {
- readonly cause: "user-cancelled" | "execution-failed";
- readonly reason?: string;
-};
-
-export type BuildExecutionAttention = {
- readonly step: "result" | "cleanup";
- readonly error: string;
-};
-
-export type BuildExecutionTurn = {
- readonly owner: string;
- readonly acquiredAt: number;
-};
-
-export type BuildResultWriteLease = BuildExecutionTurn;
-
-/**
- * The complete active Runtime root for one Build.
- *
- * It has no persisted lifecycle phase. Scheduling is derived from `wakeAt` and `turn`; the one
- * immutable execution conclusion is `decision`; `stop` records why new work must stop while
- * the Result is written. Operator attention is an independent fact.
- */
-export type BuildExecutionSnapshot = BuildExecutionRequest & {
- readonly createdAt: number;
- /** An execution context has been assigned; losing it ends this attempt. */
- readonly startedAt?: number;
- /** Absent when waiting for a resource release. */
- readonly wakeAt?: number;
- /** Only these Operations can advance the Build until their next outcome. */
- readonly operationWait?: readonly string[];
- readonly turn?: BuildExecutionTurn;
- readonly resultWrite?: BuildResultWriteLease;
- readonly stop?: BuildExecutionStop;
- readonly decision?: BuildExecutionDecision;
- readonly attention?: BuildExecutionAttention;
-};
-
-export type BuildExecutionActivity = "ready" | "running" | "waiting" | "saving-result";
-
-export function buildExecutionActivity(
- execution: BuildExecutionSnapshot,
- now = Date.now(),
-): BuildExecutionActivity {
- if (execution.decision !== undefined) return "saving-result";
- if (execution.turn !== undefined) return "running";
- return execution.wakeAt === undefined || execution.wakeAt > now ? "waiting" : "ready";
-}
-
-/** Ephemeral acknowledgement returned after active Runtime state has been removed. */
-export type BuildCompletion = BuildExecutionDecision & {
- readonly build: string;
-};
-
-export type BuildExecutionStore = {
- create(request: BuildExecutionRequest, options?: { readonly now?: number }): Promise<BuildExecutionSnapshot>;
- read(build: string): Promise<BuildExecutionSnapshot | undefined>;
- list(): Promise<readonly BuildExecutionSnapshot[]>;
- /** Lightweight scheduling views; no Definition, Profile or Operation payloads are loaded. */
- listUnstarted(): Promise<readonly string[]>;
- listReady(now?: number): Promise<readonly string[]>;
- /** Atomically take one ready, undecided execution turn for this Worker owner. */
- claim(owner: string, now?: number, build?: string): Promise<BuildExecutionSnapshot | undefined>;
- start(build: string, now?: number): Promise<BuildExecutionSnapshot>;
- /** Conclude after the owner confirms this execution context has ended. Never repeats external work. */
- interrupt(build: string, reason: string): Promise<BuildExecutionSnapshot>;
- /** An unobserved stop wakes the next turn immediately to finish the attempt. */
- releaseTurn(build: string, owner: string, wakeAt: number | undefined, operationWait?: readonly string[]): Promise<BuildExecutionSnapshot>;
- /** Freeze the one conclusion. An execution with a decision can never be claimed again. */
- decide(build: string, owner: string, outcome: BuildOutcome, reason?: string): Promise<BuildExecutionSnapshot>;
- /** Record the first stop request. Repeated requests cannot replace its cause or reason. */
- requestStop(build: string, stop: BuildExecutionStop): Promise<BuildExecutionSnapshot>;
- setAttention(build: string, attention: BuildExecutionAttention | undefined): Promise<BuildExecutionSnapshot>;
- claimResultWrite(build: string, owner: string, now?: number): Promise<BuildExecutionSnapshot | undefined>;
- releaseResultWrite(build: string, owner: string): Promise<BuildExecutionSnapshot>;
- /** Clear only Result-writer ownership left by the previous Runtime process and record attention. */
- reclaimResultWrites(): Promise<readonly string[]>;
- acquireCapacity(request: CapacityAcquireRequest): Promise<CapacityAcquire>;
- releaseCapacity(build: string, command: string): Promise<void>;
- releaseBuildCapacity(build: string): Promise<void>;
- reclaimActionCapacity(): Promise<void>;
- listCapacity(): Promise<readonly CapacityReservation[]>;
-};
export type CommandExecutionReceipt = {
readonly build: string;
@@ -123,10 +14,7 @@ export type CommandExecutionBegin = {
readonly receipt: CommandExecutionReceipt;
};
-/**
- * Live handoff for commands that complete in one call. It prevents the same Build from invoking
- * an immediate Producer or Endpoint again after the process stops between execution and Core fact.
- */
+/** Live handoff for an immediate command between invocation and the accepted Kernel fact. */
export type CommandExecutionStore = {
begin(build: string, command: string): Promise<CommandExecutionBegin>;
reportProgress(build: string, command: string, activity: NonNullable<CommandExecutionReceipt["activity"]>): Promise<void>;
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index f1e663ef..50fe35a2 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,5 +1,3 @@
-export { plannedNeeds } from "@hypit/core";
-export type * from "./catalog.js";
export {
CompositeCredentialStore,
credentialRef,
@@ -12,11 +10,9 @@ export {
export type * from "./credentials.js";
export type * from "./capacity.js";
export { capacityUnits } from "./capacity.js";
-export { buildExecutionActivity } from "./execution.js";
export type * from "./execution.js";
export type * from "./operations.js";
-export { LocalBuildScheduler } from "./scheduler.js";
-export type * from "./submission.js";
+export { InProcessBuildScheduler } from "./scheduler.js";
export {
isStreamingResourceStore,
} from "./types.js";
diff --git a/packages/runtime/src/scheduler.ts b/packages/runtime/src/scheduler.ts
index ef973c2e..89884ed8 100644
--- a/packages/runtime/src/scheduler.ts
+++ b/packages/runtime/src/scheduler.ts
@@ -1,4 +1,4 @@
-import { BuildMachine, reduce } from "@hypit/core";
+import { BuildMachine, reduce } from "@hypit/kernel";
import type { BuildState, CommandResult } from "@hypit/protocol";
import { capacityUnits } from "./capacity.js";
@@ -51,7 +51,7 @@ function buildCommandKey(build: string, command: string): string {
* across all submitted Builds,
* but never searches a Graph: every runnable command is regenerated by Core through the Executor.
*/
-export class LocalBuildScheduler {
+export class InProcessBuildScheduler {
readonly #executor: RuntimeCommandExecutor;
readonly #buildStore: BuildSchedulerOptions["buildStore"];
readonly #onStateChange: BuildSchedulerOptions["onStateChange"];
diff --git a/packages/runtime/src/submission.ts b/packages/runtime/src/submission.ts
deleted file mode 100644
index 12ab235e..00000000
--- a/packages/runtime/src/submission.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import type { BuildDefinition } from "@hypit/protocol";
-import type { BuildCatalogDescriptor } from "./catalog.js";
-import type { BuildExecutionRequest, BuildExecutionSnapshot } from "./execution.js";
-
-export type PendingBuildSubmission = BuildExecutionRequest & {
- readonly createdAt: number;
-};
-
-export type PendingBuildCommit = BuildExecutionRequest & {
- readonly definition: BuildDefinition;
- readonly catalog: BuildCatalogDescriptor;
-};
-
-/**
- * One exact cross-store submission transaction. A pending submission is not schedulable and can
- * only become active execution or be explicitly discarded with its Result draft and temporary resources.
- */
-export type PendingBuildStore = {
- prepare(request: BuildExecutionRequest, options?: { readonly now?: number }): Promise<PendingBuildSubmission>;
- read(build: string): Promise<PendingBuildSubmission | undefined>;
- list(): Promise<readonly PendingBuildSubmission[]>;
- commit(request: PendingBuildCommit): Promise<BuildExecutionSnapshot>;
- discard(build: string): Promise<void>;
-};
diff --git a/packages/runtime/src/types.ts b/packages/runtime/src/types.ts
index 9b5b9c07..a79d8c4d 100644
--- a/packages/runtime/src/types.ts
+++ b/packages/runtime/src/types.ts
@@ -4,7 +4,7 @@ import type {
BuildFact,
BuildState,
CommandResult,
- CoreCommand,
+ BuildCommand,
ResourceId,
} from "@hypit/protocol";
import type { OperationSnapshot } from "./operations.js";
@@ -16,7 +16,7 @@ export type RuntimeBlockedCommand = {
};
export type RuntimeRunnableCommand = {
- readonly command: CoreCommand;
+ readonly command: BuildCommand;
/** Every resource is acquired atomically before the command can cause a side effect. */
readonly resources: readonly RuntimeResourceClaim[];
/** Asynchronous work retains one shared in-flight reservation while polling. */
@@ -60,7 +60,7 @@ export type RuntimeExecutionResult =
/** Build-local indexed execution view. Definition + Facts remain the only durable representation. */
export type RuntimeBuildExecution = {
view(): BuildState;
- commands(): readonly CoreCommand[];
+ commands(): readonly BuildCommand[];
record(id: string): import("@hypit/protocol").TypedRecord | undefined;
};
@@ -145,7 +145,7 @@ export type ScheduledBuild =
export type SchedulerExecutionOutcome = {
readonly command: string;
- readonly kind: CoreCommand["kind"];
+ readonly kind: BuildCommand["kind"];
readonly resources: readonly string[];
readonly status: "completed" | "pending" | "deferred" | "error";
readonly operation?: string;
diff --git a/packages/source/README.md b/packages/source/README.md
index 4cb0d300..f5310438 100644
--- a/packages/source/README.md
+++ b/packages/source/README.md
@@ -1,13 +1,18 @@
# `@hypit/source`
-The smallest source bootstrap shared by Author and Run compilation.
+The byte-oriented Source contract shared by Author and Run compilation.
-It recognizes exactly one mandatory bounded Header:
+`SourceUnit` contains opaque bytes and Workspace-canonical identity. `ResolvedSource` pairs those
+bytes with the exact trusted Frontend selected by the caller, Workspace mount or package Source
+export. Source itself never guesses from a suffix or body and has no default parser.
+
+`@hypit/source/text` is the optional adapter used by Hypit's self-described UTF-8 author files. It
+recognizes one bounded Header such as:
```xml
<?svml using="@hypit/markup@1"?>
```
-The Header selects an exact trusted Frontend. There is no suffix dispatch and no default parser.
-The package masks the Header while preserving UTF-16 source offsets and line breaks, but does not recognize imports,
-XML, Script, Recipes, Run syntax or domain Types. Those belong to the selected Frontend.
+The adapter masks the Header while preserving UTF-16 offsets and line breaks. Other Workspaces can
+produce `ResolvedSource` directly and need not use text or a Header. Neither entry recognizes
+imports, XML, Script, Recipes, Run syntax or domain Types; those belong to the selected Frontend.
diff --git a/packages/source/package.json b/packages/source/package.json
index 8f4b60e5..9367cb7a 100644
--- a/packages/source/package.json
+++ b/packages/source/package.json
@@ -5,7 +5,8 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./text": "./src/header.ts"
},
"dependencies": {
"@hypit/protocol": "workspace:*"
diff --git a/packages/source/src/header.ts b/packages/source/src/header.ts
index 061edbaf..e952194f 100644
--- a/packages/source/src/header.ts
+++ b/packages/source/src/header.ts
@@ -79,3 +79,20 @@ export function maskSourceHeader(text: string, header: SourceHeader): string {
const prefix = text.slice(0, header.end).replace(/[^\r\n]/g, " ");
return `${prefix}${text.slice(header.end)}`;
}
+
+/** Optional adapter for Hypit's self-described UTF-8 author-file convention. */
+export function resolveSelfDescribedTextSource(input: {
+ readonly id: string;
+ readonly name: string;
+ readonly text: string;
+}): import("./unit.js").ResolvedSource {
+ const header = parseSourceHeader(input.name, input.text);
+ return {
+ frontend: header.using,
+ unit: {
+ id: input.id,
+ name: input.name,
+ bytes: new TextEncoder().encode(maskSourceHeader(input.text, header)),
+ },
+ };
+}
diff --git a/packages/source/src/index.ts b/packages/source/src/index.ts
index 2d21762f..4ddac878 100644
--- a/packages/source/src/index.ts
+++ b/packages/source/src/index.ts
@@ -1,17 +1,13 @@
-export {
- maskSourceHeader,
- parseSourceHeader,
- SourceHeaderError,
-} from "./header.js";
-export type { SourceHeader } from "./header.js";
export type {
Awaitable,
ResolvedSourceAsset,
+ ResolvedSource,
SourceAssetRequest,
SourceAssetResolver,
SourceImportRequest,
SourceResolver,
SourceUnit,
} from "./unit.js";
-/** Logical package address for Source Frontends selected by a Source Header. */
+export { decodeSourceText } from "./unit.js";
+/** Logical package address for Frontend facets selected by a ResolvedSource authority. */
export const sourceFrontendPackageAbi = "hypit.source-frontend@1";
diff --git a/packages/source/src/unit.ts b/packages/source/src/unit.ts
index 06754fa8..ac69d25c 100644
--- a/packages/source/src/unit.ts
+++ b/packages/source/src/unit.ts
@@ -1,10 +1,17 @@
import type { BlobRef, SourceRange } from "@hypit/protocol";
export type SourceUnit = {
- /** Host-canonical identity used only for recursion and diagnostics. */
+ /** Workspace-canonical identity used only for recursion and diagnostics. */
readonly id: string;
readonly name: string;
- readonly text: string;
+ /** Opaque source payload. Its selected Frontend alone decides how to decode it. */
+ readonly bytes: Uint8Array;
+};
+
+/** A Workspace resolution. The Frontend choice is explicit and never guessed by the compiler. */
+export type ResolvedSource = {
+ readonly unit: SourceUnit;
+ readonly frontend: string;
};
export type SourceImportRequest = {
@@ -16,7 +23,7 @@ export type SourceImportRequest = {
export type SourceAssetRequest = {
readonly from: string;
readonly mediaType: string;
- /** Package-owned bytes admitted by the compiler before a Workspace is consulted. */
+ /** Package-owned bytes handed to the Workspace for identity and attachment ownership. */
readonly bytes?: Uint8Array;
readonly range?: SourceRange;
};
@@ -30,9 +37,16 @@ export type Awaitable<T> = T | Promise<T>;
export type SourceResolver = (
importer: SourceUnit,
request: SourceImportRequest,
-) => Awaitable<SourceUnit>;
+) => Awaitable<ResolvedSource>;
export type SourceAssetResolver = (
importer: SourceUnit,
request: SourceAssetRequest,
) => Awaitable<ResolvedSourceAsset>;
+
+const utf8 = new TextDecoder("utf-8", { fatal: true });
+
+/** Explicit adapter for textual Frontends; Source itself remains byte-oriented. */
+export function decodeSourceText(source: SourceUnit): string {
+ return utf8.decode(source.bytes);
+}
diff --git a/packages/source/test/header.test.ts b/packages/source/test/text.test.ts
similarity index 92%
rename from packages/source/test/header.test.ts
rename to packages/source/test/text.test.ts
index 9647b186..3e46980d 100644
--- a/packages/source/test/header.test.ts
+++ b/packages/source/test/text.test.ts
@@ -5,7 +5,7 @@ import {
maskSourceHeader,
parseSourceHeader,
SourceHeaderError,
-} from "@hypit/source";
+} from "@hypit/source/text";
test("Source Header explicitly selects one Frontend and masking preserves offsets", () => {
const text = '<?svml using="@hypit/markup@1"?>\n\n<svml/>\n';
@@ -28,8 +28,8 @@ test("Header masking preserves UTF-16 offsets for a non-BMP Frontend request", (
test("Source Header accepts a UTF-8 BOM but no implicit or duplicate Frontend", () => {
assert.equal(
- parseSourceHeader("bom.svs", '\ufeff<?svml using="@hypit/svs@1"?>\n<sheet/>').using,
- "@hypit/svs@1",
+ parseSourceHeader("bom.svs", '\ufeff<?svml using="@hypit/recipe@1"?>\n<sheet/>').using,
+ "@hypit/recipe@1",
);
assert.throws(
() => parseSourceHeader("missing.svml", "<svml/>"),
diff --git a/packages/workspace-fs-node/README.md b/packages/workspace-fs-node/README.md
deleted file mode 100644
index ddab1a81..00000000
--- a/packages/workspace-fs-node/README.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# `@hypit/workspace-fs-node`
-
-Reference Node filesystem implementation of the host-neutral `Workspace` contract.
-
-Every `open()` call creates one isolated compilation session. It canonicalizes real paths, confines
-local SourceUnit and Source Asset reads to the configured root, rejects symlink escapes, locks each
-Source edge to the first bytes observed and returns defensive Resource attachments. File attachments
-also carry their resolved `file:` URI so Result publication can preserve the external reference.
-The Resource's identity and metadata belong to the compilation session; its file remains a live
-dependency rather than becoming a persistent snapshot.
-
-A Host may supply an external Source resolver. One explicit non-relative Source locator can then
-open a SourceUnit in a separate canonical root; that Source's relative imports and assets remain
-inside its own root instead of inheriting project filesystem authority. The resolver returns a
-locator and a root—it does not widen either root or grant executable-package authority. This
-adapter itself contains no Frontend, package-manager, Core, Runtime, Provider or domain knowledge.
diff --git a/packages/workspace-fs-node/test/workspace.test.ts b/packages/workspace-fs-node/test/workspace.test.ts
deleted file mode 100644
index 02200dae..00000000
--- a/packages/workspace-fs-node/test/workspace.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import assert from "node:assert/strict";
-import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import test from "node:test";
-
-import { WorkspaceError } from "@hypit/workspace";
-import { NodeFilesystemWorkspace } from "../src/index.js";
-
-test("an in-root Source whose basename starts with .. is admitted", async () => {
- const parent = await mkdtemp(join(tmpdir(), "hypit-workspace-dotdot-name-"));
- const root = join(parent, "project");
- try {
- await mkdir(root);
- const entryPath = join(root, "..keep.svml");
- await writeFile(entryPath, "inside", "utf8");
- await writeFile(join(parent, "outside.svs"), "outside", "utf8");
- const session = await new NodeFilesystemWorkspace({ root }).open(entryPath);
- assert.equal(session.entry.text, "inside");
- await assert.rejects(
- async () => await session.resolveSource(session.entry, { from: "../outside.svs", alias: "escaped" }),
- (error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
- );
- await symlink(parent, join(root, "..linked"), "junction");
- await assert.rejects(
- async () => await session.resolveSource(session.entry, { from: "./..linked/outside.svs", alias: "linked" }),
- (error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
- );
- } finally {
- await rm(parent, { recursive: true, force: true });
- }
-});
diff --git a/packages/workspace/package.json b/packages/workspace/package.json
index d4a155ab..93de36d3 100644
--- a/packages/workspace/package.json
+++ b/packages/workspace/package.json
@@ -5,7 +5,8 @@
"private": true,
"type": "module",
"exports": {
- ".": "./src/index.ts"
+ ".": "./src/index.ts",
+ "./node": "./src/node/index.ts"
},
"dependencies": {
"@hypit/protocol": "workspace:*",
diff --git a/packages/workspace/src/index.ts b/packages/workspace/src/index.ts
index 42d99a83..5e896f74 100644
--- a/packages/workspace/src/index.ts
+++ b/packages/workspace/src/index.ts
@@ -2,12 +2,12 @@ import type {
Awaitable,
SourceAssetResolver,
SourceResolver,
- SourceUnit,
+ ResolvedSource,
} from "@hypit/source";
import type { BlobRef } from "@hypit/protocol";
/** Repeatably openable transfer bytes admitted by the selected Workspace. */
-export type ArtifactAttachment = {
+export type BlobAttachment = {
readonly artifact: BlobRef;
/** Stable external address, when the Workspace supplies a file by reference. */
readonly location?: string;
@@ -16,10 +16,10 @@ export type ArtifactAttachment = {
/** One isolated, read-once definition session for exactly one compilation. */
export interface WorkspaceSession {
- readonly entry: SourceUnit;
+ readonly entry: ResolvedSource;
readonly resolveSource: SourceResolver;
readonly resolveAsset: SourceAssetResolver;
- attachments(): Awaitable<readonly ArtifactAttachment[]>;
+ attachments(): Awaitable<readonly BlobAttachment[]>;
}
/** Replaceable definition environment: filesystem, browser, Git, memory or remote workspace. */
diff --git a/packages/workspace-fs-node/src/index.ts b/packages/workspace/src/node/index.ts
similarity index 66%
rename from packages/workspace-fs-node/src/index.ts
rename to packages/workspace/src/node/index.ts
index d25ff151..0590d6bc 100644
--- a/packages/workspace-fs-node/src/index.ts
+++ b/packages/workspace/src/node/index.ts
@@ -1,6 +1,9 @@
export { NodeFilesystemWorkspace } from "./workspace.js";
export type {
+ NodeFilesystemExternalAsset,
+ NodeFilesystemExternalAssetResolver,
NodeFilesystemExternalSource,
NodeFilesystemExternalSourceResolver,
+ NodeFilesystemSourceAdapter,
NodeFilesystemWorkspaceOptions,
} from "./workspace.js";
diff --git a/packages/workspace-fs-node/src/workspace.ts b/packages/workspace/src/node/workspace.ts
similarity index 62%
rename from packages/workspace-fs-node/src/workspace.ts
rename to packages/workspace/src/node/workspace.ts
index 67757f0b..4694754a 100644
--- a/packages/workspace-fs-node/src/workspace.ts
+++ b/packages/workspace/src/node/workspace.ts
@@ -6,16 +6,18 @@ import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path
import type {
Awaitable,
+ ResolvedSource,
SourceAssetRequest,
SourceImportRequest,
SourceUnit,
} from "@hypit/source";
+import { resolveSelfDescribedTextSource } from "@hypit/source/text";
import type {
- ArtifactAttachment,
+ BlobAttachment,
Workspace,
WorkspaceSession,
-} from "@hypit/workspace";
-import { WorkspaceError } from "@hypit/workspace";
+} from "../index.js";
+import { WorkspaceError } from "../index.js";
import type { BlobRef } from "@hypit/protocol";
function isWithin(root: string, path: string): boolean {
@@ -26,6 +28,8 @@ function isWithin(root: string, path: string): boolean {
export type NodeFilesystemExternalSource = {
readonly root: string;
readonly source: string;
+ /** Optional explicit override for sources that are not self-described text. */
+ readonly frontend?: string;
};
export type NodeFilesystemExternalSourceResolver = (
@@ -33,31 +37,55 @@ export type NodeFilesystemExternalSourceResolver = (
request: SourceImportRequest,
) => Awaitable<NodeFilesystemExternalSource>;
+export type NodeFilesystemExternalAsset = {
+ readonly root: string;
+ readonly asset: string;
+};
+
+export type NodeFilesystemExternalAssetResolver = (
+ importer: SourceUnit,
+ request: SourceAssetRequest,
+) => Awaitable<NodeFilesystemExternalAsset>;
+
+export type NodeFilesystemSourceAdapter = (
+ source: SourceUnit,
+) => Awaitable<ResolvedSource>;
+
+const utf8 = new TextDecoder("utf-8", { fatal: true });
+const selfDescribedTextSource: NodeFilesystemSourceAdapter = (source) =>
+ resolveSelfDescribedTextSource({ ...source, text: utf8.decode(source.bytes) });
+
class NodeFilesystemWorkspaceSession implements WorkspaceSession {
readonly root: string;
- readonly entry: SourceUnit;
+ readonly entry: ResolvedSource;
readonly #assetRoots: readonly string[];
readonly #externalSourceResolver: NodeFilesystemExternalSourceResolver | undefined;
+ readonly #externalAssetResolver: NodeFilesystemExternalAssetResolver | undefined;
+ readonly #sourceAdapter: NodeFilesystemSourceAdapter;
readonly #sourceCache = new Map<string, SourceUnit>();
readonly #sourceRoots = new Map<string, string>();
readonly #assetIdentity = new Map<string, {
readonly resource: BlobRef["resource"];
readonly size: number;
}>();
- readonly #attachments = new Map<string, ArtifactAttachment>();
+ readonly #attachments = new Map<string, BlobAttachment>();
private constructor(
root: string,
- entry: SourceUnit,
+ entry: ResolvedSource,
assetRoots: readonly string[],
externalSourceResolver: NodeFilesystemExternalSourceResolver | undefined,
+ externalAssetResolver: NodeFilesystemExternalAssetResolver | undefined,
+ sourceAdapter: NodeFilesystemSourceAdapter,
) {
this.root = root;
this.entry = entry;
this.#assetRoots = assetRoots;
this.#externalSourceResolver = externalSourceResolver;
- this.#sourceCache.set(entry.id, entry);
- this.#sourceRoots.set(entry.id, root);
+ this.#externalAssetResolver = externalAssetResolver;
+ this.#sourceAdapter = sourceAdapter;
+ this.#sourceCache.set(entry.unit.id, entry.unit);
+ this.#sourceRoots.set(entry.unit.id, root);
}
static async open(
@@ -65,6 +93,8 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
entryLocator: string,
assetRootLocators: readonly string[],
externalSourceResolver: NodeFilesystemExternalSourceResolver | undefined,
+ externalAssetResolver: NodeFilesystemExternalAssetResolver | undefined,
+ sourceAdapter: NodeFilesystemSourceAdapter,
): Promise<NodeFilesystemWorkspaceSession> {
const root = await realpath(resolve(rootLocator));
const assetRoots = await Promise.all(assetRootLocators.map(async (path) => await realpath(resolve(path))));
@@ -76,12 +106,20 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
canonicalEntry,
);
}
- const entry: SourceUnit = {
+ const entryUnit: SourceUnit = {
id: canonicalEntry,
name: relative(root, canonicalEntry) || basename(canonicalEntry) || canonicalEntry,
- text: await readFile(canonicalEntry, "utf8"),
+ bytes: await readFile(canonicalEntry),
};
- return new NodeFilesystemWorkspaceSession(root, entry, [root, ...assetRoots], externalSourceResolver);
+ const entry = await sourceAdapter(entryUnit);
+ return new NodeFilesystemWorkspaceSession(
+ root,
+ entry,
+ [root, ...assetRoots],
+ externalSourceResolver,
+ externalAssetResolver,
+ sourceAdapter,
+ );
}
async #loadSource(path: string, sourceRootLocator: string): Promise<SourceUnit> {
@@ -109,7 +147,7 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
const unit: SourceUnit = {
id: canonical,
name: relative(sourceRoot, canonical) || basename(canonical) || canonical,
- text: await readFile(canonical, "utf8"),
+ bytes: await readFile(canonical),
};
this.#sourceCache.set(canonical, unit);
this.#sourceRoots.set(canonical, sourceRoot);
@@ -119,13 +157,14 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
readonly resolveSource = async (
importer: SourceUnit,
request: SourceImportRequest,
- ): Promise<SourceUnit> => {
+ ): Promise<ResolvedSource> => {
const importerRoot = this.#sourceRoots.get(importer.id);
if (importerRoot === undefined) {
throw new WorkspaceError("UNKNOWN_SOURCE_IMPORTER", `${importer.id} is outside this Workspace`, importer.id);
}
if (request.from.startsWith("./") || request.from.startsWith("../")) {
- return await this.#loadSource(resolve(dirname(importer.id), request.from), importerRoot);
+ const unit = await this.#loadSource(resolve(dirname(importer.id), request.from), importerRoot);
+ return await this.#sourceAdapter(unit);
}
if (this.#externalSourceResolver === undefined) {
throw new WorkspaceError(
@@ -135,26 +174,53 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
);
}
const external = await this.#externalSourceResolver(importer, request);
- return await this.#loadSource(external.source, external.root);
+ const unit = await this.#loadSource(external.source, external.root);
+ return external.frontend === undefined
+ ? await this.#sourceAdapter(unit)
+ : { unit, frontend: external.frontend };
};
readonly resolveAsset = async (
importer: SourceUnit,
request: SourceAssetRequest,
) => {
- if (!request.from.startsWith("./") && !request.from.startsWith("../")) {
- throw new WorkspaceError(
- "UNSUPPORTED_SOURCE_ASSET",
- `Source asset ${request.from} must be relative`,
- request.from,
- );
- }
const importerRoot = this.#sourceRoots.get(importer.id);
if (importerRoot === undefined) {
throw new WorkspaceError("UNKNOWN_SOURCE_IMPORTER", `${importer.id} is outside this Workspace`, importer.id);
}
- const canonical = await realpath(resolve(dirname(importer.id), request.from));
- const allowedRoots = importerRoot === this.root ? this.#assetRoots : [importerRoot];
+ if (request.bytes !== undefined) {
+ const bytes = Uint8Array.from(request.bytes);
+ const artifact: BlobRef = {
+ kind: "blob",
+ resource: `res_${randomUUID()}`,
+ size: bytes.byteLength,
+ mediaType: request.mediaType,
+ };
+ this.#attachments.set(`${artifact.resource}\u0000${artifact.mediaType}`, {
+ artifact: { ...artifact },
+ open: async () => (async function* () { yield Uint8Array.from(bytes); })(),
+ });
+ return { artifact };
+ }
+ const relativeAsset = request.from.startsWith("./") || request.from.startsWith("../");
+ let canonical: string;
+ let allowedRoots: readonly string[];
+ if (relativeAsset) {
+ canonical = await realpath(resolve(dirname(importer.id), request.from));
+ allowedRoots = importerRoot === this.root ? this.#assetRoots : [importerRoot];
+ } else {
+ if (this.#externalAssetResolver === undefined) {
+ throw new WorkspaceError(
+ "UNSUPPORTED_SOURCE_ASSET",
+ `Source asset ${request.from} has no resolver in this Workspace`,
+ request.from,
+ );
+ }
+ const external = await this.#externalAssetResolver(importer, request);
+ const externalRoot = await realpath(resolve(external.root));
+ canonical = await realpath(resolve(external.asset));
+ allowedRoots = [externalRoot];
+ }
if (!allowedRoots.some((root) => isWithin(root, canonical))) {
throw new WorkspaceError(
"SOURCE_ASSET_OUTSIDE_ROOT",
@@ -185,7 +251,7 @@ class NodeFilesystemWorkspaceSession implements WorkspaceSession {
return { artifact: { ...artifact } };
};
- attachments(): readonly ArtifactAttachment[] {
+ attachments(): readonly BlobAttachment[] {
return [...this.#attachments.values()]
.sort((left, right) => {
const byResource = left.artifact.resource.localeCompare(right.artifact.resource);
@@ -202,6 +268,10 @@ export type NodeFilesystemWorkspaceOptions = {
readonly assetRoots?: readonly string[];
/** Host-owned resolver for explicit non-relative Source locators, each with its own read boundary. */
readonly externalSourceResolver?: NodeFilesystemExternalSourceResolver;
+ /** Host-owned resolver for explicit non-relative asset locators, each with its own read boundary. */
+ readonly externalAssetResolver?: NodeFilesystemExternalAssetResolver;
+ /** Selects a Frontend for each admitted Source. Defaults to the legacy self-described text adapter. */
+ readonly sourceAdapter?: NodeFilesystemSourceAdapter;
};
/** Node filesystem implementation of the host-neutral, one-compilation Workspace contract. */
@@ -209,11 +279,15 @@ export class NodeFilesystemWorkspace implements Workspace {
readonly #root: string | undefined;
readonly #assetRoots: readonly string[];
readonly #externalSourceResolver: NodeFilesystemExternalSourceResolver | undefined;
+ readonly #externalAssetResolver: NodeFilesystemExternalAssetResolver | undefined;
+ readonly #sourceAdapter: NodeFilesystemSourceAdapter;
constructor(options: NodeFilesystemWorkspaceOptions = {}) {
this.#root = options.root;
this.#assetRoots = options.assetRoots ?? [];
this.#externalSourceResolver = options.externalSourceResolver;
+ this.#externalAssetResolver = options.externalAssetResolver;
+ this.#sourceAdapter = options.sourceAdapter ?? selfDescribedTextSource;
}
async open(entryLocator: string): Promise<WorkspaceSession> {
@@ -223,6 +297,8 @@ export class NodeFilesystemWorkspace implements Workspace {
entry,
this.#assetRoots,
this.#externalSourceResolver,
+ this.#externalAssetResolver,
+ this.#sourceAdapter,
);
}
}
diff --git a/packages/workspace/test/node/workspace.test.ts b/packages/workspace/test/node/workspace.test.ts
new file mode 100644
index 00000000..852b35ea
--- /dev/null
+++ b/packages/workspace/test/node/workspace.test.ts
@@ -0,0 +1,65 @@
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+
+import { WorkspaceError } from "@hypit/workspace";
+import { NodeFilesystemWorkspace } from "../../src/node/index.js";
+import { decodeSourceText } from "@hypit/source";
+
+const rawSourceAdapter = (unit: import("@hypit/source").SourceUnit) => ({ unit, frontend: "test.frontend@1" });
+
+test("an in-root Source whose basename starts with .. is admitted", async () => {
+ const parent = await mkdtemp(join(tmpdir(), "hypit-workspace-dotdot-name-"));
+ const root = join(parent, "project");
+ try {
+ await mkdir(root);
+ const entryPath = join(root, "..keep.svml");
+ await writeFile(entryPath, "inside", "utf8");
+ await writeFile(join(parent, "outside.svs"), "outside", "utf8");
+ const session = await new NodeFilesystemWorkspace({ root, sourceAdapter: rawSourceAdapter }).open(entryPath);
+ assert.equal(decodeSourceText(session.entry.unit), "inside");
+ await assert.rejects(
+ async () => await session.resolveSource(session.entry.unit, { from: "../outside.svs", alias: "escaped" }),
+ (error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
+ );
+ await symlink(parent, join(root, "..linked"), "junction");
+ await assert.rejects(
+ async () => await session.resolveSource(session.entry.unit, { from: "./..linked/outside.svs", alias: "linked" }),
+ (error: unknown) => error instanceof WorkspaceError && error.code === "SOURCE_OUTSIDE_ROOT",
+ );
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});
+
+test("a Host-resolved package asset stays inside the resolver's explicit root", async () => {
+ const parent = await mkdtemp(join(tmpdir(), "hypit-workspace-package-asset-"));
+ const project = join(parent, "project");
+ const installed = join(parent, "installed-font");
+ try {
+ await mkdir(project);
+ await mkdir(join(installed, "files"), { recursive: true });
+ const entryPath = join(project, "main.svml");
+ const fontPath = join(installed, "files", "brand.woff2");
+ await writeFile(entryPath, "source", "utf8");
+ await writeFile(fontPath, "font bytes", "utf8");
+ const session = await new NodeFilesystemWorkspace({
+ root: project,
+ sourceAdapter: rawSourceAdapter,
+ externalAssetResolver(_importer, request) {
+ assert.equal(request.from, "package:@acme/brand-fonts/files/brand.woff2");
+ return { root: installed, asset: fontPath };
+ },
+ }).open(entryPath);
+ const resolved = await session.resolveAsset(session.entry.unit, {
+ from: "package:@acme/brand-fonts/files/brand.woff2",
+ mediaType: "font/woff2",
+ });
+ assert.equal(resolved.artifact.mediaType, "font/woff2");
+ assert.equal((await session.attachments()).length, 1);
+ } finally {
+ await rm(parent, { recursive: true, force: true });
+ }
+});