Files
zen/bindings/nodejs/index.d.ts
T
stefan-gorules 6c0ca51354 feat: policy engine (#450)
* feat: policy engine

* fix: cargo fmt

* fix: resolve issues with miri
2026-06-23 18:51:47 +02:00

571 lines
17 KiB
TypeScript

/* auto-generated by NAPI-RS */
/* eslint-disable */
export type PolicyPropertyKind = 'input' | 'computed';
export type PolicyFieldKind = 'scalar' | 'enum' | 'relationship' | 'reference';
export type PolicySeverity = 'error' | 'warning' | 'hint';
/** Text range, `[start, end)` byte offsets. */
export type PolicySpan = [number, number];
/** Rename target — a top-level entity, an entity field, or a global property. */
export type PolicyRenameTarget =
| { kind: 'entity'; name: string }
| { kind: 'field'; entity: string; field: string }
| { kind: 'global'; name: string };
/** What kind of span a cursor is sitting in, with any disambiguation. */
export type PolicyCursorTarget =
| { kind: 'expression'; id: string }
| { kind: 'assertionOutput' }
| { kind: 'expressionKey' }
| { kind: 'matchTarget' }
| { kind: 'matchValue'; id: string }
| { kind: 'decisionTableHead'; col: string }
| { kind: 'decisionTableCell'; row: string; col: string }
| { kind: 'dataModelName' }
| { kind: 'dataModelProperty'; id: string };
/**
* How an entity field came into existence — declared by a DataModel
* (`schema`) or produced by a rule block (`computed`). Computed fields
* whose value provably consists of entity instances (identity preserved
* through filter / index / slice) carry `instanceOf`.
*/
export type PolicyFieldOrigin =
| { origin: 'schema'; source: string; fieldKind: PolicyFieldKindInfo }
| { origin: 'computed'; writtenBy: PolicyPropertyWriter; instanceOf?: PolicyInstanceOf };
export type PolicyDiagnosticCode =
| 'UNDEFINED_VARIABLE'
| 'TYPE_MISMATCH'
| 'INVALID_EXPRESSION'
| 'PARSE_ERROR'
| 'MISSING_DEFAULT_BRANCH'
| 'EMPTY_BLOCK'
| 'MIXED_SCOPE'
| 'CYCLIC_DEPENDENCY'
| 'DUPLICATE_WRITER'
| 'INVALID_WRITE_PATH'
| 'INPUT_OVERRIDE'
| 'SELF_REFERENCING_WRITE'
| 'UNREACHABLE_ENTITY_READ'
| 'PARTIAL_OBJECT_WRITE'
| 'DATA_MODEL_COLLISION'
| 'UNKNOWN_DATA_MODEL_TARGET'
| 'DUPLICATE_PROPERTY'
| 'DUPLICATE_ENUM_VALUE'
| 'INVALID_NAME'
| 'MAX_DEPTH_EXCEEDED'
| 'IMPORT_NOT_FOUND'
| 'CIRCULAR_IMPORT'
| 'REDUNDANT_NULLISH'
| 'REPEATED_DERIVATION'
| 'PREFER_MATCH'
| 'REDUNDANT_TABLE_ROW'
| 'NON_DISCRIMINATING_COLUMN'
| 'REDUNDANT_PARENTHESES';
export type PolicyVariableType =
| { type: 'any' }
| { type: 'null' }
| { type: 'bool' }
| { type: 'string' }
| { type: 'number' }
| { type: 'date' }
| { type: 'interval' }
| { type: 'const'; value: string }
| { type: 'enum'; name: string | null; values: string[] }
| { type: 'array'; items: PolicyVariableType }
| { type: 'object'; fields: Record<string, PolicyVariableType> }
| { type: 'nullable'; inner: PolicyVariableType };
/**
* Wire-format block — the same shape passed into `setPolicy` / `updateBlock`.
* The engine emits these inside `replaceBlock` / `insertBlock` edits so a
* host can swap them in by id without text-span surgery.
*/
export interface PolicyWireBlock {
id: string;
type: string;
props: { dataJson?: string; schemaJson?: string };
}
/**
* Block-level edit emitted by code-mod operations (rename today; cascade
* delete / code-actions / extract-refactor planned). Hosts apply each by
* id-keyed swap (same path as `updateBlock` / `removeBlock`).
*
* - `replaceBlock` — overwrite an existing block's wire content.
* - `deleteBlock` — remove a block by id.
* - `insertBlock` — append a new block (after `afterBlockId` if given).
*/
export type PolicyEngineEdit =
| {
kind: 'replaceBlock';
policyPath: string;
blockId: string;
newBlock: PolicyWireBlock;
}
| { kind: 'deleteBlock'; policyPath: string; blockId: string }
| {
kind: 'insertBlock';
policyPath: string;
afterBlockId?: string;
newBlock: PolicyWireBlock;
};
/**
* What kind of usage site a `PolicyReferenceSite` represents.
*
* - `expressionRead` — a read in an expression body (assertion condition,
* decision-table cell, decision-tree statement value).
* - `writeKey` — an `entity.field` write target (assertion output, DT
* column head, tree statement key).
* - `dataModel` — a declaration site in a data-model block (entity name,
* property name, or relationship/reference target).
*/
export type PolicyReferenceKind = 'expressionRead' | 'writeKey' | 'dataModel';
/**
* One usage site of a `PolicyRenameTarget` in the workspace, returned by
* `references()`. Carries enough context to navigate to the site or render
* a "find references" panel.
*/
export interface PolicyReferenceSite {
policyPath: string;
blockId: string;
expressionId?: string;
/** The full original source string this site lives in. */
source: string;
/** Character offsets within `source` (LSP-style). */
span: PolicySpan;
kind: PolicyReferenceKind;
}
/**
* One node in the transitive dependency tree returned by `dependencies()`.
* Each node names a property; `writtenBy` is the block that produces it
* (absent for inputs — those are leaves). `deps` is the next layer of the
* dependency tree, recursively. Cycles in the dep graph (cut by the
* engine's self-edge skip) are protected here too — any revisited node has
* empty `deps`.
*/
export interface PolicyDependencyNode {
property: string;
writtenBy?: PolicyPropertyWriter;
unresolved?: boolean;
resolvedType: PolicyVariableType;
deps: PolicyDependencyNode[];
}
export interface PolicyEvaluationResult {
output?: unknown;
/** Evaluation duration in microseconds. */
duration?: number;
trace?: PolicyTrace;
/** Present when a block failed mid-evaluation; `trace` then holds the partial trace up to the failure. */
error?: PolicyEvaluationFailure;
}
export interface PolicyEvaluationFailure {
policyPath: string;
blockId: string;
expression: string;
message: string;
}
export interface PolicyTrace {
engineVersion: string;
properties: Record<string, unknown>;
executions: PolicyBlockExecution[];
}
export interface PolicyBlockExecution {
blockId: string;
policyPath?: string;
instancePath?: string;
trace: PolicyBlockTrace;
operandValues?: Record<string, unknown>;
writes?: PolicyWriteTrace[];
reads?: string[];
}
export interface PolicyWriteTrace {
path: string;
value: unknown;
}
export interface PolicyDecisionTableExtras {
inputPass: string;
}
export type PolicyBlockTrace =
| {
kind: 'assertion';
result: boolean;
conditions: { id: string; result: boolean }[];
}
| {
kind: 'decisionTable';
matchedRows: number[];
evaluations: Record<string, unknown>[];
extras?: PolicyDecisionTableExtras;
}
| {
kind: 'expression';
property: string;
value: unknown;
}
| {
kind: 'match';
matchedArm?: string;
value: unknown;
arms: { id: string; result: boolean }[];
};
export declare class PolicyWorkspace {
constructor()
setPolicy(path: string, document: any): void
removePolicy(path: string): boolean
/**
* Upsert a single block in an existing policy (replace-by-id or append).
* Errors when the policy does not exist — call `setPolicy` first to
* create one.
*/
updateBlock(req: PolicyUpdateBlockRequest): void
/**
* Remove a block from an existing policy by id. Returns `true` when a
* block was removed, `false` when the policy or block didn't exist.
*/
removeBlock(req: PolicyRemoveBlockRequest): boolean
policyPaths(): Array<string>
/**
* `max_diagnostics` caps the returned list (default: 100). Pass `0` for
* no cap.
*/
diagnostics(policyPath: string, maxDiagnostics?: number | undefined | null): Array<PolicyDiagnostic>
/**
* `max_diagnostics` caps the returned list (default: 100). Pass `0` for
* no cap.
*/
allDiagnostics(maxDiagnostics?: number | undefined | null): Array<PolicyDiagnostic>
entities(req: PolicyScopeRequest): Array<PolicyEntityInfo>
globals(req: PolicyScopeRequest): Array<PolicyGlobalInfo>
inputs(req: PolicyScopeRequest): Array<PolicyInputProperty>
outputs(req: PolicyScopeRequest): Array<PolicyOutputProperty>
conditionalSchema(req: PolicyScopeRequest): PolicyConditionalSchema
inspect(cursor: PolicyExpressionCursor): PolicyInspectResult | null
completions(cursor: PolicyExpressionCursor): Array<PolicyCompletion>
prepareRename(cursor: PolicyExpressionCursor): PolicyPrepareRenameResult | null
/**
* Returns block-level edits the host applies via id-keyed swap (same
* path as `update_block`). Each edit's `kind` field discriminates the
* variant; `replaceBlock` carries a `newBlock` payload that is the
* rewritten wire-format `BlockDoc`.
*/
rename(req: PolicyRenameRequest): PolicyEngineEdit[]
/**
* Returns every site in the workspace where `target` is used. Same
* visitor as `rename`; carries policy/block/expression/source/span/kind
* for each site so hosts can render a "find references" panel or drive
* navigation.
*/
references(target: any): PolicyReferenceSite[]
/**
* Default-valued JSON object that matches the workspace's input shape
* for `req.policy_path` (and optionally `req.goals`). Hosts use it as
* the initial value of a "Run simulation" panel so `evaluate` can be
* called immediately without first authoring an input by hand.
*/
inputSkeleton(req: PolicyScopeRequest): unknown
/**
* Returns the transitive dependency tree rooted at `target`. Inverse
* of `references()`. Per-write granularity — multi-output blocks
* don't conflate sibling outputs' deps.
*/
dependencies(target: string): PolicyDependencyNode
evaluate(req: PolicyEvaluateRequest): PolicyEvaluationResult
enhanceTrace(req: PolicyEvaluateRequest): PolicyEvaluationResult
componentMembers(policy: string): Array<string>
crossComponentWriteConflicts(): Array<PolicyWriteConflict>
}
export declare class ZenDecision {
constructor()
evaluate(context: any, opts?: ZenEvaluateOptions | undefined | null): Promise<ZenEngineResponse>
safeEvaluate(context: any, opts?: ZenEvaluateOptions | undefined | null): Promise<{ success: true, data: ZenEngineResponse } | { success: false; error: any; }>
validate(): void
}
export declare class ZenDecisionContent {
constructor(content: Buffer | object)
toBuffer(): Buffer
}
export declare class ZenEngine {
constructor(options?: ZenEngineOptions | undefined | null)
evaluate(key: string, context: any, opts?: ZenEvaluateOptions | undefined | null): Promise<ZenEngineResponse>
createDecision(content: ZenDecisionContent | Buffer | object): ZenDecision
getDecision(key: string): Promise<ZenDecision>
safeEvaluate(key: string, context: any, opts?: ZenEvaluateOptions | undefined | null): Promise<{ success: true, data: ZenEngineResponse } | { success: false; error: any; }>
safeGetDecision(key: string): Promise<{ success: true, data: ZenDecision } | { success: false; error: any; }>
evaluateBatch(requests: Array<EvaluateBatchRequest>, opts?: ZenEvaluateOptions | undefined | null): Promise<Array<EvaluateBatchResult>>
reload(): Promise<void>
compileFailures(): Array<{ key: string; kind: string; diagnostics?: Array<{ code: string; message: string; severity: string }>; error?: string }>
dispose(): void
}
export declare class ZenEngineHandlerRequest {
constructor()
get node(): DecisionNode
get input(): any
getField(path: string): unknown
getFieldRaw(path: string): unknown
}
export interface DecisionNode {
id: string
name: string
kind: string
config: any
}
export interface EvaluateBatchRequest {
key: string
context: any
}
export interface EvaluateBatchResult {
success: boolean
data?: any
error?: any
}
export declare function evaluateExpression(expression: string, context?: any | undefined | null): Promise<any>
export declare function evaluateExpressionSync(expression: string, context?: any | undefined | null): any
export declare function evaluateUnaryExpression(expression: string, context: any): Promise<boolean>
export declare function evaluateUnaryExpressionSync(expression: string, context: any): boolean
export declare function overrideConfig(config: ZenConfig): void
export interface PolicyCompletion {
label: string
kind: string
detail: string
info: string
}
export interface PolicyConditionalSchema {
kind: "union" | "flat"
common: PolicySchemaGroup
union?: PolicyDiscriminatedUnion
conditional?: PolicySchemaGroup
}
export interface PolicyDiagnostic {
code: PolicyDiagnosticCode
message: string
severity: PolicySeverity
policyPath: string
blockId?: string
span?: PolicySpan
expressionId?: string
target?: PolicyCursorTarget
}
export interface PolicyDiscriminantVariant {
value?: string
arm: string
group: PolicySchemaGroup
}
export interface PolicyDiscriminatedUnion {
property: string
resolvedType: PolicyVariableType
variants: Array<PolicyDiscriminantVariant>
}
export interface PolicyEntityFieldInfo {
name: string
resolvedType: PolicyVariableType
origin: PolicyFieldOrigin
}
export interface PolicyEntityInfo {
name: string
fields: Array<PolicyEntityFieldInfo>
}
export interface PolicyEvaluateRequest {
policyPath: string
input: unknown
/** Goals to evaluate. Omit or pass empty for full evaluation. */
goals?: Array<string>
trace?: boolean
}
export interface PolicyExpressionCursor {
policyPath: string
blockId: string
pos: number
/**
* Tagged `{ kind, ...payload }` discriminating what kind of span the
* cursor sits in. See `PolicyCursorTarget` in the TypeScript types.
*/
target: PolicyCursorTarget
}
/**
* Kept as a `#[napi(object)]` struct purely so NAPI-RS emits the TS type
* used by `PolicyFieldOrigin.schema.fieldKind`. The runtime shape is
* hand-built in [`field_kind_to_json`].
*/
export interface PolicyFieldKindInfo {
kind: PolicyFieldKind
target?: string
array?: boolean
}
export interface PolicyGlobalInfo {
name: string
resolvedType: PolicyVariableType
origin: PolicyFieldOrigin
}
export interface PolicyGuardedProperty {
path: string
resolvedType: PolicyVariableType
requiredWhen?: string
}
export interface PolicyInputProperty {
path: string
resolvedType: PolicyVariableType
}
export interface PolicyInspectResult {
span: PolicySpan
kind: PolicyVariableType
label: string
}
export interface PolicyInstanceOf {
target: string
array: boolean
}
export interface PolicyOutputProperty {
path: string
resolvedType: PolicyVariableType
kind: PolicyPropertyKind
writtenBy?: PolicyPropertyWriter
instanceOf?: PolicyInstanceOf
}
export interface PolicyPrepareRenameResult {
target: PolicyRenameTarget
span: PolicySpan
}
export interface PolicyPropertyWriter {
policyPath: string
blockId: string
}
export interface PolicyRemoveBlockRequest {
policyPath: string
blockId: string
}
export interface PolicyRenameRequest {
target: PolicyRenameTarget
newName: string
}
export interface PolicySchemaGroup {
inputs: Array<PolicyGuardedProperty>
outputs: Array<PolicyGuardedProperty>
}
export interface PolicyScopeRequest {
policyPath: string
/**
* Goals to constrain schema introspection to. Omit or pass empty
* for everything reachable from the policy.
*/
goals?: Array<string>
}
export interface PolicyUpdateBlockRequest {
policyPath: string
/**
* A single wire block (same shape as one entry of `PolicyDocument.blocks`).
* Upserted by `block.id`: replaces in place if present, appends otherwise.
*/
block: unknown
}
export interface PolicyWriteConflict {
path: string
policies: Array<string>
}
export declare function renderTemplate(template: string, context: any): Promise<any>
export declare function renderTemplateSync(template: string, context: any): any
export interface ZenConfig {
nodesInContext?: boolean
functionTimeoutMillis?: number
httpAuth?: boolean
}
export interface ZenEngineHandlerResponse {
output: any
traceData?: any
}
export interface ZenEngineOptions {
loader?: ((key: string) => Promise<Buffer | ZenDecisionContent>) | { type: 'static'; content: Record<string, object> } | { type: 'fs'; path: string } | { type: 'zip'; bytes: Buffer }
customHandler?: (request: ZenEngineHandlerRequest) => Promise<ZenEngineHandlerResponse>
httpHandler?: (request: ZenHttpHandlerRequest) => Promise<ZenHttpHandlerResponse>
}
export interface ZenEngineResponse {
performance: string
result: any
trace?: Record<string, ZenEngineTrace>
}
export interface ZenEngineTrace {
id: string
name: string
input: any
output: any
performance?: string
traceData?: any
order: number
}
export interface ZenEvaluateOptions {
maxDepth?: number
trace?: boolean | 'string' | 'reference' | 'referenceString'
}
export interface ZenHttpHandlerRequest {
method: string
url: string
body?: any
headers: Record<string, string>
params: Record<string, string>
}
export interface ZenHttpHandlerResponse {
status: number
headers: any
data: any
}