From 265e014719a0ca370244b3eadf169ce2a5fcd6e2 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 12 Oct 2026 21:03:23 +0200 Subject: [PATCH 01/22] feat: add typed HashQL TypeScript SDK --- libs/@local/hashql/sdk/typescript/README.md | 154 +++- .../hashql/sdk/typescript/docs/authoring.md | 739 ++++++++++++++++++ .../__snapshots__/filters.test.ts.snap | 393 ++++++++++ .../typescript/examples/api-tour.test-d.ts | 494 ++++++++++++ .../sdk/typescript/examples/filters.test.ts | 110 +++ .../hashql/sdk/typescript/examples/filters.ts | 378 +++++++++ .../@local/hashql/sdk/typescript/package.json | 7 +- .../sdk/typescript/src/internal/array.ts | 11 + .../sdk/typescript/src/internal/scan.ts | 159 ++++ .../src/internal/schema-arbitrary.ts | 57 ++ .../hashql/sdk/typescript/src/jexpr/Call.ts | 45 ++ .../hashql/sdk/typescript/src/jexpr/Dict.ts | 56 ++ .../hashql/sdk/typescript/src/jexpr/Float.ts | 45 ++ .../sdk/typescript/src/jexpr/Function.ts | 87 +++ .../hashql/sdk/typescript/src/jexpr/Ident.ts | 131 ++++ .../sdk/typescript/src/jexpr/Identifier.ts | 48 ++ .../sdk/typescript/src/jexpr/Integer.ts | 54 ++ .../typescript/src/jexpr/LabeledArgument.ts | 48 ++ .../hashql/sdk/typescript/src/jexpr/List.ts | 45 ++ .../sdk/typescript/src/jexpr/Literal.ts | 46 ++ .../hashql/sdk/typescript/src/jexpr/Path.ts | 109 +++ .../hashql/sdk/typescript/src/jexpr/Struct.ts | 45 ++ .../hashql/sdk/typescript/src/jexpr/Tuple.ts | 45 ++ .../sdk/typescript/src/jexpr/compile.ts | 153 ++++ .../hashql/sdk/typescript/src/jexpr/index.ts | 444 +++++++++++ .../hashql/sdk/typescript/src/jexpr/schema.ts | 263 +++++++ .../src/jexpr/type/Expression.test.ts | 80 ++ .../sdk/typescript/src/jexpr/type/Generic.ts | 61 ++ .../src/jexpr/type/GenericArgument.ts | 31 + .../typescript/src/jexpr/type/GenericBound.ts | 31 + .../typescript/src/jexpr/type/Intersection.ts | 31 + .../typescript/src/jexpr/type/Reference.ts | 29 + .../sdk/typescript/src/jexpr/type/Struct.ts | 28 + .../sdk/typescript/src/jexpr/type/Tuple.ts | 28 + .../sdk/typescript/src/jexpr/type/Union.ts | 28 + .../sdk/typescript/src/jexpr/type/index.ts | 462 +++++++++++ .../sdk/typescript/src/jexpr/type/schema.ts | 136 ++++ libs/@local/hashql/sdk/typescript/src/main.ts | 11 +- .../sdk/typescript/src/playground.test-d.ts | 247 ++++++ .../sdk/typescript/src/playground.test.ts | 202 +++++ .../hashql/sdk/typescript/src/playground.ts | 134 ++++ .../hashql/sdk/typescript/src/program/Do.ts | 201 +++++ .../src/program/Expression.test-d.ts | 428 ++++++++++ .../typescript/src/program/Expression.test.ts | 148 ++++ .../sdk/typescript/src/program/Expression.ts | 342 ++++++++ .../typescript/src/program/ExpressionType.ts | 361 +++++++++ .../typescript/src/program/Fluent.test-d.ts | 69 ++ .../sdk/typescript/src/program/Fluent.test.ts | 105 +++ .../sdk/typescript/src/program/Fluent.ts | 100 +++ .../typescript/src/program/Import.test-d.ts | 91 +++ .../sdk/typescript/src/program/Import.test.ts | 217 +++++ .../typescript/src/program/Inputs.test-d.ts | 314 ++++++++ .../sdk/typescript/src/program/Inputs.test.ts | 64 ++ .../sdk/typescript/src/program/Inputs.ts | 55 ++ .../typescript/src/program/Module.test-d.ts | 219 ++++++ .../sdk/typescript/src/program/Module.test.ts | 302 +++++++ .../sdk/typescript/src/program/Module.ts | 275 +++++++ .../src/program/Primitive.test-d.ts | 229 ++++++ .../typescript/src/program/Primitive.test.ts | 131 ++++ .../typescript/src/program/Program.test-d.ts | 204 +++++ .../typescript/src/program/Program.test.ts | 433 ++++++++++ .../typescript/src/program/ProgramError.ts | 59 ++ .../sdk/typescript/src/program/Query.ts | 171 ++++ .../typescript/src/program/TypeExpression.ts | 145 ++++ .../sdk/typescript/src/program/Utilities.ts | 270 +++++++ .../sdk/typescript/src/program/ast/Binding.ts | 24 + .../sdk/typescript/src/program/ast/Expr.ts | 14 + .../sdk/typescript/src/program/ast/If.ts | 23 + .../sdk/typescript/src/program/ast/Import.ts | 24 + .../sdk/typescript/src/program/ast/Let.ts | 23 + .../sdk/typescript/src/program/ast/Newtype.ts | 24 + .../sdk/typescript/src/program/ast/Node.ts | 5 + .../sdk/typescript/src/program/ast/Type.ts | 24 + .../sdk/typescript/src/program/ast/index.ts | 8 + .../sdk/typescript/src/program/index.ts | 85 ++ .../sdk/typescript/src/program/ir/Import.ts | 153 ++++ .../sdk/typescript/src/program/ir/Let.ts | 57 ++ .../sdk/typescript/src/program/ir/Newtype.ts | 79 ++ .../sdk/typescript/src/program/ir/Node.ts | 58 ++ .../sdk/typescript/src/program/ir/Scope.ts | 65 ++ .../sdk/typescript/src/program/ir/Type.ts | 57 ++ .../sdk/typescript/src/program/ir/index.ts | 6 + .../sdk/typescript/src/type/index.test-d.ts | 187 +++++ .../hashql/sdk/typescript/src/type/index.ts | 248 ++++++ .../hashql/sdk/typescript/tsconfig.json | 2 +- yarn.config.cjs | 2 +- yarn.lock | 221 +++++- 87 files changed, 12018 insertions(+), 9 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/docs/authoring.md create mode 100644 libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap create mode 100644 libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/internal/array.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/internal/scan.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/List.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/playground.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/playground.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/playground.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Do.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Expression.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Fluent.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Import.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Inputs.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Module.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Module.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Program.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Query.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Utilities.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/If.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ast/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/type/index.ts diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 2d836a0eb64..81397e461b5 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -1,3 +1,153 @@ -# HashQL TypeScript SDK +# HashQL SDK -TypeScript SDK for HashQL. +The SDK constructs HashQL query syntax. TypeScript checks the authoring API. The HashQL compiler resolves names and checks the emitted program. `JExpr` provides the low-level expression builders and serializer. Construction does not execute the query. + +Start with the [authoring guide](docs/authoring.md). It provides a complete construction example, focused API examples and rules for developers and coding agents. + +## Programs + +A program has separate module, value and type environments. A value and a type can have the same name. Each step receives `$` plus the environments it needs: + +| Step | Callback arguments | Introduces | +| ---------------- | ------------------ | ------------------------------------------------ | +| `Let` | `$`, values, types | One value binding | +| `Type` | `$`, types | One type alias | +| `Newtype` | `$`, types | A nominal type and its constructor | +| `Import` | `$`, modules | Selected exports in every applicable environment | +| Final expression | `$`, values, types | The block's result | + +`$` supplies literals, typed inputs, conditionals and query helpers. Its `ref` property holds the current module declarations. For example, `$.ref.math.values.cmp` accesses a declared value without importing its name locally. + +```ts +import { Result } from "effect"; +import { Module, Program, program } from "@local/hashql"; +import type { Type as Semantic } from "@local/hashql"; + +const userId: unique symbol = Symbol("UserId"); +const query = Result.gen(function* () { + const kernel = yield* Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }); + + const { Do, Let, Type, Newtype, Import } = Program.withPrelude({ + modules: { kernel }, + }); + + const expression = yield* Do( + Import((_, { kernel }) => kernel), + Type("Count", (_, { Integer }) => Integer), + Newtype("UserId", userId, (_, { Count }) => Count), + Let("id", (_, { UserId }) => UserId(7n)), + ($, { id }, { UserId }) => $.input("id", UserId, id), + ); + + return yield* Program.compile(program(expression)); +}); +``` + +`query` is a `Result`. `Do` returns its result after the final expression callback. Declaration steps and nested expressions retain failures internally, allowing composition without unwrapping each expression. A failed declaration skips later callbacks. Host callback exceptions propagate unchanged rather than becoming construction errors. + +`ProgramError.Construction` has the tag `ProgramConstructionError` and a tagged `reason`. Reasons identify invalid names, module paths, type arities, argument counts, expression syntax and malformed blocks. Parser-backed reasons retain their underlying `cause` without exposing the parser's error type in the program API. + +`Let` introduces one sequential binding. Later steps see a reference to that binding. Declarations wrap their bodies in HashQL special forms, not closures. Bindings retain their authored names, with identifier quoting where required. Later declarations shadow names only in their own environments. + +`Type` preserves the underlying semantic type. `Newtype` produces a distinct `Semantic.Opaque` type. Its unique symbol supplies TypeScript's nominal identity and is not serialized. Use a distinct symbol for each distinct declaration, including declarations with the same HashQL name. These builders currently define concrete types, not parameterized local declarations. + +## Imports + +`Import` emits a HashQL `use` expression and introduces local references. `Import((_, { math }) => math)` imports every exported name. A second argument selects names, such as `["cmp"]`, or renames them, such as `{ cmp: "compare" }`. An alias of `"_"` retains the original name. Each selected name enters every environment in which the module exports it, including a same-named type and constructor. Imported child modules expose references beneath their local module name. + +`Program.Do` starts with empty environments. `Program.withPrelude` accepts optional `modules`, `values` and `types` records without emitting imports. The positional `Do` overloads support up to eight declaration steps and a final expression. Chained nested blocks have no fixed step count. + +## Conditional blocks + +Each branch of `$.if` returns an expression. A branch needing declarations uses the scope-bound step methods and ends with `Expr`: + +```ts +import { Result } from "effect"; +import { Let, Program, program } from "@local/hashql"; + +const conditional = Program.Do( + Let("outer", ($) => $.integer(7)), + ($, { outer }) => + $.if( + true, + () => $.Let("inner", () => outer).Expr((_, { inner }) => inner), + () => outer, + ), +); + +const compiled = Result.flatMap(conditional, (expression) => + Program.compile(program(expression)), +); +``` + +Branches inherit the enclosing environments, but their declarations remain local. Both callbacks run during construction, and a failure in either branch fails the containing expression. HashQL chooses which branch to evaluate when executing the query. Native JavaScript `if` tests an expression handle's truthiness, not the represented Boolean value. + +## Declarations and expressions + +`Module.define` binds declarations to absolute HashQL paths and returns a `Result`. Its `modules`, `types` and `values` records remain separate. Copying an existing export into another declaration preserves its original reference. `Module.root` assembles an existing module tree and also returns a `Result`. Both operations copy and freeze their export records. + +`Module.value` declares a value, `Module.type` declares a concrete type, and `Module.genericType` declares a parameterized type. Declarations supply trusted semantic annotations. Neither `Expression.fromJExpr` nor `TypeExpression.fromType` proves that arbitrary syntax has type `T`. `Expression.fromJExpr` also trusts the supplied input requirements. Use `Inputs.Empty` for syntax without inputs. Generated declarations must obtain that information from their source. + +The package does not include a generated standard-library bundle. + +Type applications preserve the declared semantic result and retain construction failures. `TypeExpression.toType` returns the underlying type syntax as a `Result`. A type expression is not itself raw `JExpr.Type` syntax. + +Expression handles support typed projections, `$project`, `$index` and function calls. Direct `then` access returns `undefined` to prevent Promise assimilation. Use `$project("then")` for that field. Generic function declarations use `Semantic.GenericFunction` with a `Semantic.FunctionSignature` mapping argument descriptors to a function signature. + +`$.literal` accepts JavaScript primitives other than `undefined` and symbols. A `number` produces `Semantic.PrimitiveNumber`, and a `bigint` produces `Semantic.PrimitiveInteger`. This distinction follows the host type, not the value: `1` remains Number even when the serializer emits integer literal syntax. Use `$.number` to construct Number explicitly or `$.integer` for checked integer construction. Non-finite numbers produce construction failures. + +Compatible primitives also work as function arguments, index keys, input defaults, comparison and Boolean operands, conditional conditions and branches, and query predicate results. Strings always denote literals, not references. Primitives contribute no input requirements. Arrays, objects and block bodies still need explicit expression construction. + +`$.input(name, type, defaultValue?)` selects its default only when the host omits the input. The SDK checks matching semantic descriptors rather than general HashQL subtyping. A Number parameter rejects Integer handles and bigints. `$.assume()(expression)` changes the SDK annotation while preserving input requirements. It emits no conversion or HashQL type assertion, and does not prove the new annotation. + +Value operations live under `expression.$`: `eq`, `ne`, Boolean `and`, `or`, `isTrue`, `isFalse`, and optional-value `isNone`. Query operations chain directly through `$.query.entities(now()).filter("vertex", predicate).collect()`. The `entities` declaration in the value environment determines the query's argument and vertex types. A filter emits a closure with the supplied parameter name. A query stored in a `Let` binding loses its query-chain methods intentionally, matching a compiler restriction. Complete the chain before binding its collected result. + +## Reusable expressions and inputs + +`Expression.Expression` carries its semantic result type and a record of input descriptors. Composition combines those records through calls, projections, indexing, value operations, filters and blocks. `Expression.Inputs` extracts the record. `Program.Inputs` extracts it from a program. + +```ts +import { Result } from "effect"; +import { Expression, Module, Program } from "@local/hashql"; +import type { Type } from "@local/hashql"; + +const query = Result.gen(function* () { + const kernel = yield* Module.define("::kernel::type", { + types: { + Integer: Module.type(), + Boolean: Module.type(), + }, + }); + + const count = Expression.input("count", kernel.types.Integer); + + const nonzero = count.$.ne(0n); + + const expression = yield* Program.Do(($) => + nonzero.$.and($.input("enabled", kernel.types.Boolean, true)), + ); + + return Program.program(expression); +}); + +export type Inputs = Program.Inputs>; +// { readonly count: Type.PrimitiveInteger; readonly enabled?: Type.PrimitiveBoolean } +``` + +The saved `nonzero` expression can participate in other programs with its `count` requirement intact. A default makes its input optional. Combining uses of the same name intersects their semantic types, and any required use makes the name required. Incompatible primitive types produce `Type.Never` in that record. This describes the requirements without adding a runtime SDK validator. + +Requirements include both conditional branches, defaults' own dependencies and every emitted `Let` initializer, including shadowed or unused bindings. They describe the constructed syntax conservatively rather than predicting which branches will execute. An expression constructed and discarded in JavaScript contributes nothing. References to local HashQL bindings retain their lexical scope requirements. + +## Syntax trees and examples + +Serialization traverses the constructed tree rather than rerunning authoring callbacks. `Let`, `Type`, `Newtype` and `Import` nodes own their child. `If` owns its condition and both branches. Every completed node implements `compile(): JExpr.Expression` without an external scope or child. + +`Expression.toNode` returns the handle's tree as a `Result`. `Expression.toJExpr` compiles it to J-Expr, and `Program.compile` also serializes it. A saved JavaScript handle still depends on the lexical scope of the HashQL name it references. The compiler owns name resolution, capture analysis and free-reference validation. + +The [authoring guide](docs/authoring.md) is the tutorial and API reference. The [checked examples](examples/api-tour.test-d.ts) retain exact-type assertions and `@ts-expect-error` cases in the package checks. These checks validate the SDK, not HashQL compiler acceptance or graph execution. + +[`examples/filters.ts`](examples/filters.ts) compares existing J-Expr queries and frontend selection predicates with typed constructions. Start at `allEntities`. These examples construct syntax without frontend integration or a graph connection. Their static module fixtures unwrap declaration results explicitly. + +Run the package checks with `yarn workspace @local/hashql test:unit`, `lint:tsc`, `lint:oxlint` and `build`. diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md new file mode 100644 index 00000000000..a744bfb2e06 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -0,0 +1,739 @@ +# Authoring HashQL with the TypeScript SDK + +The `@local/hashql` package builds HashQL programs from TypeScript. You describe the HashQL modules a program uses and compose expressions from typed handles. The SDK then serializes the result to J-Expr, the JSON syntax the HashQL compiler reads. The SDK neither runs nor compiles a query. It gives you typed composition and a syntax tree, and the HashQL compiler decides whether that tree is a valid program. + +This guide starts with one complete program and then works through each part of the API with focused examples. The [authoring rules](#authoring-rules) at the end condense it into rules that a person or a coding agent can follow while writing a program. + +## What checks a program + +TypeScript, construction and the HashQL compiler each catch different mistakes. + +| Stage | When it runs | What it checks | +| --------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| TypeScript | While you write the code | Which names each step can see, call arguments, projections, indexing, nominal identity and input requirements, all against the types your declarations state | +| Construction | When your code calls the SDK | Binding, import, parameter and export names, module paths, type argument counts, finite numbers, block shape and J-Expr structure | +| HashQL compiler | When you compile the program | Name resolution, lexical scope, the actual types of the modules you declared and the rules for graph queries | + +TypeScript and construction both trust your declarations. If you declare that `::core::math::add` takes two integers, the SDK accepts calls that match that declaration and nothing else. A program that type-checks and constructs can still fail to compile, for example when a declaration disagrees with the real definition or a reference leaves the scope that binds it. This guide shows what TypeScript and construction accept. Whether a program compiles is the compiler's answer, and this guide doesn't run the compiler. + +## A complete first program + +This program declares the two modules it uses, binds an optional `page` input and returns the next page number. + +```ts +import { Result } from "effect"; +import { Import, Let, Module, Program, program } from "@local/hashql"; +import type { Type } from "@local/hashql"; + +type IntegerOperation = Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger +>; + +const built = Result.gen(function* () { + // Describe the HashQL declarations this program uses. + const kernel = yield* Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }); + const math = yield* Module.define("::core::math", { + values: { add: Module.value() }, + }); + + // Make the modules visible to the program's steps. + const { Do } = Program.withPrelude({ modules: { kernel, math } }); + + const root = yield* Do( + Import((_, { math }) => math, ["add"]), + Let("page", ($) => $.input("page", $.ref.kernel.types.Integer, 1n)), + (_, { page, add }) => add(page, 1n), + ); + + return program(root); +}); + +// The host may omit `page`, because the input has a default. +export type PageInputs = Program.Inputs>; +// { readonly page?: Type.PrimitiveInteger } + +const compiled = Result.flatMap(built, Program.compile); + +Result.match(compiled, { + onSuccess: (jexpr) => console.log(jexpr), + onFailure: (error) => console.error(error.reason._tag, error.message), +}); +``` + +The program has five parts. + +1. `Module.define` binds TypeScript descriptions of HashQL types to absolute paths. It returns a `Result` because a path or export name can be invalid. The program yields that `Result` inside `Result.gen`. +2. `Program.withPrelude` makes the modules available to every step without emitting any HashQL import. +3. `Do` takes declaration steps followed by one final callback. `Import` emits a HashQL `use` and brings `add` into the value environment. `Let` binds `page` to an input. The final callback returns the program's result expression. +4. `program(root)` wraps the result expression, and `Program.compile` serializes it to a J-Expr string. Both `Do` and `Program.compile` return a `Result`. +5. The caller handles both outcomes. A failure is a `ProgramError.Construction` with a tagged `reason`. + +`IntegerOperation` limits this example's `add` declaration to its Integer-to-Integer specialization. The compiler's complete signature also supports other numeric arguments. + +On success the program prints this J-Expr, shown here with line breaks: + +```json +[ + "::kernel::special_form::use", + "::core::math", + { "#tuple": ["add"] }, + [ + "::kernel::special_form::let", + "page", + [ + "::kernel::special_form::input", + "page", + "::kernel::type::Integer", + { "#literal": 1 } + ], + ["add", "page", { "#literal": 1 }] + ] +] +``` + +## Shared declarations for the examples + +The remaining examples are shorter. Each assumes the imports and declarations below, and states any further declarations it needs beside its own code. + +```ts +import { Result } from "effect"; +import { + Expression, + Import, + Let, + Module, + Newtype, + Program, +} from "@local/hashql"; +import type { Inputs, Type } from "@local/hashql"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Boolean: Module.type(), + Integer: Module.type(), + Number: Module.type(), + String: Module.type(), + }, + }), +); + +const math = Result.getOrThrow( + Module.define("::core::math", { + values: { + add: Module.value< + Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger + > + >(), + sqrt: Module.value< + Type.Function + >(), + }, + }), +); + +const { Do } = Program.withPrelude({ modules: { kernel, math } }); +``` + +These declarations never change and construct successfully, so the examples unwrap them with `Result.getOrThrow`. It throws if a declaration fails. In application code, prefer yielding each `Result` inside `Result.gen` as the first program does. + +## Environments and steps + +A program has three separate environments: modules, values and types. A value and a type can share a name. Each declaration changes only the environments it adds names to, so a `Let` never touches a type. + +Each step's callback receives `$` first, followed by the environments that step may use: + +| Step | Callback arguments | Introduces | +| -------------- | ------------------ | ------------------------------------------------------- | +| `Let` | `$`, values, types | One value binding | +| `Type` | `$`, types | One type alias | +| `Newtype` | `$`, types | One nominal type and its constructor | +| `Import` | `$`, modules | The selected exports, in each environment that has them | +| Final callback | `$`, values, types | The block's result | + +`$` holds the helpers a callback needs: + +- `$.literal`, `$.integer` and `$.number` turn host values into expressions. +- `$.input` declares a value the host supplies when it runs the query. +- `$.if` builds a HashQL conditional. +- `$.assume` changes an expression's TypeScript type without changing its syntax. +- `$.ref` holds the module environment, so `$.ref.math.values.add` reaches a declared value without importing it. +- `$.query` starts a graph query, when the value environment holds an `entities` function. +- `$.Let`, `$.Type`, `$.Newtype`, `$.Import` and `$.Expr` start a nested block. + +`Program.Do` starts with empty environments. `Program.withPrelude` accepts optional `modules`, `values` and `types` records and returns `Do` together with `Let`, `Type`, `Newtype` and `Import`. The prelude only seeds the environments. It emits no HashQL. The package also exports `Let`, `Newtype` and `Import` directly. `Type` is available as `Program.Type` or from `withPrelude`, because the top-level `Type` export names the namespace of type descriptors. + +## Declaring modules + +`Module.define(path, definition)` binds declarations to an absolute HashQL path. The definition has optional `modules`, `types` and `values` records, and each key in them is one export: + +- `Module.value()` declares a value of type `T`, such as a function. +- `Module.type()` declares a concrete type. +- `Module.genericType(arity)` declares a type constructor that takes `arity` type arguments. +- An existing module under `modules` becomes a child module. An existing export copied into another module keeps its original path. + +These records are the only place where one JavaScript object describes more than one declaration. They describe what a module exports. Declaration steps inside a program work differently: each `Let`, `Type` or `Newtype` step declares exactly one name. + +`Module.define` returns a `Result`. A relative path, an invalid path or an invalid export name produces a construction failure. `Module.root` assembles already defined modules into a tree and also returns a `Result`. Both copy and freeze their records, so later changes to your objects don't change a module. + +A declaration is a trusted annotation. The package includes no standard library, so you write declarations for the parts of HashQL a program uses, including the graph functions a query needs. The compiler checks the emitted program against the real definitions. Generated declarations must take their types from the definitions they describe. + +A module's values are expressions that refer to their absolute path. You can use them through `$.ref` without importing anything: + +```ts +// Uses: math, Do. +const viaRef = Do(($) => $.ref.math.values.add(7n, 2n)); +// Compiles to ["::core::math::add",{"#literal":7},{"#literal":2}] +``` + +## Ordered declarations and shadowing + +`Do` runs its construction steps in order, and each step sees the names that earlier steps introduced. A later declaration shadows an earlier one of the same name, and only in its own environment. + +This order determines callback name visibility, not a HashQL evaluation schedule. HashQL is pure, and a binding cannot refer to itself. The compiler orders the resulting bindings. + +```ts +// Uses: kernel, Do. +const ordered = Do( + Import((_, { kernel }) => kernel, ["Integer"]), + Let("limit", ($) => $.integer(10)), + Let("previous", (_, { limit }) => limit), + // Shadows the value `limit` for the steps that follow. + Let("limit", ($) => $.literal("ten")), + // A value named `Integer` leaves the type `Integer` untouched. + Let("Integer", ($) => $.literal("a value named Integer")), + ($, { limit, previous }, { Integer }) => + $.if( + limit.$.eq("ten"), + () => previous, + () => $.input("fallback", Integer), + ), +); +``` + +In the final callback, `previous` is an Integer expression, `limit` is a String expression, and the type `Integer` is still the kernel type. Each `Let` emits a HashQL `let` that wraps the steps after it, so the second `limit` binding sits inside the first. + +Each step declares one name. `Let`, `Type` and `Newtype` take a name and a callback that returns one expression or type. A callback can't return a record of declarations, so binding three values takes three `Let` steps. + +The positional form of `Do` accepts up to eight declaration steps before the final callback. For more, continue with a nested block: `$` starts one, and its chained methods have no fixed step limit. + +```ts +// Uses: Do. +const chained = Do(($) => + $.Let("first", ($) => $.integer(1)) + .Let("second", (_, { first }) => first) + .Let("third", (_, { second }) => second) + .Expr((_, { third }) => third), +); +``` + +A chain must end with `Expr`, which takes the final callback and returns the block's expression. + +## Nominal identity + +`Newtype` introduces a nominal type and its constructor under one name. The constructor wraps a value of the underlying type. A `unique symbol` gives the type its identity in TypeScript and isn't emitted. + +```ts +// Uses: kernel, Do. +const userId: unique symbol = Symbol("UserId"); +const accountId: unique symbol = Symbol("AccountId"); + +const owner = Do( + Import((_, { kernel }) => kernel, ["Integer"]), + Newtype("UserId", userId, (_, { Integer }) => Integer), + Let("owner", (_, { UserId }) => UserId(1n)), + ($, { owner, UserId }, types) => { + // @ts-expect-error The representation 2n doesn't have the nominal type. + $.input("id", types.UserId, 2n); + return $.if( + owner.$.eq(UserId(1n)), + () => $.input("id", types.UserId, UserId(2n)), + () => owner, + ); + }, +); +``` + +`types.UserId` is the nominal type, and the value `UserId` is its constructor. To pass an Integer where the program needs a `UserId`, wrap it with the constructor. + +Declarations that share a HashQL name are different types in TypeScript when their symbols differ: + +```ts +// Uses: kernel, Do, userId and accountId from the previous example. +const shadowedId = Do( + Import((_, { kernel }) => kernel, ["Integer"]), + Newtype("Id", userId, (_, { Integer }) => Integer), + Let("first", (_, { Id }) => Id(1n)), + Newtype("Id", accountId, (_, { Integer }) => Integer), + (_, { first, Id }) => { + // @ts-expect-error The later `Id` is a different nominal type. + first.$.eq(Id(2n)); + return first; + }, +); +``` + +Give each `Newtype` its own `unique symbol`, including declarations that share a HashQL name. A symbol widened to plain `symbol` can't tell declarations apart, and TypeScript rejects it. + +`Type` declares an alias instead. An alias keeps the underlying type, so `Type("Count", (_, { Integer }) => Integer)` produces a type that TypeScript treats as Integer. `Type` and `Newtype` currently declare concrete types only, without type parameters. + +## Imports and renaming + +`Import` takes a callback that selects a module from the module environment and an optional selection. It emits a HashQL `use` around the steps that follow and adds local names for the selected exports: + +- `Import(select)` imports every export. +- `Import(select, ["add", "sqrt"])` imports the listed exports. +- `Import(select, { add: "sum" })` imports `add` under the local name `sum`. An alias of `"_"` keeps the original name. + +```ts +// Uses: kernel, math, Do. +const imported = Do( + Import((_, { math }) => math, { add: "sum" }), + Import((_, { kernel }) => kernel, { Integer: "_", String: "Text" }), + ($, { sum }, { Integer }) => sum($.input("count", Integer), 2n), +); +``` + +A selected name enters every environment in which the module exports it, so one import provides both a type and a constructor of the same name. TypeScript rejects a selection that names no export of the declared module. + +Importing a child module adds it to the module environment under its local name. `$.ref` then reaches it by that name: + +```ts +// Uses: math. +const core = Result.getOrThrow(Module.define("::core", { modules: { math } })); + +const viaChild = Program.withPrelude({ modules: { core } }).Do( + Import((_, { core }) => core, { math: "m" }), + ($) => $.ref.m.values.add(7n, 2n), +); +// Compiles to a `use` of `::core` around a call to `m::add`. +``` + +Refer to declarations through handles: callback environments, imports and `$.ref`. A string is always a string literal. `$.literal("add")` is the text `"add"`, not a reference to the function. + +## Projections and indexing + +An expression handle offers the fields and positions of its type as typed properties. This example declares a `Profile` type in a hypothetical `::example::profile` module, which stands for a module in your own HashQL environment. + +```ts +// Uses: Do. Declares the module below. +type Profile = Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly scores: Type.List; + readonly labels: Type.Dict; + readonly location: Type.Tuple< + readonly [Type.PrimitiveNumber, Type.PrimitiveNumber] + >; +}>; + +const profiles = Result.getOrThrow( + Module.define("::example::profile", { + types: { Profile: Module.type() }, + }), +); + +const label = Program.withPrelude({ modules: { profiles } }).Do( + Import((_, { profiles }) => profiles, ["Profile"]), + Let("profile", ($, _values, { Profile }) => $.input("profile", Profile)), + (_, { profile }) => profile.labels.$index(profile.name), +); +``` + +With `profile` bound to a `Profile` expression, these accessors are available: + +| Expression | Result type | +| ---------------------------- | ----------------- | +| `profile.name` | `String` | +| `profile.$project("name")` | `String` | +| `profile.location[0]` | `Number` | +| `profile.scores.$index(0n)` | `Integer \| Null` | +| `profile.labels.$index("x")` | `String \| Null` | + +Indexing a list or dictionary includes `Null` in its result type, because the key might not be present. A list key is an Integer, and a dictionary key has the dictionary's key type. A field the struct doesn't declare is a TypeScript error. A projection or index requires the inputs of the expression it reads, together with those of its key. + +Projections reach through opaque types to their representation. A union or intersection offers a field when every member offers it. + +Direct access to a `then` field returns `undefined`. This stops JavaScript from treating a handle as a Promise. Use `$project("then")` for that field. `$project` and `$index` also work for any other field or key. + +## Typed calls + +A handle whose type is a function is callable with typed arguments. + +```ts +// Uses: kernel, math, Do. +const sum = Do(($) => { + const count = $.input("count", $.ref.kernel.types.Integer); + // @ts-expect-error `add` takes Integer arguments, and 2 is a Number. + $.ref.math.values.add(count, 2); + // @ts-expect-error `add` takes exactly two arguments. + $.ref.math.values.add(count); + return $.ref.math.values.add(count, 2n); +}); +``` + +The result has the declared return type, and its input requirements combine those of the callee and every argument. Here `sum` requires a `count` input. + +Module values are ordinary handles, so you can call them outside a block as well: `math.values.add(7n, 2n)` is an Integer expression. + +For a function whose types depend on its arguments, declare `Type.GenericFunction` with a `Type.FunctionSignature` that maps the argument types to a function type. The SDK applies the signature at each call and doesn't infer it from HashQL. + +## Value operations + +The `.$` property of a handle exposes value operations that emit standard-library calls: + +- `eq` and `ne` compare with a value of the same type, emitting `::core::cmp::eq` and `::core::cmp::ne`. +- On Boolean expressions, `and`, `or`, `isTrue` and `isFalse` emit `::core::bool::and`, `::core::bool::or` and comparisons with `true` or `false`. +- On a union that includes the `::core::option::None` opaque type, `isNone` compares with `None`. + +The operand of `eq` or `ne` must have exactly the receiver's type, and the operand of `and` or `or` must be Boolean. A matching host primitive also works. The [primitives section](#primitives-and-explicit-assumptions) explains what "exactly" means here. + +## Queries + +`$.query` builds graph queries. It exists when the value environment holds an `entities` function that returns a graph type, `Type.Opaque<"::graph::Graph", …>`. The graph type's `'marker` field names the vertex type, and the SDK reads the query's vertex type from it. + +The package doesn't generate these declarations. Like the module declarations above, they are yours to write. This example declares only the entity field it reads: + +```ts +// Uses: kernel. Declares the graph fixtures below. +type Entity = Type.Opaque< + "::graph::types::knowledge::entity::Entity", + Type.Struct<{ + readonly metadata: Type.Struct<{ + readonly archived: Type.PrimitiveBoolean; + }>; + }> +>; +type EntityGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Entity }> +>; +type TemporalAxes = Type.Opaque< + "::graph::temporal::QueryTemporalAxes", + Type.Unknown +>; + +const head = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: + Module.value>(), + }, + }), +); +const temporal = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: + Module.value>(), + }, + }), +); + +const graph = Program.withPrelude({ + modules: { kernel }, + values: { + entities: head.values.entities, + now: temporal.values.decision_time_now, + }, +}); +``` + +A query starts at `$.query.entities(...)`, adds filters and ends with `collect()`: + +```ts +// Uses: the graph fixtures above. +const isLive = (entity: Expression.Expression) => + entity.metadata.archived.$.isFalse(); + +const live = graph.Do(($, { now }) => + $.query + .entities(now()) + .filter("entity", isLive) + .filter("entity", (entity) => + entity.metadata.archived.$.eq( + $.input("archived", $.ref.kernel.types.Boolean, false), + ), + ) + .collect(), +); +``` + +`live` is a construction Result containing one list-valued expression, with an optional `archived` input. Each `filter` emits a closure whose parameter has the name you pass, so that name must be a valid identifier. A predicate is an ordinary function from a vertex expression to a Boolean expression, and you can reuse it across queries. Predicate inputs accumulate in the query's requirements. + +### Queries and `Let` + +A `Let` binding holds a plain expression of the bound value's type. A query stored in a binding loses `filter` and `collect`. This is intentional: it matches a restriction the HashQL compiler places on graph query chains. Build the whole chain in one expression, and bind the collected result or the values the query depends on: + +```ts +// Uses: the graph fixtures and isLive above. +const firstLive = graph.Do( + Let("axes", (_, { now }) => now()), + Let("live", ($, { axes }) => + $.query.entities(axes).filter("entity", isLive).collect(), + ), + (_, { live }) => live.$index(0n), +); +``` + +Binding `$.query.entities(axes)` without `collect()` gives a binding of the graph type, and TypeScript reports `filter` on it as an unknown property. + +## Input requirements + +An expression handle has two types: the HashQL type of its value, and a record of the inputs it requires. `Expression.Expression` carries both. Composition combines the records, so a reusable expression keeps its requirements wherever you use it. + +```ts +// Uses: kernel, Do. +const count = Expression.input("count", kernel.types.Integer); +const nonzero = count.$.ne(0n); +// Expression.Expression + +const enabled = Do(($) => + nonzero.$.and($.input("enabled", $.ref.kernel.types.Boolean, true)), +); + +export type EnabledInputs = Expression.Inputs< + Result.Result.Success +>; +// { readonly count: Type.PrimitiveInteger; readonly enabled?: Type.PrimitiveBoolean } +``` + +`Expression.Inputs` extracts the record from an expression and `Program.Inputs

` from a program. The record follows these rules: + +- An input with a default is optional for the host. The default's own requirements join the record. +- Calls, projections, indexing, value operations, filters, conditionals and blocks combine the requirements of their parts. +- Uses of one name intersect their types, and a required use makes the name required. Uses with incompatible primitive types produce `Type.Never` for that name instead of an error at the use site. Give inputs of different types different names. +- A conditional requires the inputs of its condition and both branches, because the record describes the constructed syntax rather than predicting which branch runs. +- A reference to a `Let` binding requires the inputs of its initializer. + +A type annotation can't hide a requirement. Annotating `nonzero` with an empty input record is a TypeScript error: + +```ts +// Uses: nonzero from the previous example. +// @ts-expect-error The empty record has no room for `count`. +const hidden: Expression.Expression = + nonzero; +``` + +Let TypeScript infer the type, or name the requirement with `Expression.Inputs`. The record is a TypeScript type. The SDK adds no runtime validator for the values a host supplies. + +### Discarded host expressions and unused bindings + +Only syntax that ends up in the tree counts. An expression you construct in JavaScript and then drop contributes nothing, while an unused `Let` binding is still emitted with its initializer. + +```ts +// Uses: Do. +const discarded = Do(($) => { + // JavaScript drops this handle, so the program never contains it. + $.input("ignored", $.ref.kernel.types.Integer); + return $.integer(1); +}); +// Compiles to {"#literal":1} and requires no inputs. + +const unused = Do( + // Nothing refers to `unused`, but the `let` and its initializer are emitted. + Let("unused", ($) => $.input("retained", $.ref.kernel.types.Integer)), + ($) => $.integer(1), +); +// Compiles to a `let` whose initializer is the `retained` input, and requires `retained`. +``` + +The same holds for shadowed bindings: their initializers stay in the program and in the input record. + +## Primitives and explicit assumptions + +Where the SDK expects a value, you can often pass a host primitive. `$.literal` turns one into an expression explicitly. The host type decides the HashQL type: + +| Host value | HashQL type | +| ---------- | ----------- | +| `number` | `Number` | +| `bigint` | `Integer` | +| `string` | `String` | +| `boolean` | `Boolean` | +| `null` | `Null` | + +The type follows the host type, not the value. `1` stays a Number even though the serializer emits the same literal syntax for `1` and `1n`. Use `$.number(value)` to construct a Number explicitly, or `$.integer(value)` for a checked Integer that fails construction for a fractional value. A non-finite number fails construction wherever you pass it. `undefined` and symbols are not HashQL values. + +Host primitives work as function arguments, `$index` keys, input defaults, operands of `.$` operations, `$.if` conditions and branch results, and filter predicate results. They contribute no input requirements. The callbacks of `Do`, `Let` and `Expr` must return an expression handle, so lift a host value there with `$.literal`, `$.integer` or `$.number`. + +### Exact matching + +The SDK compares types exactly and doesn't model HashQL subtyping. A parameter declared as Number rejects an Integer expression and a `bigint`, and a parameter declared as `String | Null` rejects a String expression. When you know the wider type is correct, state it with `Expression.assume` or `$.assume`: + +```ts +// Uses: kernel, math. +type NullableString = Type.Union< + readonly [Type.PrimitiveString, Type.PrimitiveNull] +>; + +const root = math.values.sqrt(2); +// @ts-expect-error Integer doesn't widen to Number in the SDK. +math.values.sqrt(2n); + +const two = Expression.assume()(Expression.integer(2)); +const rootOfTwo = math.values.sqrt(two); + +const name = Expression.input("name", kernel.types.String); +const nullable = Expression.assume()(name); +// Expression.Expression +``` + +An assumption changes only the TypeScript type. It emits no conversion and no HashQL type assertion, and `two` serializes exactly as `Expression.integer(2)` does. It preserves input requirements: `nullable` still requires `name`, and that input keeps its declared String type. An assumption doesn't prove anything either. The compiler still checks the program. + +### Conditions + +A `$.if` condition is a Boolean expression or a host `boolean`. Write `$.if(true, thenCallback, elseCallback)` rather than wrapping the constant in `$.literal`. An Integer or other non-Boolean expression is a TypeScript error as a condition. Outside a block, the top-level `If(condition, { then, else })` builds the same conditional from branches you have already constructed. + +## Local scopes and host versus HashQL evaluation + +Your TypeScript runs when it constructs the program. The HashQL it builds runs later, when the host executes the query. Most mistakes in this area come from mixing up the two. + +### Local bindings + +A nested block introduces bindings visible only inside it. Here `inner` exists in the first branch alone: + +```ts +// Uses: math, Do. +const scoped = Do( + Let("outer", ($) => $.integer(7)), + ($, { outer }) => + $.if( + true, + () => + $.Let("inner", () => math.values.add(outer, 2n)).Expr( + (_, { inner }) => inner, + ), + () => outer, + ), +); +``` + +The branch emits its own `let`, nested inside the conditional. A nested block inherits the enclosing environments, and its declarations stay local. TypeScript types each callback's environments, so naming `inner` in the other branch is a TypeScript error. + +### What a handle refers to + +An expression handle holds a piece of syntax, its HashQL type and its input record. Some handles refer to names. A `Let` binding, an imported value and a `Newtype` constructor are local identifiers. A module declaration reached through the prelude is an absolute path such as `::core::math::add`. Other handles are composite syntax: literals, inputs, calls, projections, conditionals and nested blocks. + +The SDK doesn't resolve names. The compiler resolves them, checks that each local identifier sits inside the expression that binds it, and type-checks the program. JavaScript can carry a handle for a local identifier out of the block that binds it, and TypeScript accepts the result: + +```ts +// Uses: Do. +let escaped = Expression.integer(0); +Do( + Let("local", ($) => $.integer(1)), + (_, { local }) => { + escaped = local; + return local; + }, +); +const outside = Do(() => escaped); +``` + +`outside` constructs and type-checks, but the program it emits refers to `local` outside the `let` that binds it. Rejecting that program is the compiler's job. Take handles from the callback arguments of the block that uses them. + +### Host decisions and HashQL decisions + +A JavaScript `if`, ternary or loop runs during construction and decides what syntax to build. `$.if` builds a HashQL conditional, which decides at query time. A JavaScript `if` on a handle tests the handle object, which is always truthy, not the Boolean it represents. + +```ts +// Uses: Do. +const target = 3 * 10; + +const message = (verbose: boolean) => + Do(($) => { + const count = $.input("count", $.ref.kernel.types.Integer); + // JavaScript picks one literal now, while it builds the program. + const detail = verbose ? "count equals the target" : "equal"; + // HashQL compares `count` with 30 when the query runs. + return $.if( + count.$.eq(BigInt(target)), + () => detail, + () => "different", + ); + }); +``` + +`target`, `verbose` and `detail` are host values, so the emitted program contains only their results. `message(true)` and `message(false)` build two different programs. + +### Construction order and failures + +The SDK calls your callbacks during construction, in step order. A few details follow from that: + +- The SDK constructs both branches of a `$.if`, even though HashQL evaluates only one of them. A construction failure in either branch fails the whole conditional. +- A failed step skips the later callbacks of its block. A failing `Let` in a nested block skips the steps after it, and an invalid filter parameter name skips that filter's predicate. +- Expected construction failures arrive as a failed `Result`. An exception your own callback throws isn't converted. It propagates out of `Do` unchanged. + +Don't rely on a callback running for its side effects. + +## Construction errors + +Expected construction failures arrive as a `Result` holding a `ProgramError.Construction`. Its `_tag` is `"ProgramConstructionError"`, and its `reason` says what went wrong: + +```ts +// Uses: the shared imports. +const invalid = Program.Do( + Let("not a name", ($) => $.integer(1)), + ($) => $.integer(2), +); + +if (Result.isFailure(invalid)) { + const error = invalid.failure; + console.log(error.reason._tag); // "InvalidBindingName" + console.log(error.message); // Invalid HashQL binding name: "not a name" +} +``` + +The reasons are: + +| Reason | Cause | +| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| `InvalidBindingName`, `InvalidImportName`, `InvalidParameterName`, `InvalidExportName` | A name isn't a valid HashQL identifier | +| `InvalidModulePath`, `RelativeModulePath` | A module path is invalid or not absolute | +| `InvalidTypeArity`, `TypeArgumentCount` | A type constructor has an invalid arity or wrong number of arguments | +| `InvalidExpression` | Syntax isn't valid J-Expr, including non-finite numbers | +| `InvalidBlock` | A block's steps are out of shape, or a callback returned something other than an expression | + +Reasons that come from parsing a name or syntax carry the parser's error as `cause`. The output quotes a binding name that needs quoting, such as `%`, rather than rejecting it. + +## Constructing from raw syntax + +`Expression.fromJExpr(syntax)` wraps raw J-Expr as an expression. It validates the syntax's structure and trusts both type arguments. `TypeExpression.fromType(syntax)` does the same for type syntax. The `JExpr` namespace holds builders and a serializer for raw syntax. + +Raw syntax has no input record, so these constructors take the requirements on trust. Use `Inputs.Empty` only for syntax that contains no inputs, and state every input the syntax contains. To change an expression's type, use `Expression.assume`. It keeps the requirements automatically. A raw-syntax round trip requires you to supply them again; using `Inputs.Empty` loses them: + +```ts +// Uses: kernel. +const counted = Expression.input("count", kernel.types.Integer); + +// Drops the `count` requirement: the raw syntax still contains the input. +const dropped = Expression.fromJExpr( + Result.getOrThrow(Expression.toJExpr(counted)), +); + +// Keeps it. +const kept = Expression.assume()(counted); +``` + +`Expression.toJExpr` returns an expression's J-Expr as a `Result`. `Expression.toNode` returns its syntax tree as a `Result`. `Program.compile` returns a `Result` containing the serialized program. + +## Authoring rules + +Follow these rules when you write HashQL with the SDK, whether by hand or as a coding agent. + +1. Use the SDK when you want typed composition. Describe each module the program uses with `Module.define`, with types taken from the real HashQL definitions. +2. Use only API that the package exports, as this guide shows it. Don't invent methods, helpers or overloads. `JExpr` provides raw struct and list builders, but the high-level expression API currently offers neither typed equivalents nor unchecked accessors. +3. Refer to declarations through handles from callback environments, `Import` and `$.ref`. A string is always a literal. +4. Return an expression handle from every `Do`, `Let` and `Expr` callback. Lift host values with `$.literal`, `$.integer` or `$.number`. +5. Declare one name per `Let`, `Type` or `Newtype` step. Records that list declarations belong in `Module.define`. +6. Handle every `Result`. Yield inside `Result.gen` in application code. Callback exceptions propagate unchanged rather than becoming construction Results. +7. Preserve input requirements. Let TypeScript infer handle types, use `assume` rather than raw syntax round trips, and state every input when you wrap raw syntax with `Expression.fromJExpr`. +8. Don't treat TypeScript annotations or `assume` as compiler validation. A program that type-checks still needs the HashQL compiler. +9. Keep references in their HashQL lexical scope. Take each handle from the callback arguments of the block that uses it, and don't store local bindings in outer variables. +10. Chain `filter` and `collect` before binding a query. Bind the collected result or the values the query depends on. +11. Use `$.if` for decisions the query makes and JavaScript control flow for decisions you make while building it. +12. Match types exactly. A `number` produces a Number and a `bigint` produces an Integer. State a wider type with `assume` when you know it is correct. +13. Give each `Newtype` its own `unique symbol`. diff --git a/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap new file mode 100644 index 00000000000..f67a1e1419c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap @@ -0,0 +1,393 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`filter_examples > frontend_selection: 5. Frontend: look up a published entity 1`] = ` +[ + "::kernel::special_form::let", + "webId", + [ + "::kernel::special_form::input", + "web_id", + "::graph::types::principal::actor_group::web::WebId", + ], + [ + "::kernel::special_form::let", + "entityUuid", + [ + "::kernel::special_form::input", + "entity_uuid", + "::graph::types::knowledge::entity::EntityUuid", + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::and", + [ + "::core::bool::and", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "web_id", + ], + "webId", + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + "entityUuid", + ], + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], + ], +] +`; + +exports[`filter_examples > frontend_selection: 6. Frontend: the sidebar's web and arch… 1`] = ` +[ + "::kernel::special_form::let", + "webId", + [ + "::kernel::special_form::input", + "web_id", + "::graph::types::principal::actor_group::web::WebId", + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "web_id", + ], + "webId", + ], + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::and", + [ + "::core::cmp::ne", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "archived", + ], + { + "#literal": true, + }, + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], +] +`; + +exports[`filter_examples > frontend_selection: 7. Frontend: match any supplied entity … 1`] = ` +[ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::core::bool::or", + [ + "::core::bool::or", + { + "#literal": false, + }, + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + [ + "::graph::types::knowledge::entity::EntityUuid", + [ + "::core::uuid::Uuid", + { + "#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f", + }, + ], + ], + ], + ], + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "entity_uuid", + ], + [ + "::graph::types::knowledge::entity::EntityUuid", + [ + "::core::uuid::Uuid", + { + "#literal": "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", + }, + ], + ], + ], + ], + ], + ], +] +`; + +exports[`filter_examples > frontend_selection: 8. Frontend: make draft inclusion a que… 1`] = ` +[ + "::kernel::special_form::let", + "includeDrafts", + [ + "::kernel::special_form::input", + "include_drafts", + "::kernel::type::Boolean", + { + "#literal": false, + }, + ], + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + [ + "::graph::head::entities", + [ + "::graph::tmp::decision_time_now", + ], + ], + [ + "fn", + { + "#tuple": [], + }, + { + "#struct": { + "vertex": "_", + }, + }, + "_", + [ + "::kernel::special_form::if", + "includeDrafts", + { + "#literal": true, + }, + [ + "::core::cmp::eq", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + [ + "::kernel::special_form::access", + "vertex", + "metadata", + ], + "record_id", + ], + "entity_id", + ], + "draft_id", + ], + [ + "::core::option::None", + ], + ], + ], + ], + ], + ], +] +`; diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts new file mode 100644 index 00000000000..885f155d129 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -0,0 +1,494 @@ +/** + * A checked tour of the HashQL TypeScript SDK. + * + * Each test pairs code you can write and the type TypeScript infers for it with a limitation and its supported workaround. `tsc` and `vitest --typecheck` check this file. Neither of them runs it. A rejected line carries `@ts-expect-error`, so the check fails both when an inference changes and when an expected rejection disappears. + * + * Type checking covers the authoring API. It does not execute HashQL. The SDK constructs syntax, and the HashQL compiler resolves names, checks scopes and type-checks the emitted program. Construction failures, such as an invalid binding name, arrive as a `Result` failure at run time and do not appear in these types. + * + * @module + */ +// oxlint-disable hash/naming-conventions -- HashQL type and constructor names keep their PascalCase spelling in callback arguments +// oxlint-disable vitest/prefer-expect-assertions -- type tests run through the compiler, not the runtime assertion counter +// oxlint-disable eslint/no-magic-numbers -- literal values demonstrate the numeric types +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { + Expression, + Import, + Let, + Module, + Newtype, + Program, +} from "../src/main.js"; + +import type { + Inputs, + ProgramError, + Type, + TypeExpression, +} from "../src/main.js"; + +// Declarations bind TypeScript descriptions of HashQL types to absolute paths. The SDK trusts these annotations and includes no standard-library bundle, so the fixtures below describe only what the tour uses. Application code yields each `Result` inside `Result.gen`. The tour unwraps them with `getOrThrow`. + +type NullableString = Type.Union< + readonly [Type.PrimitiveString, Type.PrimitiveNull] +>; + +type Person = Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly archived: Type.PrimitiveBoolean; + readonly scores: Type.List; + readonly labels: Type.Dict; + readonly location: Type.Tuple< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger] + >; + readonly then: Type.PrimitiveString; +}>; + +// The query helpers recognize a graph by this opaque shape. Its marker field names the vertex type. +type PersonGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Person }> +>; +type TemporalAxes = Type.Opaque< + "::graph::temporal::QueryTemporalAxes", + Type.Unknown +>; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + String: Module.type(), + Boolean: Module.type(), + }, + }), +); + +const profile = Result.getOrThrow( + Module.define("::example::profile", { + values: { + greet: + Module.value< + Type.Function + >(), + length: + Module.value< + Type.Function + >(), + }, + }), +); + +const head = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: + Module.value>(), + }, + }), +); + +const temporal = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: + Module.value>(), + }, + }), +); + +// A prelude seeds the environments without emitting imports. `$.query` offers `entities` because the value environment holds a graph-returning `entities`. +const { Do } = Program.withPrelude({ + modules: { kernel, profile }, + values: { + entities: head.values.entities, + now: temporal.values.decision_time_now, + }, +}); + +type Closed = Expression.Expression; +type Built = Result.Result< + Expression.Expression, + ProgramError.Construction +>; + +declare const person: Closed; +declare const text: Closed; + +describe("reusable_expressions", () => { + test("inputs_and_defaults", () => { + // An expression is a value you can store and reuse. Its second type parameter records the host inputs it needs. + const count = Expression.input("count", kernel.types.Integer); + const nonzero = count.$.ne(0n); + expectTypeOf(nonzero).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveBoolean, + { readonly count: Type.PrimitiveInteger } + > + >(); + + // A default makes the input optional for the host. + const page = Expression.input("page", kernel.types.Integer, 1n); + expectTypeOf>().toEqualTypeOf<{ + readonly page?: Type.PrimitiveInteger; + }>(); + + // A program that reuses `nonzero` inherits its requirement. + const root = Result.getOrThrow( + Do(($) => nonzero.$.and($.input("enabled", kernel.types.Boolean, true))), + ); + const program = Program.program(root); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly enabled?: Type.PrimitiveBoolean; + }>(); + + // Limitation: an annotation cannot hide a requirement. + // @ts-expect-error A closed expression type has no room for `count`. + const hidden: Closed = nonzero; + expectTypeOf(hidden); + // Workaround: let TypeScript infer the type, or name the requirement. + const named: Expression.Expression< + Type.PrimitiveBoolean, + Expression.Inputs + > = nonzero; + expectTypeOf(named).toEqualTypeOf(nonzero); + + // @ts-expect-error The default for an Integer input cannot be a Boolean. + Expression.input("count", kernel.types.Integer, true); + }); + + test("conflicting_input_names", () => { + // Uses of one input name intersect their types. A required use makes the name required. + const asInteger = Expression.input("shared", kernel.types.Integer); + const asString = Expression.input("shared", kernel.types.String); + const both = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else` + then: asInteger, + else: asString, + }); + + // Limitation: incompatible primitives produce `Never` in the record rather than a compile error at the use site. + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.Never; + }>(); + + // Workaround: give inputs of different types different names. + const renamed = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- the conditional names its branches `then` and `else` + then: asInteger, + else: Expression.input("label", kernel.types.String), + }); + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }>(); + }); +}); + +const userId: unique symbol = Symbol("UserId"); +const accountId: unique symbol = Symbol("AccountId"); +type UserId = Type.Opaque; + +describe("declarations", () => { + test("imports_and_aliases", () => { + const built = Do( + // Select names, and rename some of them. An alias of `"_"` keeps the original name. + Import((_, { kernel }) => kernel, { Integer: "Int", String: "_" }), + // A type alias preserves the underlying semantic type. + Program.Type("Count", (_, { Int }) => Int), + ($, _values, { Count, String }) => { + expectTypeOf(Count).toEqualTypeOf(); + expectTypeOf(String).toEqualTypeOf(); + // `$.ref` reaches module members without importing them. + return $.ref.profile.values.length($.input("name", String)); + }, + ); + expectTypeOf(built).toEqualTypeOf< + Built + >(); + + // Limitation: a selection must name an export of the declared module. + // @ts-expect-error This kernel declaration exports no `Missing`. + Import(() => kernel, ["Missing"]); + // Workaround: add the export to the module declaration, then import it. + }); + + test("nominal_types", () => { + Do( + Import((_, { kernel }) => kernel), + // A newtype introduces a nominal type and its constructor under one name. The unique symbol supplies TypeScript's identity and is not emitted. + Newtype("UserId", userId, (_, { Integer }) => Integer), + Let("owner", (_, { UserId }) => UserId(1n)), + ($, { owner, UserId }, types) => { + expectTypeOf(owner).toEqualTypeOf>(); + expectTypeOf(types.UserId).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + + // Limitation: the representation does not have the nominal type. + // @ts-expect-error An Integer default does not have type UserId. + $.input("id", types.UserId, 2n); + // Workaround: wrap the representation with the constructor. + return $.input("id", types.UserId, UserId(2n)); + }, + ); + + // oxlint-disable-next-line typescript/no-inferrable-types -- shows the rejection after widening drops the unique symbol type + const widened: symbol = Symbol("UserId"); + // @ts-expect-error A widened `symbol` cannot tell declarations apart. + Newtype("UserId", widened, () => kernel.types.Integer); + }); + + test("shadowing", () => { + Do( + Import((_, { kernel }) => kernel), + Newtype("Id", userId, (_, { Integer }) => Integer), + Let("first", (_, { Id }) => Id(1n)), + // A later declaration shadows a name for the steps after it. + Newtype("Id", accountId, (_, { Integer }) => Integer), + // Values and types live in separate environments. This value named `Integer` leaves the type `Integer` untouched. + Let("Integer", ($) => $.literal("not a type")), + (_, { first, Id, Integer }, types) => { + expectTypeOf(first).toEqualTypeOf>(); + expectTypeOf(Integer).toEqualTypeOf>(); + expectTypeOf(types.Integer).toEqualTypeOf< + typeof kernel.types.Integer + >(); + + // Limitation: the same HashQL spelling does not make two nominal types equal. + // @ts-expect-error The shadowed `Id` built `first`. + const mixed: typeof first = Id(2n); + expectTypeOf(mixed); + // Workaround: a binding keeps its declared type, so keep using `first`. + return first; + }, + ); + }); +}); + +describe("expressions", () => { + test("projections", () => { + // Struct fields and tuple positions become typed properties. + expectTypeOf(person.name).toEqualTypeOf>(); + expectTypeOf(person.location[0]).toEqualTypeOf< + Closed + >(); + // `$project` spells the same projection explicitly. + expectTypeOf(person.$project("archived")).toEqualTypeOf< + typeof person.archived + >(); + + // Limitation: direct `then` access would make every handle look like a Promise. + // @ts-expect-error The SDK reserves `then`. + expectTypeOf(person.then); + // Workaround: project the field explicitly. + expectTypeOf(person.$project("then")).toEqualTypeOf< + Closed + >(); + + // @ts-expect-error A struct has only its declared fields. + expectTypeOf(person.email); + }); + + test("indexing", () => { + // Indexing a list or dictionary may find nothing, so the result includes `Null`. + type MaybeInteger = Type.Union< + readonly [Type.PrimitiveInteger, Type.PrimitiveNull] + >; + expectTypeOf(person.scores.$index(0n)).toEqualTypeOf< + Closed + >(); + expectTypeOf(person.labels.$index(text)).toEqualTypeOf< + Closed + >(); + + // Limitation: the key must have the declared key type. + // @ts-expect-error List positions are Integer expressions. + person.scores.$index(text); + // Workaround: supply an Integer-producing expression or a bigint. + expectTypeOf( + person.scores.$index(profile.values.length(text)), + ).toEqualTypeOf>(); + }); + + test("calls", () => { + // A declared function value is callable with typed arguments. + const length = profile.values.length(person.name); + expectTypeOf(length).toEqualTypeOf>(); + // Arguments contribute their inputs to the call. + const typed = profile.values.length( + Expression.input("name", kernel.types.String), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly name: Type.PrimitiveString; + }>(); + + // @ts-expect-error `length` takes a String. + profile.values.length(person.archived); + // @ts-expect-error `length` takes exactly one argument. + profile.values.length(text, text); + }); + + test("query_composition", () => { + // Keep a predicate as an ordinary function and reuse it across queries. + const active = (vertex: Closed): Closed => + vertex.archived.$.isFalse(); + + const built = Do(($, { now }) => + $.query + .entities(now()) + .filter("person", active) + .filter("person", (vertex) => + vertex.name.$.eq($.input("name", kernel.types.String)), + ) + .collect(), + ); + // The query's vertex type comes from the `entities` declaration, and inputs from every filter accumulate in the result. + expectTypeOf(built).toEqualTypeOf< + Built, { readonly name: Type.PrimitiveString }> + >(); + + Do(($, { now }) => { + // @ts-expect-error A filter predicate must return a Boolean. + $.query.entities(now()).filter("person", (vertex) => vertex.name); + return $.literal(true); + }); + }); +}); + +describe("subtyping", () => { + test("numeric_host_types", () => { + // Numeric typing follows the host type, not whether the value has a fraction. + const number = Expression.literal(1); + const integer = Expression.literal(1n); + expectTypeOf(number).toEqualTypeOf>(); + expectTypeOf(integer).toEqualTypeOf>(); + + const acceptsNumber = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("accepts_number"); + expectTypeOf(acceptsNumber(1)).toEqualTypeOf< + Closed + >(); + // @ts-expect-error Integer does not implicitly widen to Number. + acceptsNumber(integer); + // @ts-expect-error A primitive bigint has the same restriction. + acceptsNumber(1n); + const assumed = Expression.assume()(integer); + expectTypeOf(acceptsNumber(assumed)).toEqualTypeOf< + Closed + >(); + }); + + test("explicit_widening", () => { + // HashQL accepts a String where a function expects `String | Null`. The SDK compares semantic types exactly and does not model subtyping. Limitation: the SDK rejects a semantic subtype. + // @ts-expect-error `greet` declares `String | Null`, and `text` is a String. + profile.values.greet(text); + + // Workaround: state the wider type with `Expression.assume`. It changes only the SDK annotation. It emits no conversion and no HashQL type assertion, and the compiler still checks the program. + const widened = Expression.assume()(text); + expectTypeOf(profile.values.greet(widened)).toEqualTypeOf< + Closed + >(); + }); + + test("assumed_inputs", () => { + const name = Expression.input("name", kernel.types.String); + const widened = Expression.assume()(name); + // The input keeps its declared type. Only the expression's annotation changes. + expectTypeOf(widened).toEqualTypeOf< + Expression.Expression< + NullableString, + { readonly name: Type.PrimitiveString } + > + >(); + + // Limitation: `assume` cannot discard a requirement. + // @ts-expect-error The assumed expression still needs `name`. + const closed: Closed = widened; + expectTypeOf(closed); + // Workaround: supply a default to make the input optional for the host. + const defaulted = Expression.assume()( + Expression.input("name", kernel.types.String, ""), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly name?: Type.PrimitiveString; + }>(); + }); +}); + +describe("lexical_scope", () => { + test("callback_scope", () => { + Do( + Let("outer", ($) => $.integer(1)), + ($, { outer }) => + $.if( + $.literal(true), + () => $.Let("inner", () => outer).Expr((_, { inner }) => inner), + () => + $.Expr((_, values) => { + // TypeScript types each callback environment as a record, which gives completion and catches misspelt names while you write. + // @ts-expect-error The sibling branch's binding is absent here. + expectTypeOf(values.inner); + return values.outer; + }), + ), + ); + }); + + test("escaped_reference", () => { + // Limitation: a handle is a reference to a HashQL name. JavaScript can carry it out of the block that binds the name, and TypeScript accepts the result. + let escaped: Closed = Expression.integer(0); + Do( + Let("local", ($) => $.integer(1)), + (_, { local }) => { + escaped = local; + return local; + }, + ); + const outside = Do(() => escaped); + expectTypeOf(outside).toEqualTypeOf< + Built + >(); + + // The SDK neither resolves names nor checks scopes. The HashQL compiler reports `local` as an unresolved variable when it checks the emitted program. Workaround: take handles from the callback arguments of the block that uses them, and leave free-reference checks to the compiler. + }); +}); + +describe("queries_and_let", () => { + test("bound_query", () => { + Do( + Let("people", ($, { now }) => $.query.entities(now())), + (_, { people }) => { + // `Let` gives its binding the plain expression type of the value. + expectTypeOf(people).toEqualTypeOf>(); + + // The binding loses the query methods. This is an unfinished SDK convenience. + // @ts-expect-error `filter` exists only on the query chain. + expectTypeOf(people.filter); + return people; + }, + ); + }); + + test("bind_after_collect", () => { + // Workaround: build the whole chain in one expression, and bind its collected result or the values the query depends on. + const built = Do( + Let("axes", (_, { now }) => now()), + Let("people", ($, { axes }) => + $.query + .entities(axes) + .filter("person", (vertex) => vertex.archived.$.isFalse()) + .collect(), + ), + (_, { people }) => people.$index(0n), + ); + expectTypeOf(built).toEqualTypeOf< + Built, Inputs.Empty> + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts new file mode 100644 index 00000000000..ea49df9e518 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts @@ -0,0 +1,110 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr } from "../src/main.js"; +import { examples } from "./filters.js"; + +const aliases = new Map([ + ["::core::cmp::eq", "=="], + ["::core::bool::and", "&&"], + ["::core::bool::or", "||"], +]); + +// Only spelling differs: qualified exports, explicit projections and the inferred temporal type. +// oxlint-disable-next-line typescript/no-restricted-types -- JSON enters this comparison without a trusted type +const normalize = ( + value: unknown, + imports: ReadonlyMap = new Map(), +): unknown => { + if (typeof value === "string") { + return imports.get(value) ?? value; + } + if (Array.isArray(value)) { + if (value[0] === "::kernel::special_form::use") { + const [, path, selection, body] = value; + const imported = new Map(imports); + if (selection["#tuple"] !== undefined) { + for (const name of selection["#tuple"]) { + imported.set(name, `${path}::${name}`); + } + } else { + for (const [name, alias] of Object.entries(selection["#struct"])) { + if (typeof alias === "string") { + imported.set(alias === "_" ? name : alias, `${path}::${name}`); + } + } + } + return normalize(body, imported); + } + const nodes = value.map((node) => normalize(node, imports)); + const [operation, input, field] = nodes; + let callee = operation; + if (typeof operation === "string") { + callee = operation.replace("::kernel::special_form::", ""); + } + if ( + callee === "access" && + typeof input === "string" && + typeof field === "string" + ) { + return `${input}.${field}`; + } + if ( + callee === "input" && + input === "axis" && + field === "::graph::temporal::QueryTemporalAxes" + ) { + return [callee, input, "_"]; + } + if (typeof callee === "string" && aliases.has(callee)) { + return [aliases.get(callee), ...nodes.slice(1)]; + } + if (operation === callee) { + return nodes; + } + return [callee, ...nodes.slice(1)]; + } + if (value !== null && typeof value === "object") { + if ("#literal" in value) { + return value; + } + return Object.fromEntries( + Object.entries(value).map(([name, member]) => [ + name, + normalize(member, imports), + ]), + ); + } + return value; +}; + +const jexprExamples = examples.filter(({ source }) => + source.endsWith(".jsonc"), +); +const frontendExamples = examples.filter( + ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), +); + +describe("filter_examples", () => { + test.each(examples)("valid_construction: $title", (example) => { + expect.hasAssertions(); + expect(Result.isSuccess(example.root)).toBe(true); + expect(() => + JExpr.make( + Result.getOrThrow(Result.flatMap(example.root, Expression.toJExpr)), + ), + ).not.toThrow(); + }); + + test.each(jexprExamples)("original_query: $title", (example) => { + expect.hasAssertions(); + expect( + normalize(JSON.parse(Result.getOrThrow(example.compile()))), + ).toStrictEqual(normalize(JSON.parse(example.before))); + }); + + test.each(frontendExamples)("frontend_selection: $title", (example) => { + expect.hasAssertions(); + expect(JSON.parse(Result.getOrThrow(example.compile()))).toMatchSnapshot(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts new file mode 100644 index 00000000000..f1237566b84 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters.ts @@ -0,0 +1,378 @@ +/** + * Existing queries, written with the typed HashQL DSL. + * + * Each example pairs its original syntax with a construction using Do and Let. Frontend comparisons cover selection predicates, not subgraph traversal, permissions or UI post-processing. Source paths are relative to the repository root. + * + * The declarations describe only the exports and entity fields used here. Expression helpers emit standard-library calls, and filters introduce explicitly named closure parameters. Compilation emits J-Expr without contacting the graph service. + * + * @module + */ +import { Result } from "effect"; + +import { Import, Module, Program, program } from "../src/main.js"; + +import type { Expression, Type } from "../src/main.js"; +import type * as ProgramError from "../src/program/ProgramError.js"; + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +type ActorGroupEntityUuid = Type.Opaque< + "::graph::types::principal::actor_group::ActorGroupEntityUuid", + Uuid +>; +type WebId = Type.Opaque< + "::graph::types::principal::actor_group::web::WebId", + ActorGroupEntityUuid +>; +type EntityType = Type.Opaque< + `::graph::types::knowledge::entity::${Name}`, + Value +>; +type EntityUuid = EntityType<"EntityUuid", Uuid>; +type DraftId = EntityType<"DraftId", Uuid>; +type None = Type.Opaque<"::core::option::None", Type.PrimitiveNull>; +type Draft = Type.Union< + readonly [None, Type.Opaque<"::core::option::Some", DraftId>] +>; +type EntityId = EntityType< + "EntityId", + Type.Struct<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + readonly draft_id: Draft; + }> +>; +type Entity = EntityType< + "Entity", + Type.Struct<{ + readonly metadata: EntityType< + "EntityMetadata", + Type.Struct<{ + readonly record_id: EntityType< + "RecordId", + Type.Struct<{ readonly entity_id: EntityId }> + >; + readonly archived: Type.PrimitiveBoolean; + }> + >; + }> +>; +type EntityGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Entity }> +>; +type TemporalAxes = Type.Union< + readonly [ + Type.Opaque< + "::graph::temporal::PinnedTransactionTimeTemporalAxes", + Type.Unknown + >, + Type.Opaque< + "::graph::temporal::PinnedDecisionTimeTemporalAxes", + Type.Unknown + >, + ] +>; +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const entity = Result.getOrThrow( + Module.define("::graph::types::knowledge::entity", { + types: { EntityUuid: Module.type() }, + values: { + EntityUuid: Module.value>(), + }, + }), +); +const web = Result.getOrThrow( + Module.define("::graph::types::principal::actor_group::web", { + types: { WebId: Module.type() }, + }), +); +const temporal = Result.getOrThrow( + Module.define("::graph::temporal", { + types: { QueryTemporalAxes: Module.type() }, + }), +); +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Boolean: Module.type() }, + }), +); +const head = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: + Module.value>(), + }, + }), +); +const temporary = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: + Module.value>(), + }, + }), +); + +const { Let, Do } = Program.withPrelude({ + values: { + createUuid: uuid.values.Uuid, + createEntityUuid: entity.values.EntityUuid, + ...head.values, + now: temporary.values.decision_time_now, + }, +}); +interface Example { + readonly title: string; + readonly source: string; + readonly before: string; + readonly root: Result.Result; + readonly compile: () => Result.Result; +} +const example = ( + details: Omit, + root: Result.Result< + Expression.Expression, + ProgramError.Construction + >, +): Example => ({ + ...details, + root, + compile: () => + root.pipe( + Result.flatMap((expression) => Program.compile(program(expression))), + ), +}); + +// Start here: the declarations above replace the generated library bindings still to come. + +const allEntities = example( + { + title: "1. Start a graph query", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc", + before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`, + }, + Program.Do( + Import(() => head, ["entities"]), + Import(() => temporary, { decision_time_now: "now" }), + ($, { now }) => $.query.entities(now()).collect(), + ), +); + +const entityByUuid = example( + { + title: "2. Filter by UUID, then collect", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/collect-filter-graph.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + Do(($, { now, createEntityUuid, createUuid }) => + $.query + .entities(now()) + .filter("vertex", (vertex) => + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid( + createUuid($.literal("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ), + ) + .collect(), + ), +); + +const suppliedTimeAxis = example( + { + title: "3. Supply the temporal axes as a query input", + source: "libs/@local/hashql/mir/tests/ui/reify/graph-read.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["input", "axis", "_"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + Do(($, { createEntityUuid, createUuid }) => + $.query + .entities($.input("axis", temporal.types.QueryTemporalAxes)) + .filter("vertex", (vertex) => + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid( + createUuid($.literal("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ), + ) + .collect(), + ), +); + +const predicateLocalBinding = example( + { + title: "4. Bind a value inside the predicate", + source: + "libs/@local/hashql/hir/tests/ui/lower/graph-hoisting/nested-boolean-expression-outer-let.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["let", "foo", {"#literal": false}, + ["&&", {"#literal": true}, ["||", {"#literal": true}, "foo"]]]]]]`, + }, + Do(($, { now }) => + $.query + .entities(now()) + .filter("vertex", () => + $.Let("foo", ($) => $.literal(false)).Expr(($, { foo }) => + $.literal(true).$.and($.literal(true).$.or(foo)), + ), + ) + .collect(), + ), +); + +// Frontend examples translate selection only. Inputs stand in for the original request parameters. + +const publishedEntityById = example( + { + title: "5. Frontend: look up a published entity", + source: "apps/hash-frontend/src/components/hooks/use-entity-by-id.ts", + before: `// The branch where the supplied entity ID has no draft ID. +{ + filter: { all: [ + { equal: [{ path: ["webId"] }, { parameter: webId }] }, + { equal: [{ path: ["uuid"] }, { parameter: entityUuid }] } + ] }, + includeDrafts: false +}`, + }, + Do( + Let("webId", ($) => $.input("web_id", web.types.WebId)), + Let("entityUuid", ($) => $.input("entity_uuid", entity.types.EntityUuid)), + ($, { now, webId, entityUuid }) => + $.query + .entities(now()) + .filter("vertex", (vertex) => { + const id = vertex.metadata.record_id.entity_id; + return id.web_id.$.eq(webId) + .$.and(id.entity_uuid.$.eq(entityUuid)) + .$.and(id.draft_id.$.isNone()); + }) + .collect(), + ), +); + +const sidebarSelection = example( + { + title: "6. Frontend: the sidebar's web and archive predicates", + source: + "apps/hash-frontend/src/shared/generate-sidebar-entities-query-variables.tsx", + before: `// Predicate excerpt: the separate noisy-system-type exclusion is omitted. +{ + filter: { all: [ + { notEqual: [{ path: ["archived"] }, { parameter: true }] }, + { equal: [{ path: ["webId"] }, { parameter: webId }] } + ] }, + includeDrafts: false +}`, + }, + Do( + Let("webId", ($) => $.input("web_id", web.types.WebId)), + ($, { now, webId }) => + $.query + .entities(now()) + .filter("vertex", (vertex) => + vertex.metadata.record_id.entity_id.web_id.$.eq(webId), + ) + .filter("vertex", (vertex) => + vertex.metadata.archived.$.isFalse().$.and( + vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + ), + ) + .collect(), + ), +); + +const selectedIds = [ + "e2851dbb-7376-4959-9bca-f72cafc4448f", + "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", +] as const; +const anyOfEntityIds = example( + { + title: "7. Frontend: match any supplied entity UUID", + source: "apps/hash-frontend/src/components/hooks/use-users-with-links.ts", + before: `// The ID-list predicate only; the user-type filter and avatar traversal are omitted. +{ any: userAccountIds.map((actorId) => ({ + equal: [{ path: ["uuid"] }, { parameter: actorId }] +})) }`, + }, + Do(($, { now, createEntityUuid, createUuid }) => + $.query + .entities(now()) + .filter("vertex", (vertex) => { + let matches = $.literal(false); + for (const entityUuid of selectedIds) { + matches = matches.$.or( + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid(createUuid($.literal(entityUuid))), + ), + ); + } + return matches; + }) + .collect(), + ), +); + +const optionalDrafts = example( + { + title: "8. Frontend: make draft inclusion a query-time choice", + source: "apps/hash-frontend/src/pages/shared/entity-selector.tsx", + before: `// The request flag only; the selector's later deduplication is omitted. +{ includeDrafts }`, + }, + Do( + Let("includeDrafts", ($) => + $.input("include_drafts", kernel.types.Boolean, $.literal(false)), + ), + ($, { now, includeDrafts }) => + $.query + .entities(now()) + .filter("vertex", (vertex) => + $.if( + includeDrafts, + () => $.literal(true), + () => vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + ), + ) + .collect(), + ), +); + +/** Before/after examples whose compile methods return the emitted J-Expr. */ +export const examples: readonly Example[] = [ + allEntities, + entityByUuid, + suppliedTimeAxis, + predicateLocalBinding, + publishedEntityById, + sidebarSelection, + anyOfEntityIds, + optionalDrafts, +]; diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json index 02acf0b5561..d0b8c4483d6 100644 --- a/libs/@local/hashql/sdk/typescript/package.json +++ b/libs/@local/hashql/sdk/typescript/package.json @@ -19,7 +19,12 @@ "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", "lint:tsc": "tsc --noEmit", - "test:unit": "vitest run --typecheck --passWithNoTests" + "test:unit": "vitest run --typecheck" + }, + "dependencies": { + "effect": "4.0.3", + "esrap": "2.4.0", + "oxc-parser": "0.152.0" }, "devDependencies": { "@local/oxlint": "workspace:*", diff --git a/libs/@local/hashql/sdk/typescript/src/internal/array.ts b/libs/@local/hashql/sdk/typescript/src/internal/array.ts new file mode 100644 index 00000000000..df3e6846929 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/array.ts @@ -0,0 +1,11 @@ +/** + * Array helpers that narrow readonly unions, which `Array.isArray` does not. + * + * @internal + */ + +/** Narrows `value` to its readonly array members. */ +// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- `T` accepts the non-array members without widening to `unknown` +export const isReadonlyArray = ( + value: T | readonly E[], +): value is readonly E[] => Array.isArray(value); diff --git a/libs/@local/hashql/sdk/typescript/src/internal/scan.ts b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts new file mode 100644 index 00000000000..d79d26d4bf2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts @@ -0,0 +1,159 @@ +/** + * Scans HashQL identifiers and paths while preserving quoted separators. + * + * Backtick-quoted identifiers can contain `::`. Each identifier must consume its closing backtick before a path separator can begin. + * + * @internal + */ + +import { Filter, Option } from "effect"; + +/** The kinds of identifier, matching `IdentKind` in `hashql-core`. */ +export type Kind = "Lexical" | "Symbol" | "BaseUrl"; + +/** An identifier found in the input, without its backticks. */ +export interface ScanIdent { + readonly kind: Kind; + readonly value: string; + /** Index just past the identifier, including any closing backtick. */ + readonly end: number; +} + +const backtick = "`"; + +/** ASCII operator characters, or any non-ASCII punctuation or symbol. */ +export const symbolCharacterPattern: string = String.raw`(?:[!#$%&*+./<=>?@\\^|~\[\]-]|(?![\0-\x7F])[\p{P}\p{S}])`; + +/** RFC 3986 reserved, unreserved and percent characters (`ALLOWED_URL_CHARS`). */ +const urlChar = String.raw`[\w!#$%&'()*+,./:;=?@\[\]~-]`; + +/** A Unicode character that can start a lexical identifier. */ +export const lexicalStartPattern: string = String.raw`\p{XID_Start}`; + +/** A Unicode character that can follow the first character of a lexical identifier. */ +export const lexicalContinuePattern: string = String.raw`\p{XID_Continue}`; + +/** `XID_Start XID_Continue*`, or `_` followed by at least one `XID_Continue`. */ +export const lexicalPattern: string = String.raw`(?:${lexicalStartPattern}${lexicalContinuePattern}*|_${lexicalContinuePattern}+)`; + +/** One or more symbol characters. */ +export const symbolPattern: string = String.raw`(?:${symbolCharacterPattern}+)`; + +/** + * An HTTP(S) URL-shaped identifier ending in `/`. + * + * The first character after `//` must be a non-slash URL character. This checks spelling rather than URL validity. + */ +export const baseUrlPattern: string = String.raw`(?:https?://${urlChar.replace("/", "")}${urlChar}*/)`; + +const lexical = new RegExp(lexicalPattern, "uy"); +const symbol = new RegExp(symbolPattern, "uy"); +const escapedSymbol = new RegExp( + `${backtick}(${symbolPattern})${backtick}`, + "uy", +); +const escapedBaseUrl = new RegExp( + `${backtick}(${baseUrlPattern})${backtick}`, + "uy", +); + +/** `ws("::")` from the backend: a separator with optional surrounding whitespace. */ +const separator = /[\t\n\r ]*::[\t\n\r ]*/uy; + +/** A leading `::` marking a rooted path, with optional trailing whitespace. */ +const root = /::[\t\n\r ]*/uy; + +const matchAtRaw = ( + expression: RegExp, + input: string, + start: number, +): Option.Option => { + expression.lastIndex = start; + return Option.fromNullishOr(expression.exec(input)); +}; + +const matchAt = + ( + expression: RegExp, + input: string, + start: number, + ): ((kind: Kind, group: 0 | 1) => Option.Option) => + (kind: Kind, group: 0 | 1): Option.Option => + Option.filterMap( + matchAtRaw(expression, input, start), + Filter.fromPredicateOption((match) => + Option.fromNullishOr(match[group]).pipe( + Option.map((value) => ({ + kind, + value, + end: match.index + match[0].length, + })), + ), + ), + ); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- internal only function +export const scanIdent: ( + input: string, + start: number, +) => Option.Option = (input, start) => { + if (input.startsWith(backtick, start)) { + return Option.orElse( + matchAt(escapedSymbol, input, start)("Symbol", 1), + () => matchAt(escapedBaseUrl, input, start)("BaseUrl", 1), + ); + } + + return Option.orElse(matchAt(lexical, input, start)("Lexical", 0), () => + matchAt(symbol, input, start)("Symbol", 0), + ); +}; + +export const scanIdentExact = (input: string): Option.Option => + scanIdent(input, 0).pipe( + Option.filter((ident) => ident.end === input.length), + ); + +/** A path split into its parts. */ +export interface ScanPath { + readonly rooted: boolean; + readonly segments: readonly [ScanIdent, ...ScanIdent[]]; +} + +/** + * Splits `input` into an optional leading `::` and `::`-separated identifiers. + * + * Whitespace is allowed around separators, as in the backend. Leading and + * trailing whitespace, empty segments and per-segment generic arguments are + * rejected. + */ +export const scanPath = (input: string): Option.Option => { + const rootMatch = matchAtRaw(root, input, 0); + const first = scanIdent(input, rootMatch.valueOrUndefined?.[0].length ?? 0); + + if (Option.isNone(first)) { + return Option.none(); + } + + const segments: [ScanIdent, ...ScanIdent[]] = [first.value]; + let position = first.value.end; + + while (position < input.length) { + const next = matchAtRaw(separator, input, position); + + if (Option.isNone(next)) { + return Option.none(); + } + + const segment = scanIdent(input, next.value.index + next.value[0].length); + + if (Option.isNone(segment)) { + return Option.none(); + } + + segments.push(segment.value); + position = segment.value.end; + } + + return Option.some({ rooted: rootMatch._tag === "Some", segments }); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts new file mode 100644 index 00000000000..7987f6b262a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts @@ -0,0 +1,57 @@ +/** + * Constructive arbitrary generation for schema string patterns. + * + * Effect's arbitrary compiler requires explicit character ranges for Unicode properties and lookarounds. Generation hints supply those ranges while schema validation retains the original pattern. + * + * @internal + */ +import { Schema } from "effect"; +import { memoize } from "effect/Function"; + +/** Expands a character pattern into Unicode ranges for arbitrary generation. */ +export const characterClass: (pattern: Readonly) => string = memoize( + (pattern): string => { + const maximumCodePoint = 1_114_111; + const hexadecimalRadix = 16; + const ranges: string[] = []; + let start: number | undefined = undefined; + + // include a sentinel after the final code point to close any remaining range + for (let codePoint = 0; codePoint <= maximumCodePoint + 1; codePoint += 1) { + if ( + codePoint <= maximumCodePoint && + pattern.test(String.fromCodePoint(codePoint)) + ) { + start ??= codePoint; + } else if (start !== undefined) { + const first = `\\u{${start.toString(hexadecimalRadix)}}`; + if (start === codePoint - 1) { + ranges.push(first); + } else { + const last = `\\u{${(codePoint - 1).toString(hexadecimalRadix)}}`; + ranges.push(`${first}-${last}`); + } + start = undefined; + } + } + + return `[${ranges.join("")}]`; + }, +); + +/** Requires the entire value to match a pattern, with separate generation hints. */ +export const exactly = ( + pattern: string, + generatePattern: () => string = () => pattern, +): Schema.String => + Schema.String.check( + // `$` also matches before a final line terminator. The lookahead requires end of input. + Schema.isPattern(new RegExp(`^(?:${pattern})(?![\\s\\S])`, "u"), { + arbitraryConstraint: { + // expansion runs only during arbitrary derivation, using the same Unicode tables as validation + get patterns(): readonly [Schema.Annotations.ToArbitrary.Pattern] { + return [{ source: `^(?:${generatePattern()})$`, flags: "u" }]; + }, + }, + }), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts new file mode 100644 index 00000000000..fab3da8e81f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Call} values. */ +export const Schema: typeof Defs.Call = Defs.Call; + +/** + * A function expression followed by positional or labeled arguments. + * + * The array contains at least the function expression. A function with no arguments is a one-element array. + */ +export type Call = Defs.CallType; +/** The schema-encoded representation of {@link Call}. */ +export type Encoded = Defs.CallEncoded; + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a call and its arguments. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Call = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts new file mode 100644 index 00000000000..cdac453e49a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts @@ -0,0 +1,56 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Dict} values. */ +export const Schema: typeof Defs.Dict = Defs.Dict; + +/** + * A dictionary constructor with string keys or expression-keyed entries. + * + * Record keys are literal strings. In an array of pairs, both the key and the value are expressions. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * JExpr.compile(JExpr.dict({ "user.name": JExpr.literal("Alice") })); + * // => '{"#dict":{"user.name":{"#literal":"Alice"}}}' + * + * JExpr.compile(JExpr.dict([["user.name", JExpr.literal("Alice")]])); + * // => '{"#dict":[["user.name",{"#literal":"Alice"}]]}' + * ``` + */ +export interface Dict extends Defs.DictType {} +/** The schema-encoded representation of {@link Dict}. */ +export interface Encoded extends Defs.DictEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks dictionary entries and an optional type annotation. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Dict = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts new file mode 100644 index 00000000000..2a11c45438b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Float} values. */ +export const Schema: typeof Defs.Float = Defs.Float; + +/** + * A float's source text, including a fraction or exponent. + * + * `value` uses JSON number syntax, such as `"1.0"` or `"1e3"`. Keeping the text preserves the distinction between an integer and an integral float. + */ +export interface Float extends Defs.FloatType {} +/** The schema-encoded representation of {@link Float}. */ +export interface Encoded extends Defs.FloatEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks the spelling of a float literal. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Float = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts new file mode 100644 index 00000000000..ecf77b43dbb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts @@ -0,0 +1,87 @@ +import { Record } from "effect"; +import { pipe } from "effect/Function"; + +import { isReadonlyArray } from "../internal/array.js"; +import * as Type from "./type/index.js"; + +import type * as Defs from "./schema.js"; + +/** The `_` placeholder, which asks the compiler to infer a type. */ +const inferred = "_" as const; + +export { inferred as infer }; + +/** An explicit type or {@link infer}, accepted by {@link fn} for parameter and return types. */ +export type TypeArgument = Type.Type | typeof inferred; + +/** Renders a type argument, preserving the inference placeholder. */ +const compileType = (type: TypeArgument): Defs.ExpressionType => { + if (type === inferred) { + return inferred; + } + + return Type.toExpression(type); +}; + +/** A closure's signature and body, accepted by {@link fn}. */ +export interface FnOptions { + /** + * Type parameter names, or a record mapping each name to its bound. + * + * Use {@link infer} for an unbounded parameter in a record. Defaults to no generic parameters. + */ + readonly generics?: + | readonly string[] + | Record.ReadonlyRecord; + /** Parameter names and types, in argument order. Use {@link infer} for an inferred type. */ + readonly params: Record.ReadonlyRecord; + /** The return type. Defaults to {@link infer}. */ + readonly returns?: TypeArgument; + /** The expression that computes the closure's result. */ + readonly body: Defs.ExpressionType; +} + +/** Renders named types as a struct of type expressions. */ +const compileTypes = ( + types: Record.ReadonlyRecord, +): Defs.StructType => ({ "#struct": pipe(types, Record.map(compileType)) }); + +/** Renders unbounded names as a tuple and named bounds as a struct. */ +const compileGenerics = ( + generics: FnOptions["generics"], +): Defs.TupleType | Defs.StructType => { + if (generics === undefined) { + return { "#tuple": [] }; + } + + if (isReadonlyArray(generics)) { + return { "#tuple": generics }; + } + + return compileTypes(generics); +}; + +/** + * Defines a closure with named parameters. + * + * Parameter names are in scope in the body. Their record order determines the argument order. The return type defaults to {@link infer}. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * const isDraft = JExpr.fn({ + * params: { entity: JExpr.infer }, + * body: JExpr.call("==", "entity.draft_id", JExpr.literal(null)), + * }); + * JExpr.compile(isDraft); + * // => '["fn",{"#tuple":[]},{"#struct":{"entity":"_"}},"_",["==","entity.draft_id",{"#literal":null}]]' + * ``` + */ +export const fn = (options: FnOptions): Defs.CallType => [ + "fn", + compileGenerics(options.generics), + compileTypes(options.params), + compileType(options.returns ?? inferred), + options.body, +]; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts new file mode 100644 index 00000000000..6dee2cfdbdf --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts @@ -0,0 +1,131 @@ +/** + * HashQL identifiers. + * + * An {@link Ident} stores its kind and its value without backticks, like `Ident` + * in `hashql-core`. Use {@link decodeResult} to read source syntax such as `foo`, `+`, + * `` `+` `` or `` `https://example.com/` ``, and {@link compile} to write it back. + * + * @module + */ +import { Schema as $Schema, Option, SchemaGetter, SchemaParser } from "effect"; +import { compose } from "effect/Function"; + +import * as Scan from "../internal/scan.js"; +import { characterClass, exactly } from "../internal/schema-arbitrary.js"; + +import type { Effect, SchemaIssue } from "effect"; +import type { Result } from "effect/Result"; +import type { ParseOptions } from "effect/SchemaAST"; + +const lexicalStart = new RegExp(Scan.lexicalStartPattern, "u"); +const lexicalContinue = new RegExp(Scan.lexicalContinuePattern, "u"); +const symbolCharacter = new RegExp(Scan.symbolCharacterPattern, "u"); + +const LexicalSchema: $Schema.TaggedStruct< + "Lexical", + { value: $Schema.String } +> = $Schema.TaggedStruct("Lexical", { + value: exactly(Scan.lexicalPattern, () => + Scan.lexicalPattern + .replaceAll(Scan.lexicalStartPattern, characterClass(lexicalStart)) + .replaceAll(Scan.lexicalContinuePattern, characterClass(lexicalContinue)), + ), +}); + +const SymbolSchema: $Schema.TaggedStruct<"Symbol", { value: $Schema.String }> = + $Schema.TaggedStruct("Symbol", { + value: exactly(Scan.symbolPattern, () => + Scan.symbolPattern.replace( + Scan.symbolCharacterPattern, + characterClass(symbolCharacter), + ), + ), + }); + +const BaseUrlSchema: $Schema.TaggedStruct< + "BaseUrl", + { value: $Schema.String } +> = $Schema.TaggedStruct("BaseUrl", { value: exactly(Scan.baseUrlPattern) }); + +/** + * Schema for identifier objects with unquoted values. + * + * `Arbitrary.schema(SchemaFromSelf)` generates every identifier kind. Derivation computes and caches character ranges from the runtime's Unicode tables on first use. + */ +export const SchemaFromSelf: $Schema.toTaggedUnion< + "_tag", + readonly [typeof LexicalSchema, typeof SymbolSchema, typeof BaseUrlSchema] +> = $Schema + .Union([LexicalSchema, SymbolSchema, BaseUrlSchema]) + .pipe($Schema.toTaggedUnion("_tag")); + +/** + * Codec between source syntax and an identifier object. + * + * Encoding quotes symbol and base-URL identifiers. Arbitrary generation uses the decoded {@link SchemaFromSelf}. + */ +export const Schema: $Schema.decodeTo< + typeof SchemaFromSelf, + typeof $Schema.NonEmptyString +> = $Schema.NonEmptyString.pipe( + $Schema.decodeTo(SchemaFromSelf, { + decode: SchemaGetter.transformOptional( + compose( + Option.andThen(Scan.scanIdentExact), + // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular + Option.map((value) => fromScanned(value)), + ), + ), + // oxlint-disable-next-line no-use-before-define -- lazy evaluation that is otherwise circular + encode: SchemaGetter.transform((value) => compile(value)), + }), +); + +export type Ident = (typeof Schema)["Type"]; + +export type Encoded = (typeof Schema)["Encoded"]; + +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Constructs an identifier from its tagged object representation. + * + * @throws {Error} If `value` is not valid for the given kind. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Ident = + SchemaParser.make(Schema); + +/** Constructs an identifier with schema failures in the error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Constructs an identifier, returning `None` if validation fails. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** @internal */ +export const fromScanned = (scanned: Scan.ScanIdent): Ident => ({ + _tag: scanned.kind, + value: scanned.value, +}); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const decodeResult: ( + input: string, + options?: ParseOptions, +) => Result = SchemaParser.decodeResult(Schema); + +export const compile = (ident: Ident): string => { + if (ident._tag === "Lexical") { + return ident.value; + } + + return `\`${ident.value}\``; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts new file mode 100644 index 00000000000..fac3248a271 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts @@ -0,0 +1,48 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Identifier} values. */ +export const Schema: typeof Defs.Identifier = Defs.Identifier; + +/** + * Source text interpreted as a path, type or argument shorthand. + * + * The schema accepts any string. HashQL parses it according to its position in the expression. For example, `"user"` is a path and `":user"` is a labeled-argument shorthand in a call. + */ +export type Identifier = Defs.IdentifierType; +/** The schema-encoded representation of {@link Identifier}. */ +export type Encoded = Defs.IdentifierEncoded; + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Accepts source text for a string expression. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Identifier = SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts new file mode 100644 index 00000000000..a7ced381c8a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts @@ -0,0 +1,54 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Integer} values. */ +export const Schema: typeof Defs.Integer = Defs.Integer; + +/** + * An arbitrary-precision integer's decimal source text. + * + * `value` uses JSON integer syntax, such as `"-42"`. It has no fraction or exponent. Keeping the text avoids JavaScript's numeric precision limit. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * JExpr.compile(JExpr.integer(42)); // => '{"#literal":42}' + * JExpr.compile(JExpr.integer(2n ** 64n)); // => '{"#literal":18446744073709551616}' + * ``` + */ +export interface Integer extends Defs.IntegerType {} +/** The schema-encoded representation of {@link Integer}. */ +export interface Encoded extends Defs.IntegerEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks the spelling of an integer literal. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Integer = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts new file mode 100644 index 00000000000..4c54f62fbe7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts @@ -0,0 +1,48 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link LabeledArgument} values. */ +export const Schema: typeof Defs.LabeledArgument = Defs.LabeledArgument; + +/** + * A call argument labeled with a parameter name. + * + * The object has exactly one key: `:` followed by an identifier. The value is an expression. The argument still occupies a position in the call's argument list. + */ +export interface LabeledArgument extends Defs.LabeledArgumentType {} +/** The schema-encoded representation of {@link LabeledArgument}. */ +export interface Encoded extends Defs.LabeledArgumentEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a single labeled argument and its value. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => LabeledArgument = SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts new file mode 100644 index 00000000000..3c0c265592b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link List} values. */ +export const Schema: typeof Defs.List = Defs.List; + +/** + * A list constructor whose elements are expressions. + * + * The schema checks each expression. HashQL determines their common element type. + */ +export interface List extends Defs.ListType {} +/** The schema-encoded representation of {@link List}. */ +export interface Encoded extends Defs.ListEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks list elements and an optional type annotation. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => List = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts new file mode 100644 index 00000000000..52788b09542 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts @@ -0,0 +1,46 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Literal} values. */ +export const Schema: typeof Defs.Literal = Defs.Literal; + +/** + * A primitive value in a `#literal` constructor. + * + * Numeric values use {@link Defs.Integer} or {@link Defs.Float} to preserve their source text. Strings, booleans and `null` appear directly under `#literal`. + */ +export interface Literal extends Defs.LiteralType {} +/** The schema-encoded representation of {@link Literal}. */ +export interface Encoded extends Defs.LiteralEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks a literal and an optional type annotation. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Literal = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts new file mode 100644 index 00000000000..4257d1fce1c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts @@ -0,0 +1,109 @@ +/** + * HashQL paths with an optional root and a nonempty sequence of identifiers. + * + * {@link SchemaFromSelf} validates path objects and supports schema-derived arbitrary generation. {@link Schema} decodes source text without treating `::` inside a quoted identifier as a separator. + * + * @module + */ +import { + Schema as $Schema, + Array, + Option, + SchemaGetter, + SchemaParser, + Struct, +} from "effect"; +import { compose } from "effect/Function"; + +import * as Scan from "../internal/scan.js"; +import * as Ident from "./Ident.js"; + +import type { Effect, SchemaIssue } from "effect"; +import type { Result } from "effect/Result"; +import type { ParseOptions } from "effect/SchemaAST"; + +/** + * Schema for path objects containing decoded identifiers. + * + * `Arbitrary.schema(SchemaFromSelf)` generates rooted and relative paths with at least one segment. + */ +export const SchemaFromSelf: $Schema.Struct<{ + rooted: $Schema.Boolean; + segments: $Schema.NonEmptyArray; +}> = $Schema.Struct({ + rooted: $Schema.Boolean, + segments: $Schema.NonEmptyArray(Ident.SchemaFromSelf), +}); + +/** Codec between path source text and a {@link Path} object. */ +export const Schema: $Schema.decodeTo< + typeof SchemaFromSelf, + typeof $Schema.NonEmptyString +> = $Schema.NonEmptyString.pipe( + $Schema.decodeTo(SchemaFromSelf, { + decode: SchemaGetter.transformOptional( + compose( + Option.andThen(Scan.scanPath), + Option.map( + Struct.evolve({ + segments: Array.map(Ident.fromScanned), + }), + ), + ), + ), + // oxlint-disable-next-line no-use-before-define -- circular evaluation + encode: SchemaGetter.transform((path) => compile(path)), + }), +); + +export interface Path extends $Schema.Schema.Type {} + +/** Source text representing a {@link Path}, including quotes and separators. */ +export type Encoded = $Schema.Codec.Encoded; + +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Constructs a path from its object representation. + * + * @throws {Error} If a segment is not a valid identifier. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Path = + SchemaParser.make(Schema); + +/** Constructs a path with schema failures in the error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Constructs a path, returning `None` if validation fails. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +export const compile = (path: Path): string => { + const segments = path.segments + .map((segment) => Ident.compile(segment)) + .join("::"); + + if (path.rooted) { + return `::${segments}`; + } + + return segments; +}; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const decodeResult: ( + input: string, + options?: ParseOptions, +) => Result = SchemaParser.decodeResult(Schema); + +export const isAbsolute = (path: Path): boolean => path.rooted; + +export const isRelative = (path: Path): boolean => !path.rooted; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts new file mode 100644 index 00000000000..4e05eb93fc8 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Struct} values. */ +export const Schema: typeof Defs.Struct = Defs.Struct; + +/** + * A data constructor with identifier-named fields. + * + * Each field contains an expression. The schema checks the field names as well as their values. + */ +export interface Struct extends Defs.StructType {} +/** The schema-encoded representation of {@link Struct}. */ +export interface Encoded extends Defs.StructEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks field names, field expressions and an optional type annotation. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Struct = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts new file mode 100644 index 00000000000..56358629898 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts @@ -0,0 +1,45 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +/** Schema for {@link Tuple} values. */ +export const Schema: typeof Defs.Tuple = Defs.Tuple; + +/** + * A fixed-length sequence of expressions with a type for each position. + * + * An empty tuple is valid. HashQL determines each element's type. + */ +export interface Tuple extends Defs.TupleType {} +/** The schema-encoded representation of {@link Tuple}. */ +export interface Encoded extends Defs.TupleEncoded {} + +/** Input accepted by {@link make} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks tuple elements and an optional type annotation. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * + * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Tuple = + SchemaParser.make(Schema); + +/** Runs {@link make} validation with schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** Runs {@link make} validation, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts new file mode 100644 index 00000000000..236449fb41a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts @@ -0,0 +1,153 @@ +/** + * Writes J-Expr JSON while preserving numeric literal spellings. + * + * @internal + */ +import { Record } from "effect"; + +import { isReadonlyArray } from "../internal/array.js"; + +import type * as Defs from "./schema.js"; + +/** An SDK expression tree to render. */ +type Expression = Defs.ExpressionType; + +/** Quotes object keys and joins already-rendered values. */ +const compileObject = ( + entries: readonly (readonly [string, string])[], +): string => + `{${entries.map(([key, value]) => `${JSON.stringify(key)}:${value}`).join(",")}}`; + +/** Joins already-rendered elements into a JSON array. */ +const compileArray = (items: readonly string[]): string => + `[${items.join(",")}]`; + +/** Adds an optional type annotation to a rendered data constructor. */ +const compileAnnotated = ( + key: string, + value: string, + type: string | undefined, +): string => { + if (type === undefined) { + return compileObject([[key, value]]); + } + + return compileObject([ + [key, value], + ["#type", JSON.stringify(type)], + ]); +}; + +/** Emits numeric source text directly and JSON-encodes other primitive values. */ +const compileLiteral = (value: Defs.LiteralType["#literal"]): string => { + if (value !== null && typeof value === "object") { + return value.value; + } + + return JSON.stringify(value); +}; + +/** Distinguishes a standalone expression from a labeled-argument object. */ +const isPositional = ( + argument: Expression | Defs.LabeledArgumentType, +): argument is Expression => + typeof argument === "string" || + isReadonlyArray(argument) || + !Object.keys(argument).every((key) => key.startsWith(":")); + +/** + * Renders an expression tree as compact J-Expr JSON. + * + * Numeric literals keep their stored spelling: an integer retains its full precision and an integral float retains its fraction or exponent. `JSON.stringify` would serialize the SDK's tagged numeric objects instead. + * + * Validation is separate. Use `JExpr.make` on the tree before compiling it when you need schema checks. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * JExpr.compile(JExpr.list(JExpr.float(1), JExpr.float(2.5))); + * // => '{"#list":[{"#literal":1.0},{"#literal":2.5}]}' + * ``` + */ +export const compile = (expression: Expression): string => { + if (typeof expression === "string") { + return JSON.stringify(expression); + } + + if (isReadonlyArray(expression)) { + return compileArray( + expression.map((argument) => { + if (isPositional(argument)) { + return compile(argument); + } + + return compileObject( + Record.toEntries(argument).map(([key, value]) => [ + key, + compile(value), + ]), + ); + }), + ); + } + + if ("#literal" in expression) { + return compileAnnotated( + "#literal", + compileLiteral(expression["#literal"]), + expression["#type"], + ); + } + + if ("#struct" in expression) { + return compileAnnotated( + "#struct", + compileObject( + Record.toEntries(expression["#struct"]).map(([key, value]) => [ + key, + compile(value), + ]), + ), + expression["#type"], + ); + } + + if ("#tuple" in expression) { + return compileAnnotated( + "#tuple", + compileArray(expression["#tuple"].map(compile)), + expression["#type"], + ); + } + + if ("#list" in expression) { + return compileAnnotated( + "#list", + compileArray(expression["#list"].map(compile)), + expression["#type"], + ); + } + + const entries = expression["#dict"]; + + if (isReadonlyArray(entries)) { + return compileAnnotated( + "#dict", + compileArray( + entries.map(([key, value]) => + compileArray([compile(key), compile(value)]), + ), + ), + expression["#type"], + ); + } + + return compileAnnotated( + "#dict", + compileObject( + Record.toEntries(entries).map(([key, value]) => [key, compile(value)]), + ), + expression["#type"], + ); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts new file mode 100644 index 00000000000..96522b32e65 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts @@ -0,0 +1,444 @@ +/** + * Builds HashQL queries as J-Expr expression trees. + * + * A string such as `"user"` refers to a value by name. Use {@link literal} for data: `literal("user")` is the string value `"user"`. Arrays represent calls, while objects with keys such as `#list` or `#struct` construct data. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * const query = JExpr.let("name", JExpr.literal("Alice"), "name"); + * JExpr.compile(JExpr.make(query)); + * // => '["let","name",{"#literal":"Alice"},"name"]' + * ``` + * + * The helpers assemble expressions without validating them. Use {@link make} to check the finished tree and {@link compile} to produce JSON text. {@link makeEffect} retains validation issues in an Effect, and {@link makeOption} returns only success or failure. The schema checks the tree's structure. Parsing strings as paths or types, resolving names and type checking belong to the HashQL compiler. + * + * Use {@link compile} even when the tree looks like ordinary JSON. Numeric literals retain their source text to preserve large integers and the distinction between `1` and `1.0`. + * + * @module + */ +import { SchemaParser } from "effect"; +import { dual } from "effect/Function"; + +import { isReadonlyArray } from "../internal/array.js"; +import * as Defs from "./schema.js"; +import * as Type from "./type/index.js"; + +import type * as Reference from "./type/Reference.js"; +import type { + Schema as $Schema, + Effect, + Option, + Record, + SchemaIssue, +} from "effect"; + +export * as Call from "./Call.js"; +export * as Dict from "./Dict.js"; +export * as Float from "./Float.js"; +export * as Identifier from "./Identifier.js"; +export * as Integer from "./Integer.js"; +export * as LabeledArgument from "./LabeledArgument.js"; +export * as List from "./List.js"; +export * as Literal from "./Literal.js"; +export * as Struct from "./Struct.js"; +export * as Tuple from "./Tuple.js"; +export * as Ident from "./Ident.js"; +export * as Path from "./Path.js"; +export { compile } from "./compile.js"; + +/** + * Schema for the SDK's expression-tree representation. + * + * Encoding produces {@link Encoded}, including tagged numeric literals. Use {@link compile} to produce J-Expr JSON text. + */ +export const Schema: typeof Defs.Expression = Defs.Expression; + +/** A J-Expr expression: a call, a data constructor or a string. */ +export type Expression = Defs.ExpressionType; + +/** The schema-encoded tree, with the same tagged numeric literals as {@link Expression}. */ +export type Encoded = Defs.ExpressionEncoded; + +/** Constructor input accepted by {@link Schema} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Checks an expression tree against {@link Schema}. + * + * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} when only validity matters, or {@link makeEffect} to inspect a {@link SchemaIssue.Issue} with the failing node's location. + * + * @throws {Error} If validation fails. The error carries a {@link SchemaIssue.Issue} in its `cause`. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as JExpr from "./index.js"; + * + * const query = JExpr.make(JExpr.struct({ name: JExpr.literal("Alice") })); + * JExpr.compile(query); // => '{"#struct":{"name":{"#literal":"Alice"}}}' + * + * Option.isNone(JExpr.makeOption(JExpr.struct({ "not an ident": "x" }))); // => true + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Expression = SchemaParser.make(Schema); + +/** Checks a tree with {@link make}'s options, retaining schema issues in the effect's error channel. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +/** Checks a tree with {@link make}'s options, returning `None` for a schema failure. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +export { fn, infer } from "./Function.js"; +export type { FnOptions, TypeArgument } from "./Function.js"; + +/** Data constructors that accept a `#type` annotation through {@link typed}. */ +export type Annotatable = + | Defs.StructType + | Defs.TupleType + | Defs.DictType + | Defs.ListType + | Defs.LiteralType; + +/** + * Creates a whole-number literal without a size limit for `bigint` inputs. + * + * Use a `bigint` for integers beyond `Number.MAX_SAFE_INTEGER`. A `number` may already have lost precision before this call. It must be an integer to pass {@link make} validation. See {@link Integer.Integer} for a precision example. + */ +export const integer = (value: number | bigint): Defs.LiteralType => { + if (typeof value === "number" && Number.isInteger(value)) { + return { "#literal": { _tag: "Integer", value: BigInt(value).toString() } }; + } + + return { "#literal": { _tag: "Integer", value: String(value) } }; +}; + +/** + * Creates a numeric literal that HashQL parses as a float. + * + * A float's JSON spelling must contain a fraction or exponent. Integral values therefore retain a fraction: `float(1)` compiles to `1.0`. Negative zero compiles to `-0.0`. `NaN` and infinities fail {@link make} validation. See {@link compile} for float examples. + */ +export const float = (value: number): Defs.LiteralType => { + if (Object.is(value, -0)) { + return { "#literal": { _tag: "Float", value: "-0.0" } }; + } + + const text = String(value); + + if (Number.isInteger(value) && !text.includes("e")) { + return { "#literal": { _tag: "Float", value: `${text}.0` } }; + } + + return { "#literal": { _tag: "Float", value: text } }; +}; + +/** + * Creates a literal from a primitive value. + * + * Integral numbers and `bigint` values become {@link integer} literals. Other numbers become {@link float} literals. Use {@link float} explicitly to keep `1` as `1.0` or preserve negative zero. See {@link make} for a string literal example. + */ +export const literal = ( + value: string | number | bigint | boolean | null, +): Defs.LiteralType => { + if (typeof value === "bigint") { + return integer(value); + } + + if (typeof value === "number") { + if (Number.isInteger(value)) { + return integer(value); + } + + return float(value); + } + + return { "#literal": value }; +}; + +/** + * Creates a list whose elements share a type. + * + * HashQL infers the element type. Use {@link tuple} when each position needs its own type. See {@link compile} for a list example. + */ +export const list = (...items: readonly Expression[]): Defs.ListType => ({ + "#list": items, +}); + +/** Creates a fixed-length sequence with a type for each position. */ +export const tuple = (...items: readonly Expression[]): Defs.TupleType => ({ + "#tuple": items, +}); + +/** + * Creates a struct with named fields. + * + * Field names must be identifiers, such as `name` or `` `+` ``. Each field has its own type. Use {@link dict} for arbitrary string keys. Fields follow the record's own enumerable string-key order. See {@link make} for a struct example. + */ +export const struct = ( + fields: Record.ReadonlyRecord, +): Defs.StructType => ({ "#struct": fields }); + +/** + * Creates a dictionary from string keys or key expressions. + * + * Record keys are literal strings, even when they look like paths. Use `[key, value]` pairs to compute keys from expressions. See {@link Dict.Dict} for examples of both key forms. + */ +export const dict = ( + entries: + | Record.ReadonlyRecord + | readonly (readonly [Expression, Expression])[], +): Defs.DictType => ({ "#dict": entries }); + +/** + * Sets a data constructor's type annotation. + * + * Replaces any existing `#type` annotation. Calls and paths cannot carry this field. Use {@link asType | as} to assert their types. + * + * @example + * ```ts + * import { Option, pipe } from "effect"; + * import * as Type from "./type/index.js"; + * import * as JExpr from "./index.js"; + * + * const float = Option.getOrThrow(Type.reference("Float")); + * JExpr.compile(pipe(JExpr.literal(3.14), JExpr.typed(float))); + * // => '{"#literal":3.14,"#type":"Float"}' + * ``` + */ +export const typed: { + (type: Type.Type): (self: E) => E; + (self: E, type: Type.Type): E; +} = dual( + 2, + (self: E, type: Type.Type): E => ({ + ...self, + "#type": Type.compile(type), + }), +); + +/** + * Creates a labeled argument for {@link call}, such as `{":name": value}`. + * + * Give `name` without the leading `:`. It must be an identifier. The argument remains positional in the call's argument list. See {@link call} for a labeled call example. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const label = ( + name: string, + value: Expression, +): Defs.LabeledArgumentType => ({ [`:${name}`]: value }); + +/** + * Builds a call to a function expression. + * + * `fn` can be a path or an expression that produces a function, including a closure from {@link fn}. Arguments keep their supplied order, including those created with {@link label}. + * + * @example + * ```ts + * import * as JExpr from "./index.js"; + * + * JExpr.compile(JExpr.call("greet", JExpr.label("name", JExpr.literal("Alice")))); + * // => '["greet",{":name":{"#literal":"Alice"}}]' + * ``` + */ +export const call = ( + fn: Expression, + ...args: readonly (Expression | Defs.LabeledArgumentType)[] +): Defs.CallType => [fn, ...args]; + +/** + * Selects a branch according to a Boolean expression. + * + * HashQL evaluates only the selected branch. Without `otherwise`, the query produces HashQL's `Some(then)` when the condition is true and `None` when it is false. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const conditional = ( + condition: Expression, + then: Expression, + otherwise?: Expression, +): Defs.CallType => { + if (otherwise === undefined) { + return ["::kernel::special_form::if", condition, then]; + } + + return ["::kernel::special_form::if", condition, then, otherwise]; +}; + +export { conditional as if }; + +/** + * Binds `value` to `name` within `body`. + * + * Use {@link asType | as} on `value` to give it an explicit type. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const binding = ( + name: string, + value: Expression, + body: Expression, +): Defs.CallType => ["::kernel::special_form::let", name, value, body]; + +export { binding as let }; + +/** + * Asserts an expression's type for the HashQL type checker. + * + * The assertion constrains the expression's type without converting its value. Use {@link typed} to put an annotation directly on a data constructor. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const asType = (value: Expression, type: Type.Type): Defs.CallType => [ + "as", + value, + Type.toExpression(type), +]; + +export { asType as as }; + +/** + * Items to import into the body of {@link use}. + * + * Use `"*"` for all items or an array for named imports. For aliases, supply a record from original name to local name: `{ entities: "allEntities" }` imports `entities` as `allEntities`. The alias `"_"` keeps the original name. + */ +export type Imports = + | "*" + | readonly string[] + | Record.ReadonlyRecord; + +/** Renders an import selection as a wildcard, tuple or alias record. */ +const compileImports = (imports: Imports): Expression => { + if (imports === "*") { + return imports; + } + + if (isReadonlyArray(imports)) { + return { "#tuple": imports }; + } + + return { "#struct": imports }; +}; + +/** + * Imports items from the module at `path` into `body`. + * + * {@link Imports} describes wildcard imports, named imports and aliases. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const use = ( + path: string, + imports: Imports, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::use", + path, + compileImports(imports), + body, +]; + +/** + * Reads a named query input supplied by the host. + * + * Without `defaultValue`, the host must supply the input. Otherwise, HashQL evaluates `defaultValue` when the input is absent. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const input = ( + name: string, + type: Type.Type, + defaultValue?: Expression, +): Defs.CallType => { + if (defaultValue === undefined) { + return ["::kernel::special_form::input", name, Type.toExpression(type)]; + } + + return [ + "::kernel::special_form::input", + name, + Type.toExpression(type), + defaultValue, + ]; +}; + +/** + * Selects a named field or a tuple position. + * + * Give a field identifier as a string or a zero-based tuple position as a number. Use {@link index} when the selector is an expression. Path strings such as `"entity.properties"` provide shorthand for named field access. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const access = ( + value: Expression, + field: string | number, +): Defs.CallType => { + if (typeof field === "number") { + return ["::kernel::special_form::access", value, integer(field)]; + } + + return ["::kernel::special_form::access", value, field]; +}; + +/** + * Looks up a collection element using an index expression. + * + * Use {@link literal} for a fixed index. A string such as `"offset"` refers to a value in scope. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const index = ( + value: Expression, + position: Expression, +): Defs.CallType => ["::kernel::special_form::index", value, position]; + +/** Renders a declaration name, including any generic parameters. */ +const compileName = (name: string | Reference.Reference): string => { + if (typeof name === "string") { + return name; + } + + return Type.compile(name); +}; + +/** + * Introduces a type alias in `body`. + * + * The alias denotes the same type as `type`. Use {@link newtype} for a distinct nominal type with a constructor. `name` accepts type syntax such as `"Pair"`, or a {@link Reference.Reference} declaring generic parameters. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +const typeAlias = ( + name: string | Reference.Reference, + type: Type.Type, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::type", + compileName(name), + Type.toExpression(type), + body, +]; + +export { typeAlias as type }; + +/** + * Introduces a distinct type and its constructor in `body`. + * + * The constructor has the same name as the type. `name` accepts generic parameters as described by {@link typeAlias | type}. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument +export const newtype = ( + name: string | Reference.Reference, + type: Type.Type, + body: Expression, +): Defs.CallType => [ + "::kernel::special_form::newtype", + compileName(name), + Type.toExpression(type), + body, +]; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts new file mode 100644 index 00000000000..f2b776f4859 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts @@ -0,0 +1,263 @@ +import { Option, Schema } from "effect"; + +import * as Scan from "../internal/scan.js"; + +import type { SchemaAST } from "effect"; +import type { ReadonlyRecord } from "effect/Record"; + +/** A deferred reference that permits expressions to contain other expressions. */ +// oxlint-disable-next-line no-redeclare -- redecl of type is required to make sure that the cycle is broken +type ExpressionRef = Schema.suspend< + Schema.Codec +>; +const ExpressionRef: ExpressionRef = Schema.suspend( + // oxlint-disable-next-line no-use-before-define -- recursive schema + (): Schema.Codec => Expression, +); + +/** Whether `input` is a single identifier in source form, such as `name`, `+` or `` `+` ``. */ +const isIdentSource = (input: string): boolean => + Option.isSome(Scan.scanIdentExact(input)); + +/** + * A path, a type expression or a labeled-argument shorthand. + * + * The schema accepts any string. HashQL parses it according to its position in the expression. + */ +export const Identifier: Schema.String = Schema.String.pipe( + Schema.brand("~hashql/Identifier"), +); + +/** The value described by {@link Identifier}. */ +export type IdentifierType = typeof Identifier.Type; +/** The schema-encoded form of {@link Identifier}. */ +export type IdentifierEncoded = Schema.Codec.Encoded; + +/** + * Requires every key to start with `prefix` followed by a complete identifier. + * + * Checking the whole record rejects invalid keys that `Schema.Record` would otherwise skip when matching a key schema. + */ +const hasIdentKeys = ( + prefix: string, + expected: string, +): SchemaAST.Filter> => + Schema.makeFilter( + (record: ReadonlyRecord) => + Object.keys(record) + .filter( + (key) => + !key.startsWith(prefix) || !isIdentSource(key.slice(prefix.length)), + ) + .map((key) => ({ path: [key], issue: `Expected ${expected}` })), + { expected }, + ); + +/** Colon-prefixed key text, before {@link hasIdentKeys} validates the identifier. */ +const LabelKey: Schema.TemplateLiteral = + Schema.TemplateLiteral([":", Schema.String]); + +/** + * A labeled call argument, such as `{":name": value}`. + * + * A labeled argument is positional: it occupies its place in the argument list like any other argument. + */ +export const LabeledArgument: Schema.$Record = + Schema.Record(LabelKey, ExpressionRef).check( + hasIdentKeys(":", "`:` followed by an identifier"), + Schema.isMinProperties(1), + Schema.isMaxProperties(1), + ); + +/** The value described by {@link LabeledArgument}. */ +export interface LabeledArgumentType extends Schema.Schema.Type< + typeof LabeledArgument +> {} +/** The schema-encoded form of {@link LabeledArgument}. */ +export interface LabeledArgumentEncoded extends Schema.Codec.Encoded< + typeof LabeledArgument +> {} + +/** A nonempty call array, starting with the function expression. */ +export const Call: Schema.TupleWithRest< + Schema.Tuple, + readonly [Schema.Union] +> = Schema.TupleWithRest(Schema.Tuple([ExpressionRef]), [ + Schema.Union([ExpressionRef, LabeledArgument]), +]); + +/** The value described by {@link Call}. */ +export type CallType = readonly [ + ExpressionType, + ...(ExpressionType | LabeledArgumentType)[], +]; +/** The schema-encoded form of {@link Call}. */ +export type CallEncoded = readonly [ + ExpressionEncoded, + ...(ExpressionEncoded | LabeledArgumentEncoded)[], +]; + +/** A data constructor with identifier-named fields and an optional type annotation. */ +export const Struct: Schema.Struct<{ + "#struct": Schema.$Record; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#struct": Schema.Record(Schema.String, ExpressionRef).check( + hasIdentKeys("", "an identifier"), + ), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Struct}. */ +export interface StructType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Struct}. */ +export interface StructEncoded extends Schema.Codec.Encoded {} + +/** A fixed-length sequence of expressions and an optional type annotation. */ +export const Tuple: Schema.Struct<{ + "#tuple": Schema.$Array; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#tuple": Schema.Array(ExpressionRef), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Tuple}. */ +export interface TupleType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Tuple}. */ +export interface TupleEncoded extends Schema.Codec.Encoded {} + +/** A dictionary of string-keyed values or expression pairs, with an optional type annotation. */ +export const Dict: Schema.Struct<{ + "#dict": Schema.Union< + readonly [ + Schema.$Record, + Schema.$Array>, + ] + >; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#dict": Schema.Union([ + Schema.Record(Schema.String, ExpressionRef), + Schema.Array(Schema.Tuple([ExpressionRef, ExpressionRef])), + ]), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Dict}. */ +export interface DictType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Dict}. */ +export interface DictEncoded extends Schema.Codec.Encoded {} + +/** A list of expressions and an optional type annotation. */ +export const List: Schema.Struct<{ + "#list": Schema.$Array; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#list": Schema.Array(ExpressionRef), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link List}. */ +export interface ListType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link List}. */ +export interface ListEncoded extends Schema.Codec.Encoded {} + +/** + * An integer literal in JSON number syntax, such as `-42`. + * + * Keeping the text preserves integers beyond JavaScript's numeric precision limit. + */ +export const Integer: Schema.TaggedStruct<"Integer", { value: Schema.String }> = + Schema.TaggedStruct("Integer", { + value: Schema.String.check( + Schema.isPattern(/^-?(?:0|[1-9]\d*)$/u, { + expected: "an integer in JSON number syntax", + }), + ), + }); + +/** The value described by {@link Integer}. */ +export interface IntegerType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Integer}. */ +export interface IntegerEncoded extends Schema.Codec.Encoded {} + +/** + * A float literal in JSON number syntax with a fraction or exponent, such as `1.0` or `1e3`. + * + * HashQL reads a number as a float only if its text contains a fraction or exponent. The stored text preserves that distinction. + */ +export const Float: Schema.TaggedStruct<"Float", { value: Schema.String }> = + Schema.TaggedStruct("Float", { + value: Schema.String.check( + Schema.isPattern( + /^-?(?:0|[1-9]\d*)(?:\.\d+(?:[eE][+-]?\d+)?|[eE][+-]?\d+)$/u, + { expected: "a float in JSON number syntax" }, + ), + ), + }); + +/** The value described by {@link Float}. */ +export interface FloatType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Float}. */ +export interface FloatEncoded extends Schema.Codec.Encoded {} + +/** A primitive value, with tagged source text for numbers and an optional type annotation. */ +export const Literal: Schema.Struct<{ + "#literal": Schema.Union< + readonly [ + Schema.String, + typeof Integer, + typeof Float, + Schema.Boolean, + Schema.Null, + ] + >; + "#type": Schema.optionalKey; +}> = Schema.Struct({ + "#literal": Schema.Union([ + Schema.String, + Integer, + Float, + Schema.Boolean, + Schema.Null, + ]), + "#type": Identifier.pipe(Schema.optionalKey), +}); + +/** The value described by {@link Literal}. */ +export interface LiteralType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link Literal}. */ +export interface LiteralEncoded extends Schema.Codec.Encoded {} + +/** The recursive union of calls, data constructors and string expressions. */ +export const Expression: Schema.Union< + readonly [ + typeof Call, + typeof Struct, + typeof Tuple, + typeof Dict, + typeof List, + typeof Literal, + typeof Identifier, + ] +> = Schema.Union([Call, Struct, Tuple, Dict, List, Literal, Identifier]); + +/** The value described by {@link Expression}. */ +export type ExpressionType = + | CallType + | StructType + | TupleType + | DictType + | ListType + | LiteralType + | IdentifierType; +/** The schema-encoded form of {@link Expression}. */ +export type ExpressionEncoded = + | CallEncoded + | StructEncoded + | TupleEncoded + | DictEncoded + | ListEncoded + | LiteralEncoded + | IdentifierEncoded; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts new file mode 100644 index 00000000000..b93de225a73 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts @@ -0,0 +1,80 @@ +import { Option } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../index.js"; +import * as Type from "./index.js"; + +const integer = Option.getOrThrow(Type.reference("::kernel::type::Integer")); +const text = Option.getOrThrow(Type.reference("::kernel::type::String")); +const tuple = Type.tuple(integer); +const record = Option.getOrThrow(Type.struct({ value: tuple })); +const cases: readonly (readonly [string, Type.Type, JExpr.Expression])[] = [ + ["reference", integer, "::kernel::type::Integer"], + ["tuple", tuple, { "#tuple": ["::kernel::type::Integer"] }], + ["empty_tuple", Type.tuple(), { "#tuple": [] }], + [ + "struct", + record, + { "#struct": { value: { "#tuple": ["::kernel::type::Integer"] } } }, + ], + ["empty_struct", Option.getOrThrow(Type.struct({})), { "#struct": {} }], + [ + "union", + Type.union(integer, text), + [ + "::kernel::type::Union", + "::kernel::type::Integer", + "::kernel::type::String", + ], + ], + [ + "intersection", + Type.intersection(integer, text), + [ + "::kernel::type::Intersection", + "::kernel::type::Integer", + "::kernel::type::String", + ], + ], + [ + "generic_argument", + Option.getOrThrow(Type.reference("List", tuple)), + "List<(::kernel::type::Integer,)>", + ], +]; + +describe("type_expressions", () => { + test.each(cases)("%s", (_, type, expression) => { + expect.hasAssertions(); + expect(Type.toExpression(type)).toStrictEqual(expression); + expect([ + JExpr.type("Local", type, "_")[2], + JExpr.newtype("Local", type, "_")[2], + JExpr.input("value", type)[2], + JExpr.input("value", type, "default")[2], + JExpr.as("value", type)[2], + ]).toStrictEqual([ + expression, + expression, + expression, + expression, + expression, + ]); + expect( + JExpr.fn({ params: { argument: type }, returns: type, body: "argument" }), + ).toStrictEqual([ + "fn", + { "#tuple": [] }, + { "#struct": { argument: expression } }, + expression, + "argument", + ]); + }); + + test("annotation_string", () => { + expect.hasAssertions(); + expect(JExpr.typed(JExpr.tuple(JExpr.integer(1)), tuple)["#type"]).toBe( + "(::kernel::type::Integer,)", + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts new file mode 100644 index 00000000000..3e0a05cc3c5 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts @@ -0,0 +1,61 @@ +import { Option, Result, SchemaParser } from "effect"; + +import * as Ident from "../Ident.js"; +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Generic = Defs.Generic; + +export type Generic = Defs.GenericType; +export type Encoded = Defs.GenericEncoded; + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Generic = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** + * Creates a generic argument: the `Integer` in `List`. + */ +export const argument = (type: Defs.Type): Defs.GenericArgumentType => ({ + _tag: "GenericArgument", + bound: type, +}); + +/** + * Creates a named generic constraint: the `T: Integer` in `Foo`. + * + * Returns `None` if `name` is not a valid identifier according to + * {@link Ident.decodeResult}. Without a bound, it compiles to the bare name, which + * the backend reads as a generic argument. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const bound = ( + name: string, + type?: Defs.Type, +): Option.Option => + Option.map( + Ident.decodeResult(name).pipe(Result.getSuccess), + (ident): Defs.GenericBoundType => { + if (type === undefined) { + return { _tag: "GenericBound", name: ident }; + } + + return { _tag: "GenericBound", name: ident, bound: type }; + }, + ); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts new file mode 100644 index 00000000000..f5f97833ed6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.GenericArgument = Defs.GenericArgument; + +export interface GenericArgument extends Defs.GenericArgumentType {} +export interface Encoded extends Defs.GenericArgumentEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => GenericArgument = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts new file mode 100644 index 00000000000..ef80290d7c2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.GenericBound = Defs.GenericBound; + +export interface GenericBound extends Defs.GenericBoundType {} +export interface Encoded extends Defs.GenericBoundEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => GenericBound = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts new file mode 100644 index 00000000000..0d52534c024 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts @@ -0,0 +1,31 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Intersection = Defs.Intersection; + +export interface Intersection extends Defs.IntersectionType {} +export interface Encoded extends Defs.IntersectionEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Intersection = SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts new file mode 100644 index 00000000000..59ec7550f6d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts @@ -0,0 +1,29 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Reference = Defs.Reference; + +export interface Reference extends Defs.ReferenceType {} +export interface Encoded extends Defs.ReferenceEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Reference = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = + SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts new file mode 100644 index 00000000000..1451ac28a12 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Struct = Defs.Struct; + +export interface Struct extends Defs.StructType {} +export interface Encoded extends Defs.StructEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Struct = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts new file mode 100644 index 00000000000..c9844864406 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Tuple = Defs.Tuple; + +export interface Tuple extends Defs.TupleType {} +export interface Encoded extends Defs.TupleEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Tuple = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts new file mode 100644 index 00000000000..09f8bf72aa6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts @@ -0,0 +1,28 @@ +import { SchemaParser } from "effect"; + +import * as Defs from "./schema.js"; + +import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; + +export const Schema: typeof Defs.Union = Defs.Union; + +export interface Union extends Defs.UnionType {} +export interface Encoded extends Defs.UnionEncoded {} + +type MakeIn = (typeof Schema)["~type.make.in"]; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Union = + SchemaParser.make(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts new file mode 100644 index 00000000000..093e81663ff --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts @@ -0,0 +1,462 @@ +/** + * Builds HashQL type expressions for J-Expr queries. + * + * A {@link Type} describes type syntax. Use {@link reference} for a named type and {@link struct}, {@link tuple}, {@link union} or {@link intersection} to compose types. {@link compile} renders the result as a J-Expr type expression. + * + * {@link reference} and {@link struct} return an {@link Option.Option}: an invalid name produces `None`. Name resolution and type checking belong to the HashQL compiler. + * + * @module + */ +import { Array, Option, Record, Result, SchemaParser, Tuple } from "effect"; +import { compose, dual, pipe } from "effect/Function"; + +import * as Ident from "../Ident.js"; +import * as Path from "../Path.js"; +import * as Defs from "./schema.js"; + +import type { Identifier } from "../Identifier.js"; +import type { ExpressionType } from "../schema.js"; +import type { Schema as $Schema, Effect, SchemaIssue } from "effect"; +import type { NonEmptyReadonlyArray } from "effect/Array"; + +export * as Generic from "./Generic.js"; +export * as GenericArgument from "./GenericArgument.js"; +export * as GenericBound from "./GenericBound.js"; +export * as Intersection from "./Intersection.js"; +export * as Reference from "./Reference.js"; +export * as Struct from "./Struct.js"; +export * as Tuple from "./Tuple.js"; +export * as Union from "./Union.js"; + +/** + * Schema for validating and encoding {@link Type} values. + * + * Use {@link make} to construct a value or {@link compile} to render type syntax. Schema encoding produces the tagged object representation described by {@link Encoded}. + */ +export const Schema: typeof Defs.Type = Defs.Type; + +/** + * A HashQL type expression with validated identifiers. + * + * The `_tag` discriminant selects the type's syntactic form. {@link compile} renders the expression without resolving its names or checking relationships between types. + */ +export type Type = Defs.Type; + +/** + * The tagged object representation of a {@link Type}, with unbranded identifiers. + * + * {@link Schema} encodes and decodes this representation. Use {@link compile} for a J-Expr type expression. + */ +export type Encoded = Defs.TypeEncoded; + +/** Constructor input accepted by {@link Schema} before validation. */ +type MakeIn = (typeof Schema)["~type.make.in"]; + +/** + * Constructs a type from its tagged object representation. + * + * Validates the input against {@link Schema} by default. `options.disableChecks` skips schema checks. {@link makeOption} returns `None` for validation failures, and {@link makeEffect} preserves the issue in its error channel. + * + * @throws {Error} If construction fails. A schema-validation error carries a {@link SchemaIssue.Issue} in its `cause`. + * + * @example + * ```ts + * import { Effect, Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Type.make({ + * _tag: "Reference", + * path: { rooted: false, segments: [{ _tag: "Lexical", value: "Integer" }] }, + * generics: [], + * }); + * Type.compile(integer); // => "Integer" + * + * const invalid = { + * _tag: "Reference", + * path: { rooted: false, segments: [{ _tag: "Lexical", value: "" }] }, + * generics: [], + * } as const; + * Option.isNone(Type.makeOption(invalid)); // => true + * + * const empty = Effect.runSync(Type.makeEffect({ _tag: "Tuple", members: [] })); + * Type.compile(empty); // => "()" + * ``` + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Type = + SchemaParser.make(Schema); + +/** + * Constructs a type with schema failures in the effect's error channel. + * + * Uses the construction options described by {@link make}. Fails with a {@link SchemaIssue.Issue} if the input fails schema validation. + * + * @see {@link make} for construction examples. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeEffect: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Effect.Effect = SchemaParser.makeEffect(Schema); + +/** + * Constructs a type, returning `None` if schema validation fails. + * + * Uses the construction options described by {@link make}. Use {@link makeEffect} when you need the validation issue. + * + * @see {@link make} for construction examples. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive +export const makeOption: ( + input: MakeIn, + options?: $Schema.MakeOptions, +) => Option.Option = SchemaParser.makeOption(Schema); + +/** + * Creates a type whose values satisfy at least one member type. + * + * Preserves member order, duplicates and nested unions. Use {@link or} to combine types while flattening union operands. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * Type.compile(Type.union(integer, string)); // => "(Integer | String)" + * Type.compile(Type.union(integer)); // => "Integer" + * ``` + */ +export const union = ( + ...members: NonEmptyReadonlyArray +): Defs.UnionType => ({ _tag: "Union", members }); + +/** + * Creates a type whose values satisfy every member type. + * + * Preserves member order, duplicates and nested intersections. Use {@link and} to combine types while flattening intersection operands. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const named = Option.getOrThrow(Type.reference("Named")); + * const aged = Option.getOrThrow(Type.reference("Aged")); + * Type.compile(Type.intersection(named, aged)); // => "(Named & Aged)" + * ``` + */ +export const intersection = ( + ...members: NonEmptyReadonlyArray +): Defs.IntersectionType => ({ _tag: "Intersection", members }); + +/** Exposes a readonly view of a value without copying or freezing it. */ +const asReadonlyUnsafe = (input: T): Readonly => input; + +/** + * Creates a type with named fields. + * + * Returns `None` if any field name is not a valid identifier according to {@link Ident.decodeResult}. Symbol names accept bare (`+`) or backticked (`` `+` ``) spelling. Fields follow the record's own enumerable string-key order. An empty record produces an empty struct, which {@link compile} renders as `(:)`. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const string = Option.getOrThrow(Type.reference("String")); + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const person = Option.getOrThrow(Type.struct({ name: string, age: integer })); + * Type.compile(person); // => "(name: String, age: Integer)" + * Option.isNone(Type.struct({ "": string })); // => true + * Type.compile(Option.getOrThrow(Type.struct({}))); // => "(:)" + * ``` + */ +export const struct = ( + fields: Record.ReadonlyRecord, +): Option.Option => + pipe( + Record.toEntries(fields), + Array.map( + compose( + Tuple.evolve([ + compose(Ident.decodeResult, Result.getSuccess), + Option.some, + ]), + Option.all, + ), + ), + Option.all, + Option.map(asReadonlyUnsafe), + Option.map((members) => ({ + _tag: "Struct", + members, + })), + ); + +/** + * Creates a type with positional fields. + * + * An empty tuple compiles to `()`. A single-member tuple keeps a trailing comma to distinguish it from a parenthesized type. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * Type.compile(Type.tuple()); // => "()" + * Type.compile(Type.tuple(integer)); // => "(Integer,)" + * Type.compile(Type.tuple(integer, integer)); // => "(Integer, Integer)" + * ``` + */ +export const tuple = (...members: readonly Type[]): Defs.TupleType => ({ + _tag: "Tuple", + members, +}); + +/** + * Refers to a named type with optional generic arguments or bounds. + * + * `path` uses path syntax, such as `Integer`, `core::math::add` or `::core::math::+`. Returns `None` if {@link Path.parse} rejects it. Validation checks syntax only. The HashQL compiler resolves the name and checks its generic arguments. + * + * A plain {@link Type} supplies a positional generic argument. An explicit {@link Defs.GenericType} preserves its argument or named-bound form. Generic order follows the argument list. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Generic from "./Generic.js"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const list = Option.getOrThrow(Type.reference("List", integer)); + * Type.compile(list); // => "List" + * + * const bounded = Option.getOrThrow( + * Type.reference("List", Option.getOrThrow(Generic.bound("T", integer))), + * ); + * Type.compile(bounded); // => "List" + * + * const rooted = Option.getOrThrow(Type.reference("::core::math::+", integer)); + * Type.compile(rooted); // => "::core::math::`+`" + * Option.isNone(Type.reference("")); // => true + * ``` + */ +export const reference = ( + path: string, + ...generics: readonly (Type | Defs.GenericType)[] +): Option.Option => + Option.all({ + _tag: Option.some("Reference" as const), + path: Path.decodeResult(path).pipe(Result.getSuccess), + generics: Option.some( + generics.map((generic): Defs.GenericType => { + if ( + generic._tag === "GenericArgument" || + generic._tag === "GenericBound" + ) { + return generic; + } + + return { _tag: "GenericArgument", bound: generic }; + }), + ), + }); + +/** Treats a non-union type as a single union member. */ +const unionMembers = (type: Type): NonEmptyReadonlyArray => { + if (type._tag === "Union") { + return type.members; + } + + return [type]; +}; + +/** Treats a non-intersection type as a single intersection member. */ +const intersectionMembers = (type: Type): NonEmptyReadonlyArray => { + if (type._tag === "Intersection") { + return type.members; + } + + return [type]; +}; + +/** + * Combines types into a union, flattening union operands by one level. + * + * Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat union when the initial operands have no nested unions. Use {@link union} to preserve nesting. + * + * @example + * ```ts + * import { Option } from "effect"; + * import { pipe } from "effect/Function"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * const boolean = Option.getOrThrow(Type.reference("Boolean")); + * const value = pipe(integer, Type.or(string), Type.or(boolean)); + * Type.compile(value); // => "(Integer | String | Boolean)" + * Type.compile(Type.or(integer, string)); // => "(Integer | String)" + * ``` + */ +export const or: { + (that: Type): (self: Type) => Defs.UnionType; + (self: Type, that: Type): Defs.UnionType; +} = dual( + 2, + (self: Type, that: Type): Defs.UnionType => ({ + _tag: "Union", + members: [...unionMembers(self), ...unionMembers(that)], + }), +); + +/** + * Combines types into an intersection, flattening its operands once. + * + * An intersection operand contributes its immediate members. Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat intersection when the initial operands have no nested intersections. Use {@link intersection} to preserve nesting. + * + * @example + * ```ts + * import { Option } from "effect"; + * import { pipe } from "effect/Function"; + * import * as Type from "./index.js"; + * + * const named = Option.getOrThrow(Type.reference("Named")); + * const aged = Option.getOrThrow(Type.reference("Aged")); + * const located = Option.getOrThrow(Type.reference("Located")); + * const person = pipe(named, Type.and(aged), Type.and(located)); + * Type.compile(person); // => "(Named & Aged & Located)" + * Type.compile(Type.and(named, aged)); // => "(Named & Aged)" + * ``` + */ +export const and: { + (that: Type): (self: Type) => Defs.IntersectionType; + (self: Type, that: Type): Defs.IntersectionType; +} = dual( + 2, + (self: Type, that: Type): Defs.IntersectionType => ({ + _tag: "Intersection", + members: [...intersectionMembers(self), ...intersectionMembers(that)], + }), +); + +/** Delimits a compound type expression to preserve its grouping. */ +const parenthesize = ( + members: readonly Type[], + separator: string, +): Identifier => + // oxlint-disable-next-line no-use-before-define -- recursive printer + `(${members.map((member) => compile(member)).join(separator)})`; + +/** Renders a positional argument or named bound within a generic argument list. */ +const compileGeneric: (generic: Defs.GenericType) => Identifier = + Defs.Generic.match({ + // oxlint-disable-next-line no-use-before-define -- recursive printer + GenericArgument: ({ bound }) => compile(bound), + GenericBound: ({ name, bound }) => { + if (bound === undefined) { + return Ident.compile(name); + } + + // oxlint-disable-next-line no-use-before-define -- recursive printer + return `${Ident.compile(name)}: ${compile(bound)}`; + }, + }); + +/** + * Compiles a type into J-Expr type syntax. + * + * Unions and intersections with more than one member always retain parentheses to preserve grouping in nested expressions. A single-member union or intersection compiles as its member. Empty structs use `(:)`, empty tuples use `()`, and single-member tuples retain a trailing comma. + * + * @example + * ```ts + * import { Option } from "effect"; + * import * as Type from "./index.js"; + * + * const integer = Option.getOrThrow(Type.reference("Integer")); + * const string = Option.getOrThrow(Type.reference("String")); + * const list = Option.getOrThrow( + * Type.reference("List", Type.union(integer, string)), + * ); + * Type.compile(list); // => "List<(Integer | String)>" + * ``` + */ +export const compile: (type: Type) => Identifier = Defs.Type.match({ + Union: ({ members }) => { + const [first, ...rest] = members; + + if (rest.length === 0) { + return compile(first); + } + + return parenthesize(members, " | "); + }, + Intersection: ({ members }) => { + const [first, ...rest] = members; + + if (rest.length === 0) { + return compile(first); + } + + return parenthesize(members, " & "); + }, + Struct: ({ members }) => { + if (members.length === 0) { + return "(:)"; + } + + const fields = members.map( + ([name, member]) => `${Ident.compile(name)}: ${compile(member)}`, + ); + + return `(${fields.join(", ")})`; + }, + Tuple: ({ members }) => { + const [only, ...rest] = members; + + if (only === undefined) { + return "()"; + } + + if (rest.length === 0) { + return `(${compile(only)},)`; + } + + return parenthesize(members, ", "); + }, + Reference: ({ path, generics }) => { + if (generics.length === 0) { + return Path.compile(path); + } + + const args = generics.map((generic) => compileGeneric(generic)); + return `${Path.compile(path)}<${args.join(", ")}>`; + }, +}); + +/** + * Encodes a type in an expression position, such as a type definition or closure parameter. + * + * Compound types use constructors here. Only annotation positions accept their type-syntax strings. + */ +export const toExpression: (type: Type) => ExpressionType = Defs.Type.match({ + Reference: compile, + Tuple: ({ members }) => ({ "#tuple": members.map(toExpression) }), + Struct: ({ members }) => ({ + "#struct": Object.fromEntries( + members.map(([name, member]) => [ + Ident.compile(name), + toExpression(member), + ]), + ), + }), + Union: ({ members }): ExpressionType => [ + "::kernel::type::Union", + ...members.map(toExpression), + ], + Intersection: ({ members }): ExpressionType => [ + "::kernel::type::Intersection", + ...members.map(toExpression), + ], +}); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts new file mode 100644 index 00000000000..4586d260079 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts @@ -0,0 +1,136 @@ +import { Schema } from "effect"; + +import * as Ident from "../Ident.js"; +import * as Path from "../Path.js"; + +// oxlint-disable-next-line no-redeclare -- `TypeRefType` is a bit silly +type TypeRef = Schema.suspend>; +const TypeRef: TypeRef = Schema.suspend( + // oxlint-disable-next-line no-use-before-define -- recursive schema + (): Schema.Codec => Type, +); + +export const Union: Schema.TaggedStruct< + "Union", + { members: Schema.NonEmptyArray } +> = Schema.TaggedStruct("Union", { + members: Schema.NonEmptyArray(TypeRef), +}); + +export interface UnionType extends Schema.Schema.Type {} +export interface UnionEncoded extends Schema.Codec.Encoded {} + +export const Intersection: Schema.TaggedStruct< + "Intersection", + { members: Schema.NonEmptyArray } +> = Schema.TaggedStruct("Intersection", { + members: Schema.NonEmptyArray(TypeRef), +}); + +export interface IntersectionType extends Schema.Schema.Type< + typeof Intersection +> {} +export interface IntersectionEncoded extends Schema.Codec.Encoded< + typeof Intersection +> {} + +export const Struct: Schema.TaggedStruct< + "Struct", + { members: Schema.$Array> } +> = Schema.TaggedStruct("Struct", { + members: Schema.Array(Schema.Tuple([Ident.Schema, TypeRef])), +}); + +export interface StructType extends Schema.Schema.Type {} +export interface StructEncoded extends Schema.Codec.Encoded {} + +export const Tuple: Schema.TaggedStruct< + "Tuple", + { members: Schema.$Array } +> = Schema.TaggedStruct("Tuple", { + members: Schema.Array(TypeRef), +}); + +export interface TupleType extends Schema.Schema.Type {} +export interface TupleEncoded extends Schema.Codec.Encoded {} + +export const GenericArgument: Schema.TaggedStruct< + "GenericArgument", + { bound: TypeRef } +> = Schema.TaggedStruct("GenericArgument", { + bound: TypeRef, +}); + +export interface GenericArgumentType extends Schema.Schema.Type< + typeof GenericArgument +> {} +export interface GenericArgumentEncoded extends Schema.Codec.Encoded< + typeof GenericArgument +> {} + +export const GenericBound: Schema.TaggedStruct< + "GenericBound", + { + name: typeof Ident.Schema; + bound: Schema.optionalKey; + } +> = Schema.TaggedStruct("GenericBound", { + name: Ident.Schema, + bound: TypeRef.pipe(Schema.optionalKey), +}); + +export interface GenericBoundType extends Schema.Schema.Type< + typeof GenericBound +> {} +export interface GenericBoundEncoded extends Schema.Codec.Encoded< + typeof GenericBound +> {} + +export const Generic: Schema.toTaggedUnion< + "_tag", + readonly [typeof GenericArgument, typeof GenericBound] +> = Schema.Union([GenericArgument, GenericBound]).pipe( + Schema.toTaggedUnion("_tag"), +); +export type GenericType = (typeof Generic)["Type"]; +export type GenericEncoded = (typeof Generic)["Encoded"]; + +export const Reference: Schema.TaggedStruct< + "Reference", + { path: typeof Path.Schema; generics: Schema.$Array } +> = Schema.TaggedStruct("Reference", { + path: Path.Schema, + generics: Schema.Array(Generic), +}); + +export interface ReferenceType extends Schema.Schema.Type {} +export interface ReferenceEncoded extends Schema.Codec.Encoded< + typeof Reference +> {} + +// oxlint-disable-next-line no-redeclare -- `TypeType` is a bit silly +export const Type: Schema.toTaggedUnion< + "_tag", + readonly [ + typeof Union, + typeof Intersection, + typeof Struct, + typeof Tuple, + typeof Reference, + ] +> = Schema.Union([Union, Intersection, Struct, Tuple, Reference]).pipe( + Schema.toTaggedUnion("_tag"), +); + +export type Type = + | UnionType + | IntersectionType + | StructType + | TupleType + | ReferenceType; +export type TypeEncoded = + | UnionEncoded + | IntersectionEncoded + | StructEncoded + | TupleEncoded + | ReferenceEncoded; diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index 033fd01e328..a21c3db89ec 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,2 +1,9 @@ -// oxlint-disable-next-line unicorn/require-module-specifiers -- This scaffold intentionally exposes no API. -export {}; +export * as JExpr from "./jexpr/index.js"; +export * as Expression from "./program/Expression.js"; +export * as Module from "./program/Module.js"; +export * as Program from "./program/index.js"; +export * as ProgramError from "./program/ProgramError.js"; +export { Import, Let, Newtype, If, assume, program } from "./program/index.js"; +export * as TypeExpression from "./program/TypeExpression.js"; +export type * as Type from "./type/index.js"; +export * as Inputs from "./program/Inputs.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts b/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts new file mode 100644 index 00000000000..e0090bed9bd --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts @@ -0,0 +1,247 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import * as JExpr from "./jexpr/index.js"; +import { get, makeExpression, toJExpr } from "./playground.js"; + +import type { Expression } from "./playground.js"; +import type * as Type from "./type/index.js"; +import type { ReadonlyRecord } from "effect/Record"; + +type User = Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly address: Type.Struct<{ readonly city: Type.PrimitiveString }>; +}>; + +interface Recursive extends Type.Struct<{ + readonly value: Type.PrimitiveString; + readonly next: Recursive; +}> {} + +const preserve = ( + expression: Expression, +): Expression => expression; + +const lookup = ( + dictionary: Expression>, + key: Expression, +): Expression => get(dictionary, key); + +describe("expression_types", () => { + test("struct_projection", () => { + const user = makeExpression("user"); + + expectTypeOf(user.name).toEqualTypeOf>(); + expectTypeOf(user.address.city).toEqualTypeOf< + Expression + >(); + }); + + test("generic_preservation", () => { + const user = preserve(makeExpression("user")); + + expectTypeOf(user).toEqualTypeOf>(); + expectTypeOf(user.address.city).toEqualTypeOf< + Expression + >(); + }); + + test("recursive_projection", () => { + const node = makeExpression("node"); + + expectTypeOf(node.next.next.value).toEqualTypeOf< + Expression + >(); + }); + + test("primitive_identity", () => { + const value = makeExpression(JExpr.literal("alice")); + + expectTypeOf(value).not.toEqualTypeOf>(); + expectTypeOf(toJExpr(value)).toEqualTypeOf(); + expectTypeOf(value).not.toHaveProperty("value"); + expectTypeOf(value).not.toHaveProperty("push"); + }); + + test("opaque_identity", () => { + const value = + makeExpression>("id"); + + expectTypeOf(value).not.toEqualTypeOf>(); + expectTypeOf(value).not.toEqualTypeOf< + Expression> + >(); + }); + + test("missing_field", () => { + const user = makeExpression("user"); + + expectTypeOf(user).toEqualTypeOf>(); + expectTypeOf(user).not.toHaveProperty("missing"); + // @ts-expect-error Field access cannot replace a symbolic expression. + user.name = makeExpression("other"); + }); +}); + +describe("tuple_types", () => { + test("tuple_positions", () => { + const tuple = + makeExpression< + Type.Tuple + >("tuple"); + + expectTypeOf(tuple[0]).toEqualTypeOf>(); + expectTypeOf(tuple[1]).toEqualTypeOf>(); + expectTypeOf(tuple).not.toHaveProperty("2"); + expectTypeOf(tuple).not.toHaveProperty(Number("0")); + expectTypeOf(tuple).not.toHaveProperty("length"); + expectTypeOf(tuple).not.toHaveProperty("map"); + }); + + test("tuple_empty", () => { + const tuple = makeExpression>("tuple"); + + expectTypeOf(toJExpr(tuple)).toEqualTypeOf(); + expectTypeOf(tuple).not.toHaveProperty("0"); + expectTypeOf(tuple).not.toHaveProperty(Number("0")); + }); +}); + +describe("lookup_types", () => { + test("lookup_nullable", () => { + const dictionary = + makeExpression>("users"); + const key = makeExpression(JExpr.literal("alice")); + const result = get(dictionary, key); + + expectTypeOf(result).toEqualTypeOf>(); + expectTypeOf(result).not.toHaveProperty("name"); + }); + + test("lookup_null_value", () => { + const dictionary = + makeExpression>( + "values", + ); + const key = makeExpression("key"); + + expectTypeOf(get(dictionary, key)).toEqualTypeOf< + Expression + >(); + }); + + test("lookup_expression_key", () => { + const dictionary = + makeExpression>("users"); + const user = makeExpression("user"); + + expectTypeOf(get(dictionary, user.name)).toEqualTypeOf< + Expression + >(); + }); + + test("lookup_generic_wrapper", () => { + const dictionary = + makeExpression>("users"); + const key = makeExpression("key"); + + expectTypeOf(lookup(dictionary, key)).toEqualTypeOf< + Expression + >(); + }); +}); + +describe("lookup_constraints", () => { + test("lookup_invariant_struct_key", () => { + type Key = Type.Struct<{ readonly id: Type.PrimitiveInteger }>; + const dictionary = makeExpression>("users"); + const key = makeExpression("key"); + const narrower = makeExpression< + Type.Struct<{ + readonly id: Type.PrimitiveInteger; + readonly name: Type.PrimitiveString; + }> + >("narrower"); + const broader = + makeExpression>>("broader"); + + expectTypeOf(get(dictionary, key)).toEqualTypeOf< + Expression + >(); + // @ts-expect-error An additional field makes the key narrower, not equivalent. + get(dictionary, narrower); + // @ts-expect-error The dictionary's required field cannot disappear from the key. + get(dictionary, broader); + }); + + test("lookup_invariant_union_key", () => { + type Key = Type.PrimitiveString | Type.PrimitiveNull; + const dictionary = makeExpression>("users"); + const key = makeExpression("key"); + const narrower = makeExpression("narrower"); + const broader = makeExpression("broader"); + + expectTypeOf(get(dictionary, key)).toEqualTypeOf< + Expression + >(); + // @ts-expect-error Equivalence must include every union member. + get(dictionary, narrower); + // @ts-expect-error An additional union member makes the key broader, not equivalent. + get(dictionary, broader); + }); + + test("lookup_invalid_arguments", () => { + const dictionary = + makeExpression>("users"); + const wrongKey = makeExpression(JExpr.integer(0)); + const key = makeExpression("key"); + const user = makeExpression("user"); + + expectTypeOf(get(dictionary, key)).toEqualTypeOf< + Expression + >(); + // @ts-expect-error The dictionary, not its index expression, determines the key type. + get(dictionary, wrongKey); + // @ts-expect-error A struct cannot stand in for a dictionary. + get(user, key); + // @ts-expect-error Lookup keys are expressions, not decoded JavaScript values. + get(dictionary, "alice"); + }); + + test("lookup_nullable_receiver", () => { + type Dictionary = Type.Dict; + const outer = + makeExpression>("outer"); + const key = makeExpression("key"); + const inner = get(outer, key); + + expectTypeOf(inner).toEqualTypeOf< + Expression + >(); + // @ts-expect-error A second lookup needs to handle the possibly absent dictionary. + get(inner, key); + }); +}); + +describe("binding_types", () => { + test("descriptor_rejection", () => { + const value = makeExpression("value"); + + expectTypeOf(toJExpr(value)).toEqualTypeOf(); + // @ts-expect-error A type descriptor carries no expression binding. + toJExpr({ _tag: "String", value: "alice" }); + }); + + test("binding_name_fields", () => { + const value = makeExpression< + Type.Struct<{ + readonly get: Type.PrimitiveString; + readonly push: Type.PrimitiveInteger; + readonly then: Type.PrimitiveBoolean; + }> + >("value"); + + expectTypeOf(value.get).toEqualTypeOf>(); + expectTypeOf(value.push).toEqualTypeOf>(); + expectTypeOf(value.then).toEqualTypeOf>(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/playground.test.ts b/libs/@local/hashql/sdk/typescript/src/playground.test.ts new file mode 100644 index 00000000000..499e9bca129 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/playground.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, test } from "vitest"; + +import * as JExpr from "./jexpr/index.js"; +import { get, makeExpression, toJExpr } from "./playground.js"; + +import type * as Type from "./type/index.js"; +import type { ReadonlyRecord } from "effect/Record"; + +type User = Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly address: Type.Struct<{ readonly city: Type.PrimitiveString }>; +}>; + +const collisionFields = [ + "push", + "get", + "then", + "toJSON", + "constructor", + "__proto__", +] as const; + +type Collision = Type.Struct< + ReadonlyRecord<(typeof collisionFields)[number], Type.PrimitiveString> +>; + +describe("expression_binding", () => { + test("primitive_ast", () => { + expect.hasAssertions(); + const expression = makeExpression(JExpr.integer(0)); + + expect(JExpr.compile(toJExpr(expression))).toBe('{"#literal":0}'); + }); + + test("struct_nested", () => { + expect.hasAssertions(); + const user = makeExpression("user"); + + expect(JExpr.compile(toJExpr(user.address.city))).toBe( + '["::kernel::special_form::access",["::kernel::special_form::access","user","address"],"city"]', + ); + }); + + test("projection_branches", () => { + expect.hasAssertions(); + const user = makeExpression("user"); + const name = user.name; + const city = user.address.city; + + expect(toJExpr(user)).toBe("user"); + expect(toJExpr(name)).toStrictEqual([ + "::kernel::special_form::access", + "user", + "name", + ]); + expect(toJExpr(city)).toStrictEqual([ + "::kernel::special_form::access", + ["::kernel::special_form::access", "user", "address"], + "city", + ]); + }); + + test("tuple_positions", () => { + expect.hasAssertions(); + const pair = + makeExpression< + Type.Tuple + >("pair"); + + expect(JExpr.compile(toJExpr(pair[0]))).toBe( + '["access","pair",{"#literal":0}]', + ); + expect(JExpr.compile(toJExpr(pair[1]))).toBe( + '["access","pair",{"#literal":1}]', + ); + }); + + test("tuple_empty", () => { + expect.hasAssertions(); + const empty = makeExpression>(JExpr.tuple()); + + expect(JExpr.compile(toJExpr(empty))).toBe('{"#tuple":[]}'); + }); + + test.each(collisionFields)("field_name_%s", (field) => { + expect.hasAssertions(); + const expression = makeExpression("value"); + + expect(toJExpr(expression[field])).toStrictEqual([ + "::kernel::special_form::access", + "value", + field, + ]); + }); +}); + +describe("field_identifiers", () => { + test("field_unicode", () => { + expect.hasAssertions(); + const expression = + makeExpression>( + "value", + ); + + expect(toJExpr(expression.naïve)).toStrictEqual([ + "::kernel::special_form::access", + "value", + "naïve", + ]); + }); + + test("field_symbol", () => { + expect.hasAssertions(); + const expression = + makeExpression>( + "value", + ); + + expect(toJExpr(expression["+"])).toStrictEqual([ + "::kernel::special_form::access", + "value", + "`+`", + ]); + }); + + test("field_base_url", () => { + expect.hasAssertions(); + const expression = makeExpression< + Type.Struct<{ + readonly "https://example.com/a::b/": Type.PrimitiveString; + }> + >("value"); + + expect(toJExpr(expression["https://example.com/a::b/"])).toStrictEqual([ + "::kernel::special_form::access", + "value", + "`https://example.com/a::b/`", + ]); + }); + + test.each(["", "invalid field", "01", "-1", "`+`"])( + "field_invalid_%s", + (field) => { + expect.hasAssertions(); + const expression = makeExpression("user"); + + expect(() => { + Reflect.get(expression, field); + }).toThrow("Invalid HashQL field name"); + }, + ); +}); + +describe("dictionary_lookup", () => { + test("lookup_literal_key", () => { + expect.hasAssertions(); + const dictionary = + makeExpression>("users"); + const key = makeExpression(JExpr.literal("alice")); + + expect(JExpr.compile(toJExpr(get(dictionary, key)))).toBe( + '["::kernel::special_form::index","users",{"#literal":"alice"}]', + ); + expect(toJExpr(dictionary)).toBe("users"); + }); + + test("lookup_expression_key", () => { + expect.hasAssertions(); + const dictionary = + makeExpression>("users"); + const user = makeExpression("user"); + + expect(toJExpr(get(dictionary, user.name))).toStrictEqual([ + "::kernel::special_form::index", + "users", + ["::kernel::special_form::access", "user", "name"], + ]); + }); +}); + +describe("host_interop", () => { + test("symbol_probe", () => { + expect.hasAssertions(); + const expression = makeExpression("user"); + + expect(Reflect.get(expression, Symbol.iterator)).toBeUndefined(); + expect(Reflect.get(expression, Symbol.toStringTag)).toBeUndefined(); + }); + + // oxlint-disable-next-line typescript/promise-function-async -- returns the Promise assertion directly + test("promise_assimilation", () => { + expect.hasAssertions(); + const expression = makeExpression("value"); + + expect(toJExpr(expression.then)).toStrictEqual([ + "::kernel::special_form::access", + "value", + "then", + ]); + return expect(Promise.resolve(expression)).resolves.toBe(expression); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/playground.ts b/libs/@local/hashql/sdk/typescript/src/playground.ts new file mode 100644 index 00000000000..25463a89c24 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/playground.ts @@ -0,0 +1,134 @@ +import { Option } from "effect"; + +import * as Scan from "./internal/scan.js"; +import * as Ident from "./jexpr/Ident.js"; +import * as JExpr from "./jexpr/index.js"; + +import type * as Type from "./type/index.js"; + +const Binding: unique symbol = Symbol("Expression.binding"); +class ExpressionBinding { + /** Phantom result type. The binding stores no runtime type descriptor. */ + declare readonly type: T; + readonly #expr: JExpr.Expression; + + constructor(expr: JExpr.Expression) { + this.#expr = expr; + } + + get expression(): JExpr.Expression { + return this.#expr; + } + + push( + fn: (expr: JExpr.Expression) => JExpr.Expression, + ): ExpressionBinding { + return new ExpressionBinding(fn(this.#expr)); + } +} + +interface ExpressionHandle { + readonly [Binding]: ExpressionBinding; +} + +/** + * A symbolic result, with field access preserving the selected field's type. + * + * The binding remains outside the conditional view so generic functions can infer `T`. + */ +export type Expression = ExpressionHandle & + (T extends Type.Struct + ? { + readonly [Field in Extract]: Expression< + Fields[Field] + >; + } + : T extends Type.Tuple.Any + ? { + readonly [Index in Extract< + keyof T["fields"], + `${number}` + >]: Expression; + } + : Record); + +/** Encodes one property name, including quoted identifiers and tuple positions. */ +const accessProperty = ( + expr: JExpr.Expression, + property: string, +): JExpr.Expression => { + if (/^(?:0|[1-9]\d*)$/u.test(property)) { + return JExpr.call("access", expr, JExpr.integer(BigInt(property))); + } + + const identifier = Option.orElse(Scan.scanIdentExact(property), () => + Scan.scanIdentExact(`\`${property}\``), + ); + + if (Option.isNone(identifier) || identifier.value.value !== property) { + throw new Error(`Invalid HashQL field name: ${property}`); + } + + return JExpr.access(expr, Ident.compile(Ident.fromScanned(identifier.value))); +}; + +const project = ( + binding: ExpressionBinding, +): Expression => { + const target: ExpressionHandle = { [Binding]: binding }; + const proxy = new Proxy(target, { + get( + target, + property, + ): ExpressionBinding | ExpressionHandle | undefined { + if (property === Binding) { + return target[Binding]; + } + + if (typeof property === "symbol") { + return undefined; + } + + return project( + target[Binding].push((expr) => + accessProperty(expr, property), + ), + ); + }, + }); + + // SAFETY: The target retains T's binding, and the trap creates expression bindings for projected fields. The raw-AST constructor supplies the type ascription. + return proxy as Expression; +}; + +/** + * Wraps a J-Expr expression with an unchecked result-type ascription. + * + * The caller must ensure that `initial` produces `T`. The binding carries no runtime type descriptor, so the proxy cannot check this claim. + */ +export const makeExpression = ( + initial: JExpr.Expression, +): Expression => project(new ExpressionBinding(initial)); + +/** Extracts the AST without evaluating the expression. */ +export const toJExpr = ( + expression: ExpressionHandle, +): JExpr.Expression => expression[Binding].expression; + +/** + * Constructs a dictionary lookup that returns null for an absent key. + * + * Dictionary keys are invariant, so a narrower key type is not enough. + */ +export const get = ( + dictionary: ExpressionHandle, + key: ExpressionHandle & + ([NoInfer] extends [NoInfer] + ? ExpressionHandle> + : never), +): Expression => + project( + dictionary[Binding].push((expr) => + JExpr.index(expr, toJExpr(key)), + ), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Do.ts b/libs/@local/hashql/sdk/typescript/src/program/Do.ts new file mode 100644 index 00000000000..f0ae274c763 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Do.ts @@ -0,0 +1,201 @@ +import type * as Type from "../type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Input from "./Inputs.js"; +import type * as IR from "./ir/index.js"; +import type * as ProgramError from "./ProgramError.js"; +import type { Body } from "./Utilities.js"; +import type { Result } from "effect"; + +/** Contextual overloads propagate the output universes and accumulate every declaration's inputs. */ +export interface Do { + ( + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + ( + step1: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + S4 extends IR.Scope.Scope, + I4, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + step4: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + S4 extends IR.Scope.Scope, + I4, + S5 extends IR.Scope.Scope, + I5, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + step4: IR.Node.Node, + step5: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + S4 extends IR.Scope.Scope, + I4, + S5 extends IR.Scope.Scope, + I5, + S6 extends IR.Scope.Scope, + I6, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + step4: IR.Node.Node, + step5: IR.Node.Node, + step6: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + S4 extends IR.Scope.Scope, + I4, + S5 extends IR.Scope.Scope, + I5, + S6 extends IR.Scope.Scope, + I6, + S7 extends IR.Scope.Scope, + I7, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + step4: IR.Node.Node, + step5: IR.Node.Node, + step6: IR.Node.Node, + step7: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; + < + S1 extends IR.Scope.Scope, + I1, + S2 extends IR.Scope.Scope, + I2, + S3 extends IR.Scope.Scope, + I3, + S4 extends IR.Scope.Scope, + I4, + S5 extends IR.Scope.Scope, + I5, + S6 extends IR.Scope.Scope, + I6, + S7 extends IR.Scope.Scope, + I7, + S8 extends IR.Scope.Scope, + I8, + T extends Type.Any, + Inputs, + >( + step1: IR.Node.Node, + step2: IR.Node.Node, + step3: IR.Node.Node, + step4: IR.Node.Node, + step5: IR.Node.Node, + step6: IR.Node.Node, + step7: IR.Node.Node, + step8: IR.Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts new file mode 100644 index 00000000000..1fdf59882f8 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts @@ -0,0 +1,428 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import type * as Type from "../type/index.js"; +import type { Expression } from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; + +type Left = Type.Struct<{ + readonly shared: Type.List; + readonly left: Type.PrimitiveBoolean; +}>; +type Right = Type.Struct<{ + readonly shared: Type.List; + readonly right: Type.PrimitiveInteger; +}>; + +interface Recursive extends Type.Struct<{ + readonly next: Recursive; + readonly value: Type.PrimitiveString; +}> {} + +const outOfBoundsPosition = 2; + +declare const left: Expression; +declare const position: Expression; +declare const text: Expression; +declare const union: Expression< + Type.Union, + Inputs.Empty +>; +declare const intersection: Expression< + Type.Intersection, + Inputs.Empty +>; +declare const recursive: Expression; + +const preserve = ( + expression: Expression, +): Expression => expression; + +describe("binding", () => { + test("primitive_identity", () => { + expectTypeOf< + Expression + >().not.toBeNever(); + expectTypeOf(text).not.toHaveProperty("$project"); + expectTypeOf(text).not.toHaveProperty("$index"); + expectTypeOf(text).not.toExtend< + Expression + >(); + // @ts-expect-error A non-function expression has no call signature. + text(); + }); + + test("generic_preservation", () => { + expectTypeOf(preserve(left)).toEqualTypeOf< + Expression + >(); + expectTypeOf(preserve(left).shared).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + }); + + test("recursive_projection", () => { + expectTypeOf(recursive.next.next.value).toEqualTypeOf< + Expression + >(); + expectTypeOf(recursive.$project("next").$project("value")).toEqualTypeOf< + Expression + >(); + }); + + test("opaque_forwarding", () => { + type Wrapped = Expression, Inputs.Empty>; + expectTypeOf().toEqualTypeOf< + Expression, Inputs.Empty> + >(); + expectTypeOf().not.toExtend>(); + expectTypeOf().not.toExtend< + Expression, Inputs.Empty> + >(); + }); +}); + +describe("projection", () => { + test("union_common_fields", () => { + expectTypeOf(union).not.toHaveProperty("left"); + expectTypeOf(union).not.toHaveProperty("right"); + expectTypeOf(union.shared).toEqualTypeOf< + Expression< + Type.Union< + readonly [Type.List, Type.List] + >, + Inputs.Empty + > + >(); + expectTypeOf(union.$project("shared")).toEqualTypeOf(); + // @ts-expect-error Every alternative must support the requested field. + union.$project("left"); + }); + + test("intersection_common_fields", () => { + expectTypeOf(intersection).not.toHaveProperty("left"); + expectTypeOf(intersection).not.toHaveProperty("right"); + expectTypeOf(intersection.shared).toEqualTypeOf< + Expression< + Type.Intersection< + readonly [Type.List, Type.List] + >, + Inputs.Empty + > + >(); + expectTypeOf(intersection.$project("shared")).toEqualTypeOf< + typeof intersection.shared + >(); + // @ts-expect-error An intersection projection must be valid on every member. + intersection.$project("right"); + }); + + test("nullable_receiver", () => { + type Nullable = Expression< + Type.Union, + Inputs.Empty + >; + expectTypeOf().not.toHaveProperty("shared"); + expectTypeOf().not.toHaveProperty("$project"); + expectTypeOf().not.toBeNever(); + }); + + test("tuple_positions", () => { + type Pair = Expression< + Type.Tuple, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().not.toHaveProperty("length"); + expectTypeOf().not.toHaveProperty("map"); + expectTypeOf().not.toHaveProperty(outOfBoundsPosition); + }); +}); + +declare const pair: Expression< + Type.Tuple, + Inputs.Empty +>; + +describe("tuple_projection", () => { + test("explicit_position", () => { + expectTypeOf(pair.$project(0)).toEqualTypeOf<(typeof pair)[0]>(); + // @ts-expect-error The tuple has no third position. + pair.$project(2); + // @ts-expect-error The number type does not identify one fixed tuple field. + pair.$project(Number("0")); + // @ts-expect-error Direct access also rejects nonexistent tuple positions. + expectTypeOf(pair[outOfBoundsPosition]); + }); + + test("empty_tuple", () => { + type Empty = Expression, Inputs.Empty>; + expectTypeOf().not.toBeNever(); + expectTypeOf().not.toHaveProperty(0); + expectTypeOf().not.toHaveProperty("$project"); + }); +}); + +type Overlap = Type.Intersection< + readonly [ + Type.Union, + Type.Union, + ] +>; + +type Algebra = Expression< + Type.Struct<{ + readonly overlap: Overlap; + readonly duplicate: Type.Union< + readonly [ + Type.PrimitiveString, + Type.Union, + ] + >; + readonly top: Type.Union; + readonly narrow: Type.Intersection< + readonly [Type.Unknown, Type.PrimitiveString] + >; + readonly impossible: Type.Intersection< + readonly [Type.PrimitiveString, Type.PrimitiveInteger] + >; + readonly emptyUnion: Type.Union; + readonly emptyIntersection: Type.Intersection; + }>, + Inputs.Empty +>; + +describe("composition", () => { + test("distributive_narrowing", () => { + type Narrowed = Expression< + Type.Intersection< + readonly [ + Type.Struct<{ readonly shared: Overlap["types"][0] }>, + Type.Struct<{ readonly shared: Overlap["types"][1] }>, + ] + >, + Inputs.Empty + >; + + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("union_identities", () => { + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("intersection_identities", () => { + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("numeric_intersection", () => { + type Numeric = Type.Intersection< + readonly [Type.PrimitiveInteger, Type.PrimitiveNumber] + >; + type Fields = Expression< + Type.Struct<{ readonly value: Numeric }>, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf< + Expression + >(); + }); + + test("neutral_members", () => { + type WithNever = Expression< + Type.Union, + Inputs.Empty + >; + type WithUnknown = Expression< + Type.Intersection, + Inputs.Empty + >; + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().not.toEqualTypeOf< + Expression + >(); + }); +}); + +declare const dictionary: Expression< + Type.Dict, + Inputs.Empty +>; +declare const opaqueList: Expression< + Type.Opaque<"Names", Type.List>, + Inputs.Empty +>; + +describe("indexing", () => { + test("list_nullable", () => { + expectTypeOf(left.shared.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error List indices are integer expressions. + left.shared.$index(text); + }); + + test("dictionary_nullable", () => { + expectTypeOf(dictionary.$index(text)).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + expectTypeOf(dictionary.$index(text)).not.toHaveProperty("shared"); + // @ts-expect-error The dictionary declares a string key. + dictionary.$index(position); + }); + + test("opaque_collection", () => { + expectTypeOf(opaqueList.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + }); + + test("composed_values", () => { + expectTypeOf(union.shared.$index(position)).toEqualTypeOf< + Expression + >(); + expectTypeOf(intersection.shared.$index(position)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + }); + + test("incompatible_keys", () => { + type MixedKeys = readonly [ + Type.Dict, + Type.Dict, + ]; + expectTypeOf< + Expression, Inputs.Empty> + >().not.toHaveProperty("$index"); + expectTypeOf< + Expression, Inputs.Empty> + >().not.toHaveProperty("$index"); + expectTypeOf< + Expression< + Type.Union, Type.PrimitiveNull]>, + Inputs.Empty + > + >().not.toHaveProperty("$index"); + }); +}); + +type Key = Type.Struct<{ readonly id: Type.PrimitiveInteger }>; +declare const keyed: Expression< + Type.Dict, + Inputs.Empty +>; +declare const key: Expression; +declare const narrowerKey: Expression< + Type.Struct<{ + readonly id: Type.PrimitiveInteger; + readonly name: Type.PrimitiveString; + }>, + Inputs.Empty +>; +declare const unionKeyed: Expression< + Type.Dict, Left>, + Inputs.Empty +>; +declare const unionKey: Expression< + Type.Union<[Type.PrimitiveString, Type.PrimitiveNull]>, + Inputs.Empty +>; + +declare const reserved: Expression< + Type.Struct<{ + readonly $project: Type.PrimitiveString; + readonly $index: Type.PrimitiveInteger; + readonly get: Type.PrimitiveBoolean; + readonly then: Type.PrimitiveString; + }>, + Inputs.Empty +>; +declare const incompatibleValues: Expression< + Type.Intersection< + readonly [ + Type.Dict, + Type.Dict, + ] + >, + Inputs.Empty +>; + +describe("operation_names", () => { + test("explicit_reserved_field", () => { + expectTypeOf(reserved.$project("$project")).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved.$project("$index")).toEqualTypeOf< + Expression + >(); + expectTypeOf(reserved).not.toHaveProperty("$index"); + expectTypeOf(reserved.get).toEqualTypeOf< + Expression + >(); + // @ts-expect-error JavaScript Promise interoperability reserves direct then access. + expectTypeOf(reserved.then); + expectTypeOf(reserved.$project("then")).toEqualTypeOf< + Expression + >(); + }); + + test("uninhabited_value_lookup", () => { + expectTypeOf(incompatibleValues.$index(text)).toEqualTypeOf< + Expression + >(); + }); +}); + +describe("key_identity", () => { + test("invariant_key", () => { + expectTypeOf(keyed.$index(key)).toEqualTypeOf< + Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error A narrower struct is not the declared key type. + keyed.$index(narrowerKey); + }); + + test("declared_union_key", () => { + expectTypeOf(unionKeyed.$index(unionKey)).toEqualTypeOf< + Expression, Inputs.Empty> + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts new file mode 100644 index 00000000000..c44f1c0e271 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts @@ -0,0 +1,148 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; + +import type * as Type from "../type/index.js"; +import type * as Inputs from "./Inputs.js"; + +type Vertex = Type.Struct<{ readonly name: Type.PrimitiveString }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": T }> +>; +type VertexOf = T extends Graph ? VertexType : never; + +interface Filter extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer Input, Type.Any] + ? Type.Function< + readonly [ + Graph>, + Type.Function], Type.PrimitiveBoolean>, + ], + Graph> + > + : Type.Function; +} + +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +// This handwritten declaration targets the standard-library function. +const body = Result.getOrThrow( + Module.define("::graph::body", { + values: { filter: Module.value>() }, + }), +); + +describe("expression", () => { + test("generic_filter_call", () => { + expect.hasAssertions(); + const vertices = Expression.fromJExpr, Inputs.Empty>( + "vertices", + ); + const predicate = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >([ + "::kernel::special_form::fn", + { "#tuple": [] }, + { "#struct": { vertex: "_" } }, + "_", + [ + "::core::cmp::eq", + ["::kernel::special_form::access", "vertex", "name"], + { "#literal": "Ada" }, + ], + ]); + const prelude = { select: body.values.filter }; + expect(compile(prelude.select(vertices, predicate))).toBe( + '["::graph::body::filter","vertices",["::kernel::special_form::fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",["::core::cmp::eq",["::kernel::special_form::access","vertex","name"],{"#literal":"Ada"}]]]', + ); + }); + + test("returned_function", () => { + expect.hasAssertions(); + type Unary = Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + >; + const outer = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("outer"); + const operand = Expression.fromJExpr( + JExpr.integer(2), + ); + expect(compile(outer()(operand))).toBe('[["outer"],{"#literal":2}]'); + }); + + test("projected_function", () => { + expect.hasAssertions(); + type Unary = Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + >; + const record = Expression.fromJExpr< + Type.Struct<{ readonly increment: Unary }>, + Inputs.Empty + >("record"); + const operand = Expression.fromJExpr( + JExpr.integer(2), + ); + expect(compile(record.increment(operand))).toBe( + '[["::kernel::special_form::access","record","increment"],{"#literal":2}]', + ); + }); + + test("projection_and_index", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ readonly users: Type.List }>, + Inputs.Empty + >("record"); + const index = Expression.fromJExpr( + JExpr.integer(0), + ); + expect(compile(record.users.$index(index))).toBe( + '["::kernel::special_form::index",["::kernel::special_form::access","record","users"],{"#literal":0}]', + ); + expect(compile(record.$project("users"))).toBe( + '["::kernel::special_form::access","record","users"]', + ); + }); + + test("callable_properties", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ + readonly name: Type.PrimitiveString; + readonly length: Type.PrimitiveInteger; + readonly then: Type.Function; + }>, + Inputs.Empty + >("record"); + expect(compile(record.name)).toBe( + '["::kernel::special_form::access","record","name"]', + ); + expect(compile(record.length)).toBe( + '["::kernel::special_form::access","record","length"]', + ); + expect(compile(record.$project("then")())).toBe( + '[["::kernel::special_form::access","record","then"]]', + ); + expect(Reflect.get(record, "then")).toBeUndefined(); + }); + + // oxlint-disable-next-line typescript/promise-function-async -- returns Vitest’s Promise assertion directly + test("promise_interoperability", () => { + expect.hasAssertions(); + const expression = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("function"); + return expect(Promise.resolve(expression)).resolves.toBe(expression); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts new file mode 100644 index 00000000000..222227b68c0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts @@ -0,0 +1,342 @@ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +import { Predicate, Result, Schema, identity, pipe } from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as AST from "./ast/index.js"; +import * as Fluent from "./Fluent.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; +import type { + Accessors, + Callable, + Conditional, + Normalize, +} from "./ExpressionType.js"; +import type * as Input from "./Inputs.js"; +import type { Types } from "effect"; + +export type { Conditional } from "./ExpressionType.js"; + +const TypeId = "~hashql/Expression"; +const Binding: unique symbol = Symbol("~hashql/Expression"); + +interface Variance { + readonly _T: Types.Invariant; + readonly _Inputs: Types.Contravariant; +} + +export type Primitive = Type.Primitive["value"]; + +/** The semantic input descriptors required by a value, with defaults marked optional. */ +export type Inputs = E extends Primitive + ? Input.Empty + : E extends { + readonly [TypeId]: { + readonly _Inputs: Types.Contravariant; + }; + } + ? { readonly [Key in keyof Requirements]: Requirements[Key] } + : never; + +/** An expression with its semantic type erased, for syntax-only operations. */ +export interface Any { + readonly [Binding]: Result.Result; +} + +export interface Handle extends Any { + readonly [TypeId]: Variance; +} + +export type AnyValue = Any | Primitive; + +/** Accepts an exactly typed handle or the corresponding host primitive. */ +export type Value = + | Handle + | (T extends Type.Primitive ? T["value"] : never); + +/** Host numbers remain Number regardless of their emitted literal syntax. */ +export type TypeOf = + V extends Handle + ? T + : V extends string + ? Type.PrimitiveString + : V extends boolean + ? Type.PrimitiveBoolean + : V extends bigint + ? Type.PrimitiveInteger + : V extends number + ? Type.PrimitiveNumber + : V extends null + ? Type.PrimitiveNull + : never; + +class ExpressionImpl implements Handle { + readonly [TypeId]: Variance; + + readonly #expr: Result.Result; + + constructor(expr: Result.Result) { + this.#expr = expr; + this[TypeId] = { + _T: identity, + // oxlint-disable-next-line typescript/strict-void-return -- only used for type variance + _Inputs: identity, + }; + } + + get [Binding](): Result.Result { + return this.#expr; + } +} + +/** A symbolic HashQL value with type-directed projection, indexing and calls. */ +export type Expression = Handle & + Accessors & + Callable & { readonly $: Fluent.Operations, Inputs> }; + +/** Recognizes expression handles without checking their semantic types. */ +// oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values +export const isExpression = (value: unknown): value is Any => + Predicate.hasProperty(value, Binding); + +const jexprParser = Schema.decodeResult(Schema.toType(JExpr.Schema)); + +const parseNode = ( + expression: JExpr.Expression, +): Result.Result => + Result.mapBoth(jexprParser(expression), { + onSuccess: (syntax) => new AST.Expr(syntax), + onFailure: (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExpression({ cause }), + }), + }); + +export const toNode = ( + value: AnyValue, +): Result.Result => { + if (isExpression(value)) { + return value[Binding]; + } + return parseNode(JExpr.literal(value)); +}; + +/** Extracts syntax without evaluating the represented value. */ +export const toJExpr = ( + value: AnyValue, +): Result.Result => + Result.map(toNode(value), (node) => node.compile()); + +const make = ( + impl: ExpressionImpl, +): Expression => { + const target = Object.assign( + (...args: readonly AnyValue[]) => + make( + new ExpressionImpl( + Result.map( + Result.all({ + callee: impl[Binding], + arguments: Result.all(args.map(toJExpr)), + }), + ({ callee, arguments: arguments_ }) => + new AST.Expr(JExpr.call(callee.compile(), ...arguments_)), + ), + ), + ), + { [TypeId]: impl[TypeId], [Binding]: impl[Binding] }, + ); + + const proxy = new Proxy(target, { + get( + target, + property, + receiver, + ): // oxlint-disable-next-line typescript/no-restricted-types -- proxy property reads may return arbitrary host values + unknown { + // A callable projected `then` would make the handle a JavaScript thenable. + if (property === "then") { + return undefined; + } + + if (property === "$") { + // oxlint-disable-next-line eslint/no-use-before-define -- the operation factories and expression proxy are mutually recursive + return Fluent.make(target, { fromResult, fromJExpr, toJExpr }); + } + + if (property === "$index") { + return (key: AnyValue) => { + const expr = Result.map( + Result.all({ value: target[Binding], key: toJExpr(key) }), + ({ value, key }) => new AST.Expr(JExpr.index(value.compile(), key)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + }; + } + + if (property === "$project") { + return (key: string | number) => { + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), key)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + }; + } + + if (property === Binding) { + return target[Binding]; + } + + if (property === TypeId) { + return target[TypeId]; + } + + if (typeof property === "string" && /^\d+$/u.test(property)) { + const index = Number(property); + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), index)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + } + + if (typeof property === "string") { + const expr = Result.map( + target[Binding], + (node) => new AST.Expr(JExpr.access(node.compile(), property)), + ); + const impl = new ExpressionImpl(expr); + return make(impl); + } + + return Reflect.get(target, property, receiver); + }, + }); + + // SAFETY: the target retains T's invariant marker, and the traps construct syntax for the typed operations. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the proxy implements the type-directed operations + return proxy as Expression; +}; + +export const fromResult = ( + node: Result.Result, +): Expression => make(new ExpressionImpl(node)); + +/** + * Ascribes a semantic type to syntax supplied by a declaration or another trusted builder. + * + * The caller supplies the semantic type and input requirements. This operation validates syntax only. + */ +export const fromJExpr = ( + expression: JExpr.Expression, +): Expression => fromResult(parseNode(expression)); + +export const fromNode = ( + node: AST.Node, +): Expression => fromResult(Result.succeed(node)); + +/** + * Changes the SDK's type assumption without changing the query syntax. + * + * This performs no validation or conversion and emits no HashQL type assertion. + */ +export const assume = + () => + (expression: E): Expression> => + fromResult>(toNode(expression)); + +export const literal = ( + value: V, +): Expression, Input.Empty> => fromJExpr(JExpr.literal(value)); + +export const integer = ( + value: number | bigint, +): Expression => + fromJExpr(JExpr.integer(value)); + +export const number = ( + value: number, +): Expression => + fromJExpr(JExpr.literal(value)); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs an input from its name and type +export function input( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue?: undefined, +): Expression>>; +export function input< + const Name extends string, + T extends Type.Any, + const Default extends Value>, +>( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue: Default, +): Expression< + T, + Input.Merge>>, Inputs> +>; +export function input< + const Name extends string, + T extends Type.Any, + const Default extends Value>, +>( + name: Name, + type: TypeExpression.TypeExpression, + defaultValue: Default | undefined, +): Expression>, Inputs>>; +export function input( + name: string, + type: TypeExpression.TypeExpression, + defaultValue?: AnyValue, +): Expression { + return Result.gen(function* () { + const syntax = yield* TypeExpression.toType(type); + if (defaultValue === undefined) { + return yield* toNode(fromJExpr(JExpr.input(name, syntax))); + } + + const value = yield* toJExpr(defaultValue); + return yield* toNode(fromJExpr(JExpr.input(name, syntax, value))); + }).pipe(fromResult); +} + +/** Constructs a conditional whose result type combines its branch types. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the condition and branches construct a new expression +export const ifElse = < + const Condition extends Value, + const Then extends AnyValue, + const Else extends AnyValue, +>( + condition: Condition, + branches: { + readonly then: Then; + readonly else: Else; + }, +): Expression< + Conditional, TypeOf>, + Input.Merge, Input.Merge, Inputs>> +> => + pipe( + { + condition: toNode(condition), + consequent: toNode(branches.then), + alternate: toNode(branches.else), + }, + Result.all, + Result.map( + ({ condition, consequent, alternate }) => + new AST.If(condition, consequent, alternate), + ), + fromResult< + Conditional, TypeOf>, + Input.Merge, Input.Merge, Inputs>> + >, + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts new file mode 100644 index 00000000000..e7c3f4f7cce --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts @@ -0,0 +1,361 @@ +import type * as Type from "../type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Input from "./Inputs.js"; + +type Composition = "Union" | "Intersection"; +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- the empty intersection contributes no accessor members +type EmptyAccessors = Record; + +type Same = [Left] extends [Right] + ? [Right] extends [Left] + ? true + : false + : false; + +type Includes< + Members extends readonly Type.Any[], + Member extends Type.Any, +> = Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], +] + ? Same extends true + ? true + : Includes + : false; + +type Unique< + Members extends readonly Type.Any[], + Result extends readonly Type.Any[], +> = number extends Members["length"] + ? Members + : Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], + ] + ? Includes extends true + ? Unique + : Unique + : Result; + +type MembersOf = T extends { + readonly _tag: Kind; + readonly types: infer Members extends readonly Type.Any[]; +} + ? Members + : readonly [T]; + +type Compose< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [] + ? Kind extends "Union" + ? Type.Never + : Type.Unknown + : Members extends readonly [infer Member extends Type.Any] + ? Member + : Kind extends "Union" + ? Type.Union + : Type.Intersection; + +type Join< + Left extends Type.Any, + Right extends Type.Any, +> = Left extends Type.Never + ? Right + : Right extends Type.Never + ? Left + : Left extends Type.Unknown + ? Type.Unknown + : Right extends Type.Unknown + ? Type.Unknown + : Compose< + "Union", + Unique< + readonly [ + ...MembersOf, + ...MembersOf, + ], + readonly [] + > + >; + +type PrimitiveConflict = + Left extends Type.Intersection + ? true extends { + [Index in keyof Members]: PrimitiveConflict; + }[number] + ? true + : false + : Right extends Type.Intersection + ? true extends { + [Index in keyof Members]: PrimitiveConflict; + }[number] + ? true + : false + : Left extends Type.Primitive + ? Right extends Type.Primitive + ? [Left | Right] extends [ + Type.PrimitiveInteger | Type.PrimitiveNumber, + ] + ? false + : Same extends true + ? false + : true + : false + : false; + +type MeetMembers< + Members extends readonly Type.Any[], + Other extends Type.Any, +> = { + readonly [Index in keyof Members]: Meet; +}; + +type Meet< + Left extends Type.Any, + Right extends Type.Any, +> = Left extends Type.Never + ? Type.Never + : Right extends Type.Never + ? Type.Never + : Left extends Type.Unknown + ? Right + : Right extends Type.Unknown + ? Left + : Same extends true + ? Left + : Left extends Type.Union + ? Reduce<"Union", MeetMembers, Type.Never> + : Right extends Type.Union + ? Reduce<"Union", MeetMembers, Type.Never> + : PrimitiveConflict extends true + ? Type.Never + : Compose< + "Intersection", + Unique< + readonly [ + ...MembersOf, + ...MembersOf, + ], + readonly [] + > + >; + +type Reduce< + Kind extends Composition, + Members extends readonly Type.Any[], + Result extends Type.Any, +> = number extends Members["length"] + ? Kind extends "Union" + ? Type.Union + : Type.Intersection + : Members extends readonly [ + infer Head extends Type.Any, + ...infer Tail extends readonly Type.Any[], + ] + ? Reduce< + Kind, + Tail, + Kind extends "Union" + ? Join> + : Meet> + > + : Result; + +/** Simplifies explicit unions and intersections without widening the parent expression's type. */ +export type Normalize = [T] extends [never] + ? Type.Never + : [T] extends [Type.Union] + ? Reduce<"Union", Members, Type.Never> + : [T] extends [Type.Intersection] + ? Reduce<"Intersection", Members, Type.Unknown> + : T; + +type Combine< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Reduce; + +type FieldMaps = { + readonly [Index in keyof Members]: FieldsOf>; +}; + +type ProjectMembers< + Members extends readonly Type.Any[], + Key extends PropertyKey, +> = { + readonly [Index in keyof Members]: Key extends keyof FieldsOf< + Normalize + > + ? FieldsOf>[Key] extends infer Field extends + Type.Any + ? Field + : never + : never; +}; + +/** A projection is available only when every member supports it. */ +type CombinedFields< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [] + ? EmptyAccessors + : { + readonly [Key in keyof FieldMaps[number]]: Combine< + Kind, + ProjectMembers + >; + }; + +type FieldsOf = [T] extends [Type.Struct] + ? { + readonly [Field in Extract]: Fields[Field]; + } + : [T] extends [Type.Tuple.Any] + ? { + readonly [Index in Extract< + keyof T["fields"], + `${number}` + > as Index extends `${infer Position extends number}` + ? Position + : never]: T["fields"][Index]; + } + : [T] extends [Type.Opaque] + ? FieldsOf> + : [T] extends [Type.Union] + ? CombinedFields<"Union", Members> + : [T] extends [Type.Intersection] + ? CombinedFields<"Intersection", Members> + : EmptyAccessors; + +interface IndexDescriptor { + readonly key: Type.Any; + readonly value: Type.Any; +} + +type IndexValues = { + readonly [Index in keyof Members]: IndexOf< + Normalize + > extends infer Descriptor extends IndexDescriptor + ? Descriptor["value"] + : never; +}; + +type IndexFailures< + Members extends readonly Type.Any[], + Key extends Type.Any, +> = { + readonly [Index in keyof Members]: IndexOf< + Normalize + > extends infer Descriptor + ? [Descriptor] extends [IndexDescriptor] + ? Same extends true + ? never + : Index + : Index + : Index; +}[number]; + +type CombinedIndex< + Kind extends Composition, + Members extends readonly Type.Any[], +> = Members extends readonly [ + infer Head extends Type.Any, + ...(readonly Type.Any[]), +] + ? IndexOf> extends infer Descriptor + ? [Descriptor] extends [IndexDescriptor] + ? [IndexFailures] extends [never] + ? { + readonly key: Descriptor["key"]; + readonly value: Combine>; + } + : undefined + : undefined + : undefined + : undefined; + +type IndexOf = [T] extends [Type.List] + ? { readonly key: Type.PrimitiveInteger; readonly value: Value } + : [T] extends [Type.Dict] + ? { readonly key: Key; readonly value: Value } + : [T] extends [Type.Opaque] + ? IndexOf> + : [T] extends [Type.Union] + ? CombinedIndex<"Union", Members> + : [T] extends [Type.Intersection] + ? CombinedIndex<"Intersection", Members> + : undefined; + +type ProjectionAccessors = { + readonly [Key in Exclude< + keyof Fields, + "$" | "$project" | "$index" | "then" | "~hashql/Expression" + >]: Fields[Key] extends infer Field extends Type.Any + ? Expression.Expression, Inputs> + : never; +} & ([keyof Fields] extends [never] + ? EmptyAccessors + : { + readonly $project: ( + key: Key, + ) => Fields[Key] extends infer Field extends Type.Any + ? Expression.Expression, Inputs> + : never; + }); + +type IndexAccessor = [Descriptor] extends [IndexDescriptor] + ? { + readonly $index: >( + key: Key, + ) => Expression.Expression< + Join, Type.PrimitiveNull>, + Input.Merge> + >; + } + : EmptyAccessors; + +export type Accessors = ProjectionAccessors< + FieldsOf>, + Inputs +> & + IndexAccessor>, Inputs>; + +export type Arguments = { + readonly [Index in keyof Parameters]: Expression.Value; +}; + +export type ArgumentInputs = + Input.All<{ + readonly [Index in keyof Values]: Expression.Inputs; + }>; + +type ArgumentTypes = { + readonly [Index in keyof Values]: Expression.TypeOf; +}; + +export type Callable = + T extends Type.Function + ? >( + ...args: Values + ) => Expression.Expression< + Returns, + Input.Merge> + > + : T extends Type.GenericFunction + ? ( + ...args: Values & + Arguments< + Type.Apply>["parameters"] + > + ) => Expression.Expression< + Type.Apply>["returns"], + Input.Merge> + > + : EmptyAccessors; + +export type Conditional = Join< + Normalize, + Normalize +>; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts new file mode 100644 index 00000000000..cfaff1f8d0d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts @@ -0,0 +1,69 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Program } from "../main.js"; + +import type { Type } from "../main.js"; +import type * as Inputs from "./Inputs.js"; +import type * as ProgramError from "./ProgramError.js"; +import type { Result } from "effect"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +describe("fluent_types", () => { + test("graph_vertex", () => { + const { Do } = Program.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const result = Do(($) => + $.query + .entities() + .filter("item", (item) => { + expectTypeOf(item).toEqualTypeOf< + Expression.Expression + >(); + return item.enabled.$.isFalse(); + }) + .collect(), + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, Inputs.Empty>, + ProgramError.Construction + > + >(); + Do(($) => { + // @ts-expect-error A predicate must return a Boolean. + $.query.entities().filter("item", (item) => item); + // @ts-expect-error Query construction has no compatibility adapter. + expectTypeOf($.query.from); + return $.literal(true); + }); + }); + + test("operation_domains", () => { + Program.Do(($) => { + const integer = $.integer(1); + expectTypeOf(integer).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error Boolean operations do not belong to an integer. + expectTypeOf(integer.$.and); + // @ts-expect-error Graph operations do not belong to an integer. + expectTypeOf(integer.$.collect); + // @ts-expect-error An integer is not optional. + expectTypeOf(integer.$.isNone); + // @ts-expect-error A Boolean conjunction needs a Boolean operand. + $.literal(true).$.and(integer); + return integer.$.eq($.integer(2)); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts new file mode 100644 index 00000000000..827dd1d1d17 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts @@ -0,0 +1,105 @@ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results +// oxlint-disable vitest/prefer-to-be-falsy -- these checks assert exact Boolean results +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, Program } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; +const { Do } = Program.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, +}); + +describe("fluent", () => { + test("named_filter", () => { + expect.hasAssertions(); + let calls = 0; + const result = Do(($) => + $.query + .entities() + .filter("item", (item) => { + calls += 1; + return item.enabled.$.isFalse(); + }) + .collect(), + ); + const syntax = Result.getOrThrow( + Result.flatMap(result, Expression.toJExpr), + ); + expect(syntax).toStrictEqual([ + "::graph::tail::collect", + [ + "::graph::body::filter", + ["entities"], + [ + "fn", + { "#tuple": [] }, + { "#struct": { item: "_" } }, + "_", + [ + "::core::cmp::eq", + ["::kernel::special_form::access", "item", "enabled"], + { "#literal": false }, + ], + ], + ], + ]); + expect(calls).toBe(1); + }); + + test("invalid_parameter", () => { + expect.hasAssertions(); + let called = false; + const result = Do(($) => + $.query.entities().filter("bad name", () => { + called = true; + return $.literal(true); + }), + ); + expect(Result.isFailure(result)).toBe(true); + expect(called).toBe(false); + }); + + test("predicate_failure", () => { + expect.hasAssertions(); + const result = Do(($) => + $.query + .entities() + .filter("item", () => + $.Let("bad name", ($) => $.literal(true)).Expr( + (_, values) => values["bad name"], + ), + ) + .collect(), + ); + expect(Result.isFailure(result)).toBe(true); + }); + + test("reserved_projection", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, + Inputs.Empty + >("record"); + const result = Program.Do(() => record.$project("$").$.isTrue()); + expect( + Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), + ).toStrictEqual([ + "::core::cmp::eq", + ["::kernel::special_form::access", "record", "$"], + { "#literal": true }, + ]); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts new file mode 100644 index 00000000000..090a86b8fd4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts @@ -0,0 +1,100 @@ +import { Result } from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as AST from "./ast/index.js"; + +import type * as Type from "../type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Input from "./Inputs.js"; + +interface Comparison { + readonly eq: >( + other: Other, + ) => Expression.Expression< + Type.PrimitiveBoolean, + Input.Merge> + >; + readonly ne: >( + other: Other, + ) => Expression.Expression< + Type.PrimitiveBoolean, + Input.Merge> + >; +} + +interface BooleanOperations { + readonly and: >( + other: Other, + ) => Expression.Expression< + Type.PrimitiveBoolean, + Input.Merge> + >; + readonly or: >( + other: Other, + ) => Expression.Expression< + Type.PrimitiveBoolean, + Input.Merge> + >; + readonly isTrue: () => Expression.Expression; + readonly isFalse: () => Expression.Expression; +} + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- inapplicable operations add no members +type Empty = Record; + +type Optional = + T extends Type.Union + ? Extract< + Members[number], + Type.Opaque<"::core::option::None", Type.Any> + > extends never + ? Empty + : { + readonly isNone: () => Expression.Expression< + Type.PrimitiveBoolean, + Inputs + >; + } + : Empty; + +export type Operations = Comparison & + (T extends Type.PrimitiveBoolean ? BooleanOperations : Empty) & + Optional; + +interface Runtime { + readonly eq: (other: Expression.AnyValue) => Expression.Any; + readonly ne: (other: Expression.AnyValue) => Expression.Any; + readonly and: (other: Expression.AnyValue) => Expression.Any; + readonly or: (other: Expression.AnyValue) => Expression.Any; + readonly isTrue: () => Expression.Any; + readonly isFalse: () => Expression.Any; + readonly isNone: () => Expression.Any; +} + +type Factory = Pick; + +/** The expression proxy exposes only operations allowed by its semantic descriptor. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the expression implementation supplies factories to avoid a runtime import cycle +export const make = (self: Expression.Any, factory: Factory): Runtime => { + const call = ( + path: string, + ...args: readonly Expression.AnyValue[] + ): Expression.Any => + factory.fromResult( + Result.all(args.map(factory.toJExpr)).pipe( + Result.map((args) => new AST.Expr(JExpr.call(path, ...args))), + ), + ); + + return { + eq: (other) => call("::core::cmp::eq", self, other), + ne: (other) => call("::core::cmp::ne", self, other), + and: (other) => call("::core::bool::and", self, other), + or: (other) => call("::core::bool::or", self, other), + isTrue: () => + call("::core::cmp::eq", self, factory.fromJExpr(JExpr.literal(true))), + isFalse: () => + call("::core::cmp::eq", self, factory.fromJExpr(JExpr.literal(false))), + isNone: () => call("::core::cmp::eq", self, call("::core::option::None")), + }; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts new file mode 100644 index 00000000000..981771548f3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts @@ -0,0 +1,91 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Import, Module, Program } from "../main.js"; + +import type { Expression, Inputs, Type } from "../main.js"; +import type * as ProgramError from "./ProgramError.js"; +// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); +const { Do } = Program.withPrelude({ modules: { uuid, core } }); + +describe("import_types", () => { + test("named_exports", () => { + const result = Do( + Import((_, { uuid }) => uuid, ["Uuid"]), + ($, values, types) => { + expectTypeOf(types.Uuid).toEqualTypeOf(); + expectTypeOf(values.Uuid).toEqualTypeOf(); + // @ts-expect-error Module names do not enter the type universe. + expectTypeOf(types.uuid); + // @ts-expect-error Utilities are not a flattened export namespace. + expectTypeOf($.Uuid); + return $.ref.uuid.values.Uuid($.literal("id")); + }, + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, + ProgramError.Construction + > + >(); + }); + + test("module_alias", () => { + Do( + Import((_, { core }) => core, { uuid: "ids" }), + Import((_, { ids }) => ids), + ($, { Uuid }, types) => { + expectTypeOf($.ref.ids).toEqualTypeOf(); + expectTypeOf(types.Uuid).toEqualTypeOf(); + return Uuid($.literal("id")); + }, + ); + }); + + test("invalid_exports", () => { + expectTypeOf(Program.withPrelude); + // @ts-expect-error Values must be expression handles. + Program.withPrelude({ values: { host: 1 } }); + // @ts-expect-error Modules must be module declarations. + Program.withPrelude({ modules: { uuid: uuid.values.Uuid } }); + // @ts-expect-error Types cannot be value handles. + Program.withPrelude({ types: { Uuid: uuid.values.Uuid } }); + // @ts-expect-error An import selects a module. + Import(() => ({ Uuid: uuid.values.Uuid })); + // @ts-expect-error Selected names must exist in an export universe. + Import(() => uuid, ["Missing"]); + // @ts-expect-error Alias sources must exist in an export universe. + Import(() => uuid, { Missing: "Local" }); + }); + + test("literal_types", () => { + Program.Do(($) => { + expectTypeOf($.integer(1)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf($.number(1)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf($.literal(false)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf($.literal(1)).toEqualTypeOf< + Expression.Expression + >(); + return $.literal(null); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Import.test.ts new file mode 100644 index 00000000000..9cbe3fc52f9 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Import.test.ts @@ -0,0 +1,217 @@ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results +// oxlint-disable vitest/prefer-to-be-falsy -- these checks assert exact Boolean results +// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { + Expression, + Import, + Let, + Module, + Program, + TypeExpression, +} from "../main.js"; + +import type { Type } from "../main.js"; + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); +const { Do } = Program.withPrelude({ modules: { uuid, core } }); + +const use = "::kernel::special_form::use"; +const shadowValue = 7; + +describe("import_exports", () => { + test("same_named_exports", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { uuid }) => uuid), + ($, { Uuid }, { Uuid: uuidType }) => { + expect( + Result.getOrThrow(TypeExpression.toType(uuidType)), + ).toMatchObject({ + _tag: "Reference", + path: { rooted: false, segments: [{ value: "Uuid" }] }, + }); + return Uuid($.literal("id")); + }, + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([use, "::core::uuid", "*", ["Uuid", { "#literal": "id" }]]); + }); + + test("named_import", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { uuid }) => uuid, ["Uuid"]), + ($, { Uuid }, types) => + $.input("id", types.Uuid, Uuid($.literal("fallback"))), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + use, + "::core::uuid", + { "#tuple": ["Uuid"] }, + [ + "::kernel::special_form::input", + "id", + "Uuid", + ["Uuid", { "#literal": "fallback" }], + ], + ]); + }); + + test("renamed_exports", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { uuid }) => uuid, { Uuid: "Id" }), + ($, { Id }, types) => $.input("id", types.Id, Id($.literal("fallback"))), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + use, + "::core::uuid", + { "#struct": { Uuid: "Id" } }, + [ + "::kernel::special_form::input", + "id", + "Id", + ["Id", { "#literal": "fallback" }], + ], + ]); + }); + + test("module_alias", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { core }) => core, { uuid: "ids" }), + Import((_, { ids }) => ids), + ($, { Uuid }) => Uuid($.literal("id")), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + use, + "::core", + { "#struct": { uuid: "ids" } }, + [use, "ids", "*", ["Uuid", { "#literal": "id" }]], + ]); + const qualified = Do( + Import((_, { core }) => core, { uuid: "ids" }), + ($) => $.ref.ids.values.Uuid($.literal("id")), + ); + expect( + Result.getOrThrow(Result.flatMap(qualified, Expression.toJExpr)), + ).toStrictEqual([ + use, + "::core", + { "#struct": { uuid: "ids" } }, + ["ids::Uuid", { "#literal": "id" }], + ]); + }); +}); + +describe("import_validation", () => { + test("invalid_alias", () => { + expect.hasAssertions(); + let called = false; + const result = Do( + Import((_, { uuid }) => uuid, { Uuid: "bad name" }), + ($) => { + called = true; + return $.integer(1); + }, + ); + expect(Result.isFailure(result)).toBe(true); + expect(called).toBe(false); + }); +}); + +describe("import_scope", () => { + test("independent_shadow", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { uuid }) => uuid), + Let("Uuid", ($) => $.integer(shadowValue)), + ($, { Uuid }, types) => { + expect(Result.getOrThrow(Expression.toJExpr(Uuid))).toBe("Uuid"); + return $.input("id", types.Uuid); + }, + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + use, + "::core::uuid", + "*", + [ + "::kernel::special_form::let", + "Uuid", + { "#literal": { _tag: "Integer", value: "7" } }, + ["::kernel::special_form::input", "id", "Uuid"], + ], + ]); + }); + + test("branch_import_isolation", () => { + expect.hasAssertions(); + const root = Do(($) => + $.if( + $.literal(true), + () => + $.Import((_, { uuid }) => uuid).Expr(($, { Uuid }) => + Uuid($.literal("id")), + ), + () => + $.Expr(($, values, types) => { + expect(values).toStrictEqual({}); + expect(types).toStrictEqual({}); + return $.ref.uuid.values.Uuid($.literal("fallback")); + }), + ), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::if", + { "#literal": true }, + [use, "::core::uuid", "*", ["Uuid", { "#literal": "id" }]], + ["::core::uuid::Uuid", { "#literal": "fallback" }], + ]); + }); + + test("input_defaults", () => { + expect.hasAssertions(); + const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }), + ); + const root = Program.withPrelude(kernel).Do(($, _, { Integer }) => + $.input("count", Integer, $.integer(0)), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::input", + "count", + "::kernel::type::Integer", + { "#literal": { _tag: "Integer", value: "0" } }, + ]); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts new file mode 100644 index 00000000000..4030af00c29 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts @@ -0,0 +1,314 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Let, Module, Program } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + Boolean: Module.type(), + String: Module.type(), + }, + }), +); +const integer = kernel.types.Integer; +const boolean = kernel.types.Boolean; +const string = kernel.types.String; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +interface Same extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +declare const optionalDefault: + | Expression.Expression< + Type.PrimitiveInteger, + { readonly fallback: Type.PrimitiveInteger } + > + | undefined; + +describe("input_requirements", () => { + test("required_and_default", () => { + const required = Expression.input("count", integer); + const optional = Expression.input("limit", integer, Expression.integer(10)); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly limit?: Type.PrimitiveInteger; + }>(); + // @ts-expect-error A closed-expression annotation cannot discard a required input. + const closed: Expression.Expression = + required; + expectTypeOf(closed); + // @ts-expect-error The default must have the input's declared semantic type. + Expression.input("count", integer, Expression.literal(false)); + }); + + test("uncertain_default", () => { + const value = Expression.input("count", integer, optionalDefault); + // oxlint-disable-next-line unicorn/no-useless-undefined -- checks an explicitly absent host default + const omitted = Expression.input("count", integer, undefined); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly fallback: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + }); + + test("default_dependencies", () => { + const fallback = Expression.input("fallback", integer); + const value = Expression.input("count", integer, fallback); + expectTypeOf>().toEqualTypeOf<{ + readonly count?: Type.PrimitiveInteger; + readonly fallback: Type.PrimitiveInteger; + }>(); + }); + + test("repeated_name", () => { + const optional = Expression.input( + "enabled", + boolean, + Expression.literal(true), + ); + const required = Expression.input("enabled", boolean); + const both = optional.$.and(required); + expectTypeOf>().toEqualTypeOf<{ + readonly enabled: Type.PrimitiveBoolean; + }>(); + const defaults = optional.$.or(optional); + expectTypeOf>().toEqualTypeOf<{ + readonly enabled?: Type.PrimitiveBoolean; + }>(); + }); + + test("conflicting_name", () => { + const count = Expression.input("shared", integer); + const text = Expression.input("shared", string); + const value = Expression.ifElse(Expression.literal(true), { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch + then: count, + else: text, + }); + expectTypeOf>().toEqualTypeOf<{ + readonly shared: Type.Never; + }>(); + }); +}); + +describe("operation_requirements", () => { + test("primitive_composition", () => { + const left = Expression.input("left", integer); + const right = Expression.input("right", integer); + const enabled = Expression.input("enabled", boolean); + const predicate = left.$.eq(right) + .$.and(enabled.$.isTrue()) + .$.or(enabled.$.isFalse()); + expectTypeOf>().toEqualTypeOf<{ + readonly left: Type.PrimitiveInteger; + readonly right: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + }); + + test("projection_and_index", () => { + const module = Result.getOrThrow( + Module.define("::example", { + types: { + Rows: Module.type< + Type.Struct<{ readonly values: Type.List }> + >(), + }, + }), + ); + const rows = Expression.input("rows", module.types.Rows); + const position = Expression.input("position", integer); + const projected = rows.$project("values"); + const selected = rows.values.$index(position); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly rows: Type.Struct<{ + readonly values: Type.List; + }>; + readonly position: Type.PrimitiveInteger; + }>(); + }); + + test("function_and_generic_calls", () => { + const count = Expression.input("count", integer); + const callee = Expression.fromJExpr< + Type.Function, + { readonly receiver: Type.PrimitiveBoolean } + >("callee"); + const result = callee(count); + expectTypeOf>().toEqualTypeOf<{ + readonly receiver: Type.PrimitiveBoolean; + readonly count: Type.PrimitiveInteger; + }>(); + const generic = Expression.fromJExpr< + Type.GenericFunction, + Inputs.Empty + >("same"); + const identity = generic(count); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + // @ts-expect-error Input accumulation must not widen the call's parameter types. + callee(Expression.input("wrong", boolean)); + // @ts-expect-error A fixed signature still checks arity. + callee(count, count); + }); +}); + +describe("snippet_requirements", () => { + test("reusable_snippet", () => { + const count = Expression.input("count", integer); + const snippet = count.$.ne(Expression.integer(0)); + const first = Result.getOrThrow(Program.Do(() => snippet)); + const second = Result.getOrThrow( + Program.Do(($) => snippet.$.and($.input("enabled", boolean))), + ); + const program = Program.program(second); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + }); + + test("discarded_expression", () => { + const expression = Result.getOrThrow( + Program.Do(($) => { + $.input("unused", integer); + return $.integer(1); + }), + ); + expectTypeOf(expression).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("unused_and_shadowed_declarations", () => { + const expression = Result.getOrThrow( + Program.Do( + Let("value", ($) => $.input("first", integer)), + Let("value", ($) => $.input("second", integer)), + ($) => $.integer(1), + ), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly first: Type.PrimitiveInteger; + readonly second: Type.PrimitiveInteger; + }>(); + }); + + test("nested_branches", () => { + const expression = Result.getOrThrow( + Program.Do(($) => + $.if( + $.input("condition", boolean), + () => + $.Let("ignored", ($) => $.input("left", integer)).Expr(($) => + $.integer(1), + ), + () => $.input("right", integer), + ), + ), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly condition: Type.PrimitiveBoolean; + readonly left: Type.PrimitiveInteger; + readonly right: Type.PrimitiveInteger; + }>(); + }); +}); + +describe("builder_requirements", () => { + test("query_dependencies", () => { + const { Do } = Program.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const expression = Result.getOrThrow( + Do(($) => + $.query + .entities($.input("at", integer)) + .filter("vertex", (vertex) => + vertex.enabled.$.eq($.input("enabled", boolean)), + ) + .collect(), + ), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly at: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + }); + + test("declaration_preservation", () => { + const { + Do, + Type: Alias, + Import, + } = Program.withPrelude({ modules: { kernel } }); + const expression = Result.getOrThrow( + Do( + Import((_, { kernel }) => kernel), + Let("first", ($, _, { Integer: integerType }) => + $.input("first", integerType), + ), + Alias("Count", (_, { Integer: integerType }) => integerType), + Let("second", ($, _, { Count: countType }) => + $.input("second", countType), + ), + Let("third", ($) => $.input("third", integer)), + Let("fourth", ($) => $.input("fourth", integer)), + Let("fifth", ($) => $.input("fifth", integer)), + Let("sixth", ($) => $.input("sixth", integer)), + ($) => $.integer(1), + ), + ); + expectTypeOf>().toEqualTypeOf< + "first" | "second" | "third" | "fourth" | "fifth" | "sixth" + >(); + const nested = Result.getOrThrow( + Do(($) => + $.Let("value", ($) => $.input("kept", integer)) + .Import((_, { kernel }) => kernel) + .Type("Count", (_, { Integer: integerType }) => integerType) + .Expr(($) => $.integer(1)), + ), + ); + expectTypeOf>().toEqualTypeOf<{ + readonly kept: Type.PrimitiveInteger; + }>(); + }); + + test("assumption_preservation", () => { + const source = Expression.input("source", integer); + const assumed = Expression.assume()(source); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts new file mode 100644 index 00000000000..df7a621ccc9 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts @@ -0,0 +1,64 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr, Let, Module, Program } from "../main.js"; + +import type { Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }), +); +const integer = kernel.types.Integer; +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +describe("input_composition", () => { + test("snippet_reuse", () => { + expect.hasAssertions(); + const snippet = Expression.input("count", integer, Expression.integer(7)); + const first = Result.getOrThrow(Program.Do(() => snippet)); + const second = Result.getOrThrow( + Program.Do(($) => snippet.$.eq($.input("other", integer))), + ); + expect(compile(first)).toBe( + '["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}]', + ); + expect(compile(second)).toBe( + '["::core::cmp::eq",["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}],["::kernel::special_form::input","other","::kernel::type::Integer"]]', + ); + expect(compile(snippet)).toBe(compile(first)); + }); + + test("discarded_input", () => { + expect.hasAssertions(); + const expression = Result.getOrThrow( + Program.Do(($) => { + $.input("discarded", integer); + return $.integer(1); + }), + ); + expect(compile(expression)).toBe('{"#literal":1}'); + }); + + test("unused_initializer", () => { + expect.hasAssertions(); + const expression = Result.getOrThrow( + Program.Do( + Let("unused", ($) => $.input("retained", integer)), + ($) => $.integer(1), + ), + ); + expect(compile(expression)).toBe( + '["::kernel::special_form::let","unused",["::kernel::special_form::input","retained","::kernel::type::Integer"],{"#literal":1}]', + ); + }); + + test("assumption_syntax", () => { + expect.hasAssertions(); + const expression = Expression.input("count", integer); + const assumed = Expression.assume()(expression); + expect(compile(assumed)).toBe(compile(expression)); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts new file mode 100644 index 00000000000..e0f234e4050 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts @@ -0,0 +1,55 @@ +import type * as Type from "../type/index.js"; +import type { Normalize } from "./ExpressionType.js"; +import type { Types } from "effect"; + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- a closed expression requires no input names +export type Empty = Record; + +type RequiredKeys = { + [Key in keyof Inputs]-?: Empty extends Pick ? never : Key; +}[keyof Inputs]; + +type At = Key extends keyof Inputs + ? Exclude + : never; + +type Combined = Key extends keyof Left + ? Key extends keyof Right + ? At extends infer LeftType extends Type.Any + ? At extends infer RightType extends Type.Any + ? Normalize> + : never + : never + : At + : At; + +/** A shared input must satisfy every use. One required use makes it required. */ +export type Merge = [keyof Right] extends [never] + ? Left + : [keyof Left] extends [never] + ? Right + : Types.Simplify< + { + readonly [Key in RequiredKeys | RequiredKeys]: Combined< + Left, + Right, + Key + >; + } & { + readonly [Key in Exclude< + keyof Left | keyof Right, + RequiredKeys | RequiredKeys + >]?: Combined; + } + >; + +/** Combines every member of a tuple, or conservatively intersects an array's member requirements. */ +// oxlint-disable-next-line typescript/no-restricted-types -- each member is an inferred input record +export type All = Members extends readonly [ + infer Head, + ...infer Tail, +] + ? Merge> + : number extends Members["length"] + ? Types.UnionToIntersection + : Empty; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts new file mode 100644 index 00000000000..4942171423c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts @@ -0,0 +1,219 @@ +// oxlint-disable unicorn/no-array-method-this-argument -- filter is a HashQL function, not Array.filter +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import * as Module from "./Module.js"; + +import type * as Type from "../type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; +import type { TypeExpression } from "./TypeExpression.js"; + +type Vertex = Type.Struct<{ readonly name: Type.PrimitiveString }>; +type OtherVertex = Type.Struct<{ readonly age: Type.PrimitiveInteger }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": T }> +>; +type VertexOf = T extends Graph ? VertexType : never; + +interface Filter extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer Input, Type.Any] + ? Type.Function< + readonly [ + Graph>, + Type.Function], Type.PrimitiveBoolean>, + ], + Graph> + > + : Type.Function; +} + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [ + infer Element extends Type.Any, + ] + ? Type.List + : Type.Never; +} + +interface Equal extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer Left extends Type.Any, + infer Right extends Type.Any, + ] + ? Type.Function + : Type.Function; +} + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +type Remainder = Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger +>; + +const kernelTypes = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + String: Module.type(), + List: Module.genericType(1), + }, + }), +); +const math = Result.getOrThrow( + Module.define("::core::math", { + values: { rem: Module.value() }, + }), +); +const cmp = Result.getOrThrow( + Module.define("::core::cmp", { + values: { eq: Module.value>() }, + }), +); +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const body = Result.getOrThrow( + Module.define("::graph::body", { + values: { filter: Module.value>() }, + }), +); +const modules = Result.getOrThrow( + Module.root({ + kernel: Result.getOrThrow( + Module.define("::kernel", { modules: { type: kernelTypes } }), + ), + core: Result.getOrThrow( + Module.define("::core", { modules: { math, cmp, uuid } }), + ), + graph: Result.getOrThrow(Module.define("::graph", { modules: { body } })), + }), +); +const prelude = { + rem: modules.modules.core.modules.math.values.rem, + eq: modules.modules.core.modules.cmp.values.eq, + filter: modules.modules.graph.modules.body.values.filter, + Integer: modules.modules.kernel.modules.type.types.Integer, + List: modules.modules.kernel.modules.type.types.List, +}; +const aliases = Result.getOrThrow( + Module.define("::application", { + values: { select: prelude.filter }, + types: { Sequence: prelude.List }, + }), +); + +declare const integer: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty +>; +declare const string: Expression.Expression; +declare const vertices: Expression.Expression, Inputs.Empty>; +declare const predicate: Expression.Expression< + Type.Function, + Inputs.Empty +>; +declare const otherPredicate: Expression.Expression< + Type.Function, + Inputs.Empty +>; +declare const wrongResult: Expression.Expression< + Type.Function, + Inputs.Empty +>; + +describe("module_types", () => { + test("module_call_types", () => { + expectTypeOf(prelude.rem(integer, integer)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(prelude.eq(integer, string)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(uuid.values.Uuid(string)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(uuid.types.Uuid).toEqualTypeOf>(); + // @ts-expect-error Remainder requires integers. + prelude.rem(integer, string); + // @ts-expect-error Remainder takes two operands. + prelude.rem(integer); + // @ts-expect-error Values and types occupy distinct namespaces. + uuid.types.Uuid(string); + // @ts-expect-error A newtype remains distinct from its representation. + prelude.rem(uuid.values.Uuid(string), integer); + }); + + test("generic_alias", () => { + expectTypeOf(body.values.filter(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + expectTypeOf(prelude.filter(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + expectTypeOf(aliases.values.select(vertices, predicate)).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + // @ts-expect-error The predicate's vertex must match the graph's vertex. + prelude.filter(vertices, otherPredicate); + // @ts-expect-error A predicate returns Boolean. + prelude.filter(vertices, wrongResult); + // @ts-expect-error The source must be a graph. + prelude.filter(integer, predicate); + // @ts-expect-error Filter requires a predicate. + prelude.filter(vertices); + // @ts-expect-error Filter takes two operands. + prelude.filter(vertices, predicate, integer); + }); + + test("generic_type", () => { + expectTypeOf(prelude.List(prelude.Integer)).toEqualTypeOf< + TypeExpression> + >(); + expectTypeOf( + aliases.types.Sequence(kernelTypes.types.String), + ).toEqualTypeOf>>(); + expectTypeOf(prelude.List(prelude.List(prelude.Integer))).toEqualTypeOf< + TypeExpression>> + >(); + // @ts-expect-error List requires an element type. + prelude.List(); + // @ts-expect-error List has exactly one type parameter. + prelude.List(prelude.Integer, prelude.Integer); + // @ts-expect-error A value expression is not a type expression. + prelude.List(integer); + // @ts-expect-error The constructor's arity comes from its declaration. + Module.genericType(2); + }); + + test("tree_members", () => { + expectTypeOf(modules.modules.core.modules.math.values.rem).toEqualTypeOf< + typeof prelude.rem + >(); + // @ts-expect-error Missing modules do not become arbitrary string lookups. + expectTypeOf(modules.modules.missing); + // @ts-expect-error Empty namespaces retain their exact keys. + expectTypeOf(math.types.Integer); + // @ts-expect-error A module record is readonly. + modules.modules.core = modules.modules.kernel; + // @ts-expect-error A value export is readonly. + math.values.rem = prelude.eq; + // @ts-expect-error A value declaration cannot enter the type namespace. + Module.define("::bad", { types: { value: Module.value() } }); + Result.getOrThrow( + Module.define("::bad", { + // @ts-expect-error A type declaration cannot enter the value namespace. + values: { Integer: Module.type() }, + }), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts new file mode 100644 index 00000000000..61873473863 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts @@ -0,0 +1,302 @@ +// oxlint-disable vitest/prefer-to-be-truthy -- freeze and membership checks need exact Boolean assertions +// oxlint-disable vitest/prefer-to-be-falsy -- Reflect.set needs an exact Boolean assertion +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../jexpr/index.js"; +import * as TypeSyntax from "../jexpr/type/index.js"; +import * as Expression from "./Expression.js"; +import * as Program from "./index.js"; +import * as Module from "./Module.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; +import type * as Inputs from "./Inputs.js"; + +type Remainder = Type.Function< + readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + Type.PrimitiveInteger +>; +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [ + infer Element extends Type.Any, + ] + ? Type.List + : Type.Never; +} + +const kernelTypes = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + List: Module.genericType(1), + }, + }), +); +const math = Result.getOrThrow( + Module.define("::core::math", { + values: { rem: Module.value() }, + }), +); +const uuid = Result.getOrThrow( + Module.define("::core::uuid", { + types: { Uuid: Module.type() }, + values: { + Uuid: Module.value< + Type.Function + >(), + }, + }), +); +const modules = Result.getOrThrow( + Module.root({ + kernel: Result.getOrThrow( + Module.define("::kernel", { modules: { type: kernelTypes } }), + ), + core: Result.getOrThrow( + Module.define("::core", { modules: { math, uuid } }), + ), + }), +); +const prelude = { + remainder: modules.modules.core.modules.math.values.rem, + Integer: modules.modules.kernel.modules.type.types.Integer, + List: modules.modules.kernel.modules.type.types.List, +}; +const integer = ( + value: number, +): Expression.Expression => + Expression.fromJExpr(JExpr.integer(value)); + +const dividendValue = 7; +const divisorValue = 3; +const dividend = integer(dividendValue); +const divisor = integer(divisorValue); + +const compile = (expression: Expression.Any): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); + +describe("module_exports", () => { + test("qualified_call", () => { + expect.hasAssertions(); + expect(compile(prelude.remainder(dividend, divisor))).toBe( + '["::core::math::rem",{"#literal":7},{"#literal":3}]', + ); + }); + + test("alias_identity", () => { + expect.hasAssertions(); + const aliases = Result.getOrThrow( + Module.define("::application", { + modules: { arithmetic: math }, + types: { Whole: prelude.Integer, Sequence: prelude.List }, + values: { remainder: prelude.remainder }, + }), + ); + expect(aliases.values.remainder).toBe(math.values.rem); + expect(aliases.modules).toStrictEqual({ arithmetic: math }); + expect(aliases.types.Whole).toBe(kernelTypes.types.Integer); + expect(aliases.types.Sequence).toBe(kernelTypes.types.List); + expect( + TypeSyntax.compile( + Result.getOrThrow( + TypeExpression.toType(aliases.types.Sequence(aliases.types.Whole)), + ), + ), + ).toBe("::kernel::type::List<::kernel::type::Integer>"); + }); + + test("type_and_constructor", () => { + expect.hasAssertions(); + const text = Expression.fromJExpr( + JExpr.literal("6b118660-f68e-4f4f-a3ec-e79639ca16fd"), + ); + expect( + TypeSyntax.compile( + Result.getOrThrow(TypeExpression.toType(uuid.types.Uuid)), + ), + ).toBe("::core::uuid::Uuid"); + expect(compile(uuid.values.Uuid(text))).toBe( + '["::core::uuid::Uuid",{"#literal":"6b118660-f68e-4f4f-a3ec-e79639ca16fd"}]', + ); + }); + + test("nested_type_application", () => { + expect.hasAssertions(); + const nested = prelude.List(prelude.List(prelude.Integer)); + expect( + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(nested))), + ).toBe( + "::kernel::type::List<::kernel::type::List<::kernel::type::Integer>>", + ); + expect(compile(Expression.input("values", nested))).toBe( + '["::kernel::special_form::input","values","::kernel::type::List<::kernel::type::List<::kernel::type::Integer>>"]', + ); + }); + + test("symbol_name", () => { + expect.hasAssertions(); + const operators = Result.getOrThrow( + Module.define("::core::math", { + values: { "%": Module.value() }, + }), + ); + expect(compile(operators.values["%"](dividend, divisor))).toBe( + '["::core::math::`%`",{"#literal":7},{"#literal":3}]', + ); + }); +}); + +describe("module_construction", () => { + test("record_snapshot", () => { + expect.hasAssertions(); + const definitions = { rem: math.values.rem }; + const children = { arithmetic: math }; + const snapshot = Result.getOrThrow( + Module.define("::application", { + values: definitions, + modules: children, + }), + ); + definitions.rem = Expression.fromJExpr( + "replacement", + ); + children.arithmetic = Result.getOrThrow( + Module.define("::other", { + values: { rem: Module.value() }, + }), + ); + expect(snapshot.values.rem).toBe(math.values.rem); + expect(snapshot.modules.arithmetic).toBe(math); + expect( + [ + snapshot, + snapshot.values, + snapshot.types, + snapshot.modules, + modules.modules, + ].every(Object.isFrozen), + ).toBe(true); + expect(Reflect.set(snapshot.values, "other", math.values.rem)).toBe(false); + }); + + test("prototype_names", () => { + expect.hasAssertions(); + const unusual = Result.getOrThrow( + Module.define("::example", { + values: { + ["__proto__"]: Module.value(), + constructor: Module.value(), + }, + }), + ); + const { __proto__: prototypeExport } = unusual.values; + expect(Object.hasOwn(unusual.values, "__proto__")).toBe(true); + expect(compile(prototypeExport)).toBe('"::example::__proto__"'); + expect(compile(unusual.values.constructor)).toBe( + '"::example::constructor"', + ); + }); + + test("invalid_names", () => { + expect.hasAssertions(); + expect(Module.define("core::math", {})).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "RelativeModulePath", name: "core::math" }, + }, + }); + expect(Module.define("", {})).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidModulePath", name: "" } }, + }); + for (const result of [ + Module.define("::core::math", { + values: { "": Module.value() }, + }), + Module.define("::core", { modules: { "": math } }), + Module.root({ "": math }), + Module.define("::core::math", { values: { "": math.values.rem } }), + ]) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidExportName", name: "" } }, + }); + } + }); + + test.each([-1, Number.NaN, Infinity, Number.MAX_SAFE_INTEGER + 1])( + "invalid_type_arity: %s", + (arity) => { + expect.hasAssertions(); + const result = Module.define("::generic", { + types: { Invalid: Module.genericType(arity) }, + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "InvalidTypeArity", arity }, + }, + }); + }, + ); +}); + +describe("type_application", () => { + test("declaration_failure", () => { + expect.hasAssertions(); + // @ts-expect-error The runtime call omits the required type argument. + const invalid = prelude.List(); + const identity: unique symbol = Symbol("Invalid"); + let called = false; + const body = (): Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + > => { + called = true; + return Expression.integer(1); + }; + const alias = Program.Do( + Program.Type("Alias", () => invalid), + body, + ); + const nominal = Program.Do( + Program.Newtype("Nominal", identity, () => invalid), + body, + ); + expect(alias).toStrictEqual(TypeExpression.toType(invalid)); + expect(nominal).toStrictEqual(TypeExpression.toType(invalid)); + expect(called).toBe(false); + }); + + test("runtime_type_arity", () => { + expect.hasAssertions(); + // @ts-expect-error The runtime call omits the required type argument. + const missing = prelude.List(); + // @ts-expect-error The runtime call supplies an extra type argument. + const extra = prelude.List(prelude.Integer, prelude.Integer); + expect(TypeExpression.toType(missing)).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 1, received: 0 }, + }, + }); + expect(TypeExpression.toType(extra)).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 1, received: 2 }, + }, + }); + expect(TypeExpression.toType(prelude.List(missing))).toStrictEqual( + TypeExpression.toType(missing), + ); + expect(Expression.toJExpr(Expression.input("values", extra))).toStrictEqual( + TypeExpression.toType(extra), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.ts new file mode 100644 index 00000000000..cdfa8fd91ca --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.ts @@ -0,0 +1,275 @@ +/** + * Typed declarations bound to absolute HashQL paths. + * + * Modules keep type and value exports separate because a type and its constructor can share a name. Existing exports are aliases: selecting or regrouping one never changes its reference. Declarations supply trusted type information. The HashQL compiler checks the emitted query. + * + * @module + */ +import { Result } from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; +import type * as Inputs from "./Inputs.js"; +import type { ReadonlyRecord } from "effect/Record"; + +const Declare: unique symbol = Symbol("~hashql/ModuleDeclaration"); +const TypeId: unique symbol = Symbol("~hashql/Module"); + +/** A declaration waiting for the module to supply its absolute export path. */ +export interface Declaration { + readonly [Declare]: ( + path: JExpr.Path.Path, + ) => Result.Result; +} + +/** An inspectable export table without fixing its concrete key set. */ +interface Namespace extends ReadonlyRecord {} + +/** A module with its concrete export names erased. */ +export interface Any { + readonly [TypeId]: true; + readonly path: JExpr.Path.Path; + readonly modules: Namespace; + readonly types: Namespace; + readonly values: Namespace; +} + +/** Named declarations and existing exports to assemble into a module. */ +export interface Definition { + readonly modules?: Namespace; + readonly types?: Namespace< + Declaration | TypeExpression.Export + >; + readonly values?: Namespace | Expression.Any>; +} + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent namespace intentionally has no known members +type Empty = Record; + +type Entries = Key extends keyof Shape + ? Shape[Key] + : Empty; +type Exports = { + readonly [Name in keyof Declarations]: Declarations[Name] extends Declaration< + infer Export + > + ? Export + : Declarations[Name]; +}; + +/** An immutable module record preserving each export's concrete type. */ +export interface Module { + readonly [TypeId]: true; + readonly path: JExpr.Path.Path; + readonly modules: Readonly>; + readonly types: Exports>; + readonly values: Exports>; +} + +/** Recognizes a module assembled by this SDK. */ +// oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries +export const isModule = (value: unknown): value is Any => + typeof value === "object" && value !== null && TypeId in value; + +/** Declares a value with trusted semantic type information. */ +export const value = (): Declaration< + Expression.Expression +> => ({ + [Declare]: (path) => + Result.succeed( + Expression.fromJExpr(JExpr.Path.compile(path)), + ), +}); + +/** Declares a named type without expanding it into its structural representation. */ +export const type = (): Declaration< + TypeExpression.TypeExpression +> => ({ + [Declare]: (path) => Result.succeed(TypeExpression.reference(path)), +}); + +/** Declares a named generic type with a type-level operation for its result. */ +export const genericType = ( + arity: Lambda["arity"], +): Declaration> => ({ + [Declare]: (path) => TypeExpression.constructor(path, arity), +}); + +const memberName = ( + name: string, +): Result.Result => + Result.mapError( + JExpr.Ident.decodeResult(name), + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ); + +const bind = ( + parent: JExpr.Path.Path, + entries: Namespace | Export>, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const exports: [string, Export][] = []; + + for (const [name, entry] of Object.entries(entries)) { + const ident = yield* memberName(name); + const path: JExpr.Path.Path = { + rooted: true, + segments: [...parent.segments, ident], + }; + + if (typeof entry === "object" && entry !== null && Declare in entry) { + exports.push([name, yield* entry[Declare](path)]); + } else { + exports.push([name, entry]); + } + } + + return Object.freeze(Object.fromEntries(exports)); + }); + +/** + * Binds new declarations and retains existing exports by identity. + * + * Child modules retain their own paths, including when mounted under an alias. Copying and freezing the records prevents caller mutations from adding or replacing exports afterward. + * + * Invalid paths, export names and generic arities return construction failures. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the module under construction +export const define = ( + name: string, + definition: Shape, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const path = yield* Result.mapError( + JExpr.Path.decodeResult(name), + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidModulePath({ name, cause }), + }), + ); + + if (!path.rooted) { + return yield* Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.RelativeModulePath({ name }), + }), + ); + } + + for (const child of Object.keys(definition.modules ?? {})) { + yield* memberName(child); + } + + const module = Object.freeze({ + [TypeId]: true, + path, + modules: Object.freeze({ ...definition.modules }), + types: yield* bind(path, definition.types ?? {}), + values: yield* bind(path, definition.values ?? {}), + }); + + // SAFETY: binding changes each Declaration into A without changing any key or existing export. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the heterogeneous mapping preserves each declaration result + return module as Module; + }); + +/** Rebinds a module and its exports beneath a locally imported module name. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- internal module rebinding requires both the module and its local path +export const relocate = ( + module: Any, + path: JExpr.Path.Path, +): Result.Result => + Result.gen(function* () { + const modules: [string, Any][] = []; + const values: [string, Expression.Any][] = []; + const types: [string, TypeExpression.Export][] = []; + + for (const [name, child] of Object.entries(module.modules)) { + const ident = yield* JExpr.Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ), + ); + + modules.push([ + name, + yield* relocate(child, { + rooted: path.rooted, + segments: [...path.segments, ident], + }), + ]); + } + + for (const name of Object.keys(module.values)) { + const ident = yield* JExpr.Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ), + ); + + values.push([ + name, + Expression.fromJExpr( + JExpr.Path.compile({ + rooted: path.rooted, + segments: [...path.segments, ident], + }), + ), + ]); + } + + for (const [name, type] of Object.entries(module.types)) { + const ident = yield* JExpr.Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ), + ); + + types.push([ + name, + yield* TypeExpression.relocate(type, { + rooted: path.rooted, + segments: [...path.segments, ident], + }), + ]); + } + + return Object.freeze({ + [TypeId]: true as const, + path, + modules: Object.freeze(Object.fromEntries(modules)), + values: Object.freeze(Object.fromEntries(values)), + types: Object.freeze(Object.fromEntries(types)), + }); + }); + +/** Assembles already-bound modules without rebasing their references. */ +export const root = >( + modules: Modules, +): Result.Result< + { readonly modules: Readonly }, + ProgramError.Construction +> => + Result.gen(function* () { + for (const name of Object.keys(modules)) { + yield* memberName(name); + } + + return Object.freeze({ modules: Object.freeze({ ...modules }) }); + }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts new file mode 100644 index 00000000000..bc14ef12fd6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts @@ -0,0 +1,229 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Program } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + Number: Module.type(), + Boolean: Module.type(), + }, + }), +); + +interface Identity extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +declare const hostNumber: number; +declare const optionalNumber: number | undefined; + +describe("primitive_types", () => { + test("host_numeric_types", () => { + expectTypeOf(Expression.literal(1)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(1.5)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(hostNumber)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(true)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal("name")).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Expression.literal(null)).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("exact_operands", () => { + const integer = Expression.literal(1n); + const number = Expression.literal(1); + expectTypeOf(integer.$.eq(2n)).toEqualTypeOf< + Expression.Expression + >(); + number.$.eq(2); + // @ts-expect-error A host number does not become Integer through its value. + integer.$.eq(2); + // @ts-expect-error Integer does not implicitly widen to Number. + number.$.eq(2n); + // @ts-expect-error Expression handles do not implicitly widen either. + number.$.eq(integer); + number.$.eq(Expression.assume()(integer)); + expectTypeOf(Expression.assume()(1n)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error Boolean operations reject numeric truthiness. + Expression.literal(true).$.and(1); + const id = Expression.fromJExpr< + Type.Opaque<"Id", Type.PrimitiveString>, + Inputs.Empty + >("id"); + // @ts-expect-error Strings do not stand in for nominal values. + id.$.eq("id"); + }); +}); + +describe("primitive_arguments", () => { + test("fixed_and_generic", () => { + const identity = Expression.fromJExpr< + Type.GenericFunction, + Inputs.Empty + >("identity"); + expectTypeOf(identity(7)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(identity(7n)).toEqualTypeOf< + Expression.Expression + >(); + const fixed = Expression.fromJExpr< + Type.Function< + readonly [Type.PrimitiveNumber, Type.PrimitiveString], + Type.PrimitiveBoolean + >, + { readonly receiver: Type.PrimitiveBoolean } + >("fixed"); + const result = fixed(7, "literal"); + expectTypeOf>().toEqualTypeOf<{ + readonly receiver: Type.PrimitiveBoolean; + }>(); + // @ts-expect-error The exact parameter descriptor is Number, not Integer. + fixed(7n, "literal"); + // @ts-expect-error Primitive arguments do not disable arity checking. + fixed(7); + // @ts-expect-error Objects require explicit construction. + identity({ field: true }); + }); + + test("index_key", () => { + const list = Expression.fromJExpr< + Type.List, + Inputs.Empty + >("list"); + expectTypeOf(list.$index(0n)).toEqualTypeOf< + Expression.Expression< + Type.Union, + Inputs.Empty + > + >(); + // @ts-expect-error A list index requires Integer even when a number is integral. + list.$index(0); + const dict = Expression.fromJExpr< + Type.Dict, + Inputs.Empty + >("dict"); + const selected = dict.$index("key"); + expectTypeOf(selected).toEqualTypeOf< + Expression.Expression< + Type.Union, + Inputs.Empty + > + >(); + }); +}); + +describe("primitive_requirements", () => { + test("defaults_and_operations", () => { + const count = Expression.input("count", kernel.types.Integer, 1n); + const enabled = Expression.input("enabled", kernel.types.Boolean); + const result = count.$.eq(2n).$.and(enabled).$.or(false); + expectTypeOf>().toEqualTypeOf<{ + readonly count?: Type.PrimitiveInteger; + readonly enabled: Type.PrimitiveBoolean; + }>(); + const number = Expression.input("number", kernel.types.Number, 1); + expectTypeOf>().toEqualTypeOf<{ + readonly number?: Type.PrimitiveNumber; + }>(); + const uncertain = Expression.input( + "number", + kernel.types.Number, + optionalNumber, + ); + expectTypeOf>().toEqualTypeOf<{ + readonly number: Type.PrimitiveNumber; + }>(); + // @ts-expect-error Defaults retain the declared numeric distinction. + Expression.input("count", kernel.types.Integer, 1); + // @ts-expect-error A bigint default does not widen to Number. + Expression.input("number", kernel.types.Number, 1n); + }); + + test("conditional_branches", () => { + const count = Expression.input("count", kernel.types.Integer); + const expression = Result.getOrThrow( + Program.Do(($) => + $.if( + true, + () => count, + () => 0n, + ), + ), + ); + expectTypeOf(expression).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + > + >(); + const numeric = Result.getOrThrow( + Program.Do(($) => + $.if( + true, + () => 1, + () => 2, + ), + ), + ); + expectTypeOf(numeric).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("query_arguments_and_predicate", () => { + type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; + type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> + >; + const { Do } = Program.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const expression = Result.getOrThrow( + Do(($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ), + ); + expectTypeOf(expression).toEqualTypeOf< + Expression.Expression, Inputs.Empty> + >(); + Do(($) => { + // @ts-expect-error Query arguments use the declaration's exact numeric descriptor. + $.query.entities(1n); + // @ts-expect-error A predicate does not accept numeric truthiness. + $.query.entities(1).filter("vertex", () => 1); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts new file mode 100644 index 00000000000..764cbd9c71f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts @@ -0,0 +1,131 @@ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr, Module, Program } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +const compile = (value: Expression.AnyValue): string => + JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Number: Module.type() }, + }), +); + +describe("primitive_lowering", () => { + test.each([ + [1, '{"#literal":1}'], + [1n, '{"#literal":1}'], + [1.5, '{"#literal":1.5}'], + [9_007_199_254_740_993n, '{"#literal":9007199254740993}'], + ["identifier", '{"#literal":"identifier"}'], + [true, '{"#literal":true}'], + [null, '{"#literal":null}'], + ] as const)("literal: %s", (value, expected) => { + expect.hasAssertions(); + expect(compile(Expression.literal(value))).toBe(expected); + expect(compile(value)).toBe(expected); + }); + + test("function_and_index", () => { + expect.hasAssertions(); + const call = Expression.fromJExpr< + Type.Function< + readonly [Type.PrimitiveNumber, Type.PrimitiveString], + Type.PrimitiveBoolean + >, + Inputs.Empty + >("check"); + expect(compile(call(1, "name"))).toBe( + '["check",{"#literal":1},{"#literal":"name"}]', + ); + const list = Expression.fromJExpr< + Type.List, + Inputs.Empty + >("list"); + expect(compile(list.$index(0n))).toBe( + '["::kernel::special_form::index","list",{"#literal":0}]', + ); + }); + + test("default_and_boolean_operand", () => { + expect.hasAssertions(); + const number = Expression.input("number", kernel.types.Number, 1); + expect(compile(number.$.eq(2).$.and(true))).toBe( + '["::core::bool::and",["::core::cmp::eq",["::kernel::special_form::input","number","::kernel::type::Number",{"#literal":1}],{"#literal":2}],{"#literal":true}]', + ); + }); +}); + +describe("primitive_failures", () => { + test.each([Number.NaN, Infinity, -Infinity])("nonfinite: %s", (value) => { + expect.hasAssertions(); + const number = Expression.input("number", kernel.types.Number); + for (const expression of [ + Expression.literal(value), + number.$.eq(value), + Expression.input("default", kernel.types.Number, value), + ]) { + const failure = Result.getOrThrow( + Result.flip(Expression.toJExpr(expression)), + ); + expect(failure.reason._tag).toBe("InvalidExpression"); + } + }); + + test("both_branches", () => { + expect.hasAssertions(); + const result = Program.Do(($) => + $.if( + true, + () => 1, + () => Number.NaN, + ), + ); + const failure = Result.getOrThrow(Result.flip(result)); + expect(failure.reason._tag).toBe("InvalidExpression"); + }); + + test("assumption_preserves_syntax", () => { + expect.hasAssertions(); + const integer = Expression.literal(7n); + const number = Expression.assume()(integer); + expect(compile(number)).toBe('{"#literal":7}'); + expect(compile(integer)).toBe(compile(number)); + expect(compile(Expression.assume()(7n))).toBe( + compile(number), + ); + }); +}); + +describe("primitive_query", () => { + test("arguments_and_predicate", () => { + expect.hasAssertions(); + type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; + type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> + >; + const { Do } = Program.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, + }); + const expression = Result.getOrThrow( + Do(($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ), + ); + expect(compile(expression)).toBe( + '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",{"#literal":true}]]]', + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts new file mode 100644 index 00000000000..2dee4f8ffa6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts @@ -0,0 +1,204 @@ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Import, Let, Module, Newtype, Program } from "../main.js"; + +import type { Inputs, Type, TypeExpression } from "../main.js"; +import type * as ProgramError from "./ProgramError.js"; +// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments + +const initialValue = 7; +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { + Integer: Module.type(), + String: Module.type(), + }, + }), +); +const { Do, Type: Alias } = Program.withPrelude({ modules: { kernel } }); +const firstIdentity: unique symbol = Symbol("first"); +const secondIdentity: unique symbol = Symbol("second"); + +describe("universe_types", () => { + test("universe_transitions", () => { + const result = Do( + Import((_, { kernel }) => kernel), + Alias("Count", (_, { Integer }) => Integer), + Newtype("Id", firstIdentity, (_, { Count }) => Count), + Let("id", ($, { Id }, { Id: idType }) => { + expectTypeOf(idType).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Opaque + > + >(); + return Id($.integer(initialValue)); + }), + Let("Count", ($, _, types) => { + expectTypeOf(types.Count).toEqualTypeOf(); + return $.literal("value"); + }), + ($, { id, Count }, types) => { + expectTypeOf(Count).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf($.ref.kernel).toEqualTypeOf(); + expectTypeOf(types.Count).toEqualTypeOf(); + // @ts-expect-error Modules are not value bindings. + expectTypeOf(id.kernel); + // @ts-expect-error Types cannot act as value expressions. + Expression.toJExpr(types.Count); + return id; + }, + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression< + Type.Opaque, + Inputs.Empty + >, + ProgramError.Construction + > + >(); + }); + + test("sequential_shadow", () => { + const result = Program.Do( + Let("value", ($) => $.integer(initialValue)), + Let("copy", (_, { value }) => value), + Let("value", ($) => $.literal("new")), + (_, { copy, value }) => { + expectTypeOf(copy).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(value).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error No undeclared bindings. + expectTypeOf(value.missing); + return copy; + }, + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, + ProgramError.Construction + > + >(); + }); +}); + +describe("branch_types", () => { + test("implicit_branch_scope", () => { + const result = Do( + Import((_, { kernel }) => kernel), + Let("outer", ($) => $.integer(initialValue)), + ($, { outer }) => { + const branch = $.if( + $.literal(true), + () => + $.Type("Local", (_, { Integer }) => Integer) + .Let("inner", ($, { outer }, { Local }) => + $.input("value", Local, outer), + ) + .Let("again", (_, { inner }) => inner) + .Expr((_, { again }, { Local }) => { + expectTypeOf(Local).toEqualTypeOf< + typeof kernel.types.Integer + >(); + return again; + }), + () => + $.Expr((_, values, types) => { + // @ts-expect-error The sibling branch cannot see the local value. + expectTypeOf(values.inner); + // @ts-expect-error The sibling branch cannot see the local type. + expectTypeOf(types.Local); + return outer; + }), + ); + $.if( + // @ts-expect-error An integer cannot be a conditional's condition. + outer, + () => outer, + () => outer, + ); + return branch; + }, + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression< + Type.PrimitiveInteger, + { readonly value?: Type.PrimitiveInteger } + >, + ProgramError.Construction + > + >(); + }); + + test("nominal_identity", () => { + Do( + Import((_, { kernel }) => kernel), + Newtype("Id", firstIdentity, (_, { Integer }) => Integer), + Let("first", ($, { Id }) => Id($.integer(1))), + Newtype("Id", secondIdentity, (_, { Integer }) => Integer), + ($, { Id, first }) => { + const second = Id($.integer(2)); + // @ts-expect-error Same query spelling does not make two nominal types equal. + const wrong: typeof first = second; + expectTypeOf(wrong); + // @ts-expect-error A nominal constructor needs its underlying type. + Id(first); + return second; + }, + ); + // oxlint-disable-next-line typescript/no-inferrable-types -- exercises rejection after losing the unique symbol type + const unbranded: symbol = Symbol("widened"); + // @ts-expect-error A widened symbol cannot distinguish nominal declarations. + Newtype("Id", unbranded, () => kernel.types.Integer); + }); +}); + +describe("composition_types", () => { + test("eight_steps", () => { + const result = Program.Do( + Let("first", ($) => $.integer(1)), + Let("second", (_, { first }) => first), + Let("third", (_, { second }) => second), + Let("fourth", (_, { third }) => third), + Let("fifth", (_, { fourth }) => fourth), + Let("sixth", (_, { fifth }) => fifth), + Let("seventh", (_, { sixth }) => sixth), + Let("eighth", (_, { seventh }) => seventh), + (_, { first, eighth }) => { + expectTypeOf(first).toEqualTypeOf(); + return eighth; + }, + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression, + ProgramError.Construction + > + >(); + }); + + test("callback_universes", () => { + Do( + Alias("Integer", ($, types) => { + // @ts-expect-error Type callbacks see types, not modules. + expectTypeOf(types.kernel); + return $.ref.kernel.types.Integer; + }), + Newtype("Id", firstIdentity, (_, { Integer }) => Integer), + (_, { Id }, { Integer }) => { + // @ts-expect-error The type alias is not a value expression. + Id(Integer); + return Id( + Expression.fromJExpr("free"), + ); + }, + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Program.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Program.test.ts new file mode 100644 index 00000000000..9eb6830c8c4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Program.test.ts @@ -0,0 +1,433 @@ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results +// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments +import { Result } from "effect"; +import { assert, describe, expect, test } from "vitest"; + +import { + Expression, + Import, + Let, + Module, + Newtype, + Program, + program, +} from "../main.js"; +import { Expr } from "./ast/Expr.js"; +import { If } from "./ast/If.js"; +import { Import as AstImport } from "./ast/Import.js"; +import { Let as AstLet } from "./ast/Let.js"; +import { Newtype as AstNewtype } from "./ast/Newtype.js"; +import { Type as AstType } from "./ast/Type.js"; + +import type { Inputs, Type } from "../main.js"; +import type { Node } from "./ast/Node.js"; + +const initialValue = 7; +const fractionalValue = 1.5; +const kernel = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Integer: Module.type() }, + }), +); +const { Do, Type: Alias } = Program.withPrelude({ modules: { kernel } }); +const identity: unique symbol = Symbol("Id"); + +describe("construction", () => { + test("sequential_tree", () => { + expect.hasAssertions(); + const calls: string[] = []; + const root = Program.Do( + Let("value", ($) => { + calls.push("value"); + return $.integer(initialValue); + }), + Let("copy", (_, { value }) => { + calls.push("copy"); + return value; + }), + Let("value", ($) => $.literal("new")), + (_, { copy }) => { + calls.push("body"); + return copy; + }, + ); + const tree = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); + expect(tree).toBeInstanceOf(AstLet); + expect(tree.compile()).toStrictEqual([ + "::kernel::special_form::let", + "value", + { "#literal": { _tag: "Integer", value: "7" } }, + [ + "::kernel::special_form::let", + "copy", + "value", + ["::kernel::special_form::let", "value", { "#literal": "new" }, "copy"], + ], + ]); + expect(Program.compile(program(Result.getOrThrow(root)))).toStrictEqual( + Program.compile(program(Result.getOrThrow(root))), + ); + expect(calls).toStrictEqual(["value", "copy", "body"]); + assert.instanceOf(tree, AstLet); + expect(tree.child).toBeInstanceOf(AstLet); + }); + + test("type_and_constructor", () => { + expect.hasAssertions(); + const root = Do( + Import((_, { kernel }) => kernel), + Alias("Count", (_, { Integer }) => Integer), + Newtype("Id", identity, (_, { Count }) => Count), + Let("id", ($, { Id }) => Id($.integer(initialValue))), + (_, { id }) => id, + ); + const imported = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); + assert.instanceOf>(imported, AstImport); + const tree = imported.child; + expect(tree).toBeInstanceOf(AstType); + expect(tree.compile()).toStrictEqual([ + "::kernel::special_form::type", + "Count", + "Integer", + [ + "::kernel::special_form::newtype", + "Id", + "Count", + [ + "::kernel::special_form::let", + "id", + ["Id", { "#literal": { _tag: "Integer", value: "7" } }], + "id", + ], + ], + ]); + assert.instanceOf(tree, AstType); + expect(tree.child).toBeInstanceOf(AstNewtype); + }); +}); + +describe("block_errors", () => { + test("missing_body", () => { + expect.hasAssertions(); + // @ts-expect-error Exercise the runtime boundary without a terminal callback. + const result = Program.Do(); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "InvalidBlock" }, + }, + }); + }); + + test("misplaced_body", () => { + expect.hasAssertions(); + const result = Program.Do( + // @ts-expect-error An expression callback cannot precede the terminal callback. + () => Expression.integer(1), + ($) => $.integer(2), + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "InvalidBlock" }, + }, + }); + }); + + test("invalid_body_result", () => { + expect.hasAssertions(); + // @ts-expect-error Exercise the runtime boundary with a host value. + const result = Program.Do(() => "not an expression"); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { _tag: "InvalidBlock" }, + }, + }); + }); + + test("binding_reason", () => { + expect.hasAssertions(); + const result = Program.Do( + Let("bad name", ($) => $.integer(1)), + ($) => $.integer(2), + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "ProgramConstructionError", + reason: { + _tag: "InvalidBindingName", + name: "bad name", + // oxlint-disable-next-line typescript/no-unsafe-assignment -- Vitest matchers describe expected values + cause: expect.any(Object), + }, + }, + }); + }); +}); + +describe("validation", () => { + test("declaration_short_circuit", () => { + expect.hasAssertions(); + const calls: string[] = []; + const result = Program.Do( + Let("bad name", ($) => $.integer(1)), + Let("later", ($) => { + calls.push("later"); + return $.integer(2); + }), + ($) => { + calls.push("body"); + return $.integer(initialValue); + }, + ); + expect(Result.isFailure(result)).toBe(true); + expect(calls).toStrictEqual([]); + }); + + test("type_names", () => { + expect.hasAssertions(); + expect( + Result.isFailure( + Do( + Alias("bad name", ($) => $.ref.kernel.types.Integer), + ($) => $.integer(1), + ), + ), + ).toBe(true); + expect( + Result.isFailure( + Do( + Newtype("bad name", identity, ($) => $.ref.kernel.types.Integer), + ($) => $.integer(1), + ), + ), + ).toBe(true); + }); + + test.each([Number.NaN, Infinity, -Infinity, fractionalValue])( + "invalid_integer: %s", + (value) => { + expect.hasAssertions(); + expect(Result.isFailure(Program.Do(($) => $.integer(value)))).toBe(true); + }, + ); +}); + +describe("nested_validation", () => { + test.each([true, false])("branch_failure: %s", (condition) => { + expect.hasAssertions(); + const calls: string[] = []; + const result = Program.Do(($) => + $.if( + $.literal(condition), + () => { + calls.push("then"); + return $.Let("bad name", ($) => $.integer(1)) + .Let("skipped", ($) => { + calls.push("skipped"); + return $.integer(2); + }) + .Expr(($) => { + calls.push("body"); + return $.integer(initialValue); + }); + }, + () => { + calls.push("else"); + return $.integer(initialValue); + }, + ), + ); + expect(Result.isFailure(result)).toBe(true); + expect(calls).toStrictEqual(["then", "else"]); + }); + + test("alternate_failure", () => { + expect.hasAssertions(); + const result = Program.Do(($) => + $.if( + $.literal(true), + () => $.integer(1), + () => + $.Let("bad name", ($) => $.integer(2)).Expr( + (_, values) => values["bad name"], + ), + ), + ); + expect(Result.isFailure(result)).toBe(true); + }); + + test("nested_argument_failure", () => { + expect.hasAssertions(); + const result = Program.Do(($) => { + const consume = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("consume"); + return consume( + $.Let("bad name", ($) => $.integer(1)).Expr( + (_, values) => values["bad name"], + ), + ); + }); + expect(Result.isFailure(result)).toBe(true); + }); + + test("input_default_failure", () => { + expect.hasAssertions(); + const result = Do(($) => + $.input("count", $.ref.kernel.types.Integer, $.integer(Number.NaN)), + ); + expect(Result.isFailure(result)).toBe(true); + }); +}); + +describe("branches", () => { + test("implicit_branches", () => { + expect.hasAssertions(); + const calls: string[] = []; + const root = Do( + Import((_, { kernel }) => kernel), + Let("outer", ($) => $.integer(initialValue)), + ($, { outer }) => + $.if( + $.literal(false), + () => { + calls.push("then"); + return $.Type("Local", (_, { Integer }) => Integer) + .Let("inner", ($, { outer }, { Local }) => + $.input("value", Local, outer), + ) + .Expr((_, { inner }) => inner); + }, + () => { + calls.push("else"); + return outer; + }, + ), + ); + const imported = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); + assert.instanceOf>(imported, AstImport); + const tree = imported.child; + expect(tree.compile()).toStrictEqual([ + "::kernel::special_form::let", + "outer", + { "#literal": { _tag: "Integer", value: "7" } }, + [ + "::kernel::special_form::if", + { "#literal": false }, + [ + "::kernel::special_form::type", + "Local", + "Integer", + [ + "::kernel::special_form::let", + "inner", + ["::kernel::special_form::input", "value", "Local", "outer"], + "inner", + ], + ], + "outer", + ], + ]); + tree.compile(); + expect(calls).toStrictEqual(["then", "else"]); + assert.instanceOf(tree, AstLet); + expect(tree.child).toBeInstanceOf(If); + }); + + test("nested_conditionals", () => { + expect.hasAssertions(); + const root = Program.Do(($) => + $.if( + $.literal(true), + () => + $.Let("local", ($) => $.integer(1)).Expr(($, { local }) => + $.if( + $.literal(false), + () => local, + () => $.integer(2), + ), + ), + () => $.literal("other"), + ), + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::if", + { "#literal": true }, + [ + "::kernel::special_form::let", + "local", + { "#literal": { _tag: "Integer", value: "1" } }, + [ + "::kernel::special_form::if", + { "#literal": false }, + "local", + { "#literal": { _tag: "Integer", value: "2" } }, + ], + ], + { "#literal": "other" }, + ]); + }); +}); + +describe("expressions", () => { + test("quoted_binding", () => { + expect.hasAssertions(); + const root = Program.Do( + Let("%", ($) => $.integer(initialValue)), + (_, values) => values["%"], + ); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::let", + "`%`", + { "#literal": { _tag: "Integer", value: "7" } }, + "`%`", + ]); + expect( + Result.isFailure( + Program.Do( + Let("not a name", ($) => $.integer(1)), + ($) => $.integer(2), + ), + ), + ).toBe(true); + }); + + test("expression_leaf", () => { + expect.hasAssertions(); + const root = Program.Do(($) => $.integer(initialValue)); + expect( + Result.getOrThrow(Result.flatMap(root, Expression.toNode)), + ).toBeInstanceOf(Expr); + expect( + Result.getOrThrow(Program.compile(program(Result.getOrThrow(root)))), + ).toBe('{"#literal":7}'); + }); + + test("branch_exception", () => { + expect.hasAssertions(); + const failure = new Error("branch construction"); + expect(() => + Program.Do(($) => + $.if( + $.literal(false), + () => { + throw failure; + }, + () => $.integer(1), + ), + ), + ).toThrow(failure); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts new file mode 100644 index 00000000000..90f706b1fa2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts @@ -0,0 +1,59 @@ +import { Data } from "effect"; + +interface ParserFailure { + // oxlint-disable-next-line typescript/no-restricted-types -- callers can inspect parser details without depending on the parser's error type + readonly cause: unknown; +} + +interface NameFailure extends ParserFailure { + readonly name: string; +} + +export type Reason = Data.TaggedEnum<{ + InvalidBindingName: NameFailure; + InvalidImportName: NameFailure; + InvalidParameterName: NameFailure; + InvalidExportName: NameFailure; + InvalidExpression: ParserFailure; + InvalidModulePath: NameFailure; + RelativeModulePath: { readonly name: string }; + InvalidTypeArity: { readonly arity: number }; + TypeArgumentCount: { readonly expected: number; readonly received: number }; + InvalidBlock: { readonly message: string }; +}>; + +export const Reason: Data.TaggedEnum.Constructor = + Data.taggedEnum(); + +const ConstructionBase: ReturnType< + typeof Data.TaggedError<"ProgramConstructionError"> +> = Data.TaggedError("ProgramConstructionError"); + +/** Failure to construct a program from declarations or expressions. */ +export class Construction extends ConstructionBase<{ + readonly reason: Reason; +}> { + override get message(): string { + return Reason.$match(this.reason, { + InvalidBindingName: ({ name }) => + `Invalid HashQL binding name: ${JSON.stringify(name)}`, + InvalidImportName: ({ name }) => + `Invalid HashQL import name: ${JSON.stringify(name)}`, + InvalidParameterName: ({ name }) => + `Invalid HashQL parameter name: ${JSON.stringify(name)}`, + InvalidExportName: ({ name }) => + `Invalid HashQL export name: ${JSON.stringify(name)}`, + InvalidExpression: () => + "The expression does not have valid J-Expr structure", + InvalidModulePath: ({ name }) => + `Invalid HashQL module path: ${JSON.stringify(name)}`, + RelativeModulePath: ({ name }) => + `A module declaration needs an absolute HashQL path: ${JSON.stringify(name)}`, + InvalidTypeArity: ({ arity }) => + `A type constructor needs a nonnegative safe integer arity, received ${arity}`, + TypeArgumentCount: ({ expected, received }) => + `Expected ${expected} type arguments, received ${received}`, + InvalidBlock: ({ message }) => message, + }); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts new file mode 100644 index 00000000000..ceeec161488 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -0,0 +1,171 @@ +import { Result } from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as AST from "./ast/index.js"; +import * as Expression from "./Expression.js"; +import * as ProgramError from "./ProgramError.js"; + +import type * as Type from "../type/index.js"; +import type { ArgumentInputs, Arguments } from "./ExpressionType.js"; +import type * as Inputs from "./Inputs.js"; +import type * as IR from "./ir/index.js"; + +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +export type Query< + T extends Type.Any, + Vertex extends Type.Any, + Requirements, +> = Expression.Expression & { + readonly filter: < + const Predicate extends Expression.Value, + >( + name: string, + predicate: ( + vertex: Expression.Expression, + ) => Predicate, + ) => Query< + T, + Vertex, + Inputs.Merge> + >; + readonly collect: () => Expression.Expression< + Type.List, + Requirements + >; +}; + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without an entities declaration has no query entry point +type Empty = Record; + +export type Context = S["values"] extends { + readonly entities: Expression.Handle< + Type.Function, + infer Requirements + >; +} + ? Returns extends Graph + ? { + readonly entities: >( + ...args: Values + ) => Query< + Returns, + Vertex, + Inputs.Merge> + >; + } + : Empty + : Empty; + +const chain = ( + expression: Expression.Expression, +): Query => { + const methods = { + filter: >( + name: string, + predicate: ( + vertex: Expression.Expression, + ) => Predicate, + ): Query< + T, + Vertex, + Inputs.Merge> + > => + chain( + Result.gen(function* () { + const graph = yield* Expression.toJExpr(expression); + const ident = yield* JExpr.Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidParameterName({ + name, + cause, + }), + }), + ), + ); + + const parameter = JExpr.Ident.compile(ident); + const body = yield* Expression.toJExpr( + predicate(Expression.fromJExpr(parameter)), + ); + + return new AST.Expr( + JExpr.call( + "::graph::body::filter", + graph, + JExpr.fn({ params: { [parameter]: JExpr.infer }, body }), + ), + ); + }).pipe( + Expression.fromResult< + T, + Inputs.Merge> + >, + ), + ), + collect: (): Expression.Expression, Requirements> => + Expression.fromResult( + Expression.toJExpr(expression).pipe( + Result.map( + (graph) => + new AST.Expr(JExpr.call("::graph::tail::collect", graph)), + ), + ), + ), + }; + + const proxy = new Proxy(expression, { + // oxlint-disable-next-line typescript/no-restricted-types -- a proxy can return expression members or query methods + get(target, property, receiver): unknown { + if (property === "filter") { + return methods.filter; + } + if (property === "collect") { + return methods.collect; + } + return Reflect.get(target, property, receiver); + }, + }); + + // SAFETY: the proxy preserves the expression's identity and supplies both query methods. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy cannot express added members in its return type + return proxy as Query; +}; + +export const make = (scope: S): Context => { + const entities = scope.values["entities"]; + if (entities === undefined) { + // SAFETY: no entities declaration means this context has no query entry point. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the conditional type follows the supplied scope + return {} as Context; + } + + const context = { + entities: ( + ...args: readonly Expression.AnyValue[] + ): Query => + chain( + Result.all({ + callee: Expression.toJExpr(entities), + args: Result.all(args.map(Expression.toJExpr)), + }).pipe( + Result.map( + ({ callee, args }) => new AST.Expr(JExpr.call(callee, ...args)), + ), + Expression.fromResult, + ), + ), + }; + + // oxlint-disable-next-line typescript/no-restricted-types -- the runtime driver erases each declared function signature + const erased: unknown = context; + + // SAFETY: the declaration supplies its argument types and its graph vertex type. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- runtime scope traversal erases the declaration's signature + return erased as Context; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts new file mode 100644 index 00000000000..ba39ac5b66d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts @@ -0,0 +1,145 @@ +import { Result, identity } from "effect"; + +import * as ProgramError from "./ProgramError.js"; + +import type * as JExpr from "../jexpr/index.js"; +import type * as Syntax from "../jexpr/type/index.js"; +import type * as Type from "../type/index.js"; +import type { Types } from "effect"; + +const TypeId: unique symbol = Symbol("~hashql/TypeExpression"); +const ConstructorId: unique symbol = Symbol("~hashql/TypeConstructor"); + +/** Type construction with its semantic annotation erased. */ +export interface Any { + readonly syntax: Result.Result; + readonly [TypeId]: (value: never) => Type.Any; +} + +/** Type syntax or its construction failure, annotated with its semantic type. */ +export interface TypeExpression extends Any { + readonly [TypeId]: Types.Invariant; +} + +type ArgumentTypes = { + readonly [Index in keyof Arguments]: Arguments[Index] extends TypeExpression< + infer T + > + ? T + : never; +}; + +/** A named generic type, specialized by supplying typed type expressions. */ +export interface Constructor { + readonly [ConstructorId]: { + readonly path: JExpr.Path.Path; + readonly arity: number; + }; + ( + ...args: Arguments & { readonly length: Lambda["arity"] } + ): TypeExpression>>; +} + +/** A generic type export with its parameterization erased. */ +export interface AnyConstructor { + readonly [ConstructorId]: { + readonly path: JExpr.Path.Path; + readonly arity: number; + }; +} + +/** A type namespace contains both concrete types and generic type constructors. */ +export type Export = Any | AnyConstructor; + +/** Recognizes concrete type expressions and generic type constructors. */ +// oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries +export const isExport = (value: unknown): value is Export => + ((typeof value === "object" && value !== null) || + typeof value === "function") && + (TypeId in value || ConstructorId in value); + +export const fromResult = ( + syntax: Result.Result, +): TypeExpression => ({ syntax, [TypeId]: identity }); + +export const toType = ( + type: Any, +): Result.Result => type.syntax; + +/** + * Annotates syntax supplied by a trusted type declaration. + * + * The caller must ensure that `syntax` denotes `T`, because the annotation performs no runtime type check. + */ +export const fromType = ( + syntax: Syntax.Type, +): TypeExpression => fromResult(Result.succeed(syntax)); + +/** Binds a trusted semantic declaration to a named type reference. */ +export const reference = ( + path: JExpr.Path.Path, +): TypeExpression => fromType({ _tag: "Reference", path, generics: [] }); + +/** + * Binds a trusted generic declaration to its named type reference. + * + * Runtime checking covers arity alone. The declaration supplies the relationship between the argument types and the resulting semantic type. + */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the reference under construction +export const constructor = ( + path: JExpr.Path.Path, + arity: Lambda["arity"], +): Result.Result, ProgramError.Construction> => { + if (!Number.isSafeInteger(arity) || arity < 0) { + return Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidTypeArity({ arity }), + }), + ); + } + + const instantiate = ( + ...args: Arguments & { readonly length: Lambda["arity"] } + ): TypeExpression>> => { + if (args.length !== arity) { + return fromResult( + Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.TypeArgumentCount({ + expected: arity, + received: args.length, + }), + }), + ), + ); + } + + return fromResult( + Result.map(Result.all(args.map(toType)), (arguments_) => ({ + _tag: "Reference", + path, + generics: arguments_.map((bound) => ({ + _tag: "GenericArgument", + bound, + })), + })), + ); + }; + + return Result.succeed( + Object.assign(instantiate, { [ConstructorId]: { path, arity } }), + ); +}; + +/** Rebinds an imported type name without changing its declared meaning. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a reference at the imported path +export const relocate = ( + type: Export, + path: JExpr.Path.Path, +): Result.Result => { + if (ConstructorId in type) { + return constructor(path, type[ConstructorId].arity); + } + + return Result.map(toType(type), () => reference(path)); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/program/Utilities.ts new file mode 100644 index 00000000000..8825d1d2a91 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Utilities.ts @@ -0,0 +1,270 @@ +// oxlint-disable import/max-dependencies -- block construction composes the declaration steps and expression helpers +// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods +import { Result } from "effect"; + +import * as Expression from "./Expression.js"; +import * as IR from "./ir/index.js"; +import * as ProgramError from "./ProgramError.js"; +import * as Query from "./Query.js"; + +import type * as Type from "../type/index.js"; +import type * as Input from "./Inputs.js"; +import type { Imported, Selection } from "./ir/Import.js"; +import type { Exports } from "./ir/Newtype.js"; +import type * as Scope from "./ir/Scope.js"; +import type { TypeExpression } from "./TypeExpression.js"; +import type { ReadonlyRecord } from "effect/Record"; + +export type Body = ( + utilities: Utilities, + values: S["values"], + types: S["types"], +) => Expression.Expression; + +type Wrap = IR.Node.Transition["wrap"]; + +export type BuildStep = IR.Node.Any | Body; + +/** An unfinished nested block must end with an expression. */ +export class Block { + readonly #state: Result.Result< + { + readonly scope: S; + readonly parents: readonly Wrap[]; + }, + ProgramError.Construction + >; + + constructor( + state: Result.Result< + { readonly scope: S; readonly parents: readonly Wrap[] }, + ProgramError.Construction + >, + ) { + this.#state = state; + } + + #append(step: IR.Node.Any): Block { + return new Block( + Result.flatMap(this.#state, ({ scope, parents }) => { + const input: Scope.Scope = scope; + return Result.map( + // oxlint-disable-next-line eslint/no-use-before-define -- block steps receive utilities that can create further blocks + step.elaborate(makeUtilities(input), input), + ({ scope, wrap }) => ({ scope, parents: [...parents, wrap] }), + ); + }), + ); + } + + #step( + step: IR.Node.Node, + ): Block> { + // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary + const output: unknown = this.#append(step); + + // SAFETY: elaborating this node produces its declared output scope. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the output scope erased by the shared driver + return output as Block>; + } + + Let( + name: Name, + initializer: Body, + ): Block< + Scope.Merge< + S, + { values: ReadonlyRecord> } + >, + Input.Merge + > { + return this.#step(IR.Let(name, initializer)); + } + + Type( + name: Name, + definition: ( + utilities: Utilities, + types: S["types"], + ) => TypeExpression, + ): Block< + Scope.Merge> }>, + Inputs + > { + return this.#step(IR.Type(name, definition)); + } + + Newtype< + const Name extends string, + const Identity extends symbol, + T extends Type.Any, + >( + name: Name, + identity: Identity & (symbol extends Identity ? never : Identity), + definition: ( + utilities: Utilities, + types: S["types"], + ) => TypeExpression, + ): Block>, Inputs> { + return this.#step( + IR.Newtype(name, identity, definition), + ); + } + + Import( + select: (utilities: Utilities, modules: S["modules"]) => M, + ): Block, Inputs>; + Import< + M extends Scope.Scope["modules"][string], + const Imports extends Selection, + >( + select: (utilities: Utilities, modules: S["modules"]) => M, + imports: Imports, + ): Block>, Inputs>; + Import< + M extends Scope.Scope["modules"][string], + const Imports extends Selection, + >( + select: (utilities: Utilities, modules: S["modules"]) => M, + imports?: Imports, + ): + | Block, Inputs> + | Block>, Inputs> { + if (imports === undefined) { + return this.#step(IR.Import(select)); + } + + return this.#step(IR.Import(select, imports)); + } + + Expr( + body: Body, + ): Expression.Expression> { + return Expression.fromResult( + Result.flatMap(this.#state, ({ scope, parents }) => { + // A nested block inherits names, never the wrappers that introduced them outside it. + const expression = body( + // oxlint-disable-next-line eslint/no-use-before-define -- block bodies receive utilities that can create further blocks + makeUtilities(scope), + scope.values, + scope.types, + ); + if (!Expression.isExpression(expression)) { + return Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBlock({ + message: + "An expression callback must return a HashQL expression", + }), + }), + ); + } + return Result.map(Expression.toNode(expression), (node) => { + let root = node; + for (const wrap of parents.toReversed()) { + root = wrap(root); + } + return root; + }); + }), + ); + } + + static build( + scope: Scope.Scope, + steps: readonly BuildStep[], + ): Result.Result { + let block = new Block( + Result.succeed({ scope, parents: [] }), + ); + const body = steps.at(-1); + if (typeof body !== "function" || Expression.isExpression(body)) { + return Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBlock({ + message: "A Do block must end with an expression callback", + }), + }), + ); + } + + for (const step of steps.slice(0, -1)) { + if (typeof step === "function") { + return Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBlock({ + message: "Only the last step may be an expression callback", + }), + }), + ); + } + + if ( + typeof step !== "object" || + // oxlint-disable-next-line typescript/no-unnecessary-condition -- JavaScript callers may pass null despite the overloads + step === null || + !(IR.Node.TypeId in step) + ) { + return Result.fail( + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBlock({ + message: + "A Do block expects declaration steps before its expression callback", + }), + }), + ); + } + block = block.#append(step); + } + + const expression = block.Expr(body); + return Result.map(Expression.toNode(expression), () => expression); + } +} + +const conditional = < + const Condition extends Expression.Value, + const Then extends Expression.AnyValue, + const Else extends Expression.AnyValue, +>( + condition: Condition, + consequent: () => Then, + alternate: () => Else, +): Expression.Expression< + Expression.Conditional, Expression.TypeOf>, + Input.Merge< + Expression.Inputs, + Input.Merge, Expression.Inputs> + > +> => + // oxlint-disable-next-line unicorn/no-thenable -- these are query branches, not a Promise implementation + Expression.ifElse(condition, { then: consequent(), else: alternate() }); + +export interface Utilities extends Block< + S, + Input.Empty +> { + readonly literal: typeof Expression.literal; + readonly integer: typeof Expression.integer; + readonly number: typeof Expression.number; + readonly input: typeof Expression.input; + readonly assume: typeof Expression.assume; + readonly ref: S["modules"]; + readonly query: Query.Context; + readonly if: typeof conditional; +} + +const makeUtilities = (scope: S): Utilities => + Object.assign( + new Block(Result.succeed({ scope, parents: [] })), + { + literal: Expression.literal, + integer: Expression.integer, + number: Expression.number, + input: Expression.input, + assume: Expression.assume, + ref: scope.modules, + query: Query.make(scope), + if: conditional, + }, + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts new file mode 100644 index 00000000000..85bd4449e94 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts @@ -0,0 +1,24 @@ +import { Result } from "effect"; + +import * as Ident from "../../jexpr/Ident.js"; +import * as ProgramError from "../ProgramError.js"; + +export interface Binding { + readonly name: Ident.Ident; + readonly value: Value; +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a named binding +export const make = ( + name: string, + value: Value, +): Result.Result, ProgramError.Construction> => + Ident.decodeResult(name).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidBindingName({ name, cause }), + }), + ), + Result.map((name) => ({ name, value })), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts new file mode 100644 index 00000000000..6cc91458892 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts @@ -0,0 +1,14 @@ +import type * as JExpr from "../../jexpr/index.js"; +import type { Node } from "./Node.js"; + +export class Expr implements Node { + readonly expression: JExpr.Expression; + + constructor(expression: JExpr.Expression) { + this.expression = expression; + } + + compile(): JExpr.Expression { + return this.expression; + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/If.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/If.ts new file mode 100644 index 00000000000..191848bab60 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/If.ts @@ -0,0 +1,23 @@ +import * as JExpr from "../../jexpr/index.js"; + +import type { Node } from "./Node.js"; + +export class If implements Node { + readonly condition: Node; + readonly consequent: Then; + readonly alternate: Else; + + constructor(condition: Node, consequent: Then, alternate: Else) { + this.condition = condition; + this.consequent = consequent; + this.alternate = alternate; + } + + compile(): JExpr.Expression { + return JExpr.if( + this.condition.compile(), + this.consequent.compile(), + this.alternate.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts new file mode 100644 index 00000000000..721a3fc48dc --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts @@ -0,0 +1,24 @@ +import * as JExpr from "../../jexpr/index.js"; +import * as Path from "../../jexpr/Path.js"; + +import type { Node } from "./Node.js"; + +export class Import implements Node { + readonly path: Path.Path; + readonly imports: JExpr.Imports; + readonly child: Child; + + constructor(path: Path.Path, imports: JExpr.Imports, child: Child) { + this.path = path; + this.imports = imports; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.use( + Path.compile(this.path), + this.imports, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts new file mode 100644 index 00000000000..b09017be463 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts @@ -0,0 +1,23 @@ +import * as Ident from "../../jexpr/Ident.js"; +import * as JExpr from "../../jexpr/index.js"; + +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Let implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.let( + Ident.compile(this.binding.name), + this.binding.value.compile(), + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts new file mode 100644 index 00000000000..479b9f58a5a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts @@ -0,0 +1,24 @@ +import * as Ident from "../../jexpr/Ident.js"; +import * as JExpr from "../../jexpr/index.js"; + +import type * as Syntax from "../../jexpr/type/index.js"; +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Newtype implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.newtype( + Ident.compile(this.binding.name), + this.binding.value, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts new file mode 100644 index 00000000000..9cacfcf610b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts @@ -0,0 +1,5 @@ +import type * as JExpr from "../../jexpr/index.js"; + +export interface Node { + readonly compile: () => JExpr.Expression; +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts new file mode 100644 index 00000000000..4a612fe6e7e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts @@ -0,0 +1,24 @@ +import * as Ident from "../../jexpr/Ident.js"; +import * as JExpr from "../../jexpr/index.js"; + +import type * as Syntax from "../../jexpr/type/index.js"; +import type { Binding } from "./Binding.js"; +import type { Node } from "./Node.js"; + +export class Type implements Node { + readonly binding: Binding; + readonly child: Child; + + constructor(binding: Binding, child: Child) { + this.binding = binding; + this.child = child; + } + + compile(): JExpr.Expression { + return JExpr.type( + Ident.compile(this.binding.name), + this.binding.value, + this.child.compile(), + ); + } +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/index.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/index.ts new file mode 100644 index 00000000000..7c4d651947d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/index.ts @@ -0,0 +1,8 @@ +export * from "./Binding.js"; +export * from "./Expr.js"; +export * from "./If.js"; +export * from "./Import.js"; +export * from "./Let.js"; +export * from "./Newtype.js"; +export type * from "./Node.js"; +export * from "./Type.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/index.ts b/libs/@local/hashql/sdk/typescript/src/program/index.ts new file mode 100644 index 00000000000..fa6159b74ed --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/index.ts @@ -0,0 +1,85 @@ +/** + * Builds typed programs with separate module, value and type environments. + * + * Construction evaluates the step callbacks once. The resulting syntax tree owns its children and compiles without an authoring environment. + * + * @module + */ +import { Result } from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; +import * as IR from "./ir/index.js"; +import { Block as Builder } from "./Utilities.js"; + +import type * as Type from "../type/index.js"; +import type { Do as Block } from "./Do.js"; +import type * as ProgramError from "./ProgramError.js"; +import type { BuildStep } from "./Utilities.js"; + +export { assume, ifElse as If } from "./Expression.js"; +export { Import } from "./ir/Import.js"; +export { Let } from "./ir/Let.js"; +export { Newtype } from "./ir/Newtype.js"; +export { Type } from "./ir/Type.js"; +export type { Utilities } from "./Utilities.js"; + +export interface Program { + readonly root: Expression.Expression; +} + +export type Inputs

= P extends { readonly root: infer Root } + ? Expression.Inputs + : never; + +export interface Context { + readonly Do: Block; + readonly Let: typeof IR.Let; + readonly Type: typeof IR.Type; + readonly Newtype: typeof IR.Newtype; + readonly Import: typeof IR.Import; +} + +export const withPrelude = ( + prelude: Prelude, +): Context> => { + // SAFETY: the empty scope contributes no names to any namespace. + const initial = IR.Scope.merge( + IR.Scope.empty, + prelude, + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- merging into empty retains precisely the supplied namespace types + ) as IR.Scope.From; + + const construct = ( + ...steps: readonly BuildStep[] + ): Result.Result => + Builder.build(initial, steps); + + // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary + const erased: unknown = construct; + + // SAFETY: the overloads check every transition before this driver erases its scope parameters. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the per-step scopes checked by the overloads + const Do = erased as Block>; + return Object.freeze({ + Do, + Let: IR.Let, + Type: IR.Type, + Newtype: IR.Newtype, + Import: IR.Import, + }); +}; + +const context: Context = withPrelude({}); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- composes ordered steps and a final expression callback +export const Do: Block = context.Do; + +export const program = ( + root: Expression.Expression, +): Program => Object.freeze({ root }); + +export const compile = ( + self: Program, +): Result.Result => + Result.map(Expression.toJExpr(self.root), JExpr.compile); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts new file mode 100644 index 00000000000..65a99ae058d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts @@ -0,0 +1,153 @@ +// oxlint-disable import/max-dependencies -- an import updates the module, type and value universes together +import { Result } from "effect"; + +import { isReadonlyArray } from "../../internal/array.js"; +import * as JExpr from "../../jexpr/index.js"; +import * as AST from "../ast/index.js"; +import * as Expression from "../Expression.js"; +import * as Module from "../Module.js"; +import * as ProgramError from "../ProgramError.js"; +import * as TypeExpression from "../TypeExpression.js"; +import * as Node from "./Node.js"; +import * as Scope from "./Scope.js"; + +import type * as Inputs from "../Inputs.js"; +import type { Utilities } from "../Utilities.js"; +import type { ReadonlyRecord } from "effect/Record"; + +type Name = Extract< + keyof M["modules"] | keyof M["values"] | keyof M["types"], + string +>; + +export type Selection = + | "*" + | readonly Name[] + | Partial, string>>; + +type Selected = Imports extends "*" + ? Exports + : Imports extends readonly string[] + ? Pick> + : { + readonly [Key in keyof Exports as Key extends keyof Imports + ? Imports[Key] extends "_" + ? Key + : Imports[Key] extends string + ? Imports[Key] + : never + : never]: Exports[Key]; + }; + +export interface Imported { + readonly modules: Selected; + readonly values: Selected; + readonly types: Selected; +} + +/** Imports selected module exports into their respective universes. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the selector and selection construct a declaration step +export function Import( + select: (utilities: Utilities, modules: In["modules"]) => M, +): Node.Node, Inputs.Empty>; +export function Import< + In extends Scope.Scope, + M extends Module.Any, + const Imports extends Selection, +>( + select: (utilities: Utilities, modules: In["modules"]) => M, + imports: Imports, +): Node.Node>, Inputs.Empty>; +export function Import( + select: (utilities: Utilities, modules: In["modules"]) => Module.Any, + // oxlint-disable-next-line hash/prefer-options-object -- the optional argument is the import selection itself + imports: JExpr.Imports = "*", +): Node.Any { + return Node.make((utilities: Utilities, scope: In) => + Result.gen(function* () { + const module = select(utilities, scope.modules); + + const names: [string, string][] = []; + + if (imports === "*") { + for (const name of new Set([ + ...Object.keys(module.modules), + ...Object.keys(module.values), + ...Object.keys(module.types), + ])) { + names.push([name, name]); + } + } else if (isReadonlyArray(imports)) { + for (const name of imports) { + names.push([name, name]); + } + } else { + for (const [name, alias] of Object.entries(imports)) { + if (alias === "_") { + names.push([name, name]); + } else { + names.push([name, alias]); + } + } + } + + const modules: [string, Module.Any][] = []; + const values: [string, Expression.Any][] = []; + const types: [string, TypeExpression.Export][] = []; + const renamed: [string, string][] = []; + const selected: string[] = []; + + for (const [name, alias] of names) { + const ident = yield* JExpr.Ident.decodeResult(alias).pipe( + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidImportName({ + name: alias, + cause, + }), + }), + ), + ); + selected.push(name); + renamed.push([name, JExpr.Ident.compile(ident)]); + + const path = { rooted: false, segments: [ident] as const }; + const child = module.modules[name]; + if (child !== undefined) { + modules.push([alias, yield* Module.relocate(child, path)]); + } + + if (module.values[name] !== undefined) { + values.push([ + alias, + Expression.fromJExpr(JExpr.Ident.compile(ident)), + ]); + } + + const type = module.types[name]; + if (type !== undefined) { + types.push([alias, yield* TypeExpression.relocate(type, path)]); + } + } + + const added = { + modules: Object.fromEntries(modules), + values: Object.fromEntries(values), + types: Object.fromEntries(types), + }; + + let emitted: JExpr.Imports = "*"; + if (isReadonlyArray(imports)) { + emitted = Object.freeze(selected); + } else if (imports !== "*") { + emitted = Object.freeze(Object.fromEntries(renamed)); + } + + return { + scope: Scope.merge(scope, added), + wrap: (child) => new AST.Import(module.path, emitted, child), + }; + }), + ); +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts new file mode 100644 index 00000000000..af705ac5a30 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts @@ -0,0 +1,57 @@ +import { Result } from "effect"; + +import * as Ident from "../../jexpr/Ident.js"; +import * as Binding from "../ast/Binding.js"; +import { Let as AstLet } from "../ast/Let.js"; +import * as Expression from "../Expression.js"; +import * as Node from "./Node.js"; +import * as Scope from "./Scope.js"; + +import type * as Type from "../../type/index.js"; +import type { Utilities } from "../Utilities.js"; +import type { ReadonlyRecord } from "effect/Record"; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a declaration step +export const Let = < + In extends Scope.Scope, + const Name extends string, + T extends Type.Any, + Inputs, +>( + name: Name, + initializer: ( + utilities: Utilities, + values: In["values"], + types: In["types"], + ) => Expression.Expression, +): Node.Node< + In, + Scope.Merge< + In, + { values: ReadonlyRecord> } + >, + Inputs +> => + Node.make((utilities, scope) => + Result.gen(function* () { + const value = yield* Expression.toNode( + initializer(utilities, scope.values, scope.types), + ); + const binding = yield* Binding.make(name, value); + const reference = Expression.fromJExpr( + Ident.compile(binding.name), + ); + + // SAFETY: the sole key is the literal name supplied by the caller. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a computed property widens its key to string + const values = { [name]: reference } as ReadonlyRecord< + Name, + Expression.Expression + >; + + return { + scope: Scope.merge(scope, { values }), + wrap: (child) => new AstLet(binding, child), + }; + }), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts new file mode 100644 index 00000000000..01828fa6622 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts @@ -0,0 +1,79 @@ +// oxlint-disable import/max-dependencies -- nominal declarations introduce both a type and a value constructor +import { Result } from "effect"; + +import * as Ident from "../../jexpr/Ident.js"; +import * as Binding from "../ast/Binding.js"; +import { Newtype as AstNewtype } from "../ast/Newtype.js"; +import * as Expression from "../Expression.js"; +import * as TypeExpression from "../TypeExpression.js"; +import * as Node from "./Node.js"; +import * as Scope from "./Scope.js"; + +import type * as Type from "../../type/index.js"; +import type * as Inputs from "../Inputs.js"; +import type { Utilities } from "../Utilities.js"; +import type { ReadonlyRecord } from "effect/Record"; + +export interface Exports< + Name extends string, + Identity extends symbol, + T extends Type.Any, +> { + readonly types: ReadonlyRecord< + Name, + TypeExpression.TypeExpression> + >; + readonly values: ReadonlyRecord< + Name, + Expression.Expression< + Type.Function>, + Inputs.Empty + > + >; +} + +/** The unique symbol distinguishes declarations even when their query names coincide. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a nominal declaration step +export const Newtype = < + In extends Scope.Scope, + const Name extends string, + const Identity extends symbol, + T extends Type.Any, +>( + name: Name, + _identity: Identity & (symbol extends Identity ? never : Identity), + definition: ( + utilities: Utilities, + types: In["types"], + ) => TypeExpression.TypeExpression, +): Node.Node>, Inputs.Empty> => + Node.make((utilities, scope) => + Result.gen(function* () { + const binding = yield* Binding.make( + name, + yield* TypeExpression.toType(definition(utilities, scope.types)), + ); + const reference = TypeExpression.reference>({ + rooted: false, + segments: [binding.name], + }); + + const constructor = Expression.fromJExpr< + Type.Function>, + Inputs.Empty + >(Ident.compile(binding.name)); + + const entries = { + types: { [name]: reference }, + values: { [name]: constructor }, + }; + + // SAFETY: both universes bind the same name, with the nominal type and its constructor respectively. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- computed properties widen their keys to string + const exports = entries as Exports; + return { + scope: Scope.merge(scope, exports), + wrap: (child) => new AstNewtype(binding, child), + }; + }), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts new file mode 100644 index 00000000000..bc0e0fd74a8 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts @@ -0,0 +1,58 @@ +import { identity } from "effect"; + +import type { Node as AstNode } from "../ast/Node.js"; +import type * as ProgramError from "../ProgramError.js"; +import type { Utilities } from "../Utilities.js"; +import type { Scope } from "./Scope.js"; +import type { Result, Types } from "effect"; + +export interface Variance { + readonly _In: Types.Invariant; + readonly _Out: Types.Invariant; +} + +export const TypeId = "~hashql/program/ir/Node"; + +export interface Transition { + readonly scope: Out; + readonly wrap: (child: AstNode) => AstNode; +} + +/** Runtime construction with erased scope parameters. */ +export interface Any { + readonly elaborate: ( + utilities: Utilities, + scope: Scope, + ) => Result.Result, ProgramError.Construction>; +} + +/** A construction step with independent input and output types for each universe. */ +export interface Node extends Any { + readonly [TypeId]: { + readonly inputs: Types.Contravariant; + readonly modules: Variance; + readonly values: Variance; + readonly types: Variance; + }; +} + +export const make = ( + elaborate: ( + utilities: Utilities, + scope: In, + ) => Result.Result, ProgramError.Construction>, +): Node => { + // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary + const erased: unknown = elaborate; + return { + [TypeId]: { + inputs: identity, + modules: { _In: identity, _Out: identity }, + values: { _In: identity, _Out: identity }, + types: { _In: identity, _Out: identity }, + }, + // SAFETY: block composition supplies exactly the input scope recorded in the node's type. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only the runtime driver erases the successive scopes + elaborate: erased as Any["elaborate"], + }; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts new file mode 100644 index 00000000000..19e50520dc0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts @@ -0,0 +1,65 @@ +import type * as Expression from "../Expression.js"; +import type * as Module from "../Module.js"; +import type * as TypeExpression from "../TypeExpression.js"; +import type { ReadonlyRecord } from "effect/Record"; + +/** An inspectable namespace without fixing its concrete key set. */ +interface Universe extends ReadonlyRecord {} + +export interface Scope { + readonly modules: Universe; + readonly values: Universe; + readonly types: Universe; +} + +export interface Definition { + readonly modules?: Scope["modules"]; + readonly values?: Scope["values"]; + readonly types?: Scope["types"]; +} + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty universe has no names +type EmptyNames = Record; + +type Names = + D extends ReadonlyRecord + ? Exports + : EmptyNames; + +export interface From { + readonly modules: Names; + readonly values: Names; + readonly types: Names; +} + +export type Empty = From; + +export type Extend = Readonly & Added>; + +export interface Merge { + readonly modules: Extend>; + readonly values: Extend>; + readonly types: Extend>; +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- combines separate namespaces rather than transforming the first argument +export const merge = ( + before: Before, + added: Added, +): Merge => { + const combined = Object.freeze({ + modules: Object.freeze({ ...before.modules, ...added.modules }), + values: Object.freeze({ ...before.values, ...added.values }), + types: Object.freeze({ ...before.types, ...added.types }), + }); + + // SAFETY: each spread copies one namespace, with later names replacing earlier ones. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- object spread erases the per-key override mapping + return combined as Merge; +}; + +export const empty: Empty = Object.freeze({ + modules: Object.freeze({}), + values: Object.freeze({}), + types: Object.freeze({}), +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts new file mode 100644 index 00000000000..ff0277f79c0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts @@ -0,0 +1,57 @@ +import { Result } from "effect"; + +import * as Binding from "../ast/Binding.js"; +import { Type as AstType } from "../ast/Type.js"; +import * as TypeExpression from "../TypeExpression.js"; +import * as Node from "./Node.js"; +import * as Scope from "./Scope.js"; + +import type * as Semantic from "../../type/index.js"; +import type { Empty } from "../Inputs.js"; +import type { Utilities } from "../Utilities.js"; +import type { ReadonlyRecord } from "effect/Record"; + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a type declaration step +export const Type = < + In extends Scope.Scope, + const Name extends string, + T extends Semantic.Any, +>( + name: Name, + definition: ( + utilities: Utilities, + types: In["types"], + ) => TypeExpression.TypeExpression, +): Node.Node< + In, + Scope.Merge< + In, + { types: ReadonlyRecord> } + >, + Empty +> => + Node.make((utilities, scope) => + Result.gen(function* () { + const binding = yield* Binding.make( + name, + yield* TypeExpression.toType(definition(utilities, scope.types)), + ); + + const reference = TypeExpression.reference({ + rooted: false, + segments: [binding.name], + }); + + // SAFETY: the sole key is the literal name supplied by the caller. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a computed property widens its key to string + const types = { [name]: reference } as ReadonlyRecord< + Name, + TypeExpression.TypeExpression + >; + + return { + scope: Scope.merge(scope, { types }), + wrap: (child) => new AstType(binding, child), + }; + }), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts new file mode 100644 index 00000000000..a0950340fcf --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts @@ -0,0 +1,6 @@ +export { Import } from "./Import.js"; +export { Let } from "./Let.js"; +export { Newtype } from "./Newtype.js"; +export * as Node from "./Node.js"; +export * as Scope from "./Scope.js"; +export { Type } from "./Type.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts b/libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts new file mode 100644 index 00000000000..812ba4e89c4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts @@ -0,0 +1,187 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import type * as Type from "./index.js"; + +type User = Type.Struct<{ + readonly id: Type.Opaque<"UserId", Type.PrimitiveInteger>; + readonly names: Type.List; +}>; + +interface Recursive extends Type.Struct<{ + readonly children: Type.List; +}> {} + +const preserve = (value: T): T => value; +const inspect = (value: User): User => preserve(value); + +const children = (type: Type.All): readonly Type.All[] => { + switch (type._tag) { + case "Union": + case "Intersection": { + return type.types; + } + case "Opaque": { + return [type.type]; + } + case "Struct": { + return Object.values(type.fields); + } + case "Tuple": { + return type.fields; + } + case "Dict": { + return [type.key, type.value]; + } + case "List": { + return [type.element]; + } + case "Function": { + return [...type.parameters, type.returns]; + } + case "GenericFunction": + case "Integer": + case "Number": + case "String": + case "Boolean": + case "Null": + case "Never": + case "Unknown": { + return []; + } + default: { + expectTypeOf(type).toBeNever(); + return []; + } + } +}; + +describe("composite_types", () => { + test("generic_arguments", () => { + expectTypeOf().toEqualTypeOf<"UserId">(); + expectTypeOf< + User["fields"]["names"]["element"] + >().toEqualTypeOf(); + expectTypeOf< + Type.Dict["value"] + >().toEqualTypeOf(); + }); + + test("erased_constraint", () => { + expectTypeOf(inspect).returns.toEqualTypeOf(); + expectTypeOf().toExtend(); + expectTypeOf().not.toExtend(); + expectTypeOf>().not.toExtend(); + }); + + test("inspectable_forms", () => { + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf< + Type.Union + >().toExtend(); + expectTypeOf< + Type.Intersection< + readonly [User, Type.Struct<{ readonly age: Type.PrimitiveInteger }>] + > + >().toExtend(); + expectTypeOf< + Type.Opaque<"UserId", Type.PrimitiveInteger> + >().toExtend(); + expectTypeOf< + Type.Dict + >().toExtend(); + expectTypeOf>().toExtend(); + }); + + test("recursive_record", () => { + expectTypeOf().toExtend(); + expectTypeOf< + Recursive["fields"]["children"]["element"] + >().toEqualTypeOf(); + }); +}); + +describe("tuple_types", () => { + test("tuple_fixed", () => { + expectTypeOf["fields"]>().toEqualTypeOf< + readonly [] + >(); + expectTypeOf< + Type.Tuple< + readonly [Type.PrimitiveString, Type.PrimitiveInteger] + >["fields"] + >().toEqualTypeOf(); + expectTypeOf["fields"]>().toEqualTypeOf< + [Type.PrimitiveString] + >(); + expectTypeOf>().toExtend(); + expectTypeOf().toExtend(); + }); + + test("tuple_unbounded", () => { + expectTypeOf< + // @ts-expect-error An array has no fixed arity. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A rest element has unbounded arity. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A union containing an array has no fixed arity. + Type.Tuple + >(); + }); + + test("tuple_optional", () => { + expectTypeOf< + // @ts-expect-error Tuple elements must be present. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error A trailing optional element is not fixed-arity. + Type.Tuple + >(); + }); +}); + +describe("type_boundaries", () => { + test("raw_argument_rejection", () => { + expectTypeOf< + // @ts-expect-error Tuple fields are descriptors, not JavaScript value types. + Type.Tuple + >(); + expectTypeOf< + // @ts-expect-error Struct fields must be descriptors. + Type.Struct<{ readonly age: number }> + >(); + expectTypeOf< + // @ts-expect-error Dictionary keys must be descriptors. + Type.Dict + >(); + expectTypeOf< + // @ts-expect-error The discriminant must name a supported type. + Type.List<{ readonly _tag: "Bogus" }> + >(); + }); + + test("primitive_payloads", () => { + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toEqualTypeOf(); + expectTypeOf().toBeNull(); + expectTypeOf().toBeNever(); + expectTypeOf().toBeUnknown(); + }); + + test("opaque_names", () => { + expectTypeOf>().not.toExtend< + Type.Opaque<"PostId", Type.PrimitiveInteger> + >(); + }); + + test("discriminant_narrowing", () => { + expectTypeOf(children).returns.toEqualTypeOf(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/type/index.ts b/libs/@local/hashql/sdk/typescript/src/type/index.ts new file mode 100644 index 00000000000..7489f695c82 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/type/index.ts @@ -0,0 +1,248 @@ +/** + * Compile-time descriptions of HashQL types. + * + * Use {@link Any} to constrain a generic without losing its concrete type arguments. Use {@link All} to inspect a type whose arguments are unknown and narrow it by `_tag`. Each generic type has corresponding `Any` and `All` forms. + * + * @module + */ + +import type { HKT } from "effect"; +import type { ReadonlyRecord } from "effect/Record"; + +/** A HashQL type with its parameters erased. */ +export interface Any { + readonly _tag: All["_tag"]; +} + +/** All supported type forms, with recursively inspectable children. */ +export type All = + | Union.All + | Intersection.All + | Opaque.All + | Struct.All + | Tuple.All + | Dict.All + | List.All + | Function.All + | GenericFunction.All + | Primitive + | Never + | Unknown; + +/** A type constraint with erased parameters. */ +type AnyType = Any; + +/** The union of inspectable type forms. */ +type AllTypes = All; + +/** A value belonging to at least one of the member types. */ +export interface Union { + readonly _tag: "Union"; + readonly types: T; +} + +export declare namespace Union { + /** A union with erased member parameters. */ + export type Any = Union; + /** A union whose members support discriminant narrowing. */ + export interface All extends Union {} +} + +/** A value satisfying every member type. */ +export interface Intersection { + readonly _tag: "Intersection"; + readonly types: T; +} + +export declare namespace Intersection { + /** An intersection with erased member parameters. */ + export type Any = Intersection; + /** An intersection whose members support discriminant narrowing. */ + export interface All extends Intersection {} +} + +/** A nominal type distinguished by its name and underlying type. */ +export interface Opaque { + readonly _tag: "Opaque"; + readonly name: Name; + readonly type: T; +} + +export declare namespace Opaque { + /** An opaque type with an erased name and underlying type parameters. */ + export type Any = Opaque; + /** An opaque type with an inspectable underlying type. */ + export interface All extends Opaque {} +} + +/** Field types with the concrete key set erased. */ +interface StructFields extends ReadonlyRecord {} + +/** A record with a type for each named field. */ +export interface Struct> { + readonly _tag: "Struct"; + readonly fields: T; +} + +export declare namespace Struct { + /** A struct with erased field names and type parameters. */ + export type Any = Struct>; + /** A struct whose field types support discriminant narrowing. */ + export interface All extends Struct> {} +} + +/** + * A fixed-length sequence with a type for each position. + * + * `T` must be a tuple of required elements. Arrays, optional elements and open-ended rest elements fail the constraint. {@link Tuple.Any} and {@link Tuple.All} erase the length for code that handles arbitrary tuple types. + */ +export interface Tuple< + T extends readonly Any[] & { + readonly length: number extends T["length"] ? never : number; + }, +> { + readonly _tag: "Tuple"; + readonly fields: T; +} + +export declare namespace Tuple { + /** A tuple with erased length and element type parameters. */ + export interface Any { + readonly _tag: "Tuple"; + readonly fields: readonly AnyType[]; + } + + /** A tuple whose element types support discriminant narrowing. */ + export interface All { + readonly _tag: "Tuple"; + readonly fields: readonly AllTypes[]; + } +} + +/** A dictionary with a common key type and value type. */ +export interface Dict { + readonly _tag: "Dict"; + readonly key: K; + readonly value: V; +} + +export declare namespace Dict { + /** A dictionary with erased key and value type parameters. */ + export type Any = Dict; + /** A dictionary with inspectable key and value types. */ + export interface All extends Dict {} +} + +/** A variable-length sequence with a common element type. */ +export interface List { + readonly _tag: "List"; + readonly element: T; +} + +export declare namespace List { + /** A list with erased element type parameters. */ + export type Any = List; + /** A list whose element type supports discriminant narrowing. */ + export interface All extends List {} +} + +/** A function with ordered parameters and a result type. */ +export interface Function< + Parameters extends readonly Any[], + Returns extends Any, +> { + readonly _tag: "Function"; + readonly parameters: Parameters; + readonly returns: Returns; +} + +export declare namespace Function { + export interface Any { + readonly _tag: "Function"; + readonly parameters: readonly AnyType[]; + readonly returns: AnyType; + } + export interface All extends Function {} +} + +/** A type-level operation whose input is a tuple of semantic types. */ +export interface TypeLambda extends HKT.TypeLambda { + readonly type: Any; +} + +/** Applies a declaration's type-level operation without a runtime type interpreter. */ +export type Apply< + Lambda extends TypeLambda, + Arguments extends readonly Any[], +> = HKT.Kind; + +/** A generic type declaration with a fixed number of positional type arguments. */ +export interface TypeConstructor extends TypeLambda { + readonly arity: number; +} + +/** Computes a function signature from the types of its call arguments. */ +export interface FunctionSignature extends TypeLambda { + readonly type: Function.Any; +} + +/** A function whose parameter and result types depend on its call arguments. */ +export interface GenericFunction { + readonly _tag: "GenericFunction"; + readonly signature: Signature; +} + +export declare namespace GenericFunction { + export type Any = GenericFunction; + export interface All extends GenericFunction {} +} + +/** An arbitrary-precision integer. */ +export interface PrimitiveInteger { + readonly _tag: "Integer"; + readonly value: bigint; +} + +/** A number, including integer values. */ +export interface PrimitiveNumber { + readonly _tag: "Number"; + readonly value: number; +} + +/** A string value. */ +export interface PrimitiveString { + readonly _tag: "String"; + readonly value: string; +} + +/** A Boolean value. */ +export interface PrimitiveBoolean { + readonly _tag: "Boolean"; + readonly value: boolean; +} + +/** The null value. */ +export interface PrimitiveNull { + readonly _tag: "Null"; + readonly value: null; +} + +export type Primitive = + | PrimitiveInteger + | PrimitiveNumber + | PrimitiveString + | PrimitiveBoolean + | PrimitiveNull; + +/** The bottom type, which has no values. */ +export interface Never { + readonly _tag: "Never"; + readonly value: never; +} + +/** The top type, which includes every value. */ +export interface Unknown { + readonly _tag: "Unknown"; + // oxlint-disable-next-line typescript/no-restricted-types -- represents the HashQL top type + readonly value: unknown; +} diff --git a/libs/@local/hashql/sdk/typescript/tsconfig.json b/libs/@local/hashql/sdk/typescript/tsconfig.json index 8d0f942d866..84e2b2d3868 100644 --- a/libs/@local/hashql/sdk/typescript/tsconfig.json +++ b/libs/@local/hashql/sdk/typescript/tsconfig.json @@ -12,5 +12,5 @@ "isolatedDeclarations": true, "noEmit": true }, - "include": ["src", "oxlint.config.ts", "tsdown.config.ts"] + "include": ["src", "examples", "oxlint.config.ts", "tsdown.config.ts"] } diff --git a/yarn.config.cjs b/yarn.config.cjs index 7917e429f97..c0c5a46a7ab 100644 --- a/yarn.config.cjs +++ b/yarn.config.cjs @@ -263,7 +263,7 @@ function enforceDevDependenciesAreProperlyDeclared({ Yarn }) { /** @type {Record | undefined} */ const scripts = workspace.manifest.scripts; - if (!scripts) { + if (!scripts || ignoredWorkspaces.includes(workspace.ident)) { continue; } diff --git a/yarn.lock b/yarn.lock index 5a9f7ec9eeb..1f1f2e66abf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8799,7 +8799,7 @@ __metadata: languageName: node linkType: hard -"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5, @jridgewell/sourcemap-codec@npm:^1.6.0, @jridgewell/sourcemap-codec@npm:^1.6.0-beta.0": +"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.4.15, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5, @jridgewell/sourcemap-codec@npm:^1.6.0, @jridgewell/sourcemap-codec@npm:^1.6.0-beta.0": version: 1.6.0 resolution: "@jridgewell/sourcemap-codec@npm:1.6.0" checksum: 10c0/b5be700e45a775f218589c3466c4ffea630582b4988657652da464e5ab8a7d18bf928ee4fd2363fb346ede4bea9c6ff0bae05a538358c4565ece6199531b5f72 @@ -10112,6 +10112,9 @@ __metadata: "@local/oxlint": "workspace:*" "@local/tsconfig": "workspace:*" "@tsconfig/bases": "catalog:" + effect: "npm:4.0.3" + esrap: "npm:2.4.0" + oxc-parser: "npm:0.152.0" oxlint: "catalog:" tsdown: "npm:0.23.0" typescript: "catalog:" @@ -11880,6 +11883,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-android-arm-eabi@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-android-arm-eabi@npm:0.152.0" + conditions: os=android & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-android-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-android-arm64@npm:0.127.0" @@ -11887,6 +11897,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-android-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-android-arm64@npm:0.152.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-darwin-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-darwin-arm64@npm:0.127.0" @@ -11894,6 +11911,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-darwin-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-darwin-arm64@npm:0.152.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-darwin-x64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-darwin-x64@npm:0.127.0" @@ -11901,6 +11925,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-darwin-x64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-darwin-x64@npm:0.152.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + "@oxc-parser/binding-freebsd-x64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-freebsd-x64@npm:0.127.0" @@ -11908,6 +11939,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-freebsd-x64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-freebsd-x64@npm:0.152.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.127.0" @@ -11915,6 +11953,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm-gnueabihf@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm-gnueabihf@npm:0.152.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm-musleabihf@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm-musleabihf@npm:0.127.0" @@ -11922,6 +11967,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm-musleabihf@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm-musleabihf@npm:0.152.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm64-gnu@npm:0.127.0" @@ -11929,6 +11981,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm64-gnu@npm:0.152.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-arm64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-arm64-musl@npm:0.127.0" @@ -11936,6 +11995,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-arm64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-arm64-musl@npm:0.152.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-linux-ppc64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-ppc64-gnu@npm:0.127.0" @@ -11943,6 +12009,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-ppc64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-ppc64-gnu@npm:0.152.0" + conditions: os=linux & cpu=ppc64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-riscv64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-riscv64-gnu@npm:0.127.0" @@ -11950,6 +12023,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-riscv64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-riscv64-gnu@npm:0.152.0" + conditions: os=linux & cpu=riscv64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-riscv64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-riscv64-musl@npm:0.127.0" @@ -11957,6 +12037,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-riscv64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-riscv64-musl@npm:0.152.0" + conditions: os=linux & cpu=riscv64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-linux-s390x-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-s390x-gnu@npm:0.127.0" @@ -11964,6 +12051,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-s390x-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-s390x-gnu@npm:0.152.0" + conditions: os=linux & cpu=s390x & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-x64-gnu@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-x64-gnu@npm:0.127.0" @@ -11971,6 +12065,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-x64-gnu@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-x64-gnu@npm:0.152.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + "@oxc-parser/binding-linux-x64-musl@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-linux-x64-musl@npm:0.127.0" @@ -11978,6 +12079,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-linux-x64-musl@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-linux-x64-musl@npm:0.152.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + "@oxc-parser/binding-openharmony-arm64@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-openharmony-arm64@npm:0.127.0" @@ -11985,6 +12093,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-openharmony-arm64@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-openharmony-arm64@npm:0.152.0" + conditions: os=openharmony & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-wasm32-wasi@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-wasm32-wasi@npm:0.127.0" @@ -12003,6 +12118,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-arm64-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-arm64-msvc@npm:0.152.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + "@oxc-parser/binding-win32-ia32-msvc@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-win32-ia32-msvc@npm:0.127.0" @@ -12010,6 +12132,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-ia32-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-ia32-msvc@npm:0.152.0" + conditions: os=win32 & cpu=ia32 + languageName: node + linkType: hard + "@oxc-parser/binding-win32-x64-msvc@npm:0.127.0": version: 0.127.0 resolution: "@oxc-parser/binding-win32-x64-msvc@npm:0.127.0" @@ -12017,6 +12146,13 @@ __metadata: languageName: node linkType: hard +"@oxc-parser/binding-win32-x64-msvc@npm:0.152.0": + version: 0.152.0 + resolution: "@oxc-parser/binding-win32-x64-msvc@npm:0.152.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@oxc-project/types@npm:=0.147.0": version: 0.147.0 resolution: "@oxc-project/types@npm:0.147.0" @@ -12024,7 +12160,7 @@ __metadata: languageName: node linkType: hard -"@oxc-project/types@npm:=0.152.0": +"@oxc-project/types@npm:=0.152.0, @oxc-project/types@npm:^0.152.0": version: 0.152.0 resolution: "@oxc-project/types@npm:0.152.0" checksum: 10c0/5958369f7a2d9fb1f8061ab3aa1abf9b3565cc8895e7e8b3800cd08b6d8077d7ddb4e383ff472811a63302954170a2a52c60fcd7cca38e416910c5f39861d0db @@ -28052,6 +28188,20 @@ __metadata: languageName: node linkType: hard +"esrap@npm:2.4.0": + version: 2.4.0 + resolution: "esrap@npm:2.4.0" + dependencies: + "@jridgewell/sourcemap-codec": "npm:^1.4.15" + peerDependencies: + "@typescript-eslint/types": ^8.2.0 + peerDependenciesMeta: + "@typescript-eslint/types": + optional: true + checksum: 10c0/36718ac21957031a4f99e4ebda8376e0c11b78b6c7c40dc3494f3cdd8df14cbaf13e6c3f1216feb55cac85f6a249f98a61f3e6ef8c6b1cb8555a7f6e7364227f + languageName: node + linkType: hard + "esrecurse@npm:^4.3.0": version: 4.3.0 resolution: "esrecurse@npm:4.3.0" @@ -36702,6 +36852,73 @@ __metadata: languageName: node linkType: hard +"oxc-parser@npm:0.152.0": + version: 0.152.0 + resolution: "oxc-parser@npm:0.152.0" + dependencies: + "@oxc-parser/binding-android-arm-eabi": "npm:0.152.0" + "@oxc-parser/binding-android-arm64": "npm:0.152.0" + "@oxc-parser/binding-darwin-arm64": "npm:0.152.0" + "@oxc-parser/binding-darwin-x64": "npm:0.152.0" + "@oxc-parser/binding-freebsd-x64": "npm:0.152.0" + "@oxc-parser/binding-linux-arm-gnueabihf": "npm:0.152.0" + "@oxc-parser/binding-linux-arm-musleabihf": "npm:0.152.0" + "@oxc-parser/binding-linux-arm64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-arm64-musl": "npm:0.152.0" + "@oxc-parser/binding-linux-ppc64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-riscv64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-riscv64-musl": "npm:0.152.0" + "@oxc-parser/binding-linux-s390x-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-x64-gnu": "npm:0.152.0" + "@oxc-parser/binding-linux-x64-musl": "npm:0.152.0" + "@oxc-parser/binding-openharmony-arm64": "npm:0.152.0" + "@oxc-parser/binding-win32-arm64-msvc": "npm:0.152.0" + "@oxc-parser/binding-win32-ia32-msvc": "npm:0.152.0" + "@oxc-parser/binding-win32-x64-msvc": "npm:0.152.0" + "@oxc-project/types": "npm:^0.152.0" + dependenciesMeta: + "@oxc-parser/binding-android-arm-eabi": + optional: true + "@oxc-parser/binding-android-arm64": + optional: true + "@oxc-parser/binding-darwin-arm64": + optional: true + "@oxc-parser/binding-darwin-x64": + optional: true + "@oxc-parser/binding-freebsd-x64": + optional: true + "@oxc-parser/binding-linux-arm-gnueabihf": + optional: true + "@oxc-parser/binding-linux-arm-musleabihf": + optional: true + "@oxc-parser/binding-linux-arm64-gnu": + optional: true + "@oxc-parser/binding-linux-arm64-musl": + optional: true + "@oxc-parser/binding-linux-ppc64-gnu": + optional: true + "@oxc-parser/binding-linux-riscv64-gnu": + optional: true + "@oxc-parser/binding-linux-riscv64-musl": + optional: true + "@oxc-parser/binding-linux-s390x-gnu": + optional: true + "@oxc-parser/binding-linux-x64-gnu": + optional: true + "@oxc-parser/binding-linux-x64-musl": + optional: true + "@oxc-parser/binding-openharmony-arm64": + optional: true + "@oxc-parser/binding-win32-arm64-msvc": + optional: true + "@oxc-parser/binding-win32-ia32-msvc": + optional: true + "@oxc-parser/binding-win32-x64-msvc": + optional: true + checksum: 10c0/1a4c6e193fa4c18615a8c4da49491df44264e69a14fa2666c3d108c33a6cee2e772f9c71ae94da49a2a99cfdbb6357517daed9d74dae04d55ebb93981b721868 + languageName: node + linkType: hard + "oxc-parser@npm:^0.127.0": version: 0.127.0 resolution: "oxc-parser@npm:0.127.0" From 62ffc8c8cb0b340b3b0cc7f40811d17565c44d18 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:56:25 +0200 Subject: [PATCH 02/22] feat: split HashQL authoring API --- libs/@local/hashql/sdk/typescript/README.md | 19 +- .../hashql/sdk/typescript/docs/authoring.md | 32 +-- .../typescript/examples/api-tour.test-d.ts | 12 +- .../sdk/typescript/examples/filters.test.ts | 10 +- .../hashql/sdk/typescript/examples/filters.ts | 7 +- .../@local/hashql/sdk/typescript/package.json | 4 + .../Program.test-d.ts => do/Do.test-d.ts} | 11 +- .../Program.test.ts => do/Do.test.ts} | 57 +++-- .../@local/hashql/sdk/typescript/src/do/Do.ts | 202 ++++++++++++++++++ .../src/{program => do}/Import.test-d.ts | 17 +- .../src/{program => do}/Import.test.ts | 14 +- .../src/{program/ir => do}/Import.ts | 20 +- .../typescript/src/{program/ir => do}/Let.ts | 14 +- .../src/{program/ir => do}/Newtype.ts | 18 +- .../typescript/src/{program/ir => do}/Node.ts | 11 +- .../typescript/src/{program/ir => do}/Type.ts | 14 +- .../src/{program => do}/Utilities.ts | 42 ++-- .../hashql/sdk/typescript/src/do/index.ts | 67 ++++++ libs/@local/hashql/sdk/typescript/src/main.ts | 5 +- .../hashql/sdk/typescript/src/playground.ts | 174 +++++---------- .../hashql/sdk/typescript/src/program/Do.ts | 201 ----------------- .../typescript/src/program/Fluent.test-d.ts | 7 +- .../sdk/typescript/src/program/Fluent.test.ts | 7 +- .../typescript/src/program/Inputs.test-d.ts | 21 +- .../sdk/typescript/src/program/Inputs.test.ts | 11 +- .../sdk/typescript/src/program/Module.test.ts | 10 +- .../src/program/Primitive.test-d.ts | 9 +- .../typescript/src/program/Primitive.test.ts | 7 +- .../sdk/typescript/src/program/Query.ts | 6 +- .../typescript/src/program/{ir => }/Scope.ts | 6 +- .../sdk/typescript/src/program/index.ts | 58 +---- .../sdk/typescript/src/program/ir/index.ts | 6 - .../hashql/sdk/typescript/tsdown.config.ts | 2 +- 33 files changed, 522 insertions(+), 579 deletions(-) rename libs/@local/hashql/sdk/typescript/src/{program/Program.test-d.ts => do/Do.test-d.ts} (95%) rename libs/@local/hashql/sdk/typescript/src/{program/Program.test.ts => do/Do.test.ts} (90%) create mode 100644 libs/@local/hashql/sdk/typescript/src/do/Do.ts rename libs/@local/hashql/sdk/typescript/src/{program => do}/Import.test-d.ts (87%) rename libs/@local/hashql/sdk/typescript/src/{program => do}/Import.test.ts (96%) rename libs/@local/hashql/sdk/typescript/src/{program/ir => do}/Import.ts (89%) rename libs/@local/hashql/sdk/typescript/src/{program/ir => do}/Let.ts (80%) rename libs/@local/hashql/sdk/typescript/src/{program/ir => do}/Newtype.ts (82%) rename libs/@local/hashql/sdk/typescript/src/{program/ir => do}/Node.ts (83%) rename libs/@local/hashql/sdk/typescript/src/{program/ir => do}/Type.ts (78%) rename libs/@local/hashql/sdk/typescript/src/{program => do}/Utilities.ts (87%) create mode 100644 libs/@local/hashql/sdk/typescript/src/do/index.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/program/Do.ts rename libs/@local/hashql/sdk/typescript/src/program/{ir => }/Scope.ts (93%) delete mode 100644 libs/@local/hashql/sdk/typescript/src/program/ir/index.ts diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 81397e461b5..46cbc16d3f7 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -2,11 +2,13 @@ The SDK constructs HashQL query syntax. TypeScript checks the authoring API. The HashQL compiler resolves names and checks the emitted program. `JExpr` provides the low-level expression builders and serializer. Construction does not execute the query. +Import shared types, expressions and `Program` from `@local/hashql`, and Do authoring calls from `@local/hashql/do`. The shared `program` constructor wraps the resulting expression. + Start with the [authoring guide](docs/authoring.md). It provides a complete construction example, focused API examples and rules for developers and coding agents. -## Programs +## Do authoring -A program has separate module, value and type environments. A value and a type can have the same name. Each step receives `$` plus the environments it needs: +Do authoring uses separate module, value and type environments. A value and a type can have the same name. Each step receives `$` plus the environments it needs: | Step | Callback arguments | Introduces | | ---------------- | ------------------ | ------------------------------------------------ | @@ -21,6 +23,7 @@ A program has separate module, value and type environments. A value and a type c ```ts import { Result } from "effect"; import { Module, Program, program } from "@local/hashql"; +import { withPrelude } from "@local/hashql/do"; import type { Type as Semantic } from "@local/hashql"; const userId: unique symbol = Symbol("UserId"); @@ -29,7 +32,7 @@ const query = Result.gen(function* () { types: { Integer: Module.type() }, }); - const { Do, Let, Type, Newtype, Import } = Program.withPrelude({ + const { Do, Let, Type, Newtype, Import } = withPrelude({ modules: { kernel }, }); @@ -57,7 +60,7 @@ const query = Result.gen(function* () { `Import` emits a HashQL `use` expression and introduces local references. `Import((_, { math }) => math)` imports every exported name. A second argument selects names, such as `["cmp"]`, or renames them, such as `{ cmp: "compare" }`. An alias of `"_"` retains the original name. Each selected name enters every environment in which the module exports it, including a same-named type and constructor. Imported child modules expose references beneath their local module name. -`Program.Do` starts with empty environments. `Program.withPrelude` accepts optional `modules`, `values` and `types` records without emitting imports. The positional `Do` overloads support up to eight declaration steps and a final expression. Chained nested blocks have no fixed step count. +`Do` from `@local/hashql/do` starts with empty environments. `withPrelude` from the same subpath accepts optional `modules`, `values` and `types` records without emitting imports. The positional `Do` overloads support up to eight declaration steps and a final expression. Chained nested blocks have no fixed step count. ## Conditional blocks @@ -65,9 +68,10 @@ Each branch of `$.if` returns an expression. A branch needing declarations uses ```ts import { Result } from "effect"; -import { Let, Program, program } from "@local/hashql"; +import { Program, program } from "@local/hashql"; +import { Do, Let } from "@local/hashql/do"; -const conditional = Program.Do( +const conditional = Do( Let("outer", ($) => $.integer(7)), ($, { outer }) => $.if( @@ -111,6 +115,7 @@ Value operations live under `expression.$`: `eq`, `ne`, Boolean `and`, `or`, `is ```ts import { Result } from "effect"; import { Expression, Module, Program } from "@local/hashql"; +import { Do } from "@local/hashql/do"; import type { Type } from "@local/hashql"; const query = Result.gen(function* () { @@ -125,7 +130,7 @@ const query = Result.gen(function* () { const nonzero = count.$.ne(0n); - const expression = yield* Program.Do(($) => + const expression = yield* Do(($) => nonzero.$.and($.input("enabled", kernel.types.Boolean, true)), ); diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md index a744bfb2e06..e88cd9a3a26 100644 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -2,6 +2,8 @@ The `@local/hashql` package builds HashQL programs from TypeScript. You describe the HashQL modules a program uses and compose expressions from typed handles. The SDK then serializes the result to J-Expr, the JSON syntax the HashQL compiler reads. The SDK neither runs nor compiles a query. It gives you typed composition and a syntax tree, and the HashQL compiler decides whether that tree is a valid program. +Shared types, expressions and `Program` come from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`. The resulting expressions use the same shared representation. + This guide starts with one complete program and then works through each part of the API with focused examples. The [authoring rules](#authoring-rules) at the end condense it into rules that a person or a coding agent can follow while writing a program. ## What checks a program @@ -22,7 +24,8 @@ This program declares the two modules it uses, binds an optional `page` input an ```ts import { Result } from "effect"; -import { Import, Let, Module, Program, program } from "@local/hashql"; +import { Module, Program, program } from "@local/hashql"; +import { Import, Let, withPrelude } from "@local/hashql/do"; import type { Type } from "@local/hashql"; type IntegerOperation = Type.Function< @@ -40,7 +43,7 @@ const built = Result.gen(function* () { }); // Make the modules visible to the program's steps. - const { Do } = Program.withPrelude({ modules: { kernel, math } }); + const { Do } = withPrelude({ modules: { kernel, math } }); const root = yield* Do( Import((_, { math }) => math, ["add"]), @@ -66,7 +69,7 @@ Result.match(compiled, { The program has five parts. 1. `Module.define` binds TypeScript descriptions of HashQL types to absolute paths. It returns a `Result` because a path or export name can be invalid. The program yields that `Result` inside `Result.gen`. -2. `Program.withPrelude` makes the modules available to every step without emitting any HashQL import. +2. `withPrelude` makes the modules available to every step without emitting any HashQL import. 3. `Do` takes declaration steps followed by one final callback. `Import` emits a HashQL `use` and brings `add` into the value environment. `Let` binds `page` to an input. The final callback returns the program's result expression. 4. `program(root)` wraps the result expression, and `Program.compile` serializes it to a J-Expr string. Both `Do` and `Program.compile` return a `Result`. 5. The caller handles both outcomes. A failure is a `ProgramError.Construction` with a tagged `reason`. @@ -100,14 +103,15 @@ The remaining examples are shorter. Each assumes the imports and declarations be ```ts import { Result } from "effect"; +import { Expression, Module, Program } from "@local/hashql"; import { - Expression, + Do as EmptyDo, Import, Let, - Module, Newtype, - Program, -} from "@local/hashql"; + Type as Alias, + withPrelude, +} from "@local/hashql/do"; import type { Inputs, Type } from "@local/hashql"; const kernel = Result.getOrThrow( @@ -137,7 +141,7 @@ const math = Result.getOrThrow( }), ); -const { Do } = Program.withPrelude({ modules: { kernel, math } }); +const { Do } = withPrelude({ modules: { kernel, math } }); ``` These declarations never change and construct successfully, so the examples unwrap them with `Result.getOrThrow`. It throws if a declaration fails. In application code, prefer yielding each `Result` inside `Result.gen` as the first program does. @@ -166,7 +170,7 @@ Each step's callback receives `$` first, followed by the environments that step - `$.query` starts a graph query, when the value environment holds an `entities` function. - `$.Let`, `$.Type`, `$.Newtype`, `$.Import` and `$.Expr` start a nested block. -`Program.Do` starts with empty environments. `Program.withPrelude` accepts optional `modules`, `values` and `types` records and returns `Do` together with `Let`, `Type`, `Newtype` and `Import`. The prelude only seeds the environments. It emits no HashQL. The package also exports `Let`, `Newtype` and `Import` directly. `Type` is available as `Program.Type` or from `withPrelude`, because the top-level `Type` export names the namespace of type descriptors. +`Do` from `@local/hashql/do` starts with empty environments. The imports above alias it as `EmptyDo` to distinguish it from the prelude-bound `Do`. `withPrelude` accepts optional `modules`, `values` and `types` records and returns `Do` together with `Let`, `Type`, `Newtype` and `Import`. The prelude only seeds the environments. It emits no HashQL. The same subpath exports all four declaration builders directly. The imports above alias the declaration builder `Type` as `Alias`, because `Type` from `@local/hashql` names the namespace of type descriptors. ## Declaring modules @@ -280,7 +284,7 @@ const shadowedId = Do( Give each `Newtype` its own `unique symbol`, including declarations that share a HashQL name. A symbol widened to plain `symbol` can't tell declarations apart, and TypeScript rejects it. -`Type` declares an alias instead. An alias keeps the underlying type, so `Type("Count", (_, { Integer }) => Integer)` produces a type that TypeScript treats as Integer. `Type` and `Newtype` currently declare concrete types only, without type parameters. +`Type` declares an alias instead. An alias keeps the underlying type, so `Alias("Count", (_, { Integer }) => Integer)` produces a type that TypeScript treats as Integer. `Type` and `Newtype` currently declare concrete types only, without type parameters. ## Imports and renaming @@ -307,7 +311,7 @@ Importing a child module adds it to the module environment under its local name. // Uses: math. const core = Result.getOrThrow(Module.define("::core", { modules: { math } })); -const viaChild = Program.withPrelude({ modules: { core } }).Do( +const viaChild = withPrelude({ modules: { core } }).Do( Import((_, { core }) => core, { math: "m" }), ($) => $.ref.m.values.add(7n, 2n), ); @@ -337,7 +341,7 @@ const profiles = Result.getOrThrow( }), ); -const label = Program.withPrelude({ modules: { profiles } }).Do( +const label = withPrelude({ modules: { profiles } }).Do( Import((_, { profiles }) => profiles, ["Profile"]), Let("profile", ($, _values, { Profile }) => $.input("profile", Profile)), (_, { profile }) => profile.labels.$index(profile.name), @@ -434,7 +438,7 @@ const temporal = Result.getOrThrow( }), ); -const graph = Program.withPrelude({ +const graph = withPrelude({ modules: { kernel }, values: { entities: head.values.entities, @@ -675,7 +679,7 @@ Expected construction failures arrive as a `Result` holding a `ProgramError.Cons ```ts // Uses: the shared imports. -const invalid = Program.Do( +const invalid = EmptyDo( Let("not a name", ($) => $.integer(1)), ($) => $.integer(2), ); diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts index 885f155d129..443c308611b 100644 --- a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -14,13 +14,13 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; import { - Expression, + Type as Alias, Import, Let, - Module, Newtype, - Program, -} from "../src/main.js"; + withPrelude, +} from "../src/do/index.js"; +import { Expression, Module, Program } from "../src/main.js"; import type { Inputs, @@ -100,7 +100,7 @@ const temporal = Result.getOrThrow( ); // A prelude seeds the environments without emitting imports. `$.query` offers `entities` because the value environment holds a graph-returning `entities`. -const { Do } = Program.withPrelude({ +const { Do } = withPrelude({ modules: { kernel, profile }, values: { entities: head.values.entities, @@ -198,7 +198,7 @@ describe("declarations", () => { // Select names, and rename some of them. An alias of `"_"` keeps the original name. Import((_, { kernel }) => kernel, { Integer: "Int", String: "_" }), // A type alias preserves the underlying semantic type. - Program.Type("Count", (_, { Int }) => Int), + Alias("Count", (_, { Int }) => Int), ($, _values, { Count, String }) => { expectTypeOf(Count).toEqualTypeOf(); expectTypeOf(String).toEqualTypeOf(); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts index ea49df9e518..9ede1ec9c86 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts @@ -23,16 +23,16 @@ const normalize = ( if (value[0] === "::kernel::special_form::use") { const [, path, selection, body] = value; const imported = new Map(imports); - if (selection["#tuple"] !== undefined) { - for (const name of selection["#tuple"]) { - imported.set(name, `${path}::${name}`); - } - } else { + if (selection["#tuple"] === undefined) { for (const [name, alias] of Object.entries(selection["#struct"])) { if (typeof alias === "string") { imported.set(alias === "_" ? name : alias, `${path}::${name}`); } } + } else { + for (const name of selection["#tuple"]) { + imported.set(name, `${path}::${name}`); + } } return normalize(body, imported); } diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts index f1237566b84..8fa264033f7 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.ts @@ -9,7 +9,8 @@ */ import { Result } from "effect"; -import { Import, Module, Program, program } from "../src/main.js"; +import { Do as EmptyDo, Import, withPrelude } from "../src/do/index.js"; +import { Module, Program, program } from "../src/main.js"; import type { Expression, Type } from "../src/main.js"; import type * as ProgramError from "../src/program/ProgramError.js"; @@ -121,7 +122,7 @@ const temporary = Result.getOrThrow( }), ); -const { Let, Do } = Program.withPrelude({ +const { Let, Do } = withPrelude({ values: { createUuid: uuid.values.Uuid, createEntityUuid: entity.values.EntityUuid, @@ -160,7 +161,7 @@ const allEntities = example( "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc", before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`, }, - Program.Do( + EmptyDo( Import(() => head, ["entities"]), Import(() => temporary, { decision_time_now: "now" }), ($, { now }) => $.query.entities(now()).collect(), diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json index d0b8c4483d6..b33b53909a1 100644 --- a/libs/@local/hashql/sdk/typescript/package.json +++ b/libs/@local/hashql/sdk/typescript/package.json @@ -12,6 +12,10 @@ ".": { "types": "./dist/main.d.ts", "default": "./dist/main.js" + }, + "./do": { + "types": "./dist/do/index.d.ts", + "default": "./dist/do/index.js" } }, "scripts": { diff --git a/libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts similarity index 95% rename from libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts index 2dee4f8ffa6..0df3136dbe0 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Program.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts @@ -1,10 +1,11 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Expression, Import, Let, Module, Newtype, Program } from "../main.js"; +import { Expression, Module } from "../main.js"; +import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; import type { Inputs, Type, TypeExpression } from "../main.js"; -import type * as ProgramError from "./ProgramError.js"; +import type * as ProgramError from "../program/ProgramError.js"; // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments const initialValue = 7; @@ -16,7 +17,7 @@ const kernel = Result.getOrThrow( }, }), ); -const { Do, Type: Alias } = Program.withPrelude({ modules: { kernel } }); +const { Do, Type: Alias } = withPrelude({ modules: { kernel } }); const firstIdentity: unique symbol = Symbol("first"); const secondIdentity: unique symbol = Symbol("second"); @@ -63,7 +64,7 @@ describe("universe_types", () => { }); test("sequential_shadow", () => { - const result = Program.Do( + const result = EmptyDo( Let("value", ($) => $.integer(initialValue)), Let("copy", (_, { value }) => value), Let("value", ($) => $.literal("new")), @@ -162,7 +163,7 @@ describe("branch_types", () => { describe("composition_types", () => { test("eight_steps", () => { - const result = Program.Do( + const result = EmptyDo( Let("first", ($) => $.integer(1)), Let("second", (_, { first }) => first), Let("third", (_, { second }) => second), diff --git a/libs/@local/hashql/sdk/typescript/src/program/Program.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts similarity index 90% rename from libs/@local/hashql/sdk/typescript/src/program/Program.test.ts rename to libs/@local/hashql/sdk/typescript/src/do/Do.test.ts index 9eb6830c8c4..84b2e9c6248 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Program.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts @@ -4,24 +4,17 @@ import { Result } from "effect"; import { assert, describe, expect, test } from "vitest"; -import { - Expression, - Import, - Let, - Module, - Newtype, - Program, - program, -} from "../main.js"; -import { Expr } from "./ast/Expr.js"; -import { If } from "./ast/If.js"; -import { Import as AstImport } from "./ast/Import.js"; -import { Let as AstLet } from "./ast/Let.js"; -import { Newtype as AstNewtype } from "./ast/Newtype.js"; -import { Type as AstType } from "./ast/Type.js"; +import { Expression, Module, Program, program } from "../main.js"; +import { Expr } from "../program/ast/Expr.js"; +import { If } from "../program/ast/If.js"; +import { Import as AstImport } from "../program/ast/Import.js"; +import { Let as AstLet } from "../program/ast/Let.js"; +import { Newtype as AstNewtype } from "../program/ast/Newtype.js"; +import { Type as AstType } from "../program/ast/Type.js"; +import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; import type { Inputs, Type } from "../main.js"; -import type { Node } from "./ast/Node.js"; +import type { Node } from "../program/ast/Node.js"; const initialValue = 7; const fractionalValue = 1.5; @@ -30,14 +23,14 @@ const kernel = Result.getOrThrow( types: { Integer: Module.type() }, }), ); -const { Do, Type: Alias } = Program.withPrelude({ modules: { kernel } }); +const { Do, Type: Alias } = withPrelude({ modules: { kernel } }); const identity: unique symbol = Symbol("Id"); describe("construction", () => { test("sequential_tree", () => { expect.hasAssertions(); const calls: string[] = []; - const root = Program.Do( + const root = EmptyDo( Let("value", ($) => { calls.push("value"); return $.integer(initialValue); @@ -111,7 +104,7 @@ describe("block_errors", () => { test("missing_body", () => { expect.hasAssertions(); // @ts-expect-error Exercise the runtime boundary without a terminal callback. - const result = Program.Do(); + const result = EmptyDo(); expect(result).toMatchObject({ _tag: "Failure", failure: { @@ -123,7 +116,7 @@ describe("block_errors", () => { test("misplaced_body", () => { expect.hasAssertions(); - const result = Program.Do( + const result = EmptyDo( // @ts-expect-error An expression callback cannot precede the terminal callback. () => Expression.integer(1), ($) => $.integer(2), @@ -140,7 +133,7 @@ describe("block_errors", () => { test("invalid_body_result", () => { expect.hasAssertions(); // @ts-expect-error Exercise the runtime boundary with a host value. - const result = Program.Do(() => "not an expression"); + const result = EmptyDo(() => "not an expression"); expect(result).toMatchObject({ _tag: "Failure", failure: { @@ -152,7 +145,7 @@ describe("block_errors", () => { test("binding_reason", () => { expect.hasAssertions(); - const result = Program.Do( + const result = EmptyDo( Let("bad name", ($) => $.integer(1)), ($) => $.integer(2), ); @@ -175,7 +168,7 @@ describe("validation", () => { test("declaration_short_circuit", () => { expect.hasAssertions(); const calls: string[] = []; - const result = Program.Do( + const result = EmptyDo( Let("bad name", ($) => $.integer(1)), Let("later", ($) => { calls.push("later"); @@ -214,7 +207,7 @@ describe("validation", () => { "invalid_integer: %s", (value) => { expect.hasAssertions(); - expect(Result.isFailure(Program.Do(($) => $.integer(value)))).toBe(true); + expect(Result.isFailure(EmptyDo(($) => $.integer(value)))).toBe(true); }, ); }); @@ -223,7 +216,7 @@ describe("nested_validation", () => { test.each([true, false])("branch_failure: %s", (condition) => { expect.hasAssertions(); const calls: string[] = []; - const result = Program.Do(($) => + const result = EmptyDo(($) => $.if( $.literal(condition), () => { @@ -250,7 +243,7 @@ describe("nested_validation", () => { test("alternate_failure", () => { expect.hasAssertions(); - const result = Program.Do(($) => + const result = EmptyDo(($) => $.if( $.literal(true), () => $.integer(1), @@ -265,7 +258,7 @@ describe("nested_validation", () => { test("nested_argument_failure", () => { expect.hasAssertions(); - const result = Program.Do(($) => { + const result = EmptyDo(($) => { const consume = Expression.fromJExpr< Type.Function, Inputs.Empty @@ -344,7 +337,7 @@ describe("branches", () => { test("nested_conditionals", () => { expect.hasAssertions(); - const root = Program.Do(($) => + const root = EmptyDo(($) => $.if( $.literal(true), () => @@ -382,7 +375,7 @@ describe("branches", () => { describe("expressions", () => { test("quoted_binding", () => { expect.hasAssertions(); - const root = Program.Do( + const root = EmptyDo( Let("%", ($) => $.integer(initialValue)), (_, values) => values["%"], ); @@ -396,7 +389,7 @@ describe("expressions", () => { ]); expect( Result.isFailure( - Program.Do( + EmptyDo( Let("not a name", ($) => $.integer(1)), ($) => $.integer(2), ), @@ -406,7 +399,7 @@ describe("expressions", () => { test("expression_leaf", () => { expect.hasAssertions(); - const root = Program.Do(($) => $.integer(initialValue)); + const root = EmptyDo(($) => $.integer(initialValue)); expect( Result.getOrThrow(Result.flatMap(root, Expression.toNode)), ).toBeInstanceOf(Expr); @@ -419,7 +412,7 @@ describe("expressions", () => { expect.hasAssertions(); const failure = new Error("branch construction"); expect(() => - Program.Do(($) => + EmptyDo(($) => $.if( $.literal(false), () => { diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.ts new file mode 100644 index 00000000000..a7e6a7dedc0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.ts @@ -0,0 +1,202 @@ +import type * as Expression from "../program/Expression.js"; +import type * as Input from "../program/Inputs.js"; +import type * as ProgramError from "../program/ProgramError.js"; +import type * as Scope from "../program/Scope.js"; +import type * as Type from "../type/index.js"; +import type * as Node from "./Node.js"; +import type { Body } from "./Utilities.js"; +import type { Result } from "effect"; + +/** Contextual overloads propagate the output universes and accumulate every declaration's inputs. */ +export interface Do { + ( + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + ( + step1: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + S4 extends Scope.Scope, + I4, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + step4: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + S4 extends Scope.Scope, + I4, + S5 extends Scope.Scope, + I5, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + step4: Node.Node, + step5: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression>, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + S4 extends Scope.Scope, + I4, + S5 extends Scope.Scope, + I5, + S6 extends Scope.Scope, + I6, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + step4: Node.Node, + step5: Node.Node, + step6: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + S4 extends Scope.Scope, + I4, + S5 extends Scope.Scope, + I5, + S6 extends Scope.Scope, + I6, + S7 extends Scope.Scope, + I7, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + step4: Node.Node, + step5: Node.Node, + step6: Node.Node, + step7: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; + < + S1 extends Scope.Scope, + I1, + S2 extends Scope.Scope, + I2, + S3 extends Scope.Scope, + I3, + S4 extends Scope.Scope, + I4, + S5 extends Scope.Scope, + I5, + S6 extends Scope.Scope, + I6, + S7 extends Scope.Scope, + I7, + S8 extends Scope.Scope, + I8, + T extends Type.Any, + Inputs, + >( + step1: Node.Node, + step2: Node.Node, + step3: Node.Node, + step4: Node.Node, + step5: Node.Node, + step6: Node.Node, + step7: Node.Node, + step8: Node.Node, + body: Body, + ): Result.Result< + Expression.Expression< + T, + Input.All + >, + ProgramError.Construction + >; +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts similarity index 87% rename from libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts index 981771548f3..b4dc4fadeb3 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Import.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts @@ -1,10 +1,11 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Import, Module, Program } from "../main.js"; +import { Module } from "../main.js"; +import { Do as EmptyDo, Import, withPrelude } from "./index.js"; import type { Expression, Inputs, Type } from "../main.js"; -import type * as ProgramError from "./ProgramError.js"; +import type * as ProgramError from "../program/ProgramError.js"; // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; @@ -19,7 +20,7 @@ const uuid = Result.getOrThrow( }), ); const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); -const { Do } = Program.withPrelude({ modules: { uuid, core } }); +const { Do } = withPrelude({ modules: { uuid, core } }); describe("import_types", () => { test("named_exports", () => { @@ -56,13 +57,13 @@ describe("import_types", () => { }); test("invalid_exports", () => { - expectTypeOf(Program.withPrelude); + expectTypeOf(withPrelude); // @ts-expect-error Values must be expression handles. - Program.withPrelude({ values: { host: 1 } }); + withPrelude({ values: { host: 1 } }); // @ts-expect-error Modules must be module declarations. - Program.withPrelude({ modules: { uuid: uuid.values.Uuid } }); + withPrelude({ modules: { uuid: uuid.values.Uuid } }); // @ts-expect-error Types cannot be value handles. - Program.withPrelude({ types: { Uuid: uuid.values.Uuid } }); + withPrelude({ types: { Uuid: uuid.values.Uuid } }); // @ts-expect-error An import selects a module. Import(() => ({ Uuid: uuid.values.Uuid })); // @ts-expect-error Selected names must exist in an export universe. @@ -72,7 +73,7 @@ describe("import_types", () => { }); test("literal_types", () => { - Program.Do(($) => { + EmptyDo(($) => { expectTypeOf($.integer(1)).toEqualTypeOf< Expression.Expression >(); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts similarity index 96% rename from libs/@local/hashql/sdk/typescript/src/program/Import.test.ts rename to libs/@local/hashql/sdk/typescript/src/do/Import.test.ts index 9cbe3fc52f9..221d845dea7 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Import.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts @@ -5,14 +5,8 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { - Expression, - Import, - Let, - Module, - Program, - TypeExpression, -} from "../main.js"; +import { Expression, Module, TypeExpression } from "../main.js"; +import { Import, Let, withPrelude } from "./index.js"; import type { Type } from "../main.js"; @@ -28,7 +22,7 @@ const uuid = Result.getOrThrow( }), ); const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); -const { Do } = Program.withPrelude({ modules: { uuid, core } }); +const { Do } = withPrelude({ modules: { uuid, core } }); const use = "::kernel::special_form::use"; const shadowValue = 7; @@ -202,7 +196,7 @@ describe("import_scope", () => { types: { Integer: Module.type() }, }), ); - const root = Program.withPrelude(kernel).Do(($, _, { Integer }) => + const root = withPrelude(kernel).Do(($, _, { Integer }) => $.input("count", Integer, $.integer(0)), ); expect( diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts similarity index 89% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts rename to libs/@local/hashql/sdk/typescript/src/do/Import.ts index 65a99ae058d..df43cce90f2 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.ts @@ -1,18 +1,18 @@ // oxlint-disable import/max-dependencies -- an import updates the module, type and value universes together import { Result } from "effect"; -import { isReadonlyArray } from "../../internal/array.js"; -import * as JExpr from "../../jexpr/index.js"; -import * as AST from "../ast/index.js"; -import * as Expression from "../Expression.js"; -import * as Module from "../Module.js"; -import * as ProgramError from "../ProgramError.js"; -import * as TypeExpression from "../TypeExpression.js"; +import { isReadonlyArray } from "../internal/array.js"; +import * as JExpr from "../jexpr/index.js"; +import * as AST from "../program/ast/index.js"; +import * as Expression from "../program/Expression.js"; +import * as Module from "../program/Module.js"; +import * as ProgramError from "../program/ProgramError.js"; +import * as Scope from "../program/Scope.js"; +import * as TypeExpression from "../program/TypeExpression.js"; import * as Node from "./Node.js"; -import * as Scope from "./Scope.js"; -import type * as Inputs from "../Inputs.js"; -import type { Utilities } from "../Utilities.js"; +import type * as Inputs from "../program/Inputs.js"; +import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; type Name = Extract< diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts b/libs/@local/hashql/sdk/typescript/src/do/Let.ts similarity index 80% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts rename to libs/@local/hashql/sdk/typescript/src/do/Let.ts index af705ac5a30..cdbd5e8e07c 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Let.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Let.ts @@ -1,14 +1,14 @@ import { Result } from "effect"; -import * as Ident from "../../jexpr/Ident.js"; -import * as Binding from "../ast/Binding.js"; -import { Let as AstLet } from "../ast/Let.js"; -import * as Expression from "../Expression.js"; +import * as Ident from "../jexpr/Ident.js"; +import * as Binding from "../program/ast/Binding.js"; +import { Let as AstLet } from "../program/ast/Let.js"; +import * as Expression from "../program/Expression.js"; +import * as Scope from "../program/Scope.js"; import * as Node from "./Node.js"; -import * as Scope from "./Scope.js"; -import type * as Type from "../../type/index.js"; -import type { Utilities } from "../Utilities.js"; +import type * as Type from "../type/index.js"; +import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a declaration step diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts similarity index 82% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts rename to libs/@local/hashql/sdk/typescript/src/do/Newtype.ts index 01828fa6622..eb5ad6c5199 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Newtype.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts @@ -1,17 +1,17 @@ // oxlint-disable import/max-dependencies -- nominal declarations introduce both a type and a value constructor import { Result } from "effect"; -import * as Ident from "../../jexpr/Ident.js"; -import * as Binding from "../ast/Binding.js"; -import { Newtype as AstNewtype } from "../ast/Newtype.js"; -import * as Expression from "../Expression.js"; -import * as TypeExpression from "../TypeExpression.js"; +import * as Ident from "../jexpr/Ident.js"; +import * as Binding from "../program/ast/Binding.js"; +import { Newtype as AstNewtype } from "../program/ast/Newtype.js"; +import * as Expression from "../program/Expression.js"; +import * as Scope from "../program/Scope.js"; +import * as TypeExpression from "../program/TypeExpression.js"; import * as Node from "./Node.js"; -import * as Scope from "./Scope.js"; -import type * as Type from "../../type/index.js"; -import type * as Inputs from "../Inputs.js"; -import type { Utilities } from "../Utilities.js"; +import type * as Inputs from "../program/Inputs.js"; +import type * as Type from "../type/index.js"; +import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; export interface Exports< diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts b/libs/@local/hashql/sdk/typescript/src/do/Node.ts similarity index 83% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts rename to libs/@local/hashql/sdk/typescript/src/do/Node.ts index bc0e0fd74a8..3684d885761 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Node.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Node.ts @@ -1,9 +1,9 @@ import { identity } from "effect"; -import type { Node as AstNode } from "../ast/Node.js"; -import type * as ProgramError from "../ProgramError.js"; -import type { Utilities } from "../Utilities.js"; -import type { Scope } from "./Scope.js"; +import type { Node as AstNode } from "../program/ast/Node.js"; +import type * as ProgramError from "../program/ProgramError.js"; +import type { Scope } from "../program/Scope.js"; +import type { Utilities } from "./Utilities.js"; import type { Result, Types } from "effect"; export interface Variance { @@ -11,7 +11,7 @@ export interface Variance { readonly _Out: Types.Invariant; } -export const TypeId = "~hashql/program/ir/Node"; +export const TypeId = "~hashql/do/Node"; export interface Transition { readonly scope: Out; @@ -46,6 +46,7 @@ export const make = ( const erased: unknown = elaborate; return { [TypeId]: { + // oxlint-disable-next-line typescript/strict-void-return -- only used for variance inputs: identity, modules: { _In: identity, _Out: identity }, values: { _In: identity, _Out: identity }, diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts b/libs/@local/hashql/sdk/typescript/src/do/Type.ts similarity index 78% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts rename to libs/@local/hashql/sdk/typescript/src/do/Type.ts index ff0277f79c0..50b4f4f34e7 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Type.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Type.ts @@ -1,14 +1,14 @@ import { Result } from "effect"; -import * as Binding from "../ast/Binding.js"; -import { Type as AstType } from "../ast/Type.js"; -import * as TypeExpression from "../TypeExpression.js"; +import * as Binding from "../program/ast/Binding.js"; +import { Type as AstType } from "../program/ast/Type.js"; +import * as Scope from "../program/Scope.js"; +import * as TypeExpression from "../program/TypeExpression.js"; import * as Node from "./Node.js"; -import * as Scope from "./Scope.js"; -import type * as Semantic from "../../type/index.js"; -import type { Empty } from "../Inputs.js"; -import type { Utilities } from "../Utilities.js"; +import type { Empty } from "../program/Inputs.js"; +import type * as Semantic from "../type/index.js"; +import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a type declaration step diff --git a/libs/@local/hashql/sdk/typescript/src/program/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts similarity index 87% rename from libs/@local/hashql/sdk/typescript/src/program/Utilities.ts rename to libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index 8825d1d2a91..e3ac91c57b1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -2,17 +2,21 @@ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods import { Result } from "effect"; -import * as Expression from "./Expression.js"; -import * as IR from "./ir/index.js"; -import * as ProgramError from "./ProgramError.js"; -import * as Query from "./Query.js"; +import * as Expression from "../program/Expression.js"; +import * as ProgramError from "../program/ProgramError.js"; +import * as Query from "../program/Query.js"; +import { Import } from "./Import.js"; +import { Let } from "./Let.js"; +import { Newtype } from "./Newtype.js"; +import * as Node from "./Node.js"; +import { Type as DeclareType } from "./Type.js"; +import type * as Input from "../program/Inputs.js"; +import type * as Scope from "../program/Scope.js"; +import type { TypeExpression } from "../program/TypeExpression.js"; import type * as Type from "../type/index.js"; -import type * as Input from "./Inputs.js"; -import type { Imported, Selection } from "./ir/Import.js"; -import type { Exports } from "./ir/Newtype.js"; -import type * as Scope from "./ir/Scope.js"; -import type { TypeExpression } from "./TypeExpression.js"; +import type { Imported, Selection } from "./Import.js"; +import type { Exports } from "./Newtype.js"; import type { ReadonlyRecord } from "effect/Record"; export type Body = ( @@ -21,9 +25,9 @@ export type Body = ( types: S["types"], ) => Expression.Expression; -type Wrap = IR.Node.Transition["wrap"]; +type Wrap = Node.Transition["wrap"]; -export type BuildStep = IR.Node.Any | Body; +export type BuildStep = Node.Any | Body; /** An unfinished nested block must end with an expression. */ export class Block { @@ -44,7 +48,7 @@ export class Block { this.#state = state; } - #append(step: IR.Node.Any): Block { + #append(step: Node.Any): Block { return new Block( Result.flatMap(this.#state, ({ scope, parents }) => { const input: Scope.Scope = scope; @@ -58,7 +62,7 @@ export class Block { } #step( - step: IR.Node.Node, + step: Node.Node, ): Block> { // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary const output: unknown = this.#append(step); @@ -78,7 +82,7 @@ export class Block { >, Input.Merge > { - return this.#step(IR.Let(name, initializer)); + return this.#step(Let(name, initializer)); } Type( @@ -91,7 +95,7 @@ export class Block { Scope.Merge> }>, Inputs > { - return this.#step(IR.Type(name, definition)); + return this.#step(DeclareType(name, definition)); } Newtype< @@ -107,7 +111,7 @@ export class Block { ) => TypeExpression, ): Block>, Inputs> { return this.#step( - IR.Newtype(name, identity, definition), + Newtype(name, identity, definition), ); } @@ -131,10 +135,10 @@ export class Block { | Block, Inputs> | Block>, Inputs> { if (imports === undefined) { - return this.#step(IR.Import(select)); + return this.#step(Import(select)); } - return this.#step(IR.Import(select, imports)); + return this.#step(Import(select, imports)); } Expr( @@ -203,7 +207,7 @@ export class Block { typeof step !== "object" || // oxlint-disable-next-line typescript/no-unnecessary-condition -- JavaScript callers may pass null despite the overloads step === null || - !(IR.Node.TypeId in step) + !(Node.TypeId in step) ) { return Result.fail( new ProgramError.Construction({ diff --git a/libs/@local/hashql/sdk/typescript/src/do/index.ts b/libs/@local/hashql/sdk/typescript/src/do/index.ts new file mode 100644 index 00000000000..9b5f2c3ce73 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/do/index.ts @@ -0,0 +1,67 @@ +/** + * Authors typed expressions with ordered declaration steps and scoped callbacks. + * + * @module + */ + +import * as Scope from "../program/Scope.js"; +import { Import } from "./Import.js"; +import { Let } from "./Let.js"; +import { Newtype } from "./Newtype.js"; +import { Type } from "./Type.js"; +import { Block as Builder } from "./Utilities.js"; + +import type * as Expression from "../program/Expression.js"; +import type * as ProgramError from "../program/ProgramError.js"; +import type { Do as Block } from "./Do.js"; +import type { BuildStep } from "./Utilities.js"; +import type { Result } from "effect"; + +export { Import } from "./Import.js"; +export { Let } from "./Let.js"; +export { Newtype } from "./Newtype.js"; +export { Type } from "./Type.js"; +export type { Utilities } from "./Utilities.js"; + +export interface Context { + readonly Do: Block; + readonly Let: typeof Let; + readonly Type: typeof Type; + readonly Newtype: typeof Newtype; + readonly Import: typeof Import; +} + +export const withPrelude = ( + prelude: Prelude, +): Context> => { + // SAFETY: the empty scope contributes no names to any namespace. + const initial = Scope.merge( + Scope.empty, + prelude, + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- merging into empty retains precisely the supplied namespace types + ) as Scope.From; + + const construct = ( + ...steps: readonly BuildStep[] + ): Result.Result => + Builder.build(initial, steps); + + // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary + const erased: unknown = construct; + + // SAFETY: the overloads check every transition before this driver erases its scope parameters. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the per-step scopes checked by the overloads + const Do = erased as Block>; + return Object.freeze({ + Do, + Let, + Type, + Newtype, + Import, + }); +}; + +const context: Context = withPrelude({}); + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- composes ordered steps and a final expression callback +export const Do: Block = context.Do; diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index a21c3db89ec..d5d376e8ab4 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -3,7 +3,8 @@ export * as Expression from "./program/Expression.js"; export * as Module from "./program/Module.js"; export * as Program from "./program/index.js"; export * as ProgramError from "./program/ProgramError.js"; -export { Import, Let, Newtype, If, assume, program } from "./program/index.js"; +export { program } from "./program/index.js"; +export { ifElse as If, assume } from "./program/Expression.js"; export * as TypeExpression from "./program/TypeExpression.js"; export type * as Type from "./type/index.js"; -export * as Inputs from "./program/Inputs.js"; +export type * as Inputs from "./program/Inputs.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/playground.ts b/libs/@local/hashql/sdk/typescript/src/playground.ts index 25463a89c24..d6c8544c3fc 100644 --- a/libs/@local/hashql/sdk/typescript/src/playground.ts +++ b/libs/@local/hashql/sdk/typescript/src/playground.ts @@ -1,134 +1,60 @@ -import { Option } from "effect"; - -import * as Scan from "./internal/scan.js"; -import * as Ident from "./jexpr/Ident.js"; -import * as JExpr from "./jexpr/index.js"; - -import type * as Type from "./type/index.js"; - -const Binding: unique symbol = Symbol("Expression.binding"); -class ExpressionBinding { - /** Phantom result type. The binding stores no runtime type descriptor. */ - declare readonly type: T; - readonly #expr: JExpr.Expression; - - constructor(expr: JExpr.Expression) { - this.#expr = expr; - } - - get expression(): JExpr.Expression { - return this.#expr; - } - - push( - fn: (expr: JExpr.Expression) => JExpr.Expression, - ): ExpressionBinding { - return new ExpressionBinding(fn(this.#expr)); - } -} - -interface ExpressionHandle { - readonly [Binding]: ExpressionBinding; -} - -/** - * A symbolic result, with field access preserving the selected field's type. - * - * The binding remains outside the conditional view so generic functions can infer `T`. - */ -export type Expression = ExpressionHandle & - (T extends Type.Struct - ? { - readonly [Field in Extract]: Expression< - Fields[Field] - >; - } - : T extends Type.Tuple.Any - ? { - readonly [Index in Extract< - keyof T["fields"], - `${number}` - >]: Expression; - } - : Record); - -/** Encodes one property name, including quoted identifiers and tuple positions. */ -const accessProperty = ( - expr: JExpr.Expression, - property: string, -): JExpr.Expression => { - if (/^(?:0|[1-9]\d*)$/u.test(property)) { - return JExpr.call("access", expr, JExpr.integer(BigInt(property))); +// sketch 1) proxy based interpolation, Elysia.JS style + +const program = ($) => { + // $ is just used for fluid syntax, and built-in utilities, it's the general entrypoint + const { EntityUuid, Uuid } = $.prelude(); + const { temporal } = $.modules(); + + const comparison = EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")); // would be converted into a let binding + + // if else would just "work", but would need to have the form of: + let out; + if ([expr]) { + [expr]; // cannot mention or set `out` + out = [result]; + } else { + // else **must** be set + out = [expr]; } - const identifier = Option.orElse(Scan.scanIdentExact(property), () => - Scan.scanIdentExact(`\`${property}\``), - ); - - if (Option.isNone(identifier) || identifier.value.value !== property) { - throw new Error(`Invalid HashQL field name: ${property}`); - } + // else if chains are possible, but need to obey the same rules as if/else - return JExpr.access(expr, Ident.compile(Ident.fromScanned(identifier.value))); + $.query + .entities($.input("axis", $.input("axis", temporal.QueryTemporalAxes))) + .filter( + (vertex) => + vertex.metadata.record_id.entity_id.entity_uuid === comparison, + ) + .collect(); }; -const project = ( - binding: ExpressionBinding, -): Expression => { - const target: ExpressionHandle = { [Binding]: binding }; - const proxy = new Proxy(target, { - get( - target, - property, - ): ExpressionBinding | ExpressionHandle | undefined { - if (property === Binding) { - return target[Binding]; - } +// sketch 2) mutable execution +const program = ($) => { + const { temporal } = $.modules(); + const { EntityUuid, Uuid, eq } = $.prelude(); - if (typeof property === "symbol") { - return undefined; - } + const foo = $.let("foo", [expr]); // oxlint rule for the name to be the same + const Foo = $.newtype("Foo", { + foo: BigInt, // constructor is just turned into a `Integer` type + }); // fluid constructor that just takes records, and arrays for tuples, dict is just created using the `Dict` and `List` built-in. - return project( - target[Binding].push((expr) => - accessProperty(expr, property), - ), - ); - }, - }); + const bar = Foo({ foo: 2n }); // this just works - // SAFETY: The target retains T's binding, and the trap creates expression bindings for projected fields. The raw-AST constructor supplies the type ascription. - return proxy as Expression; -}; - -/** - * Wraps a J-Expr expression with an unchecked result-type ascription. - * - * The caller must ensure that `initial` produces `T`. The binding carries no runtime type descriptor, so the proxy cannot check this claim. - */ -export const makeExpression = ( - initial: JExpr.Expression, -): Expression => project(new ExpressionBinding(initial)); - -/** Extracts the AST without evaluating the expression. */ -export const toJExpr = ( - expression: ExpressionHandle, -): JExpr.Expression => expression[Binding].expression; + // ifElse needs to be explicit + const baz = $.ifElse([expr], { then: [expr], else: [expr] }); -/** - * Constructs a dictionary lookup that returns null for an absent key. - * - * Dictionary keys are invariant, so a narrower key type is not enough. - */ -export const get = ( - dictionary: ExpressionHandle, - key: ExpressionHandle & - ([NoInfer] extends [NoInfer] - ? ExpressionHandle> - : never), -): Expression => - project( - dictionary[Binding].push((expr) => - JExpr.index(expr, toJExpr(key)), - ), + // this would NOT be converted + // const comparison = EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")); + // this would: + const comparison = $.let( + "comparison", + EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), ); + + $.query + .entities($.input("axis", $.input("axis", temporal.QueryTemporalAxes))) + .filter((vertex) => + eq(vertex.metadata.record_id.entity_id.entity_uuid, comparison), + ) + .collect(); +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Do.ts b/libs/@local/hashql/sdk/typescript/src/program/Do.ts deleted file mode 100644 index f0ae274c763..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/program/Do.ts +++ /dev/null @@ -1,201 +0,0 @@ -import type * as Type from "../type/index.js"; -import type * as Expression from "./Expression.js"; -import type * as Input from "./Inputs.js"; -import type * as IR from "./ir/index.js"; -import type * as ProgramError from "./ProgramError.js"; -import type { Body } from "./Utilities.js"; -import type { Result } from "effect"; - -/** Contextual overloads propagate the output universes and accumulate every declaration's inputs. */ -export interface Do { - ( - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - ( - step1: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - S4 extends IR.Scope.Scope, - I4, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - step4: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - S4 extends IR.Scope.Scope, - I4, - S5 extends IR.Scope.Scope, - I5, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - step4: IR.Node.Node, - step5: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression>, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - S4 extends IR.Scope.Scope, - I4, - S5 extends IR.Scope.Scope, - I5, - S6 extends IR.Scope.Scope, - I6, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - step4: IR.Node.Node, - step5: IR.Node.Node, - step6: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression< - T, - Input.All - >, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - S4 extends IR.Scope.Scope, - I4, - S5 extends IR.Scope.Scope, - I5, - S6 extends IR.Scope.Scope, - I6, - S7 extends IR.Scope.Scope, - I7, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - step4: IR.Node.Node, - step5: IR.Node.Node, - step6: IR.Node.Node, - step7: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression< - T, - Input.All - >, - ProgramError.Construction - >; - < - S1 extends IR.Scope.Scope, - I1, - S2 extends IR.Scope.Scope, - I2, - S3 extends IR.Scope.Scope, - I3, - S4 extends IR.Scope.Scope, - I4, - S5 extends IR.Scope.Scope, - I5, - S6 extends IR.Scope.Scope, - I6, - S7 extends IR.Scope.Scope, - I7, - S8 extends IR.Scope.Scope, - I8, - T extends Type.Any, - Inputs, - >( - step1: IR.Node.Node, - step2: IR.Node.Node, - step3: IR.Node.Node, - step4: IR.Node.Node, - step5: IR.Node.Node, - step6: IR.Node.Node, - step7: IR.Node.Node, - step8: IR.Node.Node, - body: Body, - ): Result.Result< - Expression.Expression< - T, - Input.All - >, - ProgramError.Construction - >; -} diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts index cfaff1f8d0d..a0caabd1fb2 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts @@ -1,6 +1,7 @@ import { describe, expectTypeOf, test } from "vitest"; -import { Expression, Program } from "../main.js"; +import { Do as EmptyDo, withPrelude } from "../do/index.js"; +import { Expression } from "../main.js"; import type { Type } from "../main.js"; import type * as Inputs from "./Inputs.js"; @@ -15,7 +16,7 @@ type Graph = Type.Opaque< describe("fluent_types", () => { test("graph_vertex", () => { - const { Do } = Program.withPrelude({ + const { Do } = withPrelude({ values: { entities: Expression.fromJExpr< Type.Function, @@ -50,7 +51,7 @@ describe("fluent_types", () => { }); test("operation_domains", () => { - Program.Do(($) => { + EmptyDo(($) => { const integer = $.integer(1); expectTypeOf(integer).toEqualTypeOf< Expression.Expression diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts index 827dd1d1d17..823e352ec9b 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts @@ -4,7 +4,8 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Expression, Program } from "../main.js"; +import { Do as EmptyDo, withPrelude } from "../do/index.js"; +import { Expression } from "../main.js"; import type { Inputs, Type } from "../main.js"; @@ -13,7 +14,7 @@ type Graph = Type.Opaque< "::graph::Graph", Type.Struct<{ readonly "'marker": Vertex }> >; -const { Do } = Program.withPrelude({ +const { Do } = withPrelude({ values: { entities: Expression.fromJExpr< Type.Function, @@ -93,7 +94,7 @@ describe("fluent", () => { Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, Inputs.Empty >("record"); - const result = Program.Do(() => record.$project("$").$.isTrue()); + const result = EmptyDo(() => record.$project("$").$.isTrue()); expect( Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), ).toStrictEqual([ diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts index 4030af00c29..8dc760e1f16 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts @@ -1,7 +1,8 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Expression, Let, Module, Program } from "../main.js"; +import { Do as EmptyDo, Let, withPrelude } from "../do/index.js"; +import { Expression, Module, Program } from "../main.js"; import type { Inputs, Type } from "../main.js"; @@ -178,9 +179,9 @@ describe("snippet_requirements", () => { test("reusable_snippet", () => { const count = Expression.input("count", integer); const snippet = count.$.ne(Expression.integer(0)); - const first = Result.getOrThrow(Program.Do(() => snippet)); + const first = Result.getOrThrow(EmptyDo(() => snippet)); const second = Result.getOrThrow( - Program.Do(($) => snippet.$.and($.input("enabled", boolean))), + EmptyDo(($) => snippet.$.and($.input("enabled", boolean))), ); const program = Program.program(second); expectTypeOf>().toEqualTypeOf<{ @@ -194,7 +195,7 @@ describe("snippet_requirements", () => { test("discarded_expression", () => { const expression = Result.getOrThrow( - Program.Do(($) => { + EmptyDo(($) => { $.input("unused", integer); return $.integer(1); }), @@ -206,7 +207,7 @@ describe("snippet_requirements", () => { test("unused_and_shadowed_declarations", () => { const expression = Result.getOrThrow( - Program.Do( + EmptyDo( Let("value", ($) => $.input("first", integer)), Let("value", ($) => $.input("second", integer)), ($) => $.integer(1), @@ -220,7 +221,7 @@ describe("snippet_requirements", () => { test("nested_branches", () => { const expression = Result.getOrThrow( - Program.Do(($) => + EmptyDo(($) => $.if( $.input("condition", boolean), () => @@ -241,7 +242,7 @@ describe("snippet_requirements", () => { describe("builder_requirements", () => { test("query_dependencies", () => { - const { Do } = Program.withPrelude({ + const { Do } = withPrelude({ values: { entities: Expression.fromJExpr< Type.Function, @@ -266,11 +267,7 @@ describe("builder_requirements", () => { }); test("declaration_preservation", () => { - const { - Do, - Type: Alias, - Import, - } = Program.withPrelude({ modules: { kernel } }); + const { Do, Type: Alias, Import } = withPrelude({ modules: { kernel } }); const expression = Result.getOrThrow( Do( Import((_, { kernel }) => kernel), diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts index df7a621ccc9..af765714440 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts @@ -1,7 +1,8 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Expression, JExpr, Let, Module, Program } from "../main.js"; +import { Do as EmptyDo, Let } from "../do/index.js"; +import { Expression, JExpr, Module } from "../main.js"; import type { Type } from "../main.js"; @@ -18,9 +19,9 @@ describe("input_composition", () => { test("snippet_reuse", () => { expect.hasAssertions(); const snippet = Expression.input("count", integer, Expression.integer(7)); - const first = Result.getOrThrow(Program.Do(() => snippet)); + const first = Result.getOrThrow(EmptyDo(() => snippet)); const second = Result.getOrThrow( - Program.Do(($) => snippet.$.eq($.input("other", integer))), + EmptyDo(($) => snippet.$.eq($.input("other", integer))), ); expect(compile(first)).toBe( '["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}]', @@ -34,7 +35,7 @@ describe("input_composition", () => { test("discarded_input", () => { expect.hasAssertions(); const expression = Result.getOrThrow( - Program.Do(($) => { + EmptyDo(($) => { $.input("discarded", integer); return $.integer(1); }), @@ -45,7 +46,7 @@ describe("input_composition", () => { test("unused_initializer", () => { expect.hasAssertions(); const expression = Result.getOrThrow( - Program.Do( + EmptyDo( Let("unused", ($) => $.input("retained", integer)), ($) => $.integer(1), ), diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts index 61873473863..562b57755b2 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts @@ -3,10 +3,10 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; +import { Type as Alias, Do as EmptyDo, Newtype } from "../do/index.js"; import * as JExpr from "../jexpr/index.js"; import * as TypeSyntax from "../jexpr/type/index.js"; import * as Expression from "./Expression.js"; -import * as Program from "./index.js"; import * as Module from "./Module.js"; import * as TypeExpression from "./TypeExpression.js"; @@ -261,12 +261,12 @@ describe("type_application", () => { called = true; return Expression.integer(1); }; - const alias = Program.Do( - Program.Type("Alias", () => invalid), + const alias = EmptyDo( + Alias("Alias", () => invalid), body, ); - const nominal = Program.Do( - Program.Newtype("Nominal", identity, () => invalid), + const nominal = EmptyDo( + Newtype("Nominal", identity, () => invalid), body, ); expect(alias).toStrictEqual(TypeExpression.toType(invalid)); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts index bc14ef12fd6..2b4a977707c 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts @@ -1,7 +1,8 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Expression, Module, Program } from "../main.js"; +import { Do as EmptyDo, withPrelude } from "../do/index.js"; +import { Expression, Module } from "../main.js"; import type { Inputs, Type } from "../main.js"; @@ -165,7 +166,7 @@ describe("primitive_requirements", () => { test("conditional_branches", () => { const count = Expression.input("count", kernel.types.Integer); const expression = Result.getOrThrow( - Program.Do(($) => + EmptyDo(($) => $.if( true, () => count, @@ -180,7 +181,7 @@ describe("primitive_requirements", () => { > >(); const numeric = Result.getOrThrow( - Program.Do(($) => + EmptyDo(($) => $.if( true, () => 1, @@ -199,7 +200,7 @@ describe("primitive_requirements", () => { "::graph::Graph", Type.Struct<{ readonly "'marker": Vertex }> >; - const { Do } = Program.withPrelude({ + const { Do } = withPrelude({ values: { entities: Expression.fromJExpr< Type.Function, diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts index 764cbd9c71f..211735629b2 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts @@ -1,7 +1,8 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Expression, JExpr, Module, Program } from "../main.js"; +import { Do as EmptyDo, withPrelude } from "../do/index.js"; +import { Expression, JExpr, Module } from "../main.js"; import type { Inputs, Type } from "../main.js"; @@ -77,7 +78,7 @@ describe("primitive_failures", () => { test("both_branches", () => { expect.hasAssertions(); - const result = Program.Do(($) => + const result = EmptyDo(($) => $.if( true, () => 1, @@ -108,7 +109,7 @@ describe("primitive_query", () => { "::graph::Graph", Type.Struct<{ readonly "'marker": Vertex }> >; - const { Do } = Program.withPrelude({ + const { Do } = withPrelude({ values: { entities: Expression.fromJExpr< Type.Function, diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts index ceeec161488..ac7152f1a9c 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -8,7 +8,7 @@ import * as ProgramError from "./ProgramError.js"; import type * as Type from "../type/index.js"; import type { ArgumentInputs, Arguments } from "./ExpressionType.js"; import type * as Inputs from "./Inputs.js"; -import type * as IR from "./ir/index.js"; +import type * as Scope from "./Scope.js"; type Graph = Type.Opaque< "::graph::Graph", @@ -41,7 +41,7 @@ export type Query< // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without an entities declaration has no query entry point type Empty = Record; -export type Context = S["values"] extends { +export type Context = S["values"] extends { readonly entities: Expression.Handle< Type.Function, infer Requirements @@ -137,7 +137,7 @@ const chain = ( return proxy as Query; }; -export const make = (scope: S): Context => { +export const make = (scope: S): Context => { const entities = scope.values["entities"]; if (entities === undefined) { // SAFETY: no entities declaration means this context has no query entry point. diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts similarity index 93% rename from libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts rename to libs/@local/hashql/sdk/typescript/src/program/Scope.ts index 19e50520dc0..6e938e38547 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/Scope.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts @@ -1,6 +1,6 @@ -import type * as Expression from "../Expression.js"; -import type * as Module from "../Module.js"; -import type * as TypeExpression from "../TypeExpression.js"; +import type * as Expression from "./Expression.js"; +import type * as Module from "./Module.js"; +import type * as TypeExpression from "./TypeExpression.js"; import type { ReadonlyRecord } from "effect/Record"; /** An inspectable namespace without fixing its concrete key set. */ diff --git a/libs/@local/hashql/sdk/typescript/src/program/index.ts b/libs/@local/hashql/sdk/typescript/src/program/index.ts index fa6159b74ed..ba8ef36c093 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/index.ts @@ -1,7 +1,5 @@ /** - * Builds typed programs with separate module, value and type environments. - * - * Construction evaluates the step callbacks once. The resulting syntax tree owns its children and compiles without an authoring environment. + * Shared completed programs and their J-Expr serialization. * * @module */ @@ -9,20 +7,9 @@ import { Result } from "effect"; import * as JExpr from "../jexpr/index.js"; import * as Expression from "./Expression.js"; -import * as IR from "./ir/index.js"; -import { Block as Builder } from "./Utilities.js"; import type * as Type from "../type/index.js"; -import type { Do as Block } from "./Do.js"; import type * as ProgramError from "./ProgramError.js"; -import type { BuildStep } from "./Utilities.js"; - -export { assume, ifElse as If } from "./Expression.js"; -export { Import } from "./ir/Import.js"; -export { Let } from "./ir/Let.js"; -export { Newtype } from "./ir/Newtype.js"; -export { Type } from "./ir/Type.js"; -export type { Utilities } from "./Utilities.js"; export interface Program { readonly root: Expression.Expression; @@ -32,49 +19,6 @@ export type Inputs

= P extends { readonly root: infer Root } ? Expression.Inputs : never; -export interface Context { - readonly Do: Block; - readonly Let: typeof IR.Let; - readonly Type: typeof IR.Type; - readonly Newtype: typeof IR.Newtype; - readonly Import: typeof IR.Import; -} - -export const withPrelude = ( - prelude: Prelude, -): Context> => { - // SAFETY: the empty scope contributes no names to any namespace. - const initial = IR.Scope.merge( - IR.Scope.empty, - prelude, - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- merging into empty retains precisely the supplied namespace types - ) as IR.Scope.From; - - const construct = ( - ...steps: readonly BuildStep[] - ): Result.Result => - Builder.build(initial, steps); - - // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary - const erased: unknown = construct; - - // SAFETY: the overloads check every transition before this driver erases its scope parameters. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the per-step scopes checked by the overloads - const Do = erased as Block>; - return Object.freeze({ - Do, - Let: IR.Let, - Type: IR.Type, - Newtype: IR.Newtype, - Import: IR.Import, - }); -}; - -const context: Context = withPrelude({}); - -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- composes ordered steps and a final expression callback -export const Do: Block = context.Do; - export const program = ( root: Expression.Expression, ): Program => Object.freeze({ root }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts b/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts deleted file mode 100644 index a0950340fcf..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/program/ir/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { Import } from "./Import.js"; -export { Let } from "./Let.js"; -export { Newtype } from "./Newtype.js"; -export * as Node from "./Node.js"; -export * as Scope from "./Scope.js"; -export { Type } from "./Type.js"; diff --git a/libs/@local/hashql/sdk/typescript/tsdown.config.ts b/libs/@local/hashql/sdk/typescript/tsdown.config.ts index 94f0cfb436d..37067ac2f7e 100644 --- a/libs/@local/hashql/sdk/typescript/tsdown.config.ts +++ b/libs/@local/hashql/sdk/typescript/tsdown.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "tsdown"; import type { UserConfig } from "tsdown"; const config: UserConfig = defineConfig({ - entry: ["src/main.ts"], + entry: ["src/main.ts", "src/do/index.ts"], format: "esm", platform: "neutral", unbundle: true, From ff4df26e164b0e4821ff96df7ccc6941e97e2c60 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:41:18 +0200 Subject: [PATCH 03/22] feat: add HashQL draft program API --- .../hashql/sdk/typescript/src/draft/index.ts | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/index.ts diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts new file mode 100644 index 00000000000..bb295bdfb9e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -0,0 +1,86 @@ +import type * as Expression from "../program/Expression.js"; +import type * as Scope from "../program/Scope.js"; +import type * as TypeExpression from "../program/TypeExpression.js"; +import type * as Type from "../type/index.js"; +import type { Result } from "effect"; +import type { ReadonlyRecord } from "effect/Record"; + +export type Inputs = ReadonlyRecord; + +declare namespace Inputs { + export type Empty = ReadonlyRecord; + + export type ProgramInput = I extends Inputs + ? { + readonly [Key in keyof I]: I[Key] extends TypeExpression.TypeExpression< + infer Type + > + ? Expression.Expression + : never; + } + : never; +} + +type ScopeKeys = + | keyof S["modules"] + | keyof S["values"] + | keyof S["types"]; + +/** `unknown` is the identity of `&`, so namespaces lacking the key drop out. */ +type Lookup = Key extends keyof Namespace + ? Namespace[Key] + : unknown; + +type Prelude = { + readonly [Key in ScopeKeys]: Lookup & + Lookup & + Lookup; +}; + +type DefaultPrelude = Scope.Scope; + +interface Context

{ + readonly prelude: () => Prelude

; + readonly let: ( + name: string, + value: Expression.Expression, + ) => Expression.Expression; + readonly newtype: ( + name: string, + value: T, + ) => Expression.Expression & TypeExpression.TypeExpression; + readonly type: ( + name: string, + value: T, + ) => TypeExpression.TypeExpression; + readonly ifElse: (( + condition: Expression.Expression, + then: ($: Context

) => Expression.Expression, + else: ($: Context

) => Expression.Expression, + ) => Expression.Expression ) | (/* the other version lol */); + + readonly query: [...] +} + +class DraftError {} + +const programWithPrelude = < + Prelude extends Scope.Scope, + I extends Inputs, + O extends Type.Any, +>( + prelude: Prelude, + inputs: I, + draft: ($: Context, inputs: I) => Expression.Expression, +): Result.Result, DraftError> => { + // todo!() +}; + +const program = ( + inputs: I, + draft: ( + $: Context, + inputs: I, + ) => Expression.Expression, +): Result.Result, DraftError> => + programWithPrelude(Scope.empty, inputs, draft); From 2e31783ec30f345516910d5e52a53cee575cd271 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:47:48 +0200 Subject: [PATCH 04/22] feat: add structural HashQL type shorthand --- .../hashql/sdk/typescript/src/do/Do.test.ts | 24 +- .../hashql/sdk/typescript/src/do/Utilities.ts | 41 +- libs/@local/hashql/sdk/typescript/src/main.ts | 2 + .../sdk/typescript/src/program/Module.ts | 4 +- .../typescript/src/program/ProgramError.ts | 105 ++++- .../sdk/typescript/src/program/Query.ts | 5 +- .../src/program/Structural.test-d.ts | 142 +++++++ .../typescript/src/program/Structural.test.ts | 102 +++++ .../sdk/typescript/src/program/Structural.ts | 371 ++++++++++++++++++ .../hashql/sdk/typescript/tsdown.config.ts | 2 +- 10 files changed, 743 insertions(+), 55 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Structural.ts diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts index 84b2e9c6248..461dea275ad 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts @@ -1,3 +1,8 @@ +/** + * Do block construction, declaration ordering and runtime validation tests. + * + * @module + */ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods // oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments @@ -109,7 +114,7 @@ describe("block_errors", () => { _tag: "Failure", failure: { _tag: "ProgramConstructionError", - reason: { _tag: "InvalidBlock" }, + reason: { _tag: "MissingBlockBody" }, }, }); }); @@ -125,7 +130,7 @@ describe("block_errors", () => { _tag: "Failure", failure: { _tag: "ProgramConstructionError", - reason: { _tag: "InvalidBlock" }, + reason: { _tag: "MisplacedBlockBody" }, }, }); }); @@ -138,11 +143,24 @@ describe("block_errors", () => { _tag: "Failure", failure: { _tag: "ProgramConstructionError", - reason: { _tag: "InvalidBlock" }, + reason: { _tag: "InvalidBodyResult" }, }, }); }); + test("invalid_step", () => { + expect.hasAssertions(); + const result = EmptyDo( + // @ts-expect-error A plain object is not a declaration step. + {}, + ($) => $.integer(2), + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidBlockStep" } }, + }); + }); + test("binding_reason", () => { expect.hasAssertions(); const result = EmptyDo( diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index e3ac91c57b1..0ea0787da45 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -1,3 +1,10 @@ +/** + * Sequential declaration blocks for the Do authoring API. + * + * Each step extends the typed scope and records how to wrap the final expression. Nested bodies inherit the scope without repeating the declarations that introduced it. {@link Block} retains construction failures until the caller completes the body. + * + * @module + */ // oxlint-disable import/max-dependencies -- block construction composes the declaration steps and expression helpers // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods import { Result } from "effect"; @@ -154,14 +161,7 @@ export class Block { scope.types, ); if (!Expression.isExpression(expression)) { - return Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidBlock({ - message: - "An expression callback must return a HashQL expression", - }), - }), - ); + return Result.fail(ProgramError.Construction.invalidBodyResult()); } return Result.map(Expression.toNode(expression), (node) => { let root = node; @@ -183,24 +183,12 @@ export class Block { ); const body = steps.at(-1); if (typeof body !== "function" || Expression.isExpression(body)) { - return Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidBlock({ - message: "A Do block must end with an expression callback", - }), - }), - ); + return Result.fail(ProgramError.Construction.missingBlockBody()); } for (const step of steps.slice(0, -1)) { if (typeof step === "function") { - return Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidBlock({ - message: "Only the last step may be an expression callback", - }), - }), - ); + return Result.fail(ProgramError.Construction.misplacedBlockBody()); } if ( @@ -209,14 +197,7 @@ export class Block { step === null || !(Node.TypeId in step) ) { - return Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidBlock({ - message: - "A Do block expects declaration steps before its expression callback", - }), - }), - ); + return Result.fail(ProgramError.Construction.invalidBlockStep()); } block = block.#append(step); } diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index d5d376e8ab4..9528ca3423f 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,6 +1,8 @@ export * as JExpr from "./jexpr/index.js"; export * as Expression from "./program/Expression.js"; export * as Module from "./program/Module.js"; +export * as Prelude from "./program/Prelude.js"; +export * as Structural from "./program/Structural.js"; export * as Program from "./program/index.js"; export * as ProgramError from "./program/ProgramError.js"; export { program } from "./program/index.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.ts index cdfa8fd91ca..5cf89f49e9e 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.ts @@ -5,7 +5,7 @@ * * @module */ -import { Result } from "effect"; +import { Predicate, Result } from "effect"; import * as JExpr from "../jexpr/index.js"; import * as Expression from "./Expression.js"; @@ -73,7 +73,7 @@ export interface Module { /** Recognizes a module assembled by this SDK. */ // oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries export const isModule = (value: unknown): value is Any => - typeof value === "object" && value !== null && TypeId in value; + Predicate.hasProperty(value, TypeId); /** Declares a value with trusted semantic type information. */ export const value = (): Declaration< diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts index 90f706b1fa2..5a3b213c8e0 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts @@ -1,26 +1,40 @@ +/** + * Recoverable failures while constructing a HashQL program. + * + * Each reason identifies a construction failure independently of its diagnostic wording. Parser failures retain their typed causes. {@link Construction} renders the human-readable message and provides constructors for failures shared by builders. + * + * @module + */ import { Data } from "effect"; -interface ParserFailure { - // oxlint-disable-next-line typescript/no-restricted-types -- callers can inspect parser details without depending on the parser's error type - readonly cause: unknown; -} +import type { Schema, SchemaIssue } from "effect"; -interface NameFailure extends ParserFailure { +interface NameFailure { readonly name: string; + readonly cause: SchemaIssue.Issue; } -export type Reason = Data.TaggedEnum<{ - InvalidBindingName: NameFailure; - InvalidImportName: NameFailure; - InvalidParameterName: NameFailure; - InvalidExportName: NameFailure; - InvalidExpression: ParserFailure; - InvalidModulePath: NameFailure; - RelativeModulePath: { readonly name: string }; - InvalidTypeArity: { readonly arity: number }; - TypeArgumentCount: { readonly expected: number; readonly received: number }; - InvalidBlock: { readonly message: string }; -}>; +export type Reason = + | Data.TaggedEnum<{ + InvalidBindingName: NameFailure; + InvalidImportName: NameFailure; + InvalidParameterName: NameFailure; + InvalidExportName: NameFailure; + InvalidExpression: { readonly cause: Schema.SchemaError }; + InvalidModulePath: NameFailure; + RelativeModulePath: { readonly name: string }; + InvalidTypeArity: { readonly arity: number }; + TypeArgumentCount: { + readonly expected: number; + readonly received: number; + }; + UnsupportedTypeConstructor: { readonly name: string }; + }> + | { readonly _tag: "UnspecializedTypeConstructor" } + | { readonly _tag: "MissingBlockBody" } + | { readonly _tag: "MisplacedBlockBody" } + | { readonly _tag: "InvalidBlockStep" } + | { readonly _tag: "InvalidBodyResult" }; export const Reason: Data.TaggedEnum.Constructor = Data.taggedEnum(); @@ -33,6 +47,51 @@ const ConstructionBase: ReturnType< export class Construction extends ConstructionBase<{ readonly reason: Reason; }> { + static invalidBindingName( + name: string, + cause: SchemaIssue.Issue, + ): Construction { + return new Construction({ + reason: Reason.InvalidBindingName({ name, cause }), + }); + } + + static invalidTypeArity(arity: number): Construction { + return new Construction({ reason: Reason.InvalidTypeArity({ arity }) }); + } + + static typeArgumentCount(expected: number, received: number): Construction { + return new Construction({ + reason: Reason.TypeArgumentCount({ expected, received }), + }); + } + + static unsupportedTypeConstructor(name: string): Construction { + return new Construction({ + reason: Reason.UnsupportedTypeConstructor({ name }), + }); + } + + static unspecializedTypeConstructor(): Construction { + return new Construction({ reason: Reason.UnspecializedTypeConstructor() }); + } + + static missingBlockBody(): Construction { + return new Construction({ reason: Reason.MissingBlockBody() }); + } + + static misplacedBlockBody(): Construction { + return new Construction({ reason: Reason.MisplacedBlockBody() }); + } + + static invalidBlockStep(): Construction { + return new Construction({ reason: Reason.InvalidBlockStep() }); + } + + static invalidBodyResult(): Construction { + return new Construction({ reason: Reason.InvalidBodyResult() }); + } + override get message(): string { return Reason.$match(this.reason, { InvalidBindingName: ({ name }) => @@ -53,7 +112,17 @@ export class Construction extends ConstructionBase<{ `A type constructor needs a nonnegative safe integer arity, received ${arity}`, TypeArgumentCount: ({ expected, received }) => `Expected ${expected} type arguments, received ${received}`, - InvalidBlock: ({ message }) => message, + UnsupportedTypeConstructor: ({ name }) => + `Unsupported primitive type constructor: ${JSON.stringify(name)}`, + UnspecializedTypeConstructor: () => + "A generic type must be specialized before use", + MissingBlockBody: () => "A Do block must end with an expression callback", + MisplacedBlockBody: () => + "Only the last step may be an expression callback", + InvalidBlockStep: () => + "A Do block expects declaration steps before its expression callback", + InvalidBodyResult: () => + "An expression callback must return a HashQL expression", }); } } diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts index ac7152f1a9c..2ffb3062109 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -54,7 +54,10 @@ export type Context = S["values"] extends { ) => Query< Returns, Vertex, - Inputs.Merge> + Inputs.Merge< + Inputs.Conservative, + ArgumentInputs + > >; } : Empty diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts new file mode 100644 index 00000000000..171a6993d07 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts @@ -0,0 +1,142 @@ +/** + * Type-level checks for structural descriptors and input requirements. + * + * The generic forwarder checks that normalization retains its caller's type parameter. Mixed tuples distinguish positional mapping from a union of element types. + * + * @module + */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; +import type * as Inputs from "./Inputs.js"; + +interface Dictionary extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : Type.Never; +} + +const dictionary = Structural.constructor( + Result.getOrThrow( + TypeExpression.constructor( + Result.getOrThrow(JExpr.Path.decodeResult("::kernel::type::Dict")), + 2, + ), + ), +); + +const withStringKey = ( + definition: D, +): TypeExpression.TypeExpression< + Type.Dict> +> => dictionary(String, definition); + +type Row = Type.Struct<{ readonly count: Type.PrimitiveInteger }>; + +const hostChoice = ( + flag: boolean, +): + | { + readonly count: Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + >; + } + | { + readonly count: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + >; + } => { + const count = Expression.input("count", Structural.type(BigInt)); + if (flag) { + return { count }; + } + return { count: Expression.integer(0) }; +}; + +describe("structural_constructor_types", () => { + test("argument_positions", () => { + expectTypeOf(dictionary(String, { count: BigInt })).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Struct<{ readonly count: Type.PrimitiveInteger }> + > + > + >(); + expectTypeOf(dictionary(Number, [Boolean, String])).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveNumber, + Type.Tuple + > + > + >(); + }); + + test("generic_forwarding", () => { + expectTypeOf(withStringKey(BigInt)).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict + > + >(); + expectTypeOf(withStringKey({ enabled: Boolean })).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }> + > + > + >(); + }); + + test("nominal_argument", () => { + const identity = Symbol("Item"); + const item = TypeExpression.reference< + Type.Opaque + >(Result.getOrThrow(JExpr.Path.decodeResult("Item"))); + expectTypeOf(dictionary(String, item)).toEqualTypeOf< + TypeExpression.TypeExpression< + Type.Dict< + Type.PrimitiveString, + Type.Opaque + > + > + >(); + }); + + test("structural_requirements", () => { + const result = Structural.value()(hostChoice(true)); + expectTypeOf(result).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The host choice may contain a required input. + const closed: Expression.Expression = result; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error Number is not the Integer descriptor required by Row. + Structural.value()({ count: 1 }); + }); + + test("argument_rejections", () => { + expectTypeOf>().toBeNever(); + // @ts-expect-error Dict requires both a key type and a value type. + dictionary(String); + // @ts-expect-error Dict accepts exactly two arguments. + dictionary(String, Number, Boolean); + // @ts-expect-error Host values are not type definitions. + dictionary("key", Number); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts new file mode 100644 index 00000000000..19cf4682a54 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts @@ -0,0 +1,102 @@ +/** + * Runtime checks for structural normalization and constructor metadata forwarding. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as JExpr from "../jexpr/index.js"; +import * as TypeSyntax from "../jexpr/type/index.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; + +interface Dictionary extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : Type.Never; +} + +const path = Result.getOrThrow(JExpr.Path.decodeResult("::kernel::type::Dict")); +const declaration = Result.getOrThrow( + TypeExpression.constructor(path, 2), +); +const dictionary = Structural.constructor(declaration); + +const compile = (definition: TypeExpression.Any): string => + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(definition))); + +describe("structural_constructor", () => { + test("mixed_arguments", () => { + expect.hasAssertions(); + expect(compile(dictionary(String, { count: BigInt }))).toBe( + "::kernel::type::Dict<::kernel::type::String, (count: ::kernel::type::Integer)>", + ); + }); + + test("forwarded_metadata", () => { + expect.hasAssertions(); + const forwarded = new Proxy(declaration, { ownKeys: (): string[] => [] }); + const adapted = Structural.constructor(forwarded); + expect(adapted).toSatisfy(TypeExpression.isConstructor); + expect(compile(adapted(String, Number))).toBe( + "::kernel::type::Dict<::kernel::type::String, ::kernel::type::Number>", + ); + }); + + test("invalid_nested_name", () => { + expect.hasAssertions(); + const result = dictionary(String, { "": BigInt }).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidBindingName", name: "" } }, + }); + }); + + test("unspecialized_type", () => { + expect.hasAssertions(); + // @ts-expect-error An unapplied constructor is not a type definition. + const result = Structural.type(declaration).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "UnspecializedTypeConstructor" }, + message: "A generic type must be specialized before use", + }, + }); + }); + + test("unsupported_constructor", () => { + expect.hasAssertions(); + // @ts-expect-error Date is outside the supported primitive shorthand. + const result = Structural.type(Date).syntax; + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "UnsupportedTypeConstructor", name: "Date" }, + message: 'Unsupported primitive type constructor: "Date"', + }, + }); + }); + + test("dynamic_arity", () => { + expect.hasAssertions(); + const dynamic = Structural.constructor( + Result.getOrThrow( + TypeExpression.constructor(path, 2), + ), + ); + expect(dynamic(String).syntax).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "TypeArgumentCount", expected: 2, received: 1 }, + }, + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts new file mode 100644 index 00000000000..1fbd1d0a0d9 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts @@ -0,0 +1,371 @@ +/** + * Structural shorthand for HashQL types and values. + * + * {@link type} normalizes host constructors, tuples and records into type syntax. {@link value} accepts a structural value only when its semantic descriptor matches the requested type. Both operations retain nested type information, and value construction combines input requirements from every possible host-side alternative. + * + * @module + */ +import { + Array, + Predicate, + Record, + Result, + Struct, + Tuple, + flow, + pipe, +} from "effect"; + +import * as JExpr from "../jexpr/index.js"; +import * as Syntax from "../jexpr/type/index.js"; +import * as Expression from "./Expression.js"; +import * as ProgramError from "./ProgramError.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type * as Type from "../type/index.js"; +import type * as Input from "./Inputs.js"; +import type { ReadonlyRecord } from "effect/Record"; + +interface Fields extends ReadonlyRecord {} + +/** Runtime type syntax, host primitive constructors, or structural shorthand. */ +export type Definition = + | TypeExpression.Any + | BigIntConstructor + | NumberConstructor + | StringConstructor + | BooleanConstructor + | readonly Definition[] + | Fields; + +/** + * Resolves shorthand to its semantic descriptor without widening its fields. + * + * This conditional distributes over host alternatives: a choice between two definitions retains both possible descriptors. Inputs outside the shorthand language resolve to `never`, allowing the same operation to serve Effect's type-level mapping functions. + */ +export type TypeOf = + D extends TypeExpression.TypeExpression + ? T + : D extends BigIntConstructor + ? Type.PrimitiveInteger + : D extends NumberConstructor + ? Type.PrimitiveNumber + : D extends StringConstructor + ? Type.PrimitiveString + : D extends BooleanConstructor + ? Type.PrimitiveBoolean + : D extends readonly Definition[] + ? { + readonly _tag: "Tuple"; + readonly fields: { readonly [K in keyof D]: TypeOf }; + } + : D extends Fields + ? Type.Struct<{ readonly [K in keyof D]: TypeOf }> + : never; + +type TupleValues = { + readonly [K in keyof T]: Value; +}; + +/** Structural host values do not implicitly unwrap nominal types. */ +export type Value = + | Expression.Value + | (T extends Type.Struct + ? { readonly [K in keyof F]: Value } + : T extends Type.Tuple.Any + ? TupleValues + : never); + +interface FieldValues extends ReadonlyRecord {} + +export type AnyValue = Expression.AnyValue | readonly AnyValue[] | FieldValues; + +/** + * Retains the input requirements of every possible host value. + * + * A TypeScript union represents a host-side choice between values. Both arms may have the same HashQL type while carrying different inputs. Construction can choose either arm, so the resulting expression must require the inputs of both arms. Tuple and record recursion also includes inputs hidden inside structural values. + */ +export type Requirements = Input.Conservative< + RequirementAlternatives +>; + +type RequirementAlternatives = V extends Expression.AnyValue + ? Expression.Inputs + : V extends readonly [ + infer H extends AnyValue, + ...infer T extends readonly AnyValue[], + ] + ? Input.Conservative, Requirements>> + : V extends readonly (infer M extends AnyValue)[] + ? [M] extends [never] + ? Input.Empty + : Input.Conservative> + : V extends FieldValues + ? [keyof V] extends [never] + ? Input.Empty + : Input.Conservative<{ [K in keyof V]: Requirements }[keyof V]> + : Input.Empty; + +/** Recognizes recursive type shorthand without confusing primitive values with constructors. */ +// oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization +export const isDefinition = (value: unknown): value is Definition => { + if (TypeExpression.isExport(value)) { + return Predicate.hasProperty(value, "syntax"); + } + + if ( + value === BigInt || + value === String || + value === Number || + value === Boolean + ) { + return true; + } + + if (!Predicate.isObject(value) || Predicate.isFunction(value)) { + return false; + } + + return Object.values(value).every(isDefinition); +}; + +/** Recognizes structural value arguments, including expressions with type capabilities too. */ +// oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization +export const isValue = (value: unknown): value is AnyValue => { + if (Expression.isExpression(value)) { + return true; + } + + if (TypeExpression.isExport(value)) { + return false; + } + + const type = typeof value; + if ( + value === null || + type === "string" || + type === "number" || + type === "bigint" || + type === "boolean" + ) { + return true; + } + + if (!Predicate.isObject(value) || Predicate.isFunction(value)) { + return false; + } + + return Object.values(value).every(isValue); +}; + +const primitiveSyntax = ( + name: "Integer" | "Number" | "String" | "Boolean", +): Syntax.Type => + Syntax.Reference.make({ + path: JExpr.Path.decodeResult(`::kernel::type::${name}`).pipe( + Result.getOrThrow, + ), + generics: [], + }); + +const primitives = { + integer: primitiveSyntax("Integer"), + number: primitiveSyntax("Number"), + string: primitiveSyntax("String"), + boolean: primitiveSyntax("Boolean"), +}; + +const typeSyntax = ( + definition: Definition, +): Result.Result => { + if (TypeExpression.isExport(definition)) { + if (Predicate.hasProperty(definition, "syntax")) { + return definition.syntax; + } + + return Result.fail( + ProgramError.Construction.unspecializedTypeConstructor(), + ); + } + + if (Predicate.isFunction(definition)) { + switch (definition) { + case BigInt: { + return Result.succeed(primitives.integer); + } + case Number: { + return Result.succeed(primitives.number); + } + case String: { + return Result.succeed(primitives.string); + } + case Boolean: { + return Result.succeed(primitives.boolean); + } + default: { + return Result.fail( + ProgramError.Construction.unsupportedTypeConstructor(definition.name), + ); + } + } + } + + if (Array.isArray(definition)) { + return pipe( + definition, + Array.map(typeSyntax), + Result.all, + Result.map((members) => ({ + _tag: "Tuple", + members, + })), + ); + } + + return pipe( + definition, + Record.toEntries, + Array.map(([name, member]) => + Result.all({ + name: pipe( + JExpr.Ident.decodeResult(name), + Result.mapError((cause) => + ProgramError.Construction.invalidBindingName(name, cause), + ), + ), + member: typeSyntax(member), + }), + ), + Result.all, + Result.map((fields) => ({ + _tag: "Struct", + members: fields.map(({ name, member }) => [name, member] as const), + })), + ); +}; + +/** Normalizes shorthand while retaining invalid names in the construction result. */ +export const type = ( + definition: D, +): TypeExpression.TypeExpression> => + pipe(definition, typeSyntax, TypeExpression.fromResult>); + +/** Applies normalization independently at every position instead of collapsing the tuple to an element union. */ +interface Normalize extends Struct.Lambda { + readonly "~lambda.out": TypeExpression.TypeExpression< + TypeOf + >; + + ( + definition: D, + ): TypeExpression.TypeExpression>; +} + +const normalize = Tuple.map(Struct.lambda(type)); + +type ArgumentTypes = { + readonly [K in keyof A]: TypeOf; +}; + +/** A named generic type accepting the same shorthand as a local alias. */ +export interface Constructor + extends TypeExpression.AnyConstructor { + ( + ...definitions: A & { readonly length: F["arity"] } + ): TypeExpression.TypeExpression>>; +} + +/** Gives an existing generic declaration the same shorthand normalization as local aliases. */ +export const constructor = ( + declaration: TypeExpression.Constructor, +): Constructor => { + const instantiate = ( + ...definitions: A & { readonly length: F["arity"] } + ): TypeExpression.TypeExpression>> => + declaration>(...normalize(definitions)); + + return TypeExpression.adaptConstructor(declaration, instantiate); +}; + +const valueSyntax = ( + value: AnyValue, +): Result.Result => { + if ( + Expression.isExpression(value) || + value === null || + typeof value !== "object" + ) { + return Expression.toJExpr(value); + } + + if (Array.isArray(value)) { + return pipe( + value, + Array.map(valueSyntax), + Result.all, + Result.map((members) => JExpr.tuple(...members)), + ); + } + + return pipe( + value, + Record.toEntries, + Array.map(([name, member]) => + pipe( + member, + valueSyntax, + Result.map((syntax) => [name, syntax] as const), + ), + ), + Result.all, + Result.map(flow(Record.fromEntries, JExpr.struct)), + ); +}; + +type ValueTypes = { + readonly [K in keyof V]: ValueType; +}; + +/** The semantic descriptor of a structural host value, without implicit widening. */ +export type ValueType = V extends Expression.AnyValue + ? Expression.TypeOf + : V extends readonly AnyValue[] + ? { + readonly _tag: "Tuple"; + readonly fields: ValueTypes; + } + : V extends FieldValues + ? Type.Struct<{ readonly [K in keyof V]: ValueType }> + : never; + +/** Checking only the value against T would discard additional fields from the reported type. */ +export type Exact = [T] extends [ + ValueType, +] + ? [ValueType] extends [T] + ? V + : never + : never; + +/** Encodes a structural value whose descriptor exactly matches the caller's requested type. */ +export const value = + () => + & AnyValue>( + input: V & Exact, + ): Expression.Expression> => + pipe( + input, + valueSyntax, + Result.flatMap(flow(Expression.fromJExpr, Expression.toNode)), + Expression.fromResult>, + ); + +/** Internal syntax conversion shared by nominal constructors. */ +export const toJExpr = ( + value: AnyValue, +): Result.Result => + pipe( + value, + valueSyntax, + Result.flatMap(flow(Expression.fromJExpr, Expression.toJExpr)), + ); diff --git a/libs/@local/hashql/sdk/typescript/tsdown.config.ts b/libs/@local/hashql/sdk/typescript/tsdown.config.ts index 37067ac2f7e..7ed4bffa303 100644 --- a/libs/@local/hashql/sdk/typescript/tsdown.config.ts +++ b/libs/@local/hashql/sdk/typescript/tsdown.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "tsdown"; import type { UserConfig } from "tsdown"; const config: UserConfig = defineConfig({ - entry: ["src/main.ts", "src/do/index.ts"], + entry: ["src/main.ts", "src/do/index.ts", "src/draft/index.ts"], format: "esm", platform: "neutral", unbundle: true, From 6a5f8e32580f3d44322825c1802055d6d26490d3 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:32:59 +0200 Subject: [PATCH 05/22] fix: preserve module exports and optional types --- .../typescript/src/program/Module.test-d.ts | 55 +++- .../sdk/typescript/src/program/Module.test.ts | 72 ++++- .../sdk/typescript/src/program/Module.ts | 278 +++++++++++------- 3 files changed, 288 insertions(+), 117 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts index 4942171423c..463d40ef0dc 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts @@ -1,3 +1,8 @@ +/** + * Type-level module checks for named exports, generic aliases and optional namespaces. + * + * @module + */ // oxlint-disable unicorn/no-array-method-this-argument -- filter is a HashQL function, not Array.filter import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; @@ -15,35 +20,33 @@ type Graph = Type.Opaque< "::graph::Graph", Type.Struct<{ readonly "'marker": T }> >; -type VertexOf = T extends Graph ? VertexType : never; +type VertexOf = T extends Graph ? V : never; interface Filter extends Type.FunctionSignature { - readonly type: this["Target"] extends readonly [infer Input, Type.Any] + readonly type: this["Target"] extends readonly [infer T, Type.Any] ? Type.Function< readonly [ - Graph>, - Type.Function], Type.PrimitiveBoolean>, + Graph>, + Type.Function], Type.PrimitiveBoolean>, ], - Graph> + Graph> > : Type.Function; } interface List extends Type.TypeConstructor { readonly arity: 1; - readonly type: this["Target"] extends readonly [ - infer Element extends Type.Any, - ] - ? Type.List + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List : Type.Never; } interface Equal extends Type.FunctionSignature { readonly type: this["Target"] extends readonly [ - infer Left extends Type.Any, - infer Right extends Type.Any, + infer L extends Type.Any, + infer R extends Type.Any, ] - ? Type.Function + ? Type.Function : Type.Function; } @@ -195,6 +198,34 @@ describe("module_types", () => { Module.genericType(2); }); + test("optional_namespaces", () => { + const definition: { + readonly types?: { + readonly Integer: Module.Declaration< + TypeExpression + >; + }; + } = {}; + const optional = Result.getOrThrow(Module.define("::optional", definition)); + expectTypeOf(optional.types.Integer).toEqualTypeOf< + TypeExpression | undefined + >(); + // @ts-expect-error The entry is optional even though the namespace table always exists. + expectTypeOf(optional.types.Integer.syntax); + }); + + test("optional_declarations", () => { + const types: { + readonly Integer?: Module.Declaration< + TypeExpression + >; + } = {}; + const optional = Result.getOrThrow(Module.define("::optional", { types })); + expectTypeOf(optional.types.Integer).toEqualTypeOf< + TypeExpression | undefined + >(); + }); + test("tree_members", () => { expectTypeOf(modules.modules.core.modules.math.values.rem).toEqualTypeOf< typeof prelude.rem diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts index 562b57755b2..7fca98c90ed 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts @@ -1,5 +1,8 @@ -// oxlint-disable vitest/prefer-to-be-truthy -- freeze and membership checks need exact Boolean assertions -// oxlint-disable vitest/prefer-to-be-falsy -- Reflect.set needs an exact Boolean assertion +/** + * Runtime checks for module binding, alias identity and invalid export names. + * + * @module + */ import { Result } from "effect"; import { describe, expect, test } from "vitest"; @@ -80,6 +83,71 @@ const compile = (expression: Expression.Any): string => JExpr.compile(Result.getOrThrow(Expression.toJExpr(expression))); describe("module_exports", () => { + test("prototype_named_export", () => { + expect.hasAssertions(); + const name = "__proto__"; + const exports = Result.getOrThrow( + Module.define("::exports", { + types: { [name]: Module.type() }, + }), + ); + expect(Object.hasOwn(exports.types, name)).toBe(true); + expect(Object.getPrototypeOf(exports.types)).toBe(Object.prototype); + expect( + TypeSyntax.compile(Result.getOrThrow(exports.types[name].syntax)), + ).toBe("::exports::__proto__"); + }); + + test("nonenumerable_exports", () => { + expect.hasAssertions(); + const types = { Integer: Module.type() }; + const children = { math }; + Object.defineProperty(types, "Integer", { enumerable: false }); + Object.defineProperty(children, "math", { enumerable: false }); + const exports = Result.getOrThrow( + Module.define("::exports", { types, modules: children }), + ); + const tree = Result.getOrThrow(Module.root(children)); + expect(Object.keys(exports.types)).toStrictEqual(["Integer"]); + expect(exports.modules.math).toBe(math); + expect(tree.modules.math).toBe(math); + }); + + test("symbol_export", () => { + expect.hasAssertions(); + const name = Symbol("not a HashQL name"); + const results = [ + Module.define("::exports", { + types: { [name]: Module.type() }, + }), + Module.define("::exports", { + values: { [name]: Module.value() }, + }), + Module.define("::exports", { modules: { [name]: math } }), + Module.root({ [name]: math }), + ]; + for (const result of results) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "SymbolExportName", name } }, + }); + } + }); + + test("optional_namespace", () => { + expect.hasAssertions(); + const definition: { + readonly types?: { + readonly Integer: Module.Declaration< + TypeExpression.TypeExpression + >; + }; + } = {}; + expect( + Result.getOrThrow(Module.define("::exports", definition)).types, + ).toStrictEqual({}); + }); + test("qualified_call", () => { expect.hasAssertions(); expect(compile(prelude.remainder(dividend, divisor))).toBe( diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.ts index 5cf89f49e9e..a6f0a4a5d3b 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.ts @@ -5,7 +5,7 @@ * * @module */ -import { Predicate, Result } from "effect"; +import { Predicate, Result, flow, pipe } from "effect"; import * as JExpr from "../jexpr/index.js"; import * as Expression from "./Expression.js"; @@ -20,14 +20,19 @@ const Declare: unique symbol = Symbol("~hashql/ModuleDeclaration"); const TypeId: unique symbol = Symbol("~hashql/Module"); /** A declaration waiting for the module to supply its absolute export path. */ -export interface Declaration { +export interface Declaration { readonly [Declare]: ( path: JExpr.Path.Path, - ) => Result.Result; + ) => Result.Result; } /** An inspectable export table without fixing its concrete key set. */ -interface Namespace extends ReadonlyRecord {} +interface Namespace extends ReadonlyRecord {} + +/** Reverse mapping lets each declaration retain the type of the export it creates. */ +type Declarations = { + readonly [K in keyof E]: Declaration | E[K]; +}; /** A module with its concrete export names erased. */ export interface Any { @@ -50,26 +55,36 @@ export interface Definition { // oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent namespace intentionally has no known members type Empty = Record; -type Entries = Key extends keyof Shape - ? Shape[Key] +/** Models possible namespace omission as optional members of an always-present table. */ +type Entries = K extends keyof S + ? undefined extends S[K] + ? Partial> + : S[K] : Empty; -type Exports = { - readonly [Name in keyof Declarations]: Declarations[Name] extends Declaration< - infer Export - > - ? Export - : Declarations[Name]; + +/** Distributes over alternatives so an optional declaration also unwraps when present. */ +type Export = D extends Declaration ? E : D; + +type Exports = { + readonly [K in keyof D]: Export; }; -/** An immutable module record preserving each export's concrete type. */ -export interface Module { +/** Bound tables retain their key-to-export relationships independently of the source declarations. */ +interface Bound { readonly [TypeId]: true; readonly path: JExpr.Path.Path; - readonly modules: Readonly>; - readonly types: Exports>; - readonly values: Exports>; + readonly modules: Readonly; + readonly types: Readonly; + readonly values: Readonly; } +/** An immutable module record preserving each export's concrete type. */ +export interface Module extends Bound< + Entries, + Exports>, + Exports> +> {} + /** Recognizes a module assembled by this SDK. */ // oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries export const isModule = (value: unknown): value is Any => @@ -79,61 +94,126 @@ export const isModule = (value: unknown): value is Any => export const value = (): Declaration< Expression.Expression > => ({ - [Declare]: (path) => - Result.succeed( - Expression.fromJExpr(JExpr.Path.compile(path)), - ), + [Declare]: flow( + JExpr.Path.compile, + Expression.fromJExpr, + Result.succeed, + ), }); /** Declares a named type without expanding it into its structural representation. */ export const type = (): Declaration< TypeExpression.TypeExpression > => ({ - [Declare]: (path) => Result.succeed(TypeExpression.reference(path)), + [Declare]: flow(TypeExpression.reference, Result.succeed), }); /** Declares a named generic type with a type-level operation for its result. */ -export const genericType = ( - arity: Lambda["arity"], -): Declaration> => ({ - [Declare]: (path) => TypeExpression.constructor(path, arity), +export const genericType = ( + arity: F["arity"], +): Declaration> => ({ + [Declare]: (path) => TypeExpression.constructor(path, arity), }); const memberName = ( name: string, ): Result.Result => - Result.mapError( + pipe( JExpr.Ident.decodeResult(name), - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidExportName({ name, cause }), - }), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidExportName({ name, cause }), + }), + ), ); -const bind = ( - parent: JExpr.Path.Path, - entries: Namespace | Export>, -): Result.Result, ProgramError.Construction> => - Result.gen(function* () { - const exports: [string, Export][] = []; +/** Symbol keys cannot appear in HashQL paths and must not disappear during binding. */ +const requireStringKeys = ( + symbols: readonly symbol[], +): Result.Result => { + const [name] = symbols; - for (const [name, entry] of Object.entries(entries)) { - const ident = yield* memberName(name); - const path: JExpr.Path.Path = { - rooted: true, - segments: [...parent.segments, ident], - }; + if (name !== undefined) { + return Result.fail(ProgramError.Construction.symbolExportName(name)); + } + + return Result.void; +}; - if (typeof entry === "object" && entry !== null && Declare in entry) { - exports.push([name, yield* entry[Declare](path)]); - } else { - exports.push([name, entry]); - } +/** + * Maps each own name at its corresponding export type. + * + * The callback is generic in K: it must produce E[K] from S[K] for the same key. This preserves the relationship that a callback over an entry union would lose. The source may contain declarations, while the destination contains bound exports. + */ +const mapEntries = < + E extends Namespace, + S extends Declarations, +>( + entries: S, + resolve: ( + name: K, + entry: S[K], + ident: JExpr.Ident.Ident, + ) => Result.Result, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + yield* pipe(entries, Object.getOwnPropertySymbols, requireStringKeys); + const exports: Partial = {}; + const member = ( + name: K, + ): Result.Result => + pipe( + memberName(name), + Result.flatMap((ident) => resolve(name, entries[name], ident)), + ); + + for (const name of Object.getOwnPropertyNames(entries)) { + const bound = yield* member(name); + // Defining the property also preserves the ordinary export name __proto__. + Object.defineProperty(exports, name, { value: bound, enumerable: true }); } - return Object.freeze(Object.fromEntries(exports)); + // SAFETY: the loop fills each own string key at its original E[K] type. TypeScript cannot prove that coverage. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes a per-key checked Partial, without changing any export type + return Object.freeze(exports as E); }); +const copyModules = >( + modules: M, +): Result.Result, ProgramError.Construction> => + mapEntries(modules, (_name, entry) => Result.succeed(entry)); + +const isDeclaration = (entry: Declaration | E): entry is Declaration => + Predicate.hasProperty(entry, Declare); + +/** Resolves each declaration without widening its semantic descriptor. */ +const bind = >( + parent: JExpr.Path.Path, + entries: Declarations | undefined, +): Result.Result | Empty, ProgramError.Construction> => { + if (entries === undefined) { + return Result.succeed(Object.freeze({})); + } + + const resolve = ( + _name: K, + entry: Declaration | E[K], + ident: JExpr.Ident.Ident, + ): Result.Result => { + if (isDeclaration(entry)) { + return entry[Declare]({ + rooted: parent.rooted, + segments: [...parent.segments, ident], + }); + } + + return Result.succeed(entry); + }; + + return mapEntries>(entries, resolve); +}; + /** * Binds new declarations and retains existing exports by identity. * @@ -142,17 +222,34 @@ const bind = ( * Invalid paths, export names and generic arities return construction failures. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the module under construction -export const define = ( +export function define( name: string, - definition: Shape, -): Result.Result, ProgramError.Construction> => - Result.gen(function* () { - const path = yield* Result.mapError( + definition: S, +): Result.Result, ProgramError.Construction>; +export function define< + M extends Namespace, + T extends Namespace, + V extends Namespace, +>( + name: string, + definition: { + readonly modules?: M; + readonly types?: Declarations; + readonly values?: Declarations; + }, +): Result.Result< + Bound, + ProgramError.Construction +> { + return Result.gen(function* () { + const path = yield* pipe( JExpr.Path.decodeResult(name), - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidModulePath({ name, cause }), - }), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidModulePath({ name, cause }), + }), + ), ); if (!path.rooted) { @@ -163,22 +260,20 @@ export const define = ( ); } - for (const child of Object.keys(definition.modules ?? {})) { - yield* memberName(child); + let modules: Readonly | Empty = Object.freeze({}); + if (definition.modules !== undefined) { + modules = yield* copyModules(definition.modules); } - const module = Object.freeze({ - [TypeId]: true, + return Object.freeze({ + [TypeId]: true as const, path, - modules: Object.freeze({ ...definition.modules }), - types: yield* bind(path, definition.types ?? {}), - values: yield* bind(path, definition.values ?? {}), + modules, + types: yield* bind(path, definition.types), + values: yield* bind(path, definition.values), }); - - // SAFETY: binding changes each Declaration into A without changing any key or existing export. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the heterogeneous mapping preserves each declaration result - return module as Module; }); +} /** Rebinds a module and its exports beneath a locally imported module name. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- internal module rebinding requires both the module and its local path @@ -192,14 +287,7 @@ export const relocate = ( const types: [string, TypeExpression.Export][] = []; for (const [name, child] of Object.entries(module.modules)) { - const ident = yield* JExpr.Ident.decodeResult(name).pipe( - Result.mapError( - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidExportName({ name, cause }), - }), - ), - ); + const ident = yield* memberName(name); modules.push([ name, @@ -211,14 +299,7 @@ export const relocate = ( } for (const name of Object.keys(module.values)) { - const ident = yield* JExpr.Ident.decodeResult(name).pipe( - Result.mapError( - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidExportName({ name, cause }), - }), - ), - ); + const ident = yield* memberName(name); values.push([ name, @@ -232,14 +313,7 @@ export const relocate = ( } for (const [name, type] of Object.entries(module.types)) { - const ident = yield* JExpr.Ident.decodeResult(name).pipe( - Result.mapError( - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidExportName({ name, cause }), - }), - ), - ); + const ident = yield* memberName(name); types.push([ name, @@ -260,16 +334,14 @@ export const relocate = ( }); /** Assembles already-bound modules without rebasing their references. */ -export const root = >( - modules: Modules, +export const root = >( + modules: M, ): Result.Result< - { readonly modules: Readonly }, + { readonly modules: Readonly }, ProgramError.Construction > => - Result.gen(function* () { - for (const name of Object.keys(modules)) { - yield* memberName(name); - } - - return Object.freeze({ modules: Object.freeze({ ...modules }) }); - }); + pipe( + modules, + copyModules, + Result.map((bound) => Object.freeze({ modules: bound })), + ); From 563f5572b74f26ba3e9049c72f4c28628bfc6132 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:39:34 +0200 Subject: [PATCH 06/22] feat: add synchronous draft authoring API --- libs/@local/hashql/sdk/typescript/README.md | 34 +- .../hashql/sdk/typescript/docs/authoring.md | 103 +++- .../typescript/examples/api-tour.test-d.ts | 5 +- .../@local/hashql/sdk/typescript/package.json | 4 + .../hashql/sdk/typescript/src/do/Do.test.ts | 44 +- .../hashql/sdk/typescript/src/do/Import.ts | 12 +- .../hashql/sdk/typescript/src/do/Utilities.ts | 6 +- .../hashql/sdk/typescript/src/draft/Body.ts | 140 +++++ .../src/draft/Construction.test-d.ts | 126 +++++ .../typescript/src/draft/Construction.test.ts | 124 +++++ .../sdk/typescript/src/draft/Context.ts | 135 +++++ .../sdk/typescript/src/draft/Draft.test-d.ts | 180 +++++++ .../sdk/typescript/src/draft/Draft.test.ts | 486 +++++++++++++++++ .../typescript/src/draft/Namespace.test.ts | 98 ++++ .../src/draft/Requirements.test-d.ts | 265 +++++++++ .../hashql/sdk/typescript/src/draft/Scribe.ts | 421 +++++++++++++++ .../sdk/typescript/src/draft/fixtures.ts | 54 ++ .../hashql/sdk/typescript/src/draft/index.ts | 204 ++++--- .../sdk/typescript/src/internal/relocation.ts | 36 ++ .../sdk/typescript/src/playground.test-d.ts | 247 --------- .../sdk/typescript/src/playground.test.ts | 202 ------- .../hashql/sdk/typescript/src/playground.ts | 60 --- .../src/program/Expression.test-d.ts | 10 +- .../typescript/src/program/Expression.test.ts | 20 +- .../sdk/typescript/src/program/Expression.ts | 143 +++-- .../typescript/src/program/ExpressionType.ts | 9 +- .../typescript/src/program/Inputs.test-d.ts | 61 +++ .../sdk/typescript/src/program/Inputs.ts | 57 +- .../typescript/src/program/Module.test-d.ts | 42 +- .../sdk/typescript/src/program/Module.test.ts | 76 +++ .../sdk/typescript/src/program/Module.ts | 158 +++--- .../src/program/Namespace.test-d.ts | 170 ++++++ .../typescript/src/program/Namespace.test.ts | 232 ++++++++ .../sdk/typescript/src/program/Namespace.ts | 509 ++++++++++++++++++ .../sdk/typescript/src/program/Prelude.ts | 139 +++++ .../typescript/src/program/PreludeTypes.ts | 50 ++ .../typescript/src/program/ProgramError.ts | 14 + .../sdk/typescript/src/program/Query.ts | 113 ++-- .../sdk/typescript/src/program/Scope.ts | 94 +++- .../src/program/Structural.test-d.ts | 18 + .../typescript/src/program/Structural.test.ts | 29 + .../sdk/typescript/src/program/Structural.ts | 24 +- .../typescript/src/program/TypeExpression.ts | 206 ++++--- 43 files changed, 4283 insertions(+), 877 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Body.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Context.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/internal/relocation.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/playground.test-d.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/playground.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/playground.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Namespace.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Prelude.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 46cbc16d3f7..8b538dd9ede 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -2,10 +2,42 @@ The SDK constructs HashQL query syntax. TypeScript checks the authoring API. The HashQL compiler resolves names and checks the emitted program. `JExpr` provides the low-level expression builders and serializer. Construction does not execute the query. -Import shared types, expressions and `Program` from `@local/hashql`, and Do authoring calls from `@local/hashql/do`. The shared `program` constructor wraps the resulting expression. +Import shared types, expressions, `Prelude` and `Program` from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`, or the executed Draft builder from `@local/hashql/draft`. Both produce expressions that the shared `program` constructor wraps. Start with the [authoring guide](docs/authoring.md). It provides a complete construction example, focused API examples and rules for developers and coding agents. +## Draft authoring + +Draft executes one synchronous callback. Declarations accumulate around the returned expression, and the explicit input schema supplies the whole program's input contract, including unused entries and discarded declaration initializers. + +```ts +import { Result } from "effect"; +import { Prelude, Program } from "@local/hashql"; +import { program } from "@local/hashql/draft"; + +const identity = Symbol("Count"); +const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { + const Count = $.newtype("Count", identity, BigInt); + const value = $.let("value", Count(inputs.count)); + return $.ifElse( + true, + () => value, + () => Count(0n), + ); +}); +const compiled = Result.flatMap(built, (expression) => + Program.compile(Program.program(expression)), +); +``` + +`$.type(name, definition)` accepts type expressions or structural shorthand. `$.newtype(name, uniqueSymbol, definition)` returns a type and callable nominal constructor together; for example, `const identity = Symbol("Foo"); const Foo = $.newtype("Foo", identity, { foo: BigInt }); Foo({ foo: 2n })`. Records describe structs, arrays describe tuples, and `List(BigInt)` and `Dict(String, BigInt)` describe collections. `number` remains Number, while `bigint` is Integer. + +`$.ifElse(condition, thenCallback, elseCallback)` supplies each branch its own context. The direct `{ then, else }` form accepts already-built values. Both callbacks construct syntax. HashQL chooses the runtime branch. Use the predicate context for declarations inside a filter. Capturing an outer context can place a declaration outside the vertex's scope. HashQL performs lexical resolution and rejects free references. + +Draft's default prelude contains primitive types, List/Dict, Uuid, EntityUuid, `eq` and `add`. It demonstrates declaration-table composition rather than mirroring the complete standard library. Draft's `withPrelude(definition)` returns `{ program }` and replaces these defaults. A custom `entities` declaration supplies the query entry point. The default has none. Do's default remains empty. See the [Draft reference](docs/authoring.md#draft-executed-authoring) for coverage and source definitions. + +Construction failures are Results. Synchronous user exceptions propagate unchanged. TypeScript rejects async callbacks. Draft continues executing a synchronous callback after a declaration fails and reports the accumulated failure at its end. + ## Do authoring Do authoring uses separate module, value and type environments. A value and a type can have the same name. Each step receives `$` plus the environments it needs: diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md index e88cd9a3a26..344d3e87ec8 100644 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -2,7 +2,7 @@ The `@local/hashql` package builds HashQL programs from TypeScript. You describe the HashQL modules a program uses and compose expressions from typed handles. The SDK then serializes the result to J-Expr, the JSON syntax the HashQL compiler reads. The SDK neither runs nor compiles a query. It gives you typed composition and a syntax tree, and the HashQL compiler decides whether that tree is a valid program. -Shared types, expressions and `Program` come from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`. The resulting expressions use the same shared representation. +Shared types, expressions, `Prelude` and `Program` come from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`, or use [Draft](#draft-executed-authoring) from `@local/hashql/draft`. The resulting expressions use the same shared representation. This guide starts with one complete program and then works through each part of the API with focused examples. The [authoring rules](#authoring-rules) at the end condense it into rules that a person or a coding agent can follow while writing a program. @@ -97,6 +97,105 @@ On success the program prints this J-Expr, shown here with line breaks: ] ``` +## Draft: executed authoring + +`program(inputTypes, ($, inputs) => expression)` executes its callback once and returns a construction Result. The second callback argument receives typed input expressions for the schema entries. Serialization never reruns the callback. Draft does not translate JavaScript source. + +```ts +import { Result } from "effect"; +import { Prelude, Program } from "@local/hashql"; +import { program, withPrelude } from "@local/hashql/draft"; + +const identity = Symbol("Foo"); +const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { + const Foo = $.newtype("Foo", identity, { foo: BigInt }); + const value = $.let("value", Foo({ foo: inputs.count })); + return $.ifElse( + true, + (branch) => branch.let("selected", value), + () => value, + ); +}); +const compiled = Result.flatMap(built, (expression) => + Program.compile(Program.program(expression)), +); +const custom = withPrelude({ types: { Count: Prelude.builtin.types.Integer } }); +const closed = custom.program({}, ($) => $.literal(1n)); +``` + +`withPrelude` returns `{ program }`, preserving the supplied module, value and type keys. It replaces the default prelude rather than extending it. `$.prelude()` flattens those three namespaces. Colliding type and value exports retain both capabilities on a fresh handle. The original exports are not mutated. Callable generic types dispatch on type arguments, and callable values on value arguments. If an argument has both capabilities, the result can retain both too. `$.modules()` offers flattened module access while each module still exposes its separate `types`, `values` and `modules` records. Namespace metadata takes precedence over same-spelled direct value fields: use `$project("syntax")` for a value field colliding with type syntax, and the separate namespace records for exports whose names collide with `path`, `types`, `values` or `modules`. Exports and projected fields called `then` remain directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Joined expressions reserve `$`, `$project` and `$index` for expression operations. Function intrinsics such as `name` and `length` do not replace module exports. + +### Declarations and structural shorthand + +- `$.let(name, expressionOrPrimitive)` emits a value binding and returns a reference. An unused binding still emits its initializer. +- `$.type(name, definition)` emits an alias and returns its type expression. +- `$.newtype(name, identity, definition)` emits a nominal declaration and returns its type expression together with a callable value constructor. Give each distinct declaration its own `unique symbol`, even when names coincide. The constructor returns the nominal type, not its representation. + +Definitions accept runtime type expressions, `BigInt`, `Number`, `String`, `Boolean`, records of definitions and tuples of definitions. The host constructors denote Integer, Number, String and Boolean respectively. Default `List` and `Dict` type constructors normalize the same shorthand: `List({ count: BigInt })` and `Dict(String, BigInt)` are valid. The kernel exports List and Dict only in its type namespace. + +Nominal constructors accept their exactly typed underlying expression or structural value, such as `Foo({ foo: 2n })`. Nested expressions keep their input requirements. TypeScript rejects wrong fields, missing fields and extra fields. The SDK does not widen semantic types implicitly. Shared `Structural.type(definition)` normalizes a type outside Draft, and `Structural.value()(value)` constructs an exactly typed struct or tuple expression. This shorthand does not implicitly unwrap nominal values or convert arrays into lists. + +### Explicit input contracts + +The output requirement record contains **every schema entry**, even when the body never uses an input. Draft checks emitted initializers, conditional branches, predicate bodies and the final expression against that schema. External expressions are usable when the schema declares every required or optional input they carry with the same semantic type. An undeclared input in a discarded `$.let` initializer is a type error, not a closed program. Merely constructing and dropping a handle emits no syntax. + +Every schema entry remains required in the result, including inputs whose uses all supply defaults. A host-side union of schemas requires the entries from every alternative, even an alternative containing no entries. `{}` produces `Inputs.Empty`. Keep expression requirements inferred or explicitly typed: `Expression.Any` and `Expression.Value` erase them and cannot prove a Draft input contract. Composition preserves that uncertainty rather than turning it into `Inputs.Empty`. Draft adds no runtime host-input validator. Trusted raw-syntax constructors and explicit type assertions can lie about requirements. They remain trust boundaries rather than proofs. + +### Branches, queries and failures + +Use `$.ifElse(condition, thenCallback, elseCallback)` for child declaration contexts. Both callbacks run during construction. The direct `$.ifElse(condition, { then, else })` form accepts already-built values and does not create a declaration scope around their earlier construction. + +A custom prelude supplies `$.query.entities` when its `entities` value returns a `::graph::Graph` opaque type with a vertex marker. Its signature determines the query arguments and vertex descriptor. The filter callback receives a predicate context first. This illustrative declaration uses an example module, not the graph service's schema: + +```ts +import { Result } from "effect"; +import { Module, Structural } from "@local/hashql"; +import { withPrelude } from "@local/hashql/draft"; +import type { Type } from "@local/hashql"; + +type Vertex = Type.Struct<{ readonly archived: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "\'marker": Vertex }> +>; +const graph = Result.getOrThrow( + Module.define("::example::graph", { + values: { + entities: + Module.value>(), + }, + }), +); +const { program } = withPrelude(graph); +const selected = program({ axis: Structural.type(BigInt) }, ($, inputs) => + $.query + .entities(inputs.axis) + .filter("vertex", (predicate, vertex) => { + const archived = predicate.let("archived", vertex.archived); + return archived.$.isFalse(); + }) + .collect(), +); +``` + +Declarations made through `predicate` stay inside the emitted filter closure. Capturing `$` from the outer callback instead still addresses the outer context. Likewise, JavaScript can save a branch-local reference and return it elsewhere. Draft does not reject those host-reference escapes: the HashQL compiler owns lexical resolution. Keep declarations on the context of the branch or predicate that uses them. Nested and reentrant programs have independent declaration state. + +Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Draft continues executing the synchronous callback after such a failure. A user-thrown synchronous exception propagates unchanged. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. + +### Default prelude coverage and authority + +`Prelude.builtin` contains representative declarations rather than a complete standard-library catalogue. Their export types derive from the declaration tables in [`Prelude.ts`](../src/program/Prelude.ts). [`PreludeTypes.ts`](../src/program/PreludeTypes.ts) supplies the nominal identities and generic semantic operations. Generated tables can use the same `Module.define` and `withPrelude` APIs. This package has no generator. + +| Exports | Compiler source under `core/src/module/std_lib/` | +| --------------------------------------------------------------------------- | ------------------------------------------------ | +| Integer, Number, String, Boolean, Null, Unknown, Never; List and Dict types | `kernel/type.rs` | +| `eq` | `core/cmp.rs` | +| `add` | `core/math.rs` | +| Uuid type and constructor | `core/uuid.rs` | +| EntityUuid type and constructor | `graph/types/knowledge/entity.rs` | + +The free `eq` function accepts independent argument types. The receiver `.$.eq` remains an exact-type operation. `add` accepts Integer or Number arguments and returns their union, reducing equal descriptors to that descriptor. The SDK never converts Integer to Number implicitly. Module routes are `entity`, `uuid`, `cmp` and `math`. Graph queries and temporal declarations must come from a custom prelude. Do still starts with empty environments. + ## Shared declarations for the examples The remaining examples are shorter. Each assumes the imports and declarations below, and states any further declarations it needs beside its own code. @@ -185,7 +284,7 @@ These records are the only place where one JavaScript object describes more than `Module.define` returns a `Result`. A relative path, an invalid path or an invalid export name produces a construction failure. `Module.root` assembles already defined modules into a tree and also returns a `Result`. Both copy and freeze their records, so later changes to your objects don't change a module. -A declaration is a trusted annotation. The package includes no standard library, so you write declarations for the parts of HashQL a program uses, including the graph functions a query needs. The compiler checks the emitted program against the real definitions. Generated declarations must take their types from the definitions they describe. +A declaration is a trusted annotation. Beyond the bounded [Draft prelude](#default-prelude-coverage-and-authority), write declarations for the parts of HashQL a program uses. The Do examples below keep their explicit fixtures. The compiler checks the emitted program against the real definitions. Generated declarations must take their types from the definitions they describe. A module's values are expressions that refer to their absolute path. You can use them through `$.ref` without importing anything: diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts index 443c308611b..d87d0910252 100644 --- a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -281,10 +281,7 @@ describe("expressions", () => { typeof person.archived >(); - // Limitation: direct `then` access would make every handle look like a Promise. - // @ts-expect-error The SDK reserves `then`. - expectTypeOf(person.then); - // Workaround: project the field explicitly. + expectTypeOf(person.then).toEqualTypeOf>(); expectTypeOf(person.$project("then")).toEqualTypeOf< Closed >(); diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json index b33b53909a1..463669fcd72 100644 --- a/libs/@local/hashql/sdk/typescript/package.json +++ b/libs/@local/hashql/sdk/typescript/package.json @@ -13,6 +13,10 @@ "types": "./dist/main.d.ts", "default": "./dist/main.js" }, + "./draft": { + "types": "./dist/draft/index.d.ts", + "default": "./dist/draft/index.js" + }, "./do": { "types": "./dist/do/index.d.ts", "default": "./dist/do/index.js" diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts index 461dea275ad..4a56e7baf04 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts @@ -3,10 +3,8 @@ * * @module */ -// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments -import { Result } from "effect"; +import { Result, pipe } from "effect"; import { assert, describe, expect, test } from "vitest"; import { Expression, Module, Program, program } from "../main.js"; @@ -19,7 +17,6 @@ import { Type as AstType } from "../program/ast/Type.js"; import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; import type { Inputs, Type } from "../main.js"; -import type { Node } from "../program/ast/Node.js"; const initialValue = 7; const fractionalValue = 1.5; @@ -50,7 +47,11 @@ describe("construction", () => { return copy; }, ); - const tree = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); + const tree = pipe( + root, + Result.flatMap(Expression.toNode), + Result.getOrThrow, + ); expect(tree).toBeInstanceOf(AstLet); expect(tree.compile()).toStrictEqual([ "::kernel::special_form::let", @@ -63,9 +64,6 @@ describe("construction", () => { ["::kernel::special_form::let", "value", { "#literal": "new" }, "copy"], ], ]); - expect(Program.compile(program(Result.getOrThrow(root)))).toStrictEqual( - Program.compile(program(Result.getOrThrow(root))), - ); expect(calls).toStrictEqual(["value", "copy", "body"]); assert.instanceOf(tree, AstLet); expect(tree.child).toBeInstanceOf(AstLet); @@ -80,8 +78,12 @@ describe("construction", () => { Let("id", ($, { Id }) => Id($.integer(initialValue))), (_, { id }) => id, ); - const imported = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); - assert.instanceOf>(imported, AstImport); + const imported = pipe( + root, + Result.flatMap(Expression.toNode), + Result.getOrThrow, + ); + assert.instanceOf>(imported, AstImport); const tree = imported.child; expect(tree).toBeInstanceOf(AstType); expect(tree.compile()).toStrictEqual([ @@ -323,8 +325,12 @@ describe("branches", () => { }, ), ); - const imported = Result.getOrThrow(Result.flatMap(root, Expression.toNode)); - assert.instanceOf>(imported, AstImport); + const imported = pipe( + root, + Result.flatMap(Expression.toNode), + Result.getOrThrow, + ); + assert.instanceOf>(imported, AstImport); const tree = imported.child; expect(tree.compile()).toStrictEqual([ "::kernel::special_form::let", @@ -370,7 +376,7 @@ describe("branches", () => { ), ); expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + pipe(root, Result.flatMap(Expression.toJExpr), Result.getOrThrow), ).toStrictEqual([ "::kernel::special_form::if", { "#literal": true }, @@ -398,7 +404,7 @@ describe("expressions", () => { (_, values) => values["%"], ); expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), + pipe(root, Result.flatMap(Expression.toJExpr), Result.getOrThrow), ).toStrictEqual([ "::kernel::special_form::let", "`%`", @@ -419,10 +425,16 @@ describe("expressions", () => { expect.hasAssertions(); const root = EmptyDo(($) => $.integer(initialValue)); expect( - Result.getOrThrow(Result.flatMap(root, Expression.toNode)), + pipe(root, Result.flatMap(Expression.toNode), Result.getOrThrow), ).toBeInstanceOf(Expr); expect( - Result.getOrThrow(Program.compile(program(Result.getOrThrow(root)))), + pipe( + root, + Result.getOrThrow, + program, + Program.compile, + Result.getOrThrow, + ), ).toBe('{"#literal":7}'); }); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts index df43cce90f2..c8bd1789e75 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.ts @@ -1,3 +1,10 @@ +/** + * Lexical imports shared by the Do authoring operations. + * + * The emitted import binds selected names locally. Export handles receive those local paths while retaining the module's declared types. The compiler resolves the import itself. + * + * @module + */ // oxlint-disable import/max-dependencies -- an import updates the module, type and value universes together import { Result } from "effect"; @@ -127,7 +134,10 @@ export function Import( const type = module.types[name]; if (type !== undefined) { - types.push([alias, yield* TypeExpression.relocate(type, path)]); + types.push([ + alias, + yield* TypeExpression.relocate(type, path), + ]); } } diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index 0ea0787da45..df59e5faf56 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -122,18 +122,18 @@ export class Block { ); } - Import( + Import>( select: (utilities: Utilities, modules: S["modules"]) => M, ): Block, Inputs>; Import< - M extends Scope.Scope["modules"][string], + M extends NonNullable, const Imports extends Selection, >( select: (utilities: Utilities, modules: S["modules"]) => M, imports: Imports, ): Block>, Inputs>; Import< - M extends Scope.Scope["modules"][string], + M extends NonNullable, const Imports extends Selection, >( select: (utilities: Utilities, modules: S["modules"]) => M, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts new file mode 100644 index 00000000000..5e8d90739ff --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts @@ -0,0 +1,140 @@ +/** + * The explicit-input policy of a Draft program callback. + * + * Every operation that emits a value checks its requirements, including discarded let initializers and nested callback bodies. This policy belongs to the program boundary rather than Context: the constructor implementation can accept more values than a particular program permits. The result conservatively requires the entire supplied schema, including unused entries. + * + * @module + */ +import type * as Expression from "../program/Expression.js"; +import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; +import type * as Input from "../program/Inputs.js"; +import type * as Scope from "../program/Scope.js"; +import type * as TypeExpression from "../program/TypeExpression.js"; +import type * as Type from "../type/index.js"; +import type * as Construction from "./Context.js"; +import type { ReadonlyRecord } from "effect/Record"; + +export type Inputs = ReadonlyRecord; +type TypeInputs = { + readonly [K in keyof I]: I[K] extends TypeExpression.TypeExpression + ? T + : never; +}; +export type Requirements = Input.Conservative>; +export type Handle = + D extends TypeExpression.TypeExpression + ? Expression.Expression>> + : never; +export type Handles = { + readonly [K in keyof I]: Handle; +}; + +// oxlint-disable-next-line typescript/no-restricted-types -- distributes the check over host alternatives without erasing any input record +type Mismatches = I extends unknown + ? { + [K in keyof I]-?: K extends keyof S + ? [S[K]] extends [Exclude] + ? [Exclude] extends [S[K]] + ? never + : K + : K + : K; + }[keyof I] + : never; + +/** All host alternatives must fit the schema. Erased requirements cannot prove that. */ +export type Check = [I] extends [never] + ? never + : [Mismatches>] extends [never] + ? // oxlint-disable-next-line typescript/no-restricted-types -- unknown is the identity of an accepted intersection constraint + unknown + : never; +type Accept = Check>; + +type Query< + S extends Scope.Scope, + I, + T extends Type.Any, + V extends Type.Any, + R, +> = Expression.Expression & { + readonly filter: >( + name: string, + predicate: ( + $: Context, + vertex: Expression.Expression, + ) => P & Accept, + ) => Query>>; + readonly collect: () => Expression.Expression, R>; +}; + +type EntityFunction = Construction.EntityFunction; +type QueryContext = [EntityFunction] extends [ + never, +] + ? // oxlint-disable-next-line typescript/no-generated-empty-object-type -- no graph declaration means no query entry point + Record + : { + readonly entities: < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, + >( + ...args: A & + Check["inputs"], ArgumentInputs>> + ) => Query< + S, + I, + EntityFunction["returns"], + EntityFunction["vertex"], + Input.Merge["inputs"], ArgumentInputs> + >; + }; + +/** A restricted view that the unrestricted constructor implements. */ +export interface Context extends Omit< + Construction.Context, + "let" | "ifElse" | "query" +> { + readonly let: ( + name: string, + value: E & Accept, + ) => Expression.Expression, Expression.Inputs>; + readonly query: QueryContext; + readonly ifElse: { + < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C & Accept, + branches: { + readonly then: T & Accept; + readonly else: E & Accept; + }, + ): Construction.Conditional; + < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C & Accept, + then: ($: Context) => T & Accept, + otherwise: ($: Context) => E & Accept, + ): Construction.Conditional; + }; +} + +export type Body< + S extends Scope.Scope, + I extends Inputs, + O extends Expression.AnyValue & Expression.Any, +> = ( + $: Context>, + inputs: Handles, +) => O & Check>, Expression.Inputs>; + +export type WithoutInputs< + S extends Scope.Scope, + I extends Inputs, + O extends Expression.AnyValue & Expression.Any, +> = ($: Context>) => ReturnType>; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts new file mode 100644 index 00000000000..ef153714ff1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts @@ -0,0 +1,126 @@ +/** Type relationships across Draft construction and its explicit-input boundary. @module */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Structural, + TypeExpression, +} from "../main.js"; +import * as Namespace from "../program/Namespace.js"; +import * as Scope from "../program/Scope.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type } from "../main.js"; +import type * as Context from "./Context.js"; + +const integer = Structural.type(BigInt); +const outside = Expression.input("outside", integer); +const unrestricted = ( + $: Context.Context, +): Expression.Expression => { + expectTypeOf($.let("outside", outside)).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly outside: Type.PrimitiveInteger } + > + >(); + return $.literal(true); +}; +const optionalPrelude = (): { + readonly types?: { readonly Integer: typeof integer }; +} => ({ types: { Integer: integer } }); + +const optionalValue = (): { + readonly value?: Expression.Expression; +} => ({}); + +describe("construction_types", () => { + test("optional_override", () => { + const base = Scope.merge(Scope.empty, { + values: { value: Expression.integer(1) }, + }); + const merged = Scope.merge(base, { values: optionalValue() }); + expectTypeOf(merged.values.value).toEqualTypeOf< + | Expression.Expression + | Expression.Expression + | undefined + >(); + }); + + test("policy_separation", () => { + // @ts-expect-error an unrestricted helper can hide inputs in discarded declarations + Draft.withPrelude({}).program({}, unrestricted); + expectTypeOf(unrestricted); + }); + + test("optional_namespace", () => { + Draft.withPrelude(optionalPrelude()).program({}, ($) => { + expectTypeOf($.prelude().Integer).toEqualTypeOf< + typeof integer | undefined + >(); + expectTypeOf($.prelude()).not.toHaveProperty("Missing"); + return $.literal(true); + }); + }); + + test("nominal_rebinding", () => { + const identity = Symbol("Box"); + Draft.program({ outside: integer }, ($) => { + const Box = $.newtype("Box", identity, { value: BigInt }); + expectTypeOf>().toEqualTypeOf< + Type.Function< + readonly [Type.Struct<{ readonly value: Type.PrimitiveInteger }>], + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + > + >(); + type Constructor = Type.Function< + readonly [Type.Struct<{ readonly value: Type.PrimitiveInteger }>], + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + >; + const bound = $.let("constructor", Box); + expectTypeOf< + Expression.TypeOf + >().toEqualTypeOf(); + const pass = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("::test::pass"); + const passed = pass(Box); + expectTypeOf< + Expression.TypeOf + >().toEqualTypeOf(); + const module = Result.getOrThrow( + Module.define("::test", { types: { Box }, values: { Box } }), + ); + const names = Namespace.flatten(module); + const moved = Result.getOrThrow( + TypeExpression.relocate( + names.Box, + Result.getOrThrow(JExpr.Path.decodeResult("::local::Box")), + ), + ); + const value = moved({ value: outside }); + expectTypeOf>().toEqualTypeOf< + Type.Opaque< + typeof identity, + Type.Struct<{ readonly value: Type.PrimitiveInteger }> + > + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + // @ts-expect-error rebinding must not widen nominal structure + moved({ value: "wrong" }); + return value; + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts new file mode 100644 index 00000000000..847de2b2a38 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts @@ -0,0 +1,124 @@ +/** Boundary and rebinding checks for executed Draft construction. @module */ +import { Result, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Structural, + TypeExpression, +} from "../main.js"; +import * as Namespace from "../program/Namespace.js"; +import * as Draft from "./index.js"; + +const integer = Structural.type(BigInt); +const compile = (expression: Expression.Any): string => + pipe( + expression, + Expression.toJExpr, + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_construction", () => { + test("symbol_input", () => { + expect.hasAssertions(); + const key = Symbol("input"); + let visits = 0; + const result = Draft.program({ [key]: integer }, ($) => { + visits += 1; + return $.literal(true); + }); + expect(Result.getFailure(result)).toMatchObject({ + _tag: "Some", + value: { reason: { _tag: "SymbolInputName", name: key } }, + }); + expect(visits).toBe(0); + }); + + test("symbol_export", () => { + expect.hasAssertions(); + const name = Symbol("export"); + const { program } = Draft.withPrelude({ + values: { + // @ts-expect-error exercise a symbol export from an unchecked caller + [name]: Expression.integer(1), + }, + }); + let visits = 0; + const result = program({}, ($) => { + visits += 1; + return $.literal(true); + }); + expect(Result.getFailure(result)).toMatchObject({ + _tag: "Some", + value: { reason: { _tag: "SymbolExportName", name } }, + }); + expect(visits).toBe(0); + }); + + test("input_own_names", () => { + expect.hasAssertions(); + const schema = { count: integer, ["__proto__"]: integer }; + Object.defineProperty(schema, "count", { enumerable: false }); + const result = Draft.program(schema, ($, inputs) => { + expect(Object.getPrototypeOf(inputs)).toBe(Object.prototype); + expect(Object.hasOwn(inputs, "count")).toBe(true); + $.let("count", inputs.count); + // oxlint-disable-next-line eslint/no-proto -- this is a declared HashQL input, not the JavaScript prototype accessor + return inputs.__proto__; + }); + expect(compile(Result.getOrThrow(result))).toContain('"__proto__"'); + }); + + test("prelude_snapshot", () => { + expect.hasAssertions(); + const first = Expression.integer(1); + const values = { value: first }; + Object.defineProperty(values, "value", { enumerable: false }); + const { program } = Draft.withPrelude({ values }); + expect(Object.isFrozen(values)).toBe(false); + values.value = Expression.integer(2); + const result = program({}, ($) => $.prelude().value); + expect(compile(Result.getOrThrow(result))).toBe('{"#literal":1}'); + }); + + test("nominal_relocation", () => { + expect.hasAssertions(); + const identity = Symbol("Box"); + const result = Draft.program({}, ($) => { + const Box = $.newtype("Box", identity, { value: BigInt }); + const module = pipe( + Module.define("::test", { types: { Box }, values: { Box } }), + Result.getOrThrow, + ); + const joined = Namespace.flatten(module).Box; + const first = pipe( + joined, + TypeExpression.relocate( + Result.getOrThrow(JExpr.Path.decodeResult("::first::Box")), + ), + Result.getOrThrow, + ); + const moved = pipe( + first, + TypeExpression.relocate( + Result.getOrThrow(JExpr.Path.decodeResult("::second::Box")), + ), + Result.getOrThrow, + ); + expect(Expression.isExpression(moved)).toBe(true); + expect(TypeExpression.isExport(moved)).toBe(true); + expect(Result.getOrThrow(TypeExpression.toType(moved))).toStrictEqual({ + _tag: "Reference", + path: Result.getOrThrow(JExpr.Path.decodeResult("::second::Box")), + generics: [], + }); + return moved({ value: 2n }); + }); + expect(compile(Result.getOrThrow(result))).toContain( + '["::second::Box",{"#struct":{"value":{"#literal":2}}}]', + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts new file mode 100644 index 00000000000..03105f439e6 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -0,0 +1,135 @@ +/** + * Typed construction operations inside a synchronous Draft callback. + * + * Context preserves each operation's semantic type and input requirements. It does not select an input policy: the program callback contract checks declarations against its explicit input schema. Nested callbacks receive fresh declaration collectors with the same prelude. + * + * @module + */ +import type { Relocatable, Relocate } from "../internal/relocation.js"; +import type * as Expression from "../program/Expression.js"; +import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; +import type * as Inputs from "../program/Inputs.js"; +import type * as Namespace from "../program/Namespace.js"; +import type * as QueryTypes from "../program/Query.js"; +import type * as Scope from "../program/Scope.js"; +import type * as Structural from "../program/Structural.js"; +import type * as TypeExpression from "../program/TypeExpression.js"; +import type * as Type from "../type/index.js"; + +export type NominalCall = < + const V extends Structural.Value & Structural.AnyValue, +>( + value: Structural.Exact, +) => Expression.Expression, Structural.Requirements>; + +/** Each constructor has one rebinding result rather than an intersection of recursive overloads. */ +export interface NominalValue + extends Expression.Any, NominalCall { + readonly $: Expression.Expression< + Type.Function>, + Inputs.Empty + >["$"]; + readonly "~hashql/Expression": Expression.Handle< + Type.Function>, + Inputs.Empty + >["~hashql/Expression"]; + readonly [Relocate]: Relocatable>[typeof Relocate]; +} + +export type Nominal = Namespace.Joined< + NominalValue, + TypeExpression.TypeExpression> +>; + +export type Query< + S extends Scope.Scope, + T extends Type.Any, + V extends Type.Any, + I, +> = Expression.Expression & { + readonly filter: >( + name: string, + predicate: ( + $: Context, + vertex: Expression.Expression, + ) => P, + ) => Query>>; + readonly collect: () => Expression.Expression, I>; +}; + +export type EntityFunction = + QueryTypes.EntityFunction; + +export type Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, +>( + ...args: A +) => Query< + S, + EntityFunction["returns"], + EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> +>; + +export type QueryContext = [EntityFunction] extends [ + never, +] + ? // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without a graph declaration supplies no query entry point + Record + : { readonly entities: Entities }; + +export type Branches< + S extends Scope.Scope, + T extends Expression.AnyValue, + E extends Expression.AnyValue, +> = + | readonly [branches: { readonly then: T; readonly else: E }] + | readonly [then: ($: Context) => T, otherwise: ($: Context) => E]; + +export type Conditional< + C extends Expression.Value, + T extends Expression.AnyValue, + E extends Expression.AnyValue, +> = Expression.Expression< + Expression.Conditional, Expression.TypeOf>, + Inputs.Merge< + Expression.Inputs, + Inputs.Merge, Expression.Inputs> + > +>; + +export interface Context { + readonly prelude: () => Namespace.Flatten; + readonly modules: () => Namespace.Modules; + readonly literal: typeof Expression.literal; + readonly integer: typeof Expression.integer; + readonly number: typeof Expression.number; + readonly assume: typeof Expression.assume; + readonly input: typeof Expression.input; + readonly query: QueryContext; + readonly let: ( + name: string, + value: E, + ) => Expression.Expression, Expression.Inputs>; + readonly type: ( + name: string, + definition: D, + ) => TypeExpression.TypeExpression>; + readonly newtype: < + const N extends symbol, + const D extends Structural.Definition, + >( + name: string, + identity: symbol extends N ? never : N, + definition: D, + ) => Nominal>; + readonly ifElse: < + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C, + ...branches: Branches + ) => Conditional; +} diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts new file mode 100644 index 00000000000..ab59fc6ad8a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts @@ -0,0 +1,180 @@ +import { Result } from "effect"; +// oxlint-disable unicorn/no-thenable -- then is the HashQL conditional-branch key +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude, Structural } from "../main.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type, TypeExpression } from "../main.js"; + +const integer = Structural.type(BigInt); +const string = Structural.type(String); + +// oxlint-disable-next-line typescript/promise-function-async -- this fixture supplies a Promise where the synchronous API rejects one +const asynchronousBody = (): Promise< + Expression.Expression +> => Promise.resolve(Expression.literal(true)); + +const alternative = (left: A, _right: B): A | B => left; + +describe("draft_types", () => { + test("conservative_inputs", () => { + const result = Draft.program( + { count: integer, label: string }, + ($, inputs) => { + expectTypeOf(inputs.count).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveInteger, + { readonly count: Type.PrimitiveInteger } + > + >(); + $.let("discarded", inputs.count); + return $.literal(true); + }, + ); + expectTypeOf(Result.getOrThrow(result)).toEqualTypeOf< + Expression.Expression< + Type.PrimitiveBoolean, + { + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + } + > + >(); + expectTypeOf( + Result.getOrThrow(Draft.program({}, ($) => $.literal(true))), + ).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("schema_checks", () => { + const outside = Expression.input("outside", integer); + const optional = Expression.input("optional", integer, 1n); + // @ts-expect-error undeclared final input + Draft.program({}, () => outside); + Draft.program({}, ($) => { + // @ts-expect-error discarded initializer still requires an input + $.let("lost", outside); + // @ts-expect-error the schema must include optional external inputs + $.let("optional", optional); + $.ifElse( + true, + // @ts-expect-error child final expression contains an undeclared input + () => outside, + () => 1n, + ); + // @ts-expect-error direct branch contains an undeclared input + $.ifElse(true, { then: outside, else: 1n }); + return $.literal(true); + }); + Draft.program({ outside: integer }, ($) => $.let("allowed", outside)); + const selected = alternative(outside, Expression.input("other", integer)); + const composed = Expression.ifElse(true, { then: selected, else: 1n }); + expectTypeOf(composed); + // @ts-expect-error composition cannot erase alternative undeclared inputs + Draft.program({}, ($) => $.let("lostAlternative", composed)); + // @ts-expect-error same input name with incompatible type + Draft.program({ outside: string }, () => outside); + // @ts-expect-error async callbacks do not construct programs + Draft.program({}, asynchronousBody); + }); + + test("nominal_identity", () => { + const identity = Symbol("Foo"); + const otherIdentity = Symbol("Foo"); + Draft.program({ count: integer }, ($, inputs) => { + const Foo = $.newtype("Foo", identity, { foo: BigInt }); + const Other = $.newtype("Foo", otherIdentity, { foo: BigInt }); + const widened: symbol = identity; + // @ts-expect-error a widened symbol cannot supply a distinct nominal identity + $.newtype("Wide", widened, BigInt); + // @ts-expect-error semantic descriptors are not runtime type definitions + $.type("Phantom", { _tag: "Integer" }); + const value = Foo({ foo: inputs.count }); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + // @ts-expect-error primitive host number is not Integer + Foo({ foo: 2 }); + // @ts-expect-error missing structural field + Foo({}); + // @ts-expect-error extra structural field is not an exact ascription + Foo({ foo: 2n, extra: true }); + // @ts-expect-error distinct unique symbols retain nominal identity + const mismatch: typeof value = Other({ foo: inputs.count }); + expectTypeOf(mismatch); + // @ts-expect-error cannot substitute a plain underlying record for nominal value + const underlying: typeof value = $.literal(2n); + expectTypeOf(underlying); + return value; + }); + }); + + test("metadata_types", () => { + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Shared: Module.type() }, + values: { + Shared: + Module.value< + Type.Struct<{ readonly syntax: Type.PrimitiveInteger }> + >(), + }, + }), + ); + Draft.withPrelude(custom).program({}, ($) => { + const { Shared } = $.prelude(); + // @ts-expect-error metadata is a Result, not also an expression handle + const impossible: Expression.Any = Shared.syntax; + expectTypeOf(impossible); + return Shared.$project("syntax"); + }); + }); + + test("prelude_capabilities", () => { + Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + const { Uuid, EntityUuid, eq, add, List, Integer } = $.prelude(); + const comparison = $.let("comparison", EntityUuid(Uuid("uuid"))); + const list = List(Integer); + expectTypeOf(list).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + // @ts-expect-error arithmetic excludes strings + add("one", "two"); + // @ts-expect-error List has one type argument + List(Integer, Integer); + // @ts-expect-error module keys remain precise + expectTypeOf($.modules().uuid.UnknownExport); + const hidden = Expression.input("hidden", Prelude.builtin.types.Boolean); + $.query.entities(inputs.axis).filter( + "vertex", + // @ts-expect-error predicate final expressions must fit the schema + () => hidden, + ); + $.query.entities(inputs.axis).filter("vertex", (predicate) => { + // @ts-expect-error discarded predicate declarations must fit the schema + predicate.let("hidden", hidden); + return true; + }); + // @ts-expect-error nominal constructor requires a Uuid + EntityUuid("uuid"); + return $.query + .entities(inputs.axis) + .filter("vertex", (branch, vertex) => { + const selected = branch.let( + "selected", + vertex.metadata.record_id.entity_id.entity_uuid, + ); + return eq(selected, comparison); + }) + .collect(); + }); + Draft.withPrelude({}).program({}, ($) => { + // @ts-expect-error custom prelude replaces builtins + expectTypeOf($.prelude().Uuid); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts new file mode 100644 index 00000000000..7a96e991384 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts @@ -0,0 +1,486 @@ +import { Result, Schema, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { + Expression, + JExpr, + Module, + Prelude, + Program, + TypeExpression, +} from "../main.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +const compile = ( + result: Result.Result, +): Schema.Json => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + // oxlint-disable-next-line effecttsgo/schema-sync -- malformed emitted JSON must fail this synchronous test helper + Schema.decodeSync(Schema.fromJsonString(Schema.Json)), + ); + +// oxlint-disable-next-line typescript/promise-function-async -- this fixture supplies a Promise where the synchronous API rejects one +const asynchronousBody = (): Promise< + Expression.Expression +> => Promise.resolve(Expression.literal(true)); + +interface IdentitySignature extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.Function + : Type.Function; +} + +const call = (name: string, ...args: readonly Schema.Json[]): Schema.Json => [ + name, + ...args, +]; +const literal = (value: string | number | boolean): Schema.Json => ({ + "#literal": value, +}); + +describe("draft", () => { + test("ordered_declarations", () => { + expect.hasAssertions(); + let calls = 0; + const identity = Symbol("Foo"); + const result = Draft.program({}, ($) => { + calls += 1; + const Count = $.type("Count", BigInt); + const Foo = $.newtype("Foo", identity, { foo: Count }); + const value = $.let("value", Foo({ foo: 2n })); + expect(TypeExpression.isExport(Foo)).toBe(true); + expect(Expression.isExpression(Foo)).toBe(true); + expect(TypeExpression.isExport(Count)).toBe(true); + return value; + }); + const output = Result.getOrThrow( + Program.compile(Program.program(Result.getOrThrow(result))), + ); + expect(JSON.parse(output)).toStrictEqual( + call( + "::kernel::special_form::type", + "Count", + "::kernel::type::Integer", + call( + "::kernel::special_form::newtype", + "Foo", + { "#struct": { foo: "Count" } }, + call( + "::kernel::special_form::let", + "value", + call("Foo", { "#struct": { foo: literal(2) } }), + "value", + ), + ), + ), + ); + compile(result); + expect(calls).toBe(1); + }); + + test("branch_collectors", () => { + expect.hasAssertions(); + const visits: string[] = []; + const result = Draft.program({}, ($) => + $.ifElse( + false, + (branch) => { + visits.push("then"); + return branch.let("inside", branch.literal(1n)); + }, + (branch) => { + visits.push("else"); + return branch.let("other", branch.literal(2n)); + }, + ), + ); + expect(visits).toStrictEqual(["then", "else"]); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::if", + literal(false), + call("::kernel::special_form::let", "inside", literal(1), "inside"), + call("::kernel::special_form::let", "other", literal(2), "other"), + ), + ); + expect( + // oxlint-disable-next-line unicorn/no-thenable -- then is the HashQL conditional-branch key + compile(Draft.program({}, ($) => $.ifElse(true, { then: 1n, else: 2n }))), + ).toStrictEqual( + call("::kernel::special_form::if", literal(true), literal(1), literal(2)), + ); + }); + + test("reentrant_collectors", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const outer = $.let("outer", 1n); + const inner = Draft.program({}, (nested) => nested.let("inner", 2n)); + expect(compile(inner)).toStrictEqual( + call("::kernel::special_form::let", "inner", literal(2), "inner"), + ); + return $.ifElse( + true, + (branch) => + branch.ifElse( + false, + (child) => child.let("deep", outer), + () => outer, + ), + () => outer, + ); + }); + expect(JSON.stringify(compile(result))).not.toContain('"inner"'); + expect(JSON.stringify(compile(result))).toContain('"deep"'); + }); + + test("custom_query_predicate", () => { + expect.hasAssertions(); + const result = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + const { EntityUuid, Uuid, eq } = $.prelude(); + expect($.prelude().Axis).toBe(Fixtures.axis); + expect(TypeExpression.isExport(Uuid)).toBe(true); + expect(Expression.isExpression(Uuid)).toBe(true); + const comparison = $.let( + "comparison", + EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ); + return $.query + .entities(inputs.axis) + .filter("vertex", (predicate, vertex) => { + const selected = predicate.let( + "selected", + vertex.metadata.record_id.entity_id.entity_uuid, + ); + return eq(selected, comparison); + }) + .collect(); + }); + const syntax = JSON.stringify(compile(result)); + expect(syntax).toContain('"::test::graph::entities"'); + expect(syntax).toContain('"::test::graph::Axis"'); + expect(compile(result)).toStrictEqual([ + "::kernel::special_form::let", + "comparison", + expect.anything(), + [ + "::graph::tail::collect", + [ + "::graph::body::filter", + expect.anything(), + [ + "fn", + { "#tuple": [] }, + { "#struct": { vertex: "_" } }, + "_", + [ + "::kernel::special_form::let", + "selected", + expect.anything(), + ["::core::cmp::eq", "selected", "comparison"], + ], + ], + ], + ], + ]); + expect(syntax).toContain('"::core::uuid::Uuid"'); + }); + + test("custom_prelude", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Item: Module.type() }, + values: { + Item: Module.value< + Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + > + >(), + }, + }), + ); + const originalKeys = Reflect.ownKeys(custom.types.Item); + const { program } = Draft.withPrelude(custom); + const result = program({}, ($) => { + const { Item } = $.prelude(); + expect(TypeExpression.isExport(Item)).toBe(true); + expect(Expression.isExpression(Item)).toBe(true); + expect($.prelude()).not.toHaveProperty("Uuid"); + expect(Result.getOrThrow(TypeExpression.toType(Item))).toStrictEqual( + Result.getOrThrow(TypeExpression.toType(custom.types.Item)), + ); + return Item(2n); + }); + expect(compile(result)).toStrictEqual(call("::custom::Item", literal(2))); + expect(Reflect.ownKeys(custom.types.Item)).toStrictEqual(originalKeys); + expect(Object.isFrozen(custom.types)).toBe(true); + }); + + test("generic_value_collision", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value< + Type.Function< + readonly [Type.PrimitiveInteger], + Type.PrimitiveInteger + > + >(), + }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Both } = $.prelude(); + expect(TypeExpression.isExport(Both)).toBe(true); + expect(Expression.isExpression(Both)).toBe(true); + const specialized = Both(Prelude.builtin.types.Integer); + expect(TypeExpression.isExport(specialized)).toBe(true); + expect(Result.getOrThrow(TypeExpression.toType(specialized))._tag).toBe( + "Reference", + ); + return Both(2n); + }); + expect(compile(result)).toStrictEqual(call("::custom::Both", literal(2))); + }); + + test("three_namespace_collision", () => { + expect.hasAssertions(); + const child = Result.getOrThrow( + Module.define("::custom::child", { + types: { Integer: Module.type() }, + }), + ); + const generic = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value>(), + }, + }), + ); + const built = Draft.withPrelude({ + ...generic, + modules: { Both: child }, + }).program({}, ($) => { + const { Both } = $.prelude(); + expect([ + Module.isModule(Both), + TypeExpression.isConstructor(Both), + Expression.isExpression(Both), + ]).toStrictEqual([true, true, true]); + expect([Both.types.Integer, $.modules().Both.Integer]).toStrictEqual([ + child.types.Integer, + child.types.Integer, + ]); + const applied = Both(child.types.Integer); + expect(TypeExpression.isExport(applied)).toBe(true); + const combinedArgument = Draft.withPrelude(Prelude.builtin).program( + {}, + (nested) => { + const result = Both(nested.prelude().Uuid); + expect([ + TypeExpression.isExport(result), + Expression.isExpression(result), + ]).toStrictEqual([true, true]); + return nested.literal(true); + }, + ); + expect(Result.isSuccess(combinedArgument)).toBe(true); + return Both(2n); + }); + expect(compile(built)).toStrictEqual(call("::custom::Both", literal(2))); + }); + + test("nested_nominal_export", () => { + expect.hasAssertions(); + const library = Result.getOrThrow( + Module.define("::custom::library", { + modules: { entity: Prelude.builtin.modules.entity }, + }), + ); + const root = Result.getOrThrow( + Module.define("::custom", { modules: { library } }), + ); + const result = Draft.withPrelude({ + modules: { root }, + values: { Uuid: Prelude.builtin.values.Uuid }, + }).program({}, ($) => { + const EntityUuid = $.modules().root.library.entity.EntityUuid; + expect(TypeExpression.isExport(EntityUuid)).toBe(true); + expect(Expression.isExpression(EntityUuid)).toBe(true); + expect(Module.isModule($.modules().root.library.entity)).toBe(true); + const alias = $.type("Id", EntityUuid); + expect(Result.isSuccess(TypeExpression.toType(alias))).toBe(true); + return EntityUuid($.prelude().Uuid("uuid")); + }); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::type", + "Id", + "::graph::types::knowledge::entity::EntityUuid", + call( + "::graph::types::knowledge::entity::EntityUuid", + call("::core::uuid::Uuid", literal("uuid")), + ), + ), + ); + }); + + test("metadata_projection", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Shared: Module.type() }, + values: { + Shared: + Module.value< + Type.Struct<{ readonly syntax: Type.PrimitiveInteger }> + >(), + }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Shared } = $.prelude(); + expect(Result.isSuccess(Shared.syntax)).toBe(true); + expect(Result.isSuccess(TypeExpression.toType(Shared))).toBe(true); + return Shared.$project("syntax"); + }); + expect(compile(result)).toStrictEqual( + call("::kernel::special_form::access", "::custom::Shared", "syntax"), + ); + }); + + test("structural_shorthand", () => { + expect.hasAssertions(); + const identity = Symbol("Tuple"); + const result = Draft.program({}, ($) => { + const { List, Dict, String: StringType, Integer } = $.prelude(); + $.type("Collections", { + list: List(BigInt), + dict: Dict(StringType, Integer), + nested: List({ value: BigInt }), + flag: Boolean, + text: String, + number: Number, + }); + const Tuple = $.newtype("Tuple", identity, [BigInt, String]); + return Tuple([2n, "two"]); + }); + expect(JSON.stringify(compile(result))).toContain('"#tuple"'); + expect(JSON.stringify(compile(result))).toContain( + "::kernel::type::List<::kernel::type::Integer>", + ); + }); + + test("construction_failures", () => { + expect.hasAssertions(); + for (const result of [ + Draft.program({}, ($) => { + $.let("not a name", 1n); + return $.literal(true); + }), + Draft.program({}, ($) => { + $.let("bad", Infinity); + return $.literal(true); + }), + Draft.program({}, ($) => { + $.type("bad", { "not a field": BigInt }); + return $.literal(true); + }), + Draft.program({}, ($) => + $.ifElse( + true, + () => 1n, + (branch) => { + branch.let("bad", Number.NaN); + return 2n; + }, + ), + ), + ]) { + expect(result._tag).toBe("Failure"); + } + const thrown = new Error("user exception"); + expect(() => + Draft.program({}, () => { + throw thrown; + }), + ).toThrow(thrown); + // @ts-expect-error exercise an unchecked JavaScript caller + const asynchronous = Draft.program({}, asynchronousBody); + expect(Result.isFailure(asynchronous)).toBe(true); + }); + + test("invalid_query_and_nominal", () => { + expect.hasAssertions(); + let visits = 0; + const query = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => + $.query + .entities(inputs.axis) + .filter("not a name", () => { + visits += 1; + return true; + }) + .collect(), + ); + expect(Result.isFailure(query)).toBe(true); + expect(visits).toBe(0); + const identity = Symbol("Bad"); + const value = Draft.program({}, ($) => { + const Bad = $.newtype("Bad", identity, { number: Number }); + return Bad({ number: Infinity }); + }); + expect(Result.isFailure(value)).toBe(true); + const declaration = Draft.program({}, ($) => { + $.newtype("not a name", identity, BigInt); + return $.literal(true); + }); + expect(Result.isFailure(declaration)).toBe(true); + }); + + test("external_inputs", () => { + expect.hasAssertions(); + const external = Expression.input("count", Prelude.builtin.types.Integer); + const result = Draft.program( + { count: Prelude.builtin.types.Integer }, + ($) => { + $.let("unused", external); + return $.literal(true); + }, + ); + expect(compile(result)).toStrictEqual( + call( + "::kernel::special_form::let", + "unused", + call( + "::kernel::special_form::input", + "count", + "::kernel::type::Integer", + ), + literal(true), + ), + ); + }); + + test("escaped_references", () => { + expect.hasAssertions(); + let escaped: Expression.Expression = + Expression.integer(0); + Draft.program({}, ($) => { + escaped = $.let("local", 1n); + return escaped; + }); + expect(compile(Draft.program({}, () => escaped))).toBe("local"); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts new file mode 100644 index 00000000000..e83005d5611 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts @@ -0,0 +1,98 @@ +/** + * Draft integration checks for flattened prelude and module views. + * + * @module + */ +import { Result } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, Module, Structural, TypeExpression } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Type } from "../main.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const child = Result.getOrThrow( + Module.define("::child", { + values: { + name: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + $: Module.value(), + }, + types: { ["__proto__"]: Module.type() }, + }), +); + +describe("draft_namespace", () => { + test("joined_constructor", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + types: { Both: Module.genericType(1) }, + modules: { Both: child }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + const { Both } = $.prelude(); + expect(Both.name).toBe(child.values.name); + expect(Both).toSatisfy(TypeExpression.isConstructor); + expect(Both(Structural.type(BigInt))).toSatisfy(TypeExpression.isExport); + return Both.name; + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("then_export", () => { + expect.hasAssertions(); + const result = Draft.withPrelude({ + modules: { Both: child }, + values: { Both: Expression.integer(1) }, + }).program({}, ($) => { + const { Both } = $.prelude(); + expect(Both.then).toBe(child.values.then); + expect($.modules().Both.then).toBe(child.values.then); + expect(Both.values.$).toBe(child.values.$); + expect(Expression.isExpression(Both.$)).toBe(false); + return Both.$.eq(1n); + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("prototype_type", () => { + expect.hasAssertions(); + const result = Draft.withPrelude(child).program({}, ($) => { + // oxlint-disable-next-line eslint/no-proto -- __proto__ names a HashQL type export + const type = $.prelude().__proto__; + expect(type).toSatisfy(TypeExpression.isExport); + return $.literal(true); + }); + expect(result).toSatisfy(Result.isSuccess); + }); + + test("prototype_join", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + modules: { ["__proto__"]: child }, + types: { ["__proto__"]: Module.type() }, + values: { ["__proto__"]: Module.value() }, + }), + ); + const result = Draft.withPrelude(custom).program({}, ($) => { + // oxlint-disable-next-line eslint/no-proto -- __proto__ names a HashQL export in all three namespaces + const entry = $.prelude().__proto__; + expect(entry).toSatisfy(TypeExpression.isExport); + expect(entry).toSatisfy(Expression.isExpression); + expect(entry).toSatisfy(Module.isModule); + return entry; + }); + expect(result).toSatisfy(Result.isSuccess); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts new file mode 100644 index 00000000000..331e113a799 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts @@ -0,0 +1,265 @@ +import { Result } from "effect"; +// oxlint-disable unicorn/no-thenable -- then names a HashQL branch or declared export +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude, Structural } from "../main.js"; +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +import type { Inputs, Type } from "../main.js"; + +const integer = Structural.type(BigInt); +const outside = Expression.input("outside", integer); +type Box = Type.Struct<{ readonly foo: Type.PrimitiveInteger }>; + +const chooseBox = (): + | { readonly foo: Expression.Expression } + | { readonly foo: typeof outside } => ({ foo: outside }); + +const chooseTuple = (): + | readonly [Expression.Expression] + | readonly [typeof outside] => [outside]; + +const alternative = (left: A, _right: B): A | B => left; +const chooseAxes = (): + | Inputs.Empty + | { readonly axis: typeof Fixtures.axis } => ({ axis: Fixtures.axis }); + +const chooseSchema = (): + | Inputs.Empty + | { readonly outside: typeof integer } => ({ outside: integer }); + +describe("draft_requirements", () => { + test("structural_alternatives", () => { + const structural = Structural.value()(chooseBox()); + // @ts-expect-error a closed annotation cannot discard the required host alternative + const closed: Expression.Expression = structural; + expectTypeOf(closed); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + const tuple = + Structural.value>()( + chooseTuple(), + ); + // @ts-expect-error tuple alternatives also keep every requirement + const closedTuple: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = tuple; + expectTypeOf(closedTuple); + const identity = Symbol("Box"); + Draft.program({}, ($) => { + const Nominal = $.newtype("Box", identity, { foo: BigInt }); + const nominal = Nominal(chooseBox()); + // @ts-expect-error the nominal producer normalizes before exposing variance + const closedNominal: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = nominal; + expectTypeOf(closedNominal); + // @ts-expect-error discarded nominal initializers still need their inputs + $.let("lost", nominal); + // @ts-expect-error discarded structural initializers still need their inputs + $.let("lostStruct", structural); + return $.literal(true); + }); + Draft.program({ outside: integer }, ($) => $.let("allowed", structural)); + }); + + test("erased_requirements", () => { + const erased: Expression.Any = outside; + const erasedValue: Expression.Value = outside; + const conditional = Expression.ifElse(true, { + then: erasedValue, + else: 1n, + }); + const assumed = Expression.assume()(erased); + const structural = Structural.value()({ foo: erasedValue }); + const call = Prelude.builtin.values.add(erasedValue, 1n); + const defaulted = Expression.input("defaulted", integer, erasedValue); + const erasedReceiver: Expression.Expression = + outside; + const receiverCall = erasedReceiver.$.eq(outside); + const erasedCallee: Expression.Expression< + Expression.TypeOf, + never + > = Prelude.builtin.values.add; + const calleeCall = erasedCallee(outside, 1n); + const mixedAny = Expression.ifElse(true, { then: erased, else: 1n }); + const chooseErasedTuple = (): + | readonly [typeof erasedValue] + | readonly [bigint] => [erasedValue]; + const erasedTuple = + Structural.value>()( + chooseErasedTuple(), + ); + // @ts-expect-error an outer tuple alternative must not discard internal erasure + const closedTuple: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = erasedTuple; + expectTypeOf(closedTuple); + // @ts-expect-error a named argument cannot discharge an erased receiver + const closedReceiver: Expression.Expression< + Type.PrimitiveBoolean, + { readonly outside: Type.PrimitiveInteger } + > = receiverCall; + // @ts-expect-error a named argument cannot discharge an erased callee + const closedCallee: Expression.Expression< + Expression.TypeOf, + { readonly outside: Type.PrimitiveInteger } + > = calleeCall; + // @ts-expect-error a primitive branch cannot discharge an erased expression + const closedAny: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = mixedAny; + expectTypeOf(closedReceiver); + expectTypeOf(closedCallee); + expectTypeOf(closedAny); + const mixed = Expression.ifElse(true, { + then: alternative(erasedValue, Expression.integer(1)), + else: 1n, + }); + // @ts-expect-error conditional composition must not convert erasure to Empty + const closed: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = conditional; + // @ts-expect-error structural composition must not convert erasure to Empty + const closedStruct: Expression.Expression = structural; + // @ts-expect-error argument composition must not convert erasure to Empty + const closedCall: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = call; + // @ts-expect-error the unknown host alternative cannot disappear + const closedMixed: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = mixed; + expectTypeOf(closed); + expectTypeOf(closedStruct); + expectTypeOf(closedCall); + expectTypeOf(closedMixed); + // @ts-expect-error erased program output cannot prove the schema contract + Draft.program({ outside: integer }, () => erased); + Draft.program({ outside: integer, defaulted: integer }, ($) => { + // @ts-expect-error even a matching schema cannot recover erased information + $.let("any", erased); + // @ts-expect-error Value erases requirements too + $.let("value", erasedValue); + // @ts-expect-error conditional composition retains erasure + $.let("conditional", conditional); + // @ts-expect-error semantic assumptions do not recover input requirements + $.let("assumed", assumed); + // @ts-expect-error structural composition retains erasure + $.let("structural", structural); + // @ts-expect-error calls retain erasure + $.let("call", call); + // @ts-expect-error input defaults retain erasure + $.let("defaulted", defaulted); + // @ts-expect-error callee requirements remain erased after argument composition + $.let("callee", calleeCall); + // @ts-expect-error receiver requirements remain erased after operand composition + $.let("receiver", receiverCall); + const identity = Symbol("Erased"); + const Nominal = $.newtype("Erased", identity, { foo: BigInt }); + const nominal = Nominal({ foo: erasedValue }); + // @ts-expect-error nominal composition cannot restore erased requirements + const closedNominal: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = nominal; + expectTypeOf(closedNominal); + // @ts-expect-error nominal initializers retain erased requirements + $.let("nominal", nominal); + // @ts-expect-error direct branches cannot accept erased values + $.ifElse(true, { then: erasedValue, else: 1n }); + $.ifElse( + true, + // @ts-expect-error callback branches cannot accept erased values + () => erasedValue, + () => 1n, + ); + return $.literal(true); + }); + const erasedPredicate: Expression.Value = + Expression.input("flag", Structural.type(Boolean)); + Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => { + // @ts-expect-error query callbacks cannot prove erased requirements + $.query.entities(inputs.axis).filter("vertex", () => erasedPredicate); + return $.literal(true); + }); + }); + + test("schema_alternatives", () => { + const result = Draft.program(chooseSchema(), ($) => $.literal(true)); + // @ts-expect-error an empty alternative does not remove the explicit schema promise + const closed: Expression.Expression = + Result.getOrThrow(result); + expectTypeOf(closed); + const output = Result.getOrThrow(result); + expectTypeOf>().toEqualTypeOf<{ + readonly outside: Type.PrimitiveInteger; + }>(); + const branch = Draft.program(chooseSchema(), ($) => + $.ifElse( + true, + (child) => child.let("outside", outside), + () => 1n, + ), + ); + // @ts-expect-error child contexts retain the conservative schema + const closedBranch: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + > = Result.getOrThrow(branch); + expectTypeOf(closedBranch); + const axis = Expression.input("axis", Fixtures.axis); + Fixtures.program(chooseAxes(), ($) => { + const query = $.query + .entities(axis) + .filter("vertex", (predicate) => predicate.let("selected", true)); + // @ts-expect-error query contexts retain the same conservative schema + const closedQuery: Expression.Expression< + Expression.TypeOf, + Inputs.Empty + > = query; + expectTypeOf(closedQuery); + return query.collect(); + }); + }); + + test("joined_expression_operations", () => { + const child = Result.getOrThrow( + Module.define("::child", { + values: { + then: Module.value(), + $: Module.value(), + }, + }), + ); + Draft.withPrelude({ + modules: { Both: child }, + values: { Both: outside }, + }).program({ outside: integer }, ($) => { + const { Both } = $.prelude(); + const thenValue = Both.then; + // @ts-expect-error the fluent operation object is not a module value + const dollarValue: Expression.Any = Both.$; + expectTypeOf(Both).not.toHaveProperty("$project"); + expectTypeOf(Both).not.toHaveProperty("$index"); + expectTypeOf($.modules().Both.then).toEqualTypeOf< + typeof child.values.then + >(); + expectTypeOf(thenValue).toEqualTypeOf(); + expectTypeOf(dollarValue); + expectTypeOf(Both.values.then).toEqualTypeOf< + Expression.Expression + >(); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts new file mode 100644 index 00000000000..23be0a85097 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts @@ -0,0 +1,421 @@ +/** + * Collects declarations while a synchronous callback constructs an expression. + * + * Handles retain semantic parameters until conversion to syntax. Only the declaration wrappers are heterogeneous: each is already an AST operation, so their collection needs no type recovery. A child collector prevents branch and predicate declarations from escaping their lexical body. Host exceptions propagate unchanged. Expected construction failures remain Results. + * + * @module + */ +import { Result, pipe } from "effect"; + +import { + Expression, + JExpr, + ProgramError, + Structural, + TypeExpression, +} from "../main.js"; +import * as AST from "../program/ast/index.js"; +import * as Namespace from "../program/Namespace.js"; + +import type * as Syntax from "../jexpr/type/index.js"; +import type { Inputs, Type } from "../main.js"; +import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; +import type * as Scope from "../program/Scope.js"; +import type * as Body from "./Body.js"; +import type * as Context from "./Context.js"; + +type Wrap = (child: AST.Node) => AST.Node; + +/** Adds structural argument normalization without losing the nominal identity on relocation. */ +const nominalValue = ( + expression: Expression.Expression< + Type.Function>, + Inputs.Empty + >, +): Context.NominalValue => + Expression.adaptCallable(expression, (self) => { + const construct: Context.NominalCall = < + const V extends Structural.Value & Structural.AnyValue, + >( + value: Structural.Exact, + ): Expression.Expression, Structural.Requirements> => + pipe( + { + callee: Expression.toJExpr(self), + argument: Structural.toJExpr(value), + }, + Result.all, + Result.map( + ({ callee, argument }) => new AST.Expr(JExpr.call(callee, argument)), + ), + Expression.fromResult, Structural.Requirements>, + ); + + return construct; + }); + +const nominal = ( + binding: Result.Result, ProgramError.Construction>, +): Context.Nominal => { + const type = pipe( + binding, + Result.map( + (bound): Syntax.Type => ({ + _tag: "Reference", + path: { rooted: false, segments: [bound.name] }, + generics: [], + }), + ), + TypeExpression.fromResult>, + ); + + const value = pipe( + binding, + Result.map((bound) => new AST.Expr(JExpr.Ident.compile(bound.name))), + Expression.fromResult< + Type.Function>, + Inputs.Empty + >, + nominalValue, + ); + + return Namespace.combine< + Context.NominalValue, + TypeExpression.TypeExpression> + >(value, type); +}; + +class ContextImpl implements Context.Context { + readonly #scope: S & Namespace.Rebindable; + readonly #prelude: Namespace.Flatten; + readonly #modules: Namespace.Modules; + readonly #wrappers: Result.Result[] = []; + readonly query: Context.QueryContext; + readonly literal = Expression.literal; + readonly integer = Expression.integer; + readonly number = Expression.number; + readonly assume = Expression.assume; + readonly input = Expression.input; + + constructor(scope: S & Namespace.Rebindable) { + this.#scope = scope; + this.#prelude = Namespace.flatten(scope); + this.#modules = Namespace.modules(scope); + this.query = this.#queries(); + } + + prelude(): Namespace.Flatten { + return this.#prelude; + } + modules(): Namespace.Modules { + return this.#modules; + } + + let( + name: string, + value: E, + ): Expression.Expression, Expression.Inputs> { + const binding = pipe( + Expression.toNode(value), + Result.flatMap((node) => AST.make(name, node)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Let(bound, child), + ), + ), + ); + + return pipe( + binding, + Result.map((bound) => new AST.Expr(JExpr.Ident.compile(bound.name))), + Expression.fromResult, Expression.Inputs>, + ); + } + + type( + name: string, + definition: D, + ): TypeExpression.TypeExpression> { + const binding = pipe( + definition, + Structural.type, + TypeExpression.toType, + Result.flatMap((syntax) => AST.make(name, syntax)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Type(bound, child), + ), + ), + ); + + return pipe( + binding, + Result.map( + (bound): Syntax.Type => ({ + _tag: "Reference", + path: { rooted: false, segments: [bound.name] }, + generics: [], + }), + ), + TypeExpression.fromResult>, + ); + } + + readonly newtype: Context.Context["newtype"] = < + const N extends symbol, + const D extends Structural.Definition, + >( + name: string, + _identity: symbol extends N ? never : N, + definition: D, + ): Context.Nominal> => { + const binding = pipe( + definition, + Structural.type, + TypeExpression.toType, + Result.flatMap((syntax) => AST.make(name, syntax)), + ); + + this.#wrappers.push( + pipe( + binding, + Result.map( + (bound): Wrap => + (child) => + new AST.Newtype(bound, child), + ), + ), + ); + + return nominal>(binding); + }; + + ifElse< + const C extends Expression.Value, + const T extends Expression.AnyValue, + const E extends Expression.AnyValue, + >( + condition: C, + ...branches: Context.Branches + ): Context.Conditional { + const resolve = (): { + readonly consequent: Result.Result; + readonly alternate: Result.Result; + } => { + if (branches.length === 2) { + return { + consequent: new ContextImpl(this.#scope).build(branches[0]), + alternate: new ContextImpl(this.#scope).build(branches[1]), + }; + } + + return { + consequent: Expression.toNode(branches[0].then), + alternate: Expression.toNode(branches[0].else), + }; + }; + + const { consequent, alternate } = resolve(); + return pipe( + { condition: Expression.toNode(condition), consequent, alternate }, + Result.all, + Result.map( + (nodes) => + new AST.If(nodes.condition, nodes.consequent, nodes.alternate), + ), + Expression.fromResult< + Expression.Conditional, Expression.TypeOf>, + Inputs.Merge< + Expression.Inputs, + Inputs.Merge, Expression.Inputs> + > + >, + ); + } + + #query( + expression: Expression.Expression, + ): Context.Query { + const filter = >( + name: string, + predicate: ( + $: Context.Context, + vertex: Expression.Expression, + ) => P, + ): Context.Query>> => { + const scope = this.#scope; + const node = Result.gen(function* () { + const graph = yield* Expression.toJExpr(expression); + const ident = yield* pipe( + JExpr.Ident.decodeResult(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidParameterName({ + name, + cause, + }), + }), + ), + ); + + const parameter = JExpr.Ident.compile(ident); + const vertex = Expression.fromJExpr(parameter); + const body = yield* new ContextImpl(scope).build(($) => + predicate($, vertex), + ); + + return new AST.Expr( + JExpr.call( + "::graph::body::filter", + graph, + JExpr.fn({ + params: { [parameter]: JExpr.infer }, + body: body.compile(), + }), + ), + ); + }); + + return this.#query>>( + Expression.fromResult(node), + ); + }; + + const collect = (): Expression.Expression, I> => + pipe( + expression, + Expression.toJExpr, + Result.map( + (graph) => new AST.Expr(JExpr.call("::graph::tail::collect", graph)), + ), + Expression.fromResult, I>, + ); + + const proxy = new Proxy(expression, { + // oxlint-disable-next-line typescript/no-restricted-types -- proxy forwarding can return any expression property + get: (target, property, receiver): unknown => { + if (property === "filter") { + return filter; + } + + if (property === "collect") { + return collect; + } + + return Reflect.get(target, property, receiver); + }, + }); + + // SAFETY: the typed handle retains its semantic type and input requirements. The filter and collect methods retain the vertex type and propagate requirements. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy does not express the two supplied query methods + return proxy as Context.Query; + } + + #queries(): Context.QueryContext { + const declaration = this.#scope.values["entities"]; + if (declaration === undefined) { + return {}; + } + + const entities: Context.Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, + >( + ...args: A + ) => { + const expression = pipe( + { + callee: Expression.toJExpr(declaration), + args: Result.all(args.map(Expression.toJExpr)), + }, + Result.all, + Result.map( + ({ callee, args: values }) => + new AST.Expr(JExpr.call(callee, ...values)), + ), + Expression.fromResult< + Context.EntityFunction["returns"], + Inputs.Merge["inputs"], ArgumentInputs> + >, + ); + + return this.#query< + Context.EntityFunction["returns"], + Context.EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> + >(expression); + }; + + return { entities }; + } + + build( + body: ($: Context.Context) => Expression.AnyValue, + ): Result.Result { + const expression = body(this); + if ( + !Expression.isExpression(expression) && + !( + expression === null || + ["string", "number", "bigint", "boolean"].includes(typeof expression) + ) + ) { + return Result.fail(ProgramError.Construction.invalidBodyResult()); + } + + return pipe( + { + wrappers: Result.all(this.#wrappers), + node: Expression.toNode(expression), + }, + Result.all, + Result.map(({ wrappers, node }) => { + let root = node; + for (const wrap of wrappers.toReversed()) { + root = wrap(root); + } + + return root; + }), + ); + } +} + +/** Evaluates only callbacks checked against the complete explicit-input policy. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the scope and callback construct a new program +export const evaluate = < + S extends Scope.Scope, + I extends Body.Inputs, + O extends Expression.AnyValue & Expression.Any, +>( + scope: S & Namespace.Rebindable, + body: Body.WithoutInputs, +): Result.Result< + Expression.Expression, Body.Requirements>, + ProgramError.Construction +> => + pipe( + new ContextImpl(scope).build(($) => { + const expression = body($); + if (Expression.isExpression(expression)) { + return expression; + } + return Expression.fromResult, Body.Requirements>( + Result.fail(ProgramError.Construction.invalidBodyResult()), + ); + }), + Result.map(Expression.fromNode, Body.Requirements>), + ); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts new file mode 100644 index 00000000000..afae68579e0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts @@ -0,0 +1,54 @@ +/** + * Small trusted declarations for Draft query-construction tests. + * + * The vertex contains only the fields the tests project. These declarations exercise custom-prelude typing and syntax construction, not the graph service's complete entity or temporal schema. + * + * @module + */ +import { Result, pipe } from "effect"; + +import { Module, Prelude } from "../main.js"; +import * as Scope from "../program/Scope.js"; +import * as Draft from "./index.js"; + +import type { Expression, Inputs, Type, TypeExpression } from "../main.js"; + +export type Vertex = Type.Struct<{ + readonly metadata: Type.Struct<{ + readonly record_id: Type.Struct<{ + readonly entity_id: Type.Struct<{ + readonly entity_uuid: Prelude.EntityUuid; + }>; + }>; + }>; +}>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; +type Entities = Type.Function; +const declarations: { + readonly types: { + readonly Axis: Module.Declaration< + TypeExpression.TypeExpression + >; + }; + readonly values: { + readonly entities: Module.Declaration< + Expression.Expression + >; + }; +} = { types: { Axis: Module.type() }, values: { entities: Module.value() } }; +const graph: Module.Module = pipe( + Module.define("::test::graph", declarations), + Result.getOrThrow, +); + +export const scope: Scope.Merge = Scope.merge( + Prelude.builtin, + graph, +); +export const axis: typeof graph.types.Axis = graph.types.Axis; +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the schema and callback construct a test program +export const program: Draft.Program = + Draft.withPrelude(scope).program; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts index bb295bdfb9e..1d2b426143b 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -1,86 +1,138 @@ -import type * as Expression from "../program/Expression.js"; -import type * as Scope from "../program/Scope.js"; -import type * as TypeExpression from "../program/TypeExpression.js"; -import type * as Type from "../type/index.js"; -import type { Result } from "effect"; -import type { ReadonlyRecord } from "effect/Record"; - -export type Inputs = ReadonlyRecord; - -declare namespace Inputs { - export type Empty = ReadonlyRecord; - - export type ProgramInput = I extends Inputs - ? { - readonly [Key in keyof I]: I[Key] extends TypeExpression.TypeExpression< - infer Type - > - ? Expression.Expression - : never; - } - : never; -} +/** + * Synchronous program construction with an explicit input schema. + * + * The callback receives typed input handles and a prelude-specific construction context. Every emitted initializer and nested body must fit that schema, so the result can retain unused declared inputs without overlooking discarded declarations. Custom preludes replace the default and retain their exact export keys. + * + * @module + */ +import { Result, pipe } from "effect"; -type ScopeKeys = - | keyof S["modules"] - | keyof S["values"] - | keyof S["types"]; +import * as Expression from "../program/Expression.js"; +import * as Prelude from "../program/Prelude.js"; +import * as ProgramError from "../program/ProgramError.js"; +import * as Scope from "../program/Scope.js"; +import * as Scribe from "./Scribe.js"; -/** `unknown` is the identity of `&`, so namespaces lacking the key drop out. */ -type Lookup = Key extends keyof Namespace - ? Namespace[Key] - : unknown; +import type { Relocatable } from "../internal/relocation.js"; +import type { Type, TypeExpression } from "../main.js"; +import type * as Namespace from "../program/Namespace.js"; +import type * as Body from "./Body.js"; -type Prelude = { - readonly [Key in ScopeKeys]: Lookup & - Lookup & - Lookup; -}; +export type * as Context from "./Context.js"; + +export type Program = < + const I extends Body.Inputs, + const O extends Expression.AnyValue & Expression.Any, +>( + inputs: I, + draft: Body.Body, +) => Result.Result< + Expression.Expression, Body.Requirements>, + ProgramError.Construction +>; -type DefaultPrelude = Scope.Scope; - -interface Context

{ - readonly prelude: () => Prelude

; - readonly let: ( - name: string, - value: Expression.Expression, - ) => Expression.Expression; - readonly newtype: ( - name: string, - value: T, - ) => Expression.Expression & TypeExpression.TypeExpression; - readonly type: ( - name: string, - value: T, - ) => TypeExpression.TypeExpression; - readonly ifElse: (( - condition: Expression.Expression, - then: ($: Context

) => Expression.Expression, - else: ($: Context

) => Expression.Expression, - ) => Expression.Expression ) | (/* the other version lol */); - - readonly query: [...] +function inputHandle( + name: K, + type: D, +): Body.Handle; +function inputHandle( + name: K, + type: TypeExpression.TypeExpression, +): Expression.Expression>> { + return Expression.input(name, type); } -class DraftError {} +/** Creates each handle at the same schema key and semantic type, including its own input name. */ +const inputHandles = ( + schema: I, +): Result.Result, ProgramError.Construction> => { + const [symbol] = Object.getOwnPropertySymbols(schema); + if (symbol !== undefined) { + return Result.fail(ProgramError.Construction.symbolInputName(symbol)); + } -const programWithPrelude = < - Prelude extends Scope.Scope, - I extends Inputs, - O extends Type.Any, ->( - prelude: Prelude, - inputs: I, - draft: ($: Context, inputs: I) => Expression.Expression, -): Result.Result, DraftError> => { - // todo!() + const handles: Partial> = {}; + const member = (name: K): Body.Handles[K] => + inputHandle(name, schema[name]); + + for (const name of Object.getOwnPropertyNames(schema)) { + Object.defineProperty(handles, name, { + value: member(name), + enumerable: true, + }); + } + + // SAFETY: the loop fills every own string key with the handle for that exact key and semantic type. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot establish completion of a generic mapped record + return Result.succeed(Object.freeze(handles as Body.Handles)); }; -const program = ( - inputs: I, - draft: ( - $: Context, +type Rebindings = { + readonly [K in keyof E]: E[K] extends undefined + ? undefined + : Relocatable; +}; + +/** Replaces the default declarations without widening the supplied export tables. */ +export function withPrelude( + prelude: S & Namespace.Rebindable, +): { readonly program: Program> }; +export function withPrelude< + M extends Scope.Scope["modules"] & Rebindings, + T extends Scope.Scope["types"] & Rebindings, + V extends Scope.Scope["values"] & Rebindings, +>(prelude: { + readonly modules?: M; + readonly types?: T; + readonly values?: V; +}): { + readonly program: Program<{ + readonly modules: Readonly | Scope.Empty["modules"]; + readonly types: Readonly | Scope.Empty["types"]; + readonly values: Readonly | Scope.Empty["values"]; + }>; +} { + const scope = Object.freeze({ + modules: Scope.snapshot(prelude.modules ?? {}), + types: Scope.snapshot(prelude.types ?? {}), + values: Scope.snapshot(prelude.values ?? {}), + }); + + const validate = (): Result.Result< + typeof scope, + ProgramError.Construction + > => { + for (const table of [scope.modules, scope.types, scope.values]) { + const [name] = Object.getOwnPropertySymbols(table); + if (name !== undefined) { + return Result.fail(ProgramError.Construction.symbolExportName(name)); + } + } + + return Result.succeed(scope); + }; + + const validated = validate(); + const program: Program = < + const I extends Body.Inputs, + const O extends Expression.AnyValue & Expression.Any, + >( inputs: I, - ) => Expression.Expression, -): Result.Result, DraftError> => - programWithPrelude(Scope.empty, inputs, draft); + draft: Body.Body, + ) => + pipe( + Result.all({ scope: validated, handles: inputHandles(inputs) }), + Result.flatMap(({ scope: accepted, handles }) => + Scribe.evaluate(accepted, (context) => + draft(context, handles), + ), + ), + ); + + return Object.freeze({ program }); +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the schema and callback construct a new program +export const program: Program = withPrelude( + Prelude.builtin, +).program; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts new file mode 100644 index 00000000000..25cd74f0fda --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts @@ -0,0 +1,36 @@ +/** + * Typed rebinding of handles to another HashQL path. + * + * Each producer retains its own rebinding function while its semantic parameters are in scope. Consumers can then move a handle without reconstructing those parameters from an erased export. The result type names the capabilities the producer preserves, rather than promising to retain arbitrary properties added by a caller. + * + * @module + */ +import { dual } from "effect/Function"; + +import type * as JExpr from "../jexpr/index.js"; +import type * as ProgramError from "../program/ProgramError.js"; +import type { Result } from "effect"; + +export const Relocate: unique symbol = Symbol("~hashql/Relocate"); + +export interface Relocatable { + readonly [Relocate]: ( + path: JExpr.Path.Path, + ) => Result.Result; +} + +export const relocate: { + ( + path: JExpr.Path.Path, + ): (self: Relocatable) => Result.Result; + ( + self: Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = dual( + 2, + ( + self: Relocatable, + path: JExpr.Path.Path, + ): Result.Result => self[Relocate](path), +); diff --git a/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts b/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts deleted file mode 100644 index e0090bed9bd..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/playground.test-d.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { describe, expectTypeOf, test } from "vitest"; - -import * as JExpr from "./jexpr/index.js"; -import { get, makeExpression, toJExpr } from "./playground.js"; - -import type { Expression } from "./playground.js"; -import type * as Type from "./type/index.js"; -import type { ReadonlyRecord } from "effect/Record"; - -type User = Type.Struct<{ - readonly name: Type.PrimitiveString; - readonly address: Type.Struct<{ readonly city: Type.PrimitiveString }>; -}>; - -interface Recursive extends Type.Struct<{ - readonly value: Type.PrimitiveString; - readonly next: Recursive; -}> {} - -const preserve = ( - expression: Expression, -): Expression => expression; - -const lookup = ( - dictionary: Expression>, - key: Expression, -): Expression => get(dictionary, key); - -describe("expression_types", () => { - test("struct_projection", () => { - const user = makeExpression("user"); - - expectTypeOf(user.name).toEqualTypeOf>(); - expectTypeOf(user.address.city).toEqualTypeOf< - Expression - >(); - }); - - test("generic_preservation", () => { - const user = preserve(makeExpression("user")); - - expectTypeOf(user).toEqualTypeOf>(); - expectTypeOf(user.address.city).toEqualTypeOf< - Expression - >(); - }); - - test("recursive_projection", () => { - const node = makeExpression("node"); - - expectTypeOf(node.next.next.value).toEqualTypeOf< - Expression - >(); - }); - - test("primitive_identity", () => { - const value = makeExpression(JExpr.literal("alice")); - - expectTypeOf(value).not.toEqualTypeOf>(); - expectTypeOf(toJExpr(value)).toEqualTypeOf(); - expectTypeOf(value).not.toHaveProperty("value"); - expectTypeOf(value).not.toHaveProperty("push"); - }); - - test("opaque_identity", () => { - const value = - makeExpression>("id"); - - expectTypeOf(value).not.toEqualTypeOf>(); - expectTypeOf(value).not.toEqualTypeOf< - Expression> - >(); - }); - - test("missing_field", () => { - const user = makeExpression("user"); - - expectTypeOf(user).toEqualTypeOf>(); - expectTypeOf(user).not.toHaveProperty("missing"); - // @ts-expect-error Field access cannot replace a symbolic expression. - user.name = makeExpression("other"); - }); -}); - -describe("tuple_types", () => { - test("tuple_positions", () => { - const tuple = - makeExpression< - Type.Tuple - >("tuple"); - - expectTypeOf(tuple[0]).toEqualTypeOf>(); - expectTypeOf(tuple[1]).toEqualTypeOf>(); - expectTypeOf(tuple).not.toHaveProperty("2"); - expectTypeOf(tuple).not.toHaveProperty(Number("0")); - expectTypeOf(tuple).not.toHaveProperty("length"); - expectTypeOf(tuple).not.toHaveProperty("map"); - }); - - test("tuple_empty", () => { - const tuple = makeExpression>("tuple"); - - expectTypeOf(toJExpr(tuple)).toEqualTypeOf(); - expectTypeOf(tuple).not.toHaveProperty("0"); - expectTypeOf(tuple).not.toHaveProperty(Number("0")); - }); -}); - -describe("lookup_types", () => { - test("lookup_nullable", () => { - const dictionary = - makeExpression>("users"); - const key = makeExpression(JExpr.literal("alice")); - const result = get(dictionary, key); - - expectTypeOf(result).toEqualTypeOf>(); - expectTypeOf(result).not.toHaveProperty("name"); - }); - - test("lookup_null_value", () => { - const dictionary = - makeExpression>( - "values", - ); - const key = makeExpression("key"); - - expectTypeOf(get(dictionary, key)).toEqualTypeOf< - Expression - >(); - }); - - test("lookup_expression_key", () => { - const dictionary = - makeExpression>("users"); - const user = makeExpression("user"); - - expectTypeOf(get(dictionary, user.name)).toEqualTypeOf< - Expression - >(); - }); - - test("lookup_generic_wrapper", () => { - const dictionary = - makeExpression>("users"); - const key = makeExpression("key"); - - expectTypeOf(lookup(dictionary, key)).toEqualTypeOf< - Expression - >(); - }); -}); - -describe("lookup_constraints", () => { - test("lookup_invariant_struct_key", () => { - type Key = Type.Struct<{ readonly id: Type.PrimitiveInteger }>; - const dictionary = makeExpression>("users"); - const key = makeExpression("key"); - const narrower = makeExpression< - Type.Struct<{ - readonly id: Type.PrimitiveInteger; - readonly name: Type.PrimitiveString; - }> - >("narrower"); - const broader = - makeExpression>>("broader"); - - expectTypeOf(get(dictionary, key)).toEqualTypeOf< - Expression - >(); - // @ts-expect-error An additional field makes the key narrower, not equivalent. - get(dictionary, narrower); - // @ts-expect-error The dictionary's required field cannot disappear from the key. - get(dictionary, broader); - }); - - test("lookup_invariant_union_key", () => { - type Key = Type.PrimitiveString | Type.PrimitiveNull; - const dictionary = makeExpression>("users"); - const key = makeExpression("key"); - const narrower = makeExpression("narrower"); - const broader = makeExpression("broader"); - - expectTypeOf(get(dictionary, key)).toEqualTypeOf< - Expression - >(); - // @ts-expect-error Equivalence must include every union member. - get(dictionary, narrower); - // @ts-expect-error An additional union member makes the key broader, not equivalent. - get(dictionary, broader); - }); - - test("lookup_invalid_arguments", () => { - const dictionary = - makeExpression>("users"); - const wrongKey = makeExpression(JExpr.integer(0)); - const key = makeExpression("key"); - const user = makeExpression("user"); - - expectTypeOf(get(dictionary, key)).toEqualTypeOf< - Expression - >(); - // @ts-expect-error The dictionary, not its index expression, determines the key type. - get(dictionary, wrongKey); - // @ts-expect-error A struct cannot stand in for a dictionary. - get(user, key); - // @ts-expect-error Lookup keys are expressions, not decoded JavaScript values. - get(dictionary, "alice"); - }); - - test("lookup_nullable_receiver", () => { - type Dictionary = Type.Dict; - const outer = - makeExpression>("outer"); - const key = makeExpression("key"); - const inner = get(outer, key); - - expectTypeOf(inner).toEqualTypeOf< - Expression - >(); - // @ts-expect-error A second lookup needs to handle the possibly absent dictionary. - get(inner, key); - }); -}); - -describe("binding_types", () => { - test("descriptor_rejection", () => { - const value = makeExpression("value"); - - expectTypeOf(toJExpr(value)).toEqualTypeOf(); - // @ts-expect-error A type descriptor carries no expression binding. - toJExpr({ _tag: "String", value: "alice" }); - }); - - test("binding_name_fields", () => { - const value = makeExpression< - Type.Struct<{ - readonly get: Type.PrimitiveString; - readonly push: Type.PrimitiveInteger; - readonly then: Type.PrimitiveBoolean; - }> - >("value"); - - expectTypeOf(value.get).toEqualTypeOf>(); - expectTypeOf(value.push).toEqualTypeOf>(); - expectTypeOf(value.then).toEqualTypeOf>(); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/playground.test.ts b/libs/@local/hashql/sdk/typescript/src/playground.test.ts deleted file mode 100644 index 499e9bca129..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/playground.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { describe, expect, test } from "vitest"; - -import * as JExpr from "./jexpr/index.js"; -import { get, makeExpression, toJExpr } from "./playground.js"; - -import type * as Type from "./type/index.js"; -import type { ReadonlyRecord } from "effect/Record"; - -type User = Type.Struct<{ - readonly name: Type.PrimitiveString; - readonly address: Type.Struct<{ readonly city: Type.PrimitiveString }>; -}>; - -const collisionFields = [ - "push", - "get", - "then", - "toJSON", - "constructor", - "__proto__", -] as const; - -type Collision = Type.Struct< - ReadonlyRecord<(typeof collisionFields)[number], Type.PrimitiveString> ->; - -describe("expression_binding", () => { - test("primitive_ast", () => { - expect.hasAssertions(); - const expression = makeExpression(JExpr.integer(0)); - - expect(JExpr.compile(toJExpr(expression))).toBe('{"#literal":0}'); - }); - - test("struct_nested", () => { - expect.hasAssertions(); - const user = makeExpression("user"); - - expect(JExpr.compile(toJExpr(user.address.city))).toBe( - '["::kernel::special_form::access",["::kernel::special_form::access","user","address"],"city"]', - ); - }); - - test("projection_branches", () => { - expect.hasAssertions(); - const user = makeExpression("user"); - const name = user.name; - const city = user.address.city; - - expect(toJExpr(user)).toBe("user"); - expect(toJExpr(name)).toStrictEqual([ - "::kernel::special_form::access", - "user", - "name", - ]); - expect(toJExpr(city)).toStrictEqual([ - "::kernel::special_form::access", - ["::kernel::special_form::access", "user", "address"], - "city", - ]); - }); - - test("tuple_positions", () => { - expect.hasAssertions(); - const pair = - makeExpression< - Type.Tuple - >("pair"); - - expect(JExpr.compile(toJExpr(pair[0]))).toBe( - '["access","pair",{"#literal":0}]', - ); - expect(JExpr.compile(toJExpr(pair[1]))).toBe( - '["access","pair",{"#literal":1}]', - ); - }); - - test("tuple_empty", () => { - expect.hasAssertions(); - const empty = makeExpression>(JExpr.tuple()); - - expect(JExpr.compile(toJExpr(empty))).toBe('{"#tuple":[]}'); - }); - - test.each(collisionFields)("field_name_%s", (field) => { - expect.hasAssertions(); - const expression = makeExpression("value"); - - expect(toJExpr(expression[field])).toStrictEqual([ - "::kernel::special_form::access", - "value", - field, - ]); - }); -}); - -describe("field_identifiers", () => { - test("field_unicode", () => { - expect.hasAssertions(); - const expression = - makeExpression>( - "value", - ); - - expect(toJExpr(expression.naïve)).toStrictEqual([ - "::kernel::special_form::access", - "value", - "naïve", - ]); - }); - - test("field_symbol", () => { - expect.hasAssertions(); - const expression = - makeExpression>( - "value", - ); - - expect(toJExpr(expression["+"])).toStrictEqual([ - "::kernel::special_form::access", - "value", - "`+`", - ]); - }); - - test("field_base_url", () => { - expect.hasAssertions(); - const expression = makeExpression< - Type.Struct<{ - readonly "https://example.com/a::b/": Type.PrimitiveString; - }> - >("value"); - - expect(toJExpr(expression["https://example.com/a::b/"])).toStrictEqual([ - "::kernel::special_form::access", - "value", - "`https://example.com/a::b/`", - ]); - }); - - test.each(["", "invalid field", "01", "-1", "`+`"])( - "field_invalid_%s", - (field) => { - expect.hasAssertions(); - const expression = makeExpression("user"); - - expect(() => { - Reflect.get(expression, field); - }).toThrow("Invalid HashQL field name"); - }, - ); -}); - -describe("dictionary_lookup", () => { - test("lookup_literal_key", () => { - expect.hasAssertions(); - const dictionary = - makeExpression>("users"); - const key = makeExpression(JExpr.literal("alice")); - - expect(JExpr.compile(toJExpr(get(dictionary, key)))).toBe( - '["::kernel::special_form::index","users",{"#literal":"alice"}]', - ); - expect(toJExpr(dictionary)).toBe("users"); - }); - - test("lookup_expression_key", () => { - expect.hasAssertions(); - const dictionary = - makeExpression>("users"); - const user = makeExpression("user"); - - expect(toJExpr(get(dictionary, user.name))).toStrictEqual([ - "::kernel::special_form::index", - "users", - ["::kernel::special_form::access", "user", "name"], - ]); - }); -}); - -describe("host_interop", () => { - test("symbol_probe", () => { - expect.hasAssertions(); - const expression = makeExpression("user"); - - expect(Reflect.get(expression, Symbol.iterator)).toBeUndefined(); - expect(Reflect.get(expression, Symbol.toStringTag)).toBeUndefined(); - }); - - // oxlint-disable-next-line typescript/promise-function-async -- returns the Promise assertion directly - test("promise_assimilation", () => { - expect.hasAssertions(); - const expression = makeExpression("value"); - - expect(toJExpr(expression.then)).toStrictEqual([ - "::kernel::special_form::access", - "value", - "then", - ]); - return expect(Promise.resolve(expression)).resolves.toBe(expression); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/playground.ts b/libs/@local/hashql/sdk/typescript/src/playground.ts deleted file mode 100644 index d6c8544c3fc..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/playground.ts +++ /dev/null @@ -1,60 +0,0 @@ -// sketch 1) proxy based interpolation, Elysia.JS style - -const program = ($) => { - // $ is just used for fluid syntax, and built-in utilities, it's the general entrypoint - const { EntityUuid, Uuid } = $.prelude(); - const { temporal } = $.modules(); - - const comparison = EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")); // would be converted into a let binding - - // if else would just "work", but would need to have the form of: - let out; - if ([expr]) { - [expr]; // cannot mention or set `out` - out = [result]; - } else { - // else **must** be set - out = [expr]; - } - - // else if chains are possible, but need to obey the same rules as if/else - - $.query - .entities($.input("axis", $.input("axis", temporal.QueryTemporalAxes))) - .filter( - (vertex) => - vertex.metadata.record_id.entity_id.entity_uuid === comparison, - ) - .collect(); -}; - -// sketch 2) mutable execution -const program = ($) => { - const { temporal } = $.modules(); - const { EntityUuid, Uuid, eq } = $.prelude(); - - const foo = $.let("foo", [expr]); // oxlint rule for the name to be the same - const Foo = $.newtype("Foo", { - foo: BigInt, // constructor is just turned into a `Integer` type - }); // fluid constructor that just takes records, and arrays for tuples, dict is just created using the `Dict` and `List` built-in. - - const bar = Foo({ foo: 2n }); // this just works - - // ifElse needs to be explicit - const baz = $.ifElse([expr], { then: [expr], else: [expr] }); - - // this would NOT be converted - // const comparison = EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")); - // this would: - const comparison = $.let( - "comparison", - EntityUuid(Uuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), - ); - - $.query - .entities($.input("axis", $.input("axis", temporal.QueryTemporalAxes))) - .filter((vertex) => - eq(vertex.metadata.record_id.entity_id.entity_uuid, comparison), - ) - .collect(); -}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts index 1fdf59882f8..0dbe196667e 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts @@ -1,3 +1,8 @@ +/** + * Static checks for symbolic calls, field projections and input requirements. + * + * @module + */ import { describe, expectTypeOf, test } from "vitest"; import type * as Type from "../type/index.js"; @@ -394,8 +399,9 @@ describe("operation_names", () => { expectTypeOf(reserved.get).toEqualTypeOf< Expression >(); - // @ts-expect-error JavaScript Promise interoperability reserves direct then access. - expectTypeOf(reserved.then); + expectTypeOf(reserved.then).toEqualTypeOf< + Expression + >(); expectTypeOf(reserved.$project("then")).toEqualTypeOf< Expression >(); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts index c44f1c0e271..d9b11eb3c7a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts @@ -1,3 +1,8 @@ +/** + * Runtime checks for symbolic calls and property projections. + * + * @module + */ import { Result } from "effect"; import { describe, expect, test } from "vitest"; @@ -133,16 +138,9 @@ describe("expression", () => { expect(compile(record.$project("then")())).toBe( '[["::kernel::special_form::access","record","then"]]', ); - expect(Reflect.get(record, "then")).toBeUndefined(); - }); - - // oxlint-disable-next-line typescript/promise-function-async -- returns Vitest’s Promise assertion directly - test("promise_interoperability", () => { - expect.hasAssertions(); - const expression = Expression.fromJExpr< - Type.Function, - Inputs.Empty - >("function"); - return expect(Promise.resolve(expression)).resolves.toBe(expression); + const thenField = record.then; + expect(compile(thenField())).toBe( + '[["::kernel::special_form::access","record","then"]]', + ); }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts index 222227b68c0..6c269a807e1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts @@ -1,12 +1,23 @@ +/** + * Symbolic HashQL values with semantic types and input requirements. + * + * Handles build syntax rather than executing queries. Their descriptors select the available calls and projections. Rebinding retains those descriptors while replacing the referenced path, and construction failures remain attached to the handle. + * + * A projected field named `then` retains its HashQL meaning. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. + * + * @module + */ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -import { Predicate, Result, Schema, identity, pipe } from "effect"; +import { Function, Predicate, Result, Schema, identity, pipe } from "effect"; +import { Relocate } from "../internal/relocation.js"; import * as JExpr from "../jexpr/index.js"; import * as AST from "./ast/index.js"; import * as Fluent from "./Fluent.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; +import type { Relocatable } from "../internal/relocation.js"; import type * as Type from "../type/index.js"; import type { Accessors, @@ -29,50 +40,64 @@ interface Variance { export type Primitive = Type.Primitive["value"]; -/** The semantic input descriptors required by a value, with defaults marked optional. */ -export type Inputs = E extends Primitive +type InputAlternatives = E extends Primitive ? Input.Empty : E extends { readonly [TypeId]: { readonly _Inputs: Types.Contravariant; }; } - ? { readonly [Key in keyof Requirements]: Requirements[Key] } - : never; + ? [Requirements] extends [never] + ? Input.Erased + : // oxlint-disable-next-line typescript/no-restricted-types -- detects the top type in a caller annotation without erasing a value + unknown extends Requirements + ? Input.Erased + : { readonly [Key in keyof Requirements]: Requirements[Key] } + : Input.Erased; + +/** The semantic input descriptors required by every host-side alternative, with defaults marked optional. */ +export type Inputs = Input.Conservative>; /** An expression with its semantic type erased, for syntax-only operations. */ -export interface Any { +export interface Any extends Relocatable { readonly [Binding]: Result.Result; } export interface Handle extends Any { readonly [TypeId]: Variance; + readonly [Relocate]: Relocatable>[typeof Relocate]; } export type AnyValue = Any | Primitive; /** Accepts an exactly typed handle or the corresponding host primitive. */ +/** Argument compatibility needs semantic metadata, not the original callable or rebinding signature. */ export type Value = - | Handle + | (Any & Pick, typeof TypeId | typeof Binding>) | (T extends Type.Primitive ? T["value"] : never); -/** Host numbers remain Number regardless of their emitted literal syntax. */ -export type TypeOf = - V extends Handle - ? T - : V extends string - ? Type.PrimitiveString - : V extends boolean - ? Type.PrimitiveBoolean - : V extends bigint - ? Type.PrimitiveInteger - : V extends number - ? Type.PrimitiveNumber - : V extends null - ? Type.PrimitiveNull - : never; - -class ExpressionImpl implements Handle { +/** + * Reads semantic metadata without constraining an adapted callable to its original host signature. + * + * Host numbers remain Number regardless of their emitted literal syntax. + */ +export type TypeOf = V extends { + readonly [TypeId]: { readonly _T: Types.Invariant }; +} + ? T + : V extends string + ? Type.PrimitiveString + : V extends boolean + ? Type.PrimitiveBoolean + : V extends bigint + ? Type.PrimitiveInteger + : V extends number + ? Type.PrimitiveNumber + : V extends null + ? Type.PrimitiveNull + : never; + +class ExpressionImpl { readonly [TypeId]: Variance; readonly #expr: Result.Result; @@ -146,7 +171,23 @@ const make = ( ), ), ), - { [TypeId]: impl[TypeId], [Binding]: impl[Binding] }, + { + [TypeId]: impl[TypeId], + [Binding]: impl[Binding], + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + impl[Binding], + Result.map(() => + make( + new ExpressionImpl( + parseNode(JExpr.Path.compile(path)), + ), + ), + ), + ), + }, ); const proxy = new Proxy(target, { @@ -156,11 +197,6 @@ const make = ( receiver, ): // oxlint-disable-next-line typescript/no-restricted-types -- proxy property reads may return arbitrary host values unknown { - // A callable projected `then` would make the handle a JavaScript thenable. - if (property === "then") { - return undefined; - } - if (property === "$") { // oxlint-disable-next-line eslint/no-use-before-define -- the operation factories and expression proxy are mutually recursive return Fluent.make(target, { fromResult, fromJExpr, toJExpr }); @@ -219,9 +255,11 @@ const make = ( }, }); - // SAFETY: the target retains T's invariant marker, and the traps construct syntax for the typed operations. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the proxy implements the type-directed operations - return proxy as Expression; + const handle: Handle = proxy; + + // SAFETY: the handle retains T and Inputs. The traps supply their type-directed operations. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot derive conditional accessors and call signatures from proxy traps + return handle as Expression; }; export const fromResult = ( @@ -241,6 +279,45 @@ export const fromNode = ( node: AST.Node, ): Expression => fromResult(Result.succeed(node)); +/** A replacement call signature with the source expression's semantic metadata. */ +export type Adapted = C & + Pick, typeof TypeId | typeof Binding> & { + readonly $: Fluent.Operations, I>; + } & Relocatable>; + +/** + * Adapts host arguments while preserving expression metadata and rebinding. + * + * The adapter must retain the represented function's meaning. It may accept additional host shorthand and normalize it before emitting a call. The factory receives the rebound expression on each relocation, so its calls cannot retain an earlier path. Metadata is copied explicitly because it need not be enumerable on a forwarding proxy. + */ +export const adaptCallable: { + Any>( + adapt: (self: Expression) => C, + ): (self: Expression) => Adapted; + Any>( + self: Expression, + adapt: (self: Expression) => C, + ): Adapted; +} = Function.dual( + 2, + Any>( + self: Expression, + adapt: (self: Expression) => C, + ): Adapted => + Object.assign(adapt(self), { + [TypeId]: self[TypeId], + [Binding]: self[Binding], + $: self.$, + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + self[Relocate](path), + Result.map((moved) => adaptCallable(moved, adapt)), + ), + }), +); + /** * Changes the SDK's type assumption without changing the query syntax. * diff --git a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts index e7c3f4f7cce..74fbcb50464 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts @@ -1,3 +1,10 @@ +/** + * Type-level normalization, calls and projections for symbolic values. + * + * Union projections require the field in every alternative. Intersections combine field descriptors, while index access includes Null for an absent element. These calculations retain the source expression's input requirements. + * + * @module + */ import type * as Type from "../type/index.js"; import type * as Expression from "./Expression.js"; import type * as Input from "./Inputs.js"; @@ -291,7 +298,7 @@ type IndexOf = [T] extends [Type.List] type ProjectionAccessors = { readonly [Key in Exclude< keyof Fields, - "$" | "$project" | "$index" | "then" | "~hashql/Expression" + "$" | "$project" | "$index" | "~hashql/Expression" >]: Fields[Key] extends infer Field extends Type.Any ? Expression.Expression, Inputs> : never; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts index 8dc760e1f16..68539646b0d 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts @@ -39,6 +39,67 @@ declare const optionalDefault: | undefined; describe("input_requirements", () => { + test("host_alternatives_keep_every_requirement", () => { + type Alternatives = + | { readonly first: Type.PrimitiveInteger } + | { readonly second: Type.PrimitiveString }; + expectTypeOf< + Inputs.Merge + >().toEqualTypeOf<{ + readonly first: Type.PrimitiveInteger; + readonly second: Type.PrimitiveString; + readonly third: Type.PrimitiveBoolean; + }>(); + expectTypeOf< + Inputs.Conservative< + Inputs.Empty | { readonly first: Type.PrimitiveInteger } + > + >().toEqualTypeOf<{ readonly first: Type.PrimitiveInteger }>(); + expectTypeOf< + Inputs.Conservative< + | { readonly same: Type.PrimitiveInteger } + | { readonly same: Type.PrimitiveString } + > + >().toEqualTypeOf<{ readonly same: Type.Never }>(); + const alternative = + Math.random() > 0.5 + ? Expression.input("first", integer) + : Expression.input("second", integer); + const composed = Expression.ifElse(true, { then: alternative, else: 0n }); + // @ts-expect-error an empty annotation cannot hide host-side alternatives + const closed: Expression.Expression = + composed; + expectTypeOf(closed); + const choose = (): + | Expression.Expression + | Expression.Expression< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + > => + Math.random() > 0.5 + ? Expression.input("first", integer) + : Expression.integer(0); + const possiblyClosed = choose(); + const combined = Expression.ifElse(true, { + then: possiblyClosed, + else: 0n, + }); + // @ts-expect-error a closed alternative cannot make a required alternative disappear through contravariance + const hidden: Expression.Expression = + combined; + expectTypeOf(hidden); + // Do's contextual callback requires a common record for this ambiguous host union. + const block = EmptyDo< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + >(() => choose()); + // @ts-expect-error a block also keeps the required alternative + const hiddenBlock: Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty + > = Result.getOrThrow(block); + expectTypeOf(hiddenBlock); + }); test("required_and_default", () => { const required = Expression.input("count", integer); const optional = Expression.input("limit", integer, Expression.integer(10)); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts index e0f234e4050..52fd45003b1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts @@ -5,6 +5,11 @@ import type { Types } from "effect"; // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a closed expression requires no input names export type Empty = Record; +declare const ErasedRequirement: unique symbol; + +/** Unrecoverable requirements cannot be discharged by a named input schema. */ +export type Erased = { readonly [ErasedRequirement]: Type.Unknown }; + type RequiredKeys = { [Key in keyof Inputs]-?: Empty extends Pick ? never : Key; }[keyof Inputs]; @@ -23,8 +28,54 @@ type Combined = Key extends keyof Left : At : At; -/** A shared input must satisfy every use. One required use makes it required. */ -export type Merge = [keyof Right] extends [never] +type Last = + Types.UnionToIntersection< + Alternatives extends unknown ? () => Alternatives : never + > extends () => infer Member + ? Member + : never; + +// Invariance keeps a closed alternative from swallowing a narrower required record during Exclude. +type InvariantAlternatives = Requirements extends unknown + ? (value: Requirements) => Requirements + : never; + +type Unwrap = Alternative extends ( + value: infer Requirements, +) => unknown + ? Requirements + : never; + +type CollapseAlternatives = [ + Alternatives, +] extends [never] + ? Accumulated + : [Alternatives] extends [Types.UnionToIntersection] + ? MergeRecords> + : CollapseAlternatives< + Exclude>, + MergeRecords>> + >; + +/** Requires every member of a host-side alternative, preserving shared semantic constraints. */ +export type Conservative = [Requirements] extends [never] + ? Erased + : unknown extends Requirements + ? Erased + : CollapseAlternatives>; + +/** A shared input must satisfy every use, including every host-side union alternative. */ +export type Merge = [keyof Conservative] extends [never] + ? Left + : typeof ErasedRequirement extends + | keyof Conservative + | keyof Conservative + ? never + : [keyof Conservative] extends [never] + ? Conservative + : MergeRecords, Conservative>; + +type MergeRecords = [keyof Right] extends [never] ? Left : [keyof Left] extends [never] ? Right @@ -51,5 +102,5 @@ export type All = Members extends readonly [ ] ? Merge> : number extends Members["length"] - ? Types.UnionToIntersection + ? Conservative : Empty; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts index 463d40ef0dc..9d2cc2868c9 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts @@ -7,10 +7,11 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; import * as Module from "./Module.js"; import type * as Type from "../type/index.js"; -import type * as Expression from "./Expression.js"; import type * as Inputs from "./Inputs.js"; import type { TypeExpression } from "./TypeExpression.js"; @@ -226,6 +227,45 @@ describe("module_types", () => { >(); }); + test("relocated_members", () => { + const local = Result.getOrThrow(JExpr.Path.decodeResult("local")); + const relocated = Result.getOrThrow( + Module.relocate(modules.modules.core, local), + ); + expectTypeOf(relocated.modules.math.values.rem).toEqualTypeOf< + typeof prelude.rem + >(); + expectTypeOf(relocated.modules.uuid.types.Uuid).toEqualTypeOf< + TypeExpression + >(); + expectTypeOf(relocated.modules.uuid.values.Uuid(string)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The relocated function retains its semantic parameter types. + relocated.modules.math.values.rem(string, integer); + // @ts-expect-error Relocation does not introduce undeclared names. + expectTypeOf(relocated.modules.missing); + + const input = Expression.input("count", prelude.Integer); + const source = Result.getOrThrow( + Module.define("::inputs", { values: { count: input } }), + ); + const moved = Result.getOrThrow(Module.relocate(source, local)); + expectTypeOf(moved.values.count).toEqualTypeOf(); + // @ts-expect-error An imported reference still carries its source input requirement. + const closed: Expression.Expression = + moved.values.count; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + }); + + test("unpreserved_extension", () => { + const extended = Object.assign(prelude.Integer, { annotation: "extra" }); + // @ts-expect-error The type's rebinding operation does not promise to retain caller-added properties. + expectTypeOf(Module.define("::extended", { types: { Integer: extended } })); + }); + test("tree_members", () => { expectTypeOf(modules.modules.core.modules.math.values.rem).toEqualTypeOf< typeof prelude.rem diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts index 7fca98c90ed..c620a5114db 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts @@ -218,6 +218,82 @@ describe("module_exports", () => { }); }); +describe("module_relocation", () => { + test("nested_exports", () => { + expect.hasAssertions(); + const root = Result.getOrThrow( + Module.define("::source", { + modules: { arithmetic: math }, + types: { Integer: prelude.Integer, Sequence: prelude.List }, + values: { Uuid: uuid.values.Uuid }, + }), + ); + const local = Result.getOrThrow( + Module.relocate( + root, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ), + ); + expect( + compile(local.modules.arithmetic.values.rem(dividend, divisor)), + ).toBe('["local::arithmetic::rem",{"#literal":7},{"#literal":3}]'); + expect( + TypeSyntax.compile( + Result.getOrThrow(local.types.Sequence(prelude.Integer).syntax), + ), + ).toBe("local::Sequence<::kernel::type::Integer>"); + expect( + TypeSyntax.compile(Result.getOrThrow(local.types.Integer.syntax)), + ).toBe("local::Integer"); + expect(compile(local.values.Uuid("id"))).toBe( + '["local::Uuid",{"#literal":"id"}]', + ); + }); + + test("repeated_relocation", () => { + expect.hasAssertions(); + const root = Result.getOrThrow( + Module.define("::source", { modules: { arithmetic: math } }), + ); + const local = Result.getOrThrow( + Module.relocate( + root, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ), + ); + const second = Result.getOrThrow( + Module.relocate( + local, + Result.getOrThrow(JExpr.Path.decodeResult("second")), + ), + ); + expect( + compile(second.modules.arithmetic.values.rem(dividend, divisor)), + ).toBe('["second::arithmetic::rem",{"#literal":7},{"#literal":3}]'); + expect(compile(math.values.rem(dividend, divisor))).toBe( + '["::core::math::rem",{"#literal":7},{"#literal":3}]', + ); + }); + + test("value_failure", () => { + expect.hasAssertions(); + const invalid = Expression.number(Infinity); + const source = Result.getOrThrow( + Module.define("::source", { values: { invalid } }), + ); + const result = Module.relocate( + source, + Result.getOrThrow(JExpr.Path.decodeResult("local")), + ); + expect( + Result.match(result, { + onFailure: (error) => error.reason._tag, + onSuccess: () => null, + }), + ).toBe("InvalidExpression"); + }); +}); + describe("module_construction", () => { test("record_snapshot", () => { expect.hasAssertions(); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.ts index a6f0a4a5d3b..f3b000c5df9 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.ts @@ -7,11 +7,16 @@ */ import { Predicate, Result, flow, pipe } from "effect"; +import { + Relocate, + relocate as relocateHandle, +} from "../internal/relocation.js"; import * as JExpr from "../jexpr/index.js"; import * as Expression from "./Expression.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; +import type { Relocatable } from "../internal/relocation.js"; import type * as Type from "../type/index.js"; import type * as Inputs from "./Inputs.js"; import type { ReadonlyRecord } from "effect/Record"; @@ -35,7 +40,7 @@ type Declarations = { }; /** A module with its concrete export names erased. */ -export interface Any { +export interface Any extends Relocatable { readonly [TypeId]: true; readonly path: JExpr.Path.Path; readonly modules: Namespace; @@ -70,7 +75,7 @@ type Exports = { }; /** Bound tables retain their key-to-export relationships independently of the source declarations. */ -interface Bound { +interface Bound extends Relocatable> { readonly [TypeId]: true; readonly path: JExpr.Path.Path; readonly modules: Readonly; @@ -78,6 +83,25 @@ interface Bound { readonly values: Readonly; } +/** Each entry must retain its own rebinding result, not merely a common export type. */ +type Rebindings = { readonly [K in keyof E]: Relocatable }; + +/** A declared or existing export must preserve its promised capabilities when imported. */ +type Rebindable = + E extends Declaration + ? Declaration> + : E extends undefined + ? undefined + : E & Relocatable; + +type RebindableEntries = { readonly [K in keyof E]: Rebindable }; + +type RebindableDefinition = { + readonly [K in keyof S]: K extends keyof Definition + ? RebindableEntries + : S[K]; +}; + /** An immutable module record preserving each export's concrete type. */ export interface Module extends Bound< Entries, @@ -214,6 +238,55 @@ const bind = >( return mapEntries>(entries, resolve); }; +/** Rebinds each member using the result type retained by that member's producer. */ +const rebase = < + E extends Namespace & + Rebindings, +>( + path: JExpr.Path.Path, + entries: E, +): Result.Result, ProgramError.Construction> => { + const sources: Rebindings = entries; + const resolve = ( + name: K, + _entry: E[K], + ident: JExpr.Ident.Ident, + ): Result.Result => + relocateHandle(sources[name], { + rooted: path.rooted, + segments: [...path.segments, ident], + }); + + return mapEntries(entries, resolve); +}; + +/** Captures typed export tables so rebinding preserves each member's result type. */ +const bound = < + M extends Namespace & Rebindings, + T extends Namespace & Rebindings, + V extends Namespace & Rebindings, +>( + path: JExpr.Path.Path, + entries: { readonly modules: M; readonly types: T; readonly values: V }, +): Bound => + Object.freeze({ + [TypeId]: true as const, + path, + ...entries, + [Relocate]: ( + next: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + { + modules: rebase(next, entries.modules), + types: rebase(next, entries.types), + values: rebase(next, entries.values), + }, + Result.all, + Result.map((exports) => bound(next, exports)), + ), + }); + /** * Binds new declarations and retains existing exports by identity. * @@ -224,12 +297,12 @@ const bind = >( // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the module under construction export function define( name: string, - definition: S, + definition: S & RebindableDefinition, ): Result.Result, ProgramError.Construction>; export function define< - M extends Namespace, - T extends Namespace, - V extends Namespace, + M extends Namespace & Rebindings, + T extends Namespace & Rebindings, + V extends Namespace & Rebindings, >( name: string, definition: { @@ -265,9 +338,7 @@ export function define< modules = yield* copyModules(definition.modules); } - return Object.freeze({ - [TypeId]: true as const, - path, + return bound(path, { modules, types: yield* bind(path, definition.types), values: yield* bind(path, definition.values), @@ -275,63 +346,18 @@ export function define< }); } -/** Rebinds a module and its exports beneath a locally imported module name. */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- internal module rebinding requires both the module and its local path -export const relocate = ( - module: Any, - path: JExpr.Path.Path, -): Result.Result => - Result.gen(function* () { - const modules: [string, Any][] = []; - const values: [string, Expression.Any][] = []; - const types: [string, TypeExpression.Export][] = []; - - for (const [name, child] of Object.entries(module.modules)) { - const ident = yield* memberName(name); - - modules.push([ - name, - yield* relocate(child, { - rooted: path.rooted, - segments: [...path.segments, ident], - }), - ]); - } - - for (const name of Object.keys(module.values)) { - const ident = yield* memberName(name); - - values.push([ - name, - Expression.fromJExpr( - JExpr.Path.compile({ - rooted: path.rooted, - segments: [...path.segments, ident], - }), - ), - ]); - } - - for (const [name, type] of Object.entries(module.types)) { - const ident = yield* memberName(name); - - types.push([ - name, - yield* TypeExpression.relocate(type, { - rooted: path.rooted, - segments: [...path.segments, ident], - }), - ]); - } - - return Object.freeze({ - [TypeId]: true as const, - path, - modules: Object.freeze(Object.fromEntries(modules)), - values: Object.freeze(Object.fromEntries(values)), - types: Object.freeze(Object.fromEntries(types)), - }); - }); +/** Rebinds a module tree while preserving each export's declared type. */ +export const relocate: { + ( + path: JExpr.Path.Path, + ): ( + self: Any & Relocatable, + ) => Result.Result; + ( + self: Any & Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = relocateHandle; /** Assembles already-bound modules without rebasing their references. */ export const root = >( diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts new file mode 100644 index 00000000000..d7789a81eea --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts @@ -0,0 +1,170 @@ +/** + * Static checks for joined capabilities, optional names and relocation. + * + * @module + */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../jexpr/index.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; +import * as Namespace from "./Namespace.js"; +import * as Structural from "./Structural.js"; + +import type { Inputs, Type, TypeExpression } from "../main.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const identity = Symbol("Item"); +type Item = Type.Opaque; +const child = Result.getOrThrow( + Module.define("::child", { + values: { + count: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + }, + }), +); +const source = Result.getOrThrow( + Module.define("::source", { + modules: { Item: child, List: child }, + types: { Item: Module.type(), List: Module.genericType(1) }, + values: { + Item: Module.value< + Type.Function + >(), + List: Module.value< + Type.Function + >(), + }, + }), +); +const flat = Namespace.flatten(source); +const path = Result.getOrThrow(JExpr.Path.decodeResult("local")); + +describe("namespace_types", () => { + test("joined_types", () => { + expectTypeOf(flat.Item(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(flat.Item.count).toEqualTypeOf(); + expectTypeOf(flat.Item.then).toEqualTypeOf(); + expectTypeOf(Structural.type(flat.Item)).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + expectTypeOf(flat.List(Structural.type(BigInt))).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expectTypeOf(flat.List(1n)).toEqualTypeOf< + Expression.Expression + >(); + // @ts-expect-error The value constructor requires Integer. + flat.Item("wrong"); + // @ts-expect-error No namespace declared this name. + expectTypeOf(flat.missing); + // @ts-expect-error Empty type tables do not introduce arbitrary names. + expectTypeOf(flat.Item.types.missing); + }); + + test("joined_relocation", () => { + const moved = Result.getOrThrow(relocate(flat.List, path)); + expectTypeOf(moved).toEqualTypeOf(); + expectTypeOf(moved.count).toEqualTypeOf(); + expectTypeOf(moved(Structural.type(String))).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expectTypeOf(moved(1n)).toEqualTypeOf< + Expression.Expression + >(); + const twice = Result.getOrThrow(relocate(moved, path)); + expectTypeOf(twice).toEqualTypeOf(); + }); + + test("optional_names", () => { + const types: { + readonly Maybe?: TypeExpression.TypeExpression; + } = {}; + const modules: { readonly child?: typeof child } = {}; + const optional = Namespace.flatten({ modules, types, values: {} }); + expectTypeOf(optional.Maybe).toEqualTypeOf< + TypeExpression.TypeExpression | undefined + >(); + expectTypeOf>().toEqualTypeOf< + typeof types + >(); + // @ts-expect-error Narrow the optional module before reading its members. + expectTypeOf(optional.child.count); + const explicit = Namespace.modules({ modules, types: {}, values: {} }); + // @ts-expect-error Explicit module views also preserve optional entries. + expectTypeOf(explicit.child.count); + const shared = Namespace.flatten({ + modules: {}, + types, + values: { Maybe: Expression.integer(1) }, + }); + expectTypeOf(shared.Maybe).not.toBeUndefined(); + }); + + test("projection_collision", () => { + const value = Structural.value< + Type.Struct<{ + readonly count: Type.PrimitiveString; + readonly own: Type.PrimitiveBoolean; + }> + >()({ count: "shadowed", own: true }); + const joined = Namespace.flatten({ + modules: { Both: child }, + types: { Both: Structural.type(BigInt) }, + values: { Both: value }, + }).Both; + expectTypeOf(joined.count).toEqualTypeOf(); + expectTypeOf(joined.own).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(joined.$project("count")).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(Structural.type(joined)).toEqualTypeOf< + TypeExpression.TypeExpression + >(); + }); + + test("unpreserved_properties", () => { + const extended = Object.assign(Structural.type(BigInt), { note: "extra" }); + // @ts-expect-error Rebinding the producer would drop note. + Namespace.combine(extended, Expression.integer(1)); + Namespace.flatten({ + modules: {}, + // @ts-expect-error A joined namespace must preserve every promised property. + types: { Both: extended }, + values: { Both: Expression.integer(1) }, + }); + expectTypeOf(extended.note).toEqualTypeOf(); + const optional: { readonly Both?: typeof extended } = {}; + // @ts-expect-error Optional producers must preserve their properties when present. + Namespace.flatten({ modules: {}, types: optional, values: {} }); + }); + + test("input_requirements", () => { + const input = Expression.input("count", Structural.type(BigInt)); + const joined = Namespace.combine(input, Structural.type(BigInt)); + const moved = Result.getOrThrow(relocate(joined, path)); + expectTypeOf>().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + }>(); + // @ts-expect-error Moving a reference does not erase its input requirement. + const closed: Expression.Expression = + moved; + expectTypeOf(closed).toEqualTypeOf< + Expression.Expression + >(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts new file mode 100644 index 00000000000..22fc8d2d5d7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts @@ -0,0 +1,232 @@ +/** + * Runtime checks for namespace forwarding and relocation of joined handles. + * + * @module + */ +import { Result, flow } from "effect"; +import { describe, expect, test } from "vitest"; + +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../jexpr/index.js"; +import * as TypeSyntax from "../jexpr/type/index.js"; +import { Expression, Module, Structural, TypeExpression } from "../main.js"; +import * as Namespace from "./Namespace.js"; + +import type * as Type from "../type/index.js"; + +interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : Type.Never; +} + +const path = flow(JExpr.Path.decodeResult, Result.getOrThrow); +const valueSyntax = flow(Expression.toJExpr, Result.getOrThrow); +const typeSyntax = flow( + TypeExpression.toType, + Result.getOrThrow, + TypeSyntax.compile, +); +const child = Result.getOrThrow( + Module.define("::child", { + values: { + count: Module.value(), + // oxlint-disable-next-line unicorn/no-thenable -- this is a HashQL export name + then: Module.value(), + $: Module.value(), + name: Module.value(), + length: Module.value(), + prototype: Module.value(), + constructor: Module.value(), + toString: Module.value(), + syntax: Module.value(), + }, + }), +); +const source = Result.getOrThrow( + Module.define("::source", { + modules: { Both: child }, + types: { Both: Module.genericType(1) }, + values: { + Both: Module.value< + Type.Function + >(), + }, + }), +); + +describe("namespace", () => { + test("joined_dispatch", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined).toSatisfy(TypeExpression.isConstructor); + expect(joined).toSatisfy(Expression.isExpression); + expect(joined).toSatisfy(Module.isModule); + expect(typeSyntax(joined(Structural.type(BigInt)))).toBe( + "::source::Both<::kernel::type::Integer>", + ); + expect(valueSyntax(joined(1n))).toStrictEqual([ + "::source::Both", + { "#literal": { _tag: "Integer", value: "1" } }, + ]); + }); + + test("joined_relocation", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + const moved = Result.getOrThrow(relocate(joined, path("local"))); + expect(typeSyntax(moved(Structural.type(String)))).toBe( + "local<::kernel::type::String>", + ); + expect(valueSyntax(moved(1n))).toStrictEqual([ + "local", + { "#literal": { _tag: "Integer", value: "1" } }, + ]); + expect(valueSyntax(moved.count)).toBe("local::count"); + }); + + test("repeated_relocation", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + const moved = Result.getOrThrow(relocate(joined, path("local"))); + const twice = Result.getOrThrow(relocate(moved, path("again"))); + expect(typeSyntax(twice(Structural.type(BigInt)))).toBe( + "again<::kernel::type::Integer>", + ); + expect(valueSyntax(twice.count)).toBe("again::count"); + expect(valueSyntax(joined.count)).toBe("::child::count"); + }); + + test("ordinary_then", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined.then).toBe(child.values.then); + expect("then" in joined).toBe(true); + expect(Namespace.modules(source).Both.then).toBe(child.values.then); + expect(joined.values.$).toBe(child.values.$); + expect(Expression.isExpression(joined.$)).toBe(false); + }); + + test("function_intrinsics", () => { + expect.hasAssertions(); + const joined = Namespace.flatten(source).Both; + expect(joined.name).toBe(child.values.name); + // oxlint-disable-next-line vitest/prefer-to-have-length -- length holds the declared HashQL export + expect(joined.length).toBe(child.values.length); + expect(joined.prototype).toBe(child.values.prototype); + expect(joined.constructor).toBe(child.values.constructor); + expect(joined.toString).toBe(child.values.toString); + }); + + test("projection_collision", () => { + expect.hasAssertions(); + const value = Structural.value< + Type.Struct<{ + readonly count: Type.PrimitiveString; + readonly own: Type.PrimitiveBoolean; + }> + >()({ count: "shadowed", own: true }); + const joined = Namespace.flatten({ + modules: { Both: child }, + types: { Both: Structural.type(BigInt) }, + values: { Both: value }, + }).Both; + expect(joined.count).toBe(child.values.count); + expect(typeSyntax(joined)).toBe("::kernel::type::Integer"); + expect(valueSyntax(joined.own)).toStrictEqual(valueSyntax(value.own)); + expect(valueSyntax(joined.$project("count"))).toStrictEqual( + valueSyntax(value.count), + ); + }); + + test("prototype_names", () => { + expect.hasAssertions(); + const custom = Result.getOrThrow( + Module.define("::custom", { + modules: { ["__proto__"]: child }, + types: { ["__proto__"]: Module.type() }, + values: { ["__proto__"]: Module.value() }, + }), + ); + // oxlint-disable-next-line eslint/no-proto -- this is an ordinary HashQL export + const joined = Namespace.flatten(custom).__proto__; + expect(joined).toSatisfy(Module.isModule); + expect(joined).toSatisfy(TypeExpression.isExport); + expect(joined).toSatisfy(Expression.isExpression); + expect(joined.count).toBe(child.values.count); + }); + + test("inherited_name", () => { + expect.hasAssertions(); + const typeOnly = Namespace.flatten({ + modules: {}, + types: { toString: Structural.type(BigInt) }, + values: {}, + }); + expect(typeOnly.toString).toSatisfy(TypeExpression.isExport); + expect(typeOnly.toString).not.toSatisfy(Expression.isExpression); + }); + + test("optional_absence", () => { + expect.hasAssertions(); + const modules: { readonly child?: typeof child } = {}; + const types: { + readonly Integer?: TypeExpression.TypeExpression; + } = {}; + expect( + Object.keys(Namespace.flatten({ modules, types, values: {} })), + ).toStrictEqual([]); + expect( + Object.keys(Namespace.modules({ modules, types, values: {} })), + ).toStrictEqual([]); + }); + + test("nonenumerable_names", () => { + expect.hasAssertions(); + const types = { Integer: Structural.type(BigInt) }; + Object.defineProperty(types, "Integer", { enumerable: false }); + const flat = Namespace.flatten({ modules: {}, types, values: {} }); + expect(flat.Integer).toBe(types.Integer); + expect(Object.keys(flat)).toStrictEqual(["Integer"]); + }); + + test("joined_failure", () => { + expect.hasAssertions(); + const failed = Expression.number(Number.NaN); + const joined = Namespace.combine(failed, Structural.type(BigInt)); + expect(relocate(joined, path("local"))).toMatchObject({ _tag: "Failure" }); + }); + + test("module_view_relocation", () => { + expect.hasAssertions(); + const tree = Result.getOrThrow( + Module.define("::tree", { modules: { nested: child } }), + ); + const view = Namespace.modules({ + modules: { tree }, + types: {}, + values: {}, + }).tree; + const moved = Result.getOrThrow(relocate(view, path("local"))); + expect(valueSyntax(moved.nested.count)).toBe("local::nested::count"); + expect(valueSyntax(moved.modules.nested.values.count)).toBe( + "local::nested::count", + ); + }); + + test("join_order", () => { + expect.hasAssertions(); + const module = Namespace.modules(source).Both; + const value = Structural.value< + Type.Struct<{ readonly count: Type.PrimitiveString }> + >()({ count: "shadowed" }); + const type = Structural.type(BigInt); + const joined = Namespace.combine(Namespace.combine(type, value), module); + expect(typeSyntax(joined)).toBe("::kernel::type::Integer"); + expect(joined.count).toBe(child.values.count); + expect(valueSyntax(joined.$project("count"))).toStrictEqual( + valueSyntax(value.count), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts new file mode 100644 index 00000000000..c5fd75cf714 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts @@ -0,0 +1,509 @@ +/** + * Shared names with separate module, type and value capabilities. + * + * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Expression operations remain available through `$`, `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. + * + * @module + */ +import { Function, Predicate, Result, pipe } from "effect"; + +import { Relocate } from "../internal/relocation.js"; +import * as Expression from "./Expression.js"; +import * as Module from "./Module.js"; +import * as Structural from "./Structural.js"; +import * as TypeExpression from "./TypeExpression.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type { JExpr, Type } from "../main.js"; +import type { Accessors } from "./ExpressionType.js"; +import type * as ProgramError from "./ProgramError.js"; +import type * as Scope from "./Scope.js"; + +/** A producer that retains a rebinding operation in its result. */ +interface Capability extends Relocatable {} + +type RebindableEntry = E extends Capability ? Relocatable : E; + +/** Scope exports need string names and producers that preserve their properties during rebinding. */ +export type Rebindable = { + readonly [N in keyof S]: N extends keyof Scope.Scope + ? { + readonly [K in keyof S[N]]: K extends symbol + ? never + : RebindableEntry; + } + : S[N]; +}; +const Components: unique symbol = Symbol("~hashql/NamespaceComponents"); + +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent capability contributes no properties +type Empty = Record; +type Present = E extends undefined ? Empty : E; +type Lookup = K extends keyof S ? S[K] : undefined; + +/** Keeps original producers available after repeated joins, including their generic call signatures. */ +type Part = E extends { + readonly [Components]: readonly [infer L, infer R]; +} + ? Part extends undefined + ? Part + : Part + : E extends C + ? E + : undefined; + +type Parts = Part extends undefined ? Part : Part; + +type Metadata = Omit< + Present, + keyof Present | (V extends Expression.Any ? ExpressionReserved : never) +> & + Present; + +type ExpressionReserved = "$" | "$project" | "$index" | "~hashql/Expression"; + +/** Removes shadowed projections without discarding generic call signatures. */ +type WithMetadata = V extends Expression.Any + ? M & + (Expression.TypeOf extends + | Type.Function.Any + | Type.GenericFunction.Any + | Type.Primitive + ? V + : Expression.Handle, Expression.Inputs> & + Omit< + Accessors, Expression.Inputs>, + Exclude + > & + Pick< + Expression.Expression, Expression.Inputs>, + "$" + >) + : M & V; + +type Combined = WithMetadata< + Present>, + Metadata< + Parts, + Parts, + Parts + > +>; + +/** The last relocation signature returns the whole joined capability set. */ +export type Joined = Combined & { + readonly [Components]: readonly [L, R]; +} & Relocatable>; + +/** Distributes over optional entries instead of intersecting their undefined alternatives. */ +type Selected = L extends undefined + ? R + : R extends undefined + ? L + : Joined; + +type ModuleView = M & + Omit, keyof M> & + Relocatable>; + +type Viewed = M extends Module.Any ? ModuleView : undefined; + +type Member = Selected, V>, T>; + +type Keys = + | keyof S["modules"] + | keyof S["types"] + | keyof S["values"]; + +type RequiredKeys = { + [K in keyof S]-?: undefined extends S[K] ? never : K; +}[keyof S]; + +type RequiredNames = + | RequiredKeys + | RequiredKeys + | RequiredKeys; + +/** A guaranteed export in any namespace makes the flattened name required. */ +export type Flatten = { + readonly [K in Keys as K extends RequiredNames ? K : never]: Member< + Lookup, + Lookup, + Lookup + >; +} & { + readonly [K in Keys as K extends RequiredNames ? never : K]?: Exclude< + Member< + Lookup, + Lookup, + Lookup + >, + undefined + >; +}; + +export type Modules = { + readonly [K in keyof S["modules"]]: Viewed; +}; + +const combinedHandles = new WeakMap< + Capability, + readonly [] | readonly [Capability, Capability] +>(); + +/** Finds the original producer rather than mistaking a combined marker for a second producer. */ +const find = ( + candidate: Capability, + predicate: (candidate: Capability) => candidate is E, +): E | undefined => { + const components = combinedHandles.get(candidate); + if (components?.length === 2) { + return find(components[1], predicate) ?? find(components[0], predicate); + } + + if (predicate(candidate)) { + return candidate; + } + + return undefined; +}; + +// Function intrinsics are not declared namespace exports. Joined proxies check their sources. +const hasExport = (candidate: Capability, key: PropertyKey): boolean => { + if (combinedHandles.has(candidate)) { + return key in candidate; + } + + if (typeof candidate === "function") { + return Object.prototype.propertyIsEnumerable.call(candidate, key); + } + + return Object.hasOwn(candidate, key); +}; + +const expressionReserved = new Set([ + "$", + "$project", + "$index", + "~hashql/Expression", +]); + +/** + * Selects a callable capability from the runtime argument category. + * + * Proxy calls arrive without their generic argument tuple. The public intersection retains each source signature. This boundary invokes only the matching SDK callable. Its result is another SDK capability. + */ +const invoke = ( + candidate: Capability | undefined, + // oxlint-disable-next-line typescript/no-restricted-types -- a proxy call receives unchecked host arguments + args: readonly unknown[], +): Capability | undefined => { + if (typeof candidate !== "function") { + return undefined; + } + + const typeCall = + TypeExpression.isConstructor(candidate) && + args.every(Structural.isDefinition); + + const valueCall = + Expression.isExpression(candidate) && args.every(Structural.isValue); + + if (!typeCall && !valueCall) { + return undefined; + } + + // SAFETY: each matching SDK callable returns a type or value handle. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- invocation erases the argument tuple at the proxy boundary + return Reflect.apply(candidate, undefined, args) as Capability; +}; + +/** Joins concrete capability producers and rebinds both with their original result types. */ +export const combine: { + >( + right: R, + ): >(left: L) => Joined; + < + L extends Capability & Relocatable, + R extends Capability & Relocatable, + >( + left: L, + right: R, + ): Joined; +} = Function.dual( + 2, + < + L extends Capability & Relocatable, + R extends Capability & Relocatable, + >( + left: L, + right: R, + ): Joined => { + const leftSource: Relocatable = left; + const rightSource: Relocatable = right; + + const rebind = ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + Result.all({ + left: leftSource[Relocate](path), + right: rightSource[Relocate](path), + }), + Result.map((moved) => combine(moved.left, moved.right)), + ); + + const type = + find(right, TypeExpression.isExport) ?? + find(left, TypeExpression.isExport); + + const value = + find(right, Expression.isExpression) ?? + find(left, Expression.isExpression); + + const module = find(right, Module.isModule) ?? find(left, Module.isModule); + + // oxlint-disable-next-line typescript/no-restricted-types -- proxy invocation selects a callable from the host arguments + const callable = (...args: readonly unknown[]): Capability | undefined => { + const first = invoke(type, args); + const second = invoke(value, args); + + if (first === undefined) { + return second; + } + + if (second === undefined) { + return first; + } + + return combine(first, second); + }; + + const components: readonly [L, R] = [left, right]; + + let target: Relocatable> = { [Relocate]: rebind }; + if (typeof left === "function" || typeof right === "function") { + target = Object.assign(callable, target); + } + + const proxy = new Proxy(target, { + has: (_target, key): boolean => + key === Relocate || + key === Components || + hasExport(left, key) || + hasExport(right, key), + // oxlint-disable-next-line typescript/no-restricted-types -- a property trap returns heterogeneous host properties + get: (_target, key): unknown => { + if (key === Components) { + return components; + } + + if (key === Relocate) { + return rebind; + } + + if (expressionReserved.has(key) && value !== undefined) { + return Reflect.get(value, key); + } + + if (type !== undefined && hasExport(type, key)) { + return Reflect.get(type, key); + } + + if (module !== undefined && hasExport(module, key)) { + return Reflect.get(module, key); + } + + if (value !== undefined) { + return Reflect.get(value, key); + } + + return Reflect.get(_target, key); + }, + }); + + combinedHandles.set(proxy, components); + + // SAFETY: property forwarding implements Combined; rebind already returns Joined. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy cannot express forwarded properties or overloaded calls + return proxy as Joined; + }, +); + +function select< + L extends Capability | undefined, + R extends Capability | undefined, +>(left: L, right: R): Selected; +function select< + L extends Capability & Relocatable, + R extends Capability & Relocatable, +>(left: L | undefined, right: R | undefined): L | R | Joined | undefined { + if (left === undefined) { + return right; + } + + if (right === undefined) { + return left; + } + + return combine(left, right); +} + +/** A module view rebuilds its flattened children from the rebound module. */ +function viewModule(module: M): ModuleView; +function viewModule>( + module: M, +): ModuleView { + // oxlint-disable-next-line eslint/no-use-before-define -- module views and child flattening are mutually recursive + const children = flattenScope(module); + const source: Relocatable = module; + + const rebind = ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe( + source[Relocate](path), + Result.map((moved) => viewModule(moved)), + ); + + const target = { [Relocate]: rebind }; + const proxy = new Proxy(target, { + has: (_target, key): boolean => + key === Relocate || + hasExport(module, key) || + Object.hasOwn(children, key), + // oxlint-disable-next-line typescript/no-restricted-types -- a property trap returns heterogeneous host properties + get: (_target, key): unknown => { + if (key === Relocate) { + return rebind; + } + if (hasExport(module, key)) { + return Reflect.get(module, key); + } + return Reflect.get(children, key); + }, + }); + + combinedHandles.set(proxy, []); + + // SAFETY: module properties take precedence over children, exactly as ModuleView specifies. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy does not model forwarded properties + return proxy as ModuleView; +} + +function viewOptional(module: M): Viewed; +function viewOptional( + module: M | undefined, +): ModuleView | undefined { + if (module === undefined) { + return undefined; + } + return viewModule(module); +} + +/** Resolves one key while retaining all three source export types. */ +const member = < + M extends Module.Any | undefined, + T extends TypeExpression.Export | undefined, + V extends Expression.Any | undefined, +>( + module: M, + type: T, + value: V, +): Member => select(select(viewOptional(module), value), type); + +/** Reads own names to exclude inherited object properties from namespace declarations. */ +function lookup( + table: S, + name: K, +): Lookup; +function lookup( + table: Readonly>, + name: K, +): E | undefined { + if (Object.hasOwn(table, name)) { + return table[name]; + } + + return undefined; +} + +/** Per-key results before mapping absent alternatives to optional properties. */ +type Members = { + readonly [K in Keys]: Member< + Lookup, + Lookup, + Lookup + >; +}; + +/** Property definition preserves __proto__ without losing the key-to-value relationship. */ +const define = ( + table: Partial, + name: K, + value: O[K], +): void => { + Object.defineProperty(table, name, { value, enumerable: true }); +}; + +/** Copies each namespace key once without introducing names from missing tables. */ +const flattenScope = (scope: S): Flatten => { + const entries: Partial> = {}; + + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K ties three lookups to the same destination member + const resolve = & string>(name: K): void => { + const value = member( + lookup(scope.modules, name), + lookup(scope.types, name), + lookup(scope.values, name), + ); + + if (value !== undefined) { + define, K>(entries, name, value); + } + }; + + const names = new Set([ + ...Object.getOwnPropertyNames(scope.modules), + ...Object.getOwnPropertyNames(scope.types), + ...Object.getOwnPropertyNames(scope.values), + ]); + + for (const name of names) { + resolve(name); + } + + // SAFETY: the loop checks each own key at Members[K]. Absent alternatives become optional properties. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes the per-key mapped table after enumerating its names + return Object.freeze(entries) as Flatten; +}; + +/** Joins a checked scope. Module.define performs the same producer check for nested tables. */ +export const flatten = ( + scope: S & Rebindable, +): Flatten => flattenScope(scope); + +/** Keeps only module names, with their child exports available directly. */ +export const modules = ( + scope: S & Pick, "modules">, +): Modules => { + const entries: Partial> = {}; + const sources: S["modules"] = scope.modules; + + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K ties the module producer to its destination view + const resolve = (name: K): void => { + const view = viewOptional(sources[name]); + + if (Predicate.isNotUndefined(view)) { + define, K>(entries, name, view); + } + }; + + for (const name of Object.getOwnPropertyNames(scope.modules)) { + resolve(name); + } + + // SAFETY: the loop checks each own module name at Modules[K]. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes the per-key module table + return Object.freeze(entries) as Modules; +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts b/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts new file mode 100644 index 00000000000..3b4af2ea455 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts @@ -0,0 +1,139 @@ +/** + * A small default set of declarations for expression construction. + * + * Export types derive from the bound declarations, without a second list of semantic annotations. Generated declarations can supply the same module, type and value tables to Draft.withPrelude. This default includes primitive types, List, Dict, UUID identities, equality and addition. It is not a complete standard-library binding. + * + * @module + */ +import { Result, pipe } from "effect"; + +import * as Module from "./Module.js"; +import * as Scope from "./Scope.js"; +import * as Structural from "./Structural.js"; + +import type * as Type from "../type/index.js"; +import type * as Expression from "./Expression.js"; +import type * as Inputs from "./Inputs.js"; +import type * as Semantic from "./PreludeTypes.js"; +import type * as TypeExpression from "./TypeExpression.js"; + +export type * from "./PreludeTypes.js"; + +type TypeDeclaration = Module.Declaration< + TypeExpression.TypeExpression +>; +type ValueDeclaration = Module.Declaration< + Expression.Expression +>; + +// Explicit declaration annotations let isolated declaration emit retain the inferred module exports. +const primitiveDeclarations: { + readonly types: { + readonly Integer: TypeDeclaration; + readonly Number: TypeDeclaration; + readonly String: TypeDeclaration; + readonly Boolean: TypeDeclaration; + readonly Null: TypeDeclaration; + readonly Unknown: TypeDeclaration; + readonly Never: TypeDeclaration; + readonly List: Module.Declaration< + TypeExpression.Constructor + >; + readonly Dict: Module.Declaration< + TypeExpression.Constructor + >; + }; +} = { + types: { + Integer: Module.type(), + Number: Module.type(), + String: Module.type(), + Boolean: Module.type(), + Null: Module.type(), + Unknown: Module.type(), + Never: Module.type(), + List: Module.genericType(1), + Dict: Module.genericType(2), + }, +}; +const uuidDeclarations: { + readonly types: { readonly Uuid: TypeDeclaration }; + readonly values: { + readonly Uuid: ValueDeclaration< + Type.Function + >; + }; +} = { types: { Uuid: Module.type() }, values: { Uuid: Module.value() } }; +const entityDeclarations: { + readonly types: { readonly EntityUuid: TypeDeclaration }; + readonly values: { + readonly EntityUuid: ValueDeclaration< + Type.Function + >; + }; +} = { + types: { EntityUuid: Module.type() }, + values: { EntityUuid: Module.value() }, +}; +const comparisonDeclarations: { + readonly values: { + readonly eq: ValueDeclaration>; + }; +} = { values: { eq: Module.value() } }; +const arithmeticDeclarations: { + readonly values: { + readonly add: ValueDeclaration>; + }; +} = { values: { add: Module.value() } }; + +const primitives: Module.Module = pipe( + Module.define("::kernel::type", primitiveDeclarations), + Result.getOrThrow, +); +const uuid: Module.Module = pipe( + Module.define("::core::uuid", uuidDeclarations), + Result.getOrThrow, +); +const entity: Module.Module = pipe( + Module.define("::graph::types::knowledge::entity", entityDeclarations), + Result.getOrThrow, +); +const cmp: Module.Module = pipe( + Module.define("::core::cmp", comparisonDeclarations), + Result.getOrThrow, +); +const math: Module.Module = pipe( + Module.define("::core::math", arithmeticDeclarations), + Result.getOrThrow, +); + +/** Derives exports from declaration tables without repeating their semantic annotations. */ +export type Builtin = Scope.From<{ + readonly modules: { + readonly entity: typeof entity; + readonly uuid: typeof uuid; + readonly cmp: typeof cmp; + readonly math: typeof math; + }; + readonly types: Omit & { + readonly List: Structural.Constructor; + readonly Dict: Structural.Constructor; + } & typeof uuid.types & + typeof entity.types; + readonly values: typeof uuid.values & + typeof entity.values & + typeof cmp.values & + typeof math.values; +}>; + +export const builtin: Builtin = Scope.merge(Scope.empty, { + modules: { entity, uuid, cmp, math }, + types: { + ...primitives.types, + List: Structural.constructor(primitives.types.List), + Dict: Structural.constructor(primitives.types.Dict), + ...uuid.types, + ...entity.types, + }, + values: { ...uuid.values, ...entity.values, ...cmp.values, ...math.values }, +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts b/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts new file mode 100644 index 00000000000..a4874b7f2b8 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts @@ -0,0 +1,50 @@ +/** + * Semantic operations used by the representative default declarations. + * + * Named identities use their absolute HashQL paths. Generic signatures inspect the semantic argument tuple supplied by the expression or type constructor, without widening it to a common element type. + * + * @module + */ +import type * as Type from "../type/index.js"; +import type { Conditional } from "./ExpressionType.js"; + +export type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +export type EntityUuid = Type.Opaque< + "::graph::types::knowledge::entity::EntityUuid", + Uuid +>; + +export interface List extends Type.TypeConstructor { + readonly arity: 1; + readonly type: this["Target"] extends readonly [infer T extends Type.Any] + ? Type.List + : never; +} + +export interface Dict extends Type.TypeConstructor { + readonly arity: 2; + readonly type: this["Target"] extends readonly [ + infer K extends Type.Any, + infer V extends Type.Any, + ] + ? Type.Dict + : never; +} + +export interface Comparison extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer L extends Type.Any, + infer R extends Type.Any, + ] + ? Type.Function + : Type.Function; +} + +export interface Arithmetic extends Type.FunctionSignature { + readonly type: this["Target"] extends readonly [ + infer L extends Type.PrimitiveInteger | Type.PrimitiveNumber, + infer R extends Type.PrimitiveInteger | Type.PrimitiveNumber, + ] + ? Type.Function> + : Type.Function; +} diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts index 5a3b213c8e0..c6caa15e256 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts @@ -20,6 +20,8 @@ export type Reason = InvalidImportName: NameFailure; InvalidParameterName: NameFailure; InvalidExportName: NameFailure; + SymbolExportName: { readonly name: symbol }; + SymbolInputName: { readonly name: symbol }; InvalidExpression: { readonly cause: Schema.SchemaError }; InvalidModulePath: NameFailure; RelativeModulePath: { readonly name: string }; @@ -56,6 +58,14 @@ export class Construction extends ConstructionBase<{ }); } + static symbolExportName(name: symbol): Construction { + return new Construction({ reason: Reason.SymbolExportName({ name }) }); + } + + static symbolInputName(name: symbol): Construction { + return new Construction({ reason: Reason.SymbolInputName({ name }) }); + } + static invalidTypeArity(arity: number): Construction { return new Construction({ reason: Reason.InvalidTypeArity({ arity }) }); } @@ -102,6 +112,10 @@ export class Construction extends ConstructionBase<{ `Invalid HashQL parameter name: ${JSON.stringify(name)}`, InvalidExportName: ({ name }) => `Invalid HashQL export name: ${JSON.stringify(name)}`, + SymbolExportName: ({ name }) => + `A HashQL export needs a string name, received ${String(name)}`, + SymbolInputName: ({ name }) => + `A HashQL input needs a string name, received ${String(name)}`, InvalidExpression: () => "The expression does not have valid J-Expr structure", InvalidModulePath: ({ name }) => diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts index 2ffb3062109..4cfbba7e8e8 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -1,4 +1,11 @@ -import { Result } from "effect"; +/** + * Query operations derived from a declared graph-producing function. + * + * The graph marker carries the vertex descriptor through filtering and collection. Both authoring APIs read that descriptor from EntityFunction rather than maintaining a separate graph schema. + * + * @module + */ +import { Result, pipe } from "effect"; import * as JExpr from "../jexpr/index.js"; import * as AST from "./ast/index.js"; @@ -41,27 +48,36 @@ export type Query< // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without an entities declaration has no query entry point type Empty = Record; -export type Context = S["values"] extends { - readonly entities: Expression.Handle< - Type.Function, - infer Requirements - >; +/** Reads one function's arguments, result, requirements and graph vertex from its semantic metadata. */ +export type EntityFunction = S["values"] extends { + readonly entities: infer E extends Expression.Any; } - ? Returns extends Graph - ? { - readonly entities: >( - ...args: Values - ) => Query< - Returns, - Vertex, - Inputs.Merge< - Inputs.Conservative, - ArgumentInputs - > - >; - } - : Empty - : Empty; + ? Expression.TypeOf extends Type.Function + ? R extends Graph + ? { + readonly args: A; + readonly returns: R; + readonly vertex: V; + readonly inputs: Inputs.Conservative>; + } + : never + : never + : never; + +type Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, +>( + ...args: A +) => Query< + EntityFunction["returns"], + EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> +>; + +export type Context = [EntityFunction] extends [never] + ? Empty + : { readonly entities: Entities }; const chain = ( expression: Expression.Expression, @@ -141,34 +157,37 @@ const chain = ( }; export const make = (scope: S): Context => { - const entities = scope.values["entities"]; - if (entities === undefined) { - // SAFETY: no entities declaration means this context has no query entry point. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the conditional type follows the supplied scope - return {} as Context; + const declaration = scope.values["entities"]; + if (declaration === undefined) { + return {}; } - const context = { - entities: ( - ...args: readonly Expression.AnyValue[] - ): Query => - chain( - Result.all({ - callee: Expression.toJExpr(entities), - args: Result.all(args.map(Expression.toJExpr)), - }).pipe( - Result.map( - ({ callee, args }) => new AST.Expr(JExpr.call(callee, ...args)), - ), - Expression.fromResult, - ), + const entities: Entities = < + const A extends readonly Expression.AnyValue[] & + Arguments["args"]>, + >( + ...args: A + ) => + pipe( + { + callee: Expression.toJExpr(declaration), + args: Result.all(args.map(Expression.toJExpr)), + }, + Result.all, + Result.map( + ({ callee, args: values }) => + new AST.Expr(JExpr.call(callee, ...values)), ), - }; - - // oxlint-disable-next-line typescript/no-restricted-types -- the runtime driver erases each declared function signature - const erased: unknown = context; + Expression.fromResult< + EntityFunction["returns"], + Inputs.Merge["inputs"], ArgumentInputs> + >, + chain< + EntityFunction["returns"], + EntityFunction["vertex"], + Inputs.Merge["inputs"], ArgumentInputs> + >, + ); - // SAFETY: the declaration supplies its argument types and its graph vertex type. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- runtime scope traversal erases the declaration's signature - return erased as Context; + return { entities }; }; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Scope.ts b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts index 6e938e38547..20c3d7f29ec 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Scope.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts @@ -1,10 +1,16 @@ +/** + * Immutable tables of module, type and value exports. + * + * Missing namespace tables introduce no names. Optional tables contribute optional names instead of an arbitrary string index. Merging retains an earlier export when its replacement is optional, and snapshots include non-enumerable own exports without freezing the caller's records. + * + * @module + */ import type * as Expression from "./Expression.js"; import type * as Module from "./Module.js"; import type * as TypeExpression from "./TypeExpression.js"; import type { ReadonlyRecord } from "effect/Record"; -/** An inspectable namespace without fixing its concrete key set. */ -interface Universe extends ReadonlyRecord {} +interface Universe extends ReadonlyRecord {} export interface Scope { readonly modules: Universe; @@ -18,13 +24,14 @@ export interface Definition { readonly types?: Scope["types"]; } -// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty universe has no names +// oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty namespace has no names type EmptyNames = Record; -type Names = - D extends ReadonlyRecord - ? Exports - : EmptyNames; +type Names = K extends keyof D + ? undefined extends D[K] + ? Partial> + : NonNullable + : EmptyNames; export interface From { readonly modules: Names; @@ -34,28 +41,71 @@ export interface From { export type Empty = From; -export type Extend = Readonly & Added>; +type RequiredKeys = { + [K in keyof S]-?: EmptyNames extends Pick ? never : K; +}[keyof S]; +type At = K extends keyof S ? S[K] : undefined; +type Overridden = K extends keyof A + ? K extends RequiredKeys + ? A[K] + : A[K] | At + : At; -export interface Merge { - readonly modules: Extend>; - readonly values: Extend>; - readonly types: Extend>; +/** Optional replacements retain the earlier type as an alternative. */ +export type Extend = { + readonly [K in RequiredKeys | RequiredKeys]: Overridden; +} & { + readonly [K in Exclude< + keyof B | keyof A, + RequiredKeys | RequiredKeys + >]?: Overridden; +}; + +export interface Merge { + readonly modules: Extend>; + readonly values: Extend>; + readonly types: Extend>; } +/** Copies own exports, including non-enumerable names, without freezing the caller's table. */ +export const snapshot = ( + entries: E, +): Readonly => { + const copy = { ...entries }; + + for (const name of Object.getOwnPropertyNames(entries)) { + Object.defineProperty(copy, name, { + value: entries[name], + enumerable: true, + }); + } + + return Object.freeze(copy); +}; + // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- combines separate namespaces rather than transforming the first argument -export const merge = ( - before: Before, - added: Added, -): Merge => { +export const merge = ( + before: B, + added: A, +): Merge => { const combined = Object.freeze({ - modules: Object.freeze({ ...before.modules, ...added.modules }), - values: Object.freeze({ ...before.values, ...added.values }), - types: Object.freeze({ ...before.types, ...added.types }), + modules: Object.freeze({ + ...snapshot(before.modules), + ...snapshot(added.modules ?? {}), + }), + values: Object.freeze({ + ...snapshot(before.values), + ...snapshot(added.values ?? {}), + }), + types: Object.freeze({ + ...snapshot(before.types), + ...snapshot(added.types ?? {}), + }), }); - // SAFETY: each spread copies one namespace, with later names replacing earlier ones. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- object spread erases the per-key override mapping - return combined as Merge; + // SAFETY: each namespace copies all own exports, replacing an earlier value only when the later table supplies that name. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- object spread cannot express per-key optional override alternatives + return combined as Merge; }; export const empty: Empty = Object.freeze({ diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts index 171a6993d07..11662f66983 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts @@ -116,6 +116,24 @@ describe("structural_constructor_types", () => { >(); }); + test("relocated_types", () => { + const local = Result.getOrThrow(JExpr.Path.decodeResult("Dictionary")); + const moved = Result.getOrThrow(TypeExpression.relocate(dictionary, local)); + expectTypeOf(moved).toEqualTypeOf(); + expectTypeOf(moved(String, { count: BigInt })).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + const identity = Symbol("Item"); + const item = + TypeExpression.reference< + Type.Opaque + >(local); + const alias = Result.getOrThrow(TypeExpression.relocate(item, local)); + expectTypeOf(alias).toEqualTypeOf(); + // @ts-expect-error Relocation preserves the constructor's arity. + moved(String); + }); + test("structural_requirements", () => { const result = Structural.value()(hostChoice(true)); expectTypeOf(result).toEqualTypeOf< diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts index 19cf4682a54..8e11dc96046 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts @@ -50,6 +50,35 @@ describe("structural_constructor", () => { ); }); + test("relocated_constructor", () => { + expect.hasAssertions(); + const local = Result.getOrThrow(JExpr.Path.decodeResult("Dictionary")); + const moved = Result.getOrThrow(TypeExpression.relocate(dictionary, local)); + expect(compile(moved(String, { count: BigInt }))).toBe( + "Dictionary<::kernel::type::String, (count: ::kernel::type::Integer)>", + ); + const second = Result.getOrThrow( + TypeExpression.relocate( + moved, + Result.getOrThrow(JExpr.Path.decodeResult("Other")), + ), + ); + expect(compile(second(Boolean, Number))).toBe( + "Other<::kernel::type::Boolean, ::kernel::type::Number>", + ); + expect(compile(dictionary(String, Number))).toBe( + "::kernel::type::Dict<::kernel::type::String, ::kernel::type::Number>", + ); + }); + + test("relocated_failure", () => { + expect.hasAssertions(); + const invalid = Structural.type({ "": Number }); + expect(TypeExpression.relocate(invalid, path)).toStrictEqual( + invalid.syntax, + ); + }); + test("invalid_nested_name", () => { expect.hasAssertions(); const result = dictionary(String, { "": BigInt }).syntax; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts index 1fbd1d0a0d9..ef371bafbfe 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts @@ -22,6 +22,7 @@ import * as Expression from "./Expression.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; +import type { Relocatable, Relocate } from "../internal/relocation.js"; import type * as Type from "../type/index.js"; import type * as Input from "./Inputs.js"; import type { ReadonlyRecord } from "effect/Record"; @@ -122,7 +123,7 @@ export const isDefinition = (value: unknown): value is Definition => { return true; } - if (!Predicate.isObject(value) || Predicate.isFunction(value)) { + if (!Predicate.isObjectOrArray(value) || Predicate.isFunction(value)) { return false; } @@ -151,7 +152,7 @@ export const isValue = (value: unknown): value is AnyValue => { return true; } - if (!Predicate.isObject(value) || Predicate.isFunction(value)) { + if (!Predicate.isObjectOrArray(value) || Predicate.isFunction(value)) { return false; } @@ -270,6 +271,8 @@ type ArgumentTypes = { /** A named generic type accepting the same shorthand as a local alias. */ export interface Constructor extends TypeExpression.AnyConstructor { + readonly [Relocate]: Relocatable>[typeof Relocate]; + ( ...definitions: A & { readonly length: F["arity"] } ): TypeExpression.TypeExpression>>; @@ -278,14 +281,15 @@ export interface Constructor /** Gives an existing generic declaration the same shorthand normalization as local aliases. */ export const constructor = ( declaration: TypeExpression.Constructor, -): Constructor => { - const instantiate = ( - ...definitions: A & { readonly length: F["arity"] } - ): TypeExpression.TypeExpression>> => - declaration>(...normalize(definitions)); - - return TypeExpression.adaptConstructor(declaration, instantiate); -}; +): Constructor => + TypeExpression.adaptConstructor( + declaration, + (source) => + ( + ...definitions: A & { readonly length: F["arity"] } + ): TypeExpression.TypeExpression>> => + source>(...normalize(definitions)), + ); const valueSyntax = ( value: AnyValue, diff --git a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts index ba39ac5b66d..9d8819c594a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts @@ -1,7 +1,20 @@ -import { Result, identity } from "effect"; +/** + * Type syntax annotated with its HashQL semantic meaning. + * + * A {@link TypeExpression} carries syntax or a construction failure alongside a type-level descriptor. A {@link Constructor} specializes a named generic type while preserving its semantic argument tuple. Declarations supply these descriptors, and the HashQL compiler validates their use in the emitted program. + * + * @module + */ +import { Predicate, Result, identity, pipe } from "effect"; +import { dual } from "effect/Function"; +import { + Relocate, + relocate as relocateHandle, +} from "../internal/relocation.js"; import * as ProgramError from "./ProgramError.js"; +import type { Relocatable } from "../internal/relocation.js"; import type * as JExpr from "../jexpr/index.js"; import type * as Syntax from "../jexpr/type/index.js"; import type * as Type from "../type/index.js"; @@ -11,41 +24,42 @@ const TypeId: unique symbol = Symbol("~hashql/TypeExpression"); const ConstructorId: unique symbol = Symbol("~hashql/TypeConstructor"); /** Type construction with its semantic annotation erased. */ -export interface Any { +export interface Any extends Relocatable { readonly syntax: Result.Result; - readonly [TypeId]: (value: never) => Type.Any; + readonly [TypeId]: Types.Covariant; } /** Type syntax or its construction failure, annotated with its semantic type. */ export interface TypeExpression extends Any { - readonly [TypeId]: Types.Invariant; + readonly [TypeId]: Types.Covariant; + readonly [Relocate]: Relocatable>[typeof Relocate]; } -type ArgumentTypes = { - readonly [Index in keyof Arguments]: Arguments[Index] extends TypeExpression< - infer T - > - ? T - : never; -}; - -/** A named generic type, specialized by supplying typed type expressions. */ -export interface Constructor { +/** A generic type export with its parameterization erased. */ +export interface AnyConstructor extends Relocatable { readonly [ConstructorId]: { readonly path: JExpr.Path.Path; readonly arity: number; }; - ( - ...args: Arguments & { readonly length: Lambda["arity"] } - ): TypeExpression>>; } -/** A generic type export with its parameterization erased. */ -export interface AnyConstructor { - readonly [ConstructorId]: { - readonly path: JExpr.Path.Path; - readonly arity: number; - }; +type Arguments = { + readonly [K in keyof A]: TypeExpression; +}; + +/** + * A named generic type, specialized by supplying typed type expressions. + * + * The argument tuple carries semantic types, and `Arguments` maps each position to its handle. TypeScript infers the tuple from ordinary calls. A generic caller can also supply it explicitly without extracting and re-inferring types from already-normalized handles. + */ +export interface Constructor< + F extends Type.TypeConstructor, +> extends AnyConstructor { + readonly [Relocate]: Relocatable>[typeof Relocate]; + + ( + ...args: Arguments & { readonly length: F["arity"] } + ): TypeExpression>; } /** A type namespace contains both concrete types and generic type constructors. */ @@ -54,13 +68,29 @@ export type Export = Any | AnyConstructor; /** Recognizes concrete type expressions and generic type constructors. */ // oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries export const isExport = (value: unknown): value is Export => - ((typeof value === "object" && value !== null) || - typeof value === "function") && - (TypeId in value || ConstructorId in value); + Predicate.hasProperty(value, TypeId) || + Predicate.hasProperty(value, ConstructorId); + +/** Recognizes generic type constructors, including combined namespace handles. */ +// oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values +export const isConstructor = (value: unknown): value is AnyConstructor => + Predicate.hasProperty(value, ConstructorId); export const fromResult = ( syntax: Result.Result, -): TypeExpression => ({ syntax, [TypeId]: identity }); +): TypeExpression => ({ + syntax, + [TypeId]: identity, + [Relocate]: (path) => + pipe( + syntax, + Result.map(() => + fromResult( + Result.succeed({ _tag: "Reference", path, generics: [] }), + ), + ), + ), +}); export const toType = ( type: Any, @@ -73,7 +103,7 @@ export const toType = ( */ export const fromType = ( syntax: Syntax.Type, -): TypeExpression => fromResult(Result.succeed(syntax)); +): TypeExpression => pipe(syntax, Result.succeed, fromResult); /** Binds a trusted semantic declaration to a named type reference. */ export const reference = ( @@ -86,60 +116,98 @@ export const reference = ( * Runtime checking covers arity alone. The declaration supplies the relationship between the argument types and the resulting semantic type. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the reference under construction -export const constructor = ( +export const constructor = ( path: JExpr.Path.Path, - arity: Lambda["arity"], -): Result.Result, ProgramError.Construction> => { + arity: F["arity"], +): Result.Result, ProgramError.Construction> => { if (!Number.isSafeInteger(arity) || arity < 0) { - return Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidTypeArity({ arity }), - }), - ); + return Result.fail(ProgramError.Construction.invalidTypeArity(arity)); } - const instantiate = ( - ...args: Arguments & { readonly length: Lambda["arity"] } - ): TypeExpression>> => { + const instantiate = ( + ...args: Arguments & { readonly length: F["arity"] } + ): TypeExpression> => { if (args.length !== arity) { - return fromResult( - Result.fail( - new ProgramError.Construction({ - reason: ProgramError.Reason.TypeArgumentCount({ - expected: arity, - received: args.length, - }), - }), - ), + return pipe( + ProgramError.Construction.typeArgumentCount(arity, args.length), + Result.fail, + fromResult>, ); } - return fromResult( - Result.map(Result.all(args.map(toType)), (arguments_) => ({ - _tag: "Reference", - path, - generics: arguments_.map((bound) => ({ - _tag: "GenericArgument", - bound, - })), - })), + return pipe( + args, + (arguments_) => arguments_.map(toType), + Result.all, + Result.map( + (arguments_): Syntax.Type => ({ + _tag: "Reference", + path, + generics: arguments_.map((bound) => ({ + _tag: "GenericArgument", + bound, + })), + }), + ), + fromResult>, ); }; return Result.succeed( - Object.assign(instantiate, { [ConstructorId]: { path, arity } }), + Object.assign(instantiate, { + [ConstructorId]: { path, arity }, + [Relocate]: (next: JExpr.Path.Path) => constructor(next, arity), + }), ); }; -/** Rebinds an imported type name without changing its declared meaning. */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a reference at the imported path -export const relocate = ( - type: Export, - path: JExpr.Path.Path, -): Result.Result => { - if (ConstructorId in type) { - return constructor(path, type[ConstructorId].arity); - } +/** Rebinds a type reference or generic constructor while retaining its declared capabilities. */ +export const relocate: { + ( + path: JExpr.Path.Path, + ): ( + self: Export & Relocatable, + ) => Result.Result; + ( + self: Export & Relocatable, + path: JExpr.Path.Path, + ): Result.Result; +} = relocateHandle; + +/** An adapted callable retains both its signature and its rebinding operation. */ +type Adapted = C & + AnyConstructor & { + readonly [Relocate]: Relocatable>[typeof Relocate]; + }; - return Result.map(toType(type), () => reference(path)); -}; +/** + * Adapts a named constructor while retaining its argument normalization after rebinding. + * + * The adapter receives the rebound declaration each time. Retaining only the first callable would leave later calls pointing at the old path. Copying the marker explicitly supports forwarding proxies that do not enumerate it. + */ +export const adaptConstructor: { + Any>( + adapt: (self: S) => C, + ): (self: S & Relocatable) => Adapted; + Any>( + self: S & Relocatable, + adapt: (self: S) => C, + ): Adapted; +} = dual( + 2, + Any>( + self: S & Relocatable, + adapt: (self: S) => C, + ): Adapted => { + const build = (source: S): Adapted => + Object.assign(adapt(source), { + [ConstructorId]: source[ConstructorId], + [Relocate]: ( + path: JExpr.Path.Path, + ): Result.Result, ProgramError.Construction> => + pipe(relocateHandle(self, path), Result.map(build)), + }); + + return build(self); + }, +); From 8741bc6fe6f328a25f8aa6d660d7e05b9c5f4037 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:16:49 +0200 Subject: [PATCH 07/22] feat: add Draft filter examples and input algebra tests --- libs/@local/hashql/sdk/typescript/README.md | 2 +- .../examples/filters-declarations.ts | 142 +++++++++++++ .../typescript/examples/filters-draft.test.ts | 81 ++++++++ .../sdk/typescript/examples/filters-draft.ts | 193 ++++++++++++++++++ .../hashql/sdk/typescript/examples/filters.ts | 118 +---------- .../typescript/src/program/Inputs.test-d.ts | 96 +++++++-- .../sdk/typescript/src/program/Inputs.ts | 157 +++++++------- 7 files changed, 584 insertions(+), 205 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters-draft.ts diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 8b538dd9ede..58ffe83bc96 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -185,6 +185,6 @@ Serialization traverses the constructed tree rather than rerunning authoring cal The [authoring guide](docs/authoring.md) is the tutorial and API reference. The [checked examples](examples/api-tour.test-d.ts) retain exact-type assertions and `@ts-expect-error` cases in the package checks. These checks validate the SDK, not HashQL compiler acceptance or graph execution. -[`examples/filters.ts`](examples/filters.ts) compares existing J-Expr queries and frontend selection predicates with typed constructions. Start at `allEntities`. These examples construct syntax without frontend integration or a graph connection. Their static module fixtures unwrap declaration results explicitly. +[`examples/filters.ts`](examples/filters.ts) compares existing J-Expr queries and frontend selection predicates with Do constructions. [`examples/filters-draft.ts`](examples/filters-draft.ts) writes the same queries with Draft, using explicit schemas, local bindings and predicate callbacks. Both use the same [module declarations](examples/filters-declarations.ts). Start at `allEntities` in either file. These examples construct syntax without frontend integration or a graph connection. Their static module fixtures unwrap declaration results explicitly. Run the package checks with `yarn workspace @local/hashql test:unit`, `lint:tsc`, `lint:oxlint` and `build`. diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts new file mode 100644 index 00000000000..7947bbf13ab --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts @@ -0,0 +1,142 @@ +/** + * Minimal graph declarations shared by the Do and Draft filter examples. + * + * These declarations cover only the entity fields and standard-library exports used by the examples. Generated bindings can supply these declarations without changing the query bodies. + * + * @module + */ +import { Result } from "effect"; + +import { Module } from "../src/main.js"; + +import type { Expression, Inputs, Type, TypeExpression } from "../src/main.js"; + +type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +type ActorGroupEntityUuid = Type.Opaque< + "::graph::types::principal::actor_group::ActorGroupEntityUuid", + Uuid +>; +export type WebId = Type.Opaque< + "::graph::types::principal::actor_group::web::WebId", + ActorGroupEntityUuid +>; +type EntityType = Type.Opaque< + `::graph::types::knowledge::entity::${Name}`, + Value +>; +export type EntityUuid = EntityType<"EntityUuid", Uuid>; +type DraftId = EntityType<"DraftId", Uuid>; +type None = Type.Opaque<"::core::option::None", Type.PrimitiveNull>; +type Draft = Type.Union< + readonly [None, Type.Opaque<"::core::option::Some", DraftId>] +>; +type EntityId = EntityType< + "EntityId", + Type.Struct<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + readonly draft_id: Draft; + }> +>; +export type Entity = EntityType< + "Entity", + Type.Struct<{ + readonly metadata: EntityType< + "EntityMetadata", + Type.Struct<{ + readonly record_id: EntityType< + "RecordId", + Type.Struct<{ readonly entity_id: EntityId }> + >; + readonly archived: Type.PrimitiveBoolean; + }> + >; + }> +>; +type EntityGraph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Entity }> +>; +export type TemporalAxes = Type.Union< + readonly [ + Type.Opaque< + "::graph::temporal::PinnedTransactionTimeTemporalAxes", + Type.Unknown + >, + Type.Opaque< + "::graph::temporal::PinnedDecisionTimeTemporalAxes", + Type.Unknown + >, + ] +>; +type CreateUuid = Type.Function; +type CreateEntityUuid = Type.Function; +type Entities = Type.Function; +type Now = Type.Function; +type Value = Expression.Expression; + +export const uuid: Module.Module<{ + readonly values: { readonly Uuid: Value }; +}> = Result.getOrThrow( + Module.define("::core::uuid", { + values: { + Uuid: Module.value(), + }, + }), +); +export const entity: Module.Module<{ + readonly types: { + readonly EntityUuid: TypeExpression.TypeExpression; + }; + readonly values: { readonly EntityUuid: Value }; +}> = Result.getOrThrow( + Module.define("::graph::types::knowledge::entity", { + types: { EntityUuid: Module.type() }, + values: { + EntityUuid: Module.value(), + }, + }), +); +export const web: Module.Module<{ + readonly types: { readonly WebId: TypeExpression.TypeExpression }; +}> = Result.getOrThrow( + Module.define("::graph::types::principal::actor_group::web", { + types: { WebId: Module.type() }, + }), +); +export const temporal: Module.Module<{ + readonly types: { + readonly QueryTemporalAxes: TypeExpression.TypeExpression; + }; +}> = Result.getOrThrow( + Module.define("::graph::temporal", { + types: { QueryTemporalAxes: Module.type() }, + }), +); +export const kernel: Module.Module<{ + readonly types: { + readonly Boolean: TypeExpression.TypeExpression; + }; +}> = Result.getOrThrow( + Module.define("::kernel::type", { + types: { Boolean: Module.type() }, + }), +); +export const head: Module.Module<{ + readonly values: { readonly entities: Value }; +}> = Result.getOrThrow( + Module.define("::graph::head", { + values: { + entities: Module.value(), + }, + }), +); +export const temporary: Module.Module<{ + readonly values: { readonly decision_time_now: Value }; +}> = Result.getOrThrow( + Module.define("::graph::tmp", { + values: { + decision_time_now: Module.value(), + }, + }), +); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts new file mode 100644 index 00000000000..2e70b7e752b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts @@ -0,0 +1,81 @@ +/** Construction and input typing for the Draft filter gallery. @module */ +import { Array, Result, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import { Expression, JExpr } from "../src/main.js"; +import { examples } from "./filters-draft.js"; +import { examples as originals } from "./filters.js"; + +import type { Type } from "../src/main.js"; +import type * as ProgramError from "../src/program/ProgramError.js"; +import type { + Entity, + EntityUuid, + TemporalAxes, + WebId, +} from "./filters-declarations.js"; + +const compile = ( + result: Result.Result, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +const publishedSelection = 4; +const draftSelection = 7; +const allEntities = examples[0]; +const suppliedTimeAxis = examples[2]; +const publishedEntityById = examples[publishedSelection]; +const optionalDrafts = examples[draftSelection]; + +const comparisons = pipe( + Array.zip(examples, originals), + Array.map(([draft, original]) => ({ + draft, + original, + title: original.title, + })), +); + +describe("draft_filters", () => { + test("query_without_imports", () => { + expect.hasAssertions(); + expect(examples).toHaveLength(originals.length); + expect(compile(allEntities)).toBe( + '["::graph::tail::collect",["::graph::head::entities",["::graph::tmp::decision_time_now"]]]', + ); + }); + + test.each(Array.drop(comparisons, 1))( + "matching_selection: $title", + ({ draft, original }) => { + expect.hasAssertions(); + expect(compile(draft)).toBe(Result.getOrThrow(original.compile())); + }, + ); + + test("declared_inputs", () => { + expect.hasAssertions(); + const axis = Result.getOrThrow(suppliedTimeAxis); + const selected = Result.getOrThrow(publishedEntityById); + const flag = Result.getOrThrow(optionalDrafts); + expectTypeOf>().toEqualTypeOf< + Type.List + >(); + expectTypeOf>().toEqualTypeOf<{ + readonly axis: TemporalAxes; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + }>(); + expectTypeOf>().toEqualTypeOf<{ + readonly include_drafts: Type.PrimitiveBoolean; + }>(); + expect(compile(optionalDrafts)).toContain('"include_drafts"'); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts new file mode 100644 index 00000000000..841fed12271 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -0,0 +1,193 @@ +/** + * The filter gallery written with synchronous Draft callbacks. + * + * These programs correspond, in order, to filters.ts. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.ifElse emits a query-time branch. + * + * The shared declarations cover only the graph exports used here. Construction emits J-Expr without executing against a graph service. + * + * @module + */ +import { Array, pipe } from "effect"; + +import { withPrelude } from "../src/draft/index.js"; +import { + entity, + head, + kernel, + temporal, + temporary, + uuid, + web, +} from "./filters-declarations.js"; + +import type { Expression, Inputs, Type } from "../src/main.js"; +import type * as ProgramError from "../src/program/ProgramError.js"; +import type { + Entity, + EntityUuid, + TemporalAxes, + WebId, +} from "./filters-declarations.js"; +import type { Result } from "effect"; + +const { program } = withPrelude({ + values: { + createUuid: uuid.values.Uuid, + createEntityUuid: entity.values.EntityUuid, + ...head.values, + now: temporary.values.decision_time_now, + }, +}); + +const allEntities = program({}, ($) => { + const { now } = $.prelude(); + return $.query.entities(now()).collect(); +}); + +const entityByUuid = program({}, ($) => { + const { now, createEntityUuid, createUuid } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ) + .collect(); +}); + +const suppliedTimeAxis = program( + { axis: temporal.types.QueryTemporalAxes }, + ($, { axis }) => { + const { createEntityUuid, createUuid } = $.prelude(); + return $.query + .entities(axis) + .filter("vertex", (_, vertex) => + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), + ), + ) + .collect(); + }, +); + +const predicateLocalBinding = program({}, ($) => { + const { now } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", ($) => { + const foo = $.let("foo", false); + return $.literal(true).$.and($.literal(true).$.or(foo)); + }) + .collect(); +}); + +const publishedEntityById = program( + { web_id: web.types.WebId, entity_uuid: entity.types.EntityUuid }, + ($, inputs) => { + const { now } = $.prelude(); + const webId = $.let("webId", inputs.web_id); + const entityUuid = $.let("entityUuid", inputs.entity_uuid); + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => { + const id = vertex.metadata.record_id.entity_id; + return id.web_id.$.eq(webId) + .$.and(id.entity_uuid.$.eq(entityUuid)) + .$.and(id.draft_id.$.isNone()); + }) + .collect(); + }, +); + +const sidebarSelection = program({ web_id: web.types.WebId }, ($, inputs) => { + const { now } = $.prelude(); + const webId = $.let("webId", inputs.web_id); + return $.query + .entities(now()) + .filter("vertex", (_, vertex) => + vertex.metadata.record_id.entity_id.web_id.$.eq(webId), + ) + .filter("vertex", (_, vertex) => + vertex.metadata.archived.$.isFalse().$.and( + vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + ), + ) + .collect(); +}); + +const selectedIds = [ + "e2851dbb-7376-4959-9bca-f72cafc4448f", + "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", +] as const; + +const anyOfEntityIds = program({}, ($) => { + const { now, createEntityUuid, createUuid } = $.prelude(); + return $.query + .entities(now()) + .filter("vertex", ($, vertex) => + pipe( + selectedIds, + // oxlint-disable-next-line unicorn/no-array-reduce -- this is Effect's typed fold, not a native array method + Array.reduce($.literal(false), (matches, entityUuid) => + matches.$.or( + vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + createEntityUuid(createUuid(entityUuid)), + ), + ), + ), + ), + ) + .collect(); +}); + +// Draft retains the declared input as required, even though the emitted input supplies a default. +const optionalDrafts = program( + { include_drafts: kernel.types.Boolean }, + ($) => { + const { now } = $.prelude(); + const includeDrafts = $.let( + "includeDrafts", + $.input("include_drafts", kernel.types.Boolean, false), + ); + return $.query + .entities(now()) + .filter("vertex", ($, vertex) => + $.ifElse( + includeDrafts, + () => true, + () => vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + ), + ) + .collect(); + }, +); + +type Query = Result.Result< + Expression.Expression, I>, + ProgramError.Construction +>; + +/** The same selections as the Do gallery, retaining each Draft schema in its result type. */ +export const examples: readonly [ + allEntities: Query, + entityByUuid: Query, + suppliedTimeAxis: Query<{ readonly axis: TemporalAxes }>, + predicateLocalBinding: Query, + publishedEntityById: Query<{ + readonly web_id: WebId; + readonly entity_uuid: EntityUuid; + }>, + sidebarSelection: Query<{ readonly web_id: WebId }>, + anyOfEntityIds: Query, + optionalDrafts: Query<{ readonly include_drafts: Type.PrimitiveBoolean }>, +] = [ + allEntities, + entityByUuid, + suppliedTimeAxis, + predicateLocalBinding, + publishedEntityById, + sidebarSelection, + anyOfEntityIds, + optionalDrafts, +]; diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts index 8fa264033f7..3ff857ed3b3 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.ts @@ -10,118 +10,20 @@ import { Result } from "effect"; import { Do as EmptyDo, Import, withPrelude } from "../src/do/index.js"; -import { Module, Program, program } from "../src/main.js"; +import { Program, program } from "../src/main.js"; +import { + entity, + head, + kernel, + temporal, + temporary, + uuid, + web, +} from "./filters-declarations.js"; import type { Expression, Type } from "../src/main.js"; import type * as ProgramError from "../src/program/ProgramError.js"; -type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; -type ActorGroupEntityUuid = Type.Opaque< - "::graph::types::principal::actor_group::ActorGroupEntityUuid", - Uuid ->; -type WebId = Type.Opaque< - "::graph::types::principal::actor_group::web::WebId", - ActorGroupEntityUuid ->; -type EntityType = Type.Opaque< - `::graph::types::knowledge::entity::${Name}`, - Value ->; -type EntityUuid = EntityType<"EntityUuid", Uuid>; -type DraftId = EntityType<"DraftId", Uuid>; -type None = Type.Opaque<"::core::option::None", Type.PrimitiveNull>; -type Draft = Type.Union< - readonly [None, Type.Opaque<"::core::option::Some", DraftId>] ->; -type EntityId = EntityType< - "EntityId", - Type.Struct<{ - readonly web_id: WebId; - readonly entity_uuid: EntityUuid; - readonly draft_id: Draft; - }> ->; -type Entity = EntityType< - "Entity", - Type.Struct<{ - readonly metadata: EntityType< - "EntityMetadata", - Type.Struct<{ - readonly record_id: EntityType< - "RecordId", - Type.Struct<{ readonly entity_id: EntityId }> - >; - readonly archived: Type.PrimitiveBoolean; - }> - >; - }> ->; -type EntityGraph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Entity }> ->; -type TemporalAxes = Type.Union< - readonly [ - Type.Opaque< - "::graph::temporal::PinnedTransactionTimeTemporalAxes", - Type.Unknown - >, - Type.Opaque< - "::graph::temporal::PinnedDecisionTimeTemporalAxes", - Type.Unknown - >, - ] ->; -const uuid = Result.getOrThrow( - Module.define("::core::uuid", { - values: { - Uuid: Module.value< - Type.Function - >(), - }, - }), -); -const entity = Result.getOrThrow( - Module.define("::graph::types::knowledge::entity", { - types: { EntityUuid: Module.type() }, - values: { - EntityUuid: Module.value>(), - }, - }), -); -const web = Result.getOrThrow( - Module.define("::graph::types::principal::actor_group::web", { - types: { WebId: Module.type() }, - }), -); -const temporal = Result.getOrThrow( - Module.define("::graph::temporal", { - types: { QueryTemporalAxes: Module.type() }, - }), -); -const kernel = Result.getOrThrow( - Module.define("::kernel::type", { - types: { Boolean: Module.type() }, - }), -); -const head = Result.getOrThrow( - Module.define("::graph::head", { - values: { - entities: - Module.value>(), - }, - }), -); -const temporary = Result.getOrThrow( - Module.define("::graph::tmp", { - values: { - decision_time_now: - Module.value>(), - }, - }), -); - const { Let, Do } = withPrelude({ values: { createUuid: uuid.values.Uuid, diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts index 68539646b0d..08e0634a18f 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts @@ -38,6 +38,78 @@ declare const optionalDefault: > | undefined; +declare const hostAlternative: + | Expression.Expression< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + > + | Expression.Expression< + Type.PrimitiveInteger, + { readonly second: Type.PrimitiveInteger } + >; +declare const possiblyClosed: + | Expression.Expression + | Expression.Expression< + Type.PrimitiveInteger, + { readonly first: Type.PrimitiveInteger } + >; + +describe("requirement_algebra", () => { + test("optional_tuple", () => { + expectTypeOf< + Inputs.All< + readonly [ + first?: { readonly count?: Type.PrimitiveInteger }, + second?: { + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }, + ] + > + >().toEqualTypeOf<{ + readonly count: Type.PrimitiveInteger; + readonly label: Type.PrimitiveString; + }>(); + }); + + test("empty_and_variadic_tuple", () => { + // oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty tuple contributes no input names + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Inputs.All< + readonly [ + { readonly first: Type.PrimitiveInteger }, + ...{ readonly second: Type.PrimitiveString }[], + ] + > + >().toEqualTypeOf<{ + readonly first: Type.PrimitiveInteger; + readonly second: Type.PrimitiveString; + }>(); + }); + + test("required_conflict", () => { + expectTypeOf< + Inputs.Conservative< + | { readonly value?: Type.PrimitiveInteger } + | { readonly value: Type.PrimitiveString } + > + >().toEqualTypeOf<{ readonly value: Type.Never }>(); + expectTypeOf< + Inputs.Merge<{ readonly value?: Type.PrimitiveInteger }, Inputs.Empty> + >().toEqualTypeOf<{ readonly value?: Type.PrimitiveInteger }>(); + }); + + test("erased_metadata", () => { + expectTypeOf>().toEqualTypeOf(); + // oxlint-disable-next-line typescript/no-restricted-types -- exercises erasure of the requirement record + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + Inputs.Merge + >().toEqualTypeOf(); + }); +}); + describe("input_requirements", () => { test("host_alternatives_keep_every_requirement", () => { type Alternatives = @@ -61,26 +133,17 @@ describe("input_requirements", () => { | { readonly same: Type.PrimitiveString } > >().toEqualTypeOf<{ readonly same: Type.Never }>(); - const alternative = - Math.random() > 0.5 - ? Expression.input("first", integer) - : Expression.input("second", integer); - const composed = Expression.ifElse(true, { then: alternative, else: 0n }); + const composed = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch + then: hostAlternative, + else: 0n, + }); // @ts-expect-error an empty annotation cannot hide host-side alternatives const closed: Expression.Expression = composed; expectTypeOf(closed); - const choose = (): - | Expression.Expression - | Expression.Expression< - Type.PrimitiveInteger, - { readonly first: Type.PrimitiveInteger } - > => - Math.random() > 0.5 - ? Expression.input("first", integer) - : Expression.integer(0); - const possiblyClosed = choose(); const combined = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a query branch then: possiblyClosed, else: 0n, }); @@ -92,7 +155,7 @@ describe("input_requirements", () => { const block = EmptyDo< Type.PrimitiveInteger, { readonly first: Type.PrimitiveInteger } - >(() => choose()); + >(() => possiblyClosed); // @ts-expect-error a block also keeps the required alternative const hiddenBlock: Expression.Expression< Type.PrimitiveInteger, @@ -100,6 +163,7 @@ describe("input_requirements", () => { > = Result.getOrThrow(block); expectTypeOf(hiddenBlock); }); + test("required_and_default", () => { const required = Expression.input("count", integer); const optional = Expression.input("limit", integer, Expression.integer(10)); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts index 52fd45003b1..e118638c143 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts @@ -1,106 +1,103 @@ +/** + * Input requirements carried by expressions and programs. + * + * A required use makes a name required even when another use has a default. Shared names combine their semantic descriptors through an intersection, so incompatible uses produce Type.Never rather than a JavaScript intersection of descriptor objects. + * + * Host-side alternatives retain every possible requirement. The types here cannot know which expression the host will select, and an empty alternative must not hide a branch that needs an input. + * + * @module + */ import type * as Type from "../type/index.js"; import type { Normalize } from "./ExpressionType.js"; import type { Types } from "effect"; +/** An expression with no input requirements. */ // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a closed expression requires no input names export type Empty = Record; declare const ErasedRequirement: unique symbol; -/** Unrecoverable requirements cannot be discharged by a named input schema. */ -export type Erased = { readonly [ErasedRequirement]: Type.Unknown }; +/** Named input schemas cannot discharge unrecoverable requirements. */ +export interface Erased { + readonly [ErasedRequirement]: Type.Unknown; +} -type RequiredKeys = { - [Key in keyof Inputs]-?: Empty extends Pick ? never : Key; -}[keyof Inputs]; +type RequiredKeys = { + [K in keyof I]-?: Empty extends Pick ? never : K; +}[keyof I]; -type At = Key extends keyof Inputs - ? Exclude +type At = K extends keyof I + ? Exclude : never; -type Combined = Key extends keyof Left - ? Key extends keyof Right - ? At extends infer LeftType extends Type.Any - ? At extends infer RightType extends Type.Any - ? Normalize> +type Combined = K extends keyof L + ? K extends keyof R + ? At extends infer A extends Type.Any + ? At extends infer B extends Type.Any + ? Normalize> : never : never - : At - : At; + : At + : At; -type Last = - Types.UnionToIntersection< - Alternatives extends unknown ? () => Alternatives : never - > extends () => infer Member - ? Member - : never; +type MergeRecords = [keyof R] extends [never] + ? L + : [keyof L] extends [never] + ? R + : Types.Simplify< + { + readonly [K in RequiredKeys | RequiredKeys]: Combined; + } & { + readonly [K in Exclude< + keyof L | keyof R, + RequiredKeys | RequiredKeys + >]?: Combined; + } + >; -// Invariance keeps a closed alternative from swallowing a narrower required record during Exclude. -type InvariantAlternatives = Requirements extends unknown - ? (value: Requirements) => Requirements - : never; +// Intersecting call signatures selects one union member through the last overload. Each step removes whichever member inference selects. +type Last = Types.Covariant.Type< + Types.UnionToIntersection : never> +>; -type Unwrap = Alternative extends ( - value: infer Requirements, -) => unknown - ? Requirements - : never; +// Invariance keeps Empty from swallowing a required record during Exclude. A plain union of records would let the empty record remove every remaining alternative. +type Alternatives = I extends I ? Types.Invariant : never; -type CollapseAlternatives = [ - Alternatives, -] extends [never] - ? Accumulated - : [Alternatives] extends [Types.UnionToIntersection] - ? MergeRecords> - : CollapseAlternatives< - Exclude>, - MergeRecords>> +type Collapse = [U] extends [never] + ? I + : Types.IsUnion extends false + ? MergeRecords> + : Collapse< + Exclude>, + MergeRecords>> >; -/** Requires every member of a host-side alternative, preserving shared semantic constraints. */ -export type Conservative = [Requirements] extends [never] +/** Requires every host-side alternative, preserving shared semantic constraints. */ +export type Conservative = [I] extends [never] ? Erased - : unknown extends Requirements + : // oxlint-disable-next-line typescript/no-restricted-types -- this type-level check detects erased metadata rather than storing a runtime value + unknown extends I ? Erased - : CollapseAlternatives>; + : Collapse, Empty>; -/** A shared input must satisfy every use, including every host-side union alternative. */ -export type Merge = [keyof Conservative] extends [never] - ? Left - : typeof ErasedRequirement extends - | keyof Conservative - | keyof Conservative - ? never - : [keyof Conservative] extends [never] - ? Conservative - : MergeRecords, Conservative>; +type MergeConservative = typeof ErasedRequirement extends + | keyof L + | keyof R + ? never + : MergeRecords; -type MergeRecords = [keyof Right] extends [never] - ? Left - : [keyof Left] extends [never] - ? Right - : Types.Simplify< - { - readonly [Key in RequiredKeys | RequiredKeys]: Combined< - Left, - Right, - Key - >; - } & { - readonly [Key in Exclude< - keyof Left | keyof Right, - RequiredKeys | RequiredKeys - >]?: Combined; - } - >; +// An input-independent builder step preserves its unresolved left type parameter. Normalizing it again would change the step's generic result type. +type MergeRight = [keyof R] extends [never] + ? L + : MergeConservative, R>; + +/** Combines shared requirements, preserving the left type when the right side needs no inputs. */ +export type Merge = MergeRight>; -/** Combines every member of a tuple, or conservatively intersects an array's member requirements. */ -// oxlint-disable-next-line typescript/no-restricted-types -- each member is an inferred input record -export type All = Members extends readonly [ - infer Head, - ...infer Tail, -] - ? Merge> - : number extends Members["length"] - ? Conservative - : Empty; +/** Combines tuple members, retaining every possible requirement in arrays and optional positions. */ +// oxlint-disable-next-line typescript/no-restricted-types -- inferred metadata includes unknown and never; Conservative detects erasure instead of assuming a valid input record +export type All = T extends readonly [] + ? Empty + : T extends readonly [infer H, ...infer R] + ? Merge> + : Conservative; From 8628a46805dc8fcfccf21e257d58e4d4f62740dd Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:07:01 +0200 Subject: [PATCH 08/22] feat: add explicit predicates and lexical imports --- libs/@local/hashql/sdk/typescript/README.md | 12 +- .../hashql/sdk/typescript/docs/authoring.md | 54 +++- .../typescript/examples/api-tour.test-d.ts | 22 +- .../typescript/examples/filters-draft.test.ts | 4 +- .../sdk/typescript/examples/filters-draft.ts | 30 ++- .../hashql/sdk/typescript/examples/filters.ts | 41 +-- .../hashql/sdk/typescript/src/do/Import.ts | 172 +++---------- .../hashql/sdk/typescript/src/do/Utilities.ts | 32 ++- .../sdk/typescript/src/draft/Context.ts | 28 ++- .../sdk/typescript/src/draft/Import.test-d.ts | 54 ++++ .../sdk/typescript/src/draft/Import.test.ts | 237 ++++++++++++++++++ .../typescript/src/draft/Namespace.test.ts | 5 +- .../src/draft/Requirements.test-d.ts | 7 +- .../hashql/sdk/typescript/src/draft/Scribe.ts | 102 ++++++-- libs/@local/hashql/sdk/typescript/src/main.ts | 1 + .../sdk/typescript/src/program/Expression.ts | 21 +- .../typescript/src/program/ExpressionType.ts | 2 +- .../sdk/typescript/src/program/Fluent.ts | 100 -------- .../sdk/typescript/src/program/Import.ts | 219 ++++++++++++++++ .../typescript/src/program/Inputs.test-d.ts | 18 +- .../sdk/typescript/src/program/Inputs.test.ts | 3 +- .../typescript/src/program/Namespace.test.ts | 2 +- .../sdk/typescript/src/program/Namespace.ts | 47 ++-- .../src/program/Operators.test-d.ts | 47 ++++ .../typescript/src/program/Operators.test.ts | 117 +++++++++ .../sdk/typescript/src/program/Operators.ts | 195 ++++++++++++++ .../src/program/Primitive.test-d.ts | 24 +- .../typescript/src/program/Primitive.test.ts | 5 +- .../{Fluent.test-d.ts => Query.test-d.ts} | 17 +- .../program/{Fluent.test.ts => Query.test.ts} | 9 +- 30 files changed, 1185 insertions(+), 442 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/program/Fluent.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Import.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/program/Operators.ts rename libs/@local/hashql/sdk/typescript/src/program/{Fluent.test-d.ts => Query.test-d.ts} (81%) rename libs/@local/hashql/sdk/typescript/src/program/{Fluent.test.ts => Query.test.ts} (89%) diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 58ffe83bc96..33de4435c0e 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -90,6 +90,8 @@ const query = Result.gen(function* () { ## Imports +In Draft, `$.import(module, selection?)` emits a lexical import and returns the selected local handles. A selection can be a name list or alias record. Types and values sharing a name keep both capabilities. Use the context of the branch or predicate that should own the import. Importing does not mutate `$.prelude()` or add query entry points. + `Import` emits a HashQL `use` expression and introduces local references. `Import((_, { math }) => math)` imports every exported name. A second argument selects names, such as `["cmp"]`, or renames them, such as `{ cmp: "compare" }`. An alias of `"_"` retains the original name. Each selected name enters every environment in which the module exports it, including a same-named type and constructor. Imported child modules expose references beneath their local module name. `Do` from `@local/hashql/do` starts with empty environments. `withPrelude` from the same subpath accepts optional `modules`, `values` and `types` records without emitting imports. The positional `Do` overloads support up to eight declaration steps and a final expression. Chained nested blocks have no fixed step count. @@ -130,7 +132,7 @@ The package does not include a generated standard-library bundle. Type applications preserve the declared semantic result and retain construction failures. `TypeExpression.toType` returns the underlying type syntax as a `Result`. A type expression is not itself raw `JExpr.Type` syntax. -Expression handles support typed projections, `$project`, `$index` and function calls. Direct `then` access returns `undefined` to prevent Promise assimilation. Use `$project("then")` for that field. Generic function declarations use `Semantic.GenericFunction` with a `Semantic.FunctionSignature` mapping argument descriptors to a function signature. +Expression handles support typed projections, `$project`, `$index` and function calls. A `then` field remains directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Generic function declarations use `Semantic.GenericFunction` with a `Semantic.FunctionSignature` mapping argument descriptors to a function signature. `$.literal` accepts JavaScript primitives other than `undefined` and symbols. A `number` produces `Semantic.PrimitiveNumber`, and a `bigint` produces `Semantic.PrimitiveInteger`. This distinction follows the host type, not the value: `1` remains Number even when the serializer emits integer literal syntax. Use `$.number` to construct Number explicitly or `$.integer` for checked integer construction. Non-finite numbers produce construction failures. @@ -138,7 +140,7 @@ Compatible primitives also work as function arguments, index keys, input default `$.input(name, type, defaultValue?)` selects its default only when the host omits the input. The SDK checks matching semantic descriptors rather than general HashQL subtyping. A Number parameter rejects Integer handles and bigints. `$.assume()(expression)` changes the SDK annotation while preserving input requirements. It emits no conversion or HashQL type assertion, and does not prove the new annotation. -Value operations live under `expression.$`: `eq`, `ne`, Boolean `and`, `or`, `isTrue`, `isFalse`, and optional-value `isNone`. Query operations chain directly through `$.query.entities(now()).filter("vertex", predicate).collect()`. The `entities` declaration in the value environment determines the query's argument and vertex types. A filter emits a closure with the supplied parameter name. A query stored in a `Let` binding loses its query-chain methods intentionally, matching a compiler restriction. Complete the chain before binding its collected result. +Operators start on `$`: `eq`, `ne`, Boolean `and`, `or`, `not`, `isTrue`, `isFalse`, and optional-value `isNone`. Their results support `.and(...)`, `.or(...)` and `.not()` directly. Binary operators also support data-last composition, such as `pipe(predicate, $.and(other))`. Standalone code uses the same constructors through `Operators`. Ordinary expressions have no operator methods. Binding a predicate returns a plain Boolean expression. Query operations chain directly through `$.query.entities(now()).filter("vertex", predicate).collect()`. The `entities` declaration in the value environment determines the query's argument and vertex types. A filter emits a closure with the supplied parameter name. A query stored in a `Let` binding loses its query-chain methods intentionally, matching a compiler restriction. Complete the chain before binding its collected result. ## Reusable expressions and inputs @@ -146,7 +148,7 @@ Value operations live under `expression.$`: `eq`, `ne`, Boolean `and`, `or`, `is ```ts import { Result } from "effect"; -import { Expression, Module, Program } from "@local/hashql"; +import { Expression, Module, Operators, Program } from "@local/hashql"; import { Do } from "@local/hashql/do"; import type { Type } from "@local/hashql"; @@ -160,10 +162,10 @@ const query = Result.gen(function* () { const count = Expression.input("count", kernel.types.Integer); - const nonzero = count.$.ne(0n); + const nonzero = Operators.ne(count, 0n); const expression = yield* Do(($) => - nonzero.$.and($.input("enabled", kernel.types.Boolean, true)), + $.and(nonzero, $.input("enabled", kernel.types.Boolean, true)), ); return Program.program(expression); diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md index 344d3e87ec8..50fda4be29e 100644 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -123,7 +123,34 @@ const custom = withPrelude({ types: { Count: Prelude.builtin.types.Integer } }); const closed = custom.program({}, ($) => $.literal(1n)); ``` -`withPrelude` returns `{ program }`, preserving the supplied module, value and type keys. It replaces the default prelude rather than extending it. `$.prelude()` flattens those three namespaces. Colliding type and value exports retain both capabilities on a fresh handle. The original exports are not mutated. Callable generic types dispatch on type arguments, and callable values on value arguments. If an argument has both capabilities, the result can retain both too. `$.modules()` offers flattened module access while each module still exposes its separate `types`, `values` and `modules` records. Namespace metadata takes precedence over same-spelled direct value fields: use `$project("syntax")` for a value field colliding with type syntax, and the separate namespace records for exports whose names collide with `path`, `types`, `values` or `modules`. Exports and projected fields called `then` remain directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Joined expressions reserve `$`, `$project` and `$index` for expression operations. Function intrinsics such as `name` and `length` do not replace module exports. +`withPrelude` returns `{ program }`, preserving the supplied module, value and type keys. It replaces the default prelude rather than extending it. `$.prelude()` flattens those three namespaces. Colliding type and value exports retain both capabilities on a fresh handle. The original exports are not mutated. Callable generic types dispatch on type arguments, and callable values on value arguments. If an argument has both capabilities, the result can retain both too. `$.modules()` offers flattened module access while each module still exposes its separate `types`, `values` and `modules` records. Namespace metadata takes precedence over same-spelled direct value fields: use `$project("syntax")` for a value field colliding with type syntax, and the separate namespace records for exports whose names collide with `path`, `types`, `values` or `modules`. Exports and projected fields called `then` remain directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Joined expressions reserve `$project` and `$index` for explicit access. A field or export named `$` is an ordinary value. Function intrinsics such as `name` and `length` do not replace module exports. + +### Operators and imports + +Operators are explicit constructors on `$`, not methods attached to every expression. `$.eq(left, right)` returns a Boolean expression with `.and`, `.or` and `.not` methods. The same operations support data-last composition through `pipe`. A `$.let` binding returns a plain expression. Use an operator to compose it again. Standalone code can import `Operators` from `@local/hashql` and use the same constructors. + +```ts +import { pipe } from "effect"; +import { program } from "@local/hashql/draft"; + +const selection = program({}, ($) => { + const match = $.eq(1n, 1n).and($.not(false)); + const saved = $.let("saved", match); + return pipe(saved, $.or(false)); +}); +``` + +`$.import(module)` emits a lexical import and returns its typed local exports. Pass a name list or an alias record to select exports. An alias of `"_"` keeps the source name. Type and value exports sharing a name remain joined, and generic constructors retain their call signatures. Imports inside a branch or predicate belong to that child callback. They do not change the type or contents of `$.prelude()` or add entries to `$.query`. + +```ts +import { program } from "@local/hashql/draft"; + +const comparison = program({}, ($) => { + const { cmp } = $.modules(); + const { equal } = $.import(cmp, { eq: "equal" }); + return $.and(equal(1n, 1n), true); +}); +``` ### Declarations and structural shorthand @@ -172,7 +199,7 @@ const selected = program({ axis: Structural.type(BigInt) }, ($, inputs) => .entities(inputs.axis) .filter("vertex", (predicate, vertex) => { const archived = predicate.let("archived", vertex.archived); - return archived.$.isFalse(); + return predicate.isFalse(archived); }) .collect(), ); @@ -180,7 +207,7 @@ const selected = program({ axis: Structural.type(BigInt) }, ($, inputs) => Declarations made through `predicate` stay inside the emitted filter closure. Capturing `$` from the outer callback instead still addresses the outer context. Likewise, JavaScript can save a branch-local reference and return it elsewhere. Draft does not reject those host-reference escapes: the HashQL compiler owns lexical resolution. Keep declarations on the context of the branch or predicate that uses them. Nested and reentrant programs have independent declaration state. -Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Draft continues executing the synchronous callback after such a failure. A user-thrown synchronous exception propagates unchanged. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. +Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Those failures remain on the constructed handles, so the callback can continue. An invalid import cannot supply its promised handles and stops the current callback instead. Its failure still returns through the construction Result, even if host code catches the internal interruption. A user-thrown synchronous exception propagates unchanged. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. ### Default prelude coverage and authority @@ -194,7 +221,7 @@ Expected construction failures return `ProgramError.Construction`. Invalid bindi | Uuid type and constructor | `core/uuid.rs` | | EntityUuid type and constructor | `graph/types/knowledge/entity.rs` | -The free `eq` function accepts independent argument types. The receiver `.$.eq` remains an exact-type operation. `add` accepts Integer or Number arguments and returns their union, reducing equal descriptors to that descriptor. The SDK never converts Integer to Number implicitly. Module routes are `entity`, `uuid`, `cmp` and `math`. Graph queries and temporal declarations must come from a custom prelude. Do still starts with empty environments. +The declared prelude `eq` function accepts independent argument types. The operator `$.eq` checks equal semantic descriptors instead. `add` accepts Integer or Number arguments and returns their union, reducing equal descriptors to that descriptor. The SDK never converts Integer to Number implicitly. Module routes are `entity`, `uuid`, `cmp` and `math`. The default prelude has no graph or temporal declarations. Import declared modules in the body or supply them through a custom prelude. `$.query.entities` requires an `entities` declaration in the prelude. Do still starts with empty environments. ## Shared declarations for the examples @@ -202,7 +229,7 @@ The remaining examples are shorter. Each assumes the imports and declarations be ```ts import { Result } from "effect"; -import { Expression, Module, Program } from "@local/hashql"; +import { Expression, Module, Operators, Program } from "@local/hashql"; import { Do as EmptyDo, Import, @@ -312,7 +339,7 @@ const ordered = Do( Let("Integer", ($) => $.literal("a value named Integer")), ($, { limit, previous }, { Integer }) => $.if( - limit.$.eq("ten"), + Operators.eq(limit, "ten"), () => previous, () => $.input("fallback", Integer), ), @@ -354,7 +381,7 @@ const owner = Do( // @ts-expect-error The representation 2n doesn't have the nominal type. $.input("id", types.UserId, 2n); return $.if( - owner.$.eq(UserId(1n)), + Operators.eq(owner, UserId(1n)), () => $.input("id", types.UserId, UserId(2n)), () => owner, ); @@ -375,7 +402,7 @@ const shadowedId = Do( Newtype("Id", accountId, (_, { Integer }) => Integer), (_, { first, Id }) => { // @ts-expect-error The later `Id` is a different nominal type. - first.$.eq(Id(2n)); + Operators.eq(first, Id(2n)); return first; }, ); @@ -551,14 +578,15 @@ A query starts at `$.query.entities(...)`, adds filters and ends with `collect() ```ts // Uses: the graph fixtures above. const isLive = (entity: Expression.Expression) => - entity.metadata.archived.$.isFalse(); + Operators.isFalse(entity.metadata.archived); const live = graph.Do(($, { now }) => $.query .entities(now()) .filter("entity", isLive) .filter("entity", (entity) => - entity.metadata.archived.$.eq( + Operators.eq( + entity.metadata.archived, $.input("archived", $.ref.kernel.types.Boolean, false), ), ) @@ -592,11 +620,11 @@ An expression handle has two types: the HashQL type of its value, and a record o ```ts // Uses: kernel, Do. const count = Expression.input("count", kernel.types.Integer); -const nonzero = count.$.ne(0n); +const nonzero = Operators.ne(count, 0n); // Expression.Expression const enabled = Do(($) => - nonzero.$.and($.input("enabled", $.ref.kernel.types.Boolean, true)), + Operators.and(nonzero, $.input("enabled", $.ref.kernel.types.Boolean, true)), ); export type EnabledInputs = Expression.Inputs< @@ -753,7 +781,7 @@ const message = (verbose: boolean) => const detail = verbose ? "count equals the target" : "equal"; // HashQL compares `count` with 30 when the query runs. return $.if( - count.$.eq(BigInt(target)), + Operators.eq(count, BigInt(target)), () => detail, () => "different", ); diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts index d87d0910252..0e60fbd2cc5 100644 --- a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -21,6 +21,7 @@ import { withPrelude, } from "../src/do/index.js"; import { Expression, Module, Program } from "../src/main.js"; +import * as Operators from "../src/program/Operators.js"; import type { Inputs, @@ -121,12 +122,9 @@ describe("reusable_expressions", () => { test("inputs_and_defaults", () => { // An expression is a value you can store and reuse. Its second type parameter records the host inputs it needs. const count = Expression.input("count", kernel.types.Integer); - const nonzero = count.$.ne(0n); + const nonzero = Operators.ne(count, 0n); expectTypeOf(nonzero).toEqualTypeOf< - Expression.Expression< - Type.PrimitiveBoolean, - { readonly count: Type.PrimitiveInteger } - > + Operators.Predicate<{ readonly count: Type.PrimitiveInteger }> >(); // A default makes the input optional for the host. @@ -137,7 +135,9 @@ describe("reusable_expressions", () => { // A program that reuses `nonzero` inherits its requirement. const root = Result.getOrThrow( - Do(($) => nonzero.$.and($.input("enabled", kernel.types.Boolean, true))), + Do(($) => + Operators.and(nonzero, $.input("enabled", kernel.types.Boolean, true)), + ), ); const program = Program.program(root); expectTypeOf>().toEqualTypeOf<{ @@ -154,7 +154,9 @@ describe("reusable_expressions", () => { Type.PrimitiveBoolean, Expression.Inputs > = nonzero; - expectTypeOf(named).toEqualTypeOf(nonzero); + expectTypeOf>().toEqualTypeOf< + Expression.Inputs + >(); // @ts-expect-error The default for an Integer input cannot be a Boolean. Expression.input("count", kernel.types.Integer, true); @@ -332,14 +334,14 @@ describe("expressions", () => { test("query_composition", () => { // Keep a predicate as an ordinary function and reuse it across queries. const active = (vertex: Closed): Closed => - vertex.archived.$.isFalse(); + Operators.isFalse(vertex.archived); const built = Do(($, { now }) => $.query .entities(now()) .filter("person", active) .filter("person", (vertex) => - vertex.name.$.eq($.input("name", kernel.types.String)), + Operators.eq(vertex.name, $.input("name", kernel.types.String)), ) .collect(), ); @@ -479,7 +481,7 @@ describe("queries_and_let", () => { Let("people", ($, { axes }) => $.query .entities(axes) - .filter("person", (vertex) => vertex.archived.$.isFalse()) + .filter("person", (vertex) => Operators.isFalse(vertex.archived)) .collect(), ), (_, { people }) => people.$index(0n), diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts index 2e70b7e752b..15c5e269349 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts @@ -42,11 +42,11 @@ const comparisons = pipe( ); describe("draft_filters", () => { - test("query_without_imports", () => { + test("query_with_import", () => { expect.hasAssertions(); expect(examples).toHaveLength(originals.length); expect(compile(allEntities)).toBe( - '["::graph::tail::collect",["::graph::head::entities",["::graph::tmp::decision_time_now"]]]', + '["::kernel::special_form::use","::graph::tmp",{"#struct":{"decision_time_now":"now"}},["::graph::tail::collect",["::graph::head::entities",["now"]]]]', ); }); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts index 841fed12271..23a9be03671 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -40,7 +40,7 @@ const { program } = withPrelude({ }); const allEntities = program({}, ($) => { - const { now } = $.prelude(); + const { now } = $.import(temporary, { decision_time_now: "now" }); return $.query.entities(now()).collect(); }); @@ -49,7 +49,8 @@ const entityByUuid = program({}, ($) => { return $.query .entities(now()) .filter("vertex", (_, vertex) => - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), ), ) @@ -63,7 +64,8 @@ const suppliedTimeAxis = program( return $.query .entities(axis) .filter("vertex", (_, vertex) => - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), ), ) @@ -77,7 +79,7 @@ const predicateLocalBinding = program({}, ($) => { .entities(now()) .filter("vertex", ($) => { const foo = $.let("foo", false); - return $.literal(true).$.and($.literal(true).$.or(foo)); + return $.and(true, $.or(true, foo)); }) .collect(); }); @@ -92,9 +94,9 @@ const publishedEntityById = program( .entities(now()) .filter("vertex", (_, vertex) => { const id = vertex.metadata.record_id.entity_id; - return id.web_id.$.eq(webId) - .$.and(id.entity_uuid.$.eq(entityUuid)) - .$.and(id.draft_id.$.isNone()); + return $.eq(id.web_id, webId) + .and($.eq(id.entity_uuid, entityUuid)) + .and($.isNone(id.draft_id)); }) .collect(); }, @@ -106,11 +108,11 @@ const sidebarSelection = program({ web_id: web.types.WebId }, ($, inputs) => { return $.query .entities(now()) .filter("vertex", (_, vertex) => - vertex.metadata.record_id.entity_id.web_id.$.eq(webId), + $.eq(vertex.metadata.record_id.entity_id.web_id, webId), ) .filter("vertex", (_, vertex) => - vertex.metadata.archived.$.isFalse().$.and( - vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + $.isFalse(vertex.metadata.archived).and( + $.isNone(vertex.metadata.record_id.entity_id.draft_id), ), ) .collect(); @@ -130,8 +132,10 @@ const anyOfEntityIds = program({}, ($) => { selectedIds, // oxlint-disable-next-line unicorn/no-array-reduce -- this is Effect's typed fold, not a native array method Array.reduce($.literal(false), (matches, entityUuid) => - matches.$.or( - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + $.or( + matches, + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, createEntityUuid(createUuid(entityUuid)), ), ), @@ -156,7 +160,7 @@ const optionalDrafts = program( $.ifElse( includeDrafts, () => true, - () => vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + () => $.isNone(vertex.metadata.record_id.entity_id.draft_id), ), ) .collect(); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts index 3ff857ed3b3..f5bbc5ea3b7 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.ts @@ -88,10 +88,9 @@ const entityByUuid = example( $.query .entities(now()) .filter("vertex", (vertex) => - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( - createEntityUuid( - createUuid($.literal("e2851dbb-7376-4959-9bca-f72cafc4448f")), - ), + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), ), ) .collect(), @@ -115,10 +114,9 @@ const suppliedTimeAxis = example( $.query .entities($.input("axis", temporal.types.QueryTemporalAxes)) .filter("vertex", (vertex) => - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( - createEntityUuid( - createUuid($.literal("e2851dbb-7376-4959-9bca-f72cafc4448f")), - ), + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, + createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), ), ) .collect(), @@ -143,7 +141,7 @@ const predicateLocalBinding = example( .entities(now()) .filter("vertex", () => $.Let("foo", ($) => $.literal(false)).Expr(($, { foo }) => - $.literal(true).$.and($.literal(true).$.or(foo)), + $.and(true, $.or(true, foo)), ), ) .collect(), @@ -173,9 +171,10 @@ const publishedEntityById = example( .entities(now()) .filter("vertex", (vertex) => { const id = vertex.metadata.record_id.entity_id; - return id.web_id.$.eq(webId) - .$.and(id.entity_uuid.$.eq(entityUuid)) - .$.and(id.draft_id.$.isNone()); + + return $.eq(id.web_id, webId) + .and($.eq(id.entity_uuid, entityUuid)) + .and($.isNone(id.draft_id)); }) .collect(), ), @@ -201,12 +200,11 @@ const sidebarSelection = example( $.query .entities(now()) .filter("vertex", (vertex) => - vertex.metadata.record_id.entity_id.web_id.$.eq(webId), + $.eq(vertex.metadata.record_id.entity_id.web_id, webId), ) .filter("vertex", (vertex) => - vertex.metadata.archived.$.isFalse().$.and( - vertex.metadata.record_id.entity_id.draft_id.$.isNone(), - ), + $.isFalse(vertex.metadata.archived) // + .and($.isNone(vertex.metadata.record_id.entity_id.draft_id)), ) .collect(), ), @@ -231,12 +229,15 @@ const anyOfEntityIds = example( .filter("vertex", (vertex) => { let matches = $.literal(false); for (const entityUuid of selectedIds) { - matches = matches.$.or( - vertex.metadata.record_id.entity_id.entity_uuid.$.eq( + matches = $.or( + matches, + $.eq( + vertex.metadata.record_id.entity_id.entity_uuid, createEntityUuid(createUuid($.literal(entityUuid))), ), ); } + return matches; }) .collect(), @@ -260,8 +261,8 @@ const optionalDrafts = example( .filter("vertex", (vertex) => $.if( includeDrafts, - () => $.literal(true), - () => vertex.metadata.record_id.entity_id.draft_id.$.isNone(), + () => true, + () => $.isNone(vertex.metadata.record_id.entity_id.draft_id), ), ) .collect(), diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts index c8bd1789e75..23194f99a70 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.ts @@ -1,163 +1,51 @@ /** - * Lexical imports shared by the Do authoring operations. - * - * The emitted import binds selected names locally. Export handles receive those local paths while retaining the module's declared types. The compiler resolves the import itself. + * Lexical imports into a sequential Do scope. * * @module */ -// oxlint-disable import/max-dependencies -- an import updates the module, type and value universes together -import { Result } from "effect"; +import { Result, pipe } from "effect"; -import { isReadonlyArray } from "../internal/array.js"; -import * as JExpr from "../jexpr/index.js"; -import * as AST from "../program/ast/index.js"; -import * as Expression from "../program/Expression.js"; -import * as Module from "../program/Module.js"; -import * as ProgramError from "../program/ProgramError.js"; +import * as Imports from "../program/Import.js"; import * as Scope from "../program/Scope.js"; -import * as TypeExpression from "../program/TypeExpression.js"; import * as Node from "./Node.js"; import type * as Inputs from "../program/Inputs.js"; +import type * as Module from "../program/Module.js"; import type { Utilities } from "./Utilities.js"; -import type { ReadonlyRecord } from "effect/Record"; - -type Name = Extract< - keyof M["modules"] | keyof M["values"] | keyof M["types"], - string ->; - -export type Selection = - | "*" - | readonly Name[] - | Partial, string>>; - -type Selected = Imports extends "*" - ? Exports - : Imports extends readonly string[] - ? Pick> - : { - readonly [Key in keyof Exports as Key extends keyof Imports - ? Imports[Key] extends "_" - ? Key - : Imports[Key] extends string - ? Imports[Key] - : never - : never]: Exports[Key]; - }; -export interface Imported { - readonly modules: Selected; - readonly values: Selected; - readonly types: Selected; -} +export type { Imported, Selection } from "../program/Import.js"; /** Imports selected module exports into their respective universes. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the selector and selection construct a declaration step -export function Import( - select: (utilities: Utilities, modules: In["modules"]) => M, -): Node.Node, Inputs.Empty>; +export function Import( + select: ( + utilities: Utilities, + modules: S["modules"], + ) => M & Imports.Rebindable, +): Node.Node>, Inputs.Empty>; export function Import< - In extends Scope.Scope, + S extends Scope.Scope, M extends Module.Any, - const Imports extends Selection, + const I extends Imports.Selection, >( - select: (utilities: Utilities, modules: In["modules"]) => M, - imports: Imports, -): Node.Node>, Inputs.Empty>; -export function Import( - select: (utilities: Utilities, modules: In["modules"]) => Module.Any, + select: ( + utilities: Utilities, + modules: S["modules"], + ) => M & Imports.Rebindable, + selection: I, +): Node.Node>, Inputs.Empty>; +export function Import( + select: (utilities: Utilities, modules: S["modules"]) => Module.Any, // oxlint-disable-next-line hash/prefer-options-object -- the optional argument is the import selection itself - imports: JExpr.Imports = "*", + selection: Imports.Selection = "*", ): Node.Any { - return Node.make((utilities: Utilities, scope: In) => - Result.gen(function* () { - const module = select(utilities, scope.modules); - - const names: [string, string][] = []; - - if (imports === "*") { - for (const name of new Set([ - ...Object.keys(module.modules), - ...Object.keys(module.values), - ...Object.keys(module.types), - ])) { - names.push([name, name]); - } - } else if (isReadonlyArray(imports)) { - for (const name of imports) { - names.push([name, name]); - } - } else { - for (const [name, alias] of Object.entries(imports)) { - if (alias === "_") { - names.push([name, name]); - } else { - names.push([name, alias]); - } - } - } - - const modules: [string, Module.Any][] = []; - const values: [string, Expression.Any][] = []; - const types: [string, TypeExpression.Export][] = []; - const renamed: [string, string][] = []; - const selected: string[] = []; - - for (const [name, alias] of names) { - const ident = yield* JExpr.Ident.decodeResult(alias).pipe( - Result.mapError( - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidImportName({ - name: alias, - cause, - }), - }), - ), - ); - selected.push(name); - renamed.push([name, JExpr.Ident.compile(ident)]); - - const path = { rooted: false, segments: [ident] as const }; - const child = module.modules[name]; - if (child !== undefined) { - modules.push([alias, yield* Module.relocate(child, path)]); - } - - if (module.values[name] !== undefined) { - values.push([ - alias, - Expression.fromJExpr(JExpr.Ident.compile(ident)), - ]); - } - - const type = module.types[name]; - if (type !== undefined) { - types.push([ - alias, - yield* TypeExpression.relocate(type, path), - ]); - } - } - - const added = { - modules: Object.fromEntries(modules), - values: Object.fromEntries(values), - types: Object.fromEntries(types), - }; - - let emitted: JExpr.Imports = "*"; - if (isReadonlyArray(imports)) { - emitted = Object.freeze(selected); - } else if (imports !== "*") { - emitted = Object.freeze(Object.fromEntries(renamed)); - } - - return { - scope: Scope.merge(scope, added), - wrap: (child) => new AST.Import(module.path, emitted, child), - }; - }), + return Node.make((utilities: Utilities, scope: S) => + pipe( + Imports.bind(select(utilities, scope.modules), selection), + Result.map((declaration) => ({ + scope: Scope.merge(scope, declaration.scope), + wrap: declaration.wrap, + })), + ), ); } diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index df59e5faf56..2ed557b6bd1 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -10,6 +10,7 @@ import { Result } from "effect"; import * as Expression from "../program/Expression.js"; +import * as Operators from "../program/Operators.js"; import * as ProgramError from "../program/ProgramError.js"; import * as Query from "../program/Query.js"; import { Import } from "./Import.js"; @@ -18,6 +19,7 @@ import { Newtype } from "./Newtype.js"; import * as Node from "./Node.js"; import { Type as DeclareType } from "./Type.js"; +import type { Rebindable } from "../program/Import.js"; import type * as Input from "../program/Inputs.js"; import type * as Scope from "../program/Scope.js"; import type { TypeExpression } from "../program/TypeExpression.js"; @@ -123,29 +125,38 @@ export class Block { } Import>( - select: (utilities: Utilities, modules: S["modules"]) => M, - ): Block, Inputs>; + select: ( + utilities: Utilities, + modules: S["modules"], + ) => M & Rebindable, + ): Block>, Inputs>; Import< M extends NonNullable, const Imports extends Selection, >( - select: (utilities: Utilities, modules: S["modules"]) => M, + select: ( + utilities: Utilities, + modules: S["modules"], + ) => M & Rebindable, imports: Imports, ): Block>, Inputs>; Import< M extends NonNullable, const Imports extends Selection, >( - select: (utilities: Utilities, modules: S["modules"]) => M, + select: ( + utilities: Utilities, + modules: S["modules"], + ) => M & Rebindable, imports?: Imports, ): - | Block, Inputs> + | Block>, Inputs> | Block>, Inputs> { if (imports === undefined) { - return this.#step(Import(select)); + return this.#step(Import(select)); } - return this.#step(Import(select, imports)); + return this.#step(Import(select, imports)); } Expr( @@ -225,10 +236,8 @@ const conditional = < // oxlint-disable-next-line unicorn/no-thenable -- these are query branches, not a Promise implementation Expression.ifElse(condition, { then: consequent(), else: alternate() }); -export interface Utilities extends Block< - S, - Input.Empty -> { +export interface Utilities + extends Block, Operators.Operations { readonly literal: typeof Expression.literal; readonly integer: typeof Expression.integer; readonly number: typeof Expression.number; @@ -243,6 +252,7 @@ const makeUtilities = (scope: S): Utilities => Object.assign( new Block(Result.succeed({ scope, parents: [] })), { + ...Operators.operations, literal: Expression.literal, integer: Expression.integer, number: Expression.number, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts index 03105f439e6..cfe261701df 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -6,15 +6,20 @@ * @module */ import type { Relocatable, Relocate } from "../internal/relocation.js"; -import type * as Expression from "../program/Expression.js"; +import type { + Expression, + Inputs, + Module, + Operators, + Type, + TypeExpression, +} from "../main.js"; import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; -import type * as Inputs from "../program/Inputs.js"; +import type * as Import from "../program/Import.js"; import type * as Namespace from "../program/Namespace.js"; import type * as QueryTypes from "../program/Query.js"; import type * as Scope from "../program/Scope.js"; import type * as Structural from "../program/Structural.js"; -import type * as TypeExpression from "../program/TypeExpression.js"; -import type * as Type from "../type/index.js"; export type NominalCall = < const V extends Structural.Value & Structural.AnyValue, @@ -25,10 +30,6 @@ export type NominalCall = < /** Each constructor has one rebinding result rather than an intersection of recursive overloads. */ export interface NominalValue extends Expression.Any, NominalCall { - readonly $: Expression.Expression< - Type.Function>, - Inputs.Empty - >["$"]; readonly "~hashql/Expression": Expression.Handle< Type.Function>, Inputs.Empty @@ -99,9 +100,18 @@ export type Conditional< > >; -export interface Context { +export interface Context extends Operators.Operations { readonly prelude: () => Namespace.Flatten; readonly modules: () => Namespace.Modules; + readonly import: { + ( + module: M & Import.Rebindable, + ): Namespace.Flatten>; + >( + module: M & Import.Rebindable, + selection: I, + ): Namespace.Flatten>; + }; readonly literal: typeof Expression.literal; readonly integer: typeof Expression.integer; readonly number: typeof Expression.number; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts new file mode 100644 index 00000000000..1311de34b5e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test-d.ts @@ -0,0 +1,54 @@ +/** Import selections retain names, signatures and input requirements. @module */ +import { Result } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Module, Prelude } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Type } from "../main.js"; + +const integer = Prelude.builtin.types.Integer; +const outside = Expression.input("outside", integer); +const source = Result.getOrThrow( + Module.define("::requirements", { + values: { outside }, + types: { Integer: integer }, + }), +); + +describe("draft_import_types", () => { + test("import_names", () => { + Draft.program({ outside: integer }, ($) => { + const selected = $.import(source, { outside: "local" }); + expectTypeOf(selected).toHaveProperty("local"); + expectTypeOf(selected).not.toHaveProperty("outside"); + expectTypeOf(selected).not.toHaveProperty("Integer"); + expectTypeOf(selected.local).toEqualTypeOf(); + // @ts-expect-error An import does not mutate the existing context's prelude type. + expectTypeOf($.prelude().local); + // @ts-expect-error A selection must name a declared export. + $.import(source, ["absent"]); + // @ts-expect-error Alias sources must name declared exports. + $.import(source, { absent: "local" }); + return selected.local; + }); + }); + + test("import_requirements", () => { + // @ts-expect-error Imported handles keep requirements from their declarations. + Draft.program({}, ($) => $.import(source).outside); + Draft.program({}, ($) => { + const imported = $.import(source); + // @ts-expect-error Discarding an initializer cannot conceal an imported requirement. + $.let("discarded", imported.outside); + return $.literal(true); + }); + const result = Draft.program( + { outside: integer }, + ($) => $.import(source).outside, + ); + expectTypeOf< + Expression.Inputs> + >().toEqualTypeOf<{ readonly outside: Type.PrimitiveInteger }>(); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts new file mode 100644 index 00000000000..9f753045c2d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts @@ -0,0 +1,237 @@ +/** Lexical imports preserve selected capabilities and callback boundaries. @module */ +import { Result, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import { Do, Import } from "../do/index.js"; +import * as TypeSyntax from "../jexpr/type/index.js"; +import { Expression, JExpr, Module, Prelude, TypeExpression } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +const child = Result.getOrThrow( + Module.define("::leaf", { + values: { enabled: Module.value() }, + }), +); +const declarations = Result.getOrThrow( + Module.define("::example", { + modules: { child }, + types: { + Whole: Module.type(), + List: Prelude.builtin.types.List, + }, + values: { + Whole: + Module.value< + Type.Function + >(), + }, + }), +); +const compile = ( + result: Result.Result, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_import", () => { + test("selected_capabilities", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const { Whole, List } = $.import(declarations, ["Whole", "List"]); + expectTypeOf(Whole(1n)).toEqualTypeOf< + Expression.Expression + >(); + expectTypeOf(List(String)).toEqualTypeOf< + TypeExpression.TypeExpression> + >(); + expect( + TypeSyntax.compile( + Result.getOrThrow(TypeExpression.toType(List(String))), + ), + ).toBe("List<::kernel::type::String>"); + expect( + TypeSyntax.compile(Result.getOrThrow(TypeExpression.toType(Whole))), + ).toBe("Whole"); + return Whole(1n); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example",{"#tuple":["Whole","List"]},["Whole",{"#literal":1}]]', + ); + }); + + test("wildcard_and_nested_module", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const imported = $.import(declarations); + const { active } = $.import(imported.child, { enabled: "active" }); + expectTypeOf(active).toEqualTypeOf(); + return $.and(active, true); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example","*",["::kernel::special_form::use","child",{"#struct":{"enabled":"active"}},["::core::bool::and","active",{"#literal":true}]]]', + ); + }); + + test("branch_scope", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => + $.ifElse( + true, + ($) => { + const { Whole } = $.import(declarations, { Whole: "_" }); + return Whole(1n); + }, + () => 0n, + ), + ); + expect(compile(result)).toBe( + '["::kernel::special_form::if",{"#literal":true},["::kernel::special_form::use","::example",{"#struct":{"Whole":"Whole"}},["Whole",{"#literal":1}]],{"#literal":0}]', + ); + }); + + test("adapted_callable", () => { + expect.hasAssertions(); + const original = Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("::original"); + const adapted = Expression.adaptCallable( + original, + (self) => + (value: { + readonly text: string; + }): Expression.Expression => + self(value.text), + ); + const source = Result.getOrThrow( + Module.define("::adapted", { values: { call: adapted } }), + ); + const result = Draft.program({}, ($) => { + const { invoke } = $.import(source, { call: "invoke" }); + expectTypeOf(invoke).toEqualTypeOf(adapted); + return invoke({ text: "value" }); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::adapted",{"#struct":{"call":"invoke"}},["invoke",{"#literal":"value"}]]', + ); + const throughDo = Do( + Import(() => source, { call: "invoke" }), + (_, { invoke }) => invoke({ text: "value" }), + ); + expect(compile(throughDo)).toBe(compile(result)); + }); + + test("symbol_alias", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const imported = $.import(declarations, { Whole: "+" }); + expect(Object.hasOwn(imported, "+")).toBe(true); + return imported["+"](1n); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::example",{"#struct":{"Whole":"`+`"}},["`+`",{"#literal":1}]]', + ); + }); + + test("own_names", () => { + expect.hasAssertions(); + const values = { + ["__proto__"]: Expression.literal(true), + hidden: Expression.literal(false), + }; + Object.defineProperty(values, "hidden", { enumerable: false }); + const source = Result.getOrThrow(Module.define("::own", { values })); + const result = Draft.program({}, ($) => { + const imported = $.import(source); + expect(Object.hasOwn(imported, "__proto__")).toBe(true); + expect(Object.hasOwn(imported, "hidden")).toBe(true); + const { __proto__: prototypeNamed } = imported; + return $.and(prototypeNamed, imported.hidden); + }); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::own","*",["::core::bool::and","__proto__","hidden"]]', + ); + expect(Object.isFrozen(values)).toBe(false); + }); + + test("repeated_alias", () => { + expect.hasAssertions(); + const source = Result.getOrThrow( + Module.define("::aliases", { + values: { + first: Module.value(), + second: Module.value(), + }, + }), + ); + const result = Draft.program( + {}, + ($) => + $.import(source, { first: "selected", second: "selected" }).selected, + ); + expect(compile(result)).toBe( + '["::kernel::special_form::use","::aliases",{"#struct":{"first":"selected","second":"selected"}},"selected"]', + ); + }); + + test("symbol_selection", () => { + expect.hasAssertions(); + const hidden = Symbol("hidden"); + const selection = { Whole: "Whole", [hidden]: "hidden" }; + const result = Draft.program({}, ($) => { + $.import(declarations, selection); + return $.literal(true); + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidImportName", name: String(hidden) } }, + }); + }); + + test("invalid_alias", () => { + expect.hasAssertions(); + let continued = false; + const result = Draft.program({}, ($) => { + const { "bad name": whole } = $.import(declarations, { + Whole: "bad name", + }); + continued = true; + return whole(1n); + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { reason: { _tag: "InvalidImportName", name: "bad name" } }, + }); + expect(continued).toBe(false); + }); + + test("caught_import_failure", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + try { + $.import(declarations, { Whole: "bad name" }); + } catch { + /* The collector must still retain this construction failure. */ + } + return $.literal(true); + }); + expect(Result.isFailure(result)).toBe(true); + }); + + test("host_exception", () => { + expect.hasAssertions(); + const error = new Error("host callback"); + expect(() => + Draft.program({}, ($) => { + $.import(declarations); + throw error; + }), + ).toThrow(error); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts index e83005d5611..545ce4939d3 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts @@ -7,6 +7,7 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; import { Expression, Module, Structural, TypeExpression } from "../main.js"; +import * as Operators from "../program/Operators.js"; import * as Draft from "./index.js"; import type { Type } from "../main.js"; @@ -59,8 +60,8 @@ describe("draft_namespace", () => { expect(Both.then).toBe(child.values.then); expect($.modules().Both.then).toBe(child.values.then); expect(Both.values.$).toBe(child.values.$); - expect(Expression.isExpression(Both.$)).toBe(false); - return Both.$.eq(1n); + expect(Both.$).toBe(child.values.$); + return Operators.eq(Both, 1n); }); expect(result).toSatisfy(Result.isSuccess); }); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts index 331e113a799..3162b8e1baf 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts @@ -3,6 +3,7 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; import { Expression, Module, Prelude, Structural } from "../main.js"; +import * as Operators from "../program/Operators.js"; import * as Fixtures from "./fixtures.js"; import * as Draft from "./index.js"; @@ -80,7 +81,7 @@ describe("draft_requirements", () => { const defaulted = Expression.input("defaulted", integer, erasedValue); const erasedReceiver: Expression.Expression = outside; - const receiverCall = erasedReceiver.$.eq(outside); + const receiverCall = Operators.eq(erasedReceiver, outside); const erasedCallee: Expression.Expression< Expression.TypeOf, never @@ -247,8 +248,8 @@ describe("draft_requirements", () => { }).program({ outside: integer }, ($) => { const { Both } = $.prelude(); const thenValue = Both.then; - // @ts-expect-error the fluent operation object is not a module value - const dollarValue: Expression.Any = Both.$; + const dollarValue = Both.$; + expectTypeOf(dollarValue).toEqualTypeOf(); expectTypeOf(Both).not.toHaveProperty("$project"); expectTypeOf(Both).not.toHaveProperty("$index"); expectTypeOf($.modules().Both.then).toEqualTypeOf< diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts index 23be0a85097..035136d4c0d 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts @@ -5,20 +5,22 @@ * * @module */ -import { Result, pipe } from "effect"; +import { Data, Result, pipe } from "effect"; import { Expression, JExpr, + Operators, ProgramError, Structural, TypeExpression, } from "../main.js"; import * as AST from "../program/ast/index.js"; +import * as Import from "../program/Import.js"; import * as Namespace from "../program/Namespace.js"; import type * as Syntax from "../jexpr/type/index.js"; -import type { Inputs, Type } from "../main.js"; +import type { Inputs, Module, Type } from "../main.js"; import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; import type * as Scope from "../program/Scope.js"; import type * as Body from "./Body.js"; @@ -85,6 +87,11 @@ const nominal = ( >(value, type); }; +/** Stops a callback when an import cannot supply its promised handles. User exceptions pass through. */ +const ConstructionFailure = Data.TaggedError("DraftConstructionFailure")<{ + readonly failure: ProgramError.Construction; +}>; + class ContextImpl implements Context.Context { readonly #scope: S & Namespace.Rebindable; readonly #prelude: Namespace.Flatten; @@ -96,6 +103,14 @@ class ContextImpl implements Context.Context { readonly number = Expression.number; readonly assume = Expression.assume; readonly input = Expression.input; + readonly eq = Operators.eq; + readonly ne = Operators.ne; + readonly and = Operators.and; + readonly or = Operators.or; + readonly not = Operators.not; + readonly isTrue = Operators.isTrue; + readonly isFalse = Operators.isFalse; + readonly isNone = Operators.isNone; constructor(scope: S & Namespace.Rebindable) { this.#scope = scope; @@ -111,6 +126,33 @@ class ContextImpl implements Context.Context { return this.#modules; } + import( + module: M & Import.Rebindable, + ): Namespace.Flatten>; + import>( + module: M & Import.Rebindable, + selection: I, + ): Namespace.Flatten>; + import>( + module: M & Import.Rebindable, + // oxlint-disable-next-line hash/prefer-options-object -- the optional argument is the import selection itself + selection: I | "*" = "*", + ): Namespace.Flatten> { + const declaration = Import.bind(module, selection); + this.#wrappers.push( + pipe( + declaration, + Result.map((imported) => imported.wrap), + ), + ); + // Keep the failure in the collector even if host code catches the private control-flow exception. + const imported = Result.getOrThrowWith( + declaration, + (failure) => new ConstructionFailure({ failure }), + ); + return Namespace.flatten>(imported.scope); + } + let( name: string, value: E, @@ -365,32 +407,40 @@ class ContextImpl implements Context.Context { build( body: ($: Context.Context) => Expression.AnyValue, ): Result.Result { - const expression = body(this); - if ( - !Expression.isExpression(expression) && - !( - expression === null || - ["string", "number", "bigint", "boolean"].includes(typeof expression) - ) - ) { - return Result.fail(ProgramError.Construction.invalidBodyResult()); - } + try { + const expression = body(this); + if ( + !Expression.isExpression(expression) && + !( + expression === null || + ["string", "number", "bigint", "boolean"].includes(typeof expression) + ) + ) { + return Result.fail(ProgramError.Construction.invalidBodyResult()); + } - return pipe( - { - wrappers: Result.all(this.#wrappers), - node: Expression.toNode(expression), - }, - Result.all, - Result.map(({ wrappers, node }) => { - let root = node; - for (const wrap of wrappers.toReversed()) { - root = wrap(root); - } + return pipe( + { + wrappers: Result.all(this.#wrappers), + node: Expression.toNode(expression), + }, + Result.all, + Result.map(({ wrappers, node }) => { + let root = node; + for (const wrap of wrappers.toReversed()) { + root = wrap(root); + } - return root; - }), - ); + return root; + }), + ); + } catch (error) { + if (error instanceof ConstructionFailure) { + return Result.fail(error.failure); + } + + throw error; + } } } diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index 9528ca3423f..2de56977d8e 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,6 +1,7 @@ export * as JExpr from "./jexpr/index.js"; export * as Expression from "./program/Expression.js"; export * as Module from "./program/Module.js"; +export * as Operators from "./program/Operators.js"; export * as Prelude from "./program/Prelude.js"; export * as Structural from "./program/Structural.js"; export * as Program from "./program/index.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts index 6c269a807e1..947033227e1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts @@ -13,18 +13,12 @@ import { Function, Predicate, Result, Schema, identity, pipe } from "effect"; import { Relocate } from "../internal/relocation.js"; import * as JExpr from "../jexpr/index.js"; import * as AST from "./ast/index.js"; -import * as Fluent from "./Fluent.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; import type { Relocatable } from "../internal/relocation.js"; import type * as Type from "../type/index.js"; -import type { - Accessors, - Callable, - Conditional, - Normalize, -} from "./ExpressionType.js"; +import type { Accessors, Callable, Conditional } from "./ExpressionType.js"; import type * as Input from "./Inputs.js"; import type { Types } from "effect"; @@ -119,7 +113,7 @@ class ExpressionImpl { /** A symbolic HashQL value with type-directed projection, indexing and calls. */ export type Expression = Handle & Accessors & - Callable & { readonly $: Fluent.Operations, Inputs> }; + Callable; /** Recognizes expression handles without checking their semantic types. */ // oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values @@ -197,11 +191,6 @@ const make = ( receiver, ): // oxlint-disable-next-line typescript/no-restricted-types -- proxy property reads may return arbitrary host values unknown { - if (property === "$") { - // oxlint-disable-next-line eslint/no-use-before-define -- the operation factories and expression proxy are mutually recursive - return Fluent.make(target, { fromResult, fromJExpr, toJExpr }); - } - if (property === "$index") { return (key: AnyValue) => { const expr = Result.map( @@ -281,9 +270,8 @@ export const fromNode = ( /** A replacement call signature with the source expression's semantic metadata. */ export type Adapted = C & - Pick, typeof TypeId | typeof Binding> & { - readonly $: Fluent.Operations, I>; - } & Relocatable>; + Pick, typeof TypeId | typeof Binding> & + Relocatable>; /** * Adapts host arguments while preserving expression metadata and rebinding. @@ -307,7 +295,6 @@ export const adaptCallable: { Object.assign(adapt(self), { [TypeId]: self[TypeId], [Binding]: self[Binding], - $: self.$, [Relocate]: ( path: JExpr.Path.Path, ): Result.Result, ProgramError.Construction> => diff --git a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts index 74fbcb50464..2742572988d 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts @@ -298,7 +298,7 @@ type IndexOf = [T] extends [Type.List] type ProjectionAccessors = { readonly [Key in Exclude< keyof Fields, - "$" | "$project" | "$index" | "~hashql/Expression" + "$project" | "$index" | "~hashql/Expression" >]: Fields[Key] extends infer Field extends Type.Any ? Expression.Expression, Inputs> : never; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts b/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts deleted file mode 100644 index 090a86b8fd4..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/program/Fluent.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { Result } from "effect"; - -import * as JExpr from "../jexpr/index.js"; -import * as AST from "./ast/index.js"; - -import type * as Type from "../type/index.js"; -import type * as Expression from "./Expression.js"; -import type * as Input from "./Inputs.js"; - -interface Comparison { - readonly eq: >( - other: Other, - ) => Expression.Expression< - Type.PrimitiveBoolean, - Input.Merge> - >; - readonly ne: >( - other: Other, - ) => Expression.Expression< - Type.PrimitiveBoolean, - Input.Merge> - >; -} - -interface BooleanOperations { - readonly and: >( - other: Other, - ) => Expression.Expression< - Type.PrimitiveBoolean, - Input.Merge> - >; - readonly or: >( - other: Other, - ) => Expression.Expression< - Type.PrimitiveBoolean, - Input.Merge> - >; - readonly isTrue: () => Expression.Expression; - readonly isFalse: () => Expression.Expression; -} - -// oxlint-disable-next-line typescript/no-generated-empty-object-type -- inapplicable operations add no members -type Empty = Record; - -type Optional = - T extends Type.Union - ? Extract< - Members[number], - Type.Opaque<"::core::option::None", Type.Any> - > extends never - ? Empty - : { - readonly isNone: () => Expression.Expression< - Type.PrimitiveBoolean, - Inputs - >; - } - : Empty; - -export type Operations = Comparison & - (T extends Type.PrimitiveBoolean ? BooleanOperations : Empty) & - Optional; - -interface Runtime { - readonly eq: (other: Expression.AnyValue) => Expression.Any; - readonly ne: (other: Expression.AnyValue) => Expression.Any; - readonly and: (other: Expression.AnyValue) => Expression.Any; - readonly or: (other: Expression.AnyValue) => Expression.Any; - readonly isTrue: () => Expression.Any; - readonly isFalse: () => Expression.Any; - readonly isNone: () => Expression.Any; -} - -type Factory = Pick; - -/** The expression proxy exposes only operations allowed by its semantic descriptor. */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the expression implementation supplies factories to avoid a runtime import cycle -export const make = (self: Expression.Any, factory: Factory): Runtime => { - const call = ( - path: string, - ...args: readonly Expression.AnyValue[] - ): Expression.Any => - factory.fromResult( - Result.all(args.map(factory.toJExpr)).pipe( - Result.map((args) => new AST.Expr(JExpr.call(path, ...args))), - ), - ); - - return { - eq: (other) => call("::core::cmp::eq", self, other), - ne: (other) => call("::core::cmp::ne", self, other), - and: (other) => call("::core::bool::and", self, other), - or: (other) => call("::core::bool::or", self, other), - isTrue: () => - call("::core::cmp::eq", self, factory.fromJExpr(JExpr.literal(true))), - isFalse: () => - call("::core::cmp::eq", self, factory.fromJExpr(JExpr.literal(false))), - isNone: () => call("::core::cmp::eq", self, call("::core::option::None")), - }; -}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.ts b/libs/@local/hashql/sdk/typescript/src/program/Import.ts new file mode 100644 index 00000000000..f47bbe4445f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Import.ts @@ -0,0 +1,219 @@ +/** + * Typed lexical imports shared by the authoring APIs. + * + * Selection changes local names, not the declared types or callable capabilities. Each selected producer rebinds itself before the namespace join. The compiler remains responsible for resolving the emitted import. + * + * @module + */ +import { Array, Result, SchemaParser, pipe } from "effect"; + +import { isReadonlyArray } from "../internal/array.js"; +import { relocate } from "../internal/relocation.js"; +import * as JExpr from "../jexpr/index.js"; +import * as AST from "./ast/index.js"; +import * as ProgramError from "./ProgramError.js"; + +import type { Relocatable } from "../internal/relocation.js"; +import type * as Module from "./Module.js"; +import type * as Namespace from "./Namespace.js"; +import type { ReadonlyRecord } from "effect/Record"; + +type Name = Extract< + keyof M["modules"] | keyof M["values"] | keyof M["types"], + string +>; +export type Selection = + | "*" + | readonly Name[] + | Partial, string>>; + +type Selected = I extends "*" + ? E + : I extends readonly string[] + ? Pick> + : { + readonly [K in keyof E as K extends keyof I + ? I[K] extends "_" + ? K + : I[K] extends string + ? I[K] + : never + : never]: E[K]; + }; + +export interface Imported { + readonly modules: Selected; + readonly values: Selected; + readonly types: Selected; +} + +interface Plan { + readonly names: ReadonlyMap< + string, + { readonly alias: string; readonly ident: JExpr.Ident.Ident } + >; + readonly syntax: JExpr.Imports; +} + +const decodeName = SchemaParser.decodeUnknownResult(JExpr.Ident.Schema); + +const importName = ( + name: string | undefined, +): Result.Result => + pipe( + decodeName(name), + Result.mapError( + (cause) => + new ProgramError.Construction({ + reason: ProgramError.Reason.InvalidImportName({ + name: String(name), + cause, + }), + }), + ), + ); + +const requests = ( + module: Module.Any, + selection: Selection, +): readonly (readonly [string, string | undefined])[] => { + if (selection === "*") { + return Array.map( + [ + ...new Set([ + ...Object.getOwnPropertyNames(module.modules), + ...Object.getOwnPropertyNames(module.types), + ...Object.getOwnPropertyNames(module.values), + ]), + ], + (name) => [name, name] as const, + ); + } + + if (isReadonlyArray(selection)) { + return pipe( + selection, + Array.map((name) => [name, name] as const), + ); + } + + return pipe( + Object.getOwnPropertyNames(selection), + Array.map((name) => { + const alias = selection[name]; + if (alias === "_") { + return [name, name] as const; + } + + return [name, alias] as const; + }), + ); +}; + +const plan = ( + module: Module.Any, + selection: Selection, +): Result.Result => + Result.gen(function* () { + const names = new Map< + string, + { readonly alias: string; readonly ident: JExpr.Ident.Ident } + >(); + + const aliases: [string, string][] = []; + for (const [name, alias] of requests(module, selection)) { + const ident = yield* importName(alias); + names.set(name, { alias: String(alias), ident }); + aliases.push([name, JExpr.Ident.compile(ident)]); + } + + if (typeof selection === "object") { + for (const name of Object.getOwnPropertySymbols(selection)) { + yield* importName(String(name)); + } + } + + let syntax: JExpr.Imports = "*"; + if (isReadonlyArray(selection)) { + syntax = Object.freeze([...names.keys()]); + } else if (selection !== "*") { + syntax = Object.freeze(Object.fromEntries(aliases)); + } + + return { names, syntax }; + }); + +interface Capability extends Relocatable {} +type Rebindings = { readonly [K in keyof E]: Relocatable }; + +export interface Rebindable { + readonly modules: M["modules"] & Rebindings; + readonly types: M["types"] & Rebindings; + readonly values: M["values"] & Rebindings; +} + +/** Rebinds each value at its original E[K] type before asserting the renamed table. */ +const select = , I>( + entries: E & Rebindings, + names: Plan["names"], +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const selected: Partial> = {}; + const sources: Rebindings = entries; + // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K retains the original producer result E[K] before the alias changes its key + const member = ( + name: K, + { + alias, + ident, + }: { readonly alias: string; readonly ident: JExpr.Ident.Ident }, + ): Result.Result>, ProgramError.Construction> => + pipe( + relocate(sources[name], { rooted: false, segments: [ident] }), + Result.map((value) => + Object.defineProperty(selected, alias, { + value, + enumerable: true, + configurable: true, + }), + ), + ); + + for (const name of Object.getOwnPropertyNames(entries)) { + const ident = names.get(name); + if (ident !== undefined) { + yield* member(name, ident); + } + } + + // SAFETY: Plan selects the requested source names and aliases; member retains E[K] for each selected key, including non-enumerable own exports. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- TypeScript cannot express this key remapping through Object.defineProperty + return Object.freeze(selected) as Selected; + }); + +export interface Declaration { + readonly scope: Imported & Namespace.Rebindable>; + readonly wrap: (child: AST.Node) => AST.Node; +} + +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the module and selection construct a declaration +export const bind = >( + module: M & Rebindable, + selection: I, +): Result.Result, ProgramError.Construction> => + Result.gen(function* () { + const selected = yield* plan(module, selection); + const scope: Imported = yield* Result.all({ + modules: select(module.modules, selected.names), + types: select(module.types, selected.names), + values: select(module.values, selected.names), + }); + + return { + // SAFETY: every selected member came from a producer checked by Rebindable, and its own relocation returns that same capability. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- mapped selections retain the producer bound that TypeScript cannot distribute through Selected + scope: scope as Imported & Namespace.Rebindable>, + wrap: (child: AST.Node): AST.Node => + new AST.Import(module.path, selected.syntax, child), + }; + }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts index 08e0634a18f..39b561ac945 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts @@ -3,6 +3,7 @@ import { describe, expectTypeOf, test } from "vitest"; import { Do as EmptyDo, Let, withPrelude } from "../do/index.js"; import { Expression, Module, Program } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Inputs, Type } from "../main.js"; @@ -210,11 +211,11 @@ describe("input_requirements", () => { Expression.literal(true), ); const required = Expression.input("enabled", boolean); - const both = optional.$.and(required); + const both = Operators.and(optional, required); expectTypeOf>().toEqualTypeOf<{ readonly enabled: Type.PrimitiveBoolean; }>(); - const defaults = optional.$.or(optional); + const defaults = Operators.or(optional, optional); expectTypeOf>().toEqualTypeOf<{ readonly enabled?: Type.PrimitiveBoolean; }>(); @@ -239,9 +240,10 @@ describe("operation_requirements", () => { const left = Expression.input("left", integer); const right = Expression.input("right", integer); const enabled = Expression.input("enabled", boolean); - const predicate = left.$.eq(right) - .$.and(enabled.$.isTrue()) - .$.or(enabled.$.isFalse()); + const predicate = Operators.or( + Operators.and(Operators.eq(left, right), Operators.isTrue(enabled)), + Operators.isFalse(enabled), + ); expectTypeOf>().toEqualTypeOf<{ readonly left: Type.PrimitiveInteger; readonly right: Type.PrimitiveInteger; @@ -303,10 +305,10 @@ describe("operation_requirements", () => { describe("snippet_requirements", () => { test("reusable_snippet", () => { const count = Expression.input("count", integer); - const snippet = count.$.ne(Expression.integer(0)); + const snippet = Operators.ne(count, Expression.integer(0)); const first = Result.getOrThrow(EmptyDo(() => snippet)); const second = Result.getOrThrow( - EmptyDo(($) => snippet.$.and($.input("enabled", boolean))), + EmptyDo(($) => Operators.and(snippet, $.input("enabled", boolean))), ); const program = Program.program(second); expectTypeOf>().toEqualTypeOf<{ @@ -380,7 +382,7 @@ describe("builder_requirements", () => { $.query .entities($.input("at", integer)) .filter("vertex", (vertex) => - vertex.enabled.$.eq($.input("enabled", boolean)), + Operators.eq(vertex.enabled, $.input("enabled", boolean)), ) .collect(), ), diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts index af765714440..b6dd4edae97 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "vitest"; import { Do as EmptyDo, Let } from "../do/index.js"; import { Expression, JExpr, Module } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Type } from "../main.js"; @@ -21,7 +22,7 @@ describe("input_composition", () => { const snippet = Expression.input("count", integer, Expression.integer(7)); const first = Result.getOrThrow(EmptyDo(() => snippet)); const second = Result.getOrThrow( - EmptyDo(($) => snippet.$.eq($.input("other", integer))), + EmptyDo(($) => Operators.eq(snippet, $.input("other", integer))), ); expect(compile(first)).toBe( '["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}]', diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts index 22fc8d2d5d7..06ec63b20c4 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts @@ -105,7 +105,7 @@ describe("namespace", () => { expect("then" in joined).toBe(true); expect(Namespace.modules(source).Both.then).toBe(child.values.then); expect(joined.values.$).toBe(child.values.$); - expect(Expression.isExpression(joined.$)).toBe(false); + expect(joined.$).toBe(child.values.$); }); test("function_intrinsics", () => { diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts index c5fd75cf714..a5f71235548 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts @@ -1,11 +1,11 @@ /** * Shared names with separate module, type and value capabilities. * - * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Expression operations remain available through `$`, `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. + * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Explicit projection and indexing remain available through `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. * * @module */ -import { Function, Predicate, Result, pipe } from "effect"; +import { Function, Result, pipe } from "effect"; import { Relocate } from "../internal/relocation.js"; import * as Expression from "./Expression.js"; @@ -60,7 +60,7 @@ type Metadata = Omit< > & Present; -type ExpressionReserved = "$" | "$project" | "$index" | "~hashql/Expression"; +type ExpressionReserved = "$project" | "$index" | "~hashql/Expression"; /** Removes shadowed projections without discarding generic call signatures. */ type WithMetadata = V extends Expression.Any @@ -74,10 +74,6 @@ type WithMetadata = V extends Expression.Any Omit< Accessors, Expression.Inputs>, Exclude - > & - Pick< - Expression.Expression, Expression.Inputs>, - "$" >) : M & V; @@ -142,9 +138,12 @@ export type Flatten = { >; }; -export type Modules = { - readonly [K in keyof S["modules"]]: Viewed; -}; +interface ModuleScope { + readonly modules: S["modules"]; + readonly types: Empty; + readonly values: Empty; +} +export type Modules = Flatten>; const combinedHandles = new WeakMap< Capability, @@ -182,7 +181,6 @@ const hasExport = (candidate: Capability, key: PropertyKey): boolean => { }; const expressionReserved = new Set([ - "$", "$project", "$index", "~hashql/Expression", @@ -486,24 +484,9 @@ export const flatten = ( /** Keeps only module names, with their child exports available directly. */ export const modules = ( scope: S & Pick, "modules">, -): Modules => { - const entries: Partial> = {}; - const sources: S["modules"] = scope.modules; - - // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- K ties the module producer to its destination view - const resolve = (name: K): void => { - const view = viewOptional(sources[name]); - - if (Predicate.isNotUndefined(view)) { - define, K>(entries, name, view); - } - }; - - for (const name of Object.getOwnPropertyNames(scope.modules)) { - resolve(name); - } - - // SAFETY: the loop checks each own module name at Modules[K]. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- completes the per-key module table - return Object.freeze(entries) as Modules; -}; +): Modules => + flattenScope>({ + modules: scope.modules, + types: {}, + values: {}, + }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts new file mode 100644 index 00000000000..1c56fe98aae --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts @@ -0,0 +1,47 @@ +/** Operator domains and input inference in both argument orders. @module */ +import { pipe } from "effect"; +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression, Operators, Prelude } from "../main.js"; + +import type { Inputs, Type } from "../main.js"; + +describe("operator_types", () => { + test("operator_domains", () => { + const count = Expression.input("count", Prelude.builtin.types.Integer); + const other = Expression.input("other", Prelude.builtin.types.Integer, 0n); + const first = Operators.eq(count, other); + const last = pipe(count, Operators.eq(other)); + expectTypeOf(first).toEqualTypeOf< + Operators.Predicate<{ + readonly count: Type.PrimitiveInteger; + readonly other?: Type.PrimitiveInteger; + }> + >(); + expectTypeOf(last).toEqualTypeOf(first); + expectTypeOf(count).not.toHaveProperty("$"); + expectTypeOf(Expression.literal(true)).not.toHaveProperty("and"); + // @ts-expect-error Integer and Number remain distinct in the data-last form. + pipe(count, Operators.eq(1)); + // @ts-expect-error Negation does not coerce numeric truthiness. + Operators.not(count); + // @ts-expect-error A conjunction requires a Boolean left operand. + pipe(count, Operators.and(true)); + // @ts-expect-error Only an option union admits None checking. + Operators.isNone(count); + const left = Symbol("Left"); + const right = Symbol("Right"); + const firstNominal = Expression.fromJExpr< + Type.Opaque, + Inputs.Empty + >("a"); + const secondNominal = Expression.fromJExpr< + Type.Opaque, + Inputs.Empty + >("b"); + // @ts-expect-error A pipe cannot equate distinct nominal identities. + pipe(firstNominal, Operators.eq(secondNominal)); + // @ts-expect-error A fluent predicate still requires Boolean operands. + first.and(count); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts new file mode 100644 index 00000000000..13e38af8859 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts @@ -0,0 +1,117 @@ +/** Explicit operator composition and relocation. @module */ +// oxlint-disable unicorn/no-array-method-this-argument -- Result.flatMap is not an array method +import { Result, pipe } from "effect"; +import { describe, expect, expectTypeOf, test } from "vitest"; + +import * as Draft from "../draft/index.js"; +import { Relocate } from "../internal/relocation.js"; +import { Expression, JExpr, Operators, Prelude } from "../main.js"; + +import type { Type } from "../main.js"; + +const syntax = (expression: Expression.Any): JExpr.Expression => + Result.getOrThrow(Expression.toJExpr(expression)); + +describe("operators", () => { + test("composition_forms", () => { + expect.hasAssertions(); + const count = Expression.input("count", Prelude.builtin.types.Integer); + const enabled = Expression.input( + "enabled", + Prelude.builtin.types.Boolean, + true, + ); + const chained = Operators.eq(count, 1n).and(enabled).or(false).not(); + const piped = pipe( + count, + Operators.eq(1n), + Operators.and(enabled), + Operators.or(false), + Operators.not, + ); + const nested = Operators.not( + Operators.or(Operators.and(Operators.eq(count, 1n), enabled), false), + ); + expect(syntax(chained)).toStrictEqual(syntax(piped)); + expect(syntax(nested)).toStrictEqual(syntax(chained)); + expect(syntax(chained)).toStrictEqual([ + "::core::bool::not", + [ + "::core::bool::or", + [ + "::core::bool::and", + [ + "::core::cmp::eq", + [ + "::kernel::special_form::input", + "count", + "::kernel::type::Integer", + ], + JExpr.literal(1n), + ], + [ + "::kernel::special_form::input", + "enabled", + "::kernel::type::Boolean", + { "#literal": true }, + ], + ], + { "#literal": false }, + ], + ]); + expectTypeOf(chained).toEqualTypeOf< + Operators.Predicate<{ + readonly count: Type.PrimitiveInteger; + readonly enabled?: Type.PrimitiveBoolean; + }> + >(); + expectTypeOf(piped).toEqualTypeOf(chained); + expect(Expression.isExpression(chained)).toBe(true); + }); + + test("context_binding", () => { + expect.hasAssertions(); + const result = Draft.program({}, ($) => { + const composed = $.eq(1n, 1n).and($.not(false)); + const bound = $.let("selected", composed); + expectTypeOf(bound).not.toHaveProperty("and"); + return pipe(bound, $.or(false)); + }); + expect( + Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), + ).toStrictEqual([ + "::kernel::special_form::let", + "selected", + [ + "::core::bool::and", + ["::core::cmp::eq", JExpr.literal(1n), JExpr.literal(1n)], + ["::core::bool::not", { "#literal": false }], + ], + ["::core::bool::or", "selected", { "#literal": false }], + ]); + }); + + test("relocated_chain", () => { + expect.hasAssertions(); + const original = Operators.eq(1n, 2n); + const first = Result.getOrThrow( + original[Relocate](Result.getOrThrow(JExpr.Path.decodeResult("first"))), + ); + const second = Result.getOrThrow( + first[Relocate](Result.getOrThrow(JExpr.Path.decodeResult("second"))), + ); + expect(syntax(second.and(false))).toStrictEqual([ + "::core::bool::and", + "second", + { "#literal": false }, + ]); + expect(syntax(second.not())).toStrictEqual(["::core::bool::not", "second"]); + expect(Expression.isExpression(second)).toBe(true); + }); + + test("construction_failure", () => { + expect.hasAssertions(); + const failure = Operators.eq(Number.POSITIVE_INFINITY, 1).and(true).not(); + expect(Result.isFailure(Expression.toNode(failure))).toBe(true); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.ts b/libs/@local/hashql/sdk/typescript/src/program/Operators.ts new file mode 100644 index 00000000000..6f046f9bde8 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/program/Operators.ts @@ -0,0 +1,195 @@ +/** + * Explicit predicate construction with fluent and data-last composition. + * + * Ordinary expressions have no operator methods. These constructors return Boolean expressions with chaining methods. Binding one through let produces an ordinary expression again. Both composition forms emit HashQL calls, not host predicates, and preserve every operand's input requirements. + * + * @module + */ +import { Array, Function, Result, pipe } from "effect"; + +import { Relocate } from "../internal/relocation.js"; +import * as JExpr from "../jexpr/index.js"; +import * as AST from "./ast/index.js"; +import * as Expression from "./Expression.js"; + +import type * as Type from "../type/index.js"; +import type { Normalize } from "./ExpressionType.js"; +import type * as Inputs from "./Inputs.js"; +import type * as ProgramError from "./ProgramError.js"; + +type BooleanValue = Expression.Value; +type Requirements = Inputs.Merge< + Expression.Inputs, + Expression.Inputs +>; + +export interface Predicate extends Expression.Expression< + Type.PrimitiveBoolean, + I +> { + readonly and: ( + other: R, + ) => Predicate>>; + readonly or: ( + other: R, + ) => Predicate>>; + readonly not: () => Predicate; + readonly [Relocate]: ( + path: JExpr.Path.Path, + ) => Result.Result, ProgramError.Construction>; +} + +const call = ( + path: string, + operands: readonly Expression.AnyValue[], +): Predicate => + // oxlint-disable-next-line eslint/no-use-before-define -- syntax construction and predicate decoration are mutually recursive + predicate( + pipe( + operands, + Array.map(Expression.toJExpr), + Result.all, + Result.map((arguments_) => new AST.Expr(JExpr.call(path, ...arguments_))), + ), + ); + +/** Copies metadata from a freshly constructed handle, whose marker properties are own and enumerable. */ +const predicate = ( + node: Result.Result, +): Predicate => { + const expression = Expression.fromResult(node); + return { + ...expression, + and: ( + other: R, + ): Predicate>> => + call("::core::bool::and", [expression, other]), + or: ( + other: R, + ): Predicate>> => + call("::core::bool::or", [expression, other]), + not: (): Predicate => call("::core::bool::not", [expression]), + [Relocate]: (path) => + pipe( + expression[Relocate](path), + Result.map((moved) => predicate(Expression.toNode(moved))), + ), + }; +}; + +interface Comparison { + ( + right: R, + ): >>>( + left: L, + ) => Predicate>; + < + const L extends Expression.AnyValue, + const R extends Expression.Value>>, + >( + left: L, + right: R, + ): Predicate>; +} + +const comparison = (path: string): Comparison => + Function.dual( + 2, + < + const L extends Expression.AnyValue, + const R extends Expression.Value>>, + >( + left: L, + right: R, + ): Predicate> => call(path, [left, right]), + ); + +/** Compares operands with the same semantic descriptor. */ +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests +export const eq: Comparison = comparison("::core::cmp::eq"); +// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests +export const ne: Comparison = comparison("::core::cmp::ne"); + +interface BooleanCombination { + ( + right: R, + ): (left: L) => Predicate>; + ( + left: L, + right: R, + ): Predicate>; +} + +const combination = (path: string): BooleanCombination => + Function.dual( + 2, + ( + left: L, + right: R, + ): Predicate> => call(path, [left, right]), + ); + +export const and: BooleanCombination = combination("::core::bool::and"); +export const or: BooleanCombination = combination("::core::bool::or"); +export const not = ( + expression: E, +): Predicate> => call("::core::bool::not", [expression]); +export const isTrue = ( + expression: E, +): Predicate> => + call("::core::cmp::eq", [expression, true]); +export const isFalse = ( + expression: E, +): Predicate> => + call("::core::cmp::eq", [expression, false]); + +type Optional = + Normalize> extends Type.Union + ? Extract< + M[number], + Type.Opaque<"::core::option::None", Type.Any> + > extends never + ? never + : E + : never; + +export const isNone = ( + expression: E & Optional, +): Predicate> => + pipe( + Expression.toJExpr(expression), + Result.map( + (value) => + new AST.Expr( + JExpr.call( + "::core::cmp::eq", + value, + JExpr.call("::core::option::None"), + ), + ), + ), + predicate>, + ); + +/** The same constructors are available on authoring contexts and as standalone functions. */ +export interface Operations { + readonly eq: typeof eq; + readonly ne: typeof ne; + readonly and: typeof and; + readonly or: typeof or; + readonly not: typeof not; + readonly isTrue: typeof isTrue; + readonly isFalse: typeof isFalse; + readonly isNone: typeof isNone; +} + +export const operations: Operations = { + eq, + ne, + and, + or, + not, + isTrue, + isFalse, + isNone, +}; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts index 2b4a977707c..c39d4b69c39 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts @@ -3,6 +3,7 @@ import { describe, expectTypeOf, test } from "vitest"; import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression, Module } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Inputs, Type } from "../main.js"; @@ -53,28 +54,28 @@ describe("primitive_types", () => { test("exact_operands", () => { const integer = Expression.literal(1n); const number = Expression.literal(1); - expectTypeOf(integer.$.eq(2n)).toEqualTypeOf< - Expression.Expression + expectTypeOf(Operators.eq(integer, 2n)).toEqualTypeOf< + Operators.Predicate >(); - number.$.eq(2); + Operators.eq(number, 2); // @ts-expect-error A host number does not become Integer through its value. - integer.$.eq(2); + Operators.eq(integer, 2); // @ts-expect-error Integer does not implicitly widen to Number. - number.$.eq(2n); + Operators.eq(number, 2n); // @ts-expect-error Expression handles do not implicitly widen either. - number.$.eq(integer); - number.$.eq(Expression.assume()(integer)); + Operators.eq(number, integer); + Operators.eq(number, Expression.assume()(integer)); expectTypeOf(Expression.assume()(1n)).toEqualTypeOf< Expression.Expression >(); // @ts-expect-error Boolean operations reject numeric truthiness. - Expression.literal(true).$.and(1); + Operators.and(Expression.literal(true), 1); const id = Expression.fromJExpr< Type.Opaque<"Id", Type.PrimitiveString>, Inputs.Empty >("id"); // @ts-expect-error Strings do not stand in for nominal values. - id.$.eq("id"); + Operators.eq(id, "id"); }); }); @@ -140,7 +141,10 @@ describe("primitive_requirements", () => { test("defaults_and_operations", () => { const count = Expression.input("count", kernel.types.Integer, 1n); const enabled = Expression.input("enabled", kernel.types.Boolean); - const result = count.$.eq(2n).$.and(enabled).$.or(false); + const result = Operators.or( + Operators.and(Operators.eq(count, 2n), enabled), + false, + ); expectTypeOf>().toEqualTypeOf<{ readonly count?: Type.PrimitiveInteger; readonly enabled: Type.PrimitiveBoolean; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts index 211735629b2..2e32951b035 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "vitest"; import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression, JExpr, Module } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Inputs, Type } from "../main.js"; @@ -54,7 +55,7 @@ describe("primitive_lowering", () => { test("default_and_boolean_operand", () => { expect.hasAssertions(); const number = Expression.input("number", kernel.types.Number, 1); - expect(compile(number.$.eq(2).$.and(true))).toBe( + expect(compile(Operators.and(Operators.eq(number, 2), true))).toBe( '["::core::bool::and",["::core::cmp::eq",["::kernel::special_form::input","number","::kernel::type::Number",{"#literal":1}],{"#literal":2}],{"#literal":true}]', ); }); @@ -66,7 +67,7 @@ describe("primitive_failures", () => { const number = Expression.input("number", kernel.types.Number); for (const expression of [ Expression.literal(value), - number.$.eq(value), + Operators.eq(number, value), Expression.input("default", kernel.types.Number, value), ]) { const failure = Result.getOrThrow( diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.test-d.ts similarity index 81% rename from libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/program/Query.test-d.ts index a0caabd1fb2..e63eb6c5bc6 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.test-d.ts @@ -2,6 +2,7 @@ import { describe, expectTypeOf, test } from "vitest"; import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Type } from "../main.js"; import type * as Inputs from "./Inputs.js"; @@ -14,7 +15,7 @@ type Graph = Type.Opaque< Type.Struct<{ readonly "'marker": Vertex }> >; -describe("fluent_types", () => { +describe("query_types", () => { test("graph_vertex", () => { const { Do } = withPrelude({ values: { @@ -31,7 +32,7 @@ describe("fluent_types", () => { expectTypeOf(item).toEqualTypeOf< Expression.Expression >(); - return item.enabled.$.isFalse(); + return Operators.isFalse(item.enabled); }) .collect(), ); @@ -56,15 +57,13 @@ describe("fluent_types", () => { expectTypeOf(integer).toEqualTypeOf< Expression.Expression >(); - // @ts-expect-error Boolean operations do not belong to an integer. - expectTypeOf(integer.$.and); - // @ts-expect-error Graph operations do not belong to an integer. - expectTypeOf(integer.$.collect); + expectTypeOf(integer).not.toHaveProperty("$"); + expectTypeOf(integer).not.toHaveProperty("collect"); // @ts-expect-error An integer is not optional. - expectTypeOf(integer.$.isNone); + Operators.isNone(integer); // @ts-expect-error A Boolean conjunction needs a Boolean operand. - $.literal(true).$.and(integer); - return integer.$.eq($.integer(2)); + Operators.and($.literal(true), integer); + return Operators.eq(integer, $.integer(2)); }); }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.test.ts similarity index 89% rename from libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts rename to libs/@local/hashql/sdk/typescript/src/program/Query.test.ts index 823e352ec9b..c7d900c3807 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Fluent.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.test.ts @@ -1,11 +1,10 @@ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results -// oxlint-disable vitest/prefer-to-be-falsy -- these checks assert exact Boolean results import { Result } from "effect"; import { describe, expect, test } from "vitest"; import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression } from "../main.js"; +import * as Operators from "./Operators.js"; import type { Inputs, Type } from "../main.js"; @@ -23,7 +22,7 @@ const { Do } = withPrelude({ }, }); -describe("fluent", () => { +describe("query", () => { test("named_filter", () => { expect.hasAssertions(); let calls = 0; @@ -32,7 +31,7 @@ describe("fluent", () => { .entities() .filter("item", (item) => { calls += 1; - return item.enabled.$.isFalse(); + return Operators.isFalse(item.enabled); }) .collect(), ); @@ -94,7 +93,7 @@ describe("fluent", () => { Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, Inputs.Empty >("record"); - const result = EmptyDo(() => record.$project("$").$.isTrue()); + const result = EmptyDo(() => Operators.isTrue(record.$project("$"))); expect( Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), ).toStrictEqual([ From 14af22e4835ee6fef5e76c25b2bd9beef08dddfd Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:21:59 +0200 Subject: [PATCH 09/22] feat: wrap Draft callback exceptions in results --- libs/@local/hashql/sdk/typescript/README.md | 6 +- .../hashql/sdk/typescript/docs/authoring.md | 8 +-- .../sdk/typescript/examples/filters-draft.ts | 4 +- .../hashql/sdk/typescript/src/draft/Body.ts | 4 +- .../sdk/typescript/src/draft/Context.ts | 2 +- .../sdk/typescript/src/draft/Draft.test-d.ts | 4 +- .../sdk/typescript/src/draft/Draft.test.ts | 17 ++--- .../typescript/src/draft/Exception.test.ts | 62 +++++++++++++++++++ .../sdk/typescript/src/draft/Import.test.ts | 18 +++--- .../src/draft/Requirements.test-d.ts | 6 +- .../hashql/sdk/typescript/src/draft/Scribe.ts | 14 +++-- .../typescript/src/program/ProgramError.ts | 8 ++- 12 files changed, 112 insertions(+), 41 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 33de4435c0e..0f720185e13 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -19,7 +19,7 @@ const identity = Symbol("Count"); const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { const Count = $.newtype("Count", identity, BigInt); const value = $.let("value", Count(inputs.count)); - return $.ifElse( + return $.if( true, () => value, () => Count(0n), @@ -32,11 +32,11 @@ const compiled = Result.flatMap(built, (expression) => `$.type(name, definition)` accepts type expressions or structural shorthand. `$.newtype(name, uniqueSymbol, definition)` returns a type and callable nominal constructor together; for example, `const identity = Symbol("Foo"); const Foo = $.newtype("Foo", identity, { foo: BigInt }); Foo({ foo: 2n })`. Records describe structs, arrays describe tuples, and `List(BigInt)` and `Dict(String, BigInt)` describe collections. `number` remains Number, while `bigint` is Integer. -`$.ifElse(condition, thenCallback, elseCallback)` supplies each branch its own context. The direct `{ then, else }` form accepts already-built values. Both callbacks construct syntax. HashQL chooses the runtime branch. Use the predicate context for declarations inside a filter. Capturing an outer context can place a declaration outside the vertex's scope. HashQL performs lexical resolution and rejects free references. +`$.if(condition, thenCallback, elseCallback)` supplies each branch its own context. The direct `{ then, else }` form accepts already-built values. Both callbacks construct syntax. HashQL chooses the runtime branch. Use the predicate context for declarations inside a filter. Capturing an outer context can place a declaration outside the vertex's scope. HashQL performs lexical resolution and rejects free references. Draft's default prelude contains primitive types, List/Dict, Uuid, EntityUuid, `eq` and `add`. It demonstrates declaration-table composition rather than mirroring the complete standard library. Draft's `withPrelude(definition)` returns `{ program }` and replaces these defaults. A custom `entities` declaration supplies the query entry point. The default has none. Do's default remains empty. See the [Draft reference](docs/authoring.md#draft-executed-authoring) for coverage and source definitions. -Construction failures are Results. Synchronous user exceptions propagate unchanged. TypeScript rejects async callbacks. Draft continues executing a synchronous callback after a declaration fails and reports the accumulated failure at its end. +Draft returns construction failures as Results. Synchronous callback exceptions become `ProgramError.Construction` with a `CallbackException` reason. Its `Cause.UnknownError` retains the thrown value as its cause. TypeScript rejects async callbacks. Failed declarations remain in the collector, while an invalid import stops its callback because it cannot supply the promised handles. ## Do authoring diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md index 50fda4be29e..116f67e6126 100644 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -110,7 +110,7 @@ const identity = Symbol("Foo"); const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { const Foo = $.newtype("Foo", identity, { foo: BigInt }); const value = $.let("value", Foo({ foo: inputs.count })); - return $.ifElse( + return $.if( true, (branch) => branch.let("selected", value), () => value, @@ -170,7 +170,7 @@ Every schema entry remains required in the result, including inputs whose uses a ### Branches, queries and failures -Use `$.ifElse(condition, thenCallback, elseCallback)` for child declaration contexts. Both callbacks run during construction. The direct `$.ifElse(condition, { then, else })` form accepts already-built values and does not create a declaration scope around their earlier construction. +Use `$.if(condition, thenCallback, elseCallback)` for child declaration contexts. Both callbacks run during construction. The direct `$.if(condition, { then, else })` form accepts already-built values and does not create a declaration scope around their earlier construction. A custom prelude supplies `$.query.entities` when its `entities` value returns a `::graph::Graph` opaque type with a vertex marker. Its signature determines the query arguments and vertex descriptor. The filter callback receives a predicate context first. This illustrative declaration uses an example module, not the graph service's schema: @@ -207,7 +207,7 @@ const selected = program({ axis: Structural.type(BigInt) }, ($, inputs) => Declarations made through `predicate` stay inside the emitted filter closure. Capturing `$` from the outer callback instead still addresses the outer context. Likewise, JavaScript can save a branch-local reference and return it elsewhere. Draft does not reject those host-reference escapes: the HashQL compiler owns lexical resolution. Keep declarations on the context of the branch or predicate that uses them. Nested and reentrant programs have independent declaration state. -Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Those failures remain on the constructed handles, so the callback can continue. An invalid import cannot supply its promised handles and stops the current callback instead. Its failure still returns through the construction Result, even if host code catches the internal interruption. A user-thrown synchronous exception propagates unchanged. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. +Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Those failures remain on the constructed handles, so the callback can continue. An invalid import cannot supply its promised handles and stops the current callback instead. Its failure still returns through the construction Result, even if host code catches the internal interruption. A synchronous callback exception returns a construction failure with a `CallbackException` reason. Its `Cause.UnknownError` retains the original thrown value as its cause. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. ### Default prelude coverage and authority @@ -860,7 +860,7 @@ Follow these rules when you write HashQL with the SDK, whether by hand or as a c 3. Refer to declarations through handles from callback environments, `Import` and `$.ref`. A string is always a literal. 4. Return an expression handle from every `Do`, `Let` and `Expr` callback. Lift host values with `$.literal`, `$.integer` or `$.number`. 5. Declare one name per `Let`, `Type` or `Newtype` step. Records that list declarations belong in `Module.define`. -6. Handle every `Result`. Yield inside `Result.gen` in application code. Callback exceptions propagate unchanged rather than becoming construction Results. +6. Handle every `Result`. Yield inside `Result.gen` in application code. Draft wraps callback exceptions as construction failures. Do callback exceptions propagate unchanged. 7. Preserve input requirements. Let TypeScript infer handle types, use `assume` rather than raw syntax round trips, and state every input when you wrap raw syntax with `Expression.fromJExpr`. 8. Don't treat TypeScript annotations or `assume` as compiler validation. A program that type-checks still needs the HashQL compiler. 9. Keep references in their HashQL lexical scope. Take each handle from the callback arguments of the block that uses it, and don't store local bindings in outer variables. diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts index 23a9be03671..3c2aaade1ee 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -1,7 +1,7 @@ /** * The filter gallery written with synchronous Draft callbacks. * - * These programs correspond, in order, to filters.ts. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.ifElse emits a query-time branch. + * These programs correspond, in order, to filters.ts. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.if emits a query-time branch. * * The shared declarations cover only the graph exports used here. Construction emits J-Expr without executing against a graph service. * @@ -157,7 +157,7 @@ const optionalDrafts = program( return $.query .entities(now()) .filter("vertex", ($, vertex) => - $.ifElse( + $.if( includeDrafts, () => true, () => $.isNone(vertex.metadata.record_id.entity_id.draft_id), diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts index 5e8d90739ff..fa50e6236fb 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts @@ -93,14 +93,14 @@ type QueryContext = [EntityFunction] extends [ /** A restricted view that the unrestricted constructor implements. */ export interface Context extends Omit< Construction.Context, - "let" | "ifElse" | "query" + "let" | "if" | "query" > { readonly let: ( name: string, value: E & Accept, ) => Expression.Expression, Expression.Inputs>; readonly query: QueryContext; - readonly ifElse: { + readonly if: { < const C extends Expression.Value, const T extends Expression.AnyValue, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts index cfe261701df..eb6c097b8c4 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -134,7 +134,7 @@ export interface Context extends Operators.Operations { identity: symbol extends N ? never : N, definition: D, ) => Nominal>; - readonly ifElse: < + readonly if: < const C extends Expression.Value, const T extends Expression.AnyValue, const E extends Expression.AnyValue, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts index ab59fc6ad8a..73a3f06a20d 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test-d.ts @@ -59,14 +59,14 @@ describe("draft_types", () => { $.let("lost", outside); // @ts-expect-error the schema must include optional external inputs $.let("optional", optional); - $.ifElse( + $.if( true, // @ts-expect-error child final expression contains an undeclared input () => outside, () => 1n, ); // @ts-expect-error direct branch contains an undeclared input - $.ifElse(true, { then: outside, else: 1n }); + $.if(true, { then: outside, else: 1n }); return $.literal(true); }); Draft.program({ outside: integer }, ($) => $.let("allowed", outside)); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts index 7a96e991384..b871a1f808f 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts @@ -89,7 +89,7 @@ describe("draft", () => { expect.hasAssertions(); const visits: string[] = []; const result = Draft.program({}, ($) => - $.ifElse( + $.if( false, (branch) => { visits.push("then"); @@ -112,7 +112,7 @@ describe("draft", () => { ); expect( // oxlint-disable-next-line unicorn/no-thenable -- then is the HashQL conditional-branch key - compile(Draft.program({}, ($) => $.ifElse(true, { then: 1n, else: 2n }))), + compile(Draft.program({}, ($) => $.if(true, { then: 1n, else: 2n }))), ).toStrictEqual( call("::kernel::special_form::if", literal(true), literal(1), literal(2)), ); @@ -126,10 +126,10 @@ describe("draft", () => { expect(compile(inner)).toStrictEqual( call("::kernel::special_form::let", "inner", literal(2), "inner"), ); - return $.ifElse( + return $.if( true, (branch) => - branch.ifElse( + branch.if( false, (child) => child.let("deep", outer), () => outer, @@ -399,7 +399,7 @@ describe("draft", () => { return $.literal(true); }), Draft.program({}, ($) => - $.ifElse( + $.if( true, () => 1n, (branch) => { @@ -411,12 +411,7 @@ describe("draft", () => { ]) { expect(result._tag).toBe("Failure"); } - const thrown = new Error("user exception"); - expect(() => - Draft.program({}, () => { - throw thrown; - }), - ).toThrow(thrown); + // @ts-expect-error exercise an unchecked JavaScript caller const asynchronous = Draft.program({}, asynchronousBody); expect(Result.isFailure(asynchronous)).toBe(true); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts new file mode 100644 index 00000000000..90c7df679d0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Exception.test.ts @@ -0,0 +1,62 @@ +import { Cause, Result, pipe } from "effect"; +import { assert, describe, expect, test } from "vitest"; + +import * as Fixtures from "./fixtures.js"; +import * as Draft from "./index.js"; + +describe("draft_exceptions", () => { + test.each([new Error("user exception"), "non-error", undefined])( + "host_exception_%#", + (thrown) => { + expect.hasAssertions(); + const result = Draft.program({}, () => { + // oxlint-disable-next-line typescript/only-throw-error -- unchecked JavaScript callbacks can throw arbitrary values + throw thrown; + }); + const failure = pipe(result, Result.flip, Result.getOrThrow); + assert(failure.reason._tag === "CallbackException"); + expect(failure.reason.cause).toBeInstanceOf(Cause.UnknownError); + expect(failure.reason.cause.cause).toBe(thrown); + expect(failure.message).toBe("A program callback threw an exception"); + }, + ); + + test("branch_exception", () => { + expect.hasAssertions(); + const thrown = new Error("branch callback"); + const fail = (): bigint => { + throw thrown; + }; + const results = [ + Draft.program({}, ($) => $.if(false, fail, () => 1n)), + Draft.program({}, ($) => $.if(true, () => 1n, fail)), + ]; + for (const result of results) { + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + } + }); + + test("predicate_exception", () => { + expect.hasAssertions(); + const thrown = new Error("predicate callback"); + const result = Fixtures.program({ axis: Fixtures.axis }, ($, inputs) => + $.query + .entities(inputs.axis) + .filter("vertex", (): boolean => { + throw thrown; + }) + .collect(), + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts index 9f753045c2d..d40a0d40192 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts @@ -81,7 +81,7 @@ describe("draft_import", () => { test("branch_scope", () => { expect.hasAssertions(); const result = Draft.program({}, ($) => - $.ifElse( + $.if( true, ($) => { const { Whole } = $.import(declarations, { Whole: "_" }); @@ -227,11 +227,15 @@ describe("draft_import", () => { test("host_exception", () => { expect.hasAssertions(); const error = new Error("host callback"); - expect(() => - Draft.program({}, ($) => { - $.import(declarations); - throw error; - }), - ).toThrow(error); + const result = Draft.program({}, ($) => { + $.import(declarations); + throw error; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: error } }, + }, + }); }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts index 3162b8e1baf..a25ea1841e2 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts @@ -177,8 +177,8 @@ describe("draft_requirements", () => { // @ts-expect-error nominal initializers retain erased requirements $.let("nominal", nominal); // @ts-expect-error direct branches cannot accept erased values - $.ifElse(true, { then: erasedValue, else: 1n }); - $.ifElse( + $.if(true, { then: erasedValue, else: 1n }); + $.if( true, // @ts-expect-error callback branches cannot accept erased values () => erasedValue, @@ -206,7 +206,7 @@ describe("draft_requirements", () => { readonly outside: Type.PrimitiveInteger; }>(); const branch = Draft.program(chooseSchema(), ($) => - $.ifElse( + $.if( true, (child) => child.let("outside", outside), () => 1n, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts index 035136d4c0d..bfef1509d75 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts @@ -1,11 +1,11 @@ /** * Collects declarations while a synchronous callback constructs an expression. * - * Handles retain semantic parameters until conversion to syntax. Only the declaration wrappers are heterogeneous: each is already an AST operation, so their collection needs no type recovery. A child collector prevents branch and predicate declarations from escaping their lexical body. Host exceptions propagate unchanged. Expected construction failures remain Results. + * Handles retain semantic parameters until conversion to syntax. Only the declaration wrappers are heterogeneous: each is already an AST operation, so their collection needs no type recovery. A child collector prevents branch and predicate declarations from escaping their lexical body. Callback exceptions retain their original cause inside construction failures. * * @module */ -import { Data, Result, pipe } from "effect"; +import { Cause, Data, Result, pipe } from "effect"; import { Expression, @@ -87,7 +87,7 @@ const nominal = ( >(value, type); }; -/** Stops a callback when an import cannot supply its promised handles. User exceptions pass through. */ +/** Stops a callback when an import cannot supply its promised handles. */ const ConstructionFailure = Data.TaggedError("DraftConstructionFailure")<{ readonly failure: ProgramError.Construction; }>; @@ -244,7 +244,7 @@ class ContextImpl implements Context.Context { return nominal>(binding); }; - ifElse< + if< const C extends Expression.Value, const T extends Expression.AnyValue, const E extends Expression.AnyValue, @@ -439,7 +439,11 @@ class ContextImpl implements Context.Context { return Result.fail(error.failure); } - throw error; + return Result.fail( + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + ); } } } diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts index c6caa15e256..c7886a837b1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts @@ -7,7 +7,7 @@ */ import { Data } from "effect"; -import type { Schema, SchemaIssue } from "effect"; +import type { Cause, Schema, SchemaIssue } from "effect"; interface NameFailure { readonly name: string; @@ -23,6 +23,7 @@ export type Reason = SymbolExportName: { readonly name: symbol }; SymbolInputName: { readonly name: symbol }; InvalidExpression: { readonly cause: Schema.SchemaError }; + CallbackException: { readonly cause: Cause.UnknownError }; InvalidModulePath: NameFailure; RelativeModulePath: { readonly name: string }; InvalidTypeArity: { readonly arity: number }; @@ -102,6 +103,10 @@ export class Construction extends ConstructionBase<{ return new Construction({ reason: Reason.InvalidBodyResult() }); } + static callbackException(cause: Cause.UnknownError): Construction { + return new Construction({ reason: Reason.CallbackException({ cause }) }); + } + override get message(): string { return Reason.$match(this.reason, { InvalidBindingName: ({ name }) => @@ -118,6 +123,7 @@ export class Construction extends ConstructionBase<{ `A HashQL input needs a string name, received ${String(name)}`, InvalidExpression: () => "The expression does not have valid J-Expr structure", + CallbackException: () => "A program callback threw an exception", InvalidModulePath: ({ name }) => `Invalid HashQL module path: ${JSON.stringify(name)}`, RelativeModulePath: ({ name }) => From 2a6097ccfc383737e22d8915ce7cefc69caca50a Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 13:56:03 +0200 Subject: [PATCH 10/22] fix: capture exceptions in HashQL callbacks --- .../hashql/sdk/typescript/src/do/Do.test.ts | 16 -- .../sdk/typescript/src/do/Exception.test.ts | 244 ++++++++++++++++++ .../hashql/sdk/typescript/src/do/Utilities.ts | 81 +++++- .../sdk/typescript/src/program/Query.ts | 13 +- 4 files changed, 321 insertions(+), 33 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts index 4a56e7baf04..d5a1db4212c 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts @@ -437,20 +437,4 @@ describe("expressions", () => { ), ).toBe('{"#literal":7}'); }); - - test("branch_exception", () => { - expect.hasAssertions(); - const failure = new Error("branch construction"); - expect(() => - EmptyDo(($) => - $.if( - $.literal(false), - () => { - throw failure; - }, - () => $.integer(1), - ), - ), - ).toThrow(failure); - }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts new file mode 100644 index 00000000000..e43dd31d96f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts @@ -0,0 +1,244 @@ +import { Cause, Result, pipe } from "effect"; +import { assert, describe, expect, test } from "vitest"; + +import { Expression } from "../main.js"; +import { + Type as DeclareType, + Do, + Import, + Let, + Newtype, + withPrelude, +} from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +const identity: unique symbol = Symbol("Exception"); +type ConstructionResult = Result.Result< + Expression.Any, + ProgramError.Construction +>; +type SuccessBody = () => Expression.Expression< + Type.PrimitiveInteger, + Inputs.Empty +>; +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; +const queryContext = withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function, + Inputs.Empty + >("entities"), + }, +}); + +describe("do_exceptions", () => { + test.each([new Error("user exception"), "non-error", undefined])( + "host_exception_%#", + (thrown) => { + expect.hasAssertions(); + const result = Do(() => { + // oxlint-disable-next-line typescript/only-throw-error -- unchecked JavaScript callbacks can throw arbitrary values + throw thrown; + }); + const failure = pipe(result, Result.flip, Result.getOrThrow); + assert(failure.reason._tag === "CallbackException"); + expect(failure.reason.cause).toBeInstanceOf(Cause.UnknownError); + expect(failure.reason.cause.cause).toBe(thrown); + expect(failure.message).toBe("A program callback threw an exception"); + }, + ); + + test.each([ + { + name: "let", + run: (fail: () => never, later: SuccessBody): ConstructionResult => + Do(Let("value", fail), Let("later", later), later), + }, + { + name: "type", + run: (fail: () => never, later: SuccessBody): ConstructionResult => + Do(DeclareType("Value", fail), Let("later", later), later), + }, + { + name: "newtype", + run: (fail: () => never, later: SuccessBody): ConstructionResult => + Do(Newtype("Value", identity, fail), Let("later", later), later), + }, + { + name: "import", + run: (fail: () => never, later: SuccessBody): ConstructionResult => + Do(Import(fail), Let("later", later), later), + }, + ])("declaration_$name", ({ run }) => { + expect.hasAssertions(); + const thrown = new Error("declaration callback"); + const calls: string[] = []; + const result = run( + () => { + calls.push("declaration"); + throw thrown; + }, + () => { + calls.push("later"); + return Expression.integer(1); + }, + ); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(calls).toStrictEqual(["declaration"]); + }); + + test("nested_declaration", () => { + expect.hasAssertions(); + const thrown = new Error("nested declaration"); + let continued = false; + const result = Do(($) => { + const expression = $.Let("value", () => { + throw thrown; + }).Expr(($) => $.integer(1)); + continued = true; + return expression; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(continued).toBe(true); + }); + + test("nested_body", () => { + expect.hasAssertions(); + const thrown = new Error("nested body"); + let continued = false; + const result = Do(($) => { + const expression = $.Let("value", ($) => $.integer(1)).Expr(() => { + throw thrown; + }); + continued = true; + return expression; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(continued).toBe(true); + }); + + test("consequent_exception", () => { + expect.hasAssertions(); + const thrown = new Error("consequent callback"); + const calls: string[] = []; + const result = Do(($) => { + const expression = $.if( + false, + () => { + calls.push("then"); + throw thrown; + }, + () => { + calls.push("else"); + return 1n; + }, + ); + calls.push("body"); + return expression; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(calls).toStrictEqual(["then", "else", "body"]); + }); + + test("alternate_exception", () => { + expect.hasAssertions(); + const thrown = new Error("alternate callback"); + let continued = false; + const result = Do(($) => { + const expression = $.if( + true, + () => 1n, + () => { + throw thrown; + }, + ); + continued = true; + return expression; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(continued).toBe(true); + }); + + test("branch_failure_priority", () => { + expect.hasAssertions(); + const invalid = Expression.integer(Number.NaN); + const failure = pipe( + invalid, + Expression.toNode, + Result.flip, + Result.getOrThrow, + ); + let alternateCalled = false; + const result = Do(($) => + $.if( + false, + () => invalid, + () => { + alternateCalled = true; + throw new Error("alternate callback"); + }, + ), + ); + expect(pipe(result, Result.flip, Result.getOrThrow)).toBe(failure); + expect(alternateCalled).toBe(true); + }); + + test("predicate_exception", () => { + expect.hasAssertions(); + const thrown = new Error("predicate callback"); + let continued = false; + let laterPredicate = false; + const result = queryContext.Do(($) => { + const expression = $.query + .entities() + .filter("vertex", (): boolean => { + throw thrown; + }) + .filter("later", () => { + laterPredicate = true; + return true; + }) + .collect(); + continued = true; + return expression; + }); + expect(result).toMatchObject({ + _tag: "Failure", + failure: { + reason: { _tag: "CallbackException", cause: { cause: thrown } }, + }, + }); + expect(continued).toBe(true); + expect(laterPredicate).toBe(false); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index 2ed557b6bd1..f7ce002ae7f 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -7,8 +7,9 @@ */ // oxlint-disable import/max-dependencies -- block construction composes the declaration steps and expression helpers // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -import { Result } from "effect"; +import { Cause, Result, identity, pipe } from "effect"; +import { If as AstIf } from "../program/ast/If.js"; import * as Expression from "../program/Expression.js"; import * as Operators from "../program/Operators.js"; import * as ProgramError from "../program/ProgramError.js"; @@ -19,6 +20,7 @@ import { Newtype } from "./Newtype.js"; import * as Node from "./Node.js"; import { Type as DeclareType } from "./Type.js"; +import type { Node as AstNode } from "../program/ast/Node.js"; import type { Rebindable } from "../program/Import.js"; import type * as Input from "../program/Inputs.js"; import type * as Scope from "../program/Scope.js"; @@ -61,10 +63,20 @@ export class Block { return new Block( Result.flatMap(this.#state, ({ scope, parents }) => { const input: Scope.Scope = scope; - return Result.map( - // oxlint-disable-next-line eslint/no-use-before-define -- block steps receive utilities that can create further blocks - step.elaborate(makeUtilities(input), input), - ({ scope, wrap }) => ({ scope, parents: [...parents, wrap] }), + return pipe( + Result.try({ + // oxlint-disable-next-line eslint/no-use-before-define -- block steps receive utilities that can create further blocks + try: () => step.elaborate(makeUtilities(input), input), + catch: (error) => + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + }), + Result.flatMap(identity), + Result.map(({ scope, wrap }) => ({ + scope, + parents: [...parents, wrap], + })), ); }), ); @@ -165,12 +177,25 @@ export class Block { return Expression.fromResult( Result.flatMap(this.#state, ({ scope, parents }) => { // A nested block inherits names, never the wrappers that introduced them outside it. - const expression = body( - // oxlint-disable-next-line eslint/no-use-before-define -- block bodies receive utilities that can create further blocks - makeUtilities(scope), - scope.values, - scope.types, - ); + const evaluated = Result.try({ + try: () => + body( + // oxlint-disable-next-line eslint/no-use-before-define -- block bodies receive utilities that can create further blocks + makeUtilities(scope), + scope.values, + scope.types, + ), + catch: (error) => + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + }); + + if (Result.isFailure(evaluated)) { + return Result.fail(evaluated.failure); + } + + const expression = evaluated.success; if (!Expression.isExpression(expression)) { return Result.fail(ProgramError.Construction.invalidBodyResult()); } @@ -218,6 +243,20 @@ export class Block { } } +const evaluateBranch = ( + body: () => Expression.AnyValue, +): Result.Result => + pipe( + Result.try({ + try: body, + catch: (error) => + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + }), + Result.flatMap(Expression.toNode), + ); + const conditional = < const Condition extends Expression.Value, const Then extends Expression.AnyValue, @@ -233,8 +272,24 @@ const conditional = < Input.Merge, Expression.Inputs> > > => - // oxlint-disable-next-line unicorn/no-thenable -- these are query branches, not a Promise implementation - Expression.ifElse(condition, { then: consequent(), else: alternate() }); + pipe( + { + condition: Expression.toNode(condition), + consequent: evaluateBranch(consequent), + alternate: evaluateBranch(alternate), + }, + Result.all, + Result.map( + (nodes) => new AstIf(nodes.condition, nodes.consequent, nodes.alternate), + ), + Expression.fromResult< + Expression.Conditional, Expression.TypeOf>, + Input.Merge< + Expression.Inputs, + Input.Merge, Expression.Inputs> + > + >, + ); export interface Utilities extends Block, Operators.Operations { diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts index 4cfbba7e8e8..49c00c1188a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -5,7 +5,7 @@ * * @module */ -import { Result, pipe } from "effect"; +import { Cause, Result, pipe } from "effect"; import * as JExpr from "../jexpr/index.js"; import * as AST from "./ast/index.js"; @@ -109,9 +109,14 @@ const chain = ( ); const parameter = JExpr.Ident.compile(ident); - const body = yield* Expression.toJExpr( - predicate(Expression.fromJExpr(parameter)), - ); + const condition = yield* Result.try({ + try: () => predicate(Expression.fromJExpr(parameter)), + catch: (error) => + ProgramError.Construction.callbackException( + new Cause.UnknownError(error), + ), + }); + const body = yield* Expression.toJExpr(condition); return new AST.Expr( JExpr.call( From 24b0970369a19e71f65b404633a8503167b598f4 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:08:49 +0200 Subject: [PATCH 11/22] refactor: improve HashQL schema and filter tests --- .../sdk/typescript/examples/filters.test.ts | 175 +++++++++++++----- .../sdk/typescript/src/do/Import.test.ts | 2 - .../src/internal/schema-arbitrary.test.ts | 23 +++ .../src/internal/schema-arbitrary.ts | 36 ++-- .../hashql/sdk/typescript/src/jexpr/schema.ts | 1 - .../sdk/typescript/src/jexpr/type/schema.ts | 2 - 6 files changed, 176 insertions(+), 63 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts index 9ede1ec9c86..f140c3df6ce 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts @@ -1,6 +1,7 @@ -import { Result } from "effect"; +import { Array, Record, Result, Schema, flow, pipe } from "effect"; import { describe, expect, test } from "vitest"; +import { isReadonlyArray } from "../src/internal/array.js"; import { Expression, JExpr } from "../src/main.js"; import { examples } from "./filters.js"; @@ -10,38 +11,74 @@ const aliases = new Map([ ["::core::bool::or", "||"], ]); +const parseJson = flow( + Schema.decodeResult(Schema.fromJsonString(Schema.Json)), + Result.getOrThrow, +); +const parseImport = flow( + Schema.decodeUnknownResult( + Schema.Tuple([ + Schema.Literal("::kernel::special_form::use"), + Schema.String, + Schema.Union([ + Schema.Struct({ "#tuple": Schema.Array(Schema.String) }), + Schema.Struct({ + "#struct": Schema.Record(Schema.String, Schema.String), + }), + ]), + Schema.Json, + ]), + ), + Result.getOrThrow, +); + +const resolveImport = ( + value: Schema.JsonArray, + imports: ReadonlyMap, +): { + readonly body: Schema.Json; + readonly imports: ReadonlyMap; +} => { + const [, path, selection, body] = parseImport(value); + const imported = new Map(imports); + if ("#tuple" in selection) { + for (const name of selection["#tuple"]) { + imported.set(name, `${path}::${name}`); + } + } else { + for (const [name, alias] of Record.toEntries(selection["#struct"])) { + let binding = alias; + if (alias === "_") { + binding = name; + } + imported.set(binding, `${path}::${name}`); + } + } + return { body, imports: imported }; +}; + // Only spelling differs: qualified exports, explicit projections and the inferred temporal type. -// oxlint-disable-next-line typescript/no-restricted-types -- JSON enters this comparison without a trusted type const normalize = ( - value: unknown, + value: Schema.Json, imports: ReadonlyMap = new Map(), -): unknown => { +): Schema.Json => { if (typeof value === "string") { return imports.get(value) ?? value; } - if (Array.isArray(value)) { + if (isReadonlyArray(value)) { if (value[0] === "::kernel::special_form::use") { - const [, path, selection, body] = value; - const imported = new Map(imports); - if (selection["#tuple"] === undefined) { - for (const [name, alias] of Object.entries(selection["#struct"])) { - if (typeof alias === "string") { - imported.set(alias === "_" ? name : alias, `${path}::${name}`); - } - } - } else { - for (const name of selection["#tuple"]) { - imported.set(name, `${path}::${name}`); - } - } - return normalize(body, imported); + const imported = resolveImport(value, imports); + return normalize(imported.body, imported.imports); } - const nodes = value.map((node) => normalize(node, imports)); + const nodes = pipe( + value, + Array.map((node) => normalize(node, imports)), + ); const [operation, input, field] = nodes; - let callee = operation; - if (typeof operation === "string") { - callee = operation.replace("::kernel::special_form::", ""); + if (typeof operation !== "string") { + return nodes; } + const callee = operation.replace("::kernel::special_form::", ""); if ( callee === "access" && typeof input === "string" && @@ -56,42 +93,94 @@ const normalize = ( ) { return [callee, input, "_"]; } - if (typeof callee === "string" && aliases.has(callee)) { - return [aliases.get(callee), ...nodes.slice(1)]; - } - if (operation === callee) { - return nodes; - } - return [callee, ...nodes.slice(1)]; + return [aliases.get(callee) ?? callee, ...Array.drop(nodes, 1)]; } if (value !== null && typeof value === "object") { if ("#literal" in value) { return value; } - return Object.fromEntries( - Object.entries(value).map(([name, member]) => [ - name, - normalize(member, imports), - ]), + return pipe( + value, + Record.map((member) => normalize(member, imports)), ); } return value; }; -const jexprExamples = examples.filter(({ source }) => - source.endsWith(".jsonc"), +const jexprExamples = pipe( + examples, + Array.filter(({ source }) => source.endsWith(".jsonc")), ); -const frontendExamples = examples.filter( - ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), +const frontendExamples = pipe( + examples, + Array.filter( + ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), + ), ); +describe("query_normalization", () => { + test("import_aliases", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::example", + { "#struct": { left: "binding", right: "_" } }, + ["binding", "right", { "#literal": "binding" }], + ]), + ).toStrictEqual([ + "::example::left", + "::example::right", + { "#literal": "binding" }, + ]); + }); + + test("import_shadowing", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::outer", + { "#tuple": ["value"] }, + [ + "pair", + "value", + [ + "::kernel::special_form::use", + "::inner", + { "#tuple": ["value"] }, + "value", + ], + "value", + ], + ]), + ).toStrictEqual([ + "pair", + "::outer::value", + "::inner::value", + "::outer::value", + ]); + }); + + test("literal_values", () => { + expect.hasAssertions(); + expect(normalize(["==", "field", { "#literal": false }])).not.toStrictEqual( + normalize(["==", "field", { "#literal": true }]), + ); + }); +}); + describe("filter_examples", () => { test.each(examples)("valid_construction: $title", (example) => { expect.hasAssertions(); expect(Result.isSuccess(example.root)).toBe(true); expect(() => JExpr.make( - Result.getOrThrow(Result.flatMap(example.root, Expression.toJExpr)), + pipe( + example.root, + Result.flatMap(Expression.toJExpr), + Result.getOrThrow, + ), ), ).not.toThrow(); }); @@ -99,12 +188,12 @@ describe("filter_examples", () => { test.each(jexprExamples)("original_query: $title", (example) => { expect.hasAssertions(); expect( - normalize(JSON.parse(Result.getOrThrow(example.compile()))), - ).toStrictEqual(normalize(JSON.parse(example.before))); + normalize(parseJson(Result.getOrThrow(example.compile()))), + ).toStrictEqual(normalize(parseJson(example.before))); }); test.each(frontendExamples)("frontend_selection: $title", (example) => { expect.hasAssertions(); - expect(JSON.parse(Result.getOrThrow(example.compile()))).toMatchSnapshot(); + expect(parseJson(Result.getOrThrow(example.compile()))).toMatchSnapshot(); }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts index 221d845dea7..eb89e6b9477 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts @@ -1,6 +1,4 @@ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -// oxlint-disable vitest/prefer-to-be-truthy -- these checks assert exact Boolean results -// oxlint-disable vitest/prefer-to-be-falsy -- these checks assert exact Boolean results // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments import { Result } from "effect"; import { describe, expect, test } from "vitest"; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts new file mode 100644 index 00000000000..5f6be37183d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.test.ts @@ -0,0 +1,23 @@ +import { Result, Schema, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { exactly } from "./schema-arbitrary.js"; + +const generatePattern = (): string => "[a-z]+"; +const cases = [ + { name: "direct_default", schema: exactly("[a-z]+") }, + { name: "direct_hint", schema: exactly("[a-z]+", generatePattern) }, + { name: "pipe_default", schema: pipe("[a-z]+", exactly()) }, + { name: "pipe_hint", schema: pipe("[a-z]+", exactly(generatePattern)) }, +]; + +describe("exact_pattern", () => { + test.each(cases)("$name", ({ schema }) => { + expect.hasAssertions(); + const decode = Schema.decodeResult(schema); + expect(Result.getOrThrow(decode("letters"))).toBe("letters"); + expect(Result.isFailure(decode("1letters"))).toBe(true); + expect(Result.isFailure(decode("letters1"))).toBe(true); + expect(Result.isFailure(decode("letters\n"))).toBe(true); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts index 7987f6b262a..c29bfd80cfb 100644 --- a/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts +++ b/libs/@local/hashql/sdk/typescript/src/internal/schema-arbitrary.ts @@ -6,7 +6,7 @@ * @internal */ import { Schema } from "effect"; -import { memoize } from "effect/Function"; +import { dual, memoize } from "effect/Function"; /** Expands a character pattern into Unicode ranges for arbitrary generation. */ export const characterClass: (pattern: Readonly) => string = memoize( @@ -40,18 +40,24 @@ export const characterClass: (pattern: Readonly) => string = memoize( ); /** Requires the entire value to match a pattern, with separate generation hints. */ -export const exactly = ( - pattern: string, - generatePattern: () => string = () => pattern, -): Schema.String => - Schema.String.check( - // `$` also matches before a final line terminator. The lookahead requires end of input. - Schema.isPattern(new RegExp(`^(?:${pattern})(?![\\s\\S])`, "u"), { - arbitraryConstraint: { - // expansion runs only during arbitrary derivation, using the same Unicode tables as validation - get patterns(): readonly [Schema.Annotations.ToArbitrary.Pattern] { - return [{ source: `^(?:${generatePattern()})$`, flags: "u" }]; +export const exactly: { + (generatePattern?: () => string): (pattern: string) => Schema.String; + (pattern: string, generatePattern?: () => string): Schema.String; +} = dual( + (args) => typeof args[0] === "string", + ( + pattern: string, + generatePattern: () => string = () => pattern, + ): Schema.String => + Schema.String.check( + // `$` also matches before a final line terminator. The lookahead requires end of input. + Schema.isPattern(new RegExp(`^(?:${pattern})(?![\\s\\S])`, "u"), { + arbitraryConstraint: { + // expansion runs only during arbitrary derivation, using the same Unicode tables as validation + get patterns(): readonly [Schema.Annotations.ToArbitrary.Pattern] { + return [{ source: `^(?:${generatePattern()})$`, flags: "u" }]; + }, }, - }, - }), - ); + }), + ), +); diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts index f2b776f4859..c74aedba209 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts @@ -6,7 +6,6 @@ import type { SchemaAST } from "effect"; import type { ReadonlyRecord } from "effect/Record"; /** A deferred reference that permits expressions to contain other expressions. */ -// oxlint-disable-next-line no-redeclare -- redecl of type is required to make sure that the cycle is broken type ExpressionRef = Schema.suspend< Schema.Codec >; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts index 4586d260079..65362a24186 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts @@ -3,7 +3,6 @@ import { Schema } from "effect"; import * as Ident from "../Ident.js"; import * as Path from "../Path.js"; -// oxlint-disable-next-line no-redeclare -- `TypeRefType` is a bit silly type TypeRef = Schema.suspend>; const TypeRef: TypeRef = Schema.suspend( // oxlint-disable-next-line no-use-before-define -- recursive schema @@ -108,7 +107,6 @@ export interface ReferenceEncoded extends Schema.Codec.Encoded< typeof Reference > {} -// oxlint-disable-next-line no-redeclare -- `TypeType` is a bit silly export const Type: Schema.toTaggedUnion< "_tag", readonly [ From d0fd36439e5d96cc8b4bf3eaa6283f739a0c2fdf Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:22:58 +0200 Subject: [PATCH 12/22] docs: expand hashql sdk api documentation --- .../sdk/typescript/examples/filters-draft.ts | 5 + .../@local/hashql/sdk/typescript/src/do/Do.ts | 6 +- .../hashql/sdk/typescript/src/do/Import.ts | 8 +- .../hashql/sdk/typescript/src/do/Let.ts | 7 + .../hashql/sdk/typescript/src/do/Newtype.ts | 39 ++++- .../hashql/sdk/typescript/src/do/Node.ts | 22 ++- .../hashql/sdk/typescript/src/do/Type.ts | 7 + .../hashql/sdk/typescript/src/do/Utilities.ts | 78 ++++++++- .../hashql/sdk/typescript/src/do/index.ts | 79 ++++++++- .../hashql/sdk/typescript/src/draft/Body.ts | 155 ++++++++++++++++- .../sdk/typescript/src/draft/Context.ts | 72 +++++++- .../hashql/sdk/typescript/src/draft/index.ts | 108 +++++++++++- .../hashql/sdk/typescript/src/jexpr/Call.ts | 8 +- .../hashql/sdk/typescript/src/jexpr/Dict.ts | 21 +-- .../hashql/sdk/typescript/src/jexpr/Float.ts | 8 +- .../sdk/typescript/src/jexpr/Function.ts | 23 +-- .../hashql/sdk/typescript/src/jexpr/Ident.ts | 47 ++++- .../sdk/typescript/src/jexpr/Identifier.ts | 10 +- .../sdk/typescript/src/jexpr/Integer.ts | 21 +-- .../typescript/src/jexpr/LabeledArgument.ts | 10 +- .../hashql/sdk/typescript/src/jexpr/List.ts | 6 +- .../sdk/typescript/src/jexpr/Literal.ts | 10 +- .../hashql/sdk/typescript/src/jexpr/Path.ts | 42 ++++- .../hashql/sdk/typescript/src/jexpr/Struct.ts | 10 +- .../hashql/sdk/typescript/src/jexpr/Tuple.ts | 10 +- .../sdk/typescript/src/jexpr/compile.ts | 16 +- .../hashql/sdk/typescript/src/jexpr/index.ts | 125 ++++++++------ .../hashql/sdk/typescript/src/jexpr/schema.ts | 2 +- .../sdk/typescript/src/jexpr/type/Generic.ts | 4 +- .../typescript/src/jexpr/type/Reference.ts | 5 + .../sdk/typescript/src/jexpr/type/index.ts | 42 ++--- .../sdk/typescript/src/jexpr/type/schema.ts | 18 ++ libs/@local/hashql/sdk/typescript/src/main.ts | 9 + .../sdk/typescript/src/program/Expression.ts | 161 ++++++++++++++++-- .../typescript/src/program/ExpressionType.ts | 13 ++ .../sdk/typescript/src/program/Import.ts | 39 +++++ .../sdk/typescript/src/program/Inputs.ts | 49 +++++- .../sdk/typescript/src/program/Module.ts | 146 ++++++++++++++-- .../sdk/typescript/src/program/Namespace.ts | 22 ++- .../sdk/typescript/src/program/Operators.ts | 43 ++++- .../sdk/typescript/src/program/Prelude.ts | 57 ++++++- .../typescript/src/program/PreludeTypes.ts | 16 +- .../typescript/src/program/ProgramError.ts | 54 +++++- .../sdk/typescript/src/program/Query.ts | 43 ++++- .../sdk/typescript/src/program/Scope.ts | 20 +++ .../sdk/typescript/src/program/Structural.ts | 84 ++++++++- .../typescript/src/program/TypeExpression.ts | 73 +++++++- .../sdk/typescript/src/program/ast/Node.ts | 2 + .../sdk/typescript/src/program/index.ts | 27 +++ .../hashql/sdk/typescript/src/type/index.ts | 141 ++++++++++++++- 50 files changed, 1788 insertions(+), 235 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts index 3c2aaade1ee..b8b1c4daec0 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -61,6 +61,7 @@ const suppliedTimeAxis = program( { axis: temporal.types.QueryTemporalAxes }, ($, { axis }) => { const { createEntityUuid, createUuid } = $.prelude(); + return $.query .entities(axis) .filter("vertex", (_, vertex) => @@ -79,6 +80,7 @@ const predicateLocalBinding = program({}, ($) => { .entities(now()) .filter("vertex", ($) => { const foo = $.let("foo", false); + return $.and(true, $.or(true, foo)); }) .collect(); @@ -90,6 +92,7 @@ const publishedEntityById = program( const { now } = $.prelude(); const webId = $.let("webId", inputs.web_id); const entityUuid = $.let("entityUuid", inputs.entity_uuid); + return $.query .entities(now()) .filter("vertex", (_, vertex) => { @@ -105,6 +108,7 @@ const publishedEntityById = program( const sidebarSelection = program({ web_id: web.types.WebId }, ($, inputs) => { const { now } = $.prelude(); const webId = $.let("webId", inputs.web_id); + return $.query .entities(now()) .filter("vertex", (_, vertex) => @@ -154,6 +158,7 @@ const optionalDrafts = program( "includeDrafts", $.input("include_drafts", kernel.types.Boolean, false), ); + return $.query .entities(now()) .filter("vertex", ($, vertex) => diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.ts index a7e6a7dedc0..b9e74411d98 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.ts @@ -7,7 +7,11 @@ import type * as Node from "./Node.js"; import type { Body } from "./Utilities.js"; import type { Result } from "effect"; -/** Contextual overloads propagate the output universes and accumulate every declaration's inputs. */ +/** + * The call signatures of a Do block constructor whose blocks start in the scope `Initial`. + * + * Each overload threads the scope through zero to eight declaration steps, so every step and the final body see the names the earlier steps introduced. The result's input requirements combine those of every step with the body's. For more than eight steps, continue in a nested block started from a callback's `$`. + */ export interface Do { ( body: Body, diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts index 23194f99a70..a8899aa2864 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.ts @@ -15,7 +15,13 @@ import type { Utilities } from "./Utilities.js"; export type { Imported, Selection } from "../program/Import.js"; -/** Imports selected module exports into their respective universes. */ +/** + * Imports a module's exports as a Do block step. + * + * When a block elaborates the step, it calls `select` with the utilities and the modules visible at that point, then emits a HashQL `use` of the returned module around everything after this step. Each selected export enters every environment that declares it, under its local name: modules join the modules environment and `$.ref`, types join the types and values join the values. The imported handles are local names that keep their declared semantic types and call signatures. + * + * Omitting `selection` imports every export. Given a name array, the step imports those exports. Given an alias record, it imports each listed export under a new name, where `"_"` keeps the export's own name. Invalid HashQL identifiers as aliases, and symbol keys in the record, fail construction with `InvalidImportName`, and the block then skips its remaining callbacks. + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the selector and selection construct a declaration step export function Import( select: ( diff --git a/libs/@local/hashql/sdk/typescript/src/do/Let.ts b/libs/@local/hashql/sdk/typescript/src/do/Let.ts index cdbd5e8e07c..51b1a07017e 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Let.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Let.ts @@ -11,6 +11,13 @@ import type * as Type from "../type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; +/** + * Declares a value binding as a Do block step. + * + * When a block elaborates the step, it calls `initializer` with the utilities, values and types visible at that point. The block emits a HashQL `let` that binds `name` to the initializer around everything after this step. Later steps see `name` in their values environment as a reference with the initializer's semantic type and input requirements. A later binding with the same name shadows this one in the values environment only. + * + * The block emits the binding even when nothing refers to it, so its initializer's inputs stay in the program. Names that need quoting, such as `%`, appear quoted in the output. An invalid HashQL identifier fails construction with `InvalidBindingName` after the initializer has run, and the block skips its remaining callbacks. + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a declaration step export const Let = < In extends Scope.Scope, diff --git a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts index eb5ad6c5199..a00e9a4fcc7 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts @@ -14,15 +14,18 @@ import type * as Type from "../type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; +/** The names a `Newtype` step adds: the nominal type and its constructor, both under the declared name. */ export interface Exports< Name extends string, Identity extends symbol, T extends Type.Any, > { + /** The nominal type, an opaque type over `T` distinguished by `Identity`. */ readonly types: ReadonlyRecord< Name, TypeExpression.TypeExpression> >; + /** The constructor, a function from the underlying type `T` to the nominal type. */ readonly values: ReadonlyRecord< Name, Expression.Expression< @@ -32,7 +35,41 @@ export interface Exports< >; } -/** The unique symbol distinguishes declarations even when their query names coincide. */ +/** + * Declares a nominal type and its constructor as a Do block step. + * + * When a block elaborates the step, it calls `definition` with the utilities and the types visible at that point, then emits a HashQL `newtype` declaration around everything after this step. Later steps see `name` in two environments: as the opaque type `Type.Opaque` among their types, and as its constructor among their values. The constructor takes a value of the underlying type `T` and emits a call to `name`. A value of the nominal type does not convert back to `T` implicitly. + * + * `identity` must have a `unique symbol` type. It exists only for TypeScript and is never emitted: two declarations with the same name but different symbols produce incompatible types, and a symbol widened to `symbol` is a type error. A name that is not a valid HashQL identifier fails construction with `InvalidBindingName`, and the block skips its remaining callbacks. + * + * @example Declare a nominal identifier and construct a value. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Import, Let, Newtype, withPrelude } from "@local/hashql/do"; + * import { Result } from "effect"; + * + * const kernel = Result.getOrThrow( + * Module.define("::kernel::type", { + * types: { Integer: Module.type() }, + * }), + * ); + * const userId: unique symbol = Symbol("UserId"); + * const { Do } = withPrelude({ modules: { kernel } }); + * + * const owner = Do( + * Import((_, { kernel }) => kernel, ["Integer"]), + * Newtype("UserId", userId, (_, { Integer }) => Integer), + * Let("owner", (_, { UserId }) => UserId(1n)), + * (_, { owner }) => owner, + * ); + * assert.equal( + * Result.getOrThrow(Result.flatMap(owner, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::use","::kernel::type",{"#tuple":["Integer"]},["::kernel::special_form::newtype","UserId","Integer",["::kernel::special_form::let","owner",["UserId",{"#literal":1}],"owner"]]]', + * ); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a nominal declaration step export const Newtype = < In extends Scope.Scope, diff --git a/libs/@local/hashql/sdk/typescript/src/do/Node.ts b/libs/@local/hashql/sdk/typescript/src/do/Node.ts index 3684d885761..863f4ba5a3c 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Node.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Node.ts @@ -6,27 +6,45 @@ import type { Scope } from "../program/Scope.js"; import type { Utilities } from "./Utilities.js"; import type { Result, Types } from "effect"; +/** Invariant markers for one environment's scope before and after a declaration step. */ export interface Variance { readonly _In: Types.Invariant; readonly _Out: Types.Invariant; } +/** + * The property key that marks a value as a declaration step. + * + * `Do` fails with `InvalidBlockStep` when a value in a step position is neither a callback nor marked with this key. + */ export const TypeId = "~hashql/do/Node"; +/** The outcome of elaborating a declaration step: the scope later steps see and the wrapper that emits the declaration. */ export interface Transition { + /** The scope after the declaration, which the following steps and the body receive. */ readonly scope: Out; + /** Places the declaration around `child`, the syntax of everything that follows it in the block. */ readonly wrap: (child: AstNode) => AstNode; } -/** Runtime construction with erased scope parameters. */ +/** A declaration step with its scope parameters erased, as a block's runtime driver handles it. */ export interface Any { + /** + * Runs the step's callback against the current scope and returns the declaration's transition or construction failure. + * + * A block calls it while constructing, once per step, after the preceding steps succeed. The block converts an exception thrown here into a `CallbackException` failure. + */ readonly elaborate: ( utilities: Utilities, scope: Scope, ) => Result.Result, ProgramError.Construction>; } -/** A construction step with independent input and output types for each universe. */ +/** + * A typed declaration step from the scope `In` to the scope `Out`, contributing the input requirements `Inputs`. + * + * `Let`, `Type`, `Newtype` and `Import` construct steps. Creating one runs none of its callbacks: a block runs the callback each time it elaborates the step. The marker property records each environment's scope before and after the step, which lets the Do overloads infer the scope of every later step. + */ export interface Node extends Any { readonly [TypeId]: { readonly inputs: Types.Contravariant; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Type.ts b/libs/@local/hashql/sdk/typescript/src/do/Type.ts index 50b4f4f34e7..fddae52aa32 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Type.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Type.ts @@ -11,6 +11,13 @@ import type * as Semantic from "../type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; +/** + * Declares a type alias as a Do block step. + * + * When a block elaborates the step, it calls `definition` with the utilities and the types visible at that point. The block emits a HashQL `type` declaration around everything after this step. Later steps see `name` in their types environment as a reference to the alias, carrying the definition's semantic type, so TypeScript treats the alias as that type. Use `Newtype` for a distinct nominal type. A value or module with the same name stays visible. + * + * A name that is not a valid HashQL identifier fails construction with `InvalidBindingName`, and the block skips its remaining callbacks. + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a type declaration step export const Type = < In extends Scope.Scope, diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index f7ce002ae7f..46708a0ce54 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -30,6 +30,11 @@ import type { Imported, Selection } from "./Import.js"; import type { Exports } from "./Newtype.js"; import type { ReadonlyRecord } from "effect/Record"; +/** + * A callback that returns an expression from the utilities, values and types of the scope `S`. + * + * It types a block's final body and the initializer of a nested `Let`. As a final body, it must return an expression handle: any other value fails construction with `InvalidBodyResult`, so lift a host primitive with `$.literal`, `$.integer` or `$.number`. + */ export type Body = ( utilities: Utilities, values: S["values"], @@ -40,7 +45,13 @@ type Wrap = Node.Transition["wrap"]; export type BuildStep = Node.Any | Body; -/** An unfinished nested block must end with an expression. */ +/** + * A nested Do block under construction, started from a callback's `$`. + * + * `Let`, `Type`, `Newtype` and `Import` each elaborate one declaration immediately: they run the step's callback with the block's current scope and return a block whose scope includes the declaration. Once a step fails, later methods skip their callbacks and keep that failure. {@link Block.Expr} ends the chain with a body and returns the block's expression, which wraps the body in the block's declarations. Those declarations stay inside that expression, and the enclosing callback's scope does not gain them. + * + * A failure, including an exception thrown by one of the callbacks, does not interrupt the enclosing callback. It stays attached to the returned expression and fails construction of any program that contains it. + */ export class Block { readonly #state: Result.Result< { @@ -93,6 +104,7 @@ export class Block { return output as Block>; } + /** Appends a value binding, as the `Let` step does, running `initializer` now unless an earlier step failed. */ Let( name: Name, initializer: Body, @@ -106,6 +118,7 @@ export class Block { return this.#step(Let(name, initializer)); } + /** Appends a type alias, as the `Type` step does, running `definition` now unless an earlier step failed. */ Type( name: Name, definition: ( @@ -119,6 +132,7 @@ export class Block { return this.#step(DeclareType(name, definition)); } + /** Appends a nominal type and its constructor, as the `Newtype` step does, running `definition` now unless an earlier step failed. */ Newtype< const Name extends string, const Identity extends symbol, @@ -136,6 +150,7 @@ export class Block { ); } + /** Appends an import of the module `select` returns, as the `Import` step does, running `select` now unless an earlier step failed. */ Import>( select: ( utilities: Utilities, @@ -171,6 +186,11 @@ export class Block { return this.#step(Import(select, imports)); } + /** + * Ends the block with its body and returns the block's expression. + * + * The body runs now with the block's scope, unless an earlier step failed. The returned expression wraps the body's expression in this block's declarations, in step order, and combines the input requirements of every step with the body's. It is an expression rather than a `Result`, and it carries any construction failure, including one from a callback's exception. + */ Expr( body: Body, ): Expression.Expression> { @@ -257,6 +277,7 @@ const evaluateBranch = ( Result.flatMap(Expression.toNode), ); +/** Constructs a HashQL conditional, running both branch callbacks during construction. */ const conditional = < const Condition extends Expression.Value, const Then extends Expression.AnyValue, @@ -291,15 +312,70 @@ const conditional = < >, ); +/** + * The `$` argument of every Do callback: expression constructors and an empty nested block at the callback's scope. + * + * Because `$` is itself a {@link Block}, `$.Let`, `$.Type`, `$.Newtype`, `$.Import` and `$.Expr` start a nested block whose declarations stay inside the expression it returns. The predicate constructors `eq`, `ne`, `and`, `or`, `not`, `isTrue`, `isFalse` and `isNone` are the standalone `Operators` functions. + */ export interface Utilities extends Block, Operators.Operations { + /** Lifts a host primitive to an expression whose type follows the host type. This is `Expression.literal`. */ readonly literal: typeof Expression.literal; + /** Constructs an Integer literal, failing construction for a fractional or non-finite number. This is `Expression.integer`. */ readonly integer: typeof Expression.integer; + /** Constructs a Number literal. This is `Expression.number`. */ readonly number: typeof Expression.number; + /** References a program input, optionally with a default. This is `Expression.input`. */ readonly input: typeof Expression.input; + /** Changes an expression's semantic type assumption without validating that semantic type. This is `Expression.assume`. */ readonly assume: typeof Expression.assume; + /** + * The modules visible at this point: the prelude's modules and those imported by earlier steps, under their local names. + * + * Reach a module's exports through its `modules`, `types` and `values` records, such as `$.ref.math.values.add`. A prelude module's exports refer to their declared paths, and an imported module's exports refer to their paths under its local name. + */ readonly ref: S["modules"]; + /** + * Graph query entry points, present when the values environment holds a suitable `entities` function. + * + * `entities` exists when that function returns a `::graph::Graph` opaque type, whose vertex type the query's predicates receive. Each `filter` predicate runs during the `filter` call, unless the query already carries a failure or the parameter name is invalid. An exception it throws becomes a `CallbackException` failure on the query. + */ readonly query: Query.Context; + /** + * Constructs a HashQL conditional from a Boolean condition and two branch callbacks. + * + * Both callbacks run immediately, then-branch first, whatever the condition's value: HashQL decides the condition when the query runs, so construction needs both branches. Each callback returns an expression or a host primitive and takes no arguments. Start a nested block from the enclosing `$` for declarations local to a branch. + * + * An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. If more than one part fails, the expression carries the first failure in the order condition, then-branch, else-branch. + * + * @example Construct both branches, one with a local binding. + * ```ts + * import assert from "node:assert/strict"; + * import { Program } from "@local/hashql"; + * import { Do } from "@local/hashql/do"; + * import { Result } from "effect"; + * + * const visited: string[] = []; + * const result = Do(($) => + * $.if( + * true, + * () => { + * visited.push("then"); + * return $.Let("local", ($) => $.integer(1)).Expr((_, { local }) => local); + * }, + * () => { + * visited.push("else"); + * return $.integer(2); + * }, + * ), + * ); + * assert.deepEqual(visited, ["then", "else"]); + * assert.equal( + * Result.getOrThrow(Result.flatMap(result, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::if",{"#literal":true},["::kernel::special_form::let","local",{"#literal":1},"local"],{"#literal":2}]', + * ); + * ``` + */ readonly if: typeof conditional; } diff --git a/libs/@local/hashql/sdk/typescript/src/do/index.ts b/libs/@local/hashql/sdk/typescript/src/do/index.ts index 9b5f2c3ce73..75040220892 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/index.ts @@ -1,5 +1,37 @@ /** - * Authors typed expressions with ordered declaration steps and scoped callbacks. + * Authors typed HashQL expressions as blocks of ordered declaration steps. + * + * A block lists declaration steps and ends with a body callback. {@link Let}, {@link Type}, {@link Newtype} and {@link Import} construct the steps, and {@link Do} runs them in order. Each step's callback sees the modules, values and types that earlier steps introduced, and each step emits a declaration around the rest of the block. The result is a construction `Result` holding the block's expression, whose input requirements TypeScript infers from every step and the body. Callbacks construct syntax and never execute a query. + * + * {@link withPrelude} seeds a block's environments with existing declarations, such as modules from `Module.define`. Every callback's `$` argument, described by `Utilities`, holds expression constructors, conditionals, queries and nested blocks. Draft, at `@local/hashql/draft`, builds the same expressions from one callback and an explicit input schema. + * + * @example Import a function and bind its result. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Import, Let, withPrelude } from "@local/hashql/do"; + * import { Result } from "effect"; + * + * type Add = Type.Function< + * readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + * Type.PrimitiveInteger + * >; + * const math = Result.getOrThrow( + * Module.define("::core::math", { values: { add: Module.value() } }), + * ); + * const { Do } = withPrelude({ modules: { math } }); + * + * const total = Do( + * Import((_, { math }) => math, ["add"]), + * Let("total", (_, { add }) => add(1n, 2n)), + * (_, { total }) => total, + * ); + * assert.equal( + * Result.getOrThrow(Result.flatMap(total, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::use","::core::math",{"#tuple":["add"]},["::kernel::special_form::let","total",["add",{"#literal":1},{"#literal":2}],"total"]]', + * ); + * ``` * * @module */ @@ -23,7 +55,13 @@ export { Newtype } from "./Newtype.js"; export { Type } from "./Type.js"; export type { Utilities } from "./Utilities.js"; +/** + * The constructors {@link withPrelude} returns for one prelude. + * + * Only `Do` depends on the prelude. `Let`, `Type`, `Newtype` and `Import` are this module's step constructors, returned unchanged so that one destructuring supplies the whole vocabulary. + */ export interface Context { + /** Constructs blocks that start in the scope the prelude seeded. */ readonly Do: Block; readonly Let: typeof Let; readonly Type: typeof Type; @@ -31,6 +69,13 @@ export interface Context { readonly Import: typeof Import; } +/** + * Binds {@link Do} to a prelude of existing module, value and type declarations. + * + * The prelude's optional `modules`, `values` and `types` records seed every block's environments. Step callbacks and bodies receive those environments as arguments, and `$.ref` holds the modules. A module from `Module.define` is itself a valid prelude. Seeding emits no HashQL, because a prelude export already refers to its declaration, typically by absolute path. The returned `Do` includes nothing from `Prelude.builtin` unless the prelude supplies it. + * + * `withPrelude` copies the records' own string-keyed exports when you call it, so later additions or replacements in them do not reach the returned `Do`. + */ export const withPrelude = ( prelude: Prelude, ): Context> => { @@ -63,5 +108,37 @@ export const withPrelude = ( const context: Context = withPrelude({}); +/** + * Constructs an expression from ordered declaration steps and a final body, starting with empty environments. + * + * `Do(step1, ..., stepN, body)` runs synchronously. It elaborates each step in argument order, running the step's callback with the scope the earlier steps produced, then runs `body` with the final scope. Nested blocks, conditionals and query predicates inside those callbacks also run during the call, and `$.if` runs both of its branch callbacks. The returned expression nests the declarations in step order around the body's expression. Its input requirements combine every step's with the body's, including the requirements of bindings that nothing refers to. + * + * `Do` returns construction failures rather than throwing them. The first failing step stops construction, so later callbacks and the body do not run. An exception thrown by a callback becomes a failure whose reason is `CallbackException`, with the thrown value as the cause of its `Cause.UnknownError`. Arguments that TypeScript rejects fail at runtime with `MissingBlockBody` when the last argument is not a callback, `MisplacedBlockBody` when an earlier argument is a callback and `InvalidBlockStep` for another value in a step position. A body that returns anything other than an expression handle fails with `InvalidBodyResult`. + * + * Use {@link withPrelude} to start blocks with declarations in scope. The positional form accepts up to eight steps. Continue in a nested block, started from a callback's `$`, for more. + * + * @example Observe callback order after a failed step. + * ```ts + * import assert from "node:assert/strict"; + * import { Do, Let } from "@local/hashql/do"; + * import { Result } from "effect"; + * + * const calls: string[] = []; + * const result = Do( + * Let("not a name", ($) => { + * calls.push("first"); + * return $.integer(1); + * }), + * Let("later", ($) => { + * calls.push("later"); + * return $.integer(2); + * }), + * (_, { later }) => later, + * ); + * assert.deepEqual(calls, ["first"]); + * assert.ok(Result.isFailure(result)); + * assert.equal(result.failure.reason._tag, "InvalidBindingName"); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- composes ordered steps and a final expression callback export const Do: Block = context.Do; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts index fa50e6236fb..ddf8a4a97c0 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts @@ -14,17 +14,59 @@ import type * as Type from "../type/index.js"; import type * as Construction from "./Context.js"; import type { ReadonlyRecord } from "effect/Record"; +/** + * An input schema maps each program input's name to the input's type expression. + * + * Every own string key, including a non-enumerable one, becomes an input handle. A symbol key from an unchecked caller fails construction with `SymbolInputName` before the callback runs. + */ export type Inputs = ReadonlyRecord; type TypeInputs = { readonly [K in keyof I]: I[K] extends TypeExpression.TypeExpression ? T : never; }; +/** + * The input requirements of a program built from a schema, listing every entry as required with its semantic type. + * + * Entries the callback never uses, and entries whose every use supplies a default, remain required. A schema typed as a union of records requires the entries of every alternative, including an alternative with no entries. + * + * @example Type-only: a result keeps unused entries, and a discarded binding still needs its input declared. + * ```ts + * import { Expression, Prelude } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const { Integer } = Prelude.builtin.types; + * const schema = { limit: Integer, verbose: Prelude.builtin.types.Boolean }; + * const built = Result.getOrThrow(program(schema, ($, { limit }) => $.let("limit", limit))); + * type Whole = { + * readonly limit: Type.PrimitiveInteger; + * readonly verbose: Type.PrimitiveBoolean; + * }; + * const whole: Expression.Expression = built; + * // @ts-expect-error The unused `verbose` entry stays required. + * const partial: Expression.Expression> = built; + * + * const outside = Expression.input("outside", Integer); + * program({}, ($) => { + * // @ts-expect-error The schema does not declare `outside`. + * $.let("ignored", outside); + * return $.literal(true); + * }); + * ``` + */ export type Requirements = Input.Conservative>; +/** The input handle for the schema key `K` with the type expression `D`, which references that input and requires `K`. */ export type Handle = D extends TypeExpression.TypeExpression ? Expression.Expression>> : never; +/** + * The frozen record a program callback receives as its second argument, holding one input handle per schema key. + * + * Each handle emits an input reference without a default at every use. + */ export type Handles = { readonly [K in keyof I]: Handle; }; @@ -42,7 +84,11 @@ type Mismatches = I extends unknown }[keyof I] : never; -/** All host alternatives must fit the schema. Erased requirements cannot prove that. */ +/** + * Accepts input requirements when the schema record `S` declares each of them with the same semantic type. + * + * It evaluates to `unknown`, which leaves an intersection unchanged, when every host-side alternative of the requirements fits. Otherwise it evaluates to `never`, which rejects the value it constrains. An input used with a default still needs a declaration. Erased requirements, such as those of `Expression.Any` or `Expression.Value`, never fit, because they cannot show which inputs they need. + */ export type Check = [I] extends [never] ? never : [Mismatches>] extends [never] @@ -51,6 +97,11 @@ export type Check = [I] extends [never] : never; type Accept = Check>; +/** + * A graph query under construction in a program callback, whose arguments and predicates must fit the program's schema. + * + * The query is an expression of the graph type with `filter` and `collect`. Binding it with `let` produces a plain expression without those methods. + */ type Query< S extends Scope.Scope, I, @@ -58,6 +109,11 @@ type Query< V extends Type.Any, R, > = Expression.Expression & { + /** + * Adds a filter and constructs its predicate now, in its own declaration scope. + * + * `name` becomes the filter closure's parameter. `predicate` does not run when the query already carries a failure, or when `name` is not a valid HashQL identifier, which fails construction with `InvalidParameterName`. Otherwise `predicate` runs once, immediately, with a fresh restricted context and the vertex expression. The filter closure contains the declarations made through that context. The predicate returns a Boolean expression or host boolean whose input requirements fit the schema. An exception it throws becomes a `CallbackException` failure on the returned query. + */ readonly filter: >( name: string, predicate: ( @@ -65,6 +121,7 @@ type Query< vertex: Expression.Expression, ) => P & Accept, ) => Query>>; + /** Ends the query, emitting `::graph::tail::collect`, as a list of its vertices. */ readonly collect: () => Expression.Expression, R>; }; @@ -75,6 +132,7 @@ type QueryContext = [EntityFunction] extends [ ? // oxlint-disable-next-line typescript/no-generated-empty-object-type -- no graph declaration means no query entry point Record : { + /** Starts a graph query by calling the prelude's `entities` function, with arguments whose input requirements fit the schema. */ readonly entities: < const A extends readonly Expression.AnyValue[] & Arguments["args"]>, @@ -90,17 +148,100 @@ type QueryContext = [EntityFunction] extends [ >; }; -/** A restricted view that the unrestricted constructor implements. */ +/** + * The `$` argument of a program callback, which restricts the construction context to the program's input schema. + * + * `let`, `if` and `query` accept only values whose input requirements fit the schema, and branch and predicate callbacks receive the same restricted view. The other members are the unrestricted Draft `Context.Context` operations. The unrestricted constructor implements this view, but the view is not assignable to `Context.Context`, so a helper typed with the unrestricted context cannot receive a program's `$`. + */ export interface Context extends Omit< Construction.Context, "let" | "if" | "query" > { + /** + * Binds a value to a HashQL name and returns a reference to the binding. + * + * Draft emits the binding around this callback's returned expression, in call order with its other declarations, even when nothing refers to it. `value` is an expression or host primitive whose input requirements fit the schema, and the reference keeps its semantic type and requirements. An invalid name, or a value whose construction failed, does not interrupt the callback, but Draft records the failure and the program fails. The reference is the binding's bare name, so carrying it out of this callback leaves it without its binding. + */ readonly let: ( name: string, value: E & Accept, ) => Expression.Expression, Expression.Inputs>; + /** + * Graph query entry points, present when the prelude declares an `entities` function that returns a `::graph::Graph` opaque type. + * + * The function's result type determines the vertex type that filter predicates receive. Query arguments and predicate results must fit the schema. + * + * @example Filter a declared graph with a predicate-local binding. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { withPrelude } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * type Vertex = Type.Struct<{ readonly archived: Type.PrimitiveBoolean }>; + * type Graph = Type.Opaque<"::graph::Graph", Type.Struct<{ readonly "'marker": Vertex }>>; + * const graph = Result.getOrThrow( + * Module.define("::example::graph", { + * values: { entities: Module.value>() }, + * }), + * ); + * const { program } = withPrelude(graph); + * + * let predicates = 0; + * const live = program({}, ($) => + * $.query + * .entities() + * .filter("vertex", (predicate, vertex) => { + * predicates += 1; + * const archived = predicate.let("archived", vertex.archived); + * return predicate.isFalse(archived); + * }) + * .collect(), + * ); + * assert.equal(predicates, 1); + * assert.equal( + * Result.getOrThrow(Result.flatMap(live, (root) => Program.compile(Program.program(root)))), + * '["::graph::tail::collect",["::graph::body::filter",["::example::graph::entities"],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",["::kernel::special_form::let","archived",["::kernel::special_form::access","vertex","archived"],["::core::cmp::eq","archived",{"#literal":false}]]]]]', + * ); + * ``` + */ readonly query: QueryContext; + /** + * Constructs a HashQL conditional from a Boolean condition and two branches. + * + * The condition and both branches must fit the schema, and the result combines their input requirements. HashQL decides the condition when the query runs, so construction always builds both branches. + * + * @example Construct both branches, one with a branch-local binding. + * ```ts + * import assert from "node:assert/strict"; + * import { Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const visited: string[] = []; + * const choice = program({}, ($) => + * $.if( + * false, + * (branch) => { + * visited.push("then"); + * return branch.let("inside", 1n); + * }, + * () => { + * visited.push("else"); + * return 2n; + * }, + * ), + * ); + * assert.deepEqual(visited, ["then", "else"]); + * assert.equal( + * Result.getOrThrow(Result.flatMap(choice, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::if",{"#literal":false},["::kernel::special_form::let","inside",{"#literal":1},"inside"],{"#literal":2}]', + * ); + * ``` + */ readonly if: { + /** Uses values that already exist as the branches. No callback runs, and the branches get no declaration scope of their own. */ < const C extends Expression.Value, const T extends Expression.AnyValue, @@ -112,6 +253,11 @@ export interface Context extends Omit< readonly else: E & Accept; }, ): Construction.Conditional; + /** + * Constructs each branch with a callback in its own declaration scope. + * + * Both callbacks run immediately, `then` first, whatever the condition's value. Each receives a fresh restricted context, and that branch contains the declarations made through it. Declarations made through a captured outer `$` belong to the outer callback instead. An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. + */ < const C extends Expression.Value, const T extends Expression.AnyValue, @@ -124,6 +270,11 @@ export interface Context extends Omit< }; } +/** + * The callback a Draft program runs with the restricted context and the input handles to obtain the root expression. + * + * The returned expression's input requirements must fit the schema. Returning anything other than an expression handle fails construction with `InvalidBodyResult`. The type rejects an asynchronous callback, and at runtime its promise fails construction the same way. + */ export type Body< S extends Scope.Scope, I extends Inputs, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts index eb6c097b8c4..778faa6550d 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -21,13 +21,22 @@ import type * as QueryTypes from "../program/Query.js"; import type * as Scope from "../program/Scope.js"; import type * as Structural from "../program/Structural.js"; +/** + * The call signature of a Draft nominal constructor: it wraps an exactly typed value of the underlying type `T` as the nominal type. + * + * The argument can be an expression or structural shorthand, such as a record of expressions and primitives for a struct. TypeScript rejects missing, extra and wrongly typed fields. The result requires the inputs the argument requires. + */ export type NominalCall = < const V extends Structural.Value & Structural.AnyValue, >( value: Structural.Exact, ) => Expression.Expression, Structural.Requirements>; -/** Each constructor has one rebinding result rather than an intersection of recursive overloads. */ +/** + * A Draft nominal constructor: an expression of function type that also accepts structural shorthand. + * + * Rebinding it, as an import or module export does, keeps both the call signature and the nominal identity. Each constructor has one rebinding result rather than an intersection of recursive overloads. + */ export interface NominalValue extends Expression.Any, NominalCall { readonly "~hashql/Expression": Expression.Handle< @@ -37,17 +46,28 @@ export interface NominalValue readonly [Relocate]: Relocatable>[typeof Relocate]; } +/** The result of `newtype`: one handle that is both the nominal type expression and its constructor. */ export type Nominal = Namespace.Joined< NominalValue, TypeExpression.TypeExpression> >; +/** + * A graph query under construction with the unrestricted context: an expression of the graph type with `filter` and `collect`. + * + * Binding it with `let` produces a plain expression without those methods. + */ export type Query< S extends Scope.Scope, T extends Type.Any, V extends Type.Any, I, > = Expression.Expression & { + /** + * Adds a filter and constructs its predicate now, in its own declaration scope. + * + * `name` becomes the filter closure's parameter. `predicate` does not run when the query already carries a failure, or when `name` is not a valid HashQL identifier, which fails construction with `InvalidParameterName`. Otherwise `predicate` runs once, immediately, with a fresh context and the vertex expression. The filter closure contains the declarations made through that context. An exception the predicate throws becomes a `CallbackException` failure on the returned query. + */ readonly filter: >( name: string, predicate: ( @@ -55,12 +75,15 @@ export type Query< vertex: Expression.Expression, ) => P, ) => Query>>; + /** Ends the query, emitting `::graph::tail::collect`, as a list of its vertices. */ readonly collect: () => Expression.Expression, I>; }; +/** The argument, result, vertex and input types of the scope's `entities` function, or `never` when it has none returning a graph. */ export type EntityFunction = QueryTypes.EntityFunction; +/** The `entities` entry point: calls the scope's `entities` function and returns a query over its vertex type. */ export type Entities = < const A extends readonly Expression.AnyValue[] & Arguments["args"]>, @@ -73,6 +96,7 @@ export type Entities = < Inputs.Merge["inputs"], ArgumentInputs> >; +/** The query entry points of a context: `entities` when the scope declares a graph-returning `entities` function, otherwise none. */ export type QueryContext = [EntityFunction] extends [ never, ] @@ -80,6 +104,7 @@ export type QueryContext = [EntityFunction] extends [ Record : { readonly entities: Entities }; +/** The branch arguments of `if`: one record of values that already exist, or two callbacks that each construct a branch in its own context. */ export type Branches< S extends Scope.Scope, T extends Expression.AnyValue, @@ -88,6 +113,7 @@ export type Branches< | readonly [branches: { readonly then: T; readonly else: E }] | readonly [then: ($: Context) => T, otherwise: ($: Context) => E]; +/** The expression `if` returns: its type combines the branch types, and its input requirements combine the condition's with both branches'. */ export type Conditional< C extends Expression.Value, T extends Expression.AnyValue, @@ -100,9 +126,27 @@ export type Conditional< > >; +/** + * The unrestricted Draft construction context for the scope `S`. + * + * Its operations construct syntax and collect declarations, accepting values regardless of their input requirements. Draft emits each declaration around the declaring callback's returned expression, in call order. Draft programs give their callbacks a view of this interface restricted to the program's input schema. That view is not assignable to this interface, and a callback written against this interface is not accepted as a program body. The predicate constructors `eq`, `ne`, `and`, `or`, `not`, `isTrue`, `isFalse` and `isNone` are the standalone `Operators` functions. + */ export interface Context extends Operators.Operations { + /** + * Returns the prelude's exports as one record. + * + * Same-named module, type and value exports become one handle that keeps each capability. The record does not change when the callback imports a module. + */ readonly prelude: () => Namespace.Flatten; + /** Returns the prelude's modules, each with its child exports also available directly as properties. */ readonly modules: () => Namespace.Modules; + /** + * Imports a module's exports into the declaring callback and returns them as handles. + * + * Draft emits the import around the callback's returned expression, in call order with its other declarations. Omitting `selection` imports every export. Given a name array, `import` selects those exports. Given an alias record, it imports each listed export under a new name, where `"_"` keeps the export's own name. The returned record joins same-named exports as `prelude()` does and refers to them by their local names. It leaves `prelude()`, `modules()` and `query` unchanged. + * + * Unlike the other declarations, a failed import interrupts the callback, because it cannot supply the handles it promises. An invalid alias and a symbol key in the alias record both stop the callback with an `InvalidImportName` failure. The program returns the failure even if the callback catches the interruption. + */ readonly import: { ( module: M & Import.Rebindable, @@ -112,20 +156,41 @@ export interface Context extends Operators.Operations { selection: I, ): Namespace.Flatten>; }; + /** Lifts a host primitive to an expression whose type follows the host type. This is `Expression.literal`. */ readonly literal: typeof Expression.literal; + /** Constructs an Integer literal, failing construction for a fractional or non-finite number. This is `Expression.integer`. */ readonly integer: typeof Expression.integer; + /** Constructs a Number literal. This is `Expression.number`. */ readonly number: typeof Expression.number; + /** Changes an expression's semantic type assumption without validating that semantic type. This is `Expression.assume`. */ readonly assume: typeof Expression.assume; + /** References a program input, optionally with a default. This is `Expression.input`. */ readonly input: typeof Expression.input; + /** Graph query entry points, present when the prelude declares an `entities` function that returns a `::graph::Graph` opaque type. */ readonly query: QueryContext; + /** + * Binds a value to a HashQL name and returns a reference to the binding. + * + * Draft emits the binding around the declaring callback's returned expression, in call order with its other declarations, even when nothing refers to it. An invalid name, or a value whose construction failed, does not interrupt the callback, but Draft records the failure and the program fails. The reference is the binding's bare name, so carrying it out of the declaring callback leaves it without its binding. + */ readonly let: ( name: string, value: E, ) => Expression.Expression, Expression.Inputs>; + /** + * Declares a type alias and returns a reference to it. + * + * `definition` is a type expression or structural shorthand. `BigInt`, `Number`, `String` and `Boolean` denote the primitive types, and records and arrays of definitions denote structs and tuples. Draft emits the alias around the declaring callback's returned expression, in call order with its other declarations. An invalid name or definition leaves the callback running, but Draft records the failure and the program fails. + */ readonly type: ( name: string, definition: D, ) => TypeExpression.TypeExpression>; + /** + * Declares a nominal type and returns one handle that is both the type and its constructor. + * + * The handle is a type expression for `Type.Opaque`, where `T` is the definition's type, and a constructor from an exactly typed value of `T`, including structural shorthand. Calling it emits a call to the declared name. `identity` must have a `unique symbol` type. It distinguishes declarations in TypeScript, and the output never contains it. Draft emits the declaration and records its failures as for `type`. + */ readonly newtype: < const N extends symbol, const D extends Structural.Definition, @@ -134,6 +199,11 @@ export interface Context extends Operators.Operations { identity: symbol extends N ? never : N, definition: D, ) => Nominal>; + /** + * Constructs a HashQL conditional from a Boolean condition and two branches. + * + * A `{ then, else }` record supplies values that already exist and creates no declaration scope. A pair of callbacks constructs the branches instead. Both run immediately, `then` first, whatever the condition's value, each with a fresh context whose declarations stay inside that branch. An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. + */ readonly if: < const C extends Expression.Value, const T extends Expression.AnyValue, diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts index 1d2b426143b..bd3b8af9cfb 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -1,7 +1,27 @@ /** * Synchronous program construction with an explicit input schema. * - * The callback receives typed input handles and a prelude-specific construction context. Every emitted initializer and nested body must fit that schema, so the result can retain unused declared inputs without overlooking discarded declarations. Custom preludes replace the default and retain their exact export keys. + * {@link program} runs one callback that receives a construction context `$` and typed handles for the inputs its schema declares. Draft emits the declarations made through `$`, such as `$.let`, `$.type`, `$.newtype` and `$.import`, around the callback's returned expression in call order. Every emitted initializer and nested body must fit the schema, so the result can retain unused declared inputs without overlooking discarded declarations. Branch and query-predicate callbacks receive their own contexts, whose declarations stay inside that branch or predicate. + * + * {@link program} uses `Prelude.builtin`. {@link withPrelude} creates a program constructor for custom declarations instead, replacing the default and retaining their exact export keys. The `Context` namespace names the construction operation types. Do, at `@local/hashql/do`, builds the same expressions from ordered declaration steps and infers input requirements rather than declaring them. + * + * @example Bind a computed value and compare it with an input. + * ```ts + * import assert from "node:assert/strict"; + * import { Prelude, Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const atLimit = program({ count: Prelude.builtin.types.Integer }, ($, { count }) => { + * const { add } = $.prelude(); + * const next = $.let("next", add(count, 1n)); + * return $.eq(next, 10n); + * }); + * assert.equal( + * Result.getOrThrow(Result.flatMap(atLimit, (root) => Program.compile(Program.program(root)))), + * '["::kernel::special_form::let","next",["::core::math::add",["::kernel::special_form::input","count","::kernel::type::Integer"],{"#literal":1}],["::core::cmp::eq","next",{"#literal":10}]]', + * ); + * ``` * * @module */ @@ -20,6 +40,11 @@ import type * as Body from "./Body.js"; export type * as Context from "./Context.js"; +/** + * A Draft program constructor whose callbacks see the scope `S`. + * + * It takes an input schema and a callback, and returns the root expression or a construction failure. The result requires every schema entry. {@link program} documents the callback's timing and failure contract, which every constructor from {@link withPrelude} shares. + */ export type Program = < const I extends Body.Inputs, const O extends Expression.AnyValue & Expression.Any, @@ -73,7 +98,41 @@ type Rebindings = { : Relocatable; }; -/** Replaces the default declarations without widening the supplied export tables. */ +/** + * Creates a program constructor whose callbacks see a custom prelude instead of the built-in one. + * + * The prelude's optional `modules`, `types` and `values` records replace `Prelude.builtin` entirely, without widening the supplied export tables. A callback reaches them through `$.prelude()`, which joins same-named exports into one handle, and `$.modules()`. A `values.entities` function that returns a `::graph::Graph` opaque type enables `$.query.entities`. A module from `Module.define` is a valid prelude. Seeding emits no HashQL, because each export already refers to its declaration. + * + * `withPrelude` copies the records' own string-keyed exports, including non-enumerable ones, when you call it. Later changes to the records do not reach the returned constructor, and `withPrelude` does not freeze them. The parameter type requires each export to be a rebindable SDK producer, such as a module, type expression or expression handle. A symbol-keyed export from an unchecked caller makes every program call return a `SymbolExportName` failure before its callback runs. + * + * @example Use a module as the whole prelude. + * ```ts + * import assert from "node:assert/strict"; + * import { Module, Program } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { withPrelude } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * type Add = Type.Function< + * readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], + * Type.PrimitiveInteger + * >; + * const math = Result.getOrThrow( + * Module.define("::core::math", { values: { add: Module.value() } }), + * ); + * const { program } = withPrelude(math); + * + * const sum = program({}, ($) => { + * const names = $.prelude(); + * assert.equal("Uuid" in names, false); + * return names.add(1n, 2n); + * }); + * assert.equal( + * Result.getOrThrow(Result.flatMap(sum, (root) => Program.compile(Program.program(root)))), + * '["::core::math::add",{"#literal":1},{"#literal":2}]', + * ); + * ``` + */ export function withPrelude( prelude: S & Namespace.Rebindable, ): { readonly program: Program> }; @@ -132,6 +191,51 @@ export function withPrelude< return Object.freeze({ program }); } +/** + * Constructs a program's root expression with the built-in prelude. + * + * The callback runs synchronously with a construction context and typed input handles. Its operations build syntax rather than executing a query. The root expression retains every declared input requirement, including unused schema entries. A symbol input name causes a construction failure before the callback runs. + * + * Both conditional branch callbacks construct syntax, regardless of the condition's value. Host-side effects in those callbacks happen during construction. + * + * Use {@link withPrelude} to supply custom declarations. + * + * @param inputs - The input names and their semantic type expressions. + * @param draft - A synchronous construction callback returning an expression handle. + * @returns The root expression or a construction failure. Synchronous callback exceptions become `CallbackException` failures retaining the thrown value. Expected construction failures retain their original reasons. + * + * @example Construct and serialize a program. + * ```ts + * import assert from "node:assert/strict"; + * import { Program } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * let calls = 0; + * const result = program({}, ($) => { + * calls += 1; + * return $.literal("ready"); + * }); + * assert.equal(calls, 1); + * assert.equal( + * Result.getOrThrow(Result.flatMap(result, (root) => Program.compile(Program.program(root)))), + * '{"#literal":"ready"}', + * ); + * ``` + * + * @example Inspect a callback failure. + * ```ts + * import assert from "node:assert/strict"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const result = program({}, () => { + * throw new Error("Missing application configuration"); + * }); + * assert.ok(Result.isFailure(result)); + * assert.equal(result.failure.reason._tag, "CallbackException"); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the schema and callback construct a new program export const program: Program = withPrelude( Prelude.builtin, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts index fab3da8e81f..25bec4dc600 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts @@ -20,9 +20,9 @@ export type Encoded = Defs.CallEncoded; type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks a call and its arguments. + * Checks a call's structure and every nested expression. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * The array needs at least the function expression, and each later element must be an expression or a labeled argument. The result is a new array. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,14 +30,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Call = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts index cdac453e49a..7e3da238452 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts @@ -10,17 +10,18 @@ export const Schema: typeof Defs.Dict = Defs.Dict; /** * A dictionary constructor with string keys or expression-keyed entries. * - * Record keys are literal strings. In an array of pairs, both the key and the value are expressions. + * Record keys are literal strings. In an array of pairs, both the key and the value are expressions, so the string key `"user.name"` below is a field access rather than literal text. * - * @example + * @example Compare a literal key with a computed key. * ```ts - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * - * JExpr.compile(JExpr.dict({ "user.name": JExpr.literal("Alice") })); - * // => '{"#dict":{"user.name":{"#literal":"Alice"}}}' + * const literalKey = JExpr.dict({ "user.name": JExpr.literal("Alice") }); + * assert.equal(JExpr.compile(literalKey), '{"#dict":{"user.name":{"#literal":"Alice"}}}'); * - * JExpr.compile(JExpr.dict([["user.name", JExpr.literal("Alice")]])); - * // => '{"#dict":[["user.name",{"#literal":"Alice"}]]}' + * const computedKey = JExpr.dict([["user.name", JExpr.literal("Alice")]]); + * assert.equal(JExpr.compile(computedKey), '{"#dict":[["user.name",{"#literal":"Alice"}]]}'); * ``` */ export interface Dict extends Defs.DictType {} @@ -33,7 +34,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; /** * Checks dictionary entries and an optional type annotation. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * Record keys can be any string, and `#type` can be any text. Each value, and each key in the pair form, must be an expression. The result is a new dictionary. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -41,14 +42,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Dict = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts index 2a11c45438b..7d7d430ede3 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts @@ -20,9 +20,9 @@ export interface Encoded extends Defs.FloatEncoded {} type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks the spelling of a float literal. + * Checks that `value` is a float in JSON number syntax, such as `1.0` or `1e3`. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * The text needs a fraction or exponent, so `1` and `1.` fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,14 +30,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Float = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts index ecf77b43dbb..44b11f32ed0 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts @@ -6,12 +6,12 @@ import * as Type from "./type/index.js"; import type * as Defs from "./schema.js"; -/** The `_` placeholder, which asks the compiler to infer a type. */ +/** The `_` placeholder, which asks the HashQL compiler to infer a type in a {@link fn} signature. */ const inferred = "_" as const; export { inferred as infer }; -/** An explicit type or {@link infer}, accepted by {@link fn} for parameter and return types. */ +/** An explicit type or {@link inferred | infer}, accepted by {@link fn} for parameter and return types. */ export type TypeArgument = Type.Type | typeof inferred; /** Renders a type argument, preserving the inference placeholder. */ @@ -28,14 +28,14 @@ export interface FnOptions { /** * Type parameter names, or a record mapping each name to its bound. * - * Use {@link infer} for an unbounded parameter in a record. Defaults to no generic parameters. + * An array becomes a `#tuple` of unbounded names. In a record, use {@link inferred | infer} for an unbounded parameter. Defaults to no generic parameters. */ readonly generics?: | readonly string[] | Record.ReadonlyRecord; - /** Parameter names and types, in argument order. Use {@link infer} for an inferred type. */ + /** Parameter names and types, in argument order. Names must be identifiers. Use {@link inferred | infer} for an inferred type. */ readonly params: Record.ReadonlyRecord; - /** The return type. Defaults to {@link infer}. */ + /** The return type. Defaults to {@link inferred | infer}. */ readonly returns?: TypeArgument; /** The expression that computes the closure's result. */ readonly body: Defs.ExpressionType; @@ -64,18 +64,21 @@ const compileGenerics = ( /** * Defines a closure with named parameters. * - * Parameter names are in scope in the body. Their record order determines the argument order. The return type defaults to {@link infer}. + * The result is the call `["fn", generics, params, returns, body]`. Parameter names are in scope in the body, and their record order determines the argument order. The return type defaults to {@link inferred | infer}. Types are written as constructor syntax, as in `JExpr.as`. The builder checks neither the body nor its use of the parameters. Call the closure with `JExpr.call` or bind it with `JExpr.let`. * - * @example + * @example Define a predicate with an inferred parameter type. * ```ts - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * * const isDraft = JExpr.fn({ * params: { entity: JExpr.infer }, * body: JExpr.call("==", "entity.draft_id", JExpr.literal(null)), * }); - * JExpr.compile(isDraft); - * // => '["fn",{"#tuple":[]},{"#struct":{"entity":"_"}},"_",["==","entity.draft_id",{"#literal":null}]]' + * assert.equal( + * JExpr.compile(isDraft), + * '["fn",{"#tuple":[]},{"#struct":{"entity":"_"}},"_",["==","entity.draft_id",{"#literal":null}]]', + * ); * ``` */ export const fn = (options: FnOptions): Defs.CallType => [ diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts index 6dee2cfdbdf..4ff9b302838 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts @@ -1,9 +1,7 @@ /** - * HashQL identifiers. + * Single HashQL identifiers and their source spelling. * - * An {@link Ident} stores its kind and its value without backticks, like `Ident` - * in `hashql-core`. Use {@link decodeResult} to read source syntax such as `foo`, `+`, - * `` `+` `` or `` `https://example.com/` ``, and {@link compile} to write it back. + * An {@link Ident} stores its kind and its value without backticks, like `Ident` in `hashql-core`. Use {@link decodeResult} to read source syntax such as `foo`, `+`, `` `+` `` or `` `https://example.com/` ``, and {@link compile} to write it back. Paths, field access and the `_` placeholder are wider string expressions rather than identifiers. * * @module */ @@ -62,7 +60,7 @@ export const SchemaFromSelf: $Schema.toTaggedUnion< /** * Codec between source syntax and an identifier object. * - * Encoding quotes symbol and base-URL identifiers. Arbitrary generation uses the decoded {@link SchemaFromSelf}. + * Decoding accepts exactly one identifier. Encoding quotes symbol and base-URL identifiers. {@link make} validates the decoded object rather than source text. Arbitrary generation uses the decoded {@link SchemaFromSelf}. */ export const Schema: $Schema.decodeTo< typeof SchemaFromSelf, @@ -81,29 +79,38 @@ export const Schema: $Schema.decodeTo< }), ); +/** + * The decoded form of an identifier, with its kind in `_tag` and its value without backticks. + * + * A `Lexical` value is a Unicode identifier, either `XID_Start XID_Continue*` or `_` followed by at least one `XID_Continue` character. A `Symbol` value is one or more ASCII operator characters, `!#$%&*+-./<=>?@\^|~[]`, or non-ASCII punctuation and symbols, such as `+` or `==`. A `BaseUrl` value is an `http` or `https` URL ending in `/`, checked for spelling rather than validity. An object written directly is unchecked until {@link make} validates it. + */ export type Ident = (typeof Schema)["Type"]; +/** Identifier source text, with backticks around a quoted symbol or base URL. */ export type Encoded = (typeof Schema)["Encoded"]; +/** Input accepted by {@link make} before validation: an identifier object, not source text. */ type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Constructs an identifier from its tagged object representation. + * Checks an identifier object, such as `{ _tag: "Symbol", value: "+" }`, against its kind's pattern. * - * @throws {Error} If `value` is not valid for the given kind. + * Use {@link decodeResult} for source text. When `_tag` is omitted, the result takes the kind whose pattern matches `value`. + * + * @throws {Error} If `value` is not valid for the given kind. The error's `cause` is a {@link SchemaIssue.Issue}. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Ident = SchemaParser.make(Schema); -/** Constructs an identifier with schema failures in the error channel. */ +/** Checks an identifier object like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Constructs an identifier, returning `None` if validation fails. */ +/** Checks an identifier object like {@link make}, returning `None` if validation fails. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, @@ -116,12 +123,34 @@ export const fromScanned = (scanned: Scan.ScanIdent): Ident => ({ value: scanned.value, }); +/** + * Decodes exactly one identifier from source text. + * + * A symbol can be bare or backticked. A base URL must be backticked. Any other text, including surrounding whitespace or a `::` separator, fails with a {@link SchemaIssue.Issue} in the returned `Result`. + * + * @example Decode an operator and print it back. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * import { Result } from "effect"; + * + * const plus = Result.getOrThrow(JExpr.Ident.decodeResult("+")); + * assert.deepEqual(plus, { _tag: "Symbol", value: "+" }); + * assert.equal(JExpr.Ident.compile(plus), "`+`"); + * assert.ok(Result.isFailure(JExpr.Ident.decodeResult("user.name"))); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const decodeResult: ( input: string, options?: ParseOptions, ) => Result = SchemaParser.decodeResult(Schema); +/** + * Writes an identifier as source text. + * + * A lexical value is written as is. A symbol or base URL is wrapped in backticks, so the bare `+` decodes and compiles to `` `+` ``. The value is not validated. + */ export const compile = (ident: Ident): string => { if (ident._tag === "Lexical") { return ident.value; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts index fac3248a271..0eac28462fa 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts @@ -10,7 +10,7 @@ export const Schema: typeof Defs.Identifier = Defs.Identifier; /** * Source text interpreted as a path, type or argument shorthand. * - * The schema accepts any string. HashQL parses it according to its position in the expression. For example, `"user"` is a path and `":user"` is a labeled-argument shorthand in a call. + * The schema accepts any string, including the empty string. HashQL parses it according to its position in the expression. In an expression position, `"user"` is a path, `"user.name"` and `"items[0]"` access a field and an element, and `"_"` is a placeholder. In a call argument, `":user"` is shorthand for the labeled argument `{":user": "user"}`. A type position reads the text as type syntax. For a single identifier object, see `JExpr.Ident`. */ export type Identifier = Defs.IdentifierType; /** The schema-encoded representation of {@link Identifier}. */ @@ -20,9 +20,9 @@ export type Encoded = Defs.IdentifierEncoded; type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Accepts source text for a string expression. + * Accepts any string as a string expression. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * The schema has no checks, so this confirms only that the input is a string. HashQL parses the text when it compiles the program. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -32,7 +32,7 @@ export const make: ( options?: $Schema.MakeOptions, ) => Identifier = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, @@ -40,7 +40,7 @@ export const makeEffect: ( ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts index a7ced381c8a..d2eca78c7d0 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts @@ -8,16 +8,17 @@ import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; export const Schema: typeof Defs.Integer = Defs.Integer; /** - * An arbitrary-precision integer's decimal source text. + * An arbitrary-precision integer's decimal source text, stored in a literal's `#literal` field. * - * `value` uses JSON integer syntax, such as `"-42"`. It has no fraction or exponent. Keeping the text avoids JavaScript's numeric precision limit. + * `value` uses JSON integer syntax, such as `"-42"`. It has no fraction or exponent. Keeping the text avoids JavaScript's numeric precision limit, but a `number` loses precision before `JExpr.integer` reads it. Pass a `bigint` for integers beyond `Number.MAX_SAFE_INTEGER`. * - * @example + * @example Keep an integer beyond JavaScript's safe range. * ```ts - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * - * JExpr.compile(JExpr.integer(42)); // => '{"#literal":42}' - * JExpr.compile(JExpr.integer(2n ** 64n)); // => '{"#literal":18446744073709551616}' + * assert.equal(JExpr.compile(JExpr.integer(2n ** 64n)), '{"#literal":18446744073709551616}'); + * assert.equal(JExpr.compile(JExpr.integer(2 ** 53 + 1)), '{"#literal":9007199254740992}'); * ``` */ export interface Integer extends Defs.IntegerType {} @@ -28,9 +29,9 @@ export interface Encoded extends Defs.IntegerEncoded {} type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks the spelling of an integer literal. + * Checks that `value` is an integer in JSON number syntax, such as `-42`. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * Leading zeros, a fraction and an exponent fail. `_tag` may be omitted, and the result supplies it. `options.disableChecks` skips the spelling check and keeps only the object's shape. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -38,7 +39,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Integer = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, @@ -46,7 +47,7 @@ export const makeEffect: ( ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts index 4c54f62fbe7..d9476a7b8e5 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts @@ -10,7 +10,7 @@ export const Schema: typeof Defs.LabeledArgument = Defs.LabeledArgument; /** * A call argument labeled with a parameter name. * - * The object has exactly one key: `:` followed by an identifier. The value is an expression. The argument still occupies a position in the call's argument list. + * The object has exactly one key: `:` followed by an identifier. The value is an expression. It can appear anywhere after the function in a call array, and HashQL's parser gathers it into the call's labeled arguments rather than its positional ones. */ export interface LabeledArgument extends Defs.LabeledArgumentType {} /** The schema-encoded representation of {@link LabeledArgument}. */ @@ -20,9 +20,9 @@ export interface Encoded extends Defs.LabeledArgumentEncoded {} type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks a single labeled argument and its value. + * Checks a labeled argument's single key and its value. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * The object needs exactly one key, `:` followed by an identifier, and an expression as its value. `options.disableChecks` skips the key checks along with the checks inside the value. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -32,7 +32,7 @@ export const make: ( options?: $Schema.MakeOptions, ) => LabeledArgument = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, @@ -40,7 +40,7 @@ export const makeEffect: ( ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts index 3c0c265592b..add1db5c2b7 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts @@ -22,7 +22,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; /** * Checks list elements and an optional type annotation. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * Each element must be an expression, and `#type` can be any text. The result is a new list. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,14 +30,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => List = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts index 52788b09542..bf2b94d41de 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts @@ -10,7 +10,7 @@ export const Schema: typeof Defs.Literal = Defs.Literal; /** * A primitive value in a `#literal` constructor. * - * Numeric values use {@link Defs.Integer} or {@link Defs.Float} to preserve their source text. Strings, booleans and `null` appear directly under `#literal`. + * Numeric values are tagged `JExpr.Integer` or `JExpr.Float` objects that preserve their source text. Strings, booleans and `null` appear directly under `#literal`, and a string here is a string value rather than a name. `#type` holds optional annotation text. */ export interface Literal extends Defs.LiteralType {} /** The schema-encoded representation of {@link Literal}. */ @@ -20,9 +20,9 @@ export interface Encoded extends Defs.LiteralEncoded {} type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks a literal and an optional type annotation. + * Checks a literal's value and an optional type annotation. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * A string, boolean or `null` value is accepted as is. A numeric value must be a tagged integer or float object with valid spelling, and its `_tag` may be omitted. `#type` can be any text. `options.disableChecks` skips the numeric spelling check. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,7 +30,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Literal = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, @@ -38,7 +38,7 @@ export const makeEffect: ( ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts index 4257d1fce1c..470aa6dce31 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts @@ -1,7 +1,7 @@ /** * HashQL paths with an optional root and a nonempty sequence of identifiers. * - * {@link SchemaFromSelf} validates path objects and supports schema-derived arbitrary generation. {@link Schema} decodes source text without treating `::` inside a quoted identifier as a separator. + * {@link SchemaFromSelf} validates path objects and supports schema-derived arbitrary generation. {@link Schema} and {@link decodeResult} decode source text without treating `::` inside a quoted identifier as a separator, and {@link compile} writes it back. Path text is narrower than a string expression, which can also hold field access, index access or generic arguments. * * @module */ @@ -56,36 +56,49 @@ export const Schema: $Schema.decodeTo< }), ); +/** + * The decoded form of a path, with its root flag and its identifier segments in order. + * + * `rooted` is `true` for a leading `::`, as in `::core::math`. `segments` holds at least one identifier object from `JExpr.Ident`. An object written directly is unchecked until {@link make} validates it. + */ export interface Path extends $Schema.Schema.Type {} /** Source text representing a {@link Path}, including quotes and separators. */ export type Encoded = $Schema.Codec.Encoded; +/** Input accepted by {@link make} before validation: a path object, not source text. */ type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Constructs a path from its object representation. + * Checks a path object, requiring at least one segment and a valid identifier in each. * - * @throws {Error} If a segment is not a valid identifier. + * Use {@link decodeResult} for source text. + * + * @throws {Error} If a segment is not a valid identifier or `segments` is empty. The error's `cause` is a {@link SchemaIssue.Issue}. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Path = SchemaParser.make(Schema); -/** Constructs a path with schema failures in the error channel. */ +/** Checks a path object like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Constructs a path, returning `None` if validation fails. */ +/** Checks a path object like {@link make}, returning `None` if validation fails. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Option.Option = SchemaParser.makeOption(Schema); +/** + * Writes a path as source text. + * + * Segments are joined by `::`, with a leading `::` for a rooted path, and each segment is written like `JExpr.Ident.compile`, with backticks around a symbol or base URL. Whitespace that decoding accepted around separators is not kept. The segments are not validated. + */ export const compile = (path: Path): string => { const segments = path.segments .map((segment) => Ident.compile(segment)) @@ -98,12 +111,31 @@ export const compile = (path: Path): string => { return segments; }; +/** + * Decodes path text into a {@link Path}. + * + * The text is an optional leading `::` followed by `::`-separated identifiers, with whitespace allowed around each separator. A backticked base URL, such as `` `https://example.com/a::b/` ``, can contain `::`. Surrounding whitespace, an empty segment, generic arguments such as `List` and field access such as `user.name` fail with a {@link SchemaIssue.Issue} in the returned `Result`. + * + * @example Decode a rooted operator path. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; + * import { Result } from "effect"; + * + * const add = Result.getOrThrow(JExpr.Path.decodeResult("::core :: math::+")); + * assert.ok(JExpr.Path.isAbsolute(add)); + * assert.equal(JExpr.Path.compile(add), "::core::math::`+`"); + * assert.ok(Result.isFailure(JExpr.Path.decodeResult("List"))); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const decodeResult: ( input: string, options?: ParseOptions, ) => Result = SchemaParser.decodeResult(Schema); +/** Whether the path starts with `::`. */ export const isAbsolute = (path: Path): boolean => path.rooted; +/** Whether the path has no leading `::`. */ export const isRelative = (path: Path): boolean => !path.rooted; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts index 4e05eb93fc8..9a6ef5251ba 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts @@ -4,7 +4,7 @@ import * as Defs from "./schema.js"; import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; -/** Schema for {@link Struct} values. */ +/** Schema for `Struct` values. */ export const Schema: typeof Defs.Struct = Defs.Struct; /** @@ -13,7 +13,7 @@ export const Schema: typeof Defs.Struct = Defs.Struct; * Each field contains an expression. The schema checks the field names as well as their values. */ export interface Struct extends Defs.StructType {} -/** The schema-encoded representation of {@link Struct}. */ +/** The schema-encoded representation of `Struct`. */ export interface Encoded extends Defs.StructEncoded {} /** Input accepted by {@link make} before validation. */ @@ -22,7 +22,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; /** * Checks field names, field expressions and an optional type annotation. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * Field names must be identifiers, such as `name` or `` `+` ``. Field values must be expressions. `#type` can be any text. The result is a new struct. `options.disableChecks` skips the field-name check and the checks inside nested values. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,14 +30,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Struct = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts index 56358629898..09c23d5688e 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts @@ -4,7 +4,7 @@ import * as Defs from "./schema.js"; import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; -/** Schema for {@link Tuple} values. */ +/** Schema for `Tuple` values. */ export const Schema: typeof Defs.Tuple = Defs.Tuple; /** @@ -13,7 +13,7 @@ export const Schema: typeof Defs.Tuple = Defs.Tuple; * An empty tuple is valid. HashQL determines each element's type. */ export interface Tuple extends Defs.TupleType {} -/** The schema-encoded representation of {@link Tuple}. */ +/** The schema-encoded representation of `Tuple`. */ export interface Encoded extends Defs.TupleEncoded {} /** Input accepted by {@link make} before validation. */ @@ -22,7 +22,7 @@ type MakeIn = (typeof Schema)["~type.make.in"]; /** * Checks tuple elements and an optional type annotation. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. + * Each element must be an expression, and `#type` can be any text. The result is a new tuple. `options.disableChecks` skips the identifier, label and numeric-spelling checks inside nested values but keeps the structural requirements. Use {@link makeOption} to test validity or {@link makeEffect} to retain the validation issue. * * @throws {Error} If validation fails. The error's `cause` is a {@link SchemaIssue.Issue}. */ @@ -30,14 +30,14 @@ type MakeIn = (typeof Schema)["~type.make.in"]; export const make: (input: MakeIn, options?: $Schema.MakeOptions) => Tuple = SchemaParser.make(Schema); -/** Runs {@link make} validation with schema issues in the effect's error channel. */ +/** Checks a value like {@link make}, failing the synchronous effect with the issue instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, options?: $Schema.MakeOptions, ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Runs {@link make} validation, returning `None` for a schema failure. */ +/** Checks a value like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts index 236449fb41a..3cadd26e580 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts @@ -56,18 +56,20 @@ const isPositional = ( !Object.keys(argument).every((key) => key.startsWith(":")); /** - * Renders an expression tree as compact J-Expr JSON. + * Writes an expression tree as compact J-Expr JSON text. * - * Numeric literals keep their stored spelling: an integer retains its full precision and an integral float retains its fraction or exponent. `JSON.stringify` would serialize the SDK's tagged numeric objects instead. + * Each numeric literal is written from its stored text, so an integer keeps every digit and a float keeps its fraction or exponent. `JSON.stringify` would write the SDK's tagged numeric objects instead, which HashQL rejects because a `#literal` value must be a JSON primitive. Strings are JSON-escaped, and object keys follow each object's own enumerable string-key order. A call argument whose keys all start with `:` is written as a labeled argument. * - * Validation is separate. Use `JExpr.make` on the tree before compiling it when you need schema checks. + * Serialization does not validate. A literal that `JExpr.make` would reject keeps its stored text, so the output can contain non-JSON text such as `NaN`. An object without a constructor key throws a `TypeError`. Check a tree from an untrusted source with `JExpr.make` before compiling it. * - * @example + * @example Serialize exact numbers, unlike JSON.stringify. * ```ts - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * - * JExpr.compile(JExpr.list(JExpr.float(1), JExpr.float(2.5))); - * // => '{"#list":[{"#literal":1.0},{"#literal":2.5}]}' + * const values = JExpr.tuple(JExpr.integer(2n ** 64n), JExpr.float(1), JExpr.float(2.5)); + * assert.equal(JExpr.compile(values), '{"#tuple":[{"#literal":18446744073709551616},{"#literal":1.0},{"#literal":2.5}]}'); + * assert.equal(JSON.stringify(JExpr.integer(1)), '{"#literal":{"_tag":"Integer","value":"1"}}'); * ``` */ export const compile = (expression: Expression): string => { diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts index 96522b32e65..5c656420e41 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts @@ -1,20 +1,22 @@ /** - * Builds HashQL queries as J-Expr expression trees. + * Builds, checks and serializes raw HashQL J-Expr syntax. * - * A string such as `"user"` refers to a value by name. Use {@link literal} for data: `literal("user")` is the string value `"user"`. Arrays represent calls, while objects with keys such as `#list` or `#struct` construct data. + * J-Expr is HashQL's JSON notation. Arrays are calls, objects keyed by `#literal`, `#struct`, `#tuple`, `#list` or `#dict` construct data, and strings are source text that HashQL parses as a name, path or type. The string `"user"` therefore refers to a value by name. Use {@link literal} for data: `literal("user")` is the string value `"user"`. * - * @example - * ```ts - * import * as JExpr from "./index.js"; + * The builders return the SDK's {@link Expression} tree, not J-Expr text. The tree stores each numeric literal as tagged source text, such as `{ _tag: "Integer", value: "42" }`, to keep integers beyond JavaScript's precision and the distinction between `1` and `1.0`. {@link compile} writes the tree as J-Expr JSON, where those literals become bare JSON numbers. `JSON.stringify` and {@link Schema} encoding keep the tagged objects, so neither produces J-Expr. * - * const query = JExpr.let("name", JExpr.literal("Alice"), "name"); - * JExpr.compile(JExpr.make(query)); - * // => '["let","name",{"#literal":"Alice"},"name"]' - * ``` + * Builders such as {@link literal}, {@link struct} and {@link call} assemble syntax without validating it, and nothing in this module executes a query. {@link make} checks a finished tree against {@link Schema} and throws on failure. {@link makeEffect} keeps the issue in an Effect, and {@link makeOption} returns `None`. The schema checks structure, identifier-named fields and labels, and numeric spelling. It does not parse string expressions or `#type` annotations, resolve names or check types. The HashQL compiler does that when it receives the program. + * + * Builders that take a type, such as {@link input} and {@link typed}, accept type syntax, which `TypeExpression.toType` extracts from a declared type expression. `Ident` and `Path` decode and print single identifiers and paths. Each constructor also has a namespace, such as `Literal` or `Call`, holding its schema, value type and checked `make` functions. * - * The helpers assemble expressions without validating them. Use {@link make} to check the finished tree and {@link compile} to produce JSON text. {@link makeEffect} retains validation issues in an Effect, and {@link makeOption} returns only success or failure. The schema checks the tree's structure. Parsing strings as paths or types, resolving names and type checking belong to the HashQL compiler. + * @example Bind a value, check the tree and serialize it. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * - * Use {@link compile} even when the tree looks like ordinary JSON. Numeric literals retain their source text to preserve large integers and the distinction between `1` and `1.0`. + * const query = JExpr.make(JExpr.let("name", JExpr.literal("Alice"), "name")); + * assert.equal(JExpr.compile(query), '["::kernel::special_form::let","name",{"#literal":"Alice"},"name"]'); + * ``` * * @module */ @@ -49,13 +51,17 @@ export * as Path from "./Path.js"; export { compile } from "./compile.js"; /** - * Schema for the SDK's expression-tree representation. + * Effect schema for the SDK's {@link Expression} tree. * - * Encoding produces {@link Encoded}, including tagged numeric literals. Use {@link compile} to produce J-Expr JSON text. + * Decoding and {@link make} check the tree's structure, identifier-named struct fields and labels, and numeric literal spelling. They accept any string expression and any `#type` text. The encoded form, {@link Encoded}, keeps the tagged numeric literals, so use {@link compile} to produce J-Expr JSON text. */ export const Schema: typeof Defs.Expression = Defs.Expression; -/** A J-Expr expression: a call, a data constructor or a string. */ +/** + * An SDK expression tree: a call array, a data constructor object or a string expression. + * + * A string is source text that HashQL parses, such as `"user"`, `"entity.properties"` or the placeholder `"_"`, rather than a string value. Numeric literals hold tagged source text, so serialize a tree with {@link compile} rather than `JSON.stringify`. + */ export type Expression = Defs.ExpressionType; /** The schema-encoded tree, with the same tagged numeric literals as {@link Expression}. */ @@ -65,21 +71,24 @@ export type Encoded = Defs.ExpressionEncoded; type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Checks an expression tree against {@link Schema}. + * Checks an expression tree against {@link Schema} and returns the checked tree. * - * Validates by default. `options.disableChecks` skips schema checks. Use {@link makeOption} when only validity matters, or {@link makeEffect} to inspect a {@link SchemaIssue.Issue} with the failing node's location. + * The result is a new tree without keys outside the matched constructor. Numeric literal objects may omit `_tag`, which the result supplies. `options.disableChecks` skips the identifier, label and numeric-spelling checks but still requires the tree's structure. `options.parseOptions` passes Effect parse options, such as `onExcessProperty: "error"` to reject unknown keys. Use {@link makeOption} when only validity matters, or {@link makeEffect} to inspect a {@link SchemaIssue.Issue} with the failing node's location. * * @throws {Error} If validation fails. The error carries a {@link SchemaIssue.Issue} in its `cause`. * - * @example + * @example Check a struct and detect an invalid field name. * ```ts + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * import { Option } from "effect"; - * import * as JExpr from "./index.js"; * - * const query = JExpr.make(JExpr.struct({ name: JExpr.literal("Alice") })); - * JExpr.compile(query); // => '{"#struct":{"name":{"#literal":"Alice"}}}' + * const person = JExpr.make(JExpr.struct({ name: JExpr.literal("Alice") })); + * assert.equal(JExpr.compile(person), '{"#struct":{"name":{"#literal":"Alice"}}}'); * - * Option.isNone(JExpr.makeOption(JExpr.struct({ "not an ident": "x" }))); // => true + * const invalid = JExpr.struct({ "not an ident": JExpr.literal("x") }); + * assert.ok(Option.isNone(JExpr.makeOption(invalid))); + * assert.throws(() => JExpr.make(invalid), { message: "Schema validation failed" }); * ``` */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive @@ -88,7 +97,7 @@ export const make: ( options?: $Schema.MakeOptions, ) => Expression = SchemaParser.make(Schema); -/** Checks a tree with {@link make}'s options, retaining schema issues in the effect's error channel. */ +/** Checks a tree like {@link make}, failing the synchronous effect with the {@link SchemaIssue.Issue} instead of throwing. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeEffect: ( input: MakeIn, @@ -96,7 +105,7 @@ export const makeEffect: ( ) => Effect.Effect = SchemaParser.makeEffect(Schema); -/** Checks a tree with {@link make}'s options, returning `None` for a schema failure. */ +/** Checks a tree like {@link make}, returning `None` instead of throwing for a schema failure. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const makeOption: ( input: MakeIn, @@ -115,9 +124,9 @@ export type Annotatable = | Defs.LiteralType; /** - * Creates a whole-number literal without a size limit for `bigint` inputs. + * Creates an integer literal from a value's exact decimal digits. * - * Use a `bigint` for integers beyond `Number.MAX_SAFE_INTEGER`. A `number` may already have lost precision before this call. It must be an integer to pass {@link make} validation. See {@link Integer.Integer} for a precision example. + * A `bigint` keeps every digit. A `number` is converted from its double value, so an integer beyond `Number.MAX_SAFE_INTEGER` may already have lost precision before this call, and `-0` becomes `0`. A non-integral or non-finite number is stored as its JavaScript text without an error. {@link make} rejects that literal, while {@link compile} emits the text, such as `1.5` or `NaN`. See `JExpr.Integer.Integer` for a precision example. */ export const integer = (value: number | bigint): Defs.LiteralType => { if (typeof value === "number" && Number.isInteger(value)) { @@ -130,7 +139,7 @@ export const integer = (value: number | bigint): Defs.LiteralType => { /** * Creates a numeric literal that HashQL parses as a float. * - * A float's JSON spelling must contain a fraction or exponent. Integral values therefore retain a fraction: `float(1)` compiles to `1.0`. Negative zero compiles to `-0.0`. `NaN` and infinities fail {@link make} validation. See {@link compile} for float examples. + * The text is JavaScript's shortest decimal for the double, so `float(0.1 + 0.2)` compiles to `0.30000000000000004`. HashQL reads a number as a float only when its text has a fraction or exponent. Integral values therefore gain a fraction: `float(1)` compiles to `1.0` and `-0` to `-0.0`. Magnitudes that JavaScript writes in exponent form keep it, such as `1e+21`. `NaN` and infinities are stored without an error. {@link make} rejects them, and {@link compile} emits text that is not JSON. See {@link compile} for float examples. */ export const float = (value: number): Defs.LiteralType => { if (Object.is(value, -0)) { @@ -149,7 +158,7 @@ export const float = (value: number): Defs.LiteralType => { /** * Creates a literal from a primitive value. * - * Integral numbers and `bigint` values become {@link integer} literals. Other numbers become {@link float} literals. Use {@link float} explicitly to keep `1` as `1.0` or preserve negative zero. See {@link make} for a string literal example. + * A string becomes a string value, unlike a bare string expression. Every `bigint` and every integral number, including `1.0`, `-0` and `1e21`, becomes an {@link integer} literal. Other numbers become {@link float} literals. Use {@link float} explicitly to keep `1` as `1.0` or preserve negative zero. See {@link make} for a string literal example. */ export const literal = ( value: string | number | bigint | boolean | null, @@ -172,7 +181,7 @@ export const literal = ( /** * Creates a list whose elements share a type. * - * HashQL infers the element type. Use {@link tuple} when each position needs its own type. See {@link compile} for a list example. + * HashQL infers the element type. Use {@link tuple} when each position needs its own type. */ export const list = (...items: readonly Expression[]): Defs.ListType => ({ "#list": items, @@ -186,7 +195,7 @@ export const tuple = (...items: readonly Expression[]): Defs.TupleType => ({ /** * Creates a struct with named fields. * - * Field names must be identifiers, such as `name` or `` `+` ``. Each field has its own type. Use {@link dict} for arbitrary string keys. Fields follow the record's own enumerable string-key order. See {@link make} for a struct example. + * Field names must be identifiers, such as `name`, `+` or `` `+` ``, which {@link make} checks and this builder does not. Each field has its own type. Use {@link dict} for arbitrary string keys. Fields follow the record's own enumerable string-key order. The tree holds the given record object rather than a copy. See {@link make} for a struct example. */ export const struct = ( fields: Record.ReadonlyRecord, @@ -195,7 +204,7 @@ export const struct = ( /** * Creates a dictionary from string keys or key expressions. * - * Record keys are literal strings, even when they look like paths. Use `[key, value]` pairs to compute keys from expressions. See {@link Dict.Dict} for examples of both key forms. + * Record keys are literal strings, even when they look like paths. JavaScript puts integer-like record keys first in ascending order, and {@link compile} keeps that order. Use `[key, value]` pairs to compute keys from expressions or to control their order. The tree holds the given record or array rather than a copy. See `JExpr.Dict.Dict` for examples of both key forms. */ export const dict = ( entries: @@ -206,17 +215,17 @@ export const dict = ( /** * Sets a data constructor's type annotation. * - * Replaces any existing `#type` annotation. Calls and paths cannot carry this field. Use {@link asType | as} to assert their types. + * Returns a shallow copy with `#type` set, replacing any existing annotation, and leaves `self` unchanged. The annotation is the type's annotation text, such as `(name: String)`, which HashQL parses and checks. Calls and paths cannot carry this field. Use {@link asType | as} to assert their types. Call it data-first as `typed(self, type)` or data-last in a pipeline. * - * @example + * @example Annotate a literal with a declared type. * ```ts - * import { Option, pipe } from "effect"; - * import * as Type from "./type/index.js"; - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import { Result, pipe } from "effect"; * - * const float = Option.getOrThrow(Type.reference("Float")); - * JExpr.compile(pipe(JExpr.literal(3.14), JExpr.typed(float))); - * // => '{"#literal":3.14,"#type":"Float"}' + * const number = Result.getOrThrow(TypeExpression.toType(Prelude.builtin.types.Number)); + * const annotated = pipe(JExpr.literal(3.14), JExpr.typed(number)); + * assert.equal(JExpr.compile(annotated), '{"#literal":3.14,"#type":"::kernel::type::Number"}'); * ``` */ export const typed: { @@ -233,7 +242,7 @@ export const typed: { /** * Creates a labeled argument for {@link call}, such as `{":name": value}`. * - * Give `name` without the leading `:`. It must be an identifier. The argument remains positional in the call's argument list. See {@link call} for a labeled call example. + * Give `name` without the leading `:`. It must be an identifier, which {@link make} checks and this builder does not. The object keeps its place in the call array. HashQL's parser gathers labeled arguments into their own list, so this one takes no positional slot. See {@link call} for a labeled call example. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument export const label = ( @@ -244,14 +253,15 @@ export const label = ( /** * Builds a call to a function expression. * - * `fn` can be a path or an expression that produces a function, including a closure from {@link fn}. Arguments keep their supplied order, including those created with {@link label}. + * `fn` can be a path or an expression that produces a function, including a closure from {@link fn}. Arguments keep their supplied order in the array, including those created with {@link label}. Neither this builder nor {@link make} checks the function's arity or argument types. * - * @example + * @example Call a function with a positional and a labeled argument. * ```ts - * import * as JExpr from "./index.js"; + * import assert from "node:assert/strict"; + * import { JExpr } from "@local/hashql"; * - * JExpr.compile(JExpr.call("greet", JExpr.label("name", JExpr.literal("Alice")))); - * // => '["greet",{":name":{"#literal":"Alice"}}]' + * const greeting = JExpr.call("greet", "user", JExpr.label("style", JExpr.literal("formal"))); + * assert.equal(JExpr.compile(greeting), '["greet","user",{":style":{"#literal":"formal"}}]'); * ``` */ export const call = ( @@ -262,7 +272,7 @@ export const call = ( /** * Selects a branch according to a Boolean expression. * - * HashQL evaluates only the selected branch. Without `otherwise`, the query produces HashQL's `Some(then)` when the condition is true and `None` when it is false. + * Both branches are already built syntax, so this call runs no host code for either of them. HashQL evaluates only the selected branch when the query runs. Without `otherwise`, or with `otherwise` set to `undefined`, the expression produces HashQL's `Some(then)` when the condition is true and `None` when it is false. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument const conditional = ( @@ -282,7 +292,7 @@ export { conditional as if }; /** * Binds `value` to `name` within `body`. * - * Use {@link asType | as} on `value` to give it an explicit type. + * `name` is emitted as given, and the HashQL compiler checks that it is an identifier. Use {@link asType | as} on `value` to give it an explicit type. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument const binding = ( @@ -296,7 +306,7 @@ export { binding as let }; /** * Asserts an expression's type for the HashQL type checker. * - * The assertion constrains the expression's type without converting its value. Use {@link typed} to put an annotation directly on a data constructor. + * The assertion constrains the expression's type without converting its value. A compound type is emitted as constructor syntax, such as a `::kernel::type::Union` call or a `#struct` of types, rather than annotation text. Use {@link typed} to put an annotation directly on a data constructor. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument const asType = (value: Expression, type: Type.Type): Defs.CallType => [ @@ -310,7 +320,7 @@ export { asType as as }; /** * Items to import into the body of {@link use}. * - * Use `"*"` for all items or an array for named imports. For aliases, supply a record from original name to local name: `{ entities: "allEntities" }` imports `entities` as `allEntities`. The alias `"_"` keeps the original name. + * Use `"*"` for all items or an array for named imports. For aliases, supply a record from original name to local name: `{ entities: "allEntities" }` imports `entities` as `allEntities`. The alias `"_"` keeps the original name. An array becomes a `#tuple` of names and a record becomes a `#struct`, whose keys {@link make} checks as identifiers. */ export type Imports = | "*" @@ -333,7 +343,7 @@ const compileImports = (imports: Imports): Expression => { /** * Imports items from the module at `path` into `body`. * - * {@link Imports} describes wildcard imports, named imports and aliases. + * `path` is path text, such as `::core::math`, which the HashQL compiler resolves. {@link Imports} describes wildcard imports, named imports and aliases. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument export const use = ( @@ -350,7 +360,18 @@ export const use = ( /** * Reads a named query input supplied by the host. * - * Without `defaultValue`, the host must supply the input. Otherwise, HashQL evaluates `defaultValue` when the input is absent. + * Without `defaultValue`, or with `defaultValue` set to `undefined`, the host must supply the input. Otherwise, HashQL evaluates `defaultValue`, asserted as `type`, when the input is absent. Obtain `type` from a declared type expression with `TypeExpression.toType`. + * + * @example Read an optional page size. + * ```ts + * import assert from "node:assert/strict"; + * import { JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import { Result } from "effect"; + * + * const integer = Result.getOrThrow(TypeExpression.toType(Prelude.builtin.types.Integer)); + * const pageSize = JExpr.input("page_size", integer, JExpr.integer(10)); + * assert.equal(JExpr.compile(pageSize), '["::kernel::special_form::input","page_size","::kernel::type::Integer",{"#literal":10}]'); + * ``` */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument export const input = ( @@ -373,7 +394,7 @@ export const input = ( /** * Selects a named field or a tuple position. * - * Give a field identifier as a string or a zero-based tuple position as a number. Use {@link index} when the selector is an expression. Path strings such as `"entity.properties"` provide shorthand for named field access. + * Give a field identifier as a string or a zero-based tuple position as a number. A number becomes an {@link integer} literal, so a non-integral position fails {@link make}. Use {@link index} when the selector is an expression. A string expression such as `"entity.properties"` is HashQL shorthand for the same named field access. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument export const access = ( @@ -410,7 +431,7 @@ const compileName = (name: string | Reference.Reference): string => { /** * Introduces a type alias in `body`. * - * The alias denotes the same type as `type`. Use {@link newtype} for a distinct nominal type with a constructor. `name` accepts type syntax such as `"Pair"`, or a {@link Reference.Reference} declaring generic parameters. + * The alias denotes the same type as `type`. Use {@link newtype} for a distinct nominal type with a constructor. `name` is text emitted as given, such as `"Pair"`, or reference type syntax, which compiles to the same form. Its generic list declares the alias's parameters, such as `T` or `T: Integer`. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructor, not an operation on its first argument const typeAlias = ( diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts index c74aedba209..547b3b5c7fc 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts @@ -59,7 +59,7 @@ const LabelKey: Schema.TemplateLiteral = /** * A labeled call argument, such as `{":name": value}`. * - * A labeled argument is positional: it occupies its place in the argument list like any other argument. + * It can appear anywhere after the function in a call array. HashQL's parser gathers labeled arguments into their own list, so a labeled argument takes no positional slot. */ export const LabeledArgument: Schema.$Record = Schema.Record(LabelKey, ExpressionRef).check( diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts index 3e0a05cc3c5..fc23c97f03e 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts @@ -40,9 +40,7 @@ export const argument = (type: Defs.Type): Defs.GenericArgumentType => ({ /** * Creates a named generic constraint: the `T: Integer` in `Foo`. * - * Returns `None` if `name` is not a valid identifier according to - * {@link Ident.decodeResult}. Without a bound, it compiles to the bare name, which - * the backend reads as a generic argument. + * Returns `None` if `name` is not a valid identifier according to `Ident.decodeResult`. Without a bound, it compiles to the bare name, which HashQL parses as a generic argument. A declaration name such as `Pair` reads that bare name as an unbounded parameter. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- false positive export const bound = ( diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts index 59ec7550f6d..f48b728cccd 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts @@ -6,6 +6,11 @@ import type { Schema as $Schema, Effect, Option, SchemaIssue } from "effect"; export const Schema: typeof Defs.Reference = Defs.Reference; +/** + * Type syntax naming a type by its decoded path, with its generic entries in order. + * + * `JExpr.type` and `JExpr.newtype` also accept a reference as a declaration name. There its generic list declares parameters: a bare name such as `T` is an unbounded parameter and `T: Integer` a bounded one. + */ export interface Reference extends Defs.ReferenceType {} export interface Encoded extends Defs.ReferenceEncoded {} diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts index 093e81663ff..1c769224a27 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts @@ -1,9 +1,9 @@ /** - * Builds HashQL type expressions for J-Expr queries. + * Builds HashQL type syntax for J-Expr queries. * - * A {@link Type} describes type syntax. Use {@link reference} for a named type and {@link struct}, {@link tuple}, {@link union} or {@link intersection} to compose types. {@link compile} renders the result as a J-Expr type expression. + * A {@link Type} is tagged type syntax. Use {@link reference} for a named type and {@link struct}, {@link tuple}, {@link union} or {@link intersection} to compose types. The syntax has two J-Expr spellings. {@link compile} writes annotation text for a `#type` field, and {@link toExpression} writes the constructor syntax that `as`, `input`, `fn`, `type` and `newtype` emit. * - * {@link reference} and {@link struct} return an {@link Option.Option}: an invalid name produces `None`. Name resolution and type checking belong to the HashQL compiler. + * {@link reference} and {@link struct} return an {@link Option.Option}: an invalid name produces `None`. The other builders accept their members without checks. Name resolution and type checking belong to the HashQL compiler. * * @module */ @@ -36,16 +36,16 @@ export * as Union from "./Union.js"; export const Schema: typeof Defs.Type = Defs.Type; /** - * A HashQL type expression with validated identifiers. + * Tagged HashQL type syntax, as accepted by `JExpr.input`, `JExpr.as`, `JExpr.typed` and the other builders that take a type. * - * The `_tag` discriminant selects the type's syntactic form. {@link compile} renders the expression without resolving its names or checking relationships between types. + * The `_tag` discriminant selects the form. `Reference` names a type by path with optional generics, `Struct` and `Tuple` list named or positional members, and `Union` and `Intersection` combine member types. Paths and member names are decoded identifier objects. `TypeExpression.toType` extracts this syntax from a declared type expression. Nothing validates an object written directly until {@link make} checks its names, and the HashQL compiler resolves those names and checks the type. */ export type Type = Defs.Type; /** - * The tagged object representation of a {@link Type}, with unbranded identifiers. + * The schema-encoded form of a {@link Type}, which writes each path and member name as source text. * - * {@link Schema} encodes and decodes this representation. Use {@link compile} for a J-Expr type expression. + * A reference's path becomes text such as `"::core::List"`, and a struct member name becomes text such as `` "`+`" ``. The rest keeps its tagged objects. {@link Schema} encodes and decodes this form, and neither form is J-Expr. Use {@link compile} or {@link toExpression} for J-Expr. */ export type Encoded = Defs.TypeEncoded; @@ -53,13 +53,13 @@ export type Encoded = Defs.TypeEncoded; type MakeIn = (typeof Schema)["~type.make.in"]; /** - * Constructs a type from its tagged object representation. + * Checks a tagged type object, including its decoded paths and names, and returns a new value. * - * Validates the input against {@link Schema} by default. `options.disableChecks` skips schema checks. {@link makeOption} returns `None` for validation failures, and {@link makeEffect} preserves the issue in its error channel. + * Validates the input against {@link Schema} by default. `options.disableChecks` skips the identifier checks but still requires the tagged structure. {@link makeOption} returns `None` for validation failures, and {@link makeEffect} preserves the issue in its error channel. * * @throws {Error} If construction fails. A schema-validation error carries a {@link SchemaIssue.Issue} in its `cause`. * - * @example + * @example Construct and check tagged type syntax. * ```ts * import { Effect, Option } from "effect"; * import * as Type from "./index.js"; @@ -117,7 +117,7 @@ export const makeOption: ( * * Preserves member order, duplicates and nested unions. Use {@link or} to combine types while flattening union operands. * - * @example + * @example Build a union without flattening. * ```ts * import { Option } from "effect"; * import * as Type from "./index.js"; @@ -137,7 +137,7 @@ export const union = ( * * Preserves member order, duplicates and nested intersections. Use {@link and} to combine types while flattening intersection operands. * - * @example + * @example Build an intersection. * ```ts * import { Option } from "effect"; * import * as Type from "./index.js"; @@ -157,9 +157,9 @@ const asReadonlyUnsafe = (input: T): Readonly => input; /** * Creates a type with named fields. * - * Returns `None` if any field name is not a valid identifier according to {@link Ident.decodeResult}. Symbol names accept bare (`+`) or backticked (`` `+` ``) spelling. Fields follow the record's own enumerable string-key order. An empty record produces an empty struct, which {@link compile} renders as `(:)`. + * Returns `None` if any field name is not a valid identifier according to `Ident.decodeResult`. Symbol names accept bare (`+`) or backticked (`` `+` ``) spelling. Fields follow the record's own enumerable string-key order. An empty record produces an empty struct, which {@link compile} renders as `(:)`. * - * @example + * @example Build a struct type and reject an invalid field name. * ```ts * import { Option } from "effect"; * import * as Type from "./index.js"; @@ -199,7 +199,7 @@ export const struct = ( * * An empty tuple compiles to `()`. A single-member tuple keeps a trailing comma to distinguish it from a parenthesized type. * - * @example + * @example Build empty, single-member and pair tuples. * ```ts * import { Option } from "effect"; * import * as Type from "./index.js"; @@ -218,11 +218,11 @@ export const tuple = (...members: readonly Type[]): Defs.TupleType => ({ /** * Refers to a named type with optional generic arguments or bounds. * - * `path` uses path syntax, such as `Integer`, `core::math::add` or `::core::math::+`. Returns `None` if {@link Path.parse} rejects it. Validation checks syntax only. The HashQL compiler resolves the name and checks its generic arguments. + * `path` uses path syntax, such as `Integer`, `core::math::add` or `::core::math::+`. Returns `None` if `Path.decodeResult` rejects it, including text with generic arguments such as `List`. Validation checks syntax only. The HashQL compiler resolves the name and checks its generic arguments. * - * A plain {@link Type} supplies a positional generic argument. An explicit {@link Defs.GenericType} preserves its argument or named-bound form. Generic order follows the argument list. + * A plain {@link Type} supplies a positional generic argument. An explicit `GenericArgument` or `GenericBound` object from the `Generic` module keeps its form. Generic order follows the argument list. * - * @example + * @example Refer to generic, bounded and rooted types. * ```ts * import { Option } from "effect"; * import * as Generic from "./Generic.js"; @@ -286,7 +286,7 @@ const intersectionMembers = (type: Type): NonEmptyReadonlyArray => { * * Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat union when the initial operands have no nested unions. Use {@link union} to preserve nesting. * - * @example + * @example Chain unions with flattening. * ```ts * import { Option } from "effect"; * import { pipe } from "effect/Function"; @@ -316,7 +316,7 @@ export const or: { * * An intersection operand contributes its immediate members. Members of `self` precede members of `that`. Duplicates remain. Chained calls produce a flat intersection when the initial operands have no nested intersections. Use {@link intersection} to preserve nesting. * - * @example + * @example Chain intersections with flattening. * ```ts * import { Option } from "effect"; * import { pipe } from "effect/Function"; @@ -369,7 +369,7 @@ const compileGeneric: (generic: Defs.GenericType) => Identifier = * * Unions and intersections with more than one member always retain parentheses to preserve grouping in nested expressions. A single-member union or intersection compiles as its member. Empty structs use `(:)`, empty tuples use `()`, and single-member tuples retain a trailing comma. * - * @example + * @example Compile a nested type. * ```ts * import { Option } from "effect"; * import * as Type from "./index.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts index 65362a24186..bb8700ccb20 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts +++ b/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts @@ -16,7 +16,9 @@ export const Union: Schema.TaggedStruct< members: Schema.NonEmptyArray(TypeRef), }); +/** Type syntax for a value of at least one member type, with annotation text `(A | B)`. */ export interface UnionType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link UnionType}, with nested paths and names as source text. */ export interface UnionEncoded extends Schema.Codec.Encoded {} export const Intersection: Schema.TaggedStruct< @@ -26,9 +28,11 @@ export const Intersection: Schema.TaggedStruct< members: Schema.NonEmptyArray(TypeRef), }); +/** Type syntax for a value of every member type, with annotation text `(A & B)`. */ export interface IntersectionType extends Schema.Schema.Type< typeof Intersection > {} +/** The schema-encoded form of {@link IntersectionType}, with nested paths and names as source text. */ export interface IntersectionEncoded extends Schema.Codec.Encoded< typeof Intersection > {} @@ -40,7 +44,9 @@ export const Struct: Schema.TaggedStruct< members: Schema.Array(Schema.Tuple([Ident.Schema, TypeRef])), }); +/** Type syntax for named fields, holding decoded name and type pairs in order. Its annotation text is `(name: T)`, or `(:)` when empty. */ export interface StructType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link StructType}, with field names, paths and nested names as source text. */ export interface StructEncoded extends Schema.Codec.Encoded {} export const Tuple: Schema.TaggedStruct< @@ -50,7 +56,9 @@ export const Tuple: Schema.TaggedStruct< members: Schema.Array(TypeRef), }); +/** Type syntax for positional members, with annotation text `(A, B)`, `(A,)` or `()`. */ export interface TupleType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link TupleType}, with nested paths and names as source text. */ export interface TupleEncoded extends Schema.Codec.Encoded {} export const GenericArgument: Schema.TaggedStruct< @@ -60,9 +68,11 @@ export const GenericArgument: Schema.TaggedStruct< bound: TypeRef, }); +/** A positional generic argument, such as the `Integer` in `List`. */ export interface GenericArgumentType extends Schema.Schema.Type< typeof GenericArgument > {} +/** The schema-encoded form of {@link GenericArgumentType}, with nested paths and names as source text. */ export interface GenericArgumentEncoded extends Schema.Codec.Encoded< typeof GenericArgument > {} @@ -78,9 +88,11 @@ export const GenericBound: Schema.TaggedStruct< bound: TypeRef.pipe(Schema.optionalKey), }); +/** A named generic parameter with an optional bound, such as the `T: Integer` in `List`. */ export interface GenericBoundType extends Schema.Schema.Type< typeof GenericBound > {} +/** The schema-encoded form of {@link GenericBoundType}, with its name, paths and nested names as source text. */ export interface GenericBoundEncoded extends Schema.Codec.Encoded< typeof GenericBound > {} @@ -91,7 +103,9 @@ export const Generic: Schema.toTaggedUnion< > = Schema.Union([GenericArgument, GenericBound]).pipe( Schema.toTaggedUnion("_tag"), ); +/** An entry in a reference's generic list: a positional argument or a named bound. */ export type GenericType = (typeof Generic)["Type"]; +/** The schema-encoded form of {@link GenericType}. */ export type GenericEncoded = (typeof Generic)["Encoded"]; export const Reference: Schema.TaggedStruct< @@ -102,7 +116,9 @@ export const Reference: Schema.TaggedStruct< generics: Schema.Array(Generic), }); +/** Type syntax naming a type by its decoded path, with its generic entries in order. */ export interface ReferenceType extends Schema.Schema.Type {} +/** The schema-encoded form of {@link ReferenceType}, with its path and nested names as source text. */ export interface ReferenceEncoded extends Schema.Codec.Encoded< typeof Reference > {} @@ -120,12 +136,14 @@ export const Type: Schema.toTaggedUnion< Schema.toTaggedUnion("_tag"), ); +/** Tagged type syntax: a union, intersection, struct, tuple or reference. */ export type Type = | UnionType | IntersectionType | StructType | TupleType | ReferenceType; +/** The schema-encoded form of {@link Type}, with paths and names as source text. */ export type TypeEncoded = | UnionEncoded | IntersectionEncoded diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index 2de56977d8e..a6cd6662ff0 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,3 +1,12 @@ +/** + * Typed HashQL syntax construction and J-Expr encoding. + * + * Use `@local/hashql/draft` for synchronous authoring with an explicit input schema, or `@local/hashql/do` for ordered declaration steps and inferred input requirements. Both produce typed expressions. {@link Expression} also provides direct construction, and {@link Program} wraps a root expression for serialization. + * + * {@link Type} describes semantic types at compile time. {@link TypeExpression} carries their syntax at runtime. {@link Module} declares trusted external names, and {@link JExpr} provides the lower-level syntax model. The SDK builds programs but does not execute them. Its type declarations require TypeScript 7. + * + * @module + */ export * as JExpr from "./jexpr/index.js"; export * as Expression from "./program/Expression.js"; export * as Module from "./program/Module.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts index 947033227e1..0433c3e1d3d 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Expression.ts @@ -7,6 +7,7 @@ * * @module */ +// oxlint-disable max-lines -- expression constructors and their API examples belong with the private handle metadata and proxy machinery // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods import { Function, Predicate, Result, Schema, identity, pipe } from "effect"; @@ -32,6 +33,7 @@ interface Variance { readonly _Inputs: Types.Contravariant; } +/** Host literals accepted without an explicit expression wrapper: strings, numbers, bigints, booleans and null. */ export type Primitive = Type.Primitive["value"]; type InputAlternatives = E extends Primitive @@ -57,15 +59,20 @@ export interface Any extends Relocatable { readonly [Binding]: Result.Result; } +/** Semantic metadata and stored construction result shared by expressions and adapted callables. */ export interface Handle extends Any { readonly [TypeId]: Variance; readonly [Relocate]: Relocatable>[typeof Relocate]; } +/** An expression or host literal accepted by syntax-only operations such as {@link toJExpr}. */ export type AnyValue = Any | Primitive; -/** Accepts an exactly typed handle or the corresponding host primitive. */ -/** Argument compatibility needs semantic metadata, not the original callable or rebinding signature. */ +/** + * An exactly typed handle or the host primitive corresponding to its semantic descriptor. + * + * Argument compatibility uses the semantic metadata that adapted callables retain. Integer operands accept bigint and Integer handles. TypeScript rejects a host number at that position rather than widening its descriptor. + */ export type Value = | (Any & Pick, typeof TypeId | typeof Binding>) | (T extends Type.Primitive ? T["value"] : never); @@ -110,12 +117,35 @@ class ExpressionImpl { } } -/** A symbolic HashQL value with type-directed projection, indexing and calls. */ +/** + * A symbolic HashQL value with type-directed projection, indexing and calls. + * + * `T` describes the represented value, not its host wrapper. `Inputs` records the inputs needed to evaluate it. Fields and tuple positions project to new expressions. Use `$project` for fields whose names collide with SDK operations. Lists and dictionaries expose `$index`, whose result includes Null for a missing entry. Callable descriptors expose a host call that constructs HashQL call syntax. + * + * Property access and calls construct syntax without reading data or executing the represented function. Extract that syntax or its retained construction failure with {@link toJExpr}. + * + * @example Project a field from a typed input. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Structural } from "@local/hashql"; + * import { Result } from "effect"; + * + * const account = Expression.input("account", Structural.type({ active: Boolean })); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(account.active)), + * Result.getOrThrow(Expression.toJExpr(account.$project("active"))), + * ); + * ``` + */ export type Expression = Handle & Accessors & Callable; -/** Recognizes expression handles without checking their semantic types. */ +/** + * Recognizes the private expression marker without checking the stored result or semantic type. + * + * Use this to distinguish SDK handles from host literals, not to validate untrusted objects. + */ // oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values export const isExpression = (value: unknown): value is Any => Predicate.hasProperty(value, Binding); @@ -133,6 +163,11 @@ const parseNode = ( }), }); +/** + * Extracts a handle's stored AST result or validates a host literal into an AST node. + * + * Existing construction failures pass through unchanged. Invalid primitive syntax, including non-finite numbers, returns an `InvalidExpression` failure. Prefer {@link toJExpr} when consuming J-Expr syntax rather than builder nodes. + */ export const toNode = ( value: AnyValue, ): Result.Result => { @@ -142,7 +177,11 @@ export const toNode = ( return parseNode(JExpr.literal(value)); }; -/** Extracts syntax without evaluating the represented value. */ +/** + * Extracts J-Expr syntax without evaluating the represented value. + * + * A failed handle returns its stored construction error. Host literals undergo the same syntax validation as {@link literal}. Serialize the resulting structured syntax with `JExpr.compile`, or wrap the expression with `Program.program` and use `Program.compile`. + */ export const toJExpr = ( value: AnyValue, ): Result.Result => @@ -251,6 +290,11 @@ const make = ( return handle as Expression; }; +/** + * Wraps an AST construction result while retaining either its node or its failure. + * + * This low-level builder operation trusts the caller to establish `T`, `Inputs` and the node's validity. Use {@link fromJExpr} when syntax needs validation. + */ export const fromResult = ( node: Result.Result, ): Expression => make(new ExpressionImpl(node)); @@ -258,12 +302,13 @@ export const fromResult = ( /** * Ascribes a semantic type to syntax supplied by a declaration or another trusted builder. * - * The caller supplies the semantic type and input requirements. This operation validates syntax only. + * The caller supplies the semantic type and input requirements. This operation validates syntax only and stores an `InvalidExpression` construction failure if validation fails. Extract it with {@link toJExpr}. It does not resolve names or infer requirements from the syntax. */ export const fromJExpr = ( expression: JExpr.Expression, ): Expression => fromResult(parseNode(expression)); +/** Wraps an already constructed AST node without validation, using caller-supplied semantic metadata as in {@link fromResult}. */ export const fromNode = ( node: AST.Node, ): Expression => fromResult(Result.succeed(node)); @@ -276,7 +321,36 @@ export type Adapted = C & /** * Adapts host arguments while preserving expression metadata and rebinding. * - * The adapter must retain the represented function's meaning. It may accept additional host shorthand and normalize it before emitting a call. The factory receives the rebound expression on each relocation, so its calls cannot retain an earlier path. Metadata is copied explicitly because it need not be enumerable on a forwarding proxy. + * The adapter must retain the represented function's meaning. It may accept additional host shorthand and normalize it before emitting a call. The factory runs immediately and again with the new source expression on each relocation. Build the returned callable from that argument rather than capturing an older expression. Exceptions from the factory or returned callable propagate to their caller. + * + * Both `adaptCallable(source, factory)` and `adaptCallable(factory)(source)` preserve the source's semantic type and input metadata. The replacement host signature comes from the factory. + * + * @example Accept trimmed host text when constructing a lookup call. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression } from "@local/hashql"; + * import type { Inputs, Type } from "@local/hashql"; + * import { Result, pipe } from "effect"; + * + * const lookup = Expression.fromJExpr< + * Type.Function, + * Inputs.Empty + * >("lookup"); + * const trimmedLookup = Expression.adaptCallable(lookup, (source) => + * (name: string) => source(name.trim()), + * ); + * const pipedLookup = pipe(lookup, Expression.adaptCallable((source) => + * (name: string) => source(name.trim()), + * )); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(trimmedLookup(" Ada "))), + * ["lookup", { "#literal": "Ada" }], + * ); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(pipedLookup(" Ada "))), + * Result.getOrThrow(Expression.toJExpr(trimmedLookup(" Ada "))), + * ); + * ``` */ export const adaptCallable: { Any>( @@ -306,29 +380,79 @@ export const adaptCallable: { ); /** - * Changes the SDK's type assumption without changing the query syntax. + * Changes an expression's semantic type assumption while preserving its syntax and input requirements. + * + * The caller establishes the semantic type `T` through a trusted declaration or other knowledge outside the SDK. The returned function accepts an expression or host primitive without validating that semantic type at runtime or converting the value. It emits no HashQL type assertion. The HashQL compiler still checks the resulting program. * - * This performs no validation or conversion and emits no HashQL type assertion. + * @example Annotate an identifier whose meaning the application establishes. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Prelude } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type UserId = Type.Opaque<"example::UserId", Type.PrimitiveString>; + * const text = Expression.input("userId", Prelude.builtin.types.String); + * const userId = Expression.assume()(text); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(userId)), + * Result.getOrThrow(Expression.toJExpr(text)), + * ); + * ``` */ export const assume = () => (expression: E): Expression> => fromResult>(toNode(expression)); +/** + * Constructs a typed host literal with no input requirements. + * + * Use a string to construct a string literal rather than a name reference. A host number has the Number descriptor even when its emitted syntax is integral. Bigints have the Integer descriptor. Non-finite numbers produce an `InvalidExpression` failure retained until {@link toJExpr}. Objects and arrays need structural construction instead. + */ export const literal = ( value: V, ): Expression, Input.Empty> => fromJExpr(JExpr.literal(value)); +/** + * Constructs an Integer literal from a bigint or integral host number. + * + * Fractions and non-finite numbers produce an `InvalidExpression` construction failure. Use bigint when the original integer exceeds the safe number range, because a number has already undergone JavaScript rounding. See {@link toJExpr} to inspect success or failure. + */ export const integer = ( value: number | bigint, ): Expression => fromJExpr(JExpr.integer(value)); +/** Constructs a Number literal, retaining non-finite values as construction failures as in {@link literal}. */ export const number = ( value: number, ): Expression => fromJExpr(JExpr.literal(value)); +/** + * References a program input, optionally supplying its default expression. + * + * The inferred {@link Inputs} record requires the input when you omit the default or pass `undefined`. A definitely present default makes this occurrence optional, but another required use of the same name takes precedence. If the default's type includes `undefined`, the input remains required. Requirements of the default expression also contribute to the result. + * + * @param name - The input name emitted into the program. + * @param type - The input's HashQL type, which also constrains the default. + * @param defaultValue - The value or expression used when the input is absent at query execution. + * @returns A symbolic reference. Use {@link toJExpr} to extract the syntax or its construction failure. + * + * @example Supply a default page size. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { Result } from "effect"; + * + * const pageSize = Expression.input("pageSize", Prelude.builtin.types.Integer, 10n); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(pageSize))), + * '["::kernel::special_form::input","pageSize","::kernel::type::Integer",{"#literal":10}]', + * ); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs an input from its name and type export function input( name: Name, @@ -372,7 +496,24 @@ export function input( }).pipe(fromResult); } -/** Constructs a conditional whose result type combines its branch types. */ +/** + * Constructs a conditional whose result type combines its branch types. + * + * The caller constructs all three operands before this call, without host short-circuiting. The result retains the condition's requirements and those of both branches, even for a literal condition. Either branch can contribute a construction failure. Equal branch descriptors remain equal, while distinct descriptors form a normalized union. + * + * @example Select a label in the represented program. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Program } from "@local/hashql"; + * import { Result } from "effect"; + * + * const label = Expression.ifElse(true, { then: "enabled", else: "disabled" }); + * assert.equal( + * Result.getOrThrow(Program.compile(Program.program(label))), + * '["::kernel::special_form::if",{"#literal":true},{"#literal":"enabled"},{"#literal":"disabled"}]', + * ); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the condition and branches construct a new expression export const ifElse = < const Condition extends Value, diff --git a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts index 2742572988d..371d548682a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts @@ -323,16 +323,23 @@ type IndexAccessor = [Descriptor] extends [IndexDescriptor] } : EmptyAccessors; +/** + * Projection and indexing operations selected by an expression's semantic descriptor. + * + * Struct fields and tuple positions support property access and `$project`. For unions and intersections, a projected field must exist in every member. `$project` also accepts operation names such as `$index` when they name actual fields. List and dictionary `$index` calls merge the key's inputs and include Null in the result for an absent element. Opaque descriptors expose the operations of their underlying type. + */ export type Accessors = ProjectionAccessors< FieldsOf>, Inputs > & IndexAccessor>, Inputs>; +/** Host arguments accepted at each semantic parameter position, including corresponding primitive shorthand. */ export type Arguments = { readonly [Index in keyof Parameters]: Expression.Value; }; +/** Combined input requirements of a call's argument tuple, retaining requirements from optional positions. */ export type ArgumentInputs = Input.All<{ readonly [Index in keyof Values]: Expression.Inputs; @@ -342,6 +349,11 @@ type ArgumentTypes = { readonly [Index in keyof Values]: Expression.TypeOf; }; +/** + * Host call signatures that construct calls to fixed or generic HashQL functions. + * + * Fixed signatures constrain each argument by its declared descriptor. Generic signatures apply the argument descriptors to the declared type-level function. Both forms merge the callee's input requirements with those of every argument. Non-function descriptors contribute no call signature. + */ export type Callable = T extends Type.Function ? >( @@ -362,6 +374,7 @@ export type Callable = > : EmptyAccessors; +/** The normalized union of two conditional branch descriptors, retaining a single descriptor when both are equal. */ export type Conditional = Join< Normalize, Normalize diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.ts b/libs/@local/hashql/sdk/typescript/src/program/Import.ts index f47bbe4445f..f7d631ccefa 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Import.ts @@ -18,15 +18,52 @@ import type * as Module from "./Module.js"; import type * as Namespace from "./Namespace.js"; import type { ReadonlyRecord } from "effect/Record"; +/** The string export names of a module across its three tables. */ type Name = Extract< keyof M["modules"] | keyof M["values"] | keyof M["types"], string >; + +/** + * The exports an import brings into scope and the local names they take. + * + * - `"*"` imports every own name in the module's three tables. + * - An array of export names imports those names unchanged. + * - A record maps export names to local aliases. The alias `"_"` keeps the export's own name. + * + * One name selects the module, type and value exports that share it. Each imported export emits its local name, and the import wraps the expression built in its scope in a `use` of the module's path. An alias that is not a HashQL identifier, or a symbol key in the record, fails construction with `InvalidImportName`. + * + * @example Import a built-in function under another name. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const { math } = Prelude.builtin.modules; + * const result = program({}, ($) => { + * const { plus } = $.import(math, { add: "plus" }); + * return plus(1n, 2n); + * }); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Result.flatMap(result, Expression.toJExpr))), + * '["::kernel::special_form::use","::core::math",{"#struct":{"add":"plus"}},["plus",{"#literal":1},{"#literal":2}]]', + * ); + * + * const invalid = program({}, ($) => { + * $.import(math, { add: "not an identifier" }); + * return $.literal(true); + * }); + * assert.ok(Result.isFailure(invalid)); + * assert.equal(invalid.failure.reason._tag, "InvalidImportName"); + * ``` + */ export type Selection = | "*" | readonly Name[] | Partial, string>>; +/** Filters and renames one table according to a selection. */ type Selected = I extends "*" ? E : I extends readonly string[] @@ -41,6 +78,7 @@ type Selected = I extends "*" : never]: E[K]; }; +/** The tables an import adds to a scope, keyed by local name and keeping each selected export's type. */ export interface Imported { readonly modules: Selected; readonly values: Selected; @@ -146,6 +184,7 @@ const plan = ( interface Capability extends Relocatable {} type Rebindings = { readonly [K in keyof E]: Relocatable }; +/** A module whose exports each rebind to their own type, as an import requires. */ export interface Rebindable { readonly modules: M["modules"] & Rebindings; readonly types: M["types"] & Rebindings; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts index e118638c143..ecad227c0af 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts @@ -17,7 +17,11 @@ export type Empty = Record; declare const ErasedRequirement: unique symbol; -/** Named input schemas cannot discharge unrecoverable requirements. */ +/** + * Marks input requirements that TypeScript could not recover. + * + * Requirement inference produces this marker when an expression's requirement record is `never` or `unknown`, or when a value lacks the SDK's requirement metadata. No input schema has the marker key, so a Draft program schema cannot satisfy an erased requirement. Merging it with a named requirement gives `never`. + */ export interface Erased { readonly [ErasedRequirement]: Type.Unknown; } @@ -72,7 +76,11 @@ type Collapse = [U] extends [never] MergeRecords>> >; -/** Requires every host-side alternative, preserving shared semantic constraints. */ +/** + * Requires every host-side alternative, preserving shared semantic constraints. + * + * A union of requirement records becomes one record that requires each name any alternative requires. `never` and `unknown` become {@link Erased}. + */ export type Conservative = [I] extends [never] ? Erased : // oxlint-disable-next-line typescript/no-restricted-types -- this type-level check detects erased metadata rather than storing a runtime value @@ -91,7 +99,42 @@ type MergeRight = [keyof R] extends [never] ? L : MergeConservative, R>; -/** Combines shared requirements, preserving the left type when the right side needs no inputs. */ +/** + * Combines shared requirements, preserving the left type when the right side needs no inputs. + * + * A name stays optional in the result only when every side that mentions it marks it optional. Where both sides mention a name, the result takes the intersection of its descriptors. + * + * @example Type-only: combine a defaulted use with a required use. + * ```ts + * import type { Inputs, Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * export const requiredWins: Equal< + * Inputs.Merge< + * { readonly limit?: Type.PrimitiveInteger }, + * { + * readonly limit: Type.PrimitiveInteger; + * readonly name: Type.PrimitiveString; + * } + * >, + * { + * readonly limit: Type.PrimitiveInteger; + * readonly name: Type.PrimitiveString; + * } + * > = true; + * export const conflictIsNever: Equal< + * Inputs.Merge< + * { readonly id: Type.PrimitiveInteger }, + * { readonly id: Type.PrimitiveString } + * >, + * { readonly id: Type.Never } + * > = true; + * ``` + */ export type Merge = MergeRight>; /** Combines tuple members, retaining every possible requirement in arrays and optional positions. */ diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/program/Module.ts index f3b000c5df9..937102f7b9a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Module.ts @@ -1,8 +1,12 @@ /** * Typed declarations bound to absolute HashQL paths. * + * A module record describes exports that the HashQL environment provides under one path. Defining it emits no syntax and creates nothing in HashQL. Its declarations emit references beneath that path for the HashQL compiler to resolve, and importing a module emits a `use` of its path. + * * Modules keep type and value exports separate because a type and its constructor can share a name. Existing exports are aliases: selecting or regrouping one never changes its reference. Declarations supply trusted type information. The HashQL compiler checks the emitted query. * + * Expected construction failures, such as an invalid path or export name, arrive in a `Result`. + * * @module */ import { Predicate, Result, flow, pipe } from "effect"; @@ -24,7 +28,11 @@ import type { ReadonlyRecord } from "effect/Record"; const Declare: unique symbol = Symbol("~hashql/ModuleDeclaration"); const TypeId: unique symbol = Symbol("~hashql/Module"); -/** A declaration waiting for the module to supply its absolute export path. */ +/** + * A declaration waiting for the module to supply its absolute export path. + * + * {@link value}, {@link type} and {@link genericType} create declarations. {@link define} binds each one to the export `E` it describes. + */ export interface Declaration { readonly [Declare]: ( path: JExpr.Path.Path, @@ -39,16 +47,28 @@ type Declarations = { readonly [K in keyof E]: Declaration | E[K]; }; -/** A module with its concrete export names erased. */ +/** + * A module with its concrete export names erased. + * + * The type and value tables are separate namespaces, so one name can hold both a type and its value constructor. + */ export interface Any extends Relocatable { readonly [TypeId]: true; + /** The path under which the module binds its exports. */ readonly path: JExpr.Path.Path; + /** Child modules by local name. */ readonly modules: Namespace; + /** Type expressions and generic type constructors by export name. */ readonly types: Namespace; + /** Value expressions by export name. */ readonly values: Namespace; } -/** Named declarations and existing exports to assemble into a module. */ +/** + * Named declarations and existing exports to assemble into a module. + * + * Each table is optional. The type and value tables accept declarations or existing exports, and the module table accepts modules that are already bound. + */ export interface Definition { readonly modules?: Namespace; readonly types?: Namespace< @@ -57,6 +77,7 @@ export interface Definition { readonly values?: Namespace | Expression.Any>; } +/** A table with no names. */ // oxlint-disable-next-line typescript/no-generated-empty-object-type -- an absent namespace intentionally has no known members type Empty = Record; @@ -70,6 +91,7 @@ type Entries = K extends keyof S /** Distributes over alternatives so an optional declaration also unwraps when present. */ type Export = D extends Declaration ? E : D; +/** Replaces each declaration in a table with the export it binds to. */ type Exports = { readonly [K in keyof D]: Export; }; @@ -77,9 +99,13 @@ type Exports = { /** Bound tables retain their key-to-export relationships independently of the source declarations. */ interface Bound extends Relocatable> { readonly [TypeId]: true; + /** The path under which the module binds its exports. */ readonly path: JExpr.Path.Path; + /** Child modules by local name. */ readonly modules: Readonly; + /** Type expressions and generic type constructors by export name. */ readonly types: Readonly; + /** Value expressions by export name. */ readonly values: Readonly; } @@ -94,27 +120,41 @@ type Rebindable = ? undefined : E & Relocatable; +/** Applies the rebinding requirement to every entry of a table. */ type RebindableEntries = { readonly [K in keyof E]: Rebindable }; +/** Requires every table of a module definition to hold rebindable entries. */ type RebindableDefinition = { readonly [K in keyof S]: K extends keyof Definition ? RebindableEntries : S[K]; }; -/** An immutable module record preserving each export's concrete type. */ +/** + * An immutable module record preserving each export's concrete type. + * + * An omitted table becomes an empty table, and the names of an optional table become optional exports. + */ export interface Module extends Bound< Entries, Exports>, Exports> > {} -/** Recognizes a module assembled by this SDK. */ +/** + * Recognizes a module assembled by this SDK. + * + * The guard checks for the module marker property. A joined namespace name that includes a module also passes, while the record {@link root} returns does not. + */ // oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries export const isModule = (value: unknown): value is Any => Predicate.hasProperty(value, TypeId); -/** Declares a value with trusted semantic type information. */ +/** + * Declares a value with trusted semantic type information. + * + * The bound export emits its absolute path, such as `::core::math::rem`, and requires no inputs. `T` decides which calls, projections and indexing TypeScript accepts, and a function descriptor makes the export callable. Nothing checks that the HashQL value has this type. + */ export const value = (): Declaration< Expression.Expression > => ({ @@ -125,14 +165,22 @@ export const value = (): Declaration< ), }); -/** Declares a named type without expanding it into its structural representation. */ +/** + * Declares a named type without expanding it into its structural representation. + * + * Once bound, the export emits a reference to its absolute path, such as `::core::uuid::Uuid`. TypeScript takes its descriptor `T` on trust. + */ export const type = (): Declaration< TypeExpression.TypeExpression > => ({ [Declare]: flow(TypeExpression.reference, Result.succeed), }); -/** Declares a named generic type with a type-level operation for its result. */ +/** + * Declares a named generic type with a type-level operation for its result. + * + * TypeScript requires `arity` to equal `F["arity"]`. Binding returns an `InvalidTypeArity` failure for an arity that is not a non-negative safe integer. The bound constructor emits applications of the export's path and checks the argument count of each call. + */ export const genericType = ( arity: F["arity"], ): Declaration> => ({ @@ -290,9 +338,43 @@ const bound = < /** * Binds new declarations and retains existing exports by identity. * - * Child modules retain their own paths, including when mounted under an alias. Copying and freezing the records prevents caller mutations from adding or replacing exports afterward. + * `name` must be an absolute path such as `::core::math`. Each declaration binds to that path extended by its key, so a value declared as `rem` emits `::core::math::rem`. An existing type expression, expression or module keeps its identity and the syntax it already emits. Child modules retain their own paths, including when mounted under an alias. Copying and freezing the records prevents caller mutations from adding or replacing exports afterward. The caller's tables are not frozen. + * + * Every own string key becomes an export, including non-enumerable keys and `__proto__`. A key must be a HashQL identifier. Emitted paths quote an operator name such as `%`, as in `` ::core::math::`%` ``. + * + * Invalid paths, export names and generic arities return construction failures. A malformed path returns `InvalidModulePath`, a relative path `RelativeModulePath`, a key that is not an identifier `InvalidExportName`, a symbol key `SymbolExportName` and an invalid generic arity `InvalidTypeArity`. Binding stops at the first failure, checking the module, type and value tables in that order. + * + * TypeScript keeps the namespaces apart: a value declaration cannot enter `types`, and a type declaration cannot enter `values`. Each existing export must rebind to its own type. TypeScript rejects a handle extended through `Object.assign`, because rebinding would drop the added properties. + * + * @example Declare a type and its value constructor under one name. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; * - * Invalid paths, export names and generic arities return construction failures. + * const uuid = Result.getOrThrow( + * Module.define("::core::uuid", { + * types: { Uuid: Module.type() }, + * values: { + * Uuid: Module.value< + * Type.Function + * >(), + * }, + * }), + * ); + * const id = Expression.input("id", uuid.types.Uuid, uuid.values.Uuid("fallback")); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(id))), + * '["::kernel::special_form::input","id","::core::uuid::Uuid",["::core::uuid::Uuid",{"#literal":"fallback"}]]', + * ); + * + * const relative = Module.define("core::uuid", {}); + * assert.ok(Result.isFailure(relative)); + * assert.equal(relative.failure.reason._tag, "RelativeModulePath"); + * ``` */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the module under construction export function define( @@ -346,7 +428,43 @@ export function define< }); } -/** Rebinds a module tree while preserving each export's declared type. */ +/** + * Rebinds a module tree while preserving each export's declared type. + * + * Every export becomes a reference to its name under `path`, including aliases of exports from other modules. Child modules are rebound recursively beneath it. The path can be relative, as it is when an import binds a module under a local name. Each export keeps its descriptor and input requirements even though its syntax becomes a reference. The original module keeps its paths. The first export that cannot be rebound, such as a value whose construction failed, returns its failure. It accepts the module first or last. + * + * @example Rebind an alias and a child module. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * const compile = (value: Expression.Any): string => + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + * const config = Result.getOrThrow( + * Module.define("::core::config", { + * values: { limit: Module.value() }, + * }), + * ); + * const app = Result.getOrThrow( + * Module.define("::app", { + * modules: { settings: config }, + * values: { maximum: config.values.limit }, + * }), + * ); + * assert.equal(compile(app.values.maximum), '"::core::config::limit"'); + * + * const local = Result.getOrThrow( + * Module.relocate(app, Result.getOrThrow(JExpr.Path.decodeResult("local"))), + * ); + * assert.equal(compile(local.values.maximum), '"local::maximum"'); + * assert.equal( + * compile(local.modules.settings.values.limit), + * '"local::settings::limit"', + * ); + * ``` + */ export const relocate: { ( path: JExpr.Path.Path, @@ -359,7 +477,11 @@ export const relocate: { ): Result.Result; } = relocateHandle; -/** Assembles already-bound modules without rebasing their references. */ +/** + * Assembles already-bound modules without rebasing their references. + * + * The result is a frozen `{ modules }` record keyed by the supplied names. It is not a module: it has no path, and {@link isModule} rejects it. Each child keeps its identity and its own path. The record fits any parameter that takes a scope definition, such as a Do or Draft prelude. Names follow the rules and failures of the module table of {@link define}. + */ export const root = >( modules: M, ): Result.Result< diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts index a5f71235548..d47b9d8b4bf 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts @@ -3,8 +3,11 @@ * * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Explicit projection and indexing remain available through `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. * + * Draft's `$.prelude()`, `$.modules()` and `$.import(...)` return these flattened views, while the Do API keeps the value and type tables apart. A name that only optional entries supply is optional, and a module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. + * * @module */ +// oxlint-disable max-lines -- capability joining and scope flattening share producer tracking, export lookup and rebinding machinery import { Function, Result, pipe } from "effect"; import { Relocate } from "../internal/relocation.js"; @@ -24,7 +27,11 @@ interface Capability extends Relocatable {} type RebindableEntry = E extends Capability ? Relocatable : E; -/** Scope exports need string names and producers that preserve their properties during rebinding. */ +/** + * Scope exports need string names and producers that preserve their properties during rebinding. + * + * Draft's `withPrelude` requires this of a custom prelude. An export extended through `Object.assign` fails it, because rebinding would drop the added properties. + */ export type Rebindable = { readonly [N in keyof S]: N extends keyof Scope.Scope ? { @@ -86,7 +93,11 @@ type Combined = WithMetadata< > >; -/** The last relocation signature returns the whole joined capability set. */ +/** + * One name carrying the capabilities of two exports, such as a value constructor and the type it constructs. + * + * Property reads follow the precedence the module introduction states. A call with type arguments reaches the type constructor, and a call with value arguments reaches the value. The last relocation signature returns the whole joined capability set. + */ export type Joined = Combined & { readonly [Components]: readonly [L, R]; } & Relocatable>; @@ -120,7 +131,11 @@ type RequiredNames = | RequiredKeys | RequiredKeys; -/** A guaranteed export in any namespace makes the flattened name required. */ +/** + * The single-object view of a scope, in which each name joins its module, type and value exports. + * + * A guaranteed export in any namespace makes the flattened name required. A name that only optional entries supply is optional. A module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. + */ export type Flatten = { readonly [K in Keys as K extends RequiredNames ? K : never]: Member< Lookup, @@ -143,6 +158,7 @@ interface ModuleScope { readonly types: Empty; readonly values: Empty; } +/** The flattened view of a scope's modules alone, each exposing its child exports directly. */ export type Modules = Flatten>; const combinedHandles = new WeakMap< diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.ts b/libs/@local/hashql/sdk/typescript/src/program/Operators.ts index 6f046f9bde8..8387009c53e 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Operators.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Operators.ts @@ -23,16 +23,24 @@ type Requirements = Inputs.Merge< Expression.Inputs >; +/** + * A Boolean expression with fluent logical composition and a retained input record. + * + * Chaining constructs syntax rather than testing a host condition. Binding the result with a declaration gives an ordinary Boolean expression. Use the standalone operators to continue composing that binding. See {@link eq} for both fluent and pipe-based forms. + */ export interface Predicate extends Expression.Expression< Type.PrimitiveBoolean, I > { + /** Combines this predicate with another Boolean operand, retaining both sets of inputs. */ readonly and: ( other: R, ) => Predicate>>; + /** Constructs a disjunction without short-circuiting host-side operand construction. */ readonly or: ( other: R, ) => Predicate>>; + /** Negates the represented predicate without changing its input requirements. */ readonly not: () => Predicate; readonly [Relocate]: ( path: JExpr.Path.Path, @@ -77,6 +85,7 @@ const predicate = ( }; }; +/** Direct and data-last comparison forms, checking the second supplied operand against the first operand's semantic descriptor. */ interface Comparison { ( right: R, @@ -104,12 +113,33 @@ const comparison = (path: string): Comparison => ): Predicate> => call(path, [left, right]), ); -/** Compares operands with the same semantic descriptor. */ +/** + * Constructs equality between operands with matching semantic descriptors. + * + * `eq(left, right)` checks the right descriptor against the left. `eq(right)(left)` fixes the right descriptor first. Host primitives use their SDK descriptors: use bigint with an Integer expression and number with a Number expression. The result retains both operands' inputs and construction failures. + * + * @example Compose the same predicate with chaining or a pipe. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Operators, Prelude } from "@local/hashql"; + * import { Result, pipe } from "effect"; + * + * const count = Expression.input("count", Prelude.builtin.types.Integer); + * const chained = Operators.eq(count, 1n).and(true).not(); + * const piped = pipe(count, Operators.eq(1n), Operators.and(true), Operators.not); + * assert.deepEqual( + * Result.getOrThrow(Expression.toJExpr(chained)), + * Result.getOrThrow(Expression.toJExpr(piped)), + * ); + * ``` + */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests export const eq: Comparison = comparison("::core::cmp::eq"); +/** Constructs inequality with the same operand constraints and composition forms as {@link eq}. */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the curried form fixes the right descriptor and checks the left; both argument orders have exact-type tests export const ne: Comparison = comparison("::core::cmp::ne"); +/** Direct and data-last forms that combine two Boolean operands and their input requirements. */ interface BooleanCombination { ( right: R, @@ -129,15 +159,20 @@ const combination = (path: string): BooleanCombination => ): Predicate> => call(path, [left, right]), ); +/** Constructs a Boolean conjunction, directly or as `and(right)(left)`, without short-circuiting host construction. */ export const and: BooleanCombination = combination("::core::bool::and"); +/** Constructs a Boolean disjunction, directly or as `or(right)(left)`, without short-circuiting host construction. */ export const or: BooleanCombination = combination("::core::bool::or"); +/** Constructs Boolean negation while retaining the operand's inputs and construction failures. */ export const not = ( expression: E, ): Predicate> => call("::core::bool::not", [expression]); +/** Constructs an equality comparison with true, returning a chainable {@link Predicate}. */ export const isTrue = ( expression: E, ): Predicate> => call("::core::cmp::eq", [expression, true]); +/** Constructs an equality comparison with false, returning a chainable {@link Predicate}. */ export const isFalse = ( expression: E, ): Predicate> => @@ -153,6 +188,11 @@ type Optional = : E : never; +/** + * Compares an optional value with the HashQL `::core::option::None` constructor. + * + * The operand's normalized descriptor must be a union containing that nominal type. Null is a different value and does not satisfy this constraint. The resulting equality expression retains the operand's TypeScript descriptor without narrowing it. + */ export const isNone = ( expression: E & Optional, ): Predicate> => @@ -183,6 +223,7 @@ export interface Operations { readonly isNone: typeof isNone; } +/** The operator functions collected for composition into authoring contexts. */ export const operations: Operations = { eq, ne, diff --git a/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts b/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts index 3b4af2ea455..8e376485335 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts @@ -3,6 +3,8 @@ * * Export types derive from the bound declarations, without a second list of semantic annotations. Generated declarations can supply the same module, type and value tables to Draft.withPrelude. This default includes primitive types, List, Dict, UUID identities, equality and addition. It is not a complete standard-library binding. * + * Draft's `program` constructs with {@link builtin}. The default `Do` of the Do API starts with an empty scope, and `withPrelude(Prelude.builtin)` from that API supplies these names. This module also re-exports the semantic types of the declarations, such as `Prelude.Uuid` and the `Prelude.Arithmetic` signature. + * * @module */ import { Result, pipe } from "effect"; @@ -107,7 +109,11 @@ const math: Module.Module = pipe( Result.getOrThrow, ); -/** Derives exports from declaration tables without repeating their semantic annotations. */ +/** + * The scope type of {@link builtin}. + * + * It derives the export types from the declaration tables without repeating their semantic annotations. + */ export type Builtin = Scope.From<{ readonly modules: { readonly entity: typeof entity; @@ -126,6 +132,55 @@ export type Builtin = Scope.From<{ typeof math.values; }>; +/** + * The built-in declarations as module, type and value tables. + * + * - `types` holds `Integer`, `Number`, `String`, `Boolean`, `Null`, `Unknown`, `Never` and the generic `List` and `Dict`, all under `::kernel::type`. It also holds `Uuid` at `::core::uuid::Uuid` and `EntityUuid` at `::graph::types::knowledge::entity::EntityUuid`. + * - `values` holds the constructors `Uuid` and `EntityUuid` at the same paths as their types, `eq` at `::core::cmp::eq` and `add` at `::core::math::add`. + * - `modules` holds `uuid` at `::core::uuid`, `entity` at `::graph::types::knowledge::entity`, `cmp` at `::core::cmp` and `math` at `::core::math`. The `::kernel::type` module that declares the primitive types is not among them. + * + * `List` and `Dict` accept structural shorthand as well as type expressions, so `List(String)` and `List(Prelude.builtin.types.String)` emit the same type. `eq` accepts operands of any two types, which need not match. `add` accepts Integer and Number operands, as `Prelude.Arithmetic` describes. The SDK takes these signatures on trust, and the HashQL compiler checks the emitted calls. + * + * Draft's `program` constructs with these declarations, while the default `Do` of the Do API starts with none. Draft's `$.prelude()` joins the three tables into one object. There `Uuid` is both the type and its constructor, and the module `cmp` exposes `eq` directly. + * + * @example Use built-in types and functions outside a program callback. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { Result } from "effect"; + * + * const { types, values } = Prelude.builtin; + * const compile = (value: Expression.AnyValue): string => + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(value))); + * + * assert.equal( + * compile(Expression.input("names", types.List(String))), + * '["::kernel::special_form::input","names","::kernel::type::List<::kernel::type::String>"]', + * ); + * assert.equal( + * compile(values.add(Expression.input("offset", types.Integer), 1n)), + * '["::core::math::add",["::kernel::special_form::input","offset","::kernel::type::Integer"],{"#literal":1}]', + * ); + * ``` + * + * @example Use one flattened name as a type and as a value constructor. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude } from "@local/hashql"; + * import { program } from "@local/hashql/draft"; + * import { Result } from "effect"; + * + * const nil = "00000000-0000-0000-0000-000000000000"; + * const result = program({ id: Prelude.builtin.types.Uuid }, ($) => { + * const { Uuid, cmp } = $.prelude(); + * return cmp.eq($.input("id", Uuid), Uuid(nil)); + * }); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Result.flatMap(result, Expression.toJExpr))), + * `["::core::cmp::eq",["::kernel::special_form::input","id","::core::uuid::Uuid"],["::core::uuid::Uuid",{"#literal":"${nil}"}]]`, + * ); + * ``` + */ export const builtin: Builtin = Scope.merge(Scope.empty, { modules: { entity, uuid, cmp, math }, types: { diff --git a/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts b/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts index a4874b7f2b8..0c496c233d0 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts @@ -1,19 +1,22 @@ /** * Semantic operations used by the representative default declarations. * - * Named identities use their absolute HashQL paths. Generic signatures inspect the semantic argument tuple supplied by the expression or type constructor, without widening it to a common element type. + * Named identities use their absolute HashQL paths. Generic signatures inspect the semantic argument tuple supplied by the expression or type constructor, without widening it to a common element type. `Prelude` re-exports these types. * * @module */ import type * as Type from "../type/index.js"; import type { Conditional } from "./ExpressionType.js"; +/** The UUID type, an opaque string named by its HashQL path. */ export type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; +/** The entity identifier type, an opaque wrapper around {@link Uuid}. */ export type EntityUuid = Type.Opaque< "::graph::types::knowledge::entity::EntityUuid", Uuid >; +/** The operation of the built-in `List`, which maps one element type to a list type. */ export interface List extends Type.TypeConstructor { readonly arity: 1; readonly type: this["Target"] extends readonly [infer T extends Type.Any] @@ -21,6 +24,7 @@ export interface List extends Type.TypeConstructor { : never; } +/** The operation of the built-in `Dict`, which maps a key type and a value type to a dictionary type. */ export interface Dict extends Type.TypeConstructor { readonly arity: 2; readonly type: this["Target"] extends readonly [ @@ -31,6 +35,11 @@ export interface Dict extends Type.TypeConstructor { : never; } +/** + * The signature of the built-in `eq`, which compares two operands and returns Boolean. + * + * The operand types need not match. A call with any other number of arguments selects parameters that no argument satisfies. + */ export interface Comparison extends Type.FunctionSignature { readonly type: this["Target"] extends readonly [ infer L extends Type.Any, @@ -40,6 +49,11 @@ export interface Comparison extends Type.FunctionSignature { : Type.Function; } +/** + * The signature of the built-in `add`. + * + * Each operand must be an Integer or a Number. The result is Integer when both operands are Integer, Number when both are Number, and the union of Integer and Number for one of each. Other operands select parameters that no argument satisfies, with a Never result. + */ export interface Arithmetic extends Type.FunctionSignature { readonly type: this["Target"] extends readonly [ infer L extends Type.PrimitiveInteger | Type.PrimitiveNumber, diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts index c7886a837b1..08f394aac75 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts @@ -14,31 +14,55 @@ interface NameFailure { readonly cause: SchemaIssue.Issue; } +/** + * A structured explanation of a construction failure, selected by `_tag`. + * + * Name and syntax failures retain their parser cause. `CallbackException` retains the original thrown value inside `Cause.UnknownError`. HashQL compiler diagnostics and query execution errors belong to later stages, outside this reason type. + */ export type Reason = | Data.TaggedEnum<{ + /** A declaration name is not a valid HashQL identifier. */ InvalidBindingName: NameFailure; + /** An imported name or alias is not a valid HashQL identifier. */ InvalidImportName: NameFailure; + /** A query callback parameter name is not a valid HashQL identifier. */ InvalidParameterName: NameFailure; + /** A module export name is not a valid HashQL identifier. */ InvalidExportName: NameFailure; + /** A module export table has a symbol key rather than a string name. */ SymbolExportName: { readonly name: symbol }; + /** An explicit input schema has a symbol key rather than a string name. */ SymbolInputName: { readonly name: symbol }; + /** A syntax value failed J-Expr schema validation. */ InvalidExpression: { readonly cause: Schema.SchemaError }; + /** A synchronous authoring callback threw a host value. */ CallbackException: { readonly cause: Cause.UnknownError }; + /** A module path failed path parsing. */ InvalidModulePath: NameFailure; + /** A module declaration used a relative path instead of the required absolute path. */ RelativeModulePath: { readonly name: string }; + /** A generic type's declared arity is not a nonnegative safe integer. */ InvalidTypeArity: { readonly arity: number }; + /** A type application supplied a different number of arguments from its declared arity. */ TypeArgumentCount: { readonly expected: number; readonly received: number; }; + /** Structural shorthand received a host constructor outside BigInt, Number, String and Boolean. */ UnsupportedTypeConstructor: { readonly name: string }; }> + /** A generic type constructor lacks its type arguments. */ | { readonly _tag: "UnspecializedTypeConstructor" } + /** A Do block has no terminal expression callback. */ | { readonly _tag: "MissingBlockBody" } + /** A Do expression callback occupies a position before the last step. */ | { readonly _tag: "MisplacedBlockBody" } + /** A Do declaration position contains something other than a supported declaration step. */ | { readonly _tag: "InvalidBlockStep" } + /** An authoring body returned something other than an expression handle. */ | { readonly _tag: "InvalidBodyResult" }; +/** Constructors and matching helpers for the tagged {@link Reason} variants. */ export const Reason: Data.TaggedEnum.Constructor = Data.taggedEnum(); @@ -46,10 +70,26 @@ const ConstructionBase: ReturnType< typeof Data.TaggedError<"ProgramConstructionError"> > = Data.TaggedError("ProgramConstructionError"); -/** Failure to construct a program from declarations or expressions. */ +/** + * Failure to construct a program from declarations or expressions. + * + * Inspect `reason._tag` for handling and `message` for display. A builder returns this error in a Result, either directly or through later syntax extraction. Error constructors create values without throwing them. + * + * @example Handle an invalid numeric literal. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression } from "@local/hashql"; + * import { Result } from "effect"; + * + * const syntax = Expression.toJExpr(Expression.number(Number.NaN)); + * assert.ok(Result.isFailure(syntax)); + * assert.equal(syntax.failure.reason._tag, "InvalidExpression"); + * ``` + */ export class Construction extends ConstructionBase<{ readonly reason: Reason; }> { + /** Retains the invalid declaration name and its parser issue. */ static invalidBindingName( name: string, cause: SchemaIssue.Issue, @@ -59,54 +99,66 @@ export class Construction extends ConstructionBase<{ }); } + /** Identifies an unsupported symbol key in a module's export table. */ static symbolExportName(name: symbol): Construction { return new Construction({ reason: Reason.SymbolExportName({ name }) }); } + /** Identifies an unsupported symbol key in an explicit input schema. */ static symbolInputName(name: symbol): Construction { return new Construction({ reason: Reason.SymbolInputName({ name }) }); } + /** Retains an arity outside the nonnegative safe-integer range. */ static invalidTypeArity(arity: number): Construction { return new Construction({ reason: Reason.InvalidTypeArity({ arity }) }); } + /** Records declared arity and the number of type arguments supplied. */ static typeArgumentCount(expected: number, received: number): Construction { return new Construction({ reason: Reason.TypeArgumentCount({ expected, received }), }); } + /** Identifies a host constructor not supported by structural type shorthand. */ static unsupportedTypeConstructor(name: string): Construction { return new Construction({ reason: Reason.UnsupportedTypeConstructor({ name }), }); } + /** Reports a generic type constructor used before specialization. */ static unspecializedTypeConstructor(): Construction { return new Construction({ reason: Reason.UnspecializedTypeConstructor() }); } + /** Reports a Do block without a terminal expression callback. */ static missingBlockBody(): Construction { return new Construction({ reason: Reason.MissingBlockBody() }); } + /** Reports a Do body callback occurring before the last step. */ static misplacedBlockBody(): Construction { return new Construction({ reason: Reason.MisplacedBlockBody() }); } + /** Reports an unsupported value in a Do declaration position. */ static invalidBlockStep(): Construction { return new Construction({ reason: Reason.InvalidBlockStep() }); } + /** Reports a body result that is not an expression handle. */ static invalidBodyResult(): Construction { return new Construction({ reason: Reason.InvalidBodyResult() }); } + /** Retains a synchronous callback exception without replacing its original cause. */ static callbackException(cause: Cause.UnknownError): Construction { return new Construction({ reason: Reason.CallbackException({ cause }) }); } + /** Human-readable rendering of the reason. Use the reason's tag rather than this wording for programmatic handling. */ override get message(): string { return Reason.$match(this.reason, { InvalidBindingName: ({ name }) => diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/program/Query.ts index 49c00c1188a..2a41af82f21 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Query.ts @@ -1,7 +1,7 @@ /** * Query operations derived from a declared graph-producing function. * - * The graph marker carries the vertex descriptor through filtering and collection. Both authoring APIs read that descriptor from EntityFunction rather than maintaining a separate graph schema. + * Authoring contexts expose `query.entities` when their value declarations contain an `entities` function returning the recognized graph descriptor. The graph marker carries the vertex type through filtering and collection. These operations construct query syntax without contacting a graph service. * * @module */ @@ -22,11 +22,48 @@ type Graph = Type.Opaque< Type.Struct<{ readonly "'marker": Vertex }> >; +/** + * A graph expression with filtering and collection operations that retain its vertex descriptor. + * + * Binding gives an ordinary expression without query methods. Complete filtering and collection before binding the result. The vertex descriptor comes from the declared `entities` function, not from inspecting stored graph data. + * + * @example Build a filtered collection with a declared graph function. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression } from "@local/hashql"; + * import type { Inputs, Type } from "@local/hashql"; + * import { withPrelude } from "@local/hashql/do"; + * import { Result } from "effect"; + * + * type Vertex = Type.Struct<{ readonly active: Type.PrimitiveBoolean }>; + * type Graph = Type.Opaque< + * "::graph::Graph", + * Type.Struct<{ readonly "'marker": Vertex }> + * >; + * const { Do } = withPrelude({ values: { + * entities: Expression.fromJExpr, Inputs.Empty>("entities"), + * } }); + * let calls = 0; + * const result = Do(($) => $.query.entities().filter("item", (item) => { + * calls += 1; + * return item.active; + * }).collect()); + * const syntax = Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)); + * assert.equal(calls, 1); + * assert.ok(Array.isArray(syntax)); + * assert.equal(syntax[0], "::graph::tail::collect"); + * ``` + */ export type Query< T extends Type.Any, Vertex extends Type.Any, Requirements, > = Expression.Expression & { + /** + * Adds a named predicate callback, invoked once during successful construction rather than once per stored vertex. + * + * An invalid graph expression or parameter name skips the callback. A synchronous callback exception becomes a `CallbackException` construction failure. Captured expressions contribute their input requirements. The name identifies the emitted HashQL function's parameter. The compiler owns lexical resolution. + */ readonly filter: < const Predicate extends Expression.Value, >( @@ -39,6 +76,7 @@ export type Query< Vertex, Inputs.Merge> >; + /** Constructs collection into a list of vertices, retaining query inputs and construction failures without executing it. */ readonly collect: () => Expression.Expression< Type.List, Requirements @@ -48,7 +86,7 @@ export type Query< // oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without an entities declaration has no query entry point type Empty = Record; -/** Reads one function's arguments, result, requirements and graph vertex from its semantic metadata. */ +/** Reads the declared `entities` function's arguments, result, requirements and graph vertex, or resolves to `never` when its descriptor does not match. */ export type EntityFunction = S["values"] extends { readonly entities: infer E extends Expression.Any; } @@ -75,6 +113,7 @@ type Entities = < Inputs.Merge["inputs"], ArgumentInputs> >; +/** Query entry points available from a scope's declared graph function, or an empty type for an absent or incompatible declaration. */ export type Context = [EntityFunction] extends [never] ? Empty : { readonly entities: Entities }; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Scope.ts b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts index 20c3d7f29ec..a295ede2dc4 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Scope.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Scope.ts @@ -3,6 +3,8 @@ * * Missing namespace tables introduce no names. Optional tables contribute optional names instead of an arbitrary string index. Merging retains an earlier export when its replacement is optional, and snapshots include non-enumerable own exports without freezing the caller's records. * + * Each scope holds the names available to a construction callback. The prelude supplies the first one, and each declaration step of the Do API merges its names into the scope of the steps after it. Do callbacks receive the value and type tables as separate arguments, while Draft's `$.prelude()` joins them into one object in which a name can hold a module, a type and a value at once. + * * @module */ import type * as Expression from "./Expression.js"; @@ -10,14 +12,24 @@ import type * as Module from "./Module.js"; import type * as TypeExpression from "./TypeExpression.js"; import type { ReadonlyRecord } from "effect/Record"; +/** A table of exports by name, in which an optional name can be absent. */ interface Universe extends ReadonlyRecord {} +/** The module, value and type tables of a construction scope. */ export interface Scope { + /** Modules by local name, the starting points for imports and qualified references. */ readonly modules: Universe; + /** Value expressions by name. */ readonly values: Universe; + /** Type expressions and generic type constructors by name. */ readonly types: Universe; } +/** + * Tables that supply a scope, such as a prelude. + * + * Each table is optional. A module record, the record `Module.root` returns and `Prelude.builtin` all fit. + */ export interface Definition { readonly modules?: Scope["modules"]; readonly values?: Scope["values"]; @@ -27,18 +39,21 @@ export interface Definition { // oxlint-disable-next-line typescript/no-generated-empty-object-type -- an empty namespace has no names type EmptyNames = Record; +/** The names one table of a definition contributes: none when omitted, optional when the table is optional. */ type Names = K extends keyof D ? undefined extends D[K] ? Partial> : NonNullable : EmptyNames; +/** The scope a definition supplies, with an empty table for each omitted one and optional names for each optional one. */ export interface From { readonly modules: Names; readonly values: Names; readonly types: Names; } +/** A scope with no names, which the default Do API starts from. */ export type Empty = From; type RequiredKeys = { @@ -61,6 +76,11 @@ export type Extend = { >]?: Overridden; }; +/** + * The scope that results from adding the names of `A` to `B`. + * + * In each table a name `A` guarantees replaces the earlier entry, and a name `A` declares as optional keeps the earlier entry as an alternative. + */ export interface Merge { readonly modules: Extend>; readonly values: Extend>; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts index ef371bafbfe..ea52197b78c 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/Structural.ts @@ -29,7 +29,11 @@ import type { ReadonlyRecord } from "effect/Record"; interface Fields extends ReadonlyRecord {} -/** Runtime type syntax, host primitive constructors, or structural shorthand. */ +/** + * A type handle, a supported host primitive constructor, a tuple of definitions or a record of field definitions. + * + * `BigInt`, `Number`, `String` and `Boolean` denote their HashQL primitive types. Arrays denote tuples, not lists. Use a declared generic type constructor for lists and dictionaries. See {@link type} for normalization. + */ export type Definition = | TypeExpression.Any | BigIntConstructor @@ -68,7 +72,11 @@ type TupleValues = { readonly [K in keyof T]: Value; }; -/** Structural host values do not implicitly unwrap nominal types. */ +/** + * A value accepted for descriptor `T`, including recursive record and tuple shorthand. + * + * Nominal descriptors require a matching handle rather than their underlying host representation. Lists and dictionaries likewise require expressions. A host array always denotes a tuple. + */ export type Value = | Expression.Value | (T extends Type.Struct @@ -79,6 +87,7 @@ export type Value = interface FieldValues extends ReadonlyRecord {} +/** Expressions and host primitives, recursively nested in tuples or field records. */ export type AnyValue = Expression.AnyValue | readonly AnyValue[] | FieldValues; /** @@ -107,7 +116,11 @@ type RequirementAlternatives = V extends Expression.AnyValue : Input.Conservative<{ [K in keyof V]: Requirements }[keyof V]> : Input.Empty; -/** Recognizes recursive type shorthand without confusing primitive values with constructors. */ +/** + * Recognizes recursive type shorthand without confusing primitive values with constructors. + * + * This dispatch check examines enumerable own string-keyed values and the SDK type marker. It does not validate field names or stored type syntax. Empty records and arrays qualify. Host objects must be acyclic. + */ // oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization export const isDefinition = (value: unknown): value is Definition => { if (TypeExpression.isExport(value)) { @@ -130,7 +143,11 @@ export const isDefinition = (value: unknown): value is Definition => { return Object.values(value).every(isDefinition); }; -/** Recognizes structural value arguments, including expressions with type capabilities too. */ +/** + * Recognizes structural value arguments, including expressions with type capabilities too. + * + * This dispatch check traverses enumerable own string-keyed values without validating field names or stored syntax. Non-finite numbers pass this check too. Validation belongs to {@link value} or {@link toJExpr}. Host objects must be acyclic. + */ // oxlint-disable-next-line typescript/no-restricted-types -- overload dispatch must distinguish arbitrary host arguments before normalization export const isValue = (value: unknown): value is AnyValue => { if (Expression.isExpression(value)) { @@ -245,7 +262,25 @@ const typeSyntax = ( ); }; -/** Normalizes shorthand while retaining invalid names in the construction result. */ +/** + * Constructs a type expression from primitive, tuple and record shorthand. + * + * The descriptor retains each tuple position and record field. Runtime records contribute enumerable own string keys. Invalid field names and failed nested type handles remain construction failures in the returned handle's `syntax` Result. The resulting type description provides no runtime validator for host values. + * + * @example Describe a record with a nested tuple. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Structural } from "@local/hashql"; + * import { Result } from "effect"; + * + * const account = Structural.type({ name: String, location: [Number, Number] }); + * const input = Expression.input("account", account); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(input))), + * '["::kernel::special_form::input","account",{"#struct":{"name":"::kernel::type::String","location":{"#tuple":["::kernel::type::Number","::kernel::type::Number"]}}}]', + * ); + * ``` + */ export const type = ( definition: D, ): TypeExpression.TypeExpression> => @@ -278,7 +313,11 @@ export interface Constructor ): TypeExpression.TypeExpression>>; } -/** Gives an existing generic declaration the same shorthand normalization as local aliases. */ +/** + * Adapts a generic type declaration to accept {@link Definition} shorthand at each argument position. + * + * The original constructor still checks arity and retains failed type arguments. Relocation rebuilds the adapter around the new declaration path. Apply the returned constructor before using it as a type. + */ export const constructor = ( declaration: TypeExpression.Constructor, ): Constructor => @@ -342,7 +381,7 @@ export type ValueType = V extends Expression.AnyValue ? Type.Struct<{ readonly [K in keyof V]: ValueType }> : never; -/** Checking only the value against T would discard additional fields from the reported type. */ +/** Accepts `V` only when its inferred structural descriptor and `T` are mutually assignable, preventing extra fields from disappearing from the reported type. */ export type Exact = [T] extends [ ValueType, ] @@ -351,7 +390,30 @@ export type Exact = [T] extends [ : never : never; -/** Encodes a structural value whose descriptor exactly matches the caller's requested type. */ +/** + * Constructs a value whose inferred structural descriptor matches the requested type. + * + * Supply the semantic descriptor first, then a value with matching fields and tuple positions. This exactness is a TypeScript constraint, not runtime semantic validation. Syntax validation returns failures through the resulting expression. Every nested expression contributes input requirements, including every alternative of a host-side union. + * + * Arrays encode tuples. Records encode enumerable own string keys; inherited, non-enumerable and symbol properties are not emitted. Host objects must be acyclic. + * + * @example Construct a typed record from host values. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Structural } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * type Account = Type.Struct<{ + * readonly name: Type.PrimitiveString; + * readonly active: Type.PrimitiveBoolean; + * }>; + * const account = Structural.value()({ name: "Ada", active: true }); + * assert.deepEqual(Result.getOrThrow(Expression.toJExpr(account)), { + * "#struct": { name: { "#literal": "Ada" }, active: { "#literal": true } }, + * }); + * ``` + */ export const value = () => & AnyValue>( @@ -364,7 +426,11 @@ export const value = Expression.fromResult>, ); -/** Internal syntax conversion shared by nominal constructors. */ +/** + * Converts structural host values to validated J-Expr syntax without assigning a semantic descriptor. + * + * Arrays encode tuples and records encode enumerable own string keys, as in {@link value}. Invalid nested syntax returns a construction failure. Existing handles contribute their stored failures unchanged. Use {@link value} when the result needs a typed expression handle. + */ export const toJExpr = ( value: AnyValue, ): Result.Result => diff --git a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts index 9d8819c594a..53e7ad465d5 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts @@ -3,6 +3,10 @@ * * A {@link TypeExpression} carries syntax or a construction failure alongside a type-level descriptor. A {@link Constructor} specializes a named generic type while preserving its semantic argument tuple. Declarations supply these descriptors, and the HashQL compiler validates their use in the emitted program. * + * Type expressions come from module declarations, the built-in prelude, structural shorthand and the type aliases of the Do and Draft APIs. They appear wherever a program names a type, such as the type of an input. The operations here that annotate syntax or a path, {@link fromResult}, {@link fromType}, {@link reference} and {@link constructor}, attach the descriptor without checking it. + * + * A failed construction stays inside the type expression. It surfaces when a caller reads the syntax, either directly or through an expression or program that uses the type. + * * @module */ import { Predicate, Result, identity, pipe } from "effect"; @@ -23,8 +27,9 @@ import type { Types } from "effect"; const TypeId: unique symbol = Symbol("~hashql/TypeExpression"); const ConstructorId: unique symbol = Symbol("~hashql/TypeConstructor"); -/** Type construction with its semantic annotation erased. */ +/** A type expression with its semantic descriptor erased, for syntax-only operations. */ export interface Any extends Relocatable { + /** The type syntax this handle emits, or the construction failure that prevented it. */ readonly syntax: Result.Result; readonly [TypeId]: Types.Covariant; } @@ -43,6 +48,7 @@ export interface AnyConstructor extends Relocatable { }; } +/** Maps each argument descriptor to the type expression accepted at that position. */ type Arguments = { readonly [K in keyof A]: TypeExpression; }; @@ -51,6 +57,8 @@ type Arguments = { * A named generic type, specialized by supplying typed type expressions. * * The argument tuple carries semantic types, and `Arguments` maps each position to its handle. TypeScript infers the tuple from ordinary calls. A generic caller can also supply it explicitly without extracting and re-inferring types from already-normalized handles. + * + * A call emits a reference to the constructor's path with one generic argument per supplied type. The result's descriptor is `Type.Apply`. TypeScript rejects a call with the wrong number of arguments. At runtime, such a call returns a type expression holding a `TypeArgumentCount` failure. An argument's construction failure becomes the result's failure. */ export interface Constructor< F extends Type.TypeConstructor, @@ -62,20 +70,29 @@ export interface Constructor< ): TypeExpression>; } -/** A type namespace contains both concrete types and generic type constructors. */ +/** An entry of a type namespace: a concrete type expression or a generic type constructor. */ export type Export = Any | AnyConstructor; -/** Recognizes concrete type expressions and generic type constructors. */ +/** + * Recognizes concrete type expressions and generic type constructors. + * + * The guard checks for the SDK's marker properties and does not check a semantic descriptor. A joined namespace name that includes a type also passes. + */ // oxlint-disable-next-line typescript/no-restricted-types -- this guard narrows unchecked environment entries export const isExport = (value: unknown): value is Export => Predicate.hasProperty(value, TypeId) || Predicate.hasProperty(value, ConstructorId); -/** Recognizes generic type constructors, including combined namespace handles. */ +/** Recognizes generic type constructors by their marker property, including combined namespace handles. */ // oxlint-disable-next-line typescript/no-restricted-types -- the guard accepts unchecked host values export const isConstructor = (value: unknown): value is AnyConstructor => Predicate.hasProperty(value, ConstructorId); +/** + * Annotates type syntax, or a construction failure, with a trusted semantic descriptor. + * + * The caller must ensure that successful syntax denotes `T`. A failure stays in the handle until something reads its syntax. Rebinding a successful result produces a reference to the new path, while a failed result keeps its failure. + */ export const fromResult = ( syntax: Result.Result, ): TypeExpression => ({ @@ -92,6 +109,7 @@ export const fromResult = ( ), }); +/** Reads the type syntax a type expression emits, or its construction failure. */ export const toType = ( type: Any, ): Result.Result => type.syntax; @@ -105,7 +123,11 @@ export const fromType = ( syntax: Syntax.Type, ): TypeExpression => pipe(syntax, Result.succeed, fromResult); -/** Binds a trusted semantic declaration to a named type reference. */ +/** + * Binds a trusted semantic declaration to a named type reference. + * + * The result emits `path` as a type reference and carries the descriptor `T`. Nothing checks that the path exists or has that meaning. `Module.type` creates the same reference for a declared export. + */ export const reference = ( path: JExpr.Path.Path, ): TypeExpression => fromType({ _tag: "Reference", path, generics: [] }); @@ -114,6 +136,39 @@ export const reference = ( * Binds a trusted generic declaration to its named type reference. * * Runtime checking covers arity alone. The declaration supplies the relationship between the argument types and the resulting semantic type. + * + * An `arity` that is not a non-negative safe integer returns an `InvalidTypeArity` failure. The successful constructor checks the argument count of each call as {@link Constructor} describes. `Module.genericType` declares the same constructor for a module export. + * + * @example Specialize a generic type and inspect an arity failure. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Prelude, TypeExpression } from "@local/hashql"; + * import type { Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * interface Pair extends Type.TypeConstructor { + * readonly arity: 2; + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Tuple + * : Type.Never; + * } + * + * const path = Result.getOrThrow(JExpr.Path.decodeResult("::example::Pair")); + * const pair = Result.getOrThrow(TypeExpression.constructor(path, 2)); + * const { types } = Prelude.builtin; + * const entry = Expression.input("entry", pair(types.String, types.Integer)); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(entry))), + * '["::kernel::special_form::input","entry","::example::Pair<::kernel::type::String, ::kernel::type::Integer>"]', + * ); + * + * const invalid = TypeExpression.constructor(path, -1); + * assert.ok(Result.isFailure(invalid)); + * assert.equal(invalid.failure.reason._tag, "InvalidTypeArity"); + * ``` */ // oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the path names the reference under construction export const constructor = ( @@ -161,7 +216,11 @@ export const constructor = ( ); }; -/** Rebinds a type reference or generic constructor while retaining its declared capabilities. */ +/** + * Rebinds a type reference or generic constructor while retaining its declared capabilities. + * + * Rebinding turns a concrete type expression into a plain reference to `path`, whatever syntax it emitted before, including a structural type. For a constructor it keeps the arity and emits applications at `path`. The result keeps the descriptor and leaves the original handle as it was. A type expression holding a construction failure returns that failure. Imports and `Module.relocate` use this operation to move each type export. It accepts the handle first or last. + */ export const relocate: { ( path: JExpr.Path.Path, @@ -183,7 +242,7 @@ type Adapted = C & /** * Adapts a named constructor while retaining its argument normalization after rebinding. * - * The adapter receives the rebound declaration each time. Retaining only the first callable would leave later calls pointing at the old path. Copying the marker explicitly supports forwarding proxies that do not enumerate it. + * The adapter receives the rebound declaration each time. Retaining only the first callable would leave later calls pointing at the old path, so build calls from the adapter's argument rather than from a captured constructor. The result keeps the constructor marker, so {@link isConstructor} accepts it and namespaces treat it as a type export. Copying the marker explicitly supports forwarding proxies that do not enumerate it. The built-in `List` and `Dict` use this to accept structural shorthand. It accepts the constructor first or last. */ export const adaptConstructor: { Any>( diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts b/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts index 9cacfcf610b..12852f43e02 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts @@ -1,5 +1,7 @@ import type * as JExpr from "../../jexpr/index.js"; +/** A builder node that emits J-Expr syntax during expression serialization. */ export interface Node { + /** Returns syntax without executing the represented HashQL expression. */ readonly compile: () => JExpr.Expression; } diff --git a/libs/@local/hashql/sdk/typescript/src/program/index.ts b/libs/@local/hashql/sdk/typescript/src/program/index.ts index ba8ef36c093..2d464890d23 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/program/index.ts @@ -11,18 +11,45 @@ import * as Expression from "./Expression.js"; import type * as Type from "../type/index.js"; import type * as ProgramError from "./ProgramError.js"; +/** + * A root expression ready for J-Expr serialization, carrying its result descriptor and input requirements. + * + * The wrapper does not establish that the expression constructed successfully or that the HashQL compiler accepts it. {@link compile} extracts syntax and returns any construction failure. Query execution is separate. + */ export interface Program { + /** The expression whose syntax becomes the program, including its retained construction result. */ readonly root: Expression.Expression; } +/** Extracts the semantic input record from a program's root, including optional requirements supplied by defaults. */ export type Inputs

= P extends { readonly root: infer Root } ? Expression.Inputs : never; +/** + * Wraps a root expression without validating or evaluating it. + * + * The constructor freezes the wrapper and retains the original handle. Its inferred result descriptor and inputs remain available through the {@link Program} type. See {@link compile} for serialization and failure handling. + */ export const program = ( root: Expression.Expression, ): Program => Object.freeze({ root }); +/** + * Serializes a program to J-Expr JSON text, or returns its retained construction failure. + * + * This is syntax serialization, not HashQL compiler execution. It does not resolve names, check the program against a graph schema or execute a query. The J-Expr serializer preserves numeric literal source text. + * + * @example Serialize a completed expression for a HashQL consumer. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, Program } from "@local/hashql"; + * import { Result } from "effect"; + * + * const program = Program.program(Expression.literal("hello")); + * assert.equal(Result.getOrThrow(Program.compile(program)), '{"#literal":"hello"}'); + * ``` + */ export const compile = ( self: Program, ): Result.Result => diff --git a/libs/@local/hashql/sdk/typescript/src/type/index.ts b/libs/@local/hashql/sdk/typescript/src/type/index.ts index 7489f695c82..8d475753d65 100644 --- a/libs/@local/hashql/sdk/typescript/src/type/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/type/index.ts @@ -1,7 +1,33 @@ /** * Compile-time descriptions of HashQL types. * - * Use {@link Any} to constrain a generic without losing its concrete type arguments. Use {@link All} to inspect a type whose arguments are unknown and narrow it by `_tag`. Each generic type has corresponding `Any` and `All` forms. + * A descriptor is a TypeScript type that stands for a HashQL type, such as `Type.Struct<{ readonly name: Type.PrimitiveString }>`. Expressions and type expressions carry descriptors so that TypeScript can check calls, projections, indexing and input requirements while the SDK builds syntax. The package exports this module as types alone: no descriptor value exists at runtime, and nothing compares a descriptor with the HashQL declaration it annotates. Declarations such as `Module.value()` and `Module.type()` take the descriptor on trust, and the HashQL compiler still checks the emitted program. + * + * Type parameters accept descriptors rather than JavaScript value types, so TypeScript rejects `Type.List` and accepts `Type.List`. Use {@link Any} to constrain a generic without losing its concrete type arguments. Use {@link All} to inspect a type whose arguments are unknown and narrow it by `_tag`. Each generic type has corresponding `Any` and `All` forms. A descriptor with an erased child, such as `Type.List`, satisfies `Any` but not `All`. + * + * @example Type-only: describe a record and read its parts. + * ```ts + * import type { Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * type User = Type.Struct<{ + * readonly id: Type.Opaque<"example::UserId", Type.PrimitiveInteger>; + * readonly names: Type.List; + * }>; + * + * export const elementIsString: Equal< + * User["fields"]["names"]["element"], + * Type.PrimitiveString + * > = true; + * export const idIsNominal: Equal< + * User["fields"]["id"]["name"], + * "example::UserId" + * > = true; + * ``` * * @module */ @@ -61,10 +87,18 @@ export declare namespace Intersection { export interface All extends Intersection {} } -/** A nominal type distinguished by its name and underlying type. */ +/** + * A nominal type distinguished by its name and underlying type. + * + * TypeScript accepts an opaque descriptor only where both the name and the underlying type match. A parameter of type `Type.PrimitiveInteger` or `Type.Opaque<"PostId", Type.PrimitiveInteger>` rejects `Type.Opaque<"UserId", Type.PrimitiveInteger>`. Projections and indexing on an expression of an opaque type still reach the fields and elements of the underlying type. + * + * The name exists only in TypeScript. Emitted syntax names the declaration that introduced the type, such as `::core::uuid::Uuid`, rather than this name. Declarations that share a name and an underlying type are therefore interchangeable to TypeScript even when they emit different HashQL types. The built-in declarations use the absolute HashQL path as the name. The Do and Draft newtype operations require a `unique symbol`, which cannot coincide with a string name. + */ export interface Opaque { readonly _tag: "Opaque"; + /** The identity TypeScript compares, a string literal or a symbol type. */ readonly name: Name; + /** The underlying representation. */ readonly type: T; } @@ -94,7 +128,7 @@ export declare namespace Struct { /** * A fixed-length sequence with a type for each position. * - * `T` must be a tuple of required elements. Arrays, optional elements and open-ended rest elements fail the constraint. {@link Tuple.Any} and {@link Tuple.All} erase the length for code that handles arbitrary tuple types. + * `T` must be a tuple of required elements. Arrays, optional elements and open-ended rest elements fail the constraint. `Tuple.Any` and `Tuple.All` erase the length for code that handles arbitrary tuple types. */ export interface Tuple< T extends readonly Any[] & { @@ -157,31 +191,104 @@ export interface Function< } export declare namespace Function { + /** A function with erased parameter and result types. */ export interface Any { readonly _tag: "Function"; readonly parameters: readonly AnyType[]; readonly returns: AnyType; } + /** A function whose parameter and result types support discriminant narrowing. */ export interface All extends Function {} } -/** A type-level operation whose input is a tuple of semantic types. */ +/** + * A type-level operation whose input is a tuple of semantic types. + * + * An implementation reads its arguments from `this["Target"]` and computes the descriptor in `type`. This is Effect's `HKT.TypeLambda` encoding with the result constrained to a descriptor. {@link TypeConstructor} and {@link FunctionSignature} are the two kinds the SDK applies. + */ export interface TypeLambda extends HKT.TypeLambda { readonly type: Any; } -/** Applies a declaration's type-level operation without a runtime type interpreter. */ +/** + * Computes the descriptor a {@link TypeLambda} produces for an argument tuple. + * + * TypeScript evaluates the operation during checking. The SDK has no runtime type interpreter, so the result is a static annotation on the syntax a call emits. + */ export type Apply< Lambda extends TypeLambda, Arguments extends readonly Any[], > = HKT.Kind; -/** A generic type declaration with a fixed number of positional type arguments. */ +/** + * A generic type declaration with a fixed number of positional type arguments. + * + * Declare `arity` as a numeric literal. TypeScript checks that the arity argument to `Module.genericType` or `TypeExpression.constructor` equals that literal. A constructor call must supply exactly that many type arguments. The `type` member maps the argument descriptors in `this["Target"]` to the resulting type. + * + * @example Type-only: declare the result of a two-argument generic type. + * ```ts + * import type { Type } from "@local/hashql"; + * + * type Equal = + * (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + * ? true + * : false; + * + * interface Pair extends Type.TypeConstructor { + * readonly arity: 2; + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Tuple + * : Type.Never; + * } + * + * export const applied: Equal< + * Type.Apply, + * Type.Tuple + * > = true; + * ``` + */ export interface TypeConstructor extends TypeLambda { + /** The number of type arguments every application supplies. */ readonly arity: number; } -/** Computes a function signature from the types of its call arguments. */ +/** + * Computes a function signature from the types of its call arguments. + * + * A call to an expression of type {@link GenericFunction} applies the signature to the descriptors of the actual arguments. TypeScript then checks each argument against the resulting `parameters` and types the call as `returns`. When the arguments do not fit the operation, return a function type whose parameters no argument satisfies, as the built-in signatures do with {@link Never}. + * + * @example Declare a generic function and call it. + * ```ts + * import assert from "node:assert/strict"; + * import { Expression, JExpr, Module } from "@local/hashql"; + * import type { Inputs, Type } from "@local/hashql"; + * import { Result } from "effect"; + * + * interface First extends Type.FunctionSignature { + * readonly type: this["Target"] extends readonly [ + * infer L extends Type.Any, + * infer R extends Type.Any, + * ] + * ? Type.Function + * : Type.Function; + * } + * + * const pairs = Result.getOrThrow( + * Module.define("::example::pairs", { + * values: { first: Module.value>() }, + * }), + * ); + * const call: Expression.Expression = + * pairs.values.first("left", 1n); + * assert.equal( + * JExpr.compile(Result.getOrThrow(Expression.toJExpr(call))), + * '["::example::pairs::first",{"#literal":"left"},{"#literal":1}]', + * ); + * ``` + */ export interface FunctionSignature extends TypeLambda { readonly type: Function.Any; } @@ -189,21 +296,32 @@ export interface FunctionSignature extends TypeLambda { /** A function whose parameter and result types depend on its call arguments. */ export interface GenericFunction { readonly _tag: "GenericFunction"; + /** The operation that derives the signature of each call. */ readonly signature: Signature; } export declare namespace GenericFunction { + /** A generic function with its signature operation erased. */ export type Any = GenericFunction; + /** A generic function, identical to {@link GenericFunction.Any} because its signature is an operation rather than an inspectable descriptor. */ export interface All extends GenericFunction {} } -/** An arbitrary-precision integer. */ +/** + * An arbitrary-precision integer. + * + * A `bigint` stands for this type in builder arguments. A JavaScript `number` stands for {@link PrimitiveNumber} even when its value is integral. + */ export interface PrimitiveInteger { readonly _tag: "Integer"; readonly value: bigint; } -/** A number, including integer values. */ +/** + * A number, including integer values. + * + * TypeScript does not widen {@link PrimitiveInteger} to this type, so a parameter of this type rejects an Integer expression or a `bigint`. + */ export interface PrimitiveNumber { readonly _tag: "Number"; readonly value: number; @@ -227,6 +345,11 @@ export interface PrimitiveNull { readonly value: null; } +/** + * The primitive types. + * + * Each `value` member names the host JavaScript value type that builders accept in place of an expression of that type, such as `"text"` for {@link PrimitiveString} or `null` for {@link PrimitiveNull}. + */ export type Primitive = | PrimitiveInteger | PrimitiveNumber From 921eda20c6f12e2746bd318893e034b97a4e38d7 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:53:55 +0200 Subject: [PATCH 13/22] docs: add HashQL TypeScript API reference --- .../hashql/sdk/typescript-docs/.gitignore | 7 + .../hashql/sdk/typescript-docs/LICENSE.md | 606 ++++ .../hashql/sdk/typescript-docs/api-entry.d.ts | 1 + .../sdk/typescript-docs/api-extractor.json | 31 + .../typescript-docs/content/docs/index.mdx | 10 + .../typescript-docs/content/docs/meta.json | 4 + .../sdk/typescript-docs/oxlint.config.ts | 58 + .../hashql/sdk/typescript-docs/package.json | 63 + .../sdk/typescript-docs/scripts/extract.mts | 17 + .../sdk/typescript-docs/scripts/render.mts | 240 ++ .../sdk/typescript-docs/scripts/transform.mts | 454 +++ .../sdk/typescript-docs/source.config.ts | 33 + .../sdk/typescript-docs/tsconfig.api.json | 17 + .../hashql/sdk/typescript-docs/tsconfig.json | 17 + .../hashql/sdk/typescript-docs/tsdoc.json | 28 + .../hashql/sdk/typescript-docs/turbo.json | 65 + .../hashql/sdk/typescript/docs/index.md | 45 + .../@local/hashql/sdk/typescript/docs/todo.md | 25 + yarn.lock | 2482 +++++++++++++++-- 19 files changed, 3903 insertions(+), 300 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript-docs/.gitignore create mode 100644 libs/@local/hashql/sdk/typescript-docs/LICENSE.md create mode 100644 libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/api-extractor.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx create mode 100644 libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/package.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts create mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/render.mts create mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts create mode 100644 libs/@local/hashql/sdk/typescript-docs/source.config.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/tsconfig.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/tsdoc.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/turbo.json create mode 100644 libs/@local/hashql/sdk/typescript/docs/index.md create mode 100644 libs/@local/hashql/sdk/typescript/docs/todo.md diff --git a/libs/@local/hashql/sdk/typescript-docs/.gitignore b/libs/@local/hashql/sdk/typescript-docs/.gitignore new file mode 100644 index 00000000000..3d789702d9f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/.gitignore @@ -0,0 +1,7 @@ +.generated/ +.next/ +.source/ +.twoslash/ +*.tsbuildinfo +content/docs/reference/ +lib/reference-links.json diff --git a/libs/@local/hashql/sdk/typescript-docs/LICENSE.md b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md new file mode 100644 index 00000000000..8ebfe728d7d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/LICENSE.md @@ -0,0 +1,606 @@ +# GNU Affero General Public License + +_Version 3, 19 November 2007_ +_Copyright © 2007 Free Software Foundation, Inc. <>_ + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +## Preamble + +The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights +with two steps: **(1)** assert copyright on the software, and **(2)** offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + +A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + +The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + +An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + +The precise terms and conditions for copying, distribution and +modification follow. + +## TERMS AND CONDITIONS + +### 0. Definitions + +“This License” refers to version 3 of the GNU Affero General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this +License. Each licensee is addressed as “you”. “Licensees” and +“recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a “modified version” of the +earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based +on the Program. + +To “propagate” a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” +to the extent that it includes a convenient and prominently visible +feature that **(1)** displays an appropriate copyright notice, and **(2)** +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +### 1. Source Code + +The “source code” for a work means the preferred form of the work +for making modifications to it. “Object code” means any non-source +form of a work. + +A “Standard Interface” means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other +than the work as a whole, that **(a)** is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and **(b)** serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +“Major Component”, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +### 2. Basic Permissions + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +### 4. Conveying Verbatim Copies + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +- **a)** The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- **b)** The work must carry prominent notices stating that it is + released under this License and any conditions added under section 7. + This requirement modifies the requirement in section 4 to + “keep intact all notices”. +- **c)** You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- **d)** If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +“aggregate” if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +- **a)** Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- **b)** Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either **(1)** a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or **(2)** access to copy the + Corresponding Source from a network server at no charge. +- **c)** Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- **d)** Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- **e)** Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A “User Product” is either **(1)** a “consumer product”, which means any +tangible personal property which is normally used for personal, family, +or household purposes, or **(2)** anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, “normally used” refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +### 7. Additional Terms + +“Additional permissions” are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + +- **a)** Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- **b)** Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- **c)** Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- **d)** Limiting the use for publicity purposes of names of licensors or + authors of the material; or +- **e)** Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- **f)** Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + +All other non-permissive additional terms are considered “further +restrictions” within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +### 8. Termination + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated **(a)** +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and **(b)** permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +### 9. Acceptance Not Required for Having Copies + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +### 10. Automatic Licensing of Downstream Recipients + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +### 11. Patents + +A “contributor” is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, “control” includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To “grant” such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either **(1)** cause the Corresponding Source to be so +available, or **(2)** arrange to deprive yourself of the benefit of the +patent license for this particular work, or **(3)** arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. “Knowingly relying” means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is “discriminatory” if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license **(a)** in connection with copies of the covered work +conveyed by you (or copies made from those copies), or **(b)** primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +### 12. No Surrender of Others' Freedom + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +### 13. Remote Network Interaction; Use with the GNU General Public License + +Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + +### 14. Revised Versions of this License + +The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License “or any later version” applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +### 15. Disclaimer of Warranty + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +### 16. Limitation of Liability + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16 + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. diff --git a/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts b/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts new file mode 100644 index 00000000000..6ea60620d77 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts @@ -0,0 +1 @@ +export * from "./.generated/declarations/program/Expression.js"; diff --git a/libs/@local/hashql/sdk/typescript-docs/api-extractor.json b/libs/@local/hashql/sdk/typescript-docs/api-extractor.json new file mode 100644 index 00000000000..272a1e4089b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/api-extractor.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "projectFolder": ".", + "mainEntryPointFilePath": "/api-entry.d.ts", + "compiler": { + "overrideTsconfig": { + "compilerOptions": { + "strict": true, + "target": "ES2024", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "skipLibCheck": true + }, + "include": ["api-entry.d.ts"] + }, + "skipLibCheck": true + }, + "apiReport": { + "enabled": false + }, + "docModel": { + "enabled": true, + "apiJsonFilePath": "/.generated/api-model/hashql.api.json" + }, + "dtsRollup": { + "enabled": false + }, + "tsdocMetadata": { + "enabled": false + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx new file mode 100644 index 00000000000..8edc54b8495 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/index.mdx @@ -0,0 +1,10 @@ +--- +title: HashQL TypeScript +description: Build typed HashQL expressions and programs in TypeScript. +--- + +## API reference + +The [Expression module](./reference/program/Expression) describes symbolic values, their semantic types and input requirements. + +The reference currently covers Expression. Examples construct and print J-Expr; they do not execute graph queries. diff --git a/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json new file mode 100644 index 00000000000..88a04097d86 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/content/docs/meta.json @@ -0,0 +1,4 @@ +{ + "title": "HashQL TypeScript", + "pages": ["index", "reference"] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts new file mode 100644 index 00000000000..6a20bba989b --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -0,0 +1,58 @@ +import { createConfig, defineConfig } from "@local/oxlint"; + +export default defineConfig({ + extends: [createConfig({ runtime: "node", frameworks: ["react", "next"] })], + ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], + overrides: [ + { + files: ["app/**/*.tsx", "*.config.mjs"], + rules: { + "import/no-default-export": "allow", // Next.js and PostCSS discover default exports. + }, + }, + { + files: ["app/**/*.tsx", "components/**/*.tsx"], + rules: { + "react/react-in-jsx-scope": "allow", // Next.js uses the automatic JSX runtime. + "react/jsx-filename-extension": ["deny", { extensions: [".tsx"] }], // This TypeScript app uses TSX. + "react/only-export-components": "allow", // Next.js discovers metadata and static parameter exports. + "oxc/no-async-await": "allow", // Server components await route parameters and syntax highlighting. + }, + }, + { + files: ["components/**/*.tsx"], + rules: { + "react/function-component-definition": [ + "deny", // Match the repository's function-expression style. + { namedComponents: "arrow-function" }, + ], + }, + }, + { + files: ["components/reference.tsx"], + rules: { + "react/no-multi-comp": "allow", // The reference table shares plain and highlighted type renderers. + }, + }, + { + files: ["components/reference-trigger.tsx"], + rules: { + "react/jsx-props-no-spreading": "allow", // Forward Base UI's trigger events, accessibility attributes and children. + "react-perf/jsx-no-jsx-as-prop": "allow", // Base UI's public render prop accepts the replacement element. + "jsx-a11y/no-redundant-roles": "allow", // The link role overrides Base UI's non-native button role. + }, + }, + { + files: ["lib/reference-twoslash.ts"], + rules: { + "no-underscore-dangle": ["deny", { allow: ["__raw"] }], // Shiki exposes fence metadata under this public field name. + }, + }, + { + files: ["app/layout.tsx"], + rules: { + "import/no-unassigned-import": "allow", // The root layout loads global CSS. + }, + }, + ], +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json new file mode 100644 index 00000000000..14c1ce2fd97 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -0,0 +1,63 @@ +{ + "name": "@local/hashql-typescript-docs", + "version": "0.0.0-private", + "private": true, + "description": "TypeScript SDK reference for HashQL", + "license": "AGPL-3", + "type": "module", + "scripts": { + "build": "next build --webpack", + "codegen": "fumadocs-mdx", + "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", + "doc:declarations": "tsc --project tsconfig.api.json", + "doc:examples": "node --experimental-strip-types scripts/examples.mts", + "doc:markdown": "api-documenter markdown --input-folder .generated/api-model --output-folder .generated/markdown", + "doc:model": "node --experimental-strip-types scripts/extract.mts", + "doc:render": "node --experimental-strip-types scripts/render.mts", + "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", + "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", + "lint:tsc": "tsc --noEmit", + "start": "next start --hostname 127.0.0.1 --port ${PORT:-4398}", + "test:unit": "node --experimental-strip-types --test scripts/*.test.mts" + }, + "dependencies": { + "@fumadocs/satteri": "0.5.1", + "@local/hashql": "workspace:*", + "fumadocs-core": "16.16.2", + "fumadocs-mdx": "15.4.6", + "fumadocs-twoslash": "4.0.1", + "fumadocs-ui": "16.16.2", + "next": "16.3.8", + "react": "19.2.6", + "react-dom": "19.2.6", + "satteri": "0.10.5" + }, + "devDependencies": { + "@local/oxlint": "workspace:*", + "@local/tsconfig": "workspace:*", + "@microsoft/api-documenter": "7.30.18", + "@microsoft/api-extractor": "7.59.4", + "@microsoft/api-extractor-model": "7.33.15", + "@microsoft/tsdoc": "0.17.1", + "@microsoft/tsdoc-config": "0.18.3", + "@tailwindcss/postcss": "4.3.3", + "@tsconfig/bases": "catalog:", + "@types/hast": "3.0.5", + "@types/mdast": "4.0.4", + "@types/mdx": "2.0.14", + "@types/node": "catalog:", + "@types/react": "19.2.14", + "@types/react-dom": "19.2.3", + "effect": "4.0.0", + "oxfmt": "0.71.0", + "oxlint": "catalog:", + "remark-mdx": "3.1.1", + "remark-parse": "11.0.0", + "remark-stringify": "11.0.0", + "shiki": "4.5.0", + "tailwindcss": "4.3.3", + "tsx": "catalog:", + "typescript": "catalog:", + "unified": "11.0.5" + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts new file mode 100644 index 00000000000..5aeb49b9016 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts @@ -0,0 +1,17 @@ +import { resolve } from "node:path"; + +import { Extractor, ExtractorConfig } from "@microsoft/api-extractor"; +import { TSDocConfigFile } from "@microsoft/tsdoc-config"; + +const root = resolve(import.meta.dirname, ".."); +const configPath = resolve(root, "api-extractor.json"); +const config = ExtractorConfig.prepare({ + configObject: ExtractorConfig.loadFile(configPath), + configObjectFullPath: configPath, + packageJsonFullPath: resolve(root, "../typescript/package.json"), + tsdocConfigFile: TSDocConfigFile.loadFile(resolve(root, "tsdoc.json")), +}); +const result = Extractor.invoke(config, { localBuild: true }); +if (!result.succeeded) { + process.exitCode = 1; +} diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts new file mode 100644 index 00000000000..d8321155ec3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts @@ -0,0 +1,240 @@ +import { createHash } from "node:crypto"; +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { ApiVariable } from "@microsoft/api-extractor-model"; + +import { + bodyOf, + callableSignatures, + declarationLinks, + inputSignatures, + introOf, + loadItems, + moduleOverview, + polishedMember, + renderIndexSummary, + renderMarkdown, + rewriteProse, +} from "./transform.mts"; + +import type { ExampleResult } from "./transform.mts"; + +const directory = import.meta.dirname; +const { resolve } = path; +const root = resolve(directory, ".."); +const input = resolve(root, "generators"); +const content = resolve(root, "app/content/docs"); +const output = resolve(content, "reference/program"); + +// oxlint-disable-next-line typescript/no-restricted-types -- Captured JSON is untrusted until every ExampleResult field is validated below. +const decodeExample = (value: unknown): ExampleResult => { + if ( + typeof value !== "object" || + value === null || + !("code" in value) || + typeof value.code !== "string" || + !("stdout" in value) || + typeof value.stdout !== "string" || + !("stderr" in value) || + typeof value.stderr !== "string" || + !("exitCode" in value) || + typeof value.exitCode !== "number" || + !("sourceSha256" in value) || + typeof value.sourceSha256 !== "string" || + !("exampleSha256" in value) || + typeof value.exampleSha256 !== "string" + ) { + throw new Error("Invalid captured example record"); + } + return { + code: value.code, + stdout: value.stdout, + stderr: value.stderr, + exitCode: value.exitCode, + sourceSha256: value.sourceSha256, + exampleSha256: value.exampleSha256, + }; +}; + +// oxlint-disable-next-line typescript/no-restricted-types -- JSON.parse has no schema; narrow the decoded container before reading its records. +const results: unknown = JSON.parse( + await readFile(resolve(directory, "examples/results.json"), "utf8"), +); +if ( + typeof results !== "object" || + results === null || + !("input" in results) || + !("adaptCallable" in results) +) { + throw new Error("Both captured examples are required"); +} +const examples = { + input: decodeExample(results.input), + adaptCallable: decodeExample(results.adaptCallable), +}; +const items = loadItems(resolve(input, "api-model/hashql.api.json")); +const symbols = new Map( + items.map((item) => [item.displayName, `#${item.displayName}`]), +); +const files = new Map([ + ["hashql.md", "#module-overview"], + ["index.md", "/docs"], +]); +const pages = new Map(); +const filenames = await readdir(resolve(input, "api-documenter")); +const memberFilenames = filenames + .toSorted() + .filter( + (filename) => + filename !== "index.md" && + filename !== "hashql.md" && + filename.endsWith(".md"), + ); +const sourceReads: Promise[] = []; +for (const filename of memberFilenames) { + sourceReads.push( + readFile(resolve(input, "api-documenter", filename), "utf8"), + ); +} +const sources = await Promise.all(sourceReads); +for (const [index, filename] of memberFilenames.entries()) { + const source = sources[index]; + if (source === undefined) { + throw new Error(`Missing Documenter page: ${filename}`); + } + const member = items.find( + (item) => filename === `hashql.${item.displayName.toLowerCase()}.md`, + ); + const anchor = + member?.displayName ?? + filename + .slice("hashql.".length, -".md".length) + .replaceAll(/[^A-Za-z0-9-]/gu, "-"); + files.set(filename, `#${anchor}`); + pages.set(filename, source); +} +const inputs = inputSignatures(items, declarationLinks(items)); +for (const signature of inputs) { + const index = Number(signature.anchor.slice("input-".length)); + let filename = `hashql.input_${index - 1}.md`; + if (index === 1) { + filename = "hashql.input.md"; + } + files.set(filename, `#${signature.anchor}`); +} +const adapted = items.find( + (item): item is ApiVariable => + item instanceof ApiVariable && item.displayName === "adaptCallable", +); +if (adapted === undefined) { + throw new Error("adaptCallable is absent from the API model"); +} +const callSignatures = callableSignatures(adapted, declarationLinks(items)); +const preamble = `import type { Type, TypeExpression } from "@local/hashql";\nimport type * as Input from ${JSON.stringify(resolve(input, "input/dist-fresh/program/Inputs.js"))};\nimport type { Expression, Adapted, Any, Inputs, Value } from ${JSON.stringify(resolve(input, "input/dist-fresh/program/Expression.js"))};`; + +const polishedSections: Promise[] = []; +for (const name of ["input", "adaptCallable"] as const) { + const source = pages.get(`hashql.${name.toLowerCase()}.md`); + if (source === undefined || source === "") { + throw new Error(`Missing Documenter page: ${name}`); + } + const example = examples[name]; + const digest = createHash("sha256").update(source).digest("hex"); + if ( + example.sourceSha256 !== digest || + example.exampleSha256 !== + createHash("sha256").update(example.code).digest("hex") + ) { + throw new Error(`Stale example capture: ${name}`); + } + let signatures = callSignatures; + if (name === "input") { + signatures = inputs; + } + polishedSections.push( + polishedMember({ + name, + source, + signatures, + preamble, + example, + files, + symbols, + }), + ); +} +const sections = await Promise.all(polishedSections); +for (const [filename, source] of pages) { + if (!/^hashql\.(?:input(?:_\d+)?|adaptcallable)\.md$/u.test(filename)) { + const anchor = files.get(filename)?.slice(1); + if (anchor === undefined || anchor === "") { + throw new Error(`Missing member anchor: ${filename}`); + } + const heading = + items.find((item) => item.displayName === anchor)?.displayName ?? + /^## (?.+)\r?$/mu.exec(source)?.groups?.title?.trim() ?? + anchor; + const tree = rewriteProse(bodyOf(source), { + files, + symbols, + section: anchor, + }); + sections.push( + `## Expression.${heading} [#${anchor}]\n\n${renderMarkdown(tree)}`, + ); + } +} +const indexRows = [...new Set(items.map((item) => item.displayName))].map( + (name) => { + const source = pages.get(`hashql.${name.toLowerCase()}.md`); + let summary = ""; + if (source !== undefined && source !== "") { + const first = introOf(bodyOf(source)).children[0]; + if (first !== undefined) { + summary = renderIndexSummary(first); + } + } + return `| [\`${name}\`](#${name}) | ${summary} |`; + }, +); +const overview = moduleOverview( + resolve(input, "input/src/program/Expression.ts"), +); +const page = `--- +title: Expression +description: Symbolic HashQL values with semantic types and input requirements. +--- + +## Module overview [#module-overview] + +${overview} + +## Members [#members] + +| Member | Description | +| --- | --- | +${indexRows.join("\n")} + +${sections.join("\n")}`; +await mkdir(output, { recursive: true }); +await writeFile(resolve(output, "Expression.mdx"), page); +await writeFile( + resolve(root, "app/lib/reference-links.json"), + `${JSON.stringify(Object.fromEntries(symbols), null, 2)}\n`, +); +await writeFile( + resolve(output, "meta.json"), + `${JSON.stringify({ title: "program", pages: ["Expression"] }, null, 2)}\n`, +); +await writeFile( + resolve(content, "reference/meta.json"), + `${JSON.stringify({ title: "API reference", pages: ["program"] }, null, 2)}\n`, +); +await writeFile( + resolve(directory, "generated.json"), + `${JSON.stringify({ page: "reference/program/Expression.mdx", moduleSource: "generators/input/src/program/Expression.ts", inputOverloads: inputs.length, callableSignatures: callSignatures.length, memberSections: sections.length, sha256: createHash("sha256").update(page).digest("hex") }, null, 2)}\n`, +); +process.stdout.write( + `Generated Expression with ${inputs.length} input overloads, ${callSignatures.length} callable signatures and both captured examples.\n`, +); diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts new file mode 100644 index 00000000000..7832a356469 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts @@ -0,0 +1,454 @@ +import { readFileSync } from "node:fs"; + +import { + ApiDeclaredItem, + ApiFunction, + ApiModel, +} from "@microsoft/api-extractor-model"; +import { DocCodeSpan, DocPlainText, DocSoftBreak } from "@microsoft/tsdoc"; +import { format } from "oxfmt"; +import remarkMdx from "remark-mdx"; +import remarkParse from "remark-parse"; +import remarkStringify from "remark-stringify"; +import ts from "typescript"; +import { unified } from "unified"; + +import formatOptions from "../../../../../oxfmt.config.ts"; + +import type { + ApiItem, + ApiVariable, + Excerpt, +} from "@microsoft/api-extractor-model"; +import type { DocNode } from "@microsoft/tsdoc"; +import type { Nodes, PhrasingContent, Root, RootContent } from "mdast"; + +export interface TypePart { + text: string; + href?: string; +} + +export interface ParameterView { + name: string; + optional: boolean; + type: TypePart[]; + description: string; +} + +export interface SignatureView { + anchor: string; + title: string; + code: string; + parameters: ParameterView[]; + returns: TypePart[]; +} + +export interface ExampleResult { + code: string; + stdout: string; + stderr: string; + exitCode: number; + sourceSha256: string; + exampleSha256: string; +} + +// Documenter emits plain Markdown with HTML comments, not MDX expressions. +const markdown = unified().use(remarkParse); +// Escape literal text for MDX only when serializing the rewritten prose. +const mdx = unified() + .use(remarkStringify, { fences: true, bullet: "-" }) + .use(remarkMdx); + +export const bodyOf = (source: string): Root => { + const tree = markdown.parse(source); + const heading = tree.children.findIndex((node) => node.type === "heading"); + if (heading === -1) { + throw new Error("Documenter page has no heading"); + } + return { type: "root", children: tree.children.slice(heading + 1) }; +}; + +export const nodeText = (node: Nodes): string => { + if (node.type === "html") { + return node.value.replaceAll(/<!--[\s\S]*?-->/gu, ""); + } + if ("value" in node) { + return node.value; + } + if ("children" in node) { + return node.children.map(nodeText).join(""); + } + return ""; +}; + +const plainDescription = (node: DocNode | undefined): string => { + if (node === undefined) { + return ""; + } + if (node instanceof DocPlainText) { + return node.text; + } + if (node instanceof DocCodeSpan) { + return node.code; + } + if (node instanceof DocSoftBreak) { + return " "; + } + if (node.kind !== "Section" && node.kind !== "Paragraph") { + throw new Error(`Unsupported parameter prose: ${node.kind}`); + } + return node.getChildNodes().map(plainDescription).join("").trim(); +}; + +export const loadItems = (modelPath: string): readonly ApiItem[] => { + const model = new ApiModel(); + const entry = model.loadPackage(modelPath).entryPoints[0]; + if (entry === undefined) { + throw new Error("API model has no entry point"); + } + return entry.members; +}; + +export const typeParts = ( + excerpt: Excerpt, + links: ReadonlyMap<string, string>, + options: { start?: number; end?: number } = {}, +): TypePart[] => { + const { start = 0, end = excerpt.text.length } = options; + const parts: TypePart[] = []; + let offset = 0; + for (const token of excerpt.spannedTokens) { + const next = offset + token.text.length; + if (next > start && offset < end) { + const text = token.text.slice( + Math.max(0, start - offset), + Math.min(token.text.length, end - offset), + ); + const part: TypePart = { text }; + if (token.canonicalReference !== undefined) { + const href = links.get(token.canonicalReference.toString()); + if (href !== undefined && href !== "") { + part.href = href; + } + } + parts.push(part); + } + offset = next; + } + return parts; +}; + +export const inputSignatures = ( + items: readonly ApiItem[], + links: ReadonlyMap<string, string>, +): SignatureView[] => { + const functions = items.filter( + (item): item is ApiFunction => + item instanceof ApiFunction && item.displayName === "input", + ); + const documented = functions.find((item) => item.tsdocComment !== undefined); + return functions.map((item) => ({ + anchor: `input-${item.overloadIndex}`, + title: `Overload ${item.overloadIndex}`, + code: item.excerpt.text, + parameters: item.parameters.map((parameter) => ({ + name: parameter.name, + optional: parameter.isOptional, + type: typeParts(parameter.parameterTypeExcerpt, links), + description: plainDescription( + parameter.tsdocParamBlock?.content ?? + documented?.parameters.find( + (candidate) => candidate.name === parameter.name, + )?.tsdocParamBlock?.content, + ), + })), + returns: typeParts(item.returnTypeExcerpt, links), + })); +}; + +export const callableSignatures = ( + item: ApiVariable, + links: ReadonlyMap<string, string>, +): SignatureView[] => { + // The API model retains a callable variable as one excerpt. Parse its syntax without invoking a checker or replacing its types. + const prefix = "declare const "; + const source = ts.createSourceFile( + "callable.d.ts", + `${prefix}${item.excerpt.text};`, + ts.ScriptTarget.Latest, + true, + ); + const statement = source.statements[0]; + if (statement === undefined || !ts.isVariableStatement(statement)) { + throw new Error("Expected a callable variable declaration"); + } + const type = statement.declarationList.declarations[0]?.type; + if (type === undefined || !ts.isTypeLiteralNode(type)) { + throw new Error("Expected an object of call signatures"); + } + const members = type.members; + return members.map((member, index) => { + if (!ts.isCallSignatureDeclaration(member) || member.type === undefined) { + throw new Error("Expected a call signature with an explicit return type"); + } + return { + anchor: `${item.displayName}-${index + 1}`, + title: `Call signature ${index + 1}`, + code: member.getText(source), + parameters: member.parameters.map((parameter) => { + if (parameter.type === undefined || !ts.isIdentifier(parameter.name)) { + throw new Error("Expected a named parameter with an explicit type"); + } + return { + name: parameter.name.text, + optional: parameter.questionToken !== undefined, + type: typeParts(item.excerpt, links, { + start: parameter.type.getStart(source) - prefix.length, + end: parameter.type.end - prefix.length, + }), + description: "", + }; + }), + returns: typeParts(item.excerpt, links, { + start: member.type.getStart(source) - prefix.length, + end: member.type.end - prefix.length, + }), + }; + }); +}; + +export const rewriteProse = ( + tree: Root, + options: { + files: ReadonlyMap<string, string>; + symbols: ReadonlyMap<string, string>; + section: string; + }, +): Root => { + const { files, symbols, section } = options; + const maximumHeadingDepth = 6; + let headingIndex = 0; + const linkInlineCode = (children: PhrasingContent[]): void => { + for (const [index, child] of children.entries()) { + if (child.type === "inlineCode") { + const name = + /^(?:Expression\.)?(?<name>[A-Za-z_$][\w$]*)(?=[(<]|$)/u.exec( + child.value, + )?.groups?.name; + if (name !== undefined && name !== "") { + const destination = symbols.get(name); + if (destination !== undefined && destination !== "") { + children[index] = { + type: "link", + url: destination, + children: [child], + }; + } + } + } + } + }; + const visit = (node: Nodes, insideLink: boolean): void => { + if (node.type === "link") { + const destination = files.get(node.url.replace(/^\.\//u, "")); + if (destination !== undefined && destination !== "") { + node.url = destination; + } else if (node.url.endsWith(".md")) { + node.url = `../../../api-documenter/${node.url.replace(/^\.\//u, "")}`; + } + } + if (node.type === "heading") { + headingIndex += 1; + if (node.depth !== maximumHeadingDepth) { + node.depth += 1; + } + node.children.push({ + type: "text", + value: ` [#${section}-detail-${headingIndex}]`, + }); + } + if (node.type === "html") { + node.value = node.value + .replaceAll(/<!--[\s\S]*?-->/gu, "") + .replaceAll(/<\/?caption>/gu, ""); + } + const withinLink = + insideLink || node.type === "link" || node.type === "linkReference"; + // Only these mdast parents accept phrasing children; block/container arrays are never rewritten. + if ( + !withinLink && + (node.type === "paragraph" || + node.type === "heading" || + node.type === "emphasis" || + node.type === "strong" || + node.type === "delete" || + node.type === "tableCell") + ) { + linkInlineCode(node.children); + } + if ("children" in node) { + for (const child of node.children) { + visit(child, withinLink); + } + } + }; + visit(tree, false); + return tree; +}; + +export const renderMarkdown = (tree: Root): string => mdx.stringify(tree); + +export const renderIndexSummary = (node: Nodes): string => + renderMarkdown({ + type: "root", + children: [ + { + type: "paragraph", + children: [ + { type: "text", value: nodeText(node).replaceAll("\n", " ") }, + ], + }, + ], + }) + .trimEnd() + .replaceAll("|", String.raw`\|`); + +export const introOf = (tree: Root): Root => { + const boundary = tree.children.findIndex( + (node) => node.type === "heading" || nodeText(node) === "Signature:", + ); + let children = tree.children; + if (boundary !== -1) { + children = tree.children.slice(0, boundary); + } + return { type: "root", children }; +}; + +const returnProse = (tree: Root): Root => { + const marker = tree.children.findIndex( + (node) => nodeText(node) === "Returns:", + ); + if (marker === -1) { + return { type: "root", children: [] }; + } + const children: RootContent[] = []; + // The first paragraph is Documenter's rendered return type; types come from model excerpts instead. + for (const node of tree.children.slice(marker + 2)) { + if (node.type === "heading") { + break; + } + children.push(node); + } + return { type: "root", children }; +}; + +export const signatureBlock = async ( + signature: SignatureView, + options: { preamble: string; callable: boolean; name: string }, +): Promise<string> => { + let before = options.preamble; + let after = ""; + if (options.callable) { + before = `${options.preamble}\ninterface CallSignature {`; + after = "\n// ---cut-after---\n}"; + } + const formatted = await format( + "signature.ts", + `${before}\n// ---cut---\n${signature.code}${after}`, + formatOptions, + ); + if (formatted.errors.length > 0) { + throw new Error( + `Cannot format ${signature.anchor}: ${JSON.stringify(formatted.errors)}`, + ); + } + return `\`\`\`ts twoslash reference title="Expression.${options.name}"\n${formatted.code.trimEnd()}\n\`\`\``; +}; + +export const polishedMember = async (options: { + name: string; + source: string; + signatures: readonly SignatureView[]; + preamble: string; + example: ExampleResult; + files: ReadonlyMap<string, string>; + symbols: ReadonlyMap<string, string>; +}): Promise<string> => { + const { name, source, signatures, preamble, example, files, symbols } = + options; + if (example.exitCode !== 0 || example.stdout.trim() === "") { + throw new Error(`Missing successful captured output for ${name}`); + } + const original = bodyOf(source); + const prose = (tree: Root): string => + renderMarkdown(rewriteProse(tree, { files, symbols, section: name })); + const returnDescription = nodeText(returnProse(original)).trim(); + const sectionBlocks = await Promise.all( + signatures.map( + async (signature) => `### ${signature.title} [#${signature.anchor}] + +${await signatureBlock(signature, { preamble, callable: name === "adaptCallable", name })} + +<ReferenceSignature id=${JSON.stringify(`${signature.anchor}-params`)} parameters={${JSON.stringify(signature.parameters)}} returns={${JSON.stringify(signature.returns)}} returnDescription={${JSON.stringify(returnDescription)}} /> +`, + ), + ); + const sections = sectionBlocks.join("\n"); + const caption = original.children.find( + (node) => node.type === "html" && node.value.includes("<caption>"), + ); + let captionText = ""; + if (caption?.type === "html") { + captionText = caption.value.replaceAll(/<\/?caption>/gu, "").trim(); + } + return `## Expression.${name} [#${name}] + +${prose(introOf(original))} +${sections} +### Example [#${name}-example] + +${captionText} + +\`\`\`ts twoslash +${example.code.trimEnd()} +\`\`\` + +#### Output [#${name}-output] + +\`\`\`text +${example.stdout.trimEnd()} +\`\`\` +`; +}; + +export const moduleOverview = (sourcePath: string): string => { + const source = readFileSync(sourcePath, "utf8"); + const comment = ts.getLeadingCommentRanges(source, 0)?.[0]; + if (comment === undefined || !source.startsWith("/**")) { + throw new Error("Module overview comment is missing"); + } + const openingCommentLength = "/**".length; + const closingCommentLength = "*/".length; + return source + .slice( + comment.pos + openingCommentLength, + comment.end - closingCommentLength, + ) + .split("\n") + .map((line) => line.replace(/^\s*\* ?/u, "")) + .filter((line) => line.trim() !== "@module") + .join("\n") + .trim(); +}; + +export const declarationLinks = ( + items: readonly ApiItem[], +): Map<string, string> => + new Map( + items + .filter((item) => item instanceof ApiDeclaredItem) + .map((item) => [ + item.canonicalReference.toString(), + `#${item.displayName}`, + ]), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/source.config.ts b/libs/@local/hashql/sdk/typescript-docs/source.config.ts new file mode 100644 index 00000000000..1fceb81368c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/source.config.ts @@ -0,0 +1,33 @@ +import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins"; +import { defineConfig, defineDocs } from "fumadocs-mdx/config"; +import { transformerTwoslash } from "fumadocs-twoslash"; + +import { referenceTwoslash } from "./lib/reference-twoslash"; + +export const docs = defineDocs({ + dir: "content/docs", + docs: { compiler: "satteri" }, +}); + +export default defineConfig({ + compiler: "satteri", + satteriOptions: { + rehypeCodeOptions: { + themes: { light: "github-light", dark: "github-dark" }, + langs: ["js", "jsx", "ts", "tsx"], + transformers: [ + ...(rehypeCodeDefaultOptions.transformers ?? []), + transformerTwoslash({ + twoslashOptions: { + compilerOptions: { + types: ["node"], + module: "ESNext", + moduleResolution: "Bundler", + }, + }, + }), + referenceTwoslash(), + ], + }, + }, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json new file mode 100644 index 00000000000..cac41c44891 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.api.json @@ -0,0 +1,17 @@ +{ + "extends": "../typescript/tsconfig.json", + "compilerOptions": { + "noEmit": false, + "emitDeclarationOnly": true, + "declaration": true, + "declarationMap": true, + "outDir": ".generated/declarations", + "rootDir": "../typescript/src", + "incremental": false + }, + "include": ["../typescript/src"], + "exclude": [ + "../typescript/src/**/*.test.ts", + "../typescript/src/**/*.test-d.ts" + ] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json new file mode 100644 index 00000000000..c83d408a40f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "extends": ["@tsconfig/bases/next", "@local/tsconfig/policy.json"], + "compilerOptions": { + "allowImportingTsExtensions": true, + "checkJs": true + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + "**/*.mts", + "**/*.mjs", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts" + ], + "exclude": ["node_modules", ".generated", ".twoslash"] +} diff --git a/libs/@local/hashql/sdk/typescript-docs/tsdoc.json b/libs/@local/hashql/sdk/typescript-docs/tsdoc.json new file mode 100644 index 00000000000..10f257f74bf --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/tsdoc.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], + "tagDefinitions": [ + { + "tagName": "@category", + "syntaxKind": "block" + }, + { + "tagName": "@stability", + "syntaxKind": "block" + }, + { + "tagName": "@since", + "syntaxKind": "block" + }, + { + "tagName": "@module", + "syntaxKind": "modifier" + } + ], + "supportForTags": { + "@category": true, + "@stability": true, + "@since": true, + "@module": true + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json new file mode 100644 index 00000000000..bf06d160a83 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json @@ -0,0 +1,65 @@ +{ + "$schema": "https://turborepo.org/schema.json", + "extends": ["//"], + "tasks": { + "doc:declarations": { + "dependsOn": ["@local/hashql#manifest"], + "inputs": [ + "$TURBO_DEFAULT$", + "../typescript/src/**", + "../typescript/tsconfig.json" + ], + "outputs": [".generated/declarations/**"] + }, + "doc:model": { + "dependsOn": ["doc:declarations"], + "outputs": [".generated/api-model/**"] + }, + "doc:markdown": { + "dependsOn": ["doc:model"], + "outputs": [".generated/markdown/**"] + }, + "doc:examples": { + "dependsOn": ["doc:markdown", "@local/hashql#build"], + "outputs": [".generated/examples/**"] + }, + "doc:render": { + "dependsOn": ["doc:examples"], + "inputs": [ + "$TURBO_DEFAULT$", + "../typescript/src/**", + "$TURBO_ROOT$/oxfmt.config.ts" + ], + "outputs": ["content/docs/reference/**", "lib/reference-links.json"] + }, + "codegen": { + "dependsOn": ["doc:render"], + "outputs": [".source/**"] + }, + "build": { + "dependsOn": ["codegen"], + "env": ["NEXT_TELEMETRY_DISABLED"], + "outputs": [".next/**", "!.next/cache/**"] + }, + "dev": { + "dependsOn": ["codegen"], + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + }, + "start": { + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + }, + "lint:tsc": { + "dependsOn": ["codegen"] + }, + "lint:oxlint": { + "dependsOn": ["codegen", "@local/oxlint#build"] + }, + "test:unit": { + "dependsOn": ["doc:markdown"] + } + } +} diff --git a/libs/@local/hashql/sdk/typescript/docs/index.md b/libs/@local/hashql/sdk/typescript/docs/index.md new file mode 100644 index 00000000000..2f49d7f6a62 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/docs/index.md @@ -0,0 +1,45 @@ +# HashQL TypeScript SDK + +- What is HashQL? +- Create your first Program +- The two different notations + +HashQL is a query language designed for interacting with the HASH graph, a bi-temporal knowledge graph database which is able to represent complex relationships through the use of strongly typed ontologies. Through HashQL, users can perform advanced graph traversals, data analysis, or retrieve entities from the graph. Unlike traditional query languages, HashQL is a fully specified programming language and enables the expression of complete programs with embedded logic. It allows for chaining of multiple operations and access to different data sources transparently to the user. Similar to the HASH graph, it is strongly typed. A notable property of HashQL is that it does not prescribe a single canonical syntax; instead, it is built to be syntax-independent, with the explicit goal of allowing different ways of interacting with the underlying graph, through different languages and thereby bindings. This lets HashQL use existing tooling instead of requiring a custom toolchain, making development easier, particularly for new users. + +> HashQL programs are full programs; they are type-checked, compiled and executed by the HASH graph. + +The TypeScript SDK is such a binding that allows you to write HashQL programs in TypeScript. + +HashQL is functional and side-effect free; what does that mean? + +**Everything is an expression.** JavaScript differentiates between expressions and statements. Expressions produce values, and statements are used to bind values to names. For example, `2 + 3` is an expression that produces the value `5`, while `let x = 2 + 3` is a statement that binds the value `5` to the name `x`. + +**Fully Functional.** HashQL does not have the notion of operators, instead everything is a function call. User-defined functions? Functions. Arithmetic operations? Functions. Control flow? Functions. Binding values to names? Functions. To make this possible, HashQL has special-form functions: functions that are special in how they are evaluated; they have a reserved interpretation and cannot be created outside of the compiler. To put it another way, in Rust terms, special forms are like Rust intrinsics; like macros, they expand at compile time early in the pipeline. + +**Side-effect free.** The language is side-effect free, what does that mean? First: the language is immutable; once a value has been bound to a name, it cannot be changed. Second: an action inside the language cannot have any observable side-effects; a side-effect is something that happens outside of the language, such as I/O or modifying the environment. + +This means that HashQL only has two constructs to work with, on top of which everything else is built: function calls and values. That's it, and this, in conjunction with everything else, has some profound consequences. Let's take a look at a program that takes an input, adds 5 to it, and returns the result: + +``` +let(x, input(in, Integer), + let(y, 5, + +(x, y) + ) +) +``` + +Not very readable, is it? That's why the specification uses a special syntax to make programs easier to read and write. The same program can be written as: + +``` +let x = input(in, Integer) in +let y = 5 in +x + y +``` + +This makes it clearer what is happening; we can see the following interesting observations: + +1. `let` bindings create a new item in their scope (everything that is behind the `in` is evaluated in the new scope) +2. `let` bindings return a value: the value of the expression that it is surrounding +3. an expression **must** return a value + +Supported operators: diff --git a/libs/@local/hashql/sdk/typescript/docs/todo.md b/libs/@local/hashql/sdk/typescript/docs/todo.md new file mode 100644 index 00000000000..08afd74d4f7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/docs/todo.md @@ -0,0 +1,25 @@ +# SDK authoring and execution + +## Language guide + +- [ ] Explain HashQL's language model, including construction time versus query execution. +- [ ] Guide readers through Draft and Do, with reusable examples and advice on choosing between them. +- [ ] Document available standard-library and graph operations, supported types and current limitations. +- [ ] Check guide examples against the SDK and include a complete parameterized query through execution. + +## Execution + +- [ ] Provide separate fetch and native Effect HTTP entry points. The Effect client must not wrap the fetch client. +- [ ] Evaluate Orval for HTTP client and schema generation. Its Effect generator currently produces schemas, not an HTTP client. +- [ ] Add graph API support for query inputs. +- [ ] Define JavaScript value encoding and result decoding, preserving each program's input and result types. +- [ ] Expose program execution with client configuration, authentication, cancellation and structured diagnostics. + +## Function authoring + +- [ ] Add a typed HashQL function-expression builder to Do and Draft. Infer the return type from the body and retain captured input requirements. Provide typed parameter handles and match the existing callback-exception behavior. Bind named functions through the existing `Let`/`let` APIs. Raw `JExpr.fn` and callable expression types already exist. + +## Authoring checks + +- [ ] Return Do callback exceptions as construction failures, matching Draft. +- [ ] Add Oxlint binding-name checks and warnings for native operators on expression handles or host control flow inside authoring callbacks. diff --git a/yarn.lock b/yarn.lock index 1f1f2e66abf..d7ecda14875 100644 --- a/yarn.lock +++ b/yarn.lock @@ -74,6 +74,13 @@ __metadata: languageName: node linkType: hard +"@alloc/quick-lru@npm:^5.2.0": + version: 5.3.0 + resolution: "@alloc/quick-lru@npm:5.3.0" + checksum: 10c0/de92309b58674d17e627e43b73db9744a7f47d1987f1e3995ed0b3bb218b25df61940cc311a3c83429bc482e140f3d90851725cac5250222f9a9a5e5ec8a4343 + languageName: node + linkType: hard + "@anthropic-ai/bedrock-sdk@npm:0.26.3": version: 0.26.3 resolution: "@anthropic-ai/bedrock-sdk@npm:0.26.3" @@ -4185,9 +4192,9 @@ __metadata: linkType: hard "@babel/runtime@npm:^7.0.0, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.13.10, @babel/runtime@npm:^7.15.4, @babel/runtime@npm:^7.16.3, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.18.6, @babel/runtime@npm:^7.23.8, @babel/runtime@npm:^7.23.9, @babel/runtime@npm:^7.24.5, @babel/runtime@npm:^7.26.0, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.28.4, @babel/runtime@npm:^7.28.6, @babel/runtime@npm:^7.29.7, @babel/runtime@npm:^7.5.5, @babel/runtime@npm:^7.7.6, @babel/runtime@npm:^7.8.7, @babel/runtime@npm:^7.9.2": - version: 7.29.7 - resolution: "@babel/runtime@npm:7.29.7" - checksum: 10c0/ca11572f7146b21e0bde6a9ed4bb6a89eafbee5f0944c7eb54d0d8a2dac962c33638a1d611e14faa71dfbb92b4b5f9236232208568a6b7d5c6f3f39ddb91771e + version: 7.29.10 + resolution: "@babel/runtime@npm:7.29.10" + checksum: 10c0/32f975da8e9c2cae6b33e1a477f8fe8bbff6722c982b5ce35f99affaf3a7a1b612c8272b43afa0e51d3000928d6f3ba38f9296301115db5640264907c027b0cd languageName: node linkType: hard @@ -4270,7 +4277,7 @@ __metadata: languageName: node linkType: hard -"@base-ui/react@npm:1.8.0": +"@base-ui/react@npm:1.8.0, @base-ui/react@npm:^1.8.0": version: 1.8.0 resolution: "@base-ui/react@npm:1.8.0" dependencies: @@ -5551,7 +5558,7 @@ __metadata: languageName: node linkType: hard -"@emnapi/core@npm:1.11.2, @emnapi/core@npm:^1.4.3": +"@emnapi/core@npm:1.11.2": version: 1.11.2 resolution: "@emnapi/core@npm:1.11.2" dependencies: @@ -5571,6 +5578,16 @@ __metadata: languageName: node linkType: hard +"@emnapi/core@npm:^1.11.1, @emnapi/core@npm:^1.4.3": + version: 1.11.3 + resolution: "@emnapi/core@npm:1.11.3" + dependencies: + "@emnapi/wasi-threads": "npm:1.2.3" + tslib: "npm:^2.4.0" + checksum: 10c0/4ca08d349a82d5d2887ccc9e12df630877b0412ddcd59b9faee61e3c3947ccead27a18257a18bfe17abdf2b0709857808ad75d423ac49edd50c32fb140a7ed6e + languageName: node + linkType: hard + "@emnapi/runtime@npm:1.11.1": version: 1.11.1 resolution: "@emnapi/runtime@npm:1.11.1" @@ -5598,7 +5615,7 @@ __metadata: languageName: node linkType: hard -"@emnapi/runtime@npm:^1.11.3, @emnapi/runtime@npm:^1.4.3": +"@emnapi/runtime@npm:^1.11.1, @emnapi/runtime@npm:^1.11.3, @emnapi/runtime@npm:^1.4.3": version: 1.11.3 resolution: "@emnapi/runtime@npm:1.11.3" dependencies: @@ -5625,6 +5642,15 @@ __metadata: languageName: node linkType: hard +"@emnapi/wasi-threads@npm:1.2.3, @emnapi/wasi-threads@npm:^1.2.2": + version: 1.2.3 + resolution: "@emnapi/wasi-threads@npm:1.2.3" + dependencies: + tslib: "npm:^2.4.0" + checksum: 10c0/5aed84bc5dbe867973b20406ca1ed95661a4892ecaef80378fdf2d37424b3f7b9c428df8a3e1d82b783a3345a530032bf049e699e1f113ea52203c3e9b4e6ce5 + languageName: node + linkType: hard + "@emotion/babel-plugin@npm:^11.13.5": version: 11.13.5 resolution: "@emotion/babel-plugin@npm:11.13.5" @@ -6819,6 +6845,104 @@ __metadata: languageName: node linkType: hard +"@fuma-translate/react@npm:^1.0.2": + version: 1.0.2 + resolution: "@fuma-translate/react@npm:1.0.2" + peerDependencies: + "@types/react": "*" + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/459792f25c4dbe682cddaaeef0d0eee9bf10779a160797c2a959746c87cd754337287437508a0e8d300c1078145c496265ec0919f154be42f6a685bf480fda78 + languageName: node + linkType: hard + +"@fumadocs/local-content@npm:0.2.2": + version: 0.2.2 + resolution: "@fumadocs/local-content@npm:0.2.2" + dependencies: + chokidar: "npm:^5.0.0" + picomatch: "npm:^4.0.7" + tinyglobby: "npm:^0.2.17" + ws: "npm:^8.21.3" + peerDependencies: + "@types/react": "*" + fumadocs-core: ^16.15.0 + react: ^19.2.0 + vite: ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + "@types/react": + optional: true + react: + optional: true + vite: + optional: true + checksum: 10c0/aa67643d9c9dbf588bbb6afce595df645213201fcdf1bb3d3a4e5d7b29726e9136818a980c330be4bbdfb8150d9846ce492a6559cc505e6e632945e50834573f + languageName: node + linkType: hard + +"@fumadocs/satteri@npm:0.5.1": + version: 0.5.1 + resolution: "@fumadocs/satteri@npm:0.5.1" + dependencies: + "@fumadocs/local-content": "npm:0.2.2" + "@fumari/image-size": "npm:^0.1.1" + "@standard-schema/spec": "npm:^1.1.0" + estree-util-to-js: "npm:^2.0.0" + fumadocs-typescript: "npm:^5.4.1" + github-slugger: "npm:^2.0.0" + hast-util-to-estree: "npm:^3.1.3" + katex: "npm:^0.18.7" + npm-to-yarn: "npm:^3.2.0" + satteri: "npm:^0.10.5" + yuku-codegen: "npm:^0.9.5" + yuku-parser: "npm:^0.9.5" + peerDependencies: + "@types/hast": "*" + "@types/mdast": "*" + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: ^16.15.3 + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/mdx": + optional: true + "@types/react": + optional: true + react: + optional: true + react-dom: + optional: true + checksum: 10c0/20d5eeceeaf4498f41f8f3eead554af61612189a78f4f7f94c3f4fef56b9af32a9a6386c5901c43d4aa0e2debc5b65de6422d164ca097f9d2070715d69025c30 + languageName: node + linkType: hard + +"@fumadocs/tailwind@npm:0.1.2": + version: 0.1.2 + resolution: "@fumadocs/tailwind@npm:0.1.2" + peerDependencies: + tailwindcss: ^4.0.0 + peerDependenciesMeta: + tailwindcss: + optional: true + checksum: 10c0/f15abd61032f59d2db428a916eb215322075f19fc57a11b127910a89ce2c25e1a88cd10cb9cef1cbe8fdd6a3502cd03d6933a04383c266eef2dd0505d311b801 + languageName: node + linkType: hard + +"@fumari/image-size@npm:^0.1.1": + version: 0.1.1 + resolution: "@fumari/image-size@npm:0.1.1" + checksum: 10c0/80f645cfffd67f3fd4e25897e2a0c1f65c0f4a786b512c48b0f0c897d5d6e19779b4b1467aae1e0012650bc1a9ee63478775cf93dc05a3de617c32278ce34624 + languageName: node + linkType: hard + "@glideapps/glide-data-grid@npm:6.0.3": version: 6.0.3 resolution: "@glideapps/glide-data-grid@npm:6.0.3" @@ -10105,7 +10229,50 @@ __metadata: languageName: unknown linkType: soft -"@local/hashql@workspace:libs/@local/hashql/sdk/typescript": +"@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs": + version: 0.0.0-use.local + resolution: "@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs" + dependencies: + "@fumadocs/satteri": "npm:0.5.1" + "@local/hashql": "workspace:*" + "@local/oxlint": "workspace:*" + "@local/tsconfig": "workspace:*" + "@microsoft/api-documenter": "npm:7.30.18" + "@microsoft/api-extractor": "npm:7.59.4" + "@microsoft/api-extractor-model": "npm:7.33.15" + "@microsoft/tsdoc": "npm:0.17.1" + "@microsoft/tsdoc-config": "npm:0.18.3" + "@tailwindcss/postcss": "npm:4.3.3" + "@tsconfig/bases": "catalog:" + "@types/hast": "npm:3.0.5" + "@types/mdast": "npm:4.0.4" + "@types/mdx": "npm:2.0.14" + "@types/node": "catalog:" + "@types/react": "npm:19.2.14" + "@types/react-dom": "npm:19.2.3" + effect: "npm:4.0.0" + fumadocs-core: "npm:16.16.2" + fumadocs-mdx: "npm:15.4.6" + fumadocs-twoslash: "npm:4.0.1" + fumadocs-ui: "npm:16.16.2" + next: "npm:16.3.8" + oxfmt: "npm:0.71.0" + oxlint: "catalog:" + react: "npm:19.2.6" + react-dom: "npm:19.2.6" + remark-mdx: "npm:3.1.1" + remark-parse: "npm:11.0.0" + remark-stringify: "npm:11.0.0" + satteri: "npm:0.10.5" + shiki: "npm:4.5.0" + tailwindcss: "npm:4.3.3" + tsx: "catalog:" + typescript: "catalog:" + unified: "npm:11.0.5" + languageName: unknown + linkType: soft + +"@local/hashql@workspace:*, @local/hashql@workspace:libs/@local/hashql/sdk/typescript": version: 0.0.0-use.local resolution: "@local/hashql@workspace:libs/@local/hashql/sdk/typescript" dependencies: @@ -10493,6 +10660,57 @@ __metadata: languageName: node linkType: hard +"@microsoft/api-documenter@npm:7.30.18": + version: 7.30.18 + resolution: "@microsoft/api-documenter@npm:7.30.18" + dependencies: + "@microsoft/api-extractor-model": "npm:7.33.15" + "@microsoft/tsdoc": "npm:~0.17.0" + "@rushstack/node-core-library": "npm:5.25.1" + "@rushstack/terminal": "npm:0.24.7" + "@rushstack/ts-command-line": "npm:5.3.17" + js-yaml: "npm:~4.3.2" + resolve: "npm:~1.22.1" + bin: + api-documenter: bin/api-documenter + checksum: 10c0/47277a9a10a2c916ffb6cf1d918a9a78002ea09d3743f1c9449af42855166227aad9c80d5b2bc298c71d658bfb155f0298480c5fc7c6e38637d308f5b2a116db + languageName: node + linkType: hard + +"@microsoft/api-extractor-model@npm:7.33.15": + version: 7.33.15 + resolution: "@microsoft/api-extractor-model@npm:7.33.15" + dependencies: + "@microsoft/tsdoc": "npm:~0.17.0" + "@microsoft/tsdoc-config": "npm:~0.18.2" + "@rushstack/node-core-library": "npm:5.25.1" + checksum: 10c0/7dce2166e3d5c0f562f99893f2b8a078e24121ed57a10970e3bcbf33cc13916dc4fd2523b685e60288d058a4b3557fa9759320cb529683a5ad743bb80e943a58 + languageName: node + linkType: hard + +"@microsoft/api-extractor@npm:7.59.4": + version: 7.59.4 + resolution: "@microsoft/api-extractor@npm:7.59.4" + dependencies: + "@microsoft/api-extractor-model": "npm:7.33.15" + "@microsoft/tsdoc": "npm:~0.17.0" + "@microsoft/tsdoc-config": "npm:~0.18.2" + "@rushstack/node-core-library": "npm:5.25.1" + "@rushstack/rig-package": "npm:0.7.4" + "@rushstack/terminal": "npm:0.24.7" + "@rushstack/ts-command-line": "npm:5.3.17" + diff: "npm:~8.0.2" + minimatch: "npm:10.2.3" + resolve: "npm:~1.22.1" + semver: "npm:~7.7.4" + source-map: "npm:~0.6.1" + typescript: "npm:5.9.3" + bin: + api-extractor: bin/api-extractor + checksum: 10c0/2b805f72318edb8dab720a2b2eb2a6b82faebbb6a6b5b836fced38875e61d344b14c7edf63724a27ab091fed4df8ef9923141f579fb1ddc7679d48ce02301e96 + languageName: node + linkType: hard + "@microsoft/fetch-event-source@npm:^2.0.1": version: 2.0.1 resolution: "@microsoft/fetch-event-source@npm:2.0.1" @@ -10512,6 +10730,18 @@ __metadata: languageName: node linkType: hard +"@microsoft/tsdoc-config@npm:0.18.3, @microsoft/tsdoc-config@npm:~0.18.2": + version: 0.18.3 + resolution: "@microsoft/tsdoc-config@npm:0.18.3" + dependencies: + "@microsoft/tsdoc": "npm:0.17.1" + ajv: "npm:~8.18.0" + jju: "npm:~1.4.0" + resolve: "npm:~1.22.2" + checksum: 10c0/8a065caa452bb7f6aa6b0cf95acad970b7e10af39a856988ba5df7e19bc482444454f7dc48b86d98908b6600b009757c34a769ba302e3bc5ef04d1076ac71fc9 + languageName: node + linkType: hard + "@microsoft/tsdoc@npm:0.16.0": version: 0.16.0 resolution: "@microsoft/tsdoc@npm:0.16.0" @@ -10519,6 +10749,13 @@ __metadata: languageName: node linkType: hard +"@microsoft/tsdoc@npm:0.17.1, @microsoft/tsdoc@npm:~0.17.0": + version: 0.17.1 + resolution: "@microsoft/tsdoc@npm:0.17.1" + checksum: 10c0/a8d5dd60edc60a8f4de7b1b260cd0633205457a630316b75fd2afe0a633d3acd3389b4e483c047d681981da89cd6448e8f6e0387dc32533ecd63fbce3a580a92 + languageName: node + linkType: hard + "@modelcontextprotocol/client@npm:2.0.0": version: 2.0.0 resolution: "@modelcontextprotocol/client@npm:2.0.0" @@ -13612,6 +13849,13 @@ __metadata: languageName: node linkType: hard +"@radix-ui/number@npm:1.1.3": + version: 1.1.3 + resolution: "@radix-ui/number@npm:1.1.3" + checksum: 10c0/da682127b62196a617d30d8b085a0b422b067a6155982aa313d33824cbeae16b95547a41ec74e0cf8cb67b30f5f825b3e9222abf6871b2ae0bf12badad4310d6 + languageName: node + linkType: hard + "@radix-ui/primitive@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/primitive@npm:1.0.1" @@ -13628,6 +13872,40 @@ __metadata: languageName: node linkType: hard +"@radix-ui/primitive@npm:1.1.7": + version: 1.1.7 + resolution: "@radix-ui/primitive@npm:1.1.7" + checksum: 10c0/6b1f8b964a57ece3490582d60df79a1c80fdba4c4331b806c4e04b11f42ac46d40a927bfc692dbd881136ec38c3f060c525dbacd6182ba6f3f0bd4284db1028e + languageName: node + linkType: hard + +"@radix-ui/react-accordion@npm:^1.2.20": + version: 1.2.21 + resolution: "@radix-ui/react-accordion@npm:1.2.21" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collapsible": "npm:1.1.21" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/7bf0870e37ea16081a265fc64b6da4cf08c02705acc8abb083bda49f5d17f0bb4fc277cb64aa9644c94dbf5128cf059b126fb31d9753ac37e2cb28e0f4468457 + languageName: node + linkType: hard + "@radix-ui/react-alert-dialog@npm:^1.0.0": version: 1.1.2 resolution: "@radix-ui/react-alert-dialog@npm:1.1.2" @@ -13691,6 +13969,51 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-arrow@npm:1.1.16": + version: 1.1.16 + resolution: "@radix-ui/react-arrow@npm:1.1.16" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/4415c516475e8468a0f23643e0a31f7642b53c2f53039324d82a969cf69239822b80350a42cf52f66300562e345c542fba9cd715ddaaadc0c695db510d606682 + languageName: node + linkType: hard + +"@radix-ui/react-collapsible@npm:1.1.21, @radix-ui/react-collapsible@npm:^1.1.20": + version: 1.1.21 + resolution: "@radix-ui/react-collapsible@npm:1.1.21" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/6e1ec58ef0848f1ec932a783456a9b5938a5de67adee2203ddb95c32b54e73c9a2858583db18853f8a8e237655f33fb15c7deb12c3d9ccbe4c923c53b312a2c1 + languageName: node + linkType: hard + "@radix-ui/react-collection@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-collection@npm:1.0.3" @@ -13736,6 +14059,28 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-collection@npm:1.1.16": + version: 1.1.16 + resolution: "@radix-ui/react-collection@npm:1.1.16" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/625282244a1b90d8dda98ec325cad7bf0a18134d7b3eade8e3a5af3403872f5e9261c90155e368e120a3836816d724c26c0890faa06231f54b6582ce11c622af + languageName: node + linkType: hard + "@radix-ui/react-compose-refs@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-compose-refs@npm:1.0.1" @@ -13764,6 +14109,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-compose-refs@npm:1.1.5": + version: 1.1.5 + resolution: "@radix-ui/react-compose-refs@npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/ab5cc8cc2f5be285981cffb64aa956d3a28427c649a953d125e900e1befb8b9a55f2d7a31bc01059d29df43ff4ae14ebc6cca7e4c2084d638cef5e5aef7cc263 + languageName: node + linkType: hard + "@radix-ui/react-context-menu@npm:^2.1.1": version: 2.2.2 resolution: "@radix-ui/react-context-menu@npm:2.2.2" @@ -13829,7 +14187,20 @@ __metadata: languageName: node linkType: hard -"@radix-ui/react-dialog@npm:1.1.2, @radix-ui/react-dialog@npm:^1.0.2": +"@radix-ui/react-context@npm:1.2.2": + version: 1.2.2 + resolution: "@radix-ui/react-context@npm:1.2.2" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/f5c15339558d64901c99f243a2538be9b28eb20e0dae1e44c8872ed12580ec27f5f309fd491f85f1b0dcb214c90fdae7eede7fe2b0d26569c4dbeffbeff451c0 + languageName: node + linkType: hard + +"@radix-ui/react-dialog@npm:1.1.2": version: 1.1.2 resolution: "@radix-ui/react-dialog@npm:1.1.2" dependencies: @@ -13861,6 +14232,39 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-dialog@npm:^1.0.2, @radix-ui/react-dialog@npm:^1.1.23": + version: 1.2.0 + resolution: "@radix-ui/react-dialog@npm:1.2.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-focus-guards": "npm:1.1.6" + "@radix-ui/react-focus-scope": "npm:1.2.0" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-portal": "npm:1.1.18" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + aria-hidden: "npm:^1.2.4" + react-remove-scroll: "npm:^2.7.2" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/f84958bed5ffaefb9d257cda6193f5ef79c48f0b8aec2fe3fa86aabf0c44edd2a1e6d969e399c3ead5623ff4c1040b365ef48ed5c4d4a36c2d8125bc41440e5d + languageName: node + linkType: hard + "@radix-ui/react-direction@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-direction@npm:1.0.1" @@ -13889,6 +14293,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-direction@npm:1.1.5, @radix-ui/react-direction@npm:^1.1.4": + version: 1.1.5 + resolution: "@radix-ui/react-direction@npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/a59a145b93fef5d101dff28dba7f5877aa6a051d9ae1106e8d80b73305f3d3d46f54195377eb690524e7954323e3cdc15d757e85da233a77d116c8b3491ada5e + languageName: node + linkType: hard + "@radix-ui/react-dismissable-layer@npm:1.0.4": version: 1.0.4 resolution: "@radix-ui/react-dismissable-layer@npm:1.0.4" @@ -13936,6 +14353,29 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-dismissable-layer@npm:1.1.20": + version: 1.1.20 + resolution: "@radix-ui/react-dismissable-layer@npm:1.1.20" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-effect-event": "npm:0.0.5" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/cd42f18d72fd30fed0b8e9888f8da204d315ffa4d55209d3a713950eb6c81666b4bb46d0b07625d0c3bd86e9ce6ac2ed1489e03b166f4944cc4524289b2820e8 + languageName: node + linkType: hard + "@radix-ui/react-dropdown-menu@npm:^2.0.1": version: 2.1.2 resolution: "@radix-ui/react-dropdown-menu@npm:2.1.2" @@ -13989,6 +14429,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-focus-guards@npm:1.1.6": + version: 1.1.6 + resolution: "@radix-ui/react-focus-guards@npm:1.1.6" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/5579dfe369f254183a010964e6df8b74c7b36e50189aef18c92538d0196785d68869e3170af77005276f393cd112b7711d5c7cb9e7ec2ca1e0b4794157447978 + languageName: node + linkType: hard + "@radix-ui/react-focus-scope@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-focus-scope@npm:1.0.3" @@ -14032,6 +14485,27 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-focus-scope@npm:1.2.0": + version: 1.2.0 + resolution: "@radix-ui/react-focus-scope@npm:1.2.0" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/67a62110fdf44172f9da44b4b05b2723ab96a4045b5f4e98445cf18825e12456972860852779802200047ad37f9f192884633de11918f066ca8a27b4ad4c3161 + languageName: node + linkType: hard + "@radix-ui/react-id@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-id@npm:1.0.1" @@ -14063,6 +14537,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-id@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-id@npm:1.1.4" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/7afa00d12d7f52b5067034108eb7d5551928f9d52875589f858ea1d5117cac3684f8ea291d4f09a88b9499bc4bb6e3279e4a9073d7c8feb15a855d28656b53a4 + languageName: node + linkType: hard + "@radix-ui/react-menu@npm:2.1.2": version: 2.1.2 resolution: "@radix-ui/react-menu@npm:2.1.2" @@ -14099,25 +14588,25 @@ __metadata: languageName: node linkType: hard -"@radix-ui/react-popover@npm:^1.0.2": - version: 1.1.2 - resolution: "@radix-ui/react-popover@npm:1.1.2" - dependencies: - "@radix-ui/primitive": "npm:1.1.0" - "@radix-ui/react-compose-refs": "npm:1.1.0" - "@radix-ui/react-context": "npm:1.1.1" - "@radix-ui/react-dismissable-layer": "npm:1.1.1" - "@radix-ui/react-focus-guards": "npm:1.1.1" - "@radix-ui/react-focus-scope": "npm:1.1.0" - "@radix-ui/react-id": "npm:1.1.0" - "@radix-ui/react-popper": "npm:1.2.0" - "@radix-ui/react-portal": "npm:1.1.2" - "@radix-ui/react-presence": "npm:1.1.1" - "@radix-ui/react-primitive": "npm:2.0.0" - "@radix-ui/react-slot": "npm:1.1.0" - "@radix-ui/react-use-controllable-state": "npm:1.1.0" - aria-hidden: "npm:^1.1.1" - react-remove-scroll: "npm:2.6.0" +"@radix-ui/react-navigation-menu@npm:^1.2.22": + version: 1.3.0 + resolution: "@radix-ui/react-navigation-menu@npm:1.3.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + "@radix-ui/react-use-previous": "npm:1.1.4" + "@radix-ui/react-visually-hidden": "npm:1.2.12" peerDependencies: "@types/react": "*" "@types/react-dom": "*" @@ -14128,7 +14617,41 @@ __metadata: optional: true "@types/react-dom": optional: true - checksum: 10c0/d8fb4e3507a3cd6168bdbb6b840fb8eb538b3b1ce62192a1dcc4e8e4947fbf082c437c0ad5f6faed078006dcb7073867e493378d04c50372c6ea826c5a811f2c + checksum: 10c0/6bc91839b2ae091dcbb3d0a3a9454f2353f8a70f1f54b6186538e3ce511aec6df27b8ab06286914313b899fbfaa6bc80f68ee63f9bbdff842921200c43730c56 + languageName: node + linkType: hard + +"@radix-ui/react-popover@npm:^1.0.2, @radix-ui/react-popover@npm:^1.1.23": + version: 1.2.0 + resolution: "@radix-ui/react-popover@npm:1.2.0" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-dismissable-layer": "npm:1.1.20" + "@radix-ui/react-focus-guards": "npm:1.1.6" + "@radix-ui/react-focus-scope": "npm:1.2.0" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-popper": "npm:1.3.8" + "@radix-ui/react-portal": "npm:1.1.18" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + aria-hidden: "npm:^1.2.4" + react-remove-scroll: "npm:^2.7.2" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/98d4dfc51814bc687626d49d1d2a266b7ed55f46b3e76c311f7bb08c9db574da30dfcd997bad9fb1c00d863d7fc2d0592f02ef73596025904b19a209cdd72e68 languageName: node linkType: hard @@ -14189,6 +14712,34 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-popper@npm:1.3.8": + version: 1.3.8 + resolution: "@radix-ui/react-popper@npm:1.3.8" + dependencies: + "@floating-ui/react-dom": "npm:^2.0.0" + "@radix-ui/react-arrow": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + "@radix-ui/react-use-rect": "npm:1.1.4" + "@radix-ui/react-use-size": "npm:1.1.5" + "@radix-ui/rect": "npm:1.1.3" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/4ffdb1ac696cd3dfdeb14e994f37f8c483977ffdb8ca7c1ae7de3a5e819588f094a63b163f255e6f02e35e5a22d488a2bad78ca63825777aebc547e026378aca + languageName: node + linkType: hard + "@radix-ui/react-portal@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-portal@npm:1.0.3" @@ -14209,6 +14760,26 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-portal@npm:1.1.18": + version: 1.1.18 + resolution: "@radix-ui/react-portal@npm:1.1.18" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/f24928e9bdb9d2c3a6e97598eb4631e1be61419775b445b03c07e402aebf36c1ed12bfc0e6b21c536ebbe17fb50a0cad410d7463b3af2f04e5b4302a817517e9 + languageName: node + linkType: hard + "@radix-ui/react-portal@npm:1.1.2": version: 1.1.2 resolution: "@radix-ui/react-portal@npm:1.1.2" @@ -14249,6 +14820,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-presence@npm:1.1.11, @radix-ui/react-presence@npm:^1.1.10": + version: 1.1.11 + resolution: "@radix-ui/react-presence@npm:1.1.11" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/480ab17f9a2a1d962d7a6b8f7d3ca0342fd4124a22c70d6dce4d4b54a0ffd60e5863ca3ad351a9132e565b4d6eeb479162f7449b5a42cdd7e294bf6b8247d9ba + languageName: node + linkType: hard + "@radix-ui/react-primitive@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-primitive@npm:1.0.3" @@ -14288,6 +14878,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-primitive@npm:2.1.11": + version: 2.1.11 + resolution: "@radix-ui/react-primitive@npm:2.1.11" + dependencies: + "@radix-ui/react-slot": "npm:1.4.0" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/686665064e118791fa484fc9dbf3e6106b3876620fc5fa82b50919801c9d683b648de7b3db03d6c700407c5bc1820156437899f74776adb76226fb62ef9a79f6 + languageName: node + linkType: hard + "@radix-ui/react-roving-focus@npm:1.1.0": version: 1.1.0 resolution: "@radix-ui/react-roving-focus@npm:1.1.0" @@ -14315,6 +14924,63 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-roving-focus@npm:1.1.20": + version: 1.1.20 + resolution: "@radix-ui/react-roving-focus@npm:1.1.20" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-collection": "npm:1.1.16" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + "@radix-ui/react-use-is-hydrated": "npm:0.1.3" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/2074812db86c2c348af80f0505d24e863e2771538083ed7acf4f515a749a06beed19ff9590fb98a9c3aacd981a27d3c3f002036713cfe72e3076863dde02b273 + languageName: node + linkType: hard + +"@radix-ui/react-scroll-area@npm:^1.2.18": + version: 1.3.0 + resolution: "@radix-ui/react-scroll-area@npm:1.3.0" + dependencies: + "@radix-ui/number": "npm:1.1.3" + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-compose-refs": "npm:1.1.5" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-slot": "npm:1.4.0" + "@radix-ui/react-use-callback-ref": "npm:1.1.4" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/ec144e0b42036631dd1d898412f5638f2a1b45dfc0b91fc0fe9dca348c5044120e324a095c95f576df2aa00a7f734cafd9d95cee893f97552a483e13455f17f6 + languageName: node + linkType: hard + "@radix-ui/react-select@npm:^1.2.0": version: 1.2.2 resolution: "@radix-ui/react-select@npm:1.2.2" @@ -14415,6 +15081,47 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-slot@npm:1.4.0, @radix-ui/react-slot@npm:^1.3.3": + version: 1.4.0 + resolution: "@radix-ui/react-slot@npm:1.4.0" + dependencies: + "@radix-ui/react-compose-refs": "npm:1.1.5" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/a8c5be704183d4e388280191d6245458b45b059ea8530a523e8f87820b6eab407e06b749f63df5284204e66fc2ba5c8a934a74c61a17272f79ca98eae1403baa + languageName: node + linkType: hard + +"@radix-ui/react-tabs@npm:^1.1.21": + version: 1.1.22 + resolution: "@radix-ui/react-tabs@npm:1.1.22" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-context": "npm:1.2.2" + "@radix-ui/react-direction": "npm:1.1.5" + "@radix-ui/react-id": "npm:1.1.4" + "@radix-ui/react-presence": "npm:1.1.11" + "@radix-ui/react-primitive": "npm:2.1.11" + "@radix-ui/react-roving-focus": "npm:1.1.20" + "@radix-ui/react-use-controllable-state": "npm:1.2.6" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/5cc3698ec307606bd0f5a2e6c0d273aaf958e344d6035f071566b0372cceae1ecd8827ea92745e4bd0a1f1264014ad3366cc72f094c161e0fdac20922826ea00 + languageName: node + linkType: hard + "@radix-ui/react-toast@npm:^1.1.1": version: 1.2.2 resolution: "@radix-ui/react-toast@npm:1.2.2" @@ -14473,6 +15180,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-callback-ref@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-callback-ref@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/d5cc1248ab6a58b12eefd3115c98fb438b74b2e6dec463d2e097d27df8e9f40b9d8693ee10a422da4f7a688fbe52c62cc2fe3aa5972020b9425b86a2a28f5f01 + languageName: node + linkType: hard + "@radix-ui/react-use-controllable-state@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-controllable-state@npm:1.0.1" @@ -14504,6 +15224,38 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-controllable-state@npm:1.2.6": + version: 1.2.6 + resolution: "@radix-ui/react-use-controllable-state@npm:1.2.6" + dependencies: + "@radix-ui/primitive": "npm:1.1.7" + "@radix-ui/react-use-effect-event": "npm:0.0.5" + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/1672c3fa5c1f2dbc354db4d403523eef15bcbe24448b911e67e3e95f351b72ffc1dc1021a225d98116cd78d1c96e6280f1645ac6d6b9930df46b180b8a6f11a5 + languageName: node + linkType: hard + +"@radix-ui/react-use-effect-event@npm:0.0.5": + version: 0.0.5 + resolution: "@radix-ui/react-use-effect-event@npm:0.0.5" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/36eb3523d3c30e88615e0492aed5c644e61eb4fec98097de0fb2ee1cf33d7684b76e8a34bedb0aa7c25b412e0ef56c83b16772e9716d03d61901bc1b98cb1993 + languageName: node + linkType: hard + "@radix-ui/react-use-escape-keydown@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-use-escape-keydown@npm:1.0.3" @@ -14535,6 +15287,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-is-hydrated@npm:0.1.3": + version: 0.1.3 + resolution: "@radix-ui/react-use-is-hydrated@npm:0.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/ec5d8cd7dcb825d23c9e622cb78605242ae6ae5744549f4713fd543a2a2003c356031bac3bd8db353579e6cd9f71798b59915f54de7b78b442e847024f2a5ff9 + languageName: node + linkType: hard + "@radix-ui/react-use-layout-effect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-layout-effect@npm:1.0.1" @@ -14563,6 +15328,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-layout-effect@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-layout-effect@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/427df10bb3c55de36afd6b9a749fb4b72b0f78840ae4abb5dda24aa09d653ede2d264c96a8030f58db353498f42b2bce929510c777004e250f7845b06c782bcf + languageName: node + linkType: hard + "@radix-ui/react-use-previous@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-previous@npm:1.0.1" @@ -14591,6 +15369,19 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-previous@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-previous@npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/e291d635ef2ec1813ad499aa4d14b6da81042831549140e8a71ab982540322a9abbe629ebffb175258b9c60e77fd0736b9b4fe1cd76066912fd5270783030778 + languageName: node + linkType: hard + "@radix-ui/react-use-rect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-rect@npm:1.0.1" @@ -14622,6 +15413,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-rect@npm:1.1.4": + version: 1.1.4 + resolution: "@radix-ui/react-use-rect@npm:1.1.4" + dependencies: + "@radix-ui/rect": "npm:1.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/3acfe9265f9fbdcdead05ec4540a95d8932fb53e9eabd73c080650122424d3d5247260d349ea2d91b2712af9670a27ac2110400671b98d061b2347390fe29490 + languageName: node + linkType: hard + "@radix-ui/react-use-size@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/react-use-size@npm:1.0.1" @@ -14653,6 +15459,21 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-use-size@npm:1.1.5": + version: 1.1.5 + resolution: "@radix-ui/react-use-size@npm:1.1.5" + dependencies: + "@radix-ui/react-use-layout-effect": "npm:1.1.4" + peerDependencies: + "@types/react": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/03f05b04f6bd342e07b749d9e92700e21c3d0e5309d2d5d1f4fab719e76f4db5d21683b664c491b9fdebccbfe798f37a12deb6e6afd99ce2b2e4a58eae649811 + languageName: node + linkType: hard + "@radix-ui/react-visually-hidden@npm:1.0.3": version: 1.0.3 resolution: "@radix-ui/react-visually-hidden@npm:1.0.3" @@ -14692,6 +15513,25 @@ __metadata: languageName: node linkType: hard +"@radix-ui/react-visually-hidden@npm:1.2.12": + version: 1.2.12 + resolution: "@radix-ui/react-visually-hidden@npm:1.2.12" + dependencies: + "@radix-ui/react-primitive": "npm:2.1.11" + peerDependencies: + "@types/react": "*" + "@types/react-dom": "*" + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + "@types/react-dom": + optional: true + checksum: 10c0/37202abfe37d26167199988d375ecdcd973c6f0e95d486645fb671d5f963a7b4ceaf1c18b5d20df7e3ff82b04ba6fc0ec3ab321017d12e8b620b4f7d181833a9 + languageName: node + linkType: hard + "@radix-ui/rect@npm:1.0.1": version: 1.0.1 resolution: "@radix-ui/rect@npm:1.0.1" @@ -14708,6 +15548,13 @@ __metadata: languageName: node linkType: hard +"@radix-ui/rect@npm:1.1.3": + version: 1.1.3 + resolution: "@radix-ui/rect@npm:1.1.3" + checksum: 10c0/9396d6c4dbd8da51c0bef7481e1e46e7f371e27cc6a55c1079e854f3aa9f7dd89e02d98cc36e861e8d43fbb775eb76b06bdf5879fa12f25116bea676af2926da + languageName: node + linkType: hard + "@react-sigma/core@npm:4.0.3": version: 4.0.3 resolution: "@react-sigma/core@npm:4.0.3" @@ -15411,6 +16258,77 @@ __metadata: languageName: node linkType: hard +"@rushstack/node-core-library@npm:5.25.1": + version: 5.25.1 + resolution: "@rushstack/node-core-library@npm:5.25.1" + dependencies: + ajv: "npm:~8.20.0" + ajv-draft-04: "npm:~1.0.0" + ajv-formats: "npm:~3.0.1" + fs-extra: "npm:~11.3.0" + import-lazy: "npm:~4.0.0" + jju: "npm:~1.4.0" + resolve: "npm:~1.22.1" + semver: "npm:~7.7.4" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/914fe8144516d4d2162ae734eb00772952245aa0c9ba861320f9165dd893e4283ace0ec2892e15a2418e0232155a64445d69ba886756bc33f4d1369dad776b85 + languageName: node + linkType: hard + +"@rushstack/problem-matcher@npm:0.2.1": + version: 0.2.1 + resolution: "@rushstack/problem-matcher@npm:0.2.1" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/d6cf27f6bfcdc00763e6d51e582d4faef7109ba8906e6bb3bc375edae551c54a589ed61b7e01e9ae1dbdd4a7075fd82f2da541918b52f2233d6c86393beeaaa7 + languageName: node + linkType: hard + +"@rushstack/rig-package@npm:0.7.4": + version: 0.7.4 + resolution: "@rushstack/rig-package@npm:0.7.4" + dependencies: + jju: "npm:~1.4.0" + resolve: "npm:~1.22.1" + checksum: 10c0/0a279f10760e6b2f1252d69dc54b3912ee6e15c510f68185297c447994bfa7bb0ad5c59893b50ad3378efb0a00cd0470f537e559df2d34c60880f68ce3741d0b + languageName: node + linkType: hard + +"@rushstack/terminal@npm:0.24.7": + version: 0.24.7 + resolution: "@rushstack/terminal@npm:0.24.7" + dependencies: + "@rushstack/node-core-library": "npm:5.25.1" + "@rushstack/problem-matcher": "npm:0.2.1" + supports-color: "npm:~8.1.1" + peerDependencies: + "@types/node": "*" + peerDependenciesMeta: + "@types/node": + optional: true + checksum: 10c0/c47827b37bedb25bc572e1564b847a082ed6a6017d8ac73020e4cbd27ddbca298b5970f949026ae381755b12c531f0d9600e59fbd9a4b5373d5d9069b90a14f7 + languageName: node + linkType: hard + +"@rushstack/ts-command-line@npm:5.3.17": + version: 5.3.17 + resolution: "@rushstack/ts-command-line@npm:5.3.17" + dependencies: + "@rushstack/terminal": "npm:0.24.7" + "@types/argparse": "npm:1.0.38" + argparse: "npm:~1.0.9" + string-argv: "npm:~0.3.1" + checksum: 10c0/ced54b17f9295a43ba57f2a999037a81cac0b05f5441de7c257f033085d8a8d1defec2d6c811f1fc4f0c1f95357d1b1f90c1408200b2fec3137926368e8f5cf9 + languageName: node + linkType: hard + "@scalar/helpers@npm:0.16.0": version: 0.16.0 resolution: "@scalar/helpers@npm:0.16.0" @@ -15849,76 +16767,76 @@ __metadata: languageName: node linkType: hard -"@shikijs/core@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/core@npm:4.4.2" +"@shikijs/core@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/core@npm:4.5.0" dependencies: - "@shikijs/primitive": "npm:4.4.2" - "@shikijs/types": "npm:4.4.2" + "@shikijs/primitive": "npm:4.5.0" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" hast-util-to-html: "npm:^9.0.5" - checksum: 10c0/35058e528dcaea04d3bbf2c3ab6defc352b1d1cc90ac1283645af45f1f208218717ce10e24b27dd03fabdc2b039bedfd0bf69712de1d7ab8f0c67d8c343c6a7e + checksum: 10c0/67319596a078d314c1f336693661787cd0d226748b0a0e3267461cb99adf7328afe9c6d8a0ae2c114827751bf0a81f6f41e19d14b7b8711774e35cb0547e6a26 languageName: node linkType: hard -"@shikijs/engine-javascript@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/engine-javascript@npm:4.4.2" +"@shikijs/engine-javascript@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/engine-javascript@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" oniguruma-to-es: "npm:^4.3.6" - checksum: 10c0/2e8cf60249567da010ce73d08acba9a42ef86c29e6ac8876d196558ba633d666498c98a47f1e3ba59308b78e8b74d7e5793a9061ab1b78919fa28528c3de531a + checksum: 10c0/a0ab77786102424313ca86d0ee1a4997b76b728fd2dc37d672ef5bc25f034fb41163081f0f82c2b7dead7d51d0040717150b6f74f3c469e7543863463de44609 languageName: node linkType: hard -"@shikijs/engine-oniguruma@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/engine-oniguruma@npm:4.4.2" +"@shikijs/engine-oniguruma@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/engine-oniguruma@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" - checksum: 10c0/35ce68c3d1cfdf96626521db8f5256770f6327dcd083f8144bc8fcc43a37ae5d83c4472223784fa70b292c3bed67fa02a5130cfc6c54324d08730c760e5ee1a4 + checksum: 10c0/d1b8f010b9b8cfd6a2aae71eba0d0984465679f28e7344195c177eee9bb722313957afa1086af164cce0ffdcb47879639cd503ba84bd7739e1bc12c1100394d4 languageName: node linkType: hard -"@shikijs/langs@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/langs@npm:4.4.2" +"@shikijs/langs@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/langs@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" - checksum: 10c0/041026bd22f2a4b0a073304bf507adc0c175994edf89238ef8e94abc9eeda707e8eed0ee71c0ed2e4c662fb981b7e48d5f5165fd64ffb15596c1273e429da18c + "@shikijs/types": "npm:4.5.0" + checksum: 10c0/ea7282d2b4eff871c187d79bffd3abc3c1409f55c66483891bcae2b020e2f7658da555d7ef52f4b43333e950ad123bf71c0615109dbf734e4a367a0462afe5a2 languageName: node linkType: hard -"@shikijs/primitive@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/primitive@npm:4.4.2" +"@shikijs/primitive@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/primitive@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/6b60cd2ef0f385435283266a9c99e9274dc1a56af8f7bd31189a1b4133c31a27678cb58c5ef96772b71a031c3aa0364e1378a8d962f865a04cf6ad8dae1eba5c + checksum: 10c0/69db5b348ce778c22413800876a91e4209fc8139e40328e9446f790d4e4c72ea06230cfc9f3ee617cf1bb847d5a75d34d2c8efef50f8ecd1d2efd37ca45b771f languageName: node linkType: hard -"@shikijs/themes@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/themes@npm:4.4.2" +"@shikijs/themes@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/themes@npm:4.5.0" dependencies: - "@shikijs/types": "npm:4.4.2" - checksum: 10c0/36247ea8db358e8ccf1070d5b113d685abeb53af681f7ab0c07e025c71d53097d50fe5715ec46fb70b137bc821300cb368401effd1c076d80df6c319ae4a9d37 + "@shikijs/types": "npm:4.5.0" + checksum: 10c0/c60b6e26f4f2dd7dc0f706e81a0d3369f2711a6d4859054b5bd01396e865602d3a941b9132e6ecd234ceb5e67dd615a1a344f6d7f6398b3cdedb21b1aa821221 languageName: node linkType: hard -"@shikijs/types@npm:4.4.2": - version: 4.4.2 - resolution: "@shikijs/types@npm:4.4.2" +"@shikijs/types@npm:4.5.0": + version: 4.5.0 + resolution: "@shikijs/types@npm:4.5.0" dependencies: "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/219e6ec76378a3740545327d184771fd9b697e4c5a0a409cf3dbdb5cef5eb6e046433aa2509a9bdef7adcd0b22f70d6ca18da3a035f45679da639249caa53a6a + checksum: 10c0/139acc1740e97df84e20a45ae171b470569d3f10f0183afa36845506a7a6ea5d54e5dee7b0d1f177213f4ce26ee0f0e250cc0942c3cb07176f916584f1ee2376 languageName: node linkType: hard @@ -17554,6 +18472,170 @@ __metadata: languageName: node linkType: hard +"@tailwindcss/node@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/node@npm:4.3.3" + dependencies: + "@jridgewell/remapping": "npm:^2.3.5" + enhanced-resolve: "npm:^5.24.1" + jiti: "npm:^2.7.0" + lightningcss: "npm:1.32.0" + magic-string: "npm:^0.30.21" + source-map-js: "npm:^1.2.1" + tailwindcss: "npm:4.3.3" + checksum: 10c0/0123669be5b3e78d42b0e10cb34d547fb8574c8e7dc7a97a141c8a4ab4215852b5b1b99b97763e898e1da1493ee8424cb72e28225cc4876828c95156f94d7f0e + languageName: node + linkType: hard + +"@tailwindcss/oxide-android-arm64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-android-arm64@npm:4.3.3" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-darwin-arm64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-darwin-arm64@npm:4.3.3" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-darwin-x64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-darwin-x64@npm:4.3.3" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-freebsd-x64@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-freebsd-x64@npm:4.3.3" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm-gnueabihf@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm-gnueabihf@npm:4.3.3" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm64-gnu@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm64-gnu@npm:4.3.3" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-arm64-musl@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-arm64-musl@npm:4.3.3" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-x64-gnu@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-x64-gnu@npm:4.3.3" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@tailwindcss/oxide-linux-x64-musl@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-linux-x64-musl@npm:4.3.3" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@tailwindcss/oxide-wasm32-wasi@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-wasm32-wasi@npm:4.3.3" + dependencies: + "@emnapi/core": "npm:^1.11.1" + "@emnapi/runtime": "npm:^1.11.1" + "@emnapi/wasi-threads": "npm:^1.2.2" + "@napi-rs/wasm-runtime": "npm:^1.1.4" + "@tybys/wasm-util": "npm:^0.10.2" + tslib: "npm:^2.8.1" + conditions: cpu=wasm32 + languageName: node + linkType: hard + +"@tailwindcss/oxide-win32-arm64-msvc@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-win32-arm64-msvc@npm:4.3.3" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@tailwindcss/oxide-win32-x64-msvc@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide-win32-x64-msvc@npm:4.3.3" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + +"@tailwindcss/oxide@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/oxide@npm:4.3.3" + dependencies: + "@tailwindcss/oxide-android-arm64": "npm:4.3.3" + "@tailwindcss/oxide-darwin-arm64": "npm:4.3.3" + "@tailwindcss/oxide-darwin-x64": "npm:4.3.3" + "@tailwindcss/oxide-freebsd-x64": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm-gnueabihf": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm64-gnu": "npm:4.3.3" + "@tailwindcss/oxide-linux-arm64-musl": "npm:4.3.3" + "@tailwindcss/oxide-linux-x64-gnu": "npm:4.3.3" + "@tailwindcss/oxide-linux-x64-musl": "npm:4.3.3" + "@tailwindcss/oxide-wasm32-wasi": "npm:4.3.3" + "@tailwindcss/oxide-win32-arm64-msvc": "npm:4.3.3" + "@tailwindcss/oxide-win32-x64-msvc": "npm:4.3.3" + dependenciesMeta: + "@tailwindcss/oxide-android-arm64": + optional: true + "@tailwindcss/oxide-darwin-arm64": + optional: true + "@tailwindcss/oxide-darwin-x64": + optional: true + "@tailwindcss/oxide-freebsd-x64": + optional: true + "@tailwindcss/oxide-linux-arm-gnueabihf": + optional: true + "@tailwindcss/oxide-linux-arm64-gnu": + optional: true + "@tailwindcss/oxide-linux-arm64-musl": + optional: true + "@tailwindcss/oxide-linux-x64-gnu": + optional: true + "@tailwindcss/oxide-linux-x64-musl": + optional: true + "@tailwindcss/oxide-wasm32-wasi": + optional: true + "@tailwindcss/oxide-win32-arm64-msvc": + optional: true + "@tailwindcss/oxide-win32-x64-msvc": + optional: true + checksum: 10c0/6c38b25226dad252347451ed8953a998432b51f1e068b25e021215b886ccf8bcf3af58faf5f4ab50368091e657ca2fa341df1deca6101651eddb567122f2acb5 + languageName: node + linkType: hard + +"@tailwindcss/postcss@npm:4.3.3": + version: 4.3.3 + resolution: "@tailwindcss/postcss@npm:4.3.3" + dependencies: + "@alloc/quick-lru": "npm:^5.2.0" + "@tailwindcss/node": "npm:4.3.3" + "@tailwindcss/oxide": "npm:4.3.3" + postcss: "npm:^8.5.16" + tailwindcss: "npm:4.3.3" + checksum: 10c0/50b33643a4ba50c0d2ea0fd769d16072b0b3d2f31180df667fe5ad4ef60464b5f00931cfd5f2de2116a91219edb7a2dbd4c073b5c2f23393eab6ef1163db8dbf + languageName: node + linkType: hard + "@tanstack/devtools-event-client@npm:^0.4.1": version: 0.4.3 resolution: "@tanstack/devtools-event-client@npm:0.4.3" @@ -18292,12 +19374,12 @@ __metadata: languageName: node linkType: hard -"@tybys/wasm-util@npm:^0.10.0, @tybys/wasm-util@npm:^0.10.3": - version: 0.10.3 - resolution: "@tybys/wasm-util@npm:0.10.3" +"@tybys/wasm-util@npm:^0.10.0, @tybys/wasm-util@npm:^0.10.2, @tybys/wasm-util@npm:^0.10.3": + version: 0.10.4 + resolution: "@tybys/wasm-util@npm:0.10.4" dependencies: tslib: "npm:^2.4.0" - checksum: 10c0/fd2bd2a79c6cd8c79ed1cf7a0fa375c64589264c88a27acaf9756d556b453ea222b62a4f68dd2fbb8b3a78b6bab3b1f4fb2431b6afc6aeda8344b53a521a1cd3 + checksum: 10c0/27947f254efa3f2bc41f47040f57f41c246200c6439a9fd54c69f50940e320022c320275f138e30b543ee81ce69593905dfa7ba0831577ab636f829aafa70701 languageName: node linkType: hard @@ -18310,6 +19392,13 @@ __metadata: languageName: node linkType: hard +"@types/argparse@npm:1.0.38": + version: 1.0.38 + resolution: "@types/argparse@npm:1.0.38" + checksum: 10c0/4fc892da5df16923f48180da2d1f4562fa8b0507cf636b24780444fa0a1d7321d4dc0c0ecbee6152968823f5a2ae0d321b4f8c705a489bf1ae1245bdeb0868fd + languageName: node + linkType: hard + "@types/aria-query@npm:^5.0.1": version: 5.0.4 resolution: "@types/aria-query@npm:5.0.4" @@ -18921,6 +20010,15 @@ __metadata: languageName: node linkType: hard +"@types/hast@npm:3.0.5, @types/hast@npm:^3.0.0, @types/hast@npm:^3.0.4, @types/hast@npm:^3.0.5": + version: 3.0.5 + resolution: "@types/hast@npm:3.0.5" + dependencies: + "@types/unist": "npm:*" + checksum: 10c0/f3af8594a6903a507ed191eda944af18099198d6708c29102ae17118c3e20779f6929e91ed37e033541fd28d58055d8a5910a4366dbdf976cf81b13a464741fb + languageName: node + linkType: hard + "@types/hast@npm:^2.0.0": version: 2.3.10 resolution: "@types/hast@npm:2.3.10" @@ -18930,15 +20028,6 @@ __metadata: languageName: node linkType: hard -"@types/hast@npm:^3.0.0, @types/hast@npm:^3.0.4, @types/hast@npm:^3.0.5": - version: 3.0.5 - resolution: "@types/hast@npm:3.0.5" - dependencies: - "@types/unist": "npm:*" - checksum: 10c0/f3af8594a6903a507ed191eda944af18099198d6708c29102ae17118c3e20779f6929e91ed37e033541fd28d58055d8a5910a4366dbdf976cf81b13a464741fb - languageName: node - linkType: hard - "@types/hoist-non-react-statics@npm:^3.3.0": version: 3.3.5 resolution: "@types/hoist-non-react-statics@npm:3.3.5" @@ -19137,7 +20226,7 @@ __metadata: languageName: node linkType: hard -"@types/mdast@npm:^4.0.0, @types/mdast@npm:^4.0.4": +"@types/mdast@npm:4.0.4, @types/mdast@npm:^4.0.0, @types/mdast@npm:^4.0.4": version: 4.0.4 resolution: "@types/mdast@npm:4.0.4" dependencies: @@ -19146,10 +20235,10 @@ __metadata: languageName: node linkType: hard -"@types/mdx@npm:^2.0.0": - version: 2.0.13 - resolution: "@types/mdx@npm:2.0.13" - checksum: 10c0/5edf1099505ac568da55f9ae8a93e7e314e8cbc13d3445d0be61b75941226b005e1390d9b95caecf5dcb00c9d1bab2f1f60f6ff9876dc091a48b547495007720 +"@types/mdx@npm:2.0.14, @types/mdx@npm:^2.0.0": + version: 2.0.14 + resolution: "@types/mdx@npm:2.0.14" + checksum: 10c0/f1e3873c1e36e2685fb99222bf81a23c55a8e2edf49d0c45cabf2c875b0ae814cd6050cce5770ff1c6881ac747d2ad33731e1de32139b04cf181d8d7e1943ff4 languageName: node linkType: hard @@ -21181,6 +22270,90 @@ __metadata: languageName: node linkType: hard +"@yuku-analyzer/binding-android-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-android-arm64@npm:0.10.2" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-darwin-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-darwin-arm64@npm:0.10.2" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-darwin-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-darwin-x64@npm:0.10.2" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-freebsd-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-freebsd-x64@npm:0.10.2" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm-gnu@npm:0.10.2" + conditions: os=linux & cpu=arm & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm-musl@npm:0.10.2" + conditions: os=linux & cpu=arm & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm64-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm64-gnu@npm:0.10.2" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-arm64-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-arm64-musl@npm:0.10.2" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-x64-gnu@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-x64-gnu@npm:0.10.2" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + +"@yuku-analyzer/binding-linux-x64-musl@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-linux-x64-musl@npm:0.10.2" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + +"@yuku-analyzer/binding-win32-arm64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-win32-arm64@npm:0.10.2" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + +"@yuku-analyzer/binding-win32-x64@npm:0.10.2": + version: 0.10.2 + resolution: "@yuku-analyzer/binding-win32-x64@npm:0.10.2" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "@yuku-codegen/binding-android-arm64@npm:0.10.2": version: 0.10.2 resolution: "@yuku-codegen/binding-android-arm64@npm:0.10.2" @@ -21188,9 +22361,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-android-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-android-arm64@npm:0.9.3" +"@yuku-codegen/binding-android-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-android-arm64@npm:0.9.5" conditions: os=android & cpu=arm64 languageName: node linkType: hard @@ -21202,9 +22375,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-darwin-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-darwin-arm64@npm:0.9.3" +"@yuku-codegen/binding-darwin-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-darwin-arm64@npm:0.9.5" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard @@ -21216,9 +22389,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-darwin-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-darwin-x64@npm:0.9.3" +"@yuku-codegen/binding-darwin-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-darwin-x64@npm:0.9.5" conditions: os=darwin & cpu=x64 languageName: node linkType: hard @@ -21230,9 +22403,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-freebsd-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-freebsd-x64@npm:0.9.3" +"@yuku-codegen/binding-freebsd-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-freebsd-x64@npm:0.9.5" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard @@ -21244,9 +22417,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-arm-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm-gnu@npm:0.9.5" conditions: os=linux & cpu=arm & libc=glibc languageName: node linkType: hard @@ -21258,9 +22431,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-arm-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm-musl@npm:0.9.5" conditions: os=linux & cpu=arm & libc=musl languageName: node linkType: hard @@ -21272,9 +22445,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm64-gnu@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard @@ -21286,9 +22459,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-arm64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-arm64-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-arm64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-arm64-musl@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard @@ -21300,9 +22473,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-x64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-x64-gnu@npm:0.9.3" +"@yuku-codegen/binding-linux-x64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-x64-gnu@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard @@ -21314,9 +22487,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-linux-x64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-linux-x64-musl@npm:0.9.3" +"@yuku-codegen/binding-linux-x64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-linux-x64-musl@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard @@ -21328,9 +22501,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-win32-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-win32-arm64@npm:0.9.3" +"@yuku-codegen/binding-win32-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-win32-arm64@npm:0.9.5" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard @@ -21342,9 +22515,9 @@ __metadata: languageName: node linkType: hard -"@yuku-codegen/binding-win32-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-codegen/binding-win32-x64@npm:0.9.3" +"@yuku-codegen/binding-win32-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-codegen/binding-win32-x64@npm:0.9.5" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -21356,9 +22529,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-android-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-android-arm64@npm:0.9.3" +"@yuku-parser/binding-android-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-android-arm64@npm:0.9.5" conditions: os=android & cpu=arm64 languageName: node linkType: hard @@ -21370,9 +22543,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-darwin-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-darwin-arm64@npm:0.9.3" +"@yuku-parser/binding-darwin-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-darwin-arm64@npm:0.9.5" conditions: os=darwin & cpu=arm64 languageName: node linkType: hard @@ -21384,9 +22557,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-darwin-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-darwin-x64@npm:0.9.3" +"@yuku-parser/binding-darwin-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-darwin-x64@npm:0.9.5" conditions: os=darwin & cpu=x64 languageName: node linkType: hard @@ -21398,9 +22571,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-freebsd-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-freebsd-x64@npm:0.9.3" +"@yuku-parser/binding-freebsd-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-freebsd-x64@npm:0.9.5" conditions: os=freebsd & cpu=x64 languageName: node linkType: hard @@ -21412,9 +22585,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-arm-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm-gnu@npm:0.9.5" conditions: os=linux & cpu=arm & libc=glibc languageName: node linkType: hard @@ -21426,9 +22599,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm-musl@npm:0.9.3" +"@yuku-parser/binding-linux-arm-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm-musl@npm:0.9.5" conditions: os=linux & cpu=arm & libc=musl languageName: node linkType: hard @@ -21440,9 +22613,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm64-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-arm64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm64-gnu@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=glibc languageName: node linkType: hard @@ -21454,9 +22627,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-arm64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-arm64-musl@npm:0.9.3" +"@yuku-parser/binding-linux-arm64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-arm64-musl@npm:0.9.5" conditions: os=linux & cpu=arm64 & libc=musl languageName: node linkType: hard @@ -21468,9 +22641,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-x64-gnu@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-x64-gnu@npm:0.9.3" +"@yuku-parser/binding-linux-x64-gnu@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-x64-gnu@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=glibc languageName: node linkType: hard @@ -21482,9 +22655,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-linux-x64-musl@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-linux-x64-musl@npm:0.9.3" +"@yuku-parser/binding-linux-x64-musl@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-linux-x64-musl@npm:0.9.5" conditions: os=linux & cpu=x64 & libc=musl languageName: node linkType: hard @@ -21496,9 +22669,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-win32-arm64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-win32-arm64@npm:0.9.3" +"@yuku-parser/binding-win32-arm64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-win32-arm64@npm:0.9.5" conditions: os=win32 & cpu=arm64 languageName: node linkType: hard @@ -21510,9 +22683,9 @@ __metadata: languageName: node linkType: hard -"@yuku-parser/binding-win32-x64@npm:0.9.3": - version: 0.9.3 - resolution: "@yuku-parser/binding-win32-x64@npm:0.9.3" +"@yuku-parser/binding-win32-x64@npm:0.9.5": + version: 0.9.5 + resolution: "@yuku-parser/binding-win32-x64@npm:0.9.5" conditions: os=win32 & cpu=x64 languageName: node linkType: hard @@ -21524,10 +22697,10 @@ __metadata: languageName: node linkType: hard -"@yuku-toolchain/types@npm:^0.9.3": - version: 0.9.3 - resolution: "@yuku-toolchain/types@npm:0.9.3" - checksum: 10c0/6f3b45ac664764b6f76322af4db5110641a45c812182580394a1816a359b65b5979791f8fc43f66733411127c59bb67272234f6f44aabe1945fe5724113f3f92 +"@yuku-toolchain/types@npm:^0.9.5": + version: 0.9.5 + resolution: "@yuku-toolchain/types@npm:0.9.5" + checksum: 10c0/cc20d7de43e393656501263a8d123cb2b03a9f281e23fbb8f9a2984dded5fab5df1c3007587ec978ada752328ca708f2ffadd1e0046c5f4a60c4d06a46ff694c languageName: node linkType: hard @@ -22688,7 +23861,7 @@ __metadata: languageName: node linkType: hard -"ajv-draft-04@npm:^1.0.0": +"ajv-draft-04@npm:^1.0.0, ajv-draft-04@npm:~1.0.0": version: 1.0.0 resolution: "ajv-draft-04@npm:1.0.0" peerDependencies: @@ -22700,7 +23873,7 @@ __metadata: languageName: node linkType: hard -"ajv-formats@npm:3.0.1, ajv-formats@npm:^3.0.1": +"ajv-formats@npm:3.0.1, ajv-formats@npm:^3.0.1, ajv-formats@npm:~3.0.1": version: 3.0.1 resolution: "ajv-formats@npm:3.0.1" dependencies: @@ -22781,7 +23954,7 @@ __metadata: languageName: node linkType: hard -"ajv@npm:^8.0.0, ajv@npm:^8.0.1, ajv@npm:^8.11.2, ajv@npm:^8.17.1, ajv@npm:^8.20.0, ajv@npm:^8.9.0": +"ajv@npm:^8.0.0, ajv@npm:^8.0.1, ajv@npm:^8.11.2, ajv@npm:^8.17.1, ajv@npm:^8.20.0, ajv@npm:^8.9.0, ajv@npm:~8.20.0": version: 8.20.0 resolution: "ajv@npm:8.20.0" dependencies: @@ -22973,12 +24146,21 @@ __metadata: languageName: node linkType: hard -"aria-hidden@npm:^1.1.1": - version: 1.2.4 - resolution: "aria-hidden@npm:1.2.4" +"argparse@npm:~1.0.9": + version: 1.0.10 + resolution: "argparse@npm:1.0.10" + dependencies: + sprintf-js: "npm:~1.0.2" + checksum: 10c0/b2972c5c23c63df66bca144dbc65d180efa74f25f8fd9b7d9a0a6c88ae839db32df3d54770dcb6460cf840d232b60695d1a6b1053f599d84e73f7437087712de + languageName: node + linkType: hard + +"aria-hidden@npm:^1.1.1, aria-hidden@npm:^1.2.4": + version: 1.2.6 + resolution: "aria-hidden@npm:1.2.6" dependencies: tslib: "npm:^2.0.0" - checksum: 10c0/8abcab2e1432efc4db415e97cb3959649ddf52c8fc815d7384f43f3d3abf56f1c12852575d00df9a8927f421d7e0712652dd5f8db244ea57634344e29ecfc74a + checksum: 10c0/7720cb539497a9f760f68f98a4b30f22c6767aa0e72fa7d58279f7c164e258fc38b2699828f8de881aab0fc8e9c56d1313a3f1a965046fc0381a554dbc72b54a languageName: node linkType: hard @@ -24419,6 +25601,15 @@ __metadata: languageName: node linkType: hard +"class-variance-authority@npm:^0.7.1": + version: 0.7.1 + resolution: "class-variance-authority@npm:0.7.1" + dependencies: + clsx: "npm:^2.1.1" + checksum: 10c0/0f438cea22131808b99272de0fa933c2532d5659773bfec0c583de7b3f038378996d3350683426b8e9c74a6286699382106d71fbec52f0dd5fbb191792cccb5b + languageName: node + linkType: hard + "classcat@npm:^5.0.3, classcat@npm:^5.0.4": version: 5.0.5 resolution: "classcat@npm:5.0.5" @@ -24615,6 +25806,24 @@ __metadata: languageName: node linkType: hard +"cn@npm:^0.2.6": + version: 0.2.6 + resolution: "cn@npm:0.2.6" + bin: + cn: bin/cn.mjs + checksum: 10c0/7d5744771e897061e210d5aa49563d254518e7e032ec372991d8e1ebb1d61057b4ec538810de31ac267153e610c141ec54b0befd006c0220e772a652824b9830 + languageName: node + linkType: hard + +"cn@npm:^0.4.0": + version: 0.4.0 + resolution: "cn@npm:0.4.0" + bin: + cn: bin/cn.mjs + checksum: 10c0/e71351cdceb7dbc9b468dcb9cacc304212532fb6bb4545979426f22791f5c4738f37d13825eb68172ae355fbe8afc30386371753d093f1031f17f35a8d10f303 + languageName: node + linkType: hard + "co@npm:^4.6.0": version: 4.6.0 resolution: "co@npm:4.6.0" @@ -24912,6 +26121,13 @@ __metadata: languageName: node linkType: hard +"compute-scroll-into-view@npm:^3.0.2": + version: 3.1.1 + resolution: "compute-scroll-into-view@npm:3.1.1" + checksum: 10c0/59761ed62304a9599b52ad75d0d6fbf0669ee2ab7dd472fdb0ad9da36628414c014dea7b5810046560180ad30ffec52a953d19297f66a1d4f3aa0999b9d2521d + languageName: node + linkType: hard + "concat-map@npm:0.0.1": version: 0.0.1 resolution: "concat-map@npm:0.0.1" @@ -26168,7 +27384,7 @@ __metadata: languageName: node linkType: hard -"diff@npm:^8.0.2": +"diff@npm:^8.0.2, diff@npm:~8.0.2": version: 8.0.4 resolution: "diff@npm:8.0.4" checksum: 10c0/7ee5d03926db4039be7252ac3b0abaae1bd122a2ca971e5ca7270e444e36ff83dd906fad1a719740ca347e97ed5dc8f458a76a8391dbcd7aff363bdafb348a00 @@ -26672,7 +27888,7 @@ __metadata: languageName: node linkType: hard -"enhanced-resolve@npm:5.24.1, enhanced-resolve@npm:^5.15.0, enhanced-resolve@npm:^5.22.0, enhanced-resolve@npm:^5.7.0": +"enhanced-resolve@npm:5.24.1": version: 5.24.1 resolution: "enhanced-resolve@npm:5.24.1" dependencies: @@ -26682,6 +27898,16 @@ __metadata: languageName: node linkType: hard +"enhanced-resolve@npm:^5.15.0, enhanced-resolve@npm:^5.22.0, enhanced-resolve@npm:^5.24.1, enhanced-resolve@npm:^5.7.0": + version: 5.26.0 + resolution: "enhanced-resolve@npm:5.26.0" + dependencies: + graceful-fs: "npm:^4.2.4" + tapable: "npm:^2.3.3" + checksum: 10c0/fea1f02aa89793fecfd3ab0764be988fdf10dd5147ef65548726d918e68e3b9cf84224de37387356b54eee69363e4d59d9624dd7be9a23a0b1f568c46fa7a8a2 + languageName: node + linkType: hard + "entities@npm:^2.0.0": version: 2.2.0 resolution: "entities@npm:2.2.0" @@ -27023,7 +28249,7 @@ __metadata: languageName: node linkType: hard -"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1": +"esbuild@npm:^0.18.0 || ^0.19.0 || ^0.20.0 || ^0.21.0 || ^0.22.0 || ^0.23.0 || ^0.24.0 || ^0.25.0 || ^0.26.0 || ^0.27.0 || ^0.28.0, esbuild@npm:^0.28.0, esbuild@npm:^0.28.1, esbuild@npm:^0.28.2": version: 0.28.2 resolution: "esbuild@npm:0.28.2" dependencies: @@ -28274,6 +29500,15 @@ __metadata: languageName: node linkType: hard +"estree-util-value-to-estree@npm:^3.5.0": + version: 3.5.0 + resolution: "estree-util-value-to-estree@npm:3.5.0" + dependencies: + "@types/estree": "npm:^1.0.0" + checksum: 10c0/05c8d4b3338598929122cbfd6b127b22de4600dda8178b789b0d139e5b296e57a2343e487d6e108d8c39b18550dae2af3a110093698684db810954f353e9099b + languageName: node + linkType: hard + "estree-util-visit@npm:^2.0.0": version: 2.0.0 resolution: "estree-util-visit@npm:2.0.0" @@ -29242,6 +30477,25 @@ __metadata: languageName: node linkType: hard +"framer-motion@npm:14.0.0": + version: 14.0.0 + resolution: "framer-motion@npm:14.0.0" + dependencies: + motion-dom: "npm:14.0.0" + motion-utils: "npm:14.0.0" + tslib: "npm:^2.4.0" + peerDependencies: + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + checksum: 10c0/cc1421daef8e8245263999de59b13b3e6a5a0e6331ffba7eaf52186ce3c4da671dce96091e2f43ee982855d8c3ee86fb4c094a65507a8abc78322b98e0fceeed + languageName: node + linkType: hard + "fresh@npm:^2.0.0": version: 2.0.0 resolution: "fresh@npm:2.0.0" @@ -29296,6 +30550,17 @@ __metadata: languageName: node linkType: hard +"fs-extra@npm:~11.3.0": + version: 11.3.6 + resolution: "fs-extra@npm:11.3.6" + dependencies: + graceful-fs: "npm:^4.2.0" + jsonfile: "npm:^6.0.1" + universalify: "npm:^2.0.0" + checksum: 10c0/191c96bf71519fe08595f7920b6e568f6e44b48ed968624f35cb3bb7f4f9b05718b99cd6bf81938c0f7b1daa6d151383c33e0cbfdfe4d95419d7ea121de8e91a + languageName: node + linkType: hard + "fs-minipass@npm:^3.0.0": version: 3.0.3 resolution: "fs-minipass@npm:3.0.3" @@ -29364,6 +30629,265 @@ __metadata: languageName: node linkType: hard +"fumadocs-core@npm:16.16.2": + version: 16.16.2 + resolution: "fumadocs-core@npm:16.16.2" + dependencies: + "@fumari/image-size": "npm:^0.1.1" + estree-util-value-to-estree: "npm:^3.5.0" + github-slugger: "npm:^2.0.0" + hast-util-to-estree: "npm:^3.1.3" + hast-util-to-jsx-runtime: "npm:^2.3.6" + mdast-util-mdx: "npm:^3.0.0" + mdast-util-to-markdown: "npm:^2.1.3" + npm-to-yarn: "npm:3.2.0" + remark: "npm:^15.0.1" + remark-gfm: "npm:^4.0.1" + remark-rehype: "npm:^11.1.2" + scroll-into-view-if-needed: "npm:^3.1.0" + shiki: "npm:^4.5.0" + tinyglobby: "npm:^0.2.17" + unified: "npm:^11.0.5" + unist-util-visit: "npm:^5.1.0" + vfile: "npm:^6.0.3" + yaml: "npm:^2.9.1" + zbsearch: "npm:^4.0.1" + peerDependencies: + "@mdx-js/mdx": "*" + "@mixedbread/sdk": 0.x.x + "@modelcontextprotocol/server": 2.x.x + "@orama/core": 1.x.x + "@oramacloud/client": 2.x.x + "@tanstack/react-router": 1.x.x + "@types/estree-jsx": "*" + "@types/hast": "*" + "@types/mdast": "*" + "@types/react": "*" + algoliasearch: 5.x.x + flexsearch: "*" + lucide-react: "*" + meilisearch: ">=0.50.0 <1.0.0" + next: 16.x.x + react: ^19.2.0 + react-dom: ^19.2.0 + react-router: 7.x.x || 8.x.x + waku: "*" + zod: 4.x.x + peerDependenciesMeta: + "@mdx-js/mdx": + optional: true + "@mixedbread/sdk": + optional: true + "@modelcontextprotocol/server": + optional: true + "@orama/core": + optional: true + "@oramacloud/client": + optional: true + "@tanstack/react-router": + optional: true + "@types/estree-jsx": + optional: true + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/react": + optional: true + algoliasearch: + optional: true + flexsearch: + optional: true + lucide-react: + optional: true + meilisearch: + optional: true + next: + optional: true + react: + optional: true + react-dom: + optional: true + react-router: + optional: true + waku: + optional: true + zod: + optional: true + checksum: 10c0/dbfab29fe4a91d8e5a16dd60851e7385d1a55516ba3ec874bba67531013b82406792d6bd0c511e663ee9bfb72908af0fa0f39611c0fa604a0ee0959ad4d2c8d2 + languageName: node + linkType: hard + +"fumadocs-mdx@npm:15.4.6": + version: 15.4.6 + resolution: "fumadocs-mdx@npm:15.4.6" + dependencies: + "@mdx-js/mdx": "npm:^3.1.1" + "@standard-schema/spec": "npm:^1.1.0" + chokidar: "npm:^5.0.0" + esbuild: "npm:^0.28.2" + estree-util-value-to-estree: "npm:^3.5.0" + github-slugger: "npm:^2.0.0" + magic-string: "npm:^1.4.1" + mdast-util-mdx: "npm:^3.0.0" + picocolors: "npm:^1.1.1" + picomatch: "npm:^4.0.7" + tinyexec: "npm:^1.3.1" + tinyglobby: "npm:^0.2.17" + unified: "npm:^11.0.5" + unist-util-remove-position: "npm:^5.0.0" + unist-util-visit: "npm:^5.1.0" + vfile: "npm:^6.0.3" + yaml: "npm:^2.9.1" + yuku-analyzer: "npm:^0.10.2" + zod: "npm:^4.6.5" + peerDependencies: + "@fumadocs/satteri": 0.x.x + "@types/mdast": "*" + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: ^16.15.3 + mdast-util-directive: "*" + next: ^15.3.0 || ^16.0.0 + react: ^19.2.0 + rolldown: "*" + satteri: ^0.10.5 + vite: 7.x.x || 8.x.x + peerDependenciesMeta: + "@fumadocs/satteri": + optional: true + "@types/mdast": + optional: true + "@types/mdx": + optional: true + "@types/react": + optional: true + mdast-util-directive: + optional: true + next: + optional: true + react: + optional: true + rolldown: + optional: true + satteri: + optional: true + vite: + optional: true + bin: + fumadocs-mdx: ./bin.js + checksum: 10c0/1c14283aa67a97d8431473ba9392bec26a0101e329546795c3b0e5b03b77cce83e71213100339459cc4a5acf9988e272561cea2370773d4488b115fc8494f73a + languageName: node + linkType: hard + +"fumadocs-twoslash@npm:4.0.1": + version: 4.0.1 + resolution: "fumadocs-twoslash@npm:4.0.1" + dependencies: + "@base-ui/react": "npm:^1.8.0" + "@types/hast": "npm:^3.0.5" + cn: "npm:^0.2.6" + mdast-util-from-markdown: "npm:^2.0.3" + mdast-util-to-hast: "npm:^13.2.1" + typescript: "npm:~7.0.2" + peerDependencies: + "@types/react": "*" + fumadocs-core: ^16.15.7 + fumadocs-ui: ^16.7.16 + react: ^19.2.0 + react-dom: ^19.2.0 + shiki: ^4.4.3 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/c21deed51c7c32ef1fd3546e28d6e2704786849216975b63366d053cef134636a9c1613a1db062a1aed584bf21b0e61bdad961c4d555fb091319658056ae4bf7 + languageName: node + linkType: hard + +"fumadocs-typescript@npm:^5.4.1": + version: 5.4.1 + resolution: "fumadocs-typescript@npm:5.4.1" + dependencies: + estree-util-value-to-estree: "npm:^3.5.0" + hast-util-to-estree: "npm:^3.1.3" + hast-util-to-jsx-runtime: "npm:^2.3.6" + remark: "npm:^15.0.1" + remark-rehype: "npm:^11.1.2" + shiki: "npm:^4.4.3" + typescript: "npm:~7.0.2" + unified: "npm:^11.0.5" + unist-util-visit: "npm:^5.1.0" + peerDependencies: + "@types/estree": "*" + "@types/hast": "*" + "@types/mdast": "*" + "@types/react": "*" + fumadocs-core: ^16.7.0 + fumadocs-ui: ^16.7.0 + react: ^19.2.0 + react-dom: ^19.2.0 + peerDependenciesMeta: + "@types/estree": + optional: true + "@types/hast": + optional: true + "@types/mdast": + optional: true + "@types/react": + optional: true + fumadocs-ui: + optional: true + checksum: 10c0/70dc83d45a2edf5442bbb350c26ba387e80260ab53a584cf6c9535e604e687c9e8cf9e80fdbb7c53ce2ae8a7a90c3ca61b30c9745160e3a60ac607ac0b517142 + languageName: node + linkType: hard + +"fumadocs-ui@npm:16.16.2": + version: 16.16.2 + resolution: "fumadocs-ui@npm:16.16.2" + dependencies: + "@fuma-translate/react": "npm:^1.0.2" + "@fumadocs/tailwind": "npm:0.1.2" + "@radix-ui/react-accordion": "npm:^1.2.20" + "@radix-ui/react-collapsible": "npm:^1.1.20" + "@radix-ui/react-dialog": "npm:^1.1.23" + "@radix-ui/react-direction": "npm:^1.1.4" + "@radix-ui/react-navigation-menu": "npm:^1.2.22" + "@radix-ui/react-popover": "npm:^1.1.23" + "@radix-ui/react-presence": "npm:^1.1.10" + "@radix-ui/react-scroll-area": "npm:^1.2.18" + "@radix-ui/react-slot": "npm:^1.3.3" + "@radix-ui/react-tabs": "npm:^1.1.21" + class-variance-authority: "npm:^0.7.1" + cn: "npm:^0.4.0" + lucide-react: "npm:^1.50.0" + motion: "npm:^14.0.0" + next-themes: "npm:^0.4.6" + react-remove-scroll: "npm:^2.7.2" + rehype-raw: "npm:^7.0.0" + scroll-into-view-if-needed: "npm:^3.1.0" + shiki: "npm:^4.5.0" + unist-util-visit: "npm:^5.1.0" + peerDependencies: + "@types/mdx": "*" + "@types/react": "*" + fumadocs-core: 16.16.2 + next: 16.x.x + react: ^19.2.0 + react-dom: ^19.2.0 + takumi-js: "*" + peerDependenciesMeta: + "@types/mdx": + optional: true + "@types/react": + optional: true + next: + optional: true + takumi-js: + optional: true + checksum: 10c0/6aaab53e69a172b883d9003192371f4f63e04927582c4dc8acedc19a1daaca1e5dc3b3f92bdd235da72d038a66cdcc58f21e1abd4a76d0e78bd98ba3c7a77daf + languageName: node + linkType: hard + "function-bind@npm:^1.1.2": version: 1.1.2 resolution: "function-bind@npm:1.1.2" @@ -30504,7 +32028,7 @@ __metadata: languageName: node linkType: hard -"hast-util-to-estree@npm:^3.0.0": +"hast-util-to-estree@npm:^3.0.0, hast-util-to-estree@npm:^3.1.3": version: 3.1.3 resolution: "hast-util-to-estree@npm:3.1.3" dependencies: @@ -30547,7 +32071,7 @@ __metadata: languageName: node linkType: hard -"hast-util-to-jsx-runtime@npm:^2.0.0": +"hast-util-to-jsx-runtime@npm:^2.0.0, hast-util-to-jsx-runtime@npm:^2.3.6": version: 2.3.6 resolution: "hast-util-to-jsx-runtime@npm:2.3.6" dependencies: @@ -31456,6 +32980,13 @@ __metadata: languageName: node linkType: hard +"import-lazy@npm:~4.0.0": + version: 4.0.0 + resolution: "import-lazy@npm:4.0.0" + checksum: 10c0/a3520313e2c31f25c0b06aa66d167f329832b68a4f957d7c9daf6e0fa41822b6e84948191648b9b9d8ca82f94740cdf15eecf2401a5b42cd1c33fd84f2225cca + languageName: node + linkType: hard + "import-local@npm:^3.0.2": version: 3.2.0 resolution: "import-local@npm:3.2.0" @@ -31827,12 +33358,12 @@ __metadata: languageName: node linkType: hard -"is-core-module@npm:^2.13.0, is-core-module@npm:^2.16.0, is-core-module@npm:^2.16.1": - version: 2.16.1 - resolution: "is-core-module@npm:2.16.1" +"is-core-module@npm:^2.13.0, is-core-module@npm:^2.16.1, is-core-module@npm:^2.17.0": + version: 2.17.0 + resolution: "is-core-module@npm:2.17.0" dependencies: - hasown: "npm:^2.0.2" - checksum: 10c0/898443c14780a577e807618aaae2b6f745c8538eca5c7bc11388a3f2dc6de82b9902bcc7eb74f07be672b11bbe82dd6a6edded44a00cb3d8f933d0459905eedd + hasown: "npm:^2.0.4" + checksum: 10c0/3dc7c15ea42f846180cd2cdd57af62270e0a8d0ed31c17c85735d554089d39975e2e82e65fc7c8280a3c476ca3d0d09992d0860b4998abb769a277341feb6698 languageName: node linkType: hard @@ -32802,7 +34333,7 @@ __metadata: languageName: node linkType: hard -"js-yaml@npm:4.3.2, js-yaml@npm:^4.1.0, js-yaml@npm:^4.1.1, js-yaml@npm:^4.3.0": +"js-yaml@npm:4.3.2, js-yaml@npm:^4.1.0, js-yaml@npm:^4.1.1, js-yaml@npm:^4.3.0, js-yaml@npm:~4.3.2": version: 4.3.2 resolution: "js-yaml@npm:4.3.2" dependencies: @@ -33169,6 +34700,17 @@ __metadata: languageName: node linkType: hard +"katex@npm:^0.18.7": + version: 0.18.10 + resolution: "katex@npm:0.18.10" + dependencies: + commander: "npm:^15.0.0" + bin: + katex: cli.js + checksum: 10c0/3864a236334e9c7aef906b2fdd70defb76edfe8362372ccd5504167e8b22bbc1a48210e5d03e30e464c0c0f669e6d467b3b8b01120598fb1968c275fa5059721 + languageName: node + linkType: hard + "keygrip@npm:~1.1.0": version: 1.1.0 resolution: "keygrip@npm:1.1.0" @@ -33513,6 +35055,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-android-arm64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-android-arm64@npm:1.32.0" + conditions: os=android & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-android-arm64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-android-arm64@npm:1.33.0" @@ -33527,6 +35076,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-darwin-arm64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-darwin-arm64@npm:1.32.0" + conditions: os=darwin & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-darwin-arm64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-darwin-arm64@npm:1.33.0" @@ -33541,6 +35097,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-darwin-x64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-darwin-x64@npm:1.32.0" + conditions: os=darwin & cpu=x64 + languageName: node + linkType: hard + "lightningcss-darwin-x64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-darwin-x64@npm:1.33.0" @@ -33555,6 +35118,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-freebsd-x64@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-freebsd-x64@npm:1.32.0" + conditions: os=freebsd & cpu=x64 + languageName: node + linkType: hard + "lightningcss-freebsd-x64@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-freebsd-x64@npm:1.33.0" @@ -33569,6 +35139,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm-gnueabihf@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm-gnueabihf@npm:1.32.0" + conditions: os=linux & cpu=arm + languageName: node + linkType: hard + "lightningcss-linux-arm-gnueabihf@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm-gnueabihf@npm:1.33.0" @@ -33583,6 +35160,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm64-gnu@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm64-gnu@npm:1.32.0" + conditions: os=linux & cpu=arm64 & libc=glibc + languageName: node + linkType: hard + "lightningcss-linux-arm64-gnu@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm64-gnu@npm:1.33.0" @@ -33597,6 +35181,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-arm64-musl@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-arm64-musl@npm:1.32.0" + conditions: os=linux & cpu=arm64 & libc=musl + languageName: node + linkType: hard + "lightningcss-linux-arm64-musl@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-arm64-musl@npm:1.33.0" @@ -33611,6 +35202,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-x64-gnu@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-x64-gnu@npm:1.32.0" + conditions: os=linux & cpu=x64 & libc=glibc + languageName: node + linkType: hard + "lightningcss-linux-x64-gnu@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-x64-gnu@npm:1.33.0" @@ -33625,6 +35223,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-linux-x64-musl@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-linux-x64-musl@npm:1.32.0" + conditions: os=linux & cpu=x64 & libc=musl + languageName: node + linkType: hard + "lightningcss-linux-x64-musl@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-linux-x64-musl@npm:1.33.0" @@ -33639,6 +35244,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-win32-arm64-msvc@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-win32-arm64-msvc@npm:1.32.0" + conditions: os=win32 & cpu=arm64 + languageName: node + linkType: hard + "lightningcss-win32-arm64-msvc@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-win32-arm64-msvc@npm:1.33.0" @@ -33653,6 +35265,13 @@ __metadata: languageName: node linkType: hard +"lightningcss-win32-x64-msvc@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss-win32-x64-msvc@npm:1.32.0" + conditions: os=win32 & cpu=x64 + languageName: node + linkType: hard + "lightningcss-win32-x64-msvc@npm:1.33.0": version: 1.33.0 resolution: "lightningcss-win32-x64-msvc@npm:1.33.0" @@ -33703,6 +35322,49 @@ __metadata: languageName: node linkType: hard +"lightningcss@npm:1.32.0": + version: 1.32.0 + resolution: "lightningcss@npm:1.32.0" + dependencies: + detect-libc: "npm:^2.0.3" + lightningcss-android-arm64: "npm:1.32.0" + lightningcss-darwin-arm64: "npm:1.32.0" + lightningcss-darwin-x64: "npm:1.32.0" + lightningcss-freebsd-x64: "npm:1.32.0" + lightningcss-linux-arm-gnueabihf: "npm:1.32.0" + lightningcss-linux-arm64-gnu: "npm:1.32.0" + lightningcss-linux-arm64-musl: "npm:1.32.0" + lightningcss-linux-x64-gnu: "npm:1.32.0" + lightningcss-linux-x64-musl: "npm:1.32.0" + lightningcss-win32-arm64-msvc: "npm:1.32.0" + lightningcss-win32-x64-msvc: "npm:1.32.0" + dependenciesMeta: + lightningcss-android-arm64: + optional: true + lightningcss-darwin-arm64: + optional: true + lightningcss-darwin-x64: + optional: true + lightningcss-freebsd-x64: + optional: true + lightningcss-linux-arm-gnueabihf: + optional: true + lightningcss-linux-arm64-gnu: + optional: true + lightningcss-linux-arm64-musl: + optional: true + lightningcss-linux-x64-gnu: + optional: true + lightningcss-linux-x64-musl: + optional: true + lightningcss-win32-arm64-msvc: + optional: true + lightningcss-win32-x64-msvc: + optional: true + checksum: 10c0/70945bd55097af46fc9fab7f5ed09cd5869d85940a2acab7ee06d0117004a1d68155708a2d462531cea2fc3c67aefc9333a7068c80b0b78dd404c16838809e03 + languageName: node + linkType: hard + "lightningcss@npm:^1.33.0": version: 1.33.0 resolution: "lightningcss@npm:1.33.0" @@ -34216,6 +35878,19 @@ __metadata: languageName: node linkType: hard +"lucide-react@npm:^1.50.0": + version: 1.54.0 + resolution: "lucide-react@npm:1.54.0" + peerDependencies: + "@types/react": "*" + react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/28c80675dfd7daf76cc50fd737245c108b1d65c56c065babc3fd23d8f626cbec76aff9115a5f83e5124f80c7342b2042c64160aea6e5cb63021906b643bb2e99 + languageName: node + linkType: hard + "luxon@npm:^3.2.1": version: 3.5.0 resolution: "luxon@npm:3.5.0" @@ -34248,12 +35923,12 @@ __metadata: languageName: node linkType: hard -"magic-string@npm:^1.0.0, magic-string@npm:^1.2.3": - version: 1.4.2 - resolution: "magic-string@npm:1.4.2" +"magic-string@npm:^1.0.0, magic-string@npm:^1.2.3, magic-string@npm:^1.4.1": + version: 1.4.3 + resolution: "magic-string@npm:1.4.3" dependencies: "@jridgewell/sourcemap-codec": "npm:^1.6.0" - checksum: 10c0/d3e222c202f99ec4861e7316f473f9b1cfe335ebdf38d4f67335f842f3fe248f01ee00fd3e1a8206bcbe9855e0c41515d7c210300d8fcf6eefbb982d79e423c6 + checksum: 10c0/857743a1e7039d2e867505bb272a57cc605f610b90f6bf9ef6cbf9654e9cd64330ec35e564a58ca455350529872c3ecc01f37da934da130391237f9f593cc565 languageName: node linkType: hard @@ -34435,9 +36110,9 @@ __metadata: languageName: node linkType: hard -"mdast-util-from-markdown@npm:^2.0.0": - version: 2.0.2 - resolution: "mdast-util-from-markdown@npm:2.0.2" +"mdast-util-from-markdown@npm:^2.0.0, mdast-util-from-markdown@npm:^2.0.3": + version: 2.1.0 + resolution: "mdast-util-from-markdown@npm:2.1.0" dependencies: "@types/mdast": "npm:^4.0.0" "@types/unist": "npm:^3.0.0" @@ -34451,7 +36126,7 @@ __metadata: micromark-util-symbol: "npm:^2.0.0" micromark-util-types: "npm:^2.0.0" unist-util-stringify-position: "npm:^4.0.0" - checksum: 10c0/76eb2bd2c6f7a0318087c73376b8af6d7561c1e16654e7667e640f391341096c56142618fd0ff62f6d39e5ab4895898b9789c84cd7cec2874359a437a0e1ff15 + checksum: 10c0/63cf2c77a3b731536eb29d777bfe134c829221a07597e83c696f1e65c7893b94d617c886ec277e5f95de7b4055b11c5253c5eca01ca7549f5f47b4dc133e571c languageName: node linkType: hard @@ -34603,7 +36278,7 @@ __metadata: languageName: node linkType: hard -"mdast-util-to-hast@npm:^13.0.0": +"mdast-util-to-hast@npm:^13.0.0, mdast-util-to-hast@npm:^13.2.1": version: 13.2.1 resolution: "mdast-util-to-hast@npm:13.2.1" dependencies: @@ -34620,20 +36295,22 @@ __metadata: languageName: node linkType: hard -"mdast-util-to-markdown@npm:^2.0.0, mdast-util-to-markdown@npm:^2.1.2": - version: 2.1.2 - resolution: "mdast-util-to-markdown@npm:2.1.2" +"mdast-util-to-markdown@npm:^2.0.0, mdast-util-to-markdown@npm:^2.1.2, mdast-util-to-markdown@npm:^2.1.3": + version: 2.2.0 + resolution: "mdast-util-to-markdown@npm:2.2.0" dependencies: "@types/mdast": "npm:^4.0.0" "@types/unist": "npm:^3.0.0" longest-streak: "npm:^3.0.0" mdast-util-phrasing: "npm:^4.0.0" mdast-util-to-string: "npm:^4.0.0" + micromark-util-character: "npm:^2.0.0" micromark-util-classify-character: "npm:^2.0.0" micromark-util-decode-string: "npm:^2.0.0" + micromark-util-html-tag-name: "npm:^2.0.0" unist-util-visit: "npm:^5.0.0" zwitch: "npm:^2.0.0" - checksum: 10c0/4649722a6099f12e797bd8d6469b2b43b44e526b5182862d9c7766a3431caad2c0112929c538a972f214e63c015395e5d3f54bd81d9ac1b16e6d8baaf582f749 + checksum: 10c0/584ad697cc2e94f5a276f732d66125024a8b9ea57f9b6dcc67bc09be8414fa82bb96b790c6aff0b18b4c7e88df36ab83f781429460c2b8cc0559260d6c63358c languageName: node linkType: hard @@ -35383,6 +37060,15 @@ __metadata: languageName: node linkType: hard +"minimatch@npm:10.2.3": + version: 10.2.3 + resolution: "minimatch@npm:10.2.3" + dependencies: + brace-expansion: "npm:^5.0.2" + checksum: 10c0/d9ae5f355e8bb77a42dd8c20b950141cec8773ef8716a2bb6df7a6840cc44a00ed828883884e4f1c7b5cb505fa06a17e3ea9ca2edb18fd1dec865ea7f9fcf0e5 + languageName: node + linkType: hard + "minimatch@npm:^10.0.0, minimatch@npm:^10.0.1, minimatch@npm:^10.1.1, minimatch@npm:^10.2.2": version: 10.2.4 resolution: "minimatch@npm:10.2.4" @@ -35595,6 +37281,15 @@ __metadata: languageName: node linkType: hard +"motion-dom@npm:14.0.0": + version: 14.0.0 + resolution: "motion-dom@npm:14.0.0" + dependencies: + motion-utils: "npm:14.0.0" + checksum: 10c0/d45be2d5ca62f1c02519917c580a529cbeb05a6f585e6abc019bd0b8eaad75122eb3c037abbdc00d6bd3964b58c32cd2b6cb3ddaebbfffe901cddf79457ac630 + languageName: node + linkType: hard + "motion-dom@npm:^11.18.1": version: 11.18.1 resolution: "motion-dom@npm:11.18.1" @@ -35604,6 +37299,13 @@ __metadata: languageName: node linkType: hard +"motion-utils@npm:14.0.0": + version: 14.0.0 + resolution: "motion-utils@npm:14.0.0" + checksum: 10c0/02c3d67bfacedddb91f9a69944eb5b89cd9b15ed7aae968d9d65ec804be63197adfacc7d364586b679999b7573196b8cc6f300cb932ba6dd8e5a4b1760da33c1 + languageName: node + linkType: hard + "motion-utils@npm:^11.18.1": version: 11.18.1 resolution: "motion-utils@npm:11.18.1" @@ -35611,6 +37313,24 @@ __metadata: languageName: node linkType: hard +"motion@npm:^14.0.0": + version: 14.0.0 + resolution: "motion@npm:14.0.0" + dependencies: + framer-motion: "npm:14.0.0" + tslib: "npm:^2.4.0" + peerDependencies: + react: ^18.0.0 || ^19.0.0 + react-dom: ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + react: + optional: true + react-dom: + optional: true + checksum: 10c0/2bdbfd36a20013e3e3d072e9edfcfd261e3553a7950697e77cabc3c4607b39a9e73c218fb750b83cda4eac1a8de409b62bcc7d680eb3687209758801829e6d5c + languageName: node + linkType: hard + "mqtt-packet@npm:^9.0.1": version: 9.0.1 resolution: "mqtt-packet@npm:9.0.1" @@ -35847,12 +37567,12 @@ __metadata: languageName: node linkType: hard -"nanoid@npm:^3.0.0, nanoid@npm:^3.3.17, nanoid@npm:^3.3.18": - version: 3.3.19 - resolution: "nanoid@npm:3.3.19" +"nanoid@npm:^3.0.0, nanoid@npm:^3.3.17, nanoid@npm:^3.3.19": + version: 3.3.20 + resolution: "nanoid@npm:3.3.20" bin: nanoid: bin/nanoid.cjs - checksum: 10c0/ce7afa6258bfaa00bdc8de291cfe9913280eaa403b7d9cff3db4e4200c1913e7163577df74897958da144db473a96c67f74f57db0f542fbfe409df677bae3255 + checksum: 10c0/856e8bf3bddb959d65997bd94908be030dbc5e6ed88fb3af2a638e51d1938f4d4f454c7c7231aba340775224f88b8cfd3ce1693c70471bfd05f5b6a2227c0c1e languageName: node linkType: hard @@ -35972,6 +37692,16 @@ __metadata: languageName: node linkType: hard +"next-themes@npm:^0.4.6": + version: 0.4.6 + resolution: "next-themes@npm:0.4.6" + peerDependencies: + react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc + react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc + checksum: 10c0/83590c11d359ce7e4ced14f6ea9dd7a691d5ce6843fe2dc520fc27e29ae1c535118478d03e7f172609c41b1ef1b8da6b8dd2d2acd6cd79cac1abbdbd5b99f2c4 + languageName: node + linkType: hard + "next-tick@npm:^1.1.0": version: 1.1.0 resolution: "next-tick@npm:1.1.0" @@ -36348,6 +38078,13 @@ __metadata: languageName: node linkType: hard +"npm-to-yarn@npm:3.2.0, npm-to-yarn@npm:^3.2.0": + version: 3.2.0 + resolution: "npm-to-yarn@npm:3.2.0" + checksum: 10c0/b8e8a2bffa25ca436bbed202bbe13f05c2be85e72a15199f84923c2438e549f112c0da64071ce5be120859e798c3a2f5af80dac9ba636b772b980b783fdd5bdf + languageName: node + linkType: hard + "nprogress@npm:^0.2.0": version: 0.2.0 resolution: "nprogress@npm:0.2.0" @@ -38470,14 +40207,14 @@ __metadata: languageName: node linkType: hard -"postcss@npm:^8.3.11, postcss@npm:^8.4.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38, postcss@npm:^8.5.26, postcss@npm:^8.5.28, postcss@npm:^8.5.3, postcss@npm:^8.5.6": - version: 8.5.28 - resolution: "postcss@npm:8.5.28" +"postcss@npm:^8.3.11, postcss@npm:^8.4.14, postcss@npm:^8.4.33, postcss@npm:^8.4.38, postcss@npm:^8.5.16, postcss@npm:^8.5.26, postcss@npm:^8.5.28, postcss@npm:^8.5.3, postcss@npm:^8.5.6": + version: 8.5.29 + resolution: "postcss@npm:8.5.29" dependencies: - nanoid: "npm:^3.3.18" + nanoid: "npm:^3.3.19" picocolors: "npm:^1.1.1" - source-map-js: "npm:^1.2.1" - checksum: 10c0/9fe44215a6628d89c8a75184b92f5b2f77e16f9e5b13b39b9009bb7e8e6eccddf82c8854bae922db1f17ace6ef3445073fe38abff513caeb03e5285b1b55620a + source-map-js: "npm:^1.2.2" + checksum: 10c0/5d0c45a511e8ede0fe124d04885877525e69e3c1476f0c8c22ed53f3945bace9ca5ef8578274bdfe916b1cd0301253a52c5dbd8695115fae805cee55465088fc languageName: node linkType: hard @@ -39602,19 +41339,19 @@ __metadata: languageName: node linkType: hard -"react-remove-scroll-bar@npm:^2.3.3, react-remove-scroll-bar@npm:^2.3.6": - version: 2.3.6 - resolution: "react-remove-scroll-bar@npm:2.3.6" +"react-remove-scroll-bar@npm:^2.3.3, react-remove-scroll-bar@npm:^2.3.6, react-remove-scroll-bar@npm:^2.3.7": + version: 2.3.8 + resolution: "react-remove-scroll-bar@npm:2.3.8" dependencies: - react-style-singleton: "npm:^2.2.1" + react-style-singleton: "npm:^2.2.2" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/4e32ee04bf655a8bd3b4aacf6ffc596ae9eb1b9ba27eef83f7002632ee75371f61516ae62250634a9eae4b2c8fc6f6982d9b182de260f6c11841841e6e2e7515 + checksum: 10c0/9a0675c66cbb52c325bdbfaed80987a829c4504cefd8ff2dd3b6b3afc9a1500b8ec57b212e92c1fb654396d07bbe18830a8146fe77677d2a29ce40b5e1f78654 languageName: node linkType: hard @@ -39656,6 +41393,25 @@ __metadata: languageName: node linkType: hard +"react-remove-scroll@npm:^2.7.2": + version: 2.7.2 + resolution: "react-remove-scroll@npm:2.7.2" + dependencies: + react-remove-scroll-bar: "npm:^2.3.7" + react-style-singleton: "npm:^2.2.3" + tslib: "npm:^2.1.0" + use-callback-ref: "npm:^1.3.3" + use-sidecar: "npm:^1.1.3" + peerDependencies: + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc + peerDependenciesMeta: + "@types/react": + optional: true + checksum: 10c0/b5f3315bead75e72853f492c0b51ba8fb4fa09a4534d7fc42d6fcd59ca3e047cf213279ffc1e35b337e314ef5a04cb2b12544c85e0078802271731c27c09e5aa + languageName: node + linkType: hard + "react-resizable-panels@npm:4.6.5": version: 4.6.5 resolution: "react-resizable-panels@npm:4.6.5" @@ -39690,20 +41446,19 @@ __metadata: languageName: node linkType: hard -"react-style-singleton@npm:^2.2.1": - version: 2.2.1 - resolution: "react-style-singleton@npm:2.2.1" +"react-style-singleton@npm:^2.2.1, react-style-singleton@npm:^2.2.2, react-style-singleton@npm:^2.2.3": + version: 2.2.3 + resolution: "react-style-singleton@npm:2.2.3" dependencies: get-nonce: "npm:^1.0.0" - invariant: "npm:^2.2.4" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.8.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/6d66f3bdb65e1ec79089f80314da97c9a005087a04ee034255a5de129a4c0d9fd0bf99fa7bf642781ac2dc745ca687aae3de082bd8afdd0d117bc953241e15ad + checksum: 10c0/841938ff16d16a6b76895f4cb2e1fea957e5fe3b30febbf03a54892dae1c9153f2383e231dea0b3ba41192ad2f2849448fa859caccd288943bce32639e971bee languageName: node linkType: hard @@ -40401,7 +42156,7 @@ __metadata: languageName: node linkType: hard -"remark-mdx@npm:^3.0.0": +"remark-mdx@npm:3.1.1, remark-mdx@npm:^3.0.0": version: 3.1.1 resolution: "remark-mdx@npm:3.1.1" dependencies: @@ -40411,7 +42166,7 @@ __metadata: languageName: node linkType: hard -"remark-parse@npm:^11.0.0": +"remark-parse@npm:11.0.0, remark-parse@npm:^11.0.0": version: 11.0.0 resolution: "remark-parse@npm:11.0.0" dependencies: @@ -40448,7 +42203,7 @@ __metadata: languageName: node linkType: hard -"remark-stringify@npm:^11.0.0": +"remark-stringify@npm:11.0.0, remark-stringify@npm:^11.0.0": version: 11.0.0 resolution: "remark-stringify@npm:11.0.0" dependencies: @@ -40459,6 +42214,18 @@ __metadata: languageName: node linkType: hard +"remark@npm:^15.0.1": + version: 15.0.1 + resolution: "remark@npm:15.0.1" + dependencies: + "@types/mdast": "npm:^4.0.0" + remark-parse: "npm:^11.0.0" + remark-stringify: "npm:^11.0.0" + unified: "npm:^11.0.0" + checksum: 10c0/ba675e4a5b114355991d2c6f5b09a632121fc8825257b0d148b3938420713f9e9b6f012120604435d5c217d42742f60195ac6f898dc1339d313a6608a84dbc49 + languageName: node + linkType: hard + "remedial@npm:^1.0.7": version: 1.0.8 resolution: "remedial@npm:1.0.8" @@ -40553,9 +42320,9 @@ __metadata: linkType: hard "reselect@npm:^5.1.0, reselect@npm:^5.2.0": - version: 5.2.0 - resolution: "reselect@npm:5.2.0" - checksum: 10c0/d0a8497e404b25a769fe792eacae88b9b576c30870450cd243d76ec9427d91a59c4a2cc00d824d283448b444c4c698a8f961d771c8ae39c759313afb31950e2e + version: 5.3.0 + resolution: "reselect@npm:5.3.0" + checksum: 10c0/c79728e4f315152bfb2d82456d35075b705392d9e72c485d7d9b1061bd80af628416216d80f02a42f24dbb24d738aec7fec45806930aaa1d17c32e9875fa1bd6 languageName: node linkType: hard @@ -40603,16 +42370,17 @@ __metadata: languageName: node linkType: hard -"resolve@npm:^1.10.0, resolve@npm:^1.19.0, resolve@npm:^1.20.0, resolve@npm:^1.22.1, resolve@npm:^1.22.10, resolve@npm:^1.22.4, resolve@npm:^1.22.8, resolve@npm:~1.22.2": - version: 1.22.10 - resolution: "resolve@npm:1.22.10" +"resolve@npm:^1.10.0, resolve@npm:^1.19.0, resolve@npm:^1.20.0, resolve@npm:^1.22.1, resolve@npm:^1.22.10, resolve@npm:^1.22.4, resolve@npm:^1.22.8, resolve@npm:~1.22.1, resolve@npm:~1.22.2": + version: 1.22.13 + resolution: "resolve@npm:1.22.13" dependencies: - is-core-module: "npm:^2.16.0" + es-errors: "npm:^1.3.0" + is-core-module: "npm:^2.17.0" path-parse: "npm:^1.0.7" supports-preserve-symlinks-flag: "npm:^1.0.0" bin: resolve: bin/resolve - checksum: 10c0/8967e1f4e2cc40f79b7e080b4582b9a8c5ee36ffb46041dccb20e6461161adf69f843b43067b4a375de926a2cd669157e29a29578191def399dd5ef89a1b5203 + checksum: 10c0/8dac5b33a1f9f241500fcaf42f9033cdcaf3738c908a60a50a976ff2f6129063cbc5368b4092e42d2d264ad22aa94aaff207f3efa8d0185c68454439b11a1973 languageName: node linkType: hard @@ -40629,16 +42397,17 @@ __metadata: languageName: node linkType: hard -"resolve@patch:resolve@npm%3A^1.10.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.19.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.20.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.1#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.10#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.4#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.8#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A~1.22.2#optional!builtin<compat/resolve>": - version: 1.22.10 - resolution: "resolve@patch:resolve@npm%3A1.22.10#optional!builtin<compat/resolve>::version=1.22.10&hash=9bd1a5" +"resolve@patch:resolve@npm%3A^1.10.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.19.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.20.0#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.1#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.10#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.4#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A^1.22.8#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A~1.22.1#optional!builtin<compat/resolve>, resolve@patch:resolve@npm%3A~1.22.2#optional!builtin<compat/resolve>": + version: 1.22.13 + resolution: "resolve@patch:resolve@npm%3A1.22.13#optional!builtin<compat/resolve>::version=1.22.13&hash=9bd1a5" dependencies: - is-core-module: "npm:^2.16.0" + es-errors: "npm:^1.3.0" + is-core-module: "npm:^2.17.0" path-parse: "npm:^1.0.7" supports-preserve-symlinks-flag: "npm:^1.0.0" bin: resolve: bin/resolve - checksum: 10c0/da5c4a85971e6eeb821805d117092321c6c257a6e1e45382c0b7ef41368a7e98690e01a08bac88b111443410a49e2fb17d1802ac5c51c8fc5532d77bef9f4be9 + checksum: 10c0/bc58ee02e647a4250453eeb067796bdc087f6a89d4d5780bfe479f402ec11b9461babc155a6452020b56f3845cf49b1afd9c95fe3fc8347cba6567aa9b10c106 languageName: node linkType: hard @@ -41281,7 +43050,7 @@ __metadata: languageName: node linkType: hard -"satteri@npm:^0.10.3": +"satteri@npm:0.10.5, satteri@npm:^0.10.3, satteri@npm:^0.10.5": version: 0.10.5 resolution: "satteri@npm:0.10.5" dependencies: @@ -41407,6 +43176,15 @@ __metadata: languageName: node linkType: hard +"scroll-into-view-if-needed@npm:^3.1.0": + version: 3.1.0 + resolution: "scroll-into-view-if-needed@npm:3.1.0" + dependencies: + compute-scroll-into-view: "npm:^3.0.2" + checksum: 10c0/1f46b090e1e04fcfdef1e384f6d7e615f9f84d4176faf4dbba7347cc0a6e491e5d578eaf4dbe9618dd3d8d38efafde58535b3e00f2a21ce4178c14be364850ff + languageName: node + linkType: hard + "scslre@npm:^0.3.0": version: 0.3.0 resolution: "scslre@npm:0.3.0" @@ -41510,6 +43288,15 @@ __metadata: languageName: node linkType: hard +"semver@npm:~7.7.4": + version: 7.7.4 + resolution: "semver@npm:7.7.4" + bin: + semver: bin/semver.js + checksum: 10c0/5215ad0234e2845d4ea5bb9d836d42b03499546ddafb12075566899fc617f68794bb6f146076b6881d755de17d6c6cc73372555879ec7dce2c2feee947866ad2 + languageName: node + linkType: hard + "send@npm:^1.1.0, send@npm:^1.2.0": version: 1.2.0 resolution: "send@npm:1.2.0" @@ -41848,19 +43635,19 @@ __metadata: languageName: node linkType: hard -"shiki@npm:^4.0.2": - version: 4.4.2 - resolution: "shiki@npm:4.4.2" - dependencies: - "@shikijs/core": "npm:4.4.2" - "@shikijs/engine-javascript": "npm:4.4.2" - "@shikijs/engine-oniguruma": "npm:4.4.2" - "@shikijs/langs": "npm:4.4.2" - "@shikijs/themes": "npm:4.4.2" - "@shikijs/types": "npm:4.4.2" +"shiki@npm:4.5.0, shiki@npm:^4.0.2, shiki@npm:^4.4.3, shiki@npm:^4.5.0": + version: 4.5.0 + resolution: "shiki@npm:4.5.0" + dependencies: + "@shikijs/core": "npm:4.5.0" + "@shikijs/engine-javascript": "npm:4.5.0" + "@shikijs/engine-oniguruma": "npm:4.5.0" + "@shikijs/langs": "npm:4.5.0" + "@shikijs/themes": "npm:4.5.0" + "@shikijs/types": "npm:4.5.0" "@shikijs/vscode-textmate": "npm:^10.0.2" "@types/hast": "npm:^3.0.5" - checksum: 10c0/2bae4e358c561373ef5b5a7c3456466d91ae413250abad83a6281bc37b178fd5a6b9d5d68c9b2071d3c4f97ae11262faf04d453ecb9a5fd06af5bb765b6ef2dd + checksum: 10c0/eab0f3ca35caacbfe78a538d91b4956ff4f06aacaf3234e4f6f8d0c594d6a1612d022afbc3f11c4345dd87bb7a1dafcb8edd9ecace797b25097d91cfd473d0d1 languageName: node linkType: hard @@ -42153,7 +43940,7 @@ __metadata: languageName: node linkType: hard -"source-map-js@npm:>=0.6.2 <2.0.0, source-map-js@npm:^1.0.1, source-map-js@npm:^1.0.2, source-map-js@npm:^1.2.1": +"source-map-js@npm:>=0.6.2 <2.0.0, source-map-js@npm:^1.0.1, source-map-js@npm:^1.0.2, source-map-js@npm:^1.2.1, source-map-js@npm:^1.2.2": version: 1.2.2 resolution: "source-map-js@npm:1.2.2" checksum: 10c0/d5d6dec62266834f83dd4f8a2606a196fb1a006ca5d53b0ef80ee513b7eba2f4e2ae241f4bc129ae7e9b80dea24f6e3d92b446b7e6e96be7653cab8888168a94 @@ -42317,6 +44104,13 @@ __metadata: languageName: node linkType: hard +"sprintf-js@npm:~1.0.2": + version: 1.0.3 + resolution: "sprintf-js@npm:1.0.3" + checksum: 10c0/ecadcfe4c771890140da5023d43e190b7566d9cf8b2d238600f31bec0fc653f328da4450eb04bd59a431771a8e9cc0e118f0aa3974b683a4981b4e07abc2a5bb + languageName: node + linkType: hard + "ssri@npm:^13.0.0": version: 13.0.1 resolution: "ssri@npm:13.0.1" @@ -42493,7 +44287,7 @@ __metadata: languageName: node linkType: hard -"string-argv@npm:^0.3.2": +"string-argv@npm:^0.3.2, string-argv@npm:~0.3.1": version: 0.3.2 resolution: "string-argv@npm:0.3.2" checksum: 10c0/75c02a83759ad1722e040b86823909d9a2fc75d15dd71ec4b537c3560746e33b5f5a07f7332d1e3f88319909f82190843aa2f0a0d8c8d591ec08e93d5b8dec82 @@ -42882,7 +44676,7 @@ __metadata: languageName: node linkType: hard -"supports-color@npm:^8.0.0, supports-color@npm:^8.1.1": +"supports-color@npm:^8.0.0, supports-color@npm:^8.1.1, supports-color@npm:~8.1.1": version: 8.1.1 resolution: "supports-color@npm:8.1.1" dependencies: @@ -43045,6 +44839,13 @@ __metadata: languageName: node linkType: hard +"tailwindcss@npm:4.3.3": + version: 4.3.3 + resolution: "tailwindcss@npm:4.3.3" + checksum: 10c0/7e9cd7553cd890ffa5350efb0ca8971ba5435257d0f98bf0714994ac8f1fee5c7cdf9a9da47fe83e8ac995d728410837ac49d3ef5ea66b5afe1db312086ffae2 + languageName: node + linkType: hard + "tapable@npm:^2.0.0, tapable@npm:^2.2.1, tapable@npm:^2.3.0, tapable@npm:^2.3.3": version: 2.3.3 resolution: "tapable@npm:2.3.3" @@ -44156,6 +45957,16 @@ __metadata: languageName: node linkType: hard +"typescript@npm:5.9.3": + version: 5.9.3 + resolution: "typescript@npm:5.9.3" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/6bd7552ce39f97e711db5aa048f6f9995b53f1c52f7d8667c1abdc1700c68a76a308f579cd309ce6b53646deb4e9a1be7c813a93baaf0a28ccd536a30270e1c5 + languageName: node + linkType: hard + "typescript@npm:6.0.2": version: 6.0.2 resolution: "typescript@npm:6.0.2" @@ -44166,7 +45977,7 @@ __metadata: languageName: node linkType: hard -"typescript@npm:7.0.2": +"typescript@npm:7.0.2, typescript@npm:~7.0.2": version: 7.0.2 resolution: "typescript@npm:7.0.2" dependencies: @@ -44257,6 +46068,16 @@ __metadata: languageName: node linkType: hard +"typescript@patch:typescript@npm%3A5.9.3#optional!builtin<compat/typescript>": + version: 5.9.3 + resolution: "typescript@patch:typescript@npm%3A5.9.3#optional!builtin<compat/typescript>::version=5.9.3&hash=5786d5" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/ad09fdf7a756814dce65bc60c1657b40d44451346858eea230e10f2e95a289d9183b6e32e5c11e95acc0ccc214b4f36289dcad4bf1886b0adb84d711d336a430 + languageName: node + linkType: hard + "typescript@patch:typescript@npm%3A6.0.2#optional!builtin<compat/typescript>": version: 6.0.2 resolution: "typescript@patch:typescript@npm%3A6.0.2#optional!builtin<compat/typescript>::version=6.0.2&hash=5786d5" @@ -44277,7 +46098,7 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@npm%3A7.0.2#optional!builtin<compat/typescript>": +"typescript@patch:typescript@npm%3A7.0.2#optional!builtin<compat/typescript>, typescript@patch:typescript@npm%3A~7.0.2#optional!builtin<compat/typescript>": version: 7.0.2 resolution: "typescript@patch:typescript@npm%3A7.0.2#optional!builtin<compat/typescript>::version=7.0.2&hash=3bafbf" dependencies: @@ -44599,7 +46420,7 @@ __metadata: languageName: node linkType: hard -"unified@npm:^11.0.0, unified@npm:^11.0.4, unified@npm:^11.0.5": +"unified@npm:11.0.5, unified@npm:^11.0.0, unified@npm:^11.0.4, unified@npm:^11.0.5": version: 11.0.5 resolution: "unified@npm:11.0.5" dependencies: @@ -45098,7 +46919,7 @@ __metadata: languageName: node linkType: hard -"use-callback-ref@npm:1.3.3, use-callback-ref@npm:^1.3.0": +"use-callback-ref@npm:1.3.3, use-callback-ref@npm:^1.3.0, use-callback-ref@npm:^1.3.3": version: 1.3.3 resolution: "use-callback-ref@npm:1.3.3" dependencies: @@ -45151,19 +46972,19 @@ __metadata: languageName: node linkType: hard -"use-sidecar@npm:^1.1.2": - version: 1.1.2 - resolution: "use-sidecar@npm:1.1.2" +"use-sidecar@npm:^1.1.2, use-sidecar@npm:^1.1.3": + version: 1.1.3 + resolution: "use-sidecar@npm:1.1.3" dependencies: detect-node-es: "npm:^1.1.0" tslib: "npm:^2.0.0" peerDependencies: - "@types/react": ^16.9.0 || ^17.0.0 || ^18.0.0 - react: ^16.8.0 || ^17.0.0 || ^18.0.0 + "@types/react": "*" + react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc peerDependenciesMeta: "@types/react": optional: true - checksum: 10c0/89f0018fd9aee1fc17c85ac18c4bf8944d460d453d0d0e04ddbc8eaddf3fa591e9c74a1f8a438a1bff368a7a2417fab380bdb3df899d2194c4375b0982736de0 + checksum: 10c0/161599bf921cfaa41c85d2b01c871975ee99260f3e874c2d41c05890d41170297bdcf314bc5185e7a700de2034ac5b888e3efc8e9f35724f4918f53538d717c9 languageName: node linkType: hard @@ -46738,12 +48559,12 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0": - version: 2.9.0 - resolution: "yaml@npm:2.9.0" +"yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0, yaml@npm:^2.9.1": + version: 2.9.1 + resolution: "yaml@npm:2.9.1" bin: yaml: bin.mjs - checksum: 10c0/f340718df45e97a9551b9bf9dac61c80050bc464513b710debfb5067c380c8472e3b67809cffacb4ab5ffb5e66ef9310816c88b05f371cec60abfedd8c88e0a2 + checksum: 10c0/9d06676ef02b89559a8b10a71882bd2cdae81e8393dc8dbc871615c3259475d9609ad973d19cb3c9e71e72d6206e3d1e7aa241c7e55f3d16fd2e77db305827d6 languageName: node linkType: hard @@ -46867,6 +48688,53 @@ __metadata: languageName: node linkType: hard +"yuku-analyzer@npm:^0.10.2": + version: 0.10.2 + resolution: "yuku-analyzer@npm:0.10.2" + dependencies: + "@yuku-analyzer/binding-android-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-darwin-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-darwin-x64": "npm:0.10.2" + "@yuku-analyzer/binding-freebsd-x64": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm-musl": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm64-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-arm64-musl": "npm:0.10.2" + "@yuku-analyzer/binding-linux-x64-gnu": "npm:0.10.2" + "@yuku-analyzer/binding-linux-x64-musl": "npm:0.10.2" + "@yuku-analyzer/binding-win32-arm64": "npm:0.10.2" + "@yuku-analyzer/binding-win32-x64": "npm:0.10.2" + "@yuku-toolchain/types": "npm:^0.10.2" + yuku-ast: "npm:^0.10.2" + dependenciesMeta: + "@yuku-analyzer/binding-android-arm64": + optional: true + "@yuku-analyzer/binding-darwin-arm64": + optional: true + "@yuku-analyzer/binding-darwin-x64": + optional: true + "@yuku-analyzer/binding-freebsd-x64": + optional: true + "@yuku-analyzer/binding-linux-arm-gnu": + optional: true + "@yuku-analyzer/binding-linux-arm-musl": + optional: true + "@yuku-analyzer/binding-linux-arm64-gnu": + optional: true + "@yuku-analyzer/binding-linux-arm64-musl": + optional: true + "@yuku-analyzer/binding-linux-x64-gnu": + optional: true + "@yuku-analyzer/binding-linux-x64-musl": + optional: true + "@yuku-analyzer/binding-win32-arm64": + optional: true + "@yuku-analyzer/binding-win32-x64": + optional: true + checksum: 10c0/ac80a5c37f908c28fa1de0ebb6d7c8a247a527c3db483e77edaeb3284abc3b43a123c8d8d9b1503150ff0564d3e7f066970ed9f290ffcb3e99955c99a203e488 + languageName: node + linkType: hard + "yuku-ast@npm:^0.10.1, yuku-ast@npm:^0.10.2": version: 0.10.2 resolution: "yuku-ast@npm:0.10.2" @@ -46876,12 +48744,12 @@ __metadata: languageName: node linkType: hard -"yuku-ast@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-ast@npm:0.9.3" +"yuku-ast@npm:^0.9.3, yuku-ast@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-ast@npm:0.9.5" dependencies: - "@yuku-toolchain/types": "npm:^0.9.3" - checksum: 10c0/ddb1eb96e59405c14387ca89fb2b543e335c0e8a6928bd09205cf67d7977a7d115f081180dbcc95bcb9733e4c86955c4f7f4d15f2c8bdf5a7a1b6cb112ed25dc + "@yuku-toolchain/types": "npm:^0.9.5" + checksum: 10c0/cc6159880196008f10765e9c64d6fbc6ceab87ea5451d88907992bf007d10e1bc533c93a5a7b00bb3ac5903e13fed76be447f65d3f8e6a6da210509009e32043 languageName: node linkType: hard @@ -46931,23 +48799,23 @@ __metadata: languageName: node linkType: hard -"yuku-codegen@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-codegen@npm:0.9.3" - dependencies: - "@yuku-codegen/binding-android-arm64": "npm:0.9.3" - "@yuku-codegen/binding-darwin-arm64": "npm:0.9.3" - "@yuku-codegen/binding-darwin-x64": "npm:0.9.3" - "@yuku-codegen/binding-freebsd-x64": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm-musl": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm64-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-arm64-musl": "npm:0.9.3" - "@yuku-codegen/binding-linux-x64-gnu": "npm:0.9.3" - "@yuku-codegen/binding-linux-x64-musl": "npm:0.9.3" - "@yuku-codegen/binding-win32-arm64": "npm:0.9.3" - "@yuku-codegen/binding-win32-x64": "npm:0.9.3" - "@yuku-toolchain/types": "npm:^0.9.3" +"yuku-codegen@npm:^0.9.3, yuku-codegen@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-codegen@npm:0.9.5" + dependencies: + "@yuku-codegen/binding-android-arm64": "npm:0.9.5" + "@yuku-codegen/binding-darwin-arm64": "npm:0.9.5" + "@yuku-codegen/binding-darwin-x64": "npm:0.9.5" + "@yuku-codegen/binding-freebsd-x64": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm-musl": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm64-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-arm64-musl": "npm:0.9.5" + "@yuku-codegen/binding-linux-x64-gnu": "npm:0.9.5" + "@yuku-codegen/binding-linux-x64-musl": "npm:0.9.5" + "@yuku-codegen/binding-win32-arm64": "npm:0.9.5" + "@yuku-codegen/binding-win32-x64": "npm:0.9.5" + "@yuku-toolchain/types": "npm:^0.9.5" dependenciesMeta: "@yuku-codegen/binding-android-arm64": optional: true @@ -46973,7 +48841,7 @@ __metadata: optional: true "@yuku-codegen/binding-win32-x64": optional: true - checksum: 10c0/3468b011a118b636d0854c0c1bf464234d54a957060127446f71ed1bc17a4aab72e97667d86e3e7dbcde99b331514a2b8c95cc4cf28dbc14960440a21b5636c9 + checksum: 10c0/fff0d52b38af71a4f2f76ef44406a0c3237957ca2ed0118c156e495b48d03a431f8132808b7f52e8c09d9838267c3cbd6074b9a3e4bca825d442b7a4613bedd8 languageName: node linkType: hard @@ -47024,24 +48892,24 @@ __metadata: languageName: node linkType: hard -"yuku-parser@npm:^0.9.3": - version: 0.9.3 - resolution: "yuku-parser@npm:0.9.3" - dependencies: - "@yuku-parser/binding-android-arm64": "npm:0.9.3" - "@yuku-parser/binding-darwin-arm64": "npm:0.9.3" - "@yuku-parser/binding-darwin-x64": "npm:0.9.3" - "@yuku-parser/binding-freebsd-x64": "npm:0.9.3" - "@yuku-parser/binding-linux-arm-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-arm-musl": "npm:0.9.3" - "@yuku-parser/binding-linux-arm64-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-arm64-musl": "npm:0.9.3" - "@yuku-parser/binding-linux-x64-gnu": "npm:0.9.3" - "@yuku-parser/binding-linux-x64-musl": "npm:0.9.3" - "@yuku-parser/binding-win32-arm64": "npm:0.9.3" - "@yuku-parser/binding-win32-x64": "npm:0.9.3" - "@yuku-toolchain/types": "npm:^0.9.3" - yuku-ast: "npm:^0.9.3" +"yuku-parser@npm:^0.9.3, yuku-parser@npm:^0.9.5": + version: 0.9.5 + resolution: "yuku-parser@npm:0.9.5" + dependencies: + "@yuku-parser/binding-android-arm64": "npm:0.9.5" + "@yuku-parser/binding-darwin-arm64": "npm:0.9.5" + "@yuku-parser/binding-darwin-x64": "npm:0.9.5" + "@yuku-parser/binding-freebsd-x64": "npm:0.9.5" + "@yuku-parser/binding-linux-arm-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-arm-musl": "npm:0.9.5" + "@yuku-parser/binding-linux-arm64-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-arm64-musl": "npm:0.9.5" + "@yuku-parser/binding-linux-x64-gnu": "npm:0.9.5" + "@yuku-parser/binding-linux-x64-musl": "npm:0.9.5" + "@yuku-parser/binding-win32-arm64": "npm:0.9.5" + "@yuku-parser/binding-win32-x64": "npm:0.9.5" + "@yuku-toolchain/types": "npm:^0.9.5" + yuku-ast: "npm:^0.9.5" dependenciesMeta: "@yuku-parser/binding-android-arm64": optional: true @@ -47067,7 +48935,14 @@ __metadata: optional: true "@yuku-parser/binding-win32-x64": optional: true - checksum: 10c0/a6805b88dcea1165e31d798ffca825a68d52bedcc1ee3bf252d8434e82a4f894d28a7a78fa666c351cf976b095f20994f34ad8042412281e69d07630d229a37c + checksum: 10c0/e01bd82ac6369166320cfe64770e9e3cbd48a502844cd11afc5b11bb5cbbe484c70af804e0dde50142cc6daad9689ffeb88099731a836e32601df07813527489 + languageName: node + linkType: hard + +"zbsearch@npm:^4.0.1": + version: 4.0.1 + resolution: "zbsearch@npm:4.0.1" + checksum: 10c0/c19146c1116c816b52c613ab841b22214d49e4c9dbb58c523a71e2c32aa70466d57e61092836726f8a918d77aaf8a6bf336cd5f576e813e260a9a17e352eb2b8 languageName: node linkType: hard @@ -47133,7 +49008,7 @@ __metadata: languageName: node linkType: hard -"zod@npm:4.4.3, zod@npm:^3.25 || ^4.0, zod@npm:^3.25.0 || ^4.0.0, zod@npm:^4.0.0, zod@npm:^4.1.5, zod@npm:^4.2.0, zod@npm:^4.3.6, zod@npm:^4.4.3": +"zod@npm:4.4.3": version: 4.4.3 resolution: "zod@npm:4.4.3" checksum: 10c0/7ea31b558e88f9faf44f31dd185e2e1cbf51fed3081787fb96cc2534749b50c0acfc6da7f0922a7353ed092dd358c7d50c28ea96c94d04af64191bd33152eca3 @@ -47147,6 +49022,13 @@ __metadata: languageName: node linkType: hard +"zod@npm:^3.25 || ^4.0, zod@npm:^3.25.0 || ^4.0.0, zod@npm:^4.0.0, zod@npm:^4.1.5, zod@npm:^4.2.0, zod@npm:^4.3.6, zod@npm:^4.4.3, zod@npm:^4.6.5": + version: 4.6.5 + resolution: "zod@npm:4.6.5" + checksum: 10c0/32eb6c5e98becbe045675b2141c3611451c16ba567f9779231d79af41c4d651ca1c22f154aef7e6c6e77b929f23e43f1154ca05b82e119e922353725d6776af5 + languageName: node + linkType: hard + "zrender@npm:6.1.0": version: 6.1.0 resolution: "zrender@npm:6.1.0" From 293b958d6676afcd3eeb6e0b858b4a19f695a93b Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:47:24 +0200 Subject: [PATCH 14/22] feat: add Effect API analysis CLI to HashQL docs --- .../hashql/sdk/typescript-docs/api-entry.d.ts | 1 - .../sdk/typescript-docs/api-extractor.json | 31 ----- .../docs/task-dependencies.json | 46 +++++++ .../sdk/typescript-docs/oxlint.config.ts | 13 +- .../hashql/sdk/typescript-docs/package.json | 7 +- .../hashql/sdk/typescript-docs/src/Analyze.ts | 114 ++++++++++++++++++ .../hashql/sdk/typescript-docs/src/cli.ts | 17 +++ .../hashql/sdk/typescript-docs/tsconfig.json | 4 - .../hashql/sdk/typescript-docs/tsdoc.json | 28 ----- .../hashql/sdk/typescript-docs/turbo.json | 60 +-------- libs/@local/hashql/sdk/typescript/tsdoc.json | 1 + yarn.lock | 2 + 12 files changed, 195 insertions(+), 129 deletions(-) delete mode 100644 libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts delete mode 100644 libs/@local/hashql/sdk/typescript-docs/api-extractor.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/cli.ts delete mode 100644 libs/@local/hashql/sdk/typescript-docs/tsdoc.json diff --git a/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts b/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts deleted file mode 100644 index 6ea60620d77..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/api-entry.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./.generated/declarations/program/Expression.js"; diff --git a/libs/@local/hashql/sdk/typescript-docs/api-extractor.json b/libs/@local/hashql/sdk/typescript-docs/api-extractor.json deleted file mode 100644 index 272a1e4089b..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/api-extractor.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", - "projectFolder": ".", - "mainEntryPointFilePath": "<projectFolder>/api-entry.d.ts", - "compiler": { - "overrideTsconfig": { - "compilerOptions": { - "strict": true, - "target": "ES2024", - "module": "NodeNext", - "moduleResolution": "NodeNext", - "skipLibCheck": true - }, - "include": ["api-entry.d.ts"] - }, - "skipLibCheck": true - }, - "apiReport": { - "enabled": false - }, - "docModel": { - "enabled": true, - "apiJsonFilePath": "<projectFolder>/.generated/api-model/hashql.api.json" - }, - "dtsRollup": { - "enabled": false - }, - "tsdocMetadata": { - "enabled": false - } -} diff --git a/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json new file mode 100644 index 00000000000..4102badd337 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json @@ -0,0 +1,46 @@ +{ + "package": "@local/hashql-typescript-docs", + "dependencies": [ + "@local/hashql", + "@local/oxlint", + "@local/tsconfig" + ], + "tasks": { + "build": { + "dependsOn": [] + }, + "codegen": { + "dependsOn": [] + }, + "dev": { + "dependsOn": [], + "cache": false, + "persistent": true + }, + "lint:oxlint": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ] + }, + "lint:tsc": { + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ] + }, + "start": { + "dependsOn": [], + "cache": false, + "persistent": true + }, + "test:unit": { + "dependsOn": [], + "env": [ + "TEST_COVERAGE" + ] + } + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index 6a20bba989b..fcc1f6f3e52 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -1,9 +1,20 @@ import { createConfig, defineConfig } from "@local/oxlint"; export default defineConfig({ - extends: [createConfig({ runtime: "node", frameworks: ["react", "next"] })], + extends: [ + createConfig({ runtime: "node", frameworks: ["react", "next", "effect"] }), + ], ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], overrides: [ + { + files: ["src/**/*.ts"], + rules: { + "unicorn/filename-case": [ + "deny", // filename casing follows Effect style + { cases: { pascalCase: true, kebabCase: true } }, + ], + }, + }, { files: ["app/**/*.tsx", "*.config.mjs"], rules: { diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index 14c1ce2fd97..f233c80eb2d 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -9,11 +9,6 @@ "build": "next build --webpack", "codegen": "fumadocs-mdx", "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", - "doc:declarations": "tsc --project tsconfig.api.json", - "doc:examples": "node --experimental-strip-types scripts/examples.mts", - "doc:markdown": "api-documenter markdown --input-folder .generated/api-model --output-folder .generated/markdown", - "doc:model": "node --experimental-strip-types scripts/extract.mts", - "doc:render": "node --experimental-strip-types scripts/render.mts", "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", "lint:tsc": "tsc --noEmit", @@ -33,6 +28,7 @@ "satteri": "0.10.5" }, "devDependencies": { + "@effect/platform-node": "4.0.0", "@local/oxlint": "workspace:*", "@local/tsconfig": "workspace:*", "@microsoft/api-documenter": "7.30.18", @@ -49,6 +45,7 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "effect": "4.0.0", + "oxc-parser": "0.152.0", "oxfmt": "0.71.0", "oxlint": "catalog:", "remark-mdx": "3.1.1", diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts new file mode 100644 index 00000000000..502cf34f358 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts @@ -0,0 +1,114 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { Extractor, ExtractorConfig } from "@microsoft/api-extractor"; +import { Data, Effect, FileSystem, Path } from "effect"; +import { Command, Flag } from "effect/cli"; + +import type { IConfigFile } from "@microsoft/api-extractor"; + +const makeExtractorConfig = ({ + lib, + entry, + out, +}: { + lib: string; + entry: string; + out: string; +}): IConfigFile => ({ + projectFolder: lib, + mainEntryPointFilePath: entry, + compiler: { + tsconfigFilePath: "<projectFolder>/tsconfig.json", + }, + apiReport: { + enabled: false, + }, + docModel: { + enabled: true, + apiJsonFilePath: `${out}/api.json`, + }, + dtsRollup: { + enabled: false, + }, + tsdocMetadata: { + enabled: false, + }, +}); + +/** API Extractor finished the analysis and reported errors. */ +export class ExtractionError extends Data.TaggedError("ExtractionError")<{ + readonly errorCount: number; + readonly warningCount: number; +}> {} + +export const command = Command.make("analyze", { + lib: Flag.Directory("lib"), + include: Flag.File("include", { mustExist: true }).pipe(Flag.atLeast(1)), + out: Flag.Directory("out").pipe( + Flag.withDefault( + Effect.suspend(() => + Path.Path.pipe( + Effect.map((path) => + path.resolve(import.meta.dirname, "..", ".generated"), + ), + ), + ), + ), + ), +}); + +export const handler = command.pipe( + Command.withHandler( + Effect.fnUntraced(function* ({ lib, include, out }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const libPath = path.resolve(lib); + const outPath = path.resolve(out); + const entryPath = path.join(outPath, "api-entry.d.ts"); + + // API Extractor analyzes one entry point, so the included declaration files are re-exported from one generated module. + const entry = include + .map((file) => { + const specifier = path + .relative(outPath, path.resolve(file)) + .replace(/\.d\.(?<format>[cm]?)ts$/u, ".$<format>js"); + + if (specifier.startsWith("../")) { + return `export * from ${JSON.stringify(specifier)};\n`; + } + + return `export * from ${JSON.stringify(`./${specifier}`)};\n`; + }) + .join(""); + + yield* fs.makeDirectory(outPath, { recursive: true }); + yield* fs.writeFileString(entryPath, entry); + + // Reads `<projectFolder>/tsdoc.json`, and throws when that or any configured path is invalid. + const extractorConfig = yield* Effect.try(() => + ExtractorConfig.prepare({ + configObject: makeExtractorConfig({ + lib: libPath, + entry: entryPath, + out: outPath, + }), + configObjectFullPath: undefined, + packageJsonFullPath: path.join(libPath, "package.json"), + }), + ); + + const result = yield* Effect.try(() => + Extractor.invoke(extractorConfig, { localBuild: true }), + ); + + if (!result.succeeded) { + return yield* new ExtractionError({ + errorCount: result.errorCount, + warningCount: result.warningCount, + }); + } + + return "Ok"; + }), + ), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/cli.ts b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts new file mode 100644 index 00000000000..c2e4c8a3843 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts @@ -0,0 +1,17 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { NodeRuntime, NodeServices } from "@effect/platform-node"; +import { Effect } from "effect"; +import { Command } from "effect/cli"; + +import * as Analyze from "./Analyze.js"; + +const command = Command.make("docs").pipe( + Command.withSubcommands([Analyze.handler]), +); + +Command.run(command, { version: "0.0.1" }).pipe( + // oxlint-disable-next-line effecttsgo/strict-effect-provide -- entrypoint + Effect.provide(NodeServices.layer), + // oxlint-disable-next-line typescript/strict-void-return -- false positive + NodeRuntime.runMain, +); diff --git a/libs/@local/hashql/sdk/typescript-docs/tsconfig.json b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json index c83d408a40f..434ec35d288 100644 --- a/libs/@local/hashql/sdk/typescript-docs/tsconfig.json +++ b/libs/@local/hashql/sdk/typescript-docs/tsconfig.json @@ -1,9 +1,5 @@ { "extends": ["@tsconfig/bases/next", "@local/tsconfig/policy.json"], - "compilerOptions": { - "allowImportingTsExtensions": true, - "checkJs": true - }, "include": [ "next-env.d.ts", "**/*.ts", diff --git a/libs/@local/hashql/sdk/typescript-docs/tsdoc.json b/libs/@local/hashql/sdk/typescript-docs/tsdoc.json deleted file mode 100644 index 10f257f74bf..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/tsdoc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", - "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], - "tagDefinitions": [ - { - "tagName": "@category", - "syntaxKind": "block" - }, - { - "tagName": "@stability", - "syntaxKind": "block" - }, - { - "tagName": "@since", - "syntaxKind": "block" - }, - { - "tagName": "@module", - "syntaxKind": "modifier" - } - ], - "supportForTags": { - "@category": true, - "@stability": true, - "@since": true, - "@module": true - } -} diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json index bf06d160a83..d8012314a2a 100644 --- a/libs/@local/hashql/sdk/typescript-docs/turbo.json +++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json @@ -2,64 +2,6 @@ "$schema": "https://turborepo.org/schema.json", "extends": ["//"], "tasks": { - "doc:declarations": { - "dependsOn": ["@local/hashql#manifest"], - "inputs": [ - "$TURBO_DEFAULT$", - "../typescript/src/**", - "../typescript/tsconfig.json" - ], - "outputs": [".generated/declarations/**"] - }, - "doc:model": { - "dependsOn": ["doc:declarations"], - "outputs": [".generated/api-model/**"] - }, - "doc:markdown": { - "dependsOn": ["doc:model"], - "outputs": [".generated/markdown/**"] - }, - "doc:examples": { - "dependsOn": ["doc:markdown", "@local/hashql#build"], - "outputs": [".generated/examples/**"] - }, - "doc:render": { - "dependsOn": ["doc:examples"], - "inputs": [ - "$TURBO_DEFAULT$", - "../typescript/src/**", - "$TURBO_ROOT$/oxfmt.config.ts" - ], - "outputs": ["content/docs/reference/**", "lib/reference-links.json"] - }, - "codegen": { - "dependsOn": ["doc:render"], - "outputs": [".source/**"] - }, - "build": { - "dependsOn": ["codegen"], - "env": ["NEXT_TELEMETRY_DISABLED"], - "outputs": [".next/**", "!.next/cache/**"] - }, - "dev": { - "dependsOn": ["codegen"], - "cache": false, - "persistent": true, - "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] - }, - "start": { - "cache": false, - "persistent": true, - "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] - }, - "lint:tsc": { - "dependsOn": ["codegen"] - }, - "lint:oxlint": { - "dependsOn": ["codegen", "@local/oxlint#build"] - }, - "test:unit": { - "dependsOn": ["doc:markdown"] - } + // TODO } } diff --git a/libs/@local/hashql/sdk/typescript/tsdoc.json b/libs/@local/hashql/sdk/typescript/tsdoc.json index 802e1e09536..10f257f74bf 100644 --- a/libs/@local/hashql/sdk/typescript/tsdoc.json +++ b/libs/@local/hashql/sdk/typescript/tsdoc.json @@ -1,5 +1,6 @@ { "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["@microsoft/api-extractor/extends/tsdoc-base.json"], "tagDefinitions": [ { "tagName": "@category", diff --git a/yarn.lock b/yarn.lock index d7ecda14875..c91d46d6ba0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10233,6 +10233,7 @@ __metadata: version: 0.0.0-use.local resolution: "@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs" dependencies: + "@effect/platform-node": "npm:4.0.0" "@fumadocs/satteri": "npm:0.5.1" "@local/hashql": "workspace:*" "@local/oxlint": "workspace:*" @@ -10256,6 +10257,7 @@ __metadata: fumadocs-twoslash: "npm:4.0.1" fumadocs-ui: "npm:16.16.2" next: "npm:16.3.8" + oxc-parser: "npm:0.152.0" oxfmt: "npm:0.71.0" oxlint: "catalog:" react: "npm:19.2.6" From 89fb06aab52a6ad1954a77e4590011ffbb49563d Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:51:17 +0200 Subject: [PATCH 15/22] chore: configure API extractor warning levels --- .../hashql/sdk/typescript-docs/src/Analyze.ts | 24 ++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts index 502cf34f358..9deeb84af44 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts @@ -1,5 +1,9 @@ // oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable -import { Extractor, ExtractorConfig } from "@microsoft/api-extractor"; +import { + Extractor, + ExtractorConfig, + ExtractorLogLevel, +} from "@microsoft/api-extractor"; import { Data, Effect, FileSystem, Path } from "effect"; import { Command, Flag } from "effect/cli"; @@ -32,6 +36,20 @@ const makeExtractorConfig = ({ tsdocMetadata: { enabled: false, }, + // `prepare` merges no defaults into a config object, which means we need to supply it manually + messages: { + compilerMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + }, + extractorMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + "ae-undocumented": { logLevel: ExtractorLogLevel.None }, + "ae-wrong-input-file-type": { logLevel: ExtractorLogLevel.Error }, + }, + tsdocMessageReporting: { + default: { logLevel: ExtractorLogLevel.Warning }, + }, + }, }); /** API Extractor finished the analysis and reported errors. */ @@ -66,7 +84,7 @@ export const handler = command.pipe( const outPath = path.resolve(out); const entryPath = path.join(outPath, "api-entry.d.ts"); - // API Extractor analyzes one entry point, so the included declaration files are re-exported from one generated module. + // API Extractor only supports a single entry point, therefore we must shim multiple entry points into a single module const entry = include .map((file) => { const specifier = path @@ -84,7 +102,7 @@ export const handler = command.pipe( yield* fs.makeDirectory(outPath, { recursive: true }); yield* fs.writeFileString(entryPath, entry); - // Reads `<projectFolder>/tsdoc.json`, and throws when that or any configured path is invalid. + // May throw when `<projectFolder>/tsdoc.json` is invalid. const extractorConfig = yield* Effect.try(() => ExtractorConfig.prepare({ configObject: makeExtractorConfig({ From 5b0a1fe199622b28bd245d7c3cfa5db37eb45ce7 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:40:14 +0200 Subject: [PATCH 16/22] feat: generate reference pages from API analysis --- .../sdk/typescript-docs/oxlint.config.ts | 8 +- .../hashql/sdk/typescript-docs/package.json | 14 +- .../sdk/typescript-docs/scripts/extract.mts | 17 - .../sdk/typescript-docs/scripts/render.mts | 240 --------- .../sdk/typescript-docs/scripts/transform.mts | 454 ------------------ .../sdk/typescript-docs/src/Analysis.ts | 236 +++++++++ .../sdk/typescript-docs/src/Comment.test.ts | 171 +++++++ .../hashql/sdk/typescript-docs/src/Comment.ts | 308 ++++++++++++ .../hashql/sdk/typescript-docs/src/Mdx.ts | 15 + .../hashql/sdk/typescript-docs/src/Member.ts | 297 ++++++++++++ .../hashql/sdk/typescript-docs/src/Page.ts | 190 ++++++++ .../sdk/typescript-docs/src/Signature.ts | 118 +++++ .../hashql/sdk/typescript-docs/src/Site.ts | 426 ++++++++++++++++ .../sdk/typescript-docs/src/Sources.test.ts | 135 ++++++ .../hashql/sdk/typescript-docs/src/Sources.ts | 404 ++++++++++++++++ .../sdk/typescript-docs/src/Transform.ts | 116 +++++ .../sdk/typescript-docs/src/TransformError.ts | 68 +++ .../hashql/sdk/typescript-docs/src/cli.ts | 3 +- .../hashql/sdk/typescript-docs/turbo.json | 37 +- yarn.lock | 63 ++- 20 files changed, 2595 insertions(+), 725 deletions(-) delete mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts delete mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/render.mts delete mode 100644 libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Comment.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Member.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Page.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Signature.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Site.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Sources.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Transform.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index fcc1f6f3e52..e96a223ec0a 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -2,10 +2,16 @@ import { createConfig, defineConfig } from "@local/oxlint"; export default defineConfig({ extends: [ - createConfig({ runtime: "node", frameworks: ["react", "next", "effect"] }), + createConfig({ runtime: "node", frameworks: ["react", "next", "effect", "vitest"] }), ], ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], overrides: [ + { + files: ["src/cli.ts"], + rules: { + "vitest/require-hook": "allow", // The CLI entry point runs its command when imported; it is not a test file. + }, + }, { files: ["src/**/*.ts"], rules: { diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index f233c80eb2d..64cfce3611a 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -9,11 +9,14 @@ "build": "next build --webpack", "codegen": "fumadocs-mdx", "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", + "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --include .generated/declarations/main.d.ts", + "doc:declarations": "tsc --project tsconfig.api.json", + "doc:transform": "tsx src/cli.ts transform --lib ../typescript && oxfmt content/docs/reference", "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", "lint:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts", "lint:tsc": "tsc --noEmit", "start": "next start --hostname 127.0.0.1 --port ${PORT:-4398}", - "test:unit": "node --experimental-strip-types --test scripts/*.test.mts" + "test:unit": "vitest run" }, "dependencies": { "@fumadocs/satteri": "0.5.1", @@ -29,6 +32,7 @@ }, "devDependencies": { "@effect/platform-node": "4.0.0", + "@effect/vitest": "4.0.0", "@local/oxlint": "workspace:*", "@local/tsconfig": "workspace:*", "@microsoft/api-documenter": "7.30.18", @@ -45,9 +49,12 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "effect": "4.0.0", + "esrap": "2.4.0", "oxc-parser": "0.152.0", + "oxc-resolver": "11.24.2", "oxfmt": "0.71.0", "oxlint": "catalog:", + "remark-frontmatter": "5.0.0", "remark-mdx": "3.1.1", "remark-parse": "11.0.0", "remark-stringify": "11.0.0", @@ -55,6 +62,9 @@ "tailwindcss": "4.3.3", "tsx": "catalog:", "typescript": "catalog:", - "unified": "11.0.5" + "unified": "11.0.5", + "vite": "catalog:", + "vitest": "catalog:", + "yaml": "2.9.1" } } diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts deleted file mode 100644 index 5aeb49b9016..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/scripts/extract.mts +++ /dev/null @@ -1,17 +0,0 @@ -import { resolve } from "node:path"; - -import { Extractor, ExtractorConfig } from "@microsoft/api-extractor"; -import { TSDocConfigFile } from "@microsoft/tsdoc-config"; - -const root = resolve(import.meta.dirname, ".."); -const configPath = resolve(root, "api-extractor.json"); -const config = ExtractorConfig.prepare({ - configObject: ExtractorConfig.loadFile(configPath), - configObjectFullPath: configPath, - packageJsonFullPath: resolve(root, "../typescript/package.json"), - tsdocConfigFile: TSDocConfigFile.loadFile(resolve(root, "tsdoc.json")), -}); -const result = Extractor.invoke(config, { localBuild: true }); -if (!result.succeeded) { - process.exitCode = 1; -} diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts deleted file mode 100644 index d8321155ec3..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/scripts/render.mts +++ /dev/null @@ -1,240 +0,0 @@ -import { createHash } from "node:crypto"; -import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; -import path from "node:path"; - -import { ApiVariable } from "@microsoft/api-extractor-model"; - -import { - bodyOf, - callableSignatures, - declarationLinks, - inputSignatures, - introOf, - loadItems, - moduleOverview, - polishedMember, - renderIndexSummary, - renderMarkdown, - rewriteProse, -} from "./transform.mts"; - -import type { ExampleResult } from "./transform.mts"; - -const directory = import.meta.dirname; -const { resolve } = path; -const root = resolve(directory, ".."); -const input = resolve(root, "generators"); -const content = resolve(root, "app/content/docs"); -const output = resolve(content, "reference/program"); - -// oxlint-disable-next-line typescript/no-restricted-types -- Captured JSON is untrusted until every ExampleResult field is validated below. -const decodeExample = (value: unknown): ExampleResult => { - if ( - typeof value !== "object" || - value === null || - !("code" in value) || - typeof value.code !== "string" || - !("stdout" in value) || - typeof value.stdout !== "string" || - !("stderr" in value) || - typeof value.stderr !== "string" || - !("exitCode" in value) || - typeof value.exitCode !== "number" || - !("sourceSha256" in value) || - typeof value.sourceSha256 !== "string" || - !("exampleSha256" in value) || - typeof value.exampleSha256 !== "string" - ) { - throw new Error("Invalid captured example record"); - } - return { - code: value.code, - stdout: value.stdout, - stderr: value.stderr, - exitCode: value.exitCode, - sourceSha256: value.sourceSha256, - exampleSha256: value.exampleSha256, - }; -}; - -// oxlint-disable-next-line typescript/no-restricted-types -- JSON.parse has no schema; narrow the decoded container before reading its records. -const results: unknown = JSON.parse( - await readFile(resolve(directory, "examples/results.json"), "utf8"), -); -if ( - typeof results !== "object" || - results === null || - !("input" in results) || - !("adaptCallable" in results) -) { - throw new Error("Both captured examples are required"); -} -const examples = { - input: decodeExample(results.input), - adaptCallable: decodeExample(results.adaptCallable), -}; -const items = loadItems(resolve(input, "api-model/hashql.api.json")); -const symbols = new Map( - items.map((item) => [item.displayName, `#${item.displayName}`]), -); -const files = new Map<string, string>([ - ["hashql.md", "#module-overview"], - ["index.md", "/docs"], -]); -const pages = new Map<string, string>(); -const filenames = await readdir(resolve(input, "api-documenter")); -const memberFilenames = filenames - .toSorted() - .filter( - (filename) => - filename !== "index.md" && - filename !== "hashql.md" && - filename.endsWith(".md"), - ); -const sourceReads: Promise<string>[] = []; -for (const filename of memberFilenames) { - sourceReads.push( - readFile(resolve(input, "api-documenter", filename), "utf8"), - ); -} -const sources = await Promise.all(sourceReads); -for (const [index, filename] of memberFilenames.entries()) { - const source = sources[index]; - if (source === undefined) { - throw new Error(`Missing Documenter page: ${filename}`); - } - const member = items.find( - (item) => filename === `hashql.${item.displayName.toLowerCase()}.md`, - ); - const anchor = - member?.displayName ?? - filename - .slice("hashql.".length, -".md".length) - .replaceAll(/[^A-Za-z0-9-]/gu, "-"); - files.set(filename, `#${anchor}`); - pages.set(filename, source); -} -const inputs = inputSignatures(items, declarationLinks(items)); -for (const signature of inputs) { - const index = Number(signature.anchor.slice("input-".length)); - let filename = `hashql.input_${index - 1}.md`; - if (index === 1) { - filename = "hashql.input.md"; - } - files.set(filename, `#${signature.anchor}`); -} -const adapted = items.find( - (item): item is ApiVariable => - item instanceof ApiVariable && item.displayName === "adaptCallable", -); -if (adapted === undefined) { - throw new Error("adaptCallable is absent from the API model"); -} -const callSignatures = callableSignatures(adapted, declarationLinks(items)); -const preamble = `import type { Type, TypeExpression } from "@local/hashql";\nimport type * as Input from ${JSON.stringify(resolve(input, "input/dist-fresh/program/Inputs.js"))};\nimport type { Expression, Adapted, Any, Inputs, Value } from ${JSON.stringify(resolve(input, "input/dist-fresh/program/Expression.js"))};`; - -const polishedSections: Promise<string>[] = []; -for (const name of ["input", "adaptCallable"] as const) { - const source = pages.get(`hashql.${name.toLowerCase()}.md`); - if (source === undefined || source === "") { - throw new Error(`Missing Documenter page: ${name}`); - } - const example = examples[name]; - const digest = createHash("sha256").update(source).digest("hex"); - if ( - example.sourceSha256 !== digest || - example.exampleSha256 !== - createHash("sha256").update(example.code).digest("hex") - ) { - throw new Error(`Stale example capture: ${name}`); - } - let signatures = callSignatures; - if (name === "input") { - signatures = inputs; - } - polishedSections.push( - polishedMember({ - name, - source, - signatures, - preamble, - example, - files, - symbols, - }), - ); -} -const sections = await Promise.all(polishedSections); -for (const [filename, source] of pages) { - if (!/^hashql\.(?:input(?:_\d+)?|adaptcallable)\.md$/u.test(filename)) { - const anchor = files.get(filename)?.slice(1); - if (anchor === undefined || anchor === "") { - throw new Error(`Missing member anchor: ${filename}`); - } - const heading = - items.find((item) => item.displayName === anchor)?.displayName ?? - /^## (?<title>.+)\r?$/mu.exec(source)?.groups?.title?.trim() ?? - anchor; - const tree = rewriteProse(bodyOf(source), { - files, - symbols, - section: anchor, - }); - sections.push( - `## Expression.${heading} [#${anchor}]\n\n${renderMarkdown(tree)}`, - ); - } -} -const indexRows = [...new Set(items.map((item) => item.displayName))].map( - (name) => { - const source = pages.get(`hashql.${name.toLowerCase()}.md`); - let summary = ""; - if (source !== undefined && source !== "") { - const first = introOf(bodyOf(source)).children[0]; - if (first !== undefined) { - summary = renderIndexSummary(first); - } - } - return `| [\`${name}\`](#${name}) | ${summary} |`; - }, -); -const overview = moduleOverview( - resolve(input, "input/src/program/Expression.ts"), -); -const page = `--- -title: Expression -description: Symbolic HashQL values with semantic types and input requirements. ---- - -## Module overview [#module-overview] - -${overview} - -## Members [#members] - -| Member | Description | -| --- | --- | -${indexRows.join("\n")} - -${sections.join("\n")}`; -await mkdir(output, { recursive: true }); -await writeFile(resolve(output, "Expression.mdx"), page); -await writeFile( - resolve(root, "app/lib/reference-links.json"), - `${JSON.stringify(Object.fromEntries(symbols), null, 2)}\n`, -); -await writeFile( - resolve(output, "meta.json"), - `${JSON.stringify({ title: "program", pages: ["Expression"] }, null, 2)}\n`, -); -await writeFile( - resolve(content, "reference/meta.json"), - `${JSON.stringify({ title: "API reference", pages: ["program"] }, null, 2)}\n`, -); -await writeFile( - resolve(directory, "generated.json"), - `${JSON.stringify({ page: "reference/program/Expression.mdx", moduleSource: "generators/input/src/program/Expression.ts", inputOverloads: inputs.length, callableSignatures: callSignatures.length, memberSections: sections.length, sha256: createHash("sha256").update(page).digest("hex") }, null, 2)}\n`, -); -process.stdout.write( - `Generated Expression with ${inputs.length} input overloads, ${callSignatures.length} callable signatures and both captured examples.\n`, -); diff --git a/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts b/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts deleted file mode 100644 index 7832a356469..00000000000 --- a/libs/@local/hashql/sdk/typescript-docs/scripts/transform.mts +++ /dev/null @@ -1,454 +0,0 @@ -import { readFileSync } from "node:fs"; - -import { - ApiDeclaredItem, - ApiFunction, - ApiModel, -} from "@microsoft/api-extractor-model"; -import { DocCodeSpan, DocPlainText, DocSoftBreak } from "@microsoft/tsdoc"; -import { format } from "oxfmt"; -import remarkMdx from "remark-mdx"; -import remarkParse from "remark-parse"; -import remarkStringify from "remark-stringify"; -import ts from "typescript"; -import { unified } from "unified"; - -import formatOptions from "../../../../../oxfmt.config.ts"; - -import type { - ApiItem, - ApiVariable, - Excerpt, -} from "@microsoft/api-extractor-model"; -import type { DocNode } from "@microsoft/tsdoc"; -import type { Nodes, PhrasingContent, Root, RootContent } from "mdast"; - -export interface TypePart { - text: string; - href?: string; -} - -export interface ParameterView { - name: string; - optional: boolean; - type: TypePart[]; - description: string; -} - -export interface SignatureView { - anchor: string; - title: string; - code: string; - parameters: ParameterView[]; - returns: TypePart[]; -} - -export interface ExampleResult { - code: string; - stdout: string; - stderr: string; - exitCode: number; - sourceSha256: string; - exampleSha256: string; -} - -// Documenter emits plain Markdown with HTML comments, not MDX expressions. -const markdown = unified().use(remarkParse); -// Escape literal text for MDX only when serializing the rewritten prose. -const mdx = unified() - .use(remarkStringify, { fences: true, bullet: "-" }) - .use(remarkMdx); - -export const bodyOf = (source: string): Root => { - const tree = markdown.parse(source); - const heading = tree.children.findIndex((node) => node.type === "heading"); - if (heading === -1) { - throw new Error("Documenter page has no heading"); - } - return { type: "root", children: tree.children.slice(heading + 1) }; -}; - -export const nodeText = (node: Nodes): string => { - if (node.type === "html") { - return node.value.replaceAll(/<!--[\s\S]*?-->/gu, ""); - } - if ("value" in node) { - return node.value; - } - if ("children" in node) { - return node.children.map(nodeText).join(""); - } - return ""; -}; - -const plainDescription = (node: DocNode | undefined): string => { - if (node === undefined) { - return ""; - } - if (node instanceof DocPlainText) { - return node.text; - } - if (node instanceof DocCodeSpan) { - return node.code; - } - if (node instanceof DocSoftBreak) { - return " "; - } - if (node.kind !== "Section" && node.kind !== "Paragraph") { - throw new Error(`Unsupported parameter prose: ${node.kind}`); - } - return node.getChildNodes().map(plainDescription).join("").trim(); -}; - -export const loadItems = (modelPath: string): readonly ApiItem[] => { - const model = new ApiModel(); - const entry = model.loadPackage(modelPath).entryPoints[0]; - if (entry === undefined) { - throw new Error("API model has no entry point"); - } - return entry.members; -}; - -export const typeParts = ( - excerpt: Excerpt, - links: ReadonlyMap<string, string>, - options: { start?: number; end?: number } = {}, -): TypePart[] => { - const { start = 0, end = excerpt.text.length } = options; - const parts: TypePart[] = []; - let offset = 0; - for (const token of excerpt.spannedTokens) { - const next = offset + token.text.length; - if (next > start && offset < end) { - const text = token.text.slice( - Math.max(0, start - offset), - Math.min(token.text.length, end - offset), - ); - const part: TypePart = { text }; - if (token.canonicalReference !== undefined) { - const href = links.get(token.canonicalReference.toString()); - if (href !== undefined && href !== "") { - part.href = href; - } - } - parts.push(part); - } - offset = next; - } - return parts; -}; - -export const inputSignatures = ( - items: readonly ApiItem[], - links: ReadonlyMap<string, string>, -): SignatureView[] => { - const functions = items.filter( - (item): item is ApiFunction => - item instanceof ApiFunction && item.displayName === "input", - ); - const documented = functions.find((item) => item.tsdocComment !== undefined); - return functions.map((item) => ({ - anchor: `input-${item.overloadIndex}`, - title: `Overload ${item.overloadIndex}`, - code: item.excerpt.text, - parameters: item.parameters.map((parameter) => ({ - name: parameter.name, - optional: parameter.isOptional, - type: typeParts(parameter.parameterTypeExcerpt, links), - description: plainDescription( - parameter.tsdocParamBlock?.content ?? - documented?.parameters.find( - (candidate) => candidate.name === parameter.name, - )?.tsdocParamBlock?.content, - ), - })), - returns: typeParts(item.returnTypeExcerpt, links), - })); -}; - -export const callableSignatures = ( - item: ApiVariable, - links: ReadonlyMap<string, string>, -): SignatureView[] => { - // The API model retains a callable variable as one excerpt. Parse its syntax without invoking a checker or replacing its types. - const prefix = "declare const "; - const source = ts.createSourceFile( - "callable.d.ts", - `${prefix}${item.excerpt.text};`, - ts.ScriptTarget.Latest, - true, - ); - const statement = source.statements[0]; - if (statement === undefined || !ts.isVariableStatement(statement)) { - throw new Error("Expected a callable variable declaration"); - } - const type = statement.declarationList.declarations[0]?.type; - if (type === undefined || !ts.isTypeLiteralNode(type)) { - throw new Error("Expected an object of call signatures"); - } - const members = type.members; - return members.map((member, index) => { - if (!ts.isCallSignatureDeclaration(member) || member.type === undefined) { - throw new Error("Expected a call signature with an explicit return type"); - } - return { - anchor: `${item.displayName}-${index + 1}`, - title: `Call signature ${index + 1}`, - code: member.getText(source), - parameters: member.parameters.map((parameter) => { - if (parameter.type === undefined || !ts.isIdentifier(parameter.name)) { - throw new Error("Expected a named parameter with an explicit type"); - } - return { - name: parameter.name.text, - optional: parameter.questionToken !== undefined, - type: typeParts(item.excerpt, links, { - start: parameter.type.getStart(source) - prefix.length, - end: parameter.type.end - prefix.length, - }), - description: "", - }; - }), - returns: typeParts(item.excerpt, links, { - start: member.type.getStart(source) - prefix.length, - end: member.type.end - prefix.length, - }), - }; - }); -}; - -export const rewriteProse = ( - tree: Root, - options: { - files: ReadonlyMap<string, string>; - symbols: ReadonlyMap<string, string>; - section: string; - }, -): Root => { - const { files, symbols, section } = options; - const maximumHeadingDepth = 6; - let headingIndex = 0; - const linkInlineCode = (children: PhrasingContent[]): void => { - for (const [index, child] of children.entries()) { - if (child.type === "inlineCode") { - const name = - /^(?:Expression\.)?(?<name>[A-Za-z_$][\w$]*)(?=[(<]|$)/u.exec( - child.value, - )?.groups?.name; - if (name !== undefined && name !== "") { - const destination = symbols.get(name); - if (destination !== undefined && destination !== "") { - children[index] = { - type: "link", - url: destination, - children: [child], - }; - } - } - } - } - }; - const visit = (node: Nodes, insideLink: boolean): void => { - if (node.type === "link") { - const destination = files.get(node.url.replace(/^\.\//u, "")); - if (destination !== undefined && destination !== "") { - node.url = destination; - } else if (node.url.endsWith(".md")) { - node.url = `../../../api-documenter/${node.url.replace(/^\.\//u, "")}`; - } - } - if (node.type === "heading") { - headingIndex += 1; - if (node.depth !== maximumHeadingDepth) { - node.depth += 1; - } - node.children.push({ - type: "text", - value: ` [#${section}-detail-${headingIndex}]`, - }); - } - if (node.type === "html") { - node.value = node.value - .replaceAll(/<!--[\s\S]*?-->/gu, "") - .replaceAll(/<\/?caption>/gu, ""); - } - const withinLink = - insideLink || node.type === "link" || node.type === "linkReference"; - // Only these mdast parents accept phrasing children; block/container arrays are never rewritten. - if ( - !withinLink && - (node.type === "paragraph" || - node.type === "heading" || - node.type === "emphasis" || - node.type === "strong" || - node.type === "delete" || - node.type === "tableCell") - ) { - linkInlineCode(node.children); - } - if ("children" in node) { - for (const child of node.children) { - visit(child, withinLink); - } - } - }; - visit(tree, false); - return tree; -}; - -export const renderMarkdown = (tree: Root): string => mdx.stringify(tree); - -export const renderIndexSummary = (node: Nodes): string => - renderMarkdown({ - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: nodeText(node).replaceAll("\n", " ") }, - ], - }, - ], - }) - .trimEnd() - .replaceAll("|", String.raw`\|`); - -export const introOf = (tree: Root): Root => { - const boundary = tree.children.findIndex( - (node) => node.type === "heading" || nodeText(node) === "Signature:", - ); - let children = tree.children; - if (boundary !== -1) { - children = tree.children.slice(0, boundary); - } - return { type: "root", children }; -}; - -const returnProse = (tree: Root): Root => { - const marker = tree.children.findIndex( - (node) => nodeText(node) === "Returns:", - ); - if (marker === -1) { - return { type: "root", children: [] }; - } - const children: RootContent[] = []; - // The first paragraph is Documenter's rendered return type; types come from model excerpts instead. - for (const node of tree.children.slice(marker + 2)) { - if (node.type === "heading") { - break; - } - children.push(node); - } - return { type: "root", children }; -}; - -export const signatureBlock = async ( - signature: SignatureView, - options: { preamble: string; callable: boolean; name: string }, -): Promise<string> => { - let before = options.preamble; - let after = ""; - if (options.callable) { - before = `${options.preamble}\ninterface CallSignature {`; - after = "\n// ---cut-after---\n}"; - } - const formatted = await format( - "signature.ts", - `${before}\n// ---cut---\n${signature.code}${after}`, - formatOptions, - ); - if (formatted.errors.length > 0) { - throw new Error( - `Cannot format ${signature.anchor}: ${JSON.stringify(formatted.errors)}`, - ); - } - return `\`\`\`ts twoslash reference title="Expression.${options.name}"\n${formatted.code.trimEnd()}\n\`\`\``; -}; - -export const polishedMember = async (options: { - name: string; - source: string; - signatures: readonly SignatureView[]; - preamble: string; - example: ExampleResult; - files: ReadonlyMap<string, string>; - symbols: ReadonlyMap<string, string>; -}): Promise<string> => { - const { name, source, signatures, preamble, example, files, symbols } = - options; - if (example.exitCode !== 0 || example.stdout.trim() === "") { - throw new Error(`Missing successful captured output for ${name}`); - } - const original = bodyOf(source); - const prose = (tree: Root): string => - renderMarkdown(rewriteProse(tree, { files, symbols, section: name })); - const returnDescription = nodeText(returnProse(original)).trim(); - const sectionBlocks = await Promise.all( - signatures.map( - async (signature) => `### ${signature.title} [#${signature.anchor}] - -${await signatureBlock(signature, { preamble, callable: name === "adaptCallable", name })} - -<ReferenceSignature id=${JSON.stringify(`${signature.anchor}-params`)} parameters={${JSON.stringify(signature.parameters)}} returns={${JSON.stringify(signature.returns)}} returnDescription={${JSON.stringify(returnDescription)}} /> -`, - ), - ); - const sections = sectionBlocks.join("\n"); - const caption = original.children.find( - (node) => node.type === "html" && node.value.includes("<caption>"), - ); - let captionText = ""; - if (caption?.type === "html") { - captionText = caption.value.replaceAll(/<\/?caption>/gu, "").trim(); - } - return `## Expression.${name} [#${name}] - -${prose(introOf(original))} -${sections} -### Example [#${name}-example] - -${captionText} - -\`\`\`ts twoslash -${example.code.trimEnd()} -\`\`\` - -#### Output [#${name}-output] - -\`\`\`text -${example.stdout.trimEnd()} -\`\`\` -`; -}; - -export const moduleOverview = (sourcePath: string): string => { - const source = readFileSync(sourcePath, "utf8"); - const comment = ts.getLeadingCommentRanges(source, 0)?.[0]; - if (comment === undefined || !source.startsWith("/**")) { - throw new Error("Module overview comment is missing"); - } - const openingCommentLength = "/**".length; - const closingCommentLength = "*/".length; - return source - .slice( - comment.pos + openingCommentLength, - comment.end - closingCommentLength, - ) - .split("\n") - .map((line) => line.replace(/^\s*\* ?/u, "")) - .filter((line) => line.trim() !== "@module") - .join("\n") - .trim(); -}; - -export const declarationLinks = ( - items: readonly ApiItem[], -): Map<string, string> => - new Map( - items - .filter((item) => item instanceof ApiDeclaredItem) - .map((item) => [ - item.canonicalReference.toString(), - `#${item.displayName}`, - ]), - ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts new file mode 100644 index 00000000000..fcbdb0966b1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts @@ -0,0 +1,236 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem and Path are unstable +import { ApiDeclaredItem, ApiModel } from "@microsoft/api-extractor-model"; +import { TSDocConfiguration, TSDocParser } from "@microsoft/tsdoc"; +import { TSDocConfigFile } from "@microsoft/tsdoc-config"; +import { + Array, + Cache, + Context, + Effect, + FileSystem, + Layer, + Option, + Path, + Schema, + pipe, +} from "effect"; + +import { Sources } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { + ApiEntryPoint, + ApiItem, + ApiPackage, +} from "@microsoft/api-extractor-model"; +import type { DocComment } from "@microsoft/tsdoc"; + +/** The part of a declaration map that names the source TypeScript emitted the file from. */ +const DeclarationMap = Schema.fromJsonString( + Schema.Struct({ + sources: Schema.NonEmptyArray(Schema.String), + sourceRoot: Schema.optionalKey(Schema.String), + }), +); + +// TypeScript's declaration emit renames each source extension this way. +const declarationExtensions: readonly (readonly [string, string])[] = [ + [".d.ts", ".d.ts"], + [".mts", ".d.mts"], + [".cts", ".d.cts"], + [".tsx", ".d.ts"], + [".ts", ".d.ts"], +]; + +/** The output of the `analyze` command, with what the pages need to find their way back to the sources. */ +export class Analysis extends Context.Service< + Analysis, + { + readonly package: ApiPackage; + readonly entry: ApiEntryPoint; + /** The source modules of the declaration files the analysis entry re-exports, in order. */ + readonly roots: Array.NonEmptyReadonlyArray<string>; + /** The source file that declares an item. */ + readonly sourceOf: (item: ApiItem) => Option.Option<string>; + /** The declaration file emitted from a source module. */ + readonly declarationOf: ( + source: string, + ) => Effect.Effect<string, TransformError>; + /** Parses a module's first JSDoc comment that carries `@module`, with the TSDoc configuration the analysis used. */ + readonly moduleComment: ( + source: string, + ) => Effect.Effect<Option.Option<DocComment>, TransformError>; + } +>()("@local/hashql-typescript-docs/Analysis") {} + +export interface Options { + /** The analyzed package's folder, which the model's file paths are relative to. */ + readonly lib: string; + /** The directory `analyze` wrote. */ + readonly analysis: string; +} + +const loadEntry = Effect.fnUntraced(function* (file: string) { + const apiPackage = yield* Effect.try({ + try: () => new ApiModel().loadPackage(file), + catch: (cause) => TransformError.malformedAnalysis(String(cause)), + }); + + const entry = yield* Effect.fromOption( + Array.head(apiPackage.entryPoints), + ).pipe( + Effect.mapError(() => + TransformError.malformedAnalysis("The API model has no entry point"), + ), + ); + + return { apiPackage, entry }; +}); + +// API Extractor reads `<projectFolder>/tsdoc.json`, so comments outside the model parse with the same tags. +const loadParser = Effect.fnUntraced(function* (lib: string) { + const configFile = TSDocConfigFile.loadForFolder(lib); + + if (configFile.hasErrors) { + return yield* TransformError.malformedAnalysis( + configFile.getErrorSummary(), + ); + } + + const configuration = new TSDocConfiguration(); + configFile.configureParser(configuration); + + return new TSDocParser(configuration); +}); + +const sourceOfDeclaration = Effect.fnUntraced(function* (declaration: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const mapPath = `${declaration}.map`; + const text = yield* fs + .readFileString(mapPath) + .pipe(Effect.mapError(TransformError.fileSystem)); + const map = yield* Schema.decodeEffect(DeclarationMap)(text).pipe( + Effect.mapError((cause) => + TransformError.malformedSourceMap(mapPath, cause), + ), + ); + + return path.resolve( + path.dirname(mapPath), + map.sourceRoot ?? "", + map.sources[0], + ); +}); + +// `analyze` writes one `export * from` for each declaration file it receives, and each file's map names its source. +const loadRoots = Effect.fnUntraced(function* (entryFile: string) { + const sources = yield* Sources; + const declarations = yield* pipe( + (yield* sources.scope(entryFile)).wildcards, + Effect.forEach((specifier) => + Effect.fromOption(sources.resolve(entryFile, specifier)).pipe( + Effect.mapError(() => + TransformError.malformedAnalysis( + `${entryFile} re-exports ${specifier}, which does not exist`, + ), + ), + ), + ), + ); + + if (!Array.isReadonlyArrayNonEmpty(declarations)) { + return yield* TransformError.malformedAnalysis( + `${entryFile} re-exports no declaration file`, + ); + } + + return { + declaration: Array.headNonEmpty(declarations), + sources: yield* pipe(declarations, Effect.forEach(sourceOfDeclaration)), + }; +}); + +export const layer = ({ + lib, + analysis, +}: Options): Layer.Layer< + Analysis, + TransformError, + FileSystem.FileSystem | Path.Path | Sources +> => + Layer.effect( + Analysis, + Effect.gen(function* () { + const path = yield* Path.Path; + const sources = yield* Sources; + const services = yield* Effect.context< + FileSystem.FileSystem | Path.Path + >(); + + const { apiPackage, entry } = yield* loadEntry( + path.join(analysis, "api.json"), + ); + const parser = yield* loadParser(lib); + const roots = yield* loadRoots(path.join(analysis, "api-entry.d.ts")); + const rootSource = Array.headNonEmpty(roots.sources); + + // The emit mirrors the source tree, so the first root locates every other declaration file, and each one's map confirms it. + const declarations = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: Effect.fnUntraced(function* (source: string) { + const relative = path.relative(path.dirname(rootSource), source); + const [extension, emitted] = Array.findFirst( + declarationExtensions, + ([candidate]) => relative.endsWith(candidate), + ).pipe(Option.getOrElse(() => ["", ".d.ts"] as const)); + const declaration = path.join( + path.dirname(roots.declaration), + `${relative.slice(0, relative.length - extension.length)}${emitted}`, + ); + + if ((yield* sourceOfDeclaration(declaration)) !== source) { + return yield* TransformError.malformedAnalysis( + `${declaration} was not emitted from ${source}`, + ); + } + + return declaration; + }, Effect.provide(services)), + }); + + return Analysis.of({ + package: apiPackage, + entry, + roots: roots.sources, + sourceOf: (item) => { + if (item instanceof ApiDeclaredItem) { + return Option.fromNullishOr(item.fileUrlPath).pipe( + Option.map((file) => path.resolve(lib, file)), + ); + } + + return Option.none(); + }, + declarationOf: (source) => Cache.get(declarations, source), + moduleComment: (source) => + sources.scope(source).pipe( + Effect.map(({ comments, text }) => + Array.findFirst(comments, (comment) => + pipe( + Option.some(comment), + Option.filter(({ value }) => value.startsWith("*")), + Option.map( + ({ start, end }) => + parser.parseString(text.slice(start, end)).docComment, + ), + Option.filter((parsed) => + parsed.modifierTagSet.hasTagName("@module"), + ), + ), + ), + ), + ), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts new file mode 100644 index 00000000000..a71c5b08f67 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts @@ -0,0 +1,171 @@ +import { + StandardTags, + TSDocConfiguration, + TSDocParser, + TSDocTagDefinition, + TSDocTagSyntaxKind, +} from "@microsoft/tsdoc"; +import { Array, Effect, Option, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as Comment from "./Comment.js"; + +import type { TransformError } from "./TransformError.js"; +import type { DocBlock, DocComment } from "@microsoft/tsdoc"; + +// The SDK's `tsdoc.json` defines `@since`, and the analysis parses with it. +const configuration = (): TSDocConfiguration => { + const result = new TSDocConfiguration(); + result.addTagDefinition( + new TSDocTagDefinition({ + tagName: "@since", + syntaxKind: TSDocTagSyntaxKind.BlockTag, + }), + ); + + return result; +}; + +const parse = (lines: readonly string[]): DocComment => + new TSDocParser(configuration()).parseString( + pipe( + ["/**", ...lines.map((line) => ` * ${line}`), " */"], + Array.join("\n"), + ), + ).docComment; + +const firstExample = (lines: readonly string[]): DocBlock => + pipe( + Comment.blocksTagged(parse(lines), StandardTags.example.tagName), + Array.head, + Effect.fromOption, + Effect.orDie, + Effect.runSync, + ); + +// Only `Known` names something on a page. +const convert = <A>( + effect: Effect.Effect<A, TransformError, Comment.Links>, +): A => + effect.pipe( + Effect.provideService( + Comment.Links, + Comment.Links.of({ + resolve: (reference) => + Effect.succeed( + Option.liftPredicate( + "/docs/known", + () => reference.emitAsTsdoc() === "Known", + ), + ), + }), + ), + Effect.orDie, + Effect.runSync, + ); + +describe("comment", () => { + test("summary_links", () => { + expect.hasAssertions(); + const blocks = convert( + Comment.section( + parse(["See {@link Known}, {@link Unknown} and {@link Known | this}."]) + .summarySection, + ), + ); + + expect(blocks).toStrictEqual([ + { + type: "paragraph", + children: [ + { type: "text", value: "See " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: ", " }, + { type: "inlineCode", value: "Unknown" }, + { type: "text", value: " and " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "text", value: "this" }], + }, + { type: "text", value: "." }, + ], + }, + ]); + }); + + test("summary_unparsed_syntax", () => { + expect.hasAssertions(); + const blocks = convert( + Comment.section( + parse(["Accepts {a: 1} and links {@link type}."]).summarySection, + ), + ); + + expect(blocks).toStrictEqual([ + { + type: "paragraph", + children: [ + { type: "text", value: "Accepts " }, + { type: "text", value: "{" }, + { type: "text", value: "a: 1" }, + { type: "text", value: "}" }, + { type: "text", value: " and links " }, + { type: "inlineCode", value: "type" }, + { type: "text", value: "." }, + ], + }, + ]); + }); + + test("example_caption", () => { + expect.hasAssertions(); + const example = firstExample([ + "Summary.", + "", + "@example <caption>Build a {@link Known}.</caption>", + "```ts", + "const value = 1;", + "```", + ]); + + expect(convert(Comment.example(example))).toStrictEqual({ + caption: [ + { type: "text", value: "Build a " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: "." }, + ], + content: [{ type: "code", lang: "ts", value: "const value = 1;" }], + }); + }); + + test("example_without_caption", () => { + expect.hasAssertions(); + const example = firstExample(["@example", "```", "plain", "```"]); + + expect(convert(Comment.example(example))).toStrictEqual({ + caption: [], + content: [{ type: "code", lang: null, value: "plain" }], + }); + }); + + test("words", () => { + expect.hasAssertions(); + + expect( + pipe( + Comment.blocksTagged(parse(["@since `4.0.0` beta"]), "@since"), + Array.head, + Option.map(({ content }) => Comment.words(content)), + ), + ).toStrictEqual(Option.some("4.0.0 beta")); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts new file mode 100644 index 00000000000..71742bc7ae4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts @@ -0,0 +1,308 @@ +import { + DocCodeSpan, + DocErrorText, + DocEscapedText, + DocFencedCode, + DocHtmlEndTag, + DocHtmlStartTag, + DocInlineTag, + DocLinkTag, + DocNodeTransforms, + DocParagraph, + DocPlainText, + DocSoftBreak, + StandardTags, +} from "@microsoft/tsdoc"; +import { + Array, + Context, + Effect, + Filter, + Function, + Match, + Option, + String, + pipe, +} from "effect"; + +import { TransformError } from "./TransformError.js"; + +import type { + DocBlock, + DocComment, + DocDeclarationReference, + DocNode, + DocSection, +} from "@microsoft/tsdoc"; +import type { BlockContent, PhrasingContent } from "mdast"; + +/** Resolves declaration references in the comment under conversion, as its own module sees them. */ +export class Links extends Context.Service< + Links, + { + /** The URL of what a reference names, `None` when it names nothing on a page. */ + readonly resolve: ( + reference: DocDeclarationReference, + ) => Effect.Effect<Option.Option<string>>; + } +>()("@local/hashql-typescript-docs/Comment/Links") {} + +/** An `@example` block split at its `<caption>`. The caption is empty when the block opens without one. */ +export interface Example { + readonly caption: readonly PhrasingContent[]; + readonly content: readonly BlockContent[]; +} + +const linkTagNames: ReadonlySet<string> = new Set([ + StandardTags.link.tagName, + "@linkcode", + "@linkplain", +]); + +// TSDoc parses a link whose reference it cannot read as a generic inline tag. +const isUnparsedLink = (node: DocNode): node is DocInlineTag => + node instanceof DocInlineTag && linkTagNames.has(node.tagName); + +const text = (value: string): PhrasingContent => ({ type: "text", value }); + +const inlineCode = (value: string): PhrasingContent => ({ + type: "inlineCode", + value, +}); + +const linkLabel = (tag: DocLinkTag): PhrasingContent => { + if (tag.linkText !== undefined) { + return text(tag.linkText); + } + + return inlineCode( + tag.codeDestination?.emitAsTsdoc() ?? tag.urlDestination ?? "", + ); +}; + +const destination = Effect.fnUntraced(function* (tag: DocLinkTag) { + if (tag.urlDestination !== undefined) { + return Option.some(tag.urlDestination); + } + + if (tag.codeDestination !== undefined) { + return yield* (yield* Links).resolve(tag.codeDestination); + } + + return Option.none<string>(); +}); + +const link = (tag: DocLinkTag): Effect.Effect<PhrasingContent, never, Links> => + destination(tag).pipe( + Effect.map( + Option.match({ + onNone: () => linkLabel(tag), + onSome: (url): PhrasingContent => ({ + type: "link", + url, + children: [linkLabel(tag)], + }), + }), + ), + ); + +// TSDoc keeps the characters it could not parse as error text, and the analysis reports each at its source line. +const phrasing = ( + node: DocNode, +): Effect.Effect<PhrasingContent, TransformError, Links> => + Match.value(node).pipe( + Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => + Effect.succeed(text(value)), + ), + Match.when(Match.instanceOf(DocSoftBreak), () => Effect.succeed(text(" "))), + Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => + Effect.succeed(inlineCode(code)), + ), + Match.when(Match.instanceOf(DocEscapedText), ({ decodedText }) => + Effect.succeed(text(decodedText)), + ), + Match.when(Match.instanceOf(DocErrorText), ({ text: value }) => + Effect.succeed(text(value)), + ), + Match.when(Match.instanceOf(DocLinkTag), link), + Match.when(isUnparsedLink, ({ tagContent }) => + Effect.succeed(inlineCode(tagContent.trim())), + ), + Match.orElse(({ kind }) => + Effect.fail(TransformError.unsupportedComment(kind)), + ), + ); + +/** Converts a TSDoc paragraph to mdast phrasing content, with its spacing collapsed. */ +export const paragraph = ( + node: DocParagraph, +): Effect.Effect<PhrasingContent[], TransformError, Links> => + pipe( + DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(), + Effect.forEach(phrasing), + ); + +const block = ( + node: DocNode, +): Effect.Effect<BlockContent[], TransformError, Links> => + Match.value(node).pipe( + Match.when(Match.instanceOf(DocParagraph), (child) => + paragraph(child).pipe( + Effect.map((children): BlockContent[] => { + if (Array.isReadonlyArrayNonEmpty(children)) { + return [{ type: "paragraph", children }]; + } + + return []; + }), + ), + ), + Match.when(Match.instanceOf(DocFencedCode), ({ language, code }) => + Effect.succeed<BlockContent[]>([ + { + type: "code", + lang: Option.getOrNull( + Option.liftPredicate(language, String.isNonEmpty), + ), + value: code.trimEnd(), + }, + ]), + ), + Match.orElse(({ kind }) => + Effect.fail(TransformError.unsupportedComment(kind)), + ), + ); + +/** Converts block-level TSDoc nodes to mdast blocks. */ +export const blocks = ( + nodes: Iterable<DocNode>, +): Effect.Effect<BlockContent[], TransformError, Links> => + pipe(nodes, Effect.forEach(block), Effect.map(Array.flatten)); + +/** Converts a TSDoc section to mdast blocks. */ +export const section = ( + node: DocSection, +): Effect.Effect<BlockContent[], TransformError, Links> => + blocks(node.getChildNodes()); + +/** A comment's summary and remarks, the prose that introduces what it documents. */ +export const overview = ( + comment: DocComment, +): Effect.Effect<BlockContent[], TransformError, Links> => + Effect.all([ + section(comment.summarySection), + blocks(Array.fromNullishOr(comment.remarksBlock?.content)), + ]).pipe(Effect.map(Array.flatten)); + +/** The first paragraph of a comment's summary, which stands for it in a list. */ +export const lead = ( + comment: DocComment, +): Effect.Effect<PhrasingContent[], TransformError, Links> => + pipe( + Array.head(comment.summarySection.getChildNodes()), + Option.filter((node) => node instanceof DocParagraph), + Option.match({ + onNone: () => Effect.succeed([]), + onSome: paragraph, + }), + ); + +/** The custom blocks of a comment that carry one tag, in source order. */ +export const blocksTagged: { + (tagName: string): (comment: DocComment) => readonly DocBlock[]; + (comment: DocComment, tagName: string): readonly DocBlock[]; +} = Function.dual( + 2, + (comment: DocComment, tagName: string): readonly DocBlock[] => + comment.customBlocks.filter( + ({ blockTag }) => blockTag.tagNameWithUpperCase === tagName.toUpperCase(), + ), +); + +/** The words of a section, for tags whose value is a name or a version rather than prose. */ +export const words = (node: DocSection): string => + pipe( + node.getChildNodes(), + Array.filterMap(Filter.instanceOf(DocParagraph)), + Array.flatMap((paragraph_) => + DocNodeTransforms.trimSpacesInParagraph(paragraph_).getChildNodes(), + ), + Array.map((child) => + Match.value(child).pipe( + Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => value), + Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => code), + Match.orElse(() => " "), + ), + ), + Array.join(""), + String.trim, + ); + +// The space after a block tag and the line breaks before its content parse as text of their own. +const isBlank = (node: DocNode): boolean => + node instanceof DocSoftBreak || + (node instanceof DocPlainText && node.text.trim() === ""); + +const paragraphOf = ( + configuration: DocParagraph["configuration"], + nodes: readonly DocNode[], +): DocParagraph => { + const result = new DocParagraph({ configuration }); + result.appendNodes(nodes); + + return result; +}; + +const isCaption = + (tag: typeof DocHtmlStartTag | typeof DocHtmlEndTag) => + (node: DocNode): boolean => + node instanceof tag && node.name === "caption"; + +const isParagraph = (node: DocNode | undefined): node is DocParagraph => + node instanceof DocParagraph; + +// JSDoc's `<caption>` opens the first paragraph of an example. Everything after the caption is ordinary content. +export const example = ( + example_: DocBlock, +): Effect.Effect<Example, TransformError, Links> => { + const [first, ...rest] = example_.content.getChildNodes(); + const caption = pipe( + Option.liftPredicate(first, isParagraph), + Option.flatMap((opening) => { + const nodes = opening.getChildNodes(); + + return Option.all({ + start: pipe( + nodes, + Array.findFirstIndex((node) => !isBlank(node)), + Option.filter((index) => + Array.get(nodes, index).pipe( + Option.exists(isCaption(DocHtmlStartTag)), + ), + ), + ), + end: pipe(nodes, Array.findFirstIndex(isCaption(DocHtmlEndTag))), + }).pipe( + Option.map(({ start, end }) => ({ + title: paragraphOf( + opening.configuration, + nodes.slice(start + 1, end), + ), + remainder: paragraphOf(opening.configuration, nodes.slice(end + 1)), + })), + ); + }), + ); + + return Option.match(caption, { + onNone: () => + section(example_.content).pipe( + Effect.map((content): Example => ({ caption: [], content })), + ), + onSome: ({ title, remainder }) => + Effect.all({ + caption: paragraph(title), + content: blocks([remainder, ...rest]), + }), + }); +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts new file mode 100644 index 00000000000..4023ff1027d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts @@ -0,0 +1,15 @@ +import remarkFrontmatter from "remark-frontmatter"; +import remarkMdx from "remark-mdx"; +import remarkStringify from "remark-stringify"; +import { unified } from "unified"; + +import type { Root } from "mdast"; + +// remark-mdx escapes the characters MDX would read as JSX or expressions. +const processor = unified() + .use(remarkStringify, { bullet: "-", fences: true }) + .use(remarkFrontmatter) + .use(remarkMdx); + +/** Serializes a page's mdast, frontmatter included, as MDX. */ +export const stringify = (tree: Root): string => processor.stringify(tree); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Member.ts b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts new file mode 100644 index 00000000000..bb450552a99 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts @@ -0,0 +1,297 @@ +import { ApiDocumentedItem, ApiItemKind } from "@microsoft/api-extractor-model"; +import { StandardTags } from "@microsoft/tsdoc"; +import { Array, Effect, Filter, Option, String, identity, pipe } from "effect"; + +import * as Comment from "./Comment.js"; + +import type { TransformError } from "./TransformError.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { + DocBlock, + DocComment, + DocParamCollection, + DocSection, +} from "@microsoft/tsdoc"; +import type { BlockContent, Heading, ListItem, PhrasingContent } from "mdast"; + +/** The declarations sharing one name in a container, with their source. */ +export interface Member { + /** Overloads in declaration order, or a merged interface and namespace. */ + readonly items: Array.NonEmptyReadonlyArray<ApiItem>; + /** The statements declaring the member, as TypeScript. */ + readonly signature: string; + /** The anchor that links to an item on its page. */ + readonly anchor: (item: ApiItem) => string; +} + +const memberDepth: Heading["depth"] = 3; +const nestedDepth: Heading["depth"] = 4; + +const strong = (value: string): PhrasingContent => ({ + type: "strong", + children: [{ type: "text", value }], +}); + +const heading = (depth: Heading["depth"], anchor: string): BlockContent => ({ + type: "heading", + depth, + children: [{ type: "text", value: `${anchor} [#${anchor}]` }], +}); + +// A label opens the first paragraph of the content it introduces, or stands alone before a code block. +const labelled = ( + label: PhrasingContent, + content: readonly BlockContent[], +): BlockContent[] => { + const [first, ...rest] = content; + + if (first?.type === "paragraph") { + return [ + { + type: "paragraph", + children: [label, { type: "text", value: " " }, ...first.children], + }, + ...rest, + ]; + } + + return [{ type: "paragraph", children: [label] }, ...content]; +}; + +const commentOf = (item: ApiItem): Option.Option<DocComment> => { + if (item instanceof ApiDocumentedItem) { + return Option.fromNullishOr(item.tsdocComment); + } + + return Option.none(); +}; + +const comments = (items: readonly ApiItem[]): DocComment[] => + Array.filterMap(items, Filter.fromPredicateOption(commentOf)); + +const kindLabels: readonly (readonly [ApiItemKind, string])[] = [ + [ApiItemKind.Function, "Functions"], + [ApiItemKind.Variable, "Variables"], + [ApiItemKind.Class, "Classes"], + [ApiItemKind.Interface, "Interfaces"], + [ApiItemKind.TypeAlias, "Type aliases"], + [ApiItemKind.Enum, "Enumerations"], + [ApiItemKind.Namespace, "Namespaces"], +]; + +/** The heading that lists a member, which is its authored `@category` or else its kind. */ +export const group = (items: Array.NonEmptyReadonlyArray<ApiItem>): string => + pipe( + comments(items), + Array.findFirst((comment) => + Array.head(Comment.blocksTagged(comment, "@category")), + ), + Option.map((block) => Comment.words(block.content)), + Option.orElse(() => + Array.findFirst( + kindLabels, + ([kind]) => kind === Array.headNonEmpty(items).kind, + ).pipe(Option.map(([, label]) => label)), + ), + Option.getOrElse(() => "Other"), + ); + +/** Orders group headings: authored categories alphabetically, then kinds in a fixed order. */ +export const groupOrder = (labels: Iterable<string>): string[] => { + const present = Array.dedupe(labels); + const kinds = pipe( + kindLabels, + Array.map(([, label]) => label), + ); + + return [ + ...pipe( + present, + Array.filter((label) => !kinds.includes(label)), + Array.sortWith(identity, String.Order), + ), + ...pipe( + kinds, + Array.filter((label) => present.includes(label)), + ), + ]; +}; + +// Stability, version and internal status, each only where the comment states it. +const markers = (comment: DocComment): BlockContent[] => { + const tagged = ( + tagName: string, + label: string, + ): Option.Option<PhrasingContent[]> => + pipe( + Comment.blocksTagged(comment, tagName), + Array.head, + Option.map((block) => [ + strong(label), + { type: "text", value: ` ${Comment.words(block.content)}` }, + ]), + ); + + return pipe( + Array.getSomes([ + tagged("@stability", "Stability"), + tagged("@since", "Since"), + Option.liftPredicate([strong("Internal")], () => + comment.modifierTagSet.isInternal(), + ), + ]), + Array.match({ + onEmpty: () => [], + onNonEmpty: (facts) => [ + { + type: "paragraph", + children: pipe( + facts, + Array.intersperse<PhrasingContent[]>([ + { type: "text", value: " · " }, + ]), + Array.flatten, + ), + }, + ], + }), + ); +}; + +const parameters = ( + label: string, + collection: DocParamCollection, +): Effect.Effect<BlockContent[], TransformError, Comment.Links> => + pipe( + collection.blocks, + Effect.forEach((block) => + Comment.section(block.content).pipe( + Effect.map( + (content): ListItem => ({ + type: "listItem", + spread: false, + children: labelled( + { type: "inlineCode", value: block.parameterName }, + content, + ), + }), + ), + ), + ), + Effect.map( + Array.match({ + onEmpty: (): BlockContent[] => [], + onNonEmpty: (items): BlockContent[] => [ + { type: "paragraph", children: [strong(label)] }, + { type: "list", ordered: false, spread: false, children: [...items] }, + ], + }), + ), + ); + +const labelledSections = ( + label: string, + sections: readonly DocSection[], +): Effect.Effect<BlockContent[], TransformError, Comment.Links> => + pipe( + sections, + Effect.forEach((content) => + Comment.section(content).pipe( + Effect.map((blocks) => labelled(strong(label), blocks)), + ), + ), + Effect.map(Array.flatten), + ); + +const exampleBlocks = ({ + caption, + content, +}: Comment.Example): BlockContent[] => { + const label = Array.match(caption, { + onEmpty: (): PhrasingContent[] => [strong("Example")], + onNonEmpty: (phrasing): PhrasingContent[] => [ + strong("Example"), + { type: "text", value: " (" }, + ...phrasing, + { type: "text", value: ")" }, + ], + }); + + return [{ type: "paragraph", children: label }, ...content]; +}; + +const contentOf = (block: DocBlock | undefined): DocSection[] => + Array.fromNullishOr(block?.content); + +const documentation = ( + comment: DocComment, +): Effect.Effect<BlockContent[], TransformError, Comment.Links> => + Effect.all([ + labelledSections("Deprecated", contentOf(comment.deprecatedBlock)), + Effect.succeed(markers(comment)), + Comment.overview(comment), + parameters("Type parameters", comment.typeParams), + parameters("Parameters", comment.params), + labelledSections("Returns", contentOf(comment.returnsBlock)), + labelledSections( + "Throws", + pipe( + Comment.blocksTagged(comment, StandardTags.throws.tagName), + Array.map(({ content }) => content), + ), + ), + labelledSections( + "See", + pipe( + comment.seeBlocks, + Array.map(({ content }) => content), + ), + ), + pipe( + Comment.blocksTagged(comment, StandardTags.example.tagName), + Effect.forEach(Comment.example), + Effect.map(Array.flatMap(exampleBlocks)), + ), + ]).pipe(Effect.map(Array.flatten)); + +const descendants = (items: readonly ApiItem[]): ApiItem[] => + pipe( + items, + Array.flatMap((item) => [item, ...descendants(item.members)]), + ); + +/** Renders a member as its heading and declarations, followed by the documentation of each declaration and of every documented nested member. */ +export const render = ({ + items, + signature, + anchor, +}: Member): Effect.Effect<BlockContent[], TransformError, Comment.Links> => + Effect.all([ + Effect.succeed<BlockContent[]>([ + heading(memberDepth, anchor(Array.headNonEmpty(items))), + { type: "code", lang: "ts", value: signature }, + ]), + pipe( + comments(items), + Effect.forEach(documentation), + Effect.map(Array.flatten), + ), + pipe( + items, + Array.flatMap((item) => item.members), + descendants, + Array.flatMap((nested) => + pipe( + comments([nested]), + Array.map((comment) => ({ nested, comment })), + ), + ), + Effect.forEach(({ nested, comment }) => + Effect.all([ + Effect.succeed([heading(nestedDepth, anchor(nested))]), + documentation(comment), + ]).pipe(Effect.map(Array.flatten)), + ), + Effect.map(Array.flatten), + ), + ]).pipe(Effect.map(Array.flatten)); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts new file mode 100644 index 00000000000..d881bac7e56 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts @@ -0,0 +1,190 @@ +import { Array, Effect, Option, Record, Result, pipe } from "effect"; +import { stringify } from "yaml"; + +import { Analysis } from "./Analysis.js"; +import * as Comment from "./Comment.js"; +import * as Member from "./Member.js"; +import * as Signature from "./Signature.js"; +import { Site } from "./Site.js"; +import { TransformError } from "./TransformError.js"; + +import type { Page } from "./Site.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { BlockContent, ListItem, PhrasingContent, Root } from "mdast"; + +const withLinks = Effect.fnUntraced(function* <A>( + origin: { readonly module: string; readonly container: ApiItem }, + effect: Effect.Effect<A, TransformError, Comment.Links>, +) { + const links = yield* (yield* Site).links(origin); + + return yield* Effect.provideService(effect, Comment.Links, links); +}); + +// The modules' own comments open the page, each linking from its module. +const overview = ( + page: Page, +): Effect.Effect<BlockContent[], TransformError, Analysis | Site> => + pipe( + page.modules, + Effect.forEach((file) => + Effect.flatMap(Effect.service(Analysis), (analysis) => + analysis.moduleComment(file), + ).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (comment) => + withLinks( + { module: file, container: page.container }, + Comment.overview(comment), + ), + }), + ), + ), + ), + Effect.map(Array.flatten), + ); + +// A child page's entry carries the first paragraph of its module's comment. +const childEntry = Effect.fnUntraced(function* (child: Page) { + const analysis = yield* Analysis; + const site = yield* Site; + const file = Array.headNonEmpty(child.modules); + const summary = yield* Option.match(yield* analysis.moduleComment(file), { + onNone: () => Effect.succeed([]), + onSome: (comment) => + withLinks( + { module: file, container: child.container }, + Comment.lead(comment), + ), + }); + const title: PhrasingContent = { + type: "link", + url: site.url(child), + children: [{ type: "inlineCode", value: child.title }], + }; + + return { + type: "listItem", + spread: false, + children: [ + { + type: "paragraph", + children: Array.match(summary, { + onEmpty: () => [title], + onNonEmpty: (lead) => [ + title, + { type: "text", value: " — " }, + ...lead, + ], + }), + }, + ], + } satisfies ListItem; +}); + +const member = Effect.fnUntraced(function* ( + page: Page, + items: Array.NonEmptyReadonlyArray<ApiItem>, +) { + const site = yield* Site; + const first = Array.headNonEmpty(items); + const origin = yield* Effect.fromOption(site.origin(first)).pipe( + Effect.mapError(() => + TransformError.malformedAnalysis( + `${first.getScopedNameWithinPackage()} has no source module on a page`, + ), + ), + ); + const blocks = yield* withLinks( + origin, + Member.render({ + items, + signature: yield* Signature.make({ + name: first.displayName, + source: origin.module, + exporters: [origin.module, ...page.modules], + }), + anchor: site.anchor, + }), + ); + + return { label: Member.group(items), blocks }; +}); + +const heading = (value: string): BlockContent => ({ + type: "heading", + depth: 2, + children: [{ type: "text", value }], +}); + +const namespaces = ( + children: readonly Page[], +): Effect.Effect<BlockContent[], TransformError, Analysis | Site> => + Array.match(children, { + onEmpty: () => Effect.succeed([]), + onNonEmpty: (pages) => + pipe( + pages, + Effect.forEach(childEntry), + Effect.map((entries): BlockContent[] => [ + heading("Namespaces"), + { type: "list", ordered: false, spread: false, children: entries }, + ]), + ), + }); + +// Rendered members under their group headings, in the groups' order. +const sections = ( + rendered: readonly { + readonly label: string; + readonly blocks: BlockContent[]; + }[], +): BlockContent[] => { + const groups = Array.groupBy(rendered, ({ label }) => label); + + return pipe( + Member.groupOrder(Record.keys(groups)), + Array.flatMap((label) => [ + heading(label), + ...pipe( + groups[label] ?? [], + Array.flatMap(({ blocks }) => blocks), + ), + ]), + ); +}; + +/** Builds a page from its modules' overviews and the pages of its namespaces, followed by its members grouped by category or kind. */ +export const render = Effect.fnUntraced(function* (page: Page) { + const site = yield* Site; + const [children, items] = pipe( + page.container.members, + Array.partition((item) => + Option.match(site.pageOf(item), { + onSome: Result.succeed, + onNone: () => Result.fail(item), + }), + ), + ); + // Members sharing a name render as one: overloads, or an interface merged with a namespace. + const body = yield* Effect.all([ + overview(page), + namespaces(children), + pipe( + Array.groupBy(items, (item) => item.displayName), + Record.values, + Effect.forEach((group) => member(page, group)), + Effect.map(sections), + ), + ]); + + return { + type: "root", + children: [ + { type: "yaml", value: stringify({ title: page.title }).trimEnd() }, + ...Array.flatten(body), + ], + } satisfies Root; +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts new file mode 100644 index 00000000000..e5aa597deaf --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts @@ -0,0 +1,118 @@ +import { Array, Effect, Option, Record, pipe } from "effect"; + +import { Analysis } from "./Analysis.js"; +import { Sources } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { Declarations } from "./Sources.js"; + +/** Where an aliased name comes from: the module declaring it and its name there. */ +interface Alias { + readonly module: string; + readonly local: string; +} + +// `export { local as name }` takes the name from another module when it re-exports, from an import when the local is one, and from the exporter's own declarations otherwise. +const aliasOf = ( + exporter: string, + name: string, +): Effect.Effect<Option.Option<Alias>, TransformError, Sources> => + Effect.flatMap(Effect.service(Sources), (sources) => + sources.scope(exporter).pipe( + Effect.map(({ reexports, imports }) => + pipe( + Record.get(reexports, name), + Option.flatMap(({ local, specifier }) => + Option.match(specifier, { + onSome: (from) => + sources + .resolve(exporter, from) + .pipe(Option.map((module) => ({ module, local }))), + onNone: () => + pipe( + Record.get(imports, local), + Option.flatMap((binding) => + Option.all({ + module: sources.resolve(exporter, binding.specifier), + local: binding.imported, + }), + ), + Option.orElse(() => Option.some({ module: exporter, local })), + ), + }), + ), + ), + ), + ), + ); + +const declarationsOf = ( + source: string, +): Effect.Effect<Declarations, TransformError, Analysis | Sources> => + Effect.all([Effect.service(Analysis), Effect.service(Sources)]).pipe( + Effect.flatMap(([analysis, sources]) => + analysis.declarationOf(source).pipe(Effect.flatMap(sources.declarations)), + ), + ); + +export interface Options { + /** The name the member's module exports it under. */ + readonly name: string; + /** The source module declaring it. */ + readonly source: string; + /** Modules that may publish it under another name: the declaring module, then the page's. */ + readonly exporters: readonly string[]; +} + +/** + * The statements declaring a member, without comments. + * + * A member exported under an alias keeps its local declaration, and the export specifier that publishes the alias follows it. The SDK exports `conditional` as `if` this way, because `if` cannot name a function. + */ +export const make = ({ + name, + source, + exporters, +}: Options): Effect.Effect<string, TransformError, Analysis | Sources> => + declarationsOf(source).pipe( + Effect.flatMap(({ local }) => + Option.match(Record.get(local, name), { + onSome: (declared) => Effect.succeed(pipe(declared, Array.join("\n"))), + onNone: () => + pipe( + exporters, + Effect.forEach((exporter) => + Effect.all([ + aliasOf(exporter, name), + declarationsOf(exporter), + ]).pipe( + Effect.map(([alias, { exports }]) => + Option.all({ + statements: alias.pipe( + Option.filter(({ module }) => module === source), + Option.flatMap((found) => Record.get(local, found.local)), + ), + exported: Record.get(exports, name), + }), + ), + ), + ), + Effect.map(Array.getSomes), + Effect.flatMap( + Array.match({ + onEmpty: () => + Effect.fail( + TransformError.malformedAnalysis( + `${source} declares no ${name}`, + ), + ), + onNonEmpty: ([{ statements, exported }]) => + Effect.succeed( + pipe([...statements, exported], Array.join("\n")), + ), + }), + ), + ), + }), + ), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts new file mode 100644 index 00000000000..c87f0204721 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -0,0 +1,426 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- Path is unstable +import { + ApiItemContainerMixin, + ApiItemKind, +} from "@microsoft/api-extractor-model"; +import { + Array, + Context, + Effect, + Layer, + Option, + Path, + Record, + pipe, +} from "effect"; + +import { Analysis } from "./Analysis.js"; +import { Links } from "./Comment.js"; +import { Sources } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +import type { Scope } from "./Sources.js"; +import type { ApiItem } from "@microsoft/api-extractor-model"; +import type { DocDeclarationReference } from "@microsoft/tsdoc"; + +/** A reference page for the package, or for a namespace that a module re-exports with `export * as`. */ +export interface Page { + /** Path segments below the output directory, empty for the package page. */ + readonly path: readonly string[]; + readonly title: string; + /** The model item whose members the page documents. */ + readonly container: ApiItem; + /** The modules whose `@module` comments open the page. */ + readonly modules: Array.NonEmptyReadonlyArray<string>; +} + +/** The module a comment comes from, whose imports its links see, and the item that stands for that module's declarations. */ +export interface Origin { + readonly module: string; + readonly container: ApiItem; +} + +/** The pages of the reference and the links between them. */ +export class Site extends Context.Service< + Site, + { + readonly pages: Array.NonEmptyReadonlyArray<Page>; + /** The page documenting a container's members, if it has one. */ + readonly pageOf: (container: ApiItem) => Option.Option<Page>; + readonly url: (page: Page) => string; + /** An item's anchor on its page: its name, qualified up to the page's container. */ + readonly anchor: (item: ApiItem) => string; + readonly origin: (item: ApiItem) => Option.Option<Origin>; + /** Resolves the links of comments written at an origin. */ + readonly links: ( + origin: Origin, + ) => Effect.Effect<Links["Service"], TransformError>; + } +>()("@local/hashql-typescript-docs/Site") {} + +// Every declaration sharing the name, since an interface and a namespace merge under one. +const members = (container: ApiItem, name: string): readonly ApiItem[] => { + if (ApiItemContainerMixin.isBaseClassOf(container)) { + return container.findMembersByName(name); + } + + return []; +}; + +const ancestors = (item: ApiItem): ApiItem[] => + Array.unfold(item.parent, (parent) => + Option.fromNullishOr(parent).pipe( + Option.map((found) => [found, found.parent] as const), + ), + ); + +const directorySegments = (path: Path.Path, directory: string): string[] => + pipe( + directory.split(path.sep), + Array.filter((segment) => segment !== ""), + ); + +// A namespace that a module re-exports with `export * as` gets a page. A `namespace` declaration renders among its siblings. +const pageOfNamespace = ( + item: ApiItem, +): Effect.Effect< + Option.Option<Page>, + TransformError, + Analysis | Sources | Path.Path +> => + Effect.gen(function* () { + const analysis = yield* Analysis; + const sources = yield* Sources; + const path = yield* Path.Path; + const file = analysis + .sourceOf(item) + .pipe(Option.filter(() => item.kind === ApiItemKind.Namespace)); + + if (Option.isNone(file)) { + return Option.none(); + } + + const specifier = Record.get( + (yield* sources.scope(file.value)).namespaces, + item.displayName, + ); + + if (Option.isNone(specifier)) { + return Option.none(); + } + + const target = yield* Effect.fromOption( + sources.resolve(file.value, specifier.value), + ).pipe( + Effect.mapError(() => + TransformError.malformedAnalysis( + `${file.value} re-exports ${specifier.value}, which does not exist`, + ), + ), + ); + const directory = path.relative( + path.dirname(Array.headNonEmpty(analysis.roots)), + path.dirname(target), + ); + + return Option.some({ + path: [...directorySegments(path, directory), item.displayName], + title: item.displayName, + container: item, + modules: [target], + }); + }); + +const discover = ( + container: ApiItem, +): Effect.Effect<Page[], TransformError, Analysis | Sources | Path.Path> => + pipe( + container.members, + Effect.forEach((item) => + pageOfNamespace(item).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (page) => + discover(item).pipe(Effect.map((nested) => [page, ...nested])), + }), + ), + ), + ), + Effect.map(Array.flatten), + ); + +interface Index { + readonly pageOf: (container: ApiItem) => Option.Option<Page>; + readonly pageOfModule: (file: string) => Option.Option<Page>; + readonly url: (page: Page) => string; + readonly anchor: (item: ApiItem) => string; + readonly itemUrl: (item: ApiItem) => Option.Option<string>; + /** The nearest ancestor of an item that has a page. */ + readonly enclosing: (item: ApiItem) => Option.Option<ApiItem>; +} + +const makeIndex = (pages: readonly Page[], url: string): Index => { + const byContainer = new Map( + pipe( + pages, + Array.map((page) => [page.container, page] as const), + ), + ); + const byModule = pipe( + pages, + Array.flatMap((page) => + pipe( + page.modules, + Array.map((file) => [file, page] as const), + ), + ), + Record.fromEntries, + ); + const hasPage = (item: ApiItem): boolean => byContainer.has(item); + + const pageOf = (container: ApiItem): Option.Option<Page> => + Option.fromNullishOr(byContainer.get(container)); + const pageUrl = (page: Page): string => + pipe([url, ...page.path], Array.join("/")); + const enclosing = (item: ApiItem): Option.Option<ApiItem> => + pipe(ancestors(item), Array.findFirst(hasPage)); + const anchor = (item: ApiItem): string => + pipe( + ancestors(item), + Array.takeWhile((parent) => !hasPage(parent)), + Array.reverse, + Array.map((parent) => parent.displayName), + Array.append(item.displayName), + Array.join("."), + ); + + return { + pageOf, + pageOfModule: (file) => Record.get(byModule, file), + url: pageUrl, + anchor, + enclosing, + itemUrl: (item) => + pageOf(item).pipe( + Option.map(pageUrl), + Option.orElse(() => + enclosing(item).pipe( + Option.flatMap(pageOf), + Option.map((page) => `${pageUrl(page)}#${anchor(item)}`), + ), + ), + ), + }; +}; + +interface Resolution { + readonly index: Index; + readonly origin: Origin; + readonly scope: Scope; +} + +// The module's declarations, including those it publishes under another name with `export { local as name }`. +const declared = ( + { origin, scope }: Resolution, + name: string, +): readonly ApiItem[] => [ + ...members(origin.container, name), + ...pipe( + Record.toEntries(scope.reexports), + Array.filter( + ([, reexport]) => + reexport.local === name && Option.isNone(reexport.specifier), + ), + Array.flatMap(([exported]) => members(origin.container, exported)), + ), +]; + +const imported = ( + sources: Sources["Service"], + { index, origin, scope }: Resolution, + name: string, +): readonly ApiItem[] => + pipe( + Record.get(scope.imports, name), + Option.flatMap((binding) => + sources.resolve(origin.module, binding.specifier).pipe( + Option.flatMap(index.pageOfModule), + Option.map((page) => + Option.match(binding.imported, { + onNone: () => [page.container], + onSome: (exported) => members(page.container, exported), + }), + ), + ), + ), + Option.getOrElse(() => []), + ); + +// A symbol reference such as `[Symbol.iterator]` names no member a page lists. +const namesOf = ( + reference: DocDeclarationReference, +): Option.Option<Array.NonEmptyReadonlyArray<string>> => + pipe( + reference.memberReferences, + Array.map((part) => + Option.fromNullishOr(part.memberIdentifier?.identifier), + ), + Option.all, + Option.flatMap( + Array.match({ + onEmpty: () => Option.none(), + onNonEmpty: (names) => Option.some(names), + }), + ), + ); + +// Walks the remaining names of a reference through the members of every candidate. +const walk = ( + candidates: readonly ApiItem[], + names: readonly string[], +): readonly ApiItem[] => + Array.matchLeft(names, { + onEmpty: () => candidates, + onNonEmpty: (name, rest) => + walk( + pipe( + candidates, + Array.flatMap((parent) => members(parent, name)), + ), + rest, + ), + }); + +interface Resolver { + readonly analysis: Analysis["Service"]; + readonly sources: Sources["Service"]; + readonly resolution: Resolution; +} + +// Links resolve the way TypeScript resolves them in the comment's module: its declarations, then its imports. A reference qualified from the package resolves last. +const target = + ({ analysis, sources, resolution }: Resolver) => + (reference: DocDeclarationReference): Option.Option<ApiItem> => + pipe( + namesOf(reference), + Option.filter( + () => + reference.packageName === undefined || + reference.packageName === analysis.package.name, + ), + Option.flatMap(([head, ...tail]) => + pipe( + [ + declared(resolution, head), + imported(sources, resolution, head), + members(analysis.entry, head), + ], + Array.findFirst((found) => found.length > 0), + Option.map((found) => walk(found, tail)), + Option.flatMap(Array.head), + ), + ), + ); + +const makeLinks = + (index: Index) => + ( + origin: Origin, + ): Effect.Effect< + Links["Service"], + TransformError, + Analysis | Sources | Path.Path + > => + Effect.gen(function* () { + const analysis = yield* Analysis; + const sources = yield* Sources; + const path = yield* Path.Path; + const resolution: Resolution = { + index, + origin, + scope: yield* sources.scope(origin.module), + }; + const shown = path.relative( + path.dirname(Array.headNonEmpty(analysis.roots)), + origin.module, + ); + + return Links.of({ + resolve: (reference) => { + const resolved = target({ analysis, sources, resolution })( + reference, + ).pipe(Option.flatMap(index.itemUrl)); + + if (Option.isNone(resolved)) { + return Effect.logWarning( + `Unresolved link ${reference.emitAsTsdoc()} in ${shown}`, + ).pipe(Effect.as(resolved)); + } + + return Effect.succeed(resolved); + }, + }); + }); + +export interface Options { + /** The URL of the package page, which every other page's URL extends. */ + readonly url: string; +} + +export const layer = ({ + url, +}: Options): Layer.Layer< + Site, + TransformError, + Analysis | Sources | Path.Path +> => + Layer.effect( + Site, + Effect.gen(function* () { + const analysis = yield* Analysis; + const services = yield* Effect.context<Analysis | Sources | Path.Path>(); + const pages = yield* discover(analysis.entry).pipe( + Effect.map( + Array.prepend<Page>({ + path: [], + title: analysis.package.displayName, + container: analysis.entry, + modules: analysis.roots, + }), + ), + ); + const duplicate = pipe( + Array.groupBy(pages, (page) => pipe(page.path, Array.join("/"))), + Record.toEntries, + Array.findFirst(([, group]) => group.length > 1), + ); + + if (Option.isSome(duplicate)) { + return yield* TransformError.malformedAnalysis( + `Two namespaces render to ${duplicate.value[0]}`, + ); + } + + const index = makeIndex(pages, url); + + return Site.of({ + pages, + pageOf: index.pageOf, + url: index.url, + anchor: index.anchor, + origin: (item) => + analysis.sourceOf(item).pipe( + Option.flatMap((file) => + index.pageOfModule(file).pipe( + Option.map((page) => page.container), + Option.orElse(() => index.enclosing(item)), + Option.map((container) => ({ module: file, container })), + ), + ), + ), + links: (origin) => + makeLinks(index)(origin).pipe(Effect.provide(services)), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts new file mode 100644 index 00000000000..ee4a6b2071e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts @@ -0,0 +1,135 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem is unstable +// oxlint-disable effecttsgo/strict-effect-provide -- each test is an entry point that provides its own files +import { Effect, FileSystem, Layer, Option, Record } from "effect"; +import { describe, expect, test } from "vitest"; + +import * as Sources from "./Sources.js"; + +// Each test reads only the files it names. Any other read is a defect in the test. +const read = <A, E>( + contents: Record.ReadonlyRecord<string, string>, + effect: (sources: Sources.Sources["Service"]) => Effect.Effect<A, E>, +): A => + Effect.flatMap(Effect.service(Sources.Sources), effect).pipe( + Effect.provide( + Sources.layer.pipe( + Layer.provide( + FileSystem.layerNoop({ + readFileString: (path) => + Effect.fromOption(Record.get(contents, path)).pipe(Effect.orDie), + }), + ), + ), + ), + Effect.orDie, + Effect.runSync, + ); + +describe("sources", () => { + test("scope_bindings", () => { + expect.hasAssertions(); + const scope = read( + { + "/module.ts": [ + 'import * as Whole from "./whole.js";', + 'import { named as renamed } from "./named.js";', + 'import fallback from "./fallback.js";', + 'export * from "./everything.js";', + 'export * as Space from "./space.js";', + 'export { remote as published } from "./remote.js";', + "const local = 1;", + "export { local as alias };", + ].join("\n"), + }, + (sources) => sources.scope("/module.ts"), + ); + + expect(scope.imports).toStrictEqual({ + Whole: { specifier: "./whole.js", imported: Option.none() }, + renamed: { specifier: "./named.js", imported: Option.some("named") }, + fallback: { + specifier: "./fallback.js", + imported: Option.some("default"), + }, + }); + expect(scope.wildcards).toStrictEqual(["./everything.js"]); + expect(scope.namespaces).toStrictEqual({ Space: "./space.js" }); + expect(scope.reexports).toStrictEqual({ + published: { local: "remote", specifier: Option.some("./remote.js") }, + alias: { local: "local", specifier: Option.none() }, + }); + }); + + test("declarations_overloads", () => { + expect.hasAssertions(); + const { local } = read( + { + "/module.d.ts": [ + "/** First overload. */", + "export declare function pick(value: string): string;", + "/** Second overload. */", + "export declare function pick(value: number): number;", + "export interface Shape {", + " /** The side length. */", + " readonly side: number; // trailing", + " readonly name: string;", + "}", + ].join("\n"), + }, + (sources) => sources.declarations("/module.d.ts"), + ); + + expect(Record.get(local, "pick")).toStrictEqual( + Option.some([ + "export declare function pick(value: string): string;", + "export declare function pick(value: number): number;", + ]), + ); + expect(Record.get(local, "Shape")).toStrictEqual( + Option.some([ + [ + "export interface Shape {", + " readonly side: number; ", + " readonly name: string;", + "}", + ].join("\n"), + ]), + ); + }); + + test("declarations_alias_export", () => { + expect.hasAssertions(); + const { local, exports } = read( + { + "/module.d.ts": [ + "declare function conditional(): void;", + "export { conditional as if, other as unrelated };", + 'export { ifElse as If, assume } from "./expression.js";', + ].join("\n"), + }, + (sources) => sources.declarations("/module.d.ts"), + ); + + expect(Record.get(local, "conditional")).toStrictEqual( + Option.some(["declare function conditional(): void;"]), + ); + expect(Record.get(exports, "if")).toStrictEqual( + Option.some("export { conditional as if };"), + ); + expect(Record.get(exports, "If")).toStrictEqual( + Option.some('export { ifElse as If } from "./expression.js";'), + ); + }); + + test("syntax_error", () => { + expect.hasAssertions(); + const error = read({ "/broken.ts": "export const = ;" }, (sources) => + Effect.flip(sources.scope("/broken.ts")), + ); + + expect(error.reason).toMatchObject({ + _tag: "SourceSyntax", + file: "/broken.ts", + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts new file mode 100644 index 00000000000..2ffeaccb6c2 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts @@ -0,0 +1,404 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem is unstable +import { + Array, + Cache, + Context, + Effect, + FileSystem, + Filter, + Layer, + Option, + Record, + pipe, +} from "effect"; +import { print } from "esrap"; +import ts from "esrap/languages/ts"; +import { parseSync } from "oxc-parser"; +import { ResolverFactory } from "oxc-resolver"; + +import { TransformError } from "./TransformError.js"; + +import type { + BindingPattern, + Comment, + Declaration, + ExportAllDeclaration, + ExportNamedDeclaration, + ImportDeclaration, + ImportDeclarationSpecifier, + ModuleExportName, + Program, + Statement, + StringLiteral, + TSQualifiedName, +} from "oxc-parser"; + +/** A name an import declaration brings into a module's scope. */ +export interface Binding { + readonly specifier: string; + /** The imported export, `None` for a namespace import. */ + readonly imported: Option.Option<string>; +} + +/** A name an export specifier publishes. */ +export interface Reexport { + readonly local: string; + /** The module it is re-exported from, `None` for a binding of the exporting module. */ + readonly specifier: Option.Option<string>; +} + +/** The names a module imports and exports, and its block comments. */ +export interface Scope { + readonly text: string; + readonly imports: Record.ReadonlyRecord<string, Binding>; + /** Specifiers of `export * from`, in source order. */ + readonly wildcards: readonly string[]; + /** Specifiers of `export * as`, by exported name. */ + readonly namespaces: Record.ReadonlyRecord<string, string>; + /** Export specifiers, by exported name. */ + readonly reexports: Record.ReadonlyRecord<string, Reexport>; + readonly comments: readonly Comment[]; +} + +/** The declarations of a declaration file and the statements that publish them. */ +export interface Declarations { + /** The statements declaring each top-level name, without comments. Overloads share an entry. */ + readonly local: Record.ReadonlyRecord< + string, + Array.NonEmptyReadonlyArray<string> + >; + /** For each name an export specifier publishes, that specifier as an export statement of its own. */ + readonly exports: Record.ReadonlyRecord<string, string>; +} + +const parse = ( + file: string, + text: string, +): Effect.Effect< + Pick<ReturnType<typeof parseSync>, "program" | "comments">, + TransformError +> => { + const { program, comments, errors } = parseSync(file, text); + + return Array.match(errors, { + onEmpty: () => Effect.succeed({ program, comments }), + onNonEmpty: (failures) => + Effect.fail( + TransformError.sourceSyntax( + file, + pipe( + failures, + Array.map(({ message }) => message), + ), + ), + ), + }); +}; + +const exportName = (name: ModuleExportName): string => { + if (name.type === "Literal") { + return name.value; + } + + return name.name; +}; + +const importedName = ( + specifier: ImportDeclarationSpecifier, +): Option.Option<string> => { + if (specifier.type === "ImportSpecifier") { + return Option.some(exportName(specifier.imported)); + } + + if (specifier.type === "ImportDefaultSpecifier") { + return Option.some("default"); + } + + return Option.none(); +}; + +const isImport = (statement: Statement): statement is ImportDeclaration => + statement.type === "ImportDeclaration"; + +const isExportAll = (statement: Statement): statement is ExportAllDeclaration => + statement.type === "ExportAllDeclaration"; + +const isExportNamed = ( + statement: Statement, +): statement is ExportNamedDeclaration => + statement.type === "ExportNamedDeclaration"; + +const collectScope = (program: Program): Omit<Scope, "text" | "comments"> => { + const exportsAll = pipe(program.body, Array.filter(isExportAll)); + + return { + imports: pipe( + program.body, + Array.filter(isImport), + Array.flatMap((statement) => + pipe( + statement.specifiers, + Array.map( + (specifier) => + [ + specifier.local.name, + { + specifier: statement.source.value, + imported: importedName(specifier), + }, + ] as const, + ), + ), + ), + Record.fromEntries, + ), + wildcards: pipe( + exportsAll, + Array.filter(({ exported }) => exported === null), + Array.map(({ source }) => source.value), + ), + namespaces: pipe( + exportsAll, + Array.filterMap( + Filter.fromPredicateOption(({ exported, source }) => + Option.fromNullishOr(exported).pipe( + Option.map((name) => [exportName(name), source.value] as const), + ), + ), + ), + Record.fromEntries, + ), + reexports: pipe( + program.body, + Array.filter(isExportNamed), + Array.flatMap((statement) => + pipe( + statement.specifiers, + Array.map( + (specifier) => + [ + exportName(specifier.exported), + { + local: exportName(specifier.local), + specifier: Option.fromNullishOr(statement.source?.value), + }, + ] as const, + ), + ), + ), + Record.fromEntries, + ), + }; +}; + +const declarationTypes: ReadonlySet<string> = new Set([ + "VariableDeclaration", + "FunctionDeclaration", + "TSDeclareFunction", + "ClassDeclaration", + "TSTypeAliasDeclaration", + "TSInterfaceDeclaration", + "TSEnumDeclaration", + "TSModuleDeclaration", +] satisfies Declaration["type"][]); + +const isDeclaration = (statement: Statement): statement is Declaration => + declarationTypes.has(statement.type); + +const declarationOf = (statement: Statement): Option.Option<Declaration> => { + if (statement.type === "ExportNamedDeclaration") { + return Option.fromNullishOr(statement.declaration); + } + + return Option.liftPredicate(statement, isDeclaration); +}; + +// Destructuring patterns and string-named modules declare no name a member can have. +const identifierName = ( + node: BindingPattern | StringLiteral | TSQualifiedName | null, +): Option.Option<string> => { + if (node?.type === "Identifier") { + return Option.some(node.name); + } + + return Option.none(); +}; + +const declaredNames = (declaration: Declaration): readonly string[] => { + if (declaration.type === "VariableDeclaration") { + return pipe( + declaration.declarations, + Array.filterMap( + Filter.fromPredicateOption(({ id }) => identifierName(id)), + ), + ); + } + + return Array.fromOption(identifierName(declaration.id)); +}; + +// A comment alone on its lines leaves with those lines, so removing it leaves no blank line behind. +const commentRange = ( + text: string, + comment: Comment, +): { readonly start: number; readonly end: number } => { + const lineStart = text.lastIndexOf("\n", comment.start - 1) + 1; + const lineEnd = text.indexOf("\n", comment.end); + + if ( + lineEnd !== -1 && + text.slice(lineStart, comment.start).trim() === "" && + text.slice(comment.end, lineEnd).trim() === "" + ) { + return { start: lineStart, end: lineEnd + 1 }; + } + + return { start: comment.start, end: comment.end }; +}; + +// The text between the comments inside a statement. +const statementText = ( + text: string, + statement: Statement, + comments: readonly Comment[], +): string => { + const [cursor, pieces] = pipe( + comments, + Array.filter( + ({ start, end }) => start >= statement.start && end <= statement.end, + ), + Array.map((comment) => commentRange(text, comment)), + Array.mapAccum(statement.start, (position, range) => [ + Math.max(position, range.end), + text.slice(position, Math.max(position, range.start)), + ]), + ); + + return pipe([...pieces, text.slice(cursor, statement.end)], Array.join("")); +}; + +const collectDeclarations = ( + text: string, + program: Program, + comments: readonly Comment[], +): Declarations => ({ + local: pipe( + program.body, + Array.flatMap((statement) => + pipe( + declarationOf(statement), + Array.fromOption, + Array.flatMap(declaredNames), + Array.map((name) => ({ + name, + source: statementText(text, statement, comments), + })), + ), + ), + Array.groupBy(({ name }) => name), + Record.map(Array.map(({ source }) => source)), + ), + exports: pipe( + program.body, + Array.filter(isExportNamed), + Array.flatMap((statement) => + pipe( + statement.specifiers, + Array.map((specifier) => { + const single: ExportNamedDeclaration = { + ...statement, + specifiers: [specifier], + }; + + return [ + exportName(specifier.exported), + print(single, ts({ quotes: "double" })).code, + ] as const; + }), + ), + ), + Record.fromEntries, + ), +}); + +/** Reads TypeScript modules with oxc, each file once per run, and resolves their specifiers. */ +export class Sources extends Context.Service< + Sources, + { + /** The imports, re-exports and comments of a module. */ + readonly scope: (file: string) => Effect.Effect<Scope, TransformError>; + /** The declarations and export specifiers of a declaration file. */ + readonly declarations: ( + file: string, + ) => Effect.Effect<Declarations, TransformError>; + /** The file a module specifier written in `file` names, `None` when it names nothing on disk. */ + readonly resolve: ( + file: string, + specifier: string, + ) => Option.Option<string>; + } +>()("@local/hashql-typescript-docs/Sources") {} + +// The SDK's specifiers name the emitted `.js`, while its sources and declarations end in `.ts` and `.d.ts`. +const resolver = new ResolverFactory({ + extensionAlias: { ".js": [".ts", ".d.ts", ".js"] }, +}); + +export const layer: Layer.Layer<Sources, never, FileSystem.FileSystem> = + Layer.effect( + Sources, + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + + const read = ( + file: string, + ): Effect.Effect< + Pick<ReturnType<typeof parseSync>, "program" | "comments"> & { + readonly text: string; + }, + TransformError + > => + fs.readFileString(file).pipe( + Effect.mapError(TransformError.fileSystem), + Effect.flatMap((text) => + parse(file, text).pipe( + Effect.map((parsed) => ({ ...parsed, text })), + ), + ), + ); + + const scopes = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: (file: string) => + read(file).pipe( + Effect.map( + ({ text, program, comments }): Scope => ({ + ...collectScope(program), + text, + comments: pipe( + comments, + Array.filter(({ type }) => type === "Block"), + ), + }), + ), + ), + }); + + const declarations = yield* Cache.make({ + capacity: Number.POSITIVE_INFINITY, + lookup: (file: string) => + read(file).pipe( + Effect.map(({ text, program, comments }) => + collectDeclarations(text, program, comments), + ), + ), + }); + + return Sources.of({ + scope: (file) => Cache.get(scopes, file), + declarations: (file) => Cache.get(declarations, file), + resolve: (file, specifier) => + Option.fromNullishOr(resolver.resolveFileSync(file, specifier).path), + }); + }), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts new file mode 100644 index 00000000000..b3d2a77a459 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts @@ -0,0 +1,116 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- CLI module is unstable +import { + Array, + Effect, + FileSystem, + Layer, + Path, + Schema, + identity, + pipe, +} from "effect"; +import { Command, Flag } from "effect/cli"; + +import * as Analysis from "./Analysis.js"; +import * as Mdx from "./Mdx.js"; +import * as Page from "./Page.js"; +import * as Site from "./Site.js"; +import * as Sources from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +// The reference folder lists the package page first, then the module folders. +const Meta = Schema.fromJsonString( + Schema.Struct({ title: Schema.String, pages: Schema.Array(Schema.String) }), + { space: 2 }, +); + +const packageDirectory = ( + ...segments: string[] +): Effect.Effect<string, never, Path.Path> => + Effect.suspend(() => + Path.Path.pipe( + Effect.map((path) => + path.resolve(import.meta.dirname, "..", ...segments), + ), + ), + ); + +export const command = Command.make("transform", { + lib: Flag.Directory("lib", { mustExist: true }).pipe( + Flag.withDescription("The analyzed package's folder"), + ), + analysis: Flag.Directory("analysis", { mustExist: true }).pipe( + Flag.withDescription("The directory `analyze` wrote"), + Flag.withDefault(packageDirectory(".generated")), + ), + out: Flag.Directory("out").pipe( + Flag.withDescription( + "The directory the reference pages are written to; its previous contents are removed", + ), + Flag.withDefault(packageDirectory("content", "docs", "reference")), + ), + url: Flag.String("url").pipe( + Flag.withDescription("The URL the package page is served at"), + Flag.withDefault("/docs/reference"), + ), +}); + +// The package page is the folder's index page. +const fileOf = (path: Path.Path, out: string, page: Site.Page): string => + `${path.join( + out, + ...Array.match(page.path, { + onEmpty: () => ["index"], + onNonEmpty: identity, + }), + )}.mdx`; + +const write = Effect.fnUntraced(function* (out: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { pages } = yield* Site.Site; + // Encoding a literal of the schema's own type cannot fail. + const meta = yield* Schema.encodeEffect(Meta)({ + title: "API reference", + pages: ["index", "..."], + }).pipe(Effect.orDie); + + yield* fs + .remove(out, { recursive: true, force: true }) + .pipe(Effect.mapError(TransformError.fileSystem)); + + yield* pipe( + pages, + Effect.forEach((page) => { + const file = fileOf(path, out, page); + + return Page.render(page).pipe( + Effect.flatMap((tree) => + fs + .makeDirectory(path.dirname(file), { recursive: true }) + .pipe( + Effect.andThen(fs.writeFileString(file, Mdx.stringify(tree))), + Effect.mapError(TransformError.fileSystem), + ), + ), + ); + }), + ); + + yield* fs + .writeFileString(path.join(out, "meta.json"), meta) + .pipe(Effect.mapError(TransformError.fileSystem)); + yield* Effect.log(`Wrote ${pages.length} pages to ${out}`); +}); + +export const handler = command.pipe( + Command.withHandler(({ out }) => + Path.Path.pipe(Effect.flatMap((path) => write(path.resolve(out)))), + ), + Command.provide(({ lib, analysis, url }) => + Site.layer({ url }).pipe( + Layer.provideMerge(Analysis.layer({ lib, analysis })), + Layer.provideMerge(Sources.layer), + ), + ), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts new file mode 100644 index 00000000000..e521a88a29d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts @@ -0,0 +1,68 @@ +// oxlint-disable effecttsgo/unstable-api-usage -- PlatformError is unstable +import { Data } from "effect"; + +import type { Schema } from "effect"; +import type { PlatformError } from "effect/PlatformError"; + +/** Why building the reference pages failed. */ +export type Reason = Data.TaggedEnum<{ + /** Reading or writing a file failed. */ + FileSystem: { readonly cause: PlatformError }; + /** Oxc rejected a module that a page draws on. */ + SourceSyntax: { readonly file: string; readonly messages: readonly string[] }; + /** A declaration map does not name the source TypeScript emitted its file from. */ + MalformedSourceMap: { + readonly file: string; + readonly cause: Schema.SchemaError; + }; + /** The analysis output lacks something a page needs. */ + MalformedAnalysis: { readonly detail: string }; + /** A documentation comment uses TSDoc syntax the pages have no rendering for. */ + UnsupportedComment: { readonly kind: string }; +}>; + +/** Constructors and matching helpers for the tagged {@link Reason} variants. */ +export const Reason: Data.TaggedEnum.Constructor<Reason> = + Data.taggedEnum<Reason>(); + +const TransformErrorBase: ReturnType< + typeof Data.TaggedError<"TransformError"> +> = Data.TaggedError("TransformError"); + +/** Failure to build the reference pages from an analysis. `reason` names the input at fault. */ +export class TransformError extends TransformErrorBase<{ + readonly reason: Reason; +}> { + static readonly fileSystem = (cause: PlatformError): TransformError => + new TransformError({ reason: Reason.FileSystem({ cause }) }); + + static readonly sourceSyntax = ( + file: string, + messages: readonly string[], + ): TransformError => + new TransformError({ reason: Reason.SourceSyntax({ file, messages }) }); + + static readonly malformedSourceMap = ( + file: string, + cause: Schema.SchemaError, + ): TransformError => + new TransformError({ reason: Reason.MalformedSourceMap({ file, cause }) }); + + static readonly malformedAnalysis = (detail: string): TransformError => + new TransformError({ reason: Reason.MalformedAnalysis({ detail }) }); + + static readonly unsupportedComment = (kind: string): TransformError => + new TransformError({ reason: Reason.UnsupportedComment({ kind }) }); + + override get message(): string { + return Reason.$match(this.reason, { + FileSystem: ({ cause }) => cause.message, + SourceSyntax: ({ file, messages }) => + `${file} does not parse: ${messages.join("; ")}`, + MalformedSourceMap: ({ file, cause }) => `${file}: ${cause.message}`, + MalformedAnalysis: ({ detail }) => detail, + UnsupportedComment: ({ kind }) => + `Documentation comments use ${kind}, which the reference pages cannot render`, + }); + } +} diff --git a/libs/@local/hashql/sdk/typescript-docs/src/cli.ts b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts index c2e4c8a3843..252c5f10912 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/cli.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/cli.ts @@ -4,9 +4,10 @@ import { Effect } from "effect"; import { Command } from "effect/cli"; import * as Analyze from "./Analyze.js"; +import * as Transform from "./Transform.js"; const command = Command.make("docs").pipe( - Command.withSubcommands([Analyze.handler]), + Command.withSubcommands([Analyze.handler, Transform.handler]), ); Command.run(command, { version: "0.0.1" }).pipe( diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json index d8012314a2a..29a4d66961a 100644 --- a/libs/@local/hashql/sdk/typescript-docs/turbo.json +++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json @@ -2,6 +2,41 @@ "$schema": "https://turborepo.org/schema.json", "extends": ["//"], "tasks": { - // TODO + // TypeScript 7 emits a declaration file per module, which keeps each `export * as` a namespace API Extractor reads members from. + "doc:declarations": { + "dependsOn": ["^manifest"], + "outputs": [".generated/declarations/**"] + }, + "doc:analyze": { + "dependsOn": ["doc:declarations"], + "outputs": [".generated/api.json", ".generated/api-entry.d.ts"] + }, + "doc:transform": { + "dependsOn": ["doc:analyze"], + "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/oxfmt.config.ts"], + "outputs": ["content/docs/reference/**"] + }, + "codegen": { + "dependsOn": ["doc:transform"], + "outputs": [".source/**"] + }, + // Twoslash type-checks the examples against the SDK's built declarations. + "build": { + "dependsOn": ["codegen", "^build"], + "env": ["NEXT_TELEMETRY_DISABLED"], + "outputs": [".next/**", "!.next/cache/**"] + }, + "dev": { + "dependsOn": ["codegen", "^build"], + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + }, + "start": { + "dependsOn": ["build"], + "cache": false, + "persistent": true, + "env": ["PORT", "NEXT_TELEMETRY_DISABLED"] + } } } diff --git a/yarn.lock b/yarn.lock index c91d46d6ba0..a3d96c54d12 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10234,6 +10234,7 @@ __metadata: resolution: "@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs" dependencies: "@effect/platform-node": "npm:4.0.0" + "@effect/vitest": "npm:4.0.0" "@fumadocs/satteri": "npm:0.5.1" "@local/hashql": "workspace:*" "@local/oxlint": "workspace:*" @@ -10252,16 +10253,19 @@ __metadata: "@types/react": "npm:19.2.14" "@types/react-dom": "npm:19.2.3" effect: "npm:4.0.0" + esrap: "npm:2.4.0" fumadocs-core: "npm:16.16.2" fumadocs-mdx: "npm:15.4.6" fumadocs-twoslash: "npm:4.0.1" fumadocs-ui: "npm:16.16.2" next: "npm:16.3.8" oxc-parser: "npm:0.152.0" + oxc-resolver: "npm:11.24.2" oxfmt: "npm:0.71.0" oxlint: "catalog:" react: "npm:19.2.6" react-dom: "npm:19.2.6" + remark-frontmatter: "npm:5.0.0" remark-mdx: "npm:3.1.1" remark-parse: "npm:11.0.0" remark-stringify: "npm:11.0.0" @@ -10271,6 +10275,9 @@ __metadata: tsx: "catalog:" typescript: "catalog:" unified: "npm:11.0.5" + vite: "catalog:" + vitest: "catalog:" + yaml: "npm:2.9.1" languageName: unknown linkType: soft @@ -36132,6 +36139,20 @@ __metadata: languageName: node linkType: hard +"mdast-util-frontmatter@npm:^2.0.0": + version: 2.0.1 + resolution: "mdast-util-frontmatter@npm:2.0.1" + dependencies: + "@types/mdast": "npm:^4.0.0" + devlop: "npm:^1.0.0" + escape-string-regexp: "npm:^5.0.0" + mdast-util-from-markdown: "npm:^2.0.0" + mdast-util-to-markdown: "npm:^2.0.0" + micromark-extension-frontmatter: "npm:^2.0.0" + checksum: 10c0/d9b0b70dd9c574cc0220d4e05dd8e9d86ac972a6a5af9e0c49c839b31cb750d4313445cfbbdf9264a7fbe3f8c8d920b45358b8500f4286e6b9dc830095b25b9a + languageName: node + linkType: hard + "mdast-util-gfm-autolink-literal@npm:^2.0.0": version: 2.0.1 resolution: "mdast-util-gfm-autolink-literal@npm:2.0.1" @@ -36524,6 +36545,18 @@ __metadata: languageName: node linkType: hard +"micromark-extension-frontmatter@npm:^2.0.0": + version: 2.0.0 + resolution: "micromark-extension-frontmatter@npm:2.0.0" + dependencies: + fault: "npm:^2.0.0" + micromark-util-character: "npm:^2.0.0" + micromark-util-symbol: "npm:^2.0.0" + micromark-util-types: "npm:^2.0.0" + checksum: 10c0/7d0d876e598917a67146d29f536d6fbbf9d1b2401a77e2f64a3f80f934a63ff26fa94b01759c9185c24b2a91e4e6abf908fa7aa246f00a7778a6b37a17464300 + languageName: node + linkType: hard + "micromark-extension-gfm-autolink-literal@npm:^2.0.0": version: 2.1.0 resolution: "micromark-extension-gfm-autolink-literal@npm:2.1.0" @@ -38728,7 +38761,7 @@ __metadata: languageName: node linkType: hard -"oxc-resolver@npm:^11.19.1": +"oxc-resolver@npm:11.24.2, oxc-resolver@npm:^11.19.1": version: 11.24.2 resolution: "oxc-resolver@npm:11.24.2" dependencies: @@ -42144,6 +42177,18 @@ __metadata: languageName: node linkType: hard +"remark-frontmatter@npm:5.0.0": + version: 5.0.0 + resolution: "remark-frontmatter@npm:5.0.0" + dependencies: + "@types/mdast": "npm:^4.0.0" + mdast-util-frontmatter: "npm:^2.0.0" + micromark-extension-frontmatter: "npm:^2.0.0" + unified: "npm:^11.0.0" + checksum: 10c0/102325d5edbcf30eaf74de8a0a6e03096cc2370dfef19080fd2dd208f368fbb2323388751ac9931a1aa38a4f2828fa4bad6c52dc5249dcadcd34861693b52bf9 + languageName: node + linkType: hard + "remark-gfm@npm:4.0.1, remark-gfm@npm:^4.0.0, remark-gfm@npm:^4.0.1": version: 4.0.1 resolution: "remark-gfm@npm:4.0.1" @@ -48554,14 +48599,7 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^1.10.0": - version: 1.10.3 - resolution: "yaml@npm:1.10.3" - checksum: 10c0/c309ff85a0a569a981d71ab9cf0fef68672a16b9cdf40639d1c3b30034f6cd16ee428602bd6d64ecf006f8c8bee499023cac236538f79898aa99fb5db529a2ed - languageName: node - linkType: hard - -"yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0, yaml@npm:^2.9.1": +"yaml@npm:2.9.1, yaml@npm:^2.3.1, yaml@npm:^2.8.3, yaml@npm:^2.9.0, yaml@npm:^2.9.1": version: 2.9.1 resolution: "yaml@npm:2.9.1" bin: @@ -48570,6 +48608,13 @@ __metadata: languageName: node linkType: hard +"yaml@npm:^1.10.0": + version: 1.10.3 + resolution: "yaml@npm:1.10.3" + checksum: 10c0/c309ff85a0a569a981d71ab9cf0fef68672a16b9cdf40639d1c3b30034f6cd16ee428602bd6d64ecf006f8c8bee499023cac236538f79898aa99fb5db529a2ed + languageName: node + linkType: hard + "yargs-parser@npm:^21.1.1": version: 21.1.1 resolution: "yargs-parser@npm:21.1.1" From ec6b02716b340e827dd1f0a5e2fe0986128b9407 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 10:40:38 +0200 Subject: [PATCH 17/22] chore: clean up typescript docs linting --- .../sdk/typescript-docs/oxlint.config.ts | 5 +++- .../hashql/sdk/typescript-docs/src/Comment.ts | 28 +++++++++++-------- .../hashql/sdk/typescript-docs/src/Sources.ts | 5 ++-- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index e96a223ec0a..2b70ad30094 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -2,7 +2,10 @@ import { createConfig, defineConfig } from "@local/oxlint"; export default defineConfig({ extends: [ - createConfig({ runtime: "node", frameworks: ["react", "next", "effect", "vitest"] }), + createConfig({ + runtime: "node", + frameworks: ["react", "next", "effect", "vitest"], + }), ], ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], overrides: [ diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts index 71742bc7ae4..2995b56852f 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts @@ -63,6 +63,9 @@ const linkTagNames: ReadonlySet<string> = new Set([ const isUnparsedLink = (node: DocNode): node is DocInlineTag => node instanceof DocInlineTag && linkTagNames.has(node.tagName); +const isParagraph = (node: DocNode | undefined): node is DocParagraph => + node instanceof DocParagraph; + const text = (value: string): PhrasingContent => ({ type: "text", value }); const inlineCode = (value: string): PhrasingContent => ({ @@ -200,7 +203,7 @@ export const lead = ( ): Effect.Effect<PhrasingContent[], TransformError, Links> => pipe( Array.head(comment.summarySection.getChildNodes()), - Option.filter((node) => node instanceof DocParagraph), + Option.filter(isParagraph), Option.match({ onNone: () => Effect.succeed([]), onSome: paragraph, @@ -214,8 +217,12 @@ export const blocksTagged: { } = Function.dual( 2, (comment: DocComment, tagName: string): readonly DocBlock[] => - comment.customBlocks.filter( - ({ blockTag }) => blockTag.tagNameWithUpperCase === tagName.toUpperCase(), + pipe( + comment.customBlocks, + Array.filter( + ({ blockTag }) => + blockTag.tagNameWithUpperCase === String.toUpperCase(tagName), + ), ), ); @@ -224,8 +231,8 @@ export const words = (node: DocSection): string => pipe( node.getChildNodes(), Array.filterMap(Filter.instanceOf(DocParagraph)), - Array.flatMap((paragraph_) => - DocNodeTransforms.trimSpacesInParagraph(paragraph_).getChildNodes(), + Array.flatMap((node) => + DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(), ), Array.map((child) => Match.value(child).pipe( @@ -241,7 +248,7 @@ export const words = (node: DocSection): string => // The space after a block tag and the line breaks before its content parse as text of their own. const isBlank = (node: DocNode): boolean => node instanceof DocSoftBreak || - (node instanceof DocPlainText && node.text.trim() === ""); + (node instanceof DocPlainText && String.isEmpty(String.trim(node.text))); const paragraphOf = ( configuration: DocParagraph["configuration"], @@ -258,14 +265,11 @@ const isCaption = (node: DocNode): boolean => node instanceof tag && node.name === "caption"; -const isParagraph = (node: DocNode | undefined): node is DocParagraph => - node instanceof DocParagraph; - // JSDoc's `<caption>` opens the first paragraph of an example. Everything after the caption is ordinary content. export const example = ( - example_: DocBlock, + node: DocBlock, ): Effect.Effect<Example, TransformError, Links> => { - const [first, ...rest] = example_.content.getChildNodes(); + const [first, ...rest] = node.content.getChildNodes(); const caption = pipe( Option.liftPredicate(first, isParagraph), Option.flatMap((opening) => { @@ -296,7 +300,7 @@ export const example = ( return Option.match(caption, { onNone: () => - section(example_.content).pipe( + section(node.content).pipe( Effect.map((content): Example => ({ caption: [], content })), ), onSome: ({ title, remainder }) => diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts index 2ffeaccb6c2..9743d5abfbe 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts @@ -9,6 +9,7 @@ import { Layer, Option, Record, + String, pipe, } from "effect"; import { print } from "esrap"; @@ -247,8 +248,8 @@ const commentRange = ( if ( lineEnd !== -1 && - text.slice(lineStart, comment.start).trim() === "" && - text.slice(comment.end, lineEnd).trim() === "" + String.isEmpty(String.trim(text.slice(lineStart, comment.start))) && + String.isEmpty(String.trim(text.slice(comment.end, lineEnd))) ) { return { start: lineStart, end: lineEnd + 1 }; } From 3640f6960d6a13bc0857fef349ffcb0c98b4d897 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:28:13 +0200 Subject: [PATCH 18/22] refactor: adapt typescript docs to effect 4.0.0 --- .../docs/task-dependencies.json | 48 +++- .../sdk/typescript-docs/src/Analysis.ts | 93 ++++--- .../sdk/typescript-docs/src/Comment.test.ts | 231 +++++++++--------- .../hashql/sdk/typescript-docs/src/Comment.ts | 122 ++++----- .../hashql/sdk/typescript-docs/src/Site.ts | 1 - .../sdk/typescript-docs/src/Sources.test.ts | 222 ++++++++--------- .../hashql/sdk/typescript-docs/src/Sources.ts | 1 - .../sdk/typescript-docs/src/TransformError.ts | 15 +- 8 files changed, 395 insertions(+), 338 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json index 4102badd337..3a1f8960f0d 100644 --- a/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json +++ b/libs/@local/hashql/sdk/typescript-docs/docs/task-dependencies.json @@ -7,15 +7,45 @@ ], "tasks": { "build": { - "dependsOn": [] + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ], + "env": [ + "NEXT_TELEMETRY_DISABLED" + ] }, "codegen": { - "dependsOn": [] + "dependsOn": [ + "doc:transform" + ] }, "dev": { - "dependsOn": [], + "dependsOn": [ + "@local/hashql#build", + "@local/oxlint#build", + "codegen" + ], "cache": false, - "persistent": true + "persistent": true, + "env": [ + "NEXT_TELEMETRY_DISABLED", + "PORT" + ] + }, + "doc:analyze": { + "dependsOn": [ + "doc:declarations" + ] + }, + "doc:declarations": { + "dependsOn": [] + }, + "doc:transform": { + "dependsOn": [ + "doc:analyze" + ] }, "lint:oxlint": { "dependsOn": [ @@ -32,9 +62,15 @@ ] }, "start": { - "dependsOn": [], + "dependsOn": [ + "build" + ], "cache": false, - "persistent": true + "persistent": true, + "env": [ + "NEXT_TELEMETRY_DISABLED", + "PORT" + ] }, "test:unit": { "dependsOn": [], diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts index fcbdb0966b1..4fdd4b164b0 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts @@ -1,4 +1,3 @@ -// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem and Path are unstable import { ApiDeclaredItem, ApiModel } from "@microsoft/api-extractor-model"; import { TSDocConfiguration, TSDocParser } from "@microsoft/tsdoc"; import { TSDocConfigFile } from "@microsoft/tsdoc-config"; @@ -11,7 +10,10 @@ import { Layer, Option, Path, + Result, Schema, + Struct, + flow, pipe, } from "effect"; @@ -71,14 +73,15 @@ export interface Options { } const loadEntry = Effect.fnUntraced(function* (file: string) { - const apiPackage = yield* Effect.try({ - try: () => new ApiModel().loadPackage(file), - catch: (cause) => TransformError.malformedAnalysis(String(cause)), - }); + const apiPackage = yield* Effect.try(() => + new ApiModel().loadPackage(file), + ).pipe( + Effect.mapError((cause) => TransformError.unreadableModel(file, cause)), + ); - const entry = yield* Effect.fromOption( + const entry = yield* pipe( Array.head(apiPackage.entryPoints), - ).pipe( + Effect.fromOption, Effect.mapError(() => TransformError.malformedAnalysis("The API model has no entry point"), ), @@ -103,38 +106,50 @@ const loadParser = Effect.fnUntraced(function* (lib: string) { return new TSDocParser(configuration); }); -const sourceOfDeclaration = Effect.fnUntraced(function* (declaration: string) { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const mapPath = `${declaration}.map`; - const text = yield* fs - .readFileString(mapPath) - .pipe(Effect.mapError(TransformError.fileSystem)); - const map = yield* Schema.decodeEffect(DeclarationMap)(text).pipe( - Effect.mapError((cause) => - TransformError.malformedSourceMap(mapPath, cause), - ), - ); +const sourceOfDeclaration = Effect.fnUntraced( + function* (declaration: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; - return path.resolve( - path.dirname(mapPath), - map.sourceRoot ?? "", - map.sources[0], - ); -}); + const mapPath = `${declaration}.map`; + const text = yield* fs.readFileString(mapPath); + + const map = yield* Schema.decodeEffect(DeclarationMap)(text).pipe( + Effect.mapError((cause) => + TransformError.malformedSourceMap(mapPath, cause), + ), + ); + + return path.resolve( + path.dirname(mapPath), + map.sourceRoot ?? "", + map.sources[0], + ); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); // `analyze` writes one `export * from` for each declaration file it receives, and each file's map names its source. const loadRoots = Effect.fnUntraced(function* (entryFile: string) { const sources = yield* Sources; const declarations = yield* pipe( - (yield* sources.scope(entryFile)).wildcards, - Effect.forEach((specifier) => - Effect.fromOption(sources.resolve(entryFile, specifier)).pipe( - Effect.mapError(() => - TransformError.malformedAnalysis( - `${entryFile} re-exports ${specifier}, which does not exist`, - ), + sources.scope(entryFile), + Effect.map(Struct.get("wildcards")), + Effect.flatMap( + flow( + Array.map((specifier) => + sources + .resolve(entryFile, specifier) + .pipe( + Result.fromOption(() => + TransformError.malformedAnalysis( + `${entryFile} re-exports ${specifier}, which does not exist`, + ), + ), + ), ), + Result.all, + Effect.fromResult, ), ), ); @@ -147,7 +162,7 @@ const loadRoots = Effect.fnUntraced(function* (entryFile: string) { return { declaration: Array.headNonEmpty(declarations), - sources: yield* pipe(declarations, Effect.forEach(sourceOfDeclaration)), + sources: yield* Effect.forEach(declarations, sourceOfDeclaration), }; }); @@ -184,12 +199,14 @@ export const layer = ({ declarationExtensions, ([candidate]) => relative.endsWith(candidate), ).pipe(Option.getOrElse(() => ["", ".d.ts"] as const)); + const declaration = path.join( path.dirname(roots.declaration), `${relative.slice(0, relative.length - extension.length)}${emitted}`, ); - if ((yield* sourceOfDeclaration(declaration)) !== source) { + const declSource = yield* sourceOfDeclaration(declaration); + if (declSource !== source) { return yield* TransformError.malformedAnalysis( `${declaration} was not emitted from ${source}`, ); @@ -216,10 +233,10 @@ export const layer = ({ moduleComment: (source) => sources.scope(source).pipe( Effect.map(({ comments, text }) => - Array.findFirst(comments, (comment) => - pipe( - Option.some(comment), - Option.filter(({ value }) => value.startsWith("*")), + Array.findFirst( + comments, + flow( + Option.liftPredicate(({ value }) => value.startsWith("*")), Option.map( ({ start, end }) => parser.parseString(text.slice(start, end)).docComment, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts index a71c5b08f67..275d7be27ab 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.test.ts @@ -1,3 +1,4 @@ +import { describe, expect, layer } from "@effect/vitest"; import { StandardTags, TSDocConfiguration, @@ -5,12 +6,10 @@ import { TSDocTagDefinition, TSDocTagSyntaxKind, } from "@microsoft/tsdoc"; -import { Array, Effect, Option, pipe } from "effect"; -import { describe, expect, test } from "vitest"; +import { Array, Effect, Layer, Option, pipe } from "effect"; import * as Comment from "./Comment.js"; -import type { TransformError } from "./TransformError.js"; import type { DocBlock, DocComment } from "@microsoft/tsdoc"; // The SDK's `tsdoc.json` defines `@since`, and the analysis parses with it. @@ -34,138 +33,136 @@ const parse = (lines: readonly string[]): DocComment => ), ).docComment; -const firstExample = (lines: readonly string[]): DocBlock => +const firstExample = (lines: readonly string[]): Effect.Effect<DocBlock> => pipe( Comment.blocksTagged(parse(lines), StandardTags.example.tagName), Array.head, Effect.fromOption, Effect.orDie, - Effect.runSync, ); // Only `Known` names something on a page. -const convert = <A>( - effect: Effect.Effect<A, TransformError, Comment.Links>, -): A => - effect.pipe( - Effect.provideService( - Comment.Links, - Comment.Links.of({ - resolve: (reference) => - Effect.succeed( - Option.liftPredicate( - "/docs/known", - () => reference.emitAsTsdoc() === "Known", - ), - ), - }), - ), - Effect.orDie, - Effect.runSync, - ); - -describe("comment", () => { - test("summary_links", () => { - expect.hasAssertions(); - const blocks = convert( - Comment.section( - parse(["See {@link Known}, {@link Unknown} and {@link Known | this}."]) - .summarySection, +const links: Layer.Layer<Comment.Links> = Layer.succeed( + Comment.Links, + Comment.Links.of({ + resolve: (reference) => + Effect.succeed( + Option.liftPredicate( + "/docs/known", + () => reference.emitAsTsdoc() === "Known", + ), ), - ); + }), +); - expect(blocks).toStrictEqual([ - { - type: "paragraph", - children: [ - { type: "text", value: "See " }, +describe("comment", () => { + layer(links)((it) => { + it.effect("summary_links", () => + Effect.gen(function* () { + const blocks = yield* Comment.section( + parse([ + "See {@link Known}, {@link Unknown} and {@link Known | this}.", + ]).summarySection, + ); + + expect(blocks).toStrictEqual([ { - type: "link", - url: "/docs/known", - children: [{ type: "inlineCode", value: "Known" }], + type: "paragraph", + children: [ + { type: "text", value: "See " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: ", " }, + { type: "inlineCode", value: "Unknown" }, + { type: "text", value: " and " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "text", value: "this" }], + }, + { type: "text", value: "." }, + ], }, - { type: "text", value: ", " }, - { type: "inlineCode", value: "Unknown" }, - { type: "text", value: " and " }, + ]); + }), + ); + + it.effect("summary_unparsed_syntax", () => + Effect.gen(function* () { + const blocks = yield* Comment.section( + parse(["Accepts {a: 1} and links {@link type}."]).summarySection, + ); + + expect(blocks).toStrictEqual([ { - type: "link", - url: "/docs/known", - children: [{ type: "text", value: "this" }], + type: "paragraph", + children: [ + { type: "text", value: "Accepts " }, + { type: "text", value: "{" }, + { type: "text", value: "a: 1" }, + { type: "text", value: "}" }, + { type: "text", value: " and links " }, + { type: "inlineCode", value: "type" }, + { type: "text", value: "." }, + ], }, - { type: "text", value: "." }, - ], - }, - ]); - }); - - test("summary_unparsed_syntax", () => { - expect.hasAssertions(); - const blocks = convert( - Comment.section( - parse(["Accepts {a: 1} and links {@link type}."]).summarySection, - ), + ]); + }), ); - expect(blocks).toStrictEqual([ - { - type: "paragraph", - children: [ - { type: "text", value: "Accepts " }, - { type: "text", value: "{" }, - { type: "text", value: "a: 1" }, - { type: "text", value: "}" }, - { type: "text", value: " and links " }, - { type: "inlineCode", value: "type" }, - { type: "text", value: "." }, - ], - }, - ]); - }); - - test("example_caption", () => { - expect.hasAssertions(); - const example = firstExample([ - "Summary.", - "", - "@example <caption>Build a {@link Known}.</caption>", - "```ts", - "const value = 1;", - "```", - ]); - - expect(convert(Comment.example(example))).toStrictEqual({ - caption: [ - { type: "text", value: "Build a " }, - { - type: "link", - url: "/docs/known", - children: [{ type: "inlineCode", value: "Known" }], - }, - { type: "text", value: "." }, - ], - content: [{ type: "code", lang: "ts", value: "const value = 1;" }], - }); - }); + it.effect("example_caption", () => + Effect.gen(function* () { + const example = yield* firstExample([ + "Summary.", + "", + "@example <caption>Build a {@link Known}.</caption>", + "```ts", + "const value = 1;", + "```", + ]); + + expect(yield* Comment.example(example)).toStrictEqual({ + caption: [ + { type: "text", value: "Build a " }, + { + type: "link", + url: "/docs/known", + children: [{ type: "inlineCode", value: "Known" }], + }, + { type: "text", value: "." }, + ], + content: [{ type: "code", lang: "ts", value: "const value = 1;" }], + }); + }), + ); - test("example_without_caption", () => { - expect.hasAssertions(); - const example = firstExample(["@example", "```", "plain", "```"]); + it.effect("example_without_caption", () => + Effect.gen(function* () { + const example = yield* firstExample([ + "@example", + "```", + "plain", + "```", + ]); + + expect(yield* Comment.example(example)).toStrictEqual({ + caption: [], + content: [{ type: "code", lang: null, value: "plain" }], + }); + }), + ); - expect(convert(Comment.example(example))).toStrictEqual({ - caption: [], - content: [{ type: "code", lang: null, value: "plain" }], + it("words", () => { + expect( + pipe( + Comment.blocksTagged(parse(["@since `4.0.0` beta"]), "@since"), + Array.head, + Option.map(({ content }) => Comment.words(content)), + ), + ).toStrictEqual(Option.some("4.0.0 beta")); }); }); - - test("words", () => { - expect.hasAssertions(); - - expect( - pipe( - Comment.blocksTagged(parse(["@since `4.0.0` beta"]), "@since"), - Array.head, - Option.map(({ content }) => Comment.words(content)), - ), - ).toStrictEqual(Option.some("4.0.0 beta")); - }); }); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts index 2995b56852f..1d90aa06116 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts @@ -22,6 +22,8 @@ import { Match, Option, String, + Tuple, + flow, pipe, } from "effect"; @@ -84,19 +86,23 @@ const linkLabel = (tag: DocLinkTag): PhrasingContent => { }; const destination = Effect.fnUntraced(function* (tag: DocLinkTag) { + const links = yield* Links; + if (tag.urlDestination !== undefined) { return Option.some(tag.urlDestination); } if (tag.codeDestination !== undefined) { - return yield* (yield* Links).resolve(tag.codeDestination); + return yield* links.resolve(tag.codeDestination); } return Option.none<string>(); }); const link = (tag: DocLinkTag): Effect.Effect<PhrasingContent, never, Links> => - destination(tag).pipe( + pipe( + tag, + destination, Effect.map( Option.match({ onNone: () => linkLabel(tag), @@ -110,10 +116,10 @@ const link = (tag: DocLinkTag): Effect.Effect<PhrasingContent, never, Links> => ); // TSDoc keeps the characters it could not parse as error text, and the analysis reports each at its source line. -const phrasing = ( +const phrasing: ( node: DocNode, -): Effect.Effect<PhrasingContent, TransformError, Links> => - Match.value(node).pipe( +) => Effect.Effect<PhrasingContent, TransformError, Links> = + Match.type<DocNode>().pipe( Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => Effect.succeed(text(value)), ), @@ -145,10 +151,10 @@ export const paragraph = ( Effect.forEach(phrasing), ); -const block = ( +const block: ( node: DocNode, -): Effect.Effect<BlockContent[], TransformError, Links> => - Match.value(node).pipe( +) => Effect.Effect<BlockContent[], TransformError, Links> = + Match.type<DocNode>().pipe( Match.when(Match.instanceOf(DocParagraph), (child) => paragraph(child).pipe( Effect.map((children): BlockContent[] => { @@ -177,10 +183,12 @@ const block = ( ); /** Converts block-level TSDoc nodes to mdast blocks. */ -export const blocks = ( +export const blocks: ( nodes: Iterable<DocNode>, -): Effect.Effect<BlockContent[], TransformError, Links> => - pipe(nodes, Effect.forEach(block), Effect.map(Array.flatten)); +) => Effect.Effect<BlockContent[], TransformError, Links> = flow( + Effect.forEach(block), + Effect.map(Array.flatten), +); /** Converts a TSDoc section to mdast blocks. */ export const section = ( @@ -192,17 +200,22 @@ export const section = ( export const overview = ( comment: DocComment, ): Effect.Effect<BlockContent[], TransformError, Links> => - Effect.all([ - section(comment.summarySection), - blocks(Array.fromNullishOr(comment.remarksBlock?.content)), - ]).pipe(Effect.map(Array.flatten)); + pipe( + [ + section(comment.summarySection), + blocks(Array.fromNullishOr(comment.remarksBlock?.content)), + ], + Effect.all, + Effect.map(Array.flatten), + ); /** The first paragraph of a comment's summary, which stands for it in a list. */ export const lead = ( comment: DocComment, ): Effect.Effect<PhrasingContent[], TransformError, Links> => pipe( - Array.head(comment.summarySection.getChildNodes()), + comment.summarySection.getChildNodes(), + Array.head, Option.filter(isParagraph), Option.match({ onNone: () => Effect.succeed([]), @@ -234,8 +247,8 @@ export const words = (node: DocSection): string => Array.flatMap((node) => DocNodeTransforms.trimSpacesInParagraph(node).getChildNodes(), ), - Array.map((child) => - Match.value(child).pipe( + Array.map( + Match.type<DocNode>().pipe( Match.when(Match.instanceOf(DocPlainText), ({ text: value }) => value), Match.when(Match.instanceOf(DocCodeSpan), ({ code }) => code), Match.orElse(() => " "), @@ -268,45 +281,42 @@ const isCaption = // JSDoc's `<caption>` opens the first paragraph of an example. Everything after the caption is ordinary content. export const example = ( node: DocBlock, -): Effect.Effect<Example, TransformError, Links> => { - const [first, ...rest] = node.content.getChildNodes(); - const caption = pipe( - Option.liftPredicate(first, isParagraph), - Option.flatMap((opening) => { - const nodes = opening.getChildNodes(); - - return Option.all({ - start: pipe( - nodes, - Array.findFirstIndex((node) => !isBlank(node)), - Option.filter((index) => - Array.get(nodes, index).pipe( - Option.exists(isCaption(DocHtmlStartTag)), - ), - ), +): Effect.Effect<Example, TransformError, Links> => + Option.gen(function* () { + const [first, ...rest] = node.content.getChildNodes(); + + const opening = yield* Option.liftPredicate(first, isParagraph); + const nodes = opening.getChildNodes(); + + const start = yield* pipe( + nodes, + Array.findFirstWithIndex((node) => !isBlank(node)), + Option.filter(([node]) => isCaption(DocHtmlStartTag)(node)), + Option.map(Tuple.get(1)), + ); + const end = yield* Array.findFirstIndex(nodes, isCaption(DocHtmlEndTag)); + + return { + title: paragraphOf(opening.configuration, nodes.slice(start + 1, end)), + remainder: paragraphOf(opening.configuration, nodes.slice(end + 1)), + }; + }).pipe( + Option.match({ + onNone: () => + pipe( + node.content, + section, + Effect.map((content): Example => ({ caption: [], content })), ), - end: pipe(nodes, Array.findFirstIndex(isCaption(DocHtmlEndTag))), - }).pipe( - Option.map(({ start, end }) => ({ - title: paragraphOf( - opening.configuration, - nodes.slice(start + 1, end), + onSome: ({ title, remainder }) => + Effect.all({ + caption: paragraph(title), + content: blocks( + Array.setHeadNonEmpty( + node.content.getChildNodes() as Array.NonEmptyArray<DocNode>, + remainder, + ), ), - remainder: paragraphOf(opening.configuration, nodes.slice(end + 1)), - })), - ); + }), }), ); - - return Option.match(caption, { - onNone: () => - section(node.content).pipe( - Effect.map((content): Example => ({ caption: [], content })), - ), - onSome: ({ title, remainder }) => - Effect.all({ - caption: paragraph(title), - content: blocks([remainder, ...rest]), - }), - }); -}; diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts index c87f0204721..13078fbe8d4 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -1,4 +1,3 @@ -// oxlint-disable effecttsgo/unstable-api-usage -- Path is unstable import { ApiItemContainerMixin, ApiItemKind, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts index ee4a6b2071e..b9eaa74eeb1 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts @@ -1,135 +1,123 @@ -// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem is unstable -// oxlint-disable effecttsgo/strict-effect-provide -- each test is an entry point that provides its own files +import { describe, expect, layer } from "@effect/vitest"; import { Effect, FileSystem, Layer, Option, Record } from "effect"; -import { describe, expect, test } from "vitest"; import * as Sources from "./Sources.js"; -// Each test reads only the files it names. Any other read is a defect in the test. -const read = <A, E>( - contents: Record.ReadonlyRecord<string, string>, - effect: (sources: Sources.Sources["Service"]) => Effect.Effect<A, E>, -): A => - Effect.flatMap(Effect.service(Sources.Sources), effect).pipe( - Effect.provide( - Sources.layer.pipe( - Layer.provide( - FileSystem.layerNoop({ - readFileString: (path) => - Effect.fromOption(Record.get(contents, path)).pipe(Effect.orDie), - }), - ), - ), - ), - Effect.orDie, - Effect.runSync, - ); +const files: Record.ReadonlyRecord<string, string> = { + "/scope.ts": [ + 'import * as Whole from "./whole.js";', + 'import { named as renamed } from "./named.js";', + 'import fallback from "./fallback.js";', + 'export * from "./everything.js";', + 'export * as Space from "./space.js";', + 'export { remote as published } from "./remote.js";', + "const local = 1;", + "export { local as alias };", + ].join("\n"), + "/overloads.d.ts": [ + "/** First overload. */", + "export declare function pick(value: string): string;", + "/** Second overload. */", + "export declare function pick(value: number): number;", + "export interface Shape {", + " /** The side length. */", + " readonly side: number; // trailing", + " readonly name: string;", + "}", + ].join("\n"), + "/alias.d.ts": [ + "declare function conditional(): void;", + "export { conditional as if, other as unrelated };", + 'export { ifElse as If, assume } from "./expression.js";', + ].join("\n"), + "/broken.ts": "export const = ;", +}; + +// A read of a file the fixtures do not name is a defect in the test. +const fixtures: Layer.Layer<Sources.Sources> = Sources.layer.pipe( + Layer.provide( + FileSystem.layerNoop({ + readFileString: (path) => + Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie), + }), + ), +); describe("sources", () => { - test("scope_bindings", () => { - expect.hasAssertions(); - const scope = read( - { - "/module.ts": [ - 'import * as Whole from "./whole.js";', - 'import { named as renamed } from "./named.js";', - 'import fallback from "./fallback.js";', - 'export * from "./everything.js";', - 'export * as Space from "./space.js";', - 'export { remote as published } from "./remote.js";', - "const local = 1;", - "export { local as alias };", - ].join("\n"), - }, - (sources) => sources.scope("/module.ts"), + layer(fixtures)((it) => { + it.effect("scope_bindings", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const scope = yield* sources.scope("/scope.ts"); + + expect(scope.imports).toStrictEqual({ + Whole: { specifier: "./whole.js", imported: Option.none() }, + renamed: { specifier: "./named.js", imported: Option.some("named") }, + fallback: { + specifier: "./fallback.js", + imported: Option.some("default"), + }, + }); + expect(scope.wildcards).toStrictEqual(["./everything.js"]); + expect(scope.namespaces).toStrictEqual({ Space: "./space.js" }); + expect(scope.reexports).toStrictEqual({ + published: { local: "remote", specifier: Option.some("./remote.js") }, + alias: { local: "local", specifier: Option.none() }, + }); + }), ); - expect(scope.imports).toStrictEqual({ - Whole: { specifier: "./whole.js", imported: Option.none() }, - renamed: { specifier: "./named.js", imported: Option.some("named") }, - fallback: { - specifier: "./fallback.js", - imported: Option.some("default"), - }, - }); - expect(scope.wildcards).toStrictEqual(["./everything.js"]); - expect(scope.namespaces).toStrictEqual({ Space: "./space.js" }); - expect(scope.reexports).toStrictEqual({ - published: { local: "remote", specifier: Option.some("./remote.js") }, - alias: { local: "local", specifier: Option.none() }, - }); - }); + it.effect("declarations_overloads", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const { local } = yield* sources.declarations("/overloads.d.ts"); - test("declarations_overloads", () => { - expect.hasAssertions(); - const { local } = read( - { - "/module.d.ts": [ - "/** First overload. */", - "export declare function pick(value: string): string;", - "/** Second overload. */", - "export declare function pick(value: number): number;", - "export interface Shape {", - " /** The side length. */", - " readonly side: number; // trailing", - " readonly name: string;", - "}", - ].join("\n"), - }, - (sources) => sources.declarations("/module.d.ts"), + expect(Record.get(local, "pick")).toStrictEqual( + Option.some([ + "export declare function pick(value: string): string;", + "export declare function pick(value: number): number;", + ]), + ); + expect(Record.get(local, "Shape")).toStrictEqual( + Option.some([ + [ + "export interface Shape {", + " readonly side: number; ", + " readonly name: string;", + "}", + ].join("\n"), + ]), + ); + }), ); - expect(Record.get(local, "pick")).toStrictEqual( - Option.some([ - "export declare function pick(value: string): string;", - "export declare function pick(value: number): number;", - ]), - ); - expect(Record.get(local, "Shape")).toStrictEqual( - Option.some([ - [ - "export interface Shape {", - " readonly side: number; ", - " readonly name: string;", - "}", - ].join("\n"), - ]), - ); - }); + it.effect("declarations_alias_export", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const { local, exports } = yield* sources.declarations("/alias.d.ts"); - test("declarations_alias_export", () => { - expect.hasAssertions(); - const { local, exports } = read( - { - "/module.d.ts": [ - "declare function conditional(): void;", - "export { conditional as if, other as unrelated };", - 'export { ifElse as If, assume } from "./expression.js";', - ].join("\n"), - }, - (sources) => sources.declarations("/module.d.ts"), + expect(Record.get(local, "conditional")).toStrictEqual( + Option.some(["declare function conditional(): void;"]), + ); + expect(Record.get(exports, "if")).toStrictEqual( + Option.some("export { conditional as if };"), + ); + expect(Record.get(exports, "If")).toStrictEqual( + Option.some('export { ifElse as If } from "./expression.js";'), + ); + }), ); - expect(Record.get(local, "conditional")).toStrictEqual( - Option.some(["declare function conditional(): void;"]), - ); - expect(Record.get(exports, "if")).toStrictEqual( - Option.some("export { conditional as if };"), - ); - expect(Record.get(exports, "If")).toStrictEqual( - Option.some('export { ifElse as If } from "./expression.js";'), - ); - }); + it.effect("syntax_error", () => + Effect.gen(function* () { + const sources = yield* Sources.Sources; + const error = yield* Effect.flip(sources.scope("/broken.ts")); - test("syntax_error", () => { - expect.hasAssertions(); - const error = read({ "/broken.ts": "export const = ;" }, (sources) => - Effect.flip(sources.scope("/broken.ts")), + expect(error.reason).toMatchObject({ + _tag: "SourceSyntax", + file: "/broken.ts", + }); + }), ); - - expect(error.reason).toMatchObject({ - _tag: "SourceSyntax", - file: "/broken.ts", - }); }); }); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts index 9743d5abfbe..6bab1765fd4 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts @@ -1,4 +1,3 @@ -// oxlint-disable effecttsgo/unstable-api-usage -- FileSystem is unstable import { Array, Cache, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts index e521a88a29d..48a1ee490c6 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts @@ -1,7 +1,6 @@ -// oxlint-disable effecttsgo/unstable-api-usage -- PlatformError is unstable import { Data } from "effect"; -import type { Schema } from "effect"; +import type { Cause, Schema } from "effect"; import type { PlatformError } from "effect/PlatformError"; /** Why building the reference pages failed. */ @@ -15,6 +14,11 @@ export type Reason = Data.TaggedEnum<{ readonly file: string; readonly cause: Schema.SchemaError; }; + /** API Extractor could not load the API model the analysis wrote. */ + UnreadableModel: { + readonly file: string; + readonly cause: Cause.UnknownError; + }; /** The analysis output lacks something a page needs. */ MalformedAnalysis: { readonly detail: string }; /** A documentation comment uses TSDoc syntax the pages have no rendering for. */ @@ -48,6 +52,12 @@ export class TransformError extends TransformErrorBase<{ ): TransformError => new TransformError({ reason: Reason.MalformedSourceMap({ file, cause }) }); + static readonly unreadableModel = ( + file: string, + cause: Cause.UnknownError, + ): TransformError => + new TransformError({ reason: Reason.UnreadableModel({ file, cause }) }); + static readonly malformedAnalysis = (detail: string): TransformError => new TransformError({ reason: Reason.MalformedAnalysis({ detail }) }); @@ -60,6 +70,7 @@ export class TransformError extends TransformErrorBase<{ SourceSyntax: ({ file, messages }) => `${file} does not parse: ${messages.join("; ")}`, MalformedSourceMap: ({ file, cause }) => `${file}: ${cause.message}`, + UnreadableModel: ({ file, cause }) => `${file}: ${cause.message}`, MalformedAnalysis: ({ detail }) => detail, UnsupportedComment: ({ kind }) => `Documentation comments use ${kind}, which the reference pages cannot render`, From a897a45e6d7f9fe56cae8f96b02bff92b3499fc7 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:43:58 +0200 Subject: [PATCH 19/22] feat: build HashQL TypeScript docs site --- .../hashql/sdk/typescript-docs/.gitignore | 3 - .../typescript-docs/app/api/search/route.ts | 5 + .../app/docs/[[...slug]]/page.tsx | 56 +++ .../sdk/typescript-docs/app/docs/layout.tsx | 19 + .../hashql/sdk/typescript-docs/app/global.css | 15 + .../hashql/sdk/typescript-docs/app/layout.tsx | 21 + .../hashql/sdk/typescript-docs/app/page.tsx | 5 + .../sdk/typescript-docs/components/mdx.tsx | 16 + .../components/reference-trigger.tsx | 25 ++ .../typescript-docs/lib/reference-links.ts | 88 ++++ .../hashql/sdk/typescript-docs/lib/source.ts | 8 + .../sdk/typescript-docs/next.config.mjs | 10 + .../sdk/typescript-docs/oxlint.config.ts | 18 +- .../hashql/sdk/typescript-docs/package.json | 3 - .../sdk/typescript-docs/postcss.config.mjs | 2 + .../sdk/typescript-docs/source.config.ts | 22 +- .../sdk/typescript-docs/src/Analysis.ts | 6 +- .../sdk/typescript-docs/src/CodeBlock.test.ts | 82 ++++ .../sdk/typescript-docs/src/CodeBlock.ts | 119 ++++++ .../hashql/sdk/typescript-docs/src/Comment.ts | 17 +- .../hashql/sdk/typescript-docs/src/Member.ts | 224 ++++++---- .../hashql/sdk/typescript-docs/src/Page.ts | 102 +++-- .../sdk/typescript-docs/src/References.ts | 288 +++++++++++++ .../sdk/typescript-docs/src/Signature.test.ts | 148 +++++++ .../sdk/typescript-docs/src/Signature.ts | 222 ++++++---- .../hashql/sdk/typescript-docs/src/Site.ts | 390 +++++++++--------- .../sdk/typescript-docs/src/Sources.test.ts | 73 +++- .../hashql/sdk/typescript-docs/src/Sources.ts | 336 +++++---------- .../sdk/typescript-docs/src/Statements.ts | 251 +++++++++++ .../sdk/typescript-docs/src/Transform.ts | 70 ++-- .../sdk/typescript-docs/src/TransformError.ts | 23 ++ yarn.lock | 24 +- 32 files changed, 1952 insertions(+), 739 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/global.css create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/layout.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/app/page.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/lib/source.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/next.config.mjs create mode 100644 libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/References.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Statements.ts diff --git a/libs/@local/hashql/sdk/typescript-docs/.gitignore b/libs/@local/hashql/sdk/typescript-docs/.gitignore index 3d789702d9f..7497a23afd3 100644 --- a/libs/@local/hashql/sdk/typescript-docs/.gitignore +++ b/libs/@local/hashql/sdk/typescript-docs/.gitignore @@ -1,7 +1,4 @@ .generated/ -.next/ .source/ .twoslash/ -*.tsbuildinfo content/docs/reference/ -lib/reference-links.json diff --git a/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts new file mode 100644 index 00000000000..222bd15cb4e --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/api/search/route.ts @@ -0,0 +1,5 @@ +import { createFromSource } from "fumadocs-core/search/server"; + +import { source } from "../../../lib/source"; + +export const { GET } = createFromSource(source, { language: "english" }); diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx new file mode 100644 index 00000000000..d469bcf64c3 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/[[...slug]]/page.tsx @@ -0,0 +1,56 @@ +import { + DocsBody, + DocsDescription, + DocsPage, + DocsTitle, +} from "fumadocs-ui/layouts/docs/page"; +import { createRelativeLink } from "fumadocs-ui/mdx"; +import { notFound } from "next/navigation"; + +import { getMDXComponents } from "../../../components/mdx"; +import { source } from "../../../lib/source"; + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; + +interface PageProps { + params: Promise<{ slug?: string[] }>; +} + +export default async function Page({ params }: PageProps): Promise<ReactNode> { + const { slug } = await params; + const page = source.getPage(slug); + if (page === undefined) { + notFound(); + } + const Content = page.data.body; + const components = getMDXComponents({ + // oxlint-disable-next-line id-length -- MDX uses HTML tag names as component keys. + a: createRelativeLink(source, page), + }); + return ( + <DocsPage toc={page.data.toc} full={page.data.full}> + <DocsTitle>{page.data.title}</DocsTitle> + <DocsDescription>{page.data.description}</DocsDescription> + {/* Qualified type names may be longer than the mobile viewport. */} + {/* oxlint-disable-next-line react/forbid-component-props -- DocsBody exposes className for content layout. */} + <DocsBody className="[&_h2]:wrap-anywhere"> + <Content components={components} /> + </DocsBody> + </DocsPage> + ); +} + +export const generateStaticParams = (): { slug: string[] }[] => + source.generateParams(); + +export const generateMetadata = async ({ + params, +}: PageProps): Promise<Metadata> => { + const { slug } = await params; + const page = source.getPage(slug); + if (page === undefined) { + notFound(); + } + return { title: page.data.title, description: page.data.description }; +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx new file mode 100644 index 00000000000..432adfdef2f --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/docs/layout.tsx @@ -0,0 +1,19 @@ +import { DocsLayout } from "fumadocs-ui/layouts/docs"; + +import { source } from "../../lib/source"; + +import type { ReactNode } from "react"; + +const navigation = { title: "HashQL TypeScript", url: "/docs" }; + +export default function Layout({ + children, +}: { + children: ReactNode; +}): ReactNode { + return ( + <DocsLayout tree={source.getPageTree()} nav={navigation}> + {children} + </DocsLayout> + ); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/global.css b/libs/@local/hashql/sdk/typescript-docs/app/global.css new file mode 100644 index 00000000000..08609751b30 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/global.css @@ -0,0 +1,15 @@ +@import "tailwindcss"; +@import "fumadocs-ui/css/neutral.css"; +@import "fumadocs-ui/css/preset.css"; +@import "fumadocs-twoslash/twoslash.css"; + +/* A name that links to its documentation is underlined, whether or not Twoslash gives it a hover. */ +.twoslash a[href] { + text-decoration-line: underline; + text-decoration-color: color-mix(in oklab, currentColor 35%, transparent); + text-underline-offset: 0.25em; +} + +.twoslash a[href]:hover { + text-decoration-color: currentColor; +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx new file mode 100644 index 00000000000..3efe419aa02 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/layout.tsx @@ -0,0 +1,21 @@ +import { RootProvider } from "fumadocs-ui/provider/next"; + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; +import "./global.css"; + +export const metadata: Metadata = { title: "HashQL TypeScript" }; + +export default function Layout({ + children, +}: { + children: ReactNode; +}): ReactNode { + return ( + <html lang="en" suppressHydrationWarning> + <body className="flex min-h-screen flex-col"> + <RootProvider>{children}</RootProvider> + </body> + </html> + ); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/app/page.tsx b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx new file mode 100644 index 00000000000..03812238ab7 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/app/page.tsx @@ -0,0 +1,5 @@ +import { redirect } from "next/navigation"; + +export default function Home(): never { + redirect("/docs"); +} diff --git a/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx new file mode 100644 index 00000000000..1e0062fb6fc --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx @@ -0,0 +1,16 @@ +import { Popup, PopupContent } from "fumadocs-twoslash/ui"; +import defaultComponents from "fumadocs-ui/mdx"; + +import { ReferenceTrigger } from "./reference-trigger"; + +import type { MDXComponents } from "mdx/types"; + +export const getMDXComponents = ( + components?: MDXComponents, +): MDXComponents => ({ + ...defaultComponents, + Popup, + PopupContent, + PopupTrigger: ReferenceTrigger, + ...components, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx new file mode 100644 index 00000000000..c9e72bf392a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/reference-trigger.tsx @@ -0,0 +1,25 @@ +"use client"; + +import { PopupTrigger } from "fumadocs-twoslash/ui"; + +import type { ComponentProps, ReactNode } from "react"; + +export const ReferenceTrigger = ({ + href, + ...props +}: ComponentProps<typeof PopupTrigger> & { href?: string }): ReactNode => { + if (href === undefined) { + return <PopupTrigger {...props} />; + } + return ( + <PopupTrigger + {...props} + nativeButton={false} + render={ + <a href={href} role="link"> + {props.children} + </a> + } + /> + ); +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts new file mode 100644 index 00000000000..86ce5c31f11 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/lib/reference-links.ts @@ -0,0 +1,88 @@ +import { Array, Effect, Option, Struct, flow, pipe } from "effect"; +import { splitTokens } from "shiki/core"; + +import * as CodeBlock from "../src/CodeBlock.js"; + +import type { Element, ElementContent } from "hast"; +import type { ShikiTransformer } from "shiki"; + +const isElement = (node: ElementContent): node is Element => + node.type === "element"; + +// A popup's content is the hover text, which holds no names of the code. +const triggerIn = (node: Element): Option.Option<Element> => + pipe( + node.children, + Array.filter(isElement), + Array.filter(({ tagName }) => tagName !== "PopupContent"), + Array.findFirst((child) => + pipe( + child, + Option.liftPredicate(({ tagName }) => tagName === "PopupTrigger"), + Option.orElse(() => triggerIn(child)), + ), + ), + ); + +// Twoslash has replaced a hovered name's text with its popup by now, so its trigger becomes the link and the hover stays. +const link = (node: Element): void => { + for (const child of Array.filter(node.children, isElement)) { + const url = child.properties["data-reference"]; + + if (typeof url === "string") { + delete child.properties["data-reference"]; + Option.match(triggerIn(child), { + onNone: () => { + child.tagName = "a"; + child.properties.href = url; + }, + onSome: (trigger) => { + trigger.properties.href = url; + }, + }); + } else { + link(child); + } + } +}; + +/** Links the names a signature block's meta lists to the pages that document them. Place it after the Twoslash transformer. */ +export const referenceLinks = (): ShikiTransformer => ({ + name: "hashql:reference-links", + tokens(lines) { + const code = pipe( + lines, + Array.map(flow(Array.map(Struct.get("content")), Array.join(""))), + Array.join("\n"), + ); + // A transformer runs synchronously inside Shiki, and a block whose links do not fit its code fails the build. + const links = Effect.runSync( + CodeBlock.place(code, this.options.meta?.__raw ?? ""), + ); + const split = splitTokens( + lines, + Array.flatMap(links, ({ start, end }) => [start, end]), + ); + + // Shiki copies a token's attributes onto the element it renders. + for (const token of Array.flatten(split)) { + const found = Array.findFirst( + links, + ({ start, end }) => + start <= token.offset && token.offset + token.content.length <= end, + ); + + if (Option.isSome(found)) { + token.htmlAttrs = { + ...token.htmlAttrs, + "data-reference": found.value.url, + }; + } + } + + return split; + }, + code(code) { + link(code); + }, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/lib/source.ts b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts new file mode 100644 index 00000000000..c0e7f60ee36 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/lib/source.ts @@ -0,0 +1,8 @@ +import { loader } from "fumadocs-core/source"; + +import { docs } from "../.source/server"; + +export const source = loader({ + baseUrl: "/docs", + source: docs.toFumadocsSource(), +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/next.config.mjs b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs new file mode 100644 index 00000000000..1439b40dd5a --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/next.config.mjs @@ -0,0 +1,10 @@ +import path from "node:path"; + +import { createMDX } from "fumadocs-mdx/next"; + +export default createMDX()({ + reactStrictMode: true, + serverExternalPackages: ["typescript"], + outputFileTracingRoot: path.resolve(import.meta.dirname, "../../../../.."), + devIndicators: false, +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index 2b70ad30094..7b3c39a369f 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -24,6 +24,13 @@ export default defineConfig({ ], }, }, + { + files: ["*.config.mjs", "source.config.ts"], + rules: { + "effecttsgo/node-builtin-import": "allow", // Next.js and Fumadocs load these modules outside any Effect runtime that could provide FileSystem or Path. + "effecttsgo/schema-sync": "allow", // Next.js and Fumadocs evaluate a configuration module synchronously, and a malformed input should fail its load. + }, + }, { files: ["app/**/*.tsx", "*.config.mjs"], rules: { @@ -37,6 +44,7 @@ export default defineConfig({ "react/jsx-filename-extension": ["deny", { extensions: [".tsx"] }], // This TypeScript app uses TSX. "react/only-export-components": "allow", // Next.js discovers metadata and static parameter exports. "oxc/no-async-await": "allow", // Server components await route parameters and syntax highlighting. + "effecttsgo/async-function": "allow", // Next.js calls server components and metadata functions as async functions. }, }, { @@ -48,12 +56,6 @@ export default defineConfig({ ], }, }, - { - files: ["components/reference.tsx"], - rules: { - "react/no-multi-comp": "allow", // The reference table shares plain and highlighted type renderers. - }, - }, { files: ["components/reference-trigger.tsx"], rules: { @@ -63,9 +65,9 @@ export default defineConfig({ }, }, { - files: ["lib/reference-twoslash.ts"], + files: ["lib/reference-links.ts"], rules: { - "no-underscore-dangle": ["deny", { allow: ["__raw"] }], // Shiki exposes fence metadata under this public field name. + "no-underscore-dangle": ["deny", { allow: ["__raw"] }], // Shiki exposes a code block's meta string under this public field name. }, }, { diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index 64cfce3611a..2f257e466a2 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -35,7 +35,6 @@ "@effect/vitest": "4.0.0", "@local/oxlint": "workspace:*", "@local/tsconfig": "workspace:*", - "@microsoft/api-documenter": "7.30.18", "@microsoft/api-extractor": "7.59.4", "@microsoft/api-extractor-model": "7.33.15", "@microsoft/tsdoc": "0.17.1", @@ -49,14 +48,12 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "effect": "4.0.0", - "esrap": "2.4.0", "oxc-parser": "0.152.0", "oxc-resolver": "11.24.2", "oxfmt": "0.71.0", "oxlint": "catalog:", "remark-frontmatter": "5.0.0", "remark-mdx": "3.1.1", - "remark-parse": "11.0.0", "remark-stringify": "11.0.0", "shiki": "4.5.0", "tailwindcss": "4.3.3", diff --git a/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs new file mode 100644 index 00000000000..d062fcdae9d --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/postcss.config.mjs @@ -0,0 +1,2 @@ +const config = { plugins: { "@tailwindcss/postcss": {} } }; +export default config; diff --git a/libs/@local/hashql/sdk/typescript-docs/source.config.ts b/libs/@local/hashql/sdk/typescript-docs/source.config.ts index 1fceb81368c..a6732606197 100644 --- a/libs/@local/hashql/sdk/typescript-docs/source.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/source.config.ts @@ -1,8 +1,21 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { Schema } from "effect"; import { rehypeCodeDefaultOptions } from "fumadocs-core/mdx-plugins"; import { defineConfig, defineDocs } from "fumadocs-mdx/config"; import { transformerTwoslash } from "fumadocs-twoslash"; -import { referenceTwoslash } from "./lib/reference-twoslash"; +import { referenceLinks } from "./lib/reference-links.js"; + +// Signature blocks compile against the declaration files `doc:declarations` emits, which they name through `#declarations/`. +const ApiConfig = Schema.fromJsonString( + Schema.Struct({ compilerOptions: Schema.Struct({ outDir: Schema.String }) }), +); +const declarations = path.resolve( + Schema.decodeSync(ApiConfig)(readFileSync("tsconfig.api.json", "utf8")) + .compilerOptions.outDir, +); export const docs = defineDocs({ dir: "content/docs", @@ -21,12 +34,13 @@ export default defineConfig({ twoslashOptions: { compilerOptions: { types: ["node"], - module: "ESNext", - moduleResolution: "Bundler", + paths: { "#declarations/*": [`${declarations}/*`] }, }, }, + // Hovers show the compiler's types. The page beside them carries the documentation. + rendererRich: { jsdoc: false }, }), - referenceTwoslash(), + referenceLinks(), ], }, }, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts index 4fdd4b164b0..3c2c4a5599f 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts @@ -52,6 +52,8 @@ export class Analysis extends Context.Service< readonly entry: ApiEntryPoint; /** The source modules of the declaration files the analysis entry re-exports, in order. */ readonly roots: Array.NonEmptyReadonlyArray<string>; + /** The directory TypeScript emitted the declaration files into. The first root's file sits at its top, and the tree below mirrors the sources. */ + readonly declarationRoot: string; /** The source file that declares an item. */ readonly sourceOf: (item: ApiItem) => Option.Option<string>; /** The declaration file emitted from a source module. */ @@ -189,6 +191,7 @@ export const layer = ({ const parser = yield* loadParser(lib); const roots = yield* loadRoots(path.join(analysis, "api-entry.d.ts")); const rootSource = Array.headNonEmpty(roots.sources); + const declarationRoot = path.dirname(roots.declaration); // The emit mirrors the source tree, so the first root locates every other declaration file, and each one's map confirms it. const declarations = yield* Cache.make({ @@ -201,7 +204,7 @@ export const layer = ({ ).pipe(Option.getOrElse(() => ["", ".d.ts"] as const)); const declaration = path.join( - path.dirname(roots.declaration), + declarationRoot, `${relative.slice(0, relative.length - extension.length)}${emitted}`, ); @@ -220,6 +223,7 @@ export const layer = ({ package: apiPackage, entry, roots: roots.sources, + declarationRoot, sourceOf: (item) => { if (item instanceof ApiDeclaredItem) { return Option.fromNullishOr(item.fileUrlPath).pipe( diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts new file mode 100644 index 00000000000..be41254e7c0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "@effect/vitest"; +import { Effect, Option } from "effect"; + +import * as CodeBlock from "./CodeBlock.js"; + +const urls: readonly Option.Option<string>[] = [ + Option.some("/docs/reference/type/Type"), + Option.some('/docs/reference/type/Type#"quoted" and spaced'), + Option.none(), +]; + +describe("code_block", () => { + it.effect("urls_round_trip", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + + expect(yield* CodeBlock.urls(meta)).toStrictEqual(Option.some(urls)); + }), + ); + + // Fumadocs removes the attributes it knows and hands the rest to transformers. + it.effect("urls_beside_other_attributes", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + + expect( + yield* CodeBlock.urls(`title="Example" ${meta} lineNumbers`), + ).toStrictEqual(Option.some(urls)); + }), + ); + + it.effect("urls_absent", () => + Effect.gen(function* () { + expect(yield* CodeBlock.urls('twoslash title="Example"')).toStrictEqual( + Option.none(), + ); + }), + ); + + it.effect("urls_malformed", () => + Effect.gen(function* () { + const error = yield* Effect.flip(CodeBlock.urls('links="%5B%7B%7D%5D"')); + + expect(error.reason._tag).toBe("UnreadableCodeBlock"); + }), + ); + + // The formatter re-indents and wraps the code, and the names keep their order. + it.effect("place_after_formatting", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + const code = ["declare const value: Type.Any<", " Missing", ">;"].join( + "\n", + ); + + expect( + Array.from( + yield* CodeBlock.place(code, meta), + ({ start, end, url }) => [code.slice(start, end), url], + ), + ).toStrictEqual([ + ["Type", "/docs/reference/type/Type"], + ["Any", '/docs/reference/type/Type#"quoted" and spaced'], + ]); + }), + ); + + it.effect("place_misaligned", () => + Effect.gen(function* () { + const meta = yield* CodeBlock.meta(urls); + const error = yield* Effect.flip( + CodeBlock.place("declare const value: Type;", meta), + ); + + expect(error.reason).toMatchObject({ + _tag: "MisalignedCodeBlock", + references: 1, + links: 3, + }); + }), + ); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts new file mode 100644 index 00000000000..ee4eeca5017 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/CodeBlock.ts @@ -0,0 +1,119 @@ +/** + * The code blocks that show a member's signature. + * + * Twoslash compiles each block whole, so the declarations its hovers need sit above a cut, and the page shows only the statements below it. The block's meta lists, for each name the statements refer to and in their order, the URL that documents it. The docs site formats the code before it highlights it, so it finds the names again in the formatted code and pairs them with that list. + * + * @module + */ +import { Array, Effect, Filter, Function, Option, Schema, pipe } from "effect"; +import { parseCodeBlockAttributes } from "fumadocs-core/mdx-plugins/codeblock-utils"; + +import * as References from "./References.js"; +import { parse } from "./Sources.js"; +import { TransformError } from "./TransformError.js"; + +/** A span of the shown code that names a documented declaration, and the URL that documents it. */ +export interface Link { + readonly start: number; + readonly end: number; + readonly url: string; +} + +// `null` stands for a name that nothing on the site documents. +const Urls = Schema.fromJsonString( + Schema.Array(Schema.OptionFromNullOr(Schema.String)), +); + +const attribute = "links"; + +/** The line above which Twoslash compiles a block without showing it. */ +export const cut = "// ---cut---"; + +// Percent-encoding leaves the JSON without the quotes and spaces that would end the attribute. +/** A signature block's meta: Twoslash's trigger and, for each name the code refers to, its URL. */ +export const meta = ( + urls: readonly Option.Option<string>[], +): Effect.Effect<string, Schema.SchemaError> => + pipe( + urls, + Schema.encodeEffect(Urls), + Effect.map( + (encoded) => `twoslash ${attribute}="${encodeURIComponent(encoded)}"`, + ), + ); + +/** The URLs a code block's meta carries, `None` for a block that is not a signature. */ +export const urls = ( + blockMeta: string, +): Effect.Effect< + Option.Option<readonly Option.Option<string>[]>, + TransformError +> => + pipe( + parseCodeBlockAttributes(blockMeta, [attribute]).attributes[attribute], + Option.fromUndefinedOr, + Option.match({ + onNone: () => Effect.succeedNone, + onSome: (value) => + pipe( + value, + Schema.decodeUnknownEffect(Schema.String), + Effect.flatMap((encoded) => + Effect.try(() => decodeURIComponent(encoded)), + ), + Effect.flatMap(Schema.decodeEffect(Urls)), + Effect.mapError(TransformError.unreadableCodeBlock), + Effect.asSome, + ), + }), + ); + +const placeIn = ( + code: string, + blockMeta: string, +): Effect.Effect<readonly Link[], TransformError> => + pipe( + blockMeta, + urls, + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed([]), + onSome: (listed) => + pipe( + code, + parse("signature.d.ts"), + Effect.map(({ program }) => References.of(program)), + Effect.filterOrFail( + (references) => references.length === listed.length, + (references) => + TransformError.misalignedCodeBlock( + references.length, + listed.length, + ), + ), + Effect.map((references) => + Array.filterMap( + Array.zip(references, listed), + Filter.fromPredicateOption(([{ start, end }, url]) => + Option.map( + url, + (found): Link => ({ start, end, url: found }), + ), + ), + ), + ), + ), + }), + ), + ); + +/** Pairs a signature block's URLs, from its meta, with the names its shown code refers to, and keeps the names that have one. */ +export const place: { + ( + blockMeta: string, + ): (code: string) => Effect.Effect<readonly Link[], TransformError>; + ( + code: string, + blockMeta: string, + ): Effect.Effect<readonly Link[], TransformError>; +} = Function.dual(2, placeIn); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts index 1d90aa06116..3e603737f62 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Comment.ts @@ -298,7 +298,10 @@ export const example = ( return { title: paragraphOf(opening.configuration, nodes.slice(start + 1, end)), - remainder: paragraphOf(opening.configuration, nodes.slice(end + 1)), + content: [ + paragraphOf(opening.configuration, nodes.slice(end + 1)), + ...rest, + ], }; }).pipe( Option.match({ @@ -308,15 +311,7 @@ export const example = ( section, Effect.map((content): Example => ({ caption: [], content })), ), - onSome: ({ title, remainder }) => - Effect.all({ - caption: paragraph(title), - content: blocks( - Array.setHeadNonEmpty( - node.content.getChildNodes() as Array.NonEmptyArray<DocNode>, - remainder, - ), - ), - }), + onSome: ({ title, content }) => + Effect.all({ caption: paragraph(title), content: blocks(content) }), }), ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Member.ts b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts index bb450552a99..37ba54fc1ea 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Member.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Member.ts @@ -1,7 +1,18 @@ import { ApiDocumentedItem, ApiItemKind } from "@microsoft/api-extractor-model"; import { StandardTags } from "@microsoft/tsdoc"; -import { Array, Effect, Filter, Option, String, identity, pipe } from "effect"; +import { + Array, + Effect, + Filter, + Option, + Order, + String, + Struct, + Tuple, + pipe, +} from "effect"; +import * as CodeBlock from "./CodeBlock.js"; import * as Comment from "./Comment.js"; import type { TransformError } from "./TransformError.js"; @@ -14,12 +25,21 @@ import type { } from "@microsoft/tsdoc"; import type { BlockContent, Heading, ListItem, PhrasingContent } from "mdast"; +/** The statements declaring a member, as its code block shows them. */ +export interface Signature { + /** The statements, as TypeScript. */ + readonly code: string; + /** The rest of their declaration file, which the code block compiles them in and hides. */ + readonly context: string; + /** For each name the code refers to, in order, the URL that documents it. */ + readonly urls: readonly Option.Option<string>[]; +} + /** The declarations sharing one name in a container, with their source. */ export interface Member { /** Overloads in declaration order, or a merged interface and namespace. */ readonly items: Array.NonEmptyReadonlyArray<ApiItem>; - /** The statements declaring the member, as TypeScript. */ - readonly signature: string; + readonly signature: Signature; /** The anchor that links to an item on its page. */ readonly anchor: (item: ApiItem) => string; } @@ -38,6 +58,26 @@ const heading = (depth: Heading["depth"], anchor: string): BlockContent => ({ children: [{ type: "text", value: `${anchor} [#${anchor}]` }], }); +// Twoslash compiles the whole block for its hovers, and shows only what follows the cut. +const code = ({ + code: shown, + context, + urls, +}: Signature): Effect.Effect<BlockContent> => + pipe( + CodeBlock.meta(urls), + // Encoding values of the schema's own type cannot fail. + Effect.orDie, + Effect.map( + (meta): BlockContent => ({ + type: "code", + lang: "ts", + meta, + value: `${context}\n${CodeBlock.cut}\n${shown}`, + }), + ), + ); + // A label opens the first paragraph of the content it introduces, or stands alone before a code block. const labelled = ( label: PhrasingContent, @@ -58,16 +98,16 @@ const labelled = ( return [{ type: "paragraph", children: [label] }, ...content]; }; -const commentOf = (item: ApiItem): Option.Option<DocComment> => { - if (item instanceof ApiDocumentedItem) { - return Option.fromNullishOr(item.tsdocComment); - } - - return Option.none(); -}; - const comments = (items: readonly ApiItem[]): DocComment[] => - Array.filterMap(items, Filter.fromPredicateOption(commentOf)); + pipe( + items, + Array.filterMap(Filter.instanceOf(ApiDocumentedItem)), + Array.filterMap( + Filter.fromPredicateOption(({ tsdocComment }) => + Option.fromNullishOr(tsdocComment), + ), + ), + ); const kindLabels: readonly (readonly [ApiItemKind, string])[] = [ [ApiItemKind.Function, "Functions"], @@ -88,34 +128,32 @@ export const group = (items: Array.NonEmptyReadonlyArray<ApiItem>): string => ), Option.map((block) => Comment.words(block.content)), Option.orElse(() => - Array.findFirst( + pipe( kindLabels, - ([kind]) => kind === Array.headNonEmpty(items).kind, - ).pipe(Option.map(([, label]) => label)), + Array.findFirst(([kind]) => kind === Array.headNonEmpty(items).kind), + Option.map(Tuple.get(1)), + ), ), Option.getOrElse(() => "Other"), ); -/** Orders group headings: authored categories alphabetically, then kinds in a fixed order. */ -export const groupOrder = (labels: Iterable<string>): string[] => { - const present = Array.dedupe(labels); - const kinds = pipe( +// An authored category ranks before every kind, so categories sort among themselves by name. +const kindRank = (label: string): number => + pipe( kindLabels, - Array.map(([, label]) => label), + Array.findFirstIndex(([, kind]) => kind === label), + Option.getOrElse(() => -1), ); - return [ - ...pipe( - present, - Array.filter((label) => !kinds.includes(label)), - Array.sortWith(identity, String.Order), - ), - ...pipe( - kinds, - Array.filter((label) => present.includes(label)), - ), - ]; -}; +const groupOrder: Order.Order<string> = Order.combine( + Order.mapInput(Order.Number, kindRank), + String.Order, +); + +/** Orders groups by their heading: authored categories alphabetically, then kinds in a fixed order. */ +export const sortGroups = <A>( + groups: Iterable<readonly [string, A]>, +): (readonly [string, A])[] => Array.sortWith(groups, Tuple.get(0), groupOrder); // Stability, version and internal status, each only where the comment states it. const markers = (comment: DocComment): BlockContent[] => { @@ -165,7 +203,9 @@ const parameters = ( pipe( collection.blocks, Effect.forEach((block) => - Comment.section(block.content).pipe( + pipe( + block.content, + Comment.section, Effect.map( (content): ListItem => ({ type: "listItem", @@ -196,7 +236,9 @@ const labelledSections = ( pipe( sections, Effect.forEach((content) => - Comment.section(content).pipe( + pipe( + content, + Comment.section, Effect.map((blocks) => labelled(strong(label), blocks)), ), ), @@ -226,39 +268,37 @@ const contentOf = (block: DocBlock | undefined): DocSection[] => const documentation = ( comment: DocComment, ): Effect.Effect<BlockContent[], TransformError, Comment.Links> => - Effect.all([ - labelledSections("Deprecated", contentOf(comment.deprecatedBlock)), - Effect.succeed(markers(comment)), - Comment.overview(comment), - parameters("Type parameters", comment.typeParams), - parameters("Parameters", comment.params), - labelledSections("Returns", contentOf(comment.returnsBlock)), - labelledSections( - "Throws", - pipe( - Comment.blocksTagged(comment, StandardTags.throws.tagName), - Array.map(({ content }) => content), + pipe( + [ + labelledSections("Deprecated", contentOf(comment.deprecatedBlock)), + Effect.succeed(markers(comment)), + Comment.overview(comment), + parameters("Type parameters", comment.typeParams), + parameters("Parameters", comment.params), + labelledSections("Returns", contentOf(comment.returnsBlock)), + labelledSections( + "Throws", + Array.map( + Comment.blocksTagged(comment, StandardTags.throws.tagName), + Struct.get("content"), + ), + ), + labelledSections( + "See", + Array.map(comment.seeBlocks, Struct.get("content")), ), - ), - labelledSections( - "See", pipe( - comment.seeBlocks, - Array.map(({ content }) => content), + Comment.blocksTagged(comment, StandardTags.example.tagName), + Effect.forEach(Comment.example), + Effect.map(Array.flatMap(exampleBlocks)), ), - ), - pipe( - Comment.blocksTagged(comment, StandardTags.example.tagName), - Effect.forEach(Comment.example), - Effect.map(Array.flatMap(exampleBlocks)), - ), - ]).pipe(Effect.map(Array.flatten)); + ], + Effect.all, + Effect.map(Array.flatten), + ); const descendants = (items: readonly ApiItem[]): ApiItem[] => - pipe( - items, - Array.flatMap((item) => [item, ...descendants(item.members)]), - ); + Array.flatMap(items, (item) => [item, ...descendants(item.members)]); /** Renders a member as its heading and declarations, followed by the documentation of each declaration and of every documented nested member. */ export const render = ({ @@ -266,32 +306,38 @@ export const render = ({ signature, anchor, }: Member): Effect.Effect<BlockContent[], TransformError, Comment.Links> => - Effect.all([ - Effect.succeed<BlockContent[]>([ - heading(memberDepth, anchor(Array.headNonEmpty(items))), - { type: "code", lang: "ts", value: signature }, - ]), - pipe( - comments(items), - Effect.forEach(documentation), - Effect.map(Array.flatten), - ), - pipe( - items, - Array.flatMap((item) => item.members), - descendants, - Array.flatMap((nested) => - pipe( - comments([nested]), - Array.map((comment) => ({ nested, comment })), - ), + pipe( + [ + pipe( + signature, + code, + Effect.map((block) => [ + heading(memberDepth, anchor(Array.headNonEmpty(items))), + block, + ]), ), - Effect.forEach(({ nested, comment }) => - Effect.all([ - Effect.succeed([heading(nestedDepth, anchor(nested))]), - documentation(comment), - ]).pipe(Effect.map(Array.flatten)), + pipe( + comments(items), + Effect.forEach(documentation), + Effect.map(Array.flatten), ), - Effect.map(Array.flatten), - ), - ]).pipe(Effect.map(Array.flatten)); + pipe( + items, + Array.flatMap(Struct.get("members")), + descendants, + Array.flatMap((nested) => + Array.map(comments([nested]), (comment) => ({ nested, comment })), + ), + Effect.forEach(({ nested, comment }) => + pipe( + comment, + documentation, + Effect.map(Array.prepend(heading(nestedDepth, anchor(nested)))), + ), + ), + Effect.map(Array.flatten), + ), + ], + Effect.all, + Effect.map(Array.flatten), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts index d881bac7e56..9a8165d355c 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts @@ -1,4 +1,13 @@ -import { Array, Effect, Option, Record, Result, pipe } from "effect"; +import { + Array, + Effect, + Option, + Record, + Result, + String, + Struct, + pipe, +} from "effect"; import { stringify } from "yaml"; import { Analysis } from "./Analysis.js"; @@ -8,29 +17,30 @@ import * as Signature from "./Signature.js"; import { Site } from "./Site.js"; import { TransformError } from "./TransformError.js"; -import type { Page } from "./Site.js"; +import type { Origin, Page } from "./Site.js"; import type { ApiItem } from "@microsoft/api-extractor-model"; import type { BlockContent, ListItem, PhrasingContent, Root } from "mdast"; const withLinks = Effect.fnUntraced(function* <A>( - origin: { readonly module: string; readonly container: ApiItem }, + origin: Origin, effect: Effect.Effect<A, TransformError, Comment.Links>, ) { - const links = yield* (yield* Site).links(origin); + const site = yield* Site; + const links = yield* site.links(origin); return yield* Effect.provideService(effect, Comment.Links, links); }); // The modules' own comments open the page, each linking from its module. -const overview = ( - page: Page, -): Effect.Effect<BlockContent[], TransformError, Analysis | Site> => - pipe( +const overview = Effect.fnUntraced(function* (page: Page) { + const analysis = yield* Analysis; + + return yield* pipe( page.modules, Effect.forEach((file) => - Effect.flatMap(Effect.service(Analysis), (analysis) => - analysis.moduleComment(file), - ).pipe( + pipe( + file, + analysis.moduleComment, Effect.flatMap( Option.match({ onNone: () => Effect.succeed([]), @@ -45,18 +55,21 @@ const overview = ( ), Effect.map(Array.flatten), ); +}); // A child page's entry carries the first paragraph of its module's comment. const childEntry = Effect.fnUntraced(function* (child: Page) { const analysis = yield* Analysis; const site = yield* Site; + const file = Array.headNonEmpty(child.modules); - const summary = yield* Option.match(yield* analysis.moduleComment(file), { + const comment = yield* analysis.moduleComment(file); + const summary = yield* Option.match(comment, { onNone: () => Effect.succeed([]), - onSome: (comment) => + onSome: (found) => withLinks( { module: file, container: child.container }, - Comment.lead(comment), + Comment.lead(found), ), }); const title: PhrasingContent = { @@ -88,24 +101,38 @@ const member = Effect.fnUntraced(function* ( page: Page, items: Array.NonEmptyReadonlyArray<ApiItem>, ) { + const analysis = yield* Analysis; const site = yield* Site; + const first = Array.headNonEmpty(items); - const origin = yield* Effect.fromOption(site.origin(first)).pipe( + const origin = yield* pipe( + first, + site.origin, + Effect.fromOption, Effect.mapError(() => TransformError.malformedAnalysis( `${first.getScopedNameWithinPackage()} has no source module on a page`, ), ), ); + const declaration = yield* analysis.declarationOf(origin.module); + const signature = yield* Signature.make({ + name: first.displayName, + source: origin.module, + declaration, + root: analysis.declarationRoot, + exporters: [origin.module, ...page.modules], + }); + const resolve = yield* site.declarationLinks(origin, declaration); const blocks = yield* withLinks( origin, Member.render({ items, - signature: yield* Signature.make({ - name: first.displayName, - source: origin.module, - exporters: [origin.module, ...page.modules], - }), + signature: { + code: signature.code, + context: signature.context, + urls: Array.map(signature.references, ({ path }) => resolve(path)), + }, anchor: site.anchor, }), ); @@ -141,39 +168,32 @@ const sections = ( readonly label: string; readonly blocks: BlockContent[]; }[], -): BlockContent[] => { - const groups = Array.groupBy(rendered, ({ label }) => label); - - return pipe( - Member.groupOrder(Record.keys(groups)), - Array.flatMap((label) => [ +): BlockContent[] => + pipe( + rendered, + Array.groupBy(Struct.get("label")), + Record.toEntries, + Member.sortGroups, + Array.flatMap(([label, group]) => [ heading(label), - ...pipe( - groups[label] ?? [], - Array.flatMap(({ blocks }) => blocks), - ), + ...Array.flatMap(group, Struct.get("blocks")), ]), ); -}; /** Builds a page from its modules' overviews and the pages of its namespaces, followed by its members grouped by category or kind. */ export const render = Effect.fnUntraced(function* (page: Page) { const site = yield* Site; - const [children, items] = pipe( - page.container.members, - Array.partition((item) => - Option.match(site.pageOf(item), { - onSome: Result.succeed, - onNone: () => Result.fail(item), - }), - ), + + const [children, items] = Array.partition(page.container.members, (item) => + Result.fromOption(site.pageOf(item), () => item), ); // Members sharing a name render as one: overloads, or an interface merged with a namespace. const body = yield* Effect.all([ overview(page), namespaces(children), pipe( - Array.groupBy(items, (item) => item.displayName), + items, + Array.groupBy(Struct.get("displayName")), Record.values, Effect.forEach((group) => member(page, group)), Effect.map(sections), @@ -183,7 +203,7 @@ export const render = Effect.fnUntraced(function* (page: Page) { return { type: "root", children: [ - { type: "yaml", value: stringify({ title: page.title }).trimEnd() }, + { type: "yaml", value: String.trimEnd(stringify({ title: page.title })) }, ...Array.flatten(body), ], } satisfies Root; diff --git a/libs/@local/hashql/sdk/typescript-docs/src/References.ts b/libs/@local/hashql/sdk/typescript-docs/src/References.ts new file mode 100644 index 00000000000..42eaa80eff0 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/References.ts @@ -0,0 +1,288 @@ +/** + * The names TypeScript code refers to, each at the identifier that writes it. + * + * A reference is a chain of identifiers in a type reference, a `typeof` query or a heritage clause, whose first name no type parameter, parameter, `infer` or mapped-type key of the code binds. Formatting the code moves the references without changing their order, which is how a code block pairs them with links the transform chose before the formatter ran. + * + * @module + */ +import { + Array, + Filter, + Match, + Option, + Order, + Predicate, + Struct, + pipe, +} from "effect"; +import { Visitor } from "oxc-parser"; + +import type { + BindingPattern, + BindingProperty, + BindingRestElement, + Expression, + IdentifierName, + ParamPattern, + Program, + Span, + TSConditionalType, + TSInferType, + TSTypeName, + TSTypeParameterDeclaration, +} from "oxc-parser"; + +/** A name the statements refer to, at one of its identifiers. */ +export interface Reference { + readonly start: number; + readonly end: number; + /** The names up to and including this identifier, outermost first: `Type`, then `Type.Any`. */ + readonly path: Array.NonEmptyReadonlyArray<string>; +} + +/** A name in an entity name or a member expression, at its identifier. */ +interface Segment { + readonly name: string; + readonly start: number; + readonly end: number; +} + +const segment = ({ name, start, end }: IdentifierName): Segment => ({ + name, + start, + end, +}); + +// `this.x` names no declaration, so a qualifier that bottoms out at `this` yields nothing. +const typeNameSegments = (name: TSTypeName): readonly Segment[] => { + if (name.type === "Identifier") { + return [segment(name)]; + } + + if (name.type === "TSQualifiedName") { + return Array.match(typeNameSegments(name.left), { + onEmpty: () => [], + onNonEmpty: Array.append(segment(name.right)), + }); + } + + return []; +}; + +// Heritage clauses and `extends` name their base as an expression, which refers to a declaration only as a chain of identifiers. +const expressionSegments = (expression: Expression): readonly Segment[] => { + if (expression.type === "Identifier") { + return [segment(expression)]; + } + + if ( + expression.type === "MemberExpression" && + !expression.computed && + expression.property.type === "Identifier" + ) { + const { property } = expression; + + return Array.match(expressionSegments(expression.object), { + onEmpty: () => [], + onNonEmpty: Array.append(segment(property)), + }); + } + + return []; +}; + +const patternNames: ( + pattern: BindingPattern | ParamPattern, +) => readonly string[] = Match.type<BindingPattern | ParamPattern>().pipe( + Match.discriminatorsExhaustive("type")({ + Identifier: ({ name }) => [name], + AssignmentPattern: ({ left }) => patternNames(left), + RestElement: ({ argument }) => patternNames(argument), + TSParameterProperty: ({ parameter }) => patternNames(parameter), + ObjectPattern: ({ properties }) => + Array.flatMap( + properties, + Match.type<BindingProperty | BindingRestElement>().pipe( + Match.discriminatorsExhaustive("type")({ + Property: ({ value }) => patternNames(value), + RestElement: ({ argument }) => patternNames(argument), + }), + ), + ), + ArrayPattern: ({ elements }) => + pipe( + elements, + Array.filter(Predicate.isNotNull), + Array.flatMap((element) => patternNames(element)), + ), + }), +); + +/** Names a declaration binds over a range of the code: type parameters, `infer` and mapped-type keys as types, parameters as values. */ +interface Binder { + readonly start: number; + readonly end: number; + readonly types: readonly string[]; + readonly values: readonly string[]; +} + +/** A chain of identifiers that refers to a declaration, and the space TypeScript looks its first name up in. */ +interface Candidate { + readonly segments: Array.NonEmptyReadonlyArray<Segment>; + readonly space: "types" | "values"; +} + +/** Where the syntax binds names, and the chains of identifiers that may refer to declarations. */ +interface Collected { + readonly binders: readonly Binder[]; + readonly candidates: readonly Candidate[]; + readonly conditionals: readonly TSConditionalType[]; + readonly infers: readonly TSInferType[]; +} + +const typeParameterNames = ( + declaration: TSTypeParameterDeclaration | null | undefined, +): readonly string[] => + Array.map(declaration?.params ?? [], ({ name }) => name.name); + +const collect = (program: Program): Collected => { + const binders: Binder[] = []; + const candidates: Candidate[] = []; + const conditionals: TSConditionalType[] = []; + const infers: TSInferType[] = []; + + const binds = (node: { + readonly start: number; + readonly end: number; + readonly typeParameters?: TSTypeParameterDeclaration | null; + readonly params?: readonly ParamPattern[]; + }): void => { + binders.push({ + start: node.start, + end: node.end, + types: typeParameterNames(node.typeParameters), + values: Array.flatMap(node.params ?? [], patternNames), + }); + }; + const refers = ( + segments: readonly Segment[], + space: Candidate["space"], + ): void => { + if (Array.isReadonlyArrayNonEmpty(segments)) { + candidates.push({ segments, space }); + } + }; + + new Visitor({ + TSTypeAliasDeclaration: binds, + TSInterfaceDeclaration: binds, + ClassDeclaration: (node): void => { + binds(node); + + if (node.superClass !== null) { + refers(expressionSegments(node.superClass), "values"); + } + }, + FunctionDeclaration: binds, + FunctionExpression: binds, + TSDeclareFunction: binds, + ArrowFunctionExpression: binds, + TSFunctionType: binds, + TSConstructorType: binds, + TSMethodSignature: binds, + TSCallSignatureDeclaration: binds, + TSConstructSignatureDeclaration: binds, + // The key binds in the name and value types, which follow the constraint. + TSMappedType: ({ key, constraint, end }): void => { + binders.push({ + start: constraint.end, + end, + types: [key.name], + values: [], + }); + }, + TSConditionalType: (node): void => { + conditionals.push(node); + }, + TSInferType: (node): void => { + infers.push(node); + }, + TSTypeReference: ({ typeName }): void => { + refers(typeNameSegments(typeName), "types"); + }, + TSTypeQuery: ({ exprName }): void => { + if (exprName.type !== "TSImportType") { + refers(typeNameSegments(exprName), "values"); + } + }, + TSInterfaceHeritage: ({ expression }): void => { + refers(expressionSegments(expression), "types"); + }, + TSClassImplements: ({ expression }): void => { + refers(expressionSegments(expression), "types"); + }, + }).visit(program); + + return { binders, candidates, conditionals, infers }; +}; + +const contains = (outer: Span, inner: Span): boolean => + outer.start <= inner.start && inner.end <= outer.end; + +// An `infer` belongs to the innermost conditional whose `extends` clause holds it, and binds over that clause and the true branch. +const inferBinders = ({ conditionals, infers }: Collected): readonly Binder[] => + Array.filterMap( + infers, + Filter.fromPredicateOption((infer) => + pipe( + conditionals, + Array.filter(({ extendsType }) => contains(extendsType, infer)), + Array.sortWith( + ({ extendsType }) => extendsType.end - extendsType.start, + Order.Number, + ), + Array.head, + Option.map( + ({ extendsType, trueType }): Binder => ({ + start: extendsType.start, + end: trueType.end, + types: [infer.typeParameter.name.name], + values: [], + }), + ), + ), + ), + ); + +// Every identifier of a chain is a reference: `Type.Any` refers to `Type` at its first identifier and to `Type.Any` at its second. +const referencesAlong = ( + segments: Array.NonEmptyReadonlyArray<Segment>, +): readonly Reference[] => + Array.map( + segments, + ({ start, end }, index): Reference => ({ + start, + end, + path: [ + Array.headNonEmpty(segments).name, + ...Array.map(segments.slice(1, index + 1), Struct.get("name")), + ], + }), + ); + +/** The names a program refers to, in source order. A name bound by a type parameter, a parameter or `infer` is not a declaration a page documents, so it yields no reference. */ +export const of = (program: Program): readonly Reference[] => { + const collected = collect(program); + const binders = [...collected.binders, ...inferBinders(collected)]; + const isBound = ({ segments: [head], space }: Candidate): boolean => + Array.some( + binders, + (binder) => contains(binder, head) && binder[space].includes(head.name), + ); + + return pipe( + collected.candidates, + Array.filter((candidate) => !isBound(candidate)), + Array.flatMap(({ segments }) => referencesAlong(segments)), + ); +}; diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts new file mode 100644 index 00000000000..776d47a72c4 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, layer } from "@effect/vitest"; +import { Array, Effect, FileSystem, Layer, Path, Record } from "effect"; + +import * as Signature from "./Signature.js"; +import * as Sources from "./Sources.js"; + +import type { TransformError } from "./TransformError.js"; + +const declaration = "/declarations/program/Module.d.ts"; + +const files: Record.ReadonlyRecord<string, string> = { + "/src/program/Module.ts": [ + "declare function conditional(): void;", + "export { conditional as if };", + ].join("\n"), + [declaration]: [ + 'import * as Type from "../type/index.js";', + 'import type { Other } from "./Other.js";', + 'import type { Types } from "effect";', + "/** Not exported, so it has no page. */", + "interface Hidden<T> {", + " readonly value: T;", + "}", + "/** Picks a value. */", + "export declare function pick<T extends Type.Any>(value: T, other: Other): Hidden<T>;", + "/** Picks every key. */", + "export declare function pick<K>(key: K): {", + " [P in keyof K]: K[P] extends infer U ? U : Other;", + "};", + "declare function conditional(): Types.Invariant<Other>;", + "export { conditional as if };", + ].join("\n"), +}; + +// A read of a file the fixtures do not name is a defect in the test. +const fixtures: Layer.Layer<Sources.Sources | Path.Path> = Layer.mergeAll( + Sources.layer.pipe( + Layer.provide( + FileSystem.layerNoop({ + readFileString: (path) => + Effect.fromOption(Record.get(files, path)).pipe(Effect.orDie), + }), + ), + ), + Path.layer, +); + +const make = ( + name: string, +): Effect.Effect< + Signature.Signature, + TransformError, + Sources.Sources | Path.Path +> => + Signature.make({ + name, + source: "/src/program/Module.ts", + declaration, + root: "/declarations", + exporters: ["/src/program/Module.ts"], + }); + +// A reference reads as the text it spans and the path it resolves. +const shown = ({ + code, + references, +}: Signature.Signature): readonly (readonly [string, string])[] => + Array.map( + references, + ({ start, end, path }) => + [code.slice(start, end), Array.join(path, ".")] as const, + ); + +describe("signature", () => { + layer(fixtures)((it) => { + it.effect("overloads_code", () => + Effect.gen(function* () { + const { code } = yield* make("pick"); + + expect(code).toBe( + [ + "export declare function pick<T extends Type.Any>(value: T, other: Other): Hidden<T>;", + "export declare function pick<K>(key: K): {", + " [P in keyof K]: K[P] extends infer U ? U : Other;", + "};", + ].join("\n"), + ); + }), + ); + + // Type parameters, the mapped key and the `infer` binding name no declaration. + it.effect("references_skip_bound_names", () => + Effect.gen(function* () { + const signature = yield* make("pick"); + + expect(shown(signature)).toStrictEqual([ + ["Type", "Type"], + ["Any", "Type.Any"], + ["Other", "Other"], + ["Hidden", "Hidden"], + ["Other", "Other"], + ]); + }), + ); + + it.effect("context_excludes_shown", () => + Effect.gen(function* () { + const { context } = yield* make("pick"); + + expect(context).toBe( + [ + 'import * as Type from "#declarations/type/index.js";', + 'import type { Other } from "#declarations/program/Other.js";', + 'import type { Types } from "effect";', + "interface Hidden<T> {\n readonly value: T;\n}", + "declare function conditional(): Types.Invariant<Other>;", + ].join("\n"), + ); + }), + ); + + it.effect("alias_export", () => + Effect.gen(function* () { + const signature = yield* make("if"); + + expect(signature.code).toBe( + [ + "declare function conditional(): Types.Invariant<Other>;", + "export { conditional as if };", + ].join("\n"), + ); + expect(shown(signature)).toStrictEqual([ + ["Types", "Types"], + ["Invariant", "Types.Invariant"], + ["Other", "Other"], + ]); + }), + ); + + it.effect("undeclared_name", () => + Effect.gen(function* () { + const error = yield* Effect.flip(make("missing")); + + expect(error.reason).toMatchObject({ _tag: "MalformedAnalysis" }); + }), + ); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts index e5aa597deaf..18418ba6d42 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.ts @@ -1,10 +1,30 @@ -import { Array, Effect, Option, Record, pipe } from "effect"; +import { + Array, + Effect, + Option, + Path, + Record, + String, + Struct, + flow, + pipe, +} from "effect"; -import { Analysis } from "./Analysis.js"; -import { Sources } from "./Sources.js"; +import * as References from "./References.js"; +import { Sources, parse } from "./Sources.js"; import { TransformError } from "./TransformError.js"; -import type { Declarations } from "./Sources.js"; +import type { ScopeStatement } from "./Statements.js"; + +/** The statements declaring a member, with the declaration file they compile in. */ +export interface Signature { + /** The statements, without comments. */ + readonly code: string; + /** The declaration file's other imports and declarations. Each relative module specifier starts with `#declarations/` instead, which names the directory TypeScript emitted the declaration files into. */ + readonly context: string; + /** The names the statements refer to, in order. */ + readonly references: readonly References.Reference[]; +} /** Where an aliased name comes from: the module declaring it and its name there. */ interface Alias { @@ -13,106 +33,144 @@ interface Alias { } // `export { local as name }` takes the name from another module when it re-exports, from an import when the local is one, and from the exporter's own declarations otherwise. -const aliasOf = ( - exporter: string, - name: string, -): Effect.Effect<Option.Option<Alias>, TransformError, Sources> => - Effect.flatMap(Effect.service(Sources), (sources) => - sources.scope(exporter).pipe( - Effect.map(({ reexports, imports }) => - pipe( - Record.get(reexports, name), - Option.flatMap(({ local, specifier }) => - Option.match(specifier, { - onSome: (from) => - sources - .resolve(exporter, from) - .pipe(Option.map((module) => ({ module, local }))), - onNone: () => - pipe( - Record.get(imports, local), - Option.flatMap((binding) => - Option.all({ - module: sources.resolve(exporter, binding.specifier), - local: binding.imported, - }), - ), - Option.orElse(() => Option.some({ module: exporter, local })), - ), - }), +const aliasOf = Effect.fnUntraced(function* (exporter: string, name: string) { + const sources = yield* Sources; + const { reexports, imports } = yield* sources.scope(exporter); + + return pipe( + reexports, + Record.get(name), + Option.flatMap(({ local, specifier }) => + Option.match(specifier, { + onSome: (from) => + pipe( + sources.resolve(exporter, from), + Option.map((module): Alias => ({ module, local })), ), - ), - ), + onNone: () => + pipe( + imports, + Record.get(local), + Option.flatMap( + (binding): Option.Option<Alias> => + Option.all({ + module: sources.resolve(exporter, binding.specifier), + local: binding.imported, + }), + ), + Option.orElseSome((): Alias => ({ module: exporter, local })), + ), + }), ), ); +}); -const declarationsOf = ( - source: string, -): Effect.Effect<Declarations, TransformError, Analysis | Sources> => - Effect.all([Effect.service(Analysis), Effect.service(Sources)]).pipe( - Effect.flatMap(([analysis, sources]) => - analysis.declarationOf(source).pipe(Effect.flatMap(sources.declarations)), - ), +const statementsText = (statements: readonly ScopeStatement[]): string => + pipe(statements, Array.map(Struct.get("text")), Array.join("\n")); + +// Each relative specifier keeps naming its module wherever Twoslash compiles the context, through the path the docs site maps `#declarations/` to. +const rewriteSpecifiers = ( + { text, specifiers }: ScopeStatement, + rewrite: (specifier: string) => string, +): string => { + const [cursor, pieces] = Array.mapAccum( + specifiers, + 0, + (position, { start, end, value }) => [ + end, + `${text.slice(position, start)}${JSON.stringify(rewrite(value))}`, + ], ); + return `${Array.join(pieces, "")}${text.slice(cursor)}`; +}; + export interface Options { /** The name the member's module exports it under. */ readonly name: string; /** The source module declaring it. */ readonly source: string; + /** The declaration file TypeScript emitted from the source module. */ + readonly declaration: string; + /** The directory TypeScript emitted the declaration files into, which `#declarations/` names. */ + readonly root: string; /** Modules that may publish it under another name: the declaring module, then the page's. */ readonly exporters: readonly string[]; } /** - * The statements declaring a member, without comments. + * The statements declaring a member, without comments, and the rest of their declaration file. * - * A member exported under an alias keeps its local declaration, and the export specifier that publishes the alias follows it. The SDK exports `conditional` as `if` this way, because `if` cannot name a function. + * A member exported under an alias keeps its local declaration, and an export specifier that publishes the alias follows it. The SDK exports `conditional` as `if` this way, because `if` cannot name a function. */ -export const make = ({ +export const make = Effect.fnUntraced(function* ({ name, source, + declaration, + root, exporters, -}: Options): Effect.Effect<string, TransformError, Analysis | Sources> => - declarationsOf(source).pipe( - Effect.flatMap(({ local }) => - Option.match(Record.get(local, name), { - onSome: (declared) => Effect.succeed(pipe(declared, Array.join("\n"))), - onNone: () => - pipe( - exporters, - Effect.forEach((exporter) => - Effect.all([ - aliasOf(exporter, name), - declarationsOf(exporter), - ]).pipe( - Effect.map(([alias, { exports }]) => - Option.all({ - statements: alias.pipe( - Option.filter(({ module }) => module === source), - Option.flatMap((found) => Record.get(local, found.local)), - ), - exported: Record.get(exports, name), - }), - ), - ), - ), - Effect.map(Array.getSomes), - Effect.flatMap( - Array.match({ - onEmpty: () => - Effect.fail( - TransformError.malformedAnalysis( - `${source} declares no ${name}`, - ), - ), - onNonEmpty: ([{ statements, exported }]) => - Effect.succeed( - pipe([...statements, exported], Array.join("\n")), +}: Options) { + const sources = yield* Sources; + const path = yield* Path.Path; + + const { local, statements } = yield* sources.declarations(declaration); + + const shown = yield* Option.match(Record.get(local, name), { + onSome: (declared) => + Effect.succeed({ declared, exported: Option.none<string>() }), + onNone: () => + pipe( + exporters, + Effect.forEach((exporter) => aliasOf(exporter, name)), + Effect.map( + flow( + Array.getSomes, + Array.findFirst((alias) => + pipe( + alias, + Option.liftPredicate(({ module }) => module === source), + Option.flatMap(() => Record.get(local, alias.local)), + Option.map((declared) => ({ + declared, + exported: Option.some( + `export { ${alias.local} as ${name} };`, ), - }), + })), + ), ), ), - }), - ), + ), + Effect.flatMap(Effect.fromOption), + Effect.mapError(() => + TransformError.malformedAnalysis(`${source} declares no ${name}`), + ), + ), + }); + + const code = pipe( + [statementsText(shown.declared), ...Array.fromOption(shown.exported)], + Array.join("\n"), ); + const { program } = yield* parse(code, declaration); + + const directory = path.relative(root, path.dirname(declaration)); + const rewrite = (specifier: string): string => { + if (!String.startsWith(".")(specifier)) { + return specifier; + } + + return `#declarations/${pipe(path.join(directory, specifier), String.split(path.sep), Array.join("/"))}`; + }; + const context = pipe( + statements, + Array.filter((statement) => !shown.declared.includes(statement)), + Array.map((statement) => rewriteSpecifiers(statement, rewrite)), + Array.join("\n"), + ); + + return { + code, + context, + references: References.of(program), + } satisfies Signature; +}); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts index 13078fbe8d4..c56c8322492 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -10,6 +10,9 @@ import { Option, Path, Record, + String, + Struct, + flow, pipe, } from "effect"; @@ -39,6 +42,11 @@ export interface Origin { readonly container: ApiItem; } +/** Resolves a name path, `Type` or `Type.Any`, to the URL of what it names, `None` when it names nothing on a page. */ +export type Resolve = ( + path: Array.NonEmptyReadonlyArray<string>, +) => Option.Option<string>; + /** The pages of the reference and the links between them. */ export class Site extends Context.Service< Site, @@ -54,6 +62,11 @@ export class Site extends Context.Service< readonly links: ( origin: Origin, ) => Effect.Effect<Links["Service"], TransformError>; + /** Resolves names written in the declaration file emitted from an origin's module, as TypeScript resolves them there: the module's declarations, then its imports. */ + readonly declarationLinks: ( + origin: Origin, + declaration: string, + ) => Effect.Effect<Resolve, TransformError>; } >()("@local/hashql-typescript-docs/Site") {} @@ -68,67 +81,54 @@ const members = (container: ApiItem, name: string): readonly ApiItem[] => { const ancestors = (item: ApiItem): ApiItem[] => Array.unfold(item.parent, (parent) => - Option.fromNullishOr(parent).pipe( + pipe( + parent, + Option.fromNullishOr, Option.map((found) => [found, found.parent] as const), ), ); const directorySegments = (path: Path.Path, directory: string): string[] => - pipe( - directory.split(path.sep), - Array.filter((segment) => segment !== ""), - ); + pipe(directory, String.split(path.sep), Array.filter(String.isNonEmpty)); // A namespace that a module re-exports with `export * as` gets a page. A `namespace` declaration renders among its siblings. -const pageOfNamespace = ( - item: ApiItem, -): Effect.Effect< - Option.Option<Page>, - TransformError, - Analysis | Sources | Path.Path -> => - Effect.gen(function* () { - const analysis = yield* Analysis; - const sources = yield* Sources; - const path = yield* Path.Path; - const file = analysis - .sourceOf(item) - .pipe(Option.filter(() => item.kind === ApiItemKind.Namespace)); - - if (Option.isNone(file)) { - return Option.none(); - } - - const specifier = Record.get( - (yield* sources.scope(file.value)).namespaces, - item.displayName, - ); +const pageOfNamespace = Effect.fnUntraced(function* (item: ApiItem) { + const analysis = yield* Analysis; + const sources = yield* Sources; + const path = yield* Path.Path; + + const file = analysis.sourceOf(item); + if (item.kind !== ApiItemKind.Namespace || Option.isNone(file)) { + return Option.none<Page>(); + } - if (Option.isNone(specifier)) { - return Option.none(); - } + const { namespaces } = yield* sources.scope(file.value); + const specifier = Record.get(namespaces, item.displayName); + if (Option.isNone(specifier)) { + return Option.none<Page>(); + } - const target = yield* Effect.fromOption( - sources.resolve(file.value, specifier.value), - ).pipe( - Effect.mapError(() => - TransformError.malformedAnalysis( - `${file.value} re-exports ${specifier.value}, which does not exist`, - ), + const target = yield* pipe( + sources.resolve(file.value, specifier.value), + Effect.fromOption, + Effect.mapError(() => + TransformError.malformedAnalysis( + `${file.value} re-exports ${specifier.value}, which does not exist`, ), - ); - const directory = path.relative( - path.dirname(Array.headNonEmpty(analysis.roots)), - path.dirname(target), - ); + ), + ); + const directory = path.relative( + path.dirname(Array.headNonEmpty(analysis.roots)), + path.dirname(target), + ); - return Option.some({ - path: [...directorySegments(path, directory), item.displayName], - title: item.displayName, - container: item, - modules: [target], - }); + return Option.some<Page>({ + path: [...directorySegments(path, directory), item.displayName], + title: item.displayName, + container: item, + modules: [target], }); +}); const discover = ( container: ApiItem, @@ -136,12 +136,14 @@ const discover = ( pipe( container.members, Effect.forEach((item) => - pageOfNamespace(item).pipe( + pipe( + item, + pageOfNamespace, Effect.flatMap( Option.match({ - onNone: () => Effect.succeed([]), + onNone: () => Effect.succeed(Array.empty<Page>()), onSome: (page) => - discover(item).pipe(Effect.map((nested) => [page, ...nested])), + pipe(item, discover, Effect.map(Array.prepend(page))), }), ), ), @@ -161,18 +163,12 @@ interface Index { const makeIndex = (pages: readonly Page[], url: string): Index => { const byContainer = new Map( - pipe( - pages, - Array.map((page) => [page.container, page] as const), - ), + Array.map(pages, (page) => [page.container, page] as const), ); const byModule = pipe( pages, Array.flatMap((page) => - pipe( - page.modules, - Array.map((file) => [file, page] as const), - ), + Array.map(page.modules, (file) => [file, page] as const), ), Record.fromEntries, ); @@ -180,16 +176,16 @@ const makeIndex = (pages: readonly Page[], url: string): Index => { const pageOf = (container: ApiItem): Option.Option<Page> => Option.fromNullishOr(byContainer.get(container)); - const pageUrl = (page: Page): string => - pipe([url, ...page.path], Array.join("/")); + const pageUrl = (page: Page): string => Array.join([url, ...page.path], "/"); const enclosing = (item: ApiItem): Option.Option<ApiItem> => - pipe(ancestors(item), Array.findFirst(hasPage)); + pipe(item, ancestors, Array.findFirst(hasPage)); const anchor = (item: ApiItem): string => pipe( - ancestors(item), + item, + ancestors, Array.takeWhile((parent) => !hasPage(parent)), Array.reverse, - Array.map((parent) => parent.displayName), + Array.map(Struct.get("displayName")), Array.append(item.displayName), Array.join("."), ); @@ -201,10 +197,14 @@ const makeIndex = (pages: readonly Page[], url: string): Index => { anchor, enclosing, itemUrl: (item) => - pageOf(item).pipe( + pipe( + item, + pageOf, Option.map(pageUrl), Option.orElse(() => - enclosing(item).pipe( + pipe( + item, + enclosing, Option.flatMap(pageOf), Option.map((page) => `${pageUrl(page)}#${anchor(item)}`), ), @@ -219,42 +219,46 @@ interface Resolution { readonly scope: Scope; } +/** The declarations a name may refer to in one scope, empty when the scope has none. */ +type Lookup = (name: string) => readonly ApiItem[]; + // The module's declarations, including those it publishes under another name with `export { local as name }`. -const declared = ( - { origin, scope }: Resolution, - name: string, -): readonly ApiItem[] => [ - ...members(origin.container, name), - ...pipe( - Record.toEntries(scope.reexports), - Array.filter( - ([, reexport]) => - reexport.local === name && Option.isNone(reexport.specifier), +const declared = + ({ origin, scope }: Resolution): Lookup => + (name) => [ + ...members(origin.container, name), + ...pipe( + scope.reexports, + Record.toEntries, + Array.filter( + ([, { local, specifier }]) => + local === name && Option.isNone(specifier), + ), + Array.flatMap(([exported]) => members(origin.container, exported)), ), - Array.flatMap(([exported]) => members(origin.container, exported)), - ), -]; - -const imported = ( - sources: Sources["Service"], - { index, origin, scope }: Resolution, - name: string, -): readonly ApiItem[] => - pipe( - Record.get(scope.imports, name), - Option.flatMap((binding) => - sources.resolve(origin.module, binding.specifier).pipe( - Option.flatMap(index.pageOfModule), - Option.map((page) => - Option.match(binding.imported, { - onNone: () => [page.container], - onSome: (exported) => members(page.container, exported), - }), + ]; + +// Specifiers resolve from the origin's module, which the emitted declaration files mirror. +const imported = + (sources: Sources["Service"], { index, origin, scope }: Resolution): Lookup => + (name) => + pipe( + scope.imports, + Record.get(name), + Option.flatMap(({ specifier, imported: exported }) => + pipe( + sources.resolve(origin.module, specifier), + Option.flatMap(index.pageOfModule), + Option.map(({ container }) => + Option.match(exported, { + onNone: () => [container], + onSome: (member) => members(container, member), + }), + ), ), ), - ), - Option.getOrElse(() => []), - ); + Option.getOrElse(Array.empty), + ); // A symbol reference such as `[Symbol.iterator]` names no member a page lists. const namesOf = ( @@ -266,101 +270,91 @@ const namesOf = ( Option.fromNullishOr(part.memberIdentifier?.identifier), ), Option.all, - Option.flatMap( - Array.match({ - onEmpty: () => Option.none(), - onNonEmpty: (names) => Option.some(names), - }), - ), + Option.filter(Array.isReadonlyArrayNonEmpty<string>), ); -// Walks the remaining names of a reference through the members of every candidate. -const walk = ( - candidates: readonly ApiItem[], - names: readonly string[], -): readonly ApiItem[] => - Array.matchLeft(names, { - onEmpty: () => candidates, - onNonEmpty: (name, rest) => - walk( - pipe( - candidates, - Array.flatMap((parent) => members(parent, name)), - ), - rest, - ), - }); - -interface Resolver { - readonly analysis: Analysis["Service"]; - readonly sources: Sources["Service"]; - readonly resolution: Resolution; -} - -// Links resolve the way TypeScript resolves them in the comment's module: its declarations, then its imports. A reference qualified from the package resolves last. -const target = - ({ analysis, sources, resolution }: Resolver) => - (reference: DocDeclarationReference): Option.Option<ApiItem> => +// The first scope that declares the leading name decides it, and the remaining names walk the members of every declaration found there. +const resolveIn = + (lookups: readonly Lookup[]) => + ([ + head, + ...tail + ]: Array.NonEmptyReadonlyArray<string>): Option.Option<ApiItem> => pipe( - namesOf(reference), - Option.filter( - () => - reference.packageName === undefined || - reference.packageName === analysis.package.name, + lookups, + Array.findFirst((lookup) => + Option.liftPredicate( + lookup(head), + Array.isReadonlyArrayNonEmpty<ApiItem>, + ), ), - Option.flatMap(([head, ...tail]) => - pipe( - [ - declared(resolution, head), - imported(sources, resolution, head), - members(analysis.entry, head), - ], - Array.findFirst((found) => found.length > 0), - Option.map((found) => walk(found, tail)), - Option.flatMap(Array.head), + Option.map((found: readonly ApiItem[]) => + Array.reduce(tail, found, (candidates, name) => + Array.flatMap(candidates, (parent) => members(parent, name)), ), ), + Option.flatMap(Array.head), ); -const makeLinks = - (index: Index) => - ( - origin: Origin, - ): Effect.Effect< - Links["Service"], - TransformError, - Analysis | Sources | Path.Path - > => - Effect.gen(function* () { - const analysis = yield* Analysis; - const sources = yield* Sources; - const path = yield* Path.Path; - const resolution: Resolution = { - index, - origin, - scope: yield* sources.scope(origin.module), - }; - const shown = path.relative( - path.dirname(Array.headNonEmpty(analysis.roots)), - origin.module, - ); +const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { + const analysis = yield* Analysis; + const sources = yield* Sources; + const path = yield* Path.Path; + + const scope = yield* sources.scope(origin.module); + const resolution: Resolution = { index, origin, scope }; + // Links resolve the way TypeScript resolves them in the comment's module. A reference qualified from the package resolves last. + const fromPackage: Lookup = (name) => members(analysis.entry, name); + const target = resolveIn([ + declared(resolution), + imported(sources, resolution), + fromPackage, + ]); + const shown = path.relative( + path.dirname(Array.headNonEmpty(analysis.roots)), + origin.module, + ); + + return Links.of({ + resolve: (reference) => + pipe( + reference, + Option.liftPredicate( + ({ packageName }) => + packageName === undefined || packageName === analysis.package.name, + ), + Option.flatMap(namesOf), + Option.flatMap(target), + Option.flatMap(index.itemUrl), + Option.match({ + onNone: () => + pipe( + Effect.logWarning( + `Unresolved link ${reference.emitAsTsdoc()} in ${shown}`, + ), + Effect.as(Option.none()), + ), + onSome: flow(Option.some, Effect.succeed), + }), + ), + }); +}); - return Links.of({ - resolve: (reference) => { - const resolved = target({ analysis, sources, resolution })( - reference, - ).pipe(Option.flatMap(index.itemUrl)); +const makeDeclarationLinks = Effect.fnUntraced(function* ( + index: Index, + origin: Origin, + declaration: string, +) { + const sources = yield* Sources; - if (Option.isNone(resolved)) { - return Effect.logWarning( - `Unresolved link ${reference.emitAsTsdoc()} in ${shown}`, - ).pipe(Effect.as(resolved)); - } + const scope = yield* sources.scope(declaration); + const resolution: Resolution = { index, origin, scope }; - return Effect.succeed(resolved); - }, - }); - }); + return flow( + resolveIn([declared(resolution), imported(sources, resolution)]), + Option.flatMap(index.itemUrl), + ) satisfies Resolve; +}); export interface Options { /** The URL of the package page, which every other page's URL extends. */ @@ -379,7 +373,10 @@ export const layer = ({ Effect.gen(function* () { const analysis = yield* Analysis; const services = yield* Effect.context<Analysis | Sources | Path.Path>(); - const pages = yield* discover(analysis.entry).pipe( + + const pages = yield* pipe( + analysis.entry, + discover, Effect.map( Array.prepend<Page>({ path: [], @@ -390,7 +387,8 @@ export const layer = ({ ), ); const duplicate = pipe( - Array.groupBy(pages, (page) => pipe(page.path, Array.join("/"))), + pages, + Array.groupBy((page) => Array.join(page.path, "/")), Record.toEntries, Array.findFirst(([, group]) => group.length > 1), ); @@ -409,17 +407,25 @@ export const layer = ({ url: index.url, anchor: index.anchor, origin: (item) => - analysis.sourceOf(item).pipe( - Option.flatMap((file) => - index.pageOfModule(file).pipe( - Option.map((page) => page.container), + pipe( + item, + analysis.sourceOf, + Option.flatMap((module) => + pipe( + module, + index.pageOfModule, + Option.map(Struct.get("container")), Option.orElse(() => index.enclosing(item)), - Option.map((container) => ({ module: file, container })), + Option.map((container) => ({ module, container })), ), ), ), - links: (origin) => - makeLinks(index)(origin).pipe(Effect.provide(services)), + links: (origin) => Effect.provide(makeLinks(index, origin), services), + declarationLinks: (origin, declaration) => + Effect.provide( + makeDeclarationLinks(index, origin, declaration), + services, + ), }); }), ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts index b9eaa74eeb1..a1bf80da674 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.test.ts @@ -1,5 +1,14 @@ import { describe, expect, layer } from "@effect/vitest"; -import { Effect, FileSystem, Layer, Option, Record } from "effect"; +import { + Array, + Effect, + FileSystem, + Layer, + Option, + Record, + Struct, + pipe, +} from "effect"; import * as Sources from "./Sources.js"; @@ -25,10 +34,13 @@ const files: Record.ReadonlyRecord<string, string> = { " readonly name: string;", "}", ].join("\n"), - "/alias.d.ts": [ - "declare function conditional(): void;", - "export { conditional as if, other as unrelated };", - 'export { ifElse as If, assume } from "./expression.js";', + "/statements.d.ts": [ + 'import type { Thing } from "./thing.js";', + 'import * as Space from "../space.js";', + "/** Documented. */", + 'export declare const value: import("./other.js").Other; // trailing', + "export { value as alias };", + 'export * from "./everything.js";', ].join("\n"), "/broken.ts": "export const = ;", }; @@ -72,13 +84,20 @@ describe("sources", () => { const sources = yield* Sources.Sources; const { local } = yield* sources.declarations("/overloads.d.ts"); - expect(Record.get(local, "pick")).toStrictEqual( + const texts = (name: string): Option.Option<readonly string[]> => + pipe( + local, + Record.get(name), + Option.map(Array.map(Struct.get("text"))), + ); + + expect(texts("pick")).toStrictEqual( Option.some([ "export declare function pick(value: string): string;", "export declare function pick(value: number): number;", ]), ); - expect(Record.get(local, "Shape")).toStrictEqual( + expect(texts("Shape")).toStrictEqual( Option.some([ [ "export interface Shape {", @@ -91,20 +110,38 @@ describe("sources", () => { }), ); - it.effect("declarations_alias_export", () => + it.effect("declarations_scope_statements", () => Effect.gen(function* () { const sources = yield* Sources.Sources; - const { local, exports } = yield* sources.declarations("/alias.d.ts"); + const { statements } = yield* sources.declarations("/statements.d.ts"); - expect(Record.get(local, "conditional")).toStrictEqual( - Option.some(["declare function conditional(): void;"]), - ); - expect(Record.get(exports, "if")).toStrictEqual( - Option.some("export { conditional as if };"), - ); - expect(Record.get(exports, "If")).toStrictEqual( - Option.some('export { ifElse as If } from "./expression.js";'), - ); + // Each specifier's offsets point at its quoted literal in the comment-free text. + expect( + Array.map(statements, ({ names, text, specifiers }) => ({ + names, + text, + specifiers: Array.map(specifiers, ({ start, end, value }) => [ + text.slice(start, end), + value, + ]), + })), + ).toStrictEqual([ + { + names: ["Thing"], + text: 'import type { Thing } from "./thing.js";', + specifiers: [['"./thing.js"', "./thing.js"]], + }, + { + names: ["Space"], + text: 'import * as Space from "../space.js";', + specifiers: [['"../space.js"', "../space.js"]], + }, + { + names: ["value"], + text: 'export declare const value: import("./other.js").Other;', + specifiers: [['"./other.js"', "./other.js"]], + }, + ]); }), ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts index 6bab1765fd4..bdd76188041 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Sources.ts @@ -5,32 +5,37 @@ import { Effect, FileSystem, Filter, + Function, Layer, Option, Record, - String, + Struct, + Tuple, + flow, pipe, } from "effect"; -import { print } from "esrap"; -import ts from "esrap/languages/ts"; import { parseSync } from "oxc-parser"; import { ResolverFactory } from "oxc-resolver"; +import { + boundNames, + declarationOf, + declaredNames, + isExportAll, + isExportNamed, + isImport, + specifierLiterals, + statementText, +} from "./Statements.js"; import { TransformError } from "./TransformError.js"; +import type { File, ScopeStatement } from "./Statements.js"; import type { - BindingPattern, Comment, - Declaration, - ExportAllDeclaration, - ExportNamedDeclaration, - ImportDeclaration, ImportDeclarationSpecifier, ModuleExportName, Program, Statement, - StringLiteral, - TSQualifiedName, } from "oxc-parser"; /** A name an import declaration brings into a module's scope. */ @@ -60,40 +65,41 @@ export interface Scope { readonly comments: readonly Comment[]; } -/** The declarations of a declaration file and the statements that publish them. */ +/** The statements of a declaration file that bring names into its scope. */ export interface Declarations { /** The statements declaring each top-level name, without comments. Overloads share an entry. */ readonly local: Record.ReadonlyRecord< string, - Array.NonEmptyReadonlyArray<string> + Array.NonEmptyReadonlyArray<ScopeStatement> >; - /** For each name an export specifier publishes, that specifier as an export statement of its own. */ - readonly exports: Record.ReadonlyRecord<string, string>; + /** Every import and declaration, in source order. */ + readonly statements: readonly ScopeStatement[]; } -const parse = ( - file: string, - text: string, -): Effect.Effect< - Pick<ReturnType<typeof parseSync>, "program" | "comments">, - TransformError -> => { - const { program, comments, errors } = parseSync(file, text); - - return Array.match(errors, { - onEmpty: () => Effect.succeed({ program, comments }), - onNonEmpty: (failures) => - Effect.fail( - TransformError.sourceSyntax( - file, - pipe( - failures, - Array.map(({ message }) => message), +/** A module's syntax tree and comments. */ +export type Parsed = Pick<ReturnType<typeof parseSync>, "program" | "comments">; + +/** Parses TypeScript with oxc, failing with every syntax error it reports. The file's name selects the dialect, such as a declaration file's. */ +export const parse: { + (file: string): (text: string) => Effect.Effect<Parsed, TransformError>; + (text: string, file: string): Effect.Effect<Parsed, TransformError>; +} = Function.dual( + 2, + (text: string, file: string): Effect.Effect<Parsed, TransformError> => { + const { program, comments, errors } = parseSync(file, text); + + return Array.match(errors, { + onEmpty: () => Effect.succeed({ program, comments }), + onNonEmpty: (failures) => + Effect.fail( + TransformError.sourceSyntax( + file, + Array.map(failures, Struct.get("message")), ), ), - ), - }); -}; + }); + }, +); const exportName = (name: ModuleExportName): string => { if (name.type === "Literal") { @@ -117,37 +123,24 @@ const importedName = ( return Option.none(); }; -const isImport = (statement: Statement): statement is ImportDeclaration => - statement.type === "ImportDeclaration"; - -const isExportAll = (statement: Statement): statement is ExportAllDeclaration => - statement.type === "ExportAllDeclaration"; - -const isExportNamed = ( - statement: Statement, -): statement is ExportNamedDeclaration => - statement.type === "ExportNamedDeclaration"; - const collectScope = (program: Program): Omit<Scope, "text" | "comments"> => { - const exportsAll = pipe(program.body, Array.filter(isExportAll)); + const exportsAll = Array.filter(program.body, isExportAll); return { imports: pipe( program.body, Array.filter(isImport), Array.flatMap((statement) => - pipe( + Array.map( statement.specifiers, - Array.map( - (specifier) => - [ - specifier.local.name, - { - specifier: statement.source.value, - imported: importedName(specifier), - }, - ] as const, - ), + (specifier) => + [ + specifier.local.name, + { + specifier: statement.source.value, + imported: importedName(specifier), + }, + ] as const, ), ), Record.fromEntries, @@ -161,7 +154,9 @@ const collectScope = (program: Program): Omit<Scope, "text" | "comments"> => { exportsAll, Array.filterMap( Filter.fromPredicateOption(({ exported, source }) => - Option.fromNullishOr(exported).pipe( + pipe( + exported, + Option.fromNullishOr, Option.map((name) => [exportName(name), source.value] as const), ), ), @@ -172,18 +167,16 @@ const collectScope = (program: Program): Omit<Scope, "text" | "comments"> => { program.body, Array.filter(isExportNamed), Array.flatMap((statement) => - pipe( + Array.map( statement.specifiers, - Array.map( - (specifier) => - [ - exportName(specifier.exported), - { - local: exportName(specifier.local), - specifier: Option.fromNullishOr(statement.source?.value), - }, - ] as const, - ), + (specifier) => + [ + exportName(specifier.exported), + { + local: exportName(specifier.local), + specifier: Option.fromNullishOr(statement.source?.value), + }, + ] as const, ), ), Record.fromEntries, @@ -191,135 +184,42 @@ const collectScope = (program: Program): Omit<Scope, "text" | "comments"> => { }; }; -const declarationTypes: ReadonlySet<string> = new Set([ - "VariableDeclaration", - "FunctionDeclaration", - "TSDeclareFunction", - "ClassDeclaration", - "TSTypeAliasDeclaration", - "TSInterfaceDeclaration", - "TSEnumDeclaration", - "TSModuleDeclaration", -] satisfies Declaration["type"][]); - -const isDeclaration = (statement: Statement): statement is Declaration => - declarationTypes.has(statement.type); - -const declarationOf = (statement: Statement): Option.Option<Declaration> => { - if (statement.type === "ExportNamedDeclaration") { - return Option.fromNullishOr(statement.declaration); - } - - return Option.liftPredicate(statement, isDeclaration); -}; - -// Destructuring patterns and string-named modules declare no name a member can have. -const identifierName = ( - node: BindingPattern | StringLiteral | TSQualifiedName | null, -): Option.Option<string> => { - if (node?.type === "Identifier") { - return Option.some(node.name); - } - - return Option.none(); -}; - -const declaredNames = (declaration: Declaration): readonly string[] => { - if (declaration.type === "VariableDeclaration") { - return pipe( - declaration.declarations, - Array.filterMap( - Filter.fromPredicateOption(({ id }) => identifierName(id)), - ), - ); - } - - return Array.fromOption(identifierName(declaration.id)); -}; - -// A comment alone on its lines leaves with those lines, so removing it leaves no blank line behind. -const commentRange = ( - text: string, - comment: Comment, -): { readonly start: number; readonly end: number } => { - const lineStart = text.lastIndexOf("\n", comment.start - 1) + 1; - const lineEnd = text.indexOf("\n", comment.end); - - if ( - lineEnd !== -1 && - String.isEmpty(String.trim(text.slice(lineStart, comment.start))) && - String.isEmpty(String.trim(text.slice(comment.end, lineEnd))) - ) { - return { start: lineStart, end: lineEnd + 1 }; - } - - return { start: comment.start, end: comment.end }; -}; - -// The text between the comments inside a statement. -const statementText = ( - text: string, - statement: Statement, - comments: readonly Comment[], -): string => { - const [cursor, pieces] = pipe( - comments, - Array.filter( - ({ start, end }) => start >= statement.start && end <= statement.end, - ), - Array.map((comment) => commentRange(text, comment)), - Array.mapAccum(statement.start, (position, range) => [ - Math.max(position, range.end), - text.slice(position, Math.max(position, range.start)), - ]), - ); - - return pipe([...pieces, text.slice(cursor, statement.end)], Array.join("")); -}; - const collectDeclarations = ( text: string, - program: Program, - comments: readonly Comment[], -): Declarations => ({ - local: pipe( + { program, comments }: Parsed, +): Declarations => { + const file: File = { text, comments, literals: specifierLiterals(program) }; + const scoped = Array.filterMap( program.body, - Array.flatMap((statement) => + Filter.fromPredicateOption((statement) => pipe( - declarationOf(statement), - Array.fromOption, - Array.flatMap(declaredNames), - Array.map((name) => ({ - name, - source: statementText(text, statement, comments), - })), + statement, + boundNames, + Option.map((names): readonly [Statement, ScopeStatement] => [ + statement, + { names, ...statementText(statement, file) }, + ]), ), ), - Array.groupBy(({ name }) => name), - Record.map(Array.map(({ source }) => source)), - ), - exports: pipe( - program.body, - Array.filter(isExportNamed), - Array.flatMap((statement) => - pipe( - statement.specifiers, - Array.map((specifier) => { - const single: ExportNamedDeclaration = { - ...statement, - specifiers: [specifier], - }; + ); - return [ - exportName(specifier.exported), - print(single, ts({ quotes: "double" })).code, - ] as const; - }), + return { + local: pipe( + scoped, + Array.flatMap(([statement, scope]) => + pipe( + declarationOf(statement), + Array.fromOption, + Array.flatMap(declaredNames), + Array.map((name) => ({ name, scope })), + ), ), + Array.groupBy(Struct.get("name")), + Record.map(Array.map(Struct.get("scope"))), ), - Record.fromEntries, - ), -}); + statements: Array.map(scoped, Tuple.get(1)), + }; +}; /** Reads TypeScript modules with oxc, each file once per run, and resolves their specifiers. */ export class Sources extends Context.Service< @@ -327,7 +227,7 @@ export class Sources extends Context.Service< { /** The imports, re-exports and comments of a module. */ readonly scope: (file: string) => Effect.Effect<Scope, TransformError>; - /** The declarations and export specifiers of a declaration file. */ + /** The imports and declarations of a declaration file. */ readonly declarations: ( file: string, ) => Effect.Effect<Declarations, TransformError>; @@ -350,48 +250,38 @@ export const layer: Layer.Layer<Sources, never, FileSystem.FileSystem> = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const read = ( - file: string, - ): Effect.Effect< - Pick<ReturnType<typeof parseSync>, "program" | "comments"> & { - readonly text: string; + const read = Effect.fnUntraced( + function* (file: string) { + const text = yield* fs.readFileString(file); + const parsed = yield* parse(text, file); + + return { ...parsed, text }; }, - TransformError - > => - fs.readFileString(file).pipe( - Effect.mapError(TransformError.fileSystem), - Effect.flatMap((text) => - parse(file, text).pipe( - Effect.map((parsed) => ({ ...parsed, text })), - ), - ), - ); + Effect.catchTag("PlatformError", TransformError.fileSystem), + ); const scopes = yield* Cache.make({ capacity: Number.POSITIVE_INFINITY, - lookup: (file: string) => - read(file).pipe( - Effect.map( - ({ text, program, comments }): Scope => ({ - ...collectScope(program), - text, - comments: pipe( - comments, - Array.filter(({ type }) => type === "Block"), - ), - }), - ), + lookup: flow( + read, + Effect.map( + ({ text, program, comments }): Scope => ({ + ...collectScope(program), + text, + comments: Array.filter(comments, ({ type }) => type === "Block"), + }), ), + ), }); const declarations = yield* Cache.make({ capacity: Number.POSITIVE_INFINITY, - lookup: (file: string) => - read(file).pipe( - Effect.map(({ text, program, comments }) => - collectDeclarations(text, program, comments), - ), + lookup: flow( + read, + Effect.map(({ text, ...parsed }) => + collectDeclarations(text, parsed), ), + ), }); return Sources.of({ diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts new file mode 100644 index 00000000000..206e438cfba --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Statements.ts @@ -0,0 +1,251 @@ +/** + * The top-level statements of a TypeScript module: which names each brings into scope, and its text without comments. + * + * @module + */ +import { Array, Filter, Function, Option, Order, String, pipe } from "effect"; +import { Visitor } from "oxc-parser"; + +import type { + BindingPattern, + Comment, + Declaration, + ExportAllDeclaration, + ExportNamedDeclaration, + ImportDeclaration, + Program, + Statement, + StringLiteral, + TSImportEqualsDeclaration, + TSQualifiedName, +} from "oxc-parser"; + +/** A module specifier in a statement's text. */ +export interface Specifier { + /** Where its string literal starts in the text, quotes included. */ + readonly start: number; + readonly end: number; + readonly value: string; +} + +/** A top-level statement of a declaration file that brings names into its scope: an import or a declaration. */ +export interface ScopeStatement { + /** The names it binds. */ + readonly names: readonly string[]; + /** Its text without comments. */ + readonly text: string; + /** The module specifiers its text names, in order. */ + readonly specifiers: readonly Specifier[]; +} + +export const isImport = ( + statement: Statement, +): statement is ImportDeclaration => statement.type === "ImportDeclaration"; + +const isImportEquals = ( + statement: Statement, +): statement is TSImportEqualsDeclaration => + statement.type === "TSImportEqualsDeclaration"; + +export const isExportAll = ( + statement: Statement, +): statement is ExportAllDeclaration => + statement.type === "ExportAllDeclaration"; + +export const isExportNamed = ( + statement: Statement, +): statement is ExportNamedDeclaration => + statement.type === "ExportNamedDeclaration"; + +const declarationTypes: ReadonlySet<string> = new Set([ + "VariableDeclaration", + "FunctionDeclaration", + "TSDeclareFunction", + "ClassDeclaration", + "TSTypeAliasDeclaration", + "TSInterfaceDeclaration", + "TSEnumDeclaration", + "TSModuleDeclaration", +] satisfies Declaration["type"][]); + +const isDeclaration = (statement: Statement): statement is Declaration => + declarationTypes.has(statement.type); + +export const declarationOf = ( + statement: Statement, +): Option.Option<Declaration> => { + if (statement.type === "ExportNamedDeclaration") { + return Option.fromNullishOr(statement.declaration); + } + + return Option.liftPredicate(statement, isDeclaration); +}; + +// Destructuring patterns and string-named modules declare no name a member can have. +const identifierName = ( + node: BindingPattern | StringLiteral | TSQualifiedName | null, +): Option.Option<string> => { + if (node?.type === "Identifier") { + return Option.some(node.name); + } + + return Option.none(); +}; + +export const declaredNames = (declaration: Declaration): readonly string[] => { + if (declaration.type === "VariableDeclaration") { + return Array.filterMap( + declaration.declarations, + Filter.fromPredicateOption(({ id }) => identifierName(id)), + ); + } + + return Array.fromOption(identifierName(declaration.id)); +}; + +// The names a statement brings into the file's scope, `None` for a statement that binds none, such as an export specifier. +export const boundNames = ( + statement: Statement, +): Option.Option<readonly string[]> => { + if (isImport(statement)) { + return Option.some( + Array.map(statement.specifiers, ({ local }) => local.name), + ); + } + + if (isImportEquals(statement)) { + return Option.some([statement.id.name]); + } + + return Option.map(declarationOf(statement), declaredNames); +}; + +// The module specifiers a statement names: its own source, and those of `import("…")` types and `require("…")` references inside it. +export const specifierLiterals = ( + program: Program, +): readonly StringLiteral[] => { + const literals: StringLiteral[] = []; + const collect = (literal: StringLiteral): void => { + literals.push(literal); + }; + + new Visitor({ + ImportDeclaration: ({ source }): void => { + collect(source); + }, + TSImportType: ({ source }): void => { + collect(source); + }, + TSExternalModuleReference: ({ expression }): void => { + collect(expression); + }, + }).visit(program); + + return literals; +}; + +/** A range of a file's text that a statement's text leaves out or names as a specifier. */ +interface Cut { + readonly start: number; + readonly end: number; + readonly specifier: Option.Option<string>; +} + +// A comment alone on its lines leaves with those lines, so removing it leaves no blank line behind. +const commentRange = ( + text: string, + comment: Comment, +): { readonly start: number; readonly end: number } => { + const lineStart = text.lastIndexOf("\n", comment.start - 1) + 1; + const lineEnd = text.indexOf("\n", comment.end); + + if ( + lineEnd !== -1 && + String.isEmpty(String.trim(text.slice(lineStart, comment.start))) && + String.isEmpty(String.trim(text.slice(comment.end, lineEnd))) + ) { + return { start: lineStart, end: lineEnd + 1 }; + } + + return { start: comment.start, end: comment.end }; +}; + +/** A declaration file's text and the parts of it that statements cut out or name. */ +export interface File { + readonly text: string; + readonly comments: readonly Comment[]; + readonly literals: readonly StringLiteral[]; +} + +const textOf = ( + statement: Statement, + { text, comments, literals }: File, +): Omit<ScopeStatement, "names"> => { + const within = ({ start, end }: { start: number; end: number }): boolean => + start >= statement.start && end <= statement.end; + const cuts = pipe( + [ + ...pipe( + comments, + Array.filter(within), + Array.map( + (comment): Cut => ({ + ...commentRange(text, comment), + specifier: Option.none(), + }), + ), + ), + ...pipe( + literals, + Array.filter(within), + Array.map( + ({ start, end, value }): Cut => ({ + start, + end, + specifier: Option.some(value), + }), + ), + ), + ], + Array.sortWith((cut: Cut) => cut.start, Order.Number), + ); + const result = Array.reduce( + cuts, + { + position: statement.start, + text: "", + specifiers: Array.empty<Specifier>(), + }, + ({ position, text: written, specifiers }, { start, end, specifier }) => { + const before = `${written}${text.slice(position, Math.max(position, start))}`; + + return Option.match(specifier, { + onNone: () => ({ + position: Math.max(position, end), + text: before, + specifiers, + }), + onSome: (value) => ({ + position: end, + text: `${before}${text.slice(start, end)}`, + specifiers: Array.append(specifiers, { + start: before.length, + end: before.length + end - start, + value, + }), + }), + }); + }, + ); + + return { + text: `${result.text}${text.slice(result.position, statement.end)}`, + specifiers: result.specifiers, + }; +}; + +/** A statement's text without the comments inside it, with the offsets of its specifiers in that text. */ +export const statementText: { + (file: File): (statement: Statement) => Omit<ScopeStatement, "names">; + (statement: Statement, file: File): Omit<ScopeStatement, "names">; +} = Function.dual(2, textOf); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts index b3d2a77a459..f0e2d155eb2 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts @@ -7,7 +7,6 @@ import { Path, Schema, identity, - pipe, } from "effect"; import { Command, Flag } from "effect/cli"; @@ -27,12 +26,8 @@ const Meta = Schema.fromJsonString( const packageDirectory = ( ...segments: string[] ): Effect.Effect<string, never, Path.Path> => - Effect.suspend(() => - Path.Path.pipe( - Effect.map((path) => - path.resolve(import.meta.dirname, "..", ...segments), - ), - ), + Effect.map(Path.Path, (path) => + path.resolve(import.meta.dirname, "..", ...segments), ); export const command = Command.make("transform", { @@ -65,47 +60,38 @@ const fileOf = (path: Path.Path, out: string, page: Site.Page): string => }), )}.mdx`; -const write = Effect.fnUntraced(function* (out: string) { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { pages } = yield* Site.Site; - // Encoding a literal of the schema's own type cannot fail. - const meta = yield* Schema.encodeEffect(Meta)({ - title: "API reference", - pages: ["index", "..."], - }).pipe(Effect.orDie); - - yield* fs - .remove(out, { recursive: true, force: true }) - .pipe(Effect.mapError(TransformError.fileSystem)); +const write = Effect.fnUntraced( + function* (out: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { pages } = yield* Site.Site; - yield* pipe( - pages, - Effect.forEach((page) => { - const file = fileOf(path, out, page); + // Encoding a literal of the schema's own type cannot fail. + const meta = yield* Schema.encodeEffect(Meta)({ + title: "API reference", + pages: ["index", "..."], + }).pipe(Effect.orDie); - return Page.render(page).pipe( - Effect.flatMap((tree) => - fs - .makeDirectory(path.dirname(file), { recursive: true }) - .pipe( - Effect.andThen(fs.writeFileString(file, Mdx.stringify(tree))), - Effect.mapError(TransformError.fileSystem), - ), - ), - ); - }), - ); + yield* fs.remove(out, { recursive: true, force: true }); + yield* Effect.forEach( + pages, + Effect.fnUntraced(function* (page) { + const file = fileOf(path, out, page); + const tree = yield* Page.render(page); - yield* fs - .writeFileString(path.join(out, "meta.json"), meta) - .pipe(Effect.mapError(TransformError.fileSystem)); - yield* Effect.log(`Wrote ${pages.length} pages to ${out}`); -}); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, Mdx.stringify(tree)); + }), + ); + yield* fs.writeFileString(path.join(out, "meta.json"), meta); + yield* Effect.log(`Wrote ${pages.length} pages to ${out}`); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); export const handler = command.pipe( Command.withHandler(({ out }) => - Path.Path.pipe(Effect.flatMap((path) => write(path.resolve(out)))), + Effect.flatMap(Path.Path, (path) => write(path.resolve(out))), ), Command.provide(({ lib, analysis, url }) => Site.layer({ url }).pipe( diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts index 48a1ee490c6..62f6428b9ae 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts @@ -23,6 +23,12 @@ export type Reason = Data.TaggedEnum<{ MalformedAnalysis: { readonly detail: string }; /** A documentation comment uses TSDoc syntax the pages have no rendering for. */ UnsupportedComment: { readonly kind: string }; + /** A signature block's meta holds a `links` attribute that the transform did not write. */ + UnreadableCodeBlock: { + readonly cause: Schema.SchemaError | Cause.UnknownError; + }; + /** A signature block's code refers to a different number of names than its links cover. */ + MisalignedCodeBlock: { readonly references: number; readonly links: number }; }>; /** Constructors and matching helpers for the tagged {@link Reason} variants. */ @@ -64,6 +70,19 @@ export class TransformError extends TransformErrorBase<{ static readonly unsupportedComment = (kind: string): TransformError => new TransformError({ reason: Reason.UnsupportedComment({ kind }) }); + static readonly unreadableCodeBlock = ( + cause: Schema.SchemaError | Cause.UnknownError, + ): TransformError => + new TransformError({ reason: Reason.UnreadableCodeBlock({ cause }) }); + + static readonly misalignedCodeBlock = ( + references: number, + links: number, + ): TransformError => + new TransformError({ + reason: Reason.MisalignedCodeBlock({ references, links }), + }); + override get message(): string { return Reason.$match(this.reason, { FileSystem: ({ cause }) => cause.message, @@ -74,6 +93,10 @@ export class TransformError extends TransformErrorBase<{ MalformedAnalysis: ({ detail }) => detail, UnsupportedComment: ({ kind }) => `Documentation comments use ${kind}, which the reference pages cannot render`, + UnreadableCodeBlock: ({ cause }) => + `A signature block's links do not decode: ${cause.message}`, + MisalignedCodeBlock: ({ references, links }) => + `A signature block's code refers to ${references} names, but its links cover ${links}`, }); } } diff --git a/yarn.lock b/yarn.lock index a3d96c54d12..c4dbcc7183c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10239,7 +10239,6 @@ __metadata: "@local/hashql": "workspace:*" "@local/oxlint": "workspace:*" "@local/tsconfig": "workspace:*" - "@microsoft/api-documenter": "npm:7.30.18" "@microsoft/api-extractor": "npm:7.59.4" "@microsoft/api-extractor-model": "npm:7.33.15" "@microsoft/tsdoc": "npm:0.17.1" @@ -10253,7 +10252,6 @@ __metadata: "@types/react": "npm:19.2.14" "@types/react-dom": "npm:19.2.3" effect: "npm:4.0.0" - esrap: "npm:2.4.0" fumadocs-core: "npm:16.16.2" fumadocs-mdx: "npm:15.4.6" fumadocs-twoslash: "npm:4.0.1" @@ -10267,7 +10265,6 @@ __metadata: react-dom: "npm:19.2.6" remark-frontmatter: "npm:5.0.0" remark-mdx: "npm:3.1.1" - remark-parse: "npm:11.0.0" remark-stringify: "npm:11.0.0" satteri: "npm:0.10.5" shiki: "npm:4.5.0" @@ -10669,23 +10666,6 @@ __metadata: languageName: node linkType: hard -"@microsoft/api-documenter@npm:7.30.18": - version: 7.30.18 - resolution: "@microsoft/api-documenter@npm:7.30.18" - dependencies: - "@microsoft/api-extractor-model": "npm:7.33.15" - "@microsoft/tsdoc": "npm:~0.17.0" - "@rushstack/node-core-library": "npm:5.25.1" - "@rushstack/terminal": "npm:0.24.7" - "@rushstack/ts-command-line": "npm:5.3.17" - js-yaml: "npm:~4.3.2" - resolve: "npm:~1.22.1" - bin: - api-documenter: bin/api-documenter - checksum: 10c0/47277a9a10a2c916ffb6cf1d918a9a78002ea09d3743f1c9449af42855166227aad9c80d5b2bc298c71d658bfb155f0298480c5fc7c6e38637d308f5b2a116db - languageName: node - linkType: hard - "@microsoft/api-extractor-model@npm:7.33.15": version: 7.33.15 resolution: "@microsoft/api-extractor-model@npm:7.33.15" @@ -34342,7 +34322,7 @@ __metadata: languageName: node linkType: hard -"js-yaml@npm:4.3.2, js-yaml@npm:^4.1.0, js-yaml@npm:^4.1.1, js-yaml@npm:^4.3.0, js-yaml@npm:~4.3.2": +"js-yaml@npm:4.3.2, js-yaml@npm:^4.1.0, js-yaml@npm:^4.1.1, js-yaml@npm:^4.3.0": version: 4.3.2 resolution: "js-yaml@npm:4.3.2" dependencies: @@ -42213,7 +42193,7 @@ __metadata: languageName: node linkType: hard -"remark-parse@npm:11.0.0, remark-parse@npm:^11.0.0": +"remark-parse@npm:^11.0.0": version: 11.0.0 resolution: "remark-parse@npm:11.0.0" dependencies: From bf34383b282d1c4f3414c742801681335333568a Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:08:20 +0200 Subject: [PATCH 20/22] feat: add namespace index cards --- .../components/index-entry.tsx | 30 +++++ .../sdk/typescript-docs/components/mdx.tsx | 2 + .../sdk/typescript-docs/oxlint.config.ts | 6 + .../hashql/sdk/typescript-docs/package.json | 1 + .../hashql/sdk/typescript-docs/src/Listing.ts | 110 ++++++++++++++++++ .../hashql/sdk/typescript-docs/src/Mdx.ts | 22 +++- .../hashql/sdk/typescript-docs/src/Page.ts | 99 +++------------- .../sdk/typescript-docs/src/Signature.test.ts | 14 +-- .../hashql/sdk/typescript-docs/src/Site.ts | 60 +++++----- .../sdk/typescript-docs/src/Transform.ts | 56 +++++---- .../hashql/sdk/typescript/docs/authoring.md | 2 +- .../typescript/examples/api-tour.test-d.ts | 2 +- .../typescript/examples/filters-draft.test.ts | 2 +- .../sdk/typescript/examples/filters-draft.ts | 2 +- .../hashql/sdk/typescript/examples/filters.ts | 2 +- .../typescript/src/{jexpr => JExpr}/Call.ts | 0 .../typescript/src/{jexpr => JExpr}/Dict.ts | 0 .../typescript/src/{jexpr => JExpr}/Float.ts | 0 .../src/{jexpr => JExpr}/Function.ts | 2 +- .../typescript/src/{jexpr => JExpr}/Ident.ts | 0 .../src/{jexpr => JExpr}/Identifier.ts | 0 .../src/{jexpr => JExpr}/Integer.ts | 0 .../src/{jexpr => JExpr}/LabeledArgument.ts | 0 .../typescript/src/{jexpr => JExpr}/List.ts | 0 .../src/{jexpr => JExpr}/Literal.ts | 0 .../typescript/src/{jexpr => JExpr}/Path.ts | 0 .../typescript/src/{jexpr => JExpr}/Struct.ts | 0 .../typescript/src/{jexpr => JExpr}/Tuple.ts | 0 .../type => JExpr/Type}/Expression.test.ts | 0 .../src/{jexpr/type => JExpr/Type}/Generic.ts | 0 .../type => JExpr/Type}/GenericArgument.ts | 0 .../type => JExpr/Type}/GenericBound.ts | 0 .../type => JExpr/Type}/Intersection.ts | 0 .../{jexpr/type => JExpr/Type}/Reference.ts | 0 .../src/{jexpr/type => JExpr/Type}/Struct.ts | 0 .../src/{jexpr/type => JExpr/Type}/Tuple.ts | 0 .../src/{jexpr/type => JExpr/Type}/Union.ts | 0 .../src/{jexpr/type => JExpr/Type}/index.ts | 0 .../src/{jexpr/type => JExpr/Type}/schema.ts | 0 .../src/{jexpr => JExpr}/compile.ts | 0 .../typescript/src/{jexpr => JExpr}/index.ts | 4 +- .../typescript/src/{jexpr => JExpr}/schema.ts | 0 .../{program/ast => Program/AST}/Binding.ts | 2 +- .../src/{program/ast => Program/AST}/Expr.ts | 2 +- .../src/{program/ast => Program/AST}/If.ts | 2 +- .../{program/ast => Program/AST}/Import.ts | 4 +- .../src/{program/ast => Program/AST}/Let.ts | 4 +- .../{program/ast => Program/AST}/Newtype.ts | 6 +- .../src/{program/ast => Program/AST}/Node.ts | 2 +- .../src/{program/ast => Program/AST}/Type.ts | 6 +- .../src/{program/ast => Program/AST}/index.ts | 0 .../{program => Program}/Expression.test-d.ts | 2 +- .../{program => Program}/Expression.test.ts | 4 +- .../src/{program => Program}/Expression.ts | 6 +- .../{program => Program}/ExpressionType.ts | 2 +- .../src/{program => Program}/Import.ts | 4 +- .../src/{program => Program}/Inputs.test-d.ts | 0 .../src/{program => Program}/Inputs.test.ts | 0 .../src/{program => Program}/Inputs.ts | 2 +- .../src/{program => Program}/Module.test-d.ts | 4 +- .../src/{program => Program}/Module.test.ts | 6 +- .../src/{program => Program}/Module.ts | 4 +- .../{program => Program}/Namespace.test-d.ts | 2 +- .../{program => Program}/Namespace.test.ts | 6 +- .../src/{program => Program}/Namespace.ts | 0 .../{program => Program}/Operators.test-d.ts | 0 .../{program => Program}/Operators.test.ts | 0 .../src/{program => Program}/Operators.ts | 6 +- .../src/{program => Program}/Prelude.ts | 2 +- .../src/{program => Program}/PreludeTypes.ts | 2 +- .../{program => Program}/Primitive.test-d.ts | 0 .../{program => Program}/Primitive.test.ts | 0 .../src/{program => Program}/ProgramError.ts | 0 .../src/{program => Program}/Query.test-d.ts | 0 .../src/{program => Program}/Query.test.ts | 0 .../src/{program => Program}/Query.ts | 6 +- .../src/{program => Program}/Scope.ts | 0 .../{program => Program}/Structural.test-d.ts | 4 +- .../{program => Program}/Structural.test.ts | 6 +- .../src/{program => Program}/Structural.ts | 6 +- .../{program => Program}/TypeExpression.ts | 6 +- .../src/{program => Program}/index.ts | 4 +- .../src/{type => Type}/index.test-d.ts | 0 .../typescript/src/{type => Type}/index.ts | 0 .../hashql/sdk/typescript/src/do/Do.test-d.ts | 2 +- .../hashql/sdk/typescript/src/do/Do.test.ts | 12 +- .../@local/hashql/sdk/typescript/src/do/Do.ts | 10 +- .../sdk/typescript/src/do/Import.test-d.ts | 2 +- .../hashql/sdk/typescript/src/do/Import.ts | 10 +- .../hashql/sdk/typescript/src/do/Let.ts | 12 +- .../hashql/sdk/typescript/src/do/Newtype.ts | 16 +-- .../hashql/sdk/typescript/src/do/Node.ts | 6 +- .../hashql/sdk/typescript/src/do/Type.ts | 12 +- .../hashql/sdk/typescript/src/do/Utilities.ts | 22 ++-- .../hashql/sdk/typescript/src/do/index.ts | 6 +- .../hashql/sdk/typescript/src/draft/Body.ts | 12 +- .../src/draft/Construction.test-d.ts | 4 +- .../typescript/src/draft/Construction.test.ts | 2 +- .../sdk/typescript/src/draft/Context.ts | 12 +- .../sdk/typescript/src/draft/Import.test.ts | 2 +- .../typescript/src/draft/Namespace.test.ts | 2 +- .../src/draft/Requirements.test-d.ts | 2 +- .../hashql/sdk/typescript/src/draft/Scribe.ts | 12 +- .../sdk/typescript/src/draft/fixtures.ts | 2 +- .../hashql/sdk/typescript/src/draft/index.ts | 10 +- .../sdk/typescript/src/internal/relocation.ts | 4 +- libs/@local/hashql/sdk/typescript/src/main.ts | 26 ++--- yarn.lock | 3 +- 108 files changed, 428 insertions(+), 303 deletions(-) create mode 100644 libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx create mode 100644 libs/@local/hashql/sdk/typescript-docs/src/Listing.ts rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Call.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Dict.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Float.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Function.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Ident.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Identifier.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Integer.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/LabeledArgument.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/List.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Literal.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Path.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Struct.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/Tuple.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Expression.test.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Generic.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/GenericArgument.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/GenericBound.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Intersection.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Reference.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Struct.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Tuple.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/Union.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/index.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr/type => JExpr/Type}/schema.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/compile.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/index.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{jexpr => JExpr}/schema.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Binding.ts (93%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Expr.ts (83%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/If.ts (91%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Import.ts (84%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Let.ts (83%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Newtype.ts (76%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Node.ts (81%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/Type.ts (76%) rename libs/@local/hashql/sdk/typescript/src/{program/ast => Program/AST}/index.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Expression.test-d.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Expression.test.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Expression.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/ExpressionType.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Import.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Inputs.test-d.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Inputs.test.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Inputs.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Module.test-d.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Module.test.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Module.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Namespace.test-d.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Namespace.test.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Namespace.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Operators.test-d.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Operators.test.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Operators.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Prelude.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/PreludeTypes.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Primitive.test-d.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Primitive.test.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/ProgramError.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Query.test-d.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Query.test.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Query.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Scope.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Structural.test-d.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Structural.test.ts (96%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/Structural.ts (99%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/TypeExpression.ts (98%) rename libs/@local/hashql/sdk/typescript/src/{program => Program}/index.ts (96%) rename libs/@local/hashql/sdk/typescript/src/{type => Type}/index.test-d.ts (100%) rename libs/@local/hashql/sdk/typescript/src/{type => Type}/index.ts (100%) diff --git a/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx new file mode 100644 index 00000000000..e9880dc642c --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/components/index-entry.tsx @@ -0,0 +1,30 @@ +import { Card } from "fumadocs-ui/components/card"; + +import type { ReactNode } from "react"; + +/** A link to a page or a folder, showing its name and size above the summary its module comment opens with. */ +export const IndexEntry = ({ + name, + count, + href, + children, +}: { + name: string; + count: string; + href: string; + children?: ReactNode; +}): ReactNode => ( + <Card + href={href} + title={ + <span className="flex items-baseline justify-between gap-3"> + <span className="font-mono">{name}</span> + <span className="text-fd-muted-foreground shrink-0 font-mono text-xs font-normal"> + {count} + </span> + </span> + } + > + {children} + </Card> +); diff --git a/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx index 1e0062fb6fc..ab114ff0f60 100644 --- a/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx +++ b/libs/@local/hashql/sdk/typescript-docs/components/mdx.tsx @@ -1,6 +1,7 @@ import { Popup, PopupContent } from "fumadocs-twoslash/ui"; import defaultComponents from "fumadocs-ui/mdx"; +import { IndexEntry } from "./index-entry"; import { ReferenceTrigger } from "./reference-trigger"; import type { MDXComponents } from "mdx/types"; @@ -9,6 +10,7 @@ export const getMDXComponents = ( components?: MDXComponents, ): MDXComponents => ({ ...defaultComponents, + IndexEntry, Popup, PopupContent, PopupTrigger: ReferenceTrigger, diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index 7b3c39a369f..f1ab879f567 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -64,6 +64,12 @@ export default defineConfig({ "jsx-a11y/no-redundant-roles": "allow", // The link role overrides Base UI's non-native button role. }, }, + { + files: ["components/index-entry.tsx"], + rules: { + "react-perf/jsx-no-jsx-as-prop": "allow", // Fumadocs' Card takes its title as a node, which carries the count beside the name. These server components render once. + }, + }, { files: ["lib/reference-links.ts"], rules: { diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index 2f257e466a2..49b20e70c45 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -48,6 +48,7 @@ "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "effect": "4.0.0", + "mdast-util-mdx-jsx": "3.1.3", "oxc-parser": "0.152.0", "oxc-resolver": "11.24.2", "oxfmt": "0.71.0", diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts new file mode 100644 index 00000000000..aabc67023e1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript-docs/src/Listing.ts @@ -0,0 +1,110 @@ +import { Array, Effect, Match, Option, Record, Struct, pipe } from "effect"; + +import { Analysis } from "./Analysis.js"; +import * as Comment from "./Comment.js"; +import { Site, withLinks } from "./Site.js"; + +import type { Page } from "./Site.js"; +import type { TransformError } from "./TransformError.js"; +import type { PhrasingContent } from "mdast"; +import type { MdxJsxFlowElement } from "mdast-util-mdx-jsx"; + +// A JSX element whose attributes are all strings, rendered by one of the site's MDX components. +const element = ( + name: string, + attributes: Record.ReadonlyRecord<string, string>, + children: MdxJsxFlowElement["children"], +): MdxJsxFlowElement => ({ + type: "mdxJsxFlowElement", + name, + attributes: pipe( + attributes, + Record.toEntries, + Array.map(([key, value]) => ({ + type: "mdxJsxAttribute", + name: key, + value, + })), + ), + children, +}); + +const counted = (count: number, noun: string): string => { + if (count === 1) { + return `${count} ${noun}`; + } + + return `${count} ${noun}s`; +}; + +// An entry is a link, and a reader could not follow a link inside it, so the entry keeps a link's label alone. +const unlinked: (node: PhrasingContent) => PhrasingContent[] = + Match.type<PhrasingContent>().pipe( + Match.discriminators("type")({ + link: ({ children }) => Array.flatMap(children, unlinked), + linkReference: ({ children }) => Array.flatMap(children, unlinked), + emphasis: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + strong: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + delete: (node) => [ + { ...node, children: Array.flatMap(node.children, unlinked) }, + ], + }), + Match.orElse((node) => [node]), + ); + +// A page's entry counts the names the page documents and carries the first paragraph of its module's comment. +const pageEntry = Effect.fnUntraced(function* (page: Page) { + const analysis = yield* Analysis; + const site = yield* Site; + + const file = Array.headNonEmpty(page.modules); + const comment = yield* analysis.moduleComment(file); + const lead = yield* Option.match(comment, { + onNone: () => Effect.succeed([]), + onSome: (found) => + withLinks( + { module: file, container: page.container }, + Comment.lead(found), + ), + }); + const names = pipe( + page.container.members, + Array.map(Struct.get("displayName")), + Array.dedupe, + ); + + return element( + "IndexEntry", + { + name: page.title, + count: counted(names.length, "member"), + href: site.url(page), + }, + pipe( + Array.flatMap(lead, unlinked), + Option.liftPredicate(Array.isArrayNonEmpty), + Option.match({ + onNone: () => [], + onSome: (children) => [{ type: "paragraph", children }], + }), + ), + ); +}); + +/** Entries for a page's namespace pages, as one grid of cards. */ +export const namespaces = ( + children: readonly Page[], +): Effect.Effect<MdxJsxFlowElement[], TransformError, Analysis | Site> => + pipe( + Effect.forEach(children, pageEntry), + Effect.map((found) => + Array.match(found, { + onEmpty: () => [], + onNonEmpty: (entries) => [element("Cards", {}, [...entries])], + }), + ), + ); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts index 4023ff1027d..75bea3c378f 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Mdx.ts @@ -1,7 +1,9 @@ +import { Function, String } from "effect"; import remarkFrontmatter from "remark-frontmatter"; import remarkMdx from "remark-mdx"; import remarkStringify from "remark-stringify"; import { unified } from "unified"; +import * as Yaml from "yaml"; import type { Root } from "mdast"; @@ -11,5 +13,21 @@ const processor = unified() .use(remarkFrontmatter) .use(remarkMdx); -/** Serializes a page's mdast, frontmatter included, as MDX. */ -export const stringify = (tree: Root): string => processor.stringify(tree); +/** A page's frontmatter, which Fumadocs reads its title from. */ +export interface Frontmatter { + readonly title: string; +} + +/** Serializes a page's mdast as MDX, under its frontmatter. */ +export const stringify: { + (frontmatter: Frontmatter): (tree: Root) => string; + (tree: Root, frontmatter: Frontmatter): string; +} = Function.dual(2, (tree: Root, frontmatter: Frontmatter): string => + processor.stringify({ + ...tree, + children: [ + { type: "yaml", value: String.trimEnd(Yaml.stringify(frontmatter)) }, + ...tree.children, + ], + }), +); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts index 9a8165d355c..23c53918494 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Page.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Page.ts @@ -1,35 +1,16 @@ -import { - Array, - Effect, - Option, - Record, - Result, - String, - Struct, - pipe, -} from "effect"; -import { stringify } from "yaml"; +import { Array, Effect, Option, Record, Result, Struct, pipe } from "effect"; import { Analysis } from "./Analysis.js"; import * as Comment from "./Comment.js"; +import * as Listing from "./Listing.js"; import * as Member from "./Member.js"; import * as Signature from "./Signature.js"; -import { Site } from "./Site.js"; +import { Site, withLinks } from "./Site.js"; import { TransformError } from "./TransformError.js"; -import type { Origin, Page } from "./Site.js"; +import type { Page } from "./Site.js"; import type { ApiItem } from "@microsoft/api-extractor-model"; -import type { BlockContent, ListItem, PhrasingContent, Root } from "mdast"; - -const withLinks = Effect.fnUntraced(function* <A>( - origin: Origin, - effect: Effect.Effect<A, TransformError, Comment.Links>, -) { - const site = yield* Site; - const links = yield* site.links(origin); - - return yield* Effect.provideService(effect, Comment.Links, links); -}); +import type { BlockContent, Root } from "mdast"; // The modules' own comments open the page, each linking from its module. const overview = Effect.fnUntraced(function* (page: Page) { @@ -57,46 +38,6 @@ const overview = Effect.fnUntraced(function* (page: Page) { ); }); -// A child page's entry carries the first paragraph of its module's comment. -const childEntry = Effect.fnUntraced(function* (child: Page) { - const analysis = yield* Analysis; - const site = yield* Site; - - const file = Array.headNonEmpty(child.modules); - const comment = yield* analysis.moduleComment(file); - const summary = yield* Option.match(comment, { - onNone: () => Effect.succeed([]), - onSome: (found) => - withLinks( - { module: file, container: child.container }, - Comment.lead(found), - ), - }); - const title: PhrasingContent = { - type: "link", - url: site.url(child), - children: [{ type: "inlineCode", value: child.title }], - }; - - return { - type: "listItem", - spread: false, - children: [ - { - type: "paragraph", - children: Array.match(summary, { - onEmpty: () => [title], - onNonEmpty: (lead) => [ - title, - { type: "text", value: " — " }, - ...lead, - ], - }), - }, - ], - } satisfies ListItem; -}); - const member = Effect.fnUntraced(function* ( page: Page, items: Array.NonEmptyReadonlyArray<ApiItem>, @@ -149,18 +90,18 @@ const heading = (value: string): BlockContent => ({ const namespaces = ( children: readonly Page[], ): Effect.Effect<BlockContent[], TransformError, Analysis | Site> => - Array.match(children, { - onEmpty: () => Effect.succeed([]), - onNonEmpty: (pages) => - pipe( - pages, - Effect.forEach(childEntry), - Effect.map((entries): BlockContent[] => [ + pipe( + Listing.namespaces(children), + Effect.map( + Array.match({ + onEmpty: (): BlockContent[] => [], + onNonEmpty: (found): BlockContent[] => [ heading("Namespaces"), - { type: "list", ordered: false, spread: false, children: entries }, - ]), - ), - }); + ...found, + ], + }), + ), + ); // Rendered members under their group headings, in the groups' order. const sections = ( @@ -200,11 +141,5 @@ export const render = Effect.fnUntraced(function* (page: Page) { ), ]); - return { - type: "root", - children: [ - { type: "yaml", value: String.trimEnd(stringify({ title: page.title })) }, - ...Array.flatten(body), - ], - } satisfies Root; + return { type: "root", children: Array.flatten(body) } satisfies Root; }); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts index 776d47a72c4..640e8188cc7 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Signature.test.ts @@ -6,15 +6,15 @@ import * as Sources from "./Sources.js"; import type { TransformError } from "./TransformError.js"; -const declaration = "/declarations/program/Module.d.ts"; +const declaration = "/declarations/Program/Module.d.ts"; const files: Record.ReadonlyRecord<string, string> = { - "/src/program/Module.ts": [ + "/src/Program/Module.ts": [ "declare function conditional(): void;", "export { conditional as if };", ].join("\n"), [declaration]: [ - 'import * as Type from "../type/index.js";', + 'import * as Type from "../Type/index.js";', 'import type { Other } from "./Other.js";', 'import type { Types } from "effect";', "/** Not exported, so it has no page. */", @@ -54,10 +54,10 @@ const make = ( > => Signature.make({ name, - source: "/src/program/Module.ts", + source: "/src/Program/Module.ts", declaration, root: "/declarations", - exporters: ["/src/program/Module.ts"], + exporters: ["/src/Program/Module.ts"], }); // A reference reads as the text it spans and the path it resolves. @@ -109,8 +109,8 @@ describe("signature", () => { expect(context).toBe( [ - 'import * as Type from "#declarations/type/index.js";', - 'import type { Other } from "#declarations/program/Other.js";', + 'import * as Type from "#declarations/Type/index.js";', + 'import type { Other } from "#declarations/Program/Other.js";', 'import type { Types } from "effect";', "interface Hidden<T> {\n readonly value: T;\n}", "declare function conditional(): Types.Invariant<Other>;", diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts index c56c8322492..48fa9fad0c8 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -10,7 +10,6 @@ import { Option, Path, Record, - String, Struct, flow, pipe, @@ -70,6 +69,17 @@ export class Site extends Context.Service< } >()("@local/hashql-typescript-docs/Site") {} +/** Runs a comment's conversion with its links resolved from the comment's origin. */ +export const withLinks = Effect.fnUntraced(function* <A>( + origin: Origin, + effect: Effect.Effect<A, TransformError, Links>, +) { + const site = yield* Site; + const links = yield* site.links(origin); + + return yield* Effect.provideService(effect, Links, links); +}); + // Every declaration sharing the name, since an interface and a namespace merge under one. const members = (container: ApiItem, name: string): readonly ApiItem[] => { if (ApiItemContainerMixin.isBaseClassOf(container)) { @@ -88,14 +98,13 @@ const ancestors = (item: ApiItem): ApiItem[] => ), ); -const directorySegments = (path: Path.Path, directory: string): string[] => - pipe(directory, String.split(path.sep), Array.filter(String.isNonEmpty)); - -// A namespace that a module re-exports with `export * as` gets a page. A `namespace` declaration renders among its siblings. -const pageOfNamespace = Effect.fnUntraced(function* (item: ApiItem) { +// A namespace that a module re-exports with `export * as` gets a page below its parent's, so the URL nests as the names do. A `namespace` declaration renders among its siblings. +const pageOfNamespace = Effect.fnUntraced(function* ( + parent: Page, + item: ApiItem, +) { const analysis = yield* Analysis; const sources = yield* Sources; - const path = yield* Path.Path; const file = analysis.sourceOf(item); if (item.kind !== ApiItemKind.Namespace || Option.isNone(file)) { @@ -117,13 +126,9 @@ const pageOfNamespace = Effect.fnUntraced(function* (item: ApiItem) { ), ), ); - const directory = path.relative( - path.dirname(Array.headNonEmpty(analysis.roots)), - path.dirname(target), - ); return Option.some<Page>({ - path: [...directorySegments(path, directory), item.displayName], + path: [...parent.path, item.displayName], title: item.displayName, container: item, modules: [target], @@ -131,19 +136,18 @@ const pageOfNamespace = Effect.fnUntraced(function* (item: ApiItem) { }); const discover = ( - container: ApiItem, -): Effect.Effect<Page[], TransformError, Analysis | Sources | Path.Path> => + parent: Page, +): Effect.Effect<Page[], TransformError, Analysis | Sources> => pipe( - container.members, + parent.container.members, Effect.forEach((item) => pipe( - item, - pageOfNamespace, + pageOfNamespace(parent, item), Effect.flatMap( Option.match({ onNone: () => Effect.succeed(Array.empty<Page>()), onSome: (page) => - pipe(item, discover, Effect.map(Array.prepend(page))), + pipe(page, discover, Effect.map(Array.prepend(page))), }), ), ), @@ -179,6 +183,7 @@ const makeIndex = (pages: readonly Page[], url: string): Index => { const pageUrl = (page: Page): string => Array.join([url, ...page.path], "/"); const enclosing = (item: ApiItem): Option.Option<ApiItem> => pipe(item, ancestors, Array.findFirst(hasPage)); + const anchor = (item: ApiItem): string => pipe( item, @@ -303,6 +308,7 @@ const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { const scope = yield* sources.scope(origin.module); const resolution: Resolution = { index, origin, scope }; + // Links resolve the way TypeScript resolves them in the comment's module. A reference qualified from the package resolves last. const fromPackage: Lookup = (name) => members(analysis.entry, name); const target = resolveIn([ @@ -310,6 +316,7 @@ const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { imported(sources, resolution), fromPackage, ]); + const shown = path.relative( path.dirname(Array.headNonEmpty(analysis.roots)), origin.module, @@ -374,17 +381,16 @@ export const layer = ({ const analysis = yield* Analysis; const services = yield* Effect.context<Analysis | Sources | Path.Path>(); + const root: Page = { + path: [], + title: analysis.package.displayName, + container: analysis.entry, + modules: analysis.roots, + }; const pages = yield* pipe( - analysis.entry, + root, discover, - Effect.map( - Array.prepend<Page>({ - path: [], - title: analysis.package.displayName, - container: analysis.entry, - modules: analysis.roots, - }), - ), + Effect.map(Array.prepend(root)), ); const duplicate = pipe( pages, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts index f0e2d155eb2..3618c12b736 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts @@ -4,9 +4,10 @@ import { Effect, FileSystem, Layer, + Option, Path, Schema, - identity, + pipe, } from "effect"; import { Command, Flag } from "effect/cli"; @@ -50,21 +51,29 @@ export const command = Command.make("transform", { ), }); -// The package page is the folder's index page. -const fileOf = (path: Path.Path, out: string, page: Site.Page): string => - `${path.join( - out, - ...Array.match(page.path, { - onEmpty: () => ["index"], - onNonEmpty: identity, - }), - )}.mdx`; +// Fumadocs lists a directory's pages under its index page, so a page with namespace pages below it, the package page among them, is its directory's index. +const segmentsOf = ( + site: Site.Site["Service"], + page: Site.Page, +): readonly string[] => { + const isDirectory = + Array.isReadonlyArrayEmpty(page.path) || + Array.some(page.container.members, (item) => + Option.isSome(site.pageOf(item)), + ); + + if (isDirectory) { + return [...page.path, "index"]; + } + + return page.path; +}; const write = Effect.fnUntraced( function* (out: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const { pages } = yield* Site.Site; + const site = yield* Site.Site; // Encoding a literal of the schema's own type cannot fail. const meta = yield* Schema.encodeEffect(Meta)({ @@ -73,18 +82,25 @@ const write = Effect.fnUntraced( }).pipe(Effect.orDie); yield* fs.remove(out, { recursive: true, force: true }); - yield* Effect.forEach( - pages, - Effect.fnUntraced(function* (page) { - const file = fileOf(path, out, page); - const tree = yield* Page.render(page); + const writeMdx = Effect.fnUntraced(function* ( + segments: readonly string[], + content: string, + ) { + const file = `${path.join(out, ...segments)}.mdx`; + + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, content); + }); - yield* fs.makeDirectory(path.dirname(file), { recursive: true }); - yield* fs.writeFileString(file, Mdx.stringify(tree)); - }), + yield* Effect.forEach(site.pages, (page) => + pipe( + Page.render(page), + Effect.map(Mdx.stringify({ title: page.title })), + Effect.flatMap((content) => writeMdx(segmentsOf(site, page), content)), + ), ); yield* fs.writeFileString(path.join(out, "meta.json"), meta); - yield* Effect.log(`Wrote ${pages.length} pages to ${out}`); + yield* Effect.log(`Wrote ${site.pages.length} pages to ${out}`); }, Effect.catchTag("PlatformError", TransformError.fileSystem), ); diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md index 116f67e6126..c7c251ec962 100644 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ b/libs/@local/hashql/sdk/typescript/docs/authoring.md @@ -211,7 +211,7 @@ Expected construction failures return `ProgramError.Construction`. Invalid bindi ### Default prelude coverage and authority -`Prelude.builtin` contains representative declarations rather than a complete standard-library catalogue. Their export types derive from the declaration tables in [`Prelude.ts`](../src/program/Prelude.ts). [`PreludeTypes.ts`](../src/program/PreludeTypes.ts) supplies the nominal identities and generic semantic operations. Generated tables can use the same `Module.define` and `withPrelude` APIs. This package has no generator. +`Prelude.builtin` contains representative declarations rather than a complete standard-library catalogue. Their export types derive from the declaration tables in [`Prelude.ts`](../src/Program/Prelude.ts). [`PreludeTypes.ts`](../src/Program/PreludeTypes.ts) supplies the nominal identities and generic semantic operations. Generated tables can use the same `Module.define` and `withPrelude` APIs. This package has no generator. | Exports | Compiler source under `core/src/module/std_lib/` | | --------------------------------------------------------------------------- | ------------------------------------------------ | diff --git a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts index 0e60fbd2cc5..82c95986a66 100644 --- a/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/examples/api-tour.test-d.ts @@ -21,7 +21,7 @@ import { withPrelude, } from "../src/do/index.js"; import { Expression, Module, Program } from "../src/main.js"; -import * as Operators from "../src/program/Operators.js"; +import * as Operators from "../src/Program/Operators.js"; import type { Inputs, diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts index 15c5e269349..6081ff1681f 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts @@ -7,7 +7,7 @@ import { examples } from "./filters-draft.js"; import { examples as originals } from "./filters.js"; import type { Type } from "../src/main.js"; -import type * as ProgramError from "../src/program/ProgramError.js"; +import type * as ProgramError from "../src/Program/ProgramError.js"; import type { Entity, EntityUuid, diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts index b8b1c4daec0..13ad35765e0 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -21,7 +21,7 @@ import { } from "./filters-declarations.js"; import type { Expression, Inputs, Type } from "../src/main.js"; -import type * as ProgramError from "../src/program/ProgramError.js"; +import type * as ProgramError from "../src/Program/ProgramError.js"; import type { Entity, EntityUuid, diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts index f5bbc5ea3b7..f8c8d037ad7 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters.ts @@ -22,7 +22,7 @@ import { } from "./filters-declarations.js"; import type { Expression, Type } from "../src/main.js"; -import type * as ProgramError from "../src/program/ProgramError.js"; +import type * as ProgramError from "../src/Program/ProgramError.js"; const { Let, Do } = withPrelude({ values: { diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Call.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Call.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Dict.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Dict.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Float.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Float.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts index 44b11f32ed0..fcb5a4721e9 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/Function.ts +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Function.ts @@ -2,7 +2,7 @@ import { Record } from "effect"; import { pipe } from "effect/Function"; import { isReadonlyArray } from "../internal/array.js"; -import * as Type from "./type/index.js"; +import * as Type from "./Type/index.js"; import type * as Defs from "./schema.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Ident.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Ident.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Identifier.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Identifier.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Integer.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Integer.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/LabeledArgument.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/LabeledArgument.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/List.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/List.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/List.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/List.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Literal.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Literal.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Literal.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Path.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Struct.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Struct.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Struct.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Tuple.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/Tuple.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Tuple.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Expression.test.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Expression.test.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Expression.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Generic.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Generic.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Generic.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericArgument.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericArgument.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericArgument.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericBound.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/GenericBound.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/GenericBound.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Intersection.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Intersection.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Intersection.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Reference.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Reference.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Reference.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Struct.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Struct.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Struct.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Tuple.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Tuple.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Tuple.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/Union.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/Union.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/Union.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/index.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/index.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/index.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Type/schema.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/type/schema.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/Type/schema.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/compile.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/compile.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/compile.ts diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/index.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/jexpr/index.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/index.ts index 5c656420e41..19ff4c6a073 100644 --- a/libs/@local/hashql/sdk/typescript/src/jexpr/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/index.ts @@ -25,9 +25,9 @@ import { dual } from "effect/Function"; import { isReadonlyArray } from "../internal/array.js"; import * as Defs from "./schema.js"; -import * as Type from "./type/index.js"; +import * as Type from "./Type/index.js"; -import type * as Reference from "./type/Reference.js"; +import type * as Reference from "./Type/Reference.js"; import type { Schema as $Schema, Effect, diff --git a/libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/schema.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/jexpr/schema.ts rename to libs/@local/hashql/sdk/typescript/src/JExpr/schema.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts similarity index 93% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts index 85bd4449e94..661a8491001 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Binding.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Binding.ts @@ -1,6 +1,6 @@ import { Result } from "effect"; -import * as Ident from "../../jexpr/Ident.js"; +import * as Ident from "../../JExpr/Ident.js"; import * as ProgramError from "../ProgramError.js"; export interface Binding<Value> { diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts similarity index 83% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts index 6cc91458892..71c88addbc0 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Expr.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Expr.ts @@ -1,4 +1,4 @@ -import type * as JExpr from "../../jexpr/index.js"; +import type * as JExpr from "../../JExpr/index.js"; import type { Node } from "./Node.js"; export class Expr implements Node { diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/If.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts similarity index 91% rename from libs/@local/hashql/sdk/typescript/src/program/ast/If.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts index 191848bab60..4f5f455d631 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/If.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/If.ts @@ -1,4 +1,4 @@ -import * as JExpr from "../../jexpr/index.js"; +import * as JExpr from "../../JExpr/index.js"; import type { Node } from "./Node.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts similarity index 84% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts index 721a3fc48dc..a4252f8af81 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Import.ts @@ -1,5 +1,5 @@ -import * as JExpr from "../../jexpr/index.js"; -import * as Path from "../../jexpr/Path.js"; +import * as JExpr from "../../JExpr/index.js"; +import * as Path from "../../JExpr/Path.js"; import type { Node } from "./Node.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts similarity index 83% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts index b09017be463..bfbcce0fdf1 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Let.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Let.ts @@ -1,5 +1,5 @@ -import * as Ident from "../../jexpr/Ident.js"; -import * as JExpr from "../../jexpr/index.js"; +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; import type { Binding } from "./Binding.js"; import type { Node } from "./Node.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts similarity index 76% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts index 479b9f58a5a..d473fe65b1f 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Newtype.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Newtype.ts @@ -1,7 +1,7 @@ -import * as Ident from "../../jexpr/Ident.js"; -import * as JExpr from "../../jexpr/index.js"; +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; -import type * as Syntax from "../../jexpr/type/index.js"; +import type * as Syntax from "../../JExpr/Type/index.js"; import type { Binding } from "./Binding.js"; import type { Node } from "./Node.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts similarity index 81% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts index 12852f43e02..d4ee40bef58 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Node.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Node.ts @@ -1,4 +1,4 @@ -import type * as JExpr from "../../jexpr/index.js"; +import type * as JExpr from "../../JExpr/index.js"; /** A builder node that emits J-Expr syntax during expression serialization. */ export interface Node { diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts similarity index 76% rename from libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts index 4a612fe6e7e..2766ff1699b 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ast/Type.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/AST/Type.ts @@ -1,7 +1,7 @@ -import * as Ident from "../../jexpr/Ident.js"; -import * as JExpr from "../../jexpr/index.js"; +import * as Ident from "../../JExpr/Ident.js"; +import * as JExpr from "../../JExpr/index.js"; -import type * as Syntax from "../../jexpr/type/index.js"; +import type * as Syntax from "../../JExpr/Type/index.js"; import type { Binding } from "./Binding.js"; import type { Node } from "./Node.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ast/index.ts b/libs/@local/hashql/sdk/typescript/src/Program/AST/index.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/ast/index.ts rename to libs/@local/hashql/sdk/typescript/src/Program/AST/index.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts index 0dbe196667e..13cb4dc6fa4 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test-d.ts @@ -5,7 +5,7 @@ */ import { describe, expectTypeOf, test } from "vitest"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Expression } from "./Expression.js"; import type * as Inputs from "./Inputs.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts index d9b11eb3c7a..375ceab836e 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts @@ -6,11 +6,11 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; import * as Module from "./Module.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Inputs from "./Inputs.js"; type Vertex = Type.Struct<{ readonly name: Type.PrimitiveString }>; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Expression.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Expression.ts index 0433c3e1d3d..989391982ad 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Expression.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.ts @@ -12,13 +12,13 @@ import { Function, Predicate, Result, Schema, identity, pipe } from "effect"; import { Relocate } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; -import * as AST from "./ast/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; import type { Relocatable } from "../internal/relocation.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Accessors, Callable, Conditional } from "./ExpressionType.js"; import type * as Input from "./Inputs.js"; import type { Types } from "effect"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts b/libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts rename to libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts index 371d548682a..883c6c1b8eb 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/ExpressionType.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/ExpressionType.ts @@ -5,7 +5,7 @@ * * @module */ -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Expression from "./Expression.js"; import type * as Input from "./Inputs.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Import.ts b/libs/@local/hashql/sdk/typescript/src/Program/Import.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Import.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Import.ts index f7d631ccefa..b15a233b86b 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Import.ts @@ -9,8 +9,8 @@ import { Array, Result, SchemaParser, pipe } from "effect"; import { isReadonlyArray } from "../internal/array.js"; import { relocate } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; -import * as AST from "./ast/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; import * as ProgramError from "./ProgramError.js"; import type { Relocatable } from "../internal/relocation.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Inputs.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Inputs.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Inputs.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts index ecad227c0af..5819a898ca6 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Inputs.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.ts @@ -7,7 +7,7 @@ * * @module */ -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Normalize } from "./ExpressionType.js"; import type { Types } from "effect"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts index 9d2cc2868c9..51d654506d5 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.test-d.ts @@ -7,11 +7,11 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; import * as Module from "./Module.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Inputs from "./Inputs.js"; import type { TypeExpression } from "./TypeExpression.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Module.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts index c620a5114db..25b1e00e914 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts @@ -7,13 +7,13 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; import { Type as Alias, Do as EmptyDo, Newtype } from "../do/index.js"; -import * as JExpr from "../jexpr/index.js"; -import * as TypeSyntax from "../jexpr/type/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; import * as Expression from "./Expression.js"; import * as Module from "./Module.js"; import * as TypeExpression from "./TypeExpression.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Inputs from "./Inputs.js"; type Remainder = Type.Function< diff --git a/libs/@local/hashql/sdk/typescript/src/program/Module.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Module.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Module.ts index 937102f7b9a..011c186f8da 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts @@ -15,13 +15,13 @@ import { Relocate, relocate as relocateHandle, } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; import type { Relocatable } from "../internal/relocation.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Inputs from "./Inputs.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts index d7789a81eea..2245b154f0a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test-d.ts @@ -7,7 +7,7 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; import { relocate } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; import * as Module from "./Module.js"; import * as Namespace from "./Namespace.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts index 06ec63b20c4..6bad1688f36 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Namespace.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.test.ts @@ -7,12 +7,12 @@ import { Result, flow } from "effect"; import { describe, expect, test } from "vitest"; import { relocate } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; -import * as TypeSyntax from "../jexpr/type/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; import { Expression, Module, Structural, TypeExpression } from "../main.js"; import * as Namespace from "./Namespace.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; interface List extends Type.TypeConstructor { readonly arity: 1; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Namespace.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test-d.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Operators.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Operators.test-d.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.test.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Operators.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Operators.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Operators.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Operators.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Operators.ts index 8387009c53e..f770aea1f8a 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Operators.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts @@ -8,11 +8,11 @@ import { Array, Function, Result, pipe } from "effect"; import { Relocate } from "../internal/relocation.js"; -import * as JExpr from "../jexpr/index.js"; -import * as AST from "./ast/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; import * as Expression from "./Expression.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Normalize } from "./ExpressionType.js"; import type * as Inputs from "./Inputs.js"; import type * as ProgramError from "./ProgramError.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Prelude.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts index 8e376485335..d4a039a4e65 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Prelude.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts @@ -13,7 +13,7 @@ import * as Module from "./Module.js"; import * as Scope from "./Scope.js"; import * as Structural from "./Structural.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Expression from "./Expression.js"; import type * as Inputs from "./Inputs.js"; import type * as Semantic from "./PreludeTypes.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts b/libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts rename to libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts index 0c496c233d0..96ccdbc2536 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/PreludeTypes.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/PreludeTypes.ts @@ -5,7 +5,7 @@ * * @module */ -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Conditional } from "./ExpressionType.js"; /** The UUID type, an opaque string named by its HashQL path. */ diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Primitive.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Primitive.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/ProgramError.ts rename to libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Query.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Query.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Query.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Query.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Query.ts index 2a41af82f21..3111a9fd6f9 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts @@ -7,12 +7,12 @@ */ import { Cause, Result, pipe } from "effect"; -import * as JExpr from "../jexpr/index.js"; -import * as AST from "./ast/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as AST from "./AST/index.js"; import * as Expression from "./Expression.js"; import * as ProgramError from "./ProgramError.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { ArgumentInputs, Arguments } from "./ExpressionType.js"; import type * as Inputs from "./Inputs.js"; import type * as Scope from "./Scope.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Scope.ts b/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/program/Scope.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Scope.ts diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts index 11662f66983..69c52386fee 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test-d.ts @@ -8,12 +8,12 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; import * as Structural from "./Structural.js"; import * as TypeExpression from "./TypeExpression.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Inputs from "./Inputs.js"; interface Dictionary extends Type.TypeConstructor { diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts similarity index 96% rename from libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts index 8e11dc96046..e1df6bc9a37 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.test.ts @@ -6,12 +6,12 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import * as JExpr from "../jexpr/index.js"; -import * as TypeSyntax from "../jexpr/type/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; import * as Structural from "./Structural.js"; import * as TypeExpression from "./TypeExpression.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; interface Dictionary extends Type.TypeConstructor { readonly arity: 2; diff --git a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts b/libs/@local/hashql/sdk/typescript/src/Program/Structural.ts similarity index 99% rename from libs/@local/hashql/sdk/typescript/src/program/Structural.ts rename to libs/@local/hashql/sdk/typescript/src/Program/Structural.ts index ea52197b78c..0f4031b3a0c 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/Structural.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Structural.ts @@ -16,14 +16,14 @@ import { pipe, } from "effect"; -import * as JExpr from "../jexpr/index.js"; -import * as Syntax from "../jexpr/type/index.js"; +import * as JExpr from "../JExpr/index.js"; +import * as Syntax from "../JExpr/Type/index.js"; import * as Expression from "./Expression.js"; import * as ProgramError from "./ProgramError.js"; import * as TypeExpression from "./TypeExpression.js"; import type { Relocatable, Relocate } from "../internal/relocation.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as Input from "./Inputs.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts similarity index 98% rename from libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts rename to libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts index 53e7ad465d5..bee6592b037 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/TypeExpression.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts @@ -19,9 +19,9 @@ import { import * as ProgramError from "./ProgramError.js"; import type { Relocatable } from "../internal/relocation.js"; -import type * as JExpr from "../jexpr/index.js"; -import type * as Syntax from "../jexpr/type/index.js"; -import type * as Type from "../type/index.js"; +import type * as JExpr from "../JExpr/index.js"; +import type * as Syntax from "../JExpr/Type/index.js"; +import type * as Type from "../Type/index.js"; import type { Types } from "effect"; const TypeId: unique symbol = Symbol("~hashql/TypeExpression"); diff --git a/libs/@local/hashql/sdk/typescript/src/program/index.ts b/libs/@local/hashql/sdk/typescript/src/Program/index.ts similarity index 96% rename from libs/@local/hashql/sdk/typescript/src/program/index.ts rename to libs/@local/hashql/sdk/typescript/src/Program/index.ts index 2d464890d23..5d7e3fa82a6 100644 --- a/libs/@local/hashql/sdk/typescript/src/program/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/index.ts @@ -5,10 +5,10 @@ */ import { Result } from "effect"; -import * as JExpr from "../jexpr/index.js"; +import * as JExpr from "../JExpr/index.js"; import * as Expression from "./Expression.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type * as ProgramError from "./ProgramError.js"; /** diff --git a/libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Type/index.test-d.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/type/index.test-d.ts rename to libs/@local/hashql/sdk/typescript/src/Type/index.test-d.ts diff --git a/libs/@local/hashql/sdk/typescript/src/type/index.ts b/libs/@local/hashql/sdk/typescript/src/Type/index.ts similarity index 100% rename from libs/@local/hashql/sdk/typescript/src/type/index.ts rename to libs/@local/hashql/sdk/typescript/src/Type/index.ts diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts index 0df3136dbe0..f9266dd9f25 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts @@ -5,7 +5,7 @@ import { Expression, Module } from "../main.js"; import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; import type { Inputs, Type, TypeExpression } from "../main.js"; -import type * as ProgramError from "../program/ProgramError.js"; +import type * as ProgramError from "../Program/ProgramError.js"; // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments const initialValue = 7; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts index d5a1db4212c..3e5a5fe922e 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts @@ -8,12 +8,12 @@ import { Result, pipe } from "effect"; import { assert, describe, expect, test } from "vitest"; import { Expression, Module, Program, program } from "../main.js"; -import { Expr } from "../program/ast/Expr.js"; -import { If } from "../program/ast/If.js"; -import { Import as AstImport } from "../program/ast/Import.js"; -import { Let as AstLet } from "../program/ast/Let.js"; -import { Newtype as AstNewtype } from "../program/ast/Newtype.js"; -import { Type as AstType } from "../program/ast/Type.js"; +import { Expr } from "../Program/AST/Expr.js"; +import { If } from "../Program/AST/If.js"; +import { Import as AstImport } from "../Program/AST/Import.js"; +import { Let as AstLet } from "../Program/AST/Let.js"; +import { Newtype as AstNewtype } from "../Program/AST/Newtype.js"; +import { Type as AstType } from "../Program/AST/Type.js"; import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; import type { Inputs, Type } from "../main.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.ts index b9e74411d98..4b03efb9772 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Do.ts @@ -1,8 +1,8 @@ -import type * as Expression from "../program/Expression.js"; -import type * as Input from "../program/Inputs.js"; -import type * as ProgramError from "../program/ProgramError.js"; -import type * as Scope from "../program/Scope.js"; -import type * as Type from "../type/index.js"; +import type * as Expression from "../Program/Expression.js"; +import type * as Input from "../Program/Inputs.js"; +import type * as ProgramError from "../Program/ProgramError.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as Type from "../Type/index.js"; import type * as Node from "./Node.js"; import type { Body } from "./Utilities.js"; import type { Result } from "effect"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts index b4dc4fadeb3..243510cce41 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts @@ -5,7 +5,7 @@ import { Module } from "../main.js"; import { Do as EmptyDo, Import, withPrelude } from "./index.js"; import type { Expression, Inputs, Type } from "../main.js"; -import type * as ProgramError from "../program/ProgramError.js"; +import type * as ProgramError from "../Program/ProgramError.js"; // oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts index a8899aa2864..1c30ada09dc 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Import.ts @@ -5,15 +5,15 @@ */ import { Result, pipe } from "effect"; -import * as Imports from "../program/Import.js"; -import * as Scope from "../program/Scope.js"; +import * as Imports from "../Program/Import.js"; +import * as Scope from "../Program/Scope.js"; import * as Node from "./Node.js"; -import type * as Inputs from "../program/Inputs.js"; -import type * as Module from "../program/Module.js"; +import type * as Inputs from "../Program/Inputs.js"; +import type * as Module from "../Program/Module.js"; import type { Utilities } from "./Utilities.js"; -export type { Imported, Selection } from "../program/Import.js"; +export type { Imported, Selection } from "../Program/Import.js"; /** * Imports a module's exports as a Do block step. diff --git a/libs/@local/hashql/sdk/typescript/src/do/Let.ts b/libs/@local/hashql/sdk/typescript/src/do/Let.ts index 51b1a07017e..5af8d3be961 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Let.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Let.ts @@ -1,13 +1,13 @@ import { Result } from "effect"; -import * as Ident from "../jexpr/Ident.js"; -import * as Binding from "../program/ast/Binding.js"; -import { Let as AstLet } from "../program/ast/Let.js"; -import * as Expression from "../program/Expression.js"; -import * as Scope from "../program/Scope.js"; +import * as Ident from "../JExpr/Ident.js"; +import * as Binding from "../Program/AST/Binding.js"; +import { Let as AstLet } from "../Program/AST/Let.js"; +import * as Expression from "../Program/Expression.js"; +import * as Scope from "../Program/Scope.js"; import * as Node from "./Node.js"; -import type * as Type from "../type/index.js"; +import type * as Type from "../Type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts index a00e9a4fcc7..6ae61534c3d 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts @@ -1,16 +1,16 @@ // oxlint-disable import/max-dependencies -- nominal declarations introduce both a type and a value constructor import { Result } from "effect"; -import * as Ident from "../jexpr/Ident.js"; -import * as Binding from "../program/ast/Binding.js"; -import { Newtype as AstNewtype } from "../program/ast/Newtype.js"; -import * as Expression from "../program/Expression.js"; -import * as Scope from "../program/Scope.js"; -import * as TypeExpression from "../program/TypeExpression.js"; +import * as Ident from "../JExpr/Ident.js"; +import * as Binding from "../Program/AST/Binding.js"; +import { Newtype as AstNewtype } from "../Program/AST/Newtype.js"; +import * as Expression from "../Program/Expression.js"; +import * as Scope from "../Program/Scope.js"; +import * as TypeExpression from "../Program/TypeExpression.js"; import * as Node from "./Node.js"; -import type * as Inputs from "../program/Inputs.js"; -import type * as Type from "../type/index.js"; +import type * as Inputs from "../Program/Inputs.js"; +import type * as Type from "../Type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Node.ts b/libs/@local/hashql/sdk/typescript/src/do/Node.ts index 863f4ba5a3c..fe4f3b658a5 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Node.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Node.ts @@ -1,8 +1,8 @@ import { identity } from "effect"; -import type { Node as AstNode } from "../program/ast/Node.js"; -import type * as ProgramError from "../program/ProgramError.js"; -import type { Scope } from "../program/Scope.js"; +import type { Node as AstNode } from "../Program/AST/Node.js"; +import type * as ProgramError from "../Program/ProgramError.js"; +import type { Scope } from "../Program/Scope.js"; import type { Utilities } from "./Utilities.js"; import type { Result, Types } from "effect"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Type.ts b/libs/@local/hashql/sdk/typescript/src/do/Type.ts index fddae52aa32..18e081d587e 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Type.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Type.ts @@ -1,13 +1,13 @@ import { Result } from "effect"; -import * as Binding from "../program/ast/Binding.js"; -import { Type as AstType } from "../program/ast/Type.js"; -import * as Scope from "../program/Scope.js"; -import * as TypeExpression from "../program/TypeExpression.js"; +import * as Binding from "../Program/AST/Binding.js"; +import { Type as AstType } from "../Program/AST/Type.js"; +import * as Scope from "../Program/Scope.js"; +import * as TypeExpression from "../Program/TypeExpression.js"; import * as Node from "./Node.js"; -import type { Empty } from "../program/Inputs.js"; -import type * as Semantic from "../type/index.js"; +import type { Empty } from "../Program/Inputs.js"; +import type * as Semantic from "../Type/index.js"; import type { Utilities } from "./Utilities.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts index 46708a0ce54..1d28411a2b9 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts @@ -9,23 +9,23 @@ // oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods import { Cause, Result, identity, pipe } from "effect"; -import { If as AstIf } from "../program/ast/If.js"; -import * as Expression from "../program/Expression.js"; -import * as Operators from "../program/Operators.js"; -import * as ProgramError from "../program/ProgramError.js"; -import * as Query from "../program/Query.js"; +import { If as AstIf } from "../Program/AST/If.js"; +import * as Expression from "../Program/Expression.js"; +import * as Operators from "../Program/Operators.js"; +import * as ProgramError from "../Program/ProgramError.js"; +import * as Query from "../Program/Query.js"; import { Import } from "./Import.js"; import { Let } from "./Let.js"; import { Newtype } from "./Newtype.js"; import * as Node from "./Node.js"; import { Type as DeclareType } from "./Type.js"; -import type { Node as AstNode } from "../program/ast/Node.js"; -import type { Rebindable } from "../program/Import.js"; -import type * as Input from "../program/Inputs.js"; -import type * as Scope from "../program/Scope.js"; -import type { TypeExpression } from "../program/TypeExpression.js"; -import type * as Type from "../type/index.js"; +import type { Node as AstNode } from "../Program/AST/Node.js"; +import type { Rebindable } from "../Program/Import.js"; +import type * as Input from "../Program/Inputs.js"; +import type * as Scope from "../Program/Scope.js"; +import type { TypeExpression } from "../Program/TypeExpression.js"; +import type * as Type from "../Type/index.js"; import type { Imported, Selection } from "./Import.js"; import type { Exports } from "./Newtype.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/index.ts b/libs/@local/hashql/sdk/typescript/src/do/index.ts index 75040220892..10514212313 100644 --- a/libs/@local/hashql/sdk/typescript/src/do/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/do/index.ts @@ -36,15 +36,15 @@ * @module */ -import * as Scope from "../program/Scope.js"; +import * as Scope from "../Program/Scope.js"; import { Import } from "./Import.js"; import { Let } from "./Let.js"; import { Newtype } from "./Newtype.js"; import { Type } from "./Type.js"; import { Block as Builder } from "./Utilities.js"; -import type * as Expression from "../program/Expression.js"; -import type * as ProgramError from "../program/ProgramError.js"; +import type * as Expression from "../Program/Expression.js"; +import type * as ProgramError from "../Program/ProgramError.js"; import type { Do as Block } from "./Do.js"; import type { BuildStep } from "./Utilities.js"; import type { Result } from "effect"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts index ddf8a4a97c0..3cc583e8633 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Body.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Body.ts @@ -5,12 +5,12 @@ * * @module */ -import type * as Expression from "../program/Expression.js"; -import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; -import type * as Input from "../program/Inputs.js"; -import type * as Scope from "../program/Scope.js"; -import type * as TypeExpression from "../program/TypeExpression.js"; -import type * as Type from "../type/index.js"; +import type * as Expression from "../Program/Expression.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Input from "../Program/Inputs.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as TypeExpression from "../Program/TypeExpression.js"; +import type * as Type from "../Type/index.js"; import type * as Construction from "./Context.js"; import type { ReadonlyRecord } from "effect/Record"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts index ef153714ff1..c35cd981d3e 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test-d.ts @@ -9,8 +9,8 @@ import { Structural, TypeExpression, } from "../main.js"; -import * as Namespace from "../program/Namespace.js"; -import * as Scope from "../program/Scope.js"; +import * as Namespace from "../Program/Namespace.js"; +import * as Scope from "../Program/Scope.js"; import * as Draft from "./index.js"; import type { Inputs, Type } from "../main.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts index 847de2b2a38..e19fed04232 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Construction.test.ts @@ -9,7 +9,7 @@ import { Structural, TypeExpression, } from "../main.js"; -import * as Namespace from "../program/Namespace.js"; +import * as Namespace from "../Program/Namespace.js"; import * as Draft from "./index.js"; const integer = Structural.type(BigInt); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts index 778faa6550d..5fdbec41475 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Context.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Context.ts @@ -14,12 +14,12 @@ import type { Type, TypeExpression, } from "../main.js"; -import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; -import type * as Import from "../program/Import.js"; -import type * as Namespace from "../program/Namespace.js"; -import type * as QueryTypes from "../program/Query.js"; -import type * as Scope from "../program/Scope.js"; -import type * as Structural from "../program/Structural.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Import from "../Program/Import.js"; +import type * as Namespace from "../Program/Namespace.js"; +import type * as QueryTypes from "../Program/Query.js"; +import type * as Scope from "../Program/Scope.js"; +import type * as Structural from "../Program/Structural.js"; /** * The call signature of a Draft nominal constructor: it wraps an exactly typed value of the underlying type `T` as the nominal type. diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts index d40a0d40192..9a0543304e7 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts @@ -3,7 +3,7 @@ import { Result, pipe } from "effect"; import { describe, expect, expectTypeOf, test } from "vitest"; import { Do, Import } from "../do/index.js"; -import * as TypeSyntax from "../jexpr/type/index.js"; +import * as TypeSyntax from "../JExpr/Type/index.js"; import { Expression, JExpr, Module, Prelude, TypeExpression } from "../main.js"; import * as Draft from "./index.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts index 545ce4939d3..884d4d4bb2a 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Namespace.test.ts @@ -7,7 +7,7 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; import { Expression, Module, Structural, TypeExpression } from "../main.js"; -import * as Operators from "../program/Operators.js"; +import * as Operators from "../Program/Operators.js"; import * as Draft from "./index.js"; import type { Type } from "../main.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts index a25ea1841e2..27ac7971e8e 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Requirements.test-d.ts @@ -3,7 +3,7 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; import { Expression, Module, Prelude, Structural } from "../main.js"; -import * as Operators from "../program/Operators.js"; +import * as Operators from "../Program/Operators.js"; import * as Fixtures from "./fixtures.js"; import * as Draft from "./index.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts index bfef1509d75..1eb06177818 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Scribe.ts @@ -15,14 +15,14 @@ import { Structural, TypeExpression, } from "../main.js"; -import * as AST from "../program/ast/index.js"; -import * as Import from "../program/Import.js"; -import * as Namespace from "../program/Namespace.js"; +import * as AST from "../Program/AST/index.js"; +import * as Import from "../Program/Import.js"; +import * as Namespace from "../Program/Namespace.js"; -import type * as Syntax from "../jexpr/type/index.js"; +import type * as Syntax from "../JExpr/Type/index.js"; import type { Inputs, Module, Type } from "../main.js"; -import type { ArgumentInputs, Arguments } from "../program/ExpressionType.js"; -import type * as Scope from "../program/Scope.js"; +import type { ArgumentInputs, Arguments } from "../Program/ExpressionType.js"; +import type * as Scope from "../Program/Scope.js"; import type * as Body from "./Body.js"; import type * as Context from "./Context.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts index afae68579e0..51e7701a7c9 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/fixtures.ts @@ -8,7 +8,7 @@ import { Result, pipe } from "effect"; import { Module, Prelude } from "../main.js"; -import * as Scope from "../program/Scope.js"; +import * as Scope from "../Program/Scope.js"; import * as Draft from "./index.js"; import type { Expression, Inputs, Type, TypeExpression } from "../main.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts index bd3b8af9cfb..931eb844a31 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -27,15 +27,15 @@ */ import { Result, pipe } from "effect"; -import * as Expression from "../program/Expression.js"; -import * as Prelude from "../program/Prelude.js"; -import * as ProgramError from "../program/ProgramError.js"; -import * as Scope from "../program/Scope.js"; +import * as Expression from "../Program/Expression.js"; +import * as Prelude from "../Program/Prelude.js"; +import * as ProgramError from "../Program/ProgramError.js"; +import * as Scope from "../Program/Scope.js"; import * as Scribe from "./Scribe.js"; import type { Relocatable } from "../internal/relocation.js"; import type { Type, TypeExpression } from "../main.js"; -import type * as Namespace from "../program/Namespace.js"; +import type * as Namespace from "../Program/Namespace.js"; import type * as Body from "./Body.js"; export type * as Context from "./Context.js"; diff --git a/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts index 25cd74f0fda..4be84e3c496 100644 --- a/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts +++ b/libs/@local/hashql/sdk/typescript/src/internal/relocation.ts @@ -7,8 +7,8 @@ */ import { dual } from "effect/Function"; -import type * as JExpr from "../jexpr/index.js"; -import type * as ProgramError from "../program/ProgramError.js"; +import type * as JExpr from "../JExpr/index.js"; +import type * as ProgramError from "../Program/ProgramError.js"; import type { Result } from "effect"; export const Relocate: unique symbol = Symbol("~hashql/Relocate"); diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index a6cd6662ff0..820430a0e52 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -7,16 +7,16 @@ * * @module */ -export * as JExpr from "./jexpr/index.js"; -export * as Expression from "./program/Expression.js"; -export * as Module from "./program/Module.js"; -export * as Operators from "./program/Operators.js"; -export * as Prelude from "./program/Prelude.js"; -export * as Structural from "./program/Structural.js"; -export * as Program from "./program/index.js"; -export * as ProgramError from "./program/ProgramError.js"; -export { program } from "./program/index.js"; -export { ifElse as If, assume } from "./program/Expression.js"; -export * as TypeExpression from "./program/TypeExpression.js"; -export type * as Type from "./type/index.js"; -export type * as Inputs from "./program/Inputs.js"; +export * as JExpr from "./JExpr/index.js"; +export * as Expression from "./Program/Expression.js"; +export * as Module from "./Program/Module.js"; +export * as Operators from "./Program/Operators.js"; +export * as Prelude from "./Program/Prelude.js"; +export * as Structural from "./Program/Structural.js"; +export * as Program from "./Program/index.js"; +export * as ProgramError from "./Program/ProgramError.js"; +export { program } from "./Program/index.js"; +export { ifElse as If, assume } from "./Program/Expression.js"; +export * as TypeExpression from "./Program/TypeExpression.js"; +export type * as Type from "./Type/index.js"; +export type * as Inputs from "./Program/Inputs.js"; diff --git a/yarn.lock b/yarn.lock index c4dbcc7183c..81c55e12bd4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10256,6 +10256,7 @@ __metadata: fumadocs-mdx: "npm:15.4.6" fumadocs-twoslash: "npm:4.0.1" fumadocs-ui: "npm:16.16.2" + mdast-util-mdx-jsx: "npm:3.1.3" next: "npm:16.3.8" oxc-parser: "npm:0.152.0" oxc-resolver: "npm:11.24.2" @@ -36224,7 +36225,7 @@ __metadata: languageName: node linkType: hard -"mdast-util-mdx-jsx@npm:^3.0.0": +"mdast-util-mdx-jsx@npm:3.1.3, mdast-util-mdx-jsx@npm:^3.0.0": version: 3.1.3 resolution: "mdast-util-mdx-jsx@npm:3.1.3" dependencies: From 691d3a08e4e1592a7b0d32fafe2b956c323122fa Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Fri, 16 Oct 2026 13:34:12 +0200 Subject: [PATCH 21/22] feat: document TypeScript package entry points --- .../hashql/sdk/typescript-docs/package.json | 2 +- .../sdk/typescript-docs/src/Analysis.ts | 137 +++++++++++------- .../hashql/sdk/typescript-docs/src/Analyze.ts | 126 ++++++++++------ .../hashql/sdk/typescript-docs/src/Site.ts | 81 ++++++++--- .../sdk/typescript-docs/src/Transform.ts | 14 +- .../sdk/typescript-docs/src/TransformError.ts | 12 ++ .../hashql/sdk/typescript-docs/turbo.json | 2 +- 7 files changed, 251 insertions(+), 123 deletions(-) diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index 49b20e70c45..60592da5c48 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -9,7 +9,7 @@ "build": "next build --webpack", "codegen": "fumadocs-mdx", "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", - "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --include .generated/declarations/main.d.ts", + "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --entry .=.generated/declarations/main.d.ts --entry ./draft=.generated/declarations/draft/index.d.ts --entry ./do=.generated/declarations/do/index.d.ts", "doc:declarations": "tsc --project tsconfig.api.json", "doc:transform": "tsx src/cli.ts transform --lib ../typescript && oxfmt content/docs/reference", "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts index 3c2c4a5599f..e7d25230ee6 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analysis.ts @@ -10,7 +10,6 @@ import { Layer, Option, Path, - Result, Schema, Struct, flow, @@ -20,11 +19,7 @@ import { import { Sources } from "./Sources.js"; import { TransformError } from "./TransformError.js"; -import type { - ApiEntryPoint, - ApiItem, - ApiPackage, -} from "@microsoft/api-extractor-model"; +import type { ApiEntryPoint, ApiItem } from "@microsoft/api-extractor-model"; import type { DocComment } from "@microsoft/tsdoc"; /** The part of a declaration map that names the source TypeScript emitted the file from. */ @@ -44,15 +39,47 @@ const declarationExtensions: readonly (readonly [string, string])[] = [ [".ts", ".d.ts"], ]; +/** A subpath that a package's `exports` names: `.` for the package itself, otherwise `./` followed by a path. A pattern with `*` names no single entry point. */ +export const Subpath = Schema.String.pipe( + Schema.check(Schema.isPattern(/^\.(?:\/[^/*]+)*$/u)), +); + +/** The file `analyze` writes beside the models, which names each entry point it analyzed. */ +export const manifestFile = "entry-points.json"; + +/** The entry points `analyze` analyzed, in the order it received them. Paths are relative to the manifest's directory. */ +export const Manifest = Schema.fromJsonString( + Schema.NonEmptyArray( + Schema.Struct({ + subpath: Subpath, + /** API Extractor's model of the entry point. */ + model: Schema.String, + /** The declaration file the model was extracted from. */ + declaration: Schema.String, + }), + ), + { space: 2 }, +); + +/** An entry point of the analyzed package. */ +export interface EntryPoint { + /** The subpath the package exports it at. */ + readonly subpath: string; + /** API Extractor's model of the entry point, whose members are its exports. */ + readonly model: ApiEntryPoint; + /** The source module TypeScript emitted the entry point's declaration file from. */ + readonly module: string; +} + /** The output of the `analyze` command, with what the pages need to find their way back to the sources. */ export class Analysis extends Context.Service< Analysis, { - readonly package: ApiPackage; - readonly entry: ApiEntryPoint; - /** The source modules of the declaration files the analysis entry re-exports, in order. */ - readonly roots: Array.NonEmptyReadonlyArray<string>; - /** The directory TypeScript emitted the declaration files into. The first root's file sits at its top, and the tree below mirrors the sources. */ + /** The analyzed package's name. */ + readonly name: string; + /** The package's entry points, in the order `analyze` received them. */ + readonly entryPoints: Array.NonEmptyReadonlyArray<EntryPoint>; + /** The directory TypeScript emitted the declaration files into. The first entry point's file sits at its top, and the tree below mirrors the sources. */ readonly declarationRoot: string; /** The source file that declares an item. */ readonly sourceOf: (item: ApiItem) => Option.Option<string>; @@ -74,7 +101,7 @@ export interface Options { readonly analysis: string; } -const loadEntry = Effect.fnUntraced(function* (file: string) { +const loadModel = Effect.fnUntraced(function* (file: string) { const apiPackage = yield* Effect.try(() => new ApiModel().loadPackage(file), ).pipe( @@ -85,7 +112,7 @@ const loadEntry = Effect.fnUntraced(function* (file: string) { Array.head(apiPackage.entryPoints), Effect.fromOption, Effect.mapError(() => - TransformError.malformedAnalysis("The API model has no entry point"), + TransformError.malformedAnalysis(`${file} has no entry point`), ), ); @@ -131,42 +158,26 @@ const sourceOfDeclaration = Effect.fnUntraced( Effect.catchTag("PlatformError", TransformError.fileSystem), ); -// `analyze` writes one `export * from` for each declaration file it receives, and each file's map names its source. -const loadRoots = Effect.fnUntraced(function* (entryFile: string) { - const sources = yield* Sources; - const declarations = yield* pipe( - sources.scope(entryFile), - Effect.map(Struct.get("wildcards")), - Effect.flatMap( - flow( - Array.map((specifier) => - sources - .resolve(entryFile, specifier) - .pipe( - Result.fromOption(() => - TransformError.malformedAnalysis( - `${entryFile} re-exports ${specifier}, which does not exist`, - ), - ), - ), - ), - Result.all, - Effect.fromResult, - ), - ), - ); +const loadManifest = Effect.fnUntraced( + function* (analysis: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; - if (!Array.isReadonlyArrayNonEmpty(declarations)) { - return yield* TransformError.malformedAnalysis( - `${entryFile} re-exports no declaration file`, + const file = path.join(analysis, manifestFile); + const text = yield* fs.readFileString(file); + + const manifest = yield* Schema.decodeEffect(Manifest)(text).pipe( + Effect.mapError((cause) => TransformError.malformedManifest(file, cause)), ); - } - return { - declaration: Array.headNonEmpty(declarations), - sources: yield* Effect.forEach(declarations, sourceOfDeclaration), - }; -}); + return Array.map(manifest, ({ subpath, model, declaration }) => ({ + subpath, + model: path.resolve(analysis, model), + declaration: path.resolve(analysis, declaration), + })); + }, + Effect.catchTag("PlatformError", TransformError.fileSystem), +); export const layer = ({ lib, @@ -185,15 +196,30 @@ export const layer = ({ FileSystem.FileSystem | Path.Path >(); - const { apiPackage, entry } = yield* loadEntry( - path.join(analysis, "api.json"), - ); const parser = yield* loadParser(lib); - const roots = yield* loadRoots(path.join(analysis, "api-entry.d.ts")); - const rootSource = Array.headNonEmpty(roots.sources); - const declarationRoot = path.dirname(roots.declaration); + const manifest = yield* loadManifest(analysis); + const loaded = yield* Effect.forEach( + manifest, + Effect.fnUntraced(function* ({ subpath, model, declaration }) { + const { apiPackage, entry } = yield* loadModel(model); + const source = yield* sourceOfDeclaration(declaration); + + return { + name: apiPackage.name, + declaration, + entryPoint: { + subpath, + model: entry, + module: source, + } satisfies EntryPoint, + }; + }), + ); + const first = Array.headNonEmpty(loaded); + const rootSource = first.entryPoint.module; + const declarationRoot = path.dirname(first.declaration); - // The emit mirrors the source tree, so the first root locates every other declaration file, and each one's map confirms it. + // The emit mirrors the source tree, so the first entry point locates every other declaration file, and each one's map confirms it. const declarations = yield* Cache.make({ capacity: Number.POSITIVE_INFINITY, lookup: Effect.fnUntraced(function* (source: string) { @@ -220,9 +246,8 @@ export const layer = ({ }); return Analysis.of({ - package: apiPackage, - entry, - roots: roots.sources, + name: first.name, + entryPoints: Array.map(loaded, Struct.get("entryPoint")), declarationRoot, sourceOf: (item) => { if (item instanceof ApiDeclaredItem) { diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts index 9deeb84af44..6c45ec09465 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Analyze.ts @@ -4,19 +4,31 @@ import { ExtractorConfig, ExtractorLogLevel, } from "@microsoft/api-extractor"; -import { Data, Effect, FileSystem, Path } from "effect"; +import { + Array, + Data, + Effect, + FileSystem, + Option, + Path, + Record, + Schema, + flow, +} from "effect"; import { Command, Flag } from "effect/cli"; +import * as Analysis from "./Analysis.js"; + import type { IConfigFile } from "@microsoft/api-extractor"; const makeExtractorConfig = ({ lib, entry, - out, + model, }: { lib: string; entry: string; - out: string; + model: string; }): IConfigFile => ({ projectFolder: lib, mainEntryPointFilePath: entry, @@ -28,7 +40,7 @@ const makeExtractorConfig = ({ }, docModel: { enabled: true, - apiJsonFilePath: `${out}/api.json`, + apiJsonFilePath: model, }, dtsRollup: { enabled: false, @@ -52,15 +64,28 @@ const makeExtractorConfig = ({ }, }); -/** API Extractor finished the analysis and reported errors. */ +/** API Extractor finished analyzing an entry point and reported errors. */ export class ExtractionError extends Data.TaggedError("ExtractionError")<{ + readonly subpath: string; readonly errorCount: number; readonly warningCount: number; }> {} export const command = Command.make("analyze", { lib: Flag.Directory("lib"), - include: Flag.File("include", { mustExist: true }).pipe(Flag.atLeast(1)), + entry: Flag.KeyValuePair("entry").pipe( + Flag.withDescription( + "An export subpath and the declaration file TypeScript emitted for it, such as `./draft=<file>`. The first entry's file sits at the top of the emit", + ), + // `KeyValuePair` requires a pair, though its type does not say so. + Flag.filterMap( + flow(Record.toEntries, Option.liftPredicate(Array.isArrayNonEmpty)), + () => "Expected at least one entry point", + ), + Flag.withSchema( + Schema.NonEmptyArray(Schema.Tuple([Analysis.Subpath, Schema.String])), + ), + ), out: Flag.Directory("out").pipe( Flag.withDefault( Effect.suspend(() => @@ -74,57 +99,74 @@ export const command = Command.make("analyze", { ), }); +// API Extractor analyzes a single entry point per run, and merging several into one module would collide where two of them export the same name. +const extract = Effect.fnUntraced(function* ({ + lib, + subpath, + entry, + model, +}: { + lib: string; + subpath: string; + entry: string; + model: string; +}) { + const path = yield* Path.Path; + + // May throw when `<projectFolder>/tsdoc.json` is invalid, or when the entry is not a declaration file that exists. + const extractorConfig = yield* Effect.try(() => + ExtractorConfig.prepare({ + configObject: makeExtractorConfig({ lib, entry, model }), + configObjectFullPath: undefined, + packageJsonFullPath: path.join(lib, "package.json"), + }), + ); + + return yield* Effect.try(() => + Extractor.invoke(extractorConfig, { localBuild: true }), + ).pipe( + Effect.filterOrFail( + ({ succeeded }) => succeeded, + ({ errorCount, warningCount }) => + new ExtractionError({ subpath, errorCount, warningCount }), + ), + ); +}); + export const handler = command.pipe( Command.withHandler( - Effect.fnUntraced(function* ({ lib, include, out }) { + Effect.fnUntraced(function* ({ lib, entry, out }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const libPath = path.resolve(lib); const outPath = path.resolve(out); - const entryPath = path.join(outPath, "api-entry.d.ts"); - // API Extractor only supports a single entry point, therefore we must shim multiple entry points into a single module - const entry = include - .map((file) => { - const specifier = path - .relative(outPath, path.resolve(file)) - .replace(/\.d\.(?<format>[cm]?)ts$/u, ".$<format>js"); + yield* fs.makeDirectory(outPath, { recursive: true }); - if (specifier.startsWith("../")) { - return `export * from ${JSON.stringify(specifier)};\n`; - } + const entryPoints = yield* Effect.forEach( + entry, + Effect.fnUntraced(function* ([subpath, file], index) { + const declaration = path.resolve(file); + const model = path.join(outPath, "api", `${index}.json`); - return `export * from ${JSON.stringify(`./${specifier}`)};\n`; - }) - .join(""); + yield* extract({ lib: libPath, subpath, entry: declaration, model }); - yield* fs.makeDirectory(outPath, { recursive: true }); - yield* fs.writeFileString(entryPath, entry); - - // May throw when `<projectFolder>/tsdoc.json` is invalid. - const extractorConfig = yield* Effect.try(() => - ExtractorConfig.prepare({ - configObject: makeExtractorConfig({ - lib: libPath, - entry: entryPath, - out: outPath, - }), - configObjectFullPath: undefined, - packageJsonFullPath: path.join(libPath, "package.json"), + return { + subpath, + model: path.relative(outPath, model), + declaration: path.relative(outPath, declaration), + }; }), ); - const result = yield* Effect.try(() => - Extractor.invoke(extractorConfig, { localBuild: true }), + const manifest = yield* Schema.encodeEffect(Analysis.Manifest)( + entryPoints, + ); + yield* fs.writeFileString( + path.join(outPath, Analysis.manifestFile), + manifest, ); - - if (!result.succeeded) { - return yield* new ExtractionError({ - errorCount: result.errorCount, - warningCount: result.warningCount, - }); - } return "Ok"; }), diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts index 48fa9fad0c8..7d90621b318 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Site.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Site.ts @@ -10,6 +10,7 @@ import { Option, Path, Record, + String, Struct, flow, pipe, @@ -24,9 +25,9 @@ import type { Scope } from "./Sources.js"; import type { ApiItem } from "@microsoft/api-extractor-model"; import type { DocDeclarationReference } from "@microsoft/tsdoc"; -/** A reference page for the package, or for a namespace that a module re-exports with `export * as`. */ +/** A reference page for one of the package's entry points, or for a namespace that a module re-exports with `export * as`. */ export interface Page { - /** Path segments below the output directory, empty for the package page. */ + /** Path segments below the output directory, empty for the package page and the subpath's for another entry point's. */ readonly path: readonly string[]; readonly title: string; /** The model item whose members the page documents. */ @@ -51,6 +52,8 @@ export class Site extends Context.Service< Site, { readonly pages: Array.NonEmptyReadonlyArray<Page>; + /** The entry points' pages, in the order `analyze` received them. */ + readonly roots: Array.NonEmptyReadonlyArray<Page>; /** The page documenting a container's members, if it has one. */ readonly pageOf: (container: ApiItem) => Option.Option<Page>; readonly url: (page: Page) => string; @@ -309,16 +312,48 @@ const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { const scope = yield* sources.scope(origin.module); const resolution: Resolution = { index, origin, scope }; + // A reference's import path selects an entry point, `/draft` the one at `./draft`. Without one, it names the entry point the comment's page belongs to. + const entryPointOf = ( + reference: DocDeclarationReference, + ): Option.Option<ApiItem> => + Option.match(Option.fromNullishOr(reference.importPath), { + onNone: () => + pipe( + Array.prepend(ancestors(origin.container), origin.container), + Array.findFirst((item) => item.kind === ApiItemKind.EntryPoint), + ), + onSome: (importPath) => + pipe( + analysis.entryPoints, + Array.findFirst(({ subpath }) => subpath === `.${importPath}`), + Option.map(Struct.get("model")), + ), + }); + // Links resolve the way TypeScript resolves them in the comment's module. A reference qualified from the package resolves last. - const fromPackage: Lookup = (name) => members(analysis.entry, name); - const target = resolveIn([ - declared(resolution), - imported(sources, resolution), - fromPackage, - ]); + const fromPackage = + (reference: DocDeclarationReference): Lookup => + (name) => + pipe( + entryPointOf(reference), + Option.map((entryPoint) => members(entryPoint, name)), + Option.getOrElse(Array.empty), + ); + const target = (reference: DocDeclarationReference): Option.Option<ApiItem> => + pipe( + reference, + namesOf, + Option.flatMap( + resolveIn([ + declared(resolution), + imported(sources, resolution), + fromPackage(reference), + ]), + ), + ); const shown = path.relative( - path.dirname(Array.headNonEmpty(analysis.roots)), + path.dirname(Array.headNonEmpty(analysis.entryPoints).module), origin.module, ); @@ -328,9 +363,8 @@ const makeLinks = Effect.fnUntraced(function* (index: Index, origin: Origin) { reference, Option.liftPredicate( ({ packageName }) => - packageName === undefined || packageName === analysis.package.name, + packageName === undefined || packageName === analysis.name, ), - Option.flatMap(namesOf), Option.flatMap(target), Option.flatMap(index.itemUrl), Option.match({ @@ -381,16 +415,22 @@ export const layer = ({ const analysis = yield* Analysis; const services = yield* Effect.context<Analysis | Sources | Path.Path>(); - const root: Page = { - path: [], - title: analysis.package.displayName, - container: analysis.entry, - modules: analysis.roots, - }; + // `./draft` is the page at `draft`, below the package's own. + const roots = Array.map( + analysis.entryPoints, + ({ subpath, model, module }): Page => ({ + path: Array.drop(String.split(subpath, "/"), 1), + title: `${analysis.name}${subpath.slice(1)}`, + container: model, + modules: [module], + }), + ); const pages = yield* pipe( - root, - discover, - Effect.map(Array.prepend(root)), + roots, + Effect.forEach((root) => + pipe(root, discover, Effect.map(Array.prepend(root))), + ), + Effect.map(Array.flatten), ); const duplicate = pipe( pages, @@ -409,6 +449,7 @@ export const layer = ({ return Site.of({ pages, + roots, pageOf: index.pageOf, url: index.url, anchor: index.anchor, diff --git a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts index 3618c12b736..8ea482a471a 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/Transform.ts @@ -18,7 +18,7 @@ import * as Site from "./Site.js"; import * as Sources from "./Sources.js"; import { TransformError } from "./TransformError.js"; -// The reference folder lists the package page first, then the module folders. +// The reference folder lists the package page first, then its namespaces, then the other entry points in the order `analyze` received them. const Meta = Schema.fromJsonString( Schema.Struct({ title: Schema.String, pages: Schema.Array(Schema.String) }), { space: 2 }, @@ -75,10 +75,18 @@ const write = Effect.fnUntraced( const path = yield* Path.Path; const site = yield* Site.Site; - // Encoding a literal of the schema's own type cannot fail. + // Encoding a value of the schema's own type cannot fail. const meta = yield* Schema.encodeEffect(Meta)({ title: "API reference", - pages: ["index", "..."], + pages: [ + "index", + "...", + ...pipe( + site.roots, + Array.flatMap(({ path: segments }) => Array.take(segments, 1)), + Array.dedupe, + ), + ], }).pipe(Effect.orDie); yield* fs.remove(out, { recursive: true, force: true }); diff --git a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts index 62f6428b9ae..2df23f6871e 100644 --- a/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts +++ b/libs/@local/hashql/sdk/typescript-docs/src/TransformError.ts @@ -14,6 +14,11 @@ export type Reason = Data.TaggedEnum<{ readonly file: string; readonly cause: Schema.SchemaError; }; + /** The manifest `analyze` writes beside its models does not decode. */ + MalformedManifest: { + readonly file: string; + readonly cause: Schema.SchemaError; + }; /** API Extractor could not load the API model the analysis wrote. */ UnreadableModel: { readonly file: string; @@ -58,6 +63,12 @@ export class TransformError extends TransformErrorBase<{ ): TransformError => new TransformError({ reason: Reason.MalformedSourceMap({ file, cause }) }); + static readonly malformedManifest = ( + file: string, + cause: Schema.SchemaError, + ): TransformError => + new TransformError({ reason: Reason.MalformedManifest({ file, cause }) }); + static readonly unreadableModel = ( file: string, cause: Cause.UnknownError, @@ -89,6 +100,7 @@ export class TransformError extends TransformErrorBase<{ SourceSyntax: ({ file, messages }) => `${file} does not parse: ${messages.join("; ")}`, MalformedSourceMap: ({ file, cause }) => `${file}: ${cause.message}`, + MalformedManifest: ({ file, cause }) => `${file}: ${cause.message}`, UnreadableModel: ({ file, cause }) => `${file}: ${cause.message}`, MalformedAnalysis: ({ detail }) => detail, UnsupportedComment: ({ kind }) => diff --git a/libs/@local/hashql/sdk/typescript-docs/turbo.json b/libs/@local/hashql/sdk/typescript-docs/turbo.json index 29a4d66961a..3de78d0fc11 100644 --- a/libs/@local/hashql/sdk/typescript-docs/turbo.json +++ b/libs/@local/hashql/sdk/typescript-docs/turbo.json @@ -9,7 +9,7 @@ }, "doc:analyze": { "dependsOn": ["doc:declarations"], - "outputs": [".generated/api.json", ".generated/api-entry.d.ts"] + "outputs": [".generated/entry-points.json", ".generated/api/**"] }, "doc:transform": { "dependsOn": ["doc:analyze"], From 45b6f98282124c2f586a55c617d506ddf5ab3ce0 Mon Sep 17 00:00:00 2001 From: Bilal Mahmoud <7252775+indietyp@users.noreply.github.com> Date: Mon, 19 Oct 2026 09:43:02 +0200 Subject: [PATCH 22/22] refactor: remove Do authoring API and docs --- .../sdk/typescript-docs/oxlint.config.ts | 10 +- .../hashql/sdk/typescript-docs/package.json | 8 +- libs/@local/hashql/sdk/typescript/README.md | 193 +--- .../hashql/sdk/typescript/docs/authoring.md | 870 ------------------ .../@local/hashql/sdk/typescript/docs/todo.md | 25 - ...est.ts.snap => filters-draft.test.ts.snap} | 12 +- .../examples/filters-declarations.ts | 2 +- .../typescript/examples/filters-draft.test.ts | 207 ++++- .../sdk/typescript/examples/filters-draft.ts | 4 +- .../typescript/examples/filters-originals.ts | 100 ++ .../sdk/typescript/examples/filters.test.ts | 199 ---- .../hashql/sdk/typescript/examples/filters.ts | 282 ------ .../@local/hashql/sdk/typescript/package.json | 8 +- .../hashql/sdk/typescript/src/JExpr/Path.ts | 8 +- .../typescript/src/Program/Expression.test.ts | 11 + .../typescript/src/Program/Inputs.test-d.ts | 134 +-- .../sdk/typescript/src/Program/Inputs.test.ts | 36 +- .../sdk/typescript/src/Program/Module.test.ts | 27 - .../sdk/typescript/src/Program/Module.ts | 2 +- .../sdk/typescript/src/Program/Namespace.ts | 2 +- .../sdk/typescript/src/Program/Operators.ts | 12 - .../sdk/typescript/src/Program/Prelude.ts | 4 +- .../src/Program/Primitive.test-d.ts | 63 +- .../typescript/src/Program/Primitive.test.ts | 45 +- .../typescript/src/Program/ProgramError.ts | 26 - .../typescript/src/Program/Query.test-d.ts | 69 -- .../sdk/typescript/src/Program/Query.test.ts | 105 --- .../sdk/typescript/src/Program/Query.ts | 211 +---- .../sdk/typescript/src/Program/Scope.ts | 4 +- .../typescript/src/Program/TypeExpression.ts | 2 +- .../hashql/sdk/typescript/src/Type/index.ts | 2 +- .../hashql/sdk/typescript/src/do/Do.test-d.ts | 205 ----- .../hashql/sdk/typescript/src/do/Do.test.ts | 440 --------- .../@local/hashql/sdk/typescript/src/do/Do.ts | 206 ----- .../sdk/typescript/src/do/Exception.test.ts | 244 ----- .../sdk/typescript/src/do/Import.test-d.ts | 92 -- .../sdk/typescript/src/do/Import.test.ts | 209 ----- .../hashql/sdk/typescript/src/do/Import.ts | 57 -- .../hashql/sdk/typescript/src/do/Let.ts | 64 -- .../hashql/sdk/typescript/src/do/Newtype.ts | 116 --- .../hashql/sdk/typescript/src/do/Node.ts | 77 -- .../hashql/sdk/typescript/src/do/Type.ts | 64 -- .../hashql/sdk/typescript/src/do/Utilities.ts | 396 -------- .../hashql/sdk/typescript/src/do/index.ts | 144 --- .../sdk/typescript/src/draft/Draft.test.ts | 17 + .../sdk/typescript/src/draft/Import.test.ts | 6 - .../sdk/typescript/src/draft/Query.test-d.ts | 80 ++ .../sdk/typescript/src/draft/Query.test.ts | 77 ++ .../hashql/sdk/typescript/src/draft/index.ts | 2 +- .../sdk/typescript/src/internal/scan.ts | 8 +- libs/@local/hashql/sdk/typescript/src/main.ts | 2 +- .../hashql/sdk/typescript/tsdown.config.ts | 2 +- yarn.lock | 24 +- 53 files changed, 545 insertions(+), 4670 deletions(-) delete mode 100644 libs/@local/hashql/sdk/typescript/docs/authoring.md delete mode 100644 libs/@local/hashql/sdk/typescript/docs/todo.md rename libs/@local/hashql/sdk/typescript/examples/__snapshots__/{filters.test.ts.snap => filters-draft.test.ts.snap} (95%) create mode 100644 libs/@local/hashql/sdk/typescript/examples/filters-originals.ts delete mode 100644 libs/@local/hashql/sdk/typescript/examples/filters.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/examples/filters.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Do.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Do.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Import.test.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Import.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Let.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Newtype.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Node.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Type.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/Utilities.ts delete mode 100644 libs/@local/hashql/sdk/typescript/src/do/index.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts create mode 100644 libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts diff --git a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts index f1ab879f567..15650184fbc 100644 --- a/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts +++ b/libs/@local/hashql/sdk/typescript-docs/oxlint.config.ts @@ -1,12 +1,8 @@ -import { createConfig, defineConfig } from "@local/oxlint"; +import { defineConfig } from "@local/oxlint"; export default defineConfig({ - extends: [ - createConfig({ - runtime: "node", - frameworks: ["react", "next", "effect", "vitest"], - }), - ], + runtime: "node", + frameworks: ["react", "next", "effect", "vitest"], ignorePatterns: [".next/**", ".source/**", "next-env.d.ts"], overrides: [ { diff --git a/libs/@local/hashql/sdk/typescript-docs/package.json b/libs/@local/hashql/sdk/typescript-docs/package.json index 60592da5c48..68f8943c3cc 100644 --- a/libs/@local/hashql/sdk/typescript-docs/package.json +++ b/libs/@local/hashql/sdk/typescript-docs/package.json @@ -9,7 +9,7 @@ "build": "next build --webpack", "codegen": "fumadocs-mdx", "dev": "next dev --webpack --hostname 127.0.0.1 --port ${PORT:-4398}", - "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --entry .=.generated/declarations/main.d.ts --entry ./draft=.generated/declarations/draft/index.d.ts --entry ./do=.generated/declarations/do/index.d.ts", + "doc:analyze": "tsx src/cli.ts analyze --lib ../typescript --entry .=.generated/declarations/main.d.ts --entry ./draft=.generated/declarations/draft/index.d.ts", "doc:declarations": "tsc --project tsconfig.api.json", "doc:transform": "tsx src/cli.ts transform --lib ../typescript && oxfmt content/docs/reference", "fix:oxlint": "oxlint --disable-nested-config -c oxlint.config.ts --fix", @@ -31,8 +31,8 @@ "satteri": "0.10.5" }, "devDependencies": { - "@effect/platform-node": "4.0.0", - "@effect/vitest": "4.0.0", + "@effect/platform-node": "4.0.3", + "@effect/vitest": "4.0.3", "@local/oxlint": "workspace:*", "@local/tsconfig": "workspace:*", "@microsoft/api-extractor": "7.59.4", @@ -47,7 +47,7 @@ "@types/node": "catalog:", "@types/react": "19.2.14", "@types/react-dom": "19.2.3", - "effect": "4.0.0", + "effect": "4.0.3", "mdast-util-mdx-jsx": "3.1.3", "oxc-parser": "0.152.0", "oxc-resolver": "11.24.2", diff --git a/libs/@local/hashql/sdk/typescript/README.md b/libs/@local/hashql/sdk/typescript/README.md index 0f720185e13..966bf7981da 100644 --- a/libs/@local/hashql/sdk/typescript/README.md +++ b/libs/@local/hashql/sdk/typescript/README.md @@ -1,192 +1,3 @@ -# HashQL SDK +# HashQL TypeScript SDK -The SDK constructs HashQL query syntax. TypeScript checks the authoring API. The HashQL compiler resolves names and checks the emitted program. `JExpr` provides the low-level expression builders and serializer. Construction does not execute the query. - -Import shared types, expressions, `Prelude` and `Program` from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`, or the executed Draft builder from `@local/hashql/draft`. Both produce expressions that the shared `program` constructor wraps. - -Start with the [authoring guide](docs/authoring.md). It provides a complete construction example, focused API examples and rules for developers and coding agents. - -## Draft authoring - -Draft executes one synchronous callback. Declarations accumulate around the returned expression, and the explicit input schema supplies the whole program's input contract, including unused entries and discarded declaration initializers. - -```ts -import { Result } from "effect"; -import { Prelude, Program } from "@local/hashql"; -import { program } from "@local/hashql/draft"; - -const identity = Symbol("Count"); -const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { - const Count = $.newtype("Count", identity, BigInt); - const value = $.let("value", Count(inputs.count)); - return $.if( - true, - () => value, - () => Count(0n), - ); -}); -const compiled = Result.flatMap(built, (expression) => - Program.compile(Program.program(expression)), -); -``` - -`$.type(name, definition)` accepts type expressions or structural shorthand. `$.newtype(name, uniqueSymbol, definition)` returns a type and callable nominal constructor together; for example, `const identity = Symbol("Foo"); const Foo = $.newtype("Foo", identity, { foo: BigInt }); Foo({ foo: 2n })`. Records describe structs, arrays describe tuples, and `List(BigInt)` and `Dict(String, BigInt)` describe collections. `number` remains Number, while `bigint` is Integer. - -`$.if(condition, thenCallback, elseCallback)` supplies each branch its own context. The direct `{ then, else }` form accepts already-built values. Both callbacks construct syntax. HashQL chooses the runtime branch. Use the predicate context for declarations inside a filter. Capturing an outer context can place a declaration outside the vertex's scope. HashQL performs lexical resolution and rejects free references. - -Draft's default prelude contains primitive types, List/Dict, Uuid, EntityUuid, `eq` and `add`. It demonstrates declaration-table composition rather than mirroring the complete standard library. Draft's `withPrelude(definition)` returns `{ program }` and replaces these defaults. A custom `entities` declaration supplies the query entry point. The default has none. Do's default remains empty. See the [Draft reference](docs/authoring.md#draft-executed-authoring) for coverage and source definitions. - -Draft returns construction failures as Results. Synchronous callback exceptions become `ProgramError.Construction` with a `CallbackException` reason. Its `Cause.UnknownError` retains the thrown value as its cause. TypeScript rejects async callbacks. Failed declarations remain in the collector, while an invalid import stops its callback because it cannot supply the promised handles. - -## Do authoring - -Do authoring uses separate module, value and type environments. A value and a type can have the same name. Each step receives `$` plus the environments it needs: - -| Step | Callback arguments | Introduces | -| ---------------- | ------------------ | ------------------------------------------------ | -| `Let` | `$`, values, types | One value binding | -| `Type` | `$`, types | One type alias | -| `Newtype` | `$`, types | A nominal type and its constructor | -| `Import` | `$`, modules | Selected exports in every applicable environment | -| Final expression | `$`, values, types | The block's result | - -`$` supplies literals, typed inputs, conditionals and query helpers. Its `ref` property holds the current module declarations. For example, `$.ref.math.values.cmp` accesses a declared value without importing its name locally. - -```ts -import { Result } from "effect"; -import { Module, Program, program } from "@local/hashql"; -import { withPrelude } from "@local/hashql/do"; -import type { Type as Semantic } from "@local/hashql"; - -const userId: unique symbol = Symbol("UserId"); -const query = Result.gen(function* () { - const kernel = yield* Module.define("::kernel::type", { - types: { Integer: Module.type<Semantic.PrimitiveInteger>() }, - }); - - const { Do, Let, Type, Newtype, Import } = withPrelude({ - modules: { kernel }, - }); - - const expression = yield* Do( - Import((_, { kernel }) => kernel), - Type("Count", (_, { Integer }) => Integer), - Newtype("UserId", userId, (_, { Count }) => Count), - Let("id", (_, { UserId }) => UserId(7n)), - ($, { id }, { UserId }) => $.input("id", UserId, id), - ); - - return yield* Program.compile(program(expression)); -}); -``` - -`query` is a `Result<string, ProgramError.Construction>`. `Do` returns its result after the final expression callback. Declaration steps and nested expressions retain failures internally, allowing composition without unwrapping each expression. A failed declaration skips later callbacks. Host callback exceptions propagate unchanged rather than becoming construction errors. - -`ProgramError.Construction` has the tag `ProgramConstructionError` and a tagged `reason`. Reasons identify invalid names, module paths, type arities, argument counts, expression syntax and malformed blocks. Parser-backed reasons retain their underlying `cause` without exposing the parser's error type in the program API. - -`Let` introduces one sequential binding. Later steps see a reference to that binding. Declarations wrap their bodies in HashQL special forms, not closures. Bindings retain their authored names, with identifier quoting where required. Later declarations shadow names only in their own environments. - -`Type` preserves the underlying semantic type. `Newtype` produces a distinct `Semantic.Opaque` type. Its unique symbol supplies TypeScript's nominal identity and is not serialized. Use a distinct symbol for each distinct declaration, including declarations with the same HashQL name. These builders currently define concrete types, not parameterized local declarations. - -## Imports - -In Draft, `$.import(module, selection?)` emits a lexical import and returns the selected local handles. A selection can be a name list or alias record. Types and values sharing a name keep both capabilities. Use the context of the branch or predicate that should own the import. Importing does not mutate `$.prelude()` or add query entry points. - -`Import` emits a HashQL `use` expression and introduces local references. `Import((_, { math }) => math)` imports every exported name. A second argument selects names, such as `["cmp"]`, or renames them, such as `{ cmp: "compare" }`. An alias of `"_"` retains the original name. Each selected name enters every environment in which the module exports it, including a same-named type and constructor. Imported child modules expose references beneath their local module name. - -`Do` from `@local/hashql/do` starts with empty environments. `withPrelude` from the same subpath accepts optional `modules`, `values` and `types` records without emitting imports. The positional `Do` overloads support up to eight declaration steps and a final expression. Chained nested blocks have no fixed step count. - -## Conditional blocks - -Each branch of `$.if` returns an expression. A branch needing declarations uses the scope-bound step methods and ends with `Expr`: - -```ts -import { Result } from "effect"; -import { Program, program } from "@local/hashql"; -import { Do, Let } from "@local/hashql/do"; - -const conditional = Do( - Let("outer", ($) => $.integer(7)), - ($, { outer }) => - $.if( - true, - () => $.Let("inner", () => outer).Expr((_, { inner }) => inner), - () => outer, - ), -); - -const compiled = Result.flatMap(conditional, (expression) => - Program.compile(program(expression)), -); -``` - -Branches inherit the enclosing environments, but their declarations remain local. Both callbacks run during construction, and a failure in either branch fails the containing expression. HashQL chooses which branch to evaluate when executing the query. Native JavaScript `if` tests an expression handle's truthiness, not the represented Boolean value. - -## Declarations and expressions - -`Module.define` binds declarations to absolute HashQL paths and returns a `Result`. Its `modules`, `types` and `values` records remain separate. Copying an existing export into another declaration preserves its original reference. `Module.root` assembles an existing module tree and also returns a `Result`. Both operations copy and freeze their export records. - -`Module.value<T>` declares a value, `Module.type<T>` declares a concrete type, and `Module.genericType<Lambda>` declares a parameterized type. Declarations supply trusted semantic annotations. Neither `Expression.fromJExpr<T, Inputs>` nor `TypeExpression.fromType<T>` proves that arbitrary syntax has type `T`. `Expression.fromJExpr` also trusts the supplied input requirements. Use `Inputs.Empty` for syntax without inputs. Generated declarations must obtain that information from their source. - -The package does not include a generated standard-library bundle. - -Type applications preserve the declared semantic result and retain construction failures. `TypeExpression.toType` returns the underlying type syntax as a `Result`. A type expression is not itself raw `JExpr.Type` syntax. - -Expression handles support typed projections, `$project`, `$index` and function calls. A `then` field remains directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Generic function declarations use `Semantic.GenericFunction<Signature>` with a `Semantic.FunctionSignature` mapping argument descriptors to a function signature. - -`$.literal` accepts JavaScript primitives other than `undefined` and symbols. A `number` produces `Semantic.PrimitiveNumber`, and a `bigint` produces `Semantic.PrimitiveInteger`. This distinction follows the host type, not the value: `1` remains Number even when the serializer emits integer literal syntax. Use `$.number` to construct Number explicitly or `$.integer` for checked integer construction. Non-finite numbers produce construction failures. - -Compatible primitives also work as function arguments, index keys, input defaults, comparison and Boolean operands, conditional conditions and branches, and query predicate results. Strings always denote literals, not references. Primitives contribute no input requirements. Arrays, objects and block bodies still need explicit expression construction. - -`$.input(name, type, defaultValue?)` selects its default only when the host omits the input. The SDK checks matching semantic descriptors rather than general HashQL subtyping. A Number parameter rejects Integer handles and bigints. `$.assume<T>()(expression)` changes the SDK annotation while preserving input requirements. It emits no conversion or HashQL type assertion, and does not prove the new annotation. - -Operators start on `$`: `eq`, `ne`, Boolean `and`, `or`, `not`, `isTrue`, `isFalse`, and optional-value `isNone`. Their results support `.and(...)`, `.or(...)` and `.not()` directly. Binary operators also support data-last composition, such as `pipe(predicate, $.and(other))`. Standalone code uses the same constructors through `Operators`. Ordinary expressions have no operator methods. Binding a predicate returns a plain Boolean expression. Query operations chain directly through `$.query.entities(now()).filter("vertex", predicate).collect()`. The `entities` declaration in the value environment determines the query's argument and vertex types. A filter emits a closure with the supplied parameter name. A query stored in a `Let` binding loses its query-chain methods intentionally, matching a compiler restriction. Complete the chain before binding its collected result. - -## Reusable expressions and inputs - -`Expression.Expression<T, Inputs>` carries its semantic result type and a record of input descriptors. Composition combines those records through calls, projections, indexing, value operations, filters and blocks. `Expression.Inputs<typeof expression>` extracts the record. `Program.Inputs<typeof program>` extracts it from a program. - -```ts -import { Result } from "effect"; -import { Expression, Module, Operators, Program } from "@local/hashql"; -import { Do } from "@local/hashql/do"; -import type { Type } from "@local/hashql"; - -const query = Result.gen(function* () { - const kernel = yield* Module.define("::kernel::type", { - types: { - Integer: Module.type<Type.PrimitiveInteger>(), - Boolean: Module.type<Type.PrimitiveBoolean>(), - }, - }); - - const count = Expression.input("count", kernel.types.Integer); - - const nonzero = Operators.ne(count, 0n); - - const expression = yield* Do(($) => - $.and(nonzero, $.input("enabled", kernel.types.Boolean, true)), - ); - - return Program.program(expression); -}); - -export type Inputs = Program.Inputs<Result.Result.Success<typeof query>>; -// { readonly count: Type.PrimitiveInteger; readonly enabled?: Type.PrimitiveBoolean } -``` - -The saved `nonzero` expression can participate in other programs with its `count` requirement intact. A default makes its input optional. Combining uses of the same name intersects their semantic types, and any required use makes the name required. Incompatible primitive types produce `Type.Never` in that record. This describes the requirements without adding a runtime SDK validator. - -Requirements include both conditional branches, defaults' own dependencies and every emitted `Let` initializer, including shadowed or unused bindings. They describe the constructed syntax conservatively rather than predicting which branches will execute. An expression constructed and discarded in JavaScript contributes nothing. References to local HashQL bindings retain their lexical scope requirements. - -## Syntax trees and examples - -Serialization traverses the constructed tree rather than rerunning authoring callbacks. `Let`, `Type`, `Newtype` and `Import` nodes own their child. `If` owns its condition and both branches. Every completed node implements `compile(): JExpr.Expression` without an external scope or child. - -`Expression.toNode` returns the handle's tree as a `Result`. `Expression.toJExpr` compiles it to J-Expr, and `Program.compile` also serializes it. A saved JavaScript handle still depends on the lexical scope of the HashQL name it references. The compiler owns name resolution, capture analysis and free-reference validation. - -The [authoring guide](docs/authoring.md) is the tutorial and API reference. The [checked examples](examples/api-tour.test-d.ts) retain exact-type assertions and `@ts-expect-error` cases in the package checks. These checks validate the SDK, not HashQL compiler acceptance or graph execution. - -[`examples/filters.ts`](examples/filters.ts) compares existing J-Expr queries and frontend selection predicates with Do constructions. [`examples/filters-draft.ts`](examples/filters-draft.ts) writes the same queries with Draft, using explicit schemas, local bindings and predicate callbacks. Both use the same [module declarations](examples/filters-declarations.ts). Start at `allEntities` in either file. These examples construct syntax without frontend integration or a graph connection. Their static module fixtures unwrap declaration results explicitly. - -Run the package checks with `yarn workspace @local/hashql test:unit`, `lint:tsc`, `lint:oxlint` and `build`. +Write HashQL programs in TypeScript. The guide and the API reference are in [`@local/hashql-typescript-docs`](../typescript-docs). diff --git a/libs/@local/hashql/sdk/typescript/docs/authoring.md b/libs/@local/hashql/sdk/typescript/docs/authoring.md deleted file mode 100644 index c7c251ec962..00000000000 --- a/libs/@local/hashql/sdk/typescript/docs/authoring.md +++ /dev/null @@ -1,870 +0,0 @@ -# Authoring HashQL with the TypeScript SDK - -The `@local/hashql` package builds HashQL programs from TypeScript. You describe the HashQL modules a program uses and compose expressions from typed handles. The SDK then serializes the result to J-Expr, the JSON syntax the HashQL compiler reads. The SDK neither runs nor compiles a query. It gives you typed composition and a syntax tree, and the HashQL compiler decides whether that tree is a valid program. - -Shared types, expressions, `Prelude` and `Program` come from `@local/hashql`. Import Do authoring calls from `@local/hashql/do`, or use [Draft](#draft-executed-authoring) from `@local/hashql/draft`. The resulting expressions use the same shared representation. - -This guide starts with one complete program and then works through each part of the API with focused examples. The [authoring rules](#authoring-rules) at the end condense it into rules that a person or a coding agent can follow while writing a program. - -## What checks a program - -TypeScript, construction and the HashQL compiler each catch different mistakes. - -| Stage | When it runs | What it checks | -| --------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| TypeScript | While you write the code | Which names each step can see, call arguments, projections, indexing, nominal identity and input requirements, all against the types your declarations state | -| Construction | When your code calls the SDK | Binding, import, parameter and export names, module paths, type argument counts, finite numbers, block shape and J-Expr structure | -| HashQL compiler | When you compile the program | Name resolution, lexical scope, the actual types of the modules you declared and the rules for graph queries | - -TypeScript and construction both trust your declarations. If you declare that `::core::math::add` takes two integers, the SDK accepts calls that match that declaration and nothing else. A program that type-checks and constructs can still fail to compile, for example when a declaration disagrees with the real definition or a reference leaves the scope that binds it. This guide shows what TypeScript and construction accept. Whether a program compiles is the compiler's answer, and this guide doesn't run the compiler. - -## A complete first program - -This program declares the two modules it uses, binds an optional `page` input and returns the next page number. - -```ts -import { Result } from "effect"; -import { Module, Program, program } from "@local/hashql"; -import { Import, Let, withPrelude } from "@local/hashql/do"; -import type { Type } from "@local/hashql"; - -type IntegerOperation = Type.Function< - readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], - Type.PrimitiveInteger ->; - -const built = Result.gen(function* () { - // Describe the HashQL declarations this program uses. - const kernel = yield* Module.define("::kernel::type", { - types: { Integer: Module.type<Type.PrimitiveInteger>() }, - }); - const math = yield* Module.define("::core::math", { - values: { add: Module.value<IntegerOperation>() }, - }); - - // Make the modules visible to the program's steps. - const { Do } = withPrelude({ modules: { kernel, math } }); - - const root = yield* Do( - Import((_, { math }) => math, ["add"]), - Let("page", ($) => $.input("page", $.ref.kernel.types.Integer, 1n)), - (_, { page, add }) => add(page, 1n), - ); - - return program(root); -}); - -// The host may omit `page`, because the input has a default. -export type PageInputs = Program.Inputs<Result.Result.Success<typeof built>>; -// { readonly page?: Type.PrimitiveInteger } - -const compiled = Result.flatMap(built, Program.compile); - -Result.match(compiled, { - onSuccess: (jexpr) => console.log(jexpr), - onFailure: (error) => console.error(error.reason._tag, error.message), -}); -``` - -The program has five parts. - -1. `Module.define` binds TypeScript descriptions of HashQL types to absolute paths. It returns a `Result` because a path or export name can be invalid. The program yields that `Result` inside `Result.gen`. -2. `withPrelude` makes the modules available to every step without emitting any HashQL import. -3. `Do` takes declaration steps followed by one final callback. `Import` emits a HashQL `use` and brings `add` into the value environment. `Let` binds `page` to an input. The final callback returns the program's result expression. -4. `program(root)` wraps the result expression, and `Program.compile` serializes it to a J-Expr string. Both `Do` and `Program.compile` return a `Result`. -5. The caller handles both outcomes. A failure is a `ProgramError.Construction` with a tagged `reason`. - -`IntegerOperation` limits this example's `add` declaration to its Integer-to-Integer specialization. The compiler's complete signature also supports other numeric arguments. - -On success the program prints this J-Expr, shown here with line breaks: - -```json -[ - "::kernel::special_form::use", - "::core::math", - { "#tuple": ["add"] }, - [ - "::kernel::special_form::let", - "page", - [ - "::kernel::special_form::input", - "page", - "::kernel::type::Integer", - { "#literal": 1 } - ], - ["add", "page", { "#literal": 1 }] - ] -] -``` - -## Draft: executed authoring - -`program(inputTypes, ($, inputs) => expression)` executes its callback once and returns a construction Result. The second callback argument receives typed input expressions for the schema entries. Serialization never reruns the callback. Draft does not translate JavaScript source. - -```ts -import { Result } from "effect"; -import { Prelude, Program } from "@local/hashql"; -import { program, withPrelude } from "@local/hashql/draft"; - -const identity = Symbol("Foo"); -const built = program({ count: Prelude.builtin.types.Integer }, ($, inputs) => { - const Foo = $.newtype("Foo", identity, { foo: BigInt }); - const value = $.let("value", Foo({ foo: inputs.count })); - return $.if( - true, - (branch) => branch.let("selected", value), - () => value, - ); -}); -const compiled = Result.flatMap(built, (expression) => - Program.compile(Program.program(expression)), -); -const custom = withPrelude({ types: { Count: Prelude.builtin.types.Integer } }); -const closed = custom.program({}, ($) => $.literal(1n)); -``` - -`withPrelude` returns `{ program }`, preserving the supplied module, value and type keys. It replaces the default prelude rather than extending it. `$.prelude()` flattens those three namespaces. Colliding type and value exports retain both capabilities on a fresh handle. The original exports are not mutated. Callable generic types dispatch on type arguments, and callable values on value arguments. If an argument has both capabilities, the result can retain both too. `$.modules()` offers flattened module access while each module still exposes its separate `types`, `values` and `modules` records. Namespace metadata takes precedence over same-spelled direct value fields: use `$project("syntax")` for a value field colliding with type syntax, and the separate namespace records for exports whose names collide with `path`, `types`, `values` or `modules`. Exports and projected fields called `then` remain directly accessible. Keep handles inside their construction Result rather than passing them to `await` or `Promise.resolve`. Joined expressions reserve `$project` and `$index` for explicit access. A field or export named `$` is an ordinary value. Function intrinsics such as `name` and `length` do not replace module exports. - -### Operators and imports - -Operators are explicit constructors on `$`, not methods attached to every expression. `$.eq(left, right)` returns a Boolean expression with `.and`, `.or` and `.not` methods. The same operations support data-last composition through `pipe`. A `$.let` binding returns a plain expression. Use an operator to compose it again. Standalone code can import `Operators` from `@local/hashql` and use the same constructors. - -```ts -import { pipe } from "effect"; -import { program } from "@local/hashql/draft"; - -const selection = program({}, ($) => { - const match = $.eq(1n, 1n).and($.not(false)); - const saved = $.let("saved", match); - return pipe(saved, $.or(false)); -}); -``` - -`$.import(module)` emits a lexical import and returns its typed local exports. Pass a name list or an alias record to select exports. An alias of `"_"` keeps the source name. Type and value exports sharing a name remain joined, and generic constructors retain their call signatures. Imports inside a branch or predicate belong to that child callback. They do not change the type or contents of `$.prelude()` or add entries to `$.query`. - -```ts -import { program } from "@local/hashql/draft"; - -const comparison = program({}, ($) => { - const { cmp } = $.modules(); - const { equal } = $.import(cmp, { eq: "equal" }); - return $.and(equal(1n, 1n), true); -}); -``` - -### Declarations and structural shorthand - -- `$.let(name, expressionOrPrimitive)` emits a value binding and returns a reference. An unused binding still emits its initializer. -- `$.type(name, definition)` emits an alias and returns its type expression. -- `$.newtype(name, identity, definition)` emits a nominal declaration and returns its type expression together with a callable value constructor. Give each distinct declaration its own `unique symbol`, even when names coincide. The constructor returns the nominal type, not its representation. - -Definitions accept runtime type expressions, `BigInt`, `Number`, `String`, `Boolean`, records of definitions and tuples of definitions. The host constructors denote Integer, Number, String and Boolean respectively. Default `List` and `Dict` type constructors normalize the same shorthand: `List({ count: BigInt })` and `Dict(String, BigInt)` are valid. The kernel exports List and Dict only in its type namespace. - -Nominal constructors accept their exactly typed underlying expression or structural value, such as `Foo({ foo: 2n })`. Nested expressions keep their input requirements. TypeScript rejects wrong fields, missing fields and extra fields. The SDK does not widen semantic types implicitly. Shared `Structural.type(definition)` normalizes a type outside Draft, and `Structural.value<T>()(value)` constructs an exactly typed struct or tuple expression. This shorthand does not implicitly unwrap nominal values or convert arrays into lists. - -### Explicit input contracts - -The output requirement record contains **every schema entry**, even when the body never uses an input. Draft checks emitted initializers, conditional branches, predicate bodies and the final expression against that schema. External expressions are usable when the schema declares every required or optional input they carry with the same semantic type. An undeclared input in a discarded `$.let` initializer is a type error, not a closed program. Merely constructing and dropping a handle emits no syntax. - -Every schema entry remains required in the result, including inputs whose uses all supply defaults. A host-side union of schemas requires the entries from every alternative, even an alternative containing no entries. `{}` produces `Inputs.Empty`. Keep expression requirements inferred or explicitly typed: `Expression.Any` and `Expression.Value<T>` erase them and cannot prove a Draft input contract. Composition preserves that uncertainty rather than turning it into `Inputs.Empty`. Draft adds no runtime host-input validator. Trusted raw-syntax constructors and explicit type assertions can lie about requirements. They remain trust boundaries rather than proofs. - -### Branches, queries and failures - -Use `$.if(condition, thenCallback, elseCallback)` for child declaration contexts. Both callbacks run during construction. The direct `$.if(condition, { then, else })` form accepts already-built values and does not create a declaration scope around their earlier construction. - -A custom prelude supplies `$.query.entities` when its `entities` value returns a `::graph::Graph` opaque type with a vertex marker. Its signature determines the query arguments and vertex descriptor. The filter callback receives a predicate context first. This illustrative declaration uses an example module, not the graph service's schema: - -```ts -import { Result } from "effect"; -import { Module, Structural } from "@local/hashql"; -import { withPrelude } from "@local/hashql/draft"; -import type { Type } from "@local/hashql"; - -type Vertex = Type.Struct<{ readonly archived: Type.PrimitiveBoolean }>; -type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "\'marker": Vertex }> ->; -const graph = Result.getOrThrow( - Module.define("::example::graph", { - values: { - entities: - Module.value<Type.Function<readonly [Type.PrimitiveInteger], Graph>>(), - }, - }), -); -const { program } = withPrelude(graph); -const selected = program({ axis: Structural.type(BigInt) }, ($, inputs) => - $.query - .entities(inputs.axis) - .filter("vertex", (predicate, vertex) => { - const archived = predicate.let("archived", vertex.archived); - return predicate.isFalse(archived); - }) - .collect(), -); -``` - -Declarations made through `predicate` stay inside the emitted filter closure. Capturing `$` from the outer callback instead still addresses the outer context. Likewise, JavaScript can save a branch-local reference and return it elsewhere. Draft does not reject those host-reference escapes: the HashQL compiler owns lexical resolution. Keep declarations on the context of the branch or predicate that uses them. Nested and reentrant programs have independent declaration state. - -Expected construction failures return `ProgramError.Construction`. Invalid binding names and non-finite literal initializers fail even when the body never uses their references. Those failures remain on the constructed handles, so the callback can continue. An invalid import cannot supply its promised handles and stops the current callback instead. Its failure still returns through the construction Result, even if host code catches the internal interruption. A synchronous callback exception returns a construction failure with a `CallbackException` reason. Its `Cause.UnknownError` retains the original thrown value as its cause. Async callbacks are a type error and an unchecked async callback produces a construction failure rather than a query. - -### Default prelude coverage and authority - -`Prelude.builtin` contains representative declarations rather than a complete standard-library catalogue. Their export types derive from the declaration tables in [`Prelude.ts`](../src/Program/Prelude.ts). [`PreludeTypes.ts`](../src/Program/PreludeTypes.ts) supplies the nominal identities and generic semantic operations. Generated tables can use the same `Module.define` and `withPrelude` APIs. This package has no generator. - -| Exports | Compiler source under `core/src/module/std_lib/` | -| --------------------------------------------------------------------------- | ------------------------------------------------ | -| Integer, Number, String, Boolean, Null, Unknown, Never; List and Dict types | `kernel/type.rs` | -| `eq` | `core/cmp.rs` | -| `add` | `core/math.rs` | -| Uuid type and constructor | `core/uuid.rs` | -| EntityUuid type and constructor | `graph/types/knowledge/entity.rs` | - -The declared prelude `eq` function accepts independent argument types. The operator `$.eq` checks equal semantic descriptors instead. `add` accepts Integer or Number arguments and returns their union, reducing equal descriptors to that descriptor. The SDK never converts Integer to Number implicitly. Module routes are `entity`, `uuid`, `cmp` and `math`. The default prelude has no graph or temporal declarations. Import declared modules in the body or supply them through a custom prelude. `$.query.entities` requires an `entities` declaration in the prelude. Do still starts with empty environments. - -## Shared declarations for the examples - -The remaining examples are shorter. Each assumes the imports and declarations below, and states any further declarations it needs beside its own code. - -```ts -import { Result } from "effect"; -import { Expression, Module, Operators, Program } from "@local/hashql"; -import { - Do as EmptyDo, - Import, - Let, - Newtype, - Type as Alias, - withPrelude, -} from "@local/hashql/do"; -import type { Inputs, Type } from "@local/hashql"; - -const kernel = Result.getOrThrow( - Module.define("::kernel::type", { - types: { - Boolean: Module.type<Type.PrimitiveBoolean>(), - Integer: Module.type<Type.PrimitiveInteger>(), - Number: Module.type<Type.PrimitiveNumber>(), - String: Module.type<Type.PrimitiveString>(), - }, - }), -); - -const math = Result.getOrThrow( - Module.define("::core::math", { - values: { - add: Module.value< - Type.Function< - readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], - Type.PrimitiveInteger - > - >(), - sqrt: Module.value< - Type.Function<readonly [Type.PrimitiveNumber], Type.PrimitiveNumber> - >(), - }, - }), -); - -const { Do } = withPrelude({ modules: { kernel, math } }); -``` - -These declarations never change and construct successfully, so the examples unwrap them with `Result.getOrThrow`. It throws if a declaration fails. In application code, prefer yielding each `Result` inside `Result.gen` as the first program does. - -## Environments and steps - -A program has three separate environments: modules, values and types. A value and a type can share a name. Each declaration changes only the environments it adds names to, so a `Let` never touches a type. - -Each step's callback receives `$` first, followed by the environments that step may use: - -| Step | Callback arguments | Introduces | -| -------------- | ------------------ | ------------------------------------------------------- | -| `Let` | `$`, values, types | One value binding | -| `Type` | `$`, types | One type alias | -| `Newtype` | `$`, types | One nominal type and its constructor | -| `Import` | `$`, modules | The selected exports, in each environment that has them | -| Final callback | `$`, values, types | The block's result | - -`$` holds the helpers a callback needs: - -- `$.literal`, `$.integer` and `$.number` turn host values into expressions. -- `$.input` declares a value the host supplies when it runs the query. -- `$.if` builds a HashQL conditional. -- `$.assume` changes an expression's TypeScript type without changing its syntax. -- `$.ref` holds the module environment, so `$.ref.math.values.add` reaches a declared value without importing it. -- `$.query` starts a graph query, when the value environment holds an `entities` function. -- `$.Let`, `$.Type`, `$.Newtype`, `$.Import` and `$.Expr` start a nested block. - -`Do` from `@local/hashql/do` starts with empty environments. The imports above alias it as `EmptyDo` to distinguish it from the prelude-bound `Do`. `withPrelude` accepts optional `modules`, `values` and `types` records and returns `Do` together with `Let`, `Type`, `Newtype` and `Import`. The prelude only seeds the environments. It emits no HashQL. The same subpath exports all four declaration builders directly. The imports above alias the declaration builder `Type` as `Alias`, because `Type` from `@local/hashql` names the namespace of type descriptors. - -## Declaring modules - -`Module.define(path, definition)` binds declarations to an absolute HashQL path. The definition has optional `modules`, `types` and `values` records, and each key in them is one export: - -- `Module.value<T>()` declares a value of type `T`, such as a function. -- `Module.type<T>()` declares a concrete type. -- `Module.genericType<Lambda>(arity)` declares a type constructor that takes `arity` type arguments. -- An existing module under `modules` becomes a child module. An existing export copied into another module keeps its original path. - -These records are the only place where one JavaScript object describes more than one declaration. They describe what a module exports. Declaration steps inside a program work differently: each `Let`, `Type` or `Newtype` step declares exactly one name. - -`Module.define` returns a `Result`. A relative path, an invalid path or an invalid export name produces a construction failure. `Module.root` assembles already defined modules into a tree and also returns a `Result`. Both copy and freeze their records, so later changes to your objects don't change a module. - -A declaration is a trusted annotation. Beyond the bounded [Draft prelude](#default-prelude-coverage-and-authority), write declarations for the parts of HashQL a program uses. The Do examples below keep their explicit fixtures. The compiler checks the emitted program against the real definitions. Generated declarations must take their types from the definitions they describe. - -A module's values are expressions that refer to their absolute path. You can use them through `$.ref` without importing anything: - -```ts -// Uses: math, Do. -const viaRef = Do(($) => $.ref.math.values.add(7n, 2n)); -// Compiles to ["::core::math::add",{"#literal":7},{"#literal":2}] -``` - -## Ordered declarations and shadowing - -`Do` runs its construction steps in order, and each step sees the names that earlier steps introduced. A later declaration shadows an earlier one of the same name, and only in its own environment. - -This order determines callback name visibility, not a HashQL evaluation schedule. HashQL is pure, and a binding cannot refer to itself. The compiler orders the resulting bindings. - -```ts -// Uses: kernel, Do. -const ordered = Do( - Import((_, { kernel }) => kernel, ["Integer"]), - Let("limit", ($) => $.integer(10)), - Let("previous", (_, { limit }) => limit), - // Shadows the value `limit` for the steps that follow. - Let("limit", ($) => $.literal("ten")), - // A value named `Integer` leaves the type `Integer` untouched. - Let("Integer", ($) => $.literal("a value named Integer")), - ($, { limit, previous }, { Integer }) => - $.if( - Operators.eq(limit, "ten"), - () => previous, - () => $.input("fallback", Integer), - ), -); -``` - -In the final callback, `previous` is an Integer expression, `limit` is a String expression, and the type `Integer` is still the kernel type. Each `Let` emits a HashQL `let` that wraps the steps after it, so the second `limit` binding sits inside the first. - -Each step declares one name. `Let`, `Type` and `Newtype` take a name and a callback that returns one expression or type. A callback can't return a record of declarations, so binding three values takes three `Let` steps. - -The positional form of `Do` accepts up to eight declaration steps before the final callback. For more, continue with a nested block: `$` starts one, and its chained methods have no fixed step limit. - -```ts -// Uses: Do. -const chained = Do(($) => - $.Let("first", ($) => $.integer(1)) - .Let("second", (_, { first }) => first) - .Let("third", (_, { second }) => second) - .Expr((_, { third }) => third), -); -``` - -A chain must end with `Expr`, which takes the final callback and returns the block's expression. - -## Nominal identity - -`Newtype` introduces a nominal type and its constructor under one name. The constructor wraps a value of the underlying type. A `unique symbol` gives the type its identity in TypeScript and isn't emitted. - -```ts -// Uses: kernel, Do. -const userId: unique symbol = Symbol("UserId"); -const accountId: unique symbol = Symbol("AccountId"); - -const owner = Do( - Import((_, { kernel }) => kernel, ["Integer"]), - Newtype("UserId", userId, (_, { Integer }) => Integer), - Let("owner", (_, { UserId }) => UserId(1n)), - ($, { owner, UserId }, types) => { - // @ts-expect-error The representation 2n doesn't have the nominal type. - $.input("id", types.UserId, 2n); - return $.if( - Operators.eq(owner, UserId(1n)), - () => $.input("id", types.UserId, UserId(2n)), - () => owner, - ); - }, -); -``` - -`types.UserId` is the nominal type, and the value `UserId` is its constructor. To pass an Integer where the program needs a `UserId`, wrap it with the constructor. - -Declarations that share a HashQL name are different types in TypeScript when their symbols differ: - -```ts -// Uses: kernel, Do, userId and accountId from the previous example. -const shadowedId = Do( - Import((_, { kernel }) => kernel, ["Integer"]), - Newtype("Id", userId, (_, { Integer }) => Integer), - Let("first", (_, { Id }) => Id(1n)), - Newtype("Id", accountId, (_, { Integer }) => Integer), - (_, { first, Id }) => { - // @ts-expect-error The later `Id` is a different nominal type. - Operators.eq(first, Id(2n)); - return first; - }, -); -``` - -Give each `Newtype` its own `unique symbol`, including declarations that share a HashQL name. A symbol widened to plain `symbol` can't tell declarations apart, and TypeScript rejects it. - -`Type` declares an alias instead. An alias keeps the underlying type, so `Alias("Count", (_, { Integer }) => Integer)` produces a type that TypeScript treats as Integer. `Type` and `Newtype` currently declare concrete types only, without type parameters. - -## Imports and renaming - -`Import` takes a callback that selects a module from the module environment and an optional selection. It emits a HashQL `use` around the steps that follow and adds local names for the selected exports: - -- `Import(select)` imports every export. -- `Import(select, ["add", "sqrt"])` imports the listed exports. -- `Import(select, { add: "sum" })` imports `add` under the local name `sum`. An alias of `"_"` keeps the original name. - -```ts -// Uses: kernel, math, Do. -const imported = Do( - Import((_, { math }) => math, { add: "sum" }), - Import((_, { kernel }) => kernel, { Integer: "_", String: "Text" }), - ($, { sum }, { Integer }) => sum($.input("count", Integer), 2n), -); -``` - -A selected name enters every environment in which the module exports it, so one import provides both a type and a constructor of the same name. TypeScript rejects a selection that names no export of the declared module. - -Importing a child module adds it to the module environment under its local name. `$.ref` then reaches it by that name: - -```ts -// Uses: math. -const core = Result.getOrThrow(Module.define("::core", { modules: { math } })); - -const viaChild = withPrelude({ modules: { core } }).Do( - Import((_, { core }) => core, { math: "m" }), - ($) => $.ref.m.values.add(7n, 2n), -); -// Compiles to a `use` of `::core` around a call to `m::add`. -``` - -Refer to declarations through handles: callback environments, imports and `$.ref`. A string is always a string literal. `$.literal("add")` is the text `"add"`, not a reference to the function. - -## Projections and indexing - -An expression handle offers the fields and positions of its type as typed properties. This example declares a `Profile` type in a hypothetical `::example::profile` module, which stands for a module in your own HashQL environment. - -```ts -// Uses: Do. Declares the module below. -type Profile = Type.Struct<{ - readonly name: Type.PrimitiveString; - readonly scores: Type.List<Type.PrimitiveInteger>; - readonly labels: Type.Dict<Type.PrimitiveString, Type.PrimitiveString>; - readonly location: Type.Tuple< - readonly [Type.PrimitiveNumber, Type.PrimitiveNumber] - >; -}>; - -const profiles = Result.getOrThrow( - Module.define("::example::profile", { - types: { Profile: Module.type<Profile>() }, - }), -); - -const label = withPrelude({ modules: { profiles } }).Do( - Import((_, { profiles }) => profiles, ["Profile"]), - Let("profile", ($, _values, { Profile }) => $.input("profile", Profile)), - (_, { profile }) => profile.labels.$index(profile.name), -); -``` - -With `profile` bound to a `Profile` expression, these accessors are available: - -| Expression | Result type | -| ---------------------------- | ----------------- | -| `profile.name` | `String` | -| `profile.$project("name")` | `String` | -| `profile.location[0]` | `Number` | -| `profile.scores.$index(0n)` | `Integer \| Null` | -| `profile.labels.$index("x")` | `String \| Null` | - -Indexing a list or dictionary includes `Null` in its result type, because the key might not be present. A list key is an Integer, and a dictionary key has the dictionary's key type. A field the struct doesn't declare is a TypeScript error. A projection or index requires the inputs of the expression it reads, together with those of its key. - -Projections reach through opaque types to their representation. A union or intersection offers a field when every member offers it. - -Direct access to a `then` field returns `undefined`. This stops JavaScript from treating a handle as a Promise. Use `$project("then")` for that field. `$project` and `$index` also work for any other field or key. - -## Typed calls - -A handle whose type is a function is callable with typed arguments. - -```ts -// Uses: kernel, math, Do. -const sum = Do(($) => { - const count = $.input("count", $.ref.kernel.types.Integer); - // @ts-expect-error `add` takes Integer arguments, and 2 is a Number. - $.ref.math.values.add(count, 2); - // @ts-expect-error `add` takes exactly two arguments. - $.ref.math.values.add(count); - return $.ref.math.values.add(count, 2n); -}); -``` - -The result has the declared return type, and its input requirements combine those of the callee and every argument. Here `sum` requires a `count` input. - -Module values are ordinary handles, so you can call them outside a block as well: `math.values.add(7n, 2n)` is an Integer expression. - -For a function whose types depend on its arguments, declare `Type.GenericFunction<Signature>` with a `Type.FunctionSignature` that maps the argument types to a function type. The SDK applies the signature at each call and doesn't infer it from HashQL. - -## Value operations - -The `.$` property of a handle exposes value operations that emit standard-library calls: - -- `eq` and `ne` compare with a value of the same type, emitting `::core::cmp::eq` and `::core::cmp::ne`. -- On Boolean expressions, `and`, `or`, `isTrue` and `isFalse` emit `::core::bool::and`, `::core::bool::or` and comparisons with `true` or `false`. -- On a union that includes the `::core::option::None` opaque type, `isNone` compares with `None`. - -The operand of `eq` or `ne` must have exactly the receiver's type, and the operand of `and` or `or` must be Boolean. A matching host primitive also works. The [primitives section](#primitives-and-explicit-assumptions) explains what "exactly" means here. - -## Queries - -`$.query` builds graph queries. It exists when the value environment holds an `entities` function that returns a graph type, `Type.Opaque<"::graph::Graph", …>`. The graph type's `'marker` field names the vertex type, and the SDK reads the query's vertex type from it. - -The package doesn't generate these declarations. Like the module declarations above, they are yours to write. This example declares only the entity field it reads: - -```ts -// Uses: kernel. Declares the graph fixtures below. -type Entity = Type.Opaque< - "::graph::types::knowledge::entity::Entity", - Type.Struct<{ - readonly metadata: Type.Struct<{ - readonly archived: Type.PrimitiveBoolean; - }>; - }> ->; -type EntityGraph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Entity }> ->; -type TemporalAxes = Type.Opaque< - "::graph::temporal::QueryTemporalAxes", - Type.Unknown ->; - -const head = Result.getOrThrow( - Module.define("::graph::head", { - values: { - entities: - Module.value<Type.Function<readonly [TemporalAxes], EntityGraph>>(), - }, - }), -); -const temporal = Result.getOrThrow( - Module.define("::graph::tmp", { - values: { - decision_time_now: - Module.value<Type.Function<readonly [], TemporalAxes>>(), - }, - }), -); - -const graph = withPrelude({ - modules: { kernel }, - values: { - entities: head.values.entities, - now: temporal.values.decision_time_now, - }, -}); -``` - -A query starts at `$.query.entities(...)`, adds filters and ends with `collect()`: - -```ts -// Uses: the graph fixtures above. -const isLive = (entity: Expression.Expression<Entity, Inputs.Empty>) => - Operators.isFalse(entity.metadata.archived); - -const live = graph.Do(($, { now }) => - $.query - .entities(now()) - .filter("entity", isLive) - .filter("entity", (entity) => - Operators.eq( - entity.metadata.archived, - $.input("archived", $.ref.kernel.types.Boolean, false), - ), - ) - .collect(), -); -``` - -`live` is a construction Result containing one list-valued expression, with an optional `archived` input. Each `filter` emits a closure whose parameter has the name you pass, so that name must be a valid identifier. A predicate is an ordinary function from a vertex expression to a Boolean expression, and you can reuse it across queries. Predicate inputs accumulate in the query's requirements. - -### Queries and `Let` - -A `Let` binding holds a plain expression of the bound value's type. A query stored in a binding loses `filter` and `collect`. This is intentional: it matches a restriction the HashQL compiler places on graph query chains. Build the whole chain in one expression, and bind the collected result or the values the query depends on: - -```ts -// Uses: the graph fixtures and isLive above. -const firstLive = graph.Do( - Let("axes", (_, { now }) => now()), - Let("live", ($, { axes }) => - $.query.entities(axes).filter("entity", isLive).collect(), - ), - (_, { live }) => live.$index(0n), -); -``` - -Binding `$.query.entities(axes)` without `collect()` gives a binding of the graph type, and TypeScript reports `filter` on it as an unknown property. - -## Input requirements - -An expression handle has two types: the HashQL type of its value, and a record of the inputs it requires. `Expression.Expression<T, Inputs>` carries both. Composition combines the records, so a reusable expression keeps its requirements wherever you use it. - -```ts -// Uses: kernel, Do. -const count = Expression.input("count", kernel.types.Integer); -const nonzero = Operators.ne(count, 0n); -// Expression.Expression<Type.PrimitiveBoolean, { readonly count: Type.PrimitiveInteger }> - -const enabled = Do(($) => - Operators.and(nonzero, $.input("enabled", $.ref.kernel.types.Boolean, true)), -); - -export type EnabledInputs = Expression.Inputs< - Result.Result.Success<typeof enabled> ->; -// { readonly count: Type.PrimitiveInteger; readonly enabled?: Type.PrimitiveBoolean } -``` - -`Expression.Inputs<E>` extracts the record from an expression and `Program.Inputs<P>` from a program. The record follows these rules: - -- An input with a default is optional for the host. The default's own requirements join the record. -- Calls, projections, indexing, value operations, filters, conditionals and blocks combine the requirements of their parts. -- Uses of one name intersect their types, and a required use makes the name required. Uses with incompatible primitive types produce `Type.Never` for that name instead of an error at the use site. Give inputs of different types different names. -- A conditional requires the inputs of its condition and both branches, because the record describes the constructed syntax rather than predicting which branch runs. -- A reference to a `Let` binding requires the inputs of its initializer. - -A type annotation can't hide a requirement. Annotating `nonzero` with an empty input record is a TypeScript error: - -```ts -// Uses: nonzero from the previous example. -// @ts-expect-error The empty record has no room for `count`. -const hidden: Expression.Expression<Type.PrimitiveBoolean, Inputs.Empty> = - nonzero; -``` - -Let TypeScript infer the type, or name the requirement with `Expression.Inputs<typeof nonzero>`. The record is a TypeScript type. The SDK adds no runtime validator for the values a host supplies. - -### Discarded host expressions and unused bindings - -Only syntax that ends up in the tree counts. An expression you construct in JavaScript and then drop contributes nothing, while an unused `Let` binding is still emitted with its initializer. - -```ts -// Uses: Do. -const discarded = Do(($) => { - // JavaScript drops this handle, so the program never contains it. - $.input("ignored", $.ref.kernel.types.Integer); - return $.integer(1); -}); -// Compiles to {"#literal":1} and requires no inputs. - -const unused = Do( - // Nothing refers to `unused`, but the `let` and its initializer are emitted. - Let("unused", ($) => $.input("retained", $.ref.kernel.types.Integer)), - ($) => $.integer(1), -); -// Compiles to a `let` whose initializer is the `retained` input, and requires `retained`. -``` - -The same holds for shadowed bindings: their initializers stay in the program and in the input record. - -## Primitives and explicit assumptions - -Where the SDK expects a value, you can often pass a host primitive. `$.literal` turns one into an expression explicitly. The host type decides the HashQL type: - -| Host value | HashQL type | -| ---------- | ----------- | -| `number` | `Number` | -| `bigint` | `Integer` | -| `string` | `String` | -| `boolean` | `Boolean` | -| `null` | `Null` | - -The type follows the host type, not the value. `1` stays a Number even though the serializer emits the same literal syntax for `1` and `1n`. Use `$.number(value)` to construct a Number explicitly, or `$.integer(value)` for a checked Integer that fails construction for a fractional value. A non-finite number fails construction wherever you pass it. `undefined` and symbols are not HashQL values. - -Host primitives work as function arguments, `$index` keys, input defaults, operands of `.$` operations, `$.if` conditions and branch results, and filter predicate results. They contribute no input requirements. The callbacks of `Do`, `Let` and `Expr` must return an expression handle, so lift a host value there with `$.literal`, `$.integer` or `$.number`. - -### Exact matching - -The SDK compares types exactly and doesn't model HashQL subtyping. A parameter declared as Number rejects an Integer expression and a `bigint`, and a parameter declared as `String | Null` rejects a String expression. When you know the wider type is correct, state it with `Expression.assume` or `$.assume`: - -```ts -// Uses: kernel, math. -type NullableString = Type.Union< - readonly [Type.PrimitiveString, Type.PrimitiveNull] ->; - -const root = math.values.sqrt(2); -// @ts-expect-error Integer doesn't widen to Number in the SDK. -math.values.sqrt(2n); - -const two = Expression.assume<Type.PrimitiveNumber>()(Expression.integer(2)); -const rootOfTwo = math.values.sqrt(two); - -const name = Expression.input("name", kernel.types.String); -const nullable = Expression.assume<NullableString>()(name); -// Expression.Expression<NullableString, { readonly name: Type.PrimitiveString }> -``` - -An assumption changes only the TypeScript type. It emits no conversion and no HashQL type assertion, and `two` serializes exactly as `Expression.integer(2)` does. It preserves input requirements: `nullable` still requires `name`, and that input keeps its declared String type. An assumption doesn't prove anything either. The compiler still checks the program. - -### Conditions - -A `$.if` condition is a Boolean expression or a host `boolean`. Write `$.if(true, thenCallback, elseCallback)` rather than wrapping the constant in `$.literal`. An Integer or other non-Boolean expression is a TypeScript error as a condition. Outside a block, the top-level `If(condition, { then, else })` builds the same conditional from branches you have already constructed. - -## Local scopes and host versus HashQL evaluation - -Your TypeScript runs when it constructs the program. The HashQL it builds runs later, when the host executes the query. Most mistakes in this area come from mixing up the two. - -### Local bindings - -A nested block introduces bindings visible only inside it. Here `inner` exists in the first branch alone: - -```ts -// Uses: math, Do. -const scoped = Do( - Let("outer", ($) => $.integer(7)), - ($, { outer }) => - $.if( - true, - () => - $.Let("inner", () => math.values.add(outer, 2n)).Expr( - (_, { inner }) => inner, - ), - () => outer, - ), -); -``` - -The branch emits its own `let`, nested inside the conditional. A nested block inherits the enclosing environments, and its declarations stay local. TypeScript types each callback's environments, so naming `inner` in the other branch is a TypeScript error. - -### What a handle refers to - -An expression handle holds a piece of syntax, its HashQL type and its input record. Some handles refer to names. A `Let` binding, an imported value and a `Newtype` constructor are local identifiers. A module declaration reached through the prelude is an absolute path such as `::core::math::add`. Other handles are composite syntax: literals, inputs, calls, projections, conditionals and nested blocks. - -The SDK doesn't resolve names. The compiler resolves them, checks that each local identifier sits inside the expression that binds it, and type-checks the program. JavaScript can carry a handle for a local identifier out of the block that binds it, and TypeScript accepts the result: - -```ts -// Uses: Do. -let escaped = Expression.integer(0); -Do( - Let("local", ($) => $.integer(1)), - (_, { local }) => { - escaped = local; - return local; - }, -); -const outside = Do(() => escaped); -``` - -`outside` constructs and type-checks, but the program it emits refers to `local` outside the `let` that binds it. Rejecting that program is the compiler's job. Take handles from the callback arguments of the block that uses them. - -### Host decisions and HashQL decisions - -A JavaScript `if`, ternary or loop runs during construction and decides what syntax to build. `$.if` builds a HashQL conditional, which decides at query time. A JavaScript `if` on a handle tests the handle object, which is always truthy, not the Boolean it represents. - -```ts -// Uses: Do. -const target = 3 * 10; - -const message = (verbose: boolean) => - Do(($) => { - const count = $.input("count", $.ref.kernel.types.Integer); - // JavaScript picks one literal now, while it builds the program. - const detail = verbose ? "count equals the target" : "equal"; - // HashQL compares `count` with 30 when the query runs. - return $.if( - Operators.eq(count, BigInt(target)), - () => detail, - () => "different", - ); - }); -``` - -`target`, `verbose` and `detail` are host values, so the emitted program contains only their results. `message(true)` and `message(false)` build two different programs. - -### Construction order and failures - -The SDK calls your callbacks during construction, in step order. A few details follow from that: - -- The SDK constructs both branches of a `$.if`, even though HashQL evaluates only one of them. A construction failure in either branch fails the whole conditional. -- A failed step skips the later callbacks of its block. A failing `Let` in a nested block skips the steps after it, and an invalid filter parameter name skips that filter's predicate. -- Expected construction failures arrive as a failed `Result`. An exception your own callback throws isn't converted. It propagates out of `Do` unchanged. - -Don't rely on a callback running for its side effects. - -## Construction errors - -Expected construction failures arrive as a `Result` holding a `ProgramError.Construction`. Its `_tag` is `"ProgramConstructionError"`, and its `reason` says what went wrong: - -```ts -// Uses: the shared imports. -const invalid = EmptyDo( - Let("not a name", ($) => $.integer(1)), - ($) => $.integer(2), -); - -if (Result.isFailure(invalid)) { - const error = invalid.failure; - console.log(error.reason._tag); // "InvalidBindingName" - console.log(error.message); // Invalid HashQL binding name: "not a name" -} -``` - -The reasons are: - -| Reason | Cause | -| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | -| `InvalidBindingName`, `InvalidImportName`, `InvalidParameterName`, `InvalidExportName` | A name isn't a valid HashQL identifier | -| `InvalidModulePath`, `RelativeModulePath` | A module path is invalid or not absolute | -| `InvalidTypeArity`, `TypeArgumentCount` | A type constructor has an invalid arity or wrong number of arguments | -| `InvalidExpression` | Syntax isn't valid J-Expr, including non-finite numbers | -| `InvalidBlock` | A block's steps are out of shape, or a callback returned something other than an expression | - -Reasons that come from parsing a name or syntax carry the parser's error as `cause`. The output quotes a binding name that needs quoting, such as `%`, rather than rejecting it. - -## Constructing from raw syntax - -`Expression.fromJExpr<T, Inputs>(syntax)` wraps raw J-Expr as an expression. It validates the syntax's structure and trusts both type arguments. `TypeExpression.fromType<T>(syntax)` does the same for type syntax. The `JExpr` namespace holds builders and a serializer for raw syntax. - -Raw syntax has no input record, so these constructors take the requirements on trust. Use `Inputs.Empty` only for syntax that contains no inputs, and state every input the syntax contains. To change an expression's type, use `Expression.assume`. It keeps the requirements automatically. A raw-syntax round trip requires you to supply them again; using `Inputs.Empty` loses them: - -```ts -// Uses: kernel. -const counted = Expression.input("count", kernel.types.Integer); - -// Drops the `count` requirement: the raw syntax still contains the input. -const dropped = Expression.fromJExpr<Type.PrimitiveInteger, Inputs.Empty>( - Result.getOrThrow(Expression.toJExpr(counted)), -); - -// Keeps it. -const kept = Expression.assume<Type.PrimitiveInteger>()(counted); -``` - -`Expression.toJExpr` returns an expression's J-Expr as a `Result`. `Expression.toNode` returns its syntax tree as a `Result`. `Program.compile` returns a `Result` containing the serialized program. - -## Authoring rules - -Follow these rules when you write HashQL with the SDK, whether by hand or as a coding agent. - -1. Use the SDK when you want typed composition. Describe each module the program uses with `Module.define`, with types taken from the real HashQL definitions. -2. Use only API that the package exports, as this guide shows it. Don't invent methods, helpers or overloads. `JExpr` provides raw struct and list builders, but the high-level expression API currently offers neither typed equivalents nor unchecked accessors. -3. Refer to declarations through handles from callback environments, `Import` and `$.ref`. A string is always a literal. -4. Return an expression handle from every `Do`, `Let` and `Expr` callback. Lift host values with `$.literal`, `$.integer` or `$.number`. -5. Declare one name per `Let`, `Type` or `Newtype` step. Records that list declarations belong in `Module.define`. -6. Handle every `Result`. Yield inside `Result.gen` in application code. Draft wraps callback exceptions as construction failures. Do callback exceptions propagate unchanged. -7. Preserve input requirements. Let TypeScript infer handle types, use `assume` rather than raw syntax round trips, and state every input when you wrap raw syntax with `Expression.fromJExpr`. -8. Don't treat TypeScript annotations or `assume` as compiler validation. A program that type-checks still needs the HashQL compiler. -9. Keep references in their HashQL lexical scope. Take each handle from the callback arguments of the block that uses it, and don't store local bindings in outer variables. -10. Chain `filter` and `collect` before binding a query. Bind the collected result or the values the query depends on. -11. Use `$.if` for decisions the query makes and JavaScript control flow for decisions you make while building it. -12. Match types exactly. A `number` produces a Number and a `bigint` produces an Integer. State a wider type with `assume` when you know it is correct. -13. Give each `Newtype` its own `unique symbol`. diff --git a/libs/@local/hashql/sdk/typescript/docs/todo.md b/libs/@local/hashql/sdk/typescript/docs/todo.md deleted file mode 100644 index 08afd74d4f7..00000000000 --- a/libs/@local/hashql/sdk/typescript/docs/todo.md +++ /dev/null @@ -1,25 +0,0 @@ -# SDK authoring and execution - -## Language guide - -- [ ] Explain HashQL's language model, including construction time versus query execution. -- [ ] Guide readers through Draft and Do, with reusable examples and advice on choosing between them. -- [ ] Document available standard-library and graph operations, supported types and current limitations. -- [ ] Check guide examples against the SDK and include a complete parameterized query through execution. - -## Execution - -- [ ] Provide separate fetch and native Effect HTTP entry points. The Effect client must not wrap the fetch client. -- [ ] Evaluate Orval for HTTP client and schema generation. Its Effect generator currently produces schemas, not an HTTP client. -- [ ] Add graph API support for query inputs. -- [ ] Define JavaScript value encoding and result decoding, preserving each program's input and result types. -- [ ] Expose program execution with client configuration, authentication, cancellation and structured diagnostics. - -## Function authoring - -- [ ] Add a typed HashQL function-expression builder to Do and Draft. Infer the return type from the body and retain captured input requirements. Provide typed parameter handles and match the existing callback-exception behavior. Bind named functions through the existing `Let`/`let` APIs. Raw `JExpr.fn` and callable expression types already exist. - -## Authoring checks - -- [ ] Return Do callback exceptions as construction failures, matching Draft. -- [ ] Add Oxlint binding-name checks and warnings for native operators on expression handles or host control flow inside authoring callbacks. diff --git a/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap similarity index 95% rename from libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap rename to libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap index f67a1e1419c..899b8519029 100644 --- a/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters.test.ts.snap +++ b/libs/@local/hashql/sdk/typescript/examples/__snapshots__/filters-draft.test.ts.snap @@ -1,6 +1,6 @@ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html -exports[`filter_examples > frontend_selection: 5. Frontend: look up a published entity 1`] = ` +exports[`draft_filters > frontend_selection: 5. Frontend: look up a published entity 1`] = ` [ "::kernel::special_form::let", "webId", @@ -116,7 +116,7 @@ exports[`filter_examples > frontend_selection: 5. Frontend: look up a published ] `; -exports[`filter_examples > frontend_selection: 6. Frontend: the sidebar's web and arch… 1`] = ` +exports[`draft_filters > frontend_selection: 6. Frontend: the sidebar's web and arch… 1`] = ` [ "::kernel::special_form::let", "webId", @@ -185,7 +185,7 @@ exports[`filter_examples > frontend_selection: 6. Frontend: the sidebar's web an [ "::core::bool::and", [ - "::core::cmp::ne", + "::core::cmp::eq", [ "::kernel::special_form::access", [ @@ -196,7 +196,7 @@ exports[`filter_examples > frontend_selection: 6. Frontend: the sidebar's web an "archived", ], { - "#literal": true, + "#literal": false, }, ], [ @@ -229,7 +229,7 @@ exports[`filter_examples > frontend_selection: 6. Frontend: the sidebar's web an ] `; -exports[`filter_examples > frontend_selection: 7. Frontend: match any supplied entity … 1`] = ` +exports[`draft_filters > frontend_selection: 7. Frontend: match any supplied entity … 1`] = ` [ "::graph::tail::collect", [ @@ -323,7 +323,7 @@ exports[`filter_examples > frontend_selection: 7. Frontend: match any supplied e ] `; -exports[`filter_examples > frontend_selection: 8. Frontend: make draft inclusion a que… 1`] = ` +exports[`draft_filters > frontend_selection: 8. Frontend: make draft inclusion a que… 1`] = ` [ "::kernel::special_form::let", "includeDrafts", diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts index 7947bbf13ab..902edad8d3c 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-declarations.ts @@ -1,5 +1,5 @@ /** - * Minimal graph declarations shared by the Do and Draft filter examples. + * Minimal graph declarations for the Draft filter examples. * * These declarations cover only the entity fields and standard-library exports used by the examples. Generated bindings can supply these declarations without changing the query bodies. * diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts index 6081ff1681f..2807d4f8e5d 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.test.ts @@ -1,10 +1,11 @@ /** Construction and input typing for the Draft filter gallery. @module */ -import { Array, Result, pipe } from "effect"; +import { Array, Record, Result, Schema, flow, pipe } from "effect"; import { describe, expect, expectTypeOf, test } from "vitest"; +import { isReadonlyArray } from "../src/internal/array.js"; import { Expression, JExpr } from "../src/main.js"; import { examples } from "./filters-draft.js"; -import { examples as originals } from "./filters.js"; +import { originals } from "./filters-originals.js"; import type { Type } from "../src/main.js"; import type * as ProgramError from "../src/Program/ProgramError.js"; @@ -15,6 +16,108 @@ import type { WebId, } from "./filters-declarations.js"; +const aliases = new Map([ + ["::core::cmp::eq", "=="], + ["::core::bool::and", "&&"], + ["::core::bool::or", "||"], +]); + +const parseJson = flow( + Schema.decodeResult(Schema.fromJsonString(Schema.Json)), + Result.getOrThrow, +); +const parseImport = flow( + Schema.decodeUnknownResult( + Schema.Tuple([ + Schema.Literal("::kernel::special_form::use"), + Schema.String, + Schema.Union([ + Schema.Struct({ "#tuple": Schema.Array(Schema.String) }), + Schema.Struct({ + "#struct": Schema.Record(Schema.String, Schema.String), + }), + ]), + Schema.Json, + ]), + ), + Result.getOrThrow, +); + +const resolveImport = ( + value: Schema.JsonArray, + imports: ReadonlyMap<string, string>, +): { + readonly body: Schema.Json; + readonly imports: ReadonlyMap<string, string>; +} => { + const [, path, selection, body] = parseImport(value); + const imported = new Map(imports); + if ("#tuple" in selection) { + for (const name of selection["#tuple"]) { + imported.set(name, `${path}::${name}`); + } + } else { + for (const [name, alias] of Record.toEntries(selection["#struct"])) { + let binding = alias; + if (alias === "_") { + binding = name; + } + imported.set(binding, `${path}::${name}`); + } + } + return { body, imports: imported }; +}; + +// Only spelling differs: qualified exports, explicit projections and the inferred temporal type. +const normalize = ( + value: Schema.Json, + imports: ReadonlyMap<string, string> = new Map(), +): Schema.Json => { + if (typeof value === "string") { + return imports.get(value) ?? value; + } + if (isReadonlyArray<Schema.Json, Schema.Json>(value)) { + if (value[0] === "::kernel::special_form::use") { + const imported = resolveImport(value, imports); + return normalize(imported.body, imported.imports); + } + const nodes = pipe( + value, + Array.map((node) => normalize(node, imports)), + ); + const [operation, input, field] = nodes; + if (typeof operation !== "string") { + return nodes; + } + const callee = operation.replace("::kernel::special_form::", ""); + if ( + callee === "access" && + typeof input === "string" && + typeof field === "string" + ) { + return `${input}.${field}`; + } + if ( + callee === "input" && + input === "axis" && + field === "::graph::temporal::QueryTemporalAxes" + ) { + return [callee, input, "_"]; + } + return [aliases.get(callee) ?? callee, ...Array.drop(nodes, 1)]; + } + if (value !== null && typeof value === "object") { + if ("#literal" in value) { + return value; + } + return pipe( + value, + Record.map((member) => normalize(member, imports)), + ); + } + return value; +}; + const compile = ( result: Result.Result<Expression.Any, ProgramError.Construction>, ): string => @@ -32,14 +135,77 @@ const suppliedTimeAxis = examples[2]; const publishedEntityById = examples[publishedSelection]; const optionalDrafts = examples[draftSelection]; -const comparisons = pipe( +const gallery = pipe( Array.zip(examples, originals), - Array.map(([draft, original]) => ({ - draft, - original, - title: original.title, + Array.map(([program, { title, source, before }]) => ({ + program, + title, + source, + before, })), ); +const jexprExamples = pipe( + gallery, + Array.filter(({ source }) => source.endsWith(".jsonc")), +); +const frontendExamples = pipe( + gallery, + Array.filter( + ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), + ), +); + +describe("query_normalization", () => { + test("import_aliases", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::example", + { "#struct": { left: "binding", right: "_" } }, + ["binding", "right", { "#literal": "binding" }], + ]), + ).toStrictEqual([ + "::example::left", + "::example::right", + { "#literal": "binding" }, + ]); + }); + + test("import_shadowing", () => { + expect.hasAssertions(); + expect( + normalize([ + "::kernel::special_form::use", + "::outer", + { "#tuple": ["value"] }, + [ + "pair", + "value", + [ + "::kernel::special_form::use", + "::inner", + { "#tuple": ["value"] }, + "value", + ], + "value", + ], + ]), + ).toStrictEqual([ + "pair", + "::outer::value", + "::inner::value", + "::outer::value", + ]); + }); + + test("literal_values", () => { + expect.hasAssertions(); + expect(normalize(["==", "field", { "#literal": false }])).not.toStrictEqual( + normalize(["==", "field", { "#literal": true }]), + ); + }); +}); describe("draft_filters", () => { test("query_with_import", () => { @@ -50,13 +216,26 @@ describe("draft_filters", () => { ); }); - test.each(Array.drop(comparisons, 1))( - "matching_selection: $title", - ({ draft, original }) => { - expect.hasAssertions(); - expect(compile(draft)).toBe(Result.getOrThrow(original.compile())); - }, - ); + test.each(gallery)("valid_construction: $title", ({ program }) => { + expect.hasAssertions(); + expect(() => + JExpr.make( + pipe(program, Result.flatMap(Expression.toJExpr), Result.getOrThrow), + ), + ).not.toThrow(); + }); + + test.each(jexprExamples)("original_query: $title", ({ program, before }) => { + expect.hasAssertions(); + expect(normalize(parseJson(compile(program)))).toStrictEqual( + normalize(parseJson(before)), + ); + }); + + test.each(frontendExamples)("frontend_selection: $title", ({ program }) => { + expect.hasAssertions(); + expect(parseJson(compile(program))).toMatchSnapshot(); + }); test("declared_inputs", () => { expect.hasAssertions(); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts index 13ad35765e0..45d28b30d88 100644 --- a/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts +++ b/libs/@local/hashql/sdk/typescript/examples/filters-draft.ts @@ -1,7 +1,7 @@ /** * The filter gallery written with synchronous Draft callbacks. * - * These programs correspond, in order, to filters.ts. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.if emits a query-time branch. + * These programs reproduce, in order, the existing queries in `filters-originals.ts`. Each schema supplies the callback's second argument, and $.let introduces a named HashQL binding. Native loops and functions run during construction. $.if emits a query-time branch. * * The shared declarations cover only the graph exports used here. Construction emits J-Expr without executing against a graph service. * @@ -177,7 +177,7 @@ type Query<I> = Result.Result< ProgramError.Construction >; -/** The same selections as the Do gallery, retaining each Draft schema in its result type. */ +/** The gallery's programs, in the order of `filters-originals.ts`, retaining each Draft schema in its result type. */ export const examples: readonly [ allEntities: Query<Inputs.Empty>, entityByUuid: Query<Inputs.Empty>, diff --git a/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts new file mode 100644 index 00000000000..34603fed0b1 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/examples/filters-originals.ts @@ -0,0 +1,100 @@ +/** + * The existing queries that the Draft filter gallery reproduces, in the gallery's order. + * + * A J-Expr original comes from a HashQL compiler test, and the gallery's program must match it up to spelling. A frontend original is the selection predicate of a frontend request. It has no J-Expr form, so a snapshot pins the gallery's translation instead. Source paths are relative to the repository root. + * + * @module + */ + +/** One existing query and where it comes from. */ +export interface Original { + readonly title: string; + readonly source: string; + readonly before: string; +} + +export const originals: readonly Original[] = [ + { + title: "1. Start a graph query", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc", + before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`, + }, + { + title: "2. Filter by UUID, then collect", + source: + "libs/@local/hashql/hir/tests/ui/lower/checking/collect-filter-graph.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + { + title: "3. Supply the temporal axes as a query input", + source: "libs/@local/hashql/mir/tests/ui/reify/graph-read.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["input", "axis", "_"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["==", "vertex.metadata.record_id.entity_id.entity_uuid", + ["::graph::types::knowledge::entity::EntityUuid", + ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, + }, + { + title: "4. Bind a value inside the predicate", + source: + "libs/@local/hashql/hir/tests/ui/lower/graph-hoisting/nested-boolean-expression-outer-let.jsonc", + before: `[ + "::graph::tail::collect", + ["::graph::body::filter", + ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], + ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", + ["let", "foo", {"#literal": false}, + ["&&", {"#literal": true}, ["||", {"#literal": true}, "foo"]]]]]]`, + }, + // The gallery's inputs stand in for these requests' parameters. + { + title: "5. Frontend: look up a published entity", + source: "apps/hash-frontend/src/components/hooks/use-entity-by-id.ts", + before: `// The branch where the supplied entity ID has no draft ID. +{ + filter: { all: [ + { equal: [{ path: ["webId"] }, { parameter: webId }] }, + { equal: [{ path: ["uuid"] }, { parameter: entityUuid }] } + ] }, + includeDrafts: false +}`, + }, + { + title: "6. Frontend: the sidebar's web and archive predicates", + source: + "apps/hash-frontend/src/shared/generate-sidebar-entities-query-variables.tsx", + before: `// Predicate excerpt: the separate noisy-system-type exclusion is omitted. +{ + filter: { all: [ + { notEqual: [{ path: ["archived"] }, { parameter: true }] }, + { equal: [{ path: ["webId"] }, { parameter: webId }] } + ] }, + includeDrafts: false +}`, + }, + { + title: "7. Frontend: match any supplied entity UUID", + source: "apps/hash-frontend/src/components/hooks/use-users-with-links.ts", + before: `// The ID-list predicate only; the user-type filter and avatar traversal are omitted. +{ any: userAccountIds.map((actorId) => ({ + equal: [{ path: ["uuid"] }, { parameter: actorId }] +})) }`, + }, + { + title: "8. Frontend: make draft inclusion a query-time choice", + source: "apps/hash-frontend/src/pages/shared/entity-selector.tsx", + before: `// The request flag only; the selector's later deduplication is omitted. +{ includeDrafts }`, + }, +]; diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts b/libs/@local/hashql/sdk/typescript/examples/filters.test.ts deleted file mode 100644 index f140c3df6ce..00000000000 --- a/libs/@local/hashql/sdk/typescript/examples/filters.test.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { Array, Record, Result, Schema, flow, pipe } from "effect"; -import { describe, expect, test } from "vitest"; - -import { isReadonlyArray } from "../src/internal/array.js"; -import { Expression, JExpr } from "../src/main.js"; -import { examples } from "./filters.js"; - -const aliases = new Map([ - ["::core::cmp::eq", "=="], - ["::core::bool::and", "&&"], - ["::core::bool::or", "||"], -]); - -const parseJson = flow( - Schema.decodeResult(Schema.fromJsonString(Schema.Json)), - Result.getOrThrow, -); -const parseImport = flow( - Schema.decodeUnknownResult( - Schema.Tuple([ - Schema.Literal("::kernel::special_form::use"), - Schema.String, - Schema.Union([ - Schema.Struct({ "#tuple": Schema.Array(Schema.String) }), - Schema.Struct({ - "#struct": Schema.Record(Schema.String, Schema.String), - }), - ]), - Schema.Json, - ]), - ), - Result.getOrThrow, -); - -const resolveImport = ( - value: Schema.JsonArray, - imports: ReadonlyMap<string, string>, -): { - readonly body: Schema.Json; - readonly imports: ReadonlyMap<string, string>; -} => { - const [, path, selection, body] = parseImport(value); - const imported = new Map(imports); - if ("#tuple" in selection) { - for (const name of selection["#tuple"]) { - imported.set(name, `${path}::${name}`); - } - } else { - for (const [name, alias] of Record.toEntries(selection["#struct"])) { - let binding = alias; - if (alias === "_") { - binding = name; - } - imported.set(binding, `${path}::${name}`); - } - } - return { body, imports: imported }; -}; - -// Only spelling differs: qualified exports, explicit projections and the inferred temporal type. -const normalize = ( - value: Schema.Json, - imports: ReadonlyMap<string, string> = new Map(), -): Schema.Json => { - if (typeof value === "string") { - return imports.get(value) ?? value; - } - if (isReadonlyArray<Schema.Json, Schema.Json>(value)) { - if (value[0] === "::kernel::special_form::use") { - const imported = resolveImport(value, imports); - return normalize(imported.body, imported.imports); - } - const nodes = pipe( - value, - Array.map((node) => normalize(node, imports)), - ); - const [operation, input, field] = nodes; - if (typeof operation !== "string") { - return nodes; - } - const callee = operation.replace("::kernel::special_form::", ""); - if ( - callee === "access" && - typeof input === "string" && - typeof field === "string" - ) { - return `${input}.${field}`; - } - if ( - callee === "input" && - input === "axis" && - field === "::graph::temporal::QueryTemporalAxes" - ) { - return [callee, input, "_"]; - } - return [aliases.get(callee) ?? callee, ...Array.drop(nodes, 1)]; - } - if (value !== null && typeof value === "object") { - if ("#literal" in value) { - return value; - } - return pipe( - value, - Record.map((member) => normalize(member, imports)), - ); - } - return value; -}; - -const jexprExamples = pipe( - examples, - Array.filter(({ source }) => source.endsWith(".jsonc")), -); -const frontendExamples = pipe( - examples, - Array.filter( - ({ source }) => source.endsWith(".ts") || source.endsWith(".tsx"), - ), -); - -describe("query_normalization", () => { - test("import_aliases", () => { - expect.hasAssertions(); - expect( - normalize([ - "::kernel::special_form::use", - "::example", - { "#struct": { left: "binding", right: "_" } }, - ["binding", "right", { "#literal": "binding" }], - ]), - ).toStrictEqual([ - "::example::left", - "::example::right", - { "#literal": "binding" }, - ]); - }); - - test("import_shadowing", () => { - expect.hasAssertions(); - expect( - normalize([ - "::kernel::special_form::use", - "::outer", - { "#tuple": ["value"] }, - [ - "pair", - "value", - [ - "::kernel::special_form::use", - "::inner", - { "#tuple": ["value"] }, - "value", - ], - "value", - ], - ]), - ).toStrictEqual([ - "pair", - "::outer::value", - "::inner::value", - "::outer::value", - ]); - }); - - test("literal_values", () => { - expect.hasAssertions(); - expect(normalize(["==", "field", { "#literal": false }])).not.toStrictEqual( - normalize(["==", "field", { "#literal": true }]), - ); - }); -}); - -describe("filter_examples", () => { - test.each(examples)("valid_construction: $title", (example) => { - expect.hasAssertions(); - expect(Result.isSuccess(example.root)).toBe(true); - expect(() => - JExpr.make( - pipe( - example.root, - Result.flatMap(Expression.toJExpr), - Result.getOrThrow, - ), - ), - ).not.toThrow(); - }); - - test.each(jexprExamples)("original_query: $title", (example) => { - expect.hasAssertions(); - expect( - normalize(parseJson(Result.getOrThrow(example.compile()))), - ).toStrictEqual(normalize(parseJson(example.before))); - }); - - test.each(frontendExamples)("frontend_selection: $title", (example) => { - expect.hasAssertions(); - expect(parseJson(Result.getOrThrow(example.compile()))).toMatchSnapshot(); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/examples/filters.ts b/libs/@local/hashql/sdk/typescript/examples/filters.ts deleted file mode 100644 index f8c8d037ad7..00000000000 --- a/libs/@local/hashql/sdk/typescript/examples/filters.ts +++ /dev/null @@ -1,282 +0,0 @@ -/** - * Existing queries, written with the typed HashQL DSL. - * - * Each example pairs its original syntax with a construction using Do and Let. Frontend comparisons cover selection predicates, not subgraph traversal, permissions or UI post-processing. Source paths are relative to the repository root. - * - * The declarations describe only the exports and entity fields used here. Expression helpers emit standard-library calls, and filters introduce explicitly named closure parameters. Compilation emits J-Expr without contacting the graph service. - * - * @module - */ -import { Result } from "effect"; - -import { Do as EmptyDo, Import, withPrelude } from "../src/do/index.js"; -import { Program, program } from "../src/main.js"; -import { - entity, - head, - kernel, - temporal, - temporary, - uuid, - web, -} from "./filters-declarations.js"; - -import type { Expression, Type } from "../src/main.js"; -import type * as ProgramError from "../src/Program/ProgramError.js"; - -const { Let, Do } = withPrelude({ - values: { - createUuid: uuid.values.Uuid, - createEntityUuid: entity.values.EntityUuid, - ...head.values, - now: temporary.values.decision_time_now, - }, -}); -interface Example { - readonly title: string; - readonly source: string; - readonly before: string; - readonly root: Result.Result<Expression.Any, ProgramError.Construction>; - readonly compile: () => Result.Result<string, ProgramError.Construction>; -} -const example = <T extends Type.Any, Inputs>( - details: Omit<Example, "root" | "compile">, - root: Result.Result< - Expression.Expression<T, Inputs>, - ProgramError.Construction - >, -): Example => ({ - ...details, - root, - compile: () => - root.pipe( - Result.flatMap((expression) => Program.compile(program(expression))), - ), -}); - -// Start here: the declarations above replace the generated library bindings still to come. - -const allEntities = example( - { - title: "1. Start a graph query", - source: - "libs/@local/hashql/hir/tests/ui/lower/checking/minimal-graph.jsonc", - before: `["::graph::tail::collect", ["::graph::head::entities", ["::graph::tmp::decision_time_now"]]]`, - }, - EmptyDo( - Import(() => head, ["entities"]), - Import(() => temporary, { decision_time_now: "now" }), - ($, { now }) => $.query.entities(now()).collect(), - ), -); - -const entityByUuid = example( - { - title: "2. Filter by UUID, then collect", - source: - "libs/@local/hashql/hir/tests/ui/lower/checking/collect-filter-graph.jsonc", - before: `[ - "::graph::tail::collect", - ["::graph::body::filter", - ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], - ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", - ["==", "vertex.metadata.record_id.entity_id.entity_uuid", - ["::graph::types::knowledge::entity::EntityUuid", - ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, - }, - Do(($, { now, createEntityUuid, createUuid }) => - $.query - .entities(now()) - .filter("vertex", (vertex) => - $.eq( - vertex.metadata.record_id.entity_id.entity_uuid, - createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), - ), - ) - .collect(), - ), -); - -const suppliedTimeAxis = example( - { - title: "3. Supply the temporal axes as a query input", - source: "libs/@local/hashql/mir/tests/ui/reify/graph-read.jsonc", - before: `[ - "::graph::tail::collect", - ["::graph::body::filter", - ["::graph::head::entities", ["input", "axis", "_"]], - ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", - ["==", "vertex.metadata.record_id.entity_id.entity_uuid", - ["::graph::types::knowledge::entity::EntityUuid", - ["::core::uuid::Uuid", {"#literal": "e2851dbb-7376-4959-9bca-f72cafc4448f"}]]]]]]`, - }, - Do(($, { createEntityUuid, createUuid }) => - $.query - .entities($.input("axis", temporal.types.QueryTemporalAxes)) - .filter("vertex", (vertex) => - $.eq( - vertex.metadata.record_id.entity_id.entity_uuid, - createEntityUuid(createUuid("e2851dbb-7376-4959-9bca-f72cafc4448f")), - ), - ) - .collect(), - ), -); - -const predicateLocalBinding = example( - { - title: "4. Bind a value inside the predicate", - source: - "libs/@local/hashql/hir/tests/ui/lower/graph-hoisting/nested-boolean-expression-outer-let.jsonc", - before: `[ - "::graph::tail::collect", - ["::graph::body::filter", - ["::graph::head::entities", ["::graph::tmp::decision_time_now"]], - ["fn", {"#tuple": []}, {"#struct": {"vertex": "_"}}, "_", - ["let", "foo", {"#literal": false}, - ["&&", {"#literal": true}, ["||", {"#literal": true}, "foo"]]]]]]`, - }, - Do(($, { now }) => - $.query - .entities(now()) - .filter("vertex", () => - $.Let("foo", ($) => $.literal(false)).Expr(($, { foo }) => - $.and(true, $.or(true, foo)), - ), - ) - .collect(), - ), -); - -// Frontend examples translate selection only. Inputs stand in for the original request parameters. - -const publishedEntityById = example( - { - title: "5. Frontend: look up a published entity", - source: "apps/hash-frontend/src/components/hooks/use-entity-by-id.ts", - before: `// The branch where the supplied entity ID has no draft ID. -{ - filter: { all: [ - { equal: [{ path: ["webId"] }, { parameter: webId }] }, - { equal: [{ path: ["uuid"] }, { parameter: entityUuid }] } - ] }, - includeDrafts: false -}`, - }, - Do( - Let("webId", ($) => $.input("web_id", web.types.WebId)), - Let("entityUuid", ($) => $.input("entity_uuid", entity.types.EntityUuid)), - ($, { now, webId, entityUuid }) => - $.query - .entities(now()) - .filter("vertex", (vertex) => { - const id = vertex.metadata.record_id.entity_id; - - return $.eq(id.web_id, webId) - .and($.eq(id.entity_uuid, entityUuid)) - .and($.isNone(id.draft_id)); - }) - .collect(), - ), -); - -const sidebarSelection = example( - { - title: "6. Frontend: the sidebar's web and archive predicates", - source: - "apps/hash-frontend/src/shared/generate-sidebar-entities-query-variables.tsx", - before: `// Predicate excerpt: the separate noisy-system-type exclusion is omitted. -{ - filter: { all: [ - { notEqual: [{ path: ["archived"] }, { parameter: true }] }, - { equal: [{ path: ["webId"] }, { parameter: webId }] } - ] }, - includeDrafts: false -}`, - }, - Do( - Let("webId", ($) => $.input("web_id", web.types.WebId)), - ($, { now, webId }) => - $.query - .entities(now()) - .filter("vertex", (vertex) => - $.eq(vertex.metadata.record_id.entity_id.web_id, webId), - ) - .filter("vertex", (vertex) => - $.isFalse(vertex.metadata.archived) // - .and($.isNone(vertex.metadata.record_id.entity_id.draft_id)), - ) - .collect(), - ), -); - -const selectedIds = [ - "e2851dbb-7376-4959-9bca-f72cafc4448f", - "926b2d9b-c099-4cc4-9b0b-906b0c27bc70", -] as const; -const anyOfEntityIds = example( - { - title: "7. Frontend: match any supplied entity UUID", - source: "apps/hash-frontend/src/components/hooks/use-users-with-links.ts", - before: `// The ID-list predicate only; the user-type filter and avatar traversal are omitted. -{ any: userAccountIds.map((actorId) => ({ - equal: [{ path: ["uuid"] }, { parameter: actorId }] -})) }`, - }, - Do(($, { now, createEntityUuid, createUuid }) => - $.query - .entities(now()) - .filter("vertex", (vertex) => { - let matches = $.literal(false); - for (const entityUuid of selectedIds) { - matches = $.or( - matches, - $.eq( - vertex.metadata.record_id.entity_id.entity_uuid, - createEntityUuid(createUuid($.literal(entityUuid))), - ), - ); - } - - return matches; - }) - .collect(), - ), -); - -const optionalDrafts = example( - { - title: "8. Frontend: make draft inclusion a query-time choice", - source: "apps/hash-frontend/src/pages/shared/entity-selector.tsx", - before: `// The request flag only; the selector's later deduplication is omitted. -{ includeDrafts }`, - }, - Do( - Let("includeDrafts", ($) => - $.input("include_drafts", kernel.types.Boolean, $.literal(false)), - ), - ($, { now, includeDrafts }) => - $.query - .entities(now()) - .filter("vertex", (vertex) => - $.if( - includeDrafts, - () => true, - () => $.isNone(vertex.metadata.record_id.entity_id.draft_id), - ), - ) - .collect(), - ), -); - -/** Before/after examples whose compile methods return the emitted J-Expr. */ -export const examples: readonly Example[] = [ - allEntities, - entityByUuid, - suppliedTimeAxis, - predicateLocalBinding, - publishedEntityById, - sidebarSelection, - anyOfEntityIds, - optionalDrafts, -]; diff --git a/libs/@local/hashql/sdk/typescript/package.json b/libs/@local/hashql/sdk/typescript/package.json index 463669fcd72..2bc9e437bb6 100644 --- a/libs/@local/hashql/sdk/typescript/package.json +++ b/libs/@local/hashql/sdk/typescript/package.json @@ -16,10 +16,6 @@ "./draft": { "types": "./dist/draft/index.d.ts", "default": "./dist/draft/index.js" - }, - "./do": { - "types": "./dist/do/index.d.ts", - "default": "./dist/do/index.js" } }, "scripts": { @@ -30,9 +26,7 @@ "test:unit": "vitest run --typecheck" }, "dependencies": { - "effect": "4.0.3", - "esrap": "2.4.0", - "oxc-parser": "0.152.0" + "effect": "4.0.3" }, "devDependencies": { "@local/oxlint": "workspace:*", diff --git a/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts b/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts index 470aa6dce31..e3144de4ae2 100644 --- a/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts +++ b/libs/@local/hashql/sdk/typescript/src/JExpr/Path.ts @@ -123,7 +123,7 @@ export const compile = (path: Path): string => { * import { Result } from "effect"; * * const add = Result.getOrThrow(JExpr.Path.decodeResult("::core :: math::+")); - * assert.ok(JExpr.Path.isAbsolute(add)); + * assert.ok(add.rooted); * assert.equal(JExpr.Path.compile(add), "::core::math::`+`"); * assert.ok(Result.isFailure(JExpr.Path.decodeResult("List<Integer>"))); * ``` @@ -133,9 +133,3 @@ export const decodeResult: ( input: string, options?: ParseOptions, ) => Result<Path, SchemaIssue.Issue> = SchemaParser.decodeResult(Schema); - -/** Whether the path starts with `::`. */ -export const isAbsolute = (path: Path): boolean => path.rooted; - -/** Whether the path has no leading `::`. */ -export const isRelative = (path: Path): boolean => !path.rooted; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts index 375ceab836e..a1f12ece31e 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Expression.test.ts @@ -119,6 +119,17 @@ describe("expression", () => { ); }); + test("reserved_projection", () => { + expect.hasAssertions(); + const record = Expression.fromJExpr< + Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, + Inputs.Empty + >("record"); + expect(compile(record.$project("$"))).toBe( + '["::kernel::special_form::access","record","$"]', + ); + }); + test("callable_properties", () => { expect.hasAssertions(); const record = Expression.fromJExpr< diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts index 39b561ac945..c000b02e686 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test-d.ts @@ -1,7 +1,6 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Do as EmptyDo, Let, withPrelude } from "../do/index.js"; import { Expression, Module, Program } from "../main.js"; import * as Operators from "./Operators.js"; @@ -20,12 +19,6 @@ const integer = kernel.types.Integer; const boolean = kernel.types.Boolean; const string = kernel.types.String; -type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; -type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> ->; - interface Same extends Type.FunctionSignature { readonly type: this["Target"] extends readonly [infer T extends Type.Any] ? Type.Function<readonly [T], T> @@ -152,17 +145,6 @@ describe("input_requirements", () => { const hidden: Expression.Expression<Type.PrimitiveInteger, Inputs.Empty> = combined; expectTypeOf(hidden); - // Do's contextual callback requires a common record for this ambiguous host union. - const block = EmptyDo< - Type.PrimitiveInteger, - { readonly first: Type.PrimitiveInteger } - >(() => possiblyClosed); - // @ts-expect-error a block also keeps the required alternative - const hiddenBlock: Expression.Expression< - Type.PrimitiveInteger, - Inputs.Empty - > = Result.getOrThrow(block); - expectTypeOf(hiddenBlock); }); test("required_and_default", () => { @@ -306,12 +288,12 @@ describe("snippet_requirements", () => { test("reusable_snippet", () => { const count = Expression.input("count", integer); const snippet = Operators.ne(count, Expression.integer(0)); - const first = Result.getOrThrow(EmptyDo(() => snippet)); - const second = Result.getOrThrow( - EmptyDo(($) => Operators.and(snippet, $.input("enabled", boolean))), + const combined = Operators.and( + snippet, + Expression.input("enabled", boolean), ); - const program = Program.program(second); - expectTypeOf<Expression.Inputs<typeof first>>().toEqualTypeOf<{ + const program = Program.program(combined); + expectTypeOf<Expression.Inputs<typeof snippet>>().toEqualTypeOf<{ readonly count: Type.PrimitiveInteger; }>(); expectTypeOf<Program.Inputs<typeof program>>().toEqualTypeOf<{ @@ -319,115 +301,9 @@ describe("snippet_requirements", () => { readonly enabled: Type.PrimitiveBoolean; }>(); }); - - test("discarded_expression", () => { - const expression = Result.getOrThrow( - EmptyDo(($) => { - $.input("unused", integer); - return $.integer(1); - }), - ); - expectTypeOf(expression).toEqualTypeOf< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty> - >(); - }); - - test("unused_and_shadowed_declarations", () => { - const expression = Result.getOrThrow( - EmptyDo( - Let("value", ($) => $.input("first", integer)), - Let("value", ($) => $.input("second", integer)), - ($) => $.integer(1), - ), - ); - expectTypeOf<Expression.Inputs<typeof expression>>().toEqualTypeOf<{ - readonly first: Type.PrimitiveInteger; - readonly second: Type.PrimitiveInteger; - }>(); - }); - - test("nested_branches", () => { - const expression = Result.getOrThrow( - EmptyDo(($) => - $.if( - $.input("condition", boolean), - () => - $.Let("ignored", ($) => $.input("left", integer)).Expr(($) => - $.integer(1), - ), - () => $.input("right", integer), - ), - ), - ); - expectTypeOf<Expression.Inputs<typeof expression>>().toEqualTypeOf<{ - readonly condition: Type.PrimitiveBoolean; - readonly left: Type.PrimitiveInteger; - readonly right: Type.PrimitiveInteger; - }>(); - }); }); describe("builder_requirements", () => { - test("query_dependencies", () => { - const { Do } = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [Type.PrimitiveInteger], Graph>, - Inputs.Empty - >("entities"), - }, - }); - const expression = Result.getOrThrow( - Do(($) => - $.query - .entities($.input("at", integer)) - .filter("vertex", (vertex) => - Operators.eq(vertex.enabled, $.input("enabled", boolean)), - ) - .collect(), - ), - ); - expectTypeOf<Expression.Inputs<typeof expression>>().toEqualTypeOf<{ - readonly at: Type.PrimitiveInteger; - readonly enabled: Type.PrimitiveBoolean; - }>(); - }); - - test("declaration_preservation", () => { - const { Do, Type: Alias, Import } = withPrelude({ modules: { kernel } }); - const expression = Result.getOrThrow( - Do( - Import((_, { kernel }) => kernel), - Let("first", ($, _, { Integer: integerType }) => - $.input("first", integerType), - ), - Alias("Count", (_, { Integer: integerType }) => integerType), - Let("second", ($, _, { Count: countType }) => - $.input("second", countType), - ), - Let("third", ($) => $.input("third", integer)), - Let("fourth", ($) => $.input("fourth", integer)), - Let("fifth", ($) => $.input("fifth", integer)), - Let("sixth", ($) => $.input("sixth", integer)), - ($) => $.integer(1), - ), - ); - expectTypeOf<keyof Expression.Inputs<typeof expression>>().toEqualTypeOf< - "first" | "second" | "third" | "fourth" | "fifth" | "sixth" - >(); - const nested = Result.getOrThrow( - Do(($) => - $.Let("value", ($) => $.input("kept", integer)) - .Import((_, { kernel }) => kernel) - .Type("Count", (_, { Integer: integerType }) => integerType) - .Expr(($) => $.integer(1)), - ), - ); - expectTypeOf<Expression.Inputs<typeof nested>>().toEqualTypeOf<{ - readonly kept: Type.PrimitiveInteger; - }>(); - }); - test("assumption_preservation", () => { const source = Expression.input("source", integer); const assumed = Expression.assume<Type.PrimitiveString>()(source); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts index b6dd4edae97..71405039d9b 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Inputs.test.ts @@ -1,7 +1,6 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Do as EmptyDo, Let } from "../do/index.js"; import { Expression, JExpr, Module } from "../main.js"; import * as Operators from "./Operators.js"; @@ -20,41 +19,16 @@ describe("input_composition", () => { test("snippet_reuse", () => { expect.hasAssertions(); const snippet = Expression.input("count", integer, Expression.integer(7)); - const first = Result.getOrThrow(EmptyDo(() => snippet)); - const second = Result.getOrThrow( - EmptyDo(($) => Operators.eq(snippet, $.input("other", integer))), + const comparison = Operators.eq( + snippet, + Expression.input("other", integer), ); - expect(compile(first)).toBe( + expect(compile(snippet)).toBe( '["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}]', ); - expect(compile(second)).toBe( + expect(compile(comparison)).toBe( '["::core::cmp::eq",["::kernel::special_form::input","count","::kernel::type::Integer",{"#literal":7}],["::kernel::special_form::input","other","::kernel::type::Integer"]]', ); - expect(compile(snippet)).toBe(compile(first)); - }); - - test("discarded_input", () => { - expect.hasAssertions(); - const expression = Result.getOrThrow( - EmptyDo(($) => { - $.input("discarded", integer); - return $.integer(1); - }), - ); - expect(compile(expression)).toBe('{"#literal":1}'); - }); - - test("unused_initializer", () => { - expect.hasAssertions(); - const expression = Result.getOrThrow( - EmptyDo( - Let("unused", ($) => $.input("retained", integer)), - ($) => $.integer(1), - ), - ); - expect(compile(expression)).toBe( - '["::kernel::special_form::let","unused",["::kernel::special_form::input","retained","::kernel::type::Integer"],{"#literal":1}]', - ); }); test("assumption_syntax", () => { diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts index 25b1e00e914..690d68cafe0 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.test.ts @@ -6,7 +6,6 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Type as Alias, Do as EmptyDo, Newtype } from "../do/index.js"; import * as JExpr from "../JExpr/index.js"; import * as TypeSyntax from "../JExpr/Type/index.js"; import * as Expression from "./Expression.js"; @@ -392,32 +391,6 @@ describe("module_construction", () => { }); describe("type_application", () => { - test("declaration_failure", () => { - expect.hasAssertions(); - // @ts-expect-error The runtime call omits the required type argument. - const invalid = prelude.List(); - const identity: unique symbol = Symbol("Invalid"); - let called = false; - const body = (): Expression.Expression< - Type.PrimitiveInteger, - Inputs.Empty - > => { - called = true; - return Expression.integer(1); - }; - const alias = EmptyDo( - Alias("Alias", () => invalid), - body, - ); - const nominal = EmptyDo( - Newtype("Nominal", identity, () => invalid), - body, - ); - expect(alias).toStrictEqual(TypeExpression.toType(invalid)); - expect(nominal).toStrictEqual(TypeExpression.toType(invalid)); - expect(called).toBe(false); - }); - test("runtime_type_arity", () => { expect.hasAssertions(); // @ts-expect-error The runtime call omits the required type argument. diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Module.ts b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts index 011c186f8da..04bbfd5fae1 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Module.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Module.ts @@ -480,7 +480,7 @@ export const relocate: { /** * Assembles already-bound modules without rebasing their references. * - * The result is a frozen `{ modules }` record keyed by the supplied names. It is not a module: it has no path, and {@link isModule} rejects it. Each child keeps its identity and its own path. The record fits any parameter that takes a scope definition, such as a Do or Draft prelude. Names follow the rules and failures of the module table of {@link define}. + * The result is a frozen `{ modules }` record keyed by the supplied names. It is not a module: it has no path, and {@link isModule} rejects it. Each child keeps its identity and its own path. The record fits any parameter that takes a scope definition, such as a Draft prelude. Names follow the rules and failures of the module table of {@link define}. */ export const root = <const M extends Namespace<Any>>( modules: M, diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts index d47b9d8b4bf..90f448c8a23 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Namespace.ts @@ -3,7 +3,7 @@ * * A flattened name can be a value, a type constructor and a module at once. Type metadata wins property collisions, followed by module exports and then value projections. Explicit projection and indexing remain available through `$project` and `$index`. Rebinding a joined name moves every capability, rather than following property-lookup precedence. * - * Draft's `$.prelude()`, `$.modules()` and `$.import(...)` return these flattened views, while the Do API keeps the value and type tables apart. A name that only optional entries supply is optional, and a module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. + * Draft's `$.prelude()`, `$.modules()` and `$.import(...)` return these flattened views. A name that only optional entries supply is optional, and a module also exposes its child exports directly, beside its own `modules`, `types` and `values` tables. * * @module */ diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts index f770aea1f8a..af141f0fa87 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Operators.ts @@ -222,15 +222,3 @@ export interface Operations { readonly isFalse: typeof isFalse; readonly isNone: typeof isNone; } - -/** The operator functions collected for composition into authoring contexts. */ -export const operations: Operations = { - eq, - ne, - and, - or, - not, - isTrue, - isFalse, - isNone, -}; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts index d4a039a4e65..e93730e3ef6 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Prelude.ts @@ -3,7 +3,7 @@ * * Export types derive from the bound declarations, without a second list of semantic annotations. Generated declarations can supply the same module, type and value tables to Draft.withPrelude. This default includes primitive types, List, Dict, UUID identities, equality and addition. It is not a complete standard-library binding. * - * Draft's `program` constructs with {@link builtin}. The default `Do` of the Do API starts with an empty scope, and `withPrelude(Prelude.builtin)` from that API supplies these names. This module also re-exports the semantic types of the declarations, such as `Prelude.Uuid` and the `Prelude.Arithmetic` signature. + * Draft's `program` constructs with {@link builtin}. This module also re-exports the semantic types of the declarations, such as `Prelude.Uuid` and the `Prelude.Arithmetic` signature. * * @module */ @@ -141,7 +141,7 @@ export type Builtin = Scope.From<{ * * `List` and `Dict` accept structural shorthand as well as type expressions, so `List(String)` and `List(Prelude.builtin.types.String)` emit the same type. `eq` accepts operands of any two types, which need not match. `add` accepts Integer and Number operands, as `Prelude.Arithmetic` describes. The SDK takes these signatures on trust, and the HashQL compiler checks the emitted calls. * - * Draft's `program` constructs with these declarations, while the default `Do` of the Do API starts with none. Draft's `$.prelude()` joins the three tables into one object. There `Uuid` is both the type and its constructor, and the module `cmp` exposes `eq` directly. + * Draft's `program` constructs with these declarations, and its `$.prelude()` joins the three tables into one object. There `Uuid` is both the type and its constructor, and the module `cmp` exposes `eq` directly. * * @example <caption>Use built-in types and functions outside a program callback.</caption> * ```ts diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts index c39d4b69c39..5261a5fcc26 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test-d.ts @@ -1,7 +1,6 @@ import { Result } from "effect"; import { describe, expectTypeOf, test } from "vitest"; -import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression, Module } from "../main.js"; import * as Operators from "./Operators.js"; @@ -169,66 +168,24 @@ describe("primitive_requirements", () => { test("conditional_branches", () => { const count = Expression.input("count", kernel.types.Integer); - const expression = Result.getOrThrow( - EmptyDo(($) => - $.if( - true, - () => count, - () => 0n, - ), - ), - ); + const expression = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: count, + else: 0n, + }); expectTypeOf(expression).toEqualTypeOf< Expression.Expression< Type.PrimitiveInteger, { readonly count: Type.PrimitiveInteger } > >(); - const numeric = Result.getOrThrow( - EmptyDo(($) => - $.if( - true, - () => 1, - () => 2, - ), - ), - ); + const numeric = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: 1, + else: 2, + }); expectTypeOf(numeric).toEqualTypeOf< Expression.Expression<Type.PrimitiveNumber, Inputs.Empty> >(); }); - - test("query_arguments_and_predicate", () => { - type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; - type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> - >; - const { Do } = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [Type.PrimitiveNumber], Graph>, - Inputs.Empty - >("entities"), - }, - }); - const expression = Result.getOrThrow( - Do(($) => - $.query - .entities(1) - .filter("vertex", () => true) - .collect(), - ), - ); - expectTypeOf(expression).toEqualTypeOf< - Expression.Expression<Type.List<Vertex>, Inputs.Empty> - >(); - Do(($) => { - // @ts-expect-error Query arguments use the declaration's exact numeric descriptor. - $.query.entities(1n); - // @ts-expect-error A predicate does not accept numeric truthiness. - $.query.entities(1).filter("vertex", () => 1); - return $.literal(true); - }); - }); }); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts index 2e32951b035..035c12edf21 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Primitive.test.ts @@ -1,7 +1,6 @@ import { Result } from "effect"; import { describe, expect, test } from "vitest"; -import { Do as EmptyDo, withPrelude } from "../do/index.js"; import { Expression, JExpr, Module } from "../main.js"; import * as Operators from "./Operators.js"; @@ -79,14 +78,14 @@ describe("primitive_failures", () => { test("both_branches", () => { expect.hasAssertions(); - const result = EmptyDo(($) => - $.if( - true, - () => 1, - () => Number.NaN, - ), + const conditional = Expression.ifElse(true, { + // oxlint-disable-next-line unicorn/no-thenable -- this property holds a conditional branch + then: 1, + else: Number.NaN, + }); + const failure = Result.getOrThrow( + Result.flip(Expression.toJExpr(conditional)), ); - const failure = Result.getOrThrow(Result.flip(result)); expect(failure.reason._tag).toBe("InvalidExpression"); }); @@ -101,33 +100,3 @@ describe("primitive_failures", () => { ); }); }); - -describe("primitive_query", () => { - test("arguments_and_predicate", () => { - expect.hasAssertions(); - type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; - type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> - >; - const { Do } = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [Type.PrimitiveNumber], Graph>, - Inputs.Empty - >("entities"), - }, - }); - const expression = Result.getOrThrow( - Do(($) => - $.query - .entities(1) - .filter("vertex", () => true) - .collect(), - ), - ); - expect(compile(expression)).toBe( - '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",{"#literal":true}]]]', - ); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts b/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts index 08f394aac75..9c959ed6018 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/ProgramError.ts @@ -53,12 +53,6 @@ export type Reason = }> /** A generic type constructor lacks its type arguments. */ | { readonly _tag: "UnspecializedTypeConstructor" } - /** A Do block has no terminal expression callback. */ - | { readonly _tag: "MissingBlockBody" } - /** A Do expression callback occupies a position before the last step. */ - | { readonly _tag: "MisplacedBlockBody" } - /** A Do declaration position contains something other than a supported declaration step. */ - | { readonly _tag: "InvalidBlockStep" } /** An authoring body returned something other than an expression handle. */ | { readonly _tag: "InvalidBodyResult" }; @@ -133,21 +127,6 @@ export class Construction extends ConstructionBase<{ return new Construction({ reason: Reason.UnspecializedTypeConstructor() }); } - /** Reports a Do block without a terminal expression callback. */ - static missingBlockBody(): Construction { - return new Construction({ reason: Reason.MissingBlockBody() }); - } - - /** Reports a Do body callback occurring before the last step. */ - static misplacedBlockBody(): Construction { - return new Construction({ reason: Reason.MisplacedBlockBody() }); - } - - /** Reports an unsupported value in a Do declaration position. */ - static invalidBlockStep(): Construction { - return new Construction({ reason: Reason.InvalidBlockStep() }); - } - /** Reports a body result that is not an expression handle. */ static invalidBodyResult(): Construction { return new Construction({ reason: Reason.InvalidBodyResult() }); @@ -188,11 +167,6 @@ export class Construction extends ConstructionBase<{ `Unsupported primitive type constructor: ${JSON.stringify(name)}`, UnspecializedTypeConstructor: () => "A generic type must be specialized before use", - MissingBlockBody: () => "A Do block must end with an expression callback", - MisplacedBlockBody: () => - "Only the last step may be an expression callback", - InvalidBlockStep: () => - "A Do block expects declaration steps before its expression callback", InvalidBodyResult: () => "An expression callback must return a HashQL expression", }); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts deleted file mode 100644 index e63eb6c5bc6..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/Program/Query.test-d.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { describe, expectTypeOf, test } from "vitest"; - -import { Do as EmptyDo, withPrelude } from "../do/index.js"; -import { Expression } from "../main.js"; -import * as Operators from "./Operators.js"; - -import type { Type } from "../main.js"; -import type * as Inputs from "./Inputs.js"; -import type * as ProgramError from "./ProgramError.js"; -import type { Result } from "effect"; - -type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; -type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> ->; - -describe("query_types", () => { - test("graph_vertex", () => { - const { Do } = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [], Graph>, - Inputs.Empty - >("entities"), - }, - }); - const result = Do(($) => - $.query - .entities() - .filter("item", (item) => { - expectTypeOf(item).toEqualTypeOf< - Expression.Expression<Vertex, Inputs.Empty> - >(); - return Operators.isFalse(item.enabled); - }) - .collect(), - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression<Type.List<Vertex>, Inputs.Empty>, - ProgramError.Construction - > - >(); - Do(($) => { - // @ts-expect-error A predicate must return a Boolean. - $.query.entities().filter("item", (item) => item); - // @ts-expect-error Query construction has no compatibility adapter. - expectTypeOf($.query.from); - return $.literal(true); - }); - }); - - test("operation_domains", () => { - EmptyDo(($) => { - const integer = $.integer(1); - expectTypeOf(integer).toEqualTypeOf< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty> - >(); - expectTypeOf(integer).not.toHaveProperty("$"); - expectTypeOf(integer).not.toHaveProperty("collect"); - // @ts-expect-error An integer is not optional. - Operators.isNone(integer); - // @ts-expect-error A Boolean conjunction needs a Boolean operand. - Operators.and($.literal(true), integer); - return Operators.eq(integer, $.integer(2)); - }); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts deleted file mode 100644 index c7d900c3807..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/Program/Query.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -import { Result } from "effect"; -import { describe, expect, test } from "vitest"; - -import { Do as EmptyDo, withPrelude } from "../do/index.js"; -import { Expression } from "../main.js"; -import * as Operators from "./Operators.js"; - -import type { Inputs, Type } from "../main.js"; - -type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; -type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> ->; -const { Do } = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [], Graph>, - Inputs.Empty - >("entities"), - }, -}); - -describe("query", () => { - test("named_filter", () => { - expect.hasAssertions(); - let calls = 0; - const result = Do(($) => - $.query - .entities() - .filter("item", (item) => { - calls += 1; - return Operators.isFalse(item.enabled); - }) - .collect(), - ); - const syntax = Result.getOrThrow( - Result.flatMap(result, Expression.toJExpr), - ); - expect(syntax).toStrictEqual([ - "::graph::tail::collect", - [ - "::graph::body::filter", - ["entities"], - [ - "fn", - { "#tuple": [] }, - { "#struct": { item: "_" } }, - "_", - [ - "::core::cmp::eq", - ["::kernel::special_form::access", "item", "enabled"], - { "#literal": false }, - ], - ], - ], - ]); - expect(calls).toBe(1); - }); - - test("invalid_parameter", () => { - expect.hasAssertions(); - let called = false; - const result = Do(($) => - $.query.entities().filter("bad name", () => { - called = true; - return $.literal(true); - }), - ); - expect(Result.isFailure(result)).toBe(true); - expect(called).toBe(false); - }); - - test("predicate_failure", () => { - expect.hasAssertions(); - const result = Do(($) => - $.query - .entities() - .filter("item", () => - $.Let("bad name", ($) => $.literal(true)).Expr( - (_, values) => values["bad name"], - ), - ) - .collect(), - ); - expect(Result.isFailure(result)).toBe(true); - }); - - test("reserved_projection", () => { - expect.hasAssertions(); - const record = Expression.fromJExpr< - Type.Struct<{ readonly $: Type.PrimitiveBoolean }>, - Inputs.Empty - >("record"); - const result = EmptyDo(() => Operators.isTrue(record.$project("$"))); - expect( - Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)), - ).toStrictEqual([ - "::core::cmp::eq", - ["::kernel::special_form::access", "record", "$"], - { "#literal": true }, - ]); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Query.ts b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts index 3111a9fd6f9..e530e4670fd 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Query.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Query.ts @@ -1,19 +1,12 @@ /** - * Query operations derived from a declared graph-producing function. + * The graph-producing function that query construction recognizes. * - * Authoring contexts expose `query.entities` when their value declarations contain an `entities` function returning the recognized graph descriptor. The graph marker carries the vertex type through filtering and collection. These operations construct query syntax without contacting a graph service. + * Draft exposes `$.query.entities` when its prelude's values contain an `entities` function returning the recognized graph descriptor. The graph marker carries the vertex type through filtering and collection. * * @module */ -import { Cause, Result, pipe } from "effect"; - -import * as JExpr from "../JExpr/index.js"; -import * as AST from "./AST/index.js"; -import * as Expression from "./Expression.js"; -import * as ProgramError from "./ProgramError.js"; - import type * as Type from "../Type/index.js"; -import type { ArgumentInputs, Arguments } from "./ExpressionType.js"; +import type * as Expression from "./Expression.js"; import type * as Inputs from "./Inputs.js"; import type * as Scope from "./Scope.js"; @@ -22,70 +15,6 @@ type Graph<Vertex extends Type.Any> = Type.Opaque< Type.Struct<{ readonly "'marker": Vertex }> >; -/** - * A graph expression with filtering and collection operations that retain its vertex descriptor. - * - * Binding gives an ordinary expression without query methods. Complete filtering and collection before binding the result. The vertex descriptor comes from the declared `entities` function, not from inspecting stored graph data. - * - * @example <caption>Build a filtered collection with a declared graph function.</caption> - * ```ts - * import assert from "node:assert/strict"; - * import { Expression } from "@local/hashql"; - * import type { Inputs, Type } from "@local/hashql"; - * import { withPrelude } from "@local/hashql/do"; - * import { Result } from "effect"; - * - * type Vertex = Type.Struct<{ readonly active: Type.PrimitiveBoolean }>; - * type Graph = Type.Opaque< - * "::graph::Graph", - * Type.Struct<{ readonly "'marker": Vertex }> - * >; - * const { Do } = withPrelude({ values: { - * entities: Expression.fromJExpr<Type.Function<readonly [], Graph>, Inputs.Empty>("entities"), - * } }); - * let calls = 0; - * const result = Do(($) => $.query.entities().filter("item", (item) => { - * calls += 1; - * return item.active; - * }).collect()); - * const syntax = Result.getOrThrow(Result.flatMap(result, Expression.toJExpr)); - * assert.equal(calls, 1); - * assert.ok(Array.isArray(syntax)); - * assert.equal(syntax[0], "::graph::tail::collect"); - * ``` - */ -export type Query< - T extends Type.Any, - Vertex extends Type.Any, - Requirements, -> = Expression.Expression<T, Requirements> & { - /** - * Adds a named predicate callback, invoked once during successful construction rather than once per stored vertex. - * - * An invalid graph expression or parameter name skips the callback. A synchronous callback exception becomes a `CallbackException` construction failure. Captured expressions contribute their input requirements. The name identifies the emitted HashQL function's parameter. The compiler owns lexical resolution. - */ - readonly filter: < - const Predicate extends Expression.Value<Type.PrimitiveBoolean>, - >( - name: string, - predicate: ( - vertex: Expression.Expression<Vertex, Inputs.Empty>, - ) => Predicate, - ) => Query< - T, - Vertex, - Inputs.Merge<Requirements, Expression.Inputs<Predicate>> - >; - /** Constructs collection into a list of vertices, retaining query inputs and construction failures without executing it. */ - readonly collect: () => Expression.Expression< - Type.List<Vertex>, - Requirements - >; -}; - -// oxlint-disable-next-line typescript/no-generated-empty-object-type -- a scope without an entities declaration has no query entry point -type Empty = Record<never, never>; - /** Reads the declared `entities` function's arguments, result, requirements and graph vertex, or resolves to `never` when its descriptor does not match. */ export type EntityFunction<S extends Scope.Scope> = S["values"] extends { readonly entities: infer E extends Expression.Any; @@ -101,137 +30,3 @@ export type EntityFunction<S extends Scope.Scope> = S["values"] extends { : never : never : never; - -type Entities<S extends Scope.Scope> = < - const A extends readonly Expression.AnyValue[] & - Arguments<EntityFunction<S>["args"]>, ->( - ...args: A -) => Query< - EntityFunction<S>["returns"], - EntityFunction<S>["vertex"], - Inputs.Merge<EntityFunction<S>["inputs"], ArgumentInputs<A>> ->; - -/** Query entry points available from a scope's declared graph function, or an empty type for an absent or incompatible declaration. */ -export type Context<S extends Scope.Scope> = [EntityFunction<S>] extends [never] - ? Empty - : { readonly entities: Entities<S> }; - -const chain = <T extends Type.Any, Vertex extends Type.Any, Requirements>( - expression: Expression.Expression<T, Requirements>, -): Query<T, Vertex, Requirements> => { - const methods = { - filter: <const Predicate extends Expression.Value<Type.PrimitiveBoolean>>( - name: string, - predicate: ( - vertex: Expression.Expression<Vertex, Inputs.Empty>, - ) => Predicate, - ): Query< - T, - Vertex, - Inputs.Merge<Requirements, Expression.Inputs<Predicate>> - > => - chain( - Result.gen(function* () { - const graph = yield* Expression.toJExpr(expression); - const ident = yield* JExpr.Ident.decodeResult(name).pipe( - Result.mapError( - (cause) => - new ProgramError.Construction({ - reason: ProgramError.Reason.InvalidParameterName({ - name, - cause, - }), - }), - ), - ); - - const parameter = JExpr.Ident.compile(ident); - const condition = yield* Result.try({ - try: () => predicate(Expression.fromJExpr(parameter)), - catch: (error) => - ProgramError.Construction.callbackException( - new Cause.UnknownError(error), - ), - }); - const body = yield* Expression.toJExpr(condition); - - return new AST.Expr( - JExpr.call( - "::graph::body::filter", - graph, - JExpr.fn({ params: { [parameter]: JExpr.infer }, body }), - ), - ); - }).pipe( - Expression.fromResult< - T, - Inputs.Merge<Requirements, Expression.Inputs<Predicate>> - >, - ), - ), - collect: (): Expression.Expression<Type.List<Vertex>, Requirements> => - Expression.fromResult( - Expression.toJExpr(expression).pipe( - Result.map( - (graph) => - new AST.Expr(JExpr.call("::graph::tail::collect", graph)), - ), - ), - ), - }; - - const proxy = new Proxy(expression, { - // oxlint-disable-next-line typescript/no-restricted-types -- a proxy can return expression members or query methods - get(target, property, receiver): unknown { - if (property === "filter") { - return methods.filter; - } - if (property === "collect") { - return methods.collect; - } - return Reflect.get(target, property, receiver); - }, - }); - - // SAFETY: the proxy preserves the expression's identity and supplies both query methods. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Proxy cannot express added members in its return type - return proxy as Query<T, Vertex, Requirements>; -}; - -export const make = <S extends Scope.Scope>(scope: S): Context<S> => { - const declaration = scope.values["entities"]; - if (declaration === undefined) { - return {}; - } - - const entities: Entities<S> = < - const A extends readonly Expression.AnyValue[] & - Arguments<EntityFunction<S>["args"]>, - >( - ...args: A - ) => - pipe( - { - callee: Expression.toJExpr(declaration), - args: Result.all(args.map(Expression.toJExpr)), - }, - Result.all, - Result.map( - ({ callee, args: values }) => - new AST.Expr(JExpr.call(callee, ...values)), - ), - Expression.fromResult< - EntityFunction<S>["returns"], - Inputs.Merge<EntityFunction<S>["inputs"], ArgumentInputs<A>> - >, - chain< - EntityFunction<S>["returns"], - EntityFunction<S>["vertex"], - Inputs.Merge<EntityFunction<S>["inputs"], ArgumentInputs<A>> - >, - ); - - return { entities }; -}; diff --git a/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts b/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts index a295ede2dc4..82d7f528deb 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/Scope.ts @@ -3,7 +3,7 @@ * * Missing namespace tables introduce no names. Optional tables contribute optional names instead of an arbitrary string index. Merging retains an earlier export when its replacement is optional, and snapshots include non-enumerable own exports without freezing the caller's records. * - * Each scope holds the names available to a construction callback. The prelude supplies the first one, and each declaration step of the Do API merges its names into the scope of the steps after it. Do callbacks receive the value and type tables as separate arguments, while Draft's `$.prelude()` joins them into one object in which a name can hold a module, a type and a value at once. + * A scope holds the names a construction callback can reach, which Draft's prelude supplies. Draft's `$.prelude()` joins the tables into one object in which a name can hold a module, a type and a value at once. * * @module */ @@ -53,7 +53,7 @@ export interface From<D extends Definition> { readonly types: Names<D, "types">; } -/** A scope with no names, which the default Do API starts from. */ +/** A scope with no names. */ export type Empty = From<EmptyNames>; type RequiredKeys<S> = { diff --git a/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts index bee6592b037..88e24948667 100644 --- a/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts +++ b/libs/@local/hashql/sdk/typescript/src/Program/TypeExpression.ts @@ -3,7 +3,7 @@ * * A {@link TypeExpression} carries syntax or a construction failure alongside a type-level descriptor. A {@link Constructor} specializes a named generic type while preserving its semantic argument tuple. Declarations supply these descriptors, and the HashQL compiler validates their use in the emitted program. * - * Type expressions come from module declarations, the built-in prelude, structural shorthand and the type aliases of the Do and Draft APIs. They appear wherever a program names a type, such as the type of an input. The operations here that annotate syntax or a path, {@link fromResult}, {@link fromType}, {@link reference} and {@link constructor}, attach the descriptor without checking it. + * Type expressions come from module declarations, the built-in prelude, structural shorthand and Draft's type aliases. They appear wherever a program names a type, such as the type of an input. The operations here that annotate syntax or a path, {@link fromResult}, {@link fromType}, {@link reference} and {@link constructor}, attach the descriptor without checking it. * * A failed construction stays inside the type expression. It surfaces when a caller reads the syntax, either directly or through an expression or program that uses the type. * diff --git a/libs/@local/hashql/sdk/typescript/src/Type/index.ts b/libs/@local/hashql/sdk/typescript/src/Type/index.ts index 8d475753d65..ae530c84be4 100644 --- a/libs/@local/hashql/sdk/typescript/src/Type/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/Type/index.ts @@ -92,7 +92,7 @@ export declare namespace Intersection { * * TypeScript accepts an opaque descriptor only where both the name and the underlying type match. A parameter of type `Type.PrimitiveInteger` or `Type.Opaque<"PostId", Type.PrimitiveInteger>` rejects `Type.Opaque<"UserId", Type.PrimitiveInteger>`. Projections and indexing on an expression of an opaque type still reach the fields and elements of the underlying type. * - * The name exists only in TypeScript. Emitted syntax names the declaration that introduced the type, such as `::core::uuid::Uuid`, rather than this name. Declarations that share a name and an underlying type are therefore interchangeable to TypeScript even when they emit different HashQL types. The built-in declarations use the absolute HashQL path as the name. The Do and Draft newtype operations require a `unique symbol`, which cannot coincide with a string name. + * The name exists only in TypeScript. Emitted syntax names the declaration that introduced the type, such as `::core::uuid::Uuid`, rather than this name. Declarations that share a name and an underlying type are therefore interchangeable to TypeScript even when they emit different HashQL types. The built-in declarations use the absolute HashQL path as the name. Draft's newtype operation requires a `unique symbol`, which cannot coincide with a string name. */ export interface Opaque<Name extends string | symbol, T extends Any> { readonly _tag: "Opaque"; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts deleted file mode 100644 index f9266dd9f25..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test-d.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { Result } from "effect"; -import { describe, expectTypeOf, test } from "vitest"; - -import { Expression, Module } from "../main.js"; -import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; - -import type { Inputs, Type, TypeExpression } from "../main.js"; -import type * as ProgramError from "../Program/ProgramError.js"; -// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments - -const initialValue = 7; -const kernel = Result.getOrThrow( - Module.define("::kernel::type", { - types: { - Integer: Module.type<Type.PrimitiveInteger>(), - String: Module.type<Type.PrimitiveString>(), - }, - }), -); -const { Do, Type: Alias } = withPrelude({ modules: { kernel } }); -const firstIdentity: unique symbol = Symbol("first"); -const secondIdentity: unique symbol = Symbol("second"); - -describe("universe_types", () => { - test("universe_transitions", () => { - const result = Do( - Import((_, { kernel }) => kernel), - Alias("Count", (_, { Integer }) => Integer), - Newtype("Id", firstIdentity, (_, { Count }) => Count), - Let("id", ($, { Id }, { Id: idType }) => { - expectTypeOf(idType).toEqualTypeOf< - TypeExpression.TypeExpression< - Type.Opaque<typeof firstIdentity, Type.PrimitiveInteger> - > - >(); - return Id($.integer(initialValue)); - }), - Let("Count", ($, _, types) => { - expectTypeOf(types.Count).toEqualTypeOf<typeof kernel.types.Integer>(); - return $.literal("value"); - }), - ($, { id, Count }, types) => { - expectTypeOf(Count).toEqualTypeOf< - Expression.Expression<Type.PrimitiveString, Inputs.Empty> - >(); - expectTypeOf($.ref.kernel).toEqualTypeOf<typeof kernel>(); - expectTypeOf(types.Count).toEqualTypeOf<typeof kernel.types.Integer>(); - // @ts-expect-error Modules are not value bindings. - expectTypeOf(id.kernel); - // @ts-expect-error Types cannot act as value expressions. - Expression.toJExpr(types.Count); - return id; - }, - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression< - Type.Opaque<typeof firstIdentity, Type.PrimitiveInteger>, - Inputs.Empty - >, - ProgramError.Construction - > - >(); - }); - - test("sequential_shadow", () => { - const result = EmptyDo( - Let("value", ($) => $.integer(initialValue)), - Let("copy", (_, { value }) => value), - Let("value", ($) => $.literal("new")), - (_, { copy, value }) => { - expectTypeOf(copy).toEqualTypeOf< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty> - >(); - expectTypeOf(value).toEqualTypeOf< - Expression.Expression<Type.PrimitiveString, Inputs.Empty> - >(); - // @ts-expect-error No undeclared bindings. - expectTypeOf(value.missing); - return copy; - }, - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty>, - ProgramError.Construction - > - >(); - }); -}); - -describe("branch_types", () => { - test("implicit_branch_scope", () => { - const result = Do( - Import((_, { kernel }) => kernel), - Let("outer", ($) => $.integer(initialValue)), - ($, { outer }) => { - const branch = $.if( - $.literal(true), - () => - $.Type("Local", (_, { Integer }) => Integer) - .Let("inner", ($, { outer }, { Local }) => - $.input("value", Local, outer), - ) - .Let("again", (_, { inner }) => inner) - .Expr((_, { again }, { Local }) => { - expectTypeOf(Local).toEqualTypeOf< - typeof kernel.types.Integer - >(); - return again; - }), - () => - $.Expr((_, values, types) => { - // @ts-expect-error The sibling branch cannot see the local value. - expectTypeOf(values.inner); - // @ts-expect-error The sibling branch cannot see the local type. - expectTypeOf(types.Local); - return outer; - }), - ); - $.if( - // @ts-expect-error An integer cannot be a conditional's condition. - outer, - () => outer, - () => outer, - ); - return branch; - }, - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression< - Type.PrimitiveInteger, - { readonly value?: Type.PrimitiveInteger } - >, - ProgramError.Construction - > - >(); - }); - - test("nominal_identity", () => { - Do( - Import((_, { kernel }) => kernel), - Newtype("Id", firstIdentity, (_, { Integer }) => Integer), - Let("first", ($, { Id }) => Id($.integer(1))), - Newtype("Id", secondIdentity, (_, { Integer }) => Integer), - ($, { Id, first }) => { - const second = Id($.integer(2)); - // @ts-expect-error Same query spelling does not make two nominal types equal. - const wrong: typeof first = second; - expectTypeOf(wrong); - // @ts-expect-error A nominal constructor needs its underlying type. - Id(first); - return second; - }, - ); - // oxlint-disable-next-line typescript/no-inferrable-types -- exercises rejection after losing the unique symbol type - const unbranded: symbol = Symbol("widened"); - // @ts-expect-error A widened symbol cannot distinguish nominal declarations. - Newtype("Id", unbranded, () => kernel.types.Integer); - }); -}); - -describe("composition_types", () => { - test("eight_steps", () => { - const result = EmptyDo( - Let("first", ($) => $.integer(1)), - Let("second", (_, { first }) => first), - Let("third", (_, { second }) => second), - Let("fourth", (_, { third }) => third), - Let("fifth", (_, { fourth }) => fourth), - Let("sixth", (_, { fifth }) => fifth), - Let("seventh", (_, { sixth }) => sixth), - Let("eighth", (_, { seventh }) => seventh), - (_, { first, eighth }) => { - expectTypeOf(first).toEqualTypeOf<typeof eighth>(); - return eighth; - }, - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty>, - ProgramError.Construction - > - >(); - }); - - test("callback_universes", () => { - Do( - Alias("Integer", ($, types) => { - // @ts-expect-error Type callbacks see types, not modules. - expectTypeOf(types.kernel); - return $.ref.kernel.types.Integer; - }), - Newtype("Id", firstIdentity, (_, { Integer }) => Integer), - (_, { Id }, { Integer }) => { - // @ts-expect-error The type alias is not a value expression. - Id(Integer); - return Id( - Expression.fromJExpr<Type.PrimitiveInteger, Inputs.Empty>("free"), - ); - }, - ); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts deleted file mode 100644 index 3e5a5fe922e..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.test.ts +++ /dev/null @@ -1,440 +0,0 @@ -/** - * Do block construction, declaration ordering and runtime validation tests. - * - * @module - */ -// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments -import { Result, pipe } from "effect"; -import { assert, describe, expect, test } from "vitest"; - -import { Expression, Module, Program, program } from "../main.js"; -import { Expr } from "../Program/AST/Expr.js"; -import { If } from "../Program/AST/If.js"; -import { Import as AstImport } from "../Program/AST/Import.js"; -import { Let as AstLet } from "../Program/AST/Let.js"; -import { Newtype as AstNewtype } from "../Program/AST/Newtype.js"; -import { Type as AstType } from "../Program/AST/Type.js"; -import { Do as EmptyDo, Import, Let, Newtype, withPrelude } from "./index.js"; - -import type { Inputs, Type } from "../main.js"; - -const initialValue = 7; -const fractionalValue = 1.5; -const kernel = Result.getOrThrow( - Module.define("::kernel::type", { - types: { Integer: Module.type<Type.PrimitiveInteger>() }, - }), -); -const { Do, Type: Alias } = withPrelude({ modules: { kernel } }); -const identity: unique symbol = Symbol("Id"); - -describe("construction", () => { - test("sequential_tree", () => { - expect.hasAssertions(); - const calls: string[] = []; - const root = EmptyDo( - Let("value", ($) => { - calls.push("value"); - return $.integer(initialValue); - }), - Let("copy", (_, { value }) => { - calls.push("copy"); - return value; - }), - Let("value", ($) => $.literal("new")), - (_, { copy }) => { - calls.push("body"); - return copy; - }, - ); - const tree = pipe( - root, - Result.flatMap(Expression.toNode), - Result.getOrThrow, - ); - expect(tree).toBeInstanceOf(AstLet); - expect(tree.compile()).toStrictEqual([ - "::kernel::special_form::let", - "value", - { "#literal": { _tag: "Integer", value: "7" } }, - [ - "::kernel::special_form::let", - "copy", - "value", - ["::kernel::special_form::let", "value", { "#literal": "new" }, "copy"], - ], - ]); - expect(calls).toStrictEqual(["value", "copy", "body"]); - assert.instanceOf(tree, AstLet); - expect(tree.child).toBeInstanceOf(AstLet); - }); - - test("type_and_constructor", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { kernel }) => kernel), - Alias("Count", (_, { Integer }) => Integer), - Newtype("Id", identity, (_, { Count }) => Count), - Let("id", ($, { Id }) => Id($.integer(initialValue))), - (_, { id }) => id, - ); - const imported = pipe( - root, - Result.flatMap(Expression.toNode), - Result.getOrThrow, - ); - assert.instanceOf<AstImport<typeof imported>>(imported, AstImport); - const tree = imported.child; - expect(tree).toBeInstanceOf(AstType); - expect(tree.compile()).toStrictEqual([ - "::kernel::special_form::type", - "Count", - "Integer", - [ - "::kernel::special_form::newtype", - "Id", - "Count", - [ - "::kernel::special_form::let", - "id", - ["Id", { "#literal": { _tag: "Integer", value: "7" } }], - "id", - ], - ], - ]); - assert.instanceOf(tree, AstType); - expect(tree.child).toBeInstanceOf(AstNewtype); - }); -}); - -describe("block_errors", () => { - test("missing_body", () => { - expect.hasAssertions(); - // @ts-expect-error Exercise the runtime boundary without a terminal callback. - const result = EmptyDo(); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - _tag: "ProgramConstructionError", - reason: { _tag: "MissingBlockBody" }, - }, - }); - }); - - test("misplaced_body", () => { - expect.hasAssertions(); - const result = EmptyDo( - // @ts-expect-error An expression callback cannot precede the terminal callback. - () => Expression.integer(1), - ($) => $.integer(2), - ); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - _tag: "ProgramConstructionError", - reason: { _tag: "MisplacedBlockBody" }, - }, - }); - }); - - test("invalid_body_result", () => { - expect.hasAssertions(); - // @ts-expect-error Exercise the runtime boundary with a host value. - const result = EmptyDo(() => "not an expression"); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - _tag: "ProgramConstructionError", - reason: { _tag: "InvalidBodyResult" }, - }, - }); - }); - - test("invalid_step", () => { - expect.hasAssertions(); - const result = EmptyDo( - // @ts-expect-error A plain object is not a declaration step. - {}, - ($) => $.integer(2), - ); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { reason: { _tag: "InvalidBlockStep" } }, - }); - }); - - test("binding_reason", () => { - expect.hasAssertions(); - const result = EmptyDo( - Let("bad name", ($) => $.integer(1)), - ($) => $.integer(2), - ); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - _tag: "ProgramConstructionError", - reason: { - _tag: "InvalidBindingName", - name: "bad name", - // oxlint-disable-next-line typescript/no-unsafe-assignment -- Vitest matchers describe expected values - cause: expect.any(Object), - }, - }, - }); - }); -}); - -describe("validation", () => { - test("declaration_short_circuit", () => { - expect.hasAssertions(); - const calls: string[] = []; - const result = EmptyDo( - Let("bad name", ($) => $.integer(1)), - Let("later", ($) => { - calls.push("later"); - return $.integer(2); - }), - ($) => { - calls.push("body"); - return $.integer(initialValue); - }, - ); - expect(Result.isFailure(result)).toBe(true); - expect(calls).toStrictEqual([]); - }); - - test("type_names", () => { - expect.hasAssertions(); - expect( - Result.isFailure( - Do( - Alias("bad name", ($) => $.ref.kernel.types.Integer), - ($) => $.integer(1), - ), - ), - ).toBe(true); - expect( - Result.isFailure( - Do( - Newtype("bad name", identity, ($) => $.ref.kernel.types.Integer), - ($) => $.integer(1), - ), - ), - ).toBe(true); - }); - - test.each([Number.NaN, Infinity, -Infinity, fractionalValue])( - "invalid_integer: %s", - (value) => { - expect.hasAssertions(); - expect(Result.isFailure(EmptyDo(($) => $.integer(value)))).toBe(true); - }, - ); -}); - -describe("nested_validation", () => { - test.each([true, false])("branch_failure: %s", (condition) => { - expect.hasAssertions(); - const calls: string[] = []; - const result = EmptyDo(($) => - $.if( - $.literal(condition), - () => { - calls.push("then"); - return $.Let("bad name", ($) => $.integer(1)) - .Let("skipped", ($) => { - calls.push("skipped"); - return $.integer(2); - }) - .Expr(($) => { - calls.push("body"); - return $.integer(initialValue); - }); - }, - () => { - calls.push("else"); - return $.integer(initialValue); - }, - ), - ); - expect(Result.isFailure(result)).toBe(true); - expect(calls).toStrictEqual(["then", "else"]); - }); - - test("alternate_failure", () => { - expect.hasAssertions(); - const result = EmptyDo(($) => - $.if( - $.literal(true), - () => $.integer(1), - () => - $.Let("bad name", ($) => $.integer(2)).Expr( - (_, values) => values["bad name"], - ), - ), - ); - expect(Result.isFailure(result)).toBe(true); - }); - - test("nested_argument_failure", () => { - expect.hasAssertions(); - const result = EmptyDo(($) => { - const consume = Expression.fromJExpr< - Type.Function<readonly [Type.PrimitiveInteger], Type.PrimitiveInteger>, - Inputs.Empty - >("consume"); - return consume( - $.Let("bad name", ($) => $.integer(1)).Expr( - (_, values) => values["bad name"], - ), - ); - }); - expect(Result.isFailure(result)).toBe(true); - }); - - test("input_default_failure", () => { - expect.hasAssertions(); - const result = Do(($) => - $.input("count", $.ref.kernel.types.Integer, $.integer(Number.NaN)), - ); - expect(Result.isFailure(result)).toBe(true); - }); -}); - -describe("branches", () => { - test("implicit_branches", () => { - expect.hasAssertions(); - const calls: string[] = []; - const root = Do( - Import((_, { kernel }) => kernel), - Let("outer", ($) => $.integer(initialValue)), - ($, { outer }) => - $.if( - $.literal(false), - () => { - calls.push("then"); - return $.Type("Local", (_, { Integer }) => Integer) - .Let("inner", ($, { outer }, { Local }) => - $.input("value", Local, outer), - ) - .Expr((_, { inner }) => inner); - }, - () => { - calls.push("else"); - return outer; - }, - ), - ); - const imported = pipe( - root, - Result.flatMap(Expression.toNode), - Result.getOrThrow, - ); - assert.instanceOf<AstImport<typeof imported>>(imported, AstImport); - const tree = imported.child; - expect(tree.compile()).toStrictEqual([ - "::kernel::special_form::let", - "outer", - { "#literal": { _tag: "Integer", value: "7" } }, - [ - "::kernel::special_form::if", - { "#literal": false }, - [ - "::kernel::special_form::type", - "Local", - "Integer", - [ - "::kernel::special_form::let", - "inner", - ["::kernel::special_form::input", "value", "Local", "outer"], - "inner", - ], - ], - "outer", - ], - ]); - tree.compile(); - expect(calls).toStrictEqual(["then", "else"]); - assert.instanceOf(tree, AstLet); - expect(tree.child).toBeInstanceOf(If); - }); - - test("nested_conditionals", () => { - expect.hasAssertions(); - const root = EmptyDo(($) => - $.if( - $.literal(true), - () => - $.Let("local", ($) => $.integer(1)).Expr(($, { local }) => - $.if( - $.literal(false), - () => local, - () => $.integer(2), - ), - ), - () => $.literal("other"), - ), - ); - expect( - pipe(root, Result.flatMap(Expression.toJExpr), Result.getOrThrow), - ).toStrictEqual([ - "::kernel::special_form::if", - { "#literal": true }, - [ - "::kernel::special_form::let", - "local", - { "#literal": { _tag: "Integer", value: "1" } }, - [ - "::kernel::special_form::if", - { "#literal": false }, - "local", - { "#literal": { _tag: "Integer", value: "2" } }, - ], - ], - { "#literal": "other" }, - ]); - }); -}); - -describe("expressions", () => { - test("quoted_binding", () => { - expect.hasAssertions(); - const root = EmptyDo( - Let("%", ($) => $.integer(initialValue)), - (_, values) => values["%"], - ); - expect( - pipe(root, Result.flatMap(Expression.toJExpr), Result.getOrThrow), - ).toStrictEqual([ - "::kernel::special_form::let", - "`%`", - { "#literal": { _tag: "Integer", value: "7" } }, - "`%`", - ]); - expect( - Result.isFailure( - EmptyDo( - Let("not a name", ($) => $.integer(1)), - ($) => $.integer(2), - ), - ), - ).toBe(true); - }); - - test("expression_leaf", () => { - expect.hasAssertions(); - const root = EmptyDo(($) => $.integer(initialValue)); - expect( - pipe(root, Result.flatMap(Expression.toNode), Result.getOrThrow), - ).toBeInstanceOf(Expr); - expect( - pipe( - root, - Result.getOrThrow, - program, - Program.compile, - Result.getOrThrow, - ), - ).toBe('{"#literal":7}'); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Do.ts b/libs/@local/hashql/sdk/typescript/src/do/Do.ts deleted file mode 100644 index 4b03efb9772..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Do.ts +++ /dev/null @@ -1,206 +0,0 @@ -import type * as Expression from "../Program/Expression.js"; -import type * as Input from "../Program/Inputs.js"; -import type * as ProgramError from "../Program/ProgramError.js"; -import type * as Scope from "../Program/Scope.js"; -import type * as Type from "../Type/index.js"; -import type * as Node from "./Node.js"; -import type { Body } from "./Utilities.js"; -import type { Result } from "effect"; - -/** - * The call signatures of a Do block constructor whose blocks start in the scope `Initial`. - * - * Each overload threads the scope through zero to eight declaration steps, so every step and the final body see the names the earlier steps introduced. The result's input requirements combine those of every step with the body's. For more than eight steps, continue in a nested block started from a callback's `$`. - */ -export interface Do<Initial extends Scope.Scope> { - <T extends Type.Any, Inputs>( - body: Body<Initial, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [Inputs]>>, - ProgramError.Construction - >; - <S1 extends Scope.Scope, I1, T extends Type.Any, Inputs>( - step1: Node.Node<Initial, S1, I1>, - body: Body<S1, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [I1, Inputs]>>, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - body: Body<S2, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [I1, I2, Inputs]>>, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - body: Body<S3, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [I1, I2, I3, Inputs]>>, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - S4 extends Scope.Scope, - I4, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - step4: Node.Node<S3, S4, I4>, - body: Body<S4, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [I1, I2, I3, I4, Inputs]>>, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - S4 extends Scope.Scope, - I4, - S5 extends Scope.Scope, - I5, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - step4: Node.Node<S3, S4, I4>, - step5: Node.Node<S4, S5, I5>, - body: Body<S5, T, Inputs>, - ): Result.Result< - Expression.Expression<T, Input.All<readonly [I1, I2, I3, I4, I5, Inputs]>>, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - S4 extends Scope.Scope, - I4, - S5 extends Scope.Scope, - I5, - S6 extends Scope.Scope, - I6, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - step4: Node.Node<S3, S4, I4>, - step5: Node.Node<S4, S5, I5>, - step6: Node.Node<S5, S6, I6>, - body: Body<S6, T, Inputs>, - ): Result.Result< - Expression.Expression< - T, - Input.All<readonly [I1, I2, I3, I4, I5, I6, Inputs]> - >, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - S4 extends Scope.Scope, - I4, - S5 extends Scope.Scope, - I5, - S6 extends Scope.Scope, - I6, - S7 extends Scope.Scope, - I7, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - step4: Node.Node<S3, S4, I4>, - step5: Node.Node<S4, S5, I5>, - step6: Node.Node<S5, S6, I6>, - step7: Node.Node<S6, S7, I7>, - body: Body<S7, T, Inputs>, - ): Result.Result< - Expression.Expression< - T, - Input.All<readonly [I1, I2, I3, I4, I5, I6, I7, Inputs]> - >, - ProgramError.Construction - >; - < - S1 extends Scope.Scope, - I1, - S2 extends Scope.Scope, - I2, - S3 extends Scope.Scope, - I3, - S4 extends Scope.Scope, - I4, - S5 extends Scope.Scope, - I5, - S6 extends Scope.Scope, - I6, - S7 extends Scope.Scope, - I7, - S8 extends Scope.Scope, - I8, - T extends Type.Any, - Inputs, - >( - step1: Node.Node<Initial, S1, I1>, - step2: Node.Node<S1, S2, I2>, - step3: Node.Node<S2, S3, I3>, - step4: Node.Node<S3, S4, I4>, - step5: Node.Node<S4, S5, I5>, - step6: Node.Node<S5, S6, I6>, - step7: Node.Node<S6, S7, I7>, - step8: Node.Node<S7, S8, I8>, - body: Body<S8, T, Inputs>, - ): Result.Result< - Expression.Expression< - T, - Input.All<readonly [I1, I2, I3, I4, I5, I6, I7, I8, Inputs]> - >, - ProgramError.Construction - >; -} diff --git a/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts deleted file mode 100644 index e43dd31d96f..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Exception.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { Cause, Result, pipe } from "effect"; -import { assert, describe, expect, test } from "vitest"; - -import { Expression } from "../main.js"; -import { - Type as DeclareType, - Do, - Import, - Let, - Newtype, - withPrelude, -} from "./index.js"; - -import type { Inputs, ProgramError, Type } from "../main.js"; - -const identity: unique symbol = Symbol("Exception"); -type ConstructionResult = Result.Result< - Expression.Any, - ProgramError.Construction ->; -type SuccessBody = () => Expression.Expression< - Type.PrimitiveInteger, - Inputs.Empty ->; -type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; -type Graph = Type.Opaque< - "::graph::Graph", - Type.Struct<{ readonly "'marker": Vertex }> ->; -const queryContext = withPrelude({ - values: { - entities: Expression.fromJExpr< - Type.Function<readonly [], Graph>, - Inputs.Empty - >("entities"), - }, -}); - -describe("do_exceptions", () => { - test.each([new Error("user exception"), "non-error", undefined])( - "host_exception_%#", - (thrown) => { - expect.hasAssertions(); - const result = Do(() => { - // oxlint-disable-next-line typescript/only-throw-error -- unchecked JavaScript callbacks can throw arbitrary values - throw thrown; - }); - const failure = pipe(result, Result.flip, Result.getOrThrow); - assert(failure.reason._tag === "CallbackException"); - expect(failure.reason.cause).toBeInstanceOf(Cause.UnknownError); - expect(failure.reason.cause.cause).toBe(thrown); - expect(failure.message).toBe("A program callback threw an exception"); - }, - ); - - test.each([ - { - name: "let", - run: (fail: () => never, later: SuccessBody): ConstructionResult => - Do(Let("value", fail), Let("later", later), later), - }, - { - name: "type", - run: (fail: () => never, later: SuccessBody): ConstructionResult => - Do(DeclareType("Value", fail), Let("later", later), later), - }, - { - name: "newtype", - run: (fail: () => never, later: SuccessBody): ConstructionResult => - Do(Newtype("Value", identity, fail), Let("later", later), later), - }, - { - name: "import", - run: (fail: () => never, later: SuccessBody): ConstructionResult => - Do(Import(fail), Let("later", later), later), - }, - ])("declaration_$name", ({ run }) => { - expect.hasAssertions(); - const thrown = new Error("declaration callback"); - const calls: string[] = []; - const result = run( - () => { - calls.push("declaration"); - throw thrown; - }, - () => { - calls.push("later"); - return Expression.integer(1); - }, - ); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(calls).toStrictEqual(["declaration"]); - }); - - test("nested_declaration", () => { - expect.hasAssertions(); - const thrown = new Error("nested declaration"); - let continued = false; - const result = Do(($) => { - const expression = $.Let("value", () => { - throw thrown; - }).Expr(($) => $.integer(1)); - continued = true; - return expression; - }); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(continued).toBe(true); - }); - - test("nested_body", () => { - expect.hasAssertions(); - const thrown = new Error("nested body"); - let continued = false; - const result = Do(($) => { - const expression = $.Let("value", ($) => $.integer(1)).Expr(() => { - throw thrown; - }); - continued = true; - return expression; - }); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(continued).toBe(true); - }); - - test("consequent_exception", () => { - expect.hasAssertions(); - const thrown = new Error("consequent callback"); - const calls: string[] = []; - const result = Do(($) => { - const expression = $.if( - false, - () => { - calls.push("then"); - throw thrown; - }, - () => { - calls.push("else"); - return 1n; - }, - ); - calls.push("body"); - return expression; - }); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(calls).toStrictEqual(["then", "else", "body"]); - }); - - test("alternate_exception", () => { - expect.hasAssertions(); - const thrown = new Error("alternate callback"); - let continued = false; - const result = Do(($) => { - const expression = $.if( - true, - () => 1n, - () => { - throw thrown; - }, - ); - continued = true; - return expression; - }); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(continued).toBe(true); - }); - - test("branch_failure_priority", () => { - expect.hasAssertions(); - const invalid = Expression.integer(Number.NaN); - const failure = pipe( - invalid, - Expression.toNode, - Result.flip, - Result.getOrThrow, - ); - let alternateCalled = false; - const result = Do(($) => - $.if( - false, - () => invalid, - () => { - alternateCalled = true; - throw new Error("alternate callback"); - }, - ), - ); - expect(pipe(result, Result.flip, Result.getOrThrow)).toBe(failure); - expect(alternateCalled).toBe(true); - }); - - test("predicate_exception", () => { - expect.hasAssertions(); - const thrown = new Error("predicate callback"); - let continued = false; - let laterPredicate = false; - const result = queryContext.Do(($) => { - const expression = $.query - .entities() - .filter("vertex", (): boolean => { - throw thrown; - }) - .filter("later", () => { - laterPredicate = true; - return true; - }) - .collect(); - continued = true; - return expression; - }); - expect(result).toMatchObject({ - _tag: "Failure", - failure: { - reason: { _tag: "CallbackException", cause: { cause: thrown } }, - }, - }); - expect(continued).toBe(true); - expect(laterPredicate).toBe(false); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts deleted file mode 100644 index 243510cce41..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.test-d.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Result } from "effect"; -import { describe, expectTypeOf, test } from "vitest"; - -import { Module } from "../main.js"; -import { Do as EmptyDo, Import, withPrelude } from "./index.js"; - -import type { Expression, Inputs, Type } from "../main.js"; -import type * as ProgramError from "../Program/ProgramError.js"; -// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments - -type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; -const uuid = Result.getOrThrow( - Module.define("::core::uuid", { - types: { Uuid: Module.type<Uuid>() }, - values: { - Uuid: Module.value< - Type.Function<readonly [Type.PrimitiveString], Uuid> - >(), - }, - }), -); -const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); -const { Do } = withPrelude({ modules: { uuid, core } }); - -describe("import_types", () => { - test("named_exports", () => { - const result = Do( - Import((_, { uuid }) => uuid, ["Uuid"]), - ($, values, types) => { - expectTypeOf(types.Uuid).toEqualTypeOf<typeof uuid.types.Uuid>(); - expectTypeOf(values.Uuid).toEqualTypeOf<typeof uuid.values.Uuid>(); - // @ts-expect-error Module names do not enter the type universe. - expectTypeOf(types.uuid); - // @ts-expect-error Utilities are not a flattened export namespace. - expectTypeOf($.Uuid); - return $.ref.uuid.values.Uuid($.literal("id")); - }, - ); - expectTypeOf(result).toEqualTypeOf< - Result.Result< - Expression.Expression<Uuid, Inputs.Empty>, - ProgramError.Construction - > - >(); - }); - - test("module_alias", () => { - Do( - Import((_, { core }) => core, { uuid: "ids" }), - Import((_, { ids }) => ids), - ($, { Uuid }, types) => { - expectTypeOf($.ref.ids).toEqualTypeOf<typeof uuid>(); - expectTypeOf(types.Uuid).toEqualTypeOf<typeof uuid.types.Uuid>(); - return Uuid($.literal("id")); - }, - ); - }); - - test("invalid_exports", () => { - expectTypeOf(withPrelude); - // @ts-expect-error Values must be expression handles. - withPrelude({ values: { host: 1 } }); - // @ts-expect-error Modules must be module declarations. - withPrelude({ modules: { uuid: uuid.values.Uuid } }); - // @ts-expect-error Types cannot be value handles. - withPrelude({ types: { Uuid: uuid.values.Uuid } }); - // @ts-expect-error An import selects a module. - Import(() => ({ Uuid: uuid.values.Uuid })); - // @ts-expect-error Selected names must exist in an export universe. - Import(() => uuid, ["Missing"]); - // @ts-expect-error Alias sources must exist in an export universe. - Import(() => uuid, { Missing: "Local" }); - }); - - test("literal_types", () => { - EmptyDo(($) => { - expectTypeOf($.integer(1)).toEqualTypeOf< - Expression.Expression<Type.PrimitiveInteger, Inputs.Empty> - >(); - expectTypeOf($.number(1)).toEqualTypeOf< - Expression.Expression<Type.PrimitiveNumber, Inputs.Empty> - >(); - expectTypeOf($.literal(false)).toEqualTypeOf< - Expression.Expression<Type.PrimitiveBoolean, Inputs.Empty> - >(); - expectTypeOf($.literal(1)).toEqualTypeOf< - Expression.Expression<Type.PrimitiveNumber, Inputs.Empty> - >(); - return $.literal(null); - }); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts deleted file mode 100644 index eb89e6b9477..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -// oxlint-disable hash/naming-conventions -- examples preserve HashQL type and constructor names in separate callback arguments -import { Result } from "effect"; -import { describe, expect, test } from "vitest"; - -import { Expression, Module, TypeExpression } from "../main.js"; -import { Import, Let, withPrelude } from "./index.js"; - -import type { Type } from "../main.js"; - -type Uuid = Type.Opaque<"::core::uuid::Uuid", Type.PrimitiveString>; -const uuid = Result.getOrThrow( - Module.define("::core::uuid", { - types: { Uuid: Module.type<Uuid>() }, - values: { - Uuid: Module.value< - Type.Function<readonly [Type.PrimitiveString], Uuid> - >(), - }, - }), -); -const core = Result.getOrThrow(Module.define("::core", { modules: { uuid } })); -const { Do } = withPrelude({ modules: { uuid, core } }); - -const use = "::kernel::special_form::use"; -const shadowValue = 7; - -describe("import_exports", () => { - test("same_named_exports", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { uuid }) => uuid), - ($, { Uuid }, { Uuid: uuidType }) => { - expect( - Result.getOrThrow(TypeExpression.toType(uuidType)), - ).toMatchObject({ - _tag: "Reference", - path: { rooted: false, segments: [{ value: "Uuid" }] }, - }); - return Uuid($.literal("id")); - }, - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([use, "::core::uuid", "*", ["Uuid", { "#literal": "id" }]]); - }); - - test("named_import", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { uuid }) => uuid, ["Uuid"]), - ($, { Uuid }, types) => - $.input("id", types.Uuid, Uuid($.literal("fallback"))), - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - use, - "::core::uuid", - { "#tuple": ["Uuid"] }, - [ - "::kernel::special_form::input", - "id", - "Uuid", - ["Uuid", { "#literal": "fallback" }], - ], - ]); - }); - - test("renamed_exports", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { uuid }) => uuid, { Uuid: "Id" }), - ($, { Id }, types) => $.input("id", types.Id, Id($.literal("fallback"))), - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - use, - "::core::uuid", - { "#struct": { Uuid: "Id" } }, - [ - "::kernel::special_form::input", - "id", - "Id", - ["Id", { "#literal": "fallback" }], - ], - ]); - }); - - test("module_alias", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { core }) => core, { uuid: "ids" }), - Import((_, { ids }) => ids), - ($, { Uuid }) => Uuid($.literal("id")), - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - use, - "::core", - { "#struct": { uuid: "ids" } }, - [use, "ids", "*", ["Uuid", { "#literal": "id" }]], - ]); - const qualified = Do( - Import((_, { core }) => core, { uuid: "ids" }), - ($) => $.ref.ids.values.Uuid($.literal("id")), - ); - expect( - Result.getOrThrow(Result.flatMap(qualified, Expression.toJExpr)), - ).toStrictEqual([ - use, - "::core", - { "#struct": { uuid: "ids" } }, - ["ids::Uuid", { "#literal": "id" }], - ]); - }); -}); - -describe("import_validation", () => { - test("invalid_alias", () => { - expect.hasAssertions(); - let called = false; - const result = Do( - Import((_, { uuid }) => uuid, { Uuid: "bad name" }), - ($) => { - called = true; - return $.integer(1); - }, - ); - expect(Result.isFailure(result)).toBe(true); - expect(called).toBe(false); - }); -}); - -describe("import_scope", () => { - test("independent_shadow", () => { - expect.hasAssertions(); - const root = Do( - Import((_, { uuid }) => uuid), - Let("Uuid", ($) => $.integer(shadowValue)), - ($, { Uuid }, types) => { - expect(Result.getOrThrow(Expression.toJExpr(Uuid))).toBe("Uuid"); - return $.input("id", types.Uuid); - }, - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - use, - "::core::uuid", - "*", - [ - "::kernel::special_form::let", - "Uuid", - { "#literal": { _tag: "Integer", value: "7" } }, - ["::kernel::special_form::input", "id", "Uuid"], - ], - ]); - }); - - test("branch_import_isolation", () => { - expect.hasAssertions(); - const root = Do(($) => - $.if( - $.literal(true), - () => - $.Import((_, { uuid }) => uuid).Expr(($, { Uuid }) => - Uuid($.literal("id")), - ), - () => - $.Expr(($, values, types) => { - expect(values).toStrictEqual({}); - expect(types).toStrictEqual({}); - return $.ref.uuid.values.Uuid($.literal("fallback")); - }), - ), - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - "::kernel::special_form::if", - { "#literal": true }, - [use, "::core::uuid", "*", ["Uuid", { "#literal": "id" }]], - ["::core::uuid::Uuid", { "#literal": "fallback" }], - ]); - }); - - test("input_defaults", () => { - expect.hasAssertions(); - const kernel = Result.getOrThrow( - Module.define("::kernel::type", { - types: { Integer: Module.type<Type.PrimitiveInteger>() }, - }), - ); - const root = withPrelude(kernel).Do(($, _, { Integer }) => - $.input("count", Integer, $.integer(0)), - ); - expect( - Result.getOrThrow(Result.flatMap(root, Expression.toJExpr)), - ).toStrictEqual([ - "::kernel::special_form::input", - "count", - "::kernel::type::Integer", - { "#literal": { _tag: "Integer", value: "0" } }, - ]); - }); -}); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Import.ts b/libs/@local/hashql/sdk/typescript/src/do/Import.ts deleted file mode 100644 index 1c30ada09dc..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Import.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Lexical imports into a sequential Do scope. - * - * @module - */ -import { Result, pipe } from "effect"; - -import * as Imports from "../Program/Import.js"; -import * as Scope from "../Program/Scope.js"; -import * as Node from "./Node.js"; - -import type * as Inputs from "../Program/Inputs.js"; -import type * as Module from "../Program/Module.js"; -import type { Utilities } from "./Utilities.js"; - -export type { Imported, Selection } from "../Program/Import.js"; - -/** - * Imports a module's exports as a Do block step. - * - * When a block elaborates the step, it calls `select` with the utilities and the modules visible at that point, then emits a HashQL `use` of the returned module around everything after this step. Each selected export enters every environment that declares it, under its local name: modules join the modules environment and `$.ref`, types join the types and values join the values. The imported handles are local names that keep their declared semantic types and call signatures. - * - * Omitting `selection` imports every export. Given a name array, the step imports those exports. Given an alias record, it imports each listed export under a new name, where `"_"` keeps the export's own name. Invalid HashQL identifiers as aliases, and symbol keys in the record, fail construction with `InvalidImportName`, and the block then skips its remaining callbacks. - */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- the selector and selection construct a declaration step -export function Import<S extends Scope.Scope, M extends Module.Any>( - select: ( - utilities: Utilities<S>, - modules: S["modules"], - ) => M & Imports.Rebindable<M>, -): Node.Node<S, Scope.Merge<S, Imports.Imported<M, "*">>, Inputs.Empty>; -export function Import< - S extends Scope.Scope, - M extends Module.Any, - const I extends Imports.Selection<M>, ->( - select: ( - utilities: Utilities<S>, - modules: S["modules"], - ) => M & Imports.Rebindable<M>, - selection: I, -): Node.Node<S, Scope.Merge<S, Imports.Imported<M, I>>, Inputs.Empty>; -export function Import<S extends Scope.Scope>( - select: (utilities: Utilities<S>, modules: S["modules"]) => Module.Any, - // oxlint-disable-next-line hash/prefer-options-object -- the optional argument is the import selection itself - selection: Imports.Selection<Module.Any> = "*", -): Node.Any { - return Node.make((utilities: Utilities<S>, scope: S) => - pipe( - Imports.bind(select(utilities, scope.modules), selection), - Result.map((declaration) => ({ - scope: Scope.merge(scope, declaration.scope), - wrap: declaration.wrap, - })), - ), - ); -} diff --git a/libs/@local/hashql/sdk/typescript/src/do/Let.ts b/libs/@local/hashql/sdk/typescript/src/do/Let.ts deleted file mode 100644 index 5af8d3be961..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Let.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { Result } from "effect"; - -import * as Ident from "../JExpr/Ident.js"; -import * as Binding from "../Program/AST/Binding.js"; -import { Let as AstLet } from "../Program/AST/Let.js"; -import * as Expression from "../Program/Expression.js"; -import * as Scope from "../Program/Scope.js"; -import * as Node from "./Node.js"; - -import type * as Type from "../Type/index.js"; -import type { Utilities } from "./Utilities.js"; -import type { ReadonlyRecord } from "effect/Record"; - -/** - * Declares a value binding as a Do block step. - * - * When a block elaborates the step, it calls `initializer` with the utilities, values and types visible at that point. The block emits a HashQL `let` that binds `name` to the initializer around everything after this step. Later steps see `name` in their values environment as a reference with the initializer's semantic type and input requirements. A later binding with the same name shadows this one in the values environment only. - * - * The block emits the binding even when nothing refers to it, so its initializer's inputs stay in the program. Names that need quoting, such as `%`, appear quoted in the output. An invalid HashQL identifier fails construction with `InvalidBindingName` after the initializer has run, and the block skips its remaining callbacks. - */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a declaration step -export const Let = < - In extends Scope.Scope, - const Name extends string, - T extends Type.Any, - Inputs, ->( - name: Name, - initializer: ( - utilities: Utilities<In>, - values: In["values"], - types: In["types"], - ) => Expression.Expression<T, Inputs>, -): Node.Node< - In, - Scope.Merge< - In, - { values: ReadonlyRecord<Name, Expression.Expression<T, Inputs>> } - >, - Inputs -> => - Node.make((utilities, scope) => - Result.gen(function* () { - const value = yield* Expression.toNode( - initializer(utilities, scope.values, scope.types), - ); - const binding = yield* Binding.make(name, value); - const reference = Expression.fromJExpr<T, Inputs>( - Ident.compile(binding.name), - ); - - // SAFETY: the sole key is the literal name supplied by the caller. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a computed property widens its key to string - const values = { [name]: reference } as ReadonlyRecord< - Name, - Expression.Expression<T, Inputs> - >; - - return { - scope: Scope.merge(scope, { values }), - wrap: (child) => new AstLet(binding, child), - }; - }), - ); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts b/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts deleted file mode 100644 index 6ae61534c3d..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Newtype.ts +++ /dev/null @@ -1,116 +0,0 @@ -// oxlint-disable import/max-dependencies -- nominal declarations introduce both a type and a value constructor -import { Result } from "effect"; - -import * as Ident from "../JExpr/Ident.js"; -import * as Binding from "../Program/AST/Binding.js"; -import { Newtype as AstNewtype } from "../Program/AST/Newtype.js"; -import * as Expression from "../Program/Expression.js"; -import * as Scope from "../Program/Scope.js"; -import * as TypeExpression from "../Program/TypeExpression.js"; -import * as Node from "./Node.js"; - -import type * as Inputs from "../Program/Inputs.js"; -import type * as Type from "../Type/index.js"; -import type { Utilities } from "./Utilities.js"; -import type { ReadonlyRecord } from "effect/Record"; - -/** The names a `Newtype` step adds: the nominal type and its constructor, both under the declared name. */ -export interface Exports< - Name extends string, - Identity extends symbol, - T extends Type.Any, -> { - /** The nominal type, an opaque type over `T` distinguished by `Identity`. */ - readonly types: ReadonlyRecord< - Name, - TypeExpression.TypeExpression<Type.Opaque<Identity, T>> - >; - /** The constructor, a function from the underlying type `T` to the nominal type. */ - readonly values: ReadonlyRecord< - Name, - Expression.Expression< - Type.Function<readonly [T], Type.Opaque<Identity, T>>, - Inputs.Empty - > - >; -} - -/** - * Declares a nominal type and its constructor as a Do block step. - * - * When a block elaborates the step, it calls `definition` with the utilities and the types visible at that point, then emits a HashQL `newtype` declaration around everything after this step. Later steps see `name` in two environments: as the opaque type `Type.Opaque<Identity, T>` among their types, and as its constructor among their values. The constructor takes a value of the underlying type `T` and emits a call to `name`. A value of the nominal type does not convert back to `T` implicitly. - * - * `identity` must have a `unique symbol` type. It exists only for TypeScript and is never emitted: two declarations with the same name but different symbols produce incompatible types, and a symbol widened to `symbol` is a type error. A name that is not a valid HashQL identifier fails construction with `InvalidBindingName`, and the block skips its remaining callbacks. - * - * @example <caption>Declare a nominal identifier and construct a value.</caption> - * ```ts - * import assert from "node:assert/strict"; - * import { Module, Program } from "@local/hashql"; - * import type { Type } from "@local/hashql"; - * import { Import, Let, Newtype, withPrelude } from "@local/hashql/do"; - * import { Result } from "effect"; - * - * const kernel = Result.getOrThrow( - * Module.define("::kernel::type", { - * types: { Integer: Module.type<Type.PrimitiveInteger>() }, - * }), - * ); - * const userId: unique symbol = Symbol("UserId"); - * const { Do } = withPrelude({ modules: { kernel } }); - * - * const owner = Do( - * Import((_, { kernel }) => kernel, ["Integer"]), - * Newtype("UserId", userId, (_, { Integer }) => Integer), - * Let("owner", (_, { UserId }) => UserId(1n)), - * (_, { owner }) => owner, - * ); - * assert.equal( - * Result.getOrThrow(Result.flatMap(owner, (root) => Program.compile(Program.program(root)))), - * '["::kernel::special_form::use","::kernel::type",{"#tuple":["Integer"]},["::kernel::special_form::newtype","UserId","Integer",["::kernel::special_form::let","owner",["UserId",{"#literal":1}],"owner"]]]', - * ); - * ``` - */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a nominal declaration step -export const Newtype = < - In extends Scope.Scope, - const Name extends string, - const Identity extends symbol, - T extends Type.Any, ->( - name: Name, - _identity: Identity & (symbol extends Identity ? never : Identity), - definition: ( - utilities: Utilities<In>, - types: In["types"], - ) => TypeExpression.TypeExpression<T>, -): Node.Node<In, Scope.Merge<In, Exports<Name, Identity, T>>, Inputs.Empty> => - Node.make((utilities, scope) => - Result.gen(function* () { - const binding = yield* Binding.make( - name, - yield* TypeExpression.toType(definition(utilities, scope.types)), - ); - const reference = TypeExpression.reference<Type.Opaque<Identity, T>>({ - rooted: false, - segments: [binding.name], - }); - - const constructor = Expression.fromJExpr< - Type.Function<readonly [T], Type.Opaque<Identity, T>>, - Inputs.Empty - >(Ident.compile(binding.name)); - - const entries = { - types: { [name]: reference }, - values: { [name]: constructor }, - }; - - // SAFETY: both universes bind the same name, with the nominal type and its constructor respectively. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- computed properties widen their keys to string - const exports = entries as Exports<Name, Identity, T>; - return { - scope: Scope.merge(scope, exports), - wrap: (child) => new AstNewtype(binding, child), - }; - }), - ); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Node.ts b/libs/@local/hashql/sdk/typescript/src/do/Node.ts deleted file mode 100644 index fe4f3b658a5..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Node.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { identity } from "effect"; - -import type { Node as AstNode } from "../Program/AST/Node.js"; -import type * as ProgramError from "../Program/ProgramError.js"; -import type { Scope } from "../Program/Scope.js"; -import type { Utilities } from "./Utilities.js"; -import type { Result, Types } from "effect"; - -/** Invariant markers for one environment's scope before and after a declaration step. */ -export interface Variance<In, Out> { - readonly _In: Types.Invariant<In>; - readonly _Out: Types.Invariant<Out>; -} - -/** - * The property key that marks a value as a declaration step. - * - * `Do` fails with `InvalidBlockStep` when a value in a step position is neither a callback nor marked with this key. - */ -export const TypeId = "~hashql/do/Node"; - -/** The outcome of elaborating a declaration step: the scope later steps see and the wrapper that emits the declaration. */ -export interface Transition<Out extends Scope> { - /** The scope after the declaration, which the following steps and the body receive. */ - readonly scope: Out; - /** Places the declaration around `child`, the syntax of everything that follows it in the block. */ - readonly wrap: (child: AstNode) => AstNode; -} - -/** A declaration step with its scope parameters erased, as a block's runtime driver handles it. */ -export interface Any { - /** - * Runs the step's callback against the current scope and returns the declaration's transition or construction failure. - * - * A block calls it while constructing, once per step, after the preceding steps succeed. The block converts an exception thrown here into a `CallbackException` failure. - */ - readonly elaborate: ( - utilities: Utilities<Scope>, - scope: Scope, - ) => Result.Result<Transition<Scope>, ProgramError.Construction>; -} - -/** - * A typed declaration step from the scope `In` to the scope `Out`, contributing the input requirements `Inputs`. - * - * `Let`, `Type`, `Newtype` and `Import` construct steps. Creating one runs none of its callbacks: a block runs the callback each time it elaborates the step. The marker property records each environment's scope before and after the step, which lets the Do overloads infer the scope of every later step. - */ -export interface Node<In extends Scope, Out extends Scope, Inputs> extends Any { - readonly [TypeId]: { - readonly inputs: Types.Contravariant<Inputs>; - readonly modules: Variance<In["modules"], Out["modules"]>; - readonly values: Variance<In["values"], Out["values"]>; - readonly types: Variance<In["types"], Out["types"]>; - }; -} - -export const make = <In extends Scope, Out extends Scope, Inputs>( - elaborate: ( - utilities: Utilities<In>, - scope: In, - ) => Result.Result<Transition<Out>, ProgramError.Construction>, -): Node<In, Out, Inputs> => { - // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary - const erased: unknown = elaborate; - return { - [TypeId]: { - // oxlint-disable-next-line typescript/strict-void-return -- only used for variance - inputs: identity, - modules: { _In: identity, _Out: identity }, - values: { _In: identity, _Out: identity }, - types: { _In: identity, _Out: identity }, - }, - // SAFETY: block composition supplies exactly the input scope recorded in the node's type. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- only the runtime driver erases the successive scopes - elaborate: erased as Any["elaborate"], - }; -}; diff --git a/libs/@local/hashql/sdk/typescript/src/do/Type.ts b/libs/@local/hashql/sdk/typescript/src/do/Type.ts deleted file mode 100644 index 18e081d587e..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Type.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { Result } from "effect"; - -import * as Binding from "../Program/AST/Binding.js"; -import { Type as AstType } from "../Program/AST/Type.js"; -import * as Scope from "../Program/Scope.js"; -import * as TypeExpression from "../Program/TypeExpression.js"; -import * as Node from "./Node.js"; - -import type { Empty } from "../Program/Inputs.js"; -import type * as Semantic from "../Type/index.js"; -import type { Utilities } from "./Utilities.js"; -import type { ReadonlyRecord } from "effect/Record"; - -/** - * Declares a type alias as a Do block step. - * - * When a block elaborates the step, it calls `definition` with the utilities and the types visible at that point. The block emits a HashQL `type` declaration around everything after this step. Later steps see `name` in their types environment as a reference to the alias, carrying the definition's semantic type, so TypeScript treats the alias as that type. Use `Newtype` for a distinct nominal type. A value or module with the same name stays visible. - * - * A name that is not a valid HashQL identifier fails construction with `InvalidBindingName`, and the block skips its remaining callbacks. - */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- constructs a type declaration step -export const Type = < - In extends Scope.Scope, - const Name extends string, - T extends Semantic.Any, ->( - name: Name, - definition: ( - utilities: Utilities<In>, - types: In["types"], - ) => TypeExpression.TypeExpression<T>, -): Node.Node< - In, - Scope.Merge< - In, - { types: ReadonlyRecord<Name, TypeExpression.TypeExpression<T>> } - >, - Empty -> => - Node.make((utilities, scope) => - Result.gen(function* () { - const binding = yield* Binding.make( - name, - yield* TypeExpression.toType(definition(utilities, scope.types)), - ); - - const reference = TypeExpression.reference<T>({ - rooted: false, - segments: [binding.name], - }); - - // SAFETY: the sole key is the literal name supplied by the caller. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a computed property widens its key to string - const types = { [name]: reference } as ReadonlyRecord< - Name, - TypeExpression.TypeExpression<T> - >; - - return { - scope: Scope.merge(scope, { types }), - wrap: (child) => new AstType(binding, child), - }; - }), - ); diff --git a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts b/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts deleted file mode 100644 index 1d28411a2b9..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/Utilities.ts +++ /dev/null @@ -1,396 +0,0 @@ -/** - * Sequential declaration blocks for the Do authoring API. - * - * Each step extends the typed scope and records how to wrap the final expression. Nested bodies inherit the scope without repeating the declarations that introduced it. {@link Block} retains construction failures until the caller completes the body. - * - * @module - */ -// oxlint-disable import/max-dependencies -- block construction composes the declaration steps and expression helpers -// oxlint-disable unicorn/no-array-method-this-argument -- Result.map and Result.flatMap are not array methods -import { Cause, Result, identity, pipe } from "effect"; - -import { If as AstIf } from "../Program/AST/If.js"; -import * as Expression from "../Program/Expression.js"; -import * as Operators from "../Program/Operators.js"; -import * as ProgramError from "../Program/ProgramError.js"; -import * as Query from "../Program/Query.js"; -import { Import } from "./Import.js"; -import { Let } from "./Let.js"; -import { Newtype } from "./Newtype.js"; -import * as Node from "./Node.js"; -import { Type as DeclareType } from "./Type.js"; - -import type { Node as AstNode } from "../Program/AST/Node.js"; -import type { Rebindable } from "../Program/Import.js"; -import type * as Input from "../Program/Inputs.js"; -import type * as Scope from "../Program/Scope.js"; -import type { TypeExpression } from "../Program/TypeExpression.js"; -import type * as Type from "../Type/index.js"; -import type { Imported, Selection } from "./Import.js"; -import type { Exports } from "./Newtype.js"; -import type { ReadonlyRecord } from "effect/Record"; - -/** - * A callback that returns an expression from the utilities, values and types of the scope `S`. - * - * It types a block's final body and the initializer of a nested `Let`. As a final body, it must return an expression handle: any other value fails construction with `InvalidBodyResult`, so lift a host primitive with `$.literal`, `$.integer` or `$.number`. - */ -export type Body<S extends Scope.Scope, T extends Type.Any, Inputs> = ( - utilities: Utilities<S>, - values: S["values"], - types: S["types"], -) => Expression.Expression<T, Inputs>; - -type Wrap = Node.Transition<Scope.Scope>["wrap"]; - -export type BuildStep = Node.Any | Body<Scope.Scope, Type.Any, never>; - -/** - * A nested Do block under construction, started from a callback's `$`. - * - * `Let`, `Type`, `Newtype` and `Import` each elaborate one declaration immediately: they run the step's callback with the block's current scope and return a block whose scope includes the declaration. Once a step fails, later methods skip their callbacks and keep that failure. {@link Block.Expr} ends the chain with a body and returns the block's expression, which wraps the body in the block's declarations. Those declarations stay inside that expression, and the enclosing callback's scope does not gain them. - * - * A failure, including an exception thrown by one of the callbacks, does not interrupt the enclosing callback. It stays attached to the returned expression and fails construction of any program that contains it. - */ -export class Block<S extends Scope.Scope, Inputs> { - readonly #state: Result.Result< - { - readonly scope: S; - readonly parents: readonly Wrap[]; - }, - ProgramError.Construction - >; - - constructor( - state: Result.Result< - { readonly scope: S; readonly parents: readonly Wrap[] }, - ProgramError.Construction - >, - ) { - this.#state = state; - } - - #append(step: Node.Any): Block<Scope.Scope, never> { - return new Block( - Result.flatMap(this.#state, ({ scope, parents }) => { - const input: Scope.Scope = scope; - return pipe( - Result.try({ - // oxlint-disable-next-line eslint/no-use-before-define -- block steps receive utilities that can create further blocks - try: () => step.elaborate(makeUtilities(input), input), - catch: (error) => - ProgramError.Construction.callbackException( - new Cause.UnknownError(error), - ), - }), - Result.flatMap(identity), - Result.map(({ scope, wrap }) => ({ - scope, - parents: [...parents, wrap], - })), - ); - }), - ); - } - - #step<Out extends Scope.Scope, AddedInputs>( - step: Node.Node<S, Out, AddedInputs>, - ): Block<Out, Input.Merge<Inputs, AddedInputs>> { - // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary - const output: unknown = this.#append(step); - - // SAFETY: elaborating this node produces its declared output scope. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the output scope erased by the shared driver - return output as Block<Out, Input.Merge<Inputs, AddedInputs>>; - } - - /** Appends a value binding, as the `Let` step does, running `initializer` now unless an earlier step failed. */ - Let<const Name extends string, T extends Type.Any, AddedInputs>( - name: Name, - initializer: Body<S, T, AddedInputs>, - ): Block< - Scope.Merge< - S, - { values: ReadonlyRecord<Name, Expression.Expression<T, AddedInputs>> } - >, - Input.Merge<Inputs, AddedInputs> - > { - return this.#step(Let(name, initializer)); - } - - /** Appends a type alias, as the `Type` step does, running `definition` now unless an earlier step failed. */ - Type<const Name extends string, T extends Type.Any>( - name: Name, - definition: ( - utilities: Utilities<S>, - types: S["types"], - ) => TypeExpression<T>, - ): Block< - Scope.Merge<S, { types: ReadonlyRecord<Name, TypeExpression<T>> }>, - Inputs - > { - return this.#step(DeclareType(name, definition)); - } - - /** Appends a nominal type and its constructor, as the `Newtype` step does, running `definition` now unless an earlier step failed. */ - Newtype< - const Name extends string, - const Identity extends symbol, - T extends Type.Any, - >( - name: Name, - identity: Identity & (symbol extends Identity ? never : Identity), - definition: ( - utilities: Utilities<S>, - types: S["types"], - ) => TypeExpression<T>, - ): Block<Scope.Merge<S, Exports<Name, Identity, T>>, Inputs> { - return this.#step( - Newtype<S, Name, Identity, T>(name, identity, definition), - ); - } - - /** Appends an import of the module `select` returns, as the `Import` step does, running `select` now unless an earlier step failed. */ - Import<M extends NonNullable<Scope.Scope["modules"][string]>>( - select: ( - utilities: Utilities<S>, - modules: S["modules"], - ) => M & Rebindable<M>, - ): Block<Scope.Merge<S, Imported<M, "*">>, Inputs>; - Import< - M extends NonNullable<Scope.Scope["modules"][string]>, - const Imports extends Selection<M>, - >( - select: ( - utilities: Utilities<S>, - modules: S["modules"], - ) => M & Rebindable<M>, - imports: Imports, - ): Block<Scope.Merge<S, Imported<M, Imports>>, Inputs>; - Import< - M extends NonNullable<Scope.Scope["modules"][string]>, - const Imports extends Selection<M>, - >( - select: ( - utilities: Utilities<S>, - modules: S["modules"], - ) => M & Rebindable<M>, - imports?: Imports, - ): - | Block<Scope.Merge<S, Imported<M, "*">>, Inputs> - | Block<Scope.Merge<S, Imported<M, Imports>>, Inputs> { - if (imports === undefined) { - return this.#step(Import<S, M>(select)); - } - - return this.#step(Import<S, M, Imports>(select, imports)); - } - - /** - * Ends the block with its body and returns the block's expression. - * - * The body runs now with the block's scope, unless an earlier step failed. The returned expression wraps the body's expression in this block's declarations, in step order, and combines the input requirements of every step with the body's. It is an expression rather than a `Result`, and it carries any construction failure, including one from a callback's exception. - */ - Expr<T extends Type.Any, BodyInputs>( - body: Body<S, T, BodyInputs>, - ): Expression.Expression<T, Input.Merge<Inputs, BodyInputs>> { - return Expression.fromResult( - Result.flatMap(this.#state, ({ scope, parents }) => { - // A nested block inherits names, never the wrappers that introduced them outside it. - const evaluated = Result.try({ - try: () => - body( - // oxlint-disable-next-line eslint/no-use-before-define -- block bodies receive utilities that can create further blocks - makeUtilities(scope), - scope.values, - scope.types, - ), - catch: (error) => - ProgramError.Construction.callbackException( - new Cause.UnknownError(error), - ), - }); - - if (Result.isFailure(evaluated)) { - return Result.fail(evaluated.failure); - } - - const expression = evaluated.success; - if (!Expression.isExpression(expression)) { - return Result.fail(ProgramError.Construction.invalidBodyResult()); - } - return Result.map(Expression.toNode(expression), (node) => { - let root = node; - for (const wrap of parents.toReversed()) { - root = wrap(root); - } - return root; - }); - }), - ); - } - - static build( - scope: Scope.Scope, - steps: readonly BuildStep[], - ): Result.Result<Expression.Any, ProgramError.Construction> { - let block = new Block<Scope.Scope, never>( - Result.succeed({ scope, parents: [] }), - ); - const body = steps.at(-1); - if (typeof body !== "function" || Expression.isExpression(body)) { - return Result.fail(ProgramError.Construction.missingBlockBody()); - } - - for (const step of steps.slice(0, -1)) { - if (typeof step === "function") { - return Result.fail(ProgramError.Construction.misplacedBlockBody()); - } - - if ( - typeof step !== "object" || - // oxlint-disable-next-line typescript/no-unnecessary-condition -- JavaScript callers may pass null despite the overloads - step === null || - !(Node.TypeId in step) - ) { - return Result.fail(ProgramError.Construction.invalidBlockStep()); - } - block = block.#append(step); - } - - const expression = block.Expr(body); - return Result.map(Expression.toNode(expression), () => expression); - } -} - -const evaluateBranch = ( - body: () => Expression.AnyValue, -): Result.Result<AstNode, ProgramError.Construction> => - pipe( - Result.try({ - try: body, - catch: (error) => - ProgramError.Construction.callbackException( - new Cause.UnknownError(error), - ), - }), - Result.flatMap(Expression.toNode), - ); - -/** Constructs a HashQL conditional, running both branch callbacks during construction. */ -const conditional = < - const Condition extends Expression.Value<Type.PrimitiveBoolean>, - const Then extends Expression.AnyValue, - const Else extends Expression.AnyValue, ->( - condition: Condition, - consequent: () => Then, - alternate: () => Else, -): Expression.Expression< - Expression.Conditional<Expression.TypeOf<Then>, Expression.TypeOf<Else>>, - Input.Merge< - Expression.Inputs<Condition>, - Input.Merge<Expression.Inputs<Then>, Expression.Inputs<Else>> - > -> => - pipe( - { - condition: Expression.toNode(condition), - consequent: evaluateBranch(consequent), - alternate: evaluateBranch(alternate), - }, - Result.all, - Result.map( - (nodes) => new AstIf(nodes.condition, nodes.consequent, nodes.alternate), - ), - Expression.fromResult< - Expression.Conditional<Expression.TypeOf<Then>, Expression.TypeOf<Else>>, - Input.Merge< - Expression.Inputs<Condition>, - Input.Merge<Expression.Inputs<Then>, Expression.Inputs<Else>> - > - >, - ); - -/** - * The `$` argument of every Do callback: expression constructors and an empty nested block at the callback's scope. - * - * Because `$` is itself a {@link Block}, `$.Let`, `$.Type`, `$.Newtype`, `$.Import` and `$.Expr` start a nested block whose declarations stay inside the expression it returns. The predicate constructors `eq`, `ne`, `and`, `or`, `not`, `isTrue`, `isFalse` and `isNone` are the standalone `Operators` functions. - */ -export interface Utilities<S extends Scope.Scope> - extends Block<S, Input.Empty>, Operators.Operations { - /** Lifts a host primitive to an expression whose type follows the host type. This is `Expression.literal`. */ - readonly literal: typeof Expression.literal; - /** Constructs an Integer literal, failing construction for a fractional or non-finite number. This is `Expression.integer`. */ - readonly integer: typeof Expression.integer; - /** Constructs a Number literal. This is `Expression.number`. */ - readonly number: typeof Expression.number; - /** References a program input, optionally with a default. This is `Expression.input`. */ - readonly input: typeof Expression.input; - /** Changes an expression's semantic type assumption without validating that semantic type. This is `Expression.assume`. */ - readonly assume: typeof Expression.assume; - /** - * The modules visible at this point: the prelude's modules and those imported by earlier steps, under their local names. - * - * Reach a module's exports through its `modules`, `types` and `values` records, such as `$.ref.math.values.add`. A prelude module's exports refer to their declared paths, and an imported module's exports refer to their paths under its local name. - */ - readonly ref: S["modules"]; - /** - * Graph query entry points, present when the values environment holds a suitable `entities` function. - * - * `entities` exists when that function returns a `::graph::Graph` opaque type, whose vertex type the query's predicates receive. Each `filter` predicate runs during the `filter` call, unless the query already carries a failure or the parameter name is invalid. An exception it throws becomes a `CallbackException` failure on the query. - */ - readonly query: Query.Context<S>; - /** - * Constructs a HashQL conditional from a Boolean condition and two branch callbacks. - * - * Both callbacks run immediately, then-branch first, whatever the condition's value: HashQL decides the condition when the query runs, so construction needs both branches. Each callback returns an expression or a host primitive and takes no arguments. Start a nested block from the enclosing `$` for declarations local to a branch. - * - * An exception thrown by a callback becomes a `CallbackException` failure on the returned expression and does not interrupt the enclosing callback. If more than one part fails, the expression carries the first failure in the order condition, then-branch, else-branch. - * - * @example <caption>Construct both branches, one with a local binding.</caption> - * ```ts - * import assert from "node:assert/strict"; - * import { Program } from "@local/hashql"; - * import { Do } from "@local/hashql/do"; - * import { Result } from "effect"; - * - * const visited: string[] = []; - * const result = Do(($) => - * $.if( - * true, - * () => { - * visited.push("then"); - * return $.Let("local", ($) => $.integer(1)).Expr((_, { local }) => local); - * }, - * () => { - * visited.push("else"); - * return $.integer(2); - * }, - * ), - * ); - * assert.deepEqual(visited, ["then", "else"]); - * assert.equal( - * Result.getOrThrow(Result.flatMap(result, (root) => Program.compile(Program.program(root)))), - * '["::kernel::special_form::if",{"#literal":true},["::kernel::special_form::let","local",{"#literal":1},"local"],{"#literal":2}]', - * ); - * ``` - */ - readonly if: typeof conditional; -} - -const makeUtilities = <S extends Scope.Scope>(scope: S): Utilities<S> => - Object.assign( - new Block<S, Input.Empty>(Result.succeed({ scope, parents: [] })), - { - ...Operators.operations, - literal: Expression.literal, - integer: Expression.integer, - number: Expression.number, - input: Expression.input, - assume: Expression.assume, - ref: scope.modules, - query: Query.make(scope), - if: conditional, - }, - ); diff --git a/libs/@local/hashql/sdk/typescript/src/do/index.ts b/libs/@local/hashql/sdk/typescript/src/do/index.ts deleted file mode 100644 index 10514212313..00000000000 --- a/libs/@local/hashql/sdk/typescript/src/do/index.ts +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Authors typed HashQL expressions as blocks of ordered declaration steps. - * - * A block lists declaration steps and ends with a body callback. {@link Let}, {@link Type}, {@link Newtype} and {@link Import} construct the steps, and {@link Do} runs them in order. Each step's callback sees the modules, values and types that earlier steps introduced, and each step emits a declaration around the rest of the block. The result is a construction `Result` holding the block's expression, whose input requirements TypeScript infers from every step and the body. Callbacks construct syntax and never execute a query. - * - * {@link withPrelude} seeds a block's environments with existing declarations, such as modules from `Module.define`. Every callback's `$` argument, described by `Utilities`, holds expression constructors, conditionals, queries and nested blocks. Draft, at `@local/hashql/draft`, builds the same expressions from one callback and an explicit input schema. - * - * @example <caption>Import a function and bind its result.</caption> - * ```ts - * import assert from "node:assert/strict"; - * import { Module, Program } from "@local/hashql"; - * import type { Type } from "@local/hashql"; - * import { Import, Let, withPrelude } from "@local/hashql/do"; - * import { Result } from "effect"; - * - * type Add = Type.Function< - * readonly [Type.PrimitiveInteger, Type.PrimitiveInteger], - * Type.PrimitiveInteger - * >; - * const math = Result.getOrThrow( - * Module.define("::core::math", { values: { add: Module.value<Add>() } }), - * ); - * const { Do } = withPrelude({ modules: { math } }); - * - * const total = Do( - * Import((_, { math }) => math, ["add"]), - * Let("total", (_, { add }) => add(1n, 2n)), - * (_, { total }) => total, - * ); - * assert.equal( - * Result.getOrThrow(Result.flatMap(total, (root) => Program.compile(Program.program(root)))), - * '["::kernel::special_form::use","::core::math",{"#tuple":["add"]},["::kernel::special_form::let","total",["add",{"#literal":1},{"#literal":2}],"total"]]', - * ); - * ``` - * - * @module - */ - -import * as Scope from "../Program/Scope.js"; -import { Import } from "./Import.js"; -import { Let } from "./Let.js"; -import { Newtype } from "./Newtype.js"; -import { Type } from "./Type.js"; -import { Block as Builder } from "./Utilities.js"; - -import type * as Expression from "../Program/Expression.js"; -import type * as ProgramError from "../Program/ProgramError.js"; -import type { Do as Block } from "./Do.js"; -import type { BuildStep } from "./Utilities.js"; -import type { Result } from "effect"; - -export { Import } from "./Import.js"; -export { Let } from "./Let.js"; -export { Newtype } from "./Newtype.js"; -export { Type } from "./Type.js"; -export type { Utilities } from "./Utilities.js"; - -/** - * The constructors {@link withPrelude} returns for one prelude. - * - * Only `Do` depends on the prelude. `Let`, `Type`, `Newtype` and `Import` are this module's step constructors, returned unchanged so that one destructuring supplies the whole vocabulary. - */ -export interface Context<S extends Scope.Scope> { - /** Constructs blocks that start in the scope the prelude seeded. */ - readonly Do: Block<S>; - readonly Let: typeof Let; - readonly Type: typeof Type; - readonly Newtype: typeof Newtype; - readonly Import: typeof Import; -} - -/** - * Binds {@link Do} to a prelude of existing module, value and type declarations. - * - * The prelude's optional `modules`, `values` and `types` records seed every block's environments. Step callbacks and bodies receive those environments as arguments, and `$.ref` holds the modules. A module from `Module.define` is itself a valid prelude. Seeding emits no HashQL, because a prelude export already refers to its declaration, typically by absolute path. The returned `Do` includes nothing from `Prelude.builtin` unless the prelude supplies it. - * - * `withPrelude` copies the records' own string-keyed exports when you call it, so later additions or replacements in them do not reach the returned `Do`. - */ -export const withPrelude = <const Prelude extends Scope.Definition>( - prelude: Prelude, -): Context<Scope.From<Prelude>> => { - // SAFETY: the empty scope contributes no names to any namespace. - const initial = Scope.merge( - Scope.empty, - prelude, - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- merging into empty retains precisely the supplied namespace types - ) as Scope.From<Prelude>; - - const construct = ( - ...steps: readonly BuildStep[] - ): Result.Result<Expression.Any, ProgramError.Construction> => - Builder.build(initial, steps); - - // oxlint-disable-next-line typescript/no-restricted-types -- this is the heterogeneous driver boundary - const erased: unknown = construct; - - // SAFETY: the overloads check every transition before this driver erases its scope parameters. - // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- restores the per-step scopes checked by the overloads - const Do = erased as Block<Scope.From<Prelude>>; - return Object.freeze({ - Do, - Let, - Type, - Newtype, - Import, - }); -}; - -const context: Context<Scope.Empty> = withPrelude({}); - -/** - * Constructs an expression from ordered declaration steps and a final body, starting with empty environments. - * - * `Do(step1, ..., stepN, body)` runs synchronously. It elaborates each step in argument order, running the step's callback with the scope the earlier steps produced, then runs `body` with the final scope. Nested blocks, conditionals and query predicates inside those callbacks also run during the call, and `$.if` runs both of its branch callbacks. The returned expression nests the declarations in step order around the body's expression. Its input requirements combine every step's with the body's, including the requirements of bindings that nothing refers to. - * - * `Do` returns construction failures rather than throwing them. The first failing step stops construction, so later callbacks and the body do not run. An exception thrown by a callback becomes a failure whose reason is `CallbackException`, with the thrown value as the cause of its `Cause.UnknownError`. Arguments that TypeScript rejects fail at runtime with `MissingBlockBody` when the last argument is not a callback, `MisplacedBlockBody` when an earlier argument is a callback and `InvalidBlockStep` for another value in a step position. A body that returns anything other than an expression handle fails with `InvalidBodyResult`. - * - * Use {@link withPrelude} to start blocks with declarations in scope. The positional form accepts up to eight steps. Continue in a nested block, started from a callback's `$`, for more. - * - * @example <caption>Observe callback order after a failed step.</caption> - * ```ts - * import assert from "node:assert/strict"; - * import { Do, Let } from "@local/hashql/do"; - * import { Result } from "effect"; - * - * const calls: string[] = []; - * const result = Do( - * Let("not a name", ($) => { - * calls.push("first"); - * return $.integer(1); - * }), - * Let("later", ($) => { - * calls.push("later"); - * return $.integer(2); - * }), - * (_, { later }) => later, - * ); - * assert.deepEqual(calls, ["first"]); - * assert.ok(Result.isFailure(result)); - * assert.equal(result.failure.reason._tag, "InvalidBindingName"); - * ``` - */ -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- composes ordered steps and a final expression callback -export const Do: Block<Scope.Empty> = context.Do; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts index b871a1f808f..3b25eaa811d 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Draft.test.ts @@ -417,6 +417,23 @@ describe("draft", () => { expect(Result.isFailure(asynchronous)).toBe(true); }); + test("failed_type_declaration", () => { + expect.hasAssertions(); + // @ts-expect-error The runtime call omits the required type argument. + const invalid = Prelude.builtin.types.List(); + const identity: unique symbol = Symbol("Invalid"); + const alias = Draft.program({}, ($) => { + $.type("Alias", invalid); + return $.literal(true); + }); + const nominal = Draft.program({}, ($) => { + $.newtype("Nominal", identity, invalid); + return $.literal(true); + }); + expect(alias).toStrictEqual(TypeExpression.toType(invalid)); + expect(nominal).toStrictEqual(TypeExpression.toType(invalid)); + }); + test("invalid_query_and_nominal", () => { expect.hasAssertions(); let visits = 0; diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts index 9a0543304e7..d7ebe997939 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/Import.test.ts @@ -2,7 +2,6 @@ import { Result, pipe } from "effect"; import { describe, expect, expectTypeOf, test } from "vitest"; -import { Do, Import } from "../do/index.js"; import * as TypeSyntax from "../JExpr/Type/index.js"; import { Expression, JExpr, Module, Prelude, TypeExpression } from "../main.js"; import * as Draft from "./index.js"; @@ -120,11 +119,6 @@ describe("draft_import", () => { expect(compile(result)).toBe( '["::kernel::special_form::use","::adapted",{"#struct":{"call":"invoke"}},["invoke",{"#literal":"value"}]]', ); - const throughDo = Do( - Import(() => source, { call: "invoke" }), - (_, { invoke }) => invoke({ text: "value" }), - ); - expect(compile(throughDo)).toBe(compile(result)); }); test("symbol_alias", () => { diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts b/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts new file mode 100644 index 00000000000..37c652480fb --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Query.test-d.ts @@ -0,0 +1,80 @@ +import { describe, expectTypeOf, test } from "vitest"; + +import { Expression } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; +import type { Result } from "effect"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +describe("draft_query_types", () => { + test("graph_vertex", () => { + const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function<readonly [], Graph>, + Inputs.Empty + >("entities"), + }, + }); + const result = program({}, ($) => + $.query + .entities() + .filter("item", (_, item) => { + expectTypeOf(item).toEqualTypeOf< + Expression.Expression<Vertex, Inputs.Empty> + >(); + return $.isFalse(item.enabled); + }) + .collect(), + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression<Type.List<Vertex>, Inputs.Empty>, + ProgramError.Construction + > + >(); + program({}, ($) => { + // @ts-expect-error A predicate must return a Boolean. + $.query.entities().filter("item", (_, item) => item); + // @ts-expect-error Query construction has no compatibility adapter. + expectTypeOf($.query.from); + return $.literal(true); + }); + }); + + test("primitive_arguments", () => { + const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function<readonly [Type.PrimitiveNumber], Graph>, + Inputs.Empty + >("entities"), + }, + }); + const result = program({}, ($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ); + expectTypeOf(result).toEqualTypeOf< + Result.Result< + Expression.Expression<Type.List<Vertex>, Inputs.Empty>, + ProgramError.Construction + > + >(); + program({}, ($) => { + // @ts-expect-error Query arguments use the declaration's exact numeric descriptor. + $.query.entities(1n); + // @ts-expect-error A predicate does not accept numeric truthiness. + $.query.entities(1).filter("vertex", () => 1); + return $.literal(true); + }); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts b/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts new file mode 100644 index 00000000000..34955b60488 --- /dev/null +++ b/libs/@local/hashql/sdk/typescript/src/draft/Query.test.ts @@ -0,0 +1,77 @@ +import { Result, pipe } from "effect"; +import { describe, expect, test } from "vitest"; + +import { Expression, JExpr } from "../main.js"; +import * as Draft from "./index.js"; + +import type { Inputs, ProgramError, Type } from "../main.js"; + +type Vertex = Type.Struct<{ readonly enabled: Type.PrimitiveBoolean }>; +type Graph = Type.Opaque< + "::graph::Graph", + Type.Struct<{ readonly "'marker": Vertex }> +>; + +const { program } = Draft.withPrelude({ + values: { + entities: Expression.fromJExpr< + Type.Function<readonly [Type.PrimitiveNumber], Graph>, + Inputs.Empty + >("entities"), + }, +}); + +const compile = ( + result: Result.Result<Expression.Any, ProgramError.Construction>, +): string => + pipe( + result, + Result.flatMap(Expression.toJExpr), + Result.map(JExpr.compile), + Result.getOrThrow, + ); + +describe("draft_query", () => { + test("named_filter", () => { + expect.hasAssertions(); + let calls = 0; + const result = program({}, ($) => + $.query + .entities(1) + .filter("item", (_, item) => { + calls += 1; + return $.isFalse(item.enabled); + }) + .collect(), + ); + expect(compile(result)).toBe( + '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"item":"_"}},"_",["::core::cmp::eq",["::kernel::special_form::access","item","enabled"],{"#literal":false}]]]]', + ); + expect(calls).toBe(1); + }); + + test("primitive_predicate", () => { + expect.hasAssertions(); + const result = program({}, ($) => + $.query + .entities(1) + .filter("vertex", () => true) + .collect(), + ); + expect(compile(result)).toBe( + '["::graph::tail::collect",["::graph::body::filter",["entities",{"#literal":1}],["fn",{"#tuple":[]},{"#struct":{"vertex":"_"}},"_",{"#literal":true}]]]', + ); + }); + + test("predicate_failure", () => { + expect.hasAssertions(); + const result = program({}, ($) => + $.query + .entities(1) + .filter("item", () => $.eq(Number.NaN, 1)) + .collect(), + ); + const failure = pipe(result, Result.flip, Result.getOrThrow); + expect(failure.reason._tag).toBe("InvalidExpression"); + }); +}); diff --git a/libs/@local/hashql/sdk/typescript/src/draft/index.ts b/libs/@local/hashql/sdk/typescript/src/draft/index.ts index 931eb844a31..4b58cec6bb6 100644 --- a/libs/@local/hashql/sdk/typescript/src/draft/index.ts +++ b/libs/@local/hashql/sdk/typescript/src/draft/index.ts @@ -3,7 +3,7 @@ * * {@link program} runs one callback that receives a construction context `$` and typed handles for the inputs its schema declares. Draft emits the declarations made through `$`, such as `$.let`, `$.type`, `$.newtype` and `$.import`, around the callback's returned expression in call order. Every emitted initializer and nested body must fit the schema, so the result can retain unused declared inputs without overlooking discarded declarations. Branch and query-predicate callbacks receive their own contexts, whose declarations stay inside that branch or predicate. * - * {@link program} uses `Prelude.builtin`. {@link withPrelude} creates a program constructor for custom declarations instead, replacing the default and retaining their exact export keys. The `Context` namespace names the construction operation types. Do, at `@local/hashql/do`, builds the same expressions from ordered declaration steps and infers input requirements rather than declaring them. + * {@link program} uses `Prelude.builtin`. {@link withPrelude} creates a program constructor for custom declarations instead, replacing the default and retaining their exact export keys. The `Context` namespace names the construction operation types. * * @example <caption>Bind a computed value and compare it with an input.</caption> * ```ts diff --git a/libs/@local/hashql/sdk/typescript/src/internal/scan.ts b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts index d79d26d4bf2..db477b7e770 100644 --- a/libs/@local/hashql/sdk/typescript/src/internal/scan.ts +++ b/libs/@local/hashql/sdk/typescript/src/internal/scan.ts @@ -92,11 +92,7 @@ const matchAt = ), ); -// oxlint-disable-next-line effecttsgo/missing-pipeable-signature -- internal only function -export const scanIdent: ( - input: string, - start: number, -) => Option.Option<ScanIdent> = (input, start) => { +const scanIdent = (input: string, start: number): Option.Option<ScanIdent> => { if (input.startsWith(backtick, start)) { return Option.orElse( matchAt(escapedSymbol, input, start)("Symbol", 1), @@ -115,7 +111,7 @@ export const scanIdentExact = (input: string): Option.Option<ScanIdent> => ); /** A path split into its parts. */ -export interface ScanPath { +interface ScanPath { readonly rooted: boolean; readonly segments: readonly [ScanIdent, ...ScanIdent[]]; } diff --git a/libs/@local/hashql/sdk/typescript/src/main.ts b/libs/@local/hashql/sdk/typescript/src/main.ts index 820430a0e52..47910a919b3 100644 --- a/libs/@local/hashql/sdk/typescript/src/main.ts +++ b/libs/@local/hashql/sdk/typescript/src/main.ts @@ -1,7 +1,7 @@ /** * Typed HashQL syntax construction and J-Expr encoding. * - * Use `@local/hashql/draft` for synchronous authoring with an explicit input schema, or `@local/hashql/do` for ordered declaration steps and inferred input requirements. Both produce typed expressions. {@link Expression} also provides direct construction, and {@link Program} wraps a root expression for serialization. + * Use `@local/hashql/draft` to author a program synchronously against an explicit input schema. {@link Expression} also provides direct construction, and {@link Program} wraps a root expression for serialization. * * {@link Type} describes semantic types at compile time. {@link TypeExpression} carries their syntax at runtime. {@link Module} declares trusted external names, and {@link JExpr} provides the lower-level syntax model. The SDK builds programs but does not execute them. Its type declarations require TypeScript 7. * diff --git a/libs/@local/hashql/sdk/typescript/tsdown.config.ts b/libs/@local/hashql/sdk/typescript/tsdown.config.ts index 7ed4bffa303..dfaa6e16d6e 100644 --- a/libs/@local/hashql/sdk/typescript/tsdown.config.ts +++ b/libs/@local/hashql/sdk/typescript/tsdown.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "tsdown"; import type { UserConfig } from "tsdown"; const config: UserConfig = defineConfig({ - entry: ["src/main.ts", "src/do/index.ts", "src/draft/index.ts"], + entry: ["src/main.ts", "src/draft/index.ts"], format: "esm", platform: "neutral", unbundle: true, diff --git a/yarn.lock b/yarn.lock index 81c55e12bd4..b54c2bbb82e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8923,7 +8923,7 @@ __metadata: languageName: node linkType: hard -"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.4.15, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5, @jridgewell/sourcemap-codec@npm:^1.6.0, @jridgewell/sourcemap-codec@npm:^1.6.0-beta.0": +"@jridgewell/sourcemap-codec@npm:^1.4.14, @jridgewell/sourcemap-codec@npm:^1.5.0, @jridgewell/sourcemap-codec@npm:^1.5.5, @jridgewell/sourcemap-codec@npm:^1.6.0, @jridgewell/sourcemap-codec@npm:^1.6.0-beta.0": version: 1.6.0 resolution: "@jridgewell/sourcemap-codec@npm:1.6.0" checksum: 10c0/b5be700e45a775f218589c3466c4ffea630582b4988657652da464e5ab8a7d18bf928ee4fd2363fb346ede4bea9c6ff0bae05a538358c4565ece6199531b5f72 @@ -10233,8 +10233,8 @@ __metadata: version: 0.0.0-use.local resolution: "@local/hashql-typescript-docs@workspace:libs/@local/hashql/sdk/typescript-docs" dependencies: - "@effect/platform-node": "npm:4.0.0" - "@effect/vitest": "npm:4.0.0" + "@effect/platform-node": "npm:4.0.3" + "@effect/vitest": "npm:4.0.3" "@fumadocs/satteri": "npm:0.5.1" "@local/hashql": "workspace:*" "@local/oxlint": "workspace:*" @@ -10251,7 +10251,7 @@ __metadata: "@types/node": "catalog:" "@types/react": "npm:19.2.14" "@types/react-dom": "npm:19.2.3" - effect: "npm:4.0.0" + effect: "npm:4.0.3" fumadocs-core: "npm:16.16.2" fumadocs-mdx: "npm:15.4.6" fumadocs-twoslash: "npm:4.0.1" @@ -10287,8 +10287,6 @@ __metadata: "@local/tsconfig": "workspace:*" "@tsconfig/bases": "catalog:" effect: "npm:4.0.3" - esrap: "npm:2.4.0" - oxc-parser: "npm:0.152.0" oxlint: "catalog:" tsdown: "npm:0.23.0" typescript: "catalog:" @@ -29404,20 +29402,6 @@ __metadata: languageName: node linkType: hard -"esrap@npm:2.4.0": - version: 2.4.0 - resolution: "esrap@npm:2.4.0" - dependencies: - "@jridgewell/sourcemap-codec": "npm:^1.4.15" - peerDependencies: - "@typescript-eslint/types": ^8.2.0 - peerDependenciesMeta: - "@typescript-eslint/types": - optional: true - checksum: 10c0/36718ac21957031a4f99e4ebda8376e0c11b78b6c7c40dc3494f3cdd8df14cbaf13e6c3f1216feb55cac85f6a249f98a61f3e6ef8c6b1cb8555a7f6e7364227f - languageName: node - linkType: hard - "esrecurse@npm:^4.3.0": version: 4.3.0 resolution: "esrecurse@npm:4.3.0"